Skip to content

simiancraft/simiancraft-skills / skills/carve-github-issue

carve-github-issue

Verified

Break one GitHub issue that is too large to work into sub-issues, unattended, and keep the carving honest as the children close. A carver names the pieces along the highest natural seam (domain, tier, route, area, file, unit, material), matches each against the backlog so nothing is authored twice, and a second engine confirms the cut covers the parent before anything is created. The parent becomes a trunk that is finished by closing its children; every child close re-checks the trunk, and a trunk with nothing left goes back to the appraiser. Use when the task is "this issue is too big, split it", "carve #N into sub-issues", "is this carving still good", or when burn-down-github-issues sizes an issue over its ceiling. Requires a per-repository config (its own, or the burndown's), the codex and claude CLIs for the default seats, and GitHub sub-issues on the repository. Skip for fixing anything; this skill writes only to the tracker.

FileKindSize
SKILL.mdskill md5.9 KB
carve.tsscript10.6 KB
lib/callbacks.tsscript1.4 KB
lib/carve.test.tsscript19.0 KB
lib/carve.tsscript25.6 KB
lib/claims.test.tsscript12.9 KB
lib/claims.tsscript13.8 KB
lib/fake-tracker.tsscript9.4 KB
lib/knife.test.tsscript52.3 KB
lib/knife.tsscript52.9 KB
lib/record.tsscript12.7 KB
lib/tree.tsscript23.3 KB
lib/validate.test.tsscript12.8 KB
prompts/carve.mdmarkdown8.1 KB
prompts/confirm-carve.mdmarkdown4.1 KB
prompts/revisit.mdmarkdown4.9 KB
references/adopting.mdmarkdown6.3 KB
references/callbacks.mdmarkdown1.7 KB
references/lifecycle.mdmarkdown29.7 KB
references/seams.mdmarkdown9.1 KB
references/the-record.mdmarkdown6.6 KB

lib/knife.test.ts

View on GitHub
import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { type Context, createContext } from '../../fix-github-issue/lib/context.ts';
import type { ProjectConfig } from '../../fix-github-issue/lib/config.ts';
import { CARVE_DEFAULTS, type CarveKnobs, type Carving, type Confirmation, validateCarving, validateConfirmation } from './carve.ts';
import { FakeTracker, fakeIssue } from './fake-tracker.ts';
import { beginStop, resetStop, RunStopping } from '../../fix-github-issue/lib/shell.ts';
import { awaitReleases, type ClaimHandle, claim, keepClaimed, leaseLost } from './claims.ts';
import { loopLabels } from '../../fix-github-issue/lib/labels.ts';
import { carveIssue, workStarted } from './knife.ts';
import { type Cut, renderRecord, type Record } from './record.ts';
import { readTree } from './tree.ts';
import { Carving as CarvingDriver } from '../../burn-down-github-issues/lib/carving.ts';
import { laneState, successors } from '../../burn-down-github-issues/lib/simulate.ts';
import { ENGINES } from '../../fix-github-issue/lib/engines.ts';
import { runAgent } from '../../fix-github-issue/lib/agent.ts';

const BOT = 'loop-bot';
const HERE = import.meta.dir;
let scratch: string;

beforeAll(() => {
  scratch = mkdtempSync(join(tmpdir(), 'knife-'));
});
// A stop is process-wide, like the signal, so a case that begins one ends by lifting it.
afterEach(resetStop);

describe('the carving driver makes only moves the chart allows', () => {
  function makeDriver(ctx: Context, k: CarveKnobs, lanes: string[], appraiser?: string, confirmer?: string) {
    ctx.onLane = e => lanes.push(e.lane);
    return new CarvingDriver({ ctx, knobs: k, appraisal: { seats: { appraiser: { engine: 'fixture', model: appraiser }, confirmer: { engine: 'fixture2', model: confirmer } }, confirmCloses: true, skipLabels: ['needs-human', 'needs-decision', 'loop/skip', 'loop/parked'], maxAppraiseAttempts: 3, sizeCallbackTimeoutMinutes: 1 }, only: null, ageDays: 100, mark: (_n, _t, lane) => lanes.push(lane), log: () => {} });
  }
  function illegal(lanes: string[]) {
    return lanes.slice(1).flatMap((to, i) => lanes[i] === to || successors(laneState(lanes[i]), { ownEventsOnly: true }).has(laneState(to)) ? [] : [`${lanes[i]}->${to}`]);
  }
  for (const failure of ['carver', 'confirmer', 'setup', 'spawn'] as const) {
    test(`first carving ${failure} failure follows chart edges`, async () => {
      const io = trunk(); const ctx = ctxFor(io); const lanes = ['C1'];
      const k = knobs(fixture('carver', failure === 'carver' ? {} : carving(10)), fixture('confirmer', failure === 'confirmer' ? {} : confirmation(10, 'carve', 'cover', true)));
      if (failure === 'setup') ctx.promptsDirs = [];
      if (failure === 'spawn') io.beforeWrite = op => { if (op.argv[2] === 'create' && op.argv[1] === 'issue') throw new Error('create unavailable'); };
      const d = makeDriver(ctx, k, lanes);
      if (failure === 'setup' || failure === 'spawn') await expect(d.revisit(10, 'first carve')).rejects.toThrow();
      else await d.revisit(10, 'first carve');
      
      expect(illegal(lanes)).toEqual([]);
    });
  }
  test('a trunk whose knife throws in the sweep is rested, and the sweep goes on to the next trunk', async () => {
    const io = new FakeTracker(BOT, [fakeIssue(10, { labels: [{ name: 'size: 8' }] }), fakeIssue(20, { labels: [{ name: 'size: 8' }] })]);
    const ctx = ctxFor(io);
    // No prompts: the knife throws for every trunk it is handed.
    ctx.promptsDirs = [];
    const visited: number[] = [];
    const d = new CarvingDriver({ ctx, knobs: knobs(fixture('carver', carving(10)), fixture('confirmer', confirmation(10, 'carve', 'cover', true))), appraisal: { seats: { appraiser: { engine: 'fixture' }, confirmer: { engine: 'fixture2' } }, confirmCloses: true, skipLabels: [], maxAppraiseAttempts: 3, sizeCallbackTimeoutMinutes: 1 }, only: null, ageDays: 100, mark: (n) => visited.push(n), log: () => {} });
    await d.sweep([10, 20].map((n) => io.view(n)!));
    expect([...new Set(visited)].sort()).toEqual([10, 20]);
  });

  test('a stop during the sweep still ends it', async () => {
    const io = new FakeTracker(BOT, [fakeIssue(10, { labels: [{ name: 'size: 8' }] }), fakeIssue(20, { labels: [{ name: 'size: 8' }] })]);
    const ctx = ctxFor(io);
    ctx.promptsDirs = [];
    const visited: number[] = [];
    const d = new CarvingDriver({ ctx, knobs: knobs(fixture('carver', carving(10)), fixture('confirmer', confirmation(10, 'carve', 'cover', true))), appraisal: { seats: { appraiser: { engine: 'fixture' }, confirmer: { engine: 'fixture2' } }, confirmCloses: true, skipLabels: [], maxAppraiseAttempts: 3, sizeCallbackTimeoutMinutes: 1 }, only: null, ageDays: 100, mark: (n) => { visited.push(n); beginStop(); }, log: () => {} });
    await expect(d.sweep([10, 20].map((n) => io.view(n)!))).rejects.toThrow();
    expect([...new Set(visited)]).toEqual([10]);
  });

  for (const points of [1, 8]) {
    test(`release resumed after size ${points} was written follows chart edges`, async () => {
      const io = new FakeTracker(BOT, [fakeIssue(10, { labels: [{ name: 'loop/released' }, { name: `size: ${points}` }] })]);
      const ctx = ctxFor(io); const lanes = ['C7'];
      const k = knobs(fixture('carve', carving(10)), fixture('cover', confirmation(10, 'carve', 'cover', true)));
      await makeDriver(ctx, k, lanes).releaseAppraisal(10);
      
      expect(illegal(lanes)).toEqual([]);
    });
  }
  test('a release appraisal that fails after its lease was lost counts nothing', async () => {
    const released = () => new FakeTracker(BOT, [fakeIssue(10, { labels: [{ name: 'loop/released' }] })]);
    const k = knobs(fixture('carve', carving(10)), fixture('cover', confirmation(10, 'carve', 'cover', true)));
    const counted = (io: FakeTracker) => io.view(10)!.labels.some((l) => l.name.startsWith('loop/appraisals'));
    const lost = released(); const ctx = ctxFor(lost);
    ctx.log = (m) => {
      if (!/running appraiser/.test(m) || leaseLost(ctx, 10)) return;
      const handle: ClaimHandle = { kind: 'carving', commentId: 1, label: 'loop/carving', issue: 10, key: 'o/r#10', expires: () => 0, renew: () => { throw new Error('tracker down'); }, release: () => {} };
      keepClaimed(handle, undefined, () => 0, (fn) => (fn(), () => {}));
    };
    await makeDriver(ctx, k, ['C7'], fixture('bad-appraisal', {})).releaseAppraisal(10);
    expect(counted(lost)).toBe(false);
    // With the lease held, the same unusable appraisal is counted.
    const held = released();
    await makeDriver(ctxFor(held), k, ['C7'], fixture('bad-appraisal', {})).releaseAppraisal(10);
    expect(counted(held)).toBe(true);
  });
  for (const verdict of ['valid', 'obsolete'] as const) {
    test(`a release appraisal that lands ${verdict} after its lease was lost applies nothing`, async () => {
      const released = () => new FakeTracker(BOT, [fakeIssue(10, { labels: [{ name: 'loop/released' }] })]);
      const k = knobs(fixture('carve', carving(10)), fixture('cover', confirmation(10, 'carve', 'cover', true)));
      const appraiser = () => fixture('appraisal', { issue: 10, verdict, points: verdict === 'valid' ? 1 : undefined, reason: 'r', closeComment: 'gone' });
      const confirmer = () => fixture('close', { issue: 10, agree: true, reason: 'checked' });
      // A sizing is applied straight after the appraiser; a close only after the confirmer.
      const during = verdict === 'valid' ? /running appraiser/ : /running confirmer/;
      const applied = (io: FakeTracker) => (verdict === 'valid' ? io.view(10)!.labels.some((l) => l.name === 'size: 1') : io.view(10)!.state === 'CLOSED');
      const lost = released(); const ctx = ctxFor(lost);
      let lostDuringTurn = false;
      let marksAtLoss = -1;
      const lanes = ['C7'];
      ctx.log = (m) => {
        if (!during.test(m) || leaseLost(ctx, 10)) return;
        lostDuringTurn = true;
        marksAtLoss = lanes.length;
        const handle: ClaimHandle = { kind: 'carving', commentId: 1, label: 'loop/carving', issue: 10, key: 'o/r#10', expires: () => 0, renew: () => { throw new Error('tracker down'); }, release: () => {} };
        keepClaimed(handle, undefined, () => 0, (fn) => (fn(), () => {}));
      };
      await makeDriver(ctx, k, lanes, appraiser(), confirmer()).releaseAppraisal(10);
      // No card was placed for the issue after the loss.
      expect(lanes.length).toBe(marksAtLoss);
      // The mark is gone again once the appraisal's own lease stopped; the turn is what lost it.
      expect(lostDuringTurn).toBe(true);
      expect(leaseLost(ctx, 10)).toBe(false);
      expect(applied(lost)).toBe(false);
      // With the lease held, the same verdict is applied.
      const held = released();
      await makeDriver(ctxFor(held), k, ['C7'], appraiser(), confirmer()).releaseAppraisal(10);
      expect(applied(held)).toBe(true);
    });
  }
  test('the driver places no card when a carve lost its lease and then threw something else', async () => {
    const io = trunk(); const ctx = ctxFor(io); const lanes = ['C1'];
    const k = knobs(fixture('carve', carving(10)), fixture('cover', confirmation(10, 'carve', 'cover', true)));
    let placedBeforeLoss = -1;
    io.beforeWrite = (op) => {
      if (op.argv[1] !== 'issue' || op.argv[2] !== 'create' || leaseLost(ctx, 10)) return;
      const handle: ClaimHandle = { kind: 'carving', commentId: 1, label: 'loop/carving', issue: 10, key: 'o/r#10', expires: () => 0, renew: () => { throw new Error('tracker down'); }, release: () => {} };
      keepClaimed(handle, undefined, () => 0, (fn) => (fn(), () => {}));
      placedBeforeLoss = lanes.length;
      throw new Error('transient tracker failure');
    };
    await makeDriver(ctx, k, lanes).revisit(10, 'first carve');
    expect(placedBeforeLoss).toBeGreaterThan(0);
    expect(lanes.length).toBe(placedBeforeLoss);
  });

  test('the driver places no card when the lease is lost and the knife still returns an ordinary outcome', async () => {
    // The tracker changes under the confirmer, which the knife returns as a failed turn, not a throw,
    // without having tried a write; the lease is lost in the same moment.
    const io = trunk(); const ctx = ctxFor(io); const lanes = ['C1'];
    const k = knobs(fixture('carve', carving(10)), fixture('cover', confirmation(10, 'carve', 'cover', true)));
    let marksAtLoss = -1;
    ctx.log = (m) => {
      if (!/running confirmer/.test(m) || leaseLost(ctx, 10)) return;
      io.comment(10, 'a-person', 'one more thing about this issue');
      const handle: ClaimHandle = { kind: 'carving', commentId: 1, label: 'loop/carving', issue: 10, key: 'o/r#10', expires: () => 0, renew: () => { throw new Error('tracker down'); }, release: () => {} };
      keepClaimed(handle, undefined, () => 0, (fn) => (fn(), () => {}));
      marksAtLoss = lanes.length;
    };
    await makeDriver(ctx, k, lanes).revisit(10, 'first carve');
    expect(marksAtLoss).toBeGreaterThan(0);
    expect(lanes.length).toBe(marksAtLoss);
    expect(records(io, 10)).toEqual([]);
  });

  test('the driver places no card for a carve that lost its lease', async () => {
    const io = trunk(); const ctx = ctxFor(io); const lanes = ['C1'];
    const k = knobs(fixture('carve', carving(10)), fixture('cover', confirmation(10, 'carve', 'cover', true)));
    let placedBeforeLoss = -1;
    io.beforeWrite = (op) => {
      if (op.argv[1] !== 'issue' || op.argv[2] !== 'create' || leaseLost(ctx, 10)) return;
      const handle: ClaimHandle = { kind: 'carving', commentId: 1, label: 'loop/carving', issue: 10, key: 'o/r#10', expires: () => 0, renew: () => { throw new Error('tracker down'); }, release: () => {} };
      keepClaimed(handle, undefined, () => 0, (fn) => (fn(), () => {}));
      placedBeforeLoss = lanes.length;
    };
    await makeDriver(ctx, k, lanes).revisit(10, 'first carve');
    expect(placedBeforeLoss).toBeGreaterThan(0);
    expect(lanes.length).toBe(placedBeforeLoss);
  });
  test('an appraisal sizes an issue on a repository that has no size labels yet', async () => {
    const io = new FakeTracker(BOT, [fakeIssue(10, { labels: [{ name: 'loop/released' }] })]);
    // Like gh: a label the repository does not have cannot be put on an issue.
    io.beforeWrite = (op) => {
      const at = op.argv.indexOf('--add-label');
      if (at > -1 && op.argv[at + 1].startsWith('size:') && !io.repoLabels.has(op.argv[at + 1])) throw new Error(`'${op.argv[at + 1]}' not found`);
    };
    const k = knobs(fixture('carve', carving(10)), fixture('cover', confirmation(10, 'carve', 'cover', true)));
    // Which labels were ensured is remembered per repository for the life of the process, so this
    // adopter gets a repository no other test has touched.
    const ctx = ctxFor(io);
    ctx.project = { ...ctx.project, repo: 'o/fresh-adopter' };
    await makeDriver(ctx, k, ['C7'], fixture('appraisal', { issue: 10, verdict: 'valid', points: 1, reason: 'small' })).releaseAppraisal(10);
    expect(io.view(10)!.labels.map((l) => l.name)).toContain('size: 1');
    expect(io.view(10)!.labels.some((l) => l.name.startsWith('loop/appraisals'))).toBe(false);
  });

  test('a trunk with open children but no record enters its first carving along a chart edge', async () => {
    const io = new FakeTracker(BOT, [fakeIssue(10, { subIssues: [11] }), fakeIssue(11, { parentNumber: 10 })]);
    const ctx = ctxFor(io); const lanes = ['C5'];
    await makeDriver(ctx, knobs(fixture('bad', {}), fixture('bad2', {})), lanes).revisit(10, 'open child, no record');
    expect(illegal(lanes)).toEqual([]);
  });
  test('a resumed release with the new carving already recorded has a chart edge', async () => {
    const io = trunk(); const ctx = ctxFor(io);
    const k = knobs(fixture('carve', carving(10)), fixture('cover', confirmation(10, 'carve', 'cover', true)));
    await carveIssue(ctx, issue10, k, io);
    io.addLabel(10, 'loop/released');
    const lanes = ['C7']; await makeDriver(ctx, k, lanes).releaseAppraisal(10);
    expect(illegal(lanes)).toEqual([]);
  });
  test('lifting a carve dead letter reaches Revisiting along a chart edge', async () => {
    const io = trunk(); const ctx = ctxFor(io);
    await carveIssue(ctx, issue10, knobs(fixture('carve', carving(10)), fixture('cover', confirmation(10, 'carve', 'cover', true))), io);
    const answer = { ...carving(10), mode: 'revisit', verdict: 'still-good', cuts: undefined, chosen: undefined };
    const k = knobs(fixture('still-good', answer), fixture('agree', confirmation(10, 'revisit', 'still-good', true)), { maxRevisitsPerGeneration: 0 });
    expect((await carveIssue(ctx, issue10, k, io)).outcome).toBe('dlq');
    io.removeLabel(10, 'loop/dlq: carve');
    const lanes = ['Q2']; await makeDriver(ctx, k, lanes).revisit(10, 'person lifted carve DLQ');
    expect(readTree(ctx, 10, io).record!.epoch).toBe(2);
    expect(illegal(lanes)).toEqual([]);
  });
  test('an oversized release whose confirmer fails follows chart edges', async () => {
    const io = new FakeTracker(BOT, [fakeIssue(10, { labels: [{ name: 'loop/released' }, { name: 'size: 8' }] })]);
    const lanes = ['C7']; const ctx = ctxFor(io);
    await makeDriver(ctx, knobs(fixture('carve', carving(10)), fixture('invalid-confirmation', {})), lanes).releaseAppraisal(10);
    
    expect(illegal(lanes)).toEqual([]);
  });
  test('an interrupted applying record resumes in its own lane', async () => {
    const io = trunk(); const ctx = ctxFor(io);
    const k = knobs(fixture('carve', carving(10)), fixture('cover', confirmation(10, 'carve', 'cover', true)));
    io.beforeWrite = op => { if (op.argv[1] === 'issue' && op.argv[2] === 'create') throw new Error('interrupted'); };
    await expect(carveIssue(ctx, issue10, k, io)).rejects.toThrow();
    io.beforeWrite = null;
    const lanes = ['C4']; await makeDriver(ctx, k, lanes).revisit(10, 'finish applying');
    
    expect(illegal(lanes)).toEqual([]);
  });
  for (const oldSizeStillPresent of [true, false]) test(`interrupted release retains its outcome (old size present: ${oldSizeStillPresent})`, async () => {
    const io = trunk(); const ctx = ctxFor(io);
    const k = knobs(fixture('carve', carving(10)), fixture('cover', confirmation(10, 'carve', 'cover', true)));
    await carveIssue(ctx, issue10, k, io);
    for (const child of io.view(10)!.subIssues) io.close(child);
    const record = readTree(ctx, 10, io).record!;
    io.comment(10, BOT, renderRecord({ ...record, state: 'released', verdict: 'exhausted' }));
    if (!oldSizeStillPresent) io.removeLabel(10, 'size: 8');
    const lanes = ['C7'];
    await makeDriver(ctx, k, lanes, fixture('remainder', { issue: 10, verdict: 'valid', points: 1, reason: 'small remainder' })).revisit(10, 'finish release');
    
    expect(lanes.at(-1)).toBe('B1');
    expect(labels(io, 10)).not.toContain('loop/released');
  });
  for (const when of ['appraising', 'confirming'] as const) {
    test(`release appraisal reconciles a hold added while ${when}`, async () => {
      const io = new FakeTracker(BOT, [fakeIssue(10, { labels: [{ name: 'loop/released' }] })]);
      const ctx = ctxFor(io); const lanes = ['C7'];
      const k = knobs('', '');
      const d = makeDriver(ctx, k, lanes, fixture('appraisal', { issue: 10, verdict: 'obsolete', reason: 'no longer needed' }), fixture('close', { issue: 10, agree: true, reason: 'agreed' }));
      if (when === 'appraising') {
        // A person posts the hold after the preflight read and before the verdict is applied.
        const original = io.view.bind(io); let reads = 0;
        io.view = n => { if (n === 10 && ++reads === 5) io.addLabel(10, 'needs-human'); return original(n); };
      } else ctx.onLane = e => { lanes.push(e.lane); if (e.lane === 'A3') io.addLabel(10, 'needs-human'); };
      await d.releaseAppraisal(10);
      expect(io.view(10)!.state).toBe('OPEN');
      expect(labels(io, 10)).toContain('needs-human');
      
      expect(lanes.at(-1)).toBe('H2');
    });
  }
  test('the fixture engine supports the reproof seat used by resumes', async () => {
    const ctx = ctxFor(trunk());
    const result = await runAgent(ctx, 'worker-reprove', 10, join(scratch, 'reproof'), { engine: 'fixture', model: fixture('fixed', { issue: 10, verdict: 'fixed', pr: 7, reason: 'proved' }) }, 'reprove');
    expect(result.exitCode).toBe(0);
  });
  test('an applying record cannot hide a human hold and foreign claim on the board', async () => {
    const io = trunk(); const ctx = ctxFor(io);
    const k = knobs(fixture('carve', carving(10)), fixture('cover', confirmation(10, 'carve', 'cover', true)));
    io.beforeWrite = op => { if (op.argv[1] === 'issue' && op.argv[2] === 'create') throw new Error('interrupted'); };
    await expect(carveIssue(ctx, issue10, k, io)).rejects.toThrow();
    io.beforeWrite = null;
    io.addLabel(10, 'needs-human');
    io.comment(10, BOT, '<!-- carve-claim kind=carving run=other-host-2-2 at=2026-01-01T00:00:00Z expires=2999-01-01T00:00:00Z -->');
    const lanes: string[] = [];
    await makeDriver(ctx, k, lanes).revisit(10, 'busy held trunk');
    expect(labels(io, 10)).toContain('needs-human');
    expect(labels(io, 10)).toContain('loop/carving');
    expect(lanes.at(-1)).toBe('H2');
  });
});
afterAll(() => {
  rmSync(scratch, { recursive: true, force: true });
});

const PROJECT: ProjectConfig = {
  name: 'Test',
  repo: 'o/r',
  remote: 'origin',
  baseBranch: 'main',
  evidenceBranch: 'evidence',
  checkCommand: 'true',
  installCommand: 'true',
  conventionDocs: [],
  sizingScale: 'fib',
  sharedServices: [],
  portBase: 9000,
  portSpan: 10,
  pathAliases: [],
  sourceExtensions: ['.ts'],
  alwaysInvalidates: [],
  touchPaths: { migration: [], ci: [] },
  worktreeRoot: '../wt',
};

function fixture(name: string, answer: unknown): string {
  const path = join(scratch, `${name}-${Math.random().toString(36).slice(2)}.json`);
  writeFileSync(path, JSON.stringify(answer));
  return path;
}

function ctxFor(io: FakeTracker, runId = 'host-1-1'): Context {
  const ctx = createContext({
    project: PROJECT,
    knobs: { autoMerge: 'never', maxReviewRounds: 3, checksTimeoutMinutes: 1, smokeTimeoutMinutes: 1 },
    seats: { worker: { engine: 'fixture' }, reviewer: { engine: 'fixture2' } },
    repoRoot: scratch,
    invokeRoot: scratch,
    promptsDirs: [join(HERE, '..', 'prompts'), join(HERE, '..', '..', 'appraise-github-issues', 'prompts')],
    dryRun: false,
    runDir: join(scratch, 'runs'),
    botLogin: BOT,
    io,
    log: () => {},
    step: () => {},
  });
  ctx.runId = runId;
  return ctx;
}

/** Knobs whose seats are real engines, which a dry run does not run. */
function realSeats(): CarveKnobs {
  return { ceiling: 2, ...CARVE_DEFAULTS, callbacksDir: join(scratch, 'callbacks'), seats: { carver: { engine: 'claude' }, confirmer: { engine: 'codex' } } };
}

function knobs(carver: string, confirmer: string, partial: Partial<CarveKnobs> = {}): CarveKnobs {
  return { ceiling: 2, ...CARVE_DEFAULTS, callbacksDir: join(scratch, 'callbacks'), seats: { carver: { engine: 'fixture', model: carver }, confirmer: { engine: 'fixture2', model: confirmer } }, ...partial };
}

const body = '## Scope\nx\n## Acceptance\ny\n## Proof\nz';
const CRIT = [
  { id: 'A1', text: 'a posts table' },
  { id: 'A2', text: 'a posts API' },
  { id: 'A3', text: 'an authors table' },
];
function carving(issue: number, partial: Partial<Carving> = {}): Carving {
  return {
    issue,
    mode: 'carve',
    verdict: 'carve',
    reason: 'two domain objects',
    criteria: CRIT,
    ledger: [
      { id: 'A1', text: 'a posts table', owner: 0, status: 'open' },
      { id: 'A2', text: 'a posts API', owner: 0, status: 'open' },
      { id: 'A3', text: 'an authors table', owner: 1, status: 'open' },
    ],
    chosen: 0,
    cuts: [
      {
        seam: 'domain',
        higherRungs: [],
        relation: 'layers',
        state: 'complete',
        deferred: [],
        pieces: [
          { kind: 'author', title: '[t] posts', body, points: 2, role: 'work', criteria: ['A1', 'A2'], dependsOn: [], order: 1, orderRung: 'source-of-truth' },
          { kind: 'author', title: '[t] authors', body, points: 2, role: 'work', criteria: ['A3'], dependsOn: [0], order: 2, orderRung: 'dependency' },
        ],
        groundwork: [],
        width: null,
        balance: 'two and one',
        independence: 'authors reads nothing from posts',
      },
    ],
    ...partial,
  };
}
function confirmation(issue: number, mode: 'carve' | 'revisit', finding: Confirmation['finding'], agree: boolean): Confirmation {
  return { issue, mode, agree, finding, seam: 'agree', seamCase: '', reason: agree ? 'yes' : 'no: A3 unowned' };
}

function trunk(): FakeTracker {
  return new FakeTracker(BOT, [fakeIssue(10, { title: '[t] big', body: 'Criteria: A1 A2 A3', labels: [{ name: 'size: 8' }] })]);
}
const issue10 = { number: 10, title: '[t] big', createdAt: '2026-09-01T00:00:00Z', labels: [{ name: 'size: 8' }] };
const records = (io: FakeTracker, n: number) => io.view(n)!.comments.filter((c) => c.body.startsWith('<!-- carve-record')).map((c) => /state=(\w+)/.exec(c.body)?.[1]);
const labels = (io: FakeTracker, n: number) => io.view(n)!.labels.map((l) => l.name).sort();

describe('the knife writes nothing without the lease', () => {
  test('asks for it before it creates a label, which is a write like any other', () => {
    const source = readFileSync(new URL('./knife.ts', import.meta.url), 'utf8');
    const funnel = source.slice(source.indexOf('function addLabel('), source.indexOf('function removeLabel('));
    const lease = funnel.indexOf('holdLease(k,');
    const ensure = funnel.indexOf('ensureLabel(k.ctx,');
    expect(lease).toBeGreaterThan(-1);
    expect(ensure).toBeGreaterThan(-1);
    expect(lease).toBeLessThan(ensure);
  });
});

describe('carveIssue', () => {
  for (const role of ['carver', 'confirmer'] as const) {
    for (const repairs of [true, false]) {
      test(`${role} gets exactly one validation repair; repair succeeds: ${repairs}`, async () => {
        const io = trunk(); const ctx = ctxFor(io);
        const good = role === 'carver' ? carving(10) : confirmation(10, 'carve', 'cover', true);
        const answer = fixture('invalid', {});
        const k = knobs(role === 'carver' ? answer : fixture('carve', carving(10)), role === 'confirmer' ? answer : fixture('cover', confirmation(10, 'carve', 'cover', true)));
        const engine = ENGINES[k.seats[role].engine];
        const original = engine.command;
        const turns: Array<{ cwd: string; prompt: string }> = [];
        engine.command = (cwd, prompt, model, effort) => {
          turns.push({ cwd, prompt });
          if (turns.length === 2 && repairs) writeFileSync(answer, JSON.stringify(good));
          return original(cwd, prompt, model, effort);
        };
        try {
          const outcome = await carveIssue(ctx, issue10, k, io);
          expect(turns).toHaveLength(2);
          expect(turns[1].cwd).toBe(turns[0].cwd);
          expect(turns[1].prompt).toContain('Rejected answer:\n{}');
          const checked = role === 'carver'
            ? validateCarving({}, { mode: 'carve', knobs: k, tree: readTree(ctx, 10, io), scale: ctx.knobs.pointScale })
            : validateConfirmation({}, 'carve');
          expect(checked.ok).toBe(false);
          if (!checked.ok) expect(turns[1].prompt).toContain(`Validator faults (verbatim):\n${checked.faults.join('\n')}`);
          expect(turns[1].prompt).toContain('one repair turn');
          if (repairs) {
            expect(outcome.outcome).toBe('carve');
            expect(labels(io, 10).some(l => l.startsWith('loop/carves'))).toBe(false);
          } else {
            expect(outcome.outcome).toBe('failed');
            expect(labels(io, 10)).toContain('loop/carves: 1');
            expect(records(io, 10)).toEqual([]);
          }
        } finally {
          engine.command = original;
        }
      });
    }
  }

  for (const role of ['carver', 'confirmer'] as const) {
    test(`${role} process failure does not receive a validation repair`, async () => {
      const io = trunk(); const ctx = ctxFor(io);
      const answer = fixture('crash', {});
      writeFileSync(answer.replace(/\.json$/, `.${role}.sh`), 'exit 3\n');
      let turns = 0;
      ctx.log = message => { if (message.includes(`running ${role}`)) turns++; };
      const k = knobs(role === 'carver' ? answer : fixture('carve', carving(10)), role === 'confirmer' ? answer : fixture('cover', confirmation(10, 'carve', 'cover', true)));
      const outcome = await carveIssue(ctx, issue10, k, io);
      expect(outcome.outcome).toBe('failed');
      expect(turns).toBe(1);
      expect(labels(io, 10)).toContain('loop/carves: 1');
    });
  }

  test('a revised cut rejected after a confirmer objection is repaired within the same round', async () => {
    const io = trunk(); const ctx = ctxFor(io);
    const carver = fixture('carve', carving(10));
    const confirmer = fixture('confirm', confirmation(10, 'carve', 'gap', false));
    let carves = 0; let confirms = 0;
    ctx.log = message => {
      if (message.includes('running carver')) {
        carves++;
        writeFileSync(carver, JSON.stringify(carves === 2 ? {} : carving(10)));
      }
      if (message.includes('running confirmer') && ++confirms === 2) {
        writeFileSync(confirmer, JSON.stringify(confirmation(10, 'carve', 'cover', true)));
      }
    };
    const outcome = await carveIssue(ctx, issue10, knobs(carver, confirmer, { maxCarveRounds: 2 }), io);
    expect(outcome.outcome).toBe('carve');
    expect(carves).toBe(3);
    expect(confirms).toBe(2);
    expect(labels(io, 10).some(l => l.startsWith('loop/carves'))).toBe(false);
  });

  test('a carver stopped with the run settles nothing: no count, no record, and the claim released by the lane itself', async () => {
    const io = trunk();
    const ctx = ctxFor(io);
    ctx.log = (m) => {
      if (/running carver/.test(m)) beginStop();
    };
    const k = knobs(fixture('carve', {}), fixture('cover', confirmation(10, 'carve', 'cover', true)));
    await expect(carveIssue(ctx, issue10, k, io)).rejects.toThrow(RunStopping);
    expect(labels(io, 10).some((l) => l.startsWith('loop/carves'))).toBe(false);
    expect(records(io, 10)).toEqual([]);
    // The release is the one write the stop allows, and it happened in the lane's own finally.
    expect(labels(io, 10)).not.toContain('loop/carving');
    expect(io.view(10)!.comments.some((c) => c.body.startsWith('<!-- carve-unclaim'))).toBe(true);
    expect(await awaitReleases(0)).toEqual([]);
  });

  test('a release appraisal stopped with the run counts no failed appraisal', async () => {
    const io = new FakeTracker(BOT, [fakeIssue(10, { labels: [{ name: 'loop/released' }] })]);
    const ctx = ctxFor(io);
    ctx.log = (m) => {
      if (/running appraiser/.test(m)) beginStop();
    };
    const k = knobs(fixture('carve', carving(10)), fixture('cover', confirmation(10, 'carve', 'cover', true)));
    await expect(new CarvingDriver({ ctx, knobs: k, appraisal: { seats: { appraiser: { engine: 'fixture', model: fixture('bad', {}) }, confirmer: { engine: 'fixture2' } }, confirmCloses: true, skipLabels: [], maxAppraiseAttempts: 3, sizeCallbackTimeoutMinutes: 1 }, only: null, ageDays: 100, mark: () => {}, log: () => {} }).releaseAppraisal(10)).rejects.toThrow(RunStopping);
    expect(labels(io, 10).some((l) => l.startsWith('loop/appraisals'))).toBe(false);
    expect(await awaitReleases(0)).toEqual([]);
  });

  test('a claim is held from the moment it is posted, and a stop during its readback still releases it', async () => {
    const io = trunk();
    const ctx = ctxFor(io);
    let heldWhilePosting: string[] = [];
    io.beforeWrite = (op) => {
      if (!/^claim #10/.test(op.description)) return;
      void awaitReleases(0).then((held) => (heldWhilePosting = held));
      // Another run's earlier claim wins the readback, so this one rolls back, under the stop.
      io.comment(10, BOT, '<!-- carve-claim kind=carving run=other-host-1-1 at=2026-01-01T00:00:00Z expires=2999-01-01T00:00:00Z token=t -->');
      beginStop();
    };
    // The label write after the claim comment is refused by the stop; the claim must not stay held.
    await expect(claim(ctx, io, 10, 'carving')).rejects.toThrow(RunStopping);
    expect(heldWhilePosting).toEqual(['o/r#10']);
    // The half-made claim was withdrawn, which is the one write a stop allows, and is held no longer.
    expect(io.view(10)!.comments.filter((c) => c.body.startsWith('<!-- carve-unclaim')).length).toBe(1);
    expect(await awaitReleases(0)).toEqual([]);
  });

  test('a release that could not be written leaves the claim held, so a stop still names it', async () => {
    const io = trunk();
    const handle = await claim(ctxFor(io), io, 10, 'carving');
    if (handle === 'busy') throw new Error('expected a claim');
    io.throwOn = /^unclaim #10/;
    expect(() => handle.release()).toThrow(/injected failure/);
    expect(await awaitReleases(0)).toEqual(['o/r#10']);
    handle.release();
    expect(await awaitReleases(0)).toEqual([]);
  });

  test('a claim nobody released is named when the wait for releases runs out', async () => {
    const io = trunk();
    const handle = await claim(ctxFor(io), io, 10, 'carving');
    expect(await awaitReleases(0)).toEqual(['o/r#10']);
    if (handle !== 'busy') handle.release();
    expect(await awaitReleases(0)).toEqual([]);
  });

  test('a dry run rehearses finishing an announced generation, and stops at the first seat it does not run', async () => {
    // A real run is interrupted after the applying record and one child, the way roster's carves were.
    const io = trunk();
    const ctx = ctxFor(io);
    const k = knobs(fixture('carve', carving(10)), fixture('cover', confirmation(10, 'carve', 'cover', true)));
    io.beforeWrite = (op) => {
      if (op.argv[1] === 'issue' && op.argv[2] === 'create' && io.view(10)!.subIssues.length > 0) throw new Error('interrupted');
    };
    await expect(carveIssue(ctx, issue10, k, io)).rejects.toThrow();
    io.beforeWrite = null;
    const announced = records(io, 10);
    const children = io.view(10)!.subIssues.length;
    expect(announced).toEqual(['applying']);
    expect(children).toBe(1);

    // Now a dry run with REAL seats: it has no carver to run, and does not need one to finish this.
    const dry = ctxFor(io);
    dry.dryRun = true;
    const out = await carveIssue(dry, issue10, realSeats(), io);
    expect(out.outcome).toBe('resumed');
    expect(dry.dryRunLog.some((d) => /^create child/.test(d))).toBe(true);
    // Rehearsed, not done: the tracker is as the interrupted run left it.
    expect(records(io, 10)).toEqual(announced);
    expect(io.view(10)!.subIssues.length).toBe(children);
  });

  for (const pr of ['merged', 'open'] as const) test(`an announced generation whose reference turned out to be ${pr === 'open' ? 'an' : 'a'} ${pr} pull request goes to a person whole, with no edge to it`, async () => {
    // A cut that named #50 was announced before references were checked for pull requests, and
    // the attach of #50 was where the run stopped. GitHub answers an issue read for a pull request
    // and refuses one as a sub-issue or a blocker, so the next visit must not try either; finishing
    // part of the cut would leave edges and a ledger no later read agrees with.
    const io = trunk();
    io.issues.set(50, fakeIssue(50, { title: 'the work, already merged' }));
    const ctx = ctxFor(io);
    const pieces = [
      { kind: 'reference' as const, number: 50, points: null, role: 'work' as const, criteria: ['A1', 'A2'], dependsOn: [], order: 1, orderRung: 'source-of-truth' as const },
      { kind: 'author' as const, title: '[t] authors', body, points: 2, role: 'work' as const, criteria: ['A3'], dependsOn: [0], order: 2, orderRung: 'dependency' as const },
    ];
    const [base] = carving(10).cuts as [Cut];
    const cut: Cut = { ...base, relation: 'mixed', pieces };
    const k = knobs(fixture('carve', carving(10, { cuts: [cut] })), fixture('cover', confirmation(10, 'carve', 'cover', true)));
    io.beforeWrite = (op) => {
      if (op.argv[2] === 'edit' && op.argv[3] === '50' && op.argv.includes('--parent')) throw new Error('interrupted');
    };
    await expect(carveIssue(ctx, issue10, k, io)).rejects.toThrow();
    expect(records(io, 10)).toEqual(['applying']);

    // What #50 really is: a pull request.
    io.beforeWrite = null;
    io.issues.set(50, fakeIssue(50, pr === 'merged' ? { title: 'the work', state: 'CLOSED', stateReason: 'COMPLETED', pullRequest: 'merged' } : { title: 'the work', pullRequest: 'open' }));
    const writes = io.writes.length;
    const out = await carveIssue(ctx, issue10, k, io);
    expect(out.reason).toMatch(/#50, which is a pull request/);
    const after = io.writes.slice(writes);
    expect(after.some((w) => w.argv.includes('--parent') || w.argv.includes('--add-blocked-by'))).toBe(false);
    expect(io.view(50)!.parent).toBeNull();
    expect(out.outcome).toBe('dlq');
    expect(labels(io, 10)).toContain('loop/dlq: carve');
  });

  test('a dry run with no fixture seat stops at the carver, and calls it nothing that failed', async () => {
    const io = trunk();
    const ctx = ctxFor(io);
    ctx.dryRun = true;
    const out = await carveIssue(ctx, issue10, realSeats(), io);
    expect(out).toEqual({ outcome: 'not-run', reason: 'dry run: the carver was not run' });
    expect(io.writes).toEqual([]);
    expect(ctx.dryRunLog.some((d) => /loop\/carves/.test(d))).toBe(false);
  });

  test('a first carve on a repository that has never been carved: the generation label does not exist yet', async () => {
    const io = trunk();
    // Like gh: a label the repository does not have cannot be put on an issue. Every fixed label
    // is created at start by the driver; the generation label is a new name with every generation.
    for (const [name] of loopLabels()) io.repoLabels.add(name);
    io.beforeWrite = (op) => {
      const at = op.argv.indexOf('--add-label');
      if (at > -1 && !io.repoLabels.has(op.argv[at + 1])) throw new Error(`'${op.argv[at + 1]}' not found`);
    };
    const ctx = ctxFor(io);
    ctx.project = { ...ctx.project, repo: 'o/never-carved' };
    const out = await carveIssue(ctx, issue10, knobs(fixture('carve', carving(10)), fixture('cover', confirmation(10, 'carve', 'cover', true))), io);
    expect(out.outcome).toBe('carve');
    expect(labels(io, 10)).toContain('loop/carve-gen: 1');
    expect(labels(io, 10).some((l) => l.startsWith('loop/carves'))).toBe(false);
    expect(records(io, 10)).toEqual(['applying', 'live']);
  });

  test('a knife that loses its lease mid-carve stops writing, counts nothing, and resumes on the next visit', async () => {
    const io = trunk();
    const ctx = ctxFor(io);
    const k = knobs(fixture('carve', carving(10)), fixture('cover', confirmation(10, 'carve', 'cover', true)));
    // The lease is lost the way it is in a run: a renewal fails with the expiry already past. The
    // first child is being created when it happens, so that write lands and the next one must not.
    const loseLease = () => {
      const handle: ClaimHandle = { kind: 'carving', commentId: 1, label: 'loop/carving', issue: 10, key: 'o/r#10', expires: () => 0, renew: () => { throw new Error('tracker down'); }, release: () => {} };
      keepClaimed(handle, undefined, () => 0, (fn) => (fn(), () => {}));
    };
    io.beforeWrite = (op) => {
      if (op.argv[1] === 'issue' && op.argv[2] === 'create' && !leaseLost(ctx, 10)) loseLease();
    };
    const out = await carveIssue(ctx, issue10, k, io);
    expect(out).toMatchObject({ outcome: 'lease-lost', reason: expect.stringMatching(/lost its lease/) });
    const written = io.writes.length;
    expect(io.view(10)!.subIssues).toHaveLength(1);
    expect(labels(io, 10).some((l) => l.startsWith('loop/carves'))).toBe(false);
    expect(records(io, 10)).toEqual(['applying']);

    // The announced generation is finished by the next visit, whose fresh claim clears the loss.
    io.beforeWrite = null;
    const again = await carveIssue(ctx, issue10, k, io);
    expect(again.outcome).toBe('resumed');
    expect(io.writes.length).toBeGreaterThan(written);
    expect(io.view(10)!.subIssues).toHaveLength(2);
    expect(records(io, 10)).toEqual(['applying', 'live']);
  });
  test('a carver that fails after the lease was lost is not counted: the count is a write too', async () => {
    const io = trunk();
    const ctx = ctxFor(io);
    const k = knobs(fixture('carve', {}), fixture('cover', confirmation(10, 'carve', 'cover', true)));
    // Lost while the carver runs, which then hands back an answer the knife cannot use.
    ctx.log = (m) => {
      if (!/running carver/.test(m) || leaseLost(ctx, 10)) return;
      const handle: ClaimHandle = { kind: 'carving', commentId: 1, label: 'loop/carving', issue: 10, key: 'o/r#10', expires: () => 0, renew: () => { throw new Error('tracker down'); }, release: () => {} };
      keepClaimed(handle, undefined, () => 0, (fn) => (fn(), () => {}));
    };
    const out = await carveIssue(ctx, issue10, k, io);
    expect(out.outcome).toBe('lease-lost');
    expect(labels(io, 10).some((l) => l.startsWith('loop/carves'))).toBe(false);
    // With the lease held, the same failed turn is counted.
    ctx.log = () => {};
    expect((await carveIssue(ctx, issue10, k, io)).outcome).toBe('failed');
    expect(labels(io, 10)).toContain('loop/carves: 1');
  });
  test('a full carve: children in delivery order, an edge, no size labels, applying then live, labels, claim released', async () => {
    const io = trunk();
    const ctx = ctxFor(io);
    const out = await carveIssue(ctx, issue10, knobs(fixture('carve', carving(10)), fixture('cover', confirmation(10, 'carve', 'cover', true))), io);
    expect(out.outcome).toBe('carve');
    expect(out.generation).toBe(1);
    const t = readTree(ctx, 10, io);
    expect(t.children.map((c) => c.title)).toEqual(['[t] posts', '[t] authors']);
    expect(t.children[1].blockedBy?.nodes.map((b) => b.number)).toEqual([t.children[0].number]);
    expect(t.children.every((c) => !c.labels.some((l) => l.name.startsWith('size:')))).toBe(true);
    expect(t.children[0].body.startsWith('<!-- carve parent=10 gen=1 piece=0 -->')).toBe(true);
    expect(records(io, 10)).toEqual(['applying', 'live']);
    expect(labels(io, 10)).toEqual(['loop/carve-gen: 1', 'loop/carved', 'size: 8']);
    expect(t.claims.every((c) => c.released)).toBe(true);
    expect(t.record?.children.map((c) => c.number)).toEqual(t.children.map((c) => c.number));
  });

  test('the knife moves its own card: Carving, Confirming cut, Spawning children, in that order', async () => {
    const io = trunk();
    const ctx = ctxFor(io);
    const lanes: string[] = [];
    ctx.onLane = (event) => {
      lanes.push(event.lane);
    };
    await carveIssue(ctx, issue10, knobs(fixture('carve', carving(10)), fixture('cover', confirmation(10, 'carve', 'cover', true))), io);
    expect(lanes).toEqual(['C2', 'C3', 'C4']);
  });

  test('a dispute to the round cap is a carve dead letter, with every open leaf paused and no child created', async () => {
    const io = new FakeTracker(BOT, [fakeIssue(10, { title: '[t] big', labels: [{ name: 'size: 8' }], subIssues: [11] }), fakeIssue(11, { parentNumber: 10, title: 'leaf' })]);
    const ctx = ctxFor(io);
    const out = await carveIssue(ctx, issue10, knobs(fixture('carve', carving(10)), fixture('gap', confirmation(10, 'carve', 'gap', false))), io);
    // Two engines that never agreed is the machine giving up, not an opinion about the issue.
    expect(out.outcome).toBe('dlq');
    expect(out.reason).toMatch(/disagreed 5 times/);
    expect(labels(io, 10)).toContain('loop/dlq: carve');
    expect(labels(io, 10)).not.toContain('needs-human');
    expect(io.view(10)!.subIssues).toEqual([11]);
    expect(labels(io, 11)).toContain('loop/paused');
    expect(io.view(11)!.comments.some((c) => c.body.includes('carve-pause by=10'))).toBe(true);
    expect(records(io, 10)).toEqual(['live']);
    expect(io.view(10)!.comments.filter((c) => c.body.startsWith('<!-- carve-handoff')).length).toBe(1);
  });

  test('a crash after the first child is finished by the next run without a duplicate', async () => {
    const io = trunk();
    const ctx = ctxFor(io);
    let creates = 0;
    io.beforeWrite = (op) => {
      if (op.argv[2] === 'create' && ++creates === 2) throw new Error('boom');
    };
    const k = knobs(fixture('carve', carving(10)), fixture('cover', confirmation(10, 'carve', 'cover', true)));
    await expect(carveIssue(ctx, issue10, k, io)).rejects.toThrow('boom');
    expect(records(io, 10)).toEqual(['applying']);
    expect(labels(io, 10)).toContain('loop/carving');
    io.beforeWrite = null;
    const again = await carveIssue(ctxFor(io, 'host-2-2'), issue10, k, io);
    expect(again.outcome).toBe('resumed');
    const t = readTree(ctx, 10, io);
    expect(t.children.map((c) => c.title)).toEqual(['[t] posts', '[t] authors']);
    expect(records(io, 10)).toEqual(['applying', 'live']);
    expect(labels(io, 10)).not.toContain('loop/carving');
  });

  test('a second runner on a claimed trunk returns busy', async () => {
    const io = trunk();
    io.comment(10, BOT, '<!-- carve-claim kind=carving run=other-host-7-7 at=2026-09-03T12:00:00Z expires=2999-01-01T00:00:00Z -->');
    const out = await carveIssue(ctxFor(io), issue10, knobs(fixture('carve', carving(10)), fixture('cover', confirmation(10, 'carve', 'cover', true))), io);
    expect(out.outcome).toBe('busy');
  });

  async function carved(): Promise<{ io: FakeTracker; ctx: Context; children: number[] }> {
    const io = trunk();
    const ctx = ctxFor(io);
    const out = await carveIssue(ctx, issue10, knobs(fixture('carve', carving(10)), fixture('cover', confirmation(10, 'carve', 'cover', true))), io);
    return { io, ctx, children: out.children ?? [] };
  }
  const revisit = (issue: number, verdict: Carving['verdict'], partial: Partial<Carving> = {}): Carving => ({ ...carving(issue), mode: 'revisit', verdict, cuts: undefined, chosen: undefined, ...partial });

  test('still-good after a leaf closes: a roll of the ledger and revisits 1', async () => {
    const { io, ctx, children } = await carved();
    io.close(children[0]);
    const ledger = carving(10).ledger.map((r) => (r.owner === 0 ? { ...r, status: 'completed' as const } : r));
    const out = await carveIssue(ctx, issue10, knobs(fixture('sg', revisit(10, 'still-good', { ledger })), fixture('yes', confirmation(10, 'revisit', 'still-good', true))), io);
    expect(out.outcome).toBe('still-good');
    const r = readTree(ctx, 10, io).record as Record;
    expect(r.revisits).toBe(1);
    expect(r.ledger.filter((l) => l.status === 'completed').map((l) => l.id)).toEqual(['A1', 'A2']);
    expect(records(io, 10)).toEqual(['applying', 'live', 'live']);
  });

  test('a question pauses exactly the owner of the affected criterion; removing the hold redrives into a new epoch', async () => {
    const { io, ctx, children } = await carved();
    const out = await carveIssue(ctx, issue10, knobs(fixture('tu', revisit(10, 'too-uncertain', { affected: ['A3'] })), fixture('ho', confirmation(10, 'revisit', 'hand-off-agree', true))), io);
    expect(out.outcome).toBe('too-uncertain');
    expect(labels(io, 10)).toContain('needs-decision');
    expect(labels(io, children[1])).toContain('loop/paused');
    expect(labels(io, children[0])).not.toContain('loop/paused');
    // A revisit while held only snapshots (already recorded) and leaves it.
    const held = await carveIssue(ctx, issue10, knobs(fixture('sg', revisit(10, 'still-good')), fixture('yes', confirmation(10, 'revisit', 'still-good', true))), io);
    expect(held.outcome).toBe('left-alone');
    io.removeLabel(10, 'needs-decision');
    const redriven = await carveIssue(ctx, issue10, knobs(fixture('sg', revisit(10, 'still-good')), fixture('yes', confirmation(10, 'revisit', 'still-good', true))), io);
    expect(redriven.outcome).toBe('still-good');
    const r = readTree(ctx, 10, io).record as Record;
    expect([r.epoch, r.revisits]).toEqual([2, 0]);
    expect(labels(io, children[1])).not.toContain('loop/paused');
  });

  test('exhausted releases: released record, size and trunk labels off, loop/released on', async () => {
    const { io, ctx, children } = await carved();
    for (const c of children) io.close(c);
    const ledger = carving(10).ledger.map((r) => ({ ...r, status: 'completed' as const }));
    const out = await carveIssue(ctx, issue10, knobs(fixture('ex', revisit(10, 'exhausted', { ledger })), fixture('yes', confirmation(10, 'revisit', 'exhausted', true))), io);
    expect(out.outcome).toBe('exhausted');
    expect(labels(io, 10)).toEqual(['loop/released']);
    expect(records(io, 10)).toEqual(['applying', 'live', 'released']);
    // A later visit while released: carve mode, but nothing over the ceiling and no open child.
    const later = await carveIssue(ctx, issue10, knobs(fixture('ex', revisit(10, 'exhausted', { ledger })), fixture('yes', confirmation(10, 'revisit', 'exhausted', true))), io);
    expect(later.outcome).toBe('left-alone');
  });

  test('lifting a carve DLQ at the revisit cap starts a fresh epoch', async () => {
    const { io, ctx } = await carved();
    const k = knobs(fixture('sg', revisit(10, 'still-good')), fixture('yes', confirmation(10, 'revisit', 'still-good', true)), { maxRevisitsPerGeneration: 0 });
    const capped = await carveIssue(ctx, issue10, k, io);
    expect(capped.outcome).toBe('dlq');
    expect(readTree(ctx, 10, io).record!.seen.holds).toContain('loop/dlq: carve');
    io.removeLabel(10, 'loop/dlq: carve');
    const resumed = await carveIssue(ctx, issue10, k, io);
    expect(resumed.outcome).toBe('still-good');
    expect(readTree(ctx, 10, io).record!.epoch).toBe(2);
    expect(readTree(ctx, 10, io).record!.revisits).toBe(0);
  });

  test('a confirmed indivisible opinion follows legal board edges', async () => {
    const io = trunk(); const ctx = ctxFor(io); const lanes: string[] = [];
    ctx.onLane = e => lanes.push(e.lane);
    const k = knobs(fixture('indivisible', carving(10, { verdict: 'indivisible', cuts: undefined, chosen: undefined, affected: [] })), fixture('agree', confirmation(10, 'carve', 'hand-off-agree', true)));
    const d = new CarvingDriver({ ctx, knobs: k, appraisal: { seats: { appraiser: { engine: 'fixture' }, confirmer: { engine: 'fixture2' } }, confirmCloses: true, skipLabels: [], maxAppraiseAttempts: 3, sizeCallbackTimeoutMinutes: 1 }, only: null, ageDays: 100, mark: (_n, _t, l) => lanes.push(l), log: () => {} });
    await d.revisit(10, 'first carving');
    expect(lanes.at(-1)).toBe('H2');
    const illegal = lanes.slice(1).flatMap((to, index) => {
      const from = lanes[index];
      return from === to || successors(laneState(from), { ownEventsOnly: true }).has(laneState(to)) ? [] : [`${from}->${to}`];
    });
    expect(illegal).toEqual([]);
  });

  test('a dry run with fixture seats lands nothing and logs every write', async () => {
    const io = trunk();
    const ctx = { ...ctxFor(io), dryRun: true } as Context;
    const out = await carveIssue(ctx, issue10, knobs(fixture('carve', carving(10)), fixture('cover', confirmation(10, 'carve', 'cover', true))), io);
    expect(out.outcome).toBe('carve');
    expect(io.writes).toEqual([]);
    expect(io.view(10)!.subIssues).toEqual([]);
    expect(ctx.dryRunLog.some((l) => l.includes('create child'))).toBe(true);
    expect(ctx.dryRunLog.some((l) => l.includes('post the live record'))).toBe(true);
  });
});

describe('the local carve lock', () => {
  test('is released when the journal cannot be read, so the issue is not busy for the rest of the run', async () => {
    const io = trunk();
    // A live tracker run: no fake io on the context, so the knife takes its local lock.
    const ctx = ctxFor(io);
    ctx.io = undefined;
    mkdirSync(ctx.runDir, { recursive: true });
    const generation = readTree(ctx, 10, io).generation;
    writeFileSync(join(ctx.runDir, `carve-10-gen${generation}.json`), '{ not json');
    const k = knobs(fixture('carve', carving(10)), fixture('cover', confirmation(10, 'carve', 'cover', true)));
    await expect(carveIssue(ctx, issue10, k, io)).rejects.toThrow();
    expect(existsSync(join(ctx.runDir, 'carve-10.lock'))).toBe(false);
    rmSync(join(ctx.runDir, `carve-10-gen${generation}.json`));
  });
});

describe('an amend', () => {
  test('removes a dependency edge the confirmed amendment no longer commands', async () => {
    const io = trunk();
    const ctx = ctxFor(io);
    await carveIssue(ctx, issue10, knobs(fixture('carve', carving(10)), fixture('cover', confirmation(10, 'carve', 'cover', true))), io);
    const [posts, authors] = readTree(ctx, 10, io).children.map((c) => c.number);
    expect(io.view(authors)!.blockedBy?.nodes.map((b) => b.number)).toEqual([posts]);

    // The same two children, now independent of each other.
    const [base] = carving(10).cuts as [Cut];
    const pieces = base.pieces.map((p, i) => ({ ...p, kind: 'child' as const, number: [posts, authors][i], title: undefined, body: undefined, dependsOn: [] }));
    const amend = { ...carving(10, { cuts: [{ ...base, pieces }] }), mode: 'revisit' as const, verdict: 'amend' as const };
    const out = await carveIssue(ctx, issue10, knobs(fixture('amend', amend), fixture('agree', confirmation(10, 'revisit', 'cover', true))), io);
    expect(out.outcome).toBe('amend');
    expect(io.view(authors)!.blockedBy?.nodes ?? []).toEqual([]);
  });
});

describe('a child with work started is never superseded', () => {
  const node = (...names: string[]) => ({ number: 7, labels: names.map((name) => ({ name })), assignees: [] as string[] });
  test('reads a dead letter of any phase as started work, since the letter clears its counter', () => {
    expect(workStarted(node('loop/dlq: review'), [])).toBe(true);
    expect(workStarted(node('loop/dlq: work'), [])).toBe(true);
    expect(workStarted(node('loop/dlq'), [])).toBe(true);
  });
  test('reads a spent attempt as started work', () => {
    expect(workStarted(node('loop/attempts: 1'), [])).toBe(true);
  });
  test('reads an open pull request on its branch, or an assignee, as started work', () => {
    expect(workStarted(node('size: 2'), ['fix/null-guard-7'])).toBe(true);
    expect(workStarted({ ...node('size: 2'), assignees: ['someone'] }, [])).toBe(true);
  });
  test('reads an untouched child as not started', () => {
    expect(workStarted(node('size: 2'), ['fix/other-17'])).toBe(false);
  });
});

describe('a carve dead letter', () => {
  test('takes the spent carve count off, so lifting the label is a fresh budget for any driver', async () => {
    const io = new FakeTracker(BOT, [fakeIssue(10, { title: '[t] big', labels: [{ name: 'size: 8' }, { name: 'loop/carves: 2' }] })]);
    const ctx = ctxFor(io);
    const out = await carveIssue(ctx, issue10, knobs(fixture('carve', carving(10)), fixture('gap', confirmation(10, 'carve', 'gap', false))), io);
    expect(out.outcome).toBe('dlq');
    expect(labels(io, 10)).toContain('loop/dlq: carve');
    expect(labels(io, 10).some((l) => l.startsWith('loop/carves'))).toBe(false);
  });
});
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: 472kUpdated 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