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
/gstack-ship keeps a run's token cap when its budget start reruns mid-run, and four more budget-run fixes (GST-4132) (#4882)
Garry Tan37cad2b5268e
diff --git a/changelog.d/fix-ship-budget-reattach-supersede-lock-gst4132.md b/changelog.d/fix-ship-budget-reattach-supersede-lock-gst4132.mdnew file mode 100644index 000000000..5559adacb--- /dev/null+++ b/changelog.d/fix-ship-budget-reattach-supersede-lock-gst4132.md@@ -0,0 +1,4 @@+---+important: regression+---+**/gstack-ship keeps its token cap and clock when its budget start reruns mid-run.** While a /gstack-ship run is still open on the checkout, `gstack-ship-budget start` now always re-attaches that run instead of opening a new one with a fresh cap (or none), applies a stricter `--token-cap` (printing `CAP: lowered`) and prints `CAP: kept` for a looser one; a run already past its cap or 100 active minutes records its stop and exits 3. `resume --run` of a run a later start replaced now marks that later run replaced too, so it no longer holds gstack upgrades for 6 hours. `start --ledger` refuses a path that is the earlier run's ledger file, start takes the earlier run's lock for the whole switch so a racing `note` cannot point the record back at the old run, preflight ties each budget ledger to its run id so an earlier run's late close never ends a later run, and the 100-minute clock ignores calls from a nested checkout or submodule inside the run's checkout. Follow-up to #4877 (GST-4132).diff --git a/docs/ship-budget.md b/docs/ship-budget.mdindex c36c29bdf..7247ba938 100644--- a/docs/ship-budget.md+++ b/docs/ship-budget.md@@ -84,7 +84,9 @@ ship/DRIVER.md stops a run past 100 minutes. Measured conductors ran past it inline of prose (handoffs/ship-conductor-cost-2026-11-16), so it is now code (`lib/ship-clock.ts`). The clock countsactive minutes, not wall time (GST-4109): any stretch longer than 5 minutes with no gstack call in the call log(below) is the lane parked on CI, a reviewer it ended its turn on, or a Captain's ruling, so only its first 5 minutes-count. Only calls made in the run's own checkout count, so another lane on the same machine never keeps it running. A run that keeps calling gstack, such as a pass or phase loop that never settles, never parks, so it still+count. Only calls made in the run's own checkout count (a call whose working directory has that checkout as its git+toplevel; a nested checkout or submodule inside it is another checkout, GST-4132), so another lane on the same machine+never keeps it running. A run that keeps calling gstack, such as a pass or phase loop that never settles, never parks, so it stillstops at 100 minutes. With no call log (off Capy) the clock is wall time. In observe mode the first `note`, or`gstack-ship-phase run --record`, past 100 active minutes from the ledger's start prints@@ -317,14 +319,29 @@ ledger has already gone past its start (a note, a check or a handoff), whose /gsended, or that started over 5 minutes ago mints a new run, marks the earlier ledger `superseded_by` it (so itstops holding gstack upgrades and never writes the record or removes the marker again) and prints`SUPERSEDED: run <id> …`, so an earlier /gstack-ship in the same thread never counts against this run's cap or-clock (GST-4109); a rerun of the same start inside the same open run re-attaches. A start never lifts a stop:-on a stopped ledger it re-attaches, exits 3 and prints a `STOP:` line naming `resume`, which alone continues a-stopped run (a cap raise with the owner's `--approved-by` and `--words`). The same holds for a run that is past its-limit but not yet stopped (an observe run stops only at its next note): while the checkout's /gstack-ship run record that-opened after the ledger is still open, a `start` whose reading puts that ledger over its cap, or whose clock is past 100-active minutes, records the stop, re-attaches, exits 3 and prints a `RESUME:` line instead of minting a new run. A-/gstack-ship that has ended is superseded untouched.-Continue an earlier run with `resume --run <id>`, which clears `superseded_by`. A `resume --meter capy` that moves a run onto the Capy counter needs `--reading`, the new+clock (GST-4109). While the checkout's /gstack-ship run record is that ledger's and still open (preflight bound the+ledger to its run id, or for an older ledger the record opened after it), `start` always re-attaches the run, however far it+got: a stricter `--token-cap` (lower, or a cap where the run had none) applies and prints `CAP: lowered …`, while a higher+cap or `none` prints `CAP: kept admission_cap=<n> …`, since only `resume --token-cap` with the owner's words raises or removes+one (GST-4132). A start never lifts a stop: on a stopped ledger it+re-attaches, exits 3 and prints a `STOP:` line naming `resume`, which alone continues a stopped run (a cap raise with the+owner's `--approved-by` and `--words`). Every re-attach first checks the run's limits at this start's reading (an observe+run stops only at its next note): a run past its cap, or past 100 active minutes, records the stop, exits 3 and prints a+`RESUME:` line. A /gstack-ship that has ended is superseded untouched. In full:++| The checkout's run record | Ledger open, within its limits | Open, past a limit | Stopped | Closed |+|---|---|---|---|---|+| Open, and this ledger's | re-attach, exit 0 | record the stop, re-attach, exit 3 | re-attach, exit 3 | new run |+| Ended after the ledger started | supersede, exit 0 | supersede untouched, exit 0 | re-attach, exit 3 | new run |+| None, or another run's | a rerun within 5 minutes and before any progress re-attaches (exit 3 past a limit); otherwise supersede, exit 0 | the same | re-attach, exit 3 | new run |++`start` decides and writes while holding the earlier ledger's lock, so a `note --run <old>` racing it lands before the+supersede (which then points the record at the new run) or finds the old run superseded, and a second `start` racing it+re-reads the record and joins the run the first one opened; and it refuses `--ledger <path>`+when the path is the earlier ledger's file (by path, symlink or hard link), which a new run would overwrite.+Continue an earlier run with `resume --run <id>`, which clears `superseded_by` and marks the newest run that had+superseded it superseded in turn (`SUPERSEDED: run <id> superseded run <id>, and this resume …`), so that run stops+holding gstack upgrades; a closed one is left as it was (GST-4132). A `resume --meter capy` that moves a run onto the Capy counter needs `--reading`, the newepoch's baseline, or it would count the thread's whole counter as the run's use. The ledger and record aremirrored to a private Drive checkpoint (`GSTACK_SHIP_BUDGET_CHECKPOINT_DIR`, else theproject-user Drive folder on Capy) bound to the run id and their hashes, so after a machinediff --git a/docs/ship-policy.md b/docs/ship-policy.mdindex a5b9918d0..1955d5552 100644--- a/docs/ship-policy.md+++ b/docs/ship-policy.md@@ -1824,7 +1824,8 @@ without `--owner-ref` stop. Only gstack's commands end it: `finish` removes therecord (only when the open PR's body names that run), `gstack-ship-receipt stop`marks it stopped (a new run's preflight replaces it), `gstack-skill-end` marks it finished on anyoutcome, the run's own Step 22 `gstack-ship-budget close` marks its open record finished (the next-preflight does the same for an open record whose run's budget ledger already closed, GST-4109), and `gstack-ship-run abandon` ends a run that stopped working, never+preflight does the same for an open record whose run's budget ledger already closed, GST-4109; that ledger is the one+the run's preflight bound to its run id, so an earlier run's late close never ends a later run, GST-4132), and `gstack-ship-run abandon` ends a run that stopped working, neverwithin 60 minutes of its last beat unless the harness process it ran under isprovably gone (GST-3546). No timer ends a run. A bare marker from anolder gstack reads as `legacy` and an unreadable record as `unreadable`; bothdiff --git a/lib/ship-budget-cli.ts b/lib/ship-budget-cli.tsindex 79f0cb845..8e8e00f66 100644--- a/lib/ship-budget-cli.ts+++ b/lib/ship-budget-cli.ts@@ -15,25 +15,23 @@ import { resultLine } from './result-codes';import { readRunRecord, thisRunOwner } from './ship-run-record';import { endClosedRun } from './ship-run-live';import { resolveStateRoot } from './state-root';-import { spawnSync } from './spawn-sync';+import { withFileLock } from './spend-ledger';import {BudgetError, DEFAULT_TAIL, SUBAGENT_DEFAULT_CAP, DELEGATE_SEGMENT_CALL, DELEGATE_START_CALL, MAX_CHAIN_DEPTH, METER_CONTRACTS, SEGMENTS, SHIP_STEPS,aboveFloor, admits, applyCredits, applyReading, budgetError, creditsUsed, parseCredits, budgetLine, keepsSmallRun, labelScope, ledgerFileFor, loadCalibration, measureSettled, mintRunId, mutateLedger, newEpoch,parseNext, parseRecordBlock, parseStep, parseTokens, pointMarker, projector, readLedger, reserveIn, restoreRun, reviewPaths,- runDirFor, settleIn, stepProjection, tally, unitConstants, unreservedDispatches, usageError, writeLedger,+ runDirFor, settleIn, stepProjection, tally, unitConstants, unreservedDispatches, usageError, writeLedger, writeRecordBlock,type Ledger, type MeterKind, type Next, type Note,} from './ship-budget';import { callLogFile, countLoggedCalls, loggedCallsLine, readCallLog } from './ship-call-log';import { callsLine, countCalls } from './ship-calls';-import { callsSince, runClock, TIME_LIMIT_MIN, timeStop } from './ship-clock';+import { callsSince, gitToplevel, runClock, TIME_LIMIT_MIN, timeStop } from './ship-clock';import { claudeConfigDir, loadMeterState, newMeterState, nonceSessions, readClaudeUsage, saveMeterState, sessionJournals } from './claude-usage';export type Opts = Record<string, string | true>;export interface Outcome { stdout: string[]; exit: number }export interface Ctx { env: NodeJS.ProcessEnv; cwd: string }-const toplevel = (cwd: string) => { const r = spawnSync('git', ['rev-parse', '--show-toplevel'], { cwd, encoding: 'utf8', timeout: 10_000 }); return r.status === 0 ? r.stdout.trim() : ''; };-export function parseArgs(argv: string[], values: string[], flags: string[] = []): Opts {const out: Opts = {};for (let i = 0; i < argv.length; i++) {@@ -265,58 +263,107 @@ export function cmdStart(argv: string[], ctx: Ctx): Outcome {const callFloor = tokensOpt(o, 'call-floor');const delegate = str(o, 'delegate') ?? 'auto';if (delegate !== 'auto' && delegate !== 'never') throw usageError(`--delegate '${delegate}' is not auto or never`);- const existing = parseRecordBlock(record);- const prior = existing?.ledger && fs.existsSync(existing.ledger) ? readLedger(existing.ledger) : undefined;- const newer = prior && !prior.closed_at && !prior.stopped ? newerRun(prior, ctx.cwd) : undefined;- if (newer && liveRecord(prior!, ctx.cwd) && lapsed(prior!, o, ctx.env)) {- return mutateLedger(prior!.file, ctx.env, l => {- try { readMeter(l, o, false); } catch { /* as in lapsed */ }- const t = tally(l);- const stop = l.cap !== null && t.used + t.unknown > l.cap ? stopLines(l, { call: null, next: '1', step: '1', projected: 0, reason: 'budget_exhausted' }) : timeStop(l, ctx.cwd, '1', ctx.env) ?? [];- return { stdout: [`BUDGET_RUN: id=${l.run} ledger=${l.file}`, ...stop, `RESUME: run ${l.run} on this record was past its limit, so this start recorded its stop instead of opening a new run; a new start never lifts a stop: gstack-ship-budget resume --record ${l.record} (a cap raise needs --token-cap <n> --approved-by <who> --words <their words>)`], exit: 3 };- });- }- if (prior && !prior.closed_at && (prior.stopped || !newer)) {- return mutateLedger(prior.file, ctx.env, l => {- if (scope === 'tree' || parentCounter) l.meter_scope = 'tree';- return { stdout: [`BUDGET_RUN: id=${l.run} ledger=${l.file}`, budgetLine(l, { call: null, next: '1', projected: 0, verdict: l.stopped ? 'stop' : 'continue' }),- ...(l.stopped ? [`STOP: reason=${l.stopped.reason} at Step ${l.stopped.step}; this record's run stopped, and a new start never lifts a stop: resume first (gstack-ship-budget resume --record ${l.record}; a cap raise needs --token-cap <n> --approved-by <who> --words <their words>)`] : [])], exit: l.stopped ? 3 : 0 };- });+ const recordLedger = () => {+ const block = parseRecordBlock(record);+ let file = block?.ledger && fs.existsSync(block.ledger) ? block.ledger : undefined;+ const named = file;+ for (const seen = new Set<string>(); file && !seen.has(file);) {+ seen.add(file);+ const up = readLedger(file);+ if (up.role !== 'child' || !up.parent || !fs.existsSync(up.parent.ledger)) break;+ file = up.parent.ledger;+ }+ return { file, child: file !== named ? named : undefined };+ };+ let child: string | undefined;+ const begin = (prior: Ledger | undefined): Outcome => {+ const open = prior && !prior.closed_at ? prior : undefined;+ const newer = open && !open.stopped && !liveRecord(open, ctx.cwd) ? newerRun(open, ctx.cwd) : undefined;+ if (open && !newer) {+ const out = reattach(open, o, ctx, rawCap === undefined ? undefined : cap, scope === 'tree' || parentCounter);+ if (child && open.record) writeRecordBlock(open.record, readLedger(child));+ return out;+ }+ const ledgerOpt = str(o, 'ledger');+ if (prior && ledgerOpt !== undefined && sameFile(ledgerOpt, prior.file)) throw usageError(`--ledger ${ledgerOpt} is the earlier run ${prior.run}'s ledger (${prior.file}); a new run never writes over it: pass a new path, or omit --ledger`);+ const meter = pickMeter(o);+ if (!meter) {+ if (cap !== null) throw budgetError('BUDGET_METER_UNAVAILABLE', 'tried --reading (absent), a Claude Code session (--session/--nonce absent) and --meter estimate (not passed)');+ return { stdout: ['BUDGET: unmetered admission_cap=none (no readable meter: --reading <n> on Capy, --session <id> on Claude Code)'], exit: 0 };+ }+ const superseded = newer ? [`SUPERSEDED: run ${open!.run} on this record ${newer} and stays as it was; this /ship is a new run whose cap and clock count from its own start (to continue that run instead: gstack-ship-budget resume --run ${open!.run})`] : [];+ const run = mintRunId();+ const dir = runDirFor(ctx.env, run);+ const owner = thisRunOwner(), checkout = gitToplevel(ctx.cwd);+ const cal = loadCalibration(str(o, 'calibration'));+ const contract = METER_CONTRACTS[meter];+ const paths = reviewPaths(ctx.cwd, ctx.env);+ const sessions = meter === 'claude' ? bindClaude(o, ctx.env) : undefined;+ const l: Ledger = {+ schema_version: 1, kind: 'gstack-ship-budget', run, dir, file: ledgerOpt ?? path.join(dir, 'budget.json'), record: path.resolve(record),+ created_at: new Date().toISOString(), cap, tail: tokensOpt(o, 'reserve') ?? DEFAULT_TAIL, ...(tokensOpt(o, 'reserve') !== undefined ? { tail_explicit: true } : {}),+ stop_overhead: unitConstants(cal, contract.unit).stop_overhead,+ delegate, role: 'parent', meter: { contract, epoch: 1, baseline: 0, last: null, ...(sessions ? { sessions, config_dir: claudeConfigDir(ctx.env) } : {}), ...(str(o, 'meter-source') ? { source: str(o, 'meter-source') } : {}) },+ epochs: [], carried_used: 0, estimate_used: 0, unknown: 0, next_id: 1, reservations: [], handoffs: [], cap_raises: [],+ marker: paths.marker, review_log: paths.reviewLog, ...(str(o, 'calibration') ? { calibration: path.resolve(str(o, 'calibration')!) } : {}),+ ...(callFloor !== undefined ? { call_floor: callFloor } : {}), ...(mode === 'observe' ? { mode } : {}),+ ...(scope === 'tree' || parentCounter ? { meter_scope: 'tree' as const } : {}),+ ...(checkout ? { checkout } : {}), ...(owner ? { owner } : {}),+ };+ if (meter === 'capy' && tokensOpt(o, 'reading') === undefined) throw budgetError('BUDGET_READING_MISSING', 'start --meter capy');+ if (meter === 'capy') l.meter.baseline = tokensOpt(o, 'reading')!;+ const call = readMeter(l, o, true);+ if (meter === 'claude') l.meter.baseline = l.meter.last ?? 0;+ const out = decide(l, '0.9', { kind: 'step', step: '1' }, call, true);+ writeLedger(l, ctx.env);+ pointMarker(l.marker, l);+ if (newer) { open!.superseded_by = run; writeLedger(open!, ctx.env); }+ const note = defaultCap ? [`BUDGET_DEFAULT_CAP: ${SUBAGENT_DEFAULT_CAP / 1e6}M (a /ship run metering its own counter; --token-cap <n> or none to change it)`] : [];+ return labelScope(l, { stdout: [...superseded, `BUDGET_RUN: id=${run} ledger=${l.file}`, ...note, ...out.stdout], exit: out.exit });+ };+ for (let tries = 0; ; tries++) {+ const { file: priorFile, child: running } = recordLedger();+ child = running;+ if (!priorFile) return begin(undefined);+ const out = withFileLock(priorFile, () => { const prior = readLedger(priorFile); return prior.superseded_by && tries < 5 ? null : begin(prior); });+ if (out) return out;}- const meter = pickMeter(o);- if (!meter) {- if (cap !== null) throw budgetError('BUDGET_METER_UNAVAILABLE', 'tried --reading (absent), a Claude Code session (--session/--nonce absent) and --meter estimate (not passed)');- return { stdout: ['BUDGET: unmetered admission_cap=none (no readable meter: --reading <n> on Capy, --session <id> on Claude Code)'], exit: 0 };+}++const sameFile = (a: string, b: string) => {+ try {+ if (fs.realpathSync(a) === fs.realpathSync(b)) return true;+ const x = fs.statSync(a), y = fs.statSync(b);+ return x.ino !== 0 && x.dev === y.dev && x.ino === y.ino;+ } catch { return false; }+};++/**+ * Re-attach the record's open run instead of opening a new one (GST-4132): a stopped run exits 3 until resume lifts its stop, and any other+ * run is first checked against its limits at this start's reading (lapsed), so one already past its cap or 100 active minutes records that+ * stop and exits 3. A re-attached run keeps its own cap unless this start asks for a stricter one (asked: the cap it asked for), which+ * applies before that check; raising or removing a cap is resume's, with the owner's words.+ */+function reattach(l: Ledger, o: Opts, ctx: Ctx, asked: number | null | undefined, tree: boolean): Outcome {+ if (tree) l.meter_scope = 'tree';+ const head = [`BUDGET_RUN: id=${l.run} ledger=${l.file}`];+ const stricter = asked !== undefined && asked !== null && (l.cap === null || asked < l.cap);+ const kept = stricter ? [`CAP: lowered admission_cap=${asked} (from ${l.cap ?? 'none'}: this start re-attached run ${l.run}, and a lower cap needs no owner's words)`]+ : asked !== undefined && asked !== l.cap ? [`CAP: kept admission_cap=${l.cap ?? 'none'} (this start re-attached run ${l.run}, so --token-cap ${asked ?? 'none'} does not apply; raising or removing a cap is gstack-ship-budget resume --record ${l.record} --token-cap <n> --approved-by <who> --words <their words>)`] : [];+ if (stricter) l.cap = asked;+ let out: Outcome;+ if (!l.stopped && lapsed(l, o, ctx.env)) {+ try { readMeter(l, o, false); } catch { /* as in lapsed */ }+ const t = tally(l);+ const stop = l.cap !== null && t.used + t.unknown > l.cap ? stopLines(l, { call: null, next: '1', step: '1', projected: 0, reason: 'budget_exhausted' }) : timeStop(l, ctx.cwd, '1', ctx.env) ?? [];+ out = { stdout: [...head, ...stop, `RESUME: run ${l.run} on this record was past its limit, so this start recorded its stop instead of opening a new run; a new start never lifts a stop: gstack-ship-budget resume --record ${l.record} (a cap raise needs --token-cap <n> --approved-by <who> --words <their words>)`, ...kept], exit: 3 };+ } else {+ out = { stdout: [...head, budgetLine(l, { call: null, next: '1', projected: 0, verdict: l.stopped ? 'stop' : 'continue' }),+ ...(l.stopped ? [`STOP: reason=${l.stopped.reason} at Step ${l.stopped.step}; this record's run stopped, and a new start never lifts a stop: resume first (gstack-ship-budget resume --record ${l.record}; a cap raise needs --token-cap <n> --approved-by <who> --words <their words>)`] : []), ...kept], exit: l.stopped ? 3 : 0 };}- const superseded = newer ? [`SUPERSEDED: run ${prior!.run} on this record ${newer} and stays as it was; this /ship is a new run whose cap and clock count from its own start (to continue that run instead: gstack-ship-budget resume --run ${prior!.run})`] : [];- const run = mintRunId();- const dir = runDirFor(ctx.env, run);- const owner = thisRunOwner(), checkout = toplevel(ctx.cwd);- const cal = loadCalibration(str(o, 'calibration'));- const contract = METER_CONTRACTS[meter];- const paths = reviewPaths(ctx.cwd, ctx.env);- const sessions = meter === 'claude' ? bindClaude(o, ctx.env) : undefined;- const l: Ledger = {- schema_version: 1, kind: 'gstack-ship-budget', run, dir, file: str(o, 'ledger') ?? path.join(dir, 'budget.json'), record: path.resolve(record),- created_at: new Date().toISOString(), cap, tail: tokensOpt(o, 'reserve') ?? DEFAULT_TAIL, ...(tokensOpt(o, 'reserve') !== undefined ? { tail_explicit: true } : {}),- stop_overhead: unitConstants(cal, contract.unit).stop_overhead,- delegate, role: 'parent', meter: { contract, epoch: 1, baseline: 0, last: null, ...(sessions ? { sessions, config_dir: claudeConfigDir(ctx.env) } : {}), ...(str(o, 'meter-source') ? { source: str(o, 'meter-source') } : {}) },- epochs: [], carried_used: 0, estimate_used: 0, unknown: 0, next_id: 1, reservations: [], handoffs: [], cap_raises: [],- marker: paths.marker, review_log: paths.reviewLog, ...(str(o, 'calibration') ? { calibration: path.resolve(str(o, 'calibration')!) } : {}),- ...(callFloor !== undefined ? { call_floor: callFloor } : {}), ...(mode === 'observe' ? { mode } : {}),- ...(scope === 'tree' || parentCounter ? { meter_scope: 'tree' as const } : {}),- ...(checkout ? { checkout } : {}), ...(owner ? { owner } : {}),- };- if (meter === 'capy' && tokensOpt(o, 'reading') === undefined) throw budgetError('BUDGET_READING_MISSING', 'start --meter capy');- if (meter === 'capy') l.meter.baseline = tokensOpt(o, 'reading')!;- const call = readMeter(l, o, true);- if (meter === 'claude') l.meter.baseline = l.meter.last ?? 0;- const out = decide(l, '0.9', { kind: 'step', step: '1' }, call, true);writeLedger(l, ctx.env);- pointMarker(l.marker, l);- if (superseded.length) mutateLedger(prior!.file, ctx.env, old => { old.superseded_by = run; });- const note = defaultCap ? [`BUDGET_DEFAULT_CAP: ${SUBAGENT_DEFAULT_CAP / 1e6}M (a /ship run metering its own counter; --token-cap <n> or none to change it)`] : [];- return labelScope(l, { stdout: [...superseded, `BUDGET_RUN: id=${run} ledger=${l.file}`, ...note, ...out.stdout], exit: out.exit });+ if (stricter) pointMarker(l.marker, l);+ return labelScope(l, out);}/**@@ -326,20 +373,24 @@ export function cmdStart(argv: string[], ctx: Ctx): Outcome {* this same /ship, whose rerun of start re-attaches), or it started over RESTART_MS ago. A new start never joins an earlier /ship: it mints its* own run and marks that ledger superseded_by it (so it stops holding gstack upgrades and writing the record), so the earlier run's* tokens and minutes never count against this run's cap and clock. A stopped ledger is never superseded: start re-attaches it and- * exits 3, so only resume (with the owner's words for a cap raise) lifts a stop.+ * exits 3, so only resume (with the owner's words for a cap raise) lifts a stop. Start decides and writes holding the earlier ledger's+ * lock (GST-4132), so a note on that run lands before the supersede (which then points the record at the new run) or after it (when the+ * superseded run writes no record); the state table is in docs/ship-budget.md. A record block that names a handoff child's ledger (the child+ * writes it while it runs) is followed to its root parent's ledger, the run start re-attaches or supersedes; a re-attach then points the+ * record back at that child, whose --record commands keep metering it until it returns.*/const RESTART_MS = 5 * 60_000;/**- * Whether an open, unstopped ledger is already past its cap at this start's reading, or past 100 active minutes: a stop its next note- * would record, since an observe run stops lazily. While the checkout's run record that opened after the ledger is still open- * (liveRecord: that /ship is in progress, as after a compaction), start then records that stop and re-attaches instead of superseding- * (GST-4109), so a rerun of start never hands a run past its limit a fresh cap and clock without the owner's words. A /ship that ended- * (its record finished, stopped, abandoned or removed) is superseded untouched: the thread's later counter is never charged to it.+ * Whether the checkout's /ship run record is this ledger's and still open (that /ship is in progress, as after a compaction): the record+ * whose preflight bound this ledger (ship_run, lib/ship-run-live.ts bindPreflightLedger), or for an unbound ledger one that opened at or+ * after its start. While it is, start always re-attaches the run (GST-4132, reattach), whatever this start's --token-cap says. A /ship+ * that ended (its record finished, stopped, abandoned or removed) is superseded untouched: the thread's later counter is never charged to it.*/const liveRecord = (l: Ledger, cwd: string) => {- const read = readRunRecord(toplevel(cwd) || cwd);- return read.kind === 'record' && read.record.state === 'open' && Date.parse(read.record.started_at) >= Date.parse(l.created_at);+ const read = readRunRecord(gitToplevel(cwd) || cwd);+ return read.kind === 'record' && read.record.state === 'open' && (l.ship_run ? l.ship_run === read.record.run : Date.parse(read.record.started_at) >= Date.parse(l.created_at));};+/** Whether an open, unstopped ledger is already past its cap at this start's reading, or past 100 active minutes: a stop its next note would record, since an observe run stops lazily. */function lapsed(prior: Ledger, o: Opts, env: NodeJS.ProcessEnv): boolean {const trial = structuredClone(prior);try { readMeter(trial, o, false); } catch { /* a reading this ledger rejects leaves its cap at its last reading */ }@@ -348,7 +399,7 @@ function lapsed(prior: Ledger, o: Opts, env: NodeJS.ProcessEnv): boolean {}function newerRun(l: Ledger, cwd: string): string | undefined {if (l.notes?.length || l.steps_done?.length || l.handoffs.length || l.reservations.length > 1 || l.reservations.some(r => r.state !== 'open')) return 'already ran past its start';- const read = readRunRecord(toplevel(cwd) || cwd);+ const read = readRunRecord(gitToplevel(cwd) || cwd);if (read.kind === 'record' && read.record.state !== 'open' && Date.parse(read.record.started_at) >= Date.parse(l.created_at)) return `belongs to /ship run ${read.record.run}, which passed preflight and is ${read.record.state}`;if (Date.now() - Date.parse(l.created_at) > RESTART_MS) return `started over ${RESTART_MS / 60_000} minutes ago`;return undefined;@@ -551,14 +602,41 @@ export function cmdResume(argv: string[], ctx: Ctx): Outcome {}const was = l.stopped;delete l.stopped;+ const taken = l.superseded_by ? supersedeSuccessor(l, ctx.env) : [];delete l.superseded_by;if (was?.reason === 'past_100_minutes') l.clock_from = new Date().toISOString();pointMarker(l.marker, l);- return [`BUDGET_RUN: id=${l.run} ledger=${l.file}`, `RESUMED: from=${was ? `Step ${was.step} (${was.reason})` : 'running'}`, ...(was?.reason === 'past_100_minutes' ? [`CLOCK: restarted at ${l.clock_from} (the 100-minute limit counts from here)`] : []), budgetLine(l, { call: null, next: was?.next ?? '-', projected: 0, verdict: 'continue' })];+ return [...taken, `BUDGET_RUN: id=${l.run} ledger=${l.file}`, `RESUMED: from=${was ? `Step ${was.step} (${was.reason})` : 'running'}`, ...(was?.reason === 'past_100_minutes' ? [`CLOCK: restarted at ${l.clock_from} (the 100-minute limit counts from here)`] : []), budgetLine(l, { call: null, next: was?.next ?? '-', projected: 0, verdict: 'continue' })];});return { stdout: [...lines, ...out], exit: 0 };}+/**+ * resume --run of a superseded run (GST-4132): follow superseded_by to the newest run in the chain and mark it superseded by the resumed+ * run, so that open ledger stops holding gstack upgrades and writing the record; a closed newest run is left as it was (a closed run in+ * the middle of the chain is walked past). A run the record block names is found at the ledger it names (a start --ledger path). Runs while the resumed+ * run's ledger is locked, before it points the record back at itself.+ */+function supersedeSuccessor(l: Ledger, env: NodeJS.ProcessEnv): string[] {+ const seen = new Set([l.run]);+ for (let id = l.superseded_by; id && !seen.has(id);) {+ seen.add(id);+ const block = l.record ? parseRecordBlock(l.record) : undefined;+ const file = block?.run === id && block.ledger ? block.ledger : ledgerFileFor({ run: id }, env);+ if (!fs.existsSync(file)) return [];+ const next = mutateLedger(file, env, n => {+ if (n.superseded_by) return n.superseded_by;+ if (n.closed_at) return null;+ n.superseded_by = l.run;+ return '';+ });+ if (next === null) return [];+ if (next === '') return [`SUPERSEDED: run ${id} superseded run ${l.run}, and this resume of ${l.run} supersedes it in turn: it stays as it was and no longer holds gstack upgrades (to continue it instead: gstack-ship-budget resume --run ${id})`];+ id = next;+ }+ return [];+}+/** Rebuild a ledger from the record's gstack-budget block; open reservations are charged as unknown. */function rebuildLedger(file: string, record: string | undefined, ctx: Ctx, o: Opts): void {const b = record ? parseRecordBlock(record) : undefined;diff --git a/lib/ship-budget.ts b/lib/ship-budget.tsindex dfa610cf3..5fa10ed45 100644--- a/lib/ship-budget.ts+++ b/lib/ship-budget.ts@@ -110,6 +110,8 @@ export interface Ledger {clock_from?: string;/** The run a later start on the same record opened instead of re-attaching this one (GST-4109); resume clears it. */superseded_by?: string;+ /** The /ship run id whose preflight opened the checkout's run record right after this ledger's start (GST-4132, lib/ship-run-live.ts bindPreflightLedger). */+ ship_run?: string;}/** A refusal: exit 2 for usage and validation (stderr), exit 3 for a stop. */diff --git a/lib/ship-clock.ts b/lib/ship-clock.tsindex 7055928c1..a4d999b5e 100644--- a/lib/ship-clock.ts+++ b/lib/ship-clock.ts@@ -26,20 +26,33 @@ export const PARKED_AFTER_MS = 300_000;export const clockFrom = (l: Pick<Ledger, 'created_at' | 'clock_from'>) => l.clock_from ?? l.created_at;+/** The canonical git toplevel of `cwd` (the form a ledger's checkout records), or '' where git cannot resolve one (a deleted directory, no checkout). */+export function gitToplevel(cwd: string): string {+ const r = spawnSync('git', ['rev-parse', '--show-toplevel'], { cwd, encoding: 'utf8', timeout: 10_000 });+ return r.status === 0 ? r.stdout.trim() : '';+}+/*** The run's clock in minutes since clockFrom: wall, parked (each stretch between call-log rows, or from the clock's start to the first* row and from the last row to now, past PARKED_AFTER_MS) and active (wall minus parked), which the 100-minute stop compares. A row- * counts when it ran in the run's checkout (a row from before rows carried a cwd counts too), lasting as long as it ran, and so does this- * process's own pending row. With no row in the window (no call log: off Capy) the clock is wall time and source is wall.+ * counts when it ran in the run's checkout, lasting as long as it ran, and so does this process's own pending row (a row from before rows+ * carried a cwd counts too). In the checkout means the row's cwd has the checkout as its git toplevel (GST-4132): a plain subdirectory+ * counts, a nested checkout or submodule under it does not; a cwd git cannot resolve (since deleted) falls back to the path prefix. With no row in the window (no call log: off Capy) the clock is wall time and source is wall.*/export function runClock(l: Pick<Ledger, 'created_at' | 'clock_from' | 'checkout'>, env: NodeJS.ProcessEnv, now = Date.now()): { active: number; wall: number; parked: number; source: 'log' | 'wall' } {const from = Date.parse(clockFrom(l));const wall = Math.max(0, now - from);const self = pendingRow();- const here = (cwd: string | undefined) => !cwd || !l.checkout || cwd === l.checkout || cwd.startsWith(l.checkout + path.sep);- const spans = [...readCallLog(callLogFile(env)), ...(self ? [self] : [])].filter(r => here(r.cwd))- .map(r => [Date.parse(r.start), Date.parse(r.start) + Math.max(0, r.ms)] as const)- .filter(([s, e]) => e >= from && s <= now).map(([s, e]) => [Math.max(s, from), Math.min(e, now)] as const).sort((a, b) => a[0] - b[0]);+ const tops = new Map<string, string>();+ const here = (cwd: string | undefined) => {+ if (!cwd || !l.checkout || cwd === l.checkout) return true;+ if (!tops.has(cwd)) tops.set(cwd, gitToplevel(cwd));+ const top = tops.get(cwd)!;+ return top ? top === l.checkout : cwd.startsWith(l.checkout + path.sep);+ };+ const spans = [...readCallLog(callLogFile(env)), ...(self ? [self] : [])]+ .map(r => ({ cwd: r.cwd, s: Date.parse(r.start), e: Date.parse(r.start) + Math.max(0, r.ms) }))+ .filter(r => r.e >= from && r.s <= now && here(r.cwd)).map(r => [Math.max(r.s, from), Math.min(r.e, now)] as const).sort((a, b) => a[0] - b[0]);if (!spans.length) return { active: wall / 60_000, wall: wall / 60_000, parked: 0, source: 'wall' };let parked = 0, cursor = from;for (const [s, e] of [...spans, [now, now] as const]) {diff --git a/lib/ship-preflight.ts b/lib/ship-preflight.tsindex 6805ffe21..d893a80e6 100644--- a/lib/ship-preflight.ts+++ b/lib/ship-preflight.ts@@ -18,7 +18,7 @@ import { classifyDiff } from './review-depth';import { wtreeFingerprint } from './script-invocation';import { audit } from './ship-audit';import { changeRunRecord, openRun, readRunRecord, thisRunOwner } from './ship-run-record';-import { endClosedRun } from './ship-run-live';+import { bindPreflightLedger, endClosedRun } from './ship-run-live';import { resolveStateRoot } from './state-root';import { bin, carryNoneLines, firstLine, flagReader, gh, git, hostedOrigin, laneConcurrency, laneLine, lanes, mappedLanes, recordCiTimeout, Report, runLanes, shipPolicy, short } from './ship-bin-common';@@ -89,6 +89,7 @@ function shipRunClear(cwd: string, base: string, run: string | undefined, r: Rep}function integrate(cwd: string, base: string, run: string | undefined, r: Report): boolean {+ const began = new Date().toISOString();const branch = git(cwd, ['branch', '--show-current']).stdout.trim();r.add(`BRANCH: ${branch || '(detached)'} base=${base}`);if (!branch || branch === base) { r.stop(`on the base branch (${branch || 'detached HEAD'}): ship from a feature branch`); return false; }@@ -141,7 +142,7 @@ function integrate(cwd: string, base: string, run: string | undefined, r: Reportif (!run) return true;const owner = thisRunOwner();const opened = changeRunRecord(cwd, 'preflight', run, { ...(/^[1-9]\d*$/.test(n) ? { pr: Number(n) } : {}), ...(owner ? { owner } : {}) });- if (opened.ok) return true;+ if (opened.ok) { bindPreflightLedger(git(cwd, ['rev-parse', '--show-toplevel']).stdout.trim(), process.env, run, began, owner); return true; }r.stop(`cannot record /ship run ${run} on this checkout (${opened.why}): the base is merged, but a later full preflight could merge again under this run's reviews; check gstack-ship-run status, then rerun`);return false;}diff --git a/lib/ship-run-live.ts b/lib/ship-run-live.tsindex f286bd576..cfa27c02c 100644--- a/lib/ship-run-live.ts+++ b/lib/ship-run-live.ts@@ -9,12 +9,15 @@* stamped). A stopped run can still claim its fix-check grant and resume, so it keeps* the hold, and so does a record that is missing, open, legacy, unreadable, older than the ledger or another ledger's.* A ledger a later start superseded (superseded_by) no longer holds either.- * The same ownership ends a finished run (endClosedRun, GST-4109): an open record whose own ledger closed (Step 22's close) is marked- * finished, so it no longer blocks the next /ship on the checkout, while a record whose ledger is still open keeps blocking.+ * A finished run ends (endClosedRun, GST-4109): an open record whose own ledger closed (Step 22's close) is marked finished, so it no+ * longer blocks the next /ship on the checkout, while a record whose ledger is still open keeps blocking. Its own ledger is the one its+ * preflight bound to its run id (bindPreflightLedger, GST-4132), never one picked by timing.*/import * as fs from 'node:fs';import * as path from 'node:path';-import { changeRunRecord, ownerGone, readRunRecord, type RunRecord } from './ship-run-record';+import { mutateLedger } from './ship-budget';+import { changeRunRecord, ownerGone, readRunRecord, type RunOwner, type RunRecord } from './ship-run-record';+import { resolveStateRoot } from './state-root';export const LEDGER_HOLD_MS = 360 * 60_000;export const REVIEW_START_HOLD_MS = 120 * 60_000;@@ -43,22 +46,37 @@ const owns = (ledgers: Ledgers, l: Record<string, any>) => (r: RunRecord) => {};/**- * End a finished run: when the checkout's record is open and its own ledger (owns) closed after the record opened and belongs to that- * record's run (the record opened within PREFLIGHT_AFTER_START_MS of the ledger's start, as /ship's start-then-preflight does, or the- * ledger noted or reserved after the record opened), mark it finished (ended_by gstack-ship-budget close) and return the RUN_ENDED- * line; null when there is nothing to end. Any other ledger belongs to an earlier run (a later run that wrote no ledger of its own,- * such as an unmetered start, sits behind it), so its late close never ends that record. `checkout` is the git toplevel a ledger records.+ * Bind the ledger of the /ship whose preflight just opened `run`'s record (GST-4132): the one newest parent ledger for the checkout that is+ * open, unsuperseded and unbound, and started at most PREFLIGHT_AFTER_START_MS before this preflight began (/ship's start-then-preflight;+ * measured from the preflight's start, so a slow fetch or merge never pushes its own ledger out of the window), and not started under+ * another harness process than this preflight's `owner` (a harness every session shares, such as capy-server, proves nothing).+ * No such ledger (an unmetered /ship, a start long before its preflight, two started at once) binds nothing, so its close ends no record.+ * A bind that cannot take the ledger's lock is skipped: the record then stays open until skill-end, stop or abandon end it.+ */+export function bindPreflightLedger(checkout: string, env: NodeJS.ProcessEnv, run: string, preflightAt: string, owner: RunOwner | null = null): void {+ const began = Date.parse(preflightAt);+ const otherSession = (o: RunOwner | undefined) => !!o && !!owner && !o.shared && !owner.shared+ && (o.machine !== owner.machine || o.boot !== owner.boot || o.pid !== owner.pid || o.start !== owner.start);+ const candidates = shipLedgers(resolveStateRoot(env)).filter(({ l }) => l.checkout === checkout && l.role !== 'child' && !l.closed_at && !l.superseded_by && !l.ship_run+ && created(l) <= began && began - created(l) <= PREFLIGHT_AFTER_START_MS && !otherSession(l.owner));+ const newest = Math.max(...candidates.map(x => created(x.l)));+ const mine = candidates.filter(x => created(x.l) === newest);+ if (mine.length !== 1) return;+ try { mutateLedger(mine[0]!.file, env, l => { if (!l.closed_at && !l.superseded_by && !l.ship_run) l.ship_run = run; }); } catch { /* unbound: fails closed */ }+}++/**+ * End a finished run: when the checkout's record is open and the ledger its preflight bound to its run (bindPreflightLedger) has closed,+ * mark it finished (ended_by gstack-ship-budget close) and return the RUN_ENDED line; null when there is nothing to end. Any other+ * ledger belongs to another run (a later run that wrote no ledger of its own, such as an unmetered start, sits behind it), so its late+ * close never ends that record, however close in time the two started. `checkout` is the git toplevel a ledger records.*/export function endClosedRun(checkout: string, stateRoot: string): string | null {const read = readRunRecord(checkout);if (read.kind !== 'record' || read.record.state !== 'open') return null;- const ledgers = shipLedgers(stateRoot).filter(x => x.l.checkout === checkout);- const mine = ledgers.find(x => owns(ledgers, x.l)(read.record));- const opened = Date.parse(read.record.started_at);- const worked = mine && (opened - created(mine.l) <= PREFLIGHT_AFTER_START_MS- || [...(mine.l.notes ?? []), ...(mine.l.reservations ?? [])].some((x: { at?: string }) => Date.parse(String(x.at)) >= opened));- if (!mine?.l.closed_at || opened > Date.parse(mine.l.closed_at) || !worked) return null;const run = read.record.run;+ const mine = shipLedgers(stateRoot).find(x => x.l.checkout === checkout && x.l.ship_run === run && x.l.closed_at);+ if (!mine) return null;const done = changeRunRecord(checkout, 'close', run, { ended_by: 'gstack-ship-budget close' });return done.ok ? `RUN_ENDED: run=${run} state=finished ended_by=gstack-ship-budget close (its budget ledger ${path.basename(path.dirname(mine.file))} closed at ${mine.l.closed_at})` : null;}diff --git a/test/ship-budget.test.ts b/test/ship-budget.test.tsindex 10b4f9cd0..b92460157 100644--- a/test/ship-budget.test.ts+++ b/test/ship-budget.test.ts@@ -5,9 +5,11 @@import { afterEach, describe, expect, test } from 'bun:test';import * as fs from 'node:fs';import * as path from 'node:path';-import { spawnSync } from 'node:child_process';+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 } from './helpers/ship-budget-harness';+import { BUDGET_BIN, budgetHarness, type Harness, type Run } from './helpers/ship-budget-harness';const cal = loadCalibration();const K = unitConstants(cal, 'capy-tokens');@@ -600,3 +602,344 @@ describe('a new /ship on a reused record meters only itself (GST-4109)', () => {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');+ });+});diff --git a/test/ship-phase.test.ts b/test/ship-phase.test.tsindex 686631da5..f7223384e 100644--- a/test/ship-phase.test.ts+++ b/test/ship-phase.test.ts@@ -326,6 +326,26 @@ describe('the 100-minute stop', () => {expect(ok.status, ok.stdout + ok.stderr).toBe(0);expect(ok.stdout).not.toContain('past 100 minutes');});++ // Value: protects=gstack calls in a nested checkout or submodule under the run's checkout never count as the parent run's active time, while a+ // plain subdirectory of the checkout still does; fails_when=a lane working in a nested checkout keeps the parent checkout's parked run ticking+ // until it stops at 100 minutes, because the clock compared path prefixes (GSTA-892 ruled note at lib/ship-clock.ts:39);+ // why_new=the case above used a sibling directory; seam=the call log's cwd field; no_claim=a cwd deleted since its row, which falls back to the prefix+ test("a nested checkout's gstack calls do not keep the parent checkout's clock running; a subdirectory's do", () => {+ for (const [where, stops] of [['nested', false], ['src', true]] as const) {+ const b = box();+ start(b);+ backdate(b, 180, false);+ const dir = path.join(b.repo, where === 'nested' ? 'vendor/nested' : 'src');+ fs.mkdirSync(dir, { recursive: true });+ if (where === 'nested') expect(spawnSync('git', ['init', '-q'], { cwd: dir, timeout: 30_000 }).status).toBe(0);+ calls(b, 180, 150, b.repo);+ calls(b, 148, 22, dir);+ calls(b, 20, 0, b.repo);+ const r = bin(b, 'gstack-ship-budget', ['note', '--record', b.record, '--step', '16', '--reading', '2000', '--credits', '2']);+ expect([where, r.status, r.stdout.includes('past 100 minutes')]).toEqual([where, stops ? 3 : 0, stops]);+ }+ });});describe('calls per phase and calls= in the receipt', () => {diff --git a/test/ship-run-record.test.ts b/test/ship-run-record.test.tsindex 730b6efc7..d3acbff98 100644--- a/test/ship-run-record.test.ts+++ b/test/ship-run-record.test.ts@@ -452,4 +452,29 @@ describe('a finished run no longer blocks the next /ship, and abandon never hintexpect(next.status, next.stdout + next.stderr).toBe(0);expect(next.stdout).toMatch(/^SUPERSEDED: run \S+ on this record belongs to \/ship run r1, which passed preflight and is finished and stays as it was; /m);});++ // Value: protects=preflight binds the ledger its /ship started to that run id, and close ends only the record of the run its ledger is bound to,+ // so an earlier run's late close never ends a later unmetered run, even one that opened within 5 minutes; fails_when=endClosedRun takes the+ // earlier ledger as the later record's owner by timing (it started within 5 minutes, or noted after the record opened) and marks the live run+ // finished (GSTA-892 ruled note at lib/ship-run-live.ts:56); why_new=the late-close case above backdated the earlier ledger past the window;+ // seam=an unmetered start; no_claim=a ledger bound by an older gstack, which never ends a record (skill-end, stop or abandon do)+ test("preflight binds its run's ledger, and an earlier run's late close never ends a later run opened right after it", () => {+ const f = fx();+ const rec = startBudget(f, 'r1');+ expect(preflight(f, 'r1').status).toBe(0);+ const ledger = /ledger=(\S+)/.exec(fs.readFileSync(rec, 'utf8'))![1]!;+ expect(JSON.parse(fs.readFileSync(ledger, 'utf8')).ship_run).toBe('r1');+ fs.writeFileSync(recordFile(f), JSON.stringify({ ...record(f), state: 'abandoned' }) + '\n');+ f.advanceBase({ 'docs/a.md': 'a\n' });+ const bare = path.join(f.root, 'r2.md');+ fs.writeFileSync(bare, '# /ship record\n');+ expect(BUDGET(f, ['start', '--record', bare]).stdout).toContain('BUDGET: unmetered');+ expect(preflight(f, 'r2').status).toBe(0);+ expect(JSON.parse(fs.readFileSync(ledger, 'utf8')).ship_run).toBe('r1');+ expect(BUDGET(f, ['note', '--record', rec, '--step', '9', '--reading', '1500', '--credits', '1']).status).toBe(0);+ const late = BUDGET(f, ['close', '--record', rec, '--reading', '2000', '--credits', '2']);+ expect(late.status, late.stdout + late.stderr).toBe(0);+ expect(late.stdout).not.toContain('RUN_ENDED:');+ expect(record(f)).toMatchObject({ run: 'r2', state: 'open' });+ });});