A stopped or crashed /ship run no longer blocks the next run or its granted fix round (GST-3260) (#4654)

A /ship run that stopped or crashed no longer blocks the next run or the
fix round it stopped for, and a run that is still working past two hours
stays protected.

Why: a leftover "run in progress" note blocked fix-round grants on four
PRs, and the old 2-hour timer could mark a live run as finished.

Nothing for readers to do; a run that really died is ended with
`gstack-ship-run abandon`.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
Review-Finding: p1/specialist-batched#1 reader=security
Review-Finding: p1/specialist-batched#2 reader=testing
Review-Finding: p1/specialist-batched#3 reader=state-machines
Review-Finding: p1/specialist-batched#4 reader=state-machines
Review-Finding: lib/ship-run-record.ts:167:correctness reader=core
This commit is contained in:
Garry Tanandcapy-ai[bot] authored and GitHub committed 2026-11-22 04:37:26 +00:00
1 parent 23ee4c3dec
commit e8e755473f
28 files changed
+885 -136

No files matched your search

+8 -6
View File
@@ -68,7 +68,8 @@ const HELP = `gstack-approvals — the per-thread approval record (capy/skill/gs
a review round the PR's R51 count would not plan (docs/review-policy.md#rounds-per-pull-request): extra-round is
one round with its fix round past the cap of 2, instead of the read-only final review; it binds
that head of that PR only and is spent by the round; the lane or its Captain records it, never the owner, and
--by is recorded, not enforced; refused inside this checkout's open /ship run, so a run never grants itself
--by is recorded, not enforced; refused inside this checkout's open /ship run, so a run never grants itself;
a stopped run (gstack-ship-run status) records only the fix-check grant naming its own --stop-run and stop --head
lane-exception --head <the pushed head the owner granted at> --files <the uncovered inventory files, comma-separated>
--reason <why, one line> --words <the owner's exact words> --by <who granted>
the owner's grant that a CI-carried lane counts although exactly those files are in no run's tree.json
@@ -184,9 +185,10 @@ function main(argv: string[]): number {
if (!by || isGstackActorName(by)) return invalid('round-grant needs --by <the lane or its Captain>: gstack never grants itself a round');
const ownerRef = flags['--owner-ref']?.trim();
if (ownerRef !== undefined && (!OWNER_REF.test(ownerRef) || !(flags['--words'] ?? '').trim())) return invalid('--owner-ref relays the lane\'s or Captain\'s grant: <thread code>:<message id or timestamp> (GSTA-36:2026-11-19T12:29:59Z), with --words <their exact words>');
const open = openShipRun(process.cwd());
if (open && ownerRef === undefined) return invalid(`/ship run ${open} is open on this checkout: a round grant is the lane's or its Captain's, never the run's own; relay it with --owner-ref <thread code>:<message id or timestamp> --words <their exact words>, or record it from the lane after the run stops`);
const stopRun = (flags['--stop-run'] ?? '').trim(), findings = [...new Set((flags['--findings'] ?? '').split(',').map(f => f.trim()).filter(Boolean))];
const open = openShipRun(process.cwd());
const ownStop = open?.state === 'stopped' && !open.claim && kind === 'fix-check' && stopRun === open.run && open.stop?.head === head.stdout.trim().toLowerCase();
if (open && ownerRef === undefined && !ownStop) return invalid(`${open.line}: ${open.state !== 'stopped' ? "a round grant is the lane's or its Captain's, never the run's own" : open.claim ? `this run already spent its own stop's fix-check grant (${open.claim.grant}), so a second fix round is the lane's or its Captain's` : `a stopped run records only the fix-check grant for its own stop (--kind fix-check --stop-run ${open.run} --head ${open.stop?.head ?? '<its stop head>'})`}; relay it with --owner-ref <thread code>:<message id or timestamp> --words <their exact words>, or record it from the lane after the run stops`);
if (kind === 'fix-check' && (!STOP_RUN.test(stopRun) || !findings.length || !findings.every(f => FINDING_ID.test(f)))) return invalid('round-grant --kind fix-check needs --stop-run <the run gstack-ship-receipt stop named> and --findings <the open finding ids it is for, comma-separated>: it buys the fix round of that one stop');
if (kind !== 'fix-check' && (flags['--stop-run'] !== undefined || flags['--findings'] !== undefined)) return invalid('--stop-run and --findings belong to --kind fix-check: an extra-round grant names no stop');
const built = buildRow({ ...reviewRoundGrantRow(head.stdout.trim().toLowerCase(), Number(pr), kind, reason, kind === 'fix-check' ? { run: stopRun, findings } : undefined), words: flags['--words'] ?? reason, by, date: flags['--date'], source: ruledNoteSource({ ownerRef }) }, loc.branch);
@@ -201,7 +203,7 @@ function main(argv: string[]): number {
if (!flags['--head'] || head.status !== 0) return invalid('lane-exception needs --head <the pushed head the owner granted at, a commit in this repository>');
if (isGstackActor(flags['--by'] ?? '')) return invalid('--by names gstack; a test-lane exception is the owner\'s, so --by names who granted it');
const open = openShipRun(process.cwd());
if (open) return invalid(`/ship run ${open} is open on this checkout: a test-lane exception is the owner's, never the lane's own runner's; record it from the owner's session`);
if (open) return invalid(`${open.line}: a test-lane exception is the owner's, never the lane's own runner's; record it from the owner's session`);
const built = buildRow({ ...testLaneExceptionRow(head.stdout.trim(), files, reason), words: flags['--words'] ?? '', by: flags['--by'] ?? '', date: flags['--date'] }, loc.branch);
if ('code' in built) return fail(cmd, built);
rows = [built];
@@ -217,8 +219,8 @@ function main(argv: string[]): number {
if (ownerRef !== undefined && (!OWNER_REF.test(ownerRef) || !(flags['--words'] ?? '').trim() || !(flags['--by'] ?? '').trim())) return invalid('--owner-ref relays the owner\'s ruling: <thread code>:<message id or timestamp> (GSTA-36:2026-11-19T12:29:59Z), with --by <the owner> and --words <their exact words>');
if (notSecurity && !/:red-team$/i.test(finding)) return invalid('--not-security is the owner\'s call on a red-team finding (path:line:red-team); a security, auth or secret finding is security class by its category');
const open = openShipRun(process.cwd());
if (open && notSecurity) return invalid(`--not-security lifts a red-team finding's redaction, so it is recorded only outside a /ship run: /ship run ${open} is open on this checkout; record it after the run stops`);
if (open && ownerRef === undefined) return fail(cmd, { code: 'APPROVAL_RULING_RUN_OPEN', message: `/ship run ${open} is open on this checkout, and its own runner cannot rule on the run's findings: relay the owner's ruling with --owner-ref <thread code>:<message id or timestamp> --by <the owner> --words <their exact words>, or record it after the run stops` });
if (open && notSecurity) return invalid(`--not-security lifts a red-team finding's redaction, so it is recorded only outside a /ship run: ${open.line}; record it after the run ends`);
if (open && ownerRef === undefined) return fail(cmd, { code: 'APPROVAL_RULING_RUN_OPEN', message: `${open.line}, and its own runner cannot rule on the run's findings: relay the owner's ruling with --owner-ref <thread code>:<message id or timestamp> --by <the owner> --words <their exact words>, or record it after the run stops` });
const built = buildRow({ ...ruledNoteRow(finding, head.stdout.trim(), reason), words: flags['--words'] ?? '', by: flags['--by'] ?? '', date: flags['--date'], source: ruledNoteSource({ ownerRef, notSecurity }) }, loc.branch);
if ('code' in built) return fail(cmd, built);
rows = [built];
+2
View File
@@ -344,6 +344,8 @@ gstack_result_anchor() {
RECEIPT_CARRY_PRODUCT_CHANGED) printf '%s' 'receipt-carry-product-changed' ;;
STOP_UNBOUND) printf '%s' 'stop-unbound' ;;
GRANT_SPENT) printf '%s' 'grant-spent' ;;
SHIP_RUN_ABANDON_REFUSED) printf '%s' 'ship-run-abandon-refused' ;;
SHIP_RUN_RECORD_UNREADABLE) printf '%s' 'ship-run-record-unreadable' ;;
GRANT_UNKNOWN) printf '%s' 'grant-unknown' ;;
RECEIPT_CARRY_SCOPED_REVIEW) printf '%s' 'receipt-carry-scoped-review' ;;
DOCS_AUDIT_BLOCKED) printf '%s' 'docs-audit-blocked' ;;
+3
View File
@@ -100,6 +100,7 @@ if [ "$INPUT" = --start ]; then
const { captureReviewStart } = await import(process.env.GSTACK_REVIEW_LIB);
try { console.log(captureReviewStart(process.env.GSTACK_REVIEW_SKILL, process.env, process.env.GSTACK_REVIEW_FIX_RANGE === "--fix-range")); }
catch (e) { console.error(e.message); process.exit(1); }
try { (await import(process.env.GSTACK_REVIEW_LIB.replace(/review-evidence\.ts$/, "ship-run-record.ts"))).beatFromReview(process.cwd()); } catch {}
'
exit $?
fi
@@ -109,6 +110,7 @@ if [ "$INPUT" = --start ]; then
const capture = () => captureReviewStart(process.env.GSTACK_REVIEW_SKILL, process.env, process.env.GSTACK_REVIEW_FIX_RANGE === "--fix-range");
try { console.log(admitReviewStart(process.env.GSTACK_SHIP_BUDGET_MARKER, process.env.GSTACK_REVIEW_RESERVATION || undefined, capture)); }
catch (e) { console.error(e.message); process.exit(1); }
try { (await import(process.env.GSTACK_REVIEW_LIB.replace(/review-evidence\.ts$/, "ship-run-record.ts"))).beatFromReview(process.cwd()); } catch {}
'
exit $?
fi
@@ -149,6 +151,7 @@ if (!rec || Array.isArray(rec) || typeof rec !== 'object') { console.error('gsta
try {
console.log(JSON.stringify(bindReview(rec, process.env.GSTACK_REVIEW_TOKEN, process.env, process.env.GSTACK_REVIEW_FINDINGS || undefined)));
} catch (e) { console.error(e.message); process.exit(1); }
if (process.env.GSTACK_REVIEW_TOKEN) try { (await import(process.env.GSTACK_REVIEW_LIB.replace(/review-evidence\\.ts$/, 'ship-run-record.ts'))).beatFromReview(process.cwd()); } catch {}
") || exit 1
echo "$STAMPED" >> "$GSTACK_HOME/projects/$SLUG/$BRANCH-reviews.jsonl"
+35 -8
View File
@@ -18,6 +18,7 @@
* gstack-ship-receipt history (--pr <n> [--repo <owner/repo>] | --body <file>) [--head <sha>] [--base <branch>] [--run <id>] [--json]
* gstack-ship-receipt stub (--pr <n> [--repo <owner/repo>] | --body <file>) --run <id> [--head <sha>] [--review-loop <json|@file>] [--void]
* gstack-ship-receipt stop (--pr <n> [--repo <owner/repo>] | --body <file>) --run <id> --since <REVIEW_SINCE>
* gstack-ship-receipt abandoned (--pr <n> [--repo <owner/repo>] | --body <file>) --run <id> --by <who> --reason <one line>
* gstack-ship-receipt claim (--pr <n> [--repo <owner/repo>] | --body <file>) --run <id> --grant <approval id>
*
* `write` validates against `gstack-artifact schema ship-receipt`, prints the
@@ -66,7 +67,8 @@ import { publicRuledNote, readRuledNotes, ruledNoteText } from '../lib/ruled-not
import { appliedGateDispositions, gateDispositionText, publicGateDisposition } from '../lib/gate-dispositions';
import { securityFingerprints } from '../lib/security-findings';
import { laneExceptionBodyLines } from '../lib/test-lane-exception';
import { grantedStop, grantMarker, historyLine, placeRunEntry, prReviewHistory, reviewRoute, runStub, stopFrom, stopMarker } from '../lib/pr-review-history';
import { abandonMarker, grantedStop, grantMarker, historyLine, placeRunEntry, prReviewHistory, receiptedRun, reviewRoute, runStub, stopFrom, stopMarker } from '../lib/pr-review-history';
import { changeRunRecord } from '../lib/ship-run-record';
import { grantFor, publicRoundGrant, readReviewRoundGrants, type ReviewRoundGrant } from '../lib/review-round-grant';
import { readMechanicalLines } from '../lib/ship-mechanical';
import { patchId, productPatchAgainstBase, productRules, productSpec, verifiedOutputs } from '../lib/ship-receipt-patch';
@@ -115,11 +117,16 @@ const HELP = `gstack-ship-receipt — the \`\`\`gstack-ship-receipt\`\`\` block
stop --pr <n> | --body <file> --run <id> --since <REVIEW_SINCE>
Step 9, on NEXT: stop: record the review this run stopped on (its commit and tree, from the newest
via:ship review row bound to one committed tree) as a stop record in the runs block, and print the
round-grant command that buys its fix round (STOP_RECORD:, NEXT:); an unbound read prints
STOP_UNBOUND (exit 3) and records nothing (docs/troubleshooting.md#stop-unbound)
round-grant command that buys its fix round (STOP_RECORD:, NEXT:); the stopping row is the newest
full pass, fix-check or Step 11 voice, so the stop is the head it read (#4591); it also marks this
checkout's run record stopped at that head and tree; an unbound read prints STOP_UNBOUND (exit 3)
and records nothing (docs/troubleshooting.md#stop-unbound)
claim --pr <n> | --body <file> --run <id> --grant <approval id>
before the first dispatch of a run whose PR_REVIEW_FLAGS: name --round-grant: record that this run
spends the grant (GRANT_CLAIMED:); a grant another run claimed is refused (GRANT_SPENT, exit 3)
spends the grant (GRANT_CLAIMED:), in the PR body and in this checkout's run record; a grant
another run claimed is refused (GRANT_SPENT, exit 3)
abandoned --pr <n> | --body <file> --run <id> --by <who> --reason <one line>
gstack-ship-run abandon's PR-body half: a mark:abandoned entry in the runs block (RUN_ABANDON_MARK:)
docs-caps [--base <ref>] /ship Step 14.5: one DOCS_CAP: <path> <bytes>/<max> ok|over line per docs.caps entry of the
reviewed policy (origin/<base>'s .gstack/ship-policy.json; --policy <file> reads that file
instead); any over (or absent) file exits 1 (DOCS_AUDIT_BLOCKED)
@@ -980,8 +987,9 @@ function cmdHistory(rest: string[], json: boolean): number {
const grant = claimed ? undefined : found;
const route = answer?.ok ? { route: 'fix-check' as const, reason: `fix-check grant ${answer.grant.approval} answers the stop at ${answer.stop.head.slice(0, 12)} (run ${answer.stop.run}): one scoped fix-check of the PR's own change since it, for ${answer.grant.findings!.join(', ')}, with no new full review` } : reviewRoute(h, { grant: grant?.approval });
const flagsLine = `PR_REVIEW_FLAGS: --prior-rounds ${h.rounds} --prior-full ${h.full}${grant ? ` --round-grant ${grant.approval}` : ''}${answer?.ok ? ` --stop ${answer.stop.head}` : ''}`;
if (json) { process.stdout.write(JSON.stringify({ pr, ...h, grant: grant ?? null, stop: answer?.ok ? answer.stop : null, route }) + '\n'); return EXIT.ok; }
process.stdout.write(`${historyLine(pr, h)}\n${flagsLine}\nPR_REVIEW_ROUTE: ${route.route} (${route.reason})\n${answer && !answer.ok ? `PR_REVIEW_GRANT: not applied (${answer.why})\n` : ''}${claimed ? `PR_REVIEW_GRANT: not applied (grant ${claimed.grant} was claimed by run ${claimed.run}: a grant buys one round)\n` : ''}`);
const used = flag(rest, '--run') ? receiptedRun(read.body, flag(rest, '--run')!) : undefined;
if (json) { process.stdout.write(JSON.stringify({ pr, ...h, grant: grant ?? null, stop: answer?.ok ? answer.stop : null, route, run_used: used?.head ?? null }) + '\n'); return EXIT.ok; }
process.stdout.write(`${historyLine(pr, h)}\n${flagsLine}\nPR_REVIEW_ROUTE: ${route.route} (${route.reason})\n${answer && !answer.ok ? `PR_REVIEW_GRANT: not applied (${answer.why})\n` : ''}${claimed ? `PR_REVIEW_GRANT: not applied (grant ${claimed.grant} was claimed by run ${claimed.run}: a grant buys one round)\n` : ''}${used ? `PR_REVIEW_RUN_USED: run=${used.run} receipted at ${used.head.slice(0, 12)}\n` : ''}`);
return EXIT.ok;
}
@@ -1004,7 +1012,8 @@ function cmdStop(rest: string[]): number {
const err = postBody(rest, read.pr, placeRunEntry(read.body, stopMarker({ head: found.head, tree: found.tree, run })));
if (err) { process.stderr.write(`gstack-ship-receipt stop: ${err}; nothing recorded\n`); return EXIT.fail; }
const pr = read.pr ?? flag(rest, '--pr') ?? '<n>';
process.stdout.write(`STOP_RECORD: run=${run} head=${found.head} tree=${found.tree}\nNEXT: the lane or its Captain decides: ship with the open notes listed, park, or buy this stop's fix round with gstack-approvals round-grant --pr ${pr} --head ${found.head} --kind fix-check --stop-run ${run} --findings <the open finding ids, comma-separated> --reason "<why>" --by <the lane or its Captain>, then take --round-grant and --stop from the PR_REVIEW_FLAGS: line of gstack-ship-receipt history --pr ${pr} --base <base> --run ${run} in this run, or from a new run's preflight (docs/troubleshooting.md#pr-round-cap)\n`);
const marked = changeRunRecord(repoRoot, 'stop', run, { stop: { head: found.head, tree: found.tree } });
process.stdout.write(`STOP_RECORD: run=${run} head=${found.head} tree=${found.tree}\n${marked.ok ? '' : `RUN_RECORD: not marked stopped (${marked.why})\n`}NEXT: the lane or its Captain decides: ship with the open notes listed, park, or buy this stop's fix round with gstack-approvals round-grant --pr ${pr} --head ${found.head} --kind fix-check --stop-run ${run} --findings <the open finding ids, comma-separated> --reason "<why>" --by <the lane or its Captain>, then take --round-grant and --stop from the PR_REVIEW_FLAGS: line of gstack-ship-receipt history --pr ${pr} --base <base> --run ${run} in this run, or from a new run's preflight (docs/troubleshooting.md#pr-round-cap)\n`);
return EXIT.ok;
}
@@ -1027,7 +1036,8 @@ function cmdClaim(rest: string[]): number {
if (!again.ok) { process.stderr.write(`gstack-ship-receipt claim: ${again.why}; the claim is unconfirmed, so do not dispatch\n`); return EXIT.fail; }
const first = receiptRuns(again.body).find(r => r.mark === 'grant' && r.grant === id);
if (first?.run !== run) { process.stderr.write(`${resultLine('gstack-ship-receipt claim', 'GRANT_SPENT', `grant ${id} was claimed by run ${first?.run ?? 'another run'} while this run claimed it: a grant buys one round; the lane or its Captain records a new one`)}\n`); return EXIT.refused; }
process.stdout.write(`GRANT_CLAIMED: grant=${id} kind=${g.kind} run=${run} head=${g.head.slice(0, 12)}\n`);
const recorded = changeRunRecord(repoRoot, 'claim', run, { claim: { grant: id, ...(g.stop_run ? { stop_run: g.stop_run } : {}), stop_head: g.head, findings: g.findings ?? [] } });
process.stdout.write(`GRANT_CLAIMED: grant=${id} kind=${g.kind} run=${run} head=${g.head.slice(0, 12)}\n${recorded.ok ? '' : `RUN_RECORD: claim not recorded (${recorded.why})\n`}`);
return EXIT.ok;
}
@@ -1045,10 +1055,26 @@ function cmdStub(rest: string[]): number {
const status = rest.includes('--void') ? 'voided' : 'started';
const err = postBody(rest, read.pr, placeRunEntry(read.body, runStub({ head, run, status, loop })));
if (err) { process.stderr.write(`gstack-ship-receipt stub: ${err}; the run is not recorded\n`); return EXIT.fail; }
const repoRoot = git(['rev-parse', '--show-toplevel']);
if (repoRoot) changeRunRecord(repoRoot, 'beat', run);
process.stdout.write(`RUN_STUB: run=${run} status=${status} rounds=${loop.passes} head=${head.slice(0, 12)}\n`);
return EXIT.ok;
}
/** gstack-ship-run abandon's PR-body half (GST-3260): a mark:abandoned entry in the runs block naming the run, who ended it and why. */
function cmdAbandoned(rest: string[]): number {
const run = flag(rest, '--run'), by = flag(rest, '--by')?.trim(), reason = flag(rest, '--reason')?.trim();
if (!run || !/^[\w.:-]{1,128}$/.test(run) || !by || !reason || /[\x00-\x1f\x7f]/.test(by + reason)) { process.stderr.write('gstack-ship-receipt abandoned: --run <id>, --by <who> and --reason <one line> are required\n'); return EXIT.usage; }
const read = readBody(rest);
if (!read.ok) { process.stderr.write(`gstack-ship-receipt abandoned: ${read.why}; fix: ${read.fix}\n`); return EXIT.fail; }
const head = git(['rev-parse', 'HEAD'])?.toLowerCase();
if (!head) { process.stderr.write('gstack-ship-receipt abandoned: cannot resolve HEAD\n'); return EXIT.usage; }
const err = postBody(rest, read.pr, placeRunEntry(read.body, abandonMarker({ head, run, by, reason })));
if (err) { process.stderr.write(`gstack-ship-receipt abandoned: ${err}; not marked\n`); return EXIT.fail; }
process.stdout.write(`RUN_ABANDON_MARK: run=${run} head=${head.slice(0, 12)}\n`);
return EXIT.ok;
}
function main(argv: string[]): number {
const [cmd, ...rest] = argv;
const json = rest.includes('--json');
@@ -1063,6 +1089,7 @@ function main(argv: string[]): number {
if (cmd === 'stub') return cmdStub(rest);
if (cmd === 'stop') return cmdStop(rest);
if (cmd === 'claim') return cmdClaim(rest);
if (cmd === 'abandoned') return cmdAbandoned(rest);
process.stderr.write(`gstack-ship-receipt: unknown command ${cmd}\n${HELP}\n`);
return EXIT.usage;
}
+80
View File
@@ -0,0 +1,80 @@
#!/usr/bin/env -S bun --no-env-file --config=/dev/null
/**
* gstack-ship-run — this checkout's /ship run record (lib/ship-run-record.ts, docs/ship-policy.md#what-ends-a-run).
*
* gstack-ship-run status
* gstack-ship-run abandon --run <id> --by <lane or Captain> --reason <one line> [--sha256 <digest>] [--pr <n> [--repo <r>] | --body <file>]
* gstack-ship-run skill-end --run <session id>
*/
import * as path from 'node:path';
import { EXIT, exitTableHelp } from '../lib/headless-artifacts';
import { ghSpawnSync } from '../lib/gh-poll';
import { resultLineWithDocs } from '../lib/result-codes';
import { isGstackActorName } from '../lib/ruled-notes';
import { BIN_DIR, runScriptSync } from '../lib/script-invocation';
import { abandonRefusal, changeRunRecord, openRun, readRunRecord, RUN_ID } from '../lib/ship-run-record';
import { spawnSync } from '../lib/spawn-sync';
const HELP = `gstack-ship-run — this checkout's /ship run record (docs/ship-policy.md#what-ends-a-run)
status RUN_STATE: run=<id> state=open|stopped|finished|abandoned|legacy beat_age=<m>m …, then NEXT: with the abandon
command while the run still blocks; an unreadable record prints its sha256 and SHIP_RUN_RECORD_UNREADABLE (exit 1)
abandon --run <id> --by <the lane or its Captain> --reason <one line> [--sha256 <digest>] [--pr <n> [--repo <r>] | --body <file>]
end a run that stopped working: the record becomes abandoned with who and why, and the open PR's runs block gets a
mark: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
skill-end --run <session id>
what gstack-skill-end calls: marks the record finished (ended_by skill-end) when it names that run
${exitTableHelp()}`;
function main(argv: string[]): number {
const [cmd, ...rest] = argv;
const flag = (name: string) => { const i = rest.lastIndexOf(name); return i >= 0 ? rest[i + 1] : undefined; };
const cwd = process.cwd();
if (!cmd || cmd === '--help' || cmd === '-h') { process.stdout.write(HELP + '\n'); return cmd ? EXIT.ok : EXIT.usage; }
if (cmd === 'status') {
const read = readRunRecord(cwd);
const open = openRun(read);
if (read.kind === 'none') { process.stdout.write('RUN_STATE: none (no /ship run record on this checkout)\n'); return EXIT.ok; }
if (read.kind === 'unreadable') {
process.stdout.write(`RUN_STATE: run=unknown state=unreadable file=${read.file} sha256=${read.sha256 ?? 'unreadable'}\nNEXT: ${open!.detail}\n`);
process.stderr.write(resultLineWithDocs('gstack-ship-run status', 'SHIP_RUN_RECORD_UNREADABLE', `${read.file}: ${read.why}`) + '\n');
return EXIT.fail;
}
const rec = read.kind === 'record' ? read.record : undefined;
const age = rec ? `${Math.max(0, Math.floor((Date.now() - Date.parse(rec.beat_at)) / 60_000))}m` : 'unknown';
process.stdout.write(`RUN_STATE: run=${read.kind === 'record' ? read.record.run : read.run} state=${rec?.state ?? 'legacy'} beat_age=${age} started_at=${rec?.started_at ?? 'unknown'} head=${rec?.head.slice(0, 12) ?? 'unknown'}${rec?.stop ? ` stop=${rec.stop.head.slice(0, 12)}` : ''}${rec?.claim ? ` claim=${rec.claim.grant}` : ''}${rec?.ended_by ? ` ended_by=${rec.ended_by}` : ''}\n${open ? `NEXT: ${open.detail}\n` : ''}`);
return EXIT.ok;
}
if (cmd === 'skill-end') {
const run = flag('--run');
if (!run) { process.stderr.write('gstack-ship-run skill-end: --run <session id> is required\n'); return EXIT.usage; }
const done = changeRunRecord(cwd, 'skill-end', run, { ended_by: 'skill-end' });
process.stdout.write(done.ok ? `RUN_ENDED: run=${run} state=finished ended_by=skill-end\n` : `RUN_ENDED: none (${done.why})\n`);
return EXIT.ok;
}
if (cmd !== 'abandon') { process.stderr.write(`gstack-ship-run: unknown command ${cmd}\n${HELP}\n`); return EXIT.usage; }
const run = flag('--run'), by = flag('--by')?.trim(), reason = flag('--reason')?.trim();
if (!run || (run !== 'unknown' && !RUN_ID.test(run)) || !by || !reason || /[\x00-\x1f\x7f]/.test(by + reason)) {
process.stderr.write('gstack-ship-run abandon: --run <id> (unknown for an unreadable record), --by <the lane or its Captain> and --reason <one line> are required\n');
return EXIT.usage;
}
if (isGstackActorName(by)) { process.stderr.write('gstack-ship-run abandon: --by names gstack; the lane or its Captain abandons a run, never gstack itself\n'); return EXIT.usage; }
const done = changeRunRecord(cwd, 'abandon', run, { ended_by: by, reason }, { check: read => abandonRefusal(read, run, flag('--sha256')) });
if (!done.ok) { process.stderr.write(resultLineWithDocs('gstack-ship-run abandon', 'SHIP_RUN_ABANDON_REFUSED', `${done.why}; nothing changed`) + '\n'); return EXIT.refused; }
process.stdout.write(`RUN_ABANDONED: run=${run} from=${done.from} by=${by} at=${done.record?.beat_at}\n`);
const branch = spawnSync('git', ['branch', '--show-current'], { cwd, encoding: 'utf8', timeout: 10_000 }).stdout?.trim() ?? '';
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) { 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`);
return EXIT.ok;
}
process.exitCode = main(process.argv.slice(2));
+2
View File
@@ -69,6 +69,8 @@ case "$TEL_START" in ''|*[!0-9]*) ;; *) _TEL_DUR=$(( _TEL_END - TEL_START )) ;;
# Release the workflow lease run gstack-skill-start opened (SESSION_ID starts
# with its harness pid), so a finished run stops blocking gstack-upgrade (GST-1205).
[ -n "$SESSION_ID" ] && "$_BIN/gstack-lease" release --pid "${SESSION_ID%%-*}" --run "$SESSION_ID" >/dev/null 2>&1 || true
_SHIP_RUN=$(git rev-parse --git-path gstack-ship-run 2>/dev/null || true)
[ -n "$SESSION_ID" ] && [ -n "$_SHIP_RUN" ] && [ -f "$_SHIP_RUN" ] && "$_BIN/gstack-ship-run" skill-end --run "$SESSION_ID" >/dev/null 2>&1 || true
# Record completion before the final drain, including its durable enqueue.
# The normal sync gates still decide publication: full may sync timelines,
@@ -0,0 +1 @@
**A /ship run that stopped or died no longer blocks grants and the next /ship, and a live run past two hours no longer looks finished.** The bare run marker in the checkout's git dir is now a run record with a state (open, stopped, finished, abandoned) that only gstack's commands change: preflight opens it, review starts and finishes, stub, stop and claim keep it fresh, `gstack-ship-receipt stop` marks it stopped, `finish` removes it, and `gstack-skill-end` marks it finished on any outcome. Preflight and the approval guards read that record instead of the 120-minute lease, which another run's touch could prune while the run was still working. A stopped run may record the fix-check grant for its own stop, once per run, and nothing else; rulings relayed with `--owner-ref` still record. A new `gstack-ship-run` command prints the record (`status`) and ends a run that stopped working (`abandon --run <id> --by <who> --reason <line>`), never within 60 minutes of its last beat; a bare marker from an older gstack, or an unreadable record (by its digest), can be abandoned at any age, and every refusal names the state, the age of the last beat, the earliest abandon time and the command. Also: `gstack-ship-receipt stop` binds the stop to the head its last reading row read, a fix-check or a second-model review included, instead of refusing with `STOP_UNBOUND` (#4591); the PR's round count no longer collapses runs that reused one run id at different heads (gstack-evals#406), and preflight refuses a run id the PR body or run record already shows ended. (GST-3260)
+4 -2
View File
@@ -236,8 +236,10 @@ caught on another crew's PRs.
gstack writes for itself, `gstack` or `gstack no-stop default (K1)`, matched
whole and case-insensitively, so "gstack-evals Captain" or "GStack Minder" can
grant) and a grant from inside an open `/ship` run are refused, and `add`
refuses the scope. A stopped run's marker stays on its checkout, so the lane
records its Captain's grant there as a relay: `--owner-ref <thread
refuses the scope. A stopped run (state `stopped` in its run record,
[what ends a run](ship-policy.md#what-ends-a-run)) may record the fix-check grant
for its own stop, once per run; any other grant on that checkout, a second fix
round included, is the lane's relay of its Captain's grant: `--owner-ref <thread
code>:<message id or timestamp> --words <their exact words>`, the same relay
`gstack-approvals rule` takes, which the row keeps as `relayed:<ref>` (#4531). `--by` is otherwise the caller's own text, recorded and
not checked: a lane that records a grant (or a ruling) from another checkout
+23 -5
View File
@@ -1801,6 +1801,21 @@ construction:
the run and names the finding (path, severity, problem) for the owner instead
of a third round; the owner may grant one scoped fix-check.
<a id="what-ends-a-run"></a>
**What ends a /ship run (GST-3260).** Preflight opens the run in the checkout's
run record (`git rev-parse --git-path gstack-ship-run`), and while it is open a
full preflight, round grants, gate dispositions, lane exceptions and rulings
without `--owner-ref` stop. Only gstack's commands end it: `finish` removes the
record (only when the open PR's body names that run), `gstack-ship-receipt stop`
marks it stopped (it may then record the fix-check grant for its own stop, once
per run, and 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
within 60 minutes of its last beat. No timer ends a run. A bare marker from an
older gstack reads as `legacy` and an unreadable record as `unreadable`; both
block until abandoned. The record guards against mistakes, such as a base merge
under a run's readers or a run granting itself a round; it is not proof of who
the owner is.
<a id="ruled-notes"></a>
**Ruled notes (GST-1537).** R51's other answer to an open finding is the owner's
ruling that it ships as a disclosed note, with the note listed. The owner records
@@ -1820,7 +1835,8 @@ a later head is a new row. Its `by` is the ruler and its `recorded_at` the time.
newline or control character, a `--by` naming gstack (any `--by` that starts with
`gstack`, except a crew named `GStack <Name>` such as `GStack Minder`, which is a
person's crew; `gstack` and `gstack no-stop default (K1)` are always refused), and a ruling while this
checkout holds an open /ship run's marker (the lane's own runner) unless the lane
checkout holds an open /ship run's record (the lane's own runner; a stopped, legacy or
unreadable record counts, [what ends a run](#what-ends-a-run)) unless the lane
relays the owner's words with `--owner-ref <thread code>:<message id or timestamp>`
(on Capy the owner, a Captain, has no session on the lane's checkout). A relayed row's
source is `relayed:<owner ref>`, and its `RULED_NOTE:`, receipt entry and `Ruled note:`
@@ -1937,9 +1953,10 @@ The row is an approved `gstack-approvals` row with scope `gate_disposition
trimmed first), a `--head` that is not a commit, a `--by` naming gstack (as for
`rule`: a `GStack <Name>` crew may record), a row that
`dispositions` would not list (a head that is not 40 hex, for one), and any call
while a /ship run is open on the branch in any worktree of the repository: its
marker counts while its lease is open, the same test preflight uses, so a run parked
before finish stops counting once its 120-minute lease ends. It finds those worktrees
while a /ship run is open on the branch in any worktree of the repository: each
worktree's run record decides ([what ends a run](#what-ends-a-run)), so an open,
stopped, legacy or unreadable record counts, a finished or abandoned one does not,
and no timer ends a run. It finds those worktrees
through the git common dir, and it checks and appends under a lock there that
/ship's preflight also takes to write its marker. `add` refuses the scope and
`--source gate`, so `gate` is the only writer. A row counts only when it has every
@@ -2041,7 +2058,8 @@ The row is an approved `gstack-approvals` row with scope `test_lane_exception <h
(`lib/test-lane-exception.ts`). `lane-exception` refuses a head that is not a
commit, a file with whitespace, a multi-line reason, a `--by` naming gstack (as
for `rule`: a `GStack <Name>` crew may grant) and
any grant while this checkout holds an open /ship run's marker, and `add` refuses
any grant while this checkout holds an open /ship run's record
([what ends a run](#what-ends-a-run)), and `add` refuses
the scope, so the lane's own runner cannot write one; a row by gstack is ignored
wherever it came from. `gstack-evidence record-ci` binds a grant only when its
head is HEAD and its files are exactly the uncovered set, and only after a local
+53 -21
View File
@@ -712,32 +712,33 @@ fix-check record as Step 9's. Rerun Step 11's native pass on the same frozen tre
`review_freshness` `CURRENT`, and Step 11.5 continues to Step 12.
<a id="ship-preflight-run-open"></a>
### `STOP: /ship run <id> is open on this checkout and past its preflight (<marker>; open until its finish or for 120 minutes) ...`
### `STOP: /ship run <id> is open on this checkout and past its preflight (<record>; state …, beat_age …; …) ...`
**Meaning.** A full `gstack-ship-preflight` (Steps 1-3) ran on a checkout where a
/ship run already passed them and has not finished. A full preflight merges the
base into the working tree, and that run's review readers diff this tree, so the
merge would void their pass (gbrain-evals#317). /ship passes `--run <id>` (Step 1:
the preamble's `SESSION_ID`; `ship/DRIVER.md` Phase 2: the run dir's name). Once
Steps 1-3 succeed, preflight records the run in the checkout's git dir
(`gstack-ship-run`) and opens it on the checkout's own lease
(`<git dir>/gstack-leases`, so the driver needs no workflow lease). The run
counts as open while the marker exists, which `gstack-ship-release finish` removes
when Steps 15-16 pass, and while `bin/gstack-lease open` says so: under 120
minutes old and its holder (the harness that ran preflight) alive. A finished,
aged-out or dead run never blocks, and /ship's own first preflight (or a rerun
after a Step 3 STOP) is never refused. A different `--run` from the open run's
holder replaces it: that is a new /ship after one that stopped before finish.
The holder is the first non-shell process above preflight: the Claude Code
session, or on Capy the machine's one `capy-server`, so there only the same id or
a missing `--run` is refused. The same id, no `--run`, or an open run held by
another live process (another session) stops.
Steps 1-3 succeed, preflight opens the run in the checkout's run record (the
git dir's `gstack-ship-run`, [ship-policy.md](ship-policy.md#what-ends-a-run)).
The run stays open until a gstack command ends it: `gstack-ship-release finish`
removes the record, `gstack-ship-receipt stop` marks it stopped,
`gstack-skill-end` marks it finished, and `gstack-ship-run abandon` ends a run
that stopped working. No timer ends it, so a run that has waited two hours on CI
still blocks (GST-3260). A stopped, finished or abandoned record of another run
never blocks: the new run replaces it. A bare marker an older gstack wrote
(state `legacy`) and a record gstack can't read (state `unreadable`) block as
open. /ship's own first preflight, or a rerun after a Step 3 STOP, is never
refused. A `--run` the record already names stops with `/ship run <id> already
ended on this checkout` (or `already stopped`): a run id names one /ship run.
**What is kept.** Nothing ran: no fetch, no merge, the tree is untouched.
**Fix.** Rerun Step 5 with `gstack-ship-preflight --tests-only`, which never
merges, or let that /ship finish. If that run is no longer running (it stopped
before finish), remove the marker the STOP names (`rm <marker>`), then rerun.
merges, or let that /ship finish. If that run is no longer working, end it with
the `gstack-ship-run abandon` command the STOP prints, from the earliest time it
prints ([ship-run-abandon-refused](#ship-run-abandon-refused)), then rerun. A
reused `--run` id needs a new id.
**Expected result.** The preflight continues to `STATUS:` and `MERGE:`.
@@ -7617,8 +7618,9 @@ closes a gate finding, and nothing the lane writes on its review row does either
**Fix.** When the owner approved the gate change, record the owner's answer at the
stop head the review read, with the `fingerprint` and `gate_id` from the review row,
while no /ship run is open on that branch in any worktree (a parked run's marker stops
counting once its 120-minute lease ends, as it does for preflight):
while no /ship run is open on that branch in any worktree (a parked run's record
counts until `gstack-ship-run abandon` or another gstack command ends it, as it does
for preflight; [ship-policy.md](ship-policy.md#what-ends-a-run)):
```bash
gstack-approvals gate --finding '<fingerprint>' --gate-id <gate_id> --head <stop head> \
@@ -7891,15 +7893,45 @@ is refused) ([review-policy.md](review-policy.md#rounds-per-pull-request)).
### `STOP_UNBOUND`
**Meaning.** `gstack-ship-receipt stop` found no review of this run that
gstack can tie to one commit: the newest `via:ship` review row since
`--since` is missing, didn't finish, read a tree that moved or wasn't
committed, or its commit isn't HEAD or under it. It recorded no stop record, so
gstack can tie to one commit: the newest `via:ship` reading row since
`--since` (a full pass, a fix-check or a Step 11 voice, whichever read last,
#4591) is missing, didn't finish, read a tree that moved or wasn't committed,
or its commit isn't HEAD or under it. It recorded no stop record, so
no fix-check grant can buy that review's fix round.
**Fix.** Nothing for a grant to answer. The lane's Captain ships with the open
notes listed or parks; a fresh `/ship` run gives the head its review
([review-policy.md](review-policy.md#rounds-per-pull-request)).
<a id="ship-run-abandon-refused"></a>
### `SHIP_RUN_ABANDON_REFUSED`
**Meaning.** `gstack-ship-run abandon` left the run record as it was. Either
the run beat (preflight, a review start or finish, stub, stop or claim) in the
last 60 minutes, so it may still be working; or the record names another run,
or already ended (finished or abandoned); or the record is unreadable and the
`--sha256` given isn't its digest. `--by` naming gstack itself is a usage error.
**Fix.** Run `gstack-ship-run status`. It prints the run, its state, its
`beat_age` and the exact abandon command. Wait until the earliest abandon time
when the run may still be working, and pass the run the record names. Abandon
completes in one call: after `RUN_ABANDONED` the record is ended, so never
rerun it, even when `RUN_ABANDON_PR` says the PR body entry was skipped or not
recorded (add that entry with `gstack-ship-receipt abandoned` instead).
<a id="ship-run-record-unreadable"></a>
### `SHIP_RUN_RECORD_UNREADABLE`
**Meaning.** This checkout's /ship run record (the git dir's `gstack-ship-run`)
is neither a run record nor a bare run id. Every guard reads it as an open run
(it fails closed), so preflight, round grants, rulings without `--owner-ref`,
gate dispositions and lane exceptions stop until it is ended.
**Fix.** If no /ship run is working on this checkout, run the command
`gstack-ship-run status` prints once:
`gstack-ship-run abandon --run unknown --sha256 <digest> --by <lane or Captain> --reason "<one line>"`.
The digest binds the abandon to the bytes you inspected.
<a id="grant-spent"></a>
### `GRANT_SPENT`
+10 -31
View File
@@ -17,13 +17,12 @@
import { createHash } from 'node:crypto';
import { spawnSync } from './spawn-sync';
import * as fs from 'node:fs';
import * as path from 'node:path';
import { appendRows, locate, readRecord, type ApprovalRow, type Env, type RecordError, type StoreLocation } from './approval-record';
import type { ShipReceipt } from './headless-artifacts';
import type { ResultCodeName } from './result-codes';
import { isGstackActor, type RuledNote } from './ruled-notes';
import { isSecurityFinding, REDACTED_FINDING, REDACTED_REASON, REDACTED_WORDS } from './security-findings';
import { BIN_DIR, runScriptSync } from './script-invocation';
import { openRun, readRunRecord, withGateLock } from './ship-run-record';
export interface GateDisposition { finding: string; gate_id: string; head: string; by: string; reason: string; words: string; at: string; approval: string }
@@ -104,53 +103,33 @@ export function appliedGateDispositions(cwd: string, o: { branch?: string; pin:
/**
* The /ship runs open on `branch` in any worktree of this repository (found through the git common dir); a detached worktree's run
* counts too. A marker counts while its run's lease is open (`gstack-lease open`, the test preflight uses), so a run parked before
* finish stops counting once its 120-minute lease ends; a lease check that cannot run counts the marker as open.
* counts too. Each worktree's run record decides (lib/ship-run-record.ts): an open, stopped, legacy or unreadable record counts,
* a finished or abandoned one does not, and no timer ends a run. `detail` is the record's state, beat_age and abandon command.
*/
export function openShipRunsOn(cwd: string, branch: string): string[] {
export function openShipRunsOn(cwd: string, branch: string): Array<{ text: string; detail: string }> {
const list = spawnSync('git', ['worktree', 'list', '--porcelain'], { cwd, encoding: 'utf8', timeout: 10_000 });
if (list.status !== 0) return [`unknown (git worktree list failed: ${(list.stderr ?? '').trim().slice(0, 120)})`];
if (list.status !== 0) return [{ text: `unknown (git worktree list failed: ${(list.stderr ?? '').trim().slice(0, 120)})`, detail: '' }];
const here = spawnSync('git', ['rev-parse', '--show-toplevel'], { cwd, encoding: 'utf8', timeout: 10_000 }).stdout?.trim() ?? '';
const real = (p: string) => { try { return fs.realpathSync(p); } catch { return p; } };
const open: string[] = [];
const open: Array<{ text: string; detail: string }> = [];
for (const block of list.stdout.split(/\n\n+/).filter(b => b.trim())) {
const dir = /^worktree (.+)$/m.exec(block)?.[1];
const on = /^branch refs\/heads\/(.+)$/m.exec(block)?.[1];
if (!dir || /^bare$/m.test(block) || (on !== undefined && on !== branch)) continue;
const marker = spawnSync('git', ['rev-parse', '--git-path', 'gstack-ship-run'], { cwd: dir, encoding: 'utf8', timeout: 10_000 });
if (marker.status !== 0 || !marker.stdout.trim()) continue;
let run = '';
try { run = fs.readFileSync(path.resolve(dir, marker.stdout.trim()), 'utf8').trim(); } catch { continue; }
if (!run || runScriptSync(path.join(BIN_DIR, 'gstack-lease'), ['open', '--root', dir, '--run', run], { cwd: dir, encoding: 'utf8', timeout: 60_000 }).status === 1) continue;
open.push(real(dir) === real(here) ? `${run} is open on this checkout` : `${run} is open in the worktree ${dir}`);
const run = openRun(readRunRecord(dir));
if (!run) continue;
open.push({ text: real(dir) === real(here) ? `${run.run} is open on this checkout` : `${run.run} is open in the worktree ${dir}`, detail: `${run.run}: ${run.detail}` });
}
return open;
}
/** Run `fn` holding the repository's gate-disposition lock (a directory in the git common dir; one older than a minute is stale). */
export function withGateLock<T>(cwd: string, fn: () => T, waitMs = 15_000): T | RecordError {
const common = spawnSync('git', ['rev-parse', '--git-common-dir'], { cwd, encoding: 'utf8', timeout: 10_000 });
if (common.status !== 0 || !common.stdout.trim()) return { code: 'APPROVAL_RECORD_WRITE_FAILED', message: `no git common dir at ${cwd}, so the gate-disposition lock cannot be taken` };
const lock = path.join(path.resolve(cwd, common.stdout.trim()), 'gstack-gate-disposition.lock');
const until = Date.now() + waitMs;
for (;;) {
try { fs.mkdirSync(lock); break; } catch (e: any) {
if (e.code !== 'EEXIST') return { code: 'APPROVAL_RECORD_WRITE_FAILED', message: `${lock}: ${e.code ?? e.message}` };
try { if (Date.now() - fs.statSync(lock).mtimeMs > 60_000) { fs.rmSync(lock, { recursive: true, force: true }); continue; } } catch { continue; }
if (Date.now() > until) return { code: 'APPROVAL_RECORD_WRITE_FAILED', message: `${lock} is held; another gate disposition or /ship preflight is writing (rerun in a moment)` };
Bun.sleepSync(100);
}
}
try { return fn(); } finally { fs.rmSync(lock, { recursive: true, force: true }); }
}
/** Append one disposition row under the lock, refused while any /ship run is open on its branch in any worktree (the check and the append are one step). */
export function recordGateDisposition(cwd: string, loc: StoreLocation, row: ApprovalRow): ReturnType<typeof appendRows> {
const signed = { ...row, digest: gateDispositionDigest(row as unknown as Record<string, unknown>) } as ApprovalRow;
if (!gateDispositions([signed], loc.branch).length) return { code: 'APPROVAL_RECORD_INVALID', message: 'the row would not count as a gate disposition (gstack-approvals dispositions would not list it: a 40-hex --head and one-line fields are required), so it would close nothing; nothing was written' };
const held = withGateLock(cwd, () => {
const open = openShipRunsOn(cwd, loc.branch);
if (open.length) return { code: 'APPROVAL_RECORD_INVALID' as const, message: `/ship run ${open.join('; /ship run ')} (branch ${loc.branch}): a gate disposition is the owner's, never the lane's own runner's; record it from the owner's session once no /ship run is open on the branch` };
if (open.length) return { code: 'APPROVAL_RECORD_INVALID' as const, message: `/ship run ${open.map(o => o.text).join('; /ship run ')} (branch ${loc.branch}): a gate disposition is the owner's, never the lane's own runner's; record it from the owner's session once no /ship run is open on the branch (${open.map(o => o.detail).filter(Boolean).join('; ')})` };
return appendRows(loc, [signed]);
});
return held;
+16 -4
View File
@@ -39,13 +39,17 @@ function entries(body: string): ReceiptRun[] {
return [...receiptRuns(body), ...(current && typeof current.head === 'string' ? [receiptRun(current)] : [])];
}
/**
* A run's stub and its own receipt at the same head count once (the newer entry stands); entries at different heads always count,
* so a run id reused across /ship runs never hides their rounds (gstack-evals#406: three receipts of ship-406 read rounds=1).
*/
export function prReviewHistory(body: string): PrReviewHistory {
const all = entries(body).filter(e => !e.mark);
const reviewed = new Map<string, ReceiptRun>();
const ordered: Array<ReceiptRun | string> = [];
all.forEach((e, i) => {
if (e.status || e.carry_kind || e.carried_from) { ordered.push(e); return; }
const key = e.run ? `run:${e.run}` : `#${i}`;
if (e.status === 'voided' || e.carry_kind || e.carried_from) { ordered.push(e); return; }
const key = e.run ? `run:${e.run}@${e.head}` : `#${i}`;
if (!reviewed.has(key)) ordered.push(key);
reviewed.set(key, e);
});
@@ -94,15 +98,23 @@ export const runStub = (o: { head: string; run: string; status: 'started' | 'voi
*/
export const stopMarker = (o: { head: string; tree: string; run: string }): ReceiptRun => ({ head: o.head, run: o.run, mark: 'stop', tree: o.tree });
export const grantMarker = (o: { head: string; run: string; grant: string }): ReceiptRun => ({ head: o.head, run: o.run, mark: 'grant', grant: o.grant });
/** gstack-ship-run abandon's entry (GST-3260): who ended a run that stopped working, and why, at the head it was abandoned on. */
export const abandonMarker = (o: { head: string; run: string; by: string; reason: string }): ReceiptRun => ({ head: o.head, run: o.run, mark: 'abandoned', by: o.by, reason: o.reason });
/** The newest receipt a run id already wrote, in the runs block or current: a run id names one /ship run (gstack-evals#406). */
export const receiptedRun = (body: string, run: string) => entries(body).filter(e => e.run === run && !e.mark && !e.status).at(-1);
/** The rows a /ship stop can follow: a full pass, a fix-check, or a Step 11 voice (#4591 stopped on its voices after a fix-check). */
const STOP_READERS = new Set(['review', 'review-fix-check', 'adversarial-review', 'codex-review']);
/**
* The stop record for the newest via:ship review row of this run (at or after since), or why none binds: the row must be complete,
* The stop record for the newest via:ship reading row of this run (at or after since): a full pass, a fix-check or a Step 11 voice,
* whichever read last, so the stop binds to the head that row read (#4591). Or why none binds: the row must be complete,
* bound to one tree from start to end (verified, or incomplete because it stopped) that is its commit's own tree, read on a clean
* worktree, and that commit must be HEAD or an ancestor of it. A read gstack can't tie to a commit gives a grant nothing to answer.
*/
export function stopFrom(rows: readonly Record<string, any>[], since: string, o: { treeOf: (commit: string) => string | undefined; onHead: (commit: string) => boolean }): { ok: true; head: string; tree: string } | { ok: false; why: string } {
const sinceMs = Date.parse(since);
const row = rows.filter(r => r && r.via === 'ship' && r.skill === 'review' && (!Number.isFinite(sinceMs) || Date.parse(r.timestamp) >= sinceMs)).at(-1);
const row = rows.filter(r => r && r.via === 'ship' && STOP_READERS.has(r.skill) && (!Number.isFinite(sinceMs) || Date.parse(r.timestamp) >= sinceMs)).at(-1);
if (!row) return { ok: false, why: `no via:ship review row at or after ${since}` };
const b = row.review_binding, head = typeof row.commit_full === 'string' ? row.commit_full.toLowerCase() : '';
if (row.completed !== true) return { ok: false, why: 'the stopping review is not complete (a reader is missing)' };
+10
View File
@@ -455,6 +455,16 @@ export const RELEASE_RESULT_CODES = {
summary: 'another /ship run already claimed this round grant, and a grant buys one round',
fix: 'the lane or its Captain records a new grant for the stop the PR is at now (gstack-ship-receipt stop prints the command)',
},
SHIP_RUN_ABANDON_REFUSED: {
anchor: 'ship-run-abandon-refused',
summary: 'gstack-ship-run abandon left the /ship run record as it was: the run beat in the last 60 minutes, the record names another run or already ended, or an unreadable record\'s digest did not match',
fix: 'read gstack-ship-run status: wait until the earliest abandon time it prints if the run may still be working, pass the run it names (an unreadable record: --run unknown --sha256 <its digest>), and leave an ended run alone',
},
SHIP_RUN_RECORD_UNREADABLE: {
anchor: 'ship-run-record-unreadable',
summary: 'this checkout\'s /ship run record (git dir gstack-ship-run) is neither a run record nor a run id, so every guard reads it as an open run',
fix: 'if no /ship run is working on this checkout, end it with the gstack-ship-run abandon --run unknown --sha256 <digest> command status prints, once',
},
GRANT_UNKNOWN: {
anchor: 'grant-unknown',
summary: 'the branch approval record holds no approved review_round_grant row with this id',
+6 -9
View File
@@ -5,11 +5,9 @@
* full sha of the stop head the owner ruled at; the row's `by` is the ruler and its `recorded_at` the time. A review-log field
* never makes one, so the lane that logged a finding cannot close it.
*/
import { spawnSync } from 'node:child_process';
import * as fs from 'node:fs';
import * as path from 'node:path';
import { locate, readRecord, type ApprovalRow, type Env } from './approval-record';
import { isSecurityFinding, REDACTED_FINDING, REDACTED_REASON } from './security-findings';
import { openRun, readRunRecord } from './ship-run-record';
export interface RuledNote { finding: string; head: string; by: string; reason: string; at: string; approval: string; relayed?: string; not_security?: true }
@@ -70,9 +68,8 @@ export const publicRuledNote = (n: RuledNote): RuledNote => !isSecurityFinding(n
/** The one-line form finish prints after `RULED_NOTE: ` and the PR body carries after `Ruled note: `, from publicRuledNote. */
export const ruledNoteText = (note: RuledNote) => { const n = publicRuledNote(note); return `${n.finding} at ${n.head.slice(0, 12)} ruled by ${n.by}${n.relayed ? ` (relayed from ${n.relayed})` : ''} at ${n.at}: ${n.reason} (approval ${n.approval})`; };
/** The /ship run open on this checkout (its marker in the git dir, which finish removes), if any. */
export function openShipRun(cwd: string): string | undefined {
const p = spawnSync('git', ['rev-parse', '--git-path', 'gstack-ship-run'], { cwd, encoding: 'utf8', timeout: 10_000 });
if (p.status !== 0 || !p.stdout.trim()) return undefined;
try { return fs.readFileSync(path.resolve(cwd, p.stdout.trim()), 'utf8').trim() || undefined; } catch { return undefined; }
}
/**
* The /ship run this checkout's run record holds open (open, stopped, legacy or unreadable), with the line a refusal prints: its state,
* beat_age and abandon command; none once the run finished or was abandoned (lib/ship-run-record.ts).
*/
export const openShipRun = (cwd: string) => openRun(readRunRecord(cwd));
-5
View File
@@ -28,11 +28,6 @@ const done = (r: { status: number | null; stdout?: string | Buffer | null; stder
export function git(cwd: string, args: string[], timeout = 120_000): Run {
return done(spawnSync('git', args, { cwd, encoding: 'utf8', timeout, maxBuffer: 64 * 1024 * 1024, env: { ...process.env, GIT_TERMINAL_PROMPT: '0' } }));
}
/** GST-1204: the /ship run that passed Steps 1-3 on this checkout, recorded in its own git dir (per worktree) until finish clears it; empty outside a checkout. */
export function shipRunMarker(cwd: string): string {
const p = git(cwd, ['rev-parse', '--git-path', 'gstack-ship-run']);
return p.status === 0 && p.stdout.trim() ? path.resolve(cwd, p.stdout.trim()) : '';
}
export function bin(cwd: string, name: string, args: string[], timeout = 600_000): Run {
return done(runScriptSync(path.join(BIN_DIR, name), args, { cwd, encoding: 'utf8', timeout, maxBuffer: 64 * 1024 * 1024 }));
}
+30 -24
View File
@@ -17,15 +17,16 @@ import { reviewPlanTimeoutMs } from './review-collect';
import { classifyDiff } from './review-depth';
import { wtreeFingerprint } from './script-invocation';
import { audit } from './ship-audit';
import { withGateLock } from './gate-dispositions';
import { bin, carryNoneLines, firstLine, flagReader, gh, git, hostedOrigin, laneConcurrency, laneLine, lanes, mappedLanes, recordCiTimeout, Report, runLanes, shipPolicy, shipRunMarker, short } from './ship-bin-common';
import { changeRunRecord, openRun, readRunRecord } from './ship-run-record';
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)
gstack-ship-preflight --base <base> [--lane <label>=<command>]... Steps 1-3; with lanes also Step 5
--run <id> the /ship run (SESSION_ID, or the driver's run dir name): once Steps 1-3 pass it is recorded in
this checkout's git dir and opened on its lease, and a later full preflight stops until finish
clears it or 120 minutes pass, because its merge would move the tree the run's readers diff (GST-1204)
--run <id> the /ship run (SESSION_ID, or the driver's run dir name): once Steps 1-3 pass it is opened in this
checkout's run record (git dir gstack-ship-run), and a later full preflight stops until finish, stop,
gstack-skill-end or gstack-ship-run abandon ends it, because its merge would move the tree the run's
readers diff (GST-1204, GST-3260); a --run the record already names stops too (one id, one run)
--run-uncarried-here run a lane origin/<base> maps in ship_lanes_from here when its CI carry refuses; without it any
refused carry stops with SHIP_LANE_NOT_CARRIED before any lane runs, naming the CI route (GST-3019, GST-3277)
gstack-ship-preflight --tests-only --base <base> --lane <label>=<command>... Step 5 only (after a repair)
@@ -57,22 +58,26 @@ const DIST = /(^|\/)(cmd\/[^/]+\/main\.go|bin\/[^/]+|Cargo\.toml|setup\.py|packa
const RUN_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
/**
* GST-1204: a full preflight merges the base, so it stops while the /ship run that already passed Steps 1-3 on this checkout
* is open: its marker is in the git dir (finish removes it) and its run is open on the checkout's own lease (gstack-lease
* open: GST-1205's released, 120-minute and dead-holder rules). The run's readers diff this tree. A different --run whose
* caller is the open run's holder (the harness behind preflight: the Claude Code session, or Capy's one capy-server) is a
* new /ship after one that stopped before finish, so it goes on; the same id, no --run, or another live holder's run stops.
* A --run is opened on the lease here, before the fetch, and one that cannot be is a STOP, never an unprotected run.
* GST-1204, GST-3260: a full preflight merges the base, so it stops while another /ship run's record on this checkout is open, legacy
* (a bare marker) or unreadable: that run's readers diff this tree, and no timer ends it (lib/ship-run-record.ts). A stopped, finished
* 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.
*/
function shipRunClear(cwd: string, base: string, run: string | undefined, r: Report): boolean {
const marker = shipRunMarker(cwd);
const open = marker && fs.existsSync(marker) ? fs.readFileSync(marker, 'utf8').trim() : '';
const lease = (verb: string, id: string, from = false) => bin(cwd, 'gstack-lease', [verb, '--root', cwd, '--run', id, ...(from ? ['--from', String(process.ppid)] : [])], 60_000);
if (RUN_ID.test(open) && lease('open', open).status === 0 && !(run && run !== open && lease('open', open, true).status === 0)) {
r.stop(`/ship run ${open} is open on this checkout and past its preflight (${marker}; open until its finish or for 120 minutes): a full preflight would merge origin/${base} into the tree its review readers diff; rerun Step 5 with --tests-only, or let that /ship finish; if it is no longer running, rm ${marker}, then rerun`);
const read = readRunRecord(cwd);
const open = openRun(read);
if (open && (open.state !== 'stopped' || !run)) {
r.stop(`/ship run ${open.run} is open on this checkout and past its preflight (${read.file}; ${open.detail}): a full preflight would merge origin/${base} into the tree its review readers diff; rerun Step 5 with --tests-only, or let that /ship finish`);
return false;
}
const touch = run ? lease('touch', run, true) : undefined;
if (run && read.kind === 'record' && read.record.run === run) {
const { state, ended_by } = read.record;
r.stop(`/ship run ${run} already ${state === 'stopped' ? 'stopped' : 'ended'} on this checkout (state ${state}${ended_by ? `, ended_by ${ended_by}` : ''}): a run id names one /ship run, and a full preflight under it would merge origin/${base} into the tree that run reviewed; rerun Step 5 with --tests-only, or start the new /ship with a new --run id (gstack-ship-run status)`);
return false;
}
const touch = run ? bin(cwd, 'gstack-lease', ['touch', '--root', cwd, '--run', run, '--from', String(process.ppid)], 60_000) : undefined;
if (!touch || touch.status === 0) return true;
r.stop(`cannot record /ship run ${run} on this checkout's lease (${firstLine(touch.stderr) || `gstack-lease touch exit ${touch.status}`}): unrecorded, a later full preflight could merge origin/${base} under this run's reviews; fix that, then rerun`);
return false;
@@ -107,8 +112,10 @@ function integrate(cwd: string, base: string, run: string | undefined, r: Report
// R51 per pull request (GST-2673): the rounds earlier heads spent, which Step 9 passes to every plan, and the review this
// head gets: a product change runs Steps 2-16, whose plan is the merge head's full review; a re-check never carries.
const hist = bin(cwd, 'gstack-ship-receipt', ['history', '--pr', n, '--base', base, ...(run ? ['--run', run] : [])], 120_000);
const histLines = hist.stdout.split('\n').filter(l => /^PR_REVIEW_(HISTORY|FLAGS|ROUTE): /.test(l));
const histLines = hist.stdout.split('\n').filter(l => /^PR_REVIEW_(HISTORY|FLAGS|ROUTE|RUN_USED): /.test(l));
histLines.forEach(l => r.add(l));
const reused = histLines.find(l => l.startsWith('PR_REVIEW_RUN_USED: '));
if (reused) { r.stop(`${reused.slice('PR_REVIEW_RUN_USED: '.length)} in PR #${n}'s body: a run id names one /ship run, so each head's rounds count once; start this /ship with a new --run id (gstack-evals#406)`); return false; }
if (hist.status !== 0 || !histLines.some(l => l.startsWith('PR_REVIEW_FLAGS: '))) r.add('PR_REVIEW_FLAGS: --prior-rounds 0').add(`PR_REVIEW_ROUTE: first (history unavailable: ${firstLine(hist.stderr) || `gstack-ship-receipt history exit ${hist.status}`}; the plan counts this run's rounds only)`);
if (line.startsWith('CARRY: would carry')) {
r.next(`carry route (Step 1.4): fix what the base merge broke (CHANGELOG, size caps), commit, gstack-ship-release push --branch ${branch} --early, gstack-ci-carry wait --base ${base} (CI_CARRY: none is not a stop), gstack-pregate --allow-repo-commands, then gstack-ship-receipt carry --pr ${n} --base ${base} --pregate .gstack/tmp/pregate.json`);
@@ -126,12 +133,11 @@ function integrate(cwd: string, base: string, run: string | undefined, r: Report
if (scopeError) r.add(`SCOPE: unknown (gstack-diff-scope origin/${base}: SCOPE_ERROR=${scopeError})`);
else r.add(`SCOPE: frontend=${/SCOPE_FRONTEND=true/.test(scope)}${/SCOPE_FRONTEND=true/.test(scope) ? ' (Step 9 runs the static design lite check only, no preview declared; mention /design-review when no design review exists)' : ''}`);
if (!merge(cwd, base, r)) return false;
const marker = run && shipRunMarker(cwd);
try {
const locked = marker ? withGateLock(cwd, () => fs.writeFileSync(marker, `${run}\n`)) : undefined;
if (locked && 'code' in locked) throw new Error(locked.message);
} catch (e) { r.stop(`cannot record /ship run ${run} in ${marker} (${firstLine((e as Error).message)}): the base is merged, but a later full preflight could merge again under this run's reviews; fix that, then rerun`); return false; }
return true;
if (!run) return true;
const opened = changeRunRecord(cwd, 'preflight', run, /^[1-9]\d*$/.test(n) ? { pr: Number(n) } : {});
if (opened.ok) 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;
}
/** The diff against origin/<base> must be about the PR's size: far more files (a stale or wrong base, HARN-15's 17,000-file review of main's history) or fewer (a fork's origin ahead of the PR's base, which would leave commits out of the gate scan) stops before any reader runs. Checked only when HEAD is the PR's pushed head. */
+2 -2
View File
@@ -133,8 +133,8 @@ export const RUNS_RE = /```gstack-receipt-runs[ \t]*\r?\n([\s\S]*?)\r?\n```[ \t]
* carries), `carry` for any other hop. status: a /ship run that
* started and wrote no receipt yet (`started`, its counters so far) or ended on an infrastructure failure (`voided`).
*/
export type ReceiptRun = Pick<ShipReceipt, 'head' | 'version' | 'gstack_version' | 'run' | 'review_loop' | 'review_loop_exception'> & { depth?: string; carried_from?: string; carry_kind?: 'carry' | 'recheck'; status?: 'started' | 'voided'; mark?: 'stop' | 'grant'; tree?: string; grant?: string };
/** The runs block keeps the newest RECEIPT_RUNS_KEPT run entries and every stop or grant marker (lib/pr-review-history.ts), in order. */
export type ReceiptRun = Pick<ShipReceipt, 'head' | 'version' | 'gstack_version' | 'run' | 'review_loop' | 'review_loop_exception'> & { depth?: string; carried_from?: string; carry_kind?: 'carry' | 'recheck'; status?: 'started' | 'voided'; mark?: 'stop' | 'grant' | 'abandoned'; tree?: string; grant?: string; by?: string; reason?: string };
/** The runs block keeps the newest RECEIPT_RUNS_KEPT run entries and every stop, grant or abandoned marker (lib/pr-review-history.ts), in order. */
export function keptRuns(runs: readonly ReceiptRun[]): ReceiptRun[] {
const keep = new Set(runs.filter(r => !r.mark).slice(-RECEIPT_RUNS_KEPT));
return runs.filter(r => r.mark || keep.has(r));
+17 -6
View File
@@ -16,7 +16,8 @@ import { versionAtRef } from './restamp';
import { classifyPath } from './review-depth';
import { matchesAny } from './ship-policy';
import { baseHolds, boundedPaths, comparePath, contextPacket, gateEditedPaths, isTestCode, PACKET_SECTION_CAP, readScopedReview, touchedPaths, type BoundedKind, type PatchSides } from './ship-patch';
import { heldBy } from './ship-receipt';
import { extractReceipt, heldBy, receiptRuns } from './ship-receipt';
import { finishRun, readRunRecord } from './ship-run-record';
import { locate, readRecord } from './approval-record';
import { mechanicalPaths, writeMechanicalRecord } from './ship-mechanical';
import { uidSidecars } from './ship-sidecar';
@@ -39,7 +40,7 @@ import { finishPlan, recordFinishPlan } from './plan-record';
import { PREPUSH_CHECK_IDS } from './pregate/index';
import { checkBranch, loadPlainTitlePolicy, type PlainFinding } from './plain-title';
import { buildRunCheck } from './pregate/run-check';
import { bin, carryLane, carryNoneLines, evidenceExempt, firstLine, flagReader, fragmentPath, gh, git, hostedOrigin, laneLine, lanes, mappedLanes, recordCiTimeout, releasePaths, Report, runLanes, sh, shipPolicy, shipRunMarker, short, stampedFiles } from './ship-bin-common';
import { bin, carryLane, carryNoneLines, evidenceExempt, firstLine, flagReader, fragmentPath, gh, git, hostedOrigin, laneLine, lanes, mappedLanes, recordCiTimeout, releasePaths, Report, runLanes, sh, shipPolicy, short, stampedFiles } from './ship-bin-common';
export const RELEASE_HELP = `gstack-ship-release — /ship Steps 12 and 15-17 (ship/SKILL.md)
@@ -570,16 +571,26 @@ function docsFresh(cwd: string, base: string, postFile: string, moved: readonly
return true;
}
/** Steps 15-16; once they pass, the /ship run's preflight marker is cleared, so a full preflight may merge the base again (GST-1204). */
/**
* Steps 15-16; once they pass, the /ship run's record is removed, so a full preflight may merge the base again (GST-1204). Only the
* record of a run the open PR's body names (a stub, stop, grant or receipt entry) is removed, or any run's when no PR is open: a late
* finish never removes another run's record (GST-3260); gh failing keeps it.
*/
export async function finish(argv: readonly string[], cwd: string): Promise<Report> {
const { flag } = flagReader(argv);
const plan = finishPlan(cwd, flag('--base')!, flag('--plan'));
if (plan.failure) return new Report().add(plan.line!).stop(`${plan.failure.message} (${plan.failure.code}); fix: ${plan.failure.fix}`);
const r = await finishStages(argv, cwd);
if (plan.line) r.lines.unshift(plan.line);
if (r.exit === 0) recordFinishPlan(cwd, flag('--plan') ? plan.record : undefined);
const marker = r.exit === 0 && shipRunMarker(cwd);
if (marker) fs.rmSync(marker, { force: true });
if (r.exit !== 0) return r;
recordFinishPlan(cwd, flag('--plan') ? plan.record : undefined);
if (readRunRecord(cwd).kind === 'none') return r;
const branch = git(cwd, ['branch', '--show-current']).stdout.trim();
const listed = hostedOrigin(cwd) && branch ? gh(cwd, ['pr', 'list', '--head', branch, '--state', 'open', '--json', 'body', '--jq', '.[0].body // empty']) : undefined;
const body = listed?.status === 0 ? listed.stdout.trim() : '';
const ended = listed && listed.status !== 0 ? { line: `RUN_RECORD: kept (gh pr list failed: ${firstLine(listed.stderr)}; finish removes a run record only when the PR body names its run)` }
: finishRun(cwd, body ? [...receiptRuns(body), extractReceipt(body).receipt].flatMap(e => typeof e?.run === 'string' ? [e.run] : []) : null);
if (ended.line) r.add(ended.line);
return r;
}
+197
View File
@@ -0,0 +1,197 @@
/**
* 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:
* 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.
*/
import { createHash } from 'node:crypto';
import * as fs from 'node:fs';
import * as path from 'node:path';
import type { RecordError } from './approval-record';
import { spawnSync } from './spawn-sync';
export type RunState = 'open' | 'stopped' | 'finished' | 'abandoned';
export interface RunRecord {
v: 1; run: string; state: RunState; pr?: number; head: string; started_at: string; beat_at: string;
stop?: { head: string; tree: string };
claim?: { grant: string; stop_run?: string; stop_head: string; findings: string[] };
ended_by?: string; reason?: string;
}
export type RunRead =
| { kind: 'none'; file: string }
| { 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';
type From = RunState | 'none' | 'legacy' | 'unreadable';
export const RUN_ID = /^[A-Za-z0-9][\w.:-]{0,127}$/;
/** A run that beat this recently is working: abandon refuses it. */
export const ABANDON_AFTER_MS = 60 * 60_000;
const STATES: readonly RunState[] = ['open', 'stopped', 'finished', 'abandoned'];
const SHA = /^[0-9a-f]{40,64}$/;
/**
* The state each command may change and the state it leaves (`kept`: the state stays, a legacy marker becomes open). Every command but
* preflight and abandon changes only its own run's record (a legacy marker whose text is the run counts, and is upgraded); preflight
* replaces another run's record only once that run stopped or ended, never one naming its own id (a run id is one /ship run).
*/
export const RUN_TRANSITIONS: Readonly<Record<RunCommand, { from: readonly From[]; to: RunState | 'kept' | 'removed' }>> = {
preflight: { from: ['none', 'stopped', 'finished', 'abandoned'], to: 'open' },
beat: { from: ['open', 'stopped', 'legacy'], to: 'kept' },
stop: { from: ['open', 'stopped', 'legacy'], to: 'stopped' },
claim: { from: ['open', 'stopped', 'legacy'], to: 'open' },
'skill-end': { from: ['open', 'stopped', 'legacy'], to: 'finished' },
finish: { from: ['open', 'stopped', 'legacy'], to: 'removed' },
abandon: { from: ['open', 'stopped', 'legacy', 'unreadable'], to: 'abandoned' },
};
const gitOut = (cwd: string, args: string[]) => {
const r = spawnSync('git', args, { cwd, encoding: 'utf8', timeout: 10_000 });
return r.status === 0 ? (r.stdout ?? '').trim() : '';
};
/** The record's path in this checkout's git dir, or '' outside a checkout. */
export function runRecordPath(cwd: string): string {
const p = gitOut(cwd, ['rev-parse', '--git-path', 'gstack-ship-run']);
return p ? path.resolve(cwd, p) : '';
}
function invalid(o: any): string | null {
if (!o || typeof o !== 'object' || Array.isArray(o) || o.v !== 1) return 'not a v1 run record';
if (typeof o.run !== 'string' || !RUN_ID.test(o.run)) return 'its run is not a run id';
if (!STATES.includes(o.state)) return `its state ${String(o.state)} is not open, stopped, finished or abandoned`;
if (!SHA.test(String(o.head)) || !Number.isFinite(Date.parse(o.started_at)) || !Number.isFinite(Date.parse(o.beat_at))) return 'head, started_at or beat_at is missing or malformed';
if (o.pr !== undefined && !(Number.isInteger(o.pr) && o.pr > 0)) return 'pr is not a PR number';
if (o.stop !== undefined && !(SHA.test(String(o.stop?.head)) && SHA.test(String(o.stop?.tree)))) return 'stop is not {head, tree}';
if (o.claim !== undefined && !(typeof o.claim?.grant === 'string' && SHA.test(String(o.claim.stop_head)) && Array.isArray(o.claim.findings))) return 'claim is not {grant, stop_head, findings}';
return null;
}
export function readRunRecord(cwd: string, file = runRecordPath(cwd)): RunRead {
if (!file) return { kind: 'none', file };
let bytes: Buffer;
try { bytes = fs.readFileSync(file); } catch (e: any) { return e?.code === 'ENOENT' ? { kind: 'none', file } : { kind: 'unreadable', file, why: `cannot read it (${e?.code ?? e?.message})` }; }
const sha256 = createHash('sha256').update(bytes).digest('hex');
const text = bytes.toString('utf8').trim();
if (!text.startsWith('{')) return RUN_ID.test(text) ? { kind: 'legacy', file, run: text } : { kind: 'unreadable', file, why: 'neither a run record nor a run id', sha256 };
let o: unknown;
try { o = JSON.parse(text); } catch { return { kind: 'unreadable', file, why: 'not valid JSON', sha256 }; }
const why = invalid(o);
return why ? { kind: 'unreadable', file, why, sha256 } : { kind: 'record', file, record: o as RunRecord };
}
/** The run a record names: its own, a legacy marker's text, or none for an unreadable file. */
export const recordRun = (read: RunRead) => read.kind === 'record' ? read.record.run : read.kind === 'legacy' ? read.run : undefined;
export interface OpenRun { run: string; state: RunState | 'legacy' | 'unreadable'; stop?: RunRecord['stop']; claim?: RunRecord['claim']; detail: string; line: string }
/**
* The run every guard must respect: an open, stopped, legacy or unreadable record; none once it finished or was abandoned. `detail` is what
* each refusal prints: the state, beat_age, the earliest time abandon takes it and the exact command.
*/
export function openRun(read: RunRead, now = Date.now()): OpenRun | undefined {
if (read.kind === 'none' || (read.kind === 'record' && (read.record.state === 'finished' || read.record.state === 'abandoned'))) return undefined;
const run = recordRun(read) ?? 'unknown';
const state = read.kind === 'record' ? read.record.state : read.kind;
const beat = read.kind === 'record' ? Date.parse(read.record.beat_at) : NaN;
const age = Number.isFinite(beat) ? `${Math.max(0, Math.floor((now - beat) / 60_000))}m` : 'unknown';
const from = new Date(Number.isFinite(beat) ? Math.max(now, beat + ABANDON_AFTER_MS) : now).toISOString();
const command = read.kind === 'unreadable'
? `gstack-ship-run abandon --run unknown --sha256 ${read.sha256 ?? '<its digest: the file is unreadable, so fix its permissions first>'} --by <lane or Captain> --reason "<one line>"`
: `gstack-ship-run abandon --run ${run} --by <lane or Captain> --reason "<one line>"`;
const detail = `state ${state}, beat_age ${age}; ${read.kind === 'unreadable' ? `${read.file} ${read.why}; ` : ''}once it has stopped working, end it from ${from} with ${command}`;
return { run, state, ...(read.kind === 'record' && read.record.stop ? { stop: read.record.stop } : {}), ...(read.kind === 'record' && read.record.claim ? { claim: read.record.claim } : {}), detail, line: `/ship run ${run} is open on this checkout (${detail})` };
}
/** Run `fn` holding the repository's gate-disposition lock (a directory in the git common dir; one older than a minute is stale). */
export function withGateLock<T>(cwd: string, fn: () => T, waitMs = 15_000): T | RecordError {
const common = spawnSync('git', ['rev-parse', '--git-common-dir'], { cwd, encoding: 'utf8', timeout: 10_000 });
if (common.status !== 0 || !common.stdout.trim()) return { code: 'APPROVAL_RECORD_WRITE_FAILED', message: `no git common dir at ${cwd}, so the gate-disposition lock cannot be taken` };
const lock = path.join(path.resolve(cwd, common.stdout.trim()), 'gstack-gate-disposition.lock');
const until = Date.now() + waitMs;
for (;;) {
try { fs.mkdirSync(lock); break; } catch (e: any) {
if (e.code !== 'EEXIST') return { code: 'APPROVAL_RECORD_WRITE_FAILED', message: `${lock}: ${e.code ?? e.message}` };
try { if (Date.now() - fs.statSync(lock).mtimeMs > 60_000) { fs.rmSync(lock, { recursive: true, force: true }); continue; } } catch { continue; }
if (Date.now() > until) return { code: 'APPROVAL_RECORD_WRITE_FAILED', message: `${lock} is held; another gate disposition or /ship preflight is writing (rerun in a moment)` };
Bun.sleepSync(100);
}
}
try { return fn(); } finally { fs.rmSync(lock, { recursive: true, force: true }); }
}
export type RunChange = { ok: true; record: RunRecord | null; from: From } | { ok: false; why: string };
/**
* Apply one command to this checkout's record under the gate lock: re-read it, check RUN_TRANSITIONS and whose run it is, run the
* caller's own `check` on what it read, then write a temp file and rename it over the record (finish removes it). A beat touches only
* beat_at. Nothing is written when any check fails.
*/
export function changeRunRecord(cwd: string, cmd: RunCommand, run: string, patch: Partial<RunRecord> = {}, o: { waitMs?: number; check?: (read: RunRead) => string | null } = {}): RunChange {
const held = withGateLock(cwd, (): RunChange => { try {
const read = readRunRecord(cwd);
if (!read.file) return { ok: false, why: 'not inside a git checkout' };
const from: From = read.kind === 'record' ? read.record.state : read.kind;
const owner = recordRun(read);
if (!RUN_TRANSITIONS[cmd].from.includes(from)) return { ok: false, why: from === 'none' ? `${cmd} needs a run record, and this checkout has none` : `${cmd} cannot change the ${from} record${owner ? ` of run ${owner}` : ''}` };
if (cmd === 'preflight' && owner === run) return { ok: false, why: `the record already names run ${run} (${from}): a run id is one /ship run` };
if (cmd !== 'preflight' && cmd !== 'abandon' && owner !== run) return { ok: false, why: `the record is run ${owner ?? 'unknown'}'s, not ${run}'s` };
const refused = o.check?.(read);
if (refused) return { ok: false, why: refused };
if (RUN_TRANSITIONS[cmd].to === 'removed') { fs.rmSync(read.file, { force: true }); return { ok: true, record: null, from }; }
const now = new Date().toISOString();
const prior = read.kind === 'record' && cmd !== 'preflight' ? read.record : undefined;
const to = RUN_TRANSITIONS[cmd].to;
const head = prior?.head ?? gitOut(cwd, ['rev-parse', 'HEAD']).toLowerCase();
if (!SHA.test(head)) return { ok: false, why: 'HEAD does not resolve to a commit' };
const record: RunRecord = cmd === 'beat' && prior ? { ...prior, beat_at: now }
: { ...prior, v: 1, run: owner && cmd !== 'preflight' ? owner : run, head, started_at: prior?.started_at ?? now, ...patch, state: to === 'kept' ? prior?.state ?? 'open' : to as RunState, beat_at: now };
const tmp = `${read.file}.${process.pid}.tmp`;
fs.writeFileSync(tmp, JSON.stringify(record) + '\n');
fs.renameSync(tmp, read.file);
return { ok: true, record, from };
} catch (e) { return { ok: false, why: (e as Error).message.split('\n')[0]! }; } }, o.waitMs);
return 'code' in held ? { ok: false, why: held.message } : held;
}
/**
* gstack-review-log --start/--finish beat the run that owns this checkout's open or stopped record. The token cap's budget marker
* names a budget run id (lib/ship-budget.ts), never the /ship run id, so it cannot pick the run. A beat never fails the review log.
*/
export function beatFromReview(cwd: string): void {
try {
const read = readRunRecord(cwd);
if (read.kind !== 'record' || !openRun(read)) return;
changeRunRecord(cwd, 'beat', read.record.run, {}, { waitMs: 2_000 });
} catch { /* a beat is advisory */ }
}
/**
* Finish's end of the run (amendment F): remove the record only when the PR body names its run (a stub, stop, grant or receipt entry),
* or when there is no PR body to read (`named` null), so a late finish never removes another run's record. An unreadable record stays.
*/
export function finishRun(cwd: string, named: readonly string[] | null): { removed: boolean; line?: string } {
const read = readRunRecord(cwd);
const owner = recordRun(read);
if (read.kind === 'unreadable') return { removed: false, line: `RUN_RECORD: kept (${read.file} ${read.why}; gstack-ship-run status prints the abandon command)` };
if (!owner || (read.kind === 'record' && !openRun(read))) return { removed: false };
if (named && !named.includes(owner)) return { removed: false, line: `RUN_RECORD: kept (the PR body names no entry of run ${owner}, so this finish is not its run's; gstack-ship-run status)` };
const done = changeRunRecord(cwd, 'finish', owner);
return done.ok ? { removed: true } : { removed: false, line: `RUN_RECORD: kept (${done.why})` };
}
/**
* gstack-ship-run abandon's checks on what it read: never as gstack, the run named exactly (an unreadable record as `unknown` with its
* digest), and never a record whose beat_at is under ABANDON_AFTER_MS old. A legacy marker or an unreadable record has no beat, so any age.
*/
export function abandonRefusal(read: RunRead, run: string, sha256: string | undefined, now = Date.now()): string | null {
if (read.kind === 'unreadable') return run !== 'unknown' ? `the record is unreadable (${read.why}): pass --run unknown --sha256 <its digest from gstack-ship-run status>`
: !read.sha256 || sha256 !== read.sha256 ? `--sha256 does not match the unreadable record's digest ${read.sha256 ?? '(unreadable bytes)'}: it changed since you read it, or the digest is wrong` : null;
if (recordRun(read) !== run) return `the record names run ${recordRun(read) ?? 'none'}, not ${run}`;
if (read.kind !== 'record') return null;
const beat = Date.parse(read.record.beat_at);
return now - beat < ABANDON_AFTER_MS ? `run ${run} beat ${Math.floor((now - beat) / 60_000)}m ago (state ${read.record.state}, beat_age ${Math.floor((now - beat) / 60_000)}m; the earliest abandon is ${new Date(beat + ABANDON_AFTER_MS).toISOString()}): a run that beat in the last 60 minutes is still working` : null;
}
+4
View File
@@ -464,6 +464,10 @@ export const KNOWN_WINDOWS_INCOMPATIBLE: Array<{ file: string; reason: string }>
file: 'test/capy-host-publish.test.ts',
reason: 'drives bin/gstack-ship-receipt, gstack-post, gstack-approvals and gstack-review-log (shebangs) plus a #!/bin/sh gh shim through test/helpers/ship-bin-fixture.ts and restamp-fixture.ts, like test/round-cap-granted-stop.test.ts',
},
{
file: 'test/ship-run-record.test.ts',
reason: 'drives bin/gstack-ship-preflight, gstack-ship-run, gstack-ship-receipt, gstack-approvals, gstack-review-log, gstack-lease and gstack-skill-end (shebangs) through test/helpers/ship-bin-fixture.ts like test/round-cap-granted-stop.test.ts; a bin spawn fails on windows-latest the same way (first-bin-spawn failure class of test/ship-uid-sidecar.test.ts)',
},
{
file: 'test/round-cap-granted-stop.test.ts',
reason: 'drives bin/gstack-ship-receipt, gstack-approvals, gstack-review-plan, gstack-review-log, gstack-review-scope and gstack-ship-release (shebangs) through test/helpers/ship-bin-fixture.ts like test/ship-finish-fixed-links.test.ts; a bin spawn fails on windows-latest the same way (first-bin-spawn failure class of test/ship-uid-sidecar.test.ts)',
+1
View File
@@ -332,6 +332,7 @@ describe('parity with the measured prototype', () => {
'lib/ship-receipt-prose.ts': 'bin/gstack-ship-receipt imports it (read --check-prose), so it reaches every consumer of the receipt binary',
'lib/ship-clock.ts': 'G2: bin/gstack-ship-receipt (write --budget-record), lib/ship-budget-cli.ts (note, resume) and lib/ship-phase.ts import it, so it reaches every consumer of the receipt and budget binaries',
'scripts/resolvers/load-injection.ts': 'GST-3157: the preamble resolvers (generate-preamble-bash, preamble-hoist) and scripts/gen-skill-docs.ts import it, so it reaches every consumer of the generated skills',
'lib/ship-run-record.ts': 'GST-3260: lib/ruled-notes.ts, lib/gate-dispositions.ts, the preflight, release and receipt libraries and bins, gstack-review-log and gstack-skill-end read or beat the run record, so it reaches every consumer of those guards',
'lib/default-base.ts': 'GST-511/GST-774: lib/ship-policy.ts (resolveBaseBranch), lib/gate-diff/git.ts, lib/pregate/context.ts, lib/ship-receipt-depth.ts and the review-plan, gate-diff, pregate, docs-candidate and diff-scope bins import or run it, so it reaches every consumer of those readers',
};
+1
View File
@@ -133,6 +133,7 @@
{ "file": "lib/evidence-bundle.ts", "movedFrom": "(new: portable evidence bundle, execution identity and ancestor check, C3/C7)" },
{ "file": "lib/tree-receipt.ts", "movedFrom": "(new: tree equality modulo stamps and per-gate reuse, C3)" },
{ "file": "lib/ship-receipt.ts", "movedFrom": "(new: the ship receipt block, PR-body placement and adoption census, C5)" },
{ "file": "lib/ship-run-record.ts", "movedFrom": "(new: the /ship run record that replaces the bare run marker, its transition table and the gate lock, GST-3260)" },
{ "file": "lib/ship-receipt-docs.ts", "movedFrom": "(new: the receipt's docs record, the owner exception and the policy doc caps, kept out of lib/ship-receipt.ts; convergence lane PR 2)" },
{ "file": "lib/spend-ledger.ts", "movedFrom": "(new: the spend cap admission ledger reserve/settle/release and the file lock, B2)" },
{ "file": "lib/outside-voice-runner.ts", "movedFrom": "(new: the outside-voice adapter interface, model families and runner selection, B3)" },
-1
View File
@@ -58,7 +58,6 @@
"lib/repo-state-clean.ts",
"lib/review-selection.ts",
"lib/review-sweep.ts",
"lib/ruled-notes.ts",
"lib/ship-clock.ts",
"lib/stamp-only.ts",
"make-pdf/src/pdftotext.ts",
+4 -2
View File
@@ -42,10 +42,12 @@ describe('prReviewHistory', () => {
expect(prReviewHistory(body)).toMatchObject({ rounds: 1, full: 1, rechecks: 1, runs: 1, heads: 3 });
});
test('the same run written twice counts once', () => {
test('the same run written twice at one head counts once; a run id reused at another head counts again (gstack-evals#406)', () => {
let body = placeReceipt('', receipt(sha('a'), { passes: 1, rounds: 1 }, { run: 'r1' }));
body = placeReceipt(body, receipt(sha('b'), { passes: 1, rounds: 1 }, { run: 'r1' }));
body = placeReceipt(body, receipt(sha('a'), { passes: 1, rounds: 1, deferred: 1 }, { run: 'r1' }));
expect(prReviewHistory(body)).toMatchObject({ rounds: 1, runs: 1 });
body = placeReceipt(body, receipt(sha('b'), { passes: 1, rounds: 1 }, { run: 'r1' }));
expect(prReviewHistory(body)).toMatchObject({ rounds: 2, runs: 2 });
});
test('a started stub counts its rounds so far until its run writes a receipt, which replaces it', () => {
+3 -2
View File
@@ -129,9 +129,10 @@ describe('the stop record binds only a review gstack can tie to one commit (stop
expect(from([{ ...bound, completed: false }]).ok).toBe(false);
expect(from([{ ...bound, commit_full: H }]).ok).toBe(false);
});
test('S5: a non-ship row or a fix-check row is not the stopping review; an earlier run\'s row is out of range', () => {
test('S5: a non-ship row is not the stopping review; a later fix-check row is, and must bind (#4591); an earlier run\'s row is out of range', () => {
expect(from([bound, { ...bound, via: 'manual', commit_full: H }])).toMatchObject({ ok: true, head: S });
expect(from([bound, { ...bound, skill: 'review-fix-check', commit_full: H }])).toMatchObject({ ok: true, head: S });
expect(from([bound, { ...bound, skill: 'review-fix-check', commit_full: H }]).ok).toBe(false);
expect(from([{ ...bound, commit_full: H }, { ...bound, skill: 'review-fix-check' }])).toMatchObject({ ok: true, head: S });
expect(from([{ ...bound, timestamp: '2026-11-17T00:00:00Z' }]).ok).toBe(false);
});
});
+4 -1
View File
@@ -210,12 +210,15 @@ describe('finish with a gate disposition (GST-2491)', () => {
describe('a disposition the lane makes for itself is refused or ignored (GST-2491)', () => {
const store = (f: ShipFx) => locate({ cwd: f.work, env: { ...process.env, GSTACK_STATE_ROOT: f.state, GSTACK_HOME: f.state, GSTACK_APPROVALS_MIRROR: '0' }, branch: 'feat' }) as StoreLocation;
test('a recorder name is trimmed and one line, and a parked run whose lease ended no longer refuses', () => {
test('a recorder name is trimmed and one line, and a parked run refuses until it is abandoned', () => {
const { f, head } = firstPass();
const lines = gate(f, GATE, head, { by: 'Founderstar\nCaptain' });
expect([lines.status, lines.stderr]).toEqual([EXIT.usage, expect.stringContaining('one line')]);
const marker = path.resolve(f.work, f.git('rev-parse', '--git-path', 'gstack-ship-run').stdout.trim());
fs.writeFileSync(marker, 'ship-906-parked\n');
expect(gate(f, GATE, head, { by: ` ${BY} ` }).stderr).toContain('ship-906-parked: state legacy, beat_age unknown');
const abandoned = run(f, 'gstack-ship-run', ['abandon', '--run', 'ship-906-parked', '--by', BY, '--reason', 'parked before finish']);
expect(abandoned.status, abandoned.stderr).toBe(0);
const spaced = gate(f, GATE, head, { by: ` ${BY} ` });
expect(spaced.status, spaced.stderr).toBe(0);
expect(run(f, 'gstack-approvals', ['dispositions']).stdout).toContain(`by ${BY} at`);
+13 -7
View File
@@ -453,7 +453,6 @@ describe('gstack-ship-preflight Step 5 pregate: head policy and timeout_s (GST-4
describe('gstack-ship-preflight during an open /ship run (GST-1204)', () => {
const CHECKOUT = { GSTACK_LEASE_DIR: '' };
const leaseFile = (f: ShipFx) => path.join(f.work, '.git', 'gstack-leases', String(process.pid));
const wtree = (f: ShipFx) => f.run(path.join(path.dirname(RELEASE), 'gstack-wtree'), [], CHECKOUT).stdout.trim();
/** Steps 12-16 in the fixture: the version bump, the docs snapshot and finish (the step that ends the run's hold on the base merge). */
const finish = (f: ShipFx) => {
@@ -469,9 +468,9 @@ describe('gstack-ship-preflight during an open /ship run (GST-1204)', () => {
const tracked = f.git('rev-parse', 'origin/main').stdout.trim();
const r = f.run(PREFLIGHT, args, CHECKOUT);
expect(r.status).toBe(3);
expect(r.stdout).toContain(`STOP: /ship run ${run} is open on this checkout and past its preflight (`);
expect(r.stdout).toMatch(new RegExp(`STOP: /ship run ${run} (is open on this checkout and past its preflight \\(\\S+gstack-ship-run; state |already ended on this checkout \\(state finished)`));
expect(r.stdout).toContain('rerun Step 5 with --tests-only');
expect(r.stdout).toMatch(/if it is no longer running, rm \S+gstack-ship-run, then rerun/);
expect(r.stdout).toMatch(new RegExp(`gstack-ship-run abandon --run ${run} --by |start the new /ship with a new --run id`));
expect(r.stdout).not.toContain('MERGE:');
expect(f.git('rev-parse', 'HEAD').stdout.trim()).toBe(head);
expect(f.git('rev-parse', 'origin/main').stdout.trim()).toBe(tracked);
@@ -508,12 +507,19 @@ describe('gstack-ship-preflight during an open /ship run (GST-1204)', () => {
expect(lineOf(repair.stdout, 'LANE')).toMatch(/^LANE: tests pass exit=0 tests_ran=3/);
});
// Value: protects=finish ends the run's hold, and a run past the 120-minute window (GST-1205's fresh rule) no longer blocks the next preflight;
// fails_when=a marker left by an earlier /ship refuses every later preflight on the checkout; why_new=GST-1204 negative control; seam=finish clears the marker, gstack-lease fresh; no_claim=dead or reused holders, covered in test/gstack-lease.test.ts
test('a finished or aged-out /ship run does not block a full preflight', () => {
// Value: protects=finish ends the run's hold, and a run abandoned after 60 minutes without a beat no longer blocks the next preflight (GST-3260: no timer
// ends a run, so the 120-minute lease no longer does); fails_when=a record left by an earlier /ship refuses every later preflight on the checkout;
// why_new=GST-1204 negative control; seam=finish removes the record, gstack-ship-run abandon ends it; no_claim=dead or reused holders
test('a finished or abandoned /ship run does not block a full preflight', () => {
const record = (f: ShipFx) => path.join(f.work, '.git', 'gstack-ship-run');
const ends: Record<string, (f: ShipFx) => void> = {
finished: finish,
'aged out': f => fs.writeFileSync(leaseFile(f), fs.readFileSync(leaseFile(f), 'utf8').replace(/^(run \S+ )(\d+)$/m, (_, p, t) => `${p}${Number(t) - 7300}`)),
abandoned: f => {
const r = JSON.parse(fs.readFileSync(record(f), 'utf8'));
fs.writeFileSync(record(f), JSON.stringify({ ...r, beat_at: new Date(Date.now() - 61 * 60_000).toISOString() }) + '\n');
const end = f.run(path.join(path.dirname(PREFLIGHT), 'gstack-ship-run'), ['abandon', '--run', 'ship-run-7', '--by', 'Captain GStack Minder (GSTA-36)', '--reason', 'the run stopped answering'], CHECKOUT);
expect(end.status, end.stderr).toBe(0);
},
};
for (const [why, end] of Object.entries(ends)) {
const f = fx();
+356
View File
@@ -0,0 +1,356 @@
/**
* GST-3260 PR 1: the /ship run record replaces the bare run marker. A run is open until a gstack command ends it (finish,
* stop, gstack-skill-end, or gstack-ship-run abandon), never because a lease line aged out or another run's touch pruned
* it (probe 002). A stopped run records only the fix-check grant for its own stop; a bare marker reads as legacy and an
* unreadable record fails closed, and both are ended with one recorded abandon. Also: a stop binds to the head its
* stopping row read (#4591), and the round history counts a reused run id once per head (gstack-evals#406).
*/
import { afterEach, describe, expect, setDefaultTimeout, test } from 'bun:test';
import { spawn } from 'node:child_process';
import * as fs from 'node:fs';
import * as path from 'node:path';
import { placeRunEntry, prReviewHistory, runStub, stopFrom } from '../lib/pr-review-history';
import { receiptRuns } from '../lib/ship-receipt';
import { lineOf, PREFLIGHT, shipFixture, type ShipFx } from './helpers/ship-bin-fixture';
setDefaultTimeout(120_000);
const BIN = path.dirname(PREFLIGHT);
const CHECKOUT = { GSTACK_LEASE_DIR: '', GSTACK_APPROVALS_MIRROR: '0' };
const CAPTAIN = 'Captain GStack Minder (GSTA-36)';
const fixtures: ShipFx[] = [];
const fx = (...a: Parameters<typeof shipFixture>) => { const f = shipFixture(...a); fixtures.push(f); return f; };
afterEach(() => { while (fixtures.length) fixtures.pop()!.cleanup(); });
const recordFile = (f: ShipFx) => path.resolve(f.work, f.git('rev-parse', '--git-path', 'gstack-ship-run').stdout.trim());
const record = (f: ShipFx) => { const t = fs.readFileSync(recordFile(f), 'utf8'); return t.trim().startsWith('{') ? JSON.parse(t) : { legacy: t.trim() }; };
/** Moves the record's clock back, as if the run started and last beat `minutes` ago. */
const age = (f: ShipFx, minutes: number) => {
const t = fs.readFileSync(recordFile(f), 'utf8');
if (!t.trim().startsWith('{')) return;
const back = (iso: string) => new Date(Date.parse(iso) - minutes * 60_000).toISOString();
const r = JSON.parse(t);
fs.writeFileSync(recordFile(f), JSON.stringify({ ...r, started_at: back(r.started_at), beat_at: back(r.beat_at) }) + '\n');
};
const run = (f: ShipFx, bin: string, args: string[]) => f.run(path.join(BIN, bin), args, CHECKOUT);
const preflight = (f: ShipFx, id?: string) => f.run(PREFLIGHT, ['--base', 'main', ...(id ? ['--run', id] : [])], CHECKOUT);
const head = (f: ShipFx) => f.git('rev-parse', 'HEAD').stdout.trim();
const grant = (f: ShipFx, kind: 'extra-round' | 'fix-check', extra: string[] = [], at = head(f)) =>
run(f, 'gstack-approvals', ['round-grant', '--pr', '7', '--head', at, '--kind', kind, ...(kind === 'fix-check' && !extra.includes('--stop-run') ? ['--stop-run', 'ro', '--findings', 'p1/outside-voice#1'] : []), ...extra, '--reason', 'fixable blocker', '--by', CAPTAIN]);
/** A review row that stopped on one open blocker, logged through gstack-review-log on the committed tree. */
const logStoppingReview = (f: ShipFx) => {
const start = run(f, 'gstack-review-log', ['--start', 'review']);
expect(start.status, start.stderr).toBe(0);
const logged = run(f, 'gstack-review-log', [JSON.stringify({ skill: 'review', timestamp: new Date().toISOString(), via: 'ship', pass: 1, review_scope: 'frozen', completed: true, converged: false, status: 'issues_found', issues_found: 1, critical: 1, informational: 0, findings: [{ fingerprint: 'src/x.ts:1:outside-voice', severity: 'CRITICAL', action: 'open', blocking: true, ledger_id: 'p1/outside-voice#1', raised_by: 'outside-voice' }] }), '--finish', start.stdout.trim()]);
expect(logged.status, logged.stderr).toBe(0);
};
describe('a /ship run stays open until a gstack command ends it (GST-3260)', () => {
// Value: protects=probe 002, a live run whose lease line another run's touch pruned after 120 minutes still blocks a full
// preflight; fails_when=preflight reads gstack-lease open and merges the base under a live run's readers; seam=the run record
test('probe 002: a live run past 120 minutes, after another run\'s lease touch, still reads open', () => {
const f = fx();
expect(preflight(f, 'r1').status).toBe(0);
const lease = path.join(f.work, '.git', 'gstack-leases', String(process.pid));
fs.writeFileSync(lease, fs.readFileSync(lease, 'utf8').replace(/^(run r1 )(\d+)$/m, (_, p, t) => `${p}${Number(t) - 10800}`));
const touch = f.run(path.join(BIN, 'gstack-lease'), ['touch', '--root', f.work, '--pid', String(process.pid), '--run', 'r2'], CHECKOUT);
expect(touch.status, touch.stderr).toBe(0);
expect(fs.readFileSync(lease, 'utf8')).not.toMatch(/^run r1 /m);
age(f, 180);
f.advanceBase({ 'docs/new.md': '# new\n' });
const again = preflight(f, 'r3');
expect(again.status).toBe(3);
expect(again.stdout).toContain('STOP: /ship run r1 is open on this checkout and past its preflight (');
expect(again.stdout).toContain('state open, beat_age 180m');
expect(again.stdout).not.toContain('MERGE:');
expect(run(f, 'gstack-ship-run', ['status']).stdout).toMatch(/^RUN_STATE: run=r1 state=open beat_age=180m /m);
});
// Value: protects=a bare marker an older gstack left (a run that died) refuses grants with its state and the way out, and one
// recorded abandon ends it, with a mark in the PR body; fails_when=the refusal says nothing about how to end the run, or
// only rm clears it; seam=gstack-approvals round-grant, gstack-ship-run abandon, gstack-ship-receipt abandoned
test('a stale bare marker reads legacy: grants refuse with the abandon command, and abandon ends it at any age', () => {
const f = fx();
fs.writeFileSync(recordFile(f), 'ship-stale-1\n');
const refused = grant(f, 'extra-round');
expect(refused.status).toBe(2);
expect(refused.stderr).toContain('/ship run ship-stale-1 is open on this checkout (state legacy, beat_age unknown;');
expect(refused.stderr).toContain('gstack-ship-run abandon --run ship-stale-1 --by <lane or Captain> --reason "<one line>"');
const body = path.join(f.root, 'body.md');
fs.writeFileSync(body, 'Fixes a thing.\n');
const end = run(f, 'gstack-ship-run', ['abandon', '--run', 'ship-stale-1', '--by', CAPTAIN, '--reason', 'the run died before finish', '--body', body]);
expect(end.status, end.stderr).toBe(0);
expect(end.stdout).toContain('RUN_ABANDONED: run=ship-stale-1 from=legacy by=Captain GStack Minder (GSTA-36)');
expect(record(f)).toMatchObject({ v: 1, run: 'ship-stale-1', state: 'abandoned', ended_by: CAPTAIN, reason: 'the run died before finish' });
expect(receiptRuns(fs.readFileSync(body, 'utf8'))).toEqual([expect.objectContaining({ mark: 'abandoned', run: 'ship-stale-1', by: CAPTAIN, reason: 'the run died before finish' })]);
expect(prReviewHistory(fs.readFileSync(body, 'utf8')).rounds).toBe(0);
const ok = grant(f, 'extra-round');
expect(ok.status, ok.stderr).toBe(0);
const again = run(f, 'gstack-ship-run', ['abandon', '--run', 'ship-stale-1', '--by', CAPTAIN, '--reason', 'twice']);
expect(again.status).toBe(3);
expect(again.stderr).toContain('(SHIP_RUN_ABANDON_REFUSED;');
});
// Value: protects=decision C, a stopped run records the fix-check grant its stop's NEXT line names and nothing else; fails_when=
// the stopped run refuses its own grant (the bare marker reads open) or grants itself an extra round; seam=gstack-ship-receipt
// stop, gstack-approvals round-grant
test('a stopped record allows its own stop\'s fix-check grant and refuses an extra round', () => {
const f = fx({ 'src/x.ts': 'export const x = 1;\n' }, { 'src/x.ts': 'export const x = 2;\n' });
expect(preflight(f, 'ro').status).toBe(0);
const s = head(f);
logStoppingReview(f);
const body = path.join(f.root, 'body.md');
fs.writeFileSync(body, 'Fixes a thing.\n');
const stop = run(f, 'gstack-ship-receipt', ['stop', '--body', body, '--pr', '7', '--run', 'ro', '--since', '2000-01-01T00:00:00Z']);
expect(stop.status, stop.stderr).toBe(0);
expect(record(f)).toMatchObject({ run: 'ro', state: 'stopped', stop: { head: s, tree: f.git('rev-parse', 'HEAD^{tree}').stdout.trim() } });
const extra = grant(f, 'extra-round');
expect(extra.status).toBe(2);
expect(extra.stderr).toContain('/ship run ro is open on this checkout (state stopped, beat_age 0m;');
expect(extra.stderr).toContain(`a stopped run records only the fix-check grant for its own stop (--kind fix-check --stop-run ro --head ${s})`);
expect(grant(f, 'fix-check', ['--stop-run', 'other', '--findings', 'p1/outside-voice#1']).status).toBe(2);
expect(grant(f, 'fix-check', [], f.git('rev-parse', 'HEAD~1').stdout.trim()).status).toBe(2);
const own = grant(f, 'fix-check');
expect(own.status, own.stderr).toBe(0);
});
// Value: protects=the own-stop exemption buys one fix round per run: once the run claimed it, a later stop needs the lane's
// relayed grant; fails_when=a run loops stop, self-grant, claim past R51's cap; seam=gstack-approvals round-grant, run record claim
test('a stopped run grants itself one fix round: after its claim, another stop needs a relayed grant', () => {
const f = fx({ 'src/x.ts': 'export const x = 1;\n' }, { 'src/x.ts': 'export const x = 2;\n' });
expect(preflight(f, 'ro').status).toBe(0);
const s = head(f);
logStoppingReview(f);
const body = path.join(f.root, 'body.md');
fs.writeFileSync(body, 'Fixes a thing.\n');
expect(run(f, 'gstack-ship-receipt', ['stop', '--body', body, '--pr', '7', '--run', 'ro', '--since', '2000-01-01T00:00:00Z']).status).toBe(0);
const g = /APPROVAL_RECORDED: (a-[0-9a-f]{12})/.exec(grant(f, 'fix-check').stdout)?.[1];
expect(g).toBeDefined();
expect(run(f, 'gstack-ship-receipt', ['claim', '--body', body, '--run', 'ro', '--grant', g!]).status).toBe(0);
fs.writeFileSync(recordFile(f), JSON.stringify({ ...record(f), state: 'stopped' }) + '\n');
const again = grant(f, 'fix-check', [], s);
expect(again.status).toBe(2);
expect(again.stderr).toContain("this run already spent its own stop's fix-check grant (" + g + ')');
});
// Value: protects=a stopped record of another run is replaced by a new --run, while a preflight with no --run stops on it;
// fails_when=a bare preflight merges the base under the stopped run's stop head; seam=lib/ship-preflight.ts shipRunClear
test('a stopped record of another run: a new --run replaces it, a preflight with no --run stops', () => {
const f = fx();
expect(preflight(f, 'ro').status).toBe(0);
const s = head(f);
fs.writeFileSync(recordFile(f), JSON.stringify({ ...record(f), state: 'stopped', stop: { head: s, tree: f.git('rev-parse', 'HEAD^{tree}').stdout.trim() } }) + '\n');
f.advanceBase({ 'docs/new.md': '# new\n' });
const bare = preflight(f);
expect(bare.status).toBe(3);
expect(bare.stdout).toContain('STOP: /ship run ro is open on this checkout and past its preflight (');
expect(bare.stdout).not.toContain('MERGE:');
const next = preflight(f, 'r2');
expect(next.status, next.stdout).toBe(0);
expect(lineOf(next.stdout, 'MERGE')).toMatch(/^MERGE: merged origin\/main at /);
expect(record(f)).toMatchObject({ run: 'r2', state: 'open' });
});
// Value: protects=stop and claim upgrade a bare marker that names their run, and claim writes the grant it spends into the record;
// fails_when=a legacy marker stays bare after stop, or the claim lives only in the PR body; seam=gstack-ship-receipt stop/claim
test('stop and claim upgrade a legacy marker naming their run; claim records the grant and reopens the run', () => {
const f = fx({ 'src/x.ts': 'export const x = 1;\n' }, { 'src/x.ts': 'export const x = 2;\n' });
const s = head(f);
fs.writeFileSync(recordFile(f), 'ro\n');
logStoppingReview(f);
const body = path.join(f.root, 'body.md');
fs.writeFileSync(body, 'Fixes a thing.\n');
expect(run(f, 'gstack-ship-receipt', ['stop', '--body', body, '--pr', '7', '--run', 'ro', '--since', '2000-01-01T00:00:00Z']).status).toBe(0);
expect(record(f)).toMatchObject({ v: 1, run: 'ro', state: 'stopped', stop: { head: s } });
const g = /APPROVAL_RECORDED: (a-[0-9a-f]{12})/.exec(grant(f, 'fix-check').stdout)?.[1];
expect(g).toBeDefined();
const claim = run(f, 'gstack-ship-receipt', ['claim', '--body', body, '--run', 'ro', '--grant', g!]);
expect(claim.status, claim.stderr).toBe(0);
expect(record(f)).toMatchObject({ run: 'ro', state: 'open', stop: { head: s }, claim: { grant: g, stop_run: 'ro', stop_head: s, findings: ['p1/outside-voice#1'] } });
});
// Value: protects=an unreadable record fails closed (preflight and grants refuse) and one abandon naming its digest ends it;
// fails_when=a corrupt record reads as no run; seam=lib/ship-run-record.ts readRunRecord, gstack-ship-run
test('an unreadable record stops preflight and grants; abandon --run unknown takes only its digest', () => {
const f = fx();
fs.writeFileSync(recordFile(f), '{"v":1,"run":\n');
f.advanceBase({ 'docs/new.md': '# new\n' });
const pre = preflight(f, 'r2');
expect(pre.status).toBe(3);
expect(pre.stdout).toContain('STOP: /ship run unknown is open on this checkout and past its preflight (');
expect(pre.stdout).toContain('state unreadable');
expect(grant(f, 'extra-round').stderr).toContain('state unreadable');
const status = run(f, 'gstack-ship-run', ['status']);
expect(status.status).toBe(1);
expect(status.stderr).toContain('(SHIP_RUN_RECORD_UNREADABLE;');
const sha = /sha256=([0-9a-f]{64})/.exec(status.stdout)?.[1];
expect(sha).toBeDefined();
const end = (digest: string) => run(f, 'gstack-ship-run', ['abandon', '--run', 'unknown', '--sha256', digest, '--by', CAPTAIN, '--reason', 'corrupt record']);
expect(end('0'.repeat(64)).status).toBe(3);
expect(end(sha!).status).toBe(0);
const next = preflight(f, 'r2');
expect(next.status, next.stdout).toBe(0);
expect(lineOf(next.stdout, 'MERGE')).toMatch(/^MERGE: merged origin\/main at /);
expect(record(f)).toMatchObject({ run: 'r2', state: 'open' });
});
// Value: protects=abandon refuses a run that beat in the last 60 minutes and gstack's own names, and a review-log beat counts;
// fails_when=a working run can be abandoned by mistake; seam=gstack-ship-run abandon, gstack-review-log --start
test('abandon refuses under 60 minutes and as gstack; a review start beats the run', () => {
const f = fx();
expect(preflight(f, 'r1').status).toBe(0);
const end = (by = CAPTAIN) => run(f, 'gstack-ship-run', ['abandon', '--run', 'r1', '--by', by, '--reason', 'stopped answering']);
const young = end();
expect(young.status).toBe(3);
expect(young.stderr).toContain('(SHIP_RUN_ABANDON_REFUSED;');
expect(young.stderr).toMatch(/beat_age 0m; the earliest abandon is \d{4}-\d\d-\d\dT/);
age(f, 61);
expect(end('gstack').status).toBe(2);
expect(run(f, 'gstack-ship-run', ['abandon', '--run', 'r9', '--by', CAPTAIN, '--reason', 'x']).status).toBe(3);
const start = run(f, 'gstack-review-log', ['--start', 'review']);
expect(start.status, start.stderr).toBe(0);
expect(Date.now() - Date.parse(record(f).beat_at)).toBeLessThan(60_000);
expect(end().status).toBe(3);
age(f, 61);
const ok = end();
expect(ok.status, ok.stderr).toBe(0);
expect(ok.stdout).toContain('RUN_ABANDON_PR: skipped (no open PR');
});
// Value: protects=amendment C, gstack-skill-end ends its session's run on any outcome so the next preflight replaces it, and
// never touches another run; fails_when=a crashed or aborted /ship leaves an open run; seam=bin/gstack-skill-end
for (const outcome of ['error', 'abort']) {
test(`gstack-skill-end --outcome ${outcome} finishes its own run only`, () => {
const f = fx();
const skillEnd = (id: string) => f.run(path.join(BIN, 'gstack-skill-end'), ['--skill', 'ship', '--outcome', outcome, '--session-id', id, '--tel-start', '0'], { GSTACK_LEASE_DIR: path.join(f.root, 'install-leases') });
expect(preflight(f, 's1').status).toBe(0);
expect(skillEnd('other-session').status).toBe(0);
expect(record(f)).toMatchObject({ run: 's1', state: 'open' });
expect(skillEnd('s1').status).toBe(0);
expect(record(f)).toMatchObject({ run: 's1', state: 'finished', ended_by: 'skill-end' });
f.advanceBase({ 'docs/new.md': '# new\n' });
const reused = preflight(f, 's1');
expect(reused.status).toBe(3);
expect(reused.stdout).toContain('STOP: /ship run s1 already ended on this checkout (state finished, ended_by skill-end)');
const next = preflight(f, 's2');
expect(next.status, next.stdout).toBe(0);
expect(record(f)).toMatchObject({ run: 's2', state: 'open' });
});
}
// Value: protects=two preflights racing to open a run: the compare-and-swap under the gate lock lets exactly one write;
// fails_when=both record (the second overwrites the first); seam=lib/ship-run-record.ts changeRunRecord under withGateLock
test('two racing preflights: exactly one opens the run', async () => {
const f = fx();
const lib = path.resolve(import.meta.dir, '..', 'lib', 'ship-run-record.ts');
const open = (id: string) => new Promise<string>(resolve => {
const child = spawn(process.execPath, ['--no-env-file', '--config=/dev/null', '-e', `const { changeRunRecord } = await import(${JSON.stringify(lib)}); process.stdout.write(JSON.stringify(changeRunRecord(process.cwd(), 'preflight', ${JSON.stringify(id)})));`], { cwd: f.work, stdio: ['ignore', 'pipe', 'pipe'] });
let out = '';
child.stdout.on('data', d => { out += d; });
child.on('close', () => resolve(out));
});
const results = (await Promise.all(Array.from({ length: 6 }, (_, i) => open(`race-${i}`)))).map(o => JSON.parse(o || '{"ok":false,"why":"no output"}'));
expect(results.filter(r => r.ok)).toHaveLength(1);
const winner = results.find(r => r.ok).record.run;
expect(record(f)).toMatchObject({ run: winner, state: 'open' });
for (const r of results.filter(x => !x.ok)) expect(r.why).toContain(`of run ${winner}`);
});
// Value: protects=rule --owner-ref stays allowed under open, stopped and legacy records while an unrelayed ruling refuses with
// the record's state; fails_when=a stopped record blocks the owner's relayed ruling; seam=gstack-approvals rule
test('rule --owner-ref records under stopped, open and legacy records; without it the refusal names the state', () => {
const f = fx();
const s = head(f);
const rule = (finding: string, extra: string[] = []) => run(f, 'gstack-approvals', ['rule', '--finding', finding, '--head', s, '--reason', 'ships as a note', '--words', 'B, note it', '--by', 'GBrain Minder (GBRA-108)', ...extra]);
const now = new Date().toISOString();
const states: Record<string, () => void> = {
stopped: () => fs.writeFileSync(recordFile(f), JSON.stringify({ v: 1, run: 'ro', state: 'stopped', head: s, started_at: now, beat_at: now, stop: { head: s, tree: f.git('rev-parse', 'HEAD^{tree}').stdout.trim() } }) + '\n'),
open: () => fs.writeFileSync(recordFile(f), JSON.stringify({ v: 1, run: 'ro', state: 'open', head: s, started_at: now, beat_at: now }) + '\n'),
legacy: () => fs.writeFileSync(recordFile(f), 'ro\n'),
};
for (const [state, make] of Object.entries(states)) {
make();
const bare = rule(`src/${state}.ts:1:correctness`);
expect([state, bare.status]).toEqual([state, 2]);
expect(bare.stderr).toContain(`/ship run ro is open on this checkout (state ${state}, `);
expect(bare.stderr).toContain('(APPROVAL_RULING_RUN_OPEN');
const relayed = rule(`src/${state}.ts:1:correctness`, ['--owner-ref', 'GBRA-108:2026-11-21T12:00:00Z']);
expect([state, relayed.status, relayed.stderr]).toEqual([state, 0, relayed.stderr]);
}
expect(run(f, 'gstack-approvals', ['lane-exception', '--head', s, '--files', 'test/a.test.ts', '--reason', 'x', '--words', 'w', '--by', 'Owner']).stderr).toContain('state legacy');
});
// Value: protects=preflight refuses a run id the PR body already shows receipted (gstack-evals#406 reused ship-406 across three
// runs); fails_when=history prints nothing for a reused id; seam=gstack-ship-receipt history --run
test('history names a --run the PR body already receipted', () => {
const f = fx();
const body = path.join(f.root, 'body.md');
const receipted = placeRunEntry('Fixes a thing.\n', { head: 'a'.repeat(40), run: 'ship-406', review_loop: { passes: 1, blocking_found: 0, deferred: 0 } });
fs.writeFileSync(body, receipted);
const used = run(f, 'gstack-ship-receipt', ['history', '--body', body, '--pr', '7', '--base', 'main', '--run', 'ship-406']);
expect(used.stdout).toContain(`PR_REVIEW_RUN_USED: run=ship-406 receipted at ${'a'.repeat(12)}`);
expect(run(f, 'gstack-ship-receipt', ['history', '--body', body, '--pr', '7', '--base', 'main', '--run', 'ship-407']).stdout).not.toContain('PR_REVIEW_RUN_USED');
});
});
describe('finish removes only the run record the PR body names (amendment F)', () => {
// Value: protects=finish never removes another run's record; fails_when=a stopped run's late finish deletes the next run's open
// record; seam=lib/ship-run-record.ts finishRun
test('a record whose run the PR body does not name stays; a named one, or one with no PR, is removed', async () => {
const { finishRun } = await import('../lib/ship-run-record');
const f = fx();
expect(preflight(f, 'run-b').status).toBe(0);
expect(finishRun(f.work, ['run-a'])).toMatchObject({ removed: false });
expect(record(f)).toMatchObject({ run: 'run-b', state: 'open' });
expect(finishRun(f.work, ['run-a', 'run-b'])).toMatchObject({ removed: true });
expect(fs.existsSync(recordFile(f))).toBe(false);
expect(preflight(f, 'run-c').status).toBe(0);
expect(finishRun(f.work, null)).toMatchObject({ removed: true });
expect(fs.existsSync(recordFile(f))).toBe(false);
});
// Value: protects=two untested transitions: finish keeps an unreadable record, and abandon ends a stopped run past 60 minutes;
// fails_when=finish deletes a record it cannot read, or a stopped run can never be abandoned; seam=finishRun, gstack-ship-run abandon
test('finish keeps an unreadable record; abandon ends a stopped run past 60 minutes', async () => {
const { finishRun } = await import('../lib/ship-run-record');
const f = fx();
fs.writeFileSync(recordFile(f), '{"v":1,"run":\n');
expect(finishRun(f.work, null)).toMatchObject({ removed: false, line: expect.stringContaining('RUN_RECORD: kept (') });
expect(fs.readFileSync(recordFile(f), 'utf8')).toBe('{"v":1,"run":\n');
fs.rmSync(recordFile(f));
expect(preflight(f, 'ro').status).toBe(0);
fs.writeFileSync(recordFile(f), JSON.stringify({ ...record(f), state: 'stopped' }) + '\n');
age(f, 61);
const body = path.join(f.root, 'body.md');
fs.writeFileSync(body, 'Fixes a thing.\n');
const end = run(f, 'gstack-ship-run', ['abandon', '--run', 'ro', '--by', CAPTAIN, '--reason', 'stopped and never resumed', '--body', body]);
expect(end.status, end.stderr).toBe(0);
expect(record(f)).toMatchObject({ run: 'ro', state: 'abandoned', ended_by: CAPTAIN });
});
});
describe('the stop binds to the head its stopping row read (#4591)', () => {
const S = 'a'.repeat(40), E = 'e'.repeat(40), TS = 'b'.repeat(40), TE = 'f'.repeat(40);
const trees: Record<string, string> = { [S]: TS, [E]: TE };
const bound = (skill: string, commit: string, at: string, extra: Record<string, unknown> = {}) => ({ skill, via: 'ship', timestamp: at, completed: true, converged: false, commit_full: commit, tree: trees[commit], wtree: trees[commit], review_binding: { state: 'incomplete', start_wtree: trees[commit], end_wtree: trees[commit] }, ...extra });
const from = (rows: Record<string, unknown>[]) => stopFrom(rows, '2026-11-21T00:00:00Z', { treeOf: c => trees[c], onHead: c => c === S || c === E });
test('p1 -> fix-check -> Step 11 voices on a committed tree: the stop is the voices\' head, not the first pass\'s', () => {
const p1 = bound('review', S, '2026-11-21T07:00:00Z', { review_binding: { state: 'changed', start_wtree: TS, end_wtree: TE } });
const fixCheck = bound('review-fix-check', E, '2026-11-21T07:10:00Z');
const voices = bound('adversarial-review', E, '2026-11-21T07:20:00Z');
expect(from([p1, fixCheck, voices])).toEqual({ ok: true, head: E, tree: TE });
expect(from([p1, fixCheck])).toEqual({ ok: true, head: E, tree: TE });
expect(from([bound('review', S, '2026-11-21T07:00:00Z'), voices])).toEqual({ ok: true, head: E, tree: TE });
expect(from([p1, { ...voices, wtree: TS }]).ok).toBe(false);
});
});
describe('the round history counts a reused run id once per head (gstack-evals#406)', () => {
test('three entries sharing one run id at three heads read rounds=3; the same run at one head counts once', () => {
const loop = { passes: 1, blocking_found: 0, deferred: 0, rounds: 1 };
const receipt = (h: string) => ({ head: h, run: 'ship-406', review_loop: loop });
const body = [receipt('d'.repeat(40)), receipt('b'.repeat(40)), receipt('2'.repeat(40))].reduce((b, e) => placeRunEntry(b, e), 'Fixes a thing.\n');
expect(prReviewHistory(body)).toMatchObject({ rounds: 3, runs: 3, heads: 3 });
const sameHead = [runStub({ head: 'd'.repeat(40), run: 'ship-406', status: 'started', loop }), receipt('d'.repeat(40))].reduce((b, e) => placeRunEntry(b, e), 'Fixes a thing.\n');
expect(prReviewHistory(sameHead)).toMatchObject({ rounds: 1, heads: 1 });
});
});