diff --git a/bin/gstack-review-plan b/bin/gstack-review-plan index 112cb1b37..96042e248 100755 --- a/bin/gstack-review-plan +++ b/bin/gstack-review-plan @@ -39,8 +39,8 @@ import { policySelection, selectFor } from '../lib/review-selection'; import { effectiveReaders, READERS_POLICY_DEFAULT } from '../lib/ship-policy-readers'; import { classifyDiff, diffCommand, keepCommand, planReview, reviewDepthLine, reviewPlanLine, scanNumbers, ROLE_EFFORT, SCOPED_RANGE_LINES, type Depth, type History } from '../lib/review-depth'; import { classList, targetedBriefSha, targetedClasses, targetedPatchId } from '../lib/review-targeted'; -import { targetedDelta } from '../lib/review-targeted-delta'; -import { ownChangeSince } from '../lib/ship-receipt-depth'; +import { ruledCarries, targetedDelta } from '../lib/review-targeted-delta'; +import { ownChangeSince, stampPathsSince } from '../lib/ship-receipt-depth'; import { RISK_CLASSES, type RiskClass } from '../lib/review-risk'; import { readRuledNotes, ruledEditLine, ruledEdits } from '../lib/ruled-notes'; @@ -190,6 +190,7 @@ function main(): number { let fixRange: { base: string; runtime_lines: number | null; error?: string; touched_gate?: true; ruled?: string[] } | undefined; let routed: ReturnType | null = null; let ruledAll = false; + let stamps = new Set(); let own: string | null = null; if (rangeBase) { const unread = (error: string) => ({ base: rangeBase, runtime_lines: null, error }); @@ -202,10 +203,12 @@ function main(): number { const commit = collectCommit(root, resolved, own); const range = classifyDiff({ ...commit, registry, scope: scopeOf([resolved, '--head', own]), gateTagged: gateTagsOf(['--commit', own]), ...riskPaths, ...(active ? { excluded: active.excluded } : {}) }); const edits = readRuledNotes(root).filter(n => n.finding.startsWith('edit:')); - routed = edits.length && commit.paths.length && !range.errors.length ? ruledEdits(root, commit.paths, head, edits) : null; + stamps = edits.length ? new Set(stampPathsSince(root, ref, resolved, own, head)) : stamps; + const toRule = commit.paths.filter(p => !stamps.has(p)); + routed = edits.length && toRule.length && !range.errors.length ? ruledEdits(root, toRule, head, edits) : null; const tagsBeyond = (ruled: ReadonlyMap) => { const g = runGateDiff(['--commit', own!, '--format', 'jsonl']); - return g.status !== 0 || (g.stdout ?? '').split('\n').slice(1).some(l => { try { const h = JSON.parse(l) as { path?: string; tags?: unknown[] }; return !!h.tags?.length && !ruled.has(h.path ?? ''); } catch { return false; } }); }; - ruledAll = !!routed && routed.ruled.size === commit.paths.length && !tagsBeyond(routed.ruled); + return g.status !== 0 || (g.stdout ?? '').split('\n').slice(1).some(l => { try { const h = JSON.parse(l) as { path?: string; tags?: unknown[] }; return !!h.tags?.length && !ruled.has(h.path ?? '') && !stamps.has(h.path ?? ''); } catch { return false; } }); }; + ruledAll = !!routed && routed.ruled.size === toRule.length && !tagsBeyond(routed.ruled); fixRange = range.errors.length ? unread([...range.errors.slice(0, 5).map(e => `${e.code} ${e.input}`), ...(range.errors.length > 5 ? [`+${range.errors.length - 5} more`] : [])].join('; ')) : !commit.paths.length ? unread('the fix range is empty: commit the fix after the range base (a base merge alone is not the PR\'s own change)') : ruledAll ? { base: rangeBase, runtime_lines: 0, ruled: [...routed!.ruled.keys()].sort() } @@ -230,7 +233,7 @@ function main(): number { const pairs = status ? Array.from({ length: status.length >> 1 }, (_, i) => [status[2 * i]!, status[2 * i + 1]!] as const) : undefined; const edited = pairs?.filter(([s]) => s !== 'D').map(([, p]) => p), deleted = pairs?.filter(([s]) => s === 'D').map(([, p]) => p) ?? []; const spaced = edited?.filter(p => /\s/.test(p)) ?? []; - const rulable = edited?.filter(p => !spaced.includes(p) && !routed?.ruled.has(p)); + const rulable = edited?.filter(p => !spaced.includes(p) && !routed?.ruled.has(p) && !stamps.has(p)); const quote = (s: string) => `'${s.replace(/'/g, `'\\''`)}'`; const rule = (finding: string) => `gstack-approvals rule --finding ${finding} --head ${head} --reason '' --by '' --words '' --owner-ref :`; plan.next.reason += `; if the owner rules instead that the edit ships as a disclosed note, record that ruling once per edited path (each path shell-quoted; the owner-ref is the relay this open /gstack-ship run needs): ${rulable?.length ? rulable.map(p => rule(quote(`edit:${p}`))).join(' && ') : rule("'edit:'")}, then rerun finish, which routes each ruled path at the ruled bytes as RULED_EDIT${spaced.length ? `; ${spaced.map(quote).join(', ')} cannot be ruled (a finding holds no whitespace), so an edit there keeps the fix and runs /gstack-ship again` : ''}${deleted.length ? `; a deletion (${deleted.map(quote).join(', ')}) cannot be ruled, so it keeps the fix and runs /gstack-ship again` : ''}`; @@ -238,7 +241,9 @@ function main(): number { const ranArg = flag('--targeted-ran'); const delta = plan.next.step !== 'done' || !targeted.classes.length || ran ? null : rangeBase && ranArg ? targetedDelta(root, ref, rangeBase, ranArg) : null; - const ruledRead = ruledAll && plan.next.step === 'done' && targeted.classes.length > 0 && !ran && !(delta?.state === 'skip' && delta.carried); + const ruledCarry = ruledAll && plan.next.step === 'done' && targeted.classes.length > 0 && !ran && !!rangeBase && !!ranArg && ruledCarries(root, ref, rangeBase, ranArg, active?.excluded); + const ruledRead = ruledAll && plan.next.step === 'done' && targeted.classes.length > 0 && !ran && !(delta?.state === 'skip' && delta.carried) && !ruledCarry; + if (ruledCarry) plan.skipped.push(`targeted-only read (every edit since --range-base is ruled a note and none carries a targeted class, so the record read at ${rangeBase!.slice(0, 12)} carries with the rulings; gstack-ship-receipt write records them)`); if (delta?.state === 'dispatch' || ruledRead) { const why = delta?.state === 'dispatch' ? `the only change since is docs whose claim the record cannot carry (${delta.paths.join(', ')}) after the targeted read at ${delta.range_base.slice(0, 12)}` : 'every edit since --range-base is ruled a note, but no targeted record covers the ruled bytes'; diff --git a/bin/gstack-review-scope b/bin/gstack-review-scope index dcff39bad..202b24c5e 100755 --- a/bin/gstack-review-scope +++ b/bin/gstack-review-scope @@ -223,7 +223,7 @@ function cmdSummary(rest: string[], json: boolean): number { const fixCheckRows = new Set(logged.filter(r => r.skill === FIX_CHECK_SKILL).map(r => JSON.stringify([r.pass ?? null, r.commit_full ?? r.commit ?? '', r.review_binding?.started_at ?? r.timestamp ?? '', (Array.isArray(r.findings) ? r.findings : []).map((f: any) => f?.ledger_id ?? f?.fingerprint ?? '').sort()]))); const ran = ledgerPasses.filter(p => !(p.started < sinceMs)); const fixCheckLedgers = ran.filter(p => p.fixCheck); - const unloggedPasses = !logged.length ? ran.filter(p => !p.fixCheck) : ran.filter(p => !p.fixCheck && /^p\d+$/.test(p.name ?? '') && !passRows.some(r => `p${r.pass}` === p.name)); + const unloggedPasses = !logged.length ? ran.filter(p => !p.fixCheck) : ran.filter(p => !p.fixCheck && !p.targetedOnly && /^p\d+$/.test(p.name ?? '') && !passRows.some(r => `p${r.pass}` === p.name)); const unlogged = [...unloggedPasses, ...(fixCheckLedgers.length > fixCheckRows.size ? fixCheckLedgers : [])]; if (unlogged.length) process.stderr.write(`REVIEW_ROWS_MISSING: ${unloggedPasses.length ? 'readers ran' : 'a fix-check reader ran'} (ledger ${unlogged.map(p => p.name).join(', ')}) with no ${!logged.length ? 'review-log' : unloggedPasses.length ? 'review' : 'review-fix-check'} row from this run since ${since}: Step 9.4's persistence never ran for ${unlogged.length === 1 ? 'it' : 'them'}, so a stop, a fix-check grant or finish cannot bind ${unlogged.length === 1 ? 'it' : 'them'}; log each pass and fix-check with gstack-review-log --start/--finish, and never hand-run a reader\n`); for (const v of summary.voided ?? []) process.stderr.write(`REVIEW_SCOPE_VOIDED: ${v}\n`); diff --git a/bin/gstack-ship-receipt b/bin/gstack-ship-receipt index ceb5da707..c784f2e06 100755 --- a/bin/gstack-ship-receipt +++ b/bin/gstack-ship-receipt @@ -35,6 +35,7 @@ * Query commands: no GSTACK_RESULT line. Logic: lib/ship-receipt.ts. */ import { spawnSync } from '../lib/spawn-sync'; +import { gitPath } from '../lib/git-path'; import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; @@ -55,9 +56,9 @@ import { RUNS_FENCE, receiptIssuesFrom, receiptRuns, receiptSummaryLine, renderCensus, renderReceiptBlock, unruledOpenBlockers, validateReceipt, type CensusPr, } from '../lib/ship-receipt'; import { checkDocsCaps, docsCapLine, docsExceptionLine, parseReceiptDocs } from '../lib/ship-receipt-docs'; -import { comparePath, contextPacket, PACKET_SECTION_CAP, readScopedReview, touchedPaths } from '../lib/ship-patch'; +import { absorbedByBase, comparePath, contextPacket, PACKET_SECTION_CAP, readScopedReview, touchedPaths } from '../lib/ship-patch'; import { planRecheck, recheckPacket } from '../crew/lib/ship-recheck'; -import { carryExcludeBinds, deeper, depthBelow, exceptionProblems, parseReviewTargeted, plainDocsSince, platformReceiptDepth, receiptExclude, receiptExcludeFallback, receiptReviewAtHead, receiptTargetedAtHead, targetedClassesSince, writeExcludeBinds } from '../lib/ship-receipt-depth'; +import { carryExcludeBinds, deeper, depthBelow, exceptionProblems, parseReviewTargeted, plainDocsSince, platformReceiptDepth, ruledChangeSince, receiptExclude, receiptExcludeFallback, receiptReviewAtHead, receiptTargetedAtHead, 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'; @@ -334,8 +335,8 @@ async function cmdWrite(rest: string[], json: boolean): Promise { const excludeBound = writeExcludeBinds(repoRoot, base, headSha ?? head, review, flag(rest, '--review-exclude'), flag(rest, '--docs-post'), flag(rest, '--docs-pre'), flag(rest, '--docs-audit-read')); if (!excludeBound.ok && excludeBound.packet) { const at = headSha ?? head; - const packet = path.resolve(repoRoot, git(['rev-parse', '--git-path', `gstack/docs-audit-read-${at.slice(0, 12)}.md`], repoRoot) ?? `.git/gstack/docs-audit-read-${at.slice(0, 12)}.md`); - try { fs.mkdirSync(path.dirname(packet), { recursive: true }); fs.writeFileSync(packet, excludeBound.packet.text); } + const where = gitPath(repoRoot, `gstack/docs-audit-read-${at.slice(0, 12)}.md`), packet = where.ok ? where.path : 'under the git directory'; + try { if (!where.ok) throw new Error(where.error); fs.mkdirSync(path.dirname(packet), { recursive: true }); fs.writeFileSync(packet, excludeBound.packet.text); } catch (e) { process.stderr.write(`gstack-ship-receipt write: ${excludeBound.why}, but the reader's packet ${packet} cannot be written (${(e as Error).message.split('\n')[0]}); make its directory writable, then rerun write; nothing written\n`); return EXIT.fail; } process.stderr.write(resultLine('gstack-ship-receipt write', 'RECEIPT_DOCS_AUDIT_READ', `${excludeBound.why}: one scoped reader (not a review round) reads ${packet}, then rerun write with --docs-audit-read written outside the worktree ({"head":"${at}","paths":${JSON.stringify(excludeBound.packet.paths)},"reviewer":"","verdict":"clean","packet_sha256":"${excludeBound.packet.sha256}"}); a finding goes to the lane's Captain; nothing written`) + '\n'); return EXIT.fail; @@ -348,9 +349,10 @@ async function cmdWrite(rest: string[], json: boolean): Promise { const product = reviewedProduct(repoRoot, base, head, pregateFile); let targeted: ReturnType | undefined; if (flag(rest, '--review-targeted') !== undefined) { - try { targeted = parseReviewTargeted(jsonArg(flag(rest, '--review-targeted')), product.product_patch_id ?? 'none', read => reviewedProduct(repoRoot, base, read, pregateFile).product_patch_id, read => targetedClassesSince(repoRoot, read, headSha ?? head, base, review.exclude.state === 'active' ? review.exclude.excluded : undefined), read => plainDocsSince(repoRoot, read, headSha ?? head, base), read => spawnSync('git', ['merge-base', '--is-ancestor', read, headSha ?? head], { cwd: repoRoot, timeout: 30_000 }).status === 0); } catch (e: any) { targeted = { ok: false, message: `--review-targeted: ${e.message}` }; } + try { targeted = parseReviewTargeted(jsonArg(flag(rest, '--review-targeted')), product.product_patch_id ?? 'none', read => reviewedProduct(repoRoot, base, read, pregateFile).product_patch_id, read => targetedClassesSince(repoRoot, read, headSha ?? head, base, review.exclude.state === 'active' ? review.exclude.excluded : undefined), read => plainDocsSince(repoRoot, read, headSha ?? head, base), read => spawnSync('git', ['merge-base', '--is-ancestor', read, headSha ?? head], { cwd: repoRoot, timeout: 30_000 }).status === 0, read => ruledChangeSince(repoRoot, read, headSha ?? head, base)); } catch (e: any) { targeted = { ok: false, message: `--review-targeted: ${e.message}` }; } } if (targeted && !targeted.ok) { process.stderr.write(resultLine('gstack-ship-receipt write', 'RECEIPT_INVALID', `${targeted.message}; nothing written`) + '\n'); return EXIT.fail; } + for (const e of targeted?.ok ? targeted.targeted.ruled_edits ?? [] : []) process.stderr.write(`TARGETED_RULED: ${e.path} (the targeted record read at ${targeted!.ok ? targeted!.targeted.read?.slice(0, 12) : ''} carries across the edit ruled by ${e.by}, approval ${e.approval}; no targeted class changed)\n`); const approval = approvalForReceipt({ repoRoot, base, head, citationText: [bodyText, ...flags(rest, '--approval')].join('\n'), runDirs: flags(rest, '--approval-run') }); if (approval.kind === 'invalid') { for (const line of approval.lines) process.stderr.write(resultLine('gstack-ship-receipt write', 'APPROVAL_CLASSES_INVALID', line) + '\n'); @@ -729,6 +731,7 @@ function cmdCarry(rest: string[], json: boolean): number { const contextPaths: string[] = []; const baseContext: string[] = []; const stampOnly: string[] = []; + const absorbed: string[] = []; if (retarget && reviewed !== current) changedProduct.push(`HEAD's product diff against ${base} is not the one reviewed against ${reviewedBase} (the parent has not fully landed on ${base}, or the branch changed since)`); else if (productFrom !== productHead && !retarget) { // planCarry names at most CARRY_NAMED_PATHS differing paths, so the walk stops there, and it reads only the paths the @@ -758,11 +761,11 @@ function cmdCarry(rest: string[], json: boolean): number { } if (cls !== 'product') continue; const verdict = comparePath(repoRoot, sides, p); - if (verdict === 'changed') changedProduct.push(p); + if (verdict === 'changed') (absorbedByBase(repoRoot, sides, p) ? absorbed : changedProduct).push(p); else if (verdict === 'spliced') contextPaths.push(p); else if (verdict === 'context') baseContext.push(p); } - const left = [...contextPaths, ...baseContext, ...stampOnly]; + const left = [...contextPaths, ...baseContext, ...stampOnly, ...absorbed]; if (!changedProduct.length && !left.length) changedProduct.push('(a product path outside the branch\'s touched files; compare the two base diffs)'); else if (!changedProduct.length) { const rest = [...spec.product, ...left.map(p => `:(exclude,literal)${p}`)]; @@ -781,9 +784,9 @@ function cmdCarry(rest: string[], json: boolean): number { scopedDryRun = `the base merge spliced lines into the reviewed hunks in ${contextPaths.join(', ')}: carry without --dry-run writes the scoped-review packet for one scoped reader (not a review round), then carry --scoped-review ; nothing written`; scopedReview = `spliced hunks (scoped review pending: ${contextPaths.join(', ')})`; } else if (!record) { - const gitPath = git(['rev-parse', '--git-path', `gstack/scoped-review-${head.slice(0, 12)}.md`], repoRoot); - const packet = path.resolve(repoRoot, gitPath ?? `.git/gstack/scoped-review-${head.slice(0, 12)}.md`); + const where = gitPath(repoRoot, `gstack/scoped-review-${head.slice(0, 12)}.md`), packet = where.ok ? where.path : 'under the git directory'; try { + if (!where.ok) throw new Error(where.error); fs.mkdirSync(path.dirname(packet), { recursive: true }); fs.writeFileSync(packet, packetBody.text); } catch (e) { @@ -817,14 +820,14 @@ function cmdCarry(rest: string[], json: boolean): number { else { let where = 'not written (dry run)'; if (!rest.includes('--dry-run')) { - const packet = path.resolve(repoRoot, git(['rev-parse', '--git-path', `gstack/recheck-${head.slice(0, 12)}.md`], repoRoot) ?? `.git/gstack/recheck-${head.slice(0, 12)}.md`); - try { fs.mkdirSync(path.dirname(packet), { recursive: true }); fs.writeFileSync(packet, recheckPacket({ from, head, plan: r, rangeDiff: fullRange!, ...bound })); where = packet; } + const at = gitPath(repoRoot, `gstack/recheck-${head.slice(0, 12)}.md`), packet = at.ok ? at.path : ''; + try { if (!at.ok) throw new Error(at.error); fs.mkdirSync(path.dirname(packet), { recursive: true }); fs.writeFileSync(packet, recheckPacket({ from, head, plan: r, rangeDiff: fullRange!, ...bound })); where = packet; } catch (e) { where = `unwritable: ${(e as Error).message.split('\n')[0]}`; } } process.stderr.write(`RECHECK: advisory range_diff_lines=${r.lines} range_diff_sha256=${r.sha256} packet=${where}; one reader may read it for advice, but it never carries the receipt (GST-2673): run /gstack-ship on ${head.slice(0, 12)} for the merge head's full review (docs/review-policy.md#rounds-per-pull-request)\n`); } } - plan = planCarry({ from, head, changed, productPatchId: { from: reviewed as string, head: current as string }, testPatchId: { from: testFrom, head: testHead }, changedProduct, mergeCommits: Number(mergeCommits) || 0, rangeDiff, ...(retarget ? { retargetedFrom: reviewedBase } : {}), ...(stackParent ? { stackParent } : {}), ...(scopedReview ? { scopedReview } : {}), ...(!changedProduct.length && baseContext.length ? { baseContext } : {}), ...(stampedRows.length ? { stampedRows } : {}) }); + plan = planCarry({ from, head, changed, productPatchId: { from: reviewed as string, head: current as string }, testPatchId: { from: testFrom, head: testHead }, changedProduct, mergeCommits: Number(mergeCommits) || 0, rangeDiff, ...(retarget ? { retargetedFrom: reviewedBase } : {}), ...(stackParent ? { stackParent } : {}), ...(scopedReview ? { scopedReview } : {}), ...(!changedProduct.length && baseContext.length ? { baseContext } : {}), ...(stampedRows.length ? { stampedRows } : {}), ...(!changedProduct.length && absorbed.length ? { absorbed } : {}) }); } if (!plan.ok) return refused(plan.code, plan.message); // Eligibility is not publication: a receipt that recorded a pregate is rebound only with a pregate current for HEAD, diff --git a/changelog.d/fix-ship-ruled-edit-deadlock.md b/changelog.d/fix-ship-ruled-edit-deadlock.md new file mode 100644 index 000000000..1349238bc --- /dev/null +++ b/changelog.d/fix-ship-ruled-edit-deadlock.md @@ -0,0 +1,4 @@ +--- +important: blocker +--- +**`/gstack-ship` no longer forces a whole new full review after the Captain rules in a small edit made after the final review.** The planner stopped because the release stamps written after review (VERSION, CHANGELOG) were never ruled, and the receipt refused the targeted reader's record from before the edit. Now stamps need no ruling, a ruled edit that touches no money, gate, auth or secret code keeps that record (the receipt lists the rulings), and a ruled edit that does touch such code gets one targeted reader instead of a full review. A ruled edit to a doc the docs audit checked no longer reports the docs as stale, and the targeted reader's own pass no longer shows as unbound. Inside a git worktree, gstack no longer crashes with ENOTDIR when git can't name its directory; it reports the git failure. Carrying a ship receipt across a merge of main also works when main made one of the PR's exact changes itself, such as deleting the same entry; a merge that drops or edits any other change still needs a new review. diff --git a/docs/ship-policy.md b/docs/ship-policy.md index 98bebe6a1..bfbdc7f20 100644 --- a/docs/ship-policy.md +++ b/docs/ship-policy.md @@ -1940,8 +1940,9 @@ base merge moved, and names deletions apart, because a deletion cannot be ruled. One ruling never covers another path, and a path edited again after its ruling stops finish again, even when a later commit restores the ruled bytes. A path with whitespace cannot be ruled, so an edit there keeps the fix and runs /gstack-ship again. -The ruling clears only the review stop: a changed file the documentation audit -hashed still needs the stage 3 recovery finish's stop names. The ruling is an ordinary +A ruled path the documentation audit hashed also stays fresh at stage 3 +(`DOCS: fresh … ruled=`, GBRA-108); an unruled doc edit still needs the +stage 3 recovery finish's stop names. The ruling is an ordinary ruled note, so it prints as `RULED_NOTE:`, marked `(no RULED_EDIT at this head; not applied)` when it cleared no path, the receipt records it and the PR body lists its `Ruled note:` line. @@ -1950,9 +1951,14 @@ applied)` when it cleared no path, the receipt records it and the PR body lists it prints `RULED_EDIT:` for each cleared path and `RULED_EDIT_REFUSED:` for each that did not clear, and when every path the fix range changed is cleared and the gate scan tags no other path in it, `FIX_RANGE:` reports `runtime_lines=0 ruled=` -and the range plans as no fix instead of asking for every voice again. A PR with -targeted classes still gets one targeted reader on HEAD when no targeted record -covers the ruled bytes; that read is not a review round. +and the range plans as no fix instead of asking for every voice again. Release +stamps in the range (Step 12's VERSION and CHANGELOG) need no ruling (HARN-1). +A PR with targeted classes still gets one targeted reader on HEAD when no +targeted record covers the ruled bytes; that read is not a review round, and its +ledger needs no review row. When none of the ruled edits carries a targeted +class, the record read at `--range-base` (`--targeted-ran`) carries: the plan +skips the reader and `gstack-ship-receipt write` accepts that record, printing +`TARGETED_RULED:` and listing the rulings in `review_targeted.ruled_edits`. **Security findings stay private (GST-3076).** A PR body keeps every earlier @@ -2336,6 +2342,7 @@ receipt when the base moves: | a merge of the base that edited lines next to the branch's unchanged hunks (the branch's +/- lines, file modes and symlink targets identical and in the same places) | carries with no reader; CI on the merged head is the check (reason `base context moved next to unchanged own lines`, GST-3562) | | a merge of the base that spliced lines into one of the branch's hunks (the base replaced the very lines the branch replaces and the merge kept both, GST-2975) | carries after one scoped reader reads the hunks and comes back clean (`RECEIPT_CARRY_SCOPED_REVIEW`, then `carry --scoped-review `) | | a merge of the base that only re-records the harness pin of a product file (`scripts/harness-pins/.json`; a pinned test or metadata file's pin stays product): at both heads the pin is a regular file (not a symlink), both pinned files resolve, the pin's `blob` is its file's blob, its other fields are the reviewed ones, and `scripts/harness-version.json`'s version and patterns did not move; the pinned file itself still counts as product | carries (reason `regenerated outputs`, GSTA-749) | +| a merge of the base that itself made some of the branch's exact changes (for example, both sides deleted the same entry), so those hunks left the branch's diff: a clean three-way replay of the reviewed change onto the new base gives the current file's exact bytes and mode, regular files only | carries (reason `branch hunks the base landed identically (; …)`, HARN-172) | | a merge of the base whose resolution changed product code, or moved the branch's lines elsewhere | a fresh /gstack-ship (`RECEIPT_CARRY_PRODUCT_CHANGED`) | | a rebase or force-push onto a tree the receipt covers, product diff against the new base unchanged | carries (`carry.ancestry: rewritten`) | | any other rebase or force-push | a fresh /gstack-ship (`RECEIPT_CARRY_TREE_MISMATCH`) | diff --git a/lib/git-path.ts b/lib/git-path.ts new file mode 100644 index 000000000..d43e1b454 --- /dev/null +++ b/lib/git-path.ts @@ -0,0 +1,17 @@ +/** + * Where a gstack file under this checkout's git directory lives: `git rev-parse --git-path ` (HARN-108). In a linked + * worktree `.git` is a file (`gitdir: …`), so the literal `.git/` every caller fell back to when git failed, timed out + * or printed nothing wrote through a file and failed with ENOTDIR. A failed or empty answer is now an error the caller names. + */ +import * as path from 'node:path'; +import { spawnSync } from './spawn-sync'; + +export type GitPath = { ok: true; path: string } | { ok: false; error: string }; + +export function gitPath(cwd: string, name: string, timeoutMs = 30_000): GitPath { + const r = spawnSync('git', ['rev-parse', '--git-path', name], { cwd, encoding: 'utf8', timeout: Math.max(1, timeoutMs) }); + const out = r.status === 0 ? String(r.stdout ?? '').trim() : ''; + if (out) return { ok: true, path: path.resolve(cwd, out) }; + const why = String(r.stderr ?? '').trim().split('\n')[0] || (r.error as NodeJS.ErrnoException | undefined)?.code || (r.signal ? `killed by ${r.signal}` : `exit ${r.status}`); + return { ok: false, error: `git rev-parse --git-path ${name} gave no path (${why.slice(0, 200)}), and gstack does not guess .git/${name}: in a linked worktree .git is a file` }; +} diff --git a/lib/headless-artifacts.ts b/lib/headless-artifacts.ts index 4ddcd7874..452d9fec5 100644 --- a/lib/headless-artifacts.ts +++ b/lib/headless-artifacts.ts @@ -135,7 +135,9 @@ export interface ShipReceipt { /** The `Mechanical retake: ()` lines /ship finish proved for this head's tree (lib/ship-mechanical.ts); the PR body lists each one word for word (GST-1560). */ mechanical?: string[]; /** The targeted pass on money, gate, auth and secret code (lib/review-targeted.ts), bound to the receipt's product_patch_id; `done` only with its output collected. */ - review_targeted?: { classes: string[]; rules: string; brief_sha: string; product_patch_id: string; status: 'done' | 'failed' | 'not-run'; findings: number; raised_by: string }; + review_targeted?: { classes: string[]; rules: string; brief_sha: string; product_patch_id: string; status: 'done' | 'failed' | 'not-run'; findings: number; raised_by: string; + /** Set when the reader read `read`, an ancestor, and every path the PR changed since is an owner's `edit:` ruling with no targeted class in it (HARN-1 #638): the rulings that carried the record. */ + read?: string; ruled_edits?: Array<{ path: string; approval: string; by: string }> }; /** Step 5 failures gstack-base-red proved are the base's own (lib/base-red.ts): a conditional receipt the queue refuses until /gstack-ship --resume rewrites it without this block. */ base_red?: { cases: string[]; files: string[]; base: string; lane: string; expires_at: string }; /** The pregate's owner-granted flaky exceptions (gstack-pregate clear --flaky-exception): pregate only, never a required CI check. */ @@ -282,7 +284,7 @@ export const ARTIFACT_SCHEMAS = { base_red: { type: 'object', required: ['cases', 'files', 'base', 'lane', 'expires_at'], properties: { cases: strList, files: strList, base: str, lane: str, expires_at: str } }, flaky_exception: { type: 'array', items: { type: 'object', required: ['lane', 'runs', 'cases', 'grant', 'by'], properties: { lane: str, runs: strList, cases: strList, grant: str, by: str } } }, 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_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, read: str, ruled_edits: { type: 'array', items: { type: 'object', required: ['path', 'approval', 'by'], properties: { path: str, approval: str, 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_exclude_fallback: { type: 'object', required: ['source', 'errors'], properties: { source: str, errors: strList } }, docs_audit_read: { type: 'object', required: ['paths', 'reviewer', 'packet_sha256'], properties: { paths: strList, reviewer: str, packet_sha256: str } }, diff --git a/lib/review-collect.ts b/lib/review-collect.ts index d223eb7cd..cc1148086 100644 --- a/lib/review-collect.ts +++ b/lib/review-collect.ts @@ -171,7 +171,9 @@ type Hit = { name: string; sha?: string }; /** One `git grep -l` of `patterns` over a scratch index holding `entries` (`--cached` reads their blobs, otherwise the working tree), kept under the git dir as patch-id diffs are, so an unwritable TMPDIR cannot fail the scan; a spot it cannot write is a named scan failure. */ function grepIndex(root: string, entries: readonly string[], each: readonly string[], cached: boolean, deadline: number): string[] | GrepFailure { if (!entries.length) return []; - const at = path.resolve(root, gitUntil(root, ['rev-parse', '--git-path', 'gstack-consumers'], deadline).out.trim() || '.git/gstack-consumers'); + const where = gitUntil(root, ['rev-parse', '--git-path', 'gstack-consumers'], deadline); + if (where.status !== 0 || !where.out.trim()) return { status: where.status, err: `git rev-parse --git-path gstack-consumers gave no path (${where.err || `exit ${where.status}`}), and the scan does not guess .git/gstack-consumers: in a linked worktree .git is a file`, timedOut: where.timedOut }; + const at = path.resolve(root, where.out.trim()); let dir: string; try { fs.mkdirSync(at, { recursive: true }); dir = fs.mkdtempSync(path.join(at, 'scan-')); } catch (e) { return { status: null, err: `cannot create a scratch index under ${at} (${(e as Error).message.split('\n')[0]}); make that directory writable`, timedOut: false }; } try { diff --git a/lib/review-scope.ts b/lib/review-scope.ts index 00a5a61a8..8dd958f57 100644 --- a/lib/review-scope.ts +++ b/lib/review-scope.ts @@ -16,7 +16,7 @@ */ import * as path from 'node:path'; import { SPECIALISTS } from './review-depth'; -import { quarantinedIds, rank, readLedger, type LedgerBlocker } from './review-ledger'; +import { quarantinedIds, rank, readLedger, roleOf, type LedgerBlocker } from './review-ledger'; import { isSecurityFinding, opaqueFindingId, REDACTED_REASON } from './security-findings'; import { parseSpecialistOutput } from './state-matrix'; @@ -375,6 +375,8 @@ function rowLocus(f: Record): string | null { */ export interface LedgerPass { started: number; fixCheck: boolean; ids?: string[]; /** The ledger's pass directory (p1, p2, fc): a pN with no review row of pass N is named unbound. */ name?: string; + /** Every reader it collected was the targeted reader: the targeted-only read after the loop or a ruled edit (gstack-review-plan NEXT: targeted), which is not a review round, so no review row of its pass number backs it (GSTA-876 on #4853). */ + targetedOnly?: true; /** Whether judge ran on it at all (a rejected judgment counts): a pN pass never judged that no row names, replaced by a later judged or named pass, was abandoned (voided) and counts nothing (GBEV-3); a fix-check ledger and the last pass are never voided. */ judged?: boolean; } export function ledgerPass(ledger: string, key = (id: string) => id): LedgerPass { @@ -383,7 +385,9 @@ export function ledgerPass(ledger: string, key = (id: string) => id): LedgerPass const fixCheck = events.some(e => e.event === 'output' && e.reader === 'fix-check' && e.tree_ok !== false && ((Array.isArray(e.ids) && e.ids.length > 0) || e.review === true)); const gone = quarantinedIds(events); const ids = events.flatMap(e => (e.event === 'output' && Array.isArray(e.ids) ? (e.ids as string[]).filter(id => !gone.has(id)) : e.event === 'judgment' && e.kind === 'added' && typeof e.id === 'string' ? [e.id] : [])).map(key); - return { started: Number.isFinite(started) ? started : NaN, fixCheck, ids, name: path.basename(path.dirname(path.resolve(ledger))), judged: events.some(e => e.event === 'judge') }; + const readers = events.filter(e => e.event === 'rendered' || e.event === 'sent' || e.event === 'output'); + const targetedOnly = readers.some(e => e.event === 'output') && readers.every(e => typeof e.reader === 'string' && roleOf(e.reader) === 'targeted'); + return { started: Number.isFinite(started) ? started : NaN, fixCheck, ids, name: path.basename(path.dirname(path.resolve(ledger))), judged: events.some(e => e.event === 'judge'), ...(targetedOnly ? { targetedOnly: true as const } : {}) }; } /** A fix commit's `Review-Finding: reader=` trailer (receipt attribution): the finding that commit fixed. */ @@ -461,7 +465,7 @@ export function summarizeReviewLoop(rows: readonly Record[], since: } for (const p of ledgerPasses) { const n = passNo(p); - if (n !== undefined && Number.isFinite(n) && !passes.some(r => String(r.pass) === String(n))) unbound.push(`pass ${n} (ledger ${p.name}): no review-log row, so its fixes and dispositions cannot be counted`); + if (n !== undefined && Number.isFinite(n) && !p.targetedOnly && !passes.some(r => String(r.pass) === String(n))) unbound.push(`pass ${n} (ledger ${p.name}): no review-log row, so its fixes and dispositions cannot be counted`); } const known = ledgerPasses.some(p => p.ids) ? new Set(ledgerPasses.flatMap(p => p.ids ?? [])) : null; if (known) for (const [, s] of seen) if (s.ledgerId && !known.has(s.ledgerId)) unbound.push(`ledger_id ${s.ledgerId}: no dispatch ledger of this run collected it`); diff --git a/lib/review-targeted-delta.ts b/lib/review-targeted-delta.ts index 3acd17de8..68f08c04c 100644 --- a/lib/review-targeted-delta.ts +++ b/lib/review-targeted-delta.ts @@ -12,16 +12,37 @@ */ import { spawnSync } from './spawn-sync'; import { comparePath, touchedPaths } from './ship-patch'; -import { docsChangeSince } from './ship-receipt-depth'; +import { docsChangeSince, targetedClassesSince } from './ship-receipt-depth'; export type TargetedDelta = { state: 'dispatch'; range_base: string; paths: string[] } | { state: 'skip'; reason: string; carried?: true }; /** Whether the change since `rangeBase` (where the targeted reader read the patch `ran`) earns the targeted-only read. */ +const gitIn = (root: string) => (args: string[], input?: string) => { + const r = spawnSync('git', ['-c', 'core.quotePath=false', ...args], { cwd: root, input, encoding: 'utf8', timeout: 60_000, maxBuffer: 256 * 1024 * 1024 }); + return r.status === 0 ? r.stdout : null; +}; +/** The targeted patch-id at `read` (its committed diff against its merge base with `base`), as the TARGETED line prints it. */ +function patchAt(git: ReturnType, base: string, read: string): string | undefined { + const readBase = git(['merge-base', base, read])?.trim(); + const diff = readBase ? git(['diff', '--no-color', '--no-ext-diff', readBase, read]) : null; + return diff?.trim() ? git(['patch-id', '--verbatim'], diff)?.trim().split(/\s+/)[0] : undefined; +} + +/** + * Whether the targeted record a reader made at `rangeBase` (patch `ran`) carries to HEAD across a fix range every path of which + * the owner ruled (gstack-review-plan's RULED_EDIT): only when nothing the PR changed since carries a targeted class, the rule + * gstack-ship-receipt write's ruled carry applies (parseReviewTargeted, HARN-1 #638). Otherwise the plan dispatches the reader. + */ +export function ruledCarries(root: string, base: string, rangeBase: string, ran: string, excluded?: ReadonlySet): boolean { + const git = gitIn(root); + const read = git(['rev-parse', '--verify', '--quiet', `${rangeBase}^{commit}`])?.trim(); + const head = git(['rev-parse', '--verify', '--quiet', 'HEAD^{commit}'])?.trim(); + if (!read || !head || patchAt(git, base, read) !== ran) return false; + return targetedClassesSince(root, read, head, base, excluded)?.length === 0; +} + export function targetedDelta(root: string, base: string, rangeBase: string, ran: string): TargetedDelta { - const git = (args: string[], input?: string) => { - const r = spawnSync('git', ['-c', 'core.quotePath=false', ...args], { cwd: root, input, encoding: 'utf8', timeout: 60_000, maxBuffer: 256 * 1024 * 1024 }); - return r.status === 0 ? r.stdout : null; - }; + const git = gitIn(root); const skip = (reason: string, carried?: true): TargetedDelta => ({ state: 'skip', reason, ...(carried ? { carried } : {}) }); const read = git(['rev-parse', '--verify', '--quiet', `${rangeBase}^{commit}`])?.trim(); const head = git(['rev-parse', '--verify', '--quiet', 'HEAD^{commit}'])?.trim(); @@ -30,8 +51,7 @@ export function targetedDelta(root: string, base: string, rangeBase: string, ran const readBase = git(['merge-base', base, read])?.trim(); const headBase = git(['merge-base', base, head])?.trim(); if (!readBase || !headBase) return skip(`no merge base with ${base}`); - const diff = git(['diff', '--no-color', '--no-ext-diff', readBase, read]); - const readPatch = diff?.trim() ? git(['patch-id', '--verbatim'], diff)?.trim().split(/\s+/)[0] : undefined; + const readPatch = patchAt(git, base, read); if (!readPatch || readPatch !== ran) return skip(`--targeted-ran ${ran} is not the targeted patch at range_base ${read.slice(0, 12)} (${readPatch ?? 'unreadable'}), so it does not say what the reader read`); const before = touchedPaths(root, readBase, read); const now = touchedPaths(root, headBase, head); diff --git a/lib/ship-mechanical.ts b/lib/ship-mechanical.ts index 0a73a8d87..4806e0f98 100644 --- a/lib/ship-mechanical.ts +++ b/lib/ship-mechanical.ts @@ -21,6 +21,7 @@ import { comparePath, type PatchSides } from './ship-patch'; import { matchesAny } from './ship-policy'; import { constantValue, fieldValue, VALUE_SLOT, type MechanicalConstant } from './ship-policy-mechanical'; import { sidecarLine } from './ship-sidecar'; +import { gitPath } from './git-path'; export interface MechanicalRefusal { path: string; reason: string } export interface MechanicalInput { sides?: PatchSides; base: string; candidates: readonly string[]; declared: readonly MechanicalConstant[] } @@ -133,14 +134,13 @@ export function mechanicalPaths(cwd: string, i: MechanicalInput): { proven: Reco /** The PR body and receipt line for one mechanical path. */ export const mechanicalLine = (p: string, what: string) => `Mechanical retake: ${p} (${what})`; -function recordFile(cwd: string, tree: string): string { - const rel = spawnSync('git', ['rev-parse', '--git-path', `gstack/mechanical-${tree.slice(0, 12)}.json`], { cwd, encoding: 'utf8', timeout: 30_000 }).stdout?.trim(); - return path.resolve(cwd, rel || `.git/gstack/mechanical-${tree.slice(0, 12)}.json`); -} +const recordFile = (cwd: string, tree: string) => gitPath(cwd, `gstack/mechanical-${tree.slice(0, 12)}.json`); /** Saves finish's mechanical paths and Godot UID sidecars (path -> sibling) for the tree it routed, for gstack-ship-receipt write; the error message when it cannot. */ export function writeMechanicalRecord(cwd: string, tree: string, proven: Readonly>, sidecars: Readonly> = {}): string | null { - const file = recordFile(cwd, tree); + const where = recordFile(cwd, tree); + if (!where.ok) return where.error; + const file = where.path; try { fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, JSON.stringify({ tree, paths: proven, sidecars }) + '\n'); @@ -153,7 +153,9 @@ export function writeMechanicalRecord(cwd: string, tree: string, proven: Readonl /** The mechanical and sidecar lines finish recorded for exactly this tree, which the receipt's `mechanical` lists; none when it recorded none. */ export function readMechanicalLines(cwd: string, tree: string): string[] { try { - const v = JSON.parse(fs.readFileSync(recordFile(cwd, tree), 'utf8')); + const where = recordFile(cwd, tree); + if (!where.ok) return []; + const v = JSON.parse(fs.readFileSync(where.path, 'utf8')); if (v?.tree !== tree || !v.paths || typeof v.paths !== 'object') return []; const lines = (o: unknown, line: (p: string, w: string) => string) => Object.entries(o && typeof o === 'object' ? o : {}).filter(([, w]) => typeof w === 'string').map(([p, w]) => line(p, w as string)); return [...lines(v.paths, mechanicalLine), ...lines(v.sidecars, sidecarLine)].sort(); diff --git a/lib/ship-patch.ts b/lib/ship-patch.ts index 7ac5bcb4b..50adf8f4a 100644 --- a/lib/ship-patch.ts +++ b/lib/ship-patch.ts @@ -451,3 +451,36 @@ export function readScopedReview(file: string, bind: { head?: string; tree?: str if (missing.length) return { ok: false, message: `the scoped review does not cover ${missing.slice(0, 5).join(', ')}` }; return { ok: true, review: { paths: covered, reviewer: v.reviewer.trim(), verdict: 'clean', ...(v.head ? { head: v.head } : {}), ...(v.tree ? { tree: v.tree } : {}), ...(typeof v.packet_sha256 === 'string' ? { packet_sha256: v.packet_sha256 } : {}) } }; } + +/** + * Whether a path the carry calls changed is the reviewed branch change replayed onto the current base and nothing else + * (HARN-172 on harness-evals #625): the base's own change landed some of the branch's hunks byte for byte (both sides deleted + * the same JSON entry), so they left the branch's diff, which the product patch-id reads as a change. Absorbed only when + * `git merge-file` of reviewedBase -> reviewed onto currentBase is clean and gives current's exact bytes, with the mode the same + * three-way rule gives; a conflict, a hunk dropped or edited in the resolution, a binary or a non-file entry is not. + */ +export function absorbedByBase(repoRoot: string, s: PatchSides, rel: string): boolean { + const entry = (ref: string) => { + const r = spawnSync('git', ['--literal-pathspecs', 'ls-tree', '-z', '--full-tree', ref, '--', rel], { cwd: repoRoot, encoding: 'utf8', timeout: 60_000 }); + if (r.status !== 0) return null; + const rows = r.stdout.split('\0').filter(Boolean); + if (rows.length > 1 || rows.some(e => e.slice(e.indexOf('\t') + 1) !== rel)) return null; + const [mode, type, sha] = (rows[0] ?? '').split('\t')[0]!.split(' '); + return rows.length ? (type === 'blob' ? { key: `${mode} ${sha}`, mode: mode!, sha: sha! } : null) : { key: '', mode: '', sha: '' }; + }; + const [rb, rv, cb, cv] = [s.reviewedBase, s.reviewed, s.currentBase, s.current].map(entry); + if (!rb || !rv || !cb || !cv) return false; + const replay = (b: string, r: string, c: string) => (r === b ? c : c === b || c === r ? r : null); + if (!rb.sha || !rv.sha || !cb.sha || !cv.sha) return replay(rb.key, rv.key, cb.key) === cv.key; + if (replay(rb.mode, rv.mode, cb.mode) !== cv.mode) return false; + if ([rb, rv, cb, cv].some(e => e.mode !== '100644' && e.mode !== '100755')) return false; + const blobs = [cb, rb, rv, cv].map(e => spawnSync('git', ['cat-file', 'blob', e.sha], { cwd: repoRoot, timeout: 60_000, maxBuffer: 256 * 1024 * 1024 })); + if (blobs.some(b => b.status !== 0 || b.stdout.includes(0))) return false; + let dir: string; + try { dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ship-patch-absorbed-')); } catch { return false; } + try { + const files = ['current-base', 'reviewed-base', 'reviewed'].map((n, i) => { const f = path.join(dir, n); fs.writeFileSync(f, blobs[i]!.stdout); return f; }); + const merged = spawnSync('git', ['merge-file', '-p', '-q', ...files], { cwd: repoRoot, timeout: 60_000, maxBuffer: 256 * 1024 * 1024 }); + return merged.status === 0 && Buffer.from(merged.stdout).equals(blobs[3]!.stdout); + } finally { fs.rmSync(dir, { recursive: true, force: true }); } +} diff --git a/lib/ship-receipt-depth.ts b/lib/ship-receipt-depth.ts index 9dbaceab7..2842b74a6 100644 --- a/lib/ship-receipt-depth.ts +++ b/lib/ship-receipt-depth.ts @@ -38,6 +38,7 @@ import { mergeChangelogs } from './changelog-check'; import { bindReceipt, type ReceiptBindingCode } from './ship-receipt'; import { READ_REASONS, docsAuditPacket, readDocsAuditRead, type DocsAuditRead } from './docs-audit-read'; import { carriedAudits, docsExceptionLine, parseReceiptDocs, sameRun, type CarriedAudit } from './ship-receipt-docs'; +import { readRuledNotes, ruledEdits, type RuledNote } from './ruled-notes'; export type ReceiptDepth = NonNullable; const RANK: Record = { platform: -1, light: 0, standard: 1, full: 2 }; @@ -183,7 +184,7 @@ export type ReviewTargeted = NonNullable; * test change the gate scan tags is gate class though the product patch leaves tests out), so a record never vouches for work it * did not read (GST-986). `ancestor` only words the refusal: a read commit that is not HEAD's ancestor is named as such (GST-1700). */ -export function parseReviewTargeted(value: unknown, productPatchId: string, productPatchOf: (head: string) => string | undefined, classesSince?: (read: string) => readonly TargetedClass[] | null, plainDocs?: (read: string) => boolean, ancestor?: (read: string) => boolean): { ok: true; targeted: ReviewTargeted } | { ok: false; message: string } { +export function parseReviewTargeted(value: unknown, productPatchId: string, productPatchOf: (head: string) => string | undefined, classesSince?: (read: string) => readonly TargetedClass[] | null, plainDocs?: (read: string) => boolean, ancestor?: (read: string) => boolean, ruledSince?: (read: string) => readonly RuledNote[] | null): { ok: true; targeted: ReviewTargeted } | { ok: false; message: string } { const bad = (message: string) => ({ ok: false as const, message }); if (!value || typeof value !== 'object' || Array.isArray(value)) return bad('review_targeted must be { classes, rules, brief_sha, status, findings, raised_by, head }'); const v = value as Record; @@ -195,9 +196,11 @@ export function parseReviewTargeted(value: unknown, productPatchId: string, prod if (typeof v.findings !== 'number' || !Number.isInteger(v.findings) || v.findings < 0) return bad('review_targeted.findings must be an integer >= 0'); if (typeof v.head !== 'string' || !/^[0-9a-f]{40,64}$/.test(v.head)) return bad('review_targeted.head must be the commit the targeted reader read (rerun gstack-review-dispatch verify --targeted-out with this gstack)'); const read = productPatchOf(v.head); - if ((read !== productPatchId && !plainDocs?.(v.head)) || (classesSince && classesSince(v.head)?.length !== 0)) return bad(ancestor && !ancestor(v.head) ? `the targeted reader read ${v.head.slice(0, 12)}, which is not an ancestor of HEAD (usually after a rebase or a redone merge resolution, which rewrites the commit the reader read): a targeted record carries only from HEAD or an ancestor of it${read === productPatchId ? ', even when the product patch is unchanged' : ''}, so run the targeted reader on HEAD, rerun gstack-review-dispatch verify --targeted-out and write again` : `the targeted reader read ${v.head.slice(0, 12)}, whose product patch ${read?.slice(0, 12) ?? 'cannot be read'} is not this receipt's ${productPatchId.slice(0, 12)}: the product changed after the read (only release stamps and a docs change with no numeric, results, prereg, eval, money or security claim carry the record), so run the targeted reader on HEAD and verify again`); + const moved = read !== productPatchId && !plainDocs?.(v.head); + const ruled = moved ? ruledSince?.(v.head) ?? null : null; + if ((moved && !ruled) || (classesSince && classesSince(v.head)?.length !== 0)) return bad(ancestor && !ancestor(v.head) ? `the targeted reader read ${v.head.slice(0, 12)}, which is not an ancestor of HEAD (usually after a rebase or a redone merge resolution, which rewrites the commit the reader read): a targeted record carries only from HEAD or an ancestor of it${read === productPatchId ? ', even when the product patch is unchanged' : ''}, so run the targeted reader on HEAD, rerun gstack-review-dispatch verify --targeted-out and write again` : `the targeted reader read ${v.head.slice(0, 12)}, whose product patch ${read?.slice(0, 12) ?? 'cannot be read'} is not this receipt's ${productPatchId.slice(0, 12)}: the product changed after the read (only release stamps and a docs change with no numeric, results, prereg, eval, money or security claim carry the record, and so does a change whose every path the owner ruled with no targeted class in it), so run the targeted reader on HEAD and verify again`); const classes = TARGETED_CLASSES.filter(c => (v.classes as string[]).includes(c)); - return { ok: true, targeted: { classes, rules: v.rules as string, brief_sha: v.brief_sha, product_patch_id: productPatchId, status: v.status as ReviewTargeted['status'], findings: v.findings, raised_by: (v.raised_by as string).trim() } }; + return { ok: true, targeted: { classes, rules: v.rules as string, brief_sha: v.brief_sha, product_patch_id: productPatchId, status: v.status as ReviewTargeted['status'], findings: v.findings, raised_by: (v.raised_by as string).trim(), ...(ruled ? { read: v.head, ruled_edits: ruled.map(n => ({ path: n.finding.slice('edit:'.length), approval: n.approval, by: n.by })) } : {}) } }; } export interface DepthVerdict { ok: boolean; line: string; message?: string } @@ -611,6 +614,21 @@ export function docsChangeSince(root: string, from: string, head: string, base: /** Whether the PR's own change since `from` carries a targeted record: release stamps and plain docs only (docsChangeSince). */ export const plainDocsSince = (root: string, from: string, head: string, base: string): boolean => docsChangeSince(root, from, head, base)?.verdict === 'plain'; +/** + * The owner's `edit:` rulings (docs/ship-policy.md#ruled-edits) that clear every path the PR's own change moved from `from` + * to `head`, release stamps aside (productChangeSince), each at its ruled bytes as finish and gstack-review-plan read them + * (ruledEdits); null when a path has no clearing ruling, is deleted, or the change cannot be built. A targeted record carries + * across such a change only when nothing in it carries a targeted class (parseReviewTargeted, HARN-1 #638). + */ +export function ruledChangeSince(root: string, from: string, head: string, base: string): RuledNote[] | null { + const edits = readRuledNotes(root).filter(n => n.finding.startsWith('edit:')); + const change = edits.length ? productChangeSince(root, base, from, head) : null; + const c = change ? collectCommit(root, from, change.since) : null; + if (!c || c.errors.length || !c.paths.length) return null; + const { ruled } = ruledEdits(root, c.paths, head, edits); + return ruled.size === c.paths.length ? [...ruled.values()] : null; +} + /** * ownChangeSince less its release stamps: `since` holds the PR's own change after `from` with every path whose change is a * release stamp under the base policy (`stamps`, stampPathsSince) kept at `from`, the change the targeted classes and the docs @@ -631,7 +649,7 @@ function productChangeSince(root: string, base: string, from: string, head: stri * the CHANGELOG is read against `from`'s merged with the base's (mergeChangelogs, as a base merge resolves it), so the released * sections a base merge brings are not counted as the PR's own change; an unmergeable pair keeps `from`'s and fails closed. */ -function stampPathsSince(root: string, base: string, from: string, since: string, head: string): string[] { +export function stampPathsSince(root: string, base: string, from: string, since: string, head: string): string[] { const { ref, sha } = writeBase(root, base); const load = sha ? loadPolicyAt(root, sha, ref) : null; if (!sha || !load || isUnavailable(load) || load.errors.length) return []; diff --git a/lib/ship-receipt-patch.ts b/lib/ship-receipt-patch.ts index 89a2d3083..aa1cee44e 100644 --- a/lib/ship-receipt-patch.ts +++ b/lib/ship-receipt-patch.ts @@ -9,6 +9,7 @@ import * as fs from 'node:fs'; import * as path from 'node:path'; import { spawnSync } from './spawn-sync'; import { isRegistryUnavailable, loadRegistryFromBase } from './regen'; +import { gitPath } from './git-path'; import { readPregateFile } from './pregate/index'; import { isUnavailable, loadPolicyFromBase, matchesAny, type ShipPolicy } from './ship-policy'; import { stampOnlyLine, type BranchSide } from './stamp-only'; @@ -28,7 +29,9 @@ function git(args: string[], cwd?: string): string | undefined { */ export function patchId(repoRoot: string, from: string, to: string, pathspec: string[]): string | { error: string } { const firstLine = (s: string | null | undefined, fallback: string) => (s ?? '').trim().split('\n')[0]?.slice(0, 200) || fallback; - const root = path.resolve(repoRoot, git(['rev-parse', '--git-path', 'gstack-patch-id'], repoRoot)?.trim() || '.git/gstack-patch-id'); + const where = gitPath(repoRoot, 'gstack-patch-id'); + if (!where.ok) return { error: where.error }; + const root = where.path; sweepStalePatchDirs(root); let dir: string; try { fs.mkdirSync(root, { recursive: true }); dir = fs.mkdtempSync(path.join(root, 'run-')); } catch (e) { return { error: `cannot create a temp file under ${root} (${firstLine((e as Error).message, 'mkdtemp failed')}); make that directory writable` }; } diff --git a/lib/ship-receipt.ts b/lib/ship-receipt.ts index abdff1464..431a2ec37 100644 --- a/lib/ship-receipt.ts +++ b/lib/ship-receipt.ts @@ -301,6 +301,8 @@ export interface CarryPlanInput { baseContext?: string[]; /** Stamp files the branch changed as product whose only change since the reviewed head is a stamp on the branch's own rows, the base untouched, and without which the two product patches match (GST-980). */ stampedRows?: string[]; + /** Product paths whose change since the reviewed head is only branch hunks the base landed byte for byte (absorbedByBase, lib/ship-patch.ts, HARN-172): the reviewed change replayed onto the base, nothing unreviewed. */ + absorbed?: string[]; } export interface CarryRecord { from: string; reason: string; product_patch_id: string; changed_paths: string[]; merge_commits: number; range_diff: string; covers: string[]; reruns: string[]; trees?: string[]; ancestry?: 'linear' | 'rewritten' } export type CarryPlan = { ok: true; carry: CarryRecord } | { ok: false; code: 'RECEIPT_CARRY_PRODUCT_CHANGED' | 'RECEIPT_CARRY_REFUSED' | 'RECEIPT_CARRY_TREE_MISMATCH'; message: string }; @@ -369,7 +371,7 @@ export function classifyCarryPath(rel: string, extra: { metadata?: readonly stri * branch's own rows in a stamp file the branch also changed as product (`stampedRows`, GST-980). */ export function planCarry(input: CarryPlanInput): CarryPlan { - if (input.productPatchId.from !== input.productPatchId.head && (input.changedProduct.length || (!input.scopedReview && !input.stampedRows?.length && !input.baseContext?.length))) { + if (input.productPatchId.from !== input.productPatchId.head && (input.changedProduct.length || (!input.scopedReview && !input.stampedRows?.length && !input.baseContext?.length && !input.absorbed?.length))) { const named = input.changedProduct.slice(0, CARRY_NAMED_PATHS); return { ok: false, code: 'RECEIPT_CARRY_PRODUCT_CHANGED', message: `product diff changed between ${input.from.slice(0, 12)} and ${input.head.slice(0, 12)}: ${named.join(', ') || 'patch-id differs'}${input.changedProduct.length > named.length ? ` (+${input.changedProduct.length - named.length} more)` : ''}` }; } @@ -378,6 +380,7 @@ export function planCarry(input: CarryPlanInput): CarryPlan { if (input.mergeCommits > 0) reasons.push(input.mergeCommits === 1 ? 'base merge' : `${input.mergeCommits} base merges`); if (input.baseContext?.length && input.productPatchId.from !== input.productPatchId.head) reasons.push(`base context moved next to unchanged own lines (${input.baseContext.slice(0, CARRY_NAMED_PATHS).join(', ')}${input.baseContext.length > CARRY_NAMED_PATHS ? ` (+${input.baseContext.length - CARRY_NAMED_PATHS} more)` : ''}; CI at head checks it)`); if (input.scopedReview && input.productPatchId.from !== input.productPatchId.head) reasons.push(input.scopedReview); + if (input.absorbed?.length && input.productPatchId.from !== input.productPatchId.head) reasons.push(`branch hunks the base landed identically (${input.absorbed.slice(0, CARRY_NAMED_PATHS).join(', ')}${input.absorbed.length > CARRY_NAMED_PATHS ? ` (+${input.absorbed.length - CARRY_NAMED_PATHS} more)` : ''}; the reviewed change replayed onto the base)`); if (input.stampedRows?.length && input.productPatchId.from !== input.productPatchId.head) reasons.push(`a stamp on the branch's own rows (${input.stampedRows.join(', ')})`); if (input.testPatchId.from !== input.testPatchId.head) reasons.push('test-only change'); if (input.changed.some(c => c.class === 'metadata')) reasons.push('release metadata'); diff --git a/lib/ship-release.ts b/lib/ship-release.ts index dc9879cfc..7171d18a8 100644 --- a/lib/ship-release.ts +++ b/lib/ship-release.ts @@ -35,6 +35,7 @@ import { finishPlan, recordFinishPlan } from './plan-record'; import { PREPUSH_CHECK_IDS } from './pregate/index'; import { checkBranch, loadPlainTitlePolicy, type PlainFinding } from './plain-title'; import { buildRunCheck } from './pregate/run-check'; +import { gitPath } from './git-path'; import { bin, carryLane, carryNoneLines, evidenceExempt, firstLine, flagReader, fragmentPath, gh, git, hostedOrigin, laneLine, lanes, mappedLanes, recordCiTimeout, releasePaths, Report, runLanes, sh, shipPolicy, short, stampedFiles } from './ship-bin-common'; export const RELEASE_HELP = `gstack-ship-release — /ship Steps 12 and 15-17 (ship/SKILL.md) @@ -207,7 +208,7 @@ function harnessRepin(cwd: string, from: string, to: string, p: string): boolean * fingerprint, head in range, lib/gate-dispositions.ts) as GATE_DISPOSITION (GST-2491). Authored docs keep the stage 2.2 * recheck. A granted fix-check no longer counts as a review (GST-3562 part 4): an edit after the review bound is behavior. */ -type Routed = Record<'behavior' | 'docs' | 'metadata' | 'tests' | 'base' | 'context' | 'bounded' | 'mechanical' | 'sidecar', string[]>; +type Routed = Record<'behavior' | 'docs' | 'metadata' | 'tests' | 'base' | 'context' | 'bounded' | 'mechanical' | 'sidecar' | 'ruled', string[]>; type ReviewedBase = { commit: string; parent: boolean }; type RouteOpts = { docsRechecked: boolean; contextReviewed?: string; audited: Record | null; bookkeeping: readonly string[]; mechanical: readonly MechanicalConstant[]; testCode: readonly string[]; excluded: readonly string[]; baseRelease?: string[] }; @@ -271,7 +272,7 @@ function route(cwd: string, base: string, reviewed: string, reviewedBase: Review touched = new Set([...a, ...b]); shipped = b; } - const by: Routed = { behavior: [], docs: [], metadata: [], tests: [], base: [], context: [], bounded: [], mechanical: [], sidecar: [] }; + const by: Routed = { behavior: [], docs: [], metadata: [], tests: [], base: [], context: [], bounded: [], mechanical: [], sidecar: [], ruled: [] }; const isMetadata = (p: string) => parent && shipped.has(p) ? opts.baseRelease!.includes(p) || harnessRepin(cwd, sides!.currentBase, now, p) : release.includes(p) || harnessRepin(cwd, reviewed, now, p); const onlyShipped = new Set(parent ? [...shipped].filter(p => !changedSet.has(p)) : []); const baseSide = new Set(); @@ -300,8 +301,9 @@ function route(cwd: string, base: string, reviewed: string, reviewedBase: Review } printRulings(cwd, r); const edits = readRuledNotes(cwd).filter(n => n.finding.startsWith('edit:')); - const { ruled, refused: refusedEdits } = ruledEdits(cwd, by.behavior, now, edits); + const { ruled, refused: refusedEdits } = ruledEdits(cwd, [...by.behavior, ...by.docs], now, edits); by.behavior = by.behavior.filter(p => !ruled.has(p)); + by.ruled = [...ruled.keys()].sort(); const uid = uidSidecars(cwd, { sides, candidates: parent ? [] : by.behavior, excluded: opts.excluded }); by.sidecar = Object.keys(uid.proven).sort(); by.behavior = by.behavior.filter(p => !by.sidecar.includes(p)); @@ -319,7 +321,9 @@ function route(cwd: string, base: string, reviewed: string, reviewedBase: Review if (kept) { r.stop(`the mechanical and sidecar paths cannot be recorded for gstack-ship-receipt write (${kept}): make that directory writable, then rerun finish (stage 2.1)`); return null; } const scoped = [...by.context, ...by.tests, ...by.bounded].sort(); if (scoped.length && sides) { - const packet = path.resolve(cwd, git(cwd, ['rev-parse', '--git-path', `gstack/scoped-review-${now.slice(0, 12)}.md`]).stdout.trim() || `.git/gstack/scoped-review-${now.slice(0, 12)}.md`); + const where = gitPath(cwd, `gstack/scoped-review-${now.slice(0, 12)}.md`); + if (!where.ok) { r.stop(`the scoped-review packet has no place to go (${where.error}); rerun finish (stage 2.1)`); return null; } + const packet = where.path; const built = contextPacket(cwd, sides, by.context, by.tests, late()); if (!opts.contextReviewed) { const why = [by.context.length ? `the base merge spliced lines into the reviewed hunks in ${short(by.context)}` : '', by.tests.length ? `test code changed since review in ${short(by.tests)}` : '', @@ -349,7 +353,7 @@ function route(cwd: string, base: string, reviewed: string, reviewedBase: Review * version, each against the audited bytes; GST-906), and --docs-requested fixes the audit's own result asked for do not * stale the audit (GST-391). */ -function docsFresh(cwd: string, base: string, postFile: string, moved: readonly string[], requested: string[], resultFile: string | undefined, parent: string | undefined, testCode: readonly string[], r: Report): boolean { +function docsFresh(cwd: string, base: string, postFile: string, moved: readonly string[], ruled: readonly string[], requested: string[], resultFile: string | undefined, parent: string | undefined, testCode: readonly string[], r: Report): boolean { const cmp = bin(cwd, 'gstack-docs-candidate', ['compare', postFile], 120_000); let stale: string[] | null = null; try { stale = JSON.parse(cmp.stdout).content_changed; } catch { stale = null; } @@ -403,10 +407,10 @@ function docsFresh(cwd: string, base: string, postFile: string, moved: readonly return kept !== null && merged !== null && normalizeChangelog(kept) === normalizeChangelog(audited.stdout) && normalizeChangelog(merged) === normalizeChangelog(now); }); const carried = { tests: stale.filter(p => isTestCode(p, testCode)), base: stale.filter(p => !isTestCode(p, testCode) && (moved.includes(p) || restamped.includes(p) || (!!auditBase && !!nowBase && !branchAtAudit.has(p) && !branchNow.has(p)) - || (!!auditBase && !!nowBase && /^[0-9a-f]{40,64}$/.test(nowTree) && ![...record.staged, ...record.unstaged, ...record.untracked].includes(p) && comparePath(cwd, { reviewedBase: auditBase, reviewed: record.head, currentBase: nowBase, current: nowTree }, p) === 'same'))), requested: [] as string[], accepted: [] as string[], fix_checked: [] as string[] }; + || (!!auditBase && !!nowBase && /^[0-9a-f]{40,64}$/.test(nowTree) && ![...record.staged, ...record.unstaged, ...record.untracked].includes(p) && comparePath(cwd, { reviewedBase: auditBase, reviewed: record.head, currentBase: nowBase, current: nowTree }, p) === 'same'))), requested: [] as string[], accepted: [] as string[], fix_checked: [] as string[], ruled: stale.filter(p => ruled.includes(p)) }; let audit: any = null; try { audit = resultFile ? JSON.parse(fs.readFileSync(resultFile, 'utf8')) : null; } catch { audit = null; } - for (const p of requested.filter(q => stale!.includes(q) && !carried.tests.includes(q) && !carried.base.includes(q))) { + for (const p of requested.filter(q => stale!.includes(q) && !carried.tests.includes(q) && !carried.base.includes(q) && !carried.ruled.includes(q))) { const asked = [...(Array.isArray(audit?.blockers) ? audit.blockers : []), ...(Array.isArray(audit?.decisions) ? audit.decisions : [])].filter((s: unknown) => typeof s === 'string'); const token = new RegExp(`(^|[\\s\`'"(\\[])${p.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(?::\\d+(?::\\d+)?)?(?=$|[\\s\`'")\\]]|[,.:;](?:$|\\s))`); const stat = git(cwd, ['diff', '--numstat', '--no-renames', record.head, '--', `:(literal)${p}`]).stdout.trim().split(/\s+/); @@ -420,9 +424,9 @@ function docsFresh(cwd: string, base: string, postFile: string, moved: readonly if (why) { r.stop(`--docs-requested ${p} ${why}: use stage 3 recovery`); return false; } carried.requested.push(p); } - if (carried.requested.length && bin(cwd, 'gstack-ship-receipt', ['docs-caps', '--base', base], 60_000).status !== 0) { r.stop('a --docs-requested fix breaks a doc cap (gstack-ship-receipt docs-caps): trim the file, then rerun finish'); return false; } - const left = stale.filter(p => !carried.tests.includes(p) && !carried.base.includes(p) && !carried.requested.includes(p)); - const note = left.length || stale.length === 0 ? '' : ` (carried: tests=${carried.tests.length} base=${carried.base.length} requested=${carried.requested.length})`; + if ((carried.requested.length || carried.ruled.length) && bin(cwd, 'gstack-ship-receipt', ['docs-caps', '--base', base], 60_000).status !== 0) { r.stop('a --docs-requested fix or a ruled doc edit breaks a doc cap (gstack-ship-receipt docs-caps): trim the file, then rerun finish'); return false; } + const left = stale.filter(p => !carried.tests.includes(p) && !carried.base.includes(p) && !carried.requested.includes(p) && !carried.ruled.includes(p)); + const note = left.length || stale.length === 0 ? '' : ` (carried: tests=${carried.tests.length} base=${carried.base.length} requested=${carried.requested.length}${carried.ruled.length ? ` ruled=${carried.ruled.length}` : ''})`; const exception = record.exception ? ` (blocked; documentation exception accepted by ${record.exception.accepted_by} ${record.exception.date} via ${record.exception.via})` : ''; r.add(`DOCS: ${left.length ? `stale (${short(left)})` : `fresh against the Step 14.5 post-audit snapshot${note}${exception}`}`); if (left.length) { r.stop('documentation inputs changed since the accepted audit: use stage 3 recovery (the remaining re-audit, a fix the audit\'s result asked for via --docs-requested --docs-result -result.json, or a named risk); never refresh hashes'); return false; } @@ -480,7 +484,7 @@ async function finishStages(argv: readonly string[], cwd: string): Promise bin(cwd, 'gstack-evidence', ['check', '--label', l.label, '--expect-cmd', l.command, '--max-age', '24', '--allow-paths', allow], 60_000).stdout; @@ -508,7 +512,9 @@ async function finishStages(argv: readonly string[], cwd: string): Promise `--lane '${l.label}=${l.command.replace(/'/g, `'\\''`)}'`).join(' '); if (deferred.length) { - const out = path.resolve(cwd, git(cwd, ['rev-parse', '--git-path', 'gstack/pregate-finish-preflight.json']).stdout.trim() || '.git/gstack/pregate-finish-preflight.json'); + const where = gitPath(cwd, 'gstack/pregate-finish-preflight.json'); + if (!where.ok) return r.stop(`the preflight record has no place to go (${where.error}); rerun finish`); + const out = where.path; const pg = bin(cwd, 'gstack-pregate', ['--allow-repo-commands', '--base', base, '--stage', 'preflight', '--out', out], 3_600_000); const verdict = /^PREGATE: (.+?) tree=/m.exec(pg.stdout + pg.stderr)?.[1] ?? `unreadable (exit ${pg.status})`; r.add(`PREGATE: preflight ${verdict} on the stamped tree (the tests stage runs in accept, carried from CI)`); @@ -597,10 +603,11 @@ export async function accept(argv: readonly string[], cwd: string): Promise path.resolve(cwd, git(cwd, ['rev-parse', '--git-path', `gstack/${name}`]).stdout.trim() || `.git/gstack/${name}`); + const [guards, preflight] = ['pregate-guards.json', 'pregate-finish-preflight.json'].map(n => gitPath(cwd, `gstack/${n}`)); + if (!guards!.ok || !preflight!.ok) return { line: 'GUARDS: not run (no git directory path for their record)', stop: `${[guards, preflight].map(g => (g!.ok ? '' : g!.error)).find(Boolean)}: rerun push` }; const tree = git(cwd, ['rev-parse', 'HEAD^{tree}']).stdout.trim(); - const out = gitPath('pregate-guards.json'); - for (const file of [out, gitPath('pregate-finish-preflight.json')]) { + const out = guards!.path; + for (const file of [out, preflight!.path]) { let rec: { tree?: string; checks?: { id: string; status: string; detail?: string }[] }; try { rec = JSON.parse(fs.readFileSync(file, 'utf8')); } catch { continue; } const rows = PREPUSH_CHECK_IDS.map(id => rec.checks?.find(c => c.id === id)); @@ -655,7 +662,9 @@ function pushOnce(argv: readonly string[], cwd: string, r: Report): string { if (sealed.status === 1) return refuse(`sealed output would be published: ${firstLine(sealed.stderr)}; remove it from the commits, then repeat Step 16`); if (sealed.status !== 0) return refuse(`the sealed-output guard did not run (exit ${sealed.status}: ${firstLine(sealed.stderr || sealed.stdout)}); repair it, then rerun push`); if (has('--early')) { - const out = path.resolve(cwd, git(cwd, ['rev-parse', '--git-path', 'gstack/pregate-early-push.json']).stdout.trim() || '.git/gstack/pregate-early-push.json'); + const where = gitPath(cwd, 'gstack/pregate-early-push.json'); + if (!where.ok) return refuse(`the early-push secrets scan has no place for its record (${where.error}); rerun push --early`); + const out = where.path; const scan = bin(cwd, 'gstack-pregate', ['--stage', 'preflight', '--only', 'secrets', '--out', out, ...(flag('--base') ? ['--base', flag('--base')!] : [])], 600_000); const verdict = /^PREGATE: (.+?) tree=/m.exec(scan.stdout + scan.stderr)?.[1] ?? `unreadable (exit ${scan.status})`; r.add(`SECRETS: ${verdict} (early push)`); diff --git a/scripts/lib/windows-curation.ts b/scripts/lib/windows-curation.ts index 728283347..f73783918 100644 --- a/scripts/lib/windows-curation.ts +++ b/scripts/lib/windows-curation.ts @@ -484,6 +484,14 @@ export const KNOWN_WINDOWS_INCOMPATIBLE: Array<{ file: string; reason: string }> file: 'test/ship-finish-edit-ruling.test.ts', reason: 'drives bin/gstack-ship-release, gstack-approvals, gstack-docs-candidate and gstack-wtree (shebangs) through test/helpers/ship-bin-fixture.ts like test/ship-finish-ruled-notes.test.ts, whose every case fails on windows-latest at the first bin spawn', }, + { + file: 'test/git-path-worktree.test.ts', + reason: 'puts a POSIX shell script named git first on PATH to make one git call fail; windows-latest cannot run it as git', + }, + { + file: 'test/ship-receipt-carry-absorbed.test.ts', + reason: 'drives bin/gstack-ship-receipt write and carry (shebangs) through test/helpers/ship-bin-fixture.ts like test/ship-receipt-carry-mixed.test.ts; windows-latest fails every case at the first bin spawn (windows-scoped-shard on #4862)', + }, { file: 'test/review-pass-program.test.ts', reason: 'split from test/review-pass.test.ts, which Windows never ran (its POSIX mode-bit check): runs bin/gstack-review-dispatch (a shebang) and bash git fixtures through test/helpers/review-pass-harness.ts', diff --git a/test/git-path-worktree.test.ts b/test/git-path-worktree.test.ts new file mode 100644 index 000000000..4d71dfd8e --- /dev/null +++ b/test/git-path-worktree.test.ts @@ -0,0 +1,89 @@ +/** + * HARN-108: inside a linked worktree `.git` is a file (`gitdir: …`), so every gstack file kept under the git directory must + * come from `git rev-parse --git-path`; the literal `.git/` fallback used when git failed or timed out wrote through + * that file and died with ENOTDIR (gstack-review-plan's consumer scan on `.git/gstack-consumers`). + */ +import { afterEach, describe, expect, test } from 'bun:test'; +import { spawnSync } from 'node:child_process'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { gitPath } from '../lib/git-path'; +import { collectLive } from '../lib/review-collect'; +import { readMechanicalLines, writeMechanicalRecord } from '../lib/ship-mechanical'; +import { patchId } from '../lib/ship-receipt-patch'; + +const dirs: string[] = []; +const savedPath = process.env.PATH; +const savedScan = process.env.GSTACK_CONSUMER_SCAN_TIMEOUT_MS; +afterEach(() => { + process.env.PATH = savedPath; + if (savedScan === undefined) delete process.env.GSTACK_CONSUMER_SCAN_TIMEOUT_MS; else process.env.GSTACK_CONSUMER_SCAN_TIMEOUT_MS = savedScan; + while (dirs.length) fs.rmSync(dirs.pop()!, { recursive: true, force: true }); +}); + +function worktree() { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'git-path-')); + dirs.push(root); + const main = path.join(root, 'main'), wt = path.join(root, 'wt'); + fs.mkdirSync(main); + const git = (cwd: string, ...a: string[]) => spawnSync('git', a, { cwd, encoding: 'utf8', timeout: 30_000 }); + git(main, 'init', '-q', '-b', 'main'); git(main, 'config', 'user.email', 't@t'); git(main, 'config', 'user.name', 't'); git(main, 'config', 'commit.gpgsign', 'false'); + fs.writeFileSync(path.join(main, 'README.md'), '# x\n'); git(main, 'add', '.'); git(main, 'commit', '-qm', 'base'); + expect(git(main, 'worktree', 'add', '-q', '-b', 'feat', wt).status).toBe(0); + fs.mkdirSync(path.join(wt, 'src')); fs.writeFileSync(path.join(wt, 'src', 'a.ts'), 'export const a = 1;\n'); + git(wt, 'add', '.'); git(wt, 'commit', '-qm', 'feat'); + return { main, wt, git }; +} +/** A PATH whose git fails the calls whose arguments match the shell pattern `only` (every call by default), as a hung or killed git looks to the callers. */ +function brokenGit(only = '*'): void { + const real = path.join(spawnSync('git', ['--exec-path'], { encoding: 'utf8', timeout: 10_000 }).stdout.trim(), 'git'); + const bin = fs.mkdtempSync(path.join(os.tmpdir(), 'git-path-bin-')); + dirs.push(bin); + fs.writeFileSync(path.join(bin, 'git'), `#!/bin/sh\ncase "$*" in ${only}) echo "fatal: simulated failure" >&2; exit 128;; esac\nexec '${real}' "$@"\n`, { mode: 0o755 }); + process.env.PATH = `${bin}${path.delimiter}${savedPath}`; +} + +// Value: protects=gstack files under the git dir land in the worktree's own git dir; fails_when=a caller writes through the +// .git file (ENOTDIR) or guesses .git/ after git fails; seam=lib/git-path.ts and its callers in a real git worktree +describe('git-dir paths in a linked worktree (HARN-108)', () => { + test('a real worktree: the paths resolve under its gitdir and the writers succeed', () => { + const { wt, main, git } = worktree(); + expect(fs.statSync(path.join(wt, '.git')).isFile()).toBe(true); + const at = gitPath(wt, 'gstack-consumers'); + expect(at.ok).toBe(true); + if (!at.ok) return; + expect(at.path.startsWith(path.join(fs.realpathSync(main), '.git')) || at.path.startsWith(path.join(main, '.git'))).toBe(true); + fs.mkdirSync(at.path, { recursive: true }); + const base = git(wt, 'rev-parse', 'main').stdout.trim(), head = git(wt, 'rev-parse', 'HEAD').stdout.trim(); + expect(typeof patchId(wt, base, head, ['.'])).toBe('string'); + const tree = git(wt, 'rev-parse', 'HEAD^{tree}').stdout.trim(); + expect(writeMechanicalRecord(wt, tree, { 'src/a.ts': 'golden, regenerated by x' })).toBeNull(); + expect(readMechanicalLines(wt, tree)).toEqual(['Mechanical retake: src/a.ts (golden, regenerated by x)']); + }); + + test('git failing: every writer names the failure and nothing is written through the .git file', () => { + const { wt, git } = worktree(); + const base = git(wt, 'rev-parse', 'main').stdout.trim(), head = git(wt, 'rev-parse', 'HEAD').stdout.trim(); + const tree = git(wt, 'rev-parse', 'HEAD^{tree}').stdout.trim(); + brokenGit(); + const at = gitPath(wt, 'gstack-patch-id'); + expect(at).toEqual({ ok: false, error: expect.stringContaining('gstack does not guess .git/gstack-patch-id') }); + const id = patchId(wt, base, head, ['.']); + expect(id).toEqual({ error: expect.stringContaining('git rev-parse --git-path gstack-patch-id gave no path') }); + expect(JSON.stringify(id)).not.toContain('ENOTDIR'); + expect(writeMechanicalRecord(wt, tree, { 'src/a.ts': 'x' })).toContain('gave no path'); + expect(fs.statSync(path.join(wt, '.git')).isFile()).toBe(true); + }); + + test('the consumer scan in a worktree whose git dir lookup fails names it, not ENOTDIR on .git/gstack-consumers', () => { + const { wt, git } = worktree(); + fs.mkdirSync(path.join(wt, 'data')); fs.writeFileSync(path.join(wt, 'data', 'rows.json'), '[1]\n'); + fs.writeFileSync(path.join(wt, 'src', 'read.ts'), "export const f = 'data/rows.json';\n"); + git(wt, 'add', '.'); git(wt, 'commit', '-qm', 'data'); + brokenGit('*"--git-path gstack-consumers"*'); + const errors = JSON.stringify(collectLive(wt, 'main').errors); + expect(errors).toContain('git rev-parse --git-path gstack-consumers gave no path'); + expect(errors).not.toContain('ENOTDIR'); + }); +}); diff --git a/test/ship-finish-edit-ruling.test.ts b/test/ship-finish-edit-ruling.test.ts index f8547882a..4bf702197 100644 --- a/test/ship-finish-edit-ruling.test.ts +++ b/test/ship-finish-edit-ruling.test.ts @@ -7,6 +7,7 @@ import { afterEach, describe, expect, setDefaultTimeout, test } from 'bun:test'; import * as fs from 'node:fs'; import * as path from 'node:path'; +import { DOCS_CAPS_KEY_VERSION } from '../lib/ship-policy'; import { lineOf, RELEASE, shipFixture, type ShipFx } from './helpers/ship-bin-fixture'; setDefaultTimeout(90_000); @@ -113,3 +114,52 @@ describe('finish honours an edit ruling after the final review (GST-3775)', () = expect(lineOf(r.stdout, 'RULED_EDIT_REFUSED')).toStartWith(`RULED_EDIT_REFUSED: ${routed} (its spelling holds a replacement character (U+FFFD)`); }); }); + +/** GBRA-108 (gbrain #10492, #10494): Step 14.5's audit hashed `file`, an edit to it followed the final review, and the owner ruled it. */ +function docEditedAfterAudit(file: string, base: Record = {}) { + const f = shipFixture({ 'src/x.ts': 'export const x = 1;\n', [file]: '# Notes\n\nOne line.\n', ...base }, { 'src/x.ts': 'export const x = 2;\n' }); + ships.push(f); + const reviewed = f.run(path.join(BIN, 'gstack-wtree'), []).stdout.trim(); + const post = path.join(f.root, 'post.json'); + expect(f.run(path.join(BIN, 'gstack-docs-candidate'), ['snapshot', '--out', post, '--audit-id', 'a1', '--mode', 'edit', '--base', 'main', '--docs', file]).status).toBe(0); + f.write({ [file]: '# Notes\n\nOne line.\nA second line the audit asked for.\n' }); f.commit('docs audit edit after the final review'); + return { f, stopHead: f.git('rev-parse', 'HEAD').stdout.trim(), reviewed, post }; +} +const finishRechecked = (f: ShipFx, reviewed: string, post: string) => f.run(RELEASE, ['finish', '--base', 'main', '--reviewed-tree', reviewed, '--docs-post', post, '--docs-rechecked', '--lane', LANE]); + +// Value: protects=a ruled edit to a doc the docs audit hashed carries finish's freshness check, at the ruled bytes only; +// fails_when=finish prints DOCS: stale () after RULED_EDIT (GBRA-108), or an unruled doc edit, or one edited again after +// its ruling, passes as fresh; seam=lib/ship-release.ts route's ruled paths into docsFresh +describe('a ruled edit to an audited doc keeps the docs audit fresh (GBRA-108)', () => { + test('agent-prose policy doc (behavior) and a plain doc: ruled, each carries as ruled=1', () => { + for (const file of ['docs/ship-policy.md', 'README.md']) { + const { f, stopHead, reviewed, post } = docEditedAfterAudit(file); + const before = finishRechecked(f, reviewed, post); + expect([file, before.status]).toEqual([file, 3]); + expect(rule(f, file, stopHead).status).toBe(0); + const r = finishRechecked(f, reviewed, post); + expect([file, lineOf(r.stdout, 'RULED_EDIT')]).toEqual([file, expect.stringContaining(`RULED_EDIT: ${file} (ruled at ${stopHead.slice(0, 12)}`)]); + expect([file, lineOf(r.stdout, 'DOCS')]).toEqual([file, 'DOCS: fresh against the Step 14.5 post-audit snapshot (carried: tests=0 base=0 requested=0 ruled=1)']); + } + }); + + test('an unruled doc edit, or a doc edited again after its ruling, is still stale', () => { + const plain = docEditedAfterAudit('README.md'); + expect(lineOf(finishRechecked(plain.f, plain.reviewed, plain.post).stdout, 'DOCS')).toBe('DOCS: stale (README.md)'); + const later = docEditedAfterAudit('README.md'); + expect(rule(later.f, 'README.md', later.stopHead).status).toBe(0); + later.f.write({ 'README.md': '# Notes\n\nOne line.\nA different line.\n' }); later.f.commit('edit it again'); + const r = finishRechecked(later.f, later.reviewed, later.post); + expect(lineOf(r.stdout, 'RULED_EDIT_REFUSED')).toStartWith('RULED_EDIT_REFUSED: README.md ('); + expect(lineOf(r.stdout, 'DOCS')).toBe('DOCS: stale (README.md)'); + }); + + test('a ruled doc edit that breaks a doc cap the base declares stops finish', () => { + const policy = JSON.stringify({ docs: { caps: [{ path: 'README.md', max_bytes: 30 }] }, min_gstack_version: DOCS_CAPS_KEY_VERSION }); + const { f, stopHead, reviewed, post } = docEditedAfterAudit('README.md', { '.gstack/ship-policy.json': policy }); + expect(rule(f, 'README.md', stopHead).status).toBe(0); + const r = finishRechecked(f, reviewed, post); + expect([r.status, r.stdout]).toEqual([3, expect.stringContaining('a ruled doc edit breaks a doc cap')]); + }); +}); + diff --git a/test/ship-receipt-carry-absorbed.test.ts b/test/ship-receipt-carry-absorbed.test.ts new file mode 100644 index 000000000..433774cb9 --- /dev/null +++ b/test/ship-receipt-carry-absorbed.test.ts @@ -0,0 +1,95 @@ +/** + * HARN-172 (harness-evals #625): the branch deleted one JSON array entry, main then deleted the same entry, and the lane merged + * origin/main. The branch's diff against the new base lost that hunk, so the product patch-id moved and carry refused with + * RECEIPT_CARRY_PRODUCT_CHANGED, forcing a fresh full review of a head whose every byte was reviewed. A path is now carried when + * it is exactly the reviewed change replayed onto the new base (absorbedByBase); a hunk dropped or edited in the resolution, or + * any other change, still refuses. + */ +import { afterEach, describe, expect, setDefaultTimeout, test } from 'bun:test'; +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import { EXIT } from '../lib/headless-artifacts'; +import { absorbedByBase, comparePath } from '../lib/ship-patch'; +import { extractReceipt } from '../lib/ship-receipt'; +import { RELEASE, shipFixture, type ShipFx } from './helpers/ship-bin-fixture'; + +setDefaultTimeout(120_000); +const BIN = path.dirname(RELEASE); +const RECEIPT = path.join(BIN, 'gstack-ship-receipt'); +const UNATTENDED = { GSTACK_SESSION_KIND: 'unattended' }; +const ships: ShipFx[] = []; +afterEach(() => { while (ships.length) ships.pop()!.cleanup(); }); + +const LIST = 'config/cases.json'; +const CODE = 'src/run.ts'; +const list = (ids: string[]) => `[\n${ids.map(i => ` "${i}"`).join(',\n')}\n]\n`; +const code = (n: number) => Array.from({ length: 12 }, (_, i) => `export const v${i + 1} = ${i + 1 === 6 ? n : i + 1};`).join('\n') + '\n'; +const ALL = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']; +const without = (...gone: string[]) => ALL.filter(i => !gone.includes(i)); + +/** The branch drops case "c" and edits run.ts; its receipt is written at that head; main then lands `baseList`. */ +function absorbed(baseList: string[], resolved?: Record) { + const f = shipFixture({ [LIST]: list(ALL), [CODE]: code(6) }, { [LIST]: list(without('c')), [CODE]: code(60) }); + ships.push(f); + const from = f.git('rev-parse', 'HEAD').stdout.trim(); + const reviewedBase = f.git('merge-base', 'origin/main', 'HEAD').stdout.trim(); + const body = path.join(f.root, 'body.md'); + fs.writeFileSync(body, '## Summary\n'); + const w = f.run(RECEIPT, ['write', '--pr', '5', '--base', 'main', '--body', body], UNATTENDED); + expect([w.status, w.stderr.slice(0, 400)]).toEqual([EXIT.ok, expect.any(String)]); + f.advanceBase({ [LIST]: list(baseList) }); + f.git('fetch', '-q', 'origin'); + if (f.git('merge', '-q', '--no-edit', 'origin/main').status !== 0 || resolved) { f.write(resolved ?? {}); f.commit('merge main'); } + const head = f.git('rev-parse', 'HEAD').stdout.trim(); + const sides = { reviewedBase, reviewed: from, currentBase: f.git('merge-base', 'origin/main', 'HEAD').stdout.trim(), current: head }; + const carry = () => f.run(RECEIPT, ['carry', '--body', body, '--base', 'main'], UNATTENDED); + return { f, sides, body, carry }; +} + +describe('receipt carry across a base merge that landed one of the branch\'s hunks (HARN-172)', () => { + // Value: protects=a clean base merge in which main made the branch's exact deletion keeps the receipt; fails_when=carry refuses + // RECEIPT_CARRY_PRODUCT_CHANGED for a head with no unreviewed byte (harness-evals #625); seam=gstack-ship-receipt carry and + // absorbedByBase on a real merge + test('main deleted the same entry: the path is absorbed and the receipt carries, naming it', () => { + const x = absorbed(without('c')); + expect(comparePath(x.f.work, x.sides, LIST)).toBe('changed'); + expect(absorbedByBase(x.f.work, x.sides, LIST)).toBe(true); + const r = x.carry(); + expect([r.status, r.stderr.slice(0, 600)]).toEqual([EXIT.ok, expect.any(String)]); + expect(extractReceipt(fs.readFileSync(x.body, 'utf8')).receipt!.carry!.reason).toContain(`branch hunks the base landed identically (${LIST}`); + }); + + test('main deleted the same entry and another one: still only the reviewed change replayed, so it carries', () => { + const x = absorbed(without('c', 'g')); + expect(absorbedByBase(x.f.work, x.sides, LIST)).toBe(true); + expect(x.carry().status).toBe(EXIT.ok); + }); + + test('a TMPDIR it cannot write reads as not absorbed instead of crashing the carry', () => { + const x = absorbed(without('c')); + const r = x.f.run(RECEIPT, ['carry', '--body', x.body, '--base', 'main'], { ...UNATTENDED, TMPDIR: path.join(x.f.root, 'missing', 'tmp') }); + expect([r.status === EXIT.ok, r.stderr.includes('RECEIPT_CARRY_PRODUCT_CHANGED')]).toEqual([false, true]); + }); + + test('a symlink is never absorbed: its target is not text to merge', () => { + const f = shipFixture({ [LIST]: list(ALL) }, { [CODE]: code(6) }); + ships.push(f); + const link = (to: string, msg: string) => { fs.rmSync(path.join(f.work, 'link'), { force: true }); fs.symlinkSync(to, path.join(f.work, 'link')); f.commit(msg); return f.git('rev-parse', 'HEAD').stdout.trim(); }; + const before = link('a', 'link to a'), after = link('b', 'link to b'); + expect(absorbedByBase(f.work, { reviewedBase: before, reviewed: after, currentBase: after, current: after }, 'link')).toBe(false); + }); + + // Value: protects=the fail-closed controls; fails_when=a resolution that drops or edits a branch hunk main never landed, or that + // restores an entry main deleted, carries; seam=absorbedByBase and gstack-ship-receipt carry + test('a resolution that also drops a hunk main never landed, edits a line, or keeps an entry main removed still refuses', () => { + for (const [name, resolved] of [ + ['dropped the branch edit to run.ts', { [CODE]: code(6) }], + ['edited the list', { [LIST]: list(without('c', 'd')) }], + ['kept an entry main removed', { [LIST]: list(without('c')) }], + ] as const) { + const x = absorbed(without('c', 'g'), resolved); + const r = x.carry(); + expect([name, r.status === EXIT.ok, r.stderr.includes('RECEIPT_CARRY_PRODUCT_CHANGED')]).toEqual([name, false, true]); + } + }); +}); diff --git a/test/ship-ruled-edit-targeted.test.ts b/test/ship-ruled-edit-targeted.test.ts new file mode 100644 index 000000000..a09a7f75e --- /dev/null +++ b/test/ship-ruled-edit-targeted.test.ts @@ -0,0 +1,142 @@ +/** + * HARN-1 (harness-evals #638, #646, #632, #644, #490; GSTA-876 on gstack #4853): past R51's two rounds, the lane's Captain rules a + * small edit after the read-only final review in (`gstack-approvals rule --finding edit:`). The plan then still stopped + * ("a fix followed the read-only final review"), because the fix range held the release stamps Step 12 wrote, which nobody rules, + * and the receipt refused the targeted record read before the edit, so the only exit was another whole read-only full review. + * Now stamps carry without a ruling, a ruled range with no targeted class in it carries the record (and the receipt names the + * rulings that carried it), and a ruled range that does touch a targeted class plans exactly one targeted reader. + */ +import { afterEach, describe, expect, setDefaultTimeout, test } from 'bun:test'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { ledgerPass, summarizeReviewLoop } from '../lib/review-scope'; +import { parseReviewTargeted, plainDocsSince, ruledChangeSince, targetedClassesSince } from '../lib/ship-receipt-depth'; +import { spawnSync } from '../lib/spawn-sync'; +import { BASE_POLICY, cleanup, makeFixtureRepo, runBin, type FixtureRepo } from './helpers/restamp-fixture'; + +setDefaultTimeout(120_000); +const repos: FixtureRepo[] = []; +const dirs: string[] = []; +const saved = { ...process.env }; +afterEach(() => { process.env = { ...saved }; while (repos.length) cleanup(repos.pop()!); while (dirs.length) fs.rmSync(dirs.pop()!, { recursive: true, force: true }); }); + +const MONEY_CODE = 'export const spendCapUsd = 25;\nexport function charge(amountUsd: number) { if (amountUsd > spendCapUsd) throw new Error("over cap"); return amountUsd; }\n'; +const UTIL = 'export const label = (s: string) => s.trim();\n'; +const ENV = { GSTACK_APPROVALS_MIRROR: '0' }; +const run = (repo: FixtureRepo, name: string, args: string[]) => { const r = runBin(repo, name, args, ENV); return { status: r.status, stdout: r.out, stderr: r.err }; }; + +/** A money-class PR whose final review (and its targeted reader) read `passHead`, then Step 12's stamps, then one more edit. */ +function shipped(edit: Record) { + const repo = makeFixtureRepo({ policy: BASE_POLICY }); + repos.push(repo); + const write = (files: Record, msg: string) => { + for (const [p, text] of Object.entries(files)) { fs.mkdirSync(path.dirname(path.join(repo.work, p)), { recursive: true }); fs.writeFileSync(path.join(repo.work, p), text); } + repo.git('add', '-A'); repo.git('commit', '-q', '-m', msg); + return repo.git('rev-parse', 'HEAD'); + }; + const log = fs.readFileSync(path.join(repo.work, 'CHANGELOG.md'), 'utf8'); + repo.git('checkout', '-q', '-b', 'feat'); + const passHead = write({ 'src/billing.ts': MONEY_CODE, 'src/util.ts': UTIL, 'CHANGELOG.md': log.replace('## [1.2.3.0]', '## [Unreleased]\n\n- charge() caps spend\n\n## [1.2.3.0]') }, 'feat'); + write({ VERSION: '1.2.4.0\n', 'CHANGELOG.md': log.replace('## [1.2.3.0]', '## [1.2.4.0] - 2026-11-27\n\n- charge() caps spend\n\n## [1.2.3.0]') }, 'release stamps'); + const head = write(edit, 'edit after the read-only final review'); + return { repo, passHead, head }; +} +const rule = (repo: FixtureRepo, file: string, head: string) => run(repo, 'gstack-approvals', ['rule', '--finding', `edit:${file}`, '--head', head, '--reason', 'a one-line edit after the final review ships as a disclosed note', '--words', 'ship it with the note', '--by', 'GStack Minder (GSTA-36)']); +const plan = (repo: FixtureRepo, args: string[]) => run(repo, 'gstack-review-plan', ['--base', 'main', '--post-review', '--pass', '3', '--last', 'full', '--adversarial-ran', ...args]); +const patchAt = (repo: FixtureRepo, rev: string) => { + repo.git('checkout', '-q', rev); + try { return JSON.parse(run(repo, 'gstack-review-plan', ['--base', 'main', '--json']).stdout).targeted.targeted_patch_id as string; } finally { repo.git('checkout', '-q', 'feat'); } +}; +const next = (stdout: string) => stdout.split('\n').find(l => l.startsWith('NEXT: ')) ?? ''; +const dispatches = (stdout: string) => stdout.split('\n').filter(l => l.startsWith('DISPATCH: ')); + +/** parseReviewTargeted with the receipt's own predicates (bin/gstack-ship-receipt write), for a record the reader made at `read`. */ +function bind(repo: FixtureRepo, read: string, head: string) { + Object.assign(process.env, repo.env, ENV); + delete process.env.GSTACK_APPROVALS_DIR; + const productOf = (c: string) => spawnSync('git', ['patch-id', '--verbatim'], { input: spawnSync('git', ['diff', 'main', c, '--', '.', ':(exclude)VERSION', ':(exclude)CHANGELOG.md'], { cwd: repo.work, encoding: 'utf8', timeout: 10_000 }).stdout, cwd: repo.work, encoding: 'utf8', timeout: 10_000 }).stdout.split(' ')[0]; + const record = { classes: ['money'], rules: 'r', brief_sha: 'a'.repeat(64), status: 'done', findings: 0, raised_by: 'targeted', head: read }; + return parseReviewTargeted(record, productOf(head)!, productOf, from => targetedClassesSince(repo.work, from, head, 'main'), from => plainDocsSince(repo.work, from, head, 'main'), undefined, from => ruledChangeSince(repo.work, from, head, 'main')); +} + +describe('a Captain-ruled edit after the read-only final review (HARN-1)', () => { + // Value: protects=a ruled edit outside every targeted class ships on the record the final review's targeted reader made, with + // the rulings recorded; fails_when=the plan stops on the release stamps in the fix range, or the receipt refuses the record + // read before the ruled edit (RECEIPT_INVALID), forcing a whole new read-only full review; seam=bin/gstack-review-plan + // --range-base and parseReviewTargeted with ruledChangeSince + test('a ruled edit with no targeted class: the plan is done and the receipt carries the record, naming the ruling', () => { + const { repo, passHead, head } = shipped({ 'src/util.ts': UTIL.replace('trim()', 'trim().toLowerCase()') }); + const ran = patchAt(repo, passHead); + expect(next(plan(repo, ['--range-base', passHead, '--targeted-ran', ran]).stdout)).toStartWith('NEXT: stop ('); + expect(bind(repo, passHead, head).ok).toBe(false); + expect(rule(repo, 'src/util.ts', head).status).toBe(0); + const p = plan(repo, ['--range-base', passHead, '--targeted-ran', ran]); + expect(p.status, p.stderr).toBe(0); + expect(p.stdout).toContain(`FIX_RANGE: runtime_lines=0 base=${passHead} ruled=1`); + expect(next(p.stdout)).toStartWith('NEXT: done (every edit since --range-base is ruled a note (RULED_EDIT)'); + expect(dispatches(p.stdout)).toEqual([]); + expect(p.stdout).toContain(`SKIP: targeted-only read (every edit since --range-base is ruled a note and none carries a targeted class, so the record read at ${passHead.slice(0, 12)} carries`); + const b = bind(repo, passHead, head); + expect(b).toMatchObject({ ok: true, targeted: { classes: ['money'], read: passHead, ruled_edits: [{ path: 'src/util.ts', approval: expect.stringMatching(/^a-[0-9a-f]{12}$/), by: 'GStack Minder (GSTA-36)' }] } }); + const unread = plan(repo, ['--range-base', passHead]); + expect(next(unread.stdout)).toStartWith('NEXT: targeted ('); + expect(dispatches(unread.stdout)).toEqual(['DISPATCH: targeted targeted effort=full classes=money']); + }); + + // Value: protects=a ruled edit that changes money code gets exactly one targeted reader on HEAD (not a round, not a full review) + // and the old record never carries it; fails_when=the plan stops for a new full review, or the receipt binds the record read + // before the money edit; seam=bin/gstack-review-plan and parseReviewTargeted + test('a ruled edit in money code: one targeted reader on HEAD, and the earlier record does not carry', () => { + const { repo, passHead, head } = shipped({ 'src/billing.ts': MONEY_CODE.replace('25', '30') }); + const ran = patchAt(repo, passHead); + expect(rule(repo, 'src/billing.ts', head).status).toBe(0); + const p = plan(repo, ['--range-base', passHead, '--targeted-ran', ran]); + expect(p.status, p.stderr).toBe(0); + expect(next(p.stdout)).toStartWith('NEXT: targeted (the loop is done and every edit since --range-base is ruled a note'); + expect(dispatches(p.stdout)).toEqual(['DISPATCH: targeted targeted effort=full classes=money']); + expect(bind(repo, passHead, head)).toMatchObject({ ok: false, message: expect.stringContaining('the product changed after the read') }); + expect(bind(repo, head, head).ok).toBe(true); + }); + + // Value: protects=the fail-closed negative controls; fails_when=an unruled edit, or a ruling that misses one changed path, + // plans no reader or carries the record; seam=bin/gstack-review-plan and parseReviewTargeted + test('an unruled path, or a ruling that misses one of the edited paths, still stops and still refuses the record', () => { + const { repo, passHead, head } = shipped({ 'src/util.ts': UTIL.replace('trim()', 'trim().toLowerCase()'), 'src/other.ts': 'export const o = 1;\n' }); + const ran = patchAt(repo, passHead); + expect(rule(repo, 'src/util.ts', head).status).toBe(0); + const p = plan(repo, ['--range-base', passHead, '--targeted-ran', ran]); + expect(next(p.stdout)).toStartWith('NEXT: stop ('); + expect(p.stdout).toContain(`--finding 'edit:src/other.ts' --head ${head}`); + expect(p.stdout).not.toContain("--finding 'edit:VERSION'"); + expect(bind(repo, passHead, head).ok).toBe(false); + }); +}); + +// Value: protects=the targeted-only read (one targeted reader on HEAD after a ruled edit, not a review round) counts as bound; +// fails_when=review-scope prints REVIEW_SCOPE_UNBOUND: pass 3 (ledger p3) for it (GSTA-876 on #4853), or a real pass 3 with +// no review row stops being named; seam=lib/review-scope.ts ledgerPass and summarizeReviewLoop +describe('a targeted-only read has no review row and is not unbound (GSTA-876)', () => { + const since = '2026-11-26T19:00:00Z'; + const rows = [1, 2].map(pass => ({ skill: 'review', via: 'ship', pass, timestamp: `2026-11-26T19:0${pass}:00Z`, commit_full: String(pass).repeat(40), findings: [] })); + function ledger(reader: string, more: Record[] = []): string { + const dir = path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'targeted-only-')), 'p3'); + fs.mkdirSync(dir); + dirs.push(path.dirname(dir)); + const file = path.join(dir, 'review-ledger.jsonl'); + fs.writeFileSync(file, [{ event: 'rendered', reader, at: '2026-11-26T19:10:00Z' }, ...more, { event: 'output', reader, ids: [] }].map(e => JSON.stringify(e)).join('\n') + '\n'); + return file; + } + test('p3 with only the targeted reader is bound; p3 with any other reader is still unbound', () => { + const only = ledgerPass(ledger('targeted')); + expect(only.targetedOnly).toBe(true); + expect(summarizeReviewLoop(rows, since, [[]], [only]).unbound).toBeUndefined(); + const other = ledgerPass(ledger('red-team')); + expect(other.targetedOnly).toBeUndefined(); + expect(summarizeReviewLoop(rows, since, [[]], [other]).unbound).toEqual(['pass 3 (ledger p3): no review-log row, so its fixes and dispositions cannot be counted']); + const silent = ledgerPass(ledger('targeted', [{ event: 'rendered', reader: 'red-team' }, { event: 'sent', reader: 'red-team' }])); + expect(silent.targetedOnly).toBeUndefined(); + expect(summarizeReviewLoop(rows, since, [[]], [silent]).unbound).toEqual(['pass 3 (ledger p3): no review-log row, so its fixes and dispositions cannot be counted']); + }); +}); +