From bea98d888ab83f7bed1071591546e07f0733bee6 Mon Sep 17 00:00:00 2001 From: garrytan Date: Wed, 18 Nov 2026 09:17:54 +0000 Subject: [PATCH 1/6] Let an owner rule a blocker from the final review below the bar, so the PR ships with it listed (GST-2273, GST-3005) Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- bin/gstack-approvals | 14 +- bin/gstack-doctor-components.sh | 1 + bin/gstack-review-plan | 4 +- bin/gstack-ship-receipt | 97 ++++++++- ...se-a-ruled-stop-and-read-only-deferrals.md | 4 + docs/review-policy.md | 49 ++++- docs/ship-policy.md | 4 + docs/troubleshooting.md | 25 +++ lib/headless-artifacts.ts | 4 +- lib/pr-review-history.ts | 5 +- lib/result-codes-release.ts | 7 +- lib/review-round-grant.ts | 19 ++ lib/ruled-notes.ts | 26 +++ lib/ruled-stop.ts | 119 ++++++++++ lib/ship-receipt-depth.ts | 36 +-- lib/ship-release.ts | 5 +- scripts/lib/windows-curation.ts | 4 + ship/sections/pr-body.md | 3 +- ship/sections/pr-body.md.tmpl | 3 +- ship/sections/review-army.md | 4 + ship/sections/review-army.md.tmpl | 4 + .../files/ship/sections/review-army.md.json | 2 +- .../review-pins/replays/GST-2273.json | 1 + test/round-cap-granted-stop.test.ts | 24 +- test/ruled-stop.test.ts | 206 ++++++++++++++++++ ...-a-ruled-stop-and-read-only-deferrals.json | 4 + 26 files changed, 627 insertions(+), 47 deletions(-) create mode 100644 changelog.d/owner-rulings-close-a-ruled-stop-and-read-only-deferrals.md create mode 100644 lib/ruled-stop.ts create mode 100644 test/fixtures/review-pins/replays/GST-2273.json create mode 100644 test/ruled-stop.test.ts create mode 100644 test/size-ledger/ship/owner-rulings-close-a-ruled-stop-and-read-only-deferrals.json diff --git a/bin/gstack-approvals b/bin/gstack-approvals index e5b7fd7eb0b..744906b66d4 100755 --- a/bin/gstack-approvals +++ b/bin/gstack-approvals @@ -29,7 +29,7 @@ import { spawnSync } from 'node:child_process'; import * as path from 'node:path'; import { EXIT, exitTableHelp } from '../lib/headless-artifacts'; import { appendRows, branchExists, buildRow, importAutoplan, locate, readRecord, renderMode, renderRecord, repoVisibility, syncRecord, type RecordError, type StoreLocation } from '../lib/approval-record'; -import { GSTACK_ACTOR, openShipRun, RULED_NOTE_SCOPE, ruledNoteRow, ruledNotes, ruledNoteText } from '../lib/ruled-notes'; +import { GSTACK_ACTOR, openShipRun, RULED_NOTE_SCOPE, ruledNoteRow, ruledNotes, ruledNoteText, stopRulingRow } from '../lib/ruled-notes'; import { resultLine } from '../lib/result-codes'; import { parsePlanLine, publicPlanLine, resolvePlan } from '../lib/plan-record'; import { TEST_LANE_EXCEPTION_SCOPE, testLaneExceptionRow } from '../lib/test-lane-exception'; @@ -43,10 +43,12 @@ const HELP = `gstack-approvals — the per-thread approval record (capy/skill/gs import --autoplan [--by ] [--stack ] --stack writes the same rows to every branch of a stack; each branch is checked first, and one unknown branch writes none rule --finding --head --reason - --words --by + --words --by [--pr --stop-run ] the owner's ruling that a review finding ships as a disclosed note (docs/ship-policy.md#ruled-notes); finish counts that finding closed on a fix-check whose range_base..commit holds the head, and the receipt and PR body - list it; refused inside this checkout's open /ship run + list it; refused inside this checkout's open /ship run. With --pr and --stop-run, --finding is the ledger id + of one open finding of the stop record that run left at --head (gstack-ship-receipt ruled-stop lists them), + and only that stop's ruled-stop check applies it rulings the "Ruled note: …" lines the Pre-Landing Review and the PR body carry gate --finding --gate-id --head --reason --words --by @@ -208,7 +210,11 @@ function main(argv: string[]): number { if (GSTACK_ACTOR.test((flags['--by'] ?? '').trim())) return invalid('--by names gstack; a ruling is the owner\'s, so --by names who ruled'); const open = openShipRun(process.cwd()); if (open) return invalid(`/ship run ${open} is open on this checkout: a ruling is the owner's, never the lane's own runner's; record it from the owner's session`); - const built = buildRow({ ...ruledNoteRow(finding, head.stdout.trim(), reason), words: flags['--words'] ?? '', by: flags['--by'] ?? '', date: flags['--date'] }, loc.branch); + const stopRun = flags['--stop-run']?.trim(), pr = flags['--pr']?.trim(); + if ((stopRun === undefined) !== (pr === undefined)) return invalid('a stop ruling names both --pr and --stop-run ; omit both for a fix-check ruling by fingerprint'); + if (stopRun !== undefined && (!STOP_RUN.test(stopRun) || !/^[1-9]\d*$/.test(pr!) || !FINDING_ID.test(finding))) return invalid('a stop ruling needs --pr , --stop-run and --finding '); + const ruling = stopRun !== undefined ? stopRulingRow(finding, head.stdout.trim(), Number(pr), stopRun, reason) : ruledNoteRow(finding, head.stdout.trim(), reason); + const built = buildRow({ ...ruling, words: flags['--words'] ?? '', by: flags['--by'] ?? '', date: flags['--date'] }, loc.branch); if ('code' in built) return fail(cmd, built); rows = [built]; } else if (cmd === 'gate') { diff --git a/bin/gstack-doctor-components.sh b/bin/gstack-doctor-components.sh index a66a19b59a1..6a1fddce196 100644 --- a/bin/gstack-doctor-components.sh +++ b/bin/gstack-doctor-components.sh @@ -341,6 +341,7 @@ gstack_result_anchor() { RECEIPT_CARRY_TREE_MISMATCH) printf '%s' 'receipt-carry-tree-mismatch' ;; RECEIPT_CARRY_PRODUCT_CHANGED) printf '%s' 'receipt-carry-product-changed' ;; STOP_UNBOUND) printf '%s' 'stop-unbound' ;; + RULED_STOP_OPEN) printf '%s' 'ruled-stop-open' ;; GRANT_SPENT) printf '%s' 'grant-spent' ;; GRANT_UNKNOWN) printf '%s' 'grant-unknown' ;; RECEIPT_CARRY_SCOPED_REVIEW) printf '%s' 'receipt-carry-scoped-review' ;; diff --git a/bin/gstack-review-plan b/bin/gstack-review-plan index 929edc6938b..427da9757dd 100755 --- a/bin/gstack-review-plan +++ b/bin/gstack-review-plan @@ -25,7 +25,7 @@ import * as path from 'node:path'; import { spawnSync } from 'node:child_process'; import { baseContainsHead } from '../lib/default-base'; import { locate, readRecord } from '../lib/approval-record'; -import { reviewRoundGrants } from '../lib/review-round-grant'; +import { readGrantedStop, reviewRoundGrants } from '../lib/review-round-grant'; import { EXIT, exitTableHelp } from '../lib/headless-artifacts'; import { resultLine } from '../lib/result-codes'; import { runScriptSync } from '../lib/script-invocation'; @@ -197,6 +197,8 @@ function main(): number { 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 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; } + const stamp = g?.kind === 'fix-check' && root ? readGrantedStop(root) : undefined; + if (g?.kind === 'fix-check' && (stamp?.grant !== g.approval || stamp.head !== g.head || stamp.pr !== g.pr)) { process.stderr.write(`gstack-review-plan: --round-grant ${roundGrant}: gstack-ship-receipt history on this checkout has not matched this fix-check grant to the PR's newest stop record (its run, head and findings)${stamp ? `; it last matched grant ${stamp.grant}` : ''}: run gstack-ship-receipt history --pr ${g.pr} --base --run here and pass the --round-grant and --stop its PR_REVIEW_FLAGS: line prints (docs/troubleshooting.md#stop-unbound)\n`); return EXIT.refused; } if (g?.kind === 'fix-check') grantedStop = g.approval; 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; } diff --git a/bin/gstack-ship-receipt b/bin/gstack-ship-receipt index a91041a11a8..7e9e11b99e0 100755 --- a/bin/gstack-ship-receipt +++ b/bin/gstack-ship-receipt @@ -56,16 +56,19 @@ import { import { checkDocsCaps, docsCapLine, docsExceptionLine, parseReceiptDocs } from '../lib/ship-receipt-docs'; import { comparePath, contextPacket, PACKET_SECTION_CAP, readScopedReview, touchedPaths } from '../lib/ship-patch'; import { planRecheck, recheckPacket } from '../crew/lib/ship-recheck'; -import { carryExcludeBinds, deeper, depthBelow, exceptionHead, exceptionLoopProblem, exceptionProblems, parseReviewLoopException, parseReviewTargeted, plainDocsSince, platformReceiptDepth, receiptExclude, receiptReviewAtHead, receiptTargetedAtHead, reviewLoopExceptionLine, targetedClassesSince, writeExcludeBinds } from '../lib/ship-receipt-depth'; +import { type ReviewLoopException, carryExcludeBinds, deeper, depthBelow, exceptionHead, exceptionLoopProblem, exceptionProblems, parseReviewLoopException, parseReviewTargeted, plainDocsSince, platformReceiptDepth, receiptExclude, receiptReviewAtHead, receiptTargetedAtHead, reviewLoopExceptionLine, targetedClassesSince, writeExcludeBinds } from '../lib/ship-receipt-depth'; import { RISK_CLASSES, type RiskClass } from '../lib/review-risk'; import { checkReceiptProse, proseLine } from '../lib/ship-receipt-prose'; import { resolveStateRoot } from '../lib/state-root'; import { readPause, receiptBaseRed } from '../lib/base-red'; -import { readRuledNotes, ruledNoteText } from '../lib/ruled-notes'; +import { readRuledNotes, ruledNoteText, stopRulings } from '../lib/ruled-notes'; +import { ledgerTraits, ruledStop, ruledStopLines, type RuledStop } from '../lib/ruled-stop'; +import { ledgerBlockers } from '../lib/review-ledger'; +import { locate, readRecord } from '../lib/approval-record'; import { appliedGateDispositions, gateDispositionText } from '../lib/gate-dispositions'; import { laneExceptionBodyLines } from '../lib/test-lane-exception'; import { grantedStop, grantMarker, historyLine, placeRunEntry, prReviewHistory, reviewRoute, runStub, stopFrom, stopMarker } from '../lib/pr-review-history'; -import { grantFor, readReviewRoundGrants, type ReviewRoundGrant } from '../lib/review-round-grant'; +import { grantFor, readReviewRoundGrants, writeGrantedStop, type ReviewRoundGrant } from '../lib/review-round-grant'; import { readMechanicalLines } from '../lib/ship-mechanical'; import { isRegistryUnavailable, loadRegistryFromBase } from '../lib/regen'; import { runCalls } from '../lib/ship-clock'; @@ -114,6 +117,11 @@ const HELP = `gstack-ship-receipt — the \`\`\`gstack-ship-receipt\`\`\` block 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) + ruled-stop --pr | --body --run --since --dir + after a stop the owner ruled (Step 11.5): whether every open finding of this run's stop record has + a stop ruling (gstack-approvals rule --pr --stop-run) at HEAD, the stop's head: one + RULED_STOP_FINDING: line per finding, then RULED_STOP: closed (exit 0) or open, none or unbound + (RULED_STOP_OPEN, exit 3; docs/troubleshooting.md#ruled-stop-open) 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) @@ -134,7 +142,10 @@ write flags: --pr --head --base --version --gated-tree --predecessor --gate ({accepted_by, date, via, reason, fix_check: {head, findings[, files]}}: the owner accepted a stop after a fix-check edit; needs --review-loop with fix_checks >= 1, fix_check.head an ancestor of the head, and with --body the "Review-loop exception: …" line verbatim; or second_pass: {head, deferred: []} in place of fix_check for a stop after - the second full pass with a finding left open, needing passes >= 2 and deferred >= 1; else REVIEW_LOOP_EXCEPTION_INVALID). Every receipt records gstack_version and + the second full pass with a finding left open, needing passes >= 2 and deferred >= 1; or read_only: {head, deferred} for a ruled stop + of the read-only final review; --ruled-stop (with --run, --since and --dir) reruns the ruled-stop check, which must read closed with + exactly the deferred ids, and is required for read_only (history before this run shows two full rounds) and lets second_pass take + its ruled ids without deferred >= 1; else REVIEW_LOOP_EXCEPTION_INVALID). Every receipt records gstack_version and review_depth: the depth HEAD needs, recomputed from the committed range (--head must be HEAD; a dirty checkout or an unreadable input records full). --review-exclude (the digest= on gstack-review-dispatch verify's REVIEW_EXCLUDE_RECORD: line, which the reviewers' briefs @@ -300,11 +311,14 @@ function cmdWrite(rest: string[], json: boolean): number { const refuse = (why: string) => { process.stderr.write(resultLineWithDocs('gstack-ship-receipt write', 'REVIEW_LOOP_EXCEPTION_INVALID', `${why}; nothing written`) + '\n'); return EXIT.fail; }; try { loopException = parseReviewLoopException(jsonArg(flag(rest, '--review-loop-exception'))); } catch (e: any) { return refuse(`--review-loop-exception: ${e.message}`); } if (!loopException.ok) return refuse(loopException.message); + const ruledProblem = ruledStopException(rest, repoRoot, bodyFile ? bodyText : undefined, loopException.exception); + if (typeof ruledProblem === 'string') return refuse(ruledProblem); + if (ruledProblem) loopException.exception.ruled = ruledProblem.ruled; let loop: unknown; try { loop = jsonArg(flag(rest, '--review-loop')); } catch {} const loopProblem = exceptionLoopProblem(loopException.exception, parseReviewLoop(loop)); if (loopProblem) return refuse(`--review-loop-exception ${loopProblem}`); const fc = exceptionHead(loopException.exception); - if (spawnSync('git', ['merge-base', '--is-ancestor', fc, head], { cwd: repoRoot }).status !== 0) return refuse(`${loopException.exception.fix_check ? 'fix_check' : 'second_pass'}.head ${fc.slice(0, 12)} is not ${head.slice(0, 12)} or an ancestor of it`); + if (spawnSync('git', ['merge-base', '--is-ancestor', fc, head], { cwd: repoRoot }).status !== 0) return refuse(`${loopException.exception.fix_check ? 'fix_check' : loopException.exception.read_only ? 'read_only' : 'second_pass'}.head ${fc.slice(0, 12)} is not ${head.slice(0, 12)} or an ancestor of it`); const line = reviewLoopExceptionLine(loopException.exception); if (bodyFile && !bodyText.split(/\r?\n/).some(l => l.trim() === line)) return refuse(`${bodyFile} does not carry the exception line verbatim: ${JSON.stringify(line)}`); } @@ -1095,6 +1109,7 @@ function cmdHistory(rest: string[], json: boolean): number { const claimed = found && !answer?.ok ? receiptRuns(read.body).find(r => r.mark === 'grant' && r.grant === found.approval && r.run !== flag(rest, '--run')) : undefined; 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 }); + if (repoRoot && /^\d+$/.test(pr)) writeGrantedStop(repoRoot, answer?.ok ? { pr: Number(pr), grant: answer.grant.approval, head: answer.stop.head, run: answer.stop.run!, findings: answer.grant.findings! } : null); 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` : ''}`); @@ -1124,6 +1139,77 @@ function cmdStop(rest: string[]): number { return EXIT.ok; } +/** The ruled-stop check's inputs, read from the PR body, the review log, this run's ledgers under --dir and the approval record. */ +function readRuledStop(rest: string[], repoRoot: string, body: string, pr: number): RuledStop | string { + const run = flag(rest, '--run'), since = flag(rest, '--since'), dir = flag(rest, '--dir'); + if (!run || !/^[\w.:-]{1,120}$/.test(run) || !since || !dir) return '--run , --since and --dir are required'; + const log = runScriptSync(path.join(path.dirname(Bun.fileURLToPath(import.meta.url)), 'gstack-review-read'), [], { cwd: repoRoot, encoding: 'utf8', timeout: 60_000, maxBuffer: 64 * 1024 * 1024 }); + if (log.status !== 0) return `gstack-review-read exited ${log.status}`; + const sinceMs = Date.parse(since); + const rows = (log.stdout ?? '').split('\n---CONFIG---')[0]!.split('\n').flatMap(l => { try { const v = JSON.parse(l); return v && typeof v === 'object' && v.via === 'ship' && !(Date.parse(v.timestamp) < sinceMs) ? [v] : []; } catch { return []; } }); + let files: string[]; + try { files = (fs.readdirSync(dir, { recursive: true }) as string[]).filter(p => path.basename(p) === 'review-ledger.jsonl').sort().map(p => path.join(dir, p)); } catch (e: any) { return `--dir ${dir}: ${e.code ?? e.message}`; } + if (!files.length) return `--dir ${dir} holds no review-ledger.jsonl: name the run directory this run's passes wrote`; + const keyOf = (file: string) => (id: string) => `${path.basename(path.dirname(path.resolve(file)))}/${id}`; + let blockers: string[], traits: ReturnType; + try { blockers = files.flatMap(f => ledgerBlockers(f).map(b => keyOf(f)(b.id))); traits = files.flatMap(f => ledgerTraits(f, keyOf(f))); } catch (e: any) { return (e as Error).message.split('\n')[0]!; } + const loc = locate({ cwd: repoRoot, env: process.env }); + if ('code' in loc) return `the approval record is unreadable: ${loc.message}`; + const stop = receiptRuns(body).filter(r => r.mark === 'stop').at(-1); + return ruledStop({ pr, run, stop: stop && { head: stop.head, tree: stop.tree, run: stop.run! }, rows, blockers, traits, rulings: stopRulings(readRecord(loc).rows) }); +} + +/** + * write --review-loop-exception with --ruled-stop (GST-2273, GST-3005): rerun the ruled-stop check; it must read closed with exactly + * the exception's deferred ids at its head, and a read_only exception also needs two full rounds in the PR's history before this run. + * The body carries one "Ruled note: …" line per ruling. Returns the verified approval ids, null without --ruled-stop, or the refusal. + */ +function ruledStopException(rest: string[], repoRoot: string, bodyText: string | undefined, e: ReviewLoopException): { ruled: string[] } | null | string { + if (e.ruled) return 'ruled is written by --ruled-stop from the verified stop rulings: leave it out of the exception'; + if (!rest.includes('--ruled-stop')) return e.read_only ? 'read_only needs --ruled-stop: the owner rules each open finding of the read-only final review' : null; + const stopOf = e.second_pass ?? e.read_only; + if (!stopOf) return '--ruled-stop takes a second_pass or read_only exception: a fix-check stop is ruled by fingerprint at finish'; + const pr = Number(flag(rest, '--pr') ?? NaN); + if (!Number.isInteger(pr) || pr < 1) return '--ruled-stop needs --pr : the rulings name the PR'; + const hasStop = (b: string | undefined) => !!b && receiptRuns(b).some(r => r.mark === 'stop'); + const live = hasStop(bodyText) ? { ok: true as const, body: bodyText! } : readBody(['--pr', String(pr), ...(flag(rest, '--repo') ? ['--repo', flag(rest, '--repo')!] : [])]); + if (!live.ok) return `--ruled-stop: ${live.why}`; + const r = readRuledStop(rest, repoRoot, live.body, pr); + if (typeof r === 'string') return `--ruled-stop: ${r}`; + if (r.state !== 'closed') return `--ruled-stop: ${ruledStopLines(r, pr).at(-1)!}`; + if (r.stop!.head !== stopOf.head) return `--ruled-stop: the ruled stop is at ${r.stop!.head.slice(0, 12)}, not the exception head ${stopOf.head.slice(0, 12)}`; + const ids = r.findings.map(f => f.id); + if (JSON.stringify([...new Set(stopOf.deferred)].sort()) !== JSON.stringify([...ids].sort()) || stopOf.deferred.length !== ids.length) return `--ruled-stop: deferred must name exactly the ruled stop's findings (${ids.join(', ')}), not ${stopOf.deferred.join(', ')}`; + if (e.read_only) { + const before = prReviewHistory(live.body, { except: flag(rest, '--run') }); + if (before.full < 2) return `--ruled-stop: read_only needs two full review rounds before this run, and the PR body shows ${before.full}: a read-only final review follows the PR's two rounds`; + } + const missing = bodyText !== undefined ? r.findings.map(f => `Ruled note: ${ruledNoteText(f.ruling!)}`).find(l => !bodyText.split(/\r?\n/).some(b => b.trim() === l)) : undefined; + if (missing) return `the body does not list ${JSON.stringify(missing)}`; + return { ruled: r.findings.map(f => f.ruling!.approval) }; +} + +/** Step 11.5 after a ruled stop (GST-2273, GST-3005): whether the owner ruled every open finding of this run's stop at HEAD. */ +function cmdRuledStop(rest: string[]): number { + const repoRoot = git(['rev-parse', '--show-toplevel']); + if (!repoRoot) { process.stderr.write('gstack-ship-receipt ruled-stop: run it inside the git checkout\n'); return EXIT.usage; } + const read = readBody(rest); + if (!read.ok) { process.stderr.write(`gstack-ship-receipt ruled-stop: ${read.why}; fix: ${read.fix}\n`); return EXIT.fail; } + const pr = Number(flag(rest, '--pr') ?? NaN); + if (!Number.isInteger(pr) || pr < 1) { process.stderr.write('gstack-ship-receipt ruled-stop: --pr is required (the PR the rulings name)\n'); return EXIT.usage; } + const r = readRuledStop(rest, repoRoot, read.body, pr); + if (typeof r === 'string') { process.stderr.write(`gstack-ship-receipt ruled-stop: ${r}\n`); return EXIT.usage; } + const head = git(['rev-parse', 'HEAD'], repoRoot) ?? ''; + const dirty = spawnSync('git', ['diff', '--quiet', 'HEAD', '--'], { cwd: repoRoot, timeout: 30_000 }).status !== 0; + const moved = !r.stop ? '' : head !== r.stop.head ? `HEAD ${head.slice(0, 12)} is not the stop's head ${r.stop.head.slice(0, 12)}: a head move voids the rulings` : dirty ? 'the worktree has uncommitted changes: the rulings bind the stop\'s committed tree' : ''; + const lines = ruledStopLines(r, pr); + process.stdout.write(lines.slice(0, -1).map(l => l + '\n').join('')); + if (r.state !== 'closed' || moved) { process.stderr.write(resultLine('gstack-ship-receipt ruled-stop', 'RULED_STOP_OPEN', moved || lines.at(-1)!.replace(/^RULED_STOP: /, '')) + '\n'); return EXIT.refused; } + for (const f of r.findings) process.stdout.write(`RULED_NOTE: ${ruledNoteText(f.ruling!)}\n`); + process.stdout.write(lines.at(-1)! + '\n'); + return EXIT.ok; +} + /** Before a granted round's first dispatch: this run spends the grant, so no other run can buy the same round with it. */ function cmdClaim(rest: string[]): number { const run = flag(rest, '--run'), id = flag(rest, '--grant'); @@ -1178,6 +1264,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 === 'ruled-stop') return cmdRuledStop(rest); process.stderr.write(`gstack-ship-receipt: unknown command ${cmd}\n${HELP}\n`); return EXIT.usage; } diff --git a/changelog.d/owner-rulings-close-a-ruled-stop-and-read-only-deferrals.md b/changelog.d/owner-rulings-close-a-ruled-stop-and-read-only-deferrals.md new file mode 100644 index 00000000000..9d04edaec5e --- /dev/null +++ b/changelog.d/owner-rulings-close-a-ruled-stop-and-read-only-deferrals.md @@ -0,0 +1,4 @@ +--- +important: blocker +--- +- **An owner can now rule a blocker found by /ship's final review below the floor, and the PR ships with it listed as a note (GST-2273, GST-3005).** Before, a ruling after a round-2 full review changed nothing, though the docs said it closed the finding, and a PR past its two review rounds had no way to record an owner-accepted deferral from its read-only final review. A ruling now names one open finding of the stop /ship recorded, by its review id (`gstack-approvals rule --pr --stop-run --head --finding`). `gstack-ship-receipt ruled-stop` then shows whether every open finding of that stop is ruled, and the receipt records the deferral only after running that check again. Gate findings and security-class blockers can't be ruled, and a later commit voids the rulings. The review log and its summary still show a ruled finding as open. diff --git a/docs/review-policy.md b/docs/review-policy.md index 9f381c3d2a9..477b4d286bb 100644 --- a/docs/review-policy.md +++ b/docs/review-policy.md @@ -93,7 +93,8 @@ incomplete coverage, which blocks until the reviewer is rerun. 3. **Two rounds is the cap** (R51): a full pass, a scoped pass ([below](#scoped-pass)) or a fix-check is a round. After round 2 the run finishes with its open notes listed in the PR body and receipt (an owner-ruled - note is closed and listed: [ruled notes](ship-policy.md#ruled-notes)), or stops for + blocker ships as a listed note through the receipt, [ruled stops](#rounds-per-pull-request) + item 7; review-read and the loop summary still show it open), or stops for the owner when a blocking finding is open, or was fixed in round 2 and is unverified, or a round-2 fix edited a gate-class path, naming it (path, severity, problem). The cap limits fix rounds, not Step 11's voices: on gate @@ -215,7 +216,10 @@ caught on another crew's PRs. head, or another run claimed it (`PR_REVIEW_GRANT: not applied (why)`). A fix-check found nothing to read (an empty, reverted or base-only change) plans no fix-check. The fix-check never earns another: a blocker there - stops with `PR_ROUND_CAP` again. + stops with `PR_ROUND_CAP` again. `gstack-ship-receipt history` keeps the + grant it matched to the stop record in the git dir, and the plan's + `--stop` and finish's fix-check take a fix-check grant only when it is that + one, so a grant passed by hand without that check buys nothing. - **`--kind extra-round`, before review.** One round past the cap, with its fix round, at a head no review has stopped at: instead of the read-only review. Step 1's `PR_REVIEW_FLAGS:` adds `--round-grant ` when the grant names @@ -228,14 +232,39 @@ caught on another crew's PRs. first dispatch, which writes a grant record into the runs block; a grant another run claimed is refused (`GRANT_SPENT`), a voided run's claim still spends it, and stop and grant records are never trimmed from the block. - gstack never grants itself a round: `--by` naming gstack (any name starting - with "gstack", so a Captain called GStack Minder writes "Captain GStack - Minder") and a grant from inside an open `/ship` run are refused, and `add` - refuses the scope. `--by` is otherwise the caller's own text, recorded and - not checked: a lane that records a grant (or a ruling) from another checkout - under its Captain's name can't be told apart from the Captain doing it, so the - Captain's check of the receipt's `review_round_grants` and the PR body's lines - is the control. The receipt lists grants under `review_round_grants`. + gstack never grants itself a round: a `--by` whose first word is gstack + ("gstack", "gstack-bot", "GStack Minder"; "gstackbot" is not refused, so a + Captain called GStack Minder writes "Captain GStack Minder") and a grant from + inside an open `/ship` run are refused, and `add` refuses the scope. `--by` + is otherwise the caller's own text, recorded and not checked: a lane that + records a grant (or a ruling) from another checkout under its Captain's name + can't be told apart from the Captain doing it, so the Captain's check of the + receipt's `review_round_grants` and the PR body's lines is the control. The + receipt lists grants under `review_round_grants`. +7. **Ruled stops** (GST-2273, GST-3005). The owner can rule an open blocker of + a stop below the floor, so it ships as a listed note instead of a fix. The + ruling names one finding of the stop record item 6 describes: + `gstack-approvals rule --pr --stop-run --head + --finding --reason --words --by `, + recorded outside the run, with the same `--by` rules and risk as item 6. It + applies only in the run that stopped, at the stop's head: after the rulings, + `gstack-ship-receipt ruled-stop` lists every open finding of that stop (the + blocking findings of this run's rows at the stop's head, by ledger id, and + every blocker this run's ledgers hold that no row fixed or classified below + the floor) and prints `RULED_STOP: closed` when each one has a ruling naming + its id, that head, the PR and the run. A gate finding (a gate on its row or in + its ledger line) takes a gate disposition and never a ruling, a security-class + blocker is fixed or the PR parks, and a finding without a ledger id can't be + named; each keeps the stop open (`RULED_STOP_OPEN`), as does a head move or a + stop record of another run. On `closed`, Step 11.5 saves the stop's tree and + the receipt takes the deferral: `second_pass` after a run's second full pass, + or `read_only` after the read-only final review of a PR whose history shows + two full rounds before this run. `gstack-ship-receipt write --ruled-stop` + reruns the check, takes exactly the ruled ids as `deferred`, records the + rulings under `ruled`, and needs each `Ruled note: …` line in the body. + Rulings act only there: review-read, the loop summary and the dispatch judge + never read them, so a ruled finding stays open in the raw evidence and shows as + owner-deferred only in the receipt and the PR body. ### Transitions diff --git a/docs/ship-policy.md b/docs/ship-policy.md index aba79c3181d..ef77f1e5fb0 100644 --- a/docs/ship-policy.md +++ b/docs/ship-policy.md @@ -1699,6 +1699,10 @@ gstack-approvals rule --finding '' --head --reason '' --words '' --by '' ``` +A blocker of a recorded stop (a round-2 full pass or the read-only final review) is +ruled by its ledger id with `--pr --stop-run ` instead, and only the +ruled-stop check and the receipt apply it ([review policy](review-policy.md#rounds-per-pull-request) item 7). + The row is an approved `gstack-approvals` row with scope `ruled_note ` and ask `ruled_note at : `, with the head's full sha, so two findings ruled with the same reason in one reply get two rows, and a ruling at diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index ffb1045e9fa..980d7bd7d60 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -7484,6 +7484,31 @@ mirror. **Fix.** Pass the id `gstack-approvals round-grant` printed, from a checkout that sees that record ([troubleshooting](#pr-round-cap)). + +### `RULED_STOP_OPEN` + +**Meaning.** `gstack-ship-receipt ruled-stop` found this run's stop not closed +by owner rulings ([review policy](review-policy.md#rounds-per-pull-request) item 7). Each +`RULED_STOP_FINDING:` line names one open finding of the stop and why it is +still open: no stop ruling names it, it is a gate finding (`RULING_GATED`), it +is a security-class blocker (`RULING_SECURITY_CLASS`), or its row names no +ledger id. It is also printed when the PR body's newest stop record is another +run's or missing, when a read at the stop's head is not bound to its tree on a +clean checkout, or when HEAD moved off the stop's head. A +`RULED_STOP_RULING:` line names a ruling that matches no open finding (another +id, head, run or PR). + +**Fix.** + +1. For each finding the owner rules below the floor, the owner records, outside + this run: `gstack-approvals rule --pr --stop-run --head --finding --reason '' --words '' --by ''`. Then rerun `ruled-stop`. +2. A gate finding takes `gstack-approvals gate`; a security-class blocker is + fixed (a grant buys its fix round, item 6) or the PR parks with its owner. +3. After a head move, the rulings bind the old head: the head gets its review + the usual way. + ### `RECEIPT_PROSE_MISMATCH` diff --git a/lib/headless-artifacts.ts b/lib/headless-artifacts.ts index bd8df14b804..7e03d6af6f3 100644 --- a/lib/headless-artifacts.ts +++ b/lib/headless-artifacts.ts @@ -127,7 +127,7 @@ export interface ShipReceipt { gstack_version?: string; review_depth?: { depth: 'platform' | 'light' | 'standard' | 'full'; class: 'docs' | 'tests' | 'code' | 'gate'; runtime_lines: number; rules: string; base: string; registry: string | null; gate_scan: { tagged: number | null; head: string }; reasons: string[]; risk?: string[]; mode?: 'lean' | 'panel' | 'platform'; platform_review?: { id: string; head: string; reviewer: string }; declared?: string[]; detected?: string[] }; /** The owner's acceptance of a stop after a fix-check edit under frozen scope (#3559); the PR body repeats it word for word. */ - review_loop_exception?: { accepted_by: string; date: string; via: string; reason: string; fix_check?: { head: string; findings: number; files?: string[] }; second_pass?: { head: string; deferred: string[] } }; + review_loop_exception?: { accepted_by: string; date: string; via: string; reason: string; fix_check?: { head: string; findings: number; files?: string[] }; second_pass?: { head: string; deferred: string[] }; read_only?: { head: string; deferred: string[] }; /** The stop rulings gstack-ship-receipt write --ruled-stop verified (lib/ruled-stop.ts): the deferred ids closed by owner ruling. */ ruled?: string[] }; /** Review round grants the lane or its Captain recorded for this PR (gstack-approvals round-grant, lib/review-round-grant.ts; GST-2673): never the owner's, so never in review_loop_exception. */ review_round_grants?: Array<{ kind: 'extra-round' | 'fix-check'; head: string; pr: number; by: string; reason: string; at: string; approval: string; stop_run?: string; findings?: string[] }>; /** The owner's rulings that a finding ships as a disclosed note (gstack-approvals rule, lib/ruled-notes.ts); the PR body lists each one word for word (GST-1537). */ @@ -282,7 +282,7 @@ export const ARTIFACT_SCHEMAS = { review_depth: { type: 'object', required: ['depth', 'class', 'runtime_lines', 'rules', 'base', 'gate_scan'], properties: { depth: { enum: ['platform', 'light', 'standard', 'full'] }, mode: { enum: ['lean', 'panel', 'platform'] }, platform_review: { type: 'object', required: ['id', 'head', 'reviewer'], properties: { id: str, head: str, reviewer: str } }, class: { enum: ['docs', 'tests', 'code', 'gate'] }, runtime_lines: { type: 'integer', minimum: 0 }, rules: str, base: str, registry: nullableStr, gate_scan: { type: 'object', required: ['tagged', 'head'], properties: { tagged: { type: ['integer', 'null'], minimum: 0 }, head: str } }, reasons: strList, risk: { type: 'array', items: { enum: ['money', 'auth', 'secret', 'security', 'data', 'eval', 'policy'] } }, declared: { type: 'array', items: { enum: ['money', 'auth', 'secret', 'security', 'data', 'eval', 'policy'] } }, detected: { type: 'array', items: { enum: ['money', 'auth', 'secret', 'security', 'data', 'eval', 'policy'] } } } }, review_targeted: { type: 'object', required: ['classes', 'rules', 'brief_sha', 'product_patch_id', 'status', 'findings', 'raised_by'], properties: { classes: { type: 'array', items: { enum: ['money', 'gate', 'auth', 'secret'] } }, rules: str, brief_sha: str, product_patch_id: str, status: { enum: ['done', 'failed', 'not-run'] }, findings: { type: 'integer', minimum: 0 }, raised_by: str } }, review_exclude: { type: 'object', required: ['source', 'patterns', 'applied', 'excluded', 'excluded_bytes', 'kept', 'gate_tagged', 'patterns_sha256', 'list_sha256', 'digest'], properties: { source: str, patterns: strList, applied: strList, excluded: { type: 'integer', minimum: 0 }, excluded_bytes: { type: 'integer', minimum: 0 }, kept: { type: 'integer', minimum: 0 }, gate_tagged: strList, patterns_sha256: str, list_sha256: str, digest: str } }, - review_loop_exception: { type: 'object', required: ['accepted_by', 'date', 'via', 'reason'], properties: { accepted_by: str, date: str, via: str, reason: str, fix_check: { type: 'object', required: ['head', 'findings'], properties: { head: str, findings: { type: 'integer', minimum: 0 }, files: strList } }, second_pass: { type: 'object', required: ['head', 'deferred'], properties: { head: str, deferred: strList } } } }, + review_loop_exception: { type: 'object', required: ['accepted_by', 'date', 'via', 'reason'], properties: { accepted_by: str, date: str, via: str, reason: str, fix_check: { type: 'object', required: ['head', 'findings'], properties: { head: str, findings: { type: 'integer', minimum: 0 }, files: strList } }, second_pass: { type: 'object', required: ['head', 'deferred'], properties: { head: str, deferred: strList } }, read_only: { type: 'object', required: ['head', 'deferred'], properties: { head: str, deferred: strList } }, ruled: strList } }, review_round_grants: { type: 'array', items: { type: 'object', required: ['kind', 'head', 'pr', 'by', 'reason', 'at', 'approval'], properties: { kind: { enum: ['extra-round', 'fix-check'] }, head: str, pr: { type: 'integer', minimum: 1 }, by: str, reason: str, at: str, approval: str, stop_run: str, findings: { type: 'array', items: str } } } }, ruled_notes: { type: 'array', items: { type: 'object', required: ['finding', 'head', 'by', 'reason', 'at', 'approval'], properties: { finding: str, head: str, by: str, reason: str, at: str, approval: str } } }, gate_dispositions: { type: 'array', items: { type: 'object', required: ['finding', 'gate_id', 'head', 'by', 'reason', 'words', 'at', 'approval'], properties: { finding: str, gate_id: str, head: str, by: str, reason: str, words: str, at: str, approval: str } } }, diff --git a/lib/pr-review-history.ts b/lib/pr-review-history.ts index 6946cef623e..6104e7adf1f 100644 --- a/lib/pr-review-history.ts +++ b/lib/pr-review-history.ts @@ -39,8 +39,9 @@ function entries(body: string): ReceiptRun[] { return [...receiptRuns(body), ...(current && typeof current.head === 'string' ? [receiptRun(current)] : [])]; } -export function prReviewHistory(body: string): PrReviewHistory { - const all = entries(body).filter(e => !e.mark); +/** except: leave one run out (a read_only exception counts the PR's rounds before the run that writes it). */ +export function prReviewHistory(body: string, o: { except?: string } = {}): PrReviewHistory { + const all = entries(body).filter(e => !e.mark && (o.except === undefined || e.run !== o.except)); const reviewed = new Map(); const ordered: Array = []; all.forEach((e, i) => { diff --git a/lib/result-codes-release.ts b/lib/result-codes-release.ts index e0c2538d898..5070aab7edc 100644 --- a/lib/result-codes-release.ts +++ b/lib/result-codes-release.ts @@ -418,7 +418,7 @@ export const RELEASE_RESULT_CODES = { REVIEW_LOOP_EXCEPTION_INVALID: { anchor: 'review-loop-exception-invalid', summary: 'write --review-loop-exception got an exception that is malformed, accepts a stop the review loop does not show (a fix_check with review_loop.fix_checks 0 or missing, or a second_pass with fewer than two passes or no deferred finding), names a head that is not the receipt head or its ancestor, or is missing from the PR body', - fix: 'pass { accepted_by, date, via, reason } plus fix_check: { head, findings } or second_pass: { head, deferred: [] } with the owner’s words, the --review-loop summary that shows that stop, and the printed "Review-loop exception: …" line in the body', + fix: 'pass { accepted_by, date, via, reason } plus fix_check: { head, findings }, second_pass: { head, deferred: [] } or, with --ruled-stop, read_only: { head, deferred } with the owner’s words, the --review-loop summary that shows that stop, and the printed "Review-loop exception: …" line in the body', }, CI_CARRY_RERUN_MALFORMED: { anchor: 'ci-carry-rerun-malformed', @@ -440,6 +440,11 @@ export const RELEASE_RESULT_CODES = { summary: 'gstack-ship-receipt stop found no review of this run bound to one committed tree, so it recorded no stop record', fix: 'nothing for a grant to answer: the lane or its Captain ships with the open notes listed or parks; a fresh /ship run gives the head its review', }, + RULED_STOP_OPEN: { + anchor: 'ruled-stop-open', + summary: 'gstack-ship-receipt ruled-stop found this run\'s stop not closed by owner rulings: a finding has no stop ruling, is a gate or security-class finding, the stop is unbound or another run\'s, or HEAD moved off the stop\'s head', + fix: 'the owner rules each open finding it lists with gstack-approvals rule --pr --stop-run --head --finding, outside this run; a gate finding takes gstack-approvals gate and a security-class blocker is fixed or parks; otherwise ship the stop the usual way', + }, GRANT_SPENT: { anchor: 'grant-spent', summary: 'another /ship run already claimed this round grant, and a grant buys one round', diff --git a/lib/review-round-grant.ts b/lib/review-round-grant.ts index afd052d0f6e..faf02e41899 100644 --- a/lib/review-round-grant.ts +++ b/lib/review-round-grant.ts @@ -8,6 +8,8 @@ * --by is recorded, not enforced. */ 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 { GSTACK_ACTOR } from './ruled-notes'; @@ -38,6 +40,23 @@ export function reviewRoundGrants(rows: readonly ApprovalRow[]): ReviewRoundGran return out; } +/** + * The stop a fix-check grant answered when gstack-ship-receipt history last checked it against the PR body's stop record, kept in + * the git dir: the planner's --stop and finish's fix-check link take a fix-check grant only when it is this one, so a grant passed + * by hand without history's check (another stop run, other findings) buys nothing. + */ +export interface GrantedStopStamp { pr: number; grant: string; head: string; run: string; findings: string[] } +const stampPath = (cwd: string) => { const p = spawnSync('git', ['rev-parse', '--git-path', 'gstack-granted-stop'], { cwd, encoding: 'utf8', timeout: 10_000 }); return p.status === 0 && p.stdout.trim() ? path.resolve(cwd, p.stdout.trim()) : undefined; }; +export function writeGrantedStop(cwd: string, stamp: GrantedStopStamp | null): void { + const p = stampPath(cwd); + if (!p) return; + if (stamp) fs.writeFileSync(p, JSON.stringify(stamp) + '\n'); else fs.rmSync(p, { force: true }); +} +export function readGrantedStop(cwd: string): GrantedStopStamp | undefined { + const p = stampPath(cwd); + try { const v = JSON.parse(fs.readFileSync(p!, 'utf8')); return v && typeof v.grant === 'string' && typeof v.head === 'string' ? v : undefined; } catch { return undefined; } +} + export function readReviewRoundGrants(cwd: string, env: Env = process.env): ReviewRoundGrant[] { const loc = locate({ cwd, env }); return 'code' in loc ? [] : reviewRoundGrants(readRecord(loc).rows); diff --git a/lib/ruled-notes.ts b/lib/ruled-notes.ts index 4b24e9c41b5..f4d7cd900dc 100644 --- a/lib/ruled-notes.ts +++ b/lib/ruled-notes.ts @@ -33,6 +33,32 @@ export function ruledNotes(rows: readonly ApprovalRow[]): RuledNote[] { return [...byFinding.values()]; } +/** + * A stop ruling (GST-2273, GST-3005): the owner's ruling that one open finding of one recorded stop ships as a disclosed note. It + * names the finding by its run-unique ledger id, the stop's head, the PR and the run that stopped (the stop record + * gstack-ship-receipt stop wrote), so it closes that finding of that stop and nothing else. lib/ruled-stop.ts applies it; + * review-read, the loop summary and the dispatch judge never read it. + */ +export interface StopRuling extends RuledNote { pr: number; stop_run: string } + +const STOP_SCOPE = /^ruled_note (\S+) ([0-9a-f]{40}) pr=([1-9]\d*) stop=([\w.:-]{1,120})$/; + +export const stopRulingRow = (finding: string, head: string, pr: number, run: string, reason: string) => + ({ scope: `ruled_note ${finding} ${head} pr=${pr} stop=${run}`, ask: `ruled_note ${finding} at ${head}: ${reason}` }); + +/** The approved stop rulings, one per finding, head, PR and stop run (the newest wins). */ +export function stopRulings(rows: readonly ApprovalRow[]): StopRuling[] { + const byKey = new Map(); + for (const r of rows) { + const scope = STOP_SCOPE.exec(r.scope), ask = ASK.exec(r.ask); + if (r.outcome !== 'approved' || !scope || !ask || ask[1] !== scope[1] || ask[2] !== scope[2] || GSTACK_ACTOR.test(r.by)) continue; + const key = scope.slice(1, 5).join(' '); + byKey.delete(key); + byKey.set(key, { finding: scope[1]!, head: scope[2]!, pr: Number(scope[3]), stop_run: scope[4]!, by: r.by, reason: ask[3]!, at: r.recorded_at, approval: r.id }); + } + return [...byKey.values()]; +} + /** The rulings in the checked-out branch's approval record (and its mirror). */ export function readRuledNotes(cwd: string, env: Env = process.env): RuledNote[] { const loc = locate({ cwd, env }); diff --git a/lib/ruled-stop.ts b/lib/ruled-stop.ts new file mode 100644 index 00000000000..70353c042b7 --- /dev/null +++ b/lib/ruled-stop.ts @@ -0,0 +1,119 @@ +/** + * The ruled-stop check (GST-2273, GST-3005, docs/review-policy.md item 7): whether the owner ruled every open finding of the stop + * this /ship run recorded, so the run may ship them as disclosed notes. The stop is the newest stop record in the PR body + * (gstack-ship-receipt stop, lib/pr-review-history.ts stopFrom: a review bound to one committed tree). Its open findings are the + * blocking findings of this run's review rows at that head, each named by its run-unique ledger id, plus every blocker this + * run's dispatch ledgers hold that no row fixed or classified below the floor. A finding closes only by a stop ruling naming its + * id, that head, the PR and this run (lib/ruled-notes.ts stopRulings); a gate finding (a gate on its row or in its ledger line) + * and a security-class blocker never close this way. Review-read, the loop summary and the dispatch judge never read rulings, so a + * ruled finding stays open in the raw evidence and shows as owner-deferred only in the receipt and the PR body. + */ +import * as fs from 'node:fs'; +import { rank, readLedger, type MergedLine } from './review-ledger'; +import type { StopRuling } from './ruled-notes'; + +export interface LedgerTrait { key: string; reader: string; gate?: string; category?: string } +export interface OpenFinding { id: string; why: 'ruled' | 'open' | 'gated' | 'security' | 'unnamed'; ruling?: StopRuling } +export interface RuledStop { + state: 'closed' | 'open' | 'none' | 'unbound'; + why?: string; + stop?: { head: string; tree: string; run: string }; + findings: OpenFinding[]; + /** Rulings for this PR that name no open finding of this stop (another id, head or run). */ + unmatched: StopRuling[]; +} + +const SECURITY = /^(security|auth|secrets?|privacy|data[-_ ]?loss)$/i; +const FIXED = new Set(['fixed', 'auto-fixed']); +const bound = (r: Record, tree: string) => { + const b = r.review_binding; + return r.completed === true && r.dirty !== true && r.tree === tree && !!b && (b.state === 'verified' || b.state === 'incomplete') && b.start_wtree === tree && b.end_wtree === tree && (r.wtree === undefined || r.wtree === tree); +}; +const blocks = (f: Record) => (typeof f.blocking === 'boolean' ? f.blocking : rank(f.severity) === 4); +const gateOf = (texts: readonly string[]) => { + for (const t of texts) { try { const o = JSON.parse(t); if (o && typeof o.gate === 'string' && o.gate) return o.gate as string; } catch { /* a prose finding */ } } + return texts.map(t => /\bRH-\d+\b/.exec(t)?.[0]).find(Boolean); +}; + +/** Each collected finding's reader, and the gate and category its merged line or judged reason names, keyed /. */ +export function ledgerTraits(ledger: string, keyOf: (id: string) => string): LedgerTrait[] { + const events = readLedger(ledger); + const reasons = new Map(); + const judge = [...events].reverse().find(e => e.event === 'judge' && e.ok === true); + if (judge && typeof judge.judged === 'string' && fs.existsSync(judge.judged)) { + for (const l of fs.readFileSync(judge.judged, 'utf8').split('\n')) { try { const j = JSON.parse(l); if (typeof j?.id === 'string' && typeof j.reason === 'string') reasons.set(j.id, j.reason); } catch { /* not a judged line */ } } + } + const out = new Map(); + for (const o of events.filter(e => e.event === 'output' && Array.isArray(e.ids) && typeof e.merged === 'string')) { + const lines = fs.readFileSync(String(o.merged), 'utf8').split('\n').flatMap(l => { try { return [JSON.parse(l) as MergedLine]; } catch { return []; } }); + for (const id of o.ids as string[]) { + const line = lines.find(l => l.id === id); + const raw = line?.raw ?? ''; + let category: string | undefined; + try { const j = JSON.parse(raw); category = typeof j?.category === 'string' ? j.category : typeof j?.specialist === 'string' ? j.specialist : undefined; } catch { /* prose */ } + const gate = gateOf([raw, reasons.get(id) ?? '']); + out.set(keyOf(id), { key: keyOf(id), reader: String(o.reader), ...(gate ? { gate } : {}), ...(category ? { category } : {}) }); + } + } + return [...out.values()]; +} + +/** + * The check itself. rows: this run's via:ship review-log rows (oldest first); blockers: the keys of the blockers this run's ledgers + * hold (lib/review-ledger.ts ledgerBlockers); traits: ledgerTraits for every collected finding; rulings: the approved stop rulings. + */ +export function ruledStop(o: { pr: number; run: string; stop?: { head: string; tree?: string; run: string }; rows: readonly Record[]; blockers: readonly string[]; traits: readonly LedgerTrait[]; rulings: readonly StopRuling[] }): RuledStop { + const mine = o.rulings.filter(r => r.pr === o.pr); + const unbound = (why: string): RuledStop => ({ state: 'unbound', why, findings: [], unmatched: mine }); + const s = o.stop; + if (!s || !s.tree) return unbound('the PR body holds no stop record; gstack-ship-receipt stop records the stop this run is answering'); + if (s.run !== o.run) return unbound(`the newest stop record is run ${s.run}'s, not this run's (${o.run}): a ruling closes a finding only in the run that stopped on it`); + const atStop = o.rows.filter(r => (r.skill === 'review' || r.skill === 'adversarial-review') && String(r.commit_full ?? '').toLowerCase() === s.head); + if (!atStop.some(r => r.skill === 'review')) return unbound(`no review row of this run at the stop head ${s.head.slice(0, 12)}`); + const loose = atStop.find(r => !bound(r, s.tree!)); + if (loose) return unbound(`the ${loose.skill} row at ${s.head.slice(0, 12)} is not bound to the stop's tree on a clean worktree (binding ${loose.review_binding?.state ?? 'missing'}): a ruling closes only a finding read on that commit`); + const traits = new Map(o.traits.map(t => [t.key, t])); + const settled = new Set(o.rows.flatMap(r => (Array.isArray(r.findings) ? r.findings : []).filter((f: any) => f && typeof f.ledger_id === 'string' && (FIXED.has(f.action) || f.blocking === false)).map((f: any) => f.ledger_id as string))); + const open = new Map(); + for (const r of atStop) for (const f of (Array.isArray(r.findings) ? r.findings : []) as Record[]) { + if (!f || typeof f !== 'object' || !blocks(f) || FIXED.has(f.action)) continue; + const id = typeof f.ledger_id === 'string' && f.ledger_id ? f.ledger_id : `${String(f.fingerprint ?? '?')} (no ledger id)`; + const t = traits.get(id); + open.set(id, { gate: !!f.gate || !!f.gate_id || !!t?.gate, security: [f.category, f.raised_by, t?.category].some(c => typeof c === 'string' && SECURITY.test(c)), named: typeof f.ledger_id === 'string' && !!f.ledger_id }); + } + for (const key of o.blockers) { + if (settled.has(key) || open.has(key)) continue; + const t = traits.get(key); + open.set(key, { gate: !!t?.gate, security: [t?.category, t?.reader].some(c => typeof c === 'string' && SECURITY.test(c)), named: true }); + } + const findings: OpenFinding[] = [...open].sort(([a], [b]) => a.localeCompare(b)).map(([id, f]) => { + const ruling = [...mine].reverse().find(r => r.finding === id && r.head === s.head && r.stop_run === s.run); + const why = !f.named ? 'unnamed' : f.gate ? 'gated' : f.security ? 'security' : ruling ? 'ruled' : 'open'; + return { id, why, ...(ruling && why === 'ruled' ? { ruling } : {}) }; + }); + const used = new Set(findings.flatMap(f => (f.ruling ? [f.ruling.approval] : []))); + const unmatched = mine.filter(r => !used.has(r.approval)); + const stop = { head: s.head, tree: s.tree, run: s.run }; + if (!findings.length) return { state: 'none', why: 'the stop holds no open finding to rule', stop, findings, unmatched }; + return { state: findings.every(f => f.why === 'ruled') ? 'closed' : 'open', stop, findings, unmatched }; +} + +const LABEL: Record = { + ruled: 'ruled', + open: 'open: no stop ruling names it', + gated: 'RULING_GATED: a gate finding takes a gate disposition (gstack-approvals gate), never a ruling', + security: 'RULING_SECURITY_CLASS: a security-class blocker is fixed, or the PR parks with its owner', + unnamed: 'open: the row names no ledger id, so no ruling can name it', +}; + +/** The lines gstack-ship-receipt ruled-stop prints, the RULED_STOP: line last. */ +export function ruledStopLines(r: RuledStop, pr: number): string[] { + const lines = r.findings.map(f => `RULED_STOP_FINDING: ${f.id} ${LABEL[f.why]}${f.ruling ? ` by ${f.ruling.by} (approval ${f.ruling.approval})` : ''}`); + for (const u of r.unmatched) lines.push(`RULED_STOP_RULING: ${u.finding} at ${u.head.slice(0, 12)} run ${u.stop_run} (approval ${u.approval}): not applied, it names no open finding of this stop`); + const open = r.findings.filter(f => f.why !== 'ruled').length; + const s = r.stop; + lines.push(r.state === 'closed' ? `RULED_STOP: closed run=${s!.run} head=${s!.head} tree=${s!.tree} ids=${r.findings.map(f => f.id).join(',')}` + : r.state === 'open' ? `RULED_STOP: open ${open} of ${r.findings.length} at ${s!.head.slice(0, 12)}: the owner rules each open one with gstack-approvals rule --pr ${pr} --stop-run ${s!.run} --head ${s!.head} --finding --reason '' --words '' --by '', outside this run` + : `RULED_STOP: ${r.state} (${r.why})`); + return lines; +} diff --git a/lib/ship-receipt-depth.ts b/lib/ship-receipt-depth.ts index 58190ae6926..3e606a658bf 100644 --- a/lib/ship-receipt-depth.ts +++ b/lib/ship-receipt-depth.ts @@ -154,25 +154,28 @@ export const deeper = (a: D, b: D): D => (RANK[a] /** * `write --review-loop-exception` input and the queue's check: who accepted the stop, when, where, why, and the stop it accepts: - * the fix-check it followed (`fix_check`), or the second full pass that left a finding open (`second_pass`, the deferred - * finding ids; TRUT-7). + * the fix-check it followed (`fix_check`), the second full pass that left a finding open (`second_pass`, the deferred + * finding ids; TRUT-7), or the read-only final review of a PR past its two rounds whose open findings the owner ruled + * (`read_only`, GST-3005). `ruled` lists the stop rulings write --ruled-stop verified for the deferred ids (GST-2273). */ export function parseReviewLoopException(value: unknown): { ok: true; exception: ReviewLoopException } | { ok: false; message: string } { const bad = (message: string) => ({ ok: false as const, message }); - if (!value || typeof value !== 'object' || Array.isArray(value)) return bad('review_loop_exception must be { accepted_by, date, via, reason, fix_check: { head, findings[, files] } | second_pass: { head, deferred: [] } }'); + if (!value || typeof value !== 'object' || Array.isArray(value)) return bad('review_loop_exception must be { accepted_by, date, via, reason, fix_check: { head, findings[, files] } | second_pass: { head, deferred: [] } | read_only: { head, deferred: [] } }'); const v = value as Record; - for (const key of Object.keys(v)) if (!['accepted_by', 'date', 'via', 'reason', 'fix_check', 'second_pass'].includes(key)) return bad(`review_loop_exception: unknown key ${JSON.stringify(key)}`); + for (const key of Object.keys(v)) if (!['accepted_by', 'date', 'via', 'reason', 'fix_check', 'second_pass', 'read_only', 'ruled'].includes(key)) return bad(`review_loop_exception: unknown key ${JSON.stringify(key)}`); for (const key of ['accepted_by', 'date', 'via', 'reason']) if (!text(v[key])) return bad(`review_loop_exception.${key} must be a non-empty one-line string`); if (!/^\d{4}-\d{2}-\d{2}$/.test(v.date as string)) return bad('review_loop_exception.date must be YYYY-MM-DD'); - if ((v.fix_check === undefined) === (v.second_pass === undefined)) return bad('review_loop_exception names exactly one of fix_check or second_pass: the stop it accepts'); - const accepted = { accepted_by: (v.accepted_by as string).trim(), date: v.date as string, via: (v.via as string).trim(), reason: (v.reason as string).trim() }; - if (v.second_pass !== undefined) { - const s = v.second_pass as Record | null; - if (!s || typeof s !== 'object' || Array.isArray(s)) return bad('review_loop_exception.second_pass must be { head, deferred: [] }'); - for (const key of Object.keys(s)) if (!['head', 'deferred'].includes(key)) return bad(`review_loop_exception.second_pass: unknown key ${JSON.stringify(key)}`); - if (!sha(s.head)) return bad('review_loop_exception.second_pass.head must be the full commit the second full pass reviewed'); - if (!Array.isArray(s.deferred) || !s.deferred.length || !s.deferred.every(text)) return bad('review_loop_exception.second_pass.deferred must name the open finding the owner accepted by id'); - return { ok: true, exception: { ...accepted, second_pass: { head: s.head, deferred: (s.deferred as string[]).slice(0, 20).map(d => d.trim()) } } }; + if ([v.fix_check, v.second_pass, v.read_only].filter(x => x !== undefined).length !== 1) return bad('review_loop_exception names exactly one of fix_check or second_pass (or read_only): the stop it accepts'); + if (v.ruled !== undefined && (!Array.isArray(v.ruled) || !v.ruled.length || !v.ruled.every(text) || v.fix_check !== undefined)) return bad('review_loop_exception.ruled lists the stop rulings (approval ids) of a second_pass or read_only stop'); + const accepted = { accepted_by: (v.accepted_by as string).trim(), date: v.date as string, via: (v.via as string).trim(), reason: (v.reason as string).trim(), ...(v.ruled ? { ruled: (v.ruled as string[]).slice(0, 20).map(d => d.trim()) } : {}) }; + const stopKey = v.second_pass !== undefined ? 'second_pass' : v.read_only !== undefined ? 'read_only' : undefined; + if (stopKey) { + const s = v[stopKey] as Record | null; + if (!s || typeof s !== 'object' || Array.isArray(s)) return bad(`review_loop_exception.${stopKey} must be { head, deferred: [] }`); + for (const key of Object.keys(s)) if (!['head', 'deferred'].includes(key)) return bad(`review_loop_exception.${stopKey}: unknown key ${JSON.stringify(key)}`); + if (!sha(s.head)) return bad(`review_loop_exception.${stopKey}.head must be the full commit the ${stopKey === 'read_only' ? 'read-only final review' : 'second full pass'} reviewed`); + if (!Array.isArray(s.deferred) || !s.deferred.length || !s.deferred.every(text)) return bad(`review_loop_exception.${stopKey}.deferred must name the open finding the owner accepted by id`); + return { ok: true, exception: { ...accepted, [stopKey]: { head: s.head, deferred: (s.deferred as string[]).slice(0, 20).map(d => d.trim()) } } }; } const f = v.fix_check as Record | null; if (!f || typeof f !== 'object' || Array.isArray(f)) return bad('review_loop_exception.fix_check must be { head, findings[, files] }'); @@ -185,17 +188,18 @@ export function parseReviewLoopException(value: unknown): { ok: true; exception: } /** The commit the accepted stop reviewed: the fix-check's head or the second full pass's. */ -export const exceptionHead = (e: ReviewLoopException) => (e.fix_check ?? e.second_pass)!.head; +export const exceptionHead = (e: ReviewLoopException) => (e.fix_check ?? e.second_pass ?? e.read_only)!.head; /** Whether the review loop shows the stop the exception accepts: a fix-check ran, or two full passes left a finding deferred. */ export function exceptionLoopProblem(e: ReviewLoopException, loop: ShipReceipt['review_loop']): string | null { if (e.fix_check) return loop?.fix_checks ? null : 'needs --review-loop with fix_checks >= 1: the stop it accepts follows a fix-check'; - return (loop?.passes ?? 0) >= 2 && (loop?.deferred ?? 0) >= 1 ? null : 'second_pass needs --review-loop with passes >= 2 and deferred >= 1: the stop it accepts follows the second full pass with a finding left open'; + if (e.read_only) return !e.ruled ? 'read_only needs ruled: the owner rules each open finding of the read-only final review, and write --ruled-stop records the rulings' : (loop?.passes ?? 0) >= 1 ? null : 'read_only needs --review-loop with passes >= 1: the stop it accepts follows the read-only final review'; + return (loop?.passes ?? 0) >= 2 && (e.ruled || (loop?.deferred ?? 0) >= 1) ? null : 'second_pass needs --review-loop with passes >= 2 and deferred >= 1: the stop it accepts follows the second full pass with a finding left open'; } /** The line the PR body must carry, word for word, while the exception stands. */ export function reviewLoopExceptionLine(e: ReviewLoopException): string { - const stop = e.fix_check ? `fix-check at ${e.fix_check.head.slice(0, 12)}, ${e.fix_check.findings} finding${e.fix_check.findings === 1 ? '' : 's'}` : `second full pass at ${e.second_pass!.head.slice(0, 12)}, deferred ${e.second_pass!.deferred.join(', ')}`; + const stop = e.fix_check ? `fix-check at ${e.fix_check.head.slice(0, 12)}, ${e.fix_check.findings} finding${e.fix_check.findings === 1 ? '' : 's'}` : e.read_only ? `read-only final review at ${e.read_only.head.slice(0, 12)}, deferred ${e.read_only.deferred.join(', ')}` : `second full pass at ${e.second_pass!.head.slice(0, 12)}, deferred ${e.second_pass!.deferred.join(', ')}`; return `Review-loop exception: accepted by ${e.accepted_by} ${e.date} via ${e.via}: ${e.reason} (${stop})`; } diff --git a/lib/ship-release.ts b/lib/ship-release.ts index 8de60aa8f1b..4e83cb5cd87 100644 --- a/lib/ship-release.ts +++ b/lib/ship-release.ts @@ -26,7 +26,7 @@ import { isCriticalFinding, isOpenByAction } from './headless-artifacts'; import { fingerprintPath, normalizePath } from './review-scope'; import { forbidSpecs } from './review-fetch'; import { readRuledNotes, ruledNoteText } from './ruled-notes'; -import { reviewRoundGrants } from './review-round-grant'; +import { readGrantedStop, reviewRoundGrants } from './review-round-grant'; import { dispositionedOn, gateDispositionText, gateKey, readGateDispositions } from './gate-dispositions'; import { parseReviewLoopException, type ReviewLoopException } from './ship-receipt-depth'; import { parseReceiptDocs, type ReceiptDocs } from './ship-receipt-docs'; @@ -319,10 +319,11 @@ function fixChecked(cwd: string, o: BridgeOpts & { now: string; parent?: string; const grants = chain.length ? (loc => 'file' in loc ? readRecord(loc).rows : [])(locate({ cwd, env: process.env })).filter(g => g.outcome === 'approved' && (`${g.ask} ${g.scope}`.includes('review_loop_grant') || reviewRoundGrants([g]).some(x => x.kind === 'fix-check'))) : []; const granted: (typeof grants[number] | undefined)[] = []; const used = new Set(); + const stamp = readGrantedStop(cwd); for (let k = chain.length - 1; k >= 0; k--) { const l = chain[k]!; const g = 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'); return (fc ? (commitOf(fc.head) === l.from && stamp?.grant === fc.approval && stamp.head === fc.head ? [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; diff --git a/scripts/lib/windows-curation.ts b/scripts/lib/windows-curation.ts index 8b2198d8a64..426a973f068 100644 --- a/scripts/lib/windows-curation.ts +++ b/scripts/lib/windows-curation.ts @@ -452,6 +452,10 @@ export const KNOWN_WINDOWS_INCOMPATIBLE: Array<{ file: string; reason: string }> file: 'test/round-cap-granted-stop.test.ts', reason: 'drives bin/gstack-ship-receipt, gstack-approvals, gstack-review-plan, gstack-review-log, gstack-review-scope and gstack-ship-release (shebangs) through test/helpers/ship-bin-fixture.ts like test/ship-finish-fixed-links.test.ts; a bin spawn fails on windows-latest the same way (first-bin-spawn failure class of test/ship-uid-sidecar.test.ts)', }, + { + file: 'test/ruled-stop.test.ts', + reason: 'drives bin/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)', + }, { file: 'test/ship-uid-sidecar.test.ts', reason: 'drives bin/gstack-ship-release, gstack-ship-receipt, gstack-docs-candidate and gstack-wtree (shebangs) through test/helpers/ship-bin-fixture.ts like test/ship-mechanical-retake.test.ts; windows-latest fails every case at the first bin spawn (windows-scoped-shard, run 42205201312)', diff --git a/ship/sections/pr-body.md b/ship/sections/pr-body.md index 87bf1c6af1a..e2b8a8234d8 100644 --- a/ship/sections/pr-body.md +++ b/ship/sections/pr-body.md @@ -254,7 +254,8 @@ NS=$(~/.claude/skills/gstack/bin/gstack-no-stop list | sed -n 's/^NO_STOP_FILE: ~/.claude/skills/gstack/bin/gstack-ship-receipt write --pr --run --base --gate @.gstack/tmp/ship-gate.json --pregate .gstack/tmp/pregate.json --issues @.gstack/tmp/issues.json --review-loop @.gstack/tmp/review-loop.json --docs @.gstack/tmp/docs-audit.json $([ -s .gstack/tmp/targeted.json ] && echo --review-targeted @.gstack/tmp/targeted.json) ${NS:+--no-stop "@$NS"} --body "$PR_BODY_FILE" ``` -If write refuses `review_targeted` for a docs claim added after the read, or after a granted fix round (add its `--grant`), rerun Step 9's plan with `--range-base +After a ruled stop (`RULED_STOP: closed`), write adds `--review-loop-exception @ --ruled-stop --since "$REVIEW_SINCE" --dir ` and the body +carries each `Ruled note: …` line. If write refuses `review_targeted` for a docs claim added after the read, or after a granted fix round (add its `--grant`), rerun Step 9's plan with `--range-base --targeted-ran `; on `NEXT: targeted`, run that one reader (`pass`, its voices stage, `verify --targeted-out .gstack/tmp/targeted.json`) and write again. A Step 5 red-base pause adds `--base-red ` (a conditional receipt the queue diff --git a/ship/sections/pr-body.md.tmpl b/ship/sections/pr-body.md.tmpl index c0bfb63ad70..4560a947334 100644 --- a/ship/sections/pr-body.md.tmpl +++ b/ship/sections/pr-body.md.tmpl @@ -237,7 +237,8 @@ NS=$(~/.claude/skills/gstack/bin/gstack-no-stop list | sed -n 's/^NO_STOP_FILE: ~/.claude/skills/gstack/bin/gstack-ship-receipt write --pr --run --base --gate @.gstack/tmp/ship-gate.json --pregate .gstack/tmp/pregate.json --issues @.gstack/tmp/issues.json --review-loop @.gstack/tmp/review-loop.json --docs @.gstack/tmp/docs-audit.json $([ -s .gstack/tmp/targeted.json ] && echo --review-targeted @.gstack/tmp/targeted.json) ${NS:+--no-stop "@$NS"} --body "$PR_BODY_FILE" ``` -If write refuses `review_targeted` for a docs claim added after the read, or after a granted fix round (add its `--grant`), rerun Step 9's plan with `--range-base +After a ruled stop (`RULED_STOP: closed`), write adds `--review-loop-exception @ --ruled-stop --since "$REVIEW_SINCE" --dir ` and the body +carries each `Ruled note: …` line. If write refuses `review_targeted` for a docs claim added after the read, or after a granted fix round (add its `--grant`), rerun Step 9's plan with `--range-base --targeted-ran `; on `NEXT: targeted`, run that one reader (`pass`, its voices stage, `verify --targeted-out .gstack/tmp/targeted.json`) and write again. A Step 5 red-base pause adds `--base-red ` (a conditional receipt the queue diff --git a/ship/sections/review-army.md b/ship/sections/review-army.md index 082eab2ef40..5443d661cc1 100644 --- a/ship/sections/review-army.md +++ b/ship/sections/review-army.md @@ -830,6 +830,10 @@ After persistence, record missing output, CYCLES and fixes in the invocation rec `gstack-review-scope summary --since "$REVIEW_SINCE" --no-ledger --out .gstack/tmp/review-loop.json && gstack-ship-receipt stub --pr --run --review-loop @.gstack/tmp/review-loop.json` so a run that stops still counts its rounds (Step 19's write, same `--run`, replaces it). On `NEXT: stop` with a PR open, also run `gstack-ship-receipt stop --pr --run --since "$REVIEW_SINCE"` and report its `NEXT:` line with the stop. +When the owner rules that stop's open findings below the floor instead (docs/review-policy.md#rounds-per-pull-request item 7), this run +runs `gstack-ship-receipt ruled-stop --pr --run --since "$REVIEW_SINCE" --dir `; on `RULED_STOP: closed` it +continues at Step 11.5 with the stop's tree, its body carries each `RULED_NOTE:` line as `Ruled note: …`, and Step 19's write adds +`--review-loop-exception` (`second_pass`, or `read_only` after a read-only final review) with `--ruled-stop --since "$REVIEW_SINCE" --dir `. Decision 1 always applies first. Then, under `frozen`, run `gstack-review-plan --base --pass $PASS --last full` with each flag that holds (`--fixed-blocking`, `--fixed-below`, `--blocking-open`, `--touched-gate` for a fix to an item 2.5 path, `--critical-found` when this pass diff --git a/ship/sections/review-army.md.tmpl b/ship/sections/review-army.md.tmpl index 686aa5151de..80280ea577e 100644 --- a/ship/sections/review-army.md.tmpl +++ b/ship/sections/review-army.md.tmpl @@ -240,6 +240,10 @@ After persistence, record missing output, CYCLES and fixes in the invocation rec `gstack-review-scope summary --since "$REVIEW_SINCE" --no-ledger --out .gstack/tmp/review-loop.json && gstack-ship-receipt stub --pr --run --review-loop @.gstack/tmp/review-loop.json` so a run that stops still counts its rounds (Step 19's write, same `--run`, replaces it). On `NEXT: stop` with a PR open, also run `gstack-ship-receipt stop --pr --run --since "$REVIEW_SINCE"` and report its `NEXT:` line with the stop. +When the owner rules that stop's open findings below the floor instead (docs/review-policy.md#rounds-per-pull-request item 7), this run +runs `gstack-ship-receipt ruled-stop --pr --run --since "$REVIEW_SINCE" --dir `; on `RULED_STOP: closed` it +continues at Step 11.5 with the stop's tree, its body carries each `RULED_NOTE:` line as `Ruled note: …`, and Step 19's write adds +`--review-loop-exception` (`second_pass`, or `read_only` after a read-only final review) with `--ruled-stop --since "$REVIEW_SINCE" --dir `. Decision 1 always applies first. Then, under `frozen`, run `gstack-review-plan --base --pass $PASS --last full` with each flag that holds (`--fixed-blocking`, `--fixed-below`, `--blocking-open`, `--touched-gate` for a fix to an item 2.5 path, `--critical-found` when this pass diff --git a/test/fixtures/review-pins/files/ship/sections/review-army.md.json b/test/fixtures/review-pins/files/ship/sections/review-army.md.json index bf41f60130c..c636f0761e0 100644 --- a/test/fixtures/review-pins/files/ship/sections/review-army.md.json +++ b/test/fixtures/review-pins/files/ship/sections/review-army.md.json @@ -1 +1 @@ -{"sha":"3bbbd295c2301c35c253d0ad8a151dad09d731b94019a306a298226bae985fca","replay":"GST-2968"} +{"sha":"d7ff3455fe27e6cd9051651d7ef9e73907732f0261f3c5b4ab761b7238401698","replay":"GST-2273"} diff --git a/test/fixtures/review-pins/replays/GST-2273.json b/test/fixtures/review-pins/replays/GST-2273.json new file mode 100644 index 00000000000..5520d2d1252 --- /dev/null +++ b/test/fixtures/review-pins/replays/GST-2273.json @@ -0,0 +1 @@ +{"replay":"GST-2273","justification":"GST-2273 and GST-3005 (GSTA-608 PR 2): owner stop rulings, gstack-ship-receipt ruled-stop, and the receipt's read_only and ruled second_pass exceptions. No reader, depth, dispatch, brief, checklist or finding rule changes. Deterministic no-loss replay, preregistered before the run (captain drive handoffs/GSTA-608/no-loss-replay-pr2-prereg.md), no paid run: lib/review-depth.ts is byte-identical to main f87d4325, and nextStep over the same 9,830,400 History x depth cases as GST-2968 gives 0 changed steps and 0 changed reasons (step-sequence sha256 63e41d14897294d0647a13690cabeaa5f11f17657ef4b2c181c7a041b3dbc515 on both). ship/sections/review-army.md changes only Step 9's /ship bookkeeping prose after a stop (run gstack-ship-receipt ruled-stop once the owner rules the stop, then continue at Step 11.5 and write the ruled deferral), which no reviewer reads. Every brief body lib/review-brief.ts cuts from the ship sections keeps its pinned hash (test/fixtures/review-pins/brief-bodies unchanged). Under CREW rule 15 such non-reviewer /ship prose is out of the replay's scope."} diff --git a/test/round-cap-granted-stop.test.ts b/test/round-cap-granted-stop.test.ts index c7d52445d84..6a200d89c1e 100644 --- a/test/round-cap-granted-stop.test.ts +++ b/test/round-cap-granted-stop.test.ts @@ -13,7 +13,7 @@ import * as path from 'node:path'; import type { ApprovalRow } from '../lib/approval-record'; import { grantedStop, grantMarker, placeRunEntry, prReviewHistory, runStub, stopFrom, stopMarker } from '../lib/pr-review-history'; import { nextStep } from '../lib/review-depth'; -import { reviewRoundGrantRow, reviewRoundGrants } from '../lib/review-round-grant'; +import { reviewRoundGrantRow, reviewRoundGrants, writeGrantedStop } from '../lib/review-round-grant'; import { receiptRuns } from '../lib/ship-receipt'; import { RELEASE, shipFixture, type ShipFx } from './helpers/ship-bin-fixture'; @@ -197,6 +197,7 @@ describe('the CLI seams', () => { const r = stopRepo(); const s = r.head(); const g = grantId(r.run('gstack-approvals', ['round-grant', '--pr', '7', '--head', s, '--kind', 'fix-check', '--stop-run', 'ro', '--findings', 'f#1', '--reason', 'x', '--by', 'Captain GStack Minder']).stdout)!; + writeGrantedStop(r.f.work, { pr: 7, grant: g, head: s, run: 'ro', findings: ['f#1'] }); const plan = (extra: string[]) => r.run('gstack-review-plan', ['--base', 'main', '--gate-tagged', '0', '--prior-rounds', '3', '--prior-full', '3', '--pr', '7', '--round-grant', g, ...extra]); expect(plan(['--stop', s]).stdout).toContain('next=stop'); expect(plan([]).status).toBe(3); @@ -206,6 +207,22 @@ describe('the CLI seams', () => { expect(r.run('gstack-review-plan', ['--base', 'main', '--gate-tagged', '0', '--prior-full', '3', '--pr', '7', '--round-grant', x, '--stop', s]).status).toBe(3); }); + // Value: protects=a fix-check grant passed to the planner by hand buys nothing until history matched it to the PR's newest stop + // record (the #4479 trail read's flag); fails_when=the planner checks only the grant row's head and PR; seam=gstack-review-plan + test('the plan takes a fix-check grant only after history matched it to the stop record on this checkout', () => { + const r = stopRepo(); + const s = r.head(); + const g = grantId(r.run('gstack-approvals', ['round-grant', '--pr', '7', '--head', s, '--kind', 'fix-check', '--stop-run', 'ro', '--findings', 'f#1', '--reason', 'x', '--by', 'Captain GStack Minder']).stdout)!; + const plan = () => r.run('gstack-review-plan', ['--base', 'main', '--gate-tagged', '0', '--prior-rounds', '3', '--prior-full', '3', '--pr', '7', '--round-grant', g, '--stop', s]); + const bare = plan(); + expect(bare.status).toBe(3); + expect(bare.stderr).toContain('gstack-ship-receipt history'); + writeGrantedStop(r.f.work, { pr: 7, grant: 'a-000000000009', head: s, run: 'ro', findings: ['f#1'] }); + expect(plan().status).toBe(3); + writeGrantedStop(r.f.work, { pr: 7, grant: g, head: s, run: 'ro', findings: ['f#1'] }); + expect(plan().status).toBe(0); + }); + test('S1: stop records nothing for an unbound read (STOP_UNBOUND)', () => { const r = stopRepo(); const out = r.run('gstack-ship-receipt', ['stop', '--body', r.body, '--pr', '7', '--run', 'ro', '--since', '2000-01-01T00:00:00Z']); @@ -237,6 +254,7 @@ describe('the CLI seams', () => { const r = stopRepo(); const s = r.head(); const g = grantId(r.run('gstack-approvals', ['round-grant', '--pr', '7', '--head', s, '--kind', 'fix-check', '--stop-run', 'ro', '--findings', 'f#1', '--reason', 'x', '--by', 'Captain GStack Minder']).stdout)!; + writeGrantedStop(r.f.work, { pr: 7, grant: g, head: s, run: 'ro', findings: ['f#1'] }); r.f.write({ 'src/x.ts': 'export const x = 3;\n' }); r.f.commit('fix'); const fixed = r.head(); const plan = (rangeBase: string) => r.run('gstack-review-plan', ['--base', 'main', '--gate-tagged', '0', '--prior-rounds', '3', '--prior-full', '3', '--pr', '7', '--round-grant', g, '--stop', s, '--post-review', '--last', 'fix-check', '--range-base', rangeBase]); @@ -259,6 +277,7 @@ describe('finish and the summary count a run whose only round is the granted fix const reviewedBase = f.git('merge-base', 'origin/main', 'HEAD').stdout.trim(); const g = run('gstack-approvals', ['round-grant', '--pr', '7', '--head', s, '--kind', 'fix-check', '--stop-run', 'ro', '--findings', 'p1/outside-voice#1', '--reason', 'fixable blocker', '--by', 'Captain GStack Minder (GSTA-36)']); expect(g.status, g.stderr).toBe(0); + writeGrantedStop(f.work, { pr: 7, grant: grantId(g.stdout)!, head: s, run: 'ro', findings: ['p1/outside-voice#1'] }); f.write({ 'src/x.ts': 'export const x = 3;\n' }); f.commit('fix the read-only review blocker'); const since = new Date(Date.now() - 1000).toISOString(); const start = run('gstack-review-log', ['--start', 'review-fix-check']); @@ -272,5 +291,8 @@ describe('finish and the summary count a run whose only round is the granted fix expect(run('gstack-docs-candidate', ['snapshot', '--out', post, '--audit-id', 'a1', '--mode', 'edit', '--base', 'main', '--docs', 'README.md']).status).toBe(0); const fin = f.run(RELEASE, ['finish', '--base', 'main', '--reviewed-tree', reviewed, '--docs-post', post, '--reviewed-base', reviewedBase, '--lane', 'tests=printf " 3 pass\\n 0 fail\\nRan 3 tests across 1 file. [5.00ms]\\n"'], { GSTACK_APPROVALS_MIRROR: '0' }); expect(fin.stdout).toMatch(/^FIX_CHECK: reviewed .*src\/x\.ts.*grant a-[0-9a-f]{12}\)$/m); + writeGrantedStop(f.work, null); + const unstamped = f.run(RELEASE, ['finish', '--base', 'main', '--reviewed-tree', reviewed, '--docs-post', post, '--reviewed-base', reviewedBase, '--lane', 'tests=printf " 3 pass\\n 0 fail\\nRan 3 tests across 1 file. [5.00ms]\\n"'], { GSTACK_APPROVALS_MIRROR: '0' }); + expect(unstamped.stdout).not.toMatch(/^FIX_CHECK: reviewed /m); }); }); diff --git a/test/ruled-stop.test.ts b/test/ruled-stop.test.ts new file mode 100644 index 00000000000..8300fb41eee --- /dev/null +++ b/test/ruled-stop.test.ts @@ -0,0 +1,206 @@ +/** + * GST-2273 and GST-3005: an owner ruling could not close a finding on a round-2 full pass (docs/review-policy.md said it could), + * and a read-only final review had no way to record an owner-accepted deferral. A stop ruling now names one open finding of one + * recorded stop (its ledger id, the stop's head, the PR and the run that stopped), gstack-ship-receipt ruled-stop says whether the + * owner ruled every open finding of that stop, and receipt write takes the ruled stop as a second_pass or read_only exception after + * rerunning that check. Review-read, the loop summary and the dispatch judge still never read rulings. Row ids are the case matrix's + * (captain drive handoffs/GSTA-608/case-matrix.md). + */ +import { afterEach, describe, expect, setDefaultTimeout, test } from 'bun:test'; +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import type { ApprovalRow } from '../lib/approval-record'; +import { placeRunEntry, runStub } from '../lib/pr-review-history'; +import { ruledNotes, stopRulingRow, stopRulings, type StopRuling } from '../lib/ruled-notes'; +import { ruledStop, ruledStopLines, type LedgerTrait } from '../lib/ruled-stop'; +import { extractReceipt } from '../lib/ship-receipt'; +import { reviewLoopExceptionLine } from '../lib/ship-receipt-depth'; +import { RELEASE, shipFixture, type ShipFx } from './helpers/ship-bin-fixture'; + +setDefaultTimeout(120_000); +const BIN = path.dirname(RELEASE); +const fxs: ShipFx[] = []; +afterEach(() => { while (fxs.length) fxs.pop()!.cleanup(); }); + +const S = 'a'.repeat(40), S2 = 'b'.repeat(40), T = 'd'.repeat(40), T2 = 'e'.repeat(40); +const ID = 'p2/outside-voice#1', ID2 = 'p2/specialist#2', ID3 = 'p2/red-team#1'; +const BY = 'Captain GStack Minder (GSTA-36)'; +const blocker = (id: string, o: Record = {}) => ({ fingerprint: 'src/x.ts:1:' + id, severity: 'CRITICAL', blocking: true, action: 'open', ledger_id: id, raised_by: 'outside-voice', ...o }); +const row = (findings: Record[], o: Record = {}) => + ({ skill: 'review', via: 'ship', pass: 2, timestamp: '2026-11-18T01:00:00Z', completed: true, converged: false, dirty: false, commit_full: S, tree: T, wtree: T, review_binding: { state: 'incomplete', start_wtree: T, end_wtree: T }, findings, ...o }); +const ruling = (finding: string, o: Partial = {}): StopRuling => ({ finding, head: S, pr: 7, stop_run: 'r2', by: BY, reason: 'below the floor', at: '2026-11-18T02:00:00Z', approval: 'a-' + finding.replace(/\W/g, '').slice(-12).padStart(12, '0'), ...o }); +const check = (o: { rows?: Record[]; blockers?: string[]; traits?: LedgerTrait[]; rulings?: StopRuling[]; stop?: { head: string; tree?: string; run: string } } = {}) => + ruledStop({ pr: 7, run: 'r2', stop: o.stop ?? { head: S, tree: T, run: 'r2' }, rows: o.rows ?? [row([blocker(ID)])], blockers: o.blockers ?? [ID], traits: o.traits ?? [], rulings: o.rulings ?? [] }); +const approval = (id: string, o: Partial & { scope: string; ask: string }): ApprovalRow => + ({ id, date: '2026-11-18', recorded_at: '2026-11-18T00:00:00Z', words: 'w', by: BY, pending: 'none', outcome: 'approved', source: 'manual', branch: 'b', ...o } as ApprovalRow); + +describe('which findings of the stop a ruling closes (lib/ruled-stop.ts)', () => { + // Value: protects=GST-2273's shape: a round-2 full pass blocked on one finding, ruled by its id at the stop head, closes; + // fails_when=the check ignores stop rulings or matches by fingerprint; seam=ruledStop + test('R1: the one open finding, ruled by id at the stop head for this PR and run, closes the stop', () => { + const r = check({ rulings: [ruling(ID)] }); + expect(r).toMatchObject({ state: 'closed', findings: [{ id: ID, why: 'ruled' }], unmatched: [] }); + expect(ruledStopLines(r, 7).at(-1)).toBe('RULED_STOP: closed run=r2 head=' + S + ' tree=' + T + ' ids=' + ID); + }); + test('R2/R3/X6: a ruling naming another id, another head, another stop run or another PR closes nothing', () => { + for (const r of [ruling(ID2), ruling(ID, { head: S2 }), ruling(ID, { stop_run: 'r1' })]) { + expect(check({ rulings: [r] })).toMatchObject({ state: 'open', findings: [{ id: ID, why: 'open' }], unmatched: [r] }); + } + expect(check({ rulings: [ruling(ID, { pr: 8 })] })).toMatchObject({ state: 'open', unmatched: [] }); + }); + test('R4/H1: a gate finding never closes by ruling, whether the gate is on its row or only in its ledger line', () => { + expect(check({ rows: [row([blocker(ID, { gate: 'test-weakening', gate_id: 'g1' })])], rulings: [ruling(ID)] }).findings).toEqual([{ id: ID, why: 'gated' }]); + expect(check({ traits: [{ key: ID, reader: 'outside-voice', gate: 'RH-1' }], rulings: [ruling(ID)] })).toMatchObject({ state: 'open', findings: [{ id: ID, why: 'gated' }] }); + }); + test('R5: a security-class blocker never closes by ruling (decision B)', () => { + expect(check({ rows: [row([blocker(ID, { raised_by: 'security' })])], rulings: [ruling(ID)] }).findings).toEqual([{ id: ID, why: 'security' }]); + expect(check({ traits: [{ key: ID, reader: 'specialist-batched', category: 'security' }], rulings: [ruling(ID)] }).state).toBe('open'); + }); + test('R9: two of three open findings ruled leaves the stop open on the third', () => { + const r = check({ rows: [row([blocker(ID), blocker(ID2), blocker(ID3)])], blockers: [], rulings: [ruling(ID), ruling(ID3)] }); + expect(r.state).toBe('open'); + expect(r.findings.map(f => [f.id, f.why])).toEqual([[ID3, 'ruled'], [ID, 'ruled'], [ID2, 'open']].sort()); + expect(ruledStopLines(r, 7).at(-1)).toStartWith('RULED_STOP: open 1 of 3'); + }); + test('R10/H4: re-logged at a later head, the stop there is new; a ruling at the old head closes nothing', () => { + const later = check({ stop: { head: S2, tree: T2, run: 'r2' }, rows: [row([blocker(ID)]), row([blocker(ID)], { commit_full: S2, tree: T2, wtree: T2, review_binding: { state: 'incomplete', start_wtree: T2, end_wtree: T2 } })], rulings: [ruling(ID)] }); + expect(later).toMatchObject({ state: 'open', findings: [{ id: ID, why: 'open' }] }); + }); + test('R11/H5: a fingerprint closes nothing; a second finding whose fingerprint aliases the ruled id stays open', () => { + expect(check({ rulings: [ruling('src/x.ts:1:' + ID)] }).state).toBe('open'); + const alias = check({ rows: [row([blocker(ID), blocker(ID2, { fingerprint: 'id=' + ID })])], blockers: [], rulings: [ruling(ID)] }); + expect(alias.findings.find(f => f.id === ID2)?.why).toBe('open'); + }); + test('H2/H3/S1: a read whose tree changed, on a dirty worktree or unfinished binds no ruled stop', () => { + for (const o of [{ review_binding: { state: 'changed', start_wtree: T, end_wtree: T2 } }, { dirty: true }, { completed: false }, { wtree: T2 }]) { + expect(check({ rows: [row([blocker(ID)], o)], rulings: [ruling(ID)] }).state).toBe('unbound'); + } + expect(check({ rows: [row([blocker(ID)]), { ...row([]), skill: 'adversarial-review', review_binding: { state: 'changed', start_wtree: T, end_wtree: T2 } }], rulings: [ruling(ID)] }).state).toBe('unbound'); + }); + test('X6: another run\'s stop, or no stop record, binds nothing in this run', () => { + expect(check({ stop: { head: S, tree: T, run: 'r1' }, rulings: [ruling(ID, { stop_run: 'r1' })] }).state).toBe('unbound'); + expect(ruledStop({ pr: 7, run: 'r2', rows: [row([blocker(ID)])], blockers: [], traits: [], rulings: [] }).state).toBe('unbound'); + }); + test('X12: a blocker only the ledgers hold is open, and closes only by its own id; a row that fixed it settles it', () => { + expect(check({ rows: [row([])], blockers: [ID] })).toMatchObject({ state: 'open', findings: [{ id: ID, why: 'open' }] }); + expect(check({ rows: [row([])], blockers: [ID], rulings: [ruling(ID)] }).state).toBe('closed'); + expect(check({ rows: [row([{ ...blocker('p1/outside-voice#1'), action: 'fixed' }], { pass: 1 }), row([])], blockers: ['p1/outside-voice#1'] }).state).toBe('none'); + }); + test('X17: a stop with no open finding has nothing to rule, and a finding with no ledger id cannot be named', () => { + expect(check({ rows: [row([{ ...blocker(ID), blocking: false, action: 'noted' }])], blockers: [] }).state).toBe('none'); + const { ledger_id: _, ...bare } = blocker(ID); + expect(check({ rows: [row([bare])], blockers: [] }).findings[0]!.why).toBe('unnamed'); + }); +}); + +describe('the stop ruling row (lib/ruled-notes.ts)', () => { + test('R6/R8: gstack rulings and unapproved rows are no rulings; the newest of two for the same finding wins', () => { + const one = approval('a-000000000001', { ...stopRulingRow(ID, S, 7, 'r2', 'first') }); + const two = approval('a-000000000002', { ...stopRulingRow(ID, S, 7, 'r2', 'second') }); + expect(stopRulings([one, two]).map(r => r.reason)).toEqual(['second']); + expect(stopRulings([approval('a-000000000003', { ...stopRulingRow(ID, S, 7, 'r2', 'x'), by: 'gstack no-stop default (K1)' })])).toEqual([]); + expect(stopRulings([approval('a-000000000004', { ...stopRulingRow(ID, S, 7, 'r2', 'x'), outcome: 'pending' })])).toEqual([]); + }); + test('X23: a stop ruling is not a fix-check ruling, and a fix-check ruling is not a stop ruling', () => { + const stopRow = approval('a-000000000005', { ...stopRulingRow(ID, S, 7, 'r2', 'x') }); + const legacy = approval('a-000000000006', { scope: 'ruled_note ' + ID + ' ' + S, ask: 'ruled_note ' + ID + ' at ' + S + ': x' }); + expect(ruledNotes([stopRow])).toEqual([]); + expect(stopRulings([legacy])).toEqual([]); + }); +}); + +/** A fixture at the stop head S: run r2's round-2 review row with one open blocker, its ledger, and a body with the stop record. */ +function ruledRepo(o: { priorFull?: number; passes?: number } = {}) { + const f = shipFixture({ 'src/x.ts': 'export const x = 1;\n' }, { 'src/x.ts': 'export const x = 2;\n' }); + fxs.push(f); + const run = (bin: string, args: string[]) => f.run(path.join(BIN, bin), args, { GSTACK_APPROVALS_MIRROR: '0' }); + const s = f.git('rev-parse', 'HEAD').stdout.trim(); + const since = new Date(Date.now() - 1000).toISOString(); + const start = run('gstack-review-log', ['--start', 'review']); + expect(start.status, start.stderr).toBe(0); + const logged = run('gstack-review-log', [JSON.stringify({ skill: 'review', timestamp: new Date().toISOString(), via: 'ship', pass: o.passes ?? 2, review_scope: 'frozen', completed: true, converged: false, status: 'issues_found', issues_found: 1, critical: 1, informational: 0, findings: [blocker(ID)] }), '--finish', start.stdout.trim()]); + expect(logged.status, logged.stderr).toBe(0); + const dir = path.join(f.root, 'run'); + fs.mkdirSync(path.join(dir, 'p2'), { recursive: true }); + const merged = path.join(dir, 'p2', 'merged.jsonl'); + fs.writeFileSync(merged, JSON.stringify({ id: 'outside-voice#1', reader: 'outside-voice', label: 'CRITICAL', raw: 'src/x.ts:1 the export changes a published value. Severity: Critical Blocks: yes', output_sha256: 'x' }) + '\n'); + fs.writeFileSync(path.join(dir, 'p2', 'review-ledger.jsonl'), JSON.stringify({ event: 'output', at: new Date().toISOString(), reader: 'outside-voice', ids: ['outside-voice#1'], merged }) + '\n'); + const body = path.join(f.root, 'body.md'); + const prior = o.priorFull ?? 0; + fs.writeFileSync(body, prior ? placeRunEntry('Fixes a thing.\n', runStub({ head: 'c'.repeat(40), run: 'r1', status: 'started', loop: { passes: prior, blocking_found: 1, deferred: 0, rounds: prior } })) : 'Fixes a thing.\n'); + const stop = run('gstack-ship-receipt', ['stop', '--body', body, '--pr', '7', '--run', 'r2', '--since', since]); + expect(stop.status, stop.stderr).toBe(0); + const rule = (finding: string, extra: string[] = []) => run('gstack-approvals', ['rule', '--pr', '7', '--stop-run', 'r2', '--head', s, '--finding', finding, '--reason', 'the value change is intended', '--words', 'ship it as a note', '--by', BY, ...extra]); + const ruled = () => run('gstack-ship-receipt', ['ruled-stop', '--body', body, '--pr', '7', '--run', 'r2', '--since', since, '--dir', dir]); + const exception = (kind: 'second_pass' | 'read_only', deferred = [ID]) => ({ accepted_by: BY, date: '2026-11-18', via: 'GSTA-608', reason: 'ruled below the floor', [kind]: { head: s, deferred } }); + const write = (e: Record, loop: Record, extra: string[] = ['--ruled-stop']) => + run('gstack-ship-receipt', ['write', '--pr', '7', '--base', 'main', '--version', '1.0.0', '--session-kind', 'unattended', '--body', body, '--run', 'r2', '--since', since, '--dir', dir, '--review-loop', JSON.stringify(loop), '--review-loop-exception', JSON.stringify(e), ...extra]); + return { f, run, s, body, dir, rule, ruled, exception, write }; +} +const notesOf = (stdout: string) => [...stdout.matchAll(/^RULED_NOTE: (.+)$/gm)].map(m => 'Ruled note: ' + m[1]); +const withLines = (body: string, lines: string[]) => fs.writeFileSync(body, fs.readFileSync(body, 'utf8').replace('Fixes a thing.\n', 'Fixes a thing.\n\n' + lines.join('\n') + '\n')); + +describe('the ruled-stop check and the receipt that takes it (gstack-ship-receipt ruled-stop, write --ruled-stop)', () => { + // Value: protects=GST-2273 end to end: a ruling recorded with the stop's printed command closes the stop in the run that stopped, + // and the receipt records the deferral only after rerunning the check; fails_when=rule writes no stop ruling, ruled-stop reads + // another identity, or write accepts a deferral broader than the rulings; seam=gstack-approvals rule, gstack-ship-receipt + test('R1/D4/D3: rule the open finding, ruled-stop reads closed, and write takes exactly that deferral as second_pass', () => { + const r = ruledRepo(); + const before = r.ruled(); + expect(before.status, before.stderr + before.stdout).toBe(3); + expect(before.stderr).toContain('(RULED_STOP_OPEN'); + expect(before.stdout).toContain('RULED_STOP_FINDING: ' + ID + ' open'); + const rule = r.rule(ID); + expect(rule.status, rule.stderr).toBe(0); + const after = r.ruled(); + expect(after.status, after.stderr).toBe(0); + expect(after.stdout).toContain('RULED_STOP: closed run=r2 head=' + r.s); + const e = r.exception('second_pass'); + const loop = { passes: 2, blocking_found: 1, deferred: 0, scope: 'frozen' }; + const wide = r.write(r.exception('second_pass', [ID, 'p2/red-team#1']), loop); + expect(wide.status).toBe(1); + expect(wide.stderr).toContain('deferred must name exactly'); + const unlisted = r.write(e, loop); + expect(unlisted.status).toBe(1); + expect(unlisted.stderr).toContain('does not list "Ruled note: ' + ID); + withLines(r.body, [notesOf(after.stdout)[0]!, reviewLoopExceptionLine(e as never)]); + const ok = r.write(e, loop); + expect(ok.status, ok.stderr).toBe(0); + const rec = extractReceipt(fs.readFileSync(r.body, 'utf8')).receipt!; + expect(rec.review_loop_exception).toMatchObject({ second_pass: { head: r.s, deferred: [ID] }, ruled: [expect.stringMatching(/^a-[0-9a-f]{12}$/)] }); + const forged = r.write({ ...e, ruled: ['a-000000000000'] }, loop); + expect(forged.stderr).toContain('ruled is written by --ruled-stop'); + }); + + // Value: protects=GST-3005: a read-only final review of a PR past its two rounds records the owner's ruled deferral, and the + // negative control with fewer earlier rounds is refused; fails_when=write counts this run's own pass, or takes read_only + // without the ruled-stop check; seam=gstack-ship-receipt write + test('D1/D2/R12: read_only takes a ruled read-only review after two earlier full rounds, and refuses with fewer', () => { + for (const [prior, want] of [[2, 0], [1, 1]] as const) { + const r = ruledRepo({ priorFull: prior, passes: 1 }); + expect(r.rule(ID).status).toBe(0); + const closed = r.ruled(); + expect(closed.status, closed.stderr).toBe(0); + const e = r.exception('read_only'); + withLines(r.body, [notesOf(closed.stdout)[0]!, reviewLoopExceptionLine(e as never)]); + const loop = { passes: 1, blocking_found: 1, deferred: 0, scope: 'frozen' }; + const out = r.write(e, loop); + if (out.status !== want) throw new Error(`prior=${prior} status=${out.status}: ${out.stderr}`); + if (want) expect(out.stderr).toContain('two full review rounds before this run'); + else expect(r.write(e, loop, []).stderr).toContain('read_only needs --ruled-stop'); + } + }); + + test('R10/R6: a head move voids the ruled stop; a ruling from inside the open run is refused', () => { + const r = ruledRepo(); + expect(r.rule(ID).status).toBe(0); + r.f.write({ 'src/x.ts': 'export const x = 3;\n' }); r.f.commit('a later change'); + const moved = r.ruled(); + expect(moved.status).toBe(3); + expect(moved.stderr).toContain('a head move voids the rulings'); + fs.writeFileSync(path.join(r.f.work, '.git', 'gstack-ship-run'), 'r2\n'); + const inside = r.rule(ID2); + expect(inside.status).toBe(2); + expect(inside.stderr).toContain('is open on this checkout'); + }); +}); diff --git a/test/size-ledger/ship/owner-rulings-close-a-ruled-stop-and-read-only-deferrals.json b/test/size-ledger/ship/owner-rulings-close-a-ruled-stop-and-read-only-deferrals.json new file mode 100644 index 00000000000..b97c6fbd1cd --- /dev/null +++ b/test/size-ledger/ship/owner-rulings-close-a-ruled-stop-and-read-only-deferrals.json @@ -0,0 +1,4 @@ +{ + "bytes": 744, + "why": "ruled stops: Step 9 runs gstack-ship-receipt ruled-stop after the owner rules a stop, and Step 19 writes the ruled deferral (GST-2273, GST-3005)" +} From 52e75f5fbce679ebf1a7ec3c44ef287a27435e09 Mon Sep 17 00:00:00 2001 From: garrytan Date: Wed, 18 Nov 2026 09:24:53 +0000 Subject: [PATCH 2/6] Load the ruled-stop check only when a command uses it, so installs with only bin/ and lib/ keep working Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- bin/gstack-ship-receipt | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/bin/gstack-ship-receipt b/bin/gstack-ship-receipt index 7e9e11b99e0..19b07ecbede 100755 --- a/bin/gstack-ship-receipt +++ b/bin/gstack-ship-receipt @@ -62,8 +62,7 @@ import { checkReceiptProse, proseLine } from '../lib/ship-receipt-prose'; import { resolveStateRoot } from '../lib/state-root'; import { readPause, receiptBaseRed } from '../lib/base-red'; import { readRuledNotes, ruledNoteText, stopRulings } from '../lib/ruled-notes'; -import { ledgerTraits, ruledStop, ruledStopLines, type RuledStop } from '../lib/ruled-stop'; -import { ledgerBlockers } from '../lib/review-ledger'; +import type { RuledStop } from '../lib/ruled-stop'; import { locate, readRecord } from '../lib/approval-record'; import { appliedGateDispositions, gateDispositionText } from '../lib/gate-dispositions'; import { laneExceptionBodyLines } from '../lib/test-lane-exception'; @@ -1151,6 +1150,9 @@ function readRuledStop(rest: string[], repoRoot: string, body: string, pr: numbe try { files = (fs.readdirSync(dir, { recursive: true }) as string[]).filter(p => path.basename(p) === 'review-ledger.jsonl').sort().map(p => path.join(dir, p)); } catch (e: any) { return `--dir ${dir}: ${e.code ?? e.message}`; } if (!files.length) return `--dir ${dir} holds no review-ledger.jsonl: name the run directory this run's passes wrote`; const keyOf = (file: string) => (id: string) => `${path.basename(path.dirname(path.resolve(file)))}/${id}`; + // Loaded here, not at the top: the ledger reader pulls in the review briefs, and installs that carry only bin/ and lib/ run every other command. + const { ledgerTraits, ruledStop } = require('../lib/ruled-stop') as typeof import('../lib/ruled-stop'); + const { ledgerBlockers } = require('../lib/review-ledger') as typeof import('../lib/review-ledger'); let blockers: string[], traits: ReturnType; try { blockers = files.flatMap(f => ledgerBlockers(f).map(b => keyOf(f)(b.id))); traits = files.flatMap(f => ledgerTraits(f, keyOf(f))); } catch (e: any) { return (e as Error).message.split('\n')[0]!; } const loc = locate({ cwd: repoRoot, env: process.env }); @@ -1176,7 +1178,7 @@ function ruledStopException(rest: string[], repoRoot: string, bodyText: string | if (!live.ok) return `--ruled-stop: ${live.why}`; const r = readRuledStop(rest, repoRoot, live.body, pr); if (typeof r === 'string') return `--ruled-stop: ${r}`; - if (r.state !== 'closed') return `--ruled-stop: ${ruledStopLines(r, pr).at(-1)!}`; + if (r.state !== 'closed') return `--ruled-stop: ${(require('../lib/ruled-stop') as typeof import('../lib/ruled-stop')).ruledStopLines(r, pr).at(-1)!}`; if (r.stop!.head !== stopOf.head) return `--ruled-stop: the ruled stop is at ${r.stop!.head.slice(0, 12)}, not the exception head ${stopOf.head.slice(0, 12)}`; const ids = r.findings.map(f => f.id); if (JSON.stringify([...new Set(stopOf.deferred)].sort()) !== JSON.stringify([...ids].sort()) || stopOf.deferred.length !== ids.length) return `--ruled-stop: deferred must name exactly the ruled stop's findings (${ids.join(', ')}), not ${stopOf.deferred.join(', ')}`; @@ -1202,7 +1204,7 @@ function cmdRuledStop(rest: string[]): number { const head = git(['rev-parse', 'HEAD'], repoRoot) ?? ''; const dirty = spawnSync('git', ['diff', '--quiet', 'HEAD', '--'], { cwd: repoRoot, timeout: 30_000 }).status !== 0; const moved = !r.stop ? '' : head !== r.stop.head ? `HEAD ${head.slice(0, 12)} is not the stop's head ${r.stop.head.slice(0, 12)}: a head move voids the rulings` : dirty ? 'the worktree has uncommitted changes: the rulings bind the stop\'s committed tree' : ''; - const lines = ruledStopLines(r, pr); + const lines = (require('../lib/ruled-stop') as typeof import('../lib/ruled-stop')).ruledStopLines(r, pr); process.stdout.write(lines.slice(0, -1).map(l => l + '\n').join('')); if (r.state !== 'closed' || moved) { process.stderr.write(resultLine('gstack-ship-receipt ruled-stop', 'RULED_STOP_OPEN', moved || lines.at(-1)!.replace(/^RULED_STOP: /, '')) + '\n'); return EXIT.refused; } for (const f of r.findings) process.stdout.write(`RULED_NOTE: ${ruledNoteText(f.ruling!)}\n`); From b466b336f4f59ae6eb2b05c10688ad39bb807db5 Mon Sep 17 00:00:00 2001 From: garrytan Date: Wed, 18 Nov 2026 09:44:10 +0000 Subject: [PATCH 3/6] Treat a blocker whose reviewer is the security specialist as security-class, so an owner ruling can't close it Review-Finding: p1/specialist-batched#1 reader=security Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- lib/ruled-stop.ts | 12 ++++++------ test/ruled-stop.test.ts | 4 ++++ 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/lib/ruled-stop.ts b/lib/ruled-stop.ts index 70353c042b7..3427c168e5a 100644 --- a/lib/ruled-stop.ts +++ b/lib/ruled-stop.ts @@ -12,7 +12,7 @@ import * as fs from 'node:fs'; import { rank, readLedger, type MergedLine } from './review-ledger'; import type { StopRuling } from './ruled-notes'; -export interface LedgerTrait { key: string; reader: string; gate?: string; category?: string } +export interface LedgerTrait { key: string; reader: string; gate?: string; category?: string; specialist?: string } export interface OpenFinding { id: string; why: 'ruled' | 'open' | 'gated' | 'security' | 'unnamed'; ruling?: StopRuling } export interface RuledStop { state: 'closed' | 'open' | 'none' | 'unbound'; @@ -49,10 +49,10 @@ export function ledgerTraits(ledger: string, keyOf: (id: string) => string): Led for (const id of o.ids as string[]) { const line = lines.find(l => l.id === id); const raw = line?.raw ?? ''; - let category: string | undefined; - try { const j = JSON.parse(raw); category = typeof j?.category === 'string' ? j.category : typeof j?.specialist === 'string' ? j.specialist : undefined; } catch { /* prose */ } + let category: string | undefined, specialist: string | undefined; + try { const j = JSON.parse(raw); category = typeof j?.category === 'string' ? j.category : undefined; specialist = typeof j?.specialist === 'string' ? j.specialist : undefined; } catch { /* prose */ } const gate = gateOf([raw, reasons.get(id) ?? '']); - out.set(keyOf(id), { key: keyOf(id), reader: String(o.reader), ...(gate ? { gate } : {}), ...(category ? { category } : {}) }); + out.set(keyOf(id), { key: keyOf(id), reader: String(o.reader), ...(gate ? { gate } : {}), ...(category ? { category } : {}), ...(specialist ? { specialist } : {}) }); } } return [...out.values()]; @@ -79,12 +79,12 @@ export function ruledStop(o: { pr: number; run: string; stop?: { head: string; t if (!f || typeof f !== 'object' || !blocks(f) || FIXED.has(f.action)) continue; const id = typeof f.ledger_id === 'string' && f.ledger_id ? f.ledger_id : `${String(f.fingerprint ?? '?')} (no ledger id)`; const t = traits.get(id); - open.set(id, { gate: !!f.gate || !!f.gate_id || !!t?.gate, security: [f.category, f.raised_by, t?.category].some(c => typeof c === 'string' && SECURITY.test(c)), named: typeof f.ledger_id === 'string' && !!f.ledger_id }); + open.set(id, { gate: !!f.gate || !!f.gate_id || !!t?.gate, security: [f.category, f.specialist, f.raised_by, t?.category, t?.specialist].some(c => typeof c === 'string' && SECURITY.test(c)), named: typeof f.ledger_id === 'string' && !!f.ledger_id }); } for (const key of o.blockers) { if (settled.has(key) || open.has(key)) continue; const t = traits.get(key); - open.set(key, { gate: !!t?.gate, security: [t?.category, t?.reader].some(c => typeof c === 'string' && SECURITY.test(c)), named: true }); + open.set(key, { gate: !!t?.gate, security: [t?.category, t?.specialist, t?.reader].some(c => typeof c === 'string' && SECURITY.test(c)), named: true }); } const findings: OpenFinding[] = [...open].sort(([a], [b]) => a.localeCompare(b)).map(([id, f]) => { const ruling = [...mine].reverse().find(r => r.finding === id && r.head === s.head && r.stop_run === s.run); diff --git a/test/ruled-stop.test.ts b/test/ruled-stop.test.ts index 8300fb41eee..ade69048b43 100644 --- a/test/ruled-stop.test.ts +++ b/test/ruled-stop.test.ts @@ -56,6 +56,10 @@ describe('which findings of the stop a ruling closes (lib/ruled-stop.ts)', () => expect(check({ rows: [row([blocker(ID, { raised_by: 'security' })])], rulings: [ruling(ID)] }).findings).toEqual([{ id: ID, why: 'security' }]); expect(check({ traits: [{ key: ID, reader: 'specialist-batched', category: 'security' }], rulings: [ruling(ID)] }).state).toBe('open'); }); + test('R5b: a batched-reader blocker whose specialist is security never closes by ruling, whatever its category', () => { + expect(check({ traits: [{ key: ID, reader: 'specialist-batched', category: 'injection', specialist: 'security' }], rulings: [ruling(ID)] }).findings).toEqual([{ id: ID, why: 'security' }]); + expect(check({ rows: [row([blocker(ID, { category: 'injection', specialist: 'security' })])], rulings: [ruling(ID)] }).findings).toEqual([{ id: ID, why: 'security' }]); + }); test('R9: two of three open findings ruled leaves the stop open on the third', () => { const r = check({ rows: [row([blocker(ID), blocker(ID2), blocker(ID3)])], blockers: [], rulings: [ruling(ID), ruling(ID3)] }); expect(r.state).toBe('open'); From 4c9fa21961769d0e74858a9b74556041ac6f28c8 Mon Sep 17 00:00:00 2001 From: garrytan Date: Wed, 18 Nov 2026 10:07:05 +0000 Subject: [PATCH 4/6] Refuse a ruled deferral once code changes after the ruled stop, refuse an unreadable --since, warn when the grant stamp cannot be written, and keep owner ruling lines out of the prose number check Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- bin/gstack-ship-receipt | 7 ++++++- lib/review-round-grant.ts | 7 ++++--- lib/ship-receipt-prose.ts | 6 ++++-- test/ruled-stop.test.ts | 22 ++++++++++++++++++++++ test/ship-receipt-prose.test.ts | 10 ++++++++++ 5 files changed, 46 insertions(+), 6 deletions(-) diff --git a/bin/gstack-ship-receipt b/bin/gstack-ship-receipt index 19b07ecbede..db560908167 100755 --- a/bin/gstack-ship-receipt +++ b/bin/gstack-ship-receipt @@ -1108,7 +1108,8 @@ function cmdHistory(rest: string[], json: boolean): number { const claimed = found && !answer?.ok ? receiptRuns(read.body).find(r => r.mark === 'grant' && r.grant === found.approval && r.run !== flag(rest, '--run')) : undefined; 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 }); - if (repoRoot && /^\d+$/.test(pr)) writeGrantedStop(repoRoot, answer?.ok ? { pr: Number(pr), grant: answer.grant.approval, head: answer.stop.head, run: answer.stop.run!, findings: answer.grant.findings! } : null); + const unstamped = repoRoot && /^\d+$/.test(pr) ? writeGrantedStop(repoRoot, answer?.ok ? { pr: Number(pr), grant: answer.grant.approval, head: answer.stop.head, run: answer.stop.run!, findings: answer.grant.findings! } : null) : null; + if (unstamped) process.stderr.write(`gstack-ship-receipt history: the granted-stop stamp in the git dir could not be written (${unstamped}); the plan and finish take no fix-check grant until history writes it\n`); 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` : ''}`); @@ -1145,6 +1146,7 @@ function readRuledStop(rest: string[], repoRoot: string, body: string, pr: numbe const log = runScriptSync(path.join(path.dirname(Bun.fileURLToPath(import.meta.url)), 'gstack-review-read'), [], { cwd: repoRoot, encoding: 'utf8', timeout: 60_000, maxBuffer: 64 * 1024 * 1024 }); if (log.status !== 0) return `gstack-review-read exited ${log.status}`; const sinceMs = Date.parse(since); + if (!Number.isFinite(sinceMs)) return `--since ${since} is not a timestamp: it bounds this run's review rows, so pass REVIEW_SINCE`; const rows = (log.stdout ?? '').split('\n---CONFIG---')[0]!.split('\n').flatMap(l => { try { const v = JSON.parse(l); return v && typeof v === 'object' && v.via === 'ship' && !(Date.parse(v.timestamp) < sinceMs) ? [v] : []; } catch { return []; } }); let files: string[]; try { files = (fs.readdirSync(dir, { recursive: true }) as string[]).filter(p => path.basename(p) === 'review-ledger.jsonl').sort().map(p => path.join(dir, p)); } catch (e: any) { return `--dir ${dir}: ${e.code ?? e.message}`; } @@ -1180,6 +1182,9 @@ function ruledStopException(rest: string[], repoRoot: string, bodyText: string | if (typeof r === 'string') return `--ruled-stop: ${r}`; if (r.state !== 'closed') return `--ruled-stop: ${(require('../lib/ruled-stop') as typeof import('../lib/ruled-stop')).ruledStopLines(r, pr).at(-1)!}`; if (r.stop!.head !== stopOf.head) return `--ruled-stop: the ruled stop is at ${r.stop!.head.slice(0, 12)}, not the exception head ${stopOf.head.slice(0, 12)}`; + const since = spawnSync('git', ['diff', '--name-only', r.stop!.head, 'HEAD', '--'], { cwd: repoRoot, encoding: 'utf8', timeout: 30_000 }); + const moved = since.status !== 0 ? ['(git diff failed)'] : since.stdout.split('\n').filter(p => p && !/^(changelog\.d|docs)\//.test(p)); + if (moved.length) return `--ruled-stop: ${moved.slice(0, 5).join(', ')} changed since the ruled stop at ${r.stop!.head.slice(0, 12)}: the rulings cover that commit, and only changelog.d/ and docs/ may change after it`; const ids = r.findings.map(f => f.id); if (JSON.stringify([...new Set(stopOf.deferred)].sort()) !== JSON.stringify([...ids].sort()) || stopOf.deferred.length !== ids.length) return `--ruled-stop: deferred must name exactly the ruled stop's findings (${ids.join(', ')}), not ${stopOf.deferred.join(', ')}`; if (e.read_only) { diff --git a/lib/review-round-grant.ts b/lib/review-round-grant.ts index faf02e41899..97f89ccf84d 100644 --- a/lib/review-round-grant.ts +++ b/lib/review-round-grant.ts @@ -47,10 +47,11 @@ export function reviewRoundGrants(rows: readonly ApprovalRow[]): ReviewRoundGran */ export interface GrantedStopStamp { pr: number; grant: string; head: string; run: string; findings: string[] } const stampPath = (cwd: string) => { const p = spawnSync('git', ['rev-parse', '--git-path', 'gstack-granted-stop'], { cwd, encoding: 'utf8', timeout: 10_000 }); return p.status === 0 && p.stdout.trim() ? path.resolve(cwd, p.stdout.trim()) : undefined; }; -export function writeGrantedStop(cwd: string, stamp: GrantedStopStamp | null): void { +/** Returns why the stamp could not be written or cleared, or null; without it the planner and finish take no fix-check grant. */ +export function writeGrantedStop(cwd: string, stamp: GrantedStopStamp | null): string | null { const p = stampPath(cwd); - if (!p) return; - if (stamp) fs.writeFileSync(p, JSON.stringify(stamp) + '\n'); else fs.rmSync(p, { force: true }); + if (!p) return 'git rev-parse --git-path failed'; + try { if (stamp) fs.writeFileSync(p, JSON.stringify(stamp) + '\n'); else fs.rmSync(p, { force: true }); return null; } catch (e) { return (e as Error).message.split('\n')[0]!; } } export function readGrantedStop(cwd: string): GrantedStopStamp | undefined { const p = stampPath(cwd); diff --git a/lib/ship-receipt-prose.ts b/lib/ship-receipt-prose.ts index 291c4bfc990..1ebe37bf1bc 100644 --- a/lib/ship-receipt-prose.ts +++ b/lib/ship-receipt-prose.ts @@ -107,6 +107,7 @@ function withoutExceptionLines(body: string, receipt: Record): const lines = new Set(); const loop = receipt.review_loop_exception === undefined ? undefined : parseReviewLoopException(receipt.review_loop_exception); if (loop?.ok) lines.add(reviewLoopExceptionLine(loop.exception)); + const ruled = new Set(loop?.ok ? loop.exception.ruled ?? [] : []); const docs = receipt.docs === undefined ? undefined : parseReceiptDocs(receipt.docs); const docsLine = docs?.ok ? docsExceptionLine(docs.docs) : null; if (docsLine) lines.add(docsLine); @@ -114,8 +115,9 @@ function withoutExceptionLines(body: string, receipt: Record): if (Array.isArray(receipt.gate_dispositions)) for (const d of receipt.gate_dispositions) lines.add(`Gate disposition: ${gateDispositionText(d as GateDisposition)}`); if (Array.isArray(receipt.mechanical)) for (const l of receipt.mechanical) if (typeof l === 'string') lines.add(l); for (const l of laneExceptionBodyLines(receipt.ci_carried)) lines.add(l); - if (!lines.size) return body; - return body.split(/(?<=\n)/).map(l => (lines.has(l.trim()) ? '(exception line)\n' : l)).join(''); + const stopRuling = (l: string) => ruled.has(/^Ruled note: .* \(approval (a-[0-9a-f]{12})\)$/.exec(l.trim())?.[1] ?? ''); + if (!lines.size && !ruled.size) return body; + return body.split(/(?<=\n)/).map(l => (lines.has(l.trim()) || stopRuling(l) ? '(exception line)\n' : l)).join(''); } /** diff --git a/test/ruled-stop.test.ts b/test/ruled-stop.test.ts index ade69048b43..8c3c347a95d 100644 --- a/test/ruled-stop.test.ts +++ b/test/ruled-stop.test.ts @@ -207,4 +207,26 @@ describe('the ruled-stop check and the receipt that takes it (gstack-ship-receip expect(inside.status).toBe(2); expect(inside.stderr).toContain('is open on this checkout'); }); + + // Value: protects=GST-2273: the rulings cover the stop commit only, and the run's rows are bounded by a real timestamp; + // fails_when=write takes a deferral at a later code commit, or a garbage --since keeps every earlier run's rows; seam=gstack-ship-receipt + test('D5: after the ruled stop, a write refuses a commit outside changelog.d/ and docs/, and an unparsable --since', () => { + const r = ruledRepo(); + expect(r.rule(ID).status).toBe(0); + const closed = r.ruled(); + expect(closed.status, closed.stderr).toBe(0); + const e = r.exception('second_pass'); + withLines(r.body, [notesOf(closed.stdout)[0]!, reviewLoopExceptionLine(e as never)]); + const loop = { passes: 2, blocking_found: 1, deferred: 0, scope: 'frozen' }; + r.f.write({ 'docs/x.md': 'a note\n' }); r.f.commit('docs only'); + const docs = r.write(e, loop); + expect(docs.status, docs.stderr).toBe(0); + r.f.write({ 'src/x.ts': 'export const x = 3;\n' }); r.f.commit('a later change'); + const src = r.write(e, loop); + expect(src.status).toBe(1); + expect(src.stderr).toContain('src/x.ts changed since the ruled stop'); + const garbage = r.run('gstack-ship-receipt', ['ruled-stop', '--body', r.body, '--pr', '7', '--run', 'r2', '--since', 'garbage', '--dir', r.dir]); + expect(garbage.status).toBe(2); + expect(garbage.stderr).toContain('--since garbage is not a timestamp'); + }); }); diff --git a/test/ship-receipt-prose.test.ts b/test/ship-receipt-prose.test.ts index f088ead4ba1..10594dc91aa 100644 --- a/test/ship-receipt-prose.test.ts +++ b/test/ship-receipt-prose.test.ts @@ -140,6 +140,16 @@ describe('the Review-loop exception line (GST-977, gstack-evals #139)', () => { expect(checkReceiptProse(excepted, line.replace('GEVA-2', 'GEVA-3')).mismatches).toEqual(twoSkip); expect(checkReceiptProse({ ...excepted, review_loop_exception: undefined }, line).mismatches).toEqual(twoSkip); }); + + // Value: protects=GST-2273: a stop ruling's owner reason may quote a number without failing --check-prose, and only the + // rulings the receipt's exception verified are exempt; fails_when=a ruled note's "2 skip" is read as a counter claim, or + // any line shaped like a ruled note is skipped; seam=lib/ship-receipt-prose.ts checkReceiptProse + test('a stop ruling line whose approval the exception lists is not prose; another approval id stays prose', () => { + const ruled = { ...excepted, review_loop_exception: { accepted_by: 'Garry', date: '2026-11-18', via: 'GSTA-608', reason: 'ruled', second_pass: { head: 'b'.repeat(40), deferred: ['p2/outside-voice#1'] }, ruled: ['a-00000000beef'] } }; + const note = (id: string) => `Ruled note: p2/outside-voice#1 at bbbbbbbbbbbb by Captain GStack Minder (GSTA-36): only 2 skip are affected (approval ${id})`; + expect(checkReceiptProse(ruled, `${note('a-00000000beef')}\n\nGate: 70 skip.\n`)).toEqual({ checked: 1, mismatches: [] }); + expect(checkReceiptProse(ruled, note('a-00000000cafe')).mismatches).toEqual([{ field: 'gate.unit.skip', prose: 2, receipt: 70 }]); + }); }); describe('the Documentation exception line (GST-983)', () => { From 971f94122e486df53ffd778e0a2c24cd3185731e Mon Sep 17 00:00:00 2001 From: garrytan Date: Wed, 18 Nov 2026 10:28:30 +0000 Subject: [PATCH 5/6] fix: pre-landing review fixes A ruled stop's receipt write now accepts release metadata and docs that Steps 12 to 14.5 commit after the stop, and still refuses code. Review-Finding: p1/red-team#1 reader=red-team Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- bin/gstack-ship-receipt | 8 ++++++-- test/ruled-stop.test.ts | 5 ++++- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/bin/gstack-ship-receipt b/bin/gstack-ship-receipt index db560908167..9665e7d0417 100755 --- a/bin/gstack-ship-receipt +++ b/bin/gstack-ship-receipt @@ -1183,8 +1183,12 @@ function ruledStopException(rest: string[], repoRoot: string, bodyText: string | if (r.state !== 'closed') return `--ruled-stop: ${(require('../lib/ruled-stop') as typeof import('../lib/ruled-stop')).ruledStopLines(r, pr).at(-1)!}`; if (r.stop!.head !== stopOf.head) return `--ruled-stop: the ruled stop is at ${r.stop!.head.slice(0, 12)}, not the exception head ${stopOf.head.slice(0, 12)}`; const since = spawnSync('git', ['diff', '--name-only', r.stop!.head, 'HEAD', '--'], { cwd: repoRoot, encoding: 'utf8', timeout: 30_000 }); - const moved = since.status !== 0 ? ['(git diff failed)'] : since.stdout.split('\n').filter(p => p && !/^(changelog\.d|docs)\//.test(p)); - if (moved.length) return `--ruled-stop: ${moved.slice(0, 5).join(', ')} changed since the ruled stop at ${r.stop!.head.slice(0, 12)}: the rulings cover that commit, and only changelog.d/ and docs/ may change after it`; + const base = flag(rest, '--base') ?? resolveBaseBranch(repoRoot); + const load = loadPolicyFromBase(repoRoot, base); + const release = new Set((require('../lib/ship-bin-common') as typeof import('../lib/ship-bin-common')).releasePaths(isUnavailable(load) ? null : load.policy, repoRoot, r.stop!.head, base)); + const { classifyPath } = require('../lib/review-depth') as typeof import('../lib/review-depth'); + const moved = since.status !== 0 ? ['(git diff failed)'] : since.stdout.split('\n').filter(p => p && !/^(changelog\.d|docs)\//.test(p) && !release.has(p) && classifyPath(p, repoRoot) !== 'docs'); + if (moved.length) return `--ruled-stop: ${moved.slice(0, 5).join(', ')} changed since the ruled stop at ${r.stop!.head.slice(0, 12)}: the rulings cover that commit, and only release metadata and docs may change after it`; const ids = r.findings.map(f => f.id); if (JSON.stringify([...new Set(stopOf.deferred)].sort()) !== JSON.stringify([...ids].sort()) || stopOf.deferred.length !== ids.length) return `--ruled-stop: deferred must name exactly the ruled stop's findings (${ids.join(', ')}), not ${stopOf.deferred.join(', ')}`; if (e.read_only) { diff --git a/test/ruled-stop.test.ts b/test/ruled-stop.test.ts index 8c3c347a95d..b59d51b5af9 100644 --- a/test/ruled-stop.test.ts +++ b/test/ruled-stop.test.ts @@ -210,7 +210,7 @@ describe('the ruled-stop check and the receipt that takes it (gstack-ship-receip // Value: protects=GST-2273: the rulings cover the stop commit only, and the run's rows are bounded by a real timestamp; // fails_when=write takes a deferral at a later code commit, or a garbage --since keeps every earlier run's rows; seam=gstack-ship-receipt - test('D5: after the ruled stop, a write refuses a commit outside changelog.d/ and docs/, and an unparsable --since', () => { + test('D5: after the ruled stop, a write takes release metadata and docs but refuses a code commit, and an unparsable --since', () => { const r = ruledRepo(); expect(r.rule(ID).status).toBe(0); const closed = r.ruled(); @@ -221,6 +221,9 @@ describe('the ruled-stop check and the receipt that takes it (gstack-ship-receip r.f.write({ 'docs/x.md': 'a note\n' }); r.f.commit('docs only'); const docs = r.write(e, loop); expect(docs.status, docs.stderr).toBe(0); + r.f.write({ 'VERSION': '9.9.9\n', 'CHANGELOG.md': '# Changelog\n\n## [Unreleased]\n- a note\n', 'TODOS.md': '# TODOs\n', 'README.md': '# readme\n' }); r.f.commit('release metadata and root docs'); + const release = r.write(e, loop); + expect(release.status, release.stderr).toBe(0); r.f.write({ 'src/x.ts': 'export const x = 3;\n' }); r.f.commit('a later change'); const src = r.write(e, loop); expect(src.status).toBe(1); From 5f59d56f0290a726d2e6e9742dcf5ceb008a6e2e Mon Sep 17 00:00:00 2001 From: garrytan Date: Wed, 18 Nov 2026 10:42:53 +0000 Subject: [PATCH 6/6] Count a logic change to a version-stamped policy file after the ruled stop as code, so old rulings cannot cover it Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- bin/gstack-ship-receipt | 2 +- test/ruled-stop.test.ts | 21 +++++++++++++++++++-- 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/bin/gstack-ship-receipt b/bin/gstack-ship-receipt index 9665e7d0417..52f9a637a42 100755 --- a/bin/gstack-ship-receipt +++ b/bin/gstack-ship-receipt @@ -1185,7 +1185,7 @@ function ruledStopException(rest: string[], repoRoot: string, bodyText: string | const since = spawnSync('git', ['diff', '--name-only', r.stop!.head, 'HEAD', '--'], { cwd: repoRoot, encoding: 'utf8', timeout: 30_000 }); const base = flag(rest, '--base') ?? resolveBaseBranch(repoRoot); const load = loadPolicyFromBase(repoRoot, base); - const release = new Set((require('../lib/ship-bin-common') as typeof import('../lib/ship-bin-common')).releasePaths(isUnavailable(load) ? null : load.policy, repoRoot, r.stop!.head, base)); + const release = new Set((require('../lib/ship-bin-common') as typeof import('../lib/ship-bin-common')).releasePaths(isUnavailable(load) ? null : load.policy, repoRoot, r.stop!.head, base, true)); const { classifyPath } = require('../lib/review-depth') as typeof import('../lib/review-depth'); const moved = since.status !== 0 ? ['(git diff failed)'] : since.stdout.split('\n').filter(p => p && !/^(changelog\.d|docs)\//.test(p) && !release.has(p) && classifyPath(p, repoRoot) !== 'docs'); if (moved.length) return `--ruled-stop: ${moved.slice(0, 5).join(', ')} changed since the ruled stop at ${r.stop!.head.slice(0, 12)}: the rulings cover that commit, and only release metadata and docs may change after it`; diff --git a/test/ruled-stop.test.ts b/test/ruled-stop.test.ts index b59d51b5af9..278e6c9ad23 100644 --- a/test/ruled-stop.test.ts +++ b/test/ruled-stop.test.ts @@ -114,8 +114,8 @@ describe('the stop ruling row (lib/ruled-notes.ts)', () => { }); /** A fixture at the stop head S: run r2's round-2 review row with one open blocker, its ledger, and a body with the stop record. */ -function ruledRepo(o: { priorFull?: number; passes?: number } = {}) { - const f = shipFixture({ 'src/x.ts': 'export const x = 1;\n' }, { 'src/x.ts': 'export const x = 2;\n' }); +function ruledRepo(o: { priorFull?: number; passes?: number; base?: Record } = {}) { + const f = shipFixture({ 'src/x.ts': 'export const x = 1;\n', ...o.base }, { 'src/x.ts': 'export const x = 2;\n' }); fxs.push(f); const run = (bin: string, args: string[]) => f.run(path.join(BIN, bin), args, { GSTACK_APPROVALS_MIRROR: '0' }); const s = f.git('rev-parse', 'HEAD').stdout.trim(); @@ -232,4 +232,21 @@ describe('the ruled-stop check and the receipt that takes it (gstack-ship-receip expect(garbage.status).toBe(2); expect(garbage.stderr).toContain('--since garbage is not a timestamp'); }); + + // Value: protects=GST-2273: a file the base policy stamps with the version is gate code, so a logic change to it after the + // ruled stop is refused like any code; fails_when=the release allow-list takes the policy's stamp_paths as whole files; + // seam=gstack-ship-receipt write --ruled-stop + test('D5b: a logic change to a stamp_paths file after the ruled stop is refused', () => { + const policy = { stamp_paths: ['lib/policy.ts'], stamp_patterns: ["_KEY_VERSION = '{version}'"] }; + const r = ruledRepo({ base: { '.gstack/ship-policy.json': JSON.stringify(policy) + '\n', 'lib/policy.ts': "export const P_KEY_VERSION = '1.0.0.0';\nexport const gate = true;\n" } }); + expect(r.rule(ID).status).toBe(0); + const closed = r.ruled(); + expect(closed.status, closed.stderr).toBe(0); + const e = r.exception('second_pass'); + withLines(r.body, [notesOf(closed.stdout)[0]!, reviewLoopExceptionLine(e as never)]); + r.f.write({ 'lib/policy.ts': "export const P_KEY_VERSION = '1.0.0.0';\nexport const gate = false;\n" }); r.f.commit('turn the gate off'); + const out = r.write(e, { passes: 2, blocking_found: 1, deferred: 0, scope: 'frozen' }); + expect(out.status, out.stderr).toBe(1); + expect(out.stderr).toContain('lib/policy.ts changed since the ruled stop'); + }); });