Skip to content

simiancraft/simiancraft-skills / skills/burn-down-github-issues

burn-down-github-issues

Unverified

Run an unattended burndown of a GitHub issue backlog as cards on a per-operator GitHub Projects board whose lanes are an explicit state machine: appraise and size the inbox, carve what is over the ceiling, fix the ready ones in parallel git worktrees, prove each fix on a draft pull request, have an isolated second-engine reviewer judge it, land one branch at a time with freshness checks, and dead-letter per phase whatever a machine cannot finish. Use when the task is "work the backlog unattended", "triage and fix recent issues", "run the issue loop", "burn down issues", or "where is issue N on the board". Requires a per-repository burn-down-github-issues.config.ts at the target repo's root (the loop refuses to start without it), the prove-work-on-github skill, the codex and claude CLIs for the default seats, and a gh token with the project scope for the board. Skip for one-off fixes to a known issue you are already working interactively, and for backlogs whose issues are mostly product decisions rather than code.

FileKindSize
SKILL.mdskill md17.0 KB
board.tsscript6.5 KB
callbacks/README.mdmarkdown1.1 KB
callbacks/on-size-over-ceilingother843 B
card.tsscript4.3 KB
chart-machine.tsscript3.9 KB
claim-race.tsscript6.1 KB
export-machine.tsscript1.8 KB
lanes.tsscript5.2 KB
lib/admission.test.tsscript7.6 KB
lib/admission.tsscript5.5 KB
lib/board-writer.test.tsscript3.6 KB
lib/board-writer.tsscript11.8 KB
lib/carving-revisit.test.tsscript7.5 KB
lib/carving.tsscript26.9 KB
lib/floor/config.test.tsscript456 B
lib/floor/config.tsscript8.1 KB
lib/floor/floor.test.tsscript9.9 KB
lib/floor/floor.tsscript28.7 KB
lib/floor/incident.tsscript11.2 KB
lib/floor/ledger.tsscript5.6 KB
lib/floor/probe.tsscript3.6 KB
lib/lanes.tsscript4.4 KB
lib/machine.test.tsscript11.2 KB
lib/machine.tsscript52.4 KB
lib/place-callbacks.test.tsscript2.5 KB
lib/place-callbacks.tsscript3.0 KB
lib/preflight.test.tsscript4.5 KB
lib/preflight.tsscript1.2 KB
lib/pressure.test.tsscript56.9 KB
lib/refs.test.tsscript1010 B
lib/refs.tsscript1.9 KB
lib/run-scope.test.tsscript5.4 KB
lib/run-scope.tsscript1.2 KB
lib/scenarios.test.tsscript17.1 KB
lib/simulate.test.tsscript7.3 KB
lib/simulate.tsscript7.0 KB
lib/world-sweep.test.tsscript21.4 KB
loop.source.test.tsscript4.8 KB
loop.tsscript66.2 KB
prompts/diagnose.mdmarkdown2.1 KB
prompts/walk.mdmarkdown3.6 KB
references/adopting.mdmarkdown26.3 KB
references/architecture.mdmarkdown20.7 KB
references/floor.mdmarkdown14.6 KB
references/operating.mdmarkdown19.6 KB
references/state-machine.mdmarkdown31.1 KB
status.tsscript4.9 KB
watch.tsscript6.4 KB

lib/floor/incident.ts

View on GitHub
/**
 * What happens when a walk finds the environment wrong: diagnose from the ledger, the forge, and
 * the logs; file (or find) the `floor/incident` issue; hand it to the fix pipeline; and say how it
 * ended. Filing is intrinsic rather than a callback because the pipeline is issue-shaped.
 */

import { join } from 'node:path';
import { readResult, renderPrompt, runAgent } from '../../../fix-github-issue/lib/agent.ts';
import type { Context } from '../../../fix-github-issue/lib/context.ts';
import type { Seat } from '../../../fix-github-issue/lib/engines.ts';
import { ensureLabels, parkIssue } from '../../../fix-github-issue/lib/labels.ts';
import { enrichBlockers } from '../../../fix-github-issue/lib/blockers.ts';
import { fixIssue, type FixOutcome, type Issue } from '../../../fix-github-issue/lib/pipeline.ts';
import { sh } from '../../../fix-github-issue/lib/shell.ts';
import { type LedgerEntry, lastClean, readLedger } from './ledger.ts';

type MergedPullRequest = { number: number; title: string; mergedAt: string; mergeCommit: string; paths: string[] };

/** Pull requests merged into the base since `since`, newest first, from the forge. */
export function mergedSince(ctx: Context, since: string): MergedPullRequest[] {
  const raw = sh(ctx, [
    'gh', 'pr', 'list', '-R', ctx.project.repo, '--state', 'merged', '--base', ctx.project.baseBranch, '--limit', '100',
    '--search', `merged:>=${since.slice(0, 10)}`, '--json', 'number,title,mergedAt,mergeCommit,files',
  ]);
  const rows = JSON.parse(raw) as Array<{ number: number; title: string; mergedAt: string; mergeCommit: { oid: string } | null; files: Array<{ path: string }> }>;
  return rows
    .filter((pr) => Date.parse(pr.mergedAt) >= Date.parse(since))
    .map((pr) => ({ number: pr.number, title: pr.title, mergedAt: pr.mergedAt, mergeCommit: pr.mergeCommit?.oid ?? '', paths: pr.files.map((f) => f.path) }))
    .sort((a, b) => Date.parse(b.mergedAt) - Date.parse(a.mergedAt));
}

export const INCIDENT_LABEL = 'floor/incident';
const DIAGNOSIS_FILE = 'floor-diagnosis.json';

export type Diagnosis = {
  culprit: { pullRequest: number; sha: string } | null;
  confidence: 'certain' | 'likely' | 'guess' | 'none';
  error: string;
  remedy: 'fix-forward' | 'revert' | 'outside-repository';
  summary: string;
};

export type IncidentResult = {
  issue: number;
  created: boolean;
  fix: FixOutcome | null;
  diagnosis: Diagnosis | null;
  /** True when a person now owns the incident, so walking it again should not start another fix. */
  withAPerson: boolean;
};

/** Labels the fix pipeline leaves when it stops and hands an issue to a person. */
const HUMAN_LABELS = new Set(['loop/parked', 'needs-human', 'needs-decision', 'loop/skip']);
/** A dead letter is with the loop's triage or a person, never back in a worker's hands on its own. */
const withAPersonOrTriage = (name: string) => HUMAN_LABELS.has(name) || name === 'loop/dlq' || name.startsWith('loop/dlq:');

function readLogs(command: string | undefined, cwd: string): string {
  if (!command) return '';
  const proc = Bun.spawnSync(['sh', '-c', command], { cwd, stdout: 'pipe', stderr: 'pipe', timeout: 60_000 });
  const text = `${proc.stdout.toString()}\n${proc.stderr.toString()}`.trim();
  return text.split('\n').slice(-200).join('\n');
}

/**
 * Merges between the last clean walk and the failure. An absent item reaches back to its own merge
 * as well: the clean probe at the start of the same walk would otherwise leave no suspects at all.
 */
function suspectsBetween(ctx: Context, lastGood: LedgerEntry | undefined, failed: LedgerEntry, mergedAt?: string): MergedPullRequest[] {
  const floor = Date.parse(failed.checkedAt) - 24 * 60 * 60 * 1000;
  const candidates = [lastGood?.checkedAt, mergedAt && new Date(Date.parse(mergedAt) - 60_000).toISOString()].filter((at): at is string => !!at);
  const since = candidates.length > 0 ? candidates.sort()[0] : new Date(floor).toISOString();
  try {
    return mergedSince(ctx, since).filter((pr) => pr.mergeCommit && Date.parse(pr.mergedAt) <= Date.parse(failed.checkedAt));
  } catch (error) {
    ctx.log(`could not list merges from the forge: ${(error as Error).message}`);
    return [];
  }
}

function renderSuspects(suspects: MergedPullRequest[]): string {
  if (suspects.length === 0) return '(nothing merged between the two revisions)';
  return suspects
    .map((pr) => `- #${pr.number} \`${pr.mergeCommit.slice(0, 12)}\` ${pr.mergedAt} ${pr.title}\n  paths: ${pr.paths.slice(0, 12).join(', ')}${pr.paths.length > 12 ? ', …' : ''}`)
    .join('\n');
}

/** The title every incident for an item carries, so lookups match whole titles rather than substrings. */
export function incidentTitle(itemId: string, verdict: string): string {
  return `floor: ${itemId} is ${verdict}`;
}

/** An open incident already naming this item, with whether a person owns it, or null. */
export function openIncidentFor(ctx: Context, itemId: string): { number: number; withAPerson: boolean } | null {
  const raw = sh(ctx, [
    'gh', 'issue', 'list', '--state', 'open', '--label', INCIDENT_LABEL, '--limit', '50', '--json', 'number,title,labels',
  ]);
  const rows = JSON.parse(raw) as Array<{ number: number; title: string; labels: Array<{ name: string }> }>;
  const prefix = `floor: ${itemId} is `;
  const row = rows.find((candidate) => candidate.title.startsWith(prefix));
  if (!row) return null;
  return { number: row.number, withAPerson: row.labels.some((label) => withAPersonOrTriage(label.name)) };
}

export function ensureIncidentLabel(ctx: Context): void {
  const existing = sh(ctx, ['gh', 'label', 'list', '--limit', '200', '--json', 'name', '--jq', '.[].name']).split('\n');
  if (existing.includes(INCIDENT_LABEL)) return;
  sh(ctx, ['gh', 'label', 'create', INCIDENT_LABEL, '--color', 'b60205', '--description', 'A walk of the running environment found it wrong', '--force']);
}

export async function handleIncident(
  ctx: Context,
  options: {
    dir: string;
    entry: LedgerEntry;
    checkout: string;
    walker: Seat;
    logsCommand?: string;
    maxPoints: number;
    /** When the failed item merged, for an `absent` item. */
    mergedAt?: string;
  },
): Promise<IncidentResult> {
  const { dir, entry, checkout, walker } = options;
  const ledger = readLedger(dir);
  const lastGood = lastClean(ledger);
  const suspects = suspectsBetween(ctx, lastGood, entry, options.mergedAt);
  const logs = readLogs(options.logsCommand, ctx.invokeRoot);

  // An incident already open for this item, checked first: one a person owns needs no diagnosis
  // turn and no fix, only the fresh ledger entry the walk just wrote.
  const existing = ctx.dryRun ? null : openIncidentFor(ctx, entry.itemId);
  if (existing?.withAPerson) {
    ctx.log(`incident #${existing.number} is already open for ${entry.itemId} and with a person; not working it again`);
    return { issue: existing.number, created: false, fix: null, diagnosis: null, withAPerson: true };
  }

  // Diagnosis is one agent turn, read-only, in the checkout at the failing revision.
  let diagnosis: Diagnosis | null = null;
  if (!ctx.dryRun) {
    const prompt = renderPrompt(ctx, 'diagnose.md', {
      ENTRY: JSON.stringify(entry, null, 2),
      LAST_GOOD: lastGood ? JSON.stringify(lastGood, null, 2) : '(no clean walk on record)',
      SUSPECTS: renderSuspects(suspects),
      LOGS: logs || '(no logs command configured, or it printed nothing)',
      CHECKOUT: checkout,
      DIAGNOSIS_FILE: join(checkout, DIAGNOSIS_FILE),
    });
    const run = await runAgent(ctx, 'diagnose', 0, checkout, walker, prompt);
    if (run.exitCode === 0) diagnosis = readResult<Diagnosis>(checkout, DIAGNOSIS_FILE);
    if (!diagnosis) ctx.log('the diagnosis turn produced no usable answer; filing the incident without one');
  }

  const title = incidentTitle(entry.itemId, entry.verdict);
  let issue = existing?.number ?? null;
  if (issue === null) {
    const body = [
      `A walk of the running environment found \`${entry.itemId}\` **${entry.verdict}** at ${entry.checkedAt}.`,
      '',
      '## The failing walk',
      '```json',
      JSON.stringify(entry, null, 2),
      '```',
      '',
      '## The last clean walk',
      lastGood ? '```json\n' + JSON.stringify(lastGood, null, 2) + '\n```' : '(none on record)',
      '',
      '## Merged between the two',
      renderSuspects(suspects),
      '',
      '## Diagnosis',
      diagnosis
        ? [
            `Culprit: ${diagnosis.culprit ? `#${diagnosis.culprit.pullRequest} (\`${diagnosis.culprit.sha.slice(0, 12)}\`)` : 'none named'} (${diagnosis.confidence})`,
            diagnosis.error ? `Error: \`${diagnosis.error}\`` : '',
            `Remedy: ${diagnosis.remedy}`,
            '',
            diagnosis.summary,
          ].filter((line) => line !== '').join('\n')
        : '(no diagnosis)',
      '',
      '## Log excerpt',
      '```',
      logs.split('\n').slice(-40).join('\n') || '(none)',
      '```',
      '',
      entry.evidence ? `Evidence: \`${entry.evidence}\` on the floor.` : '',
    ].join('\n');
    if (ctx.dryRun) {
      ctx.log(`  DRY RUN  would file incident "${title}"`);
      return { issue: 0, created: false, fix: null, diagnosis, withAPerson: false };
    }
    ensureIncidentLabel(ctx);
    const url = sh(ctx, ['gh', 'issue', 'create', '--title', title, '--body', body, '--label', INCIDENT_LABEL]);
    issue = Number(url.trim().split('/').pop());
    ctx.log(`filed incident #${issue}: ${title}`);
  } else {
    ctx.log(`incident #${issue} is already open for ${entry.itemId}; not filing again`);
  }

  // An incident is parked, or handed to the fix pipeline, and both write the loop's own labels. On a
  // repository no other driver has run against those do not exist yet, whether this incident was
  // just filed or was already open.
  if (!ctx.dryRun) ensureLabels(ctx);

  // A remedy outside the repository (a reindex, a config value, a vendor outage) is not code; a
  // worker would only spend a lane proving that. Park it for a person with the diagnosis attached.
  if (diagnosis?.remedy === 'outside-repository') {
    // A new incident carries the diagnosis in its body; an open one learns it here, with the park,
    // or every wake would diagnose it again and every other driver would still read it as work.
    const where = existing === null ? 'See the diagnosis above.' : `Diagnosis (${diagnosis.confidence}): ${diagnosis.summary}`;
    parkIssue(ctx, issue, `The diagnosis places the remedy outside this repository, so no fix was attempted; a person has to act on the environment. ${where}`);
    ctx.log(`incident #${issue}: parked; the remedy is outside the repository`);
    return { issue, created: existing === null, fix: null, diagnosis, withAPerson: true };
  }

  // The fix is the pipeline's job, exactly as for any other issue. The issue is read live, labels and
  // all: the pipeline's attempt and review budgets are counted on them, and an incident walked every
  // wake would otherwise start from zero each time and never run out.
  const live = JSON.parse(sh(ctx, ['gh', 'issue', 'view', String(issue), '--json', 'number,title,createdAt,labels,parent,subIssuesSummary,blockedBy'])) as Issue;
  enrichBlockers(ctx, [live]);
  const fix = await fixIssue(ctx, live, { maxPoints: options.maxPoints });
  ctx.log(`incident #${issue}: ${fix.outcome}; ${fix.reason}`);
  return { issue, created: existing === null, fix, diagnosis, withAPerson: fix.outcome !== 'merged' };
}
reverse-engineer-anythingmorluto/reaReverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis.Stars: 471kUpdated Claude CodeCodexVerifiedInstall
diagnosing-superpowersobra/superpowersUse when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness.Stars: 322kUpdated Claude CodeCodexVerifiedInstall
dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependenciesStars: 322kUpdated Claude CodeCodexVerifiedInstall
executing-plansobra/superpowersUse when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is availableStars: 322kUpdated Claude CodeCodexVerifiedInstall