Use Garry Tan's exact Claude Code setup: 23 opinionated tools that serve as CEO, Designer, Eng Manager, Release Manager, Doc Engineer, and QA
TypeScript
/gstack-ship keeps settled review findings closed, and a missing run folder no longer costs a docs-audit attempt (GST-4111) (#4875)
Garry Tan44df37961bda
diff --git a/bin/gstack-docs-candidate b/bin/gstack-docs-candidateindex 2013dec65..d7f4ffcb1 100755--- a/bin/gstack-docs-candidate+++ b/bin/gstack-docs-candidate@@ -28,6 +28,9 @@* or already contains it while the branch has commits its real base lacks is* refused (BASE_CONTAINS_HEAD, lib/default-base.ts): it would select nothing.* --run names the /ship invocation (its record's path) and is saved as run_id.+ * An --out folder that does not exist yet (the run folder, not created) refuses+ * before anything is read (DOCS_RUN_FOLDER_MISSING): no audit ran, so it spends+ * no attempt. --run is only the run's name, so it is never checked on disk.* --pre <Prepare snapshot> marks a post snapshot: it must be this audit's* (same audit id, HEAD and run) and the record saves `edited`, each path whose* content the audit changed with its content before (the Prepare hash, else@@ -250,6 +253,7 @@ function main(argv: string[]): void {const known = new Set(['--out', '--audit-id', '--mode', '--base', '--select', '--docs', '--exception', '--run', '--pre', '--carry', '--carry-stopped']);for (let i = 0; i < args.length; i += 2) if (!known.has(args[i]!)) throw new Error(`unknown argument: ${args[i]}`);const out = path.resolve(one(args, '--out'));+ if (!fs.statSync(path.dirname(out), { throwIfNoEntry: false })?.isDirectory()) throw new Error(resultLine('snapshot', 'DOCS_RUN_FOLDER_MISSING', `${path.dirname(out)} does not exist yet; this Prepare snapshot read nothing and launched no audit, so it spends no attempt`));const top = fs.realpathSync(git(['rev-parse', '--show-toplevel']).trim());if (out === top || out.startsWith(top + path.sep)) throw new Error('--out must be outside the repository');const mode = one(args, '--mode');diff --git a/bin/gstack-doctor-components.sh b/bin/gstack-doctor-components.shindex 9fca97bfa..a8925c04c 100644--- a/bin/gstack-doctor-components.sh+++ b/bin/gstack-doctor-components.sh@@ -347,6 +347,7 @@ gstack_result_anchor() {RECEIPT_DOCS_AUDIT_READ) printf '%s' 'receipt-docs-audit-read' ;;DOCS_AUDIT_BLOCKED) printf '%s' 'docs-audit-blocked' ;;DOCS_RESULT_INVALID) printf '%s' 'docs-result-invalid' ;;+ DOCS_RUN_FOLDER_MISSING) printf '%s' 'docs-run-folder-missing' ;;RECEIPT_PROSE_MISMATCH) printf '%s' 'receipt-prose-mismatch' ;;RECEIPT_CARRY_PREGATE_STALE) printf '%s' 'receipt-carry-pregate-stale' ;;RECEIPT_GIT_TOO_OLD) printf '%s' 'receipt-git-too-old' ;;diff --git a/bin/gstack-ship-receipt b/bin/gstack-ship-receiptindex 482a7ac35..326944111 100755--- a/bin/gstack-ship-receipt+++ b/bin/gstack-ship-receipt@@ -63,7 +63,7 @@ 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 { bodyLineText, bodyListsLine, INTERNAL_ID, keepsInternalIds, publicRuledNote, readRuledNotes, redactInternalIds, RELAYED_REF, repoRuledNotes, ruledNoteText } from '../lib/ruled-notes';+import { bodyLineText, bodyListsLine, INTERNAL_ID, keepsInternalIds, publicRuledNote, readRuledNotes, redactInternalIds, RELAYED_REF, repoRuledNotes, ruledNoteText, shiftedRulings } from '../lib/ruled-notes';import { renderMode, repoVisibility } from '../lib/approval-record';import { appliedGateDispositions, gateDispositionText, publicGateDisposition } from '../lib/gate-dispositions';import { securityFingerprints } from '../lib/security-findings';@@ -377,14 +377,20 @@ async function cmdWrite(rest: string[], json: boolean): Promise<number> {const loopRaw = jsonArg(flag(rest, '--review-loop'));const reviewLoop = loopRaw ? parseReviewLoop(loopRaw) : undefined;if (loopRaw && !reviewLoop) throw new Error('--review-loop needs integer passes, blocking_found and deferred (gstack-review-scope summary --out <file>, then @<file>)');- const ruledOpen = unruledOpenBlockers(loopRaw, ruledNotes, ruledHead => spawnSync('git', ['merge-base', '--is-ancestor', ruledHead, headSha ?? head], { cwd: repoRoot, timeout: 30_000 }).status === 0);+ const onHead = (ruledHead: string) => spawnSync('git', ['merge-base', '--is-ancestor', ruledHead, headSha ?? head], { cwd: repoRoot, timeout: 30_000 }).status === 0;+ const loopOpen: unknown[] = Array.isArray(loopRaw?.open) ? loopRaw.open : [];+ const rows = loopOpen.length && unruledOpenBlockers(loopRaw, ruledNotes, onHead).length ? reviewRows(repoRoot) ?? [] : [];+ const shifted = rows.length && ruledNotes.length ? shiftedRulings(repoRoot, loopOpen, rows, ruledNotes, onHead) : [];+ for (const s of shifted) process.stderr.write(s.line + '\n');+ const ruledOpen = unruledOpenBlockers(loopRaw, [...ruledNotes, ...shifted], onHead);const at = headSha ?? head, baseRef = `origin/${base.replace(/^origin\//, '')}`, run = flag(rest, '--run'), pr = Number(flag(rest, '--pr'));- const blockers = (Array.isArray(loopRaw?.open) ? loopRaw.open : []).filter((b: any) => ruledOpen.includes(typeof b === 'string' ? b : b?.id));- const rows = ruledOpen.length ? reviewRows(repoRoot) ?? [] : [];+ const blockers = loopOpen.filter((b: any) => ruledOpen.includes(typeof b === 'string' ? b : b?.id)) as Array<string | { id: string; fingerprint: string }>;const clearing = ruledOpen.length ? await import('../lib/review-trailer-clearing') : undefined;const byTrailer = clearing ? clearing.clearByTrailer(repoRoot, { head: at, baseRef, rows, open: blockers }) : [];for (const t of byTrailer) process.stderr.write(`TRAILER_CLEAR: ${t.id} (fixed by ${t.commit.slice(0, 12)}, read clean by the full review at ${t.review.slice(0, 12)})\n`);- const open = ruledOpen.filter(id => !byTrailer.some(t => t.id === id));+ const byReview = clearing ? clearing.clearByReview(repoRoot, { head: at, baseRef, rows, open: blockers.filter(b => !byTrailer.some(t => t.id === (typeof b === 'string' ? b : b.id))) }) : [];+ for (const t of byReview) process.stderr.write(`REVIEW_CLEAR: ${t.id} (fixed by ${t.commit.slice(0, 12)}, which changed its file after it was raised and carries no Review-Finding trailer; read clean by the full review at ${t.review.slice(0, 12)})\n`);+ const open = ruledOpen.filter(id => !byTrailer.some(t => t.id === id) && !byReview.some(t => t.id === id));if (open.length) { process.stderr.write(resultLineWithDocs('gstack-ship-receipt write', 'RECEIPT_BLOCKER_OPEN', `${open.join(', ')}; nothing written`) + '\n'); return EXIT.refused; }input = {schema_version: 1, pr: flag(rest, '--pr') !== undefined ? Number(flag(rest, '--pr')) : undefined, head,@@ -398,7 +404,7 @@ async function cmdWrite(rest: string[], json: boolean): Promise<number> {policy: flag(rest, '--policy') ?? tree?.policy, queue_mode: flag(rest, '--queue-mode'), preregistration: flag(rest, '--preregistration'), history: flag(rest, '--history'),...pregate, issues: issuesFile ? receiptIssuesFrom(issuesFile) : undefined, approval: approval.kind === 'ok' ? approval.approval : undefined,review_loop: reviewLoop, ...(docs?.ok ? { docs: docs.docs } : {}), ...product,- gstack_version: installedGstackVersion(), review_depth: reviewDepth, cleared_by_trailer: byTrailer.length ? byTrailer : undefined, ruled_notes: ruledNotes.length ? ruledNotes.map(publicRuledNote) : undefined, gate_dispositions: gateDispositions.map(publicGateDisposition), mechanical: mechanical.length ? mechanical : undefined, review_targeted: targeted?.ok ? targeted.targeted : undefined,+ gstack_version: installedGstackVersion(), review_depth: reviewDepth, cleared_by_trailer: byTrailer.length ? byTrailer : undefined, cleared_by_review: byReview.length ? byReview : undefined, ruled_notes: ruledNotes.length ? ruledNotes.map(publicRuledNote) : undefined, gate_dispositions: gateDispositions.map(publicGateDisposition), mechanical: mechanical.length ? mechanical : undefined, review_targeted: targeted?.ok ? targeted.targeted : undefined,design: review.frontend ? { mode: 'static', reason: 'no preview declared' } : undefined,base_red: pause ? receiptBaseRed(pause) : undefined,review_exclude: receiptExclude(review.exclude),@@ -434,7 +440,8 @@ async function cmdWrite(rest: string[], json: boolean): Promise<number> {return EXIT.fail;}const block = renderReceiptBlock(receipt);- const closed = [...(receipt.cleared_by_trailer ?? []).map(t => `Closed by fix ${t.commit.slice(0, 12)}: ${t.id} (a later full review at ${t.review.slice(0, 12)} read it clean)`)];+ const closed = [...(receipt.cleared_by_trailer ?? []).map(t => `Closed by fix ${t.commit.slice(0, 12)}: ${t.id} (a later full review at ${t.review.slice(0, 12)} read it clean)`),+ ...(receipt.cleared_by_review ?? []).map(t => `Closed by fix ${t.commit.slice(0, 12)}: ${t.id} (no Review-Finding trailer; it changed the finding's file after it was raised, and a later full review at ${t.review.slice(0, 12)} read it clean)`)];if (body) {let text = fs.existsSync(body) ? fs.readFileSync(body, 'utf8') : '';const pr = flag(rest, '--pr');diff --git a/changelog.d/fix-ship-review-closures-and-docs-attempts.md b/changelog.d/fix-ship-review-closures-and-docs-attempts.mdnew file mode 100644index 000000000..78a7efd2e--- /dev/null+++ b/changelog.d/fix-ship-review-closures-and-docs-attempts.md@@ -0,0 +1 @@+**`/gstack-ship` stops reopening findings that were already settled, and a missing run folder no longer costs a docs-audit attempt.** A finding the owner ruled as a note stays ruled when edits above it move its line (the ruled line itself unchanged); a different finding in the same file, or the same line after its text changed, still needs its own ruling. A blocker fixed in a commit with no `Review-Finding` trailer now closes when that commit changed the finding's own line after it was raised and a later full review, the read-only final review included, read the whole branch clean. Lines under a reviewer's "What I checked and found sound" list no longer count as blocking findings unless written as one, such as a line tagged "(Critical)"; a heading that only mentions a sound phrase still counts every finding under it. The docs audit's snapshot refuses up front with `DOCS_RUN_FOLDER_MISSING` when its run folder does not exist yet, so that setup mistake spends neither of the step's two attempts.diff --git a/docs/review-policy.md b/docs/review-policy.mdindex c6c24aa69..4733d254c 100644--- a/docs/review-policy.md+++ b/docs/review-policy.md@@ -209,6 +209,17 @@ nothing open at all, by its status, its findings file or an inline findingfingerprint, with or without its line, never closes by trailer, so no closureline puts its location in the PR body.+A fix commit with no trailer closes its finding the same way (`cleared_by_review`,+GSKI-1 #4) when that commit changed the finding's own line after every review-log+row that holds the finding open (the `path:line:category` line does not map+unchanged through it), and a later complete full review that read the whole PR+(a pass 1 or the read-only final review, never a repeat round that read only its+range) read it clean. This never closes a finding with no line in its fingerprint,+a finding whose raising row has no commit, a gate or security finding, a commit+that changed only other lines of the file, a change made only before the finding+was raised, or one a later round left open, so a real blocker the lane never+touched stays open. Write prints `REVIEW_CLEAR:` and the PR body says the fix had no trailer.+<a id="one-grant-path"></a>**A ruling at the cap needs no grant.** The Captain rules a blocker a note with`gstack-approvals rule` ([ruled notes](ship-policy.md#ruled-notes)); a ruled@@ -862,7 +873,7 @@ puts in the receipt:| `review_loop.passes` | full review passes this ship ran (1 or 2; up to 3 under `review_scope: diff-plus-blocking` or `all`) || `review_loop.blocking_found` | every blocker found (GST-951): the rows' blocking findings (classified, or an unclassified CRITICAL), plus each ledger CRITICAL (as collected or judged) that no row finding from the same reviewer at the same path:line accounts for (each row finding pairs with one per ledger), so an adversarial, outside-voice or not-yet-classified blocker counts and one whose newest classification is below the floor does not. An unreadable ledger, merged file or judged set, or a judged set changed since `judge`, is `REVIEW_SCOPE_LEDGER`, never a count || `review_loop.unrecorded` | blockers found that no row gives a disposition (fixed, deferred, noted, skipped, a gate answer); absent when 0 |-| `review_loop.open` | blockers a row still holds as `open` at its newest action, gate findings aside (GST-3075), each its ledger id or fingerprint (or `{ id, fingerprint }`); Step 11's `adversarial-review` row counts here like a pass's row but is never a pass or a round. Only a later row's action clears one, or a [trailer-carrying fix](#what-closes-a-finding) (`cleared_by_trailer`; a receipt written before fix-check grants were removed may still hold `cleared_by_grant`), and while any is left with no owner ruling, `gstack-ship-receipt write` refuses with [`RECEIPT_BLOCKER_OPEN`](troubleshooting.md#receipt-blocker-open); absent when 0 |+| `review_loop.open` | blockers a row still holds as `open` at its newest action, gate findings aside (GST-3075), each its ledger id or fingerprint (or `{ id, fingerprint }`); Step 11's `adversarial-review` row counts here like a pass's row but is never a pass or a round. Only a later row's action clears one, or a [trailer-carrying fix](#what-closes-a-finding) (`cleared_by_trailer`), or a trailerless fix that changed the finding's own line (`cleared_by_review`), each read clean by a later full review (a receipt written before fix-check grants were removed may still hold `cleared_by_grant`), and while any is left with no owner ruling, `gstack-ship-receipt write` refuses with [`RECEIPT_BLOCKER_OPEN`](troubleshooting.md#receipt-blocker-open); absent when 0 || `review_loop.unbound` | what could not bind (GST-1168), each printed as `REVIEW_SCOPE_UNBOUND: <what>: <why>`: a row with no start token and no readable time, a `pN` ledger with no review row of pass N (a fix-check ledger in a `pN` directory is not a pass ledger, GST-1775), a row finding's `ledger_id` no ledger collected, a `Review-Finding` trailer naming nothing; absent when 0 || `review_loop.ledgers_read` | dispatch ledgers the count read; absent under `--no-ledger` || `REVIEW_SCOPE_VOIDED:` (stderr, not a receipt field) | an abandoned pass (GBEV-3): a `pN` ledger never judged that no row names, replaced by a later `pM` ledger (M > N) that was judged or is named. Its findings are left out of every count above instead of counting as unbound and unrecorded. A fix-check ledger and the last pass are never voided |diff --git a/docs/ship-policy.md b/docs/ship-policy.mdindex 8cde626f8..34b285e91 100644--- a/docs/ship-policy.md+++ b/docs/ship-policy.md@@ -1875,6 +1875,16 @@ with the `gate_id` its gate disposition needs, since a ruling never closes onePre-Landing Review and the PR body, `gstack-ship-receipt write` records them as`ruled_notes` (each with its `head`) and refuses a `--body` that does not carry eachline word for word (bare, or as a `- ` or `* ` list item), and the READY block prints each as `RULED_NOTE:`.+A ruling still covers its finding after edits above it move its line (GSKI-1 #5):+when a later review raises `path:54:voice` and the ruling names `path:43:voice` at+an ancestor head, `gstack-ship-receipt write` maps line 43 through that file's diff+to the commit the later review read, and when the ruled line itself is unchanged and+lands on 54 it counts the open finding ruled and prints `RULED_SHIFT:`;+`gstack-review-read` applies the same match to a row that carries the moved+fingerprint and holds the ruling's head in its range. Another line+in the same file, another voice or category, a ruled line whose text changed, a+renamed or binary file and a security finding never match, so each still needs its+own ruling.Step 11.5 reads the same rulings: `gstack-review-read` applies a ruling to a Step 9or Step 11 row that carries the finding and whose `range_base..commit` holds theruling's head (a first pass, with no `range_base`: its own commit), lists itsdiff --git a/docs/troubleshooting.md b/docs/troubleshooting.mdindex 71238b315..144b9c4e8 100644--- a/docs/troubleshooting.md+++ b/docs/troubleshooting.md@@ -8112,6 +8112,22 @@ remaining re-audit with the printed `RETRY_NOTE:` text appended to its prompt,word for word; it quotes the exact keys. With no attempt left, Step 14.5 stopsand reports this code and the keys it names([ship/sections/documentation.md](../ship/sections/documentation.md)).++<a id="docs-run-folder-missing"></a>+### `DOCS_RUN_FOLDER_MISSING`++**Meaning.** `gstack-docs-candidate snapshot`, /gstack-ship Step 14.5's Prepare+snapshot, was given an `--out` path whose folder does not exist yet,+usually because the /ship run folder (the invocation record's directory) was not+created before the docs audit. It refused before reading the repository or+writing anything, and no audit child was launched, so it spends none of the+step's two attempts (GSKI-1 #13; before, it died with a raw `ENOENT` that lanes+counted as a failed launch).++**Fix.** Create the run folder, or correct the path, and rerun the same+snapshot. Keep the attempt count where it was+([ship/sections/documentation.md](../ship/sections/documentation.md)).+<a id="gstack-pr-wait"></a>## gstack-pr-waitdiff --git a/lib/gate-dispositions.ts b/lib/gate-dispositions.tsindex 1ff8dc553..55be2799c 100644--- a/lib/gate-dispositions.ts+++ b/lib/gate-dispositions.ts@@ -20,7 +20,7 @@ import * as fs from 'node:fs';import { appendRows, locate, readRecord, repoVisibility, type ApprovalRow, type Env, type RecordError, type RepoVisibility, type StoreLocation } from './approval-record';import type { ShipReceipt } from './headless-artifacts';import type { ResultCodeName } from './result-codes';-import { isGstackActor, redactInternalIds, type RuledNote } from './ruled-notes';+import { isGstackActor, redactInternalIds, shiftedFinding, type RuledNote } from './ruled-notes';import { isSecurityFinding, REDACTED_FINDING, REDACTED_REASON, REDACTED_WORDS } from './security-findings';import { openRun, readRunRecord, withGateLock } from './ship-run-record';@@ -208,11 +208,16 @@ export function dispositionedOn(cwd: string, row: Record<string, any>, dispositi/*** The owner's rulings that apply to a review row, as gstack-review-read reads it for Step 11.5 (harness-evals#498, HARN-1): a* ruling for a finding the row carries that is not a gate finding (a ruling never closes one), recorded at a head inside the- * row's range by the same test dispositions use.+ * row's range by the same test dispositions use. A ruling whose line only moved by the row's commit (shiftedFinding, GSKI-1 #5) applies+ * under the fingerprint the row carries, so receipt write and Step 11.5 read the same rulings.*/export function ruledOn(cwd: string, row: Record<string, any>, notes: readonly RuledNote[]): RuledNote[] {const fingerprints = new Set((Array.isArray(row?.findings) ? row.findings : []).flatMap((f: any) => f && !f.gate && typeof f.fingerprint === 'string' ? [f.fingerprint] : []));- const mine = notes.filter(n => fingerprints.has(n.finding));+ const at = typeof row?.commit_full === 'string' && /^[0-9a-f]{40}$/.test(row.commit_full) ? row.commit_full : '';+ const moved = (n: RuledNote) => { const m = at ? /^(.+):[1-9]\d*:([^:\s]+)$/.exec(n.finding) : null;+ const fp = m && [...fingerprints].some(f => f.startsWith(`${m[1]}:`) && f.endsWith(`:${m[2]}`)) ? shiftedFinding(cwd, n.finding, n.head, at) : null;+ return fp && fp !== n.finding && fingerprints.has(fp) ? [{ ...n, finding: fp }] : []; };+ const mine = notes.flatMap(n => (fingerprints.has(n.finding) ? [n] : moved(n)));const holds = mine.length ? rowRange(cwd, row) : null;return holds ? mine.filter(n => holds(n.head)) : [];}diff --git a/lib/headless-artifacts.ts b/lib/headless-artifacts.tsindex 452d9fec5..63404a634 100644--- a/lib/headless-artifacts.ts+++ b/lib/headless-artifacts.ts@@ -128,6 +128,8 @@ export interface ShipReceipt {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 open blockers a Review-Finding trailer's fix closed because a later full round read it clean (clearByTrailer, #4597). */cleared_by_trailer?: Array<{ id: string; commit: string; review: string }>;+ /** The open blockers a fix with no Review-Finding trailer closed: it changed the finding's file after the finding was raised, and a later full round read it clean (clearByReview, GSKI-1 #4). */+ cleared_by_review?: Array<{ id: string; commit: string; review: 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). */ruled_notes?: Array<{ finding: string; head: string; by: string; reason: string; at: string; approval: string; relayed?: string; not_security?: true }>;/** The owner's dispositions of gate findings (gstack-approvals gate, lib/gate-dispositions.ts); the PR body lists each one word for word (GST-2491). */@@ -291,6 +293,7 @@ export const ARTIFACT_SCHEMAS = {// Legacy (GST-3562 part 4): receipts written before fix-check and round grants were removed may carry these; nothing reads them.review_loop_exception: { type: 'object' }, review_round_grants: { type: 'array' }, cleared_by_grant: { type: 'object' },cleared_by_trailer: { type: 'array', items: { type: 'object', required: ['id', 'commit', 'review'], properties: { id: str, commit: str, review: str } } },+ cleared_by_review: { type: 'array', items: { type: 'object', required: ['id', 'commit', 'review'], properties: { id: str, commit: str, review: 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, relayed: str, not_security: { const: true } } } },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 } } },mechanical: strList,diff --git a/lib/result-codes-release.ts b/lib/result-codes-release.tsindex 17d6d038a..77464dd91 100644--- a/lib/result-codes-release.ts+++ b/lib/result-codes-release.ts@@ -490,6 +490,11 @@ export const RELEASE_RESULT_CODES = {summary: 'the documentation audit child\'s last line (/ship Step 14.5) does not meet the result contract: a key is missing, unknown or repeated once whitespace around keys is trimmed, a field has the wrong type or value, or documentation_section is empty or a placeholder; the audit result cannot be used, and this is a malformed reply, not a blocked audit',fix: 'on FORMAT_REPAIR:, re-ask once for the last line with gstack-docs-candidate repair-prompt and check the reply with result --repair-of, which uses no attempt; otherwise run the one remaining re-audit with the RETRY_NOTE: line appended to its prompt verbatim; with no attempt left, Step 14.5 stops with this code and the keys it names',},+ DOCS_RUN_FOLDER_MISSING: {+ anchor: 'docs-run-folder-missing',+ summary: 'the documentation audit\'s Prepare snapshot (/ship Step 14.5) writes its --out record into a folder (the /ship run folder) that does not exist yet, so it refused before reading anything; no audit was launched, so this spends none of the step\'s two attempts',+ fix: 'create the /ship run folder (the invocation record\'s directory) or correct the path, then rerun the same snapshot; do not count it as an attempt',+ },RECEIPT_PROSE_MISMATCH: {anchor: 'receipt-prose-mismatch',summary: 'the PR body quotes a counter the ship receipt also records (review passes, deferred findings, gate case counts) with a different number, so the prose and the receipt disagree about the same run',diff --git a/lib/review-ledger.ts b/lib/review-ledger.tsindex 9a192f818..658bff94f 100644--- a/lib/review-ledger.ts+++ b/lib/review-ledger.ts@@ -58,6 +58,19 @@ const ANY_LABEL = new RegExp(`(?<![A-Za-z0-9])(${LABELS})(?![A-Za-z0-9])`);/** A heading that is only a label ("## High", "**Critical findings**") gives its label to the top-level list items under it, until the next heading or bold-only line. */const LABEL_HEADING = new RegExp(`^(?:#{1,6}\\s*|\\*\\*)(${LABELS})(?:\\s+(?:findings?|severity|issues?))?\\s*:?\\**\\s*$`);const HEADING = /^(?:#{1,6}\s|\*\*[^*]+\*\*:?$)/;+/**+ * A heading over what the reader checked and found sound ("## What I checked and found sound", "### What holds up", "**Verified:**",+ * GSTA-830 #4800): the whole heading is the title and nothing else, so "## Summary: … found sound", "## Strengths and one critical problem"+ * and "What I verified" alone never are (p3/red-team#2 on #4875). Its bullet items and their indented lines are not findings unless shaped+ * as one (a lead label, a delimited severity tag such as "(Critical)", "[High]", "**Low**" or "High:", a Severity or Blocks field,+ * Blocks: yes, JSON), so "- The Critical path in a.ts:42 handles it" never blocks. Any other line (a heading, a numbered+ * item, a bold finding lead, a paragraph) ends the section, so a finding after it still collects. A skipped bullet stays the context of+ * a Severity or Blocks field line after it, which collects with that bullet's text. A "Summary" heading is not one: its+ * lines may be the only copy of a finding. "Verified issues" and "Looks good except" headings keep collecting.+ */+const SOUND_HEADING = /^(?:#{1,6}\s*|\*\*\s*)(?:(?:what (?:else )?(?:i |we )?)?(?:checked|verified|read) and (?:found )?(?:sound|clean|correct|fine|no (?:defects?|issues?|problems?)(?: in)?)|(?:everything (?:else )?)?found (?:sound|clean|correct|fine)|what (?:holds|held) up|verified|(?:what )?looks? (?:good|sound|correct|fine)|strengths|no (?:issues|problems|findings) found)\s*[:.]?\s*(?:\*\*)?\s*[:.]?\s*$/i;+/** A severity label set off as a tag ("(Critical)", "[High]", "**Low**", "High:"), unlike the bare word in "the Critical path". */+const SEVERITY_TAG = new RegExp(`[([]\\s*(?:${LABELS})\\s*[,)\\]]|\\*\\*\\s*(?:${LABELS})\\s*\\*\\*|(?<![A-Za-z0-9])(?:${LABELS})\\s*:`);const LIST_ITEM = /^(?:[-*+]|\d+[.)])\s+\S/;/** A numbered finding heading ("**1. …**", "### 2) …", GST-1031) or a finding lead that names its number ("**Finding 1 (FIXABLE): …**", GST-1657). */const NUMBERED_HEAD = /^(?:#{1,6}\s+|\*\*\s*)(?:\d+[.)]\s|Finding\s+\d+\b)/;@@ -211,6 +224,7 @@ function parseLabelled(reader: string, output: string, fixableRaises: boolean):type Finding = { label: string; raw: string; fields: Set<string>; list: boolean; lead?: string; fixable?: boolean; heading?: boolean; item?: boolean; nested?: boolean; closed?: boolean; section?: boolean; context?: string };const out: Finding[] = [];let section: string | null = null;+ let sound = false;let current: Finding | null = null;let head = '';let gap = false;@@ -263,7 +277,10 @@ function parseLabelled(reader: string, output: string, fixableRaises: boolean):continue;}const heading = LABEL_HEADING.exec(t);- if (heading) { section = fixableRaises ? named(heading[1]!) : heading[1]!; current = null; head = ''; continue; }+ if (heading) { section = fixableRaises ? named(heading[1]!) : heading[1]!; sound = false; current = null; head = ''; continue; }+ if (!indented && HEADING.test(t) && (sound = SOUND_HEADING.test(t))) { section = null; current = null; head = ''; continue; }+ if (sound && !indented && !/^[-*+]\s/.test(t)) sound = false;+ if (sound && !(LEAD_LABEL.test(t) || SEVERITY_TAG.test(t) || !!t.match(STATED_SEVERITY) || BLOCKS_YES.test(t) || t.startsWith('{'))) { current = null; head = t; continue; }const field = fieldOf(t);if (!afterGap && current?.heading && !current.fields.size && (field !== undefined || t.match(BLOCKS_FIELD)) && !ANY_LABEL.test(t.replace(SEVERITY_FIELD, ' '))&& !LIST_ITEM.test(t) && !LOCUS.test(t) && !HEADING.test(t) && !NUMBERED_HEAD.test(t) && !t.startsWith('{')diff --git a/lib/review-trailer-clearing.ts b/lib/review-trailer-clearing.tsindex cf8a3f0e9..2c8f88e42 100644--- a/lib/review-trailer-clearing.ts+++ b/lib/review-trailer-clearing.ts@@ -1,12 +1,14 @@/*** review-trailer-clearing: when an open blocker closes without an owner ruling (#4597, docs/review-policy.md#what-closes-a-finding).- * A fix commit carries the finding's Review-Finding trailer and a later complete full review of the branch read it clean;- * gstack-ship-receipt write closes exactly those blockers through clearByTrailer and records them as cleared_by_trailer. Every+ * A later complete full review of the branch read it clean after a fix commit that either carries the finding's Review-Finding trailer+ * (clearByTrailer, cleared_by_trailer) or, with no trailer, changed the finding's file after the finding was raised (clearByReview,+ * cleared_by_review, GSKI-1 #4); gstack-ship-receipt write closes exactly those blockers and records them. Every* input is a record gstack's tools wrote (the review log and the branch's commits); the agent's --review-loop file only lists* which blockers are open. The granted fix-check route that shared this module was removed in GST-3562 part 4.*/import { spawnSync } from './spawn-sync';import { parseFixTrailers, rowTime } from './review-scope';+import { traceFinding } from './ruled-notes';import { isSecurityFinding } from './security-findings';type Row = Record<string, any>;@@ -24,27 +26,69 @@ const treeOf = (cwd: string, c: string) => git(cwd, ['rev-parse', '--verify', '-const findingsOf = (r: Row): Row[] => (Array.isArray(r?.findings) ? r.findings.filter((f: unknown) => !!f && typeof f === 'object') : []);const nameOf = (b: OpenBlocker) => (typeof b === 'string' ? b : b.id);+/**+ * The later complete full review that read `fix` clean: a `review` row of /ship (not a fix-range or scoped repeat) that started after+ * `after`, finished and converged, bound to its own committed tree on this branch with `fix` inside its range and its commit, and+ * left nothing open (its status, findings_open from a findings file, an inline open finding). `whole` also requires it to have read+ * the whole PR (`range_base` null: a pass 1 or the read-only final review), not only a repeat round's range.+ */+function cleanReviewOf(cwd: string, rows: readonly Row[], after: number, fix: string, head: string, whole = false): Row | undefined {+ const inRange = (from: unknown) => from == null || (typeof from === 'string' && (b => !!b && !ancestor(cwd, fix, b))(git(cwd, ['rev-parse', '--verify', '--quiet', `${from}^{commit}`])?.trim()));+ return rows.find(r => r?.skill === 'review' && r.via === 'ship' && r.completed === true && r.scope !== 'fix-range' && r.scope !== 'scoped' && rowTime(r) > after && (!whole || r.range_base == null)+ && r.converged === true && r.review_binding?.state === 'verified' && inRange(r.range_base) && typeof r.tree === 'string' && r.review_binding.start_wtree === r.tree && r.review_binding.end_wtree === r.tree+ && SHA.test(String(r.commit_full)) && treeOf(cwd, r.commit_full) === r.tree && ancestor(cwd, fix, r.commit_full) && ancestor(cwd, r.commit_full, head)+ && r.status !== 'issues_found' && r.status !== 'issues_open' && Number(r.findings_open ?? 0) === 0 && !findingsOf(r).some(f => f.action === 'open'));+}++/** The rows that hold blocker `b` open, each with its finding. */+const raisedBy = (rows: readonly Row[], b: OpenBlocker) => {+ const id = nameOf(b), fp = typeof b === 'string' ? b : b.fingerprint;+ return rows.flatMap(r => findingsOf(r).filter(f => f.action === 'open' && (f.ledger_id === id || (f.ledger_id === undefined && f.fingerprint === fp))).map(f => ({ r, f })));+};+/*** The #4597 route: an open blocker closes when a branch commit carries its Review-Finding trailer (its exact ledger id, or its- * fingerprint when no other open blocker shares it) and a later complete full review, bound to its own committed tree on this- * branch and holding that commit in its range, left nothing open (its status, findings_open from a findings file, an inline open- * finding). Gate findings never close this way.+ * fingerprint when no other open blocker shares it) and a later complete full review (cleanReviewOf) holding that commit read it+ * clean. Gate findings never close this way.*/export function clearByTrailer(cwd: string, o: { head: string; baseRef: string; rows: readonly Row[]; open: readonly OpenBlocker[] }): TrailerClearing[] {const log = git(cwd, ['log', '--no-merges', '--format=%H%x00%(trailers:key=Review-Finding,valueonly,separator=%x1f)%x1e', `${o.baseRef}..${o.head}`]);const trailers = (log ?? '').split('\x1e').flatMap(rec => { const [sha, values] = rec.trim().split('\0'); return sha && values ? parseFixTrailers(sha, values.split('\x1f').map(v => v.trim()).filter(Boolean)) : []; });return o.open.flatMap(b => {const id = nameOf(b), fp = typeof b === 'string' ? b : b.fingerprint;- const raised = o.rows.flatMap(r => findingsOf(r).filter(f => f.action === 'open' && (f.ledger_id === id || (f.ledger_id === undefined && f.fingerprint === fp))).map(f => ({ r, f })));+ const raised = raisedBy(o.rows, b);const alone = o.open.filter(c => (typeof c === 'string' ? c : c.fingerprint) === fp).length === 1;const t = trailers.find(x => x.finding === id || (alone && x.finding === fp));if (!t || !raised.length || raised.some(x => x.f.gate !== undefined) || isSecurityFinding(t.finding)) return [];- const after = Math.max(...raised.map(x => rowTime(x.r)));- const inRange = (from: unknown, fix: string) => from == null || (typeof from === 'string' && (b => !!b && !ancestor(cwd, fix, b))(git(cwd, ['rev-parse', '--verify', '--quiet', `${from}^{commit}`])?.trim()));- const review = o.rows.find(r => r?.skill === 'review' && r.via === 'ship' && r.completed === true && r.scope !== 'fix-range' && r.scope !== 'scoped' && rowTime(r) > after- && r.converged === true && r.review_binding?.state === 'verified' && inRange(r.range_base, t.commit) && typeof r.tree === 'string' && r.review_binding.start_wtree === r.tree && r.review_binding.end_wtree === r.tree- && SHA.test(String(r.commit_full)) && treeOf(cwd, r.commit_full) === r.tree && ancestor(cwd, t.commit, r.commit_full) && ancestor(cwd, r.commit_full, o.head)- && r.status !== 'issues_found' && r.status !== 'issues_open' && Number(r.findings_open ?? 0) === 0 && !findingsOf(r).some(f => f.action === 'open'));+ const review = cleanReviewOf(cwd, o.rows, Math.max(...raised.map(x => rowTime(x.r))), t.commit, o.head);return review ? [{ id, commit: t.commit, review: review.commit_full as string }] : [];});}++/**+ * The GSKI-1 #4 route, for a fix commit with no trailer: an open blocker closes when a commit made after every row that holds it open+ * (not an ancestor of any of their commits) changed the finding's own line (its `path:line:category` fingerprint does not map unchanged+ * through that commit: traceFinding returns 'changed', never for a binary file or a git error), and a later complete full review that read the whole PR (cleanReviewOf with `whole`: a pass 1 or+ * the read-only final review, never a repeat round that read only its range) holding that commit read it clean. The invariant that keeps a+ * real blocker open: a finding with no line, a raising row with no commit or another fingerprint under the same ledger id (ids restart per+ * /ship run), a gate or security-class finding, a commit that left the finding's line as it was, a change made only before it was raised,+ * a review of only a range, and a later round that left anything open never close.+ */+export function clearByReview(cwd: string, o: { head: string; baseRef: string; rows: readonly Row[]; open: readonly OpenBlocker[] }): TrailerClearing[] {+ return o.open.flatMap(b => {+ const id = nameOf(b), fp = typeof b === 'string' ? b : b.fingerprint;+ const raised = raisedBy(o.rows, b).filter(x => x.f.fingerprint === fp);+ const m = /^(.+):[1-9]\d*:[^:\s]+$/.exec(fp);+ if (!m || !raised.length || raised.some(x => x.f.gate !== undefined || isSecurityFinding(x.f)) || isSecurityFinding(fp) || isSecurityFinding(id)) return [];+ const at = raised.map(x => String(x.r.commit_full));+ if (!at.every(c => SHA.test(c))) return [];+ const newest = raised.reduce((a, x) => (rowTime(x.r) >= rowTime(a.r) ? x : a)).r.commit_full as string;+ const after = Math.max(...raised.map(x => rowTime(x.r)));+ const touched = (git(cwd, ['--literal-pathspecs', 'log', '--no-merges', '--format=%H', `${o.baseRef}..${o.head}`, '--', m[1]!]) ?? '').split('\n').map(c => c.trim()).filter(c => SHA.test(c));+ for (const fix of touched.filter(c => at.every(a => !ancestor(cwd, c, a)) && ancestor(cwd, newest, c) && traceFinding(cwd, fp, newest, c) === 'changed')) {+ const review = cleanReviewOf(cwd, o.rows, after, fix, o.head, true);+ if (review) return [{ id, commit: fix, review: review.commit_full as string }];+ }+ return [];+ });+}diff --git a/lib/ruled-notes.ts b/lib/ruled-notes.tsindex 999509e15..52e4a4f43 100644--- a/lib/ruled-notes.ts+++ b/lib/ruled-notes.ts@@ -146,3 +146,62 @@ export function ruledEdits(cwd: string, paths: readonly string[], now: string, e}return { ruled, refused };}++/**+ * A ruled finding after its line moved (GST-4111, GSKI-1 #5): `finding`, a `path:line:category` fingerprint ruled at `from`, as the+ * fingerprint of the same line at `to`, where a later review raised it again. It maps only when `from` is `to` or an ancestor of it+ * and the diff between them on that one path leaves the ruled line itself untouched, so the line moved only because lines above it were+ * added or removed; the result keeps the identity (path, line, category) an unshifted ruling already matches. A finding with no+ * path:line, a security-class finding, a changed, deleted or renamed line, a binary file or a git failure gives null, so a different+ * finding in the same file, or the same finding on an edited line, still needs its own ruling.+ */+export function shiftedFinding(cwd: string, finding: string, from: string, to: string): string | null {+ const t = traceFinding(cwd, finding, from, to);+ return t === 'changed' ? null : t;+}++/**+ * Where a `path:line:category` finding at `from` sits at `to`: its moved fingerprint; 'changed' only when git shows a commit in between+ * rewrote that line or deleted (or renamed away) its file; null when nothing can be shown (not an ancestor, a security-class finding, a+ * binary file, a git error), so a caller that needs proof of a change fails closed.+ */+export function traceFinding(cwd: string, finding: string, from: string, to: string): string | 'changed' | null {+ const m = /^(.+):([1-9]\d*):([^:\s]+)$/.exec(finding);+ if (!m || isSecurityFinding(finding)) return null;+ const [, file, at, category] = m as unknown as [string, string, string, string];+ const git = (args: string[]) => { const r = spawnSync('git', args, { cwd, encoding: 'utf8', timeout: 60_000, maxBuffer: 64 * 1024 * 1024 }); return r.status === 0 ? String(r.stdout ?? '') : null; };+ if (git(['merge-base', '--is-ancestor', from, to]) === null) return null;+ if (git(['--literal-pathspecs', 'cat-file', '-e', `${to}:${file}`]) === null) {+ const gone = git(['--literal-pathspecs', 'ls-tree', '-r', '--full-tree', '--name-only', to, '--', file]) === '';+ return gone && git(['--literal-pathspecs', 'cat-file', '-e', `${from}:${file}`]) !== null ? 'changed' : null;+ }+ const diff = git(['--literal-pathspecs', '-c', 'core.quotePath=false', 'diff', '--no-color', '--no-ext-diff', '--no-textconv', '--no-renames', '-U0', from, to, '--', file]);+ if (diff === null || /^Binary files /m.test(diff)) return null;+ const line = Number(at);+ let delta = 0;+ for (const h of diff.matchAll(/^@@ -(\d+)(?:,(\d+))? \+\d+(?:,(\d+))? @@/gm)) {+ const start = Number(h[1]), removed = h[2] === undefined ? 1 : Number(h[2]), added = h[3] === undefined ? 1 : Number(h[3]);+ if (removed > 0 && line >= start && line < start + removed) return 'changed';+ if (removed > 0 ? start + removed <= line : start < line) delta += added - removed;+ }+ return `${file}:${line + delta}:${category}`;+}++/**+ * The open blockers a ruling covers after its line moved (shiftedFinding): each open blocker's fingerprint, at the commit of the newest+ * review-log row that holds it open, against every ruling on the same path and category whose head `onHead` accepts. One alias per+ * match, `{ finding: <the open fingerprint>, head: <the ruling's head> }`, for unruledOpenBlockers, with the line write prints.+ */+export function shiftedRulings(cwd: string, open: readonly unknown[], rows: readonly Record<string, any>[], notes: readonly RuledNote[], onHead: (head: string) => boolean): Array<{ finding: string; head: string; line: string }> {+ const out: Array<{ finding: string; head: string; line: string }> = [];+ for (const o of open) {+ const id = typeof o === 'string' ? o : (o as any)?.id, fp = typeof o === 'string' ? o : (o as any)?.fingerprint;+ const m = typeof id === 'string' && typeof fp === 'string' ? /^(.+):[1-9]\d*:([^:\s]+)$/.exec(fp) : null;+ if (!m) continue;+ const raisedAt = rows.filter(r => typeof r?.commit_full === 'string' && /^[0-9a-f]{40}$/.test(r.commit_full) && Array.isArray(r.findings)+ && r.findings.some((f: any) => f && f.action === 'open' && f.fingerprint === fp && (f.ledger_id === id || f.ledger_id === undefined))).at(-1)?.commit_full as string | undefined;+ const note = raisedAt && notes.find(n => n.finding !== fp && n.finding.startsWith(`${m[1]}:`) && n.finding.endsWith(`:${m[2]}`) && onHead(n.head) && shiftedFinding(cwd, n.finding, n.head, raisedAt) === fp);+ if (note) out.push({ finding: fp, head: note.head, line: `RULED_SHIFT: ${id} is ${note.finding} ruled at ${note.head.slice(0, 12)} (approval ${note.approval}); only lines above it changed by ${raisedAt!.slice(0, 12)}, so the ruling covers it` });+ }+ return out;+}diff --git a/lib/ship-receipt.ts b/lib/ship-receipt.tsindex adc9d9a06..1597939f6 100644--- a/lib/ship-receipt.ts+++ b/lib/ship-receipt.ts@@ -54,7 +54,7 @@ const KEY_ORDER: Array<keyof ShipReceipt | 'docs'> = ['schema_version', 'pr', 'head', 'version', 'base', 'gated_tree', 'predecessor', 'tree', 'gate_reuse', 'gate', 'ci', 'ci_carried', 'spend_usd', 'calls','session_kind', 'artifacts_consumed', 'run', 'thread', 'policy', 'queue_mode', 'preregistration', 'history','head_tree', 'product_patch_id', 'gstack_version', 'review_depth', 'pregate', 'requires_remote', 'issues', 'approval', 'docs', 'review_loop',- 'cleared_by_trailer', 'ruled_notes', 'gate_dispositions', 'mechanical', 'review_targeted', 'design', 'review_exclude', 'review_exclude_fallback', 'docs_audit_read', 'carry', 'base_red', 'flaky_exception', 'no_stop',+ 'cleared_by_trailer', 'cleared_by_review', 'ruled_notes', 'gate_dispositions', 'mechanical', 'review_targeted', 'design', 'review_exclude', 'review_exclude_fallback', 'docs_audit_read', 'carry', 'base_red', 'flaky_exception', 'no_stop',];/** Keys in the fixed order so identifiers lead; undefined values are dropped. */diff --git a/ship/sections/documentation.md b/ship/sections/documentation.mdindex 7ea98bcce..f00737c82 100644--- a/ship/sections/documentation.md+++ b/ship/sections/documentation.md@@ -8,6 +8,7 @@ Store-only releases audit `read-only` before distribution, without branch gatesnever a third attempt, even after Step 16 changes. Increment before each launchor inline takeover, including failed launches; inline work follows the samevalidation gates. A stale snapshot is neither a new attempt nor a current audit.+A Prepare `snapshot` that refuses (`DOCS_RUN_FOLDER_MISSING`: its `--out` folder does not exist yet) launched nothing and spends no attempt: create the folder, rerun it.Save each child's output and run `~/.claude/skills/gstack/bin/gstack-docs-candidate attempt <output> --state <record dir>/docs-attempts.json`:`ATTEMPT: not-counted` (its install check refused it before any audit) takes the increment back once; run the install fix, then relaunch.Save the child handle. An exited child with missing output is stopped, but its audit is blocked.diff --git a/ship/sections/documentation.md.tmpl b/ship/sections/documentation.md.tmplindex fc0febc29..cdc01ac69 100644--- a/ship/sections/documentation.md.tmpl+++ b/ship/sections/documentation.md.tmpl@@ -6,6 +6,7 @@ Store-only releases audit `read-only` before distribution, without branch gatesnever a third attempt, even after Step 16 changes. Increment before each launchor inline takeover, including failed launches; inline work follows the samevalidation gates. A stale snapshot is neither a new attempt nor a current audit.+A Prepare `snapshot` that refuses (`DOCS_RUN_FOLDER_MISSING`: its `--out` folder does not exist yet) launched nothing and spends no attempt: create the folder, rerun it.Save each child's output and run `~/.claude/skills/gstack/bin/gstack-docs-candidate attempt <output> --state <record dir>/docs-attempts.json`:`ATTEMPT: not-counted` (its install check refused it before any audit) takes the increment back once; run the install fix, then relaunch.Save the child handle. An exited child with missing output is stopped, but its audit is blocked.diff --git a/test/docs-audit-result.test.ts b/test/docs-audit-result.test.tsindex f79886618..975b9f538 100644--- a/test/docs-audit-result.test.ts+++ b/test/docs-audit-result.test.ts@@ -546,3 +546,48 @@ describe('an earlier blocked line for the same audit carries into the last line'expect(r.stdout).toContain('DOCS_RESULT: ok status=blocked');});});++// Value: protects=a Prepare snapshot whose --out folder does not exist yet (--run is only a name) fails fast with DOCS_RUN_FOLDER_MISSING before+// any audit runs, writes nothing, and says it spends no attempt, so both Step 14.5 attempts stay for real audits (GSKI-1 #13);+// fails_when=snapshot dies with a raw ENOENT after reading the repository, which the lane counted as a failed launch;+// seam=bin/gstack-docs-candidate snapshot and ship/sections/documentation.md's attempt budget+describe('GSKI-1 #13: a missing run folder refuses the snapshot before any attempt', () => {+ test('snapshot into a run folder that does not exist yet refuses, writes nothing, and the same snapshot succeeds once it exists', () => {+ const root = scratch();+ const repo = path.join(root, 'repo');+ const git = (...args: string[]) => spawnSync('git', ['-c', 'user.name=Fixture', '-c', '[email protected]', '-c', 'commit.gpgsign=false', ...args], { cwd: repo, encoding: 'utf8', timeout: 20_000 });+ fs.mkdirSync(repo);+ git('init', '-q', '-b', 'main');+ fs.writeFileSync(path.join(repo, 'README.md'), '# Fx\n');+ git('add', '-A'); git('commit', '-qm', 'base');+ git('checkout', '-qb', 'feat');+ fs.writeFileSync(path.join(repo, 'a.ts'), 'export const a = 1;\n');+ git('add', '-A'); git('commit', '-qm', 'feat');+ const runDir = path.join(root, 'ship-run');+ const snapshot = (args: string[]) => spawnSync(BIN, ['snapshot', '--audit-id', 'docs-1', '--mode', 'read-only', '--base', 'main', ...args], { cwd: repo, encoding: 'utf8', timeout: 20_000 });+ for (const args of [['--out', path.join(runDir, 'docs-1.json'), '--run', path.join(runDir, 'record.md')], ['--out', path.join(runDir, 'docs-1.json')]]) {+ const r = snapshot(args);+ expect(r.status).toBe(1);+ expect(r.stderr).toContain('(DOCS_RUN_FOLDER_MISSING)');+ expect(r.stderr).toContain(runDir);+ expect(r.stderr).toContain('spends no attempt');+ expect(r.stdout).toBe('');+ expect(fs.existsSync(runDir)).toBe(false);+ }+ fs.writeFileSync(runDir, 'a file, not a folder');+ const notDir = snapshot(['--out', path.join(runDir, 'docs-1.json')]);+ expect(notDir.status).toBe(1);+ expect(notDir.stderr).toContain('(DOCS_RUN_FOLDER_MISSING)');+ fs.rmSync(runDir);+ const named = snapshot(['--out', path.join(root, 'named.json'), '--run', path.join(root, 'absent', 'record.md')]);+ expect(named.status, named.stderr).toBe(0);+ expect(JSON.parse(fs.readFileSync(path.join(root, 'named.json'), 'utf8')).run_id).toBe(path.join(root, 'absent', 'record.md'));+ fs.mkdirSync(runDir);+ const ok = snapshot(['--out', path.join(runDir, 'docs-1.json'), '--run', path.join(runDir, 'record.md')]);+ expect(ok.status, ok.stderr).toBe(0);+ expect(fs.readdirSync(runDir)).toEqual(['docs-1.json']);+ const section = fs.readFileSync(path.join(ROOT, 'ship', 'sections', 'documentation.md'), 'utf8');+ expect(section).toContain('`DOCS_RUN_FOLDER_MISSING`');+ expect(section).toMatch(/refuses[^.]*launched nothing[^.]*spends no attempt/);+ });+});diff --git a/test/review-ledger-verdict-line.test.ts b/test/review-ledger-verdict-line.test.tsindex 4f42cc3eb..627d05e25 100644--- a/test/review-ledger-verdict-line.test.ts+++ b/test/review-ledger-verdict-line.test.ts@@ -4,7 +4,7 @@* findings it summarizes, each of which already said "Severity: Low. Blocks: no". Excerpt of that captured output below.*/import { describe, expect, test } from 'bun:test';-import { parseFindings } from '../lib/review-ledger';+import { parseFindings, parseReply } from '../lib/review-ledger';const CAPTURED_3901_P2 = ['REVIEWED_TREE: 7be72149fbd6d1b8e713c7c42ef4cd9ba6373e20 /workspace/gstack',@@ -46,3 +46,51 @@ describe('native verdict line (collector severity inflation)', () => {expect(labels('All FIXABLE, none blocks. Blocks: yes')).toEqual(['CRITICAL']);});});++// Value: protects=lines under a reviewer's "what I checked and found sound" heading never collect as findings unless they are shaped+// as one (GSTA-830 #4800, adversarial-native#5); fails_when=a prose line naming "Critical" and a file:line in that list blocks with+// REVIEW_VERDICT blocking=0 (parsed=2, agrees=false); seam=lib/review-ledger.ts parseReply; no_claim=a "Summary" heading, whose+// lines may restate the only copy of a finding, keeps collecting+describe('GST-4111 fix 4: a sound-checks section is not a findings section', () => {+ const SOUND = ['NO FINDINGS', '', '## What I checked and found sound', '', '- The Critical path in lib/foo.ts:42 handles the empty case.',+ '- Critical branch at lib/bar.ts:9 is covered by test/bar.test.ts.', '', 'REVIEW_VERDICT: blocking=0'].join('\n');+ test('every reader role parses no finding from a sound-checks list and the verdict agrees', () => {+ for (const role of ['specialist', 'red-team', 'adversarial-native', 'outside-voice', 'targeted']) {+ const r = parseReply(role, SOUND, true, true);+ expect(r.findings, role).toEqual([]);+ expect(r.verdict, role).toEqual({ state: 'valid', parsed: 0, declared: 0, agrees: true });+ }+ for (const heading of ['### What holds up', '**Verified:**', '## Checked and found clean', '## Looks good']) {+ expect(parseReply('specialist', SOUND.replace('## What I checked and found sound', heading), true, true).findings, heading).toEqual([]);+ }+ });+ test('negative controls: a labelled finding inside the section, a findings heading after it, and a Summary heading still collect', () => {+ const inside = ['## What I checked and found sound', '', '- The Critical path in lib/foo.ts:42 is fine.', '- CRITICAL: lib/auth.ts:7 skips the token check.', '- lib/q.ts:3 drops rows. Blocks: yes'].join('\n');+ expect(parseReply('specialist', inside).findings.map(f => f.label)).toEqual(['CRITICAL', 'CRITICAL']);+ const after = ['## What I checked and found sound', '', '- The Critical path in lib/foo.ts:42 is fine.', '', '## Findings', '', '- The Critical path in lib/foo.ts:50 drops the lock.'].join('\n');+ expect(parseReply('outside-voice', after).findings.map(f => f.raw)).toEqual(['- The Critical path in lib/foo.ts:50 drops the lock.']);+ const summary = ['## Summary', '', '- The Critical path in lib/foo.ts:42 drops the lock.'].join('\n');+ expect(parseReply('red-team', summary).findings.map(f => f.label)).toEqual(['Critical']);+ const lead = ['**What holds up.**', '', '- The Critical path in lib/foo.ts:42 is fine.', '', '**Finding 1 (FIXABLE): the lock in lib/foo.ts:50 is never released.** It leaks.', '1. CRITICAL lib/foo.ts:60 drops rows'].join('\n');+ expect(parseReply('adversarial-native', lead).findings.map(f => f.raw.slice(0, 13))).toEqual(['**Finding 1 (', '1. CRITICAL l']);+ const broken = ['## What I verified was broken', '', '- Dropped writes at lib/cache.ts:42 when the queue fills.', ' Severity: High', ' Blocks: yes'].join('\n');+ expect(parseReply('outside-voice', broken).findings.map(f => f.raw)).toEqual([expect.stringContaining('lib/cache.ts:42')]);+ expect(parseReply('specialist', ['## What I verified', '', '- src/a.ts:42 null deref crashes the worker on empty input (High)'].join('\n')).findings.map(f => f.label)).toEqual(['High']);+ const fielded = ['## What I checked and found sound', '', '- Dropped writes at lib/cache.ts:42 when the queue fills.', 'Severity: High', 'Blocks: yes'].join('\n');+ expect(parseReply('specialist', fielded).findings.map(f => f.raw)).toEqual([expect.stringContaining('lib/cache.ts:42')]);+ expect(parseReply('specialist', ['## Verified issues', '', '- The Critical path in lib/foo.ts:42 drops the lock.'].join('\n')).findings).toHaveLength(1);+ });+ // Value: protects=a heading that only mentions a sound phrase, or a delimited severity tag on a bullet under a real sound heading,+ // never hides a finding (p3/red-team#2 on #4875: the filter failed open against main); fails_when=parseFindings returns no finding+ // for '## Summary: … found sound' or '## Strengths and one critical problem' followed by a '(Critical)' bullet; seam=parseReply+ test('fails open never: mixed headings and tagged bullets still collect', () => {+ const bullet = '- a.ts:42 swallows the timeout error and the deploy never retries (Critical)';+ for (const heading of ['## Summary: one blocker below, everything else found sound', '## Strengths and one critical problem', '## Looks good apart from one thing', '**What holds up, and what does not**']) {+ expect(parseReply('red-team', [heading, '', bullet].join('\n')).findings.map(f => f.label), heading).toEqual(['Critical']);+ }+ for (const tagged of [bullet, '- a.ts:42 swallows the timeout error [Critical]', '- a.ts:42 swallows the timeout error, **High**', '- The retry loop drops errors. High: a.ts:42']) {+ expect(parseReply('specialist', ['## What I checked and found sound', '', tagged].join('\n')).findings, tagged).toHaveLength(1);+ }+ expect(parseReply('specialist', ['**What else I checked and found no defect in**', '', '- The Critical path in lib/foo.ts:42 is fine.'].join('\n')).findings).toEqual([]);+ });+});diff --git a/test/review-trailer-clearing.test.ts b/test/review-trailer-clearing.test.tsindex 9cdce4254..f76e1589d 100644--- a/test/review-trailer-clearing.test.ts+++ b/test/review-trailer-clearing.test.ts@@ -6,7 +6,9 @@import { afterEach, describe, expect, setDefaultTimeout, test } from 'bun:test';import * as fs from 'node:fs';import * as path from 'node:path';-import { clearByTrailer } from '../lib/review-trailer-clearing';+import { clearByReview, clearByTrailer } from '../lib/review-trailer-clearing';+import { readRuledNotes, shiftedFinding, traceFinding } from '../lib/ruled-notes';+import { ruledOn } from '../lib/gate-dispositions';import { extractReceipt } from '../lib/ship-receipt';import { RELEASE, shipFixture, type ShipFx } from './helpers/ship-bin-fixture';@@ -96,3 +98,160 @@ describe('a Review-Finding trailer plus a later clean full round closes the findexpect(byFingerprint('src/x.ts::security')).toEqual([]);});});++const lines = (n: number, tag = 'v') => Array.from({ length: n }, (_, i) => `export const ${tag}${i + 1} = ${i + 1};`).join('\n') + '\n';++/** One run of /ship up to a stop: pass 1 clean, then Step 11 raises `finding` at the current HEAD. */+function raised(files: Record<string, string>, finding: Record<string, unknown>) {+ const f = shipFixture({ 'src/x.ts': 'export const x = 1;\n', 'src/y.ts': 'export const y = 1;\n' }, files);+ fxs.push(f);+ const run = (bin: string, args: string[]) => f.run(path.join(BIN, bin), args, { GSTACK_APPROVALS_MIRROR: '0' });+ const g = { f, run, body: path.join(f.root, 'body.md'), since: new Date(Date.now() - 1000).toISOString(), fixRun: 'r1' } as LoggedRun;+ fs.writeFileSync(g.body, 'Fixes a thing.\n');+ logRow(g, 'review', { pass: 1, ...CLEAN });+ logRow(g, 'adversarial-review', { status: 'issues_found', source: 'outside-voice', phase: 'adversarial', gate: 'informational', completed: true, findings: [finding] });+ return g;+}++describe('GSKI-1 #4: a fix with no Review-Finding trailer closes once a later clean full review read it', () => {+ // Value: protects=a blocker fixed in a commit with no trailer closes when a later complete full review of a head holding that+ // commit read the branch clean and the commit changed the finding's file after it was raised (GSKI-1 #4, 8426619);+ // fails_when=write refuses RECEIPT_BLOCKER_OPEN after the clean read-only final review; seam=gstack-ship-receipt write+ test('a fix commit that changed the finding\'s file, with no trailer, plus a later clean full round closes the blocker', () => {+ const g = raised({ 'src/x.ts': 'export const x = 2;\n' }, blocker);+ g.f.write({ 'src/x.ts': 'export const x = 3;\n' });+ g.f.git('add', '-A'); g.f.git('commit', '-qm', 'fix the outside voice blocker');+ expect(summaryThenWrite(g).w.status).toBe(3);+ logRow(g, 'review', { pass: 2, ...CLEAN });+ const { loop, w } = summaryThenWrite(g);+ expect(loop.open).toEqual([{ id: ID, fingerprint: FP }]);+ expect(w.status, w.stderr).toBe(0);+ expect(w.stderr).toContain('REVIEW_CLEAR: ' + ID + ' (fixed by ' + headOf(g.f).slice(0, 12));+ const receipt = extractReceipt(fs.readFileSync(g.body, 'utf8')).receipt;+ expect(receipt?.cleared_by_review).toEqual([{ id: ID, commit: headOf(g.f), review: headOf(g.f) }]);+ expect(receipt?.cleared_by_trailer).toBeUndefined();+ });+ // Value: protects=a clean full round never closes a blocker no commit after the raise touched (the fix went elsewhere, or the+ // only change to its file came before it was raised); fails_when=a later clean round alone closes an unaddressed blocker;+ // seam=gstack-ship-receipt write and clearByReview+ // Value: protects=a commit that changed the finding's file but not its line never closes it, even with a clean whole-PR review+ // (pass-2 voices on #4875: two blockers in one file, one fixed); fails_when=any edit to the same file closes an untouched blocker;+ // seam=gstack-ship-receipt write and clearByReview+ test('a commit that changed another line of the finding\'s file leaves the blocker open', () => {+ const g = raised({ 'src/x.ts': lines(30) }, { ...blocker, fingerprint: 'src/x.ts:5:outside-voice' });+ g.f.write({ 'src/x.ts': lines(30).replace('export const v20 = 20;', 'export const v20 = 2000;') });+ g.f.git('add', '-A'); g.f.git('commit', '-qm', 'edit another line');+ logRow(g, 'review', { pass: 2, ...CLEAN });+ const { w } = summaryThenWrite(g);+ expect(w.status).toBe(3);+ expect(w.stderr).toContain('RECEIPT_BLOCKER_OPEN');+ });+ test('negative controls: no change to the finding\'s file after the raise, a dirty later round, a security or pathless finding', () => {+ const g = raised({ 'src/x.ts': 'export const x = 2;\n' }, blocker);+ g.f.write({ 'src/y.ts': 'export const y = 2;\n' });+ g.f.git('add', '-A'); g.f.git('commit', '-qm', 'an unrelated change');+ logRow(g, 'review', { pass: 2, ...CLEAN });+ const { loop, w } = summaryThenWrite(g);+ expect(w.status).toBe(3);+ expect(w.stderr).toContain('RECEIPT_BLOCKER_OPEN');+ const rows = rowsOf(g), pass2 = rows.filter(r => r.skill === 'review').at(-1)!;+ expect(clearByReview(g.f.work, { head: headOf(g.f), baseRef: 'origin/main', rows, open: loop.open })).toEqual([]);+ const fixed = raised({ 'src/x.ts': 'export const x = 2;\n' }, blocker);+ fixed.f.write({ 'src/x.ts': 'export const x = 3;\n' });+ fixed.f.git('add', '-A'); fixed.f.git('commit', '-qm', 'fix');+ logRow(fixed, 'review', { pass: 2, ...CLEAN });+ const fixedRows = rowsOf(fixed), fixedPass2 = fixedRows.filter(r => r.skill === 'review').at(-1)!;+ const by = (r2: Record<string, unknown>, open: unknown[] = [{ id: ID, fingerprint: FP }], rows = fixedRows.filter(r => r !== fixedPass2)) =>+ clearByReview(fixed.f.work, { head: headOf(fixed.f), baseRef: 'origin/main', rows: [...rows, r2], open: open as any });+ expect(by(fixedPass2)).toHaveLength(1);+ expect(by({ ...fixedPass2, status: 'issues_found', findings: [{ fingerprint: 'src/y.ts:1:style', severity: 'INFORMATIONAL', action: 'open' }] })).toEqual([]);+ expect(by({ ...fixedPass2, converged: false, review_binding: { ...fixedPass2.review_binding, state: 'incomplete' } })).toEqual([]);+ expect(by({ ...fixedPass2, range_base: headOf(fixed.f) })).toEqual([]);+ expect(by({ ...fixedPass2, scope: 'scoped' })).toEqual([]);+ // Value: protects=a repeat round that read only its range never closes a trailerless blocker outside it (pass-2 voices on #4875);+ // fails_when=a clean range review closes it; seam=clearByReview+ expect(by({ ...fixedPass2, range_base: fixed.f.git('rev-parse', 'HEAD~1').stdout.trim() })).toEqual([]);+ const reused = { skill: 'review', via: 'ship', timestamp: '2026-01-01T00:00:00Z', commit_full: fixed.f.git('rev-parse', 'HEAD~1').stdout.trim(), findings: [{ ...blocker, fingerprint: 'src/y.ts:1:outside-voice' }] };+ expect(by(fixedPass2, [{ id: ID, fingerprint: FP }], [reused, ...fixedRows.filter(r => r !== fixedPass2)])).toHaveLength(1);+ const sec = fixedRows.filter(r => r !== fixedPass2).map(r => r.skill === 'adversarial-review' ? { ...r, findings: [{ ...blocker, fingerprint: 'src/x.ts:1:security', ledger_id: undefined }] } : r);+ expect(by(fixedPass2, ['src/x.ts:1:security'], sec)).toEqual([]);+ const pathless = fixedRows.filter(r => r !== fixedPass2).map(r => r.skill === 'adversarial-review' ? { ...r, findings: [{ ...blocker, fingerprint: 'p1/outside-voice#1' }] } : r);+ expect(by(fixedPass2, [ID], pathless)).toEqual([]);+ void pass2;+ });+ // Value: protects=a commit only closes a trailerless blocker when git shows its line changed or its file deleted; a binary file or+ // a git failure proves nothing (p3/specialist-batched#1 on #4875); fails_when=a byte edit to a binary file, read as "line+ // changed" because the diff could not be mapped, closes the blocker; seam=clearByReview and traceFinding+ test('fails closed: a binary file edit proves nothing, a deleted file counts as changed', () => {+ const bin = { ...blocker, fingerprint: 'bin.dat:1:outside-voice' };+ const g = raised({ 'bin.dat': 'a\0b\n' }, bin);+ g.f.write({ 'bin.dat': 'a\0c\n' });+ g.f.git('add', '-A'); g.f.git('commit', '-qm', 'touch the binary file');+ logRow(g, 'review', { pass: 2, ...CLEAN });+ expect(clearByReview(g.f.work, { head: headOf(g.f), baseRef: 'origin/main', rows: rowsOf(g), open: [{ id: ID, fingerprint: 'bin.dat:1:outside-voice' }] })).toEqual([]);+ const before = headOf(g.f);+ g.f.git('rm', '-q', 'src/x.ts'); g.f.git('commit', '-qm', 'delete the file');+ expect(traceFinding(g.f.work, FP, before, headOf(g.f))).toBe('changed');+ expect(traceFinding(g.f.work, FP, before, 'not-a-commit')).toBeNull();+ });+});++describe('GSKI-1 #5: a ruled finding stays ruled when edits above it move its line', () => {+ const rule = (g: LoggedRun, finding: string) => {+ ok(g.run('gstack-approvals', ['rule', '--finding', finding, '--head', headOf(g.f), '--reason', 'ships as a note', '--words', 'ship it as a note', '--by', 'Captain Fixture (FX-1)']));+ fs.writeFileSync(g.body, 'Fixes a thing.\n\n' + ok(g.run('gstack-approvals', ['rulings'])));+ };+ const reraise = (g: LoggedRun, finding: Record<string, unknown>) => {+ logRow(g, 'review', { pass: 2, ...CLEAN });+ logRow(g, 'adversarial-review', { status: 'issues_found', source: 'outside-voice', phase: 'adversarial', gate: 'informational', completed: true, findings: [finding] });+ };+ const AT43 = 'src/x.ts:43:outside-voice', AT54 = 'src/x.ts:54:outside-voice';+ const ruledAt43 = () => {+ const g = raised({ 'src/x.ts': lines(60) }, { ...blocker, fingerprint: AT43, ledger_id: 'p1/outside-voice#1' });+ rule(g, AT43);+ g.f.write({ 'src/x.ts': lines(11, 'added') + lines(60) });+ g.f.git('add', '-A'); g.f.git('commit', '-qm', 'add eleven lines at the top');+ return g;+ };+ // Value: protects=a ruling on path:43:voice covers the same unchanged line re-raised at :54 after 11 lines were added above it+ // (GSKI-1 #5); fails_when=write refuses RECEIPT_BLOCKER_OPEN on the shifted fingerprint; seam=gstack-ship-receipt write+ test('the same finding re-raised at its shifted line stays ruled', () => {+ const g = ruledAt43();+ reraise(g, { ...blocker, fingerprint: AT54, ledger_id: 'p2/outside-voice#1' });+ const { loop, w } = summaryThenWrite(g);+ expect(loop.open).toEqual([{ id: 'p1/outside-voice#1', fingerprint: AT43 }, { id: 'p2/outside-voice#1', fingerprint: AT54 }]);+ expect(w.status, w.stderr).toBe(0);+ expect(w.stderr).toContain('RULED_SHIFT: p2/outside-voice#1 is ' + AT43);+ expect(shiftedFinding(g.f.work, AT43, g.f.git('rev-parse', 'HEAD~1').stdout.trim(), headOf(g.f))).toBe(AT54);+ // Value: protects=Step 11.5 reads the shifted ruling too, so a stopped round-2 row that re-raised it binds like the receipt;+ // fails_when=ruledOn matches only the exact fingerprint; seam=lib/gate-dispositions.ts ruledOn+ const notes = readRuledNotes(g.f.work, { ...process.env, GSTACK_STATE_ROOT: g.f.state, GSTACK_HOME: g.f.state, GSTACK_APPROVALS_MIRROR: '0' });+ const row2 = { commit_full: headOf(g.f), range_base: g.f.git('rev-parse', 'HEAD~1').stdout.trim(), findings: [{ fingerprint: AT54, action: 'open' }, { fingerprint: 'src/x.ts:20:outside-voice', action: 'open' }] };+ expect(ruledOn(g.f.work, row2, notes).map(n => n.finding)).toEqual([AT54]);+ });+ // Value: protects=a different finding in the same file, the same line after its text changed, another voice or a security+ // finding never inherits a ruling (fail closed); fails_when=any of them writes a receipt; seam=gstack-ship-receipt write and shiftedFinding+ test('adversarial controls: another line, an edited ruled line, another voice and a security finding still block', () => {+ const other = ruledAt43();+ reraise(other, { ...blocker, fingerprint: 'src/x.ts:20:outside-voice', ledger_id: 'p2/outside-voice#1' });+ const w1 = summaryThenWrite(other).w;+ expect(w1.status).toBe(3);+ expect(w1.stderr).toContain('RECEIPT_BLOCKER_OPEN');+ const voice = ruledAt43();+ reraise(voice, { ...blocker, fingerprint: 'src/x.ts:54:red-team', raised_by: 'red-team', ledger_id: 'p2/red-team#1' });+ expect(summaryThenWrite(voice).w.status).toBe(3);+ const edited = ruledAt43();+ const was = headOf(edited.f);+ edited.f.write({ 'src/x.ts': (lines(11, 'added') + lines(60)).replace('export const v43 = 43;', 'export const v43 = 4300;') });+ edited.f.git('add', '-A'); edited.f.git('commit', '-qm', 'edit the ruled line');+ reraise(edited, { ...blocker, fingerprint: AT54, ledger_id: 'p2/outside-voice#1' });+ expect(summaryThenWrite(edited).w.status).toBe(3);+ const ruledHead = edited.f.git('rev-parse', 'HEAD~2').stdout.trim();+ expect(shiftedFinding(edited.f.work, AT43, ruledHead, was)).toBe(AT54);+ expect(shiftedFinding(edited.f.work, AT43, ruledHead, headOf(edited.f))).toBeNull();+ expect(shiftedFinding(edited.f.work, 'src/x.ts:43:security', ruledHead, was)).toBeNull();+ expect(shiftedFinding(edited.f.work, AT43, was, ruledHead)).toBeNull();+ expect(shiftedFinding(edited.f.work, 'src/x.ts::outside-voice', ruledHead, was)).toBeNull();+ expect(shiftedFinding(edited.f.work, 'src/x.ts:5:outside-voice', ruledHead, was)).toBe('src/x.ts:16:outside-voice');+ });+});diff --git a/test/size-ledger/ship/fix-ship-review-closures-and-docs-attempts.json b/test/size-ledger/ship/fix-ship-review-closures-and-docs-attempts.jsonnew file mode 100644index 000000000..0387c857e--- /dev/null+++ b/test/size-ledger/ship/fix-ship-review-closures-and-docs-attempts.json@@ -0,0 +1,4 @@+{+ "bytes": 170,+ "why": "Step 14.5 attempt budget: a refused Prepare snapshot (DOCS_RUN_FOLDER_MISSING) spends no attempt (GST-4111)"+}