Approved edits after review no longer force a new full review, and ship works in git worktrees (#4862)

Small edits that a project lead approves after the final review no
longer force a whole new review. Shipping from a git worktree no longer
crashes, and merging main no longer throws away a finished review when
main already made one of the PR's exact changes.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
Review-Finding: p1/specialist-batched#1 reader=testing
Review-Finding: p1/specialist-batched#2 reader=testing
This commit is contained in:
Garry Tanandcapy-ai[bot] authored and GitHub committed 2026-11-27 23:07:11 +00:00
1 parent 9befb56288
commit d0b59828d6
21 files changed
+582 -66

No files matched your search

+17
View File
@@ -0,0 +1,17 @@
/**
* Where a gstack file under this checkout's git directory lives: `git rev-parse --git-path <name>` (HARN-108). In a linked
* worktree `.git` is a file (`gitdir: …`), so the literal `.git/<name>` 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` };
}
+4 -2
View File
@@ -135,7 +135,9 @@ export interface ShipReceipt {
/** The `Mechanical retake: <path> (<what>)` 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:<path>` 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 } },
+3 -1
View File
@@ -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 {
+7 -3
View File
@@ -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, any>): 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: <ledger_id or fingerprint> reader=<role>` trailer (receipt attribution): the finding that commit fixed. */
@@ -461,7 +465,7 @@ export function summarizeReviewLoop(rows: readonly Record<string, any>[], 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`);
+27 -7
View File
@@ -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<typeof gitIn>, 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<string>): 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);
+8 -6
View File
@@ -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<Record<string, string>>, sidecars: Readonly<Record<string, string>> = {}): 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();
+33
View File
@@ -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 }); }
}
+22 -4
View File
@@ -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<ShipReceipt['review_depth']>;
const RANK: Record<Depth | 'platform', number> = { platform: -1, light: 0, standard: 1, full: 2 };
@@ -183,7 +184,7 @@ export type ReviewTargeted = NonNullable<ShipReceipt['review_targeted']>;
* 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<string, unknown>;
@@ -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:<path>` 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 [];
+4 -1
View File
@@ -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` }; }
+4 -1
View File
@@ -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');
+25 -16
View File
@@ -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<string, string | null> | 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<string>();
@@ -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 <path> --docs-result <audit-id>-result.json, or a named risk); never refresh hashes'); return false; }
@@ -480,7 +484,7 @@ async function finishStages(argv: readonly string[], cwd: string): Promise<Repor
const baseRelease = reviewedBase?.parent ? releasePaths(policy, cwd, git(cwd, ['merge-base', `origin/${base.replace(/^origin\//, '')}`, 'HEAD']).stdout.trim(), base, true) : undefined;
const routed = route(cwd, base, flag('--reviewed-tree')!, reviewedBase, release, { docsRechecked: has('--docs-rechecked'), contextReviewed: flag('--context-reviewed'), audited, bookkeeping, mechanical, testCode: globs('test_code'), excluded: [...globs('review_exclude_paths'), ...forbidden], baseRelease }, r);
if (!routed) return r;
if (!docsFresh(cwd, base, flag('--docs-post')!, [...routed.base, ...routed.context, ...routed.mechanical, ...stampedFiles(policy, cwd, flag('--reviewed-tree')!, base)], all('--docs-requested'), flag('--docs-result'), reviewedBase?.parent ? reviewedBase.commit : undefined, globs('test_code'), r)) return r;
if (!docsFresh(cwd, base, flag('--docs-post')!, [...routed.base, ...routed.context, ...routed.mechanical, ...stampedFiles(policy, cwd, flag('--reviewed-tree')!, base)], routed.ruled, all('--docs-requested'), flag('--docs-result'), reviewedBase?.parent ? reviewedBase.commit : undefined, globs('test_code'), r)) return r;
if (!list.length && !has('--no-lanes-approved')) return r.stop('no test lanes: require Step 5\'s explicit untested-scope approval (rerun with --no-lanes-approved) or run Steps 5-15');
const allow = evidenceExempt(release).join(',');
const check = (l: { label: string; command: string }) => 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<Repor
}
const laneArgs = list.map(l => `--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<Repo
* exact tree by this step or by finish's preflight (both under .git, which no commit can carry) is reused, never rerun.
*/
function prepushGuards(cwd: string, branch: string, base: string | undefined): { line: string; stop?: string; code?: PushFailure } {
const gitPath = (name: string) => 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)`);