After a pull request's second review round, an approved extra check now leads to a /ship sign-off (GST-3546) (#4717)

After a pull request's two review rounds, an approved extra check of the
fixes now ends in a /ship sign-off instead of a dead end.

Why: three projects (gbrain #10068, gskills #23–#25, gstack #4712) had
no way to finish after a ruling at the round limit and skipped the
sign-off or bent their records.

Nothing to do: the next /ship uses it.

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=state-machines
Review-Finding: p1/specialist-batched#3 reader=state-machines
Review-Finding: p1/red-team#1 reader=red-team
Review-Finding: p1/red-team#2 reader=red-team
Review-Finding: p2/outside-voice#1 reader=outside-voice
Review-Finding: p2/outside-voice#2 reader=outside-voice
Review-Finding: p2/outside-voice#3 reader=outside-voice
Review-Finding: p2/adversarial-native#1 reader=adversarial-native
This commit is contained in:
Garry Tanandcapy-ai[bot] authored and GitHub committed 2026-11-22 21:59:41 +00:00
1 parent c2da82e49c
commit 50cc296700
24 files changed
+704 -89

No files matched your search

+15 -4
View File
@@ -40,6 +40,8 @@ const HELP = `gstack-approvals — the per-thread approval record (capy/skill/gs
add --ask <text> --words <exact words> --by <who> --scope <what it covers>
[--pending <text>] [--outcome approved|rejected|pending|standing] [--date YYYY-MM-DD] [--source <ref>]
[--owner-ref <thread code>:<message id or timestamp>]: a row naming review_loop_grant <head> is a fix-check grant,
refused inside this checkout's open /ship run unless it relays the lane's or Captain's message with --owner-ref
import --autoplan <run dir> [--by <whose words, e.g. Garry>] [--stack <b1,b2,...>]
--stack writes the same rows to every branch of a stack; each branch is checked first, and one unknown branch writes none
rule --finding <fingerprint> --head <the stop head the owner ruled at> --reason <why it ships as a note, one line>
@@ -64,7 +66,10 @@ const HELP = `gstack-approvals — the per-thread approval record (capy/skill/gs
[--owner-ref <thread code>:<message id or timestamp>: relays the grant from the lane's or Captain's message, so it
records while a stopped /ship run is still open on this checkout; needs --words]
[--stop-run <run> --findings <ids>: fix-check only, the stop gstack-ship-receipt stop recorded and the findings
its fix round is for; it buys one scoped fix-check of the PR's own change since that stop's head]
its fix round is for; it buys one scoped fix-check of the PR's own change since that stop's head. A fix-check
with neither buys one scoped fix-check of the change since --head, the reviewed head: a post-review edit (the
docs audit), or a ruling at the cap whose run recorded no stop. A reason longer than the 300-character ask is
cut there with an ellipsis; its full words stay in --words]
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
@@ -189,9 +194,10 @@ function main(argv: string[]): number {
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');
const stopped = flags['--stop-run'] !== undefined || flags['--findings'] !== undefined;
if (kind === 'fix-check' && stopped && (!STOP_RUN.test(stopRun) || !findings.length || !findings.every(f => FINDING_ID.test(f)))) return invalid('round-grant --kind fix-check with a stop 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; with neither, it buys one scoped fix-check of the change since --head, the reviewed head (a post-review edit, or a stop no stop record holds)');
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);
const built = buildRow({ ...reviewRoundGrantRow(head.stdout.trim().toLowerCase(), Number(pr), kind, reason, kind === 'fix-check' && stopped ? { run: stopRun, findings } : undefined), words: flags['--words'] ?? reason, by, date: flags['--date'], source: ruledNoteSource({ ownerRef }) }, loc.branch);
if ('code' in built) return fail(cmd, built);
rows = [built];
} else if (cmd === 'lane-exception') {
@@ -245,7 +251,12 @@ function main(argv: string[]): number {
if (GATE_DISPOSITION_SCOPE.test(flags['--scope'] ?? '') || (flags['--source'] ?? '').trim() === GATE_SOURCE) return fail(cmd, { code: 'APPROVAL_RECORD_INVALID', message: 'a gate_disposition scope is recorded with gstack-approvals gate' });
if (TEST_LANE_EXCEPTION_SCOPE.test(flags['--scope'] ?? '')) return fail(cmd, { code: 'APPROVAL_RECORD_INVALID', message: 'a test_lane_exception scope is recorded with gstack-approvals lane-exception' });
if (REVIEW_ROUND_GRANT_SCOPE.test(flags['--scope'] ?? '')) return fail(cmd, { code: 'APPROVAL_RECORD_INVALID', message: 'a review_round_grant scope is recorded with gstack-approvals round-grant' });
const built = buildRow({ ask: flags['--ask'] ?? '', words: flags['--words'] ?? '', by: flags['--by'] ?? '', scope: flags['--scope'] ?? '', pending: flags['--pending'], outcome: flags['--outcome'], date: flags['--date'], source: flags['--source'] }, loc.branch);
const ownerRef = flags['--owner-ref']?.trim();
const grant = `${flags['--ask'] ?? ''} ${flags['--scope'] ?? ''}`.includes('review_loop_grant');
if (ownerRef !== undefined && (!grant || !OWNER_REF.test(ownerRef) || !(flags['--words'] ?? '').trim())) return fail(cmd, { code: 'APPROVAL_RECORD_INVALID', message: '--owner-ref on add relays a review_loop_grant: <thread code>:<message id or timestamp>, with --words <their exact words>' });
const open = grant ? openShipRun(process.cwd()) : undefined;
if (open && ownerRef === undefined) return fail(cmd, { code: 'APPROVAL_RECORD_INVALID', message: `${open.line}: a review_loop_grant row is a fix-check grant (GST-3546), 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 after the run ends` });
const built = buildRow({ ask: flags['--ask'] ?? '', words: flags['--words'] ?? '', by: flags['--by'] ?? '', scope: flags['--scope'] ?? '', pending: flags['--pending'], outcome: flags['--outcome'], date: flags['--date'], source: ownerRef !== undefined ? ruledNoteSource({ ownerRef }) : flags['--source'] }, loc.branch);
if ('code' in built) return fail(cmd, built);
rows = [built];
} else {
+11 -2
View File
@@ -210,10 +210,19 @@ eval_live() {
# written in the last 6 hours (every /ship program ends with a note that
# rewrites it, and Step 22's close stamps closed_at), or a review start capture
# under 120 minutes old that gstack-review-log --finish has not consumed. The
# age bounds keep an abandoned run from holding the upgrade back for good.
# age bounds keep an abandoned run from holding the upgrade back for good, and
# gstack-ship-run live (lib/ship-run-live.ts) drops a run that provably ended
# sooner: its owner process is gone, or its own /ship run record finished or
# was abandoned; a stopped run may still resume, so it holds (GST-3546). Without a working Bun the
# file-age reading below stands.
open_run() {
local sr f
local sr f live
sr=$("$ROOT/bin/gstack-paths" --get GSTACK_STATE_ROOT 2>/dev/null) && [ -n "$sr" ] || return 1
live=$("$ROOT/bin/gstack-ship-run" live --state-root "$sr" 2>/dev/null | sed -n 's/^RUN_LIVE: //p')
case "$live" in
none) return 1 ;;
?*) printf '%s\n' "$live"; return 0 ;;
esac
while IFS= read -r f; do
grep -q '"kind": *"gstack-ship-budget"' "$f" 2>/dev/null && ! grep -q '"closed_at"' "$f" 2>/dev/null || continue
echo "/ship run $(basename "$(dirname "$f")") ($f)"
+3 -3
View File
@@ -39,7 +39,7 @@ import { effectiveReaders, READERS_POLICY_DEFAULT, type EffectiveReaders } from
import { defaultRoots, foundLines, ignoredLines, inventory, quarantineStage, rerunBlocked, sweepResult, type Inventory } from '../lib/review-sweep';
import { REVIEW_DIFF_MAX_BYTES, ceilingContext, disclosureDigest, disclosureLine, parseTail, readSelection, tooLargeLine, unreadableLine, type PlanExclude, type ReaderDiff } from '../lib/review-exclude';
import { logShipCall } from '../lib/ship-call-log';
import { restampFixCheckHunks } from '../lib/review-evidence';
import { claimedFixCheckHunks, restampFixCheckHunks } from '../lib/review-evidence';
logShipCall('gstack-review-dispatch');
@@ -188,7 +188,7 @@ function render(): number {
classes: flag('--classes'), brief, ...(merged ? { checklist: path.join(ROOT, 'review/specialists/targeted.md') } : {}),
policy_exclude: policyItems.map(quote).join(' ') || undefined, ...(sel.disclosure ? { disclosure: sel.disclosure, keep: sel.keep?.map(quote).join(' ') || undefined } : {}),
...(sel.disclosure && 'excerpt_file' in sel && sel.excerpt_file ? { excerpt_file: sel.excerpt_file.file, excerpt_bytes: String(sel.excerpt_file.bytes), excerpt_sha256: sel.excerpt_file.sha256, excerpt_files: String(sel.excerpt_file.files) } : {}),
fix_list: readFile(flag('--fix-list'), 'fix list'), hunks: readFile(flag('--hunks'), 'hunks'), tests: readFile(flag('--tests'), 'tests'), callers: readFile(flag('--callers'), 'callers'),
fix_list: readFile(flag('--fix-list'), 'fix list'), hunks: (role === 'fix-check' ? claimedFixCheckHunks(process.cwd())?.text : undefined) ?? readFile(flag('--hunks'), 'hunks'), tests: readFile(flag('--tests'), 'tests'), callers: readFile(flag('--callers'), 'callers'),
};
const workdir = checkoutRoot();
const tree = checkoutTree(workdir);
@@ -508,7 +508,7 @@ function passStep(cmd: string): number {
process.stdout.write(`LOG_START: ${logStart} token=${m.log_starts[logStart]}\n`);
if (fresh && m.fix_check?.hunks && logStart.includes('review-fix-check')) {
let text: string | undefined;
try { text = fs.readFileSync(m.fix_check.hunks, 'utf8'); } catch { /* reported below; the start token is already recorded */ }
try { text = claimedFixCheckHunks(process.cwd())?.text ?? fs.readFileSync(m.fix_check.hunks, 'utf8'); } catch { /* reported below; the start token is already recorded */ }
process.stdout.write(`FIX_CHECK_HUNKS: ${text === undefined ? 'not restamped (hunks file unreadable)' : restampFixCheckHunks(process.cwd(), text) ? 'restamped' : 'not restamped (no render record with these hunks)'}\n`);
}
return EXIT.ok;
+18 -12
View File
@@ -25,7 +25,7 @@ import * as path from 'node:path';
import { spawnSync } from '../lib/spawn-sync';
import { baseContainsHead } from '../lib/default-base';
import { locate, readRecord } from '../lib/approval-record';
import { reviewRoundGrants } from '../lib/review-round-grant';
import { grantForPr, readReviewRoundGrants, reviewRoundGrants } from '../lib/review-round-grant';
import { EXIT, exitTableHelp } from '../lib/headless-artifacts';
import { resultLine } from '../lib/result-codes';
import { gateOutcomeLine } from '../lib/gate-outcomes';
@@ -46,8 +46,8 @@ import { targetedDelta } from '../lib/review-targeted-delta';
import { docsChangeSince, ownChangeSince } from '../lib/ship-receipt-depth';
import { RISK_CLASSES, type RiskClass } from '../lib/review-risk';
import { renderFixCheckPrompt } from '../scripts/resolvers/fix-check';
import { grantSpent } from '../lib/fix-check-clearing';
import { recordFixCheckHunks } from '../lib/review-evidence';
import { bindFixCheckRow, countedFixCheck, grantSpent } from '../lib/fix-check-clearing';
import { claimedFixCheckHunks, recordFixCheckHunks } from '../lib/review-evidence';
const HELP = `gstack-review-plan — the review depth of the next /ship step (docs/review-policy.md#review-depth)
@@ -144,8 +144,11 @@ function main(): number {
if (!f) return required ? null : '';
try { return fs.readFileSync(f, 'utf8'); } catch { return null; }
};
const [fixList, touchedHunks, testResults, callers] = [read('--fix-list', true), read('--hunks', true), read('--tests', true), read('--callers', false)];
if (fixList === null || touchedHunks === null || testResults === null || callers === null) { process.stderr.write('gstack-review-plan: --fix-check-prompt needs readable --fix-list, --hunks and --tests files (--callers optional)\n'); return EXIT.usage; }
const built = claimedFixCheckHunks(process.cwd());
const [fixList, given, testResults, callers] = [read('--fix-list', true), read('--hunks', !built), read('--tests', true), read('--callers', false)];
if (fixList === null || given === null || testResults === null || callers === null) { process.stderr.write('gstack-review-plan: --fix-check-prompt needs readable --fix-list and --tests files, and --hunks unless this run claimed a fix-check grant (gstack then builds them; --callers optional)\n'); return EXIT.usage; }
if (built && given && given !== built.text) process.stderr.write(`FIX_CHECK_HUNKS: built from git diff ${built.base.slice(0, 12)} HEAD (the claimed grant's head); the --hunks file differs and is not used\n`);
const touchedHunks = built?.text ?? given;
process.stdout.write(renderFixCheckPrompt({ fixList, touchedHunks, testResults, callers }));
recordFixCheckHunks(process.cwd(), touchedHunks, undefined, fixList);
return EXIT.ok;
@@ -175,18 +178,21 @@ function main(): number {
if (!root) { process.stderr.write('gstack-review-plan: run it inside a git checkout\n'); return EXIT.fail; }
process.chdir(root);
let inLoopLink = false;
let recorded: ReturnType<typeof readReviewRoundGrants> | undefined;
const bindRow = (row: Record<string, any>) => bindFixCheckRow(root, row, recorded ??= readReviewRoundGrants(root), { open: true }).ok;
if (grant) {
const loc = locate({ cwd: root, env: process.env });
const row = ('file' in loc ? readRecord(loc).rows : []).find(r => r.id === grant && r.outcome === 'approved' && `${r.ask} ${r.scope}`.includes('review_loop_grant'));
const row = ('file' in loc ? readRecord(loc).rows : []).find(r => r.id === grant && r.outcome === 'approved' && (`${r.ask} ${r.scope}`.includes('review_loop_grant') || reviewRoundGrants([r]).some(x => x.kind === 'fix-check')));
const named = row ? reviewRoundGrants([row]).find(x => x.kind === 'fix-check' && !x.legacy)?.head : undefined;
const passHead = git(['rev-parse', '--verify', '--quiet', `${rangeBase}^{commit}`])?.trim();
const ancestor = (a: string, d: string) => git(['merge-base', '--is-ancestor', a, d]) !== null;
const chained = has('--post-review') && last === 'fix-check';
const stopHead = row && passHead ? `${row.ask} ${row.scope}`.match(/\b[0-9a-f]{7,40}\b/g)?.map(s => git(['rev-parse', '--verify', '--quiet', `${s}^{commit}`])?.trim()).find(s => s && ancestor(passHead, s) && ancestor(s, 'HEAD') && !(chained && s === passHead)) : undefined;
const stopHead = row && passHead ? (named ? [named] : `${row.ask} ${row.scope}`.match(/\b[0-9a-f]{7,40}\b/g))?.map(s => git(['rev-parse', '--verify', '--quiet', `${s}^{commit}`])?.trim()).find(s => s && ancestor(passHead, s) && ancestor(s, 'HEAD') && !(chained && s === passHead)) : undefined;
inLoopLink = !chained && last === 'fix-check' && stopHead === passHead;
if (!stopHead) { process.stderr.write(`gstack-review-plan: --grant ${grant}: no approved row ${grant} naming review_loop_grant and this invocation's stop head (a commit ${chained ? `after --range-base ${rangeBase}, the last fix-check's commit, whose own grant does not carry over` : `at or after --range-base ${rangeBase}`}, at or before HEAD) in this branch's approval record (${'file' in loc ? 'gstack-approvals list' : loc.message}); record the owner's grant with gstack-approvals add --ask '... (review_loop_grant <stop head sha>)' first\n`); return EXIT.refused; }
const logged = inLoopLink ? runScriptSync(path.join(path.dirname(Bun.fileURLToPath(import.meta.url)), 'gstack-review-read'), [], { encoding: 'utf8', timeout: 60_000, maxBuffer: 64 * 1024 * 1024 }) : null;
if (logged && logged.status !== 0) { process.stderr.write(`gstack-review-plan: --grant ${grant}: gstack-review-read exited ${logged.status}, so whether a fix-check already spent this grant is unknown; no plan is safer than a fix-check the grant may not buy\n`); return EXIT.fail; }
if (logged && row && (logged.stdout ?? '').split('\n---CONFIG---')[0]!.split('\n').some(l => { try { const v = JSON.parse(l); return v?.skill === 'review-fix-check' && Date.parse(v.timestamp) > Date.parse(row.recorded_at); } catch { return false; } })) { process.stderr.write(`gstack-review-plan: --grant ${grant}: a fix-check was logged after this grant was recorded, so the grant already bought a link of the fix-check chain; the stop at --range-base ${rangeBase} needs a new grant recorded after the last fix-check (gstack-approvals add --ask '... (review_loop_grant ${passHead!.slice(0, 12)})')\n`); return EXIT.refused; }
if (logged && row && (logged.stdout ?? '').split('\n---CONFIG---')[0]!.split('\n').some(l => { try { const v = JSON.parse(l); return countedFixCheck(v, bindRow) && Date.parse(v.timestamp) > Date.parse(row.recorded_at); } catch { return false; } })) { process.stderr.write(`gstack-review-plan: --grant ${grant}: a fix-check was logged after this grant was recorded, so the grant already bought a link of the fix-check chain; the stop at --range-base ${rangeBase} needs a new grant recorded after the last fix-check (gstack-approvals add --ask '... (review_loop_grant ${passHead!.slice(0, 12)})')\n`); return EXIT.refused; }
}
const priorRounds = Number(flag('--prior-rounds') ?? '0');
const priorFull = Number(flag('--prior-full') ?? '0');
@@ -197,16 +203,16 @@ function main(): number {
if (has('--round-grant')) {
const at = git(['rev-parse', 'HEAD'])?.trim();
const loc = locate({ cwd: root, env: process.env });
const g = reviewRoundGrants('file' in loc ? readRecord(loc).rows : []).find(x => x.approval === roundGrant);
const g = readReviewRoundGrants(root).find(x => x.approval === roundGrant);
const pr = flag('--pr');
const stop = has('--stop') ? git(['rev-parse', '--verify', '--quiet', `${flag('--stop')}^{commit}`])?.trim() : undefined;
if (g && (g.kind === 'fix-check') !== has('--stop')) { process.stderr.write(`gstack-review-plan: --round-grant ${roundGrant}: ${g.kind === 'fix-check' ? 'a fix-check grant answers a stop record: pass the --stop <head> PR_REVIEW_FLAGS: prints with it' : 'an extra-round grant names no stop: --stop takes a fix-check grant'} (docs/troubleshooting.md#pr-round-cap)\n`); return EXIT.refused; }
if (g && g.kind === 'fix-check' && (stop !== g.head || (pr !== undefined && String(g.pr) !== pr))) { process.stderr.write(`gstack-review-plan: --round-grant ${roundGrant}: the fix-check grant names the stop at ${g.head.slice(0, 12)} for PR #${g.pr}, not --stop ${(flag('--stop') ?? '').slice(0, 12)}${pr ? ` and PR #${pr}` : ''}; a grant buys the fix round of the one stop it names (docs/troubleshooting.md#pr-round-cap)\n`); return EXIT.refused; }
if (g && g.kind === 'fix-check' && (stop !== g.head || (pr !== undefined && !grantForPr(g, Number(pr))))) { process.stderr.write(`gstack-review-plan: --round-grant ${roundGrant}: the fix-check grant names the stop at ${g.head.slice(0, 12)} for PR #${g.pr}, not --stop ${(flag('--stop') ?? '').slice(0, 12)}${pr ? ` and PR #${pr}` : ''}; a grant buys the fix round of the one stop it names (docs/troubleshooting.md#pr-round-cap)\n`); return EXIT.refused; }
if (g?.kind === 'fix-check') grantedStop = g.approval;
const logged = g?.kind === 'fix-check' && last === 'fix-check' ? runScriptSync(path.join(path.dirname(Bun.fileURLToPath(import.meta.url)), 'gstack-review-read'), [], { encoding: 'utf8', timeout: 60_000, maxBuffer: 64 * 1024 * 1024 }) : null;
grantUnspent = !!logged && logged.status === 0 && !grantSpent((logged.stdout ?? '').split('\n---CONFIG---')[0]!.split('\n').flatMap(l => { try { const v = JSON.parse(l); return v && typeof v === 'object' ? [v] : []; } catch { return []; } }), g!);
grantUnspent = !!logged && logged.status === 0 && !grantSpent((logged.stdout ?? '').split('\n---CONFIG---')[0]!.split('\n').flatMap(l => { try { const v = JSON.parse(l); return v && typeof v === 'object' ? [v] : []; } catch { return []; } }), g!, bindRow);
const atOrBefore = !!g && !!at && (g.head === at || git(['merge-base', '--is-ancestor', g.head, at]) !== null);
if (!roundGrant || !g || !atOrBefore || (pr !== undefined && String(g.pr) !== pr)) { process.stderr.write(`gstack-review-plan: --round-grant ${roundGrant ?? ''}: no approved review_round_grant row ${roundGrant ?? ''} naming HEAD ${(at ?? 'unknown').slice(0, 12)} or a commit before it${pr ? ` and PR #${pr}` : ''} in this branch's approval record; record one with gstack-approvals round-grant (docs/troubleshooting.md#pr-round-cap)\n`); return EXIT.refused; }
if (!roundGrant || !g || !atOrBefore || (pr !== undefined && !grantForPr(g, Number(pr)))) { process.stderr.write(`gstack-review-plan: --round-grant ${roundGrant ?? ''}: no approved review_round_grant row ${roundGrant ?? ''} naming HEAD ${(at ?? 'unknown').slice(0, 12)} or a commit before it${pr ? ` and PR #${pr}` : ''} in this branch's approval record; record one with gstack-approvals round-grant (docs/troubleshooting.md#pr-round-cap)\n`); return EXIT.refused; }
}
const collected = collectLive(root, base);
if (collected.errors.length) {
+6 -4
View File
@@ -70,7 +70,7 @@ import { laneExceptionBodyLines } from '../lib/test-lane-exception';
import { abandonMarker, grantedStop, grantMarker, historyLine, placeRunEntry, prReviewHistory, receiptedRun, reviewRoute, runStub, stopFrom, stopMarker } from '../lib/pr-review-history';
import { changeRunRecord, readRunRecord } from '../lib/ship-run-record';
import { splitAgentNotes, withAgentNotes } from '../lib/agent-notes';
import { grantFor, publicRoundGrant, readReviewRoundGrants, type ReviewRoundGrant } from '../lib/review-round-grant';
import { grantFor, grantForPr, 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';
import { runCalls } from '../lib/ship-clock';
@@ -395,7 +395,7 @@ async function cmdWrite(rest: string[], json: boolean): Promise<number> {
const at = headSha ?? head, baseRef = `origin/${base.replace(/^origin\//, '')}`, run = flag(rest, '--run'), pr = Number(flag(rest, '--pr'));
const blockers = (Array.isArray(loopRaw?.open) ? loopRaw.open : []).filter((b: any) => ruledOpen.includes(typeof b === 'string' ? b : b?.id));
const rows = ruledOpen.length ? reviewRows(repoRoot) ?? [] : [];
const grants = ruledOpen.length ? readReviewRoundGrants(repoRoot).filter(g => g.kind === 'fix-check' && g.pr === pr) : [];
const grants = ruledOpen.length ? readReviewRoundGrants(repoRoot).filter(g => g.kind === 'fix-check' && grantForPr(g, pr)) : [];
const live = grants.length && !receiptRuns(bodyText).length && flag(rest, '--pr') ? readBody(['--pr', flag(rest, '--pr')!, ...(flag(rest, '--repo') ? ['--repo', flag(rest, '--repo')!] : [])]) : undefined;
const clearing = ruledOpen.length ? await import('../lib/fix-check-clearing') : undefined;
const byGrant = !grants.length || !clearing ? undefined : !run ? { ids: [], why: 'write names no --run, so no run spent the grant' } : clearing.clearByGrant(repoRoot, { pr, run, head: at, baseRef, body: live?.ok ? live.body : bodyText, grants, rows, open: blockers });
@@ -1070,7 +1070,7 @@ function cmdClaim(rest: string[]): number {
const read = readBody(rest);
if (!read.ok) { process.stderr.write(`gstack-ship-receipt claim: ${read.why}; fix: ${read.fix}\n`); return EXIT.fail; }
const g = readReviewRoundGrants(repoRoot).find(x => x.approval === id);
if (!g) { process.stderr.write(`${resultLine('gstack-ship-receipt claim', 'GRANT_UNKNOWN', `no approved review_round_grant row ${id} in this branch's approval record`)}\n`); return EXIT.refused; }
if (!g) { process.stderr.write(`${resultLine('gstack-ship-receipt claim', 'GRANT_UNKNOWN', `no approved fix-check or round grant ${id} (a gstack-approvals round-grant row, or an owner's review_loop_grant <head> row) in this branch's approval record`)}\n`); return EXIT.refused; }
const other = receiptRuns(read.body).find(r => r.mark === 'grant' && r.grant === id && r.run !== run);
if (other) { process.stderr.write(`${resultLine('gstack-ship-receipt claim', 'GRANT_SPENT', `grant ${id} was claimed by run ${other.run}: a grant buys one round; the lane or its Captain records a new one`)}\n`); return EXIT.refused; }
const err = postBody(rest, read.pr, placeRunEntry(read.body, grantMarker({ head: g.head, run, grant: id })));
@@ -1080,7 +1080,9 @@ 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; }
const recorded = changeRunRecord(repoRoot, 'claim', run, { claim: { grant: id, ...(g.stop_run ? { stop_run: g.stop_run } : {}), stop_head: g.head, findings: g.findings ?? [], pr: g.pr } });
const bodyPr = read.pr ?? flag(rest, '--pr');
const claimPr = g.pr || (bodyPr && /^[1-9]\d*$/.test(bodyPr) ? Number(bodyPr) : undefined);
const recorded = changeRunRecord(repoRoot, 'claim', run, { claim: { grant: id, ...(g.stop_run ? { stop_run: g.stop_run } : {}), stop_head: g.head, findings: g.findings ?? [], ...(claimPr ? { pr: claimPr } : {}) } });
if (!recorded.ok && readRunRecord(repoRoot).kind !== 'none') { process.stderr.write(`gstack-ship-receipt claim: the run record did not take the claim (${recorded.why}); not claimed, so do not dispatch: the PR body already holds run ${run}'s claim, so rerun claim with this same --run once the record is writable (a new run id reads GRANT_SPENT)\n`); return EXIT.fail; }
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;
+13
View File
@@ -5,6 +5,7 @@
* 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>
* gstack-ship-run live [--state-root <dir>]
*/
import * as path from 'node:path';
import { EXIT, exitTableHelp } from '../lib/headless-artifacts';
@@ -14,6 +15,8 @@ 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';
import { liveRun } from '../lib/ship-run-live';
import { resolveStateRoot } from '../lib/state-root';
const HELP = `gstack-ship-run — this checkout's /ship run record (docs/ship-policy.md#what-ends-a-run)
@@ -27,6 +30,10 @@ const HELP = `gstack-ship-run — this checkout's /ship run record (docs/ship-po
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
live [--state-root <dir>]
RUN_LIVE: <kind> run <id> (<file>) (exit 0) for the first /ship or review run on this machine that still holds
gstack upgrades, or RUN_LIVE: none (exit 0 either way); RUN_HOLD_RELEASED: lines name runs that no longer hold because
their owner process is gone or their own run record finished or was abandoned (lib/ship-run-live.ts)
${exitTableHelp()}`;
@@ -56,6 +63,12 @@ function main(argv: string[]): number {
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 === 'live') {
const found = liveRun(flag('--state-root') ?? resolveStateRoot());
for (const e of found.ended) process.stdout.write(`RUN_HOLD_RELEASED: ${e}\n`);
process.stdout.write(`RUN_LIVE: ${found.live ?? 'none'}\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)) {
@@ -0,0 +1,4 @@
---
important: blocker
---
**A Captain's ruling after a PR's second review round now ends in a /ship receipt.** The planner, `gstack-ship-receipt claim` and `write` accept the same fix-check grant whether it was recorded with `gstack-approvals round-grant` or as an owner's `review_loop_grant <head>` row. A fix-check grant no longer needs a stop record, so an edit made after review (a docs-audit edit) or a stop gstack could not bind can get one, and its clean fix-check closes the blockers its fix list named without per-finding rule rows; a blocker nothing covers still refuses. gstack now builds the fix-check's diff from the grant's head itself, a fix-check row that doesn't count (`converged:false`, partial hunks) no longer uses up the grant, and a `round-grant --reason` longer than 300 characters is cut in the ask with the full words kept. A /ship run that finished or was abandoned, or whose process is gone, stops holding gstack upgrades at once, and `gstack-ship-run abandon` takes a run whose process is gone without the 60-minute wait. An owner's `review_loop_grant` row recorded with `gstack-approvals add` inside an open /ship run now needs `--owner-ref`, like `round-grant`. (GST-3546)
+42
View File
@@ -280,6 +280,48 @@ dispatch ledger can't be read closes nothing. finish counts the same
stamped row, anchored on the grant's stop rather than the newest reviewed tree
(#4612).
<a id="one-grant-path"></a>
**One grant path after a ruling at the cap (GST-3546).** Every fix-check grant is
the same grant, whichever row records it:
- **Either row works.** A `gstack-approvals round-grant --kind fix-check` row and
an owner's `review_loop_grant <head>` approval row are both fix-check grants
for `gstack-review-plan --grant`, `gstack-ship-receipt claim` and write. The
older row names no PR, so it binds to the PR whose run claims it.
- **A grant needs no stop record.** `round-grant --kind fix-check` with no
`--stop-run` and no `--findings` buys one scoped fix-check of the change since
`--head`, the reviewed head. Use it for a post-review edit (a Step 14.5 docs
audit edit that #4708's one-reader packet doesn't take) or a ruling at the cap
whose run recorded no stop (`STOP_UNBOUND`). The run's own claim stands in for
the stop record: the grant, the claim and the fix-check's start must be
recorded in that order.
- **What it closes.** A grant that names findings closes those, as above. A
grant with no findings list closes each open blocker the fix list given to
its clean fix-check names. A blocker that no ruling, grant or fix list covers
still refuses `RECEIPT_BLOCKER_OPEN`, so the Captain's ruling at the cap needs
no hand-written per-finding rows, and nothing is closed that no reader read.
- **gstack builds the packet.** Once a run has claimed a grant, `gstack-review-plan
--fix-check-prompt` and the pass program build the reader's hunks from `git diff
<the grant's head> HEAD` themselves (`FIX_CHECK_HUNKS:` says when a `--hunks`
file differed and was not used), so the hunks record always covers the whole
fix range.
- **A grant spends only on a counted fix-check.** A malformed row
(`converged:false`, or a claimed row whose hunks or tree don't bind) leaves the
grant unspent: the same run logs a correct row. A counted read that found
issues spends it like a clean one, so a grant still buys one fix round, and
write reads the first counted row only.
- **Only the lane or its Captain grants.** A row whose ask or scope mentions
`review_loop_grant`, in any spelling or scope, recorded with `gstack-approvals
add` inside this checkout's open /ship run is refused unless it relays their
message with `--owner-ref` and `--words`, as `round-grant` already required.
- **One read per grant.** Receipt write keeps every distinct read stamped with
the grant (a copied row counts once) and takes the first that counts; a read
whose dispatch ledger collected a finding counts as long as the row records
that finding, open or not.
- **Long reasons fit.** A `--reason` longer than the approval record's
300-character ask is cut there with an ellipsis; `--words` (the reason by
default) keeps every word.
<a id="transitions"></a>
### Transitions
+2 -1
View File
@@ -1817,7 +1817,8 @@ 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
within 60 minutes of its last beat unless the harness process it ran under is
provably gone (GST-3546). 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
+30 -7
View File
@@ -2037,7 +2037,14 @@ ends (R75: upgrades wait for the workflow boundary); fix: <install> once the
run ends (UPGRADE_BUSY))`, for a ship-budget ledger with no `closed_at`
written in the last 6 hours, or `review run <token> (<file>)` for a review
start under 120 minutes old that `gstack-review-log --finish` has not
consumed.
consumed. A run that provably ended stops deferring at once
(`gstack-ship-run live` prints `RUN_HOLD_RELEASED:` for each, GST-3546): the
harness it ran under has exited or the machine restarted, or its own run
record in its checkout finished or was abandoned (the record belongs to the
newest ledger on that checkout created before it opened). A
stopped run keeps deferring, since it may still claim its fix-check grant and
resume, and so does an open run on Capy's shared harness; end a run that
stopped working with `gstack-ship-run abandon`.
**Fix.** Wait for those sessions to finish (`bin/gstack-lease list` shows
every lease with its age and `alive|idle|dead|stale`; a holder is named as
@@ -7957,9 +7964,14 @@ gstack can tie to one commit: the newest `via:ship` reading row since
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)).
**Fix.** The lane's Captain ships with the open notes listed, parks, or rules
the fix round with a grant that needs no stop record: `gstack-approvals
round-grant --pr <n> --head <the reviewed head> --kind fix-check --reason <why>
--by <lane or Captain>` (add `--owner-ref` and `--words` inside an open run).
The run then claims it, commits the fix, runs the one scoped fix-check
`gstack-review-plan --round-grant <id> --stop <that head>` plans, and write
closes the blockers that clean fix-check's fix list named
([review-policy.md](review-policy.md#one-grant-path)).
<a id="ship-run-abandon-refused"></a>
### `SHIP_RUN_ABANDON_REFUSED`
@@ -7970,6 +7982,13 @@ 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.
A run whose owner process is provably gone (preflight records the harness it
ran under; that process exited or the machine restarted) is taken at any age,
and no longer holds gstack upgrades either (`gstack-ship-run live`, GST-3546).
On Capy every session runs under one shared harness, so there the 60 minutes
still apply to an open or stopped run; once abandoned or finished it releases
the upgrade hold at once.
**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
@@ -7995,7 +8014,10 @@ The digest binds the abandon to the bytes you inspected.
**Meaning.** `gstack-ship-receipt claim` found another `/ship` run's grant
record for this round grant in the PR body's runs block. A grant buys one round,
and a voided run's claim still spends it.
and a voided run's claim still spends it. Within the run that claimed it, a
fix-check row that doesn't count (`converged:false`, partial hunks) spends
nothing: log a correct row in the same run instead of asking for a new grant
([review-policy.md](review-policy.md#one-grant-path)).
**Fix.** Record a new grant for the stop the PR is at now; `gstack-ship-receipt
stop` prints the command ([troubleshooting](#pr-round-cap)).
@@ -8004,8 +8026,9 @@ stop` prints the command ([troubleshooting](#pr-round-cap)).
### `GRANT_UNKNOWN`
**Meaning.** `gstack-ship-receipt claim --grant <id>` found no approved
`review_round_grant` row with that id in the branch's approval record or its
mirror.
fix-check or round grant with that id in the branch's approval record or its
mirror: neither a `gstack-approvals round-grant` row nor an owner's
`review_loop_grant <head>` row (both are the same grant since GST-3546).
**Fix.** Pass the id `gstack-approvals round-grant` printed, from a checkout
that sees that record ([troubleshooting](#pr-round-cap)).
+44 -26
View File
@@ -13,7 +13,7 @@ import { createHash } from 'node:crypto';
import * as fs from 'node:fs';
import * as path from 'node:path';
import { grantedStop } from './pr-review-history';
import { ownLinesSame, type ReviewRoundGrant } from './review-round-grant';
import { grantForPr, ownLinesSame, type ReviewRoundGrant } from './review-round-grant';
import { ledgerPass, parseFixTrailers, reviewRowKey, rowTime } from './review-scope';
import { isSecurityFinding } from './security-findings';
import { receiptRuns } from './ship-receipt';
@@ -37,9 +37,18 @@ const treeOf = (cwd: string, c: string) => git(cwd, ['rev-parse', '--verify', '-
const findingsOf = (r: Row): Row[] => (Array.isArray(r?.findings) ? r.findings.filter((f: unknown) => !!f && typeof f === 'object') : []);
const nameOf = (b: OpenBlocker) => (typeof b === 'string' ? b : b.id);
/** A fix-check grant buys one fix-check: it is spent once a row carries it, or once any fix-check started after it was recorded. */
export const grantSpent = (rows: readonly Row[], g: Pick<ReviewRoundGrant, 'approval' | 'at'>) =>
rows.some(r => r?.skill === 'review-fix-check' && (r.grant === g.approval || rowTime(r) > Date.parse(g.at)));
/**
* A fix-check row that counts (GST-3546): a row stamped from a claim counts when `bind` (bindFixCheckRow with `open: true`) accepts
* it, and any other as a completed, converged read, whatever it found. A malformed row (converged:false, hunks that leave out part
* of the fix range) counts for nothing, so the run logs a correct row on the same grant; a counted read that found issues spends
* the grant like a clean one, so a grant still buys one fix round.
*/
export const countedFixCheck = (r: Row, bind?: (row: Row) => boolean) => r?.skill === 'review-fix-check'
&& (r.fix_check_base !== undefined && bind ? bind(r) : r.completed === true && r.converged === true);
/** A fix-check grant buys one counted fix-check: it is spent once a counted row carries it, or once a counted fix-check started after it was recorded. */
export const grantSpent = (rows: readonly Row[], g: Pick<ReviewRoundGrant, 'approval' | 'at'>, bind?: (row: Row) => boolean) =>
rows.some(r => countedFixCheck(r, bind) && (r.grant === g.approval || rowTime(r) > Date.parse(g.at)));
/**
* The grant-and-row binding finish and write share (amendments A, B and H): a review-fix-check row gstack-review-log stamped from a
@@ -47,9 +56,10 @@ export const grantSpent = (rows: readonly Row[], g: Pick<ReviewRoundGrant, 'appr
* range_base that disagrees; a completed, converged read bound to its commit's own tree, which contains the base; nothing open in it
* (rule e: its status, an inline finding with action open at any severity, findings_open from a findings file, an id its dispatch
* ledger collected that the row does not dispose); and the hunks its reader was given are git diff <base> <commit> over their paths,
* which cover every path that diff changes.
* which cover every path that diff changes. `open: true` asks only whether the row counts as the grant's read at all: it skips the
* nothing-open check, and an id its dispatch ledger collected needs a finding in the row, whatever its action.
*/
export function bindFixCheckRow(cwd: string, row: Row, grants: readonly ReviewRoundGrant[]): RowBinding {
export function bindFixCheckRow(cwd: string, row: Row, grants: readonly ReviewRoundGrant[], o: { open?: boolean } = {}): RowBinding {
const no = (why: string): RowBinding => ({ ok: false, why });
const base = typeof row.fix_check_base === 'string' ? row.fix_check_base.toLowerCase() : '';
const commit = typeof row.commit_full === 'string' ? row.commit_full.toLowerCase() : '';
@@ -57,11 +67,11 @@ export function bindFixCheckRow(cwd: string, row: Row, grants: readonly ReviewRo
const b = row.review_binding, h = row.hunks, findings = findingsOf(row);
if (!SHA.test(base)) return no('the row carries no fix_check_base that gstack-review-log stamped from a claim');
if (!g) return no(`its grant ${row.grant ?? 'none'} is no approved fix-check grant in this branch's approval record`);
if (g.head !== base || g.pr !== row.pr) return no(`its fix_check_base ${s12(base)} on PR #${row.pr ?? '?'} is not the stop ${s12(g.head)} that grant ${g.approval} names on PR #${g.pr}`);
if (g.head !== base || !grantForPr(g, row.pr)) return no(`its fix_check_base ${s12(base)} on PR #${row.pr ?? '?'} is not the stop ${s12(g.head)} that grant ${g.approval} names on PR #${g.pr}`);
if (row.range_base !== undefined && git(cwd, ['rev-parse', '--verify', '--quiet', `${row.range_base}^{commit}`])?.trim() !== base) return no(`its range_base ${String(row.range_base).slice(0, 12)} disagrees with the logger's fix_check_base ${s12(base)}`);
if (row.completed !== true || row.converged !== true || b?.state !== 'verified' || typeof row.tree !== 'string' || b.start_wtree !== row.tree || b.end_wtree !== row.tree) return no('it is not a completed, converged read bound to one committed tree');
if (!SHA.test(commit) || treeOf(cwd, commit) !== row.tree || !ancestor(cwd, base, commit)) return no(`its commit ${s12(commit) || 'missing'} does not hold the tree it read or does not contain the stop ${s12(base)}`);
if (row.status === 'issues_found' || row.status === 'issues_open' || Number(row.findings_open ?? 0) > 0 || findings.some(f => f.action === 'open')) return no('it left a finding open');
if (!o.open && (row.status === 'issues_found' || row.status === 'issues_open' || Number(row.findings_open ?? 0) > 0 || findings.some(f => f.action === 'open'))) return no('it left a finding open');
if (!h || typeof h.sha256 !== 'string' || !Array.isArray(h.paths) || !h.paths.length) return no('it carries no record of the hunks its reader was given');
const diff = git(cwd, ['diff', base, commit, '--', ...h.paths]);
if (diff === null || createHash('sha256').update(diff).digest('hex') !== h.sha256) return no(`the hunks its reader was given are not git diff ${s12(base)} ${s12(commit)}`);
@@ -71,7 +81,7 @@ export function bindFixCheckRow(cwd: string, row: Row, grants: readonly ReviewRo
if (typeof h.ledger === 'string') {
let ids: string[];
try { fs.readFileSync(h.ledger); ids = ledgerPass(h.ledger, id => `${path.basename(path.dirname(h.ledger))}/${id}`).ids ?? []; } catch { return no(`its dispatch ledger ${h.ledger} is unreadable`); }
const disposed = new Set(findings.filter(f => f.action !== 'open').map(f => f.ledger_id));
const disposed = new Set(findings.filter(f => o.open || f.action !== 'open').map(f => f.ledger_id));
const left = ids.filter(id => !disposed.has(id));
if (left.length) return no(`its dispatch ledger holds ${left.join(', ')}, which the row does not dispose`);
}
@@ -79,9 +89,12 @@ export function bindFixCheckRow(cwd: string, row: Row, grants: readonly ReviewRo
}
/**
* Rules a to f with amendments D and E: (a) grantedStop accepts the newest stop record's fix-check grant for this PR and run;
* (b) the PR body's first claim of the grant is this run's; (c) exactly one review-fix-check row carries the grant, stamped with
* this run, and it binds (bindFixCheckRow) at the stop's head and tree from the body, never the newest review row, on the receipt
* Rules a to f with amendments D and E: (a) grantedStop accepts the newest stop record's fix-check grant for this PR and run, or
* (GST-3546) a fix-check grant that names no stop answers its own head once this run claimed it; (b) the PR body's first claim of
* the grant is this run's; (c) every review-fix-check row carrying the grant is stamped with this run (a copy of one read, same key and
* start, counts once, and two reads never collapse into the later one), the first that counts
* (bindFixCheckRow with open: true; a malformed row before it spends nothing) is the grant's one read, and it binds clean at
* the stop's head and tree from the body, never the newest review row, on the receipt
* head or a head that only merges the base into it; (d) the stop, the claim and the row's start are recorded in that order;
* (e) inside the binding; (f) each grant id closes the one open blocker whose id it is, a fingerprint only for a blocker without a
* ledger id that no other blocker shares, never a gate finding, and only an id the fix list its reader was given named; an id
@@ -89,24 +102,29 @@ export function bindFixCheckRow(cwd: string, row: Row, grants: readonly ReviewRo
*/
export function clearByGrant(cwd: string, o: { pr: number; run: string; head: string; baseRef: string; body: string; grants: readonly ReviewRoundGrant[]; rows: readonly Row[]; open: readonly OpenBlocker[] }): GrantClearing {
const none = (why: string): GrantClearing => ({ ids: [], why });
const claimOf = (id: string) => receiptRuns(o.body).find(r => r.mark === 'grant' && r.grant === id);
const answer = grantedStop(o.body, o.grants, { pr: o.pr, head: o.head, run: o.run, isAncestor: (a, d) => ancestor(cwd, a, d) });
if (!answer) return none(`no fix-check grant for PR #${o.pr}`);
if (!answer.ok) return none(answer.why);
const { grant: g, stop } = answer;
const claim = receiptRuns(o.body).find(r => r.mark === 'grant' && r.grant === g.approval);
const unstopped = answer?.ok ? undefined : [...o.grants].reverse().find(x => x.kind === 'fix-check' && !x.stop_run && grantForPr(x, o.pr) && claimOf(x.approval)?.run === o.run && ancestor(cwd, x.head, o.head));
if (!answer?.ok && !unstopped) return none(answer ? answer.why : `no fix-check grant for PR #${o.pr}`);
const g = unstopped ?? (answer as Extract<typeof answer, { ok: true }>).grant;
const stop = unstopped ? { head: unstopped.head, tree: treeOf(cwd, unstopped.head), at: unstopped.at } : (answer as Extract<typeof answer, { ok: true }>).stop;
const claim = claimOf(g.approval);
if (claim?.run !== o.run) return none(`the PR body's first claim of grant ${g.approval} is ${claim ? `run ${claim.run}'s` : 'missing'}, not run ${o.run}'s`);
const stamped = [...new Map(o.rows.filter(r => r?.skill === 'review-fix-check' && r.grant === g.approval).map(r => [reviewRowKey(r), r] as const)).values()];
const row = stamped[0];
if (stamped.length !== 1 || row!.run !== o.run) return none(`grant ${g.approval} buys one fix-check row stamped with run ${o.run}, and the review log holds ${stamped.length}${row ? ` (run ${row.run}'s)` : ''}`);
const bound = bindFixCheckRow(cwd, row!, o.grants);
if (!bound.ok) return none(`the granted fix-check: ${bound.why}`);
if (bound.base !== stop.head || treeOf(cwd, stop.head) !== stop.tree) return none(`the granted fix-check read from ${s12(bound.base)}, not the stop record's head ${s12(stop.head)} and its tree`);
const stamped = [...o.rows.filter(r => r?.skill === 'review-fix-check' && r.grant === g.approval).map(r => [JSON.stringify([reviewRowKey(r), r.review_binding?.started_at ?? r.timestamp ?? null]), r] as const).reduce((m, [k, r]) => (m.has(k) ? m : m.set(k, r)), new Map<string, Row>()).values()];
const foreign = stamped.find(r => r.run !== o.run);
if (!stamped.length || foreign) return none(`grant ${g.approval} buys fix-check rows stamped with run ${o.run}, and the review log holds ${foreign ? `run ${foreign.run}'s` : 'none'}`);
const counted = stamped.find(r => bindFixCheckRow(cwd, r, o.grants, { open: true }).ok);
const read = bindFixCheckRow(cwd, counted ?? stamped.at(-1)!, o.grants);
if (!read.ok) return none(`the granted fix-check${counted ? ', the one counted read the grant bought,' : ''}: ${read.why}`);
const row = counted!, bound = read;
if (bound.base !== stop.head || treeOf(cwd, stop.head) !== stop.tree) return none(`the granted fix-check read from ${s12(bound.base)}, not the ${unstopped ? 'head its grant names' : "stop record's head"} ${s12(stop.head)} and its tree`);
if (bound.commit !== o.head && !(ancestor(cwd, bound.commit, o.head) && ownLinesSame(cwd, o.baseRef, bound.commit, o.head))) return none(`the granted fix-check read ${s12(bound.commit)}, and ${s12(o.head)} is neither it nor a head that only merges the base into it`);
const started = row!.review_binding?.started_at;
if (!(Date.parse(String(stop.at)) < Date.parse(String(claim.at)) && Date.parse(String(claim.at)) < Date.parse(String(started)))) return none(`the stop (${stop.at ?? 'no time'}), the claim (${claim.at ?? 'no time'}) and the fix-check's start (${started ?? 'no time'}) are not recorded in that order`);
const started = row.review_binding?.started_at;
if (!(Date.parse(String(stop.at)) < Date.parse(String(claim.at)) && Date.parse(String(claim.at)) < Date.parse(String(started)))) return none(`the ${unstopped ? 'grant' : 'stop'} (${stop.at ?? 'no time'}), the claim (${claim.at ?? 'no time'}) and the fix-check's start (${started ?? 'no time'}) are not recorded in that order`);
const gated = new Set(o.rows.flatMap(r => findingsOf(r).filter(f => f.gate !== undefined).flatMap(f => [f.ledger_id, f.fingerprint])));
const asked = new Set<string>(Array.isArray(row!.hunks?.fix_list) ? row!.hunks.fix_list : []);
const ids = g.findings!.filter(name => asked.has(name) && !isSecurityFinding(name) && o.open.filter(b => nameOf(b) === name).length === 1 && !o.open.some(b => typeof b !== 'string' && b.fingerprint === name) && !gated.has(name));
const asked = new Set<string>(Array.isArray(row.hunks?.fix_list) ? row.hunks.fix_list : []);
const listed = g.findings!.length ? g.findings! : [...asked];
const ids = listed.filter(name => asked.has(name) && !isSecurityFinding(name) && o.open.filter(b => nameOf(b) === name).length === 1 && !o.open.some(b => typeof b !== 'string' && b.fingerprint === name) && !gated.has(name));
const unasked = g.findings!.filter(name => !asked.has(name));
const unnamed = g.findings!.filter(name => asked.has(name) && !ids.includes(name));
const why = [...(unasked.length ? [`the fix list its reader was given does not name ${unasked.join(', ')}`] : []), ...(unnamed.length ? [`grant ${g.approval} names ${unnamed.join(', ')}, which no open blocker carries alone`] : [])].join('; ');
+15 -2
View File
@@ -4,7 +4,7 @@ import { closeSync, constants, fstatSync, lstatSync, mkdirSync, openSync, readFi
import { join, resolve } from 'node:path';
import { deriveReviewStatus, isCriticalFinding, isOpenByAction, readJsonl } from './headless-artifacts';
import { resultLine, type ResultCodeName } from './result-codes';
import { readRunRecord } from './ship-run-record';
import { readRunRecord, thisRunOwner } from './ship-run-record';
const DIFF_REVIEWS = new Set(['review', 'review-fix-check', 'adversarial-review', 'codex-review', 'design-review-lite', 'ship']);
const SHARED_LIBS_COVERAGE_VERSION = 1;
@@ -210,7 +210,7 @@ export function captureReviewStart(skill: string, env = process.env, fixRange =
const token = crypto.randomUUID();
writeFileSync(join(dir, `${token}.json`), JSON.stringify({
skill, repo: env.GSTACK_REVIEW_REPO, branch: env.GSTACK_REVIEW_BRANCH,
wtree: env.GSTACK_STAMP_WTREE, started_at: new Date().toISOString(),
wtree: env.GSTACK_STAMP_WTREE, started_at: new Date().toISOString(), ...(o => (o ? { owner: o } : {}))(thisRunOwner()),
...(fixBase ? { scope: 'fix-range', fix_base: fixBase } : {}),
...(claimed?.claim ? { fix_check: { base: claimed.claim.stop_head, run: claimed.run, grant: claimed.claim.grant, pr: claimed.claim.pr ?? claimed.pr } } : {}),
}), { mode: 0o600, flag: 'wx' });
@@ -496,6 +496,19 @@ const hunksFile = (cwd: string) => {
return r.status === 0 && r.stdout.trim() ? resolve(cwd, r.stdout.trim()) : '';
};
/**
* The hunks a claimed fix-check reads, built by gstack (GST-3546): git diff <the claimed grant's head> HEAD, the exact bytes
* bindFixCheckRow later compares, so a thread never hand-builds a partial or stale packet. Undefined when this checkout's run
* record holds no open claim, or git cannot diff it (the caller's --hunks file stands then).
*/
export function claimedFixCheckHunks(cwd: string): { base: string; text: string } | undefined {
const read = readRunRecord(cwd);
const base = read.kind === 'record' && read.record.state === 'open' ? read.record.claim?.stop_head : undefined;
if (!base) return undefined;
const r = spawnSync('git', ['diff', base, 'HEAD'], { cwd, encoding: 'utf8', timeout: 60_000, maxBuffer: 256 * 1024 * 1024 });
return r.status === 0 && r.stdout.trim() ? { base, text: r.stdout } : undefined;
}
/** The ledger ids, path:line:category fingerprints and a-… approval ids a fix list names: the only grant ids its clean fix-check can close. */
export function fixListNames(text: string): string[] {
return [...new Set(text.split(/[\s`'"(),;]+/).map(t => t.replace(/[.:]+$/, '')).filter(t => t.includes('#') || /:\d+:/.test(t) || /^a-[0-9a-f]{12}$/.test(t)))].sort();
+2 -2
View File
@@ -18,7 +18,7 @@ import { AgentModelError, resolveAgentModel } from './agent-model';
import { BriefError, briefFile, checkoutRoot, checkoutTree, promptHash, renderBrief, sliceDiff, sliceNote, withWorkspace, type BriefRole, type SectionTexts, type Slots } from './review-brief';
import { REVIEW_DIFF_MAX_BYTES, disclosureDigest } from './review-exclude';
import { appendEvent, readerKey } from './review-ledger';
import { recordFixCheckHunks } from './review-evidence';
import { claimedFixCheckHunks, recordFixCheckHunks } from './review-evidence';
import { policySelection, selectFor } from './review-selection';
import { SPECIALISTS, diffCommand, type Dispatch } from './review-depth';
import { TARGETED_RULES, parseClassList, targetedBriefSha, targetedRead } from './review-targeted';
@@ -250,7 +250,7 @@ export function renderStage(m: Manifest, stage: Stage, t: SectionTexts, diffFor:
if (role === 'fix-check') {
const read = (f: string | undefined, what: string) => { if (!f) return undefined; try { return fs.readFileSync(f, 'utf8'); } catch { throw new BriefError(`cannot read the fix-check ${what} ${f}`); } };
const fc = m.fix_check!;
Object.assign(slots, { fix_list: read(fc.fix_list, 'fix list'), hunks: read(fc.hunks, 'hunks'), tests: read(fc.tests, 'tests'), callers: read(fc.callers, 'callers') });
Object.assign(slots, { fix_list: read(fc.fix_list, 'fix list'), hunks: claimedFixCheckHunks(process.cwd())?.text ?? read(fc.hunks, 'hunks'), tests: read(fc.tests, 'tests'), callers: read(fc.callers, 'callers') });
recordFixCheckHunks(process.cwd(), slots.hunks ?? '', m.ledger, slots.fix_list ?? '');
}
let targeted = {};
+38 -9
View File
@@ -15,26 +15,48 @@ import { isSecurityFinding, opaqueFindingId, REDACTED_FINDING, REDACTED_REASON }
export const ROUND_GRANT_KINDS = ['extra-round', 'fix-check'] as const;
export type RoundGrantKind = (typeof ROUND_GRANT_KINDS)[number];
/** stop_run and findings: a fix-check grant's stop (the run that stopped at head) and the finding ids it is for. */
export interface ReviewRoundGrant { kind: RoundGrantKind; head: string; pr: number; by: string; reason: string; at: string; approval: string; stop_run?: string; findings?: string[] }
/**
* One grant kind (GST-3546): a fix-check grant names its head (a stop record's head, or the reviewed head a post-review edit
* follows, with no stop) and buys one scoped fix-check from it. An owner's `review_loop_grant <head>` approval row reads as the
* same grant (legacy, pr 0: it names no PR, so it binds to whichever PR claims it), so the planner, claim and write accept
* either row.
*/
export interface ReviewRoundGrant { kind: RoundGrantKind; head: string; pr: number; by: string; reason: string; at: string; approval: string; stop_run?: string; findings?: string[]; legacy?: true }
export const STOP_RUN = /^[\w.:-]{1,120}$/;
export const FINDING_ID = /^[\w.:/#@-]{1,200}$/;
const SCOPE = /^review_round_grant ([0-9a-f]{40}) pr=([1-9]\d*) kind=(extra-round|fix-check)(?: stop=(\S+) findings=(\S+))?$/;
export const LEGACY_GRANT = /\breview_loop_grant\s+([0-9a-f]{7,40})\b/;
/** Scopes recorded by their own commands, whose text may mention a grant without being one. */
export const OTHER_GRANT_ROW = /^\s*(ruled_note|gate_disposition|review_loop_exception|test_lane_exception|review_round_grant)\b/;
const ASK = /^review_round_grant (extra-round|fix-check) at ([0-9a-f]{40}) for pr ([1-9]\d*): (\S(?:.*\S)?)$/;
export const REVIEW_ROUND_GRANT_SCOPE = /^\s*review_round_grant\b/;
export const reviewRoundGrantRow = (head: string, pr: number, kind: RoundGrantKind, reason: string, stop?: { run: string; findings: readonly string[] }) =>
({ scope: `review_round_grant ${head} pr=${pr} kind=${kind}${stop ? ` stop=${stop.run} findings=${stop.findings.join(',')}` : ''}`, ask: `review_round_grant ${kind} at ${head} for pr ${pr}: ${reason}` });
/** The ask's cap (lib/approval-record.ts CAPS.ask); a longer reason is cut with an ellipsis and its full words stay in --words. */
export const ROUND_GRANT_ASK_MAX = 300;
export function reviewRoundGrantRow(head: string, pr: number, kind: RoundGrantKind, reason: string, stop?: { run: string; findings: readonly string[] }) {
const lead = `review_round_grant ${kind} at ${head} for pr ${pr}: `;
const room = ROUND_GRANT_ASK_MAX - lead.length;
const said = reason.length <= room ? reason : `${reason.slice(0, room - 1).trimEnd()}…`;
return { scope: `review_round_grant ${head} pr=${pr} kind=${kind}${stop ? ` stop=${stop.run} findings=${stop.findings.join(',')}` : ''}`, ask: lead + said };
}
export function reviewRoundGrants(rows: readonly ApprovalRow[]): ReviewRoundGrant[] {
export function reviewRoundGrants(rows: readonly ApprovalRow[], resolve?: (sha: string) => string | undefined): ReviewRoundGrant[] {
const out: ReviewRoundGrant[] = [];
for (const r of rows) {
if (r.outcome !== 'approved' || isGstackActorName(r.by)) continue;
const s = SCOPE.exec(r.scope), a = ASK.exec(r.ask);
if (r.outcome !== 'approved' || !s || !a || isGstackActorName(r.by)) continue;
if (!s && !OTHER_GRANT_ROW.test(r.scope)) {
const l = LEGACY_GRANT.exec(`${r.ask} ${r.scope}`);
const head = l ? (l[1]!.length === 40 ? l[1]! : resolve?.(l[1]!)) : undefined;
if (head) out.push({ kind: 'fix-check', head: head.toLowerCase(), pr: 0, by: r.by, reason: r.ask, at: r.recorded_at, approval: r.id, findings: [], legacy: true });
continue;
}
if (!s || !a) continue;
if (a[1] !== s[3] || a[2] !== s[1] || a[3] !== s[2]) continue;
const findings = s[5]?.split(',');
if ((s[3] === 'fix-check') !== (s[4] !== undefined) || (s[4] !== undefined && (!STOP_RUN.test(s[4]) || !findings!.every(f => FINDING_ID.test(f))))) continue;
out.push({ kind: s[3] as RoundGrantKind, head: s[1]!, pr: Number(s[2]), by: r.by, reason: a[4]!, at: r.recorded_at, approval: r.id, ...(s[4] ? { stop_run: s[4], findings } : {}) });
if ((s[3] !== 'fix-check' && s[4] !== undefined) || (s[4] !== undefined && (!STOP_RUN.test(s[4]) || !findings!.every(f => FINDING_ID.test(f))))) continue;
out.push({ kind: s[3] as RoundGrantKind, head: s[1]!, pr: Number(s[2]), by: r.by, reason: a[4]!, at: r.recorded_at, approval: r.id, ...(s[4] ? { stop_run: s[4], findings } : s[3] === 'fix-check' ? { findings: [] } : {}) });
}
return out;
}
@@ -54,9 +76,16 @@ export function publicRoundGrant(g: ReviewRoundGrant, ruled: readonly RuledNote[
export function readReviewRoundGrants(cwd: string, env: Env = process.env): ReviewRoundGrant[] {
const loc = locate({ cwd, env });
return 'code' in loc ? [] : reviewRoundGrants(readRecord(loc).rows);
if ('code' in loc) return [];
return reviewRoundGrants(readRecord(loc).rows, sha => {
const r = spawnSync('git', ['rev-parse', '--verify', '--quiet', `${sha}^{commit}`], { cwd, encoding: 'utf8', timeout: 10_000 });
return r.status === 0 ? r.stdout.trim() : undefined;
});
}
/** Whether a grant binds this PR: its own PR, or any PR for a legacy review_loop_grant row, which names none. */
export const grantForPr = (g: Pick<ReviewRoundGrant, 'pr'>, pr: number | undefined) => !g.pr || g.pr === pr;
/** The newest extra-round grant for this PR at exactly this head (a fix-check grant answers a stop instead: lib/pr-review-history.ts grantedStop). */
export const grantAt = (grants: readonly ReviewRoundGrant[], pr: number, head: string) =>
[...grants].reverse().find(g => g.kind === 'extra-round' && g.pr === pr && g.head === head.toLowerCase());
@@ -126,4 +155,4 @@ export function ownLinesSame(repoRoot: string, baseRef: string, a: string, b: st
/** The text after "Review round grant: " in the PR body. */
export const reviewRoundGrantText = (g: ReviewRoundGrant) =>
`${g.kind} at ${g.head.slice(0, 12)} for PR #${g.pr}${g.stop_run ? ` (stop ${g.stop_run}, findings ${g.findings!.join(', ')})` : ''} recorded by ${g.by} at ${g.at}: ${g.reason} (approval ${g.approval})`;
`${g.kind} at ${g.head.slice(0, 12)} for PR #${g.pr}${g.stop_run ? ` (stop ${g.stop_run}, findings ${g.findings!.join(', ')})` : g.kind === 'fix-check' ? ' (no stop: the reviewed head)' : ''} recorded by ${g.by} at ${g.at}: ${g.reason} (approval ${g.approval})`;
+6
View File
@@ -12,6 +12,8 @@ import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import { resultLine } from './result-codes';
import { thisRunOwner } from './ship-run-record';
import { spawnSync } from './spawn-sync';
import {
BudgetError, DEFAULT_TAIL, SUBAGENT_DEFAULT_CAP, DELEGATE_SEGMENT_CALL, DELEGATE_START_CALL, MAX_CHAIN_DEPTH, METER_CONTRACTS, SEGMENTS, SHIP_STEPS,
aboveFloor, admits, applyCredits, applyReading, budgetError, creditsUsed, parseCredits, budgetLine, keepsSmallRun, labelScope, ledgerFileFor, loadCalibration, measureSettled, mintRunId, mutateLedger, newEpoch,
@@ -28,6 +30,8 @@ export type Opts = Record<string, string | true>;
export interface Outcome { stdout: string[]; exit: number }
export interface Ctx { env: NodeJS.ProcessEnv; cwd: string }
const toplevel = (cwd: string) => { const r = spawnSync('git', ['rev-parse', '--show-toplevel'], { cwd, encoding: 'utf8', timeout: 10_000 }); return r.status === 0 ? r.stdout.trim() : ''; };
export function parseArgs(argv: string[], values: string[], flags: string[] = []): Opts {
const out: Opts = {};
for (let i = 0; i < argv.length; i++) {
@@ -270,6 +274,7 @@ export function cmdStart(argv: string[], ctx: Ctx): Outcome {
}
const run = mintRunId();
const dir = runDirFor(ctx.env, run);
const owner = thisRunOwner(), checkout = toplevel(ctx.cwd);
const cal = loadCalibration(str(o, 'calibration'));
const contract = METER_CONTRACTS[meter];
const paths = reviewPaths(ctx.cwd, ctx.env);
@@ -283,6 +288,7 @@ export function cmdStart(argv: string[], ctx: Ctx): Outcome {
marker: paths.marker, review_log: paths.reviewLog, ...(str(o, 'calibration') ? { calibration: path.resolve(str(o, 'calibration')!) } : {}),
...(callFloor !== undefined ? { call_floor: callFloor } : {}), ...(mode === 'observe' ? { mode } : {}),
...(scope === 'tree' || parentCounter ? { meter_scope: 'tree' as const } : {}),
...(checkout ? { checkout } : {}), ...(owner ? { owner } : {}),
};
if (meter === 'capy' && tokensOpt(o, 'reading') === undefined) throw budgetError('BUDGET_READING_MISSING', 'start --meter capy');
if (meter === 'capy') l.meter.baseline = tokensOpt(o, 'reading')!;
+3
View File
@@ -22,6 +22,7 @@ import * as crypto from 'node:crypto';
import * as fs from 'node:fs';
import * as path from 'node:path';
import { withFileLock } from './spend-ledger';
import type { RunOwner } from './ship-run-record';
import { resolveStateRoot } from './state-root';
import { resultLine, type ResultCodeName } from './result-codes';
import { capyDriveFolder } from './autoplan-checkpoint';
@@ -103,6 +104,8 @@ export interface Ledger {
/** tree: the reading is the root thread's counter (a subagent cannot read its own jam id), so every cost line carries TREE_METER. */
meter_scope?: 'tree';
stopped?: { at: string; reason: string; step: string; next: string }; closed_at?: string;
/** The checkout the run ships and the harness it runs under (GST-3546): lib/ship-run-live.ts stops counting an ended or dead run as open. */
checkout?: string; owner?: RunOwner;
/** Where the 100-minute clock starts (lib/ship-clock.ts): created_at, or the resume after a time stop. */
clock_from?: string;
}
+3 -2
View File
@@ -17,7 +17,7 @@ import { reviewPlanTimeoutMs } from './review-collect';
import { classifyDiff } from './review-depth';
import { wtreeFingerprint } from './script-invocation';
import { audit } from './ship-audit';
import { changeRunRecord, openRun, readRunRecord } from './ship-run-record';
import { changeRunRecord, openRun, readRunRecord, thisRunOwner } 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)
@@ -134,7 +134,8 @@ function integrate(cwd: string, base: string, run: string | undefined, r: Report
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;
if (!run) return true;
const opened = changeRunRecord(cwd, 'preflight', run, /^[1-9]\d*$/.test(n) ? { pr: Number(n) } : {});
const owner = thisRunOwner();
const opened = changeRunRecord(cwd, 'preflight', run, { ...(/^[1-9]\d*$/.test(n) ? { pr: Number(n) } : {}), ...(owner ? { owner } : {}) });
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;
+1 -1
View File
@@ -326,7 +326,7 @@ function fixChecked(cwd: string, o: BridgeOpts & { now: string; parent?: string;
for (let k = chain.length - 1; k >= 0; k--) {
const l = chain[k]!;
const g = l.bound?.ok ? (id => grants.find(x => x.id === id && !used.has(x.id)))(l.bound.grant.approval) : grants.filter(g => !used.has(g.id))
.flatMap(g => { const fc = reviewRoundGrants([g]).find(x => x.kind === 'fix-check'); return (fc ? (commitOf(fc.head) === l.from ? [fc.head] : []) : `${g.ask} ${g.scope}`.match(/\b[0-9a-f]{7,40}\b/g) ?? []).map(commitOf).filter(c => !!c && inRange(l, c)).map(stop => ({ g, stop })); })
.flatMap(g => { const fc = reviewRoundGrants([g]).find(x => x.kind === 'fix-check' && !x.legacy); return (fc ? (commitOf(fc.head) === l.from ? [fc.head] : []) : `${g.ask} ${g.scope}`.match(/\b[0-9a-f]{7,40}\b/g) ?? []).map(commitOf).filter(c => !!c && inRange(l, c)).map(stop => ({ g, stop })); })
.reduce<{ g: typeof grants[number]; stop: string } | undefined>((best, c) => (!best || ancestor(best.stop, c.stop) ? c : best), undefined)?.g;
if (g) used.add(g.id);
granted[k] = g;
+59
View File
@@ -0,0 +1,59 @@
/**
* ship-run-live — whether a /ship or review run on this machine still holds gstack upgrades (GST-3546, bin/gstack-capy-session's
* open_run, R75's workflow boundary). The candidates are the ones open_run always read: an unclosed ship-budget ledger written in
* the last 6 hours and an unconsumed review start under 120 minutes old. A candidate no longer holds once its run provably ended:
* its owner process is gone (ownerGone: the harness it ran under exited or the machine restarted; a shared harness such as
* capy-server proves nothing), or the checkout's /ship run record says the run finished or was abandoned and the record is this
* ledger's: the ledger is the one newest ledger for that checkout created at or before the record opened, so neither an earlier
* run's record nor a later run started on the same checkout releases it (for a review start, the record naming the run its claim
* stamped). A stopped run can still claim its fix-check grant and resume, so it keeps
* the hold, and so does a record that is missing, open, legacy, unreadable, older than the ledger or another ledger's.
*/
import * as fs from 'node:fs';
import * as path from 'node:path';
import { ownerGone, readRunRecord, type RunRecord } from './ship-run-record';
export const LEDGER_HOLD_MS = 360 * 60_000;
export const REVIEW_START_HOLD_MS = 120 * 60_000;
const ENDED = new Set(['finished', 'abandoned']);
const recordEnded = (checkout: unknown, ours: (r: RunRecord) => boolean) => {
if (typeof checkout !== 'string' || !checkout) return false;
const read = readRunRecord(checkout);
return read.kind === 'record' && ENDED.has(read.record.state) && ours(read.record);
};
const fresh = (file: string, within: number, now: number) => { try { return now - fs.statSync(file).mtimeMs < within; } catch { return false; } };
const json = (file: string): Record<string, any> | null => { try { const v = JSON.parse(fs.readFileSync(file, 'utf8')); return v && typeof v === 'object' ? v : null; } catch { return null; } };
const dirs = (dir: string) => { try { return fs.readdirSync(dir, { withFileTypes: true }).filter(d => d.isDirectory()).map(d => path.join(dir, d.name)); } catch { return []; } };
const files = (dir: string, ext: string) => { try { return fs.readdirSync(dir).filter(n => n.endsWith(ext)).map(n => path.join(dir, n)); } catch { return []; } };
/** The first run that still holds upgrades, as "<kind> run <id> (<file>)", or undefined; ended lists what no longer holds and why. */
export function liveRun(stateRoot: string, now = Date.now()): { live?: string; ended: string[] } {
const ended: string[] = [];
const ledgers = dirs(path.join(stateRoot, 'ship-runs')).map(d => ({ file: path.join(d, 'budget.json'), l: json(path.join(d, 'budget.json')) })).filter(x => x.l?.kind === 'gstack-ship-budget');
const created = (l: Record<string, any>) => Date.parse(String(l.created_at));
const owns = (l: Record<string, any>) => (r: RunRecord) => {
const before = ledgers.filter(x => x.l!.checkout === l.checkout && created(x.l!) <= Date.parse(r.started_at)).map(x => created(x.l!));
const newest = Math.max(...before);
return created(l) === newest && before.filter(t => t === newest).length === 1;
};
for (const { file, l } of ledgers) {
if (!fresh(file, LEDGER_HOLD_MS, now)) continue;
if (!l || l.closed_at) continue;
const id = path.basename(path.dirname(file));
if (ownerGone(l.owner)) { ended.push(`/ship run ${id}: its owner process ${l.owner.pid} is gone`); continue; }
if (recordEnded(l.checkout, owns(l))) { ended.push(`/ship run ${id}: the run record in ${l.checkout} has ended`); continue; }
return { live: `/ship run ${id} (${file})`, ended };
}
for (const project of dirs(path.join(stateRoot, 'projects'))) {
for (const file of files(path.join(project, '.review-starts'), '.json')) {
if (!fresh(file, REVIEW_START_HOLD_MS, now)) continue;
const s = json(file);
const id = path.basename(file, '.json');
if (ownerGone(s?.owner)) { ended.push(`review run ${id}: its owner process ${s!.owner.pid} is gone`); continue; }
if (s?.fix_check && recordEnded(s.repo, r => r.run === s.fix_check.run)) { ended.push(`review run ${id}: the /ship run record in ${s.repo} has ended`); continue; }
return { live: `review run ${id} (${file})`, ended };
}
}
return { ended };
}
+53 -3
View File
@@ -9,6 +9,7 @@
*/
import { createHash } from 'node:crypto';
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import type { RecordError } from './approval-record';
import { spawnSync } from './spawn-sync';
@@ -19,6 +20,8 @@ export interface RunRecord {
stop?: { head: string; tree: string };
claim?: { grant: string; stop_run?: string; stop_head: string; findings: string[]; pr?: number };
ended_by?: string; reason?: string;
/** The harness process preflight ran under (GST-3546): once it is provably gone, abandon takes the run at any age and it stops holding gstack upgrades. */
owner?: RunOwner;
}
export type RunRead =
| { kind: 'none'; file: string }
@@ -29,8 +32,54 @@ export type RunCommand = 'preflight' | 'beat' | 'stop' | 'claim' | 'skill-end' |
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. */
/** A run that beat this recently is working: abandon refuses it, unless its owner process is provably gone. */
export const ABANDON_AFTER_MS = 60 * 60_000;
/**
* The harness a /ship run belongs to: the first ancestor that is not a shell or one of gstack's own bun wrappers (bin/gstack-harness-pid.sh walks shells the same way), with
* this machine, its boot and the process's start time. shared marks a harness every session on the machine runs under
* (capy-server, GSTACK_SHARED_HARNESSES), whose liveness says nothing about one run.
*/
export interface RunOwner { machine: string; boot: string; pid: number; start: number; comm: string; shared?: true }
const WRAPPERS = new Set(['bash', 'sh', 'zsh', 'dash', 'ksh', 'mksh', 'ash', 'fish', 'busybox', 'bun', 'timeout', 'env', 'flock', 'xargs']);
const SHARED_HARNESSES = new Set(['capy-server']);
function procOf(pid: number): { ppid: number; start: number; comm: string } | null {
try {
const stat = fs.readFileSync(`/proc/${pid}/stat`, 'utf8');
const f = stat.slice(stat.lastIndexOf(')') + 2).split(' ');
return { ppid: Number(f[1]), start: Number(f[19]), comm: stat.slice(stat.indexOf('(') + 1, stat.lastIndexOf(')')).replace(/^-/, '') };
} catch { return null; }
}
const readTrim = (f: string) => { try { return fs.readFileSync(f, 'utf8').trim(); } catch { return ''; } };
const thisMachine = () => `${os.hostname()}/${readTrim('/etc/machine-id')}`;
/** This process's run owner, or null where /proc cannot say (off Linux): then only the run record's state and age apply. */
export function thisRunOwner(from = process.ppid): RunOwner | null {
let pid = from;
for (let hops = 0; hops < 8; hops++) {
const p = procOf(pid);
if (!p) return null;
if (WRAPPERS.has(p.comm) && p.ppid <= 1) return null;
if (!WRAPPERS.has(p.comm)) {
const boot = readTrim('/proc/sys/kernel/random/boot_id');
return boot ? { machine: thisMachine(), boot, pid, start: p.start, comm: p.comm, ...(SHARED_HARNESSES.has(p.comm) ? { shared: true as const } : {}) } : null;
}
pid = p.ppid;
}
return null;
}
/**
* Whether a run's owner is provably gone: on this machine, it ran before the last boot, or its pid now names no process or one
* that started at another time. A shared harness, another machine, a missing or malformed owner proves nothing.
*/
export function ownerGone(o: unknown): boolean {
const w = o as RunOwner | undefined;
if (!w || typeof w !== 'object' || w.shared || !Number.isInteger(w.pid) || w.pid <= 1 || !Number.isFinite(w.start) || typeof w.boot !== 'string' || w.machine !== thisMachine()) return false;
if (w.boot !== readTrim('/proc/sys/kernel/random/boot_id')) return true;
const p = procOf(w.pid);
return !p || p.start !== w.start;
}
const STATES: readonly RunState[] = ['open', 'stopped', 'finished', 'abandoned'];
const SHA = /^[0-9a-f]{40,64}$/;
@@ -185,13 +234,14 @@ export function finishRun(cwd: string, named: readonly string[] | null): { remov
/**
* 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.
* digest), and never a record whose beat_at is under ABANDON_AFTER_MS old while its owner may still run. A legacy marker or an unreadable
* record has no beat, and a record whose owner process is provably gone (ownerGone) is no longer working, so either goes at 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;
if (read.kind !== 'record' || ownerGone(read.record.owner)) 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
@@ -484,6 +484,10 @@ export const KNOWN_WINDOWS_INCOMPATIBLE: Array<{ file: string; reason: string }>
file: 'test/fix-check-clearing.test.ts',
reason: 'drives bin/gstack-ship-receipt, gstack-approvals, gstack-review-log, gstack-review-plan, gstack-review-scope, gstack-review-read and gstack-ship-release (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-ruling-path.test.ts',
reason: 'drives bin/gstack-ship-receipt, gstack-approvals, gstack-review-log, gstack-review-plan, gstack-review-scope, gstack-ship-run and gstack-ship-release (shebangs) through test/helpers/ship-bin-fixture.ts like test/fix-check-clearing.test.ts, and reads /proc for run owners; a bin spawn fails on windows-latest the same way (first-bin-spawn failure class of test/ship-uid-sidecar.test.ts)',
},
{
file: 'test/ship-receipt-claim-fail-closed.test.ts',
reason: 'drives bin/gstack-ship-preflight, gstack-ship-receipt, gstack-approvals and gstack-review-log (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)',
+13 -8
View File
@@ -185,12 +185,15 @@ describe('a granted, clean fix-check closes exactly its grant\'s findings at wri
describe('a fix-check reader given only part of the fix closes nothing', () => {
// Value: protects=the hunks a granted fix-check read cover the whole stop-to-fix diff; fails_when=hunks over one of two changed
// files bind and close the grant; seam=bindFixCheckRow
test('hunks covering only part of the stop..fix diff close nothing', () => {
// files bind and close the grant, or a hand-built partial packet reaches the claimed reader (GST-3546, gskills#25: gstack
// now builds the packet from git diff <claimed head> HEAD); seam=gstack-review-plan --fix-check-prompt, bindFixCheckRow
test('a hand-built partial packet is replaced by git diff <stop> HEAD, and a row recording partial hunks still closes nothing', () => {
const g = grantedRun({ sameRun: false, extra: { 'src/y.ts': 'export const y = 1;\n' }, hunkPaths: ['src/x.ts'] });
const row = rowsOf(g).filter(r => r.skill === 'review-fix-check').at(-1)!;
expect(row.hunks.paths).toEqual(['src/x.ts']);
expect(bindFixCheckRow(g.f.work, row, grantsOf(g))).toMatchObject({ ok: false, why: expect.stringContaining('leave out src/y.ts') });
expect(row.hunks).toMatchObject(hunksDigest(g.f.git('diff', g.S, g.F).stdout));
expect(bindFixCheckRow(g.f.work, row, grantsOf(g))).toMatchObject({ ok: true });
const partial = { ...row, hunks: { ...row.hunks, ...hunksDigest(g.f.git('diff', g.S, g.F, '--', 'src/x.ts').stdout) } };
expect(bindFixCheckRow(g.f.work, partial, grantsOf(g))).toMatchObject({ ok: false, why: expect.stringContaining('leave out src/y.ts') });
});
});
@@ -199,9 +202,11 @@ describe('harness-evals#504: a fix-check grant answering a stop after a gate-cla
// fails_when=a fix-check that ran before the grant spends it, or one that carries it leaves it unspent; seam=grantSpent
test('a grant is spent by the fix-check that carries it or starts after it, never by an earlier one', () => {
const g = { approval: 'a-2', at: '2026-11-21T01:00:00.000Z' };
expect(grantSpent([{ skill: 'review-fix-check', review_binding: { started_at: '2026-11-21T00:59:00.000Z' } }], g)).toBe(false);
expect(grantSpent([{ skill: 'review-fix-check', review_binding: { started_at: '2026-11-21T01:01:00.000Z' } }], g)).toBe(true);
expect(grantSpent([{ skill: 'review-fix-check', grant: 'a-2', review_binding: { started_at: '2026-11-21T00:00:00.000Z' } }], g)).toBe(true);
const read = (started_at: string) => ({ skill: 'review-fix-check', completed: true, converged: true, status: 'clean', review_binding: { state: 'verified', started_at } });
expect(grantSpent([{ ...read('2026-11-21T01:01:00.000Z'), converged: false }], g)).toBe(false);
expect(grantSpent([read('2026-11-21T00:59:00.000Z')], g)).toBe(false);
expect(grantSpent([read('2026-11-21T01:01:00.000Z')], g)).toBe(true);
expect(grantSpent([{ ...read('2026-11-21T00:00:00.000Z'), grant: 'a-2' }], g)).toBe(true);
});
// Value: protects=the same through the CLI: --round-grant and --stop after --last fix-check with a gate-class fix plan next=fix-check
@@ -265,7 +270,7 @@ describe('clearing refuses every gap GSTA-665\'s trail reads found in #4546 (lib
expect(clear({ run: 'fc9' }).ids).toEqual([]);
});
test('a spent grant (a second stamped row) closes nothing', () => {
expect(clear({ rows: [...base.rows, { ...fixRow(), run: 'fc2', commit_full: g.S, findings: [{ fingerprint: 'x' }] }] })).toMatchObject({ ids: [], why: expect.stringContaining('holds 2') });
expect(clear({ rows: [...base.rows, { ...fixRow(), run: 'fc2', commit_full: g.S, findings: [{ fingerprint: 'x' }] }] })).toMatchObject({ ids: [], why: expect.stringContaining("holds run fc2's") });
});
test('a row with another fix_check_base, or an agent range_base that disagrees, closes nothing', () => {
const fork = g.f.git('merge-base', 'origin/main', 'HEAD').stdout.trim();
+6 -3
View File
@@ -109,10 +109,12 @@ describe('which grant answers which stop (lib/pr-review-history.ts grantedStop)'
expect(answer(body, [fixGrant('a-000000000001')])).toMatchObject({ ok: false });
expect(prReviewHistory(stopped())).toMatchObject({ full: 3, rounds: 3, stubs: 2, heads: 2 });
});
test('a fix-check row that lacks its stop, or an extra-round row naming one, is no grant', () => {
test('a fix-check row with no stop answers its own head and no stop record (GST-3546); an extra-round row naming a stop is no grant', () => {
const bare = row('a-000000000004', { scope: 'review_round_grant ' + S + ' pr=7 kind=fix-check', ask: 'review_round_grant fix-check at ' + S + ' for pr 7: x' });
const extra = row('a-000000000005', { scope: 'review_round_grant ' + S + ' pr=7 kind=extra-round stop=ro findings=f#1', ask: 'review_round_grant extra-round at ' + S + ' for pr 7: x' });
expect(reviewRoundGrants([bare, extra])).toEqual([]);
expect(reviewRoundGrants([bare, extra])).toEqual([expect.objectContaining({ kind: 'fix-check', head: S, pr: 7, approval: 'a-000000000004', findings: [] })]);
expect(reviewRoundGrants([bare])[0]!.stop_run).toBeUndefined();
expect(answer(placeRunEntry(stopped(), grantMarker({ head: S, run: 'fc1', grant: 'a-000000000004' })), [bare])).toMatchObject({ ok: false });
});
});
@@ -156,7 +158,8 @@ describe('the CLI seams', () => {
const ok = r.run('gstack-approvals', ['round-grant', '--pr', '7', '--head', s.slice(0, 10), '--kind', 'fix-check', '--stop-run', 'ro', '--findings', 'p1/outside-voice#1,p1/red-team#2', '--reason', 'fixable blocker', '--by', 'Captain GStack Minder (GSTA-36)']);
expect(ok.status, ok.stderr).toBe(0);
expect(r.run('gstack-approvals', ['list', '--json']).stdout).toContain('review_round_grant ' + s + ' pr=7 kind=fix-check stop=ro findings=p1/outside-voice#1,p1/red-team#2');
expect(r.run('gstack-approvals', ['round-grant', '--pr', '7', '--head', s, '--kind', 'fix-check', '--reason', 'x', '--by', 'Captain GStack Minder']).status).toBe(2);
expect(r.run('gstack-approvals', ['round-grant', '--pr', '7', '--head', s, '--kind', 'fix-check', '--stop-run', 'ro', '--reason', 'x', '--by', 'Captain GStack Minder']).status).toBe(2);
expect(r.run('gstack-approvals', ['round-grant', '--pr', '7', '--head', s, '--kind', 'fix-check', '--findings', 'f#1', '--reason', 'x', '--by', 'Captain GStack Minder']).status).toBe(2);
expect(r.run('gstack-approvals', ['round-grant', '--pr', '7', '--head', s, '--kind', 'extra-round', '--stop-run', 'ro', '--findings', 'f#1', '--reason', 'x', '--by', 'Captain GStack Minder']).status).toBe(2);
expect(r.run('gstack-approvals', ['round-grant', '--pr', '7', '--head', s, '--kind', 'fix-check', '--stop-run', 'ro', '--findings', 'f#1', '--reason', 'x', '--by', 'gstack']).status).toBe(2);
});
+313
View File
@@ -0,0 +1,313 @@
/**
* GST-3546: one grant path to a receipt after a Captain rules at the round cap. Before, three crews had no route that ended in a
* receipt (gbrain #10068, gskills #23-#25, gstack #4712): an owner's review_loop_grant row was planned but claim refused it
* (GRANT_UNKNOWN) and write refused RECEIPT_BLOCKER_OPEN until per-finding rule rows were written; a stop the tools could not bind
* (STOP_UNBOUND) or a post-review docs edit had no grant at all; a malformed fix-check row (converged:false, a hand-built partial
* packet) spent the grant; a verbatim owner reason overflowed round-grant's 300-character ask; and an ended /ship run held gstack
* upgrades on its machine for an hour. Fixtures are synthetic; each case follows its report's shape.
*/
import { afterEach, describe, expect, setDefaultTimeout, test } from 'bun:test';
import { spawn, spawnSync, type ChildProcess } from 'node:child_process';
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import type { ApprovalRow } from '../lib/approval-record';
import { bindFixCheckRow, grantSpent } from '../lib/fix-check-clearing';
import { readReviewRoundGrants, reviewRoundGrantRow, reviewRoundGrants } from '../lib/review-round-grant';
import { liveRun } from '../lib/ship-run-live';
import { abandonRefusal, readRunRecord, thisRunOwner, type RunOwner } from '../lib/ship-run-record';
import { RELEASE, shipFixture, type ShipFx } from './helpers/ship-bin-fixture';
setDefaultTimeout(120_000);
const BIN = path.dirname(RELEASE);
const fxs: ShipFx[] = [];
const kids: ChildProcess[] = [];
const tmps: string[] = [];
afterEach(() => {
while (fxs.length) fxs.pop()!.cleanup();
for (const k of kids.splice(0)) k.kill('SIGKILL');
for (const d of tmps.splice(0)) fs.rmSync(d, { recursive: true, force: true });
});
const ID = 'p1/outside-voice#1', FP = 'src/x.ts:1:outside-voice';
const ID2 = 'p1/red-team#2', FP2 = 'src/x.ts:1:red-team';
const CAPTAIN = 'Captain GStack Minder (GSTA-36)';
const TEST = "import { expect, test } from 'bun:test';\ntest('a', () => { expect(2).toBe(2); });\n";
const open = (ledger_id: string, fingerprint: string) => ({ fingerprint, severity: 'CRITICAL', action: 'open', blocking: true, ledger_id, raised_by: 'outside-voice' });
const CLEAN = { completed: true, converged: true, status: 'clean', issues_found: 0, critical: 0, informational: 0, findings: [] };
const ok = (r: { status: number | null; stderr: string; stdout: string }) => { expect(r.status, r.stderr + r.stdout).toBe(0); return r.stdout; };
const headOf = (f: ShipFx) => f.git('rev-parse', 'HEAD').stdout.trim();
const marker = (f: ShipFx, run: string) => fs.writeFileSync(path.resolve(f.work, f.git('rev-parse', '--git-path', 'gstack-ship-run').stdout.trim()), run + '\n');
const grantId = (out: string) => /APPROVAL_RECORDED: (a-[0-9a-f]{12})/.exec(out)?.[1] ?? '';
interface Cap { f: ShipFx; run: (bin: string, args: string[]) => ReturnType<ShipFx['run']>; S: string; body: string; since: string }
/** Round 2 stops at S with the given blockers open, and the run records no stop (gskills#23's STOP_UNBOUND, #4712's flow). */
function atCap(blockers: Record<string, unknown>[]): Cap {
const f = shipFixture({ 'src/x.ts': 'export const x = 1;\n' }, { 'src/x.ts': 'export const x = 2;\n', 'test/x.test.ts': TEST });
fxs.push(f);
const run = (bin: string, args: string[]) => f.run(path.join(BIN, bin), args, { GSTACK_APPROVALS_MIRROR: '0' });
const body = path.join(f.root, 'body.md');
fs.writeFileSync(body, 'Fixes a thing.\n');
const since = new Date(Date.now() - 1000).toISOString();
marker(f, 'r2');
const start = ok(run('gstack-review-log', ['--start', 'review'])).trim();
ok(run('gstack-review-log', [JSON.stringify({ skill: 'review', timestamp: new Date().toISOString(), via: 'ship', review_scope: 'frozen', pass: 2, ...(blockers.length ? { completed: true, converged: false, status: 'issues_found', issues_found: blockers.length, critical: blockers.length, informational: 0, findings: blockers } : CLEAN) }), '--finish', start]));
return { f, run, S: headOf(f), body, since };
}
/** The fix commit, the claim, and one fix-check reader through the logger with the fix list given; gstack builds the hunks. */
function fixCheck(c: Cap, o: { grant: string; run: string; fixList: string; row?: Record<string, unknown>; files?: Record<string, string>; claim?: boolean }) {
if (o.files) { c.f.write(o.files); c.f.commit('fix'); }
if (o.claim !== false) ok(c.run('gstack-ship-receipt', ['claim', '--body', c.body, '--pr', '7', '--run', o.run, '--grant', o.grant]));
const start = ok(c.run('gstack-review-log', ['--start', 'review-fix-check'])).trim();
const files = Object.entries({ fixes: o.fixList, tests: '3 pass\n' }).map(([k, v]) => { const p = path.join(c.f.root, k + '.txt'); fs.writeFileSync(p, v); return p; });
const prompt = c.run('gstack-review-plan', ['--fix-check-prompt', '--fix-list', files[0]!, '--tests', files[1]!]);
ok(prompt);
ok(c.run('gstack-review-log', [JSON.stringify({ skill: 'review-fix-check', timestamp: new Date().toISOString(), via: 'ship', review_scope: 'frozen', ...CLEAN, ...o.row }), '--finish', start]));
return prompt;
}
function write(c: Cap, run: string) {
const loop = path.join(c.f.root, 'loop.json');
ok(c.run('gstack-review-scope', ['summary', '--since', c.since, '--no-ledger', '--out', loop]));
return c.run('gstack-ship-receipt', ['write', '--pr', '7', '--run', run, '--base', 'main', '--session-kind', 'unattended', '--review-loop', '@' + loop, '--body', c.body]);
}
const rows = (c: Cap) => c.run('gstack-review-read', []).stdout.split('\n---CONFIG---')[0]!.split('\n').flatMap(l => { try { const v = JSON.parse(l); return v && typeof v === 'object' ? [v] : []; } catch { return []; } });
const grantsOf = (c: Cap) => readReviewRoundGrants(c.f.work, { ...process.env, GSTACK_STATE_ROOT: c.f.state, GSTACK_HOME: c.f.state });
describe('one grant kind: planner, claim and receipt accept either row (GST-3546, #4712)', () => {
const row = (o: Partial<ApprovalRow>): ApprovalRow => ({ schema_version: 1, id: 'a-000000000009', date: '2026-11-22', recorded_at: '2026-11-22T00:00:00Z', words: 'do it', by: CAPTAIN, pending: 'none', outcome: 'approved', source: 'manual', branch: 'b', ask: '', scope: '', ...o });
// Value: protects=an owner's review_loop_grant row is the same fix-check grant claim and write read; fails_when=it parses as
// nothing (GRANT_UNKNOWN), or a ruling row that only mentions one becomes a grant; seam=reviewRoundGrants
test('a review_loop_grant row reads as a fix-check grant naming its head and no PR; other rows that mention one do not', () => {
const S = 'a'.repeat(40);
expect(reviewRoundGrants([row({ ask: `Owner grant: one scoped fix-check (review_loop_grant ${S})`, scope: 'this /ship invocation' })]))
.toEqual([expect.objectContaining({ kind: 'fix-check', head: S, pr: 0, legacy: true, findings: [] })]);
expect(reviewRoundGrants([row({ ask: 'grant (review_loop_grant abcdef1)', scope: 'x' })], s => (s === 'abcdef1' ? S : undefined))[0]?.head).toBe(S);
expect(reviewRoundGrants([row({ ask: 'grant (review_loop_grant abcdef1)', scope: 'x' })])).toEqual([]);
expect(reviewRoundGrants([row({ ask: `ruled_note x at ${S}: fixed after review_loop_grant ${S}`, scope: `ruled_note x ${S}` })])).toEqual([]);
});
// Value: protects=#4712: the planner-accepted review_loop_grant also claims, stamps the fix-check and closes the blocker its
// reader was given, with no per-finding rule rows; fails_when=claim prints GRANT_UNKNOWN or write RECEIPT_BLOCKER_OPEN;
// seam=gstack-ship-receipt claim and write
test('#4712: a review_loop_grant row claims, and its clean fix-check closes the blocker at write', () => {
const c = atCap([open(ID, FP)]);
const args = ['add', '--ask', `Owner grant: one scoped fix-check after round 2 (review_loop_grant ${c.S})`, '--words', 'do it', '--by', CAPTAIN, '--scope', 'this /ship invocation', '--json'];
const self = c.run('gstack-approvals', args);
expect([self.status, self.stderr]).toEqual([2, expect.stringContaining('never the run\'s own')]);
for (const spelling of [['--ask', `grant (review_loop_grant: ${c.S})`], ['--scope', 'review_loop_exception x', '--ask', `grant (review_loop_grant ${c.S})`]]) {
const r = c.run('gstack-approvals', ['add', ...spelling, '--words', 'do it', '--by', CAPTAIN, '--json']);
expect([r.status, r.stderr]).toEqual([2, expect.stringContaining('never the run\'s own')]);
}
const id = JSON.parse(ok(c.run('gstack-approvals', [...args, '--owner-ref', 'GSTA-36:2026-11-22T12:00:00Z']))).added[0] as string;
fixCheck(c, { grant: id, run: 'r2', fixList: 'fix ' + ID + '\n', files: { 'src/x.ts': 'export const x = 3;\n' } });
const row = rows(c).filter(r => r.skill === 'review-fix-check').at(-1)!;
expect(row).toMatchObject({ fix_check_base: c.S, grant: id, pr: 7 });
expect(bindFixCheckRow(c.f.work, row, grantsOf(c))).toMatchObject({ ok: true });
const w = write(c, 'r2');
expect(w.status, w.stderr).toBe(0);
expect(w.stderr).toContain(`FIX_CHECK_CLEAR: grant=${id} run=r2 closed=${ID}`);
});
// Value: protects=GST-3546: gstack-review-plan --grant takes a round-grant fix-check row too, at the head it names;
// fails_when=--grant refuses it ("no approved row ... naming review_loop_grant"); seam=gstack-review-plan --grant
test('the planner plans the fix-check for a round-grant fix-check row', () => {
const c = atCap([open(ID, FP)]);
const id = grantId(ok(c.run('gstack-approvals', ['round-grant', '--pr', '7', '--head', c.S, '--kind', 'fix-check', '--reason', 'Captain ruled: fix it', '--by', CAPTAIN, '--owner-ref', 'GSTA-36:2026-11-22T12:00:00Z', '--words', 'fix it'])));
const plan = c.run('gstack-review-plan', ['--base', 'main', '--gate-tagged', '0', '--pass', '2', '--last', 'full', '--fixed-blocking', '--range-base', c.S, '--grant', id]);
expect(plan.status, plan.stderr).toBe(0);
expect(plan.stdout).toContain(`NEXT: fix-check (the owner's grant ${id}`);
});
});
describe('a ruling at the cap ends in a receipt (gskills#23, GST-3546)', () => {
// Value: protects=gskills#23: after STOP_UNBOUND the Captain's grant with no stop, a claim and one clean scoped fix-check close
// the blockers its reader was given, with no hand-written per-finding rows; fails_when=write refuses RECEIPT_BLOCKER_OPEN;
// seam=gstack-approvals round-grant, gstack-ship-receipt claim and write
test('a no-stop fix-check grant closes the blockers the clean fix-check read', () => {
const c = atCap([open(ID, FP), open(ID2, FP2)]);
const id = grantId(ok(c.run('gstack-approvals', ['round-grant', '--pr', '7', '--head', c.S, '--kind', 'fix-check', '--reason', 'Captain ruled both blockers fixable', '--by', CAPTAIN, '--owner-ref', 'GSTA-36:2026-11-22T12:00:00Z', '--words', 'fix both'])));
fixCheck(c, { grant: id, run: 'r2', fixList: `fix ${ID}\nfix ${ID2}\n`, files: { 'src/x.ts': 'export const x = 3;\n' } });
const w = write(c, 'r2');
expect(w.status, w.stderr).toBe(0);
expect(w.stderr).toContain(`FIX_CHECK_CLEAR: grant=${id} run=r2 closed=${ID},${ID2}`);
});
// Value: protects=the floor: a blocker neither a ruling nor the clean fix-check covers still refuses; fails_when=write closes a
// blocker the reader was never given; seam=gstack-ship-receipt write
test('a blocker the fix list left out still refuses RECEIPT_BLOCKER_OPEN', () => {
const c = atCap([open(ID, FP), open(ID2, FP2)]);
const id = grantId(ok(c.run('gstack-approvals', ['round-grant', '--pr', '7', '--head', c.S, '--kind', 'fix-check', '--reason', 'fix one', '--by', CAPTAIN, '--owner-ref', 'GSTA-36:2026-11-22T12:00:00Z', '--words', 'fix one'])));
fixCheck(c, { grant: id, run: 'r2', fixList: `fix ${ID}\n`, files: { 'src/x.ts': 'export const x = 3;\n' } });
const w = write(c, 'r2');
expect(w.status).toBe(3);
expect(w.stderr).toContain('RECEIPT_BLOCKER_OPEN');
expect(w.stderr).toContain(ID2);
});
});
describe('a grant spends only on a counted fix-check (gskills#24, gskills#25)', () => {
// Value: protects=gskills#25: a converged:false row leaves the grant unspent, the run logs a correct row and write closes;
// fails_when=grantSpent counts the malformed row, or write refuses on two stamped rows; seam=grantSpent, clearByGrant
test('a malformed row spends nothing, and a correct row on the same grant closes the blocker', () => {
const c = atCap([open(ID, FP)]);
const id = grantId(ok(c.run('gstack-approvals', ['round-grant', '--pr', '7', '--head', c.S, '--kind', 'fix-check', '--reason', 'fix it', '--by', CAPTAIN, '--owner-ref', 'GSTA-36:2026-11-22T12:00:00Z', '--words', 'fix it'])));
fixCheck(c, { grant: id, run: 'r2', fixList: 'fix ' + ID + '\n', files: { 'src/x.ts': 'export const x = 3;\n' }, row: { converged: false } });
const bind = (r: Record<string, any>) => bindFixCheckRow(c.f.work, r, grantsOf(c)).ok;
const g = grantsOf(c).find(x => x.approval === id)!;
expect(grantSpent(rows(c), g, bind)).toBe(false);
expect(write(c, 'r2').status).toBe(3);
fixCheck(c, { grant: id, run: 'r2', fixList: 'fix ' + ID + '\n', claim: false });
expect(grantSpent(rows(c), g, bind)).toBe(true);
const w = write(c, 'r2');
expect(w.status, w.stderr).toBe(0);
expect(w.stderr).toContain(`closed=${ID}`);
});
// Value: protects=R51's one fix round: a counted read that found issues spends the grant, so a later clean row on it closes
// nothing; fails_when=a second fix-check under one grant clears the blockers; seam=grantSpent, clearByGrant
test('a counted read that found issues spends the grant; a later clean row closes nothing', () => {
const c = atCap([open(ID, FP)]);
const id = grantId(ok(c.run('gstack-approvals', ['round-grant', '--pr', '7', '--head', c.S, '--kind', 'fix-check', '--reason', 'fix it', '--by', CAPTAIN, '--owner-ref', 'GSTA-36:2026-11-22T12:00:00Z', '--words', 'fix it'])));
const found = { status: 'issues_found', issues_found: 1, critical: 0, informational: 1, findings: [{ fingerprint: 'src/x.ts:1:style', severity: 'INFORMATIONAL', action: 'open' }] };
fixCheck(c, { grant: id, run: 'r2', fixList: 'fix ' + ID + '\n', files: { 'src/x.ts': 'export const x = 3;\n' }, row: found });
const g = grantsOf(c).find(x => x.approval === id)!;
expect(grantSpent(rows(c), g, r => bindFixCheckRow(c.f.work, r, grantsOf(c), { open: true }).ok)).toBe(true);
fixCheck(c, { grant: id, run: 'r2', fixList: 'fix ' + ID + '\n', claim: false });
const w = write(c, 'r2');
expect(w.status).toBe(3);
expect(w.stderr).toContain('the one counted read the grant bought');
});
// Value: protects=a later clean row recording the same findings as fixed never replaces the first read in the receipt's dedup,
// and a read that leaves a collected dispatch-ledger id open still counts as the grant's read; fails_when=dedup keeps the last
// copy, or open:true still demands every ledger id disposed; seam=clearByGrant, bindFixCheckRow
test('the first copy of a repeated row stays the grant\'s read, and an open ledger id still counts it', () => {
const c = atCap([open(ID, FP)]);
const id = grantId(ok(c.run('gstack-approvals', ['round-grant', '--pr', '7', '--head', c.S, '--kind', 'fix-check', '--reason', 'fix it', '--by', CAPTAIN, '--owner-ref', 'GSTA-36:2026-11-22T12:00:00Z', '--words', 'fix it'])));
const finding = (action: string) => ({ fingerprint: 'src/x.ts:1:style', severity: 'INFORMATIONAL', action, ledger_id: 'fc/fix-check#1' });
fixCheck(c, { grant: id, run: 'r2', fixList: 'fix ' + ID + '\n', files: { 'src/x.ts': 'export const x = 3;\n' }, row: { status: 'issues_found', issues_found: 1, informational: 1, findings: [finding('open')] } });
const first = rows(c).filter(r => r.skill === 'review-fix-check').at(-1)!;
fixCheck(c, { grant: id, run: 'r2', fixList: 'fix ' + ID + '\n', claim: false, row: { findings: [finding('fixed')] } });
const w = write(c, 'r2');
expect(w.status).toBe(3);
expect(w.stderr).toContain('the one counted read the grant bought');
const ledger = path.join(c.f.root, 'fc', 'review-ledger.jsonl');
fs.mkdirSync(path.dirname(ledger), { recursive: true });
fs.writeFileSync(ledger, JSON.stringify({ event: 'output', reader: 'fix-check', ids: ['fix-check#1'], tree_ok: true, at: new Date().toISOString() }) + '\n');
const withLedger = { ...first, hunks: { ...first.hunks, ledger } };
expect(bindFixCheckRow(c.f.work, withLedger, grantsOf(c), { open: true })).toMatchObject({ ok: true });
expect(bindFixCheckRow(c.f.work, withLedger, grantsOf(c))).toMatchObject({ ok: false });
expect(bindFixCheckRow(c.f.work, { ...withLedger, findings: [] }, grantsOf(c), { open: true })).toMatchObject({ ok: false, why: expect.stringContaining('does not dispose') });
});
// Value: protects=gskills#25: the claimed reader's packet is git diff <claimed head> HEAD, built by gstack, so a hand-built
// partial --hunks file cannot reach it; fails_when=the row records the partial paths; seam=gstack-review-plan --fix-check-prompt
test('a partial --hunks file is replaced by the full diff since the claimed head', () => {
const c = atCap([open(ID, FP)]);
const id = grantId(ok(c.run('gstack-approvals', ['round-grant', '--pr', '7', '--head', c.S, '--kind', 'fix-check', '--reason', 'fix it', '--by', CAPTAIN, '--owner-ref', 'GSTA-36:2026-11-22T12:00:00Z', '--words', 'fix it'])));
c.f.write({ 'src/x.ts': 'export const x = 3;\n', 'src/y.ts': 'export const y = 1;\n' }); c.f.commit('fix');
ok(c.run('gstack-ship-receipt', ['claim', '--body', c.body, '--pr', '7', '--run', 'r2', '--grant', id]));
const partial = path.join(c.f.root, 'partial.diff');
fs.writeFileSync(partial, c.f.git('diff', c.S, 'HEAD', '--', 'src/x.ts').stdout);
const fixes = path.join(c.f.root, 'fixes.txt'), tests = path.join(c.f.root, 'tests.txt');
fs.writeFileSync(fixes, 'fix ' + ID + '\n'); fs.writeFileSync(tests, '3 pass\n');
const p = c.run('gstack-review-plan', ['--fix-check-prompt', '--fix-list', fixes, '--hunks', partial, '--tests', tests]);
expect(p.status, p.stderr).toBe(0);
expect(p.stderr).toContain(`FIX_CHECK_HUNKS: built from git diff ${c.S.slice(0, 12)} HEAD`);
expect(p.stdout).toContain('src/y.ts');
});
});
describe('a post-review edit with no stop gets a grant (GST-3546, gbrain#10068)', () => {
// Value: protects=a docs-audit edit after the cap, with no stop record, buys one scoped fix-check that finish counts;
// fails_when=round-grant refuses a fix-check with no --stop-run, or finish prints FIX_CHECK: not counted; seam=round-grant, finish
test('a grant at the reviewed head covers the edit, and finish counts its fix-check', () => {
const c = atCap([]);
const id = grantId(ok(c.run('gstack-approvals', ['round-grant', '--pr', '7', '--head', c.S, '--kind', 'fix-check', '--reason', 'docs audit edited code comments after review', '--by', CAPTAIN, '--owner-ref', 'GSTA-36:2026-11-22T12:00:00Z', '--words', 'one fix-check'])));
fixCheck(c, { grant: id, run: 'r2', fixList: 'review the docs-audit edit\n', files: { 'src/x.ts': '// the x value\nexport const x = 2;\n' } });
const post = path.join(c.f.root, 'post.json');
ok(c.run('gstack-docs-candidate', ['snapshot', '--out', post, '--audit-id', 'a1', '--mode', 'edit', '--base', 'main', '--docs', 'README.md']));
const F = headOf(c.f);
const fin = c.f.run(RELEASE, ['finish', '--base', 'main', '--reviewed-tree', c.f.git('rev-parse', c.S + '^{tree}').stdout.trim(), '--docs-post', post, '--reviewed-base', c.f.git('merge-base', 'origin/main', 'HEAD').stdout.trim(), '--lane', 'tests=printf " 3 pass\\n 0 fail\\nRan 3 tests across 1 file. [5.00ms]\\n"'], { GSTACK_APPROVALS_MIRROR: '0' });
expect(fin.stdout).not.toContain('FIX_CHECK: not counted');
expect(fin.stdout).toContain(`(fix-check at ${F.slice(0, 12)}, range from ${c.S.slice(0, 12)}, grant ${id})`);
});
});
describe('round-grant fits a verbatim owner reason (GST-3546 gap 2)', () => {
// Value: protects=a reason past the 300-character ask records, with the ask cut and the full words kept; fails_when=
// APPROVAL_RECORD_INVALID on the ask cap; seam=reviewRoundGrantRow, gstack-approvals round-grant
test('the ask is cut at 300 characters with an ellipsis, it still parses, and --words keeps every word', () => {
const reason = 'Ruled: ' + 'the docs audit rewrote three paragraphs of the security section after round two, and I want one scoped read of exactly that change before this ships. '.repeat(3).trim();
const built = reviewRoundGrantRow('b'.repeat(40), 7, 'fix-check', reason);
expect(built.ask.length).toBeLessThanOrEqual(300);
expect(built.ask.endsWith('…')).toBe(true);
const c = atCap([]);
const r = c.run('gstack-approvals', ['round-grant', '--pr', '7', '--head', c.S, '--kind', 'fix-check', '--reason', reason, '--by', CAPTAIN, '--owner-ref', 'GSTA-36:2026-11-22T12:00:00Z', '--words', reason]);
const id = grantId(ok(r));
const listed = JSON.parse(ok(c.run('gstack-approvals', ['list', '--json']))) as { rows?: ApprovalRow[] } | ApprovalRow[];
const row = (Array.isArray(listed) ? listed : listed.rows ?? []).find(x => x.id === id)!;
expect(row.words).toBe(reason);
expect(grantsOf(c).find(g => g.approval === id)).toMatchObject({ kind: 'fix-check', head: c.S });
});
});
describe('an ended or dead /ship run stops holding gstack upgrades (gskills#25)', () => {
const stateRoot = () => { const d = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'ship-live-'))); tmps.push(d); return d; };
const ledger = (sr: string, run: string, extra: Record<string, unknown>) => {
fs.mkdirSync(path.join(sr, 'ship-runs', run), { recursive: true });
fs.writeFileSync(path.join(sr, 'ship-runs', run, 'budget.json'), JSON.stringify({ kind: 'gstack-ship-budget', run, created_at: new Date(Date.now() - 60_000).toISOString(), ...extra }));
};
const sleeper = () => { const k = spawn('sleep', ['300'], { stdio: 'ignore' }); kids.push(k); return k.pid!; };
const ownerOf = (pid: number): RunOwner => { const o = thisRunOwner(pid)!; expect(o).not.toBeNull(); return o; };
const deadOwner = (): RunOwner => { const k = spawnSync('sleep', ['0'], { timeout: 10_000 }); const { shared: _shared, ...here } = ownerOf(process.pid); return { ...here, pid: k.pid!, comm: 'claude' }; };
// Value: protects=an ended run (its harness gone, or its own checkout run record finished or abandoned) no longer holds upgrades,
// while a live, stopped (it may still claim its grant) or unprovable one still does; fails_when=a dead run holds, a stopped run or
// an earlier run's finished record releases, or a run on a shared harness is released; seam=liveRun
test('dead owner and this run\'s finished record release; a live owner, a stopped run, an older record and a shared harness hold', () => {
if (process.platform !== 'linux') return;
const sr = stateRoot();
ledger(sr, 'dead', { owner: deadOwner() });
expect(liveRun(sr)).toMatchObject({ ended: [expect.stringContaining('/ship run dead: its owner process')] });
expect(liveRun(sr).live).toBeUndefined();
const c = atCap([]);
const recordFile = path.resolve(c.f.work, c.f.git('rev-parse', '--git-path', 'gstack-ship-run').stdout.trim());
const record = (state: string, started: number) => fs.writeFileSync(recordFile, JSON.stringify({ v: 1, run: 'r2', state, head: c.S, started_at: new Date(started).toISOString(), beat_at: new Date().toISOString() }) + '\n');
const shared = { ...ownerOf(process.pid), shared: true };
record('stopped', Date.now());
ledger(sr, 'mine', { checkout: c.f.work, owner: shared });
expect(liveRun(sr).live).toContain('/ship run mine');
record('finished', Date.now() - 3_600_000);
expect(liveRun(sr).live).toContain('/ship run mine');
ledger(sr, 'other', { checkout: c.f.work, owner: shared, created_at: new Date(Date.now() - 30_000).toISOString() });
record('finished', Date.now());
expect(liveRun(sr).live).toContain('/ship run mine');
fs.rmSync(path.join(sr, 'ship-runs', 'other'), { recursive: true });
expect(liveRun(sr).live).toBeUndefined();
ledger(sr, 'alive', { owner: ownerOf(sleeper()) });
expect(liveRun(sr).live).toContain('/ship run alive');
fs.rmSync(path.join(sr, 'ship-runs', 'alive'), { recursive: true });
ledger(sr, 'legacy', {});
expect(liveRun(sr).live).toContain('/ship run legacy');
const out = spawnSync(path.join(BIN, 'gstack-ship-run'), ['live', '--state-root', sr], { encoding: 'utf8', timeout: 60_000 });
expect(out.stdout).toContain('RUN_LIVE: /ship run legacy');
expect(out.stdout).toContain('RUN_HOLD_RELEASED: /ship run dead');
});
// Value: protects=abandon takes a run whose owner is provably gone at once, instead of after 60 minutes; fails_when=
// SHIP_RUN_ABANDON_REFUSED for a run whose harness exited; seam=abandonRefusal
test('abandon refuses a fresh run under a live or shared owner and takes one whose owner is gone', () => {
if (process.platform !== 'linux') return;
const c = atCap([]);
const now = new Date().toISOString();
const file = path.resolve(c.f.work, c.f.git('rev-parse', '--git-path', 'gstack-ship-run').stdout.trim());
const put = (owner: RunOwner) => { fs.writeFileSync(file, JSON.stringify({ v: 1, run: 'r2', state: 'open', head: c.S, started_at: now, beat_at: now, owner }) + '\n'); return readRunRecord(c.f.work); };
expect(abandonRefusal(put(ownerOf(sleeper())), 'r2', undefined)).toContain('still working');
expect(abandonRefusal(put({ ...ownerOf(process.pid), shared: true }), 'r2', undefined)).toContain('still working');
expect(abandonRefusal(put(deadOwner()), 'r2', undefined)).toBeNull();
});
});