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 stops counting idle time and earlier runs against a run's limits, and a finished run no longer blocks the next one (GST-4109) (#4877)
Garry Tan4b8c7005dc8c
diff --git a/bin/gstack-ship-run b/bin/gstack-ship-runindex 0a9990a55..8ecd3dd5b 100755--- a/bin/gstack-ship-run+++ b/bin/gstack-ship-run@@ -27,7 +27,8 @@ const HELP = `gstack-ship-run — this checkout's /ship run record (docs/ship-pomark:abandoned entry (skipped with a note when no PR body is reachable). Refused (SHIP_RUN_ABANDON_REFUSED, exit 3)while the run beat in the last 60 minutes, for another run's record, or once it ended; --by gstack is usage (2).A bare marker from an older gstack (state legacy) goes at any age; an unreadable record goes as --run unknown with- the --sha256 status printed. It completes in one call: never rerun it after RUN_ABANDONED+ the --sha256 status printed; such a record names no run, so no PR body entry is marked. A mark the PR refuses (it+ records no entry for that run) prints why and no rerun hint. It completes in one call: never rerun it after RUN_ABANDONEDskill-end --run <session id>what gstack-skill-end calls: marks the record finished (ended_by skill-end) when it names that runlive [--state-root <dir>]@@ -83,10 +84,13 @@ function main(argv: string[]): number {const listed = flag('--body') || flag('--pr') || !branch ? undefined : ghSpawnSync(['pr', 'list', '--head', branch, '--state', 'open', '--json', 'number', '--jq', '.[0].number // empty'], { cwd, encoding: 'utf8', timeout: 60_000 });const pr = flag('--pr') ?? listed?.stdout?.trim();const target = flag('--body') ? ['--body', flag('--body')!] : pr && /^[1-9]\d*$/.test(pr) ? ['--pr', pr, ...(flag('--repo') ? ['--repo', flag('--repo')!] : [])] : undefined;+ if (target && run === 'unknown') { process.stdout.write(`RUN_ABANDON_PR: skipped (an unreadable record names no run, so ${target[0] === '--pr' ? `PR #${target[1]}'s` : 'the'} body has no entry to mark); the record is abandoned, so nothing else is needed\n`); return EXIT.ok; }if (!target) { process.stdout.write(`RUN_ABANDON_PR: skipped (no open PR body reachable${branch ? ` for ${branch}` : ''}${listed?.status ? `: gh exit ${listed.status}` : ''}); the record is abandoned, so do not rerun abandon\n`); return EXIT.ok; }const mark = runScriptSync(path.join(BIN_DIR, 'gstack-ship-receipt'), ['abandoned', ...target, '--run', run, '--by', by, '--reason', reason], { cwd, encoding: 'utf8', timeout: 120_000 });process.stdout.write(mark.stdout ?? '');- if (mark.status !== 0) process.stdout.write(`RUN_ABANDON_PR: not recorded (${(mark.stderr ?? '').trim().split('\n')[0] || `gstack-ship-receipt abandoned exit ${mark.status}`}); the record is abandoned, so do not rerun abandon: add the entry with gstack-ship-receipt abandoned ${target.join(' ')} --run ${run} --by "<who>" --reason "<one line>"\n`);+ const why = (mark.stderr ?? '').trim().split('\n')[0] || `gstack-ship-receipt abandoned exit ${mark.status}`;+ if (mark.status === EXIT.refused && /records no entry for run/.test(why)) process.stdout.write(`RUN_ABANDON_PR: not recorded (${why}); the record is abandoned, so do not rerun abandon, and the PR body names no entry of this run, so no mark is needed\n`);+ else if (mark.status !== 0) process.stdout.write(`RUN_ABANDON_PR: not recorded (${why}); the record is abandoned, so do not rerun abandon: add the entry with gstack-ship-receipt abandoned ${target.join(' ')} --run ${run} --by "<who>" --reason "<one line>"\n`);return EXIT.ok;}diff --git a/changelog.d/fix-ship-budget-idle-clock-run-delta-finished-run-restart-gst4109.md b/changelog.d/fix-ship-budget-idle-clock-run-delta-finished-run-restart-gst4109.mdnew file mode 100644index 000000000..cf24a7a6a--- /dev/null+++ b/changelog.d/fix-ship-budget-idle-clock-run-delta-finished-run-restart-gst4109.md@@ -0,0 +1 @@+**`/gstack-ship` no longer stops or blocks because of time and tokens that belong to something else.** The 100-minute stop now counts active minutes: a stretch of more than 5 minutes with no gstack call (waiting on CI, a reviewer or a Captain's ruling) counts only its first 5 minutes, and only calls in the run's own checkout count, while a run that keeps calling gstack still stops at 100. A new `/gstack-ship` that reuses an earlier run's record now starts its own run instead of joining the earlier one, so the token cap and the clock count only this run's own use; `resume` still continues an earlier run and is still the only way past a budget stop, and `resume --meter capy` now needs `--reading` instead of counting the thread's whole counter. A run whose budget closed at its last step now marks its run record finished, and the next preflight ends one an older gstack left open, so a finished run no longer blocks the next `/gstack-ship` on the same checkout while a run still in progress keeps blocking. `gstack-ship-run abandon --run unknown` with an open PR no longer suggests a PR-body command that refuses the same way, and a PR-body mark that the PR refuses prints why without a rerun hint.diff --git a/docs/ship-budget.md b/docs/ship-budget.mdindex 55a9b1f09..c36c29bdf 100644--- a/docs/ship-budget.md+++ b/docs/ship-budget.md@@ -81,14 +81,18 @@ A successor thread's readings open a new epoch for credits as well as tokens### The 100-minute stopship/DRIVER.md stops a run past 100 minutes. Measured conductors ran past it in 10 of 12 runs while it was a-line of prose (handoffs/ship-conductor-cost-2026-11-16), so it is now code (`lib/ship-clock.ts`). In observe mode-the first `note`, or `gstack-ship-phase run --record`, past 100 minutes from the ledger's start prints-- STOP: past 100 minutes (<m> min since <start>) head=<sha12> rounds=<n> calls=<n> next=<next act> state=<ledger dir>/stop.json+line of prose (handoffs/ship-conductor-cost-2026-11-16), so it is now code (`lib/ship-clock.ts`). The clock counts+active 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+stops 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++ STOP: past 100 minutes (<m> active min since <start>, <p> min parked) head=<sha12> rounds=<n> calls=<n> next=<next act> state=<ledger dir>/stop.jsonRECOVER: hand <stop.json> to the next session; it runs gstack-ship-budget resume --record <rec> (the clock restarts), then reruns the phase that stoppedGSTACK_RESULT: skill=ship status=incomplete run=<ledger dir>-and exits 3. `stop.json` holds the head, the review passes noted so far (`rounds`: Step 9 notes that dispatched+and exits 3. `stop.json` holds the wall, active and parked minutes, the head, the review passes noted so far (`rounds`: Step 9 notes that dispatchedreaders), the next act (the last line under the record's Next steps heading) and the run's calls, so the stop is aclean handoff. Until `resume` the ledger stays stopped: every `note` and every `gstack-ship-phase run --record`prints the stop again and runs nothing. `resume` prints `CLOCK: restarted at <iso>` and the next 100 minutes count@@ -308,7 +312,20 @@ gstack-ship-budget resume --record <record> --token-cap <n> --approved-by Garry```Every command takes `--run` or `--record`; runs are never found by branch or directory, and a-/gstack-ship without `--resume` or `--continue` always starts a new run. The ledger and record are+/gstack-ship without `--resume` or `--continue` always starts a new run. `start` on a record whose open+ledger has already gone past its start (a note, a check or a handoff), whose /gstack-ship passed preflight and+ended, or that started over 5 minutes ago mints a new run, marks the earlier ledger `superseded_by` it (so it+stops 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+epoch'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 machinechange `resume --run <id>` restores both. A corrupt ledger@@ -325,7 +342,7 @@ observe ledger on the same record:gstack-ship-budget start --record <record> --mode observe --reading <cost.tokens>```-`start` reuses a record's ledger only while it is open, so on a closed one it mints a new run id+`start` reuses a record's ledger only while it is open and has not gone past its start, so on a closed one it mints a new run idand ledger for the same record and prints its `BUDGET_RUN:` line. The new ledger meters from its ownfirst reading: spend under the closed ledger stays in that ledger and is not carried into the newone, so add the two when you report what the run cost. On Capy, `--reading` is the thread'sdiff --git a/docs/ship-policy.md b/docs/ship-policy.mdindex 34b285e91..a5b9918d0 100644--- a/docs/ship-policy.md+++ b/docs/ship-policy.md@@ -1823,7 +1823,8 @@ full preflight, gate dispositions, lane exceptions and rulingswithout `--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 any-outcome, and `gstack-ship-run abandon` ends a run that stopped working, never+outcome, 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, 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/docs/troubleshooting.md b/docs/troubleshooting.mdindex eb0e4bf87..d9559b6c8 100644--- a/docs/troubleshooting.md+++ b/docs/troubleshooting.md@@ -2425,7 +2425,9 @@ owner's call: run the printed `RECOVER:` line; its resume needs### `gstack-ship-budget: ... (BUDGET_READING_MISSING)`**Meaning.** The run's meter is the agent's own Capy jam counter, a cap is set, and the command got no-`--reading`. Exit 2. No gstack binary can call Capy's API, so the agent reads it.+`--reading`. Exit 2. No gstack binary can call Capy's API, so the agent reads it. `resume --meter capy`+that moves a run onto the Capy counter from another meter refuses the same way, cap or not, because without the+new epoch's baseline the thread's whole counter would count as the run's use (GST-4109).**Fix.** In the execute program that runs the command, read`(await tools.thread.get({ thread_id: "<your own jam id>" })).cost.tokens` and pass it as `--reading <n>`.diff --git a/lib/ship-budget-cli.ts b/lib/ship-budget-cli.tsindex e92f9ea53..79f0cb845 100644--- a/lib/ship-budget-cli.ts+++ b/lib/ship-budget-cli.ts@@ -12,7 +12,9 @@ import * as fs from 'node:fs';import * as os from 'node:os';import * as path from 'node:path';import { resultLine } from './result-codes';-import { thisRunOwner } from './ship-run-record';+import { readRunRecord, thisRunOwner } from './ship-run-record';+import { endClosedRun } from './ship-run-live';+import { resolveStateRoot } from './state-root';import { spawnSync } from './spawn-sync';import {BudgetError, DEFAULT_TAIL, SUBAGENT_DEFAULT_CAP, DELEGATE_SEGMENT_CALL, DELEGATE_START_CALL, MAX_CHAIN_DEPTH, METER_CONTRACTS, SEGMENTS, SHIP_STEPS,@@ -23,7 +25,7 @@ import {} from './ship-budget';import { callLogFile, countLoggedCalls, loggedCallsLine, readCallLog } from './ship-call-log';import { callsLine, countCalls } from './ship-calls';-import { callsSince, timeStop } from './ship-clock';+import { callsSince, 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>;@@ -264,10 +266,21 @@ export function cmdStart(argv: string[], ctx: Ctx): Outcome {const delegate = str(o, 'delegate') ?? 'auto';if (delegate !== 'auto' && delegate !== 'never') throw usageError(`--delegate '${delegate}' is not auto or never`);const existing = parseRecordBlock(record);- if (existing?.ledger && fs.existsSync(existing.ledger) && !readLedger(existing.ledger).closed_at) {- return mutateLedger(existing.ledger, ctx.env, l => {+ 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' })], exit: l.stopped ? 3 : 0 };+ 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 meter = pickMeter(o);@@ -275,6 +288,7 @@ export function cmdStart(argv: string[], ctx: Ctx): Outcome {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 ${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);@@ -300,8 +314,44 @@ export function cmdStart(argv: string[], ctx: Ctx): Outcome {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: [`BUDGET_RUN: id=${run} ledger=${l.file}`, ...note, ...out.stdout], exit: out.exit });+ return labelScope(l, { stdout: [...superseded, `BUDGET_RUN: id=${run} ledger=${l.file}`, ...note, ...out.stdout], exit: out.exit });+}++/**+ * Why an open, unstopped ledger on the record belongs to an earlier /ship (GST-4109), or undefined for a rerun of the same start: it+ * went past its start (a note, a completed or settled step, a check's second reservation or a handoff), the checkout's /ship run+ * record opened after it started and has ended (its /ship passed preflight and finished, stopped or was abandoned; an open record is+ * 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.+ */+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.+ */+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);+};+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 */ }+ const t = tally(trial);+ return (trial.cap !== null && t.used + t.unknown > trial.cap) || (trial.mode === 'observe' && runClock(trial, env).active > TIME_LIMIT_MIN);+}+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);+ 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;}/**@@ -357,7 +407,9 @@ export function cmdSettle(argv: string[], ctx: Ctx, release = false): Outcome {export function cmdClose(argv: string[], ctx: Ctx): Outcome {const o = parseArgs(argv, ['run', 'record', 'reading', 'credits', 'approved-by', 'words']);- return mutateLedger(ledgerFileFor({ run: str(o, 'run'), record: str(o, 'record') }, ctx.env), ctx.env, l => {+ let checkout: string | undefined;+ const out = mutateLedger(ledgerFileFor({ run: str(o, 'run'), record: str(o, 'record') }, ctx.env), ctx.env, l => {+ checkout = l.checkout;readMeter(l, o, false);for (const r of l.reservations) if (r.kind === 'step' && r.state === 'open') settleIn(l, r);if (freshReading(l, o)) measureSettled(l);@@ -385,9 +437,11 @@ export function cmdClose(argv: string[], ctx: Ctx): Outcome {return { stdout: lines, exit: 3 };}l.closed_at = new Date().toISOString();- if (l.marker) { try { fs.unlinkSync(l.marker); } catch {} }+ if (l.marker && !l.superseded_by) { try { fs.unlinkSync(l.marker); } catch {} }return { stdout: lines, exit: 0 };});+ const ended = out.exit === 0 && checkout ? endClosedRun(checkout, resolveStateRoot(ctx.env)) : null;+ return ended ? { ...out, stdout: [...out.stdout, ended] } : out;}const noteText = (n: Note) => `${n.step}${n.label ? `:${n.label}` : ''} used=${n.used}${n.credits === undefined ? '' : ` credits=${n.credits}`}${n.calls === undefined ? '' : ` calls=${n.calls}`}`@@ -472,6 +526,7 @@ export function cmdResume(argv: string[], ctx: Ctx): Outcome {const meter = pickMeter(o) ?? l.meter.contract.meter;const successor = source !== undefined && source !== l.meter.source;if (successor && meter === 'capy' && str(o, 'reading') === undefined) throw budgetError('BUDGET_READING_MISSING', `resume --meter-source ${source}: a successor's counter needs --reading <its cost.tokens>, the new epoch's baseline`);+ if (meter === 'capy' && meter !== l.meter.contract.meter && str(o, 'reading') === undefined) throw budgetError('BUDGET_READING_MISSING', `resume --meter capy: run ${l.run} moves from meter=${l.meter.contract.meter} to capy, and the new epoch's baseline is --reading <cost.tokens>; without it the thread's whole counter would count as this run's use`);if (successor && l.credits && str(o, 'credits') === undefined) throw budgetError('BUDGET_READING_MISSING', `resume --meter-source ${source}: run ${l.run} meters credits; pass --credits <its cost.credits>, the new epoch's baseline`);const open = successor ? l.handoffs.filter(h => !h.reconciled_at) : [];if (open.length) throw budgetError('BUDGET_READING_REJECTED', `resume --meter-source ${source}: handoff ${open.map(h => `${h.sha} (steps ${h.from}-${h.to})`).join(', ')} still runs on ${l.meter.source ?? 'the previous'} counter, which the new epoch cannot see; wait for its RETURN, reconcile it with a reading of that counter (${open.map(h => `gstack-ship-budget reconcile --run ${l.run} --return ${h.return_file} --reading <its cost.tokens>`).join('; ')}), then resume. A reconcile without --return writes the child off as interrupted, and its later spend is never charged`);@@ -496,6 +551,7 @@ export function cmdResume(argv: string[], ctx: Ctx): Outcome {}const was = l.stopped;delete l.stopped;+ 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' })];diff --git a/lib/ship-budget.ts b/lib/ship-budget.tsindex be4a734cb..dfa610cf3 100644--- a/lib/ship-budget.ts+++ b/lib/ship-budget.ts@@ -108,6 +108,8 @@ export interface Ledger {checkout?: string; owner?: RunOwner;/** Where the 100-minute clock starts (lib/ship-clock.ts): created_at, or the resume after a time stop. */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;}/** A refusal: exit 2 for usage and validation (stderr), exit 3 for a stop. */@@ -370,7 +372,7 @@ function writePrivate(file: string, text: string): void {export function writeLedger(ledger: Ledger, env: NodeJS.ProcessEnv = process.env): void {writePrivate(ledger.file, JSON.stringify(ledger, null, 2) + '\n');- if (ledger.record) writeRecordBlock(ledger.record, ledger);+ if (ledger.record && !ledger.superseded_by) writeRecordBlock(ledger.record, ledger);mirrorRun(ledger, env);}diff --git a/lib/ship-call-log.ts b/lib/ship-call-log.tsindex 673dee5e0..ec365f8ea 100644--- a/lib/ship-call-log.ts+++ b/lib/ship-call-log.ts@@ -18,7 +18,7 @@ import * as fs from 'node:fs';import * as path from 'node:path';import { resolveStateRoot } from './state-root';-export interface CallRow { v: 1; bin: string; sub: string; step?: string; reading?: number; credits?: number; start: string; ms: number; exit: number }+export interface CallRow { v: 1; bin: string; sub: string; step?: string; reading?: number; credits?: number; start: string; ms: number; exit: number; cwd?: string }export interface LoggedCalls {calls: number; phase: number; pass: number; section: number; other: number; keepaliveEst: number;passOverhead: number[]; idleGaps: number; maxGapS: number; first: string | null; last: string | null;@@ -29,7 +29,7 @@ let pending: { bin: string; sub: string; started: number } | null = null;/** This process's own row as it will be written at exit (null when it writes none), for a count taken before it exits (lib/ship-clock.ts). */export function pendingRow(): CallRow | null {- return pending && { v: 1, bin: pending.bin, sub: pending.sub, start: new Date(pending.started).toISOString(), ms: Date.now() - pending.started, exit: 0 };+ return pending && { v: 1, bin: pending.bin, sub: pending.sub, start: new Date(pending.started).toISOString(), ms: Date.now() - pending.started, exit: 0, cwd: process.cwd() };}const ROTATE_BYTES = 8 * 1024 * 1024;const JOIN_MS = 5_000;@@ -50,7 +50,7 @@ export function logShipCall(bin: string, argv: string[] = process.argv.slice(2))pending = { bin, sub: argv[0] && !argv[0].startsWith('-') ? argv[0] : '', started };process.on('exit', code => {try {- const row: CallRow = { v: 1, bin, sub: argv[0] && !argv[0].startsWith('-') ? argv[0] : '', start: new Date(started).toISOString(), ms: Date.now() - started, exit: code };+ const row: CallRow = { v: 1, bin, sub: argv[0] && !argv[0].startsWith('-') ? argv[0] : '', start: new Date(started).toISOString(), ms: Date.now() - started, exit: code, cwd: process.cwd() };const step = flag('step'), reading = num('reading'), credits = num('credits');if (step !== undefined) row.step = step;if (reading !== undefined) row.reading = reading;diff --git a/lib/ship-clock.ts b/lib/ship-clock.tsindex 7a7589955..7055928c1 100644--- a/lib/ship-clock.ts+++ b/lib/ship-clock.ts@@ -1,10 +1,14 @@/*** ship-clock — a driven /ship's 100-minute stop and its call count, in code instead of prose (ship/DRIVER.md).* Measured conductors made 121-308 calls against the driver's 9 to 12, and 10 of 12 ran past its 100-minute stop- * (handoffs/ship-conductor-cost-2026-11-16), so the limits now print. An observe-mode run measures its time from+ * (handoffs/ship-conductor-cost-2026-11-16), so the limits now print. An observe-mode run measures its active time from* the ledger's start, or from the resume that followed a time stop; the first `gstack-ship-budget note` or- * `gstack-ship-phase run` past 100 minutes stops the run and writes its state (head, review passes, next act) to+ * `gstack-ship-phase run` past 100 active minutes stops the run and writes its state (head, review passes, next act) to* <ledger dir>/stop.json, so the next session starts from that file and the record, not from memory.+ * Active time (GST-4109) is wall time minus parked time: any stretch over PARKED_AFTER_MS with no gstack call in the call+ * log is the lane parked on CI, a Captain or a ruling, so only its first PARKED_AFTER_MS count. A run that keeps calling+ * gstack (a runaway pass or phase loop) never parks, so it still stops at 100 minutes; with no call log (off Capy) the+ * clock is wall time.* Calls come from the call log (lib/ship-call-log.ts): the calls that ran a gstack command plus its keep-alive* estimate; quick calls that run no gstack command are not in it.*/@@ -17,8 +21,33 @@ import { callLogFile, countLoggedCalls, pendingRow, readCallLog } from './ship-cexport const TIME_LIMIT_MIN = 100;export const STOP_FILE = 'stop.json';+/** The call log's idle line (lib/ship-call-log.ts, a gap that outlives the prompt cache): a longer stretch with no gstack call is parked past it. */+export const PARKED_AFTER_MS = 300_000;+export const clockFrom = (l: Pick<Ledger, 'created_at' | 'clock_from'>) => l.clock_from ?? l.created_at;-export const elapsedMin = (l: Pick<Ledger, 'created_at' | 'clock_from'>, now = Date.now()) => (now - Date.parse(clockFrom(l))) / 60_000;++/**+ * 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.+ */+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]);+ 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]) {+ parked += Math.max(0, s - cursor - PARKED_AFTER_MS);+ cursor = Math.max(cursor, e);+ }+ return { active: (wall - parked) / 60_000, wall: wall / 60_000, parked: parked / 60_000, source: 'log' };+}/*** Calls whose rows start after `since` (and at or before `until`): the log's calls plus its keep-alive estimate.@@ -59,12 +88,13 @@ export function nextAct(record: string | undefined): string | null {const oneLine = (s: string) => s.replace(/[\x00-\x1f\x7f]+/g, ' ').slice(0, 300);/**- * The time stop: null while an observe-mode run is within 100 minutes (or already stopped or closed); past them it+ * The time stop: null while an observe-mode run is within 100 active minutes (runClock; or already stopped or closed); past them it* marks the ledger stopped, writes stop.json and returns the STOP block. The caller persists the ledger (mutateLedger).*/export function timeStop(l: Ledger, cwd: string, step: string, env: NodeJS.ProcessEnv, now = Date.now(), fallbackNext = `resume, then continue after Step ${step}`): string[] | null {if (l.mode !== 'observe' || l.stopped || l.closed_at) return null;- const min = elapsedMin(l, now);+ const clock = runClock(l, env, now);+ const min = clock.active;if (!(min > TIME_LIMIT_MIN)) return null;const at = new Date(now).toISOString();const g = spawnSync('git', ['rev-parse', 'HEAD'], { cwd, encoding: 'utf8', timeout: 15_000 });@@ -74,12 +104,12 @@ export function timeStop(l: Ledger, cwd: string, step: string, env: NodeJS.Proceconst calls = callsSince(env, l.created_at, at, true);const file = path.join(l.dir, STOP_FILE);const state = { schema_version: 1, kind: 'gstack-ship-stop', reason: 'past_100_minutes', run: l.run, record: l.record ?? null, at,- clock_from: clockFrom(l), elapsed_min: Math.floor(min), step, head, rounds, next, calls };+ clock_from: clockFrom(l), elapsed_min: Math.floor(clock.wall), active_min: Math.floor(min), parked_min: Math.floor(clock.parked), clock_source: clock.source, step, head, rounds, next, calls };fs.mkdirSync(l.dir, { recursive: true, mode: 0o700 });fs.writeFileSync(file, JSON.stringify(state, null, 2) + '\n', { mode: 0o600 });l.stopped = { at, reason: 'past_100_minutes', step, next };return [- `STOP: past 100 minutes (${Math.floor(min)} min since ${clockFrom(l)}) head=${head.slice(0, 12)} rounds=${rounds} calls=${calls ?? 'unknown'} next=${oneLine(next)} state=${file}`,+ `STOP: past 100 minutes (${Math.floor(min)} active min since ${clockFrom(l)}, ${Math.floor(clock.parked)} min parked) head=${head.slice(0, 12)} rounds=${rounds} calls=${calls ?? 'unknown'} next=${oneLine(next)} state=${file}`,`RECOVER: hand ${file} to the next session; it runs gstack-ship-budget resume --record ${l.record ?? '<record>'} (the clock restarts), then reruns the phase that stopped`,`GSTACK_RESULT: skill=ship status=incomplete run=${l.dir}`,];diff --git a/lib/ship-preflight.ts b/lib/ship-preflight.tsindex dc4893c00..6805ffe21 100644--- a/lib/ship-preflight.ts+++ b/lib/ship-preflight.ts@@ -18,6 +18,8 @@ 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 { 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';export const PREFLIGHT_HELP = `gstack-ship-preflight — /ship Steps 1-3 and Step 5's pregate and lanes in one call (ship/SKILL.md)@@ -63,9 +65,12 @@ const RUN_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;* or abandoned record of another run is replaced once Steps 1-3 pass; a preflight with no --run stops on a stopped one, which it* could not replace. A record that already names this --run stops too: a run id is* one /ship run (gstack-evals#406). A --run is still opened on the checkout's lease, before the fetch, for the upgrade guard alone, and- * one that cannot be is a STOP, never an unprotected run.+ * one that cannot be is a STOP, never an unprotected run. An open record whose own budget ledger already closed is a finished run, so it+ * is ended first (endClosedRun, GST-4109); one whose ledger is still open keeps blocking.*/function shipRunClear(cwd: string, base: string, run: string | undefined, r: Report): boolean {+ const ended = endClosedRun(git(cwd, ['rev-parse', '--show-toplevel']).stdout.trim(), resolveStateRoot(process.env));+ if (ended) r.add(ended);const read = readRunRecord(cwd);const open = openRun(read);if (open && (open.state !== 'stopped' || !run)) {diff --git a/lib/ship-run-live.ts b/lib/ship-run-live.tsindex e1eee6699..f286bd576 100644--- a/lib/ship-run-live.ts+++ b/lib/ship-run-live.ts@@ -8,13 +8,17 @@* run's record nor a later run started on the same checkout releases it (for a review start, the record naming the run its claim* 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.*/import * as fs from 'node:fs';import * as path from 'node:path';-import { ownerGone, readRunRecord, type RunRecord } from './ship-run-record';+import { changeRunRecord, ownerGone, readRunRecord, type RunRecord } from './ship-run-record';export const LEDGER_HOLD_MS = 360 * 60_000;export const REVIEW_START_HOLD_MS = 120 * 60_000;+const PREFLIGHT_AFTER_START_MS = 5 * 60_000;const ENDED = new Set(['finished', 'abandoned']);const recordEnded = (checkout: unknown, ours: (r: RunRecord) => boolean) => {@@ -27,22 +31,48 @@ const json = (file: string): Record<string, any> | null => { try { const v = JSOconst dirs = (dir: string) => { try { return fs.readdirSync(dir, { withFileTypes: true }).filter(d => d.isDirectory()).map(d => path.join(dir, d.name)); } catch { return []; } };const files = (dir: string, ext: string) => { try { return fs.readdirSync(dir).filter(n => n.endsWith(ext)).map(n => path.join(dir, n)); } catch { return []; } };+type Ledgers = Array<{ file: string; l: Record<string, any> }>;+const shipLedgers = (stateRoot: string): Ledgers => dirs(path.join(stateRoot, 'ship-runs')).map(d => ({ file: path.join(d, 'budget.json'), l: json(path.join(d, 'budget.json')) }))+ .filter((x): x is Ledgers[number] => x.l?.kind === 'gstack-ship-budget');+const created = (l: Record<string, any>) => Date.parse(String(l.created_at));+/** Whether a run record is this ledger's: the ledger is the one newest ledger for its checkout created at or before the record opened. */+const owns = (ledgers: Ledgers, l: Record<string, any>) => (r: RunRecord) => {+ const before = ledgers.filter(x => x.l.checkout === l.checkout && created(x.l) <= Date.parse(r.started_at)).map(x => created(x.l));+ const newest = Math.max(...before);+ return created(l) === newest && before.filter(t => t === newest).length === 1;+};++/**+ * 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.+ */+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 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;+}+/** The first run that still holds upgrades, as "<kind> run <id> (<file>)", or undefined; ended lists what no longer holds and why. */export function liveRun(stateRoot: string, now = Date.now()): { live?: string; ended: string[] } {const ended: string[] = [];- const ledgers = dirs(path.join(stateRoot, 'ship-runs')).map(d => ({ file: path.join(d, 'budget.json'), l: json(path.join(d, 'budget.json')) })).filter(x => x.l?.kind === 'gstack-ship-budget');- const created = (l: Record<string, any>) => Date.parse(String(l.created_at));- const owns = (l: Record<string, any>) => (r: RunRecord) => {- const before = ledgers.filter(x => x.l!.checkout === l.checkout && created(x.l!) <= Date.parse(r.started_at)).map(x => created(x.l!));- const newest = Math.max(...before);- return created(l) === newest && before.filter(t => t === newest).length === 1;- };+ const ledgers = shipLedgers(stateRoot);for (const { file, l } of ledgers) {if (!fresh(file, LEDGER_HOLD_MS, now)) continue;- if (!l || l.closed_at) continue;+ if (!l || l.closed_at || l.superseded_by) continue;const id = path.basename(path.dirname(file));if (ownerGone(l.owner)) { ended.push(`/ship run ${id}: its owner process ${l.owner.pid} is gone`); continue; }- if (recordEnded(l.checkout, owns(l))) { ended.push(`/ship run ${id}: the run record in ${l.checkout} has ended`); continue; }+ if (recordEnded(l.checkout, owns(ledgers, l))) { ended.push(`/ship run ${id}: the run record in ${l.checkout} has ended`); continue; }return { live: `/ship run ${id} (${file})`, ended };}for (const project of dirs(path.join(stateRoot, 'projects'))) {diff --git a/lib/ship-run-record.ts b/lib/ship-run-record.tsindex 137d33d58..9ecfc78ce 100644--- a/lib/ship-run-record.ts+++ b/lib/ship-run-record.ts@@ -2,7 +2,8 @@* ship-run-record — the /ship run record (GST-3260, docs/ship-policy.md#what-ends-a-run). One JSON file in the checkout's git dir* (git rev-parse --git-path gstack-ship-run, one per worktree) replaces the bare run marker. Preflight opens it, every /ship command* that names its run beats it, gstack-ship-receipt stop marks it stopped and claim records the grant it spends, finish removes it,- * gstack-skill-end marks it finished, and gstack-ship-run abandon ends a run that stopped working. Liveness never rests on a timer:+ * gstack-skill-end marks it finished, the run's own budget close marks an open run finished (close, GST-4109: lib/ship-run-live.ts+ * endClosedRun), and gstack-ship-run abandon ends a run that stopped working. Liveness never rests on a timer:* a run stays open until one of those commands ends it. A bare-text marker from an older gstack reads as `legacy` and a file that is* neither as `unreadable`; every guard treats both as open (fails closed). Each change runs under the gate lock as a compare-and-swap on* run and state (RUN_TRANSITIONS). The record guards against mistakes; it is not proof of who the owner is.@@ -28,7 +29,7 @@ export type RunRead =| { kind: 'record'; file: string; record: RunRecord }| { kind: 'legacy'; file: string; run: string }| { kind: 'unreadable'; file: string; why: string; sha256?: string };-export type RunCommand = 'preflight' | 'beat' | 'stop' | 'claim' | 'skill-end' | 'finish' | 'abandon';+export type RunCommand = 'preflight' | 'beat' | 'stop' | 'claim' | 'skill-end' | 'close' | 'finish' | 'abandon';type From = RunState | 'none' | 'legacy' | 'unreadable';export const RUN_ID = /^[A-Za-z0-9][\w.:-]{0,127}$/;@@ -94,6 +95,7 @@ export const RUN_TRANSITIONS: Readonly<Record<RunCommand, { from: readonly From[stop: { from: ['open', 'stopped', 'legacy'], to: 'stopped' },claim: { from: ['open', 'stopped', 'legacy'], to: 'open' },'skill-end': { from: ['open', 'stopped', 'legacy'], to: 'finished' },+ close: { from: ['open'], to: 'finished' },finish: { from: ['open', 'stopped', 'legacy'], to: 'removed' },abandon: { from: ['open', 'stopped', 'legacy', 'unreadable'], to: 'abandoned' },};diff --git a/test/ship-budget.test.ts b/test/ship-budget.test.tsindex dd80f1145..10b4f9cd0 100644--- a/test/ship-budget.test.ts+++ b/test/ship-budget.test.ts@@ -458,3 +458,145 @@ describe('meter epochs', () => {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);+ });+});diff --git a/test/ship-phase.test.ts b/test/ship-phase.test.tsindex 499f998b1..686631da5 100644--- a/test/ship-phase.test.ts+++ b/test/ship-phase.test.ts@@ -47,10 +47,19 @@ const bin = (b: Box, name: string, args: string[], extra: NodeJS.ProcessEnv = {}const phase = (b: Box, args: string[], cmds: string[], extra: NodeJS.ProcessEnv = {}) =>bin(b, 'gstack-ship-phase', ['run', '--dir', path.join(b.root, 'run'), ...args, '--', ...cmds], extra);const ledgerOf = (b: Box) => /ledger=(\S+)/.exec(fs.readFileSync(b.record, 'utf8'))![1]!;-const backdate = (b: Box, minutes: number) => {+/** Appends a gstack call every 2 minutes from `fromMin` to `toMin` minutes ago to the box's call log, as a run that keeps working writes. */+const calls = (b: Box, fromMin: number, toMin: number, cwd?: string) => {+ const rows: string[] = [];+ for (let m = fromMin; m >= toMin; m -= 2) rows.push(JSON.stringify({ v: 1, bin: 'gstack-ship-phase', sub: 'run', start: new Date(Date.now() - m * 60_000).toISOString(), ms: 1000, exit: 0, ...(cwd ? { cwd } : {}) }));+ fs.mkdirSync(b.state, { recursive: true });+ fs.appendFileSync(path.join(b.state, 'ship-calls.jsonl'), rows.join('\n') + '\n');+};+/** Moves the run's start back `minutes`; an active run (the default) made a gstack call every 2 minutes since. */+const backdate = (b: Box, minutes: number, active = true) => {const l = JSON.parse(fs.readFileSync(ledgerOf(b), 'utf8'));l.created_at = new Date(Date.now() - minutes * 60_000).toISOString();fs.writeFileSync(ledgerOf(b), JSON.stringify(l, null, 2));+ if (active) calls(b, minutes, 0);};const start = (b: Box, mode: 'observe' | 'admit' = 'observe') => {const r = bin(b, 'gstack-ship-budget', ['start', '--record', b.record, ...(mode === 'observe' ? ['--mode', 'observe'] : []), '--reading', '1000', '--credits', '1']);@@ -218,7 +227,7 @@ describe('the 100-minute stop', () => {expect(lines[0]).toMatch(/^NOTE: 6 used=2000 credits=2/);const head = spawnSync('git', ['rev-parse', 'HEAD'], { cwd: b.repo, encoding: 'utf8', timeout: 30_000 }).stdout.trim();const dir = path.dirname(ledgerOf(b));- expect(lines[1]).toMatch(new RegExp(`^STOP: past 100 minutes \\(10[01] min since \\S+\\) head=${head.slice(0, 12)} rounds=0 calls=\\d+ next=Phase 3: audits and review state=${dir}/stop\\.json$`));+ expect(lines[1]).toMatch(new RegExp(`^STOP: past 100 minutes \\(10[01] active min since \\S+, 0 min parked\\) head=${head.slice(0, 12)} rounds=0 calls=\\d+ next=Phase 3: audits and review state=${dir}/stop\\.json$`));expect(lines.at(-1)).toBe(`GSTACK_RESULT: skill=ship status=incomplete run=${dir}`);const state = JSON.parse(fs.readFileSync(path.join(dir, 'stop.json'), 'utf8'));expect(state).toMatchObject({ kind: 'gstack-ship-stop', reason: 'past_100_minutes', head, rounds: 0, next: 'Phase 3: audits and review', step: '6', record: b.record });@@ -244,7 +253,7 @@ describe('the 100-minute stop', () => {const marker = path.join(b.root, 'phase-ran');const late = phase(b, ['--phase', '5', '--record', b.record], [`touch ${marker}`]);expect(late.status).toBe(3);- expect(late.stdout).toMatch(/^STOP: past 100 minutes \(1[12]\d min since /);+ expect(late.stdout).toMatch(/^STOP: past 100 minutes \(1[12]\d active min since /);expect(late.stdout).toContain('next=Phase 3: audits and review');expect(fs.existsSync(marker)).toBe(false);const admit = box();@@ -253,6 +262,70 @@ describe('the 100-minute stop', () => {const note = bin(admit, 'gstack-ship-budget', ['note', '--record', admit.record, '--step', '6', '--reading', '2000', '--credits', '2']);expect(note.stdout).not.toContain('past 100 minutes');});++ // Value: protects=the 100-minute clock counts active time: a lane parked on CI or a Captain ruling (no gstack call for over 5 minutes)+ // does not trip it, while a run that keeps calling gstack past 100 minutes still stops, and with no call log the clock is wall time;+ // fails_when=a run 3 hours old with 50 active minutes stops mid-run (GSKI-1 #12, HARN-1 #7), a runaway pass loop with no idle gap runs+ // on, or a host with no call log never stops; why_new=the stop was only driven with created_at backdated; seam=the call log;+ // no_claim=work that runs no gstack command, which the call log cannot see+ test('parked stretches do not count toward 100 minutes; a busy run and a run with no call log still stop', () => {+ const parked = box();+ start(parked);+ backdate(parked, 180, false);+ calls(parked, 180, 150);+ calls(parked, 20, 0);+ const ok = bin(parked, 'gstack-ship-budget', ['note', '--record', parked.record, '--step', '16', '--reading', '2000', '--credits', '2']);+ expect(ok.status, ok.stdout + ok.stderr).toBe(0);+ expect(ok.stdout).not.toContain('past 100 minutes');+ const busy = box();+ start(busy);+ backdate(busy, 180, false);+ calls(busy, 180, 150);+ calls(busy, 110, 0);+ const late = bin(busy, 'gstack-ship-budget', ['note', '--record', busy.record, '--step', '16', '--reading', '2000', '--credits', '2']);+ expect(late.status).toBe(3);+ expect(late.stdout).toMatch(/^STOP: past 100 minutes \(1[34]\d active min since \S+, 3\d min parked\) /m);+ const state = JSON.parse(fs.readFileSync(path.join(path.dirname(ledgerOf(busy)), 'stop.json'), 'utf8'));+ expect(state).toMatchObject({ clock_source: 'log', elapsed_min: 180 });+ const wall = box();+ start(wall);+ backdate(wall, 101, false);+ fs.rmSync(path.join(wall.state, 'ship-calls.jsonl'), { force: true });+ const plain = bin(wall, 'gstack-ship-budget', ['note', '--record', wall.record, '--step', '6', '--reading', '2000', '--credits', '2'], { GSTACK_CAPY: '' });+ expect(plain.status).toBe(3);+ expect(plain.stdout).toMatch(/^STOP: past 100 minutes \(10[01] active min since \S+, 0 min parked\) /m);+ });++ // Value: protects=a start on a run past 100 active minutes that no note stopped yet records the stop and re-attaches instead of+ // handing out a fresh clock; fails_when=a rerun of start supersedes a run past its time limit (targeted money reader, ship-1-p4);+ // why_new=the stop was only driven through note; seam=the ledger's created_at and the call log; no_claim=admit mode+ test('a start on a run past 100 active minutes records the time stop instead of opening a new run', async () => {+ const { changeRunRecord } = await import('../lib/ship-run-record');+ const b = box();+ start(b);+ expect(changeRunRecord(b.repo, 'preflight', 'r1').ok).toBe(true);+ backdate(b, 110);+ const again = bin(b, 'gstack-ship-budget', ['start', '--record', b.record, '--mode', 'observe', '--reading', '2000', '--credits', '2']);+ expect(again.status, again.stdout + again.stderr).toBe(3);+ expect(again.stdout).not.toContain('SUPERSEDED:');+ expect(again.stdout).toMatch(/^STOP: past 100 minutes /m);+ expect(JSON.parse(fs.readFileSync(ledgerOf(b), 'utf8')).stopped?.reason).toBe('past_100_minutes');+ });++ // Value: protects=gstack calls another checkout makes on the same state root never count as this run's active time; fails_when=a+ // parked lane stops at 100 minutes because a sibling lane on the same machine kept calling gstack (outside-voice, ship-1-p2);+ // why_new=the case above wrote rows with no cwd; seam=the call log's cwd field; no_claim=two runs in one checkout+ test("another checkout's gstack calls do not keep a parked run's clock running", () => {+ const b = box();+ start(b);+ backdate(b, 180, false);+ calls(b, 180, 150, b.repo);+ calls(b, 148, 22, path.join(b.root, 'elsewhere'));+ calls(b, 20, 0, b.repo);+ const ok = bin(b, 'gstack-ship-budget', ['note', '--record', b.record, '--step', '16', '--reading', '2000', '--credits', '2']);+ expect(ok.status, ok.stdout + ok.stderr).toBe(0);+ expect(ok.stdout).not.toContain('past 100 minutes');+ });});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 ed68fb805..730b6efc7 100644--- a/test/ship-run-record.test.ts+++ b/test/ship-run-record.test.ts@@ -336,3 +336,120 @@ describe('a stop before any PR fails when nothing records it (#4826 review)', ()expect(record(f)).toMatchObject({ run: 'rx', state: 'stopped', stop: { head: head(f) } });});});++describe('a finished run no longer blocks the next /ship, and abandon never hints a mark that refuses (GST-4109)', () => {+ const BUDGET = (f: ShipFx, args: string[]) => run(f, 'gstack-ship-budget', args);+ const startBudget = (f: ShipFx, name: string) => {+ const rec = path.join(f.root, `${name}.md`);+ fs.writeFileSync(rec, '# /ship record\n\n## Next steps\n- Step 1\n');+ const s = BUDGET(f, ['start', '--record', rec, '--mode', 'observe', '--reading', '1000', '--credits', '1']);+ expect(s.status, s.stdout + s.stderr).toBe(0);+ return rec;+ };++ // Value: protects=a /ship that finished (its ledger closed at Step 22) ends its own open run record, and a record an older gstack left open+ // behind a closed ledger is ended by the next preflight, while a run whose ledger is still open keeps blocking; fails_when=a finished+ // run blocks the next /ship until someone abandons it by hand (GSKI-1 #7), or a live run's record is ended;+ // why_new=no test ran the budget close against the run record; seam=gstack-ship-budget close, lib/ship-preflight.ts shipRunClear;+ // no_claim=a run that never reaches close, which stop, skill-end or abandon end as before+ test('close ends its own open record; preflight ends one an older close left; an unclosed run still blocks', () => {+ const f = fx();+ const rec = startBudget(f, 'r1');+ expect(preflight(f, 'r1').status).toBe(0);+ expect(BUDGET(f, ['note', '--record', rec, '--step', '9', '--reading', '1500', '--credits', '1']).status).toBe(0);+ const closed = BUDGET(f, ['close', '--record', rec, '--reading', '2000', '--credits', '2']);+ expect(closed.status, closed.stdout + closed.stderr).toBe(0);+ expect(closed.stdout).toMatch(/^RUN_ENDED: run=r1 state=finished ended_by=gstack-ship-budget close \(its budget ledger ship-\S+ closed at /m);+ expect(record(f)).toMatchObject({ run: 'r1', state: 'finished', ended_by: 'gstack-ship-budget close' });+ fs.writeFileSync(recordFile(f), JSON.stringify({ ...record(f), state: 'open', ended_by: undefined }) + '\n');+ f.advanceBase({ 'docs/new.md': '# new\n' });+ startBudget(f, 'r2');+ const next = preflight(f, 'r2');+ expect(next.status, next.stdout).toBe(0);+ expect(next.stdout).toMatch(/^RUN_ENDED: run=r1 state=finished /m);+ expect(record(f)).toMatchObject({ run: 'r2', state: 'open' });+ f.advanceBase({ 'docs/other.md': '# other\n' });+ startBudget(f, 'r3');+ const live = preflight(f, 'r3');+ expect(live.status).toBe(3);+ expect(live.stdout).toContain('STOP: /ship run r2 is open on this checkout and past its preflight (');+ expect(record(f)).toMatchObject({ run: 'r2', state: 'open' });+ });++ // Value: protects=abandon of an unreadable record with an open PR ends with no PR mark and no hint, and a mark the PR refuses prints why+ // with no rerun hint; fails_when=abandon --run unknown, or a run the PR body never recorded, prints a gstack-ship-receipt abandoned+ // command that refuses the same way (GSTA-891); why_new=only the no-PR case was driven; seam=bin/gstack-ship-run, a gh stub;+ // no_claim=gh failures, which keep the add-the-entry hint since a rerun can pass once gh works+ test('abandon --run unknown with an open PR skips the mark; a refused mark prints no looping hint', () => {+ const f = fx();+ fs.writeFileSync(recordFile(f), '{"v":1,"run":\n');+ const sha = /sha256=([0-9a-f]{64})/.exec(run(f, 'gstack-ship-run', ['status']).stdout)![1]!;+ const unknown = run(f, 'gstack-ship-run', ['abandon', '--run', 'unknown', '--sha256', sha, '--pr', '7', '--by', CAPTAIN, '--reason', 'corrupt record']);+ expect(unknown.status, unknown.stderr).toBe(0);+ expect(unknown.stdout).toContain("RUN_ABANDON_PR: skipped (an unreadable record names no run, so PR #7's body has no entry to mark)");+ expect(unknown.stdout).not.toContain('gstack-ship-receipt abandoned --pr');+ const g = fx();+ expect(preflight(g, 'r1').status).toBe(0);+ age(g, 61);+ const view = JSON.stringify({ body: 'A change.', headRefName: 'feat', headRepository: { name: 'fx' }, headRepositoryOwner: { login: 'fx' }, state: 'OPEN' });+ g.gh(`if [ "$1" = pr ] && [ "$2" = view ]; then printf '%s\\n' '${view}'; exit 0; fi; exit 0`);+ const named = run(g, 'gstack-ship-run', ['abandon', '--run', 'r1', '--pr', '7', '--by', CAPTAIN, '--reason', 'stopped answering']);+ expect(named.status, named.stderr).toBe(0);+ expect(named.stdout).toContain("RUN_ABANDON_PR: not recorded (gstack-ship-receipt abandoned: PR #7's body records no entry for run r1");+ expect(named.stdout).toContain('no mark is needed');+ expect(named.stdout).not.toContain('add the entry with');+ expect(record(g)).toMatchObject({ run: 'r1', state: 'abandoned' });+ });+ // Value: protects=preflight never ends a live run that wrote no ledger of its own after an earlier run's ledger closed; fails_when=endClosedRun takes the earlier closed ledger as the later record's owner and marks a live run finished (state-machines, ship-1-p1);+ // why_new=the case above always started a ledger per run; seam=an unmetered start; no_claim=two ledgers created in the same millisecond+ test('a later run with no ledger is never ended by an earlier closed ledger', () => {+ const f = fx();+ const rec = startBudget(f, 'r1');+ expect(preflight(f, 'r1').status).toBe(0);+ expect(BUDGET(f, ['close', '--record', rec, '--reading', '2000', '--credits', '2']).status).toBe(0);+ 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);+ f.advanceBase({ 'docs/b.md': 'b\n' });+ const r3 = preflight(f, 'r3');+ expect(r3.status).toBe(3);+ expect(r3.stdout).not.toContain('RUN_ENDED:');+ expect(record(f)).toMatchObject({ run: 'r2', state: 'open' });+ });++ // Value: protects=a late close of an earlier run's ledger never ends a later run that opened its record without a ledger; fails_when=endClosedRun takes the earlier ledger, which closed after the later record opened, as that record's owner and marks the live run finished (outside-voice, ship-1-p2);+ // why_new=the case above closed before the later run opened; seam=an unmetered start; no_claim=a ledger that keeps noting for another run+ test("an earlier run's late close never ends a later unmetered run", () => {+ 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]!;+ const l = JSON.parse(fs.readFileSync(ledger, 'utf8'));+ const back = (iso: string) => new Date(Date.parse(iso) - 30 * 60_000).toISOString();+ fs.writeFileSync(ledger, JSON.stringify({ ...l, created_at: back(l.created_at), reservations: l.reservations.map((x: { at: string }) => ({ ...x, at: back(x.at) })) }, null, 2));+ fs.writeFileSync(recordFile(f), JSON.stringify({ ...record(f), state: 'abandoned' }) + '\n');+ f.advanceBase({ 'docs/a.md': 'a\n' });+ expect(preflight(f, 'r2').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' });+ });++ // Value: protects=a start after the record's /ship passed preflight and ended is a new /ship, even within 5 minutes and with no note, while a rerun inside the open run re-attaches; fails_when=a quick second /ship re-attaches the ended run's ledger and its baseline (outside-voice, ship-1-p2), or a rerun of start mid-run splits the run;+ // why_new=the cases in ship-budget.test.ts never ran a preflight; seam=the run record's state; no_claim=a preflight with no budget start+ test('start re-attaches inside an open run and supersedes once that run ended', () => {+ const f = fx();+ const rec = startBudget(f, 'r1');+ expect(preflight(f, 'r1').status).toBe(0);+ const again = BUDGET(f, ['start', '--record', rec, '--mode', 'observe', '--reading', '1100', '--credits', '1']);+ expect(again.status, again.stdout + again.stderr).toBe(0);+ expect(again.stdout).not.toContain('SUPERSEDED:');+ fs.writeFileSync(recordFile(f), JSON.stringify({ ...record(f), state: 'finished' }) + '\n');+ const next = BUDGET(f, ['start', '--record', rec, '--mode', 'observe', '--reading', '1200', '--credits', '1']);+ expect(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);+ });+});