diff --git a/bin/gstack-approvals b/bin/gstack-approvals index c6d43b41b..6e14725ac 100755 --- a/bin/gstack-approvals +++ b/bin/gstack-approvals @@ -68,7 +68,8 @@ const HELP = `gstack-approvals — the per-thread approval record (capy/skill/gs a review round the PR's R51 count would not plan (docs/review-policy.md#rounds-per-pull-request): extra-round is one round with its fix round past the cap of 2, instead of the read-only final review; it binds that head of that PR only and is spent by the round; the lane or its Captain records it, never the owner, and - --by is recorded, not enforced; refused inside this checkout's open /ship run, so a run never grants itself + --by is recorded, not enforced; refused inside this checkout's open /ship run, so a run never grants itself; + a stopped run (gstack-ship-run status) records only the fix-check grant naming its own --stop-run and stop --head lane-exception --head --files --reason --words --by the owner's grant that a CI-carried lane counts although exactly those files are in no run's tree.json @@ -184,9 +185,10 @@ function main(argv: string[]): number { if (!by || isGstackActorName(by)) return invalid('round-grant needs --by : gstack never grants itself a round'); const ownerRef = flags['--owner-ref']?.trim(); if (ownerRef !== undefined && (!OWNER_REF.test(ownerRef) || !(flags['--words'] ?? '').trim())) return invalid('--owner-ref relays the lane\'s or Captain\'s grant: : (GSTA-36:2026-11-19T12:29:59Z), with --words '); - const open = openShipRun(process.cwd()); - if (open && ownerRef === undefined) return invalid(`/ship run ${open} is open on this checkout: a round grant is the lane's or its Captain's, never the run's own; relay it with --owner-ref : --words , or record it from the lane after the run stops`); const stopRun = (flags['--stop-run'] ?? '').trim(), findings = [...new Set((flags['--findings'] ?? '').split(',').map(f => f.trim()).filter(Boolean))]; + const open = openShipRun(process.cwd()); + const ownStop = open?.state === 'stopped' && !open.claim && kind === 'fix-check' && stopRun === open.run && open.stop?.head === head.stdout.trim().toLowerCase(); + if (open && ownerRef === undefined && !ownStop) return invalid(`${open.line}: ${open.state !== 'stopped' ? "a round grant is the lane's or its Captain's, never the run's own" : open.claim ? `this run already spent its own stop's fix-check grant (${open.claim.grant}), so a second fix round is the lane's or its Captain's` : `a stopped run records only the fix-check grant for its own stop (--kind fix-check --stop-run ${open.run} --head ${open.stop?.head ?? ''})`}; relay it with --owner-ref : --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 and --findings : it buys the fix round of that one stop'); if (kind !== 'fix-check' && (flags['--stop-run'] !== undefined || flags['--findings'] !== undefined)) return invalid('--stop-run and --findings belong to --kind fix-check: an extra-round grant names no stop'); const built = buildRow({ ...reviewRoundGrantRow(head.stdout.trim().toLowerCase(), Number(pr), kind, reason, kind === 'fix-check' ? { run: stopRun, findings } : undefined), words: flags['--words'] ?? reason, by, date: flags['--date'], source: ruledNoteSource({ ownerRef }) }, loc.branch); @@ -201,7 +203,7 @@ function main(argv: string[]): number { if (!flags['--head'] || head.status !== 0) return invalid('lane-exception needs --head '); if (isGstackActor(flags['--by'] ?? '')) return invalid('--by names gstack; a test-lane exception is the owner\'s, so --by names who granted it'); const open = openShipRun(process.cwd()); - if (open) return invalid(`/ship run ${open} is open on this checkout: a test-lane exception is the owner's, never the lane's own runner's; record it from the owner's session`); + if (open) return invalid(`${open.line}: a test-lane exception is the owner's, never the lane's own runner's; record it from the owner's session`); const built = buildRow({ ...testLaneExceptionRow(head.stdout.trim(), files, reason), words: flags['--words'] ?? '', by: flags['--by'] ?? '', date: flags['--date'] }, loc.branch); if ('code' in built) return fail(cmd, built); rows = [built]; @@ -217,8 +219,8 @@ function main(argv: string[]): number { if (ownerRef !== undefined && (!OWNER_REF.test(ownerRef) || !(flags['--words'] ?? '').trim() || !(flags['--by'] ?? '').trim())) return invalid('--owner-ref relays the owner\'s ruling: : (GSTA-36:2026-11-19T12:29:59Z), with --by and --words '); if (notSecurity && !/:red-team$/i.test(finding)) return invalid('--not-security is the owner\'s call on a red-team finding (path:line:red-team); a security, auth or secret finding is security class by its category'); const open = openShipRun(process.cwd()); - if (open && notSecurity) return invalid(`--not-security lifts a red-team finding's redaction, so it is recorded only outside a /ship run: /ship run ${open} is open on this checkout; record it after the run stops`); - if (open && ownerRef === undefined) return fail(cmd, { code: 'APPROVAL_RULING_RUN_OPEN', message: `/ship run ${open} is open on this checkout, and its own runner cannot rule on the run's findings: relay the owner's ruling with --owner-ref : --by --words , or record it after the run stops` }); + if (open && notSecurity) return invalid(`--not-security lifts a red-team finding's redaction, so it is recorded only outside a /ship run: ${open.line}; record it after the run ends`); + if (open && ownerRef === undefined) return fail(cmd, { code: 'APPROVAL_RULING_RUN_OPEN', message: `${open.line}, and its own runner cannot rule on the run's findings: relay the owner's ruling with --owner-ref : --by --words , or record it after the run stops` }); const built = buildRow({ ...ruledNoteRow(finding, head.stdout.trim(), reason), words: flags['--words'] ?? '', by: flags['--by'] ?? '', date: flags['--date'], source: ruledNoteSource({ ownerRef, notSecurity }) }, loc.branch); if ('code' in built) return fail(cmd, built); rows = [built]; diff --git a/bin/gstack-doctor-components.sh b/bin/gstack-doctor-components.sh index 0a6316f84..b20f932b7 100644 --- a/bin/gstack-doctor-components.sh +++ b/bin/gstack-doctor-components.sh @@ -344,6 +344,8 @@ gstack_result_anchor() { RECEIPT_CARRY_PRODUCT_CHANGED) printf '%s' 'receipt-carry-product-changed' ;; STOP_UNBOUND) printf '%s' 'stop-unbound' ;; GRANT_SPENT) printf '%s' 'grant-spent' ;; + SHIP_RUN_ABANDON_REFUSED) printf '%s' 'ship-run-abandon-refused' ;; + SHIP_RUN_RECORD_UNREADABLE) printf '%s' 'ship-run-record-unreadable' ;; GRANT_UNKNOWN) printf '%s' 'grant-unknown' ;; RECEIPT_CARRY_SCOPED_REVIEW) printf '%s' 'receipt-carry-scoped-review' ;; DOCS_AUDIT_BLOCKED) printf '%s' 'docs-audit-blocked' ;; diff --git a/bin/gstack-review-log b/bin/gstack-review-log index b469ee1a4..5b1e5fe76 100755 --- a/bin/gstack-review-log +++ b/bin/gstack-review-log @@ -100,6 +100,7 @@ if [ "$INPUT" = --start ]; then const { captureReviewStart } = await import(process.env.GSTACK_REVIEW_LIB); try { console.log(captureReviewStart(process.env.GSTACK_REVIEW_SKILL, process.env, process.env.GSTACK_REVIEW_FIX_RANGE === "--fix-range")); } catch (e) { console.error(e.message); process.exit(1); } + try { (await import(process.env.GSTACK_REVIEW_LIB.replace(/review-evidence\.ts$/, "ship-run-record.ts"))).beatFromReview(process.cwd()); } catch {} ' exit $? fi @@ -109,6 +110,7 @@ if [ "$INPUT" = --start ]; then const capture = () => captureReviewStart(process.env.GSTACK_REVIEW_SKILL, process.env, process.env.GSTACK_REVIEW_FIX_RANGE === "--fix-range"); try { console.log(admitReviewStart(process.env.GSTACK_SHIP_BUDGET_MARKER, process.env.GSTACK_REVIEW_RESERVATION || undefined, capture)); } catch (e) { console.error(e.message); process.exit(1); } + try { (await import(process.env.GSTACK_REVIEW_LIB.replace(/review-evidence\.ts$/, "ship-run-record.ts"))).beatFromReview(process.cwd()); } catch {} ' exit $? fi @@ -149,6 +151,7 @@ if (!rec || Array.isArray(rec) || typeof rec !== 'object') { console.error('gsta try { console.log(JSON.stringify(bindReview(rec, process.env.GSTACK_REVIEW_TOKEN, process.env, process.env.GSTACK_REVIEW_FINDINGS || undefined))); } catch (e) { console.error(e.message); process.exit(1); } +if (process.env.GSTACK_REVIEW_TOKEN) try { (await import(process.env.GSTACK_REVIEW_LIB.replace(/review-evidence\\.ts$/, 'ship-run-record.ts'))).beatFromReview(process.cwd()); } catch {} ") || exit 1 echo "$STAMPED" >> "$GSTACK_HOME/projects/$SLUG/$BRANCH-reviews.jsonl" diff --git a/bin/gstack-ship-receipt b/bin/gstack-ship-receipt index e8d18e323..12c1afd78 100755 --- a/bin/gstack-ship-receipt +++ b/bin/gstack-ship-receipt @@ -18,6 +18,7 @@ * gstack-ship-receipt history (--pr [--repo ] | --body ) [--head ] [--base ] [--run ] [--json] * gstack-ship-receipt stub (--pr [--repo ] | --body ) --run [--head ] [--review-loop ] [--void] * gstack-ship-receipt stop (--pr [--repo ] | --body ) --run --since + * gstack-ship-receipt abandoned (--pr [--repo ] | --body ) --run --by --reason * gstack-ship-receipt claim (--pr [--repo ] | --body ) --run --grant * * `write` validates against `gstack-artifact schema ship-receipt`, prints the @@ -66,7 +67,8 @@ import { publicRuledNote, readRuledNotes, ruledNoteText } from '../lib/ruled-not import { appliedGateDispositions, gateDispositionText, publicGateDisposition } from '../lib/gate-dispositions'; import { securityFingerprints } from '../lib/security-findings'; import { laneExceptionBodyLines } from '../lib/test-lane-exception'; -import { grantedStop, grantMarker, historyLine, placeRunEntry, prReviewHistory, reviewRoute, runStub, stopFrom, stopMarker } from '../lib/pr-review-history'; +import { abandonMarker, grantedStop, grantMarker, historyLine, placeRunEntry, prReviewHistory, receiptedRun, reviewRoute, runStub, stopFrom, stopMarker } from '../lib/pr-review-history'; +import { changeRunRecord } from '../lib/ship-run-record'; import { grantFor, publicRoundGrant, readReviewRoundGrants, type ReviewRoundGrant } from '../lib/review-round-grant'; import { readMechanicalLines } from '../lib/ship-mechanical'; import { patchId, productPatchAgainstBase, productRules, productSpec, verifiedOutputs } from '../lib/ship-receipt-patch'; @@ -115,11 +117,16 @@ const HELP = `gstack-ship-receipt — the \`\`\`gstack-ship-receipt\`\`\` block stop --pr | --body --run --since Step 9, on NEXT: stop: record the review this run stopped on (its commit and tree, from the newest via:ship review row bound to one committed tree) as a stop record in the runs block, and print the - round-grant command that buys its fix round (STOP_RECORD:, NEXT:); an unbound read prints - STOP_UNBOUND (exit 3) and records nothing (docs/troubleshooting.md#stop-unbound) + round-grant command that buys its fix round (STOP_RECORD:, NEXT:); the stopping row is the newest + full pass, fix-check or Step 11 voice, so the stop is the head it read (#4591); it also marks this + checkout's run record stopped at that head and tree; an unbound read prints STOP_UNBOUND (exit 3) + and records nothing (docs/troubleshooting.md#stop-unbound) claim --pr | --body --run --grant before the first dispatch of a run whose PR_REVIEW_FLAGS: name --round-grant: record that this run - spends the grant (GRANT_CLAIMED:); a grant another run claimed is refused (GRANT_SPENT, exit 3) + spends the grant (GRANT_CLAIMED:), in the PR body and in this checkout's run record; a grant + another run claimed is refused (GRANT_SPENT, exit 3) + abandoned --pr | --body --run --by --reason + gstack-ship-run abandon's PR-body half: a mark:abandoned entry in the runs block (RUN_ABANDON_MARK:) docs-caps [--base ] /ship Step 14.5: one DOCS_CAP: / ok|over line per docs.caps entry of the reviewed policy (origin/'s .gstack/ship-policy.json; --policy reads that file instead); any over (or absent) file exits 1 (DOCS_AUDIT_BLOCKED) @@ -980,8 +987,9 @@ function cmdHistory(rest: string[], json: boolean): number { const grant = claimed ? undefined : found; const route = answer?.ok ? { route: 'fix-check' as const, reason: `fix-check grant ${answer.grant.approval} answers the stop at ${answer.stop.head.slice(0, 12)} (run ${answer.stop.run}): one scoped fix-check of the PR's own change since it, for ${answer.grant.findings!.join(', ')}, with no new full review` } : reviewRoute(h, { grant: grant?.approval }); const flagsLine = `PR_REVIEW_FLAGS: --prior-rounds ${h.rounds} --prior-full ${h.full}${grant ? ` --round-grant ${grant.approval}` : ''}${answer?.ok ? ` --stop ${answer.stop.head}` : ''}`; - if (json) { process.stdout.write(JSON.stringify({ pr, ...h, grant: grant ?? null, stop: answer?.ok ? answer.stop : null, route }) + '\n'); return EXIT.ok; } - process.stdout.write(`${historyLine(pr, h)}\n${flagsLine}\nPR_REVIEW_ROUTE: ${route.route} (${route.reason})\n${answer && !answer.ok ? `PR_REVIEW_GRANT: not applied (${answer.why})\n` : ''}${claimed ? `PR_REVIEW_GRANT: not applied (grant ${claimed.grant} was claimed by run ${claimed.run}: a grant buys one round)\n` : ''}`); + const used = flag(rest, '--run') ? receiptedRun(read.body, flag(rest, '--run')!) : undefined; + if (json) { process.stdout.write(JSON.stringify({ pr, ...h, grant: grant ?? null, stop: answer?.ok ? answer.stop : null, route, run_used: used?.head ?? null }) + '\n'); return EXIT.ok; } + process.stdout.write(`${historyLine(pr, h)}\n${flagsLine}\nPR_REVIEW_ROUTE: ${route.route} (${route.reason})\n${answer && !answer.ok ? `PR_REVIEW_GRANT: not applied (${answer.why})\n` : ''}${claimed ? `PR_REVIEW_GRANT: not applied (grant ${claimed.grant} was claimed by run ${claimed.run}: a grant buys one round)\n` : ''}${used ? `PR_REVIEW_RUN_USED: run=${used.run} receipted at ${used.head.slice(0, 12)}\n` : ''}`); return EXIT.ok; } @@ -1004,7 +1012,8 @@ function cmdStop(rest: string[]): number { const err = postBody(rest, read.pr, placeRunEntry(read.body, stopMarker({ head: found.head, tree: found.tree, run }))); if (err) { process.stderr.write(`gstack-ship-receipt stop: ${err}; nothing recorded\n`); return EXIT.fail; } const pr = read.pr ?? flag(rest, '--pr') ?? ''; - process.stdout.write(`STOP_RECORD: run=${run} head=${found.head} tree=${found.tree}\nNEXT: the lane or its Captain decides: ship with the open notes listed, park, or buy this stop's fix round with gstack-approvals round-grant --pr ${pr} --head ${found.head} --kind fix-check --stop-run ${run} --findings --reason "" --by , then take --round-grant and --stop from the PR_REVIEW_FLAGS: line of gstack-ship-receipt history --pr ${pr} --base --run ${run} in this run, or from a new run's preflight (docs/troubleshooting.md#pr-round-cap)\n`); + const marked = changeRunRecord(repoRoot, 'stop', run, { stop: { head: found.head, tree: found.tree } }); + process.stdout.write(`STOP_RECORD: run=${run} head=${found.head} tree=${found.tree}\n${marked.ok ? '' : `RUN_RECORD: not marked stopped (${marked.why})\n`}NEXT: the lane or its Captain decides: ship with the open notes listed, park, or buy this stop's fix round with gstack-approvals round-grant --pr ${pr} --head ${found.head} --kind fix-check --stop-run ${run} --findings --reason "" --by , then take --round-grant and --stop from the PR_REVIEW_FLAGS: line of gstack-ship-receipt history --pr ${pr} --base --run ${run} in this run, or from a new run's preflight (docs/troubleshooting.md#pr-round-cap)\n`); return EXIT.ok; } @@ -1027,7 +1036,8 @@ function cmdClaim(rest: string[]): number { if (!again.ok) { process.stderr.write(`gstack-ship-receipt claim: ${again.why}; the claim is unconfirmed, so do not dispatch\n`); return EXIT.fail; } const first = receiptRuns(again.body).find(r => r.mark === 'grant' && r.grant === id); if (first?.run !== run) { process.stderr.write(`${resultLine('gstack-ship-receipt claim', 'GRANT_SPENT', `grant ${id} was claimed by run ${first?.run ?? 'another run'} while this run claimed it: a grant buys one round; the lane or its Captain records a new one`)}\n`); return EXIT.refused; } - process.stdout.write(`GRANT_CLAIMED: grant=${id} kind=${g.kind} run=${run} head=${g.head.slice(0, 12)}\n`); + const recorded = changeRunRecord(repoRoot, 'claim', run, { claim: { grant: id, ...(g.stop_run ? { stop_run: g.stop_run } : {}), stop_head: g.head, findings: g.findings ?? [] } }); + process.stdout.write(`GRANT_CLAIMED: grant=${id} kind=${g.kind} run=${run} head=${g.head.slice(0, 12)}\n${recorded.ok ? '' : `RUN_RECORD: claim not recorded (${recorded.why})\n`}`); return EXIT.ok; } @@ -1045,10 +1055,26 @@ function cmdStub(rest: string[]): number { const status = rest.includes('--void') ? 'voided' : 'started'; const err = postBody(rest, read.pr, placeRunEntry(read.body, runStub({ head, run, status, loop }))); if (err) { process.stderr.write(`gstack-ship-receipt stub: ${err}; the run is not recorded\n`); return EXIT.fail; } + const repoRoot = git(['rev-parse', '--show-toplevel']); + if (repoRoot) changeRunRecord(repoRoot, 'beat', run); process.stdout.write(`RUN_STUB: run=${run} status=${status} rounds=${loop.passes} head=${head.slice(0, 12)}\n`); return EXIT.ok; } +/** gstack-ship-run abandon's PR-body half (GST-3260): a mark:abandoned entry in the runs block naming the run, who ended it and why. */ +function cmdAbandoned(rest: string[]): number { + const run = flag(rest, '--run'), by = flag(rest, '--by')?.trim(), reason = flag(rest, '--reason')?.trim(); + if (!run || !/^[\w.:-]{1,128}$/.test(run) || !by || !reason || /[\x00-\x1f\x7f]/.test(by + reason)) { process.stderr.write('gstack-ship-receipt abandoned: --run , --by and --reason are required\n'); return EXIT.usage; } + const read = readBody(rest); + if (!read.ok) { process.stderr.write(`gstack-ship-receipt abandoned: ${read.why}; fix: ${read.fix}\n`); return EXIT.fail; } + const head = git(['rev-parse', 'HEAD'])?.toLowerCase(); + if (!head) { process.stderr.write('gstack-ship-receipt abandoned: cannot resolve HEAD\n'); return EXIT.usage; } + const err = postBody(rest, read.pr, placeRunEntry(read.body, abandonMarker({ head, run, by, reason }))); + if (err) { process.stderr.write(`gstack-ship-receipt abandoned: ${err}; not marked\n`); return EXIT.fail; } + process.stdout.write(`RUN_ABANDON_MARK: run=${run} head=${head.slice(0, 12)}\n`); + return EXIT.ok; +} + function main(argv: string[]): number { const [cmd, ...rest] = argv; const json = rest.includes('--json'); @@ -1063,6 +1089,7 @@ function main(argv: string[]): number { if (cmd === 'stub') return cmdStub(rest); if (cmd === 'stop') return cmdStop(rest); if (cmd === 'claim') return cmdClaim(rest); + if (cmd === 'abandoned') return cmdAbandoned(rest); process.stderr.write(`gstack-ship-receipt: unknown command ${cmd}\n${HELP}\n`); return EXIT.usage; } diff --git a/bin/gstack-ship-run b/bin/gstack-ship-run new file mode 100755 index 000000000..80111d3d1 --- /dev/null +++ b/bin/gstack-ship-run @@ -0,0 +1,80 @@ +#!/usr/bin/env -S bun --no-env-file --config=/dev/null +/** + * gstack-ship-run — this checkout's /ship run record (lib/ship-run-record.ts, docs/ship-policy.md#what-ends-a-run). + * + * gstack-ship-run status + * gstack-ship-run abandon --run --by --reason [--sha256 ] [--pr [--repo ] | --body ] + * gstack-ship-run skill-end --run + */ +import * as path from 'node:path'; +import { EXIT, exitTableHelp } from '../lib/headless-artifacts'; +import { ghSpawnSync } from '../lib/gh-poll'; +import { resultLineWithDocs } from '../lib/result-codes'; +import { isGstackActorName } from '../lib/ruled-notes'; +import { BIN_DIR, runScriptSync } from '../lib/script-invocation'; +import { abandonRefusal, changeRunRecord, openRun, readRunRecord, RUN_ID } from '../lib/ship-run-record'; +import { spawnSync } from '../lib/spawn-sync'; + +const HELP = `gstack-ship-run — this checkout's /ship run record (docs/ship-policy.md#what-ends-a-run) + + status RUN_STATE: run= state=open|stopped|finished|abandoned|legacy beat_age=m …, then NEXT: with the abandon + command while the run still blocks; an unreadable record prints its sha256 and SHIP_RUN_RECORD_UNREADABLE (exit 1) + abandon --run --by --reason [--sha256 ] [--pr [--repo ] | --body ] + end a run that stopped working: the record becomes abandoned with who and why, and the open PR's runs block gets a + mark:abandoned entry (skipped with a note when no PR body is reachable). Refused (SHIP_RUN_ABANDON_REFUSED, exit 3) + while the run beat in the last 60 minutes, for another run's record, or once it ended; --by gstack is usage (2). + A bare marker from an older gstack (state legacy) goes at any age; an unreadable record goes as --run unknown with + the --sha256 status printed. It completes in one call: never rerun it after RUN_ABANDONED + skill-end --run + what gstack-skill-end calls: marks the record finished (ended_by skill-end) when it names that run + +${exitTableHelp()}`; + +function main(argv: string[]): number { + const [cmd, ...rest] = argv; + const flag = (name: string) => { const i = rest.lastIndexOf(name); return i >= 0 ? rest[i + 1] : undefined; }; + const cwd = process.cwd(); + if (!cmd || cmd === '--help' || cmd === '-h') { process.stdout.write(HELP + '\n'); return cmd ? EXIT.ok : EXIT.usage; } + if (cmd === 'status') { + const read = readRunRecord(cwd); + const open = openRun(read); + if (read.kind === 'none') { process.stdout.write('RUN_STATE: none (no /ship run record on this checkout)\n'); return EXIT.ok; } + if (read.kind === 'unreadable') { + process.stdout.write(`RUN_STATE: run=unknown state=unreadable file=${read.file} sha256=${read.sha256 ?? 'unreadable'}\nNEXT: ${open!.detail}\n`); + process.stderr.write(resultLineWithDocs('gstack-ship-run status', 'SHIP_RUN_RECORD_UNREADABLE', `${read.file}: ${read.why}`) + '\n'); + return EXIT.fail; + } + const rec = read.kind === 'record' ? read.record : undefined; + const age = rec ? `${Math.max(0, Math.floor((Date.now() - Date.parse(rec.beat_at)) / 60_000))}m` : 'unknown'; + process.stdout.write(`RUN_STATE: run=${read.kind === 'record' ? read.record.run : read.run} state=${rec?.state ?? 'legacy'} beat_age=${age} started_at=${rec?.started_at ?? 'unknown'} head=${rec?.head.slice(0, 12) ?? 'unknown'}${rec?.stop ? ` stop=${rec.stop.head.slice(0, 12)}` : ''}${rec?.claim ? ` claim=${rec.claim.grant}` : ''}${rec?.ended_by ? ` ended_by=${rec.ended_by}` : ''}\n${open ? `NEXT: ${open.detail}\n` : ''}`); + return EXIT.ok; + } + if (cmd === 'skill-end') { + const run = flag('--run'); + if (!run) { process.stderr.write('gstack-ship-run skill-end: --run is required\n'); return EXIT.usage; } + const done = changeRunRecord(cwd, 'skill-end', run, { ended_by: 'skill-end' }); + process.stdout.write(done.ok ? `RUN_ENDED: run=${run} state=finished ended_by=skill-end\n` : `RUN_ENDED: none (${done.why})\n`); + return EXIT.ok; + } + if (cmd !== 'abandon') { process.stderr.write(`gstack-ship-run: unknown command ${cmd}\n${HELP}\n`); return EXIT.usage; } + const run = flag('--run'), by = flag('--by')?.trim(), reason = flag('--reason')?.trim(); + if (!run || (run !== 'unknown' && !RUN_ID.test(run)) || !by || !reason || /[\x00-\x1f\x7f]/.test(by + reason)) { + process.stderr.write('gstack-ship-run abandon: --run (unknown for an unreadable record), --by and --reason are required\n'); + return EXIT.usage; + } + if (isGstackActorName(by)) { process.stderr.write('gstack-ship-run abandon: --by names gstack; the lane or its Captain abandons a run, never gstack itself\n'); return EXIT.usage; } + const done = changeRunRecord(cwd, 'abandon', run, { ended_by: by, reason }, { check: read => abandonRefusal(read, run, flag('--sha256')) }); + if (!done.ok) { process.stderr.write(resultLineWithDocs('gstack-ship-run abandon', 'SHIP_RUN_ABANDON_REFUSED', `${done.why}; nothing changed`) + '\n'); return EXIT.refused; } + process.stdout.write(`RUN_ABANDONED: run=${run} from=${done.from} by=${by} at=${done.record?.beat_at}\n`); + const branch = spawnSync('git', ['branch', '--show-current'], { cwd, encoding: 'utf8', timeout: 10_000 }).stdout?.trim() ?? ''; + const listed = flag('--body') || flag('--pr') || !branch ? undefined : ghSpawnSync(['pr', 'list', '--head', branch, '--state', 'open', '--json', 'number', '--jq', '.[0].number // empty'], { cwd, encoding: 'utf8', timeout: 60_000 }); + const pr = flag('--pr') ?? listed?.stdout?.trim(); + const target = flag('--body') ? ['--body', flag('--body')!] : pr && /^[1-9]\d*$/.test(pr) ? ['--pr', pr, ...(flag('--repo') ? ['--repo', flag('--repo')!] : [])] : undefined; + if (!target) { process.stdout.write(`RUN_ABANDON_PR: skipped (no open PR body reachable${branch ? ` for ${branch}` : ''}${listed?.status ? `: gh exit ${listed.status}` : ''}); the record is abandoned, so do not rerun abandon\n`); return EXIT.ok; } + const mark = runScriptSync(path.join(BIN_DIR, 'gstack-ship-receipt'), ['abandoned', ...target, '--run', run, '--by', by, '--reason', reason], { cwd, encoding: 'utf8', timeout: 120_000 }); + process.stdout.write(mark.stdout ?? ''); + if (mark.status !== 0) process.stdout.write(`RUN_ABANDON_PR: not recorded (${(mark.stderr ?? '').trim().split('\n')[0] || `gstack-ship-receipt abandoned exit ${mark.status}`}); the record is abandoned, so do not rerun abandon: add the entry with gstack-ship-receipt abandoned ${target.join(' ')} --run ${run} --by "" --reason ""\n`); + return EXIT.ok; +} + +process.exitCode = main(process.argv.slice(2)); diff --git a/bin/gstack-skill-end b/bin/gstack-skill-end index d03a04aa1..d3b175fe8 100755 --- a/bin/gstack-skill-end +++ b/bin/gstack-skill-end @@ -69,6 +69,8 @@ case "$TEL_START" in ''|*[!0-9]*) ;; *) _TEL_DUR=$(( _TEL_END - TEL_START )) ;; # Release the workflow lease run gstack-skill-start opened (SESSION_ID starts # with its harness pid), so a finished run stops blocking gstack-upgrade (GST-1205). [ -n "$SESSION_ID" ] && "$_BIN/gstack-lease" release --pid "${SESSION_ID%%-*}" --run "$SESSION_ID" >/dev/null 2>&1 || true +_SHIP_RUN=$(git rev-parse --git-path gstack-ship-run 2>/dev/null || true) +[ -n "$SESSION_ID" ] && [ -n "$_SHIP_RUN" ] && [ -f "$_SHIP_RUN" ] && "$_BIN/gstack-ship-run" skill-end --run "$SESSION_ID" >/dev/null 2>&1 || true # Record completion before the final drain, including its durable enqueue. # The normal sync gates still decide publication: full may sync timelines, diff --git a/changelog.d/ship-run-record-replaces-stale-marker.md b/changelog.d/ship-run-record-replaces-stale-marker.md new file mode 100644 index 000000000..c0eb2ee9c --- /dev/null +++ b/changelog.d/ship-run-record-replaces-stale-marker.md @@ -0,0 +1 @@ +**A /ship run that stopped or died no longer blocks grants and the next /ship, and a live run past two hours no longer looks finished.** The bare run marker in the checkout's git dir is now a run record with a state (open, stopped, finished, abandoned) that only gstack's commands change: preflight opens it, review starts and finishes, stub, stop and claim keep it fresh, `gstack-ship-receipt stop` marks it stopped, `finish` removes it, and `gstack-skill-end` marks it finished on any outcome. Preflight and the approval guards read that record instead of the 120-minute lease, which another run's touch could prune while the run was still working. A stopped run may record the fix-check grant for its own stop, once per run, and nothing else; rulings relayed with `--owner-ref` still record. A new `gstack-ship-run` command prints the record (`status`) and ends a run that stopped working (`abandon --run --by --reason `), never within 60 minutes of its last beat; a bare marker from an older gstack, or an unreadable record (by its digest), can be abandoned at any age, and every refusal names the state, the age of the last beat, the earliest abandon time and the command. Also: `gstack-ship-receipt stop` binds the stop to the head its last reading row read, a fix-check or a second-model review included, instead of refusing with `STOP_UNBOUND` (#4591); the PR's round count no longer collapses runs that reused one run id at different heads (gstack-evals#406), and preflight refuses a run id the PR body or run record already shows ended. (GST-3260) diff --git a/docs/review-policy.md b/docs/review-policy.md index f1fce311d..265ab4c35 100644 --- a/docs/review-policy.md +++ b/docs/review-policy.md @@ -236,8 +236,10 @@ caught on another crew's PRs. gstack writes for itself, `gstack` or `gstack no-stop default (K1)`, matched whole and case-insensitively, so "gstack-evals Captain" or "GStack Minder" can grant) and a grant from inside an open `/ship` run are refused, and `add` - refuses the scope. A stopped run's marker stays on its checkout, so the lane - records its Captain's grant there as a relay: `--owner-ref : --words `, the same relay `gstack-approvals rule` takes, which the row keeps as `relayed:` (#4531). `--by` is otherwise the caller's own text, recorded and not checked: a lane that records a grant (or a ruling) from another checkout diff --git a/docs/ship-policy.md b/docs/ship-policy.md index a1eae5e9b..f978731c9 100644 --- a/docs/ship-policy.md +++ b/docs/ship-policy.md @@ -1801,6 +1801,21 @@ construction: the run and names the finding (path, severity, problem) for the owner instead of a third round; the owner may grant one scoped fix-check. + +**What ends a /ship run (GST-3260).** Preflight opens the run in the checkout's +run record (`git rev-parse --git-path gstack-ship-run`), and while it is open a +full preflight, round grants, gate dispositions, lane exceptions and rulings +without `--owner-ref` stop. Only gstack's commands end it: `finish` removes the +record (only when the open PR's body names that run), `gstack-ship-receipt stop` +marks it stopped (it may then record the fix-check grant for its own stop, once +per run, and a new run's preflight replaces it), `gstack-skill-end` marks it finished on any +outcome, and `gstack-ship-run abandon` ends a run that stopped working, never +within 60 minutes of its last beat. No timer ends a run. A bare marker from an +older gstack reads as `legacy` and an unreadable record as `unreadable`; both +block until abandoned. The record guards against mistakes, such as a base merge +under a run's readers or a run granting itself a round; it is not proof of who +the owner is. + **Ruled notes (GST-1537).** R51's other answer to an open finding is the owner's ruling that it ships as a disclosed note, with the note listed. The owner records @@ -1820,7 +1835,8 @@ a later head is a new row. Its `by` is the ruler and its `recorded_at` the time. newline or control character, a `--by` naming gstack (any `--by` that starts with `gstack`, except a crew named `GStack ` such as `GStack Minder`, which is a person's crew; `gstack` and `gstack no-stop default (K1)` are always refused), and a ruling while this -checkout holds an open /ship run's marker (the lane's own runner) unless the lane +checkout holds an open /ship run's record (the lane's own runner; a stopped, legacy or +unreadable record counts, [what ends a run](#what-ends-a-run)) unless the lane relays the owner's words with `--owner-ref :` (on Capy the owner, a Captain, has no session on the lane's checkout). A relayed row's source is `relayed:`, and its `RULED_NOTE:`, receipt entry and `Ruled note:` @@ -1937,9 +1953,10 @@ The row is an approved `gstack-approvals` row with scope `gate_disposition trimmed first), a `--head` that is not a commit, a `--by` naming gstack (as for `rule`: a `GStack ` crew may record), a row that `dispositions` would not list (a head that is not 40 hex, for one), and any call -while a /ship run is open on the branch in any worktree of the repository: its -marker counts while its lease is open, the same test preflight uses, so a run parked -before finish stops counting once its 120-minute lease ends. It finds those worktrees +while a /ship run is open on the branch in any worktree of the repository: each +worktree's run record decides ([what ends a run](#what-ends-a-run)), so an open, +stopped, legacy or unreadable record counts, a finished or abandoned one does not, +and no timer ends a run. It finds those worktrees through the git common dir, and it checks and appends under a lock there that /ship's preflight also takes to write its marker. `add` refuses the scope and `--source gate`, so `gate` is the only writer. A row counts only when it has every @@ -2041,7 +2058,8 @@ The row is an approved `gstack-approvals` row with scope `test_lane_exception ` crew may grant) and -any grant while this checkout holds an open /ship run's marker, and `add` refuses +any grant while this checkout holds an open /ship run's record +([what ends a run](#what-ends-a-run)), and `add` refuses the scope, so the lane's own runner cannot write one; a row by gstack is ignored wherever it came from. `gstack-evidence record-ci` binds a grant only when its head is HEAD and its files are exactly the uncovered set, and only after a local diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 4c243a9ab..9173f73b6 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -712,32 +712,33 @@ fix-check record as Step 9's. Rerun Step 11's native pass on the same frozen tre `review_freshness` `CURRENT`, and Step 11.5 continues to Step 12. -### `STOP: /ship run is open on this checkout and past its preflight (; open until its finish or for 120 minutes) ...` +### `STOP: /ship run is open on this checkout and past its preflight (; state …, beat_age …; …) ...` **Meaning.** A full `gstack-ship-preflight` (Steps 1-3) ran on a checkout where a /ship run already passed them and has not finished. A full preflight merges the base into the working tree, and that run's review readers diff this tree, so the merge would void their pass (gbrain-evals#317). /ship passes `--run ` (Step 1: the preamble's `SESSION_ID`; `ship/DRIVER.md` Phase 2: the run dir's name). Once -Steps 1-3 succeed, preflight records the run in the checkout's git dir -(`gstack-ship-run`) and opens it on the checkout's own lease -(`/gstack-leases`, so the driver needs no workflow lease). The run -counts as open while the marker exists, which `gstack-ship-release finish` removes -when Steps 15-16 pass, and while `bin/gstack-lease open` says so: under 120 -minutes old and its holder (the harness that ran preflight) alive. A finished, -aged-out or dead run never blocks, and /ship's own first preflight (or a rerun -after a Step 3 STOP) is never refused. A different `--run` from the open run's -holder replaces it: that is a new /ship after one that stopped before finish. -The holder is the first non-shell process above preflight: the Claude Code -session, or on Capy the machine's one `capy-server`, so there only the same id or -a missing `--run` is refused. The same id, no `--run`, or an open run held by -another live process (another session) stops. +Steps 1-3 succeed, preflight opens the run in the checkout's run record (the +git dir's `gstack-ship-run`, [ship-policy.md](ship-policy.md#what-ends-a-run)). +The run stays open until a gstack command ends it: `gstack-ship-release finish` +removes the record, `gstack-ship-receipt stop` marks it stopped, +`gstack-skill-end` marks it finished, and `gstack-ship-run abandon` ends a run +that stopped working. No timer ends it, so a run that has waited two hours on CI +still blocks (GST-3260). A stopped, finished or abandoned record of another run +never blocks: the new run replaces it. A bare marker an older gstack wrote +(state `legacy`) and a record gstack can't read (state `unreadable`) block as +open. /ship's own first preflight, or a rerun after a Step 3 STOP, is never +refused. A `--run` the record already names stops with `/ship run already +ended on this checkout` (or `already stopped`): a run id names one /ship run. **What is kept.** Nothing ran: no fetch, no merge, the tree is untouched. **Fix.** Rerun Step 5 with `gstack-ship-preflight --tests-only`, which never -merges, or let that /ship finish. If that run is no longer running (it stopped -before finish), remove the marker the STOP names (`rm `), then rerun. +merges, or let that /ship finish. If that run is no longer working, end it with +the `gstack-ship-run abandon` command the STOP prints, from the earliest time it +prints ([ship-run-abandon-refused](#ship-run-abandon-refused)), then rerun. A +reused `--run` id needs a new id. **Expected result.** The preflight continues to `STATUS:` and `MERGE:`. @@ -7617,8 +7618,9 @@ closes a gate finding, and nothing the lane writes on its review row does either **Fix.** When the owner approved the gate change, record the owner's answer at the stop head the review read, with the `fingerprint` and `gate_id` from the review row, -while no /ship run is open on that branch in any worktree (a parked run's marker stops -counting once its 120-minute lease ends, as it does for preflight): +while no /ship run is open on that branch in any worktree (a parked run's record +counts until `gstack-ship-run abandon` or another gstack command ends it, as it does +for preflight; [ship-policy.md](ship-policy.md#what-ends-a-run)): ```bash gstack-approvals gate --finding '' --gate-id --head \ @@ -7891,15 +7893,45 @@ is refused) ([review-policy.md](review-policy.md#rounds-per-pull-request)). ### `STOP_UNBOUND` **Meaning.** `gstack-ship-receipt stop` found no review of this run that -gstack can tie to one commit: the newest `via:ship` review row since -`--since` is missing, didn't finish, read a tree that moved or wasn't -committed, or its commit isn't HEAD or under it. It recorded no stop record, so +gstack can tie to one commit: the newest `via:ship` reading row since +`--since` (a full pass, a fix-check or a Step 11 voice, whichever read last, +#4591) is missing, didn't finish, read a tree that moved or wasn't committed, +or its commit isn't HEAD or under it. It recorded no stop record, so no fix-check grant can buy that review's fix round. **Fix.** Nothing for a grant to answer. The lane's Captain ships with the open notes listed or parks; a fresh `/ship` run gives the head its review ([review-policy.md](review-policy.md#rounds-per-pull-request)). + +### `SHIP_RUN_ABANDON_REFUSED` + +**Meaning.** `gstack-ship-run abandon` left the run record as it was. Either +the run beat (preflight, a review start or finish, stub, stop or claim) in the +last 60 minutes, so it may still be working; or the record names another run, +or already ended (finished or abandoned); or the record is unreadable and the +`--sha256` given isn't its digest. `--by` naming gstack itself is a usage error. + +**Fix.** Run `gstack-ship-run status`. It prints the run, its state, its +`beat_age` and the exact abandon command. Wait until the earliest abandon time +when the run may still be working, and pass the run the record names. Abandon +completes in one call: after `RUN_ABANDONED` the record is ended, so never +rerun it, even when `RUN_ABANDON_PR` says the PR body entry was skipped or not +recorded (add that entry with `gstack-ship-receipt abandoned` instead). + + +### `SHIP_RUN_RECORD_UNREADABLE` + +**Meaning.** This checkout's /ship run record (the git dir's `gstack-ship-run`) +is neither a run record nor a bare run id. Every guard reads it as an open run +(it fails closed), so preflight, round grants, rulings without `--owner-ref`, +gate dispositions and lane exceptions stop until it is ended. + +**Fix.** If no /ship run is working on this checkout, run the command +`gstack-ship-run status` prints once: +`gstack-ship-run abandon --run unknown --sha256 --by --reason ""`. +The digest binds the abandon to the bytes you inspected. + ### `GRANT_SPENT` diff --git a/lib/gate-dispositions.ts b/lib/gate-dispositions.ts index 916636271..b4c8a2a2e 100644 --- a/lib/gate-dispositions.ts +++ b/lib/gate-dispositions.ts @@ -17,13 +17,12 @@ import { createHash } from 'node:crypto'; import { spawnSync } from './spawn-sync'; import * as fs from 'node:fs'; -import * as path from 'node:path'; import { appendRows, locate, readRecord, type ApprovalRow, type Env, type RecordError, type StoreLocation } from './approval-record'; import type { ShipReceipt } from './headless-artifacts'; import type { ResultCodeName } from './result-codes'; import { isGstackActor, type RuledNote } from './ruled-notes'; import { isSecurityFinding, REDACTED_FINDING, REDACTED_REASON, REDACTED_WORDS } from './security-findings'; -import { BIN_DIR, runScriptSync } from './script-invocation'; +import { openRun, readRunRecord, withGateLock } from './ship-run-record'; export interface GateDisposition { finding: string; gate_id: string; head: string; by: string; reason: string; words: string; at: string; approval: string } @@ -104,53 +103,33 @@ export function appliedGateDispositions(cwd: string, o: { branch?: string; pin: /** * The /ship runs open on `branch` in any worktree of this repository (found through the git common dir); a detached worktree's run - * counts too. A marker counts while its run's lease is open (`gstack-lease open`, the test preflight uses), so a run parked before - * finish stops counting once its 120-minute lease ends; a lease check that cannot run counts the marker as open. + * counts too. Each worktree's run record decides (lib/ship-run-record.ts): an open, stopped, legacy or unreadable record counts, + * a finished or abandoned one does not, and no timer ends a run. `detail` is the record's state, beat_age and abandon command. */ -export function openShipRunsOn(cwd: string, branch: string): string[] { +export function openShipRunsOn(cwd: string, branch: string): Array<{ text: string; detail: string }> { const list = spawnSync('git', ['worktree', 'list', '--porcelain'], { cwd, encoding: 'utf8', timeout: 10_000 }); - if (list.status !== 0) return [`unknown (git worktree list failed: ${(list.stderr ?? '').trim().slice(0, 120)})`]; + if (list.status !== 0) return [{ text: `unknown (git worktree list failed: ${(list.stderr ?? '').trim().slice(0, 120)})`, detail: '' }]; const here = spawnSync('git', ['rev-parse', '--show-toplevel'], { cwd, encoding: 'utf8', timeout: 10_000 }).stdout?.trim() ?? ''; const real = (p: string) => { try { return fs.realpathSync(p); } catch { return p; } }; - const open: string[] = []; + const open: Array<{ text: string; detail: string }> = []; for (const block of list.stdout.split(/\n\n+/).filter(b => b.trim())) { const dir = /^worktree (.+)$/m.exec(block)?.[1]; const on = /^branch refs\/heads\/(.+)$/m.exec(block)?.[1]; if (!dir || /^bare$/m.test(block) || (on !== undefined && on !== branch)) continue; - const marker = spawnSync('git', ['rev-parse', '--git-path', 'gstack-ship-run'], { cwd: dir, encoding: 'utf8', timeout: 10_000 }); - if (marker.status !== 0 || !marker.stdout.trim()) continue; - let run = ''; - try { run = fs.readFileSync(path.resolve(dir, marker.stdout.trim()), 'utf8').trim(); } catch { continue; } - if (!run || runScriptSync(path.join(BIN_DIR, 'gstack-lease'), ['open', '--root', dir, '--run', run], { cwd: dir, encoding: 'utf8', timeout: 60_000 }).status === 1) continue; - open.push(real(dir) === real(here) ? `${run} is open on this checkout` : `${run} is open in the worktree ${dir}`); + const run = openRun(readRunRecord(dir)); + if (!run) continue; + open.push({ text: real(dir) === real(here) ? `${run.run} is open on this checkout` : `${run.run} is open in the worktree ${dir}`, detail: `${run.run}: ${run.detail}` }); } return open; } -/** Run `fn` holding the repository's gate-disposition lock (a directory in the git common dir; one older than a minute is stale). */ -export function withGateLock(cwd: string, fn: () => T, waitMs = 15_000): T | RecordError { - const common = spawnSync('git', ['rev-parse', '--git-common-dir'], { cwd, encoding: 'utf8', timeout: 10_000 }); - if (common.status !== 0 || !common.stdout.trim()) return { code: 'APPROVAL_RECORD_WRITE_FAILED', message: `no git common dir at ${cwd}, so the gate-disposition lock cannot be taken` }; - const lock = path.join(path.resolve(cwd, common.stdout.trim()), 'gstack-gate-disposition.lock'); - const until = Date.now() + waitMs; - for (;;) { - try { fs.mkdirSync(lock); break; } catch (e: any) { - if (e.code !== 'EEXIST') return { code: 'APPROVAL_RECORD_WRITE_FAILED', message: `${lock}: ${e.code ?? e.message}` }; - try { if (Date.now() - fs.statSync(lock).mtimeMs > 60_000) { fs.rmSync(lock, { recursive: true, force: true }); continue; } } catch { continue; } - if (Date.now() > until) return { code: 'APPROVAL_RECORD_WRITE_FAILED', message: `${lock} is held; another gate disposition or /ship preflight is writing (rerun in a moment)` }; - Bun.sleepSync(100); - } - } - try { return fn(); } finally { fs.rmSync(lock, { recursive: true, force: true }); } -} - /** Append one disposition row under the lock, refused while any /ship run is open on its branch in any worktree (the check and the append are one step). */ export function recordGateDisposition(cwd: string, loc: StoreLocation, row: ApprovalRow): ReturnType { const signed = { ...row, digest: gateDispositionDigest(row as unknown as Record) } as ApprovalRow; if (!gateDispositions([signed], loc.branch).length) return { code: 'APPROVAL_RECORD_INVALID', message: 'the row would not count as a gate disposition (gstack-approvals dispositions would not list it: a 40-hex --head and one-line fields are required), so it would close nothing; nothing was written' }; const held = withGateLock(cwd, () => { const open = openShipRunsOn(cwd, loc.branch); - if (open.length) return { code: 'APPROVAL_RECORD_INVALID' as const, message: `/ship run ${open.join('; /ship run ')} (branch ${loc.branch}): a gate disposition is the owner's, never the lane's own runner's; record it from the owner's session once no /ship run is open on the branch` }; + if (open.length) return { code: 'APPROVAL_RECORD_INVALID' as const, message: `/ship run ${open.map(o => o.text).join('; /ship run ')} (branch ${loc.branch}): a gate disposition is the owner's, never the lane's own runner's; record it from the owner's session once no /ship run is open on the branch (${open.map(o => o.detail).filter(Boolean).join('; ')})` }; return appendRows(loc, [signed]); }); return held; diff --git a/lib/pr-review-history.ts b/lib/pr-review-history.ts index d08b86c1c..eb5487dac 100644 --- a/lib/pr-review-history.ts +++ b/lib/pr-review-history.ts @@ -39,13 +39,17 @@ function entries(body: string): ReceiptRun[] { return [...receiptRuns(body), ...(current && typeof current.head === 'string' ? [receiptRun(current)] : [])]; } +/** + * A run's stub and its own receipt at the same head count once (the newer entry stands); entries at different heads always count, + * so a run id reused across /ship runs never hides their rounds (gstack-evals#406: three receipts of ship-406 read rounds=1). + */ export function prReviewHistory(body: string): PrReviewHistory { const all = entries(body).filter(e => !e.mark); const reviewed = new Map(); const ordered: Array = []; all.forEach((e, i) => { - if (e.status || e.carry_kind || e.carried_from) { ordered.push(e); return; } - const key = e.run ? `run:${e.run}` : `#${i}`; + if (e.status === 'voided' || e.carry_kind || e.carried_from) { ordered.push(e); return; } + const key = e.run ? `run:${e.run}@${e.head}` : `#${i}`; if (!reviewed.has(key)) ordered.push(key); reviewed.set(key, e); }); @@ -94,15 +98,23 @@ export const runStub = (o: { head: string; run: string; status: 'started' | 'voi */ export const stopMarker = (o: { head: string; tree: string; run: string }): ReceiptRun => ({ head: o.head, run: o.run, mark: 'stop', tree: o.tree }); export const grantMarker = (o: { head: string; run: string; grant: string }): ReceiptRun => ({ head: o.head, run: o.run, mark: 'grant', grant: o.grant }); +/** gstack-ship-run abandon's entry (GST-3260): who ended a run that stopped working, and why, at the head it was abandoned on. */ +export const abandonMarker = (o: { head: string; run: string; by: string; reason: string }): ReceiptRun => ({ head: o.head, run: o.run, mark: 'abandoned', by: o.by, reason: o.reason }); +/** The newest receipt a run id already wrote, in the runs block or current: a run id names one /ship run (gstack-evals#406). */ +export const receiptedRun = (body: string, run: string) => entries(body).filter(e => e.run === run && !e.mark && !e.status).at(-1); + +/** The rows a /ship stop can follow: a full pass, a fix-check, or a Step 11 voice (#4591 stopped on its voices after a fix-check). */ +const STOP_READERS = new Set(['review', 'review-fix-check', 'adversarial-review', 'codex-review']); /** - * The stop record for the newest via:ship review row of this run (at or after since), or why none binds: the row must be complete, + * The stop record for the newest via:ship reading row of this run (at or after since): a full pass, a fix-check or a Step 11 voice, + * whichever read last, so the stop binds to the head that row read (#4591). Or why none binds: the row must be complete, * bound to one tree from start to end (verified, or incomplete because it stopped) that is its commit's own tree, read on a clean * worktree, and that commit must be HEAD or an ancestor of it. A read gstack can't tie to a commit gives a grant nothing to answer. */ export function stopFrom(rows: readonly Record[], since: string, o: { treeOf: (commit: string) => string | undefined; onHead: (commit: string) => boolean }): { ok: true; head: string; tree: string } | { ok: false; why: string } { const sinceMs = Date.parse(since); - const row = rows.filter(r => r && r.via === 'ship' && r.skill === 'review' && (!Number.isFinite(sinceMs) || Date.parse(r.timestamp) >= sinceMs)).at(-1); + const row = rows.filter(r => r && r.via === 'ship' && STOP_READERS.has(r.skill) && (!Number.isFinite(sinceMs) || Date.parse(r.timestamp) >= sinceMs)).at(-1); if (!row) return { ok: false, why: `no via:ship review row at or after ${since}` }; const b = row.review_binding, head = typeof row.commit_full === 'string' ? row.commit_full.toLowerCase() : ''; if (row.completed !== true) return { ok: false, why: 'the stopping review is not complete (a reader is missing)' }; diff --git a/lib/result-codes-release.ts b/lib/result-codes-release.ts index 7306a72ee..0c5813031 100644 --- a/lib/result-codes-release.ts +++ b/lib/result-codes-release.ts @@ -455,6 +455,16 @@ export const RELEASE_RESULT_CODES = { summary: 'another /ship run already claimed this round grant, and a grant buys one round', fix: 'the lane or its Captain records a new grant for the stop the PR is at now (gstack-ship-receipt stop prints the command)', }, + SHIP_RUN_ABANDON_REFUSED: { + anchor: 'ship-run-abandon-refused', + summary: 'gstack-ship-run abandon left the /ship run record as it was: the run beat in the last 60 minutes, the record names another run or already ended, or an unreadable record\'s digest did not match', + fix: 'read gstack-ship-run status: wait until the earliest abandon time it prints if the run may still be working, pass the run it names (an unreadable record: --run unknown --sha256 ), and leave an ended run alone', + }, + SHIP_RUN_RECORD_UNREADABLE: { + anchor: 'ship-run-record-unreadable', + summary: 'this checkout\'s /ship run record (git dir gstack-ship-run) is neither a run record nor a run id, so every guard reads it as an open run', + fix: 'if no /ship run is working on this checkout, end it with the gstack-ship-run abandon --run unknown --sha256 command status prints, once', + }, GRANT_UNKNOWN: { anchor: 'grant-unknown', summary: 'the branch approval record holds no approved review_round_grant row with this id', diff --git a/lib/ruled-notes.ts b/lib/ruled-notes.ts index 28008d5ab..20df4319e 100644 --- a/lib/ruled-notes.ts +++ b/lib/ruled-notes.ts @@ -5,11 +5,9 @@ * full sha of the stop head the owner ruled at; the row's `by` is the ruler and its `recorded_at` the time. A review-log field * never makes one, so the lane that logged a finding cannot close it. */ -import { spawnSync } from 'node:child_process'; -import * as fs from 'node:fs'; -import * as path from 'node:path'; import { locate, readRecord, type ApprovalRow, type Env } from './approval-record'; import { isSecurityFinding, REDACTED_FINDING, REDACTED_REASON } from './security-findings'; +import { openRun, readRunRecord } from './ship-run-record'; export interface RuledNote { finding: string; head: string; by: string; reason: string; at: string; approval: string; relayed?: string; not_security?: true } @@ -70,9 +68,8 @@ export const publicRuledNote = (n: RuledNote): RuledNote => !isSecurityFinding(n /** The one-line form finish prints after `RULED_NOTE: ` and the PR body carries after `Ruled note: `, from publicRuledNote. */ export const ruledNoteText = (note: RuledNote) => { const n = publicRuledNote(note); return `${n.finding} at ${n.head.slice(0, 12)} ruled by ${n.by}${n.relayed ? ` (relayed from ${n.relayed})` : ''} at ${n.at}: ${n.reason} (approval ${n.approval})`; }; -/** The /ship run open on this checkout (its marker in the git dir, which finish removes), if any. */ -export function openShipRun(cwd: string): string | undefined { - const p = spawnSync('git', ['rev-parse', '--git-path', 'gstack-ship-run'], { cwd, encoding: 'utf8', timeout: 10_000 }); - if (p.status !== 0 || !p.stdout.trim()) return undefined; - try { return fs.readFileSync(path.resolve(cwd, p.stdout.trim()), 'utf8').trim() || undefined; } catch { return undefined; } -} +/** + * The /ship run this checkout's run record holds open (open, stopped, legacy or unreadable), with the line a refusal prints: its state, + * beat_age and abandon command; none once the run finished or was abandoned (lib/ship-run-record.ts). + */ +export const openShipRun = (cwd: string) => openRun(readRunRecord(cwd)); diff --git a/lib/ship-bin-common.ts b/lib/ship-bin-common.ts index d659e45f9..7ebd44da4 100644 --- a/lib/ship-bin-common.ts +++ b/lib/ship-bin-common.ts @@ -28,11 +28,6 @@ const done = (r: { status: number | null; stdout?: string | Buffer | null; stder export function git(cwd: string, args: string[], timeout = 120_000): Run { return done(spawnSync('git', args, { cwd, encoding: 'utf8', timeout, maxBuffer: 64 * 1024 * 1024, env: { ...process.env, GIT_TERMINAL_PROMPT: '0' } })); } -/** GST-1204: the /ship run that passed Steps 1-3 on this checkout, recorded in its own git dir (per worktree) until finish clears it; empty outside a checkout. */ -export function shipRunMarker(cwd: string): string { - const p = git(cwd, ['rev-parse', '--git-path', 'gstack-ship-run']); - return p.status === 0 && p.stdout.trim() ? path.resolve(cwd, p.stdout.trim()) : ''; -} export function bin(cwd: string, name: string, args: string[], timeout = 600_000): Run { return done(runScriptSync(path.join(BIN_DIR, name), args, { cwd, encoding: 'utf8', timeout, maxBuffer: 64 * 1024 * 1024 })); } diff --git a/lib/ship-preflight.ts b/lib/ship-preflight.ts index d3ec7256d..9157cc868 100644 --- a/lib/ship-preflight.ts +++ b/lib/ship-preflight.ts @@ -17,15 +17,16 @@ import { reviewPlanTimeoutMs } from './review-collect'; import { classifyDiff } from './review-depth'; import { wtreeFingerprint } from './script-invocation'; import { audit } from './ship-audit'; -import { withGateLock } from './gate-dispositions'; -import { bin, carryNoneLines, firstLine, flagReader, gh, git, hostedOrigin, laneConcurrency, laneLine, lanes, mappedLanes, recordCiTimeout, Report, runLanes, shipPolicy, shipRunMarker, short } from './ship-bin-common'; +import { changeRunRecord, openRun, readRunRecord } from './ship-run-record'; +import { bin, carryNoneLines, firstLine, flagReader, gh, git, hostedOrigin, laneConcurrency, laneLine, lanes, mappedLanes, recordCiTimeout, Report, runLanes, shipPolicy, short } from './ship-bin-common'; export const PREFLIGHT_HELP = `gstack-ship-preflight — /ship Steps 1-3 and Step 5's pregate and lanes in one call (ship/SKILL.md) gstack-ship-preflight --base [--lane