Skip to content

Use Garry Tan's exact Claude Code setup: 23 opinionated tools that serve as CEO, Designer, Eng Manager, Release Manager, Doc Engineer, and QA

TypeScript
65.6 KB
Raw Blame
/**
 * /ship token budget (GSTA-152 PR A, plan v3 items 1-2, 4, 9; build-spec r2
 * items 2-7): free, deterministic, with a fake Capy meter passed as --reading.
 */
import { afterEach, describe, expect, test } from 'bun:test';
import * as fs from 'node:fs';
import * as path from 'node:path';
import * as os from 'node:os';
import { spawn, spawnSync } from 'node:child_process';
import { bunIsolationArgs } from '../lib/bun-isolation';
import { admits, loadCalibration, METER_CONTRACTS, newEpoch, parseNext, parseTokens, segmentEstimate, stepProjection, tally, unitConstants, type Ledger } from '../lib/ship-budget';
import { BUDGET_BIN, budgetHarness, type Harness, type Run } from './helpers/ship-budget-harness';

const cal = loadCalibration();
const K = unitConstants(cal, 'capy-tokens');
const harnesses: Harness[] = [];
const fresh = () => { const h = budgetHarness(); harnesses.push(h); return h; };
afterEach(() => { while (harnesses.length) harnesses.pop()!.cleanup(); });

function started(h: Harness, args: string[]) {
  const record = h.record();
  const r = h.sb(['start', '--record', record, ...args]);
  return { record, r, run: r.code === 0 || r.code === 3 ? h.field(r.out, 'BUDGET_RUN', 'id') : '', ledger: r.code === 0 || r.code === 3 ? h.field(r.out, 'BUDGET_RUN', 'ledger') : '' };
}

describe('parsing and the admission rule', () => {
  test('token counts, step ids and roles', () => {
    expect(parseTokens('25M', '--token-cap')).toBe(25_000_000);
    expect(parseTokens('400k', '--reading')).toBe(400_000);
    expect(parseTokens('1.5M', '--reserve')).toBe(1_500_000);
    expect(() => parseTokens('lots', '--token-cap')).toThrow(/not a token count/);
    expect(parseNext('dispatch:specialist,red-team')).toEqual({ kind: 'dispatch', roles: ['specialist', 'red-team'] });
    expect(() => parseNext('7.7')).toThrow(/valid: 0.9, 1, 2/);
    expect(() => parseNext('dispatch:security')).toThrow(/unknown roles \(security\)/);
    expect(parseNext('dispatch:specialist,adversarial-native*3')).toEqual({ kind: 'dispatch', roles: ['specialist', 'adversarial-native', 'adversarial-native', 'adversarial-native'], entries: ['specialist', 'adversarial-native*3'] });
    expect(() => parseNext('dispatch:adversarial-native*9')).toThrow(/unknown roles \(adversarial-native\*9\)/);
    expect(() => parseNext('dispatch:adversarial-native*0')).toThrow(/unknown roles/);
  });

  test('exactly at the cap is admitted; one token over is not', () => {
    const t = { used: 10, reserved: 5, unknown: 1 };
    expect(admits(t, 4, 0, 20)).toBe(true);
    expect(admits(t, 5, 0, 20)).toBe(false);
    expect(admits(t, 1_000, 0, null)).toBe(true);
  });

  test('CLI boundary: a check exactly at the cap continues, one token over stops (exit 3)', () => {
    const h = fresh();
    for (const [extra, code, verdict] of [[0, 0, 'continue'], [1, 3, 'stop']] as const) {
      const cap = K.per_dispatch + K.stop_overhead - extra;
      const s = started(h, ['--token-cap', String(cap), '--reading', '3000000', '--reserve', '0']);
      expect(s.r.code).toBe(0);
      const c = h.sb(['check', '--run', s.run, '--step', '1', '--next', 'dispatch:specialist', '--reading', '3000000']);
      expect(c.code).toBe(code);
      expect(h.field(c.out, 'BUDGET', 'verdict')).toBe(verdict);
      expect(h.field(c.out, 'BUDGET', 'admission_cap')).toBe(String(cap));
    }
  });
});

describe('reservations', () => {
  test('a parallel batch is reserved as one sum; when it would overshoot only the prefix that fits is admitted', () => {
    const h = fresh();
    const cap = 2 * K.per_dispatch + K.stop_overhead + 1_000_000;
    const s = started(h, ['--token-cap', String(cap), '--reading', '0', '--reserve', '0']);
    const over = h.sb(['check', '--run', s.run, '--step', '9', '--next', 'dispatch:specialist,red-team,fix-check', '--reading', '0']);
    expect(over.code).toBe(0);
    expect(over.out).toContain('ADMIT: 2 of 3 (remaining=fix-check)');
    expect(h.ledger(s.ledger).reservations.filter((r: any) => r.kind === 'dispatch').map((r: any) => [r.tokens, r.roles])).toEqual([[2 * K.per_dispatch, ['specialist', 'red-team']]]);
  });

  test('#31 replay: a 25M cap stops before the dispatch that would cross it', () => {
    const h = fresh();
    const s = started(h, ['--token-cap', '25M', '--reading', '0']);
    let reading = 0;
    let admitted = 0;
    let stop = '';
    for (let i = 0; i < 10; i++) {
      const c = h.sb(['check', '--run', s.run, '--step', '9', '--next', 'dispatch:specialist', '--reading', String(reading)]);
      if (c.code === 3) { stop = c.out; break; }
      const id = h.field(c.out, 'RESERVATION', 'id');
      reading += 4_950_000;
      admitted++;
      expect(h.sb(['settle', '--run', s.run, '--reservation', id]).code).toBe(0);
    }
    expect(stop).toContain('STOP: reason=budget_exhausted');
    expect(reading).toBeLessThanOrEqual(25_000_000);
    expect(admitted).toBeLessThan(10);
    expect(stop).toMatch(/^RECOVER: \/gstack-ship --resume \S+ --token-cap \d+$/m);
    expect(stop.trim().split('\n').at(-1)).toMatch(/^GSTACK_RESULT: skill=ship status=incomplete run=/);
  });

  test('actual spend above its reservation is counted from the meter, and the next admission sees it', () => {
    const h = fresh();
    const cap = 30_000_000;
    const s = started(h, ['--token-cap', String(cap), '--reading', '0', '--reserve', '0']);
    const c = h.sb(['check', '--run', s.run, '--step', '9', '--next', 'dispatch:specialist', '--reading', '0']);
    const id = h.field(c.out, 'RESERVATION', 'id');
    expect(Number(h.field(c.out, 'RESERVATION', 'tokens'))).toBe(K.per_dispatch);
    const spent = 2 * K.per_dispatch;
    h.sb(['settle', '--run', s.run, '--reservation', id, '--dispatched-at', '0', '--reading', String(spent)]);
    const next = h.sb(['check', '--run', s.run, '--step', '9', '--next', 'dispatch:red-team', '--reading', String(spent)]);
    expect(Number(h.field(next.out, 'BUDGET', 'used'))).toBe(spent);
    const projected = Number(h.field(next.out, 'BUDGET', 'projected'));
    // The factor (2 x headroom) is bounded by the clean per-reader mean it was learned from (GSTA-167).
    expect(projected).toBe(Math.min(Math.ceil((K.per_dispatch * 2 * cal.headroom) / cal.round_to) * cal.round_to, spent));
    expect(next.code).toBe(spent + projected + K.stop_overhead <= cap ? 0 : 3);
    const later = h.sb(['check', '--run', s.run, '--step', '9', '--next', 'dispatch:red-team', '--reading', String(cap - K.stop_overhead - K.per_dispatch + 1)]);
    expect(later.code).toBe(3);
  });

  test('without a cap: no marker, no reservation, no GSTACK_RESULT, and usage is still metered', () => {
    const h = fresh();
    const s = started(h, ['--token-cap', 'none', '--reading', '1000']);
    expect(s.r.code).toBe(0);
    expect(s.r.out).not.toContain('RESERVATION');
    expect(s.r.out).not.toContain('GSTACK_RESULT');
    const c = h.sb(['check', '--run', s.run, '--step', '1', '--next', '2', '--reading', '5000']);
    expect(c.code).toBe(0);
    expect(h.field(c.out, 'BUDGET', 'used')).toBe('4000');
    expect(h.field(c.out, 'BUDGET', 'admission_cap')).toBe('none');
    expect(c.out).not.toContain('GSTACK_RESULT');
    const projects = path.join(h.state, 'projects');
    const markers = fs.existsSync(projects) ? fs.readdirSync(projects).flatMap(d => fs.readdirSync(path.join(projects, d))).filter(f => f.endsWith('-ship-budget.json')) : [];
    expect(markers).toEqual([]);
  });
});

describe('meters and exit codes', () => {
  test('a cap with no readable meter refuses; --meter estimate prints meter=estimate', () => {
    const h = fresh();
    const r = h.sb(['start', '--record', h.record(), '--token-cap', '25M']);
    expect(r.code).toBe(2);
    expect(r.err).toContain('(BUDGET_METER_UNAVAILABLE)');
    expect(r.err).toContain('--meter estimate (not passed)');
    const e = h.sb(['start', '--record', h.record(), '--token-cap', '25M', '--meter', 'estimate']);
    expect(e.code).toBe(0);
    expect(h.field(e.out, 'BUDGET', 'meter')).toBe('estimate');
    expect(h.field(e.out, 'BUDGET', 'unit')).toBe('estimate-tokens');
  });

  test('the Capy meter needs a reading under a cap; lower readings and readings to other meters are rejected', () => {
    const h = fresh();
    const s = started(h, ['--token-cap', '50M', '--reading', '1000']);
    const missing = h.sb(['check', '--run', s.run, '--step', '1', '--next', '2']);
    expect(missing.code).toBe(2);
    expect(missing.err).toContain('(BUDGET_READING_MISSING)');
    const lower = h.sb(['check', '--run', s.run, '--step', '1', '--next', '2', '--reading', '999']);
    expect(lower.code).toBe(2);
    expect(lower.err).toContain('(BUDGET_READING_REJECTED)');
    const est = started(h, ['--token-cap', '50M', '--meter', 'estimate']);
    const wrong = h.sb(['check', '--run', est.run, '--step', '1', '--next', '2', '--reading', '5']);
    expect(wrong.err).toContain('(BUDGET_READING_REJECTED)');
  });

  test('a meter change opens a new epoch and keeps prior usage and reservations', () => {
    const h = fresh();
    const s = started(h, ['--token-cap', '60M', '--reading', '0']);
    const c = h.sb(['check', '--run', s.run, '--step', '9', '--next', 'dispatch:specialist', '--reading', '3000000']);
    expect(c.code).toBe(0);
    const r = h.sb(['resume', '--run', s.run, '--meter', 'estimate']);
    expect(r.code).toBe(0);
    expect(r.out).toContain('EPOCH: 2 meter=estimate');
    expect(h.field(r.out, 'BUDGET', 'used')).toBe('3000000');
    expect(Number(h.field(r.out, 'BUDGET', 'reserved'))).toBeGreaterThanOrEqual(K.per_dispatch);
    expect(h.ledger(s.ledger).epochs[0].contract.unit).toBe('capy-tokens');
  });

  test('usage errors exit 2 on stderr with the value and the repair; unknown ids list the valid ones', () => {
    const h = fresh();
    const s = started(h, ['--token-cap', '50M', '--reading', '0']);
    const step = h.sb(['check', '--run', s.run, '--step', '7.7', '--next', '8', '--reading', '0']);
    expect(step.code).toBe(2);
    expect(step.out).toBe('');
    expect(step.err).toContain("--step '7.7' is not a ship step id; valid: 0.9, 1, 2, 3");
    const role = h.sb(['check', '--run', s.run, '--step', '9', '--next', 'dispatch:security', '--reading', '0']);
    expect(role.err).toContain('valid: specialist, red-team, adversarial-native, outside-voice, fix-check');
    expect(h.sb(['check', '--step', '1', '--next', '2']).err).toContain('never found by branch or directory');
    expect(h.sb(['frobnicate']).code).toBe(2);
    expect(h.sb(['start', '--record', h.record(), '--token-cap', 'lots']).err).toContain("--token-cap 'lots' is not a token count");
  });
});

describe('delegation', () => {
  test('start from a long-lived context (100k or more above the host floor) delegates the whole /ship', () => {
    const h = fresh();
    const s = started(h, ['--token-cap', '60M', '--reading', '9000000', '--prior-reading', '8740000']);
    expect(h.field(s.r.out, 'BUDGET', 'call')).toBe('260000');
    expect(h.field(s.r.out, 'BUDGET', 'above_floor')).toBe('110000');
    expect(h.field(s.r.out, 'BUDGET', 'verdict')).toBe('delegate');
    expect(s.r.out).toContain('--from 1 --to 22');
  });

  test('a segment boundary with an unknown per-call charge delegates; --delegate never stops instead', () => {
    const h = fresh();
    const a = started(h, ['--token-cap', '80M', '--reading', '0']);
    const d = h.sb(['check', '--run', a.run, '--step', '8', '--next', '9', '--reading', '100']);
    expect(d.code).toBe(0);
    expect(h.field(d.out, 'BUDGET', 'verdict')).toBe('delegate');
    expect(d.out).not.toContain('RESERVATION');
    const small = h.sb(['check', '--run', a.run, '--step', '8', '--next', '9', '--reading', '1100', '--prior-reading', '1000']);
    expect(h.field(small.out, 'BUDGET', 'verdict')).toBe('continue');
    const n = started(h, ['--token-cap', '80M', '--reading', '0', '--delegate', 'never']);
    const stop = h.sb(['check', '--run', n.run, '--step', '11.5', '--next', '12', '--reading', '100']);
    expect(stop.code).toBe(3);
    expect(stop.out).toContain('STOP: reason=context_threshold');
  });

  test('full chain: delegate, handoff, verify, child checks, 40-line return, idempotent reconcile, close', () => {
    const h = fresh();
    const s = started(h, ['--token-cap', '80M', '--reading', '1000000']);
    const d = h.sb(['check', '--run', s.run, '--step', '8', '--next', '9', '--reading', '1200000', '--prior-reading', '800000']);
    expect(h.field(d.out, 'BUDGET', 'verdict')).toBe('delegate');
    const ho = h.sb(['handoff', '--run', s.run, '--from', '9', '--to', '11.5', '--base', 'origin/main', '--reading', '1300000']);
    expect(ho.code).toBe(0);
    const brief = ho.out.match(/^HANDOFF: (\S+) sha256=([0-9a-f]{64}) sub_cap=(\d+)$/m)!;
    expect(brief).toBeTruthy();
    expect(Number(brief[3])).toBeLessThanOrEqual(segmentEstimate(cal, 'capy-tokens', '7', '11.5'));
    expect((fs.statSync(brief[1]!).mode & 0o777).toString(8)).toBe('600');
    const text = fs.readFileSync(brief[1]!, 'utf8');
    expect(text).toContain('1b4e28ba-2fa1-11d2-883f-0016d3cca427');
    expect(text).toContain('"do it" covers the CHANGELOG wording');
    expect(text).toContain('## Return contract');
    const v = h.sb(['verify-handoff', '--in', brief[1]!, '--reading', '1400000']);
    expect(v.code).toBe(0);
    const child = h.field(v.out, 'BUDGET_RUN', 'id');
    expect(h.field(v.out, 'BUDGET', 'admission_cap')).toBe(brief[3]);
    expect(h.field(v.out, 'BUDGET', 'used')).toBe('0');
    const cc = h.sb(['check', '--run', child, '--step', '8', '--next', '9', '--reading', '5000000']);
    expect(cc.code).toBe(0);
    const past = h.sb(['check', '--run', child, '--step', '11', '--next', '12', '--reading', '6000000']);
    expect(past.code).toBe(0);
    expect(past.out).toMatch(/^CONTEXT_HIGH: .*Step 12 is past this child's Steps 9-11\.5/m);
    const ret = h.sb(['return', '--run', child, '--to', '11.5', '--changed', 'Reviews,Checks', '--reading', '9000000']);
    expect(ret.code).toBe(0);
    expect(ret.out.trim().split('\n').length).toBeLessThanOrEqual(40);
    expect(ret.out.trim().split('\n').at(-1)).toMatch(/^GSTACK_RESULT: skill=ship status=complete run=/);
    const returnFile = ho.out.match(/^RETURN_FILE: (\S+)$/m)![1]!;
    const rec = h.sb(['reconcile', '--run', s.run, '--return', returnFile, '--reading', '9100000']);
    expect(rec.code).toBe(0);
    expect(rec.out).toContain('child=complete child_used=7600000');
    expect(h.field(rec.out, 'BUDGET', 'reserved')).toBe('0');
    const again = h.sb(['reconcile', '--run', s.run, '--return', returnFile, '--reading', '9200000']);
    expect(again.out).toContain('nothing charged twice');
    expect(h.field(again.out, 'BUDGET', 'reserved')).toBe('0');
    const close = h.sb(['close', '--run', s.run, '--reading', '9300000']);
    expect(close.code).toBe(0);
    expect(close.out).toContain('BUDGET_FINAL: used=8300000');
    expect(close.out).not.toContain('GSTACK_RESULT');
  });

  test('pins: HEAD moving refuses with HANDOFF_PIN_MOVED and a tampered brief refuses', () => {
    const h = fresh();
    const s = started(h, ['--token-cap', '80M', '--reading', '0']);
    const brief = () => h.sb(['handoff', '--run', s.run, '--from', '12', '--to', '22', '--base', 'origin/main', '--reading', '10']).out.match(/^HANDOFF: (\S+)/m)![1]!;
    const second = brief();
    fs.writeFileSync(path.join(h.repo, 'app.ts'), 'export const x = 3;\n');
    h.git('commit', '-qam', 'moved');
    const moved = h.sb(['verify-handoff', '--in', second, '--reading', '30']);
    expect(moved.code).toBe(3);
    expect(moved.out).toMatch(/head expected [0-9a-f]{40} actual [0-9a-f]{40}.*\(HANDOFF_PIN_MOVED\)/);
    expect(moved.out.trim().split('\n').at(-1)).toMatch(/^GSTACK_RESULT: skill=ship status=refused run=/);
    const third = brief();
    fs.appendFileSync(third, '\nextra instruction\n');
    const tampered = h.sb(['verify-handoff', '--in', third, '--reading', '40']);
    expect(tampered.code).toBe(3);
    expect(tampered.out).toMatch(/brief sha256 expected [0-9a-f]{64} actual [0-9a-f]{64}.*\(HANDOFF_PIN_MOVED\)/);
  });

  test('main moving alone keeps the merge base, so the brief still verifies', () => {
    const h = fresh();
    const s = started(h, ['--token-cap', '80M', '--reading', '0']);
    const ho = h.sb(['handoff', '--run', s.run, '--from', '12', '--to', '22', '--base', 'origin/main', '--reading', '10']);
    const file = ho.out.match(/^HANDOFF: (\S+)/m)![1]!;
    const feature = h.git('rev-parse', 'HEAD');
    h.git('checkout', '-q', 'main');
    fs.writeFileSync(path.join(h.repo, 'other.ts'), 'export {};\n');
    h.git('add', '-A');
    h.git('commit', '-qm', 'main moves');
    h.git('update-ref', 'refs/remotes/origin/main', 'HEAD');
    h.git('checkout', '-q', 'feature');
    expect(h.git('rev-parse', 'HEAD')).toBe(feature);
    expect(h.sb(['verify-handoff', '--in', file, '--reading', '20']).code).toBe(0);
  });

  test('a refused child and an interrupted child both stop the parent; their reservations settle once', () => {
    const h = fresh();
    const s = started(h, ['--token-cap', '80M', '--reading', '0']);
    const ho = h.sb(['handoff', '--run', s.run, '--from', '12', '--to', '22', '--base', 'origin/main', '--reading', '10']);
    const file = ho.out.match(/^HANDOFF: (\S+)/m)![1]!;
    const returnFile = ho.out.match(/^RETURN_FILE: (\S+)$/m)![1]!;
    fs.writeFileSync(path.join(h.repo, 'app.ts'), 'export const x = 9;\n');
    expect(h.sb(['verify-handoff', '--in', file, '--reading', '20']).code).toBe(3);
    const refused = h.sb(['reconcile', '--run', s.run, '--return', returnFile, '--reading', '30']);
    expect(refused.code).toBe(3);
    expect(refused.out).toContain('child=refused');
    expect(refused.out).toContain('NEXT: the child returned refused; regenerate the handoff');
    const ho2 = h.sb(['handoff', '--run', s.run, '--from', '12', '--to', '22', '--base', 'origin/main', '--reading', '40']);
    const sha = ho2.out.match(/sha256=([0-9a-f]{64})/)![1]!;
    const interrupted = h.sb(['reconcile', '--run', s.run, '--handoff', sha, '--reading', '5000040']);
    expect(interrupted.code).toBe(3);
    expect(interrupted.out).toContain('child=interrupted child_used=5000000');
    expect(h.ledger(s.ledger).reservations.filter((r: any) => r.kind === 'child').map((r: any) => r.state)).toEqual(['settled', 'settled']);
    expect(Number(h.field(interrupted.out, 'BUDGET', 'reserved'))).toBe(stepProjection(cal, 'capy-tokens', '1'));
  });
});

describe('Claude Code child launch', () => {
  /**
   * The argv rules of `claude --help` (2.1.292 pinned in CI, 2.1.326): a `<values...>` option takes
   * every following argument up to the next one that starts with '-', and '--' ends the options.
   */
  function parseLikeClaudeCli(argv: string[]): { options: Record<string, string[]>; prompts: string[] } {
    const variadic = new Set(['--allowedTools', '--allowed-tools', '--disallowedTools', '--disallowed-tools', '--add-dir', '--tools']);
    const valued = new Set(['--session-id', '--permission-mode', '--model', '--settings', '--output-format']);
    const options: Record<string, string[]> = {};
    const prompts: string[] = [];
    for (let i = 0; i < argv.length; i++) {
      const arg = argv[i]!;
      if (arg === '--') { prompts.push(...argv.slice(i + 1)); break; }
      if (variadic.has(arg)) {
        const values = options[arg] ??= [];
        while (i + 1 < argv.length && !argv[i + 1]!.startsWith('-')) values.push(argv[++i]!);
      } else if (valued.has(arg)) options[arg] = [argv[++i]!];
      else if (!arg.startsWith('-')) prompts.push(arg);
    }
    return { options, prompts };
  }

  /** Launches a child through a fake claude that records its argv. */
  async function launchChild(h: Harness) {
    const s = started(h, ['--token-cap', '80M', '--meter', 'estimate']);
    const ho = h.sb(['handoff', '--run', s.run, '--from', '12', '--to', '22', '--base', 'origin/main']);
    const file = ho.out.match(/^HANDOFF: (\S+)/m)![1]!;
    const argsFile = path.join(h.root, 'claude-args.txt');
    const fake = path.join(h.root, 'fake-claude');
    fs.writeFileSync(fake, `#!/bin/sh\nprintf '%s\\n' "$@" > "${argsFile}.tmp" && mv "${argsFile}.tmp" "${argsFile}"\n`, { mode: 0o755 });
    const r = h.sb(['launch', '--in', file], { GSTACK_CLAUDE_BIN: fake });
    expect(r.code).toBe(0);
    for (let i = 0; i < 50 && !fs.existsSync(argsFile); i++) await Bun.sleep(100);
    const args = fs.readFileSync(argsFile, 'utf8').split('\n').slice(0, -1);
    return { ho, file, r, session: h.field(r.out, 'CHILD', 'session'), args, parsed: parseLikeClaudeCli(args) };
  }

  test('launch runs the child in the background with explicit permission flags and the return file named', async () => {
    const h = fresh();
    const { ho, file, r, session, args, parsed } = await launchChild(h);
    expect(h.field(r.out, 'CHILD', 'return')).toBe(ho.out.match(/^RETURN_FILE: (\S+)$/m)![1]!);
    expect(args.slice(0, 7)).toEqual(['-p', '--session-id', session, '--permission-mode', 'acceptEdits', '--allowedTools', 'Bash,Read,Edit,Write,Grep,Glob']);
    expect(parsed.options['--allowedTools']).toEqual(['Bash,Read,Edit,Write,Grep,Glob']);
    expect(parsed.prompts).toHaveLength(1);
    expect(parsed.prompts[0]).toContain(`verify-handoff --in ${file} --session ${session}`);
  });

  // Value: protects=the Claude Code child loads gstack's shipping skill: Claude Code expands a skill only when the prompt starts with the typed command, and unattended Opus found a skill from its description 0 of 60 times (gstack-evals#366); fails_when=the prompt opens with prose ("Load gstack. … Run /gstack-ship") or types the bare /ship, which Claude Code reserves for its own built-in (#4775);
  //   why_new=the test above checks only that verify-handoff appears somewhere in the prompt; seam=GSTACK_CLAUDE_BIN fake; no_claim=that a real claude expands it
  test('the child prompt opens with the typed /gstack-ship --continue <brief> in both prefix modes', async () => {
    const plain = await launchChild(fresh());
    expect(plain.parsed.prompts[0]).toStartWith(`/gstack-ship --continue ${plain.file} `);
    const h = fresh();
    fs.mkdirSync(h.state, { recursive: true });
    fs.writeFileSync(path.join(h.state, 'config.yaml'), 'skill_prefix: true\n');
    const prefixed = await launchChild(h);
    expect(prefixed.parsed.prompts[0]).toStartWith(`/gstack-ship --continue ${prefixed.file} `);
  });
});

describe('stop, resume and recovery', () => {
  test('stop prints a RECOVER line; executing it needs the owner\'s words and then the run continues', () => {
    const h = fresh();
    const s = started(h, ['--token-cap', '20M', '--reading', '0']);
    const stop = h.sb(['check', '--run', s.run, '--step', '9', '--next', 'dispatch:specialist,red-team', '--reading', '9000000']);
    expect(stop.code).toBe(3);
    const recover = stop.out.match(/^RECOVER: \/gstack-ship --resume (\S+) --token-cap (\d+)$/m)!;
    expect(recover[1]).toBe(s.record);
    expect(h.sb(['check', '--run', s.run, '--step', '9', '--next', '10', '--reading', '9000000']).code).toBe(3);
    const noWords = h.sb(['resume', '--record', recover[1]!, '--token-cap', recover[2]!, '--reading', '9100000']);
    expect(noWords.code).toBe(2);
    expect(noWords.err).toContain('--approved-by');
    const ok = h.sb(['resume', '--record', recover[1]!, '--token-cap', recover[2]!, '--approved-by', 'Garry', '--words', 'raise it to finish', '--reading', '9100000']);
    expect(ok.code).toBe(0);
    expect(ok.out).toContain('RESUMED: from=Step 9 (budget_exhausted)');
    const go = h.sb(['check', '--run', s.run, '--step', '9', '--next', 'dispatch:specialist,red-team', '--reading', '9200000']);
    expect(go.code).toBe(0);
    expect(h.ledger(s.ledger).cap_raises[0]).toMatchObject({ from: 20_000_000, to: Number(recover[2]), by: 'Garry', words: 'raise it to finish' });
  });

  test('a machine change: the ledger and record come back from the checkpoint into an empty state root', () => {
    const h = fresh();
    const s = started(h, ['--token-cap', '60M', '--reading', '0']);
    const c = h.sb(['check', '--run', s.run, '--step', '9', '--next', 'dispatch:specialist', '--reading', '2000000']);
    expect(c.code).toBe(0);
    fs.rmSync(h.state, { recursive: true, force: true });
    fs.rmSync(path.dirname(s.record), { recursive: true, force: true });
    const r = h.sb(['resume', '--run', s.run, '--reading', '2500000']);
    expect(r.code).toBe(0);
    expect(r.out).toContain(`RESTORED: ledger=${s.ledger} record=${s.record}`);
    expect(h.field(r.out, 'BUDGET', 'used')).toBe('2500000');
    expect(Number(h.field(r.out, 'BUDGET', 'reserved'))).toBe(K.per_dispatch);
    expect(fs.readFileSync(s.record, 'utf8')).toContain('```gstack-budget');
  });

  test('a corrupt ledger refuses with path, schema and parse location; --rebuild-from-record charges open reservations as unknown', () => {
    const h = fresh();
    const s = started(h, ['--token-cap', '60M', '--reading', '0']);
    h.sb(['check', '--run', s.run, '--step', '9', '--next', 'dispatch:specialist', '--reading', '1000000']);
    fs.writeFileSync(s.ledger, '{"kind": "gstack-ship-budget", oops');
    const bad = h.sb(['resume', '--record', s.record, '--reading', '1500000']);
    expect(bad.code).toBe(2);
    expect(bad.err).toContain(s.ledger);
    expect(bad.err).toMatch(/schema_version unknown, parse error: .*\(BUDGET_LEDGER_INVALID\)/);
    const rebuilt = h.sb(['resume', '--record', s.record, '--rebuild-from-record', '--reading', '1500000']);
    expect(rebuilt.code).toBe(0);
    expect(rebuilt.out).toContain('REBUILT:');
    expect(h.field(rebuilt.out, 'BUDGET', 'used')).toBe('1000000');
    expect(Number(h.field(rebuilt.out, 'BUDGET', 'unknown'))).toBeGreaterThanOrEqual(K.per_dispatch);
  });
});

describe('isolation', () => {
  test('two ledgers run concurrently, and contention on one ledger never over-admits', async () => {
    const h = fresh();
    const a = started(h, ['--token-cap', '60M', '--reading', '0', '--reserve', '0']);
    const b = started(h, ['--token-cap', '60M', '--reading', '0', '--reserve', '0']);
    expect(a.ledger).not.toBe(b.ledger);
    const cap = 2 * K.per_dispatch + K.stop_overhead + stepProjection(cal, 'capy-tokens', '1');
    const tight = started(h, ['--token-cap', String(cap), '--reading', '0', '--reserve', '0']);
    const spawn = (run: string) => Bun.spawn([BUDGET_BIN, 'check', '--run', run, '--step', '9', '--next', 'dispatch:specialist', '--reading', '0'], { cwd: h.repo, env: h.env, stdout: 'pipe', stderr: 'pipe' });
    const procs = [...Array.from({ length: 6 }, () => spawn(tight.run)), spawn(a.run), spawn(b.run)];
    const codes = await Promise.all(procs.map(p => p.exited));
    expect(codes.slice(0, 6).filter(c => c === 0)).toHaveLength(2);
    expect(codes.slice(6)).toEqual([0, 0]);
    for (const file of [a.ledger, b.ledger]) expect(h.ledger(file).reservations.filter((r: any) => r.kind === 'dispatch')).toHaveLength(1);
  });

  test('budget state lives outside the checkout: gstack-wtree and git status are unchanged across checks', () => {
    const h = fresh();
    const wtree = () => spawnSync('bash', [path.join(import.meta.dir, '..', 'bin', 'gstack-wtree')], { cwd: h.repo, env: h.env, encoding: 'utf8', timeout: 30_000 }).stdout.trim();
    const before = wtree();
    const s = started(h, ['--token-cap', '60M', '--reading', '0']);
    h.sb(['check', '--run', s.run, '--step', '1', '--next', '2', '--reading', '10']);
    h.sb(['handoff', '--run', s.run, '--from', '12', '--to', '22', '--base', 'origin/main', '--reading', '20']);
    expect(wtree()).toBe(before);
    expect(h.git('status', '--porcelain')).toBe('');
    expect(s.ledger.startsWith(path.join(h.state, 'ship-runs'))).toBe(true);
    expect((fs.statSync(s.ledger).mode & 0o777).toString(8)).toBe('600');
  });
});

describe('meter epochs', () => {
  test('estimate spend survives a change of meter (estimate -> capy -> estimate)', () => {
    const l = { meter: { contract: METER_CONTRACTS.estimate, epoch: 0, baseline: 0, last: 0 }, epochs: [], carried_used: 0, estimate_used: 20_000_000, unknown: 0, reservations: [] } as unknown as Ledger;
    expect(tally(l).used).toBe(20_000_000);
    newEpoch(l, METER_CONTRACTS.capy, 100_000_000); // pregate-literal: SUBAGENT_DEFAULT_CAP=100_000_000 a meter baseline reading, not the cap
    expect(tally(l).used).toBe(20_000_000);
    l.meter.last = 103_000_000;
    newEpoch(l, METER_CONTRACTS.estimate, 0);
    expect(tally(l).used).toBe(23_000_000);
    l.estimate_used = 1_000_000;
    expect(tally(l).used).toBe(24_000_000);
  });
});

describe('a new /ship on a reused record meters only itself (GST-4109)', () => {
  // Value: protects=the token cap measures this run's own use: a start on a record whose earlier run already noted (or stopped) opens a new run at its own reading, so earlier runs in the thread never count; fails_when=start re-attaches the earlier run's ledger, so its baseline (and every token since) counts against the new run's cap (GSKI-1 #10, HARN-1 #8);
  //   why_new=start's re-attach branch was only driven by a rerun before any progress; seam=none; no_claim=the host's counter itself, which a fake --reading stands in for
  test('a start after an earlier run progressed opens a new run whose used counts from its own reading', () => {
    const h = fresh();
    const record = h.record();
    const first = h.sb(['start', '--record', record, '--mode', 'observe', '--token-cap', '50M', '--reading', '1000000', '--credits', '10']);
    const a = h.field(first.out, 'BUDGET_RUN', 'id');
    expect(h.sb(['note', '--record', record, '--step', '9', '--reading', '45000000', '--credits', '400']).code).toBe(0);
    const second = h.sb(['start', '--record', record, '--mode', 'observe', '--token-cap', '50M', '--reading', '46000000', '--credits', '410']);
    expect(second.code, second.out + second.err).toBe(0);
    const b = h.field(second.out, 'BUDGET_RUN', 'id');
    expect(b).not.toBe(a);
    expect(second.out).toContain(`SUPERSEDED: run ${a} on this record already ran past its start`);
    const note = h.sb(['note', '--record', record, '--step', '6', '--reading', '48000000', '--credits', '430']);
    expect(note.code, note.out + note.err).toBe(0);
    expect(note.out).toMatch(/^NOTE: 6 used=2000000 credits=20\b/m);
    expect(h.ledger(h.field(first.out, 'BUDGET_RUN', 'ledger')).meter.last).toBe(45_000_000);
  });

  // Value: protects=a new start never lifts a budget stop: only resume, with the owner's words for a cap raise, does; fails_when=start on a stopped run's record mints a fresh run at used=0, so a run past its cap continues with no approval (targeted money reader, ship-1-p2);
  //   why_new=the stopped re-attach was never driven; seam=none; no_claim=which run a lane should continue, its call
  test('a start on a record whose run stopped at its cap re-attaches the stopped run and exits 3; resume lifts it', () => {
    const h = fresh();
    const record = h.record();
    const first = h.sb(['start', '--record', record, '--mode', 'observe', '--token-cap', '10M', '--reading', '1000000']);
    const a = h.field(first.out, 'BUDGET_RUN', 'id');
    expect(h.sb(['note', '--record', record, '--step', '9', '--reading', '20000000']).code).toBe(3);
    const second = h.sb(['start', '--record', record, '--mode', 'observe', '--token-cap', '10M', '--reading', '21000000']);
    expect(second.code, second.out + second.err).toBe(3);
    expect(h.field(second.out, 'BUDGET_RUN', 'id')).toBe(a);
    expect(second.out).not.toContain('SUPERSEDED:');
    expect(second.out).toMatch(/^STOP: reason=budget_exhausted at Step 9; .*resume first/m);
    expect(h.ledger(h.field(first.out, 'BUDGET_RUN', 'ledger')).superseded_by).toBeUndefined();
    const resumed = h.sb(['resume', '--run', a, '--reading', '22000000', '--token-cap', '30M', '--approved-by', 'GSTA-36', '--words', 'raise it']);
    expect(resumed.code, resumed.out + resumed.err).toBe(0);
    expect(resumed.out).toContain(`BUDGET_RUN: id=${a} `);
  });

  // Value: protects=a start on a run already past its cap at this start's reading, but not yet stopped (observe mode stops at the next note), records the stop and re-attaches instead of handing out a fresh cap; fails_when=a rerun of start after compaction supersedes an over-cap run with used=0 and no owner words (targeted money reader, ship-1-p4);
  //   why_new=the stopped case above only covers a stop a note already recorded; seam=none; no_claim=admit mode, whose check stops before the cap
  test('a start on a run past its cap that no note stopped yet records the stop and exits 3', async () => {
    const { changeRunRecord } = await import('../lib/ship-run-record');
    const h = fresh();
    const record = h.record();
    const first = h.sb(['start', '--record', record, '--mode', 'observe', '--token-cap', '10M', '--reading', '1000000']);
    const a = h.field(first.out, 'BUDGET_RUN', 'id');
    expect(changeRunRecord(h.repo, 'preflight', a).ok).toBe(true);
    expect(h.sb(['note', '--record', record, '--step', '9', '--reading', '5000000']).code).toBe(0);
    const second = h.sb(['start', '--record', record, '--mode', 'observe', '--token-cap', '10M', '--reading', '20000000']);
    expect(second.code, second.out + second.err).toBe(3);
    expect(h.field(second.out, 'BUDGET_RUN', 'id')).toBe(a);
    expect(second.out).not.toContain('SUPERSEDED:');
    expect(second.out).toMatch(/^STOP: reason=budget_exhausted /m);
    expect(second.out).toMatch(/^RESUME: run \S+ on this record was past its limit/m);
    expect(h.ledger(h.field(first.out, 'BUDGET_RUN', 'ledger')).stopped?.reason).toBe('budget_exhausted');
  });

  // Value: protects=a /ship that ended without Step 22's close never blocks or is charged by the next one; fails_when=the over-limit check reads the later thread counter into the ended run's ledger, stops it and refuses the new start (red-team, ship-2-p1);
  //   why_new=the case above keeps the run record open; seam=the run record moved by changeRunRecord; no_claim=a run whose record was removed by a crash
  test('a start after an earlier /ship ended unclosed supersedes it untouched, even past its cap', async () => {
    const { changeRunRecord } = await import('../lib/ship-run-record');
    const h = fresh();
    const record = h.record();
    const first = h.sb(['start', '--record', record, '--mode', 'observe', '--reading', '1000000']);
    const a = h.field(first.out, 'BUDGET_RUN', 'id');
    expect(changeRunRecord(h.repo, 'preflight', a).ok).toBe(true);
    expect(changeRunRecord(h.repo, 'skill-end', a, { ended_by: 'skill-end' }).ok).toBe(true);
    const second = h.sb(['start', '--record', record, '--mode', 'observe', '--reading', '150000000']);
    expect(second.code, second.out + second.err).toBe(0);
    expect(second.out).toContain(`SUPERSEDED: run ${a} on this record`);
    const old = h.ledger(h.field(first.out, 'BUDGET_RUN', 'ledger'));
    expect(old.stopped).toBeUndefined();
    expect(old.meter.last).toBe(1_000_000);
  });

  // Value: protects=a rerun of the same start before any progress stays one run; fails_when=every start mints a run, so a restarted Phase 2 splits one /ship into two ledgers;
  //   why_new=the guard above narrows re-attach; seam=none; no_claim=admission-mode reruns past Step 1
  test('a rerun of start before the run progressed re-attaches the same run', () => {
    const h = fresh();
    const record = h.record();
    const first = h.sb(['start', '--record', record, '--mode', 'observe', '--reading', '1000000']);
    const again = h.sb(['start', '--record', record, '--mode', 'observe', '--reading', '1100000']);
    expect(again.code, again.out + again.err).toBe(0);
    expect(h.field(again.out, 'BUDGET_RUN', 'id')).toBe(h.field(first.out, 'BUDGET_RUN', 'id'));
    expect(again.out).not.toContain('SUPERSEDED:');
  });

  // Value: protects=a resume that moves a run onto the Capy counter takes that counter's reading as the new epoch's baseline; fails_when=resume --meter capy with no --reading sets the baseline to 0, so the thread's lifetime counter counts as this run's use;
  //   why_new=only a successor's resume required the reading; seam=none; no_claim=the Claude meter's own baseline
  test('resume --meter capy without a reading is refused instead of metering from zero', () => {
    const h = fresh();
    const record = h.record();
    expect(h.sb(['start', '--record', record, '--mode', 'observe', '--meter', 'estimate']).code).toBe(0);
    const bare = h.sb(['resume', '--record', record, '--meter', 'capy']);
    expect(bare.code).toBe(2);
    expect(bare.err).toContain('BUDGET_READING_MISSING');
    const ok = h.sb(['resume', '--record', record, '--meter', 'capy', '--reading', '900000000']);
    expect(ok.code, ok.out + ok.err).toBe(0);
    const note = h.sb(['note', '--record', record, '--step', '6', '--reading', '901000000']);
    expect(note.out).toMatch(/^NOTE: 6 used=1000000\b/m);
  });
  // Value: protects=a start re-attaches only a fresh rerun: an open run that never noted but started over 5 minutes ago is an earlier /ship, so a new start opens its own run and marks the old one superseded, which then holds no gstack upgrade; fails_when=a run parked before its first note (a preflight STOP) still lends its baseline and clock to the next /ship (red-team, ship-1-p1), or the superseded ledger keeps holding upgrades;
  //   why_new=the cases above only re-start at once; seam=the ledger's created_at, backdated; no_claim=admission-mode reruns
  test('an unprogressed run older than 5 minutes is superseded, and the superseded ledger holds no upgrade', async () => {
    const { liveRun } = await import('../lib/ship-run-live');
    const h = fresh();
    const record = h.record();
    const first = h.sb(['start', '--record', record, '--mode', 'observe', '--reading', '1000000']);
    const oldLedger = h.field(first.out, 'BUDGET_RUN', 'ledger');
    const l = h.ledger(oldLedger);
    l.created_at = new Date(Date.now() - 10 * 60_000).toISOString();
    fs.writeFileSync(oldLedger, JSON.stringify(l, null, 2));
    const second = h.sb(['start', '--record', record, '--mode', 'observe', '--reading', '30000000']);
    expect(second.code, second.out + second.err).toBe(0);
    const b = h.field(second.out, 'BUDGET_RUN', 'id');
    expect(b).not.toBe(l.run);
    expect(second.out).toContain(`SUPERSEDED: run ${l.run} on this record started over 5 minutes ago`);
    expect(h.ledger(oldLedger).superseded_by).toBe(b);
    expect(fs.readFileSync(record, 'utf8')).toContain(`run=${b} `);
    expect(h.sb(['close', '--record', record, '--reading', '31000000']).code).toBe(0);
    expect(liveRun(h.state).live).toBeUndefined();
  });

  // Value: protects=a superseded run's late write never repoints the shared record at it or removes the new run's marker; fails_when=a note or close through the old run id rewrites the record block to the superseded run, so the next note meters against the wrong ledger (outside-voice, ship-1-p2);
  //   why_new=the case above only closed the new run; seam=--run on the superseded id; no_claim=two hosts writing the same ledger at once
  test("a superseded run's late note and close leave the record pointing at the new run", () => {
    const h = fresh();
    const record = h.record();
    const first = h.sb(['start', '--record', record, '--mode', 'observe', '--reading', '1000000']);
    const a = h.field(first.out, 'BUDGET_RUN', 'id');
    expect(h.sb(['note', '--record', record, '--step', '9', '--reading', '2000000']).code).toBe(0);
    const second = h.sb(['start', '--record', record, '--mode', 'observe', '--reading', '3000000']);
    const b = h.field(second.out, 'BUDGET_RUN', 'id');
    expect(b).not.toBe(a);
    expect(h.sb(['note', '--run', a, '--step', '10', '--reading', '4000000']).code).toBe(0);
    expect(fs.readFileSync(record, 'utf8')).toContain(`run=${b} `);
    const note = h.sb(['note', '--record', record, '--step', '6', '--reading', '5000000']);
    expect(note.out).toMatch(/^NOTE: 6 used=2000000\b/m);
  });
});

describe('start, resume and close follow one state table of run record, ledger and flags (GST-4132)', () => {
  type Rec = 'open' | 'ended' | 'missing';
  type Led = 'fresh' | 'fresh-over' | 'under' | 'over' | 'stopped' | 'closed';
  /** A first start under a 10M cap at 1M, its ledger moved to `led` and the checkout's run record to `rec`, then a second start (.context/GST-4132-state-table.md). */
  async function cell(rec: Rec, led: Led, extra: string[] = []) {
    const { changeRunRecord } = await import('../lib/ship-run-record');
    const h = fresh();
    const record = h.record();
    const first = h.sb(['start', '--record', record, '--mode', 'observe', '--token-cap', '10M', '--reading', '1000000']);
    const a = h.field(first.out, 'BUDGET_RUN', 'id'), ledger = h.field(first.out, 'BUDGET_RUN', 'ledger');
    if (rec !== 'missing') expect(changeRunRecord(h.repo, 'preflight', 'r1').ok).toBe(true);
    if (led === 'under' || led === 'over') expect(h.sb(['note', '--record', record, '--step', '9', '--reading', '5000000']).code).toBe(0);
    if (led === 'stopped') expect(h.sb(['note', '--record', record, '--step', '9', '--reading', '20000000']).code).toBe(3);
    if (rec === 'ended') expect(changeRunRecord(h.repo, 'skill-end', 'r1', { ended_by: 'skill-end' }).ok).toBe(true);
    if (led === 'closed') expect(h.sb(['close', '--record', record, '--reading', '5000000']).code).toBe(0);
    const reading = led === 'over' || led === 'fresh-over' ? '20000000' : '6000000';
    const second = h.sb(['start', '--record', record, '--mode', 'observe', '--token-cap', '10M', '--reading', reading, ...extra]);
    return { h, record, a, ledger, second, b: second.code === 0 || second.code === 3 ? h.field(second.out, 'BUDGET_RUN', 'id') : '' };
  }
  const TABLE: Array<[Rec, Led, number, 'same' | 'new' | 'superseded']> = [
    ['open', 'fresh', 0, 'same'], ['open', 'fresh-over', 3, 'same'], ['open', 'under', 0, 'same'], ['open', 'over', 3, 'same'], ['open', 'stopped', 3, 'same'], ['open', 'closed', 0, 'new'],
    ['ended', 'fresh', 0, 'superseded'], ['ended', 'fresh-over', 0, 'superseded'], ['ended', 'under', 0, 'superseded'], ['ended', 'over', 0, 'superseded'], ['ended', 'stopped', 3, 'same'], ['ended', 'closed', 0, 'new'],
    ['missing', 'fresh', 0, 'same'], ['missing', 'fresh-over', 3, 'same'], ['missing', 'under', 0, 'superseded'], ['missing', 'over', 0, 'superseded'], ['missing', 'stopped', 3, 'same'], ['missing', 'closed', 0, 'new'],
  ];

  // Value: protects=every combination of run record and ledger state gets the one start outcome the state table names: while the checkout's /ship
  //   is open, start always re-attaches its run (recording a stop past a limit), a run that ended is superseded untouched, a stop is never lifted,
  //   and a closed run is left as it was; fails_when=a rerun of start inside an open /ship supersedes a run under its limit with a fresh cap and
  //   clock (GSTA-892 ruled note at cmdStart), or a re-attach hands a run already past its cap an exit 0 (GST-4132);
  //   why_new=#4877's cases drove single cells, and the open-record, under-limit cell was never driven; seam=the run record moved by
  //   changeRunRecord; no_claim=a record that preflight bound, which test/ship-run-record.test.ts drives
  test.each(TABLE)('record %s, ledger %s: start exits %d and the run is %s', async (rec, led, code, outcome) => {
    const { h, record, a, ledger, second, b } = await cell(rec, led);
    expect(second.code, second.out + second.err).toBe(code);
    const old = h.ledger(ledger);
    if (outcome === 'same') {
      expect(b).toBe(a);
      expect(second.out).not.toContain('SUPERSEDED:');
      if (code === 3) expect(second.out).toMatch(/^STOP: /m);
    } else {
      expect(b).not.toBe(a);
      expect(fs.readFileSync(record, 'utf8')).toContain(`run=${b} `);
      expect(old.superseded_by).toBe(outcome === 'superseded' ? b : undefined);
      expect(second.out.includes('SUPERSEDED:')).toBe(outcome === 'superseded');
      if (led !== 'stopped') expect(old.stopped).toBeUndefined();
      if (led === 'over' || led === 'fresh-over') expect(old.meter.last).toBe(led === 'over' ? 5_000_000 : 1_000_000);
    }
  });

  // Value: protects=a start that re-attaches an open /ship's run keeps that run's cap: --token-cap none or a larger cap never applies without the
  //   owner's words, and the start says so; fails_when=a rerun of start with --token-cap none opens an uncapped run inside the same /ship (GSTA-892);
  //   why_new=the table above passes the same cap; seam=none; no_claim=resume --token-cap, which journals a raise
  test.each([['none'], ['50M']])('a re-attaching start with --token-cap %s keeps the run\'s 10M cap', async (raw) => {
    const { h, a, ledger, second, b } = await cell('open', 'under', ['--token-cap', raw]);
    expect(second.code, second.out + second.err).toBe(0);
    expect(b).toBe(a);
    expect(h.ledger(ledger).cap).toBe(10_000_000);
    expect(second.out).toMatch(/^CAP: kept admission_cap=10000000 /m);
  });

  // Value: protects=start --ledger never writes a new run over the record's earlier ledger, by its path, a symlink or a .. path; fails_when=the new
  //   run overwrites the earlier ledger and then marks itself superseded_by its own id, so the run never meters and the earlier run's spend is lost
  //   (GSTA-892 ruled note at line 300); why_new=--ledger was never driven on a reused record; seam=none; no_claim=a ledger of another record
  test('start --ledger that aliases the earlier run\'s ledger is refused and leaves it unchanged', async () => {
    for (const led of ['under', 'closed'] as const) {
      const h = fresh();
      const record = h.record();
      const first = h.sb(['start', '--record', record, '--mode', 'observe', '--token-cap', '10M', '--reading', '1000000']);
      const ledger = h.field(first.out, 'BUDGET_RUN', 'ledger');
      expect(h.sb(['note', '--record', record, '--step', '9', '--reading', '2000000']).code).toBe(0);
      if (led === 'closed') expect(h.sb(['close', '--record', record, '--reading', '3000000']).code).toBe(0);
      const before = fs.readFileSync(ledger, 'utf8');
      const dir = path.dirname(ledger);
      const aliases = [ledger, path.join(dir, '..', path.basename(dir), 'budget.json')];
      if (process.platform !== 'win32') { fs.symlinkSync(ledger, path.join(h.root, 'alias.json')); aliases.push(path.join(h.root, 'alias.json')); }
      for (const alias of aliases) {
        const r = h.sb(['start', '--record', record, '--mode', 'observe', '--reading', '4000000', '--ledger', alias]);
        expect([led, alias, r.code]).toEqual([led, alias, 2]);
        expect(r.err).toContain('is the earlier run');
      }
      expect(fs.readFileSync(ledger, 'utf8')).toBe(before);
      const other = path.join(h.root, 'other.json');
      const ok = h.sb(['start', '--record', record, '--mode', 'observe', '--reading', '4000000', '--ledger', other]);
      expect(ok.code, ok.out + ok.err).toBe(0);
      expect(h.field(ok.out, 'BUDGET_RUN', 'ledger')).toBe(other);
    }
  });

  // Value: protects=resume --run of a superseded run marks the run that superseded it (the newest in the chain) superseded by the resumed run, so
  //   it stops holding gstack upgrades, while a closed successor is left alone; fails_when=the successor stays an open, unsuperseded ledger that
  //   holds every gstack upgrade on the machine for 6 hours (GSTA-892 ruled note at lines 548-554); why_new=resume of a superseded run was never
  //   driven; seam=--run on the superseded id; no_claim=two resumes of different runs at once
  test('resume --run of a superseded run supersedes the newest run in its chain, and leaves a closed one alone', async () => {
    const { liveRun } = await import('../lib/ship-run-live');
    const h = fresh();
    const record = h.record();
    const id = (r: Run) => h.field(r.out, 'BUDGET_RUN', 'id');
    const ledgerOf = (run: string) => path.join(h.state, 'ship-runs', run, 'budget.json');
    const a = id(h.sb(['start', '--record', record, '--mode', 'observe', '--reading', '1000000']));
    expect(h.sb(['note', '--record', record, '--step', '9', '--reading', '2000000']).code).toBe(0);
    const b = id(h.sb(['start', '--record', record, '--mode', 'observe', '--reading', '3000000']));
    expect(h.sb(['note', '--record', record, '--step', '9', '--reading', '4000000']).code).toBe(0);
    const c = id(h.sb(['start', '--record', record, '--mode', 'observe', '--reading', '5000000']));
    expect(new Set([a, b, c]).size).toBe(3);
    const resumed = h.sb(['resume', '--run', a, '--reading', '6000000']);
    expect(resumed.code, resumed.out + resumed.err).toBe(0);
    expect(resumed.out).toMatch(new RegExp(`^SUPERSEDED: run ${c} `, 'm'));
    expect(h.ledger(ledgerOf(c)).superseded_by).toBe(a);
    expect(h.ledger(ledgerOf(b)).superseded_by).toBe(c);
    expect(h.ledger(ledgerOf(a)).superseded_by).toBeUndefined();
    expect(fs.readFileSync(record, 'utf8')).toContain(`run=${a} `);
    expect(liveRun(h.state).live).toContain(a);
    expect(h.sb(['note', '--record', record, '--step', '10', '--reading', '7000000']).out).toMatch(/^NOTE: 10 used=6000000\b/m);
    const back = h.sb(['resume', '--run', c, '--reading', '8000000']);
    expect(back.out).toMatch(new RegExp(`^SUPERSEDED: run ${a} `, 'm'));
    expect(h.sb(['close', '--run', c, '--reading', '9000000']).code).toBe(0);
    const again = h.sb(['resume', '--run', a, '--reading', '9500000']);
    expect(again.code, again.out + again.err).toBe(0);
    expect(again.out).not.toContain('SUPERSEDED:');
    expect(h.ledger(ledgerOf(c)).superseded_by).toBeUndefined();
  });

  // Value: protects=start writes the new run, points the record at it and marks the earlier run superseded while holding the earlier ledger's lock,
  //   so a note on the earlier run either lands first or finds it superseded; fails_when=start points the record at the new run before it locks the
  //   earlier ledger, so a note --run <old> in between points the record back at the old run (GSTA-892 ruled note at line 315);
  //   why_new=no case raced a note against a supersede; seam=the earlier ledger's lock file, held by this test; no_claim=two hosts sharing a state root
  test('a superseding start waits on the earlier ledger\'s lock before it writes anything', async () => {
    const h = fresh();
    const record = h.record();
    const first = h.sb(['start', '--record', record, '--mode', 'observe', '--reading', '1000000']);
    const a = h.field(first.out, 'BUDGET_RUN', 'id'), ledger = h.field(first.out, 'BUDGET_RUN', 'ledger');
    expect(h.sb(['note', '--record', record, '--step', '9', '--reading', '2000000']).code).toBe(0);
    const lock = `${ledger}.lock`;
    fs.writeFileSync(lock, JSON.stringify({ pid: process.pid, host: os.hostname(), at: new Date().toISOString() }));
    const child = spawn(process.execPath, [...bunIsolationArgs(), BUDGET_BIN, 'start', '--record', record, '--mode', 'observe', '--reading', '3000000'], { cwd: h.repo, env: h.env });
    let out = '', err = '';
    child.stdout.on('data', d => { out += d; });
    child.stderr.on('data', d => { err += d; });
    const exited = new Promise<number | null>(resolve => child.on('close', resolve));
    await Bun.sleep(3000);
    expect(fs.readFileSync(record, 'utf8')).toContain(`run=${a} `);
    expect(fs.readdirSync(path.join(h.state, 'ship-runs'))).toEqual([a]);
    fs.unlinkSync(lock);
    expect(await exited, out + err).toBe(0);
    const b = h.field(out, 'BUDGET_RUN', 'id');
    expect(b).not.toBe(a);
    expect(fs.readFileSync(record, 'utf8')).toContain(`run=${b} `);
    expect(h.ledger(ledger).superseded_by).toBe(b);
  }, 30_000);
  // Value: protects=a ledger preflight bound to its run re-attaches only while that run's record is open, and once another run's record is open
  //   the earlier ledger is superseded even though that record opened after it; a bind skips a start older than 5 minutes and two starts at once;
  //   fails_when=liveRecord ignores the binding (a later /ship re-attaches an earlier run and inherits its spend), or bindPreflightLedger binds an
  //   old or ambiguous ledger (review p1 specialist-batched#2); why_new=the table above only drives unbound ledgers; seam=bindPreflightLedger called
  //   with the record changeRunRecord opened; no_claim=the preflight bin itself, which test/ship-run-record.test.ts drives
  test('a bound ledger re-attaches only for its own open record, and a bind skips an old or tied start', async () => {
    const { changeRunRecord } = await import('../lib/ship-run-record');
    const { bindPreflightLedger } = await import('../lib/ship-run-live');
    const h = fresh();
    const record = h.record();
    const first = h.sb(['start', '--record', record, '--mode', 'observe', '--token-cap', '10M', '--reading', '1000000']);
    const a = h.field(first.out, 'BUDGET_RUN', 'id'), ledger = h.field(first.out, 'BUDGET_RUN', 'ledger');
    const opened = changeRunRecord(h.repo, 'preflight', 'r1');
    if (!opened.ok) throw new Error(opened.why);
    bindPreflightLedger(h.ledger(ledger).checkout, h.env, 'r1', opened.record!.started_at);
    expect(h.ledger(ledger).ship_run).toBe('r1');
    expect(h.sb(['note', '--record', record, '--step', '9', '--reading', '5000000']).code).toBe(0);
    const again = h.sb(['start', '--record', record, '--mode', 'observe', '--token-cap', '10M', '--reading', '6000000']);
    expect([again.code, h.field(again.out, 'BUDGET_RUN', 'id')]).toEqual([0, a]);
    expect(changeRunRecord(h.repo, 'abandon', 'r1', { ended_by: 'test' }).ok).toBe(true);
    expect(changeRunRecord(h.repo, 'preflight', 'r2').ok).toBe(true);
    const next = h.sb(['start', '--record', record, '--mode', 'observe', '--token-cap', '10M', '--reading', '7000000']);
    expect(next.code, next.out + next.err).toBe(0);
    const b = h.field(next.out, 'BUDGET_RUN', 'id');
    expect(b).not.toBe(a);
    expect(h.ledger(ledger).superseded_by).toBe(b);

    const g = fresh();
    const stale = g.field(g.sb(['start', '--record', g.record('old.md'), '--mode', 'observe', '--reading', '1000000']).out, 'BUDGET_RUN', 'ledger');
    const l = g.ledger(stale);
    fs.writeFileSync(stale, JSON.stringify({ ...l, created_at: new Date(Date.now() - 10 * 60_000).toISOString() }, null, 2));
    bindPreflightLedger(l.checkout, g.env, 'r9', new Date().toISOString());
    expect(g.ledger(stale).ship_run).toBeUndefined();
    const twin = g.field(g.sb(['start', '--record', g.record('twin.md'), '--mode', 'observe', '--reading', '1000000']).out, 'BUDGET_RUN', 'ledger');
    const at = new Date().toISOString();
    for (const f of [stale, twin]) fs.writeFileSync(f, JSON.stringify({ ...g.ledger(f), created_at: at }, null, 2));
    bindPreflightLedger(l.checkout, g.env, 'r9', at);
    expect([g.ledger(stale).ship_run, g.ledger(twin).ship_run]).toEqual([undefined, undefined]);
  });

  // Value: protects=a start while the record block names a running handoff child re-attaches the child's root parent run; fails_when=start takes
  //   the child's ledger as the earlier run, so it re-attaches or supersedes the child and the parent's open run keeps its cap out of reach and
  //   holds gstack upgrades (review p1 red-team#1), or the re-attach leaves the record naming the parent, so the running child's --record
  //   commands meter the parent (review v2 outside-voice#4); why_new=no start case had a child on the record; seam=a child ledger written with writeLedger;
  //   no_claim=the handoff commands themselves (test/ship-budget-chain.test.ts)
  test('a start while the record names a handoff child re-attaches the parent run', async () => {
    const { changeRunRecord } = await import('../lib/ship-run-record');
    const { writeLedger } = await import('../lib/ship-budget');
    const h = fresh();
    const record = h.record();
    const first = h.sb(['start', '--record', record, '--mode', 'observe', '--reading', '1000000']);
    const a = h.field(first.out, 'BUDGET_RUN', 'id'), ledger = h.field(first.out, 'BUDGET_RUN', 'ledger');
    expect(changeRunRecord(h.repo, 'preflight', 'r1').ok).toBe(true);
    expect(h.sb(['note', '--record', record, '--step', '9', '--reading', '2000000']).code).toBe(0);
    const dir = path.join(h.state, 'ship-runs', 'ship-child-1');
    fs.mkdirSync(dir, { recursive: true });
    const child: Ledger = { ...h.ledger(ledger), run: 'ship-child-1', dir, file: path.join(dir, 'budget.json'), role: 'child', created_at: new Date().toISOString(), notes: [],
      parent: { run: a, ledger, handoff_sha: 'f'.repeat(64), from: '9', to: '16', return_file: path.join(dir, 'return.txt') } };
    writeLedger(child, h.env);
    expect(fs.readFileSync(record, 'utf8')).toContain('run=ship-child-1 ');
    const again = h.sb(['start', '--record', record, '--mode', 'observe', '--reading', '3000000']);
    expect(again.code, again.out + again.err).toBe(0);
    expect(h.field(again.out, 'BUDGET_RUN', 'id')).toBe(a);
    expect(again.out).not.toContain('SUPERSEDED:');
    expect(h.ledger(child.file).superseded_by).toBeUndefined();
    expect(fs.readFileSync(record, 'utf8')).toContain('run=ship-child-1 ');
  });

  // Value: protects=resume --run walks past a closed run in the middle of the supersede chain to the newest run; fails_when=the walk stops at the
  //   closed middle run and the newest run stays open, holding gstack upgrades (review p1 specialist-batched#1); why_new=the chain case above closed
  //   only the newest run; seam=close --run on the middle run; no_claim=a chain whose newest ledger file was removed
  test('resume --run walks past a closed middle run to the newest run in the chain', () => {
    const h = fresh();
    const record = h.record();
    const id = (r: Run) => h.field(r.out, 'BUDGET_RUN', 'id');
    const a = id(h.sb(['start', '--record', record, '--mode', 'observe', '--reading', '1000000']));
    expect(h.sb(['note', '--record', record, '--step', '9', '--reading', '2000000']).code).toBe(0);
    const b = id(h.sb(['start', '--record', record, '--mode', 'observe', '--reading', '3000000']));
    expect(h.sb(['note', '--record', record, '--step', '9', '--reading', '4000000']).code).toBe(0);
    const c = id(h.sb(['start', '--record', record, '--mode', 'observe', '--reading', '5000000']));
    expect(h.sb(['close', '--run', b, '--reading', '5500000']).code).toBe(0);
    const resumed = h.sb(['resume', '--run', a, '--reading', '6000000']);
    expect(resumed.code, resumed.out + resumed.err).toBe(0);
    expect(resumed.out).toMatch(new RegExp(`^SUPERSEDED: run ${c} `, 'm'));
    expect(h.ledger(path.join(h.state, 'ship-runs', c, 'budget.json')).superseded_by).toBe(a);
  });
  // Value: protects=a re-attaching start applies a stricter cap (lower, or one where the run had none) at once, checking the run against it,
  //   while a higher cap or none still needs resume with the owner's words; fails_when=a run started uncapped stays uncapped after a start
  //   that asks for a cap, because re-attach ignores every --token-cap (review v2 targeted#1); why_new=the cap cases above only ask for
  //   a higher cap or none; seam=none; no_claim=the default subagent cap, which applies only to a new run
  test('a re-attaching start applies a lower cap, and records a stop when the run is already past it', async () => {
    const { changeRunRecord } = await import('../lib/ship-run-record');
    const h = fresh();
    const record = h.record();
    const first = h.sb(['start', '--record', record, '--mode', 'observe', '--token-cap', 'none', '--reading', '1000000']);
    const a = h.field(first.out, 'BUDGET_RUN', 'id'), ledger = h.field(first.out, 'BUDGET_RUN', 'ledger');
    expect(h.ledger(ledger).cap).toBeNull();
    expect(changeRunRecord(h.repo, 'preflight', 'r1').ok).toBe(true);
    expect(h.sb(['note', '--record', record, '--step', '9', '--reading', '5000000']).code).toBe(0);
    const lower = h.sb(['start', '--record', record, '--mode', 'observe', '--token-cap', '8M', '--reading', '6000000']);
    expect([lower.code, h.field(lower.out, 'BUDGET_RUN', 'id')]).toEqual([0, a]);
    expect(lower.out).toMatch(/^CAP: lowered admission_cap=8000000 \(from none:/m);
    expect(h.ledger(ledger).cap).toBe(8_000_000);
    const past = h.sb(['start', '--record', record, '--mode', 'observe', '--token-cap', '3M', '--reading', '6500000']);
    expect([past.code, h.field(past.out, 'BUDGET_RUN', 'id')]).toEqual([3, a]);
    expect(past.out).toMatch(/^STOP: reason=budget_exhausted /m);
    expect(h.ledger(ledger)).toMatchObject({ cap: 3_000_000, stopped: { reason: 'budget_exhausted' } });
  });

  // Value: protects=two starts racing to supersede the same earlier run open one new run between them: the second re-reads the record after the
  //   lock and joins the run the first opened; fails_when=both mint a run, the second overwrites the earlier run's superseded_by and the first
  //   new run is left open and unsuperseded, holding gstack upgrades (review v2 outside-voice#3, adversarial-native#1); why_new=the lock case
  //   above raced a note; seam=the earlier ledger's lock file, held by this test while both starts wait; no_claim=two hosts sharing a state root
  test('two starts racing to supersede the same run open one new run between them', async () => {
    const h = fresh();
    const record = h.record();
    const first = h.sb(['start', '--record', record, '--mode', 'observe', '--reading', '1000000']);
    const a = h.field(first.out, 'BUDGET_RUN', 'id'), ledger = h.field(first.out, 'BUDGET_RUN', 'ledger');
    expect(h.sb(['note', '--record', record, '--step', '9', '--reading', '2000000']).code).toBe(0);
    const lock = `${ledger}.lock`;
    fs.writeFileSync(lock, JSON.stringify({ pid: process.pid, host: os.hostname(), at: new Date().toISOString() }));
    const launch = (reading: string) => {
      const child = spawn(process.execPath, [...bunIsolationArgs(), BUDGET_BIN, 'start', '--record', record, '--mode', 'observe', '--reading', reading], { cwd: h.repo, env: h.env });
      let out = '';
      child.stdout.on('data', d => { out += d; });
      child.stderr.on('data', d => { out += d; });
      return new Promise<{ code: number | null; out: string }>(resolve => child.on('close', code => resolve({ code, out })));
    };
    const runs = [launch('3000000'), launch('3100000')];
    await Bun.sleep(2000);
    fs.unlinkSync(lock);
    const [x, y] = await Promise.all(runs);
    expect([x.code, y.code], x.out + y.out).toEqual([0, 0]);
    const ids = new Set([h.field(x.out, 'BUDGET_RUN', 'id'), h.field(y.out, 'BUDGET_RUN', 'id')]);
    expect(ids.size).toBe(1);
    const b = [...ids][0]!;
    expect(b).not.toBe(a);
    expect(fs.readdirSync(path.join(h.state, 'ship-runs')).sort()).toEqual([a, b].sort());
    expect(h.ledger(ledger).superseded_by).toBe(b);
    expect(fs.readFileSync(record, 'utf8')).toContain(`run=${b} `);
  }, 30_000);

  // Value: protects=preflight binds its run's ledger by the time the preflight began, so a slow fetch or merge never leaves its own ledger
  //   unbound (and its record stuck open after Step 22's close); fails_when=the window is measured to the record's opening at preflight's
  //   end, so a preflight that takes over 5 minutes binds nothing (review v2 outside-voice#2, adversarial-native#2); why_new=the bind cases
  //   above passed the record's own time; seam=the ledger's created_at, backdated, and the time lib/ship-preflight.ts passes (its own start);
  //   no_claim=a start run long before its preflight, or the preflight bin passing its start (this case drives the bind's contract only)
  test('a ledger started 8 minutes before a slow preflight opened its record is still bound', async () => {
    const { bindPreflightLedger } = await import('../lib/ship-run-live');
    const h = fresh();
    const ledger = h.field(h.sb(['start', '--record', h.record(), '--mode', 'observe', '--reading', '1000000']).out, 'BUDGET_RUN', 'ledger');
    const l = h.ledger(ledger);
    fs.writeFileSync(ledger, JSON.stringify({ ...l, created_at: new Date(Date.now() - 8 * 60_000).toISOString() }, null, 2));
    bindPreflightLedger(l.checkout, h.env, 'r1', new Date(Date.now() - 7 * 60_000).toISOString());
    expect(h.ledger(ledger).ship_run).toBe('r1');
  });
  // Value: protects=resume --run finds a successor started with --ledger <custom path> through the record block that names it; fails_when=the
  //   walk looks only under ship-runs/<id>/budget.json, so the custom-path successor stays open and holds gstack upgrades (review v2
  //   outside-voice#5, adversarial-native#4); why_new=every chain case above used the default path; seam=start --ledger; no_claim=a custom-path
  //   run in the middle of a chain, which the record block no longer names
  test('resume --run supersedes a successor that start --ledger put at a custom path', () => {
    const h = fresh();
    const record = h.record();
    const a = h.field(h.sb(['start', '--record', record, '--mode', 'observe', '--reading', '1000000']).out, 'BUDGET_RUN', 'id');
    expect(h.sb(['note', '--record', record, '--step', '9', '--reading', '2000000']).code).toBe(0);
    const custom = path.join(h.root, 'custom', 'budget.json');
    const second = h.sb(['start', '--record', record, '--mode', 'observe', '--reading', '3000000', '--ledger', custom]);
    expect(second.code, second.out + second.err).toBe(0);
    const b = h.field(second.out, 'BUDGET_RUN', 'id');
    const resumed = h.sb(['resume', '--run', a, '--reading', '4000000']);
    expect(resumed.code, resumed.out + resumed.err).toBe(0);
    expect(resumed.out).toMatch(new RegExp(`^SUPERSEDED: run ${b} `, 'm'));
    expect(h.ledger(custom).superseded_by).toBe(a);
  });
  // Value: protects=preflight never binds a ledger another harness session started, so that session's late close never ends this run's record;
  //   fails_when=an unmetered /ship binds an earlier session's unbound ledger started within 5 minutes and that ledger's close ends the newer
  //   run (review v2 outside-voice#1); why_new=the bind cases above had one session; seam=the ledger's owner, rewritten to another pid;
  //   no_claim=a shared harness (capy-server), whose sessions the owner cannot tell apart
  test('a bind skips a ledger another harness session started', async () => {
    const { bindPreflightLedger } = await import('../lib/ship-run-live');
    const h = fresh();
    const ledger = h.field(h.sb(['start', '--record', h.record(), '--mode', 'observe', '--reading', '1000000']).out, 'BUDGET_RUN', 'ledger');
    const l = h.ledger(ledger);
    const me = { machine: 'm', boot: 'b', pid: 4242, start: 7, comm: 'claude' };
    fs.writeFileSync(ledger, JSON.stringify({ ...l, owner: { ...me, pid: 4343 } }, null, 2));
    bindPreflightLedger(l.checkout, h.env, 'r1', new Date().toISOString(), me);
    expect(h.ledger(ledger).ship_run).toBeUndefined();
    bindPreflightLedger(l.checkout, h.env, 'r1', new Date().toISOString(), { ...me, shared: true });
    expect(h.ledger(ledger).ship_run).toBe('r1');
  });
});