mirror of
https://github.com/garrytan/gstack.git
synced 2026-11-30 11:53:55 +01:00
/gstack-ship drops bought extra review rounds and the second-model trail check (GST-3829) (#4826)
/gstack-ship no longer lets anyone buy an extra review round or a narrow re-check. After two review rounds, a blocking finding ships only as an owner's recorded ruling, or the PR waits. Why: these paths were switched off last release and kept breaking; four PRs in one day tried to repair them. This is part 4 of the approved /gstack-ship simplification. Nothing to do: each removed flag now refuses with a message that names what replaced it. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> Review-Finding: p1/specialist-batched#1 reader=security Review-Finding: p2/outside-voice#3 reader=outside-voice Review-Finding: p2/adversarial-native#1 reader=adversarial-native Review-Finding: p2/adversarial-native#3 reader=adversarial-native Review-Finding: p2/adversarial-native#6 reader=adversarial-native
This commit is contained in:
1 parent
e11a5833bc
commit
ec5d7e6fbd
106 files changed
+933
-5019
No files matched your search
@@ -196,7 +196,8 @@ const MINTED_RUN_ID = /^[A-Za-z0-9._-]{1,64}-(?:\d{14}|\d{4}(?:0[1-9]|1[0-2])(?:
|
||||
const RUN_ID_STAMP = /(?:(?<!\d)\d{1,6}-)?(?:\d{14}|\d{8}-\d{6})$/;
|
||||
|
||||
/**
|
||||
* A fix-check round grant's scope as gstack-approvals round-grant writes it (lib/review-round-grant.ts): its stop= token is the
|
||||
* A fix-check round grant's scope as the retired gstack-approvals round-grant wrote it (removed in GST-3562 part 4; rows
|
||||
* recorded before still render in Approvals tables): its stop= token is the
|
||||
* /ship run id, often a PR number, a dash and a short sha (`507-7192673`), which pii.phone.e164 reads as a phone number
|
||||
* (harness-evals #507). Only a phone finding that starts inside that token of the scope field is skipped; the reason, the words
|
||||
* and every other field, a grant-shaped excerpt pasted into them included, are scanned as usual.
|
||||
|
||||
@@ -1,161 +0,0 @@
|
||||
/**
|
||||
* fix-check-clearing — the one owner of when a granted fix-check counts and what it closes (GST-3260,
|
||||
* docs/review-policy.md#what-closes-a-finding). A stop leaves a stop record in the PR body, the lane or its Captain records a
|
||||
* fix-check grant naming it, a run claims the grant, and gstack-review-log stamps that run's review-fix-check row from the claim
|
||||
* (fix_check_base, run, grant, pr) with the digest of the hunks its reader was given. finish's fixChecked counts such a row through
|
||||
* bindFixCheckRow, anchored on the grant's stop rather than the newest reviewed tree (#4612); gstack-ship-receipt write closes
|
||||
* exactly the open blockers the grant names through clearByGrant, and a fix whose Review-Finding trailer a later full round read
|
||||
* clean through clearByTrailer (#4597). Anything less closes nothing and says why on one line. Every input is a record gstack's
|
||||
* tools wrote (the PR body's stop and claim entries, the approval record, the review log); the agent's --review-loop file only
|
||||
* lists which blockers are open.
|
||||
*/
|
||||
import { createHash } from 'node:crypto';
|
||||
import * as fs from 'node:fs';
|
||||
import * as path from 'node:path';
|
||||
import { grantedStop } from './pr-review-history';
|
||||
import { grantForPr, ownLinesSame, type ReviewRoundGrant } from './review-round-grant';
|
||||
import { ledgerPass, parseFixTrailers, reviewRowKey, rowTime } from './review-scope';
|
||||
import { isSecurityFinding } from './security-findings';
|
||||
import { receiptRuns } from './ship-receipt';
|
||||
import { spawnSync } from './spawn-sync';
|
||||
|
||||
type Row = Record<string, any>;
|
||||
/** One entry of the loop summary's `open` list: a ledger id or fingerprint, or both. */
|
||||
export type OpenBlocker = string | { id: string; fingerprint: string };
|
||||
export type RowBinding = { ok: true; grant: ReviewRoundGrant; base: string; commit: string } | { ok: false; why: string };
|
||||
export interface GrantClearing { ids: string[]; approval?: string; run?: string; why?: string }
|
||||
export interface TrailerClearing { id: string; commit: string; review: string }
|
||||
|
||||
const SHA = /^[0-9a-f]{40}$/;
|
||||
const s12 = (s: string) => s.slice(0, 12);
|
||||
const git = (cwd: string, args: string[]) => {
|
||||
const r = spawnSync('git', args, { cwd, encoding: 'utf8', timeout: 60_000, maxBuffer: 64 * 1024 * 1024 });
|
||||
return r.status === 0 ? r.stdout ?? '' : null;
|
||||
};
|
||||
const ancestor = (cwd: string, a: string, d: string) => a === d || git(cwd, ['merge-base', '--is-ancestor', a, d]) !== null;
|
||||
const treeOf = (cwd: string, c: string) => git(cwd, ['rev-parse', '--verify', '--quiet', `${c}^{tree}`])?.trim();
|
||||
const findingsOf = (r: Row): Row[] => (Array.isArray(r?.findings) ? r.findings.filter((f: unknown) => !!f && typeof f === 'object') : []);
|
||||
const nameOf = (b: OpenBlocker) => (typeof b === 'string' ? b : b.id);
|
||||
|
||||
/**
|
||||
* A fix-check row that counts (GST-3546): a row stamped from a claim counts when `bind` (bindFixCheckRow with `open: true`) accepts
|
||||
* it, and any other as a completed, converged read, whatever it found. A malformed row (converged:false, hunks that leave out part
|
||||
* of the fix range) counts for nothing, so the run logs a correct row on the same grant; a counted read that found issues spends
|
||||
* the grant like a clean one, so a grant still buys one fix round.
|
||||
*/
|
||||
export const countedFixCheck = (r: Row, bind?: (row: Row) => boolean) => r?.skill === 'review-fix-check'
|
||||
&& (r.fix_check_base !== undefined && bind ? bind(r) : r.completed === true && r.converged === true);
|
||||
|
||||
/**
|
||||
* A fix-check grant buys one counted fix-check: it is spent once a counted row carries it, or once a counted fix-check that
|
||||
* carries no grant (an unclaimed read, such as one planned through gstack-review-plan --grant) started after it was recorded.
|
||||
* A row a claim stamped with another grant was that grant's read, so it never spends this one (GST-3560).
|
||||
*/
|
||||
export const grantSpent = (rows: readonly Row[], g: Pick<ReviewRoundGrant, 'approval' | 'at'>, bind?: (row: Row) => boolean) =>
|
||||
rows.some(r => countedFixCheck(r, bind) && (r.grant === g.approval || (!r.grant && rowTime(r) > Date.parse(g.at))));
|
||||
|
||||
/**
|
||||
* The grant-and-row binding finish and write share (amendments A, B and H): a review-fix-check row gstack-review-log stamped from a
|
||||
* claim, whose grant is an approved fix-check grant naming its fix_check_base as the stop head on its PR; no agent-written
|
||||
* range_base that disagrees; a completed, converged read bound to its commit's own tree, which contains the base; nothing open in it
|
||||
* (rule e: its status, an inline finding with action open at any severity, findings_open from a findings file, an id its dispatch
|
||||
* ledger collected that the row does not dispose); and the hunks its reader was given are git diff <base> <commit> over their paths,
|
||||
* which cover every path that diff changes. `open: true` asks only whether the row counts as the grant's read at all: it skips the
|
||||
* nothing-open check, and an id its dispatch ledger collected needs a finding in the row, whatever its action.
|
||||
*/
|
||||
export function bindFixCheckRow(cwd: string, row: Row, grants: readonly ReviewRoundGrant[], o: { open?: boolean } = {}): RowBinding {
|
||||
const no = (why: string): RowBinding => ({ ok: false, why });
|
||||
const base = typeof row.fix_check_base === 'string' ? row.fix_check_base.toLowerCase() : '';
|
||||
const commit = typeof row.commit_full === 'string' ? row.commit_full.toLowerCase() : '';
|
||||
const g = grants.find(x => x.kind === 'fix-check' && x.approval === row.grant);
|
||||
const b = row.review_binding, h = row.hunks, findings = findingsOf(row);
|
||||
if (!SHA.test(base)) return no('the row carries no fix_check_base that gstack-review-log stamped from a claim');
|
||||
if (!g) return no(`its grant ${row.grant ?? 'none'} is no approved fix-check grant in this branch's approval record`);
|
||||
if (g.head !== base || !grantForPr(g, row.pr)) return no(`its fix_check_base ${s12(base)} on PR #${row.pr ?? '?'} is not the stop ${s12(g.head)} that grant ${g.approval} names on PR #${g.pr}`);
|
||||
if (row.range_base !== undefined && git(cwd, ['rev-parse', '--verify', '--quiet', `${row.range_base}^{commit}`])?.trim() !== base) return no(`its range_base ${String(row.range_base).slice(0, 12)} disagrees with the logger's fix_check_base ${s12(base)}`);
|
||||
if (row.completed !== true || row.converged !== true || b?.state !== 'verified' || typeof row.tree !== 'string' || b.start_wtree !== row.tree || b.end_wtree !== row.tree) return no('it is not a completed, converged read bound to one committed tree');
|
||||
if (!SHA.test(commit) || treeOf(cwd, commit) !== row.tree || !ancestor(cwd, base, commit)) return no(`its commit ${s12(commit) || 'missing'} does not hold the tree it read or does not contain the stop ${s12(base)}`);
|
||||
if (!o.open && (row.status === 'issues_found' || row.status === 'issues_open' || Number(row.findings_open ?? 0) > 0 || findings.some(f => f.action === 'open'))) return no('it left a finding open');
|
||||
if (!h || typeof h.sha256 !== 'string' || !Array.isArray(h.paths) || !h.paths.length) return no('it carries no record of the hunks its reader was given');
|
||||
const diff = git(cwd, ['diff', base, commit, '--', ...h.paths]);
|
||||
if (diff === null || createHash('sha256').update(diff).digest('hex') !== h.sha256) return no(`the hunks its reader was given are not git diff ${s12(base)} ${s12(commit)}`);
|
||||
const changed = git(cwd, ['diff', '--name-only', base, commit]);
|
||||
const unread = changed === null ? null : changed.split('\n').filter(p => p && !h.paths.includes(p));
|
||||
if (unread === null || unread.length) return no(`the hunks its reader was given leave out ${unread?.join(', ') ?? 'paths git could not list'}, which git diff ${s12(base)} ${s12(commit)} changes`);
|
||||
if (typeof h.ledger === 'string') {
|
||||
let ids: string[];
|
||||
try { fs.readFileSync(h.ledger); ids = ledgerPass(h.ledger, id => `${path.basename(path.dirname(h.ledger))}/${id}`).ids ?? []; } catch { return no(`its dispatch ledger ${h.ledger} is unreadable`); }
|
||||
const disposed = new Set(findings.filter(f => o.open || f.action !== 'open').map(f => f.ledger_id));
|
||||
const left = ids.filter(id => !disposed.has(id));
|
||||
if (left.length) return no(`its dispatch ledger holds ${left.join(', ')}, which the row does not dispose`);
|
||||
}
|
||||
return { ok: true, grant: g, base, commit };
|
||||
}
|
||||
|
||||
/**
|
||||
* Rules a to f with amendments D and E: (a) grantedStop accepts the newest stop record's fix-check grant for this PR and run, or
|
||||
* (GST-3546) a fix-check grant that names no stop answers its own head once this run claimed it; (b) the PR body's first claim of
|
||||
* the grant is this run's; (c) every review-fix-check row carrying the grant is stamped with this run (a copy of one read, same key and
|
||||
* start, counts once, and two reads never collapse into the later one), the first that counts
|
||||
* (bindFixCheckRow with open: true; a malformed row before it spends nothing) is the grant's one read, and it binds clean at
|
||||
* the stop's head and tree from the body, never the newest review row, on the receipt
|
||||
* head or a head that only merges the base into it; (d) the stop, the claim and the row's start are recorded in that order;
|
||||
* (e) inside the binding; (f) each grant id closes the one open blocker whose id it is, a fingerprint only for a blocker without a
|
||||
* ledger id that no other blocker shares, never a gate finding, and only an id the fix list its reader was given named; an id
|
||||
* that names nothing closes nothing.
|
||||
*/
|
||||
export function clearByGrant(cwd: string, o: { pr: number; run: string; head: string; baseRef: string; body: string; grants: readonly ReviewRoundGrant[]; rows: readonly Row[]; open: readonly OpenBlocker[] }): GrantClearing {
|
||||
const none = (why: string): GrantClearing => ({ ids: [], why });
|
||||
const claimOf = (id: string) => receiptRuns(o.body).find(r => r.mark === 'grant' && r.grant === id);
|
||||
const answer = grantedStop(o.body, o.grants, { pr: o.pr, head: o.head, run: o.run, isAncestor: (a, d) => ancestor(cwd, a, d) });
|
||||
const unstopped = answer?.ok ? undefined : [...o.grants].reverse().find(x => x.kind === 'fix-check' && !x.stop_run && grantForPr(x, o.pr) && claimOf(x.approval)?.run === o.run && ancestor(cwd, x.head, o.head));
|
||||
if (!answer?.ok && !unstopped) return none(answer ? answer.why : `no fix-check grant for PR #${o.pr}`);
|
||||
const g = unstopped ?? (answer as Extract<typeof answer, { ok: true }>).grant;
|
||||
const stop = unstopped ? { head: unstopped.head, tree: treeOf(cwd, unstopped.head), at: unstopped.at } : (answer as Extract<typeof answer, { ok: true }>).stop;
|
||||
const claim = claimOf(g.approval);
|
||||
if (claim?.run !== o.run) return none(`the PR body's first claim of grant ${g.approval} is ${claim ? `run ${claim.run}'s` : 'missing'}, not run ${o.run}'s`);
|
||||
const stamped = [...o.rows.filter(r => r?.skill === 'review-fix-check' && r.grant === g.approval).map(r => [JSON.stringify([reviewRowKey(r), r.review_binding?.started_at ?? r.timestamp ?? null]), r] as const).reduce((m, [k, r]) => (m.has(k) ? m : m.set(k, r)), new Map<string, Row>()).values()];
|
||||
const foreign = stamped.find(r => r.run !== o.run);
|
||||
if (!stamped.length || foreign) return none(`grant ${g.approval} buys fix-check rows stamped with run ${o.run}, and the review log holds ${foreign ? `run ${foreign.run}'s` : 'none'}`);
|
||||
const counted = stamped.find(r => bindFixCheckRow(cwd, r, o.grants, { open: true }).ok);
|
||||
const read = bindFixCheckRow(cwd, counted ?? stamped.at(-1)!, o.grants);
|
||||
if (!read.ok) return none(`the granted fix-check${counted ? ', the one counted read the grant bought,' : ''}: ${read.why}`);
|
||||
const row = counted!, bound = read;
|
||||
if (bound.base !== stop.head || treeOf(cwd, stop.head) !== stop.tree) return none(`the granted fix-check read from ${s12(bound.base)}, not the ${unstopped ? 'head its grant names' : "stop record's head"} ${s12(stop.head)} and its tree`);
|
||||
if (bound.commit !== o.head && !(ancestor(cwd, bound.commit, o.head) && ownLinesSame(cwd, o.baseRef, bound.commit, o.head))) return none(`the granted fix-check read ${s12(bound.commit)}, and ${s12(o.head)} is neither it nor a head that only merges the base into it`);
|
||||
const started = row.review_binding?.started_at;
|
||||
if (!(Date.parse(String(stop.at)) < Date.parse(String(claim.at)) && Date.parse(String(claim.at)) < Date.parse(String(started)))) return none(`the ${unstopped ? 'grant' : 'stop'} (${stop.at ?? 'no time'}), the claim (${claim.at ?? 'no time'}) and the fix-check's start (${started ?? 'no time'}) are not recorded in that order`);
|
||||
const gated = new Set(o.rows.flatMap(r => findingsOf(r).filter(f => f.gate !== undefined).flatMap(f => [f.ledger_id, f.fingerprint])));
|
||||
const asked = new Set<string>(Array.isArray(row.hunks?.fix_list) ? row.hunks.fix_list : []);
|
||||
const listed = g.findings!.length ? g.findings! : [...asked];
|
||||
const ids = listed.filter(name => asked.has(name) && !isSecurityFinding(name) && o.open.filter(b => nameOf(b) === name).length === 1 && !o.open.some(b => typeof b !== 'string' && b.fingerprint === name) && !gated.has(name));
|
||||
const unasked = g.findings!.filter(name => !asked.has(name));
|
||||
const unnamed = g.findings!.filter(name => asked.has(name) && !ids.includes(name));
|
||||
const why = [...(unasked.length ? [`the fix list its reader was given does not name ${unasked.join(', ')}`] : []), ...(unnamed.length ? [`grant ${g.approval} names ${unnamed.join(', ')}, which no open blocker carries alone`] : [])].join('; ');
|
||||
return { ids, approval: g.approval, run: o.run, ...(why ? { why } : {}) };
|
||||
}
|
||||
|
||||
/**
|
||||
* The #4597 route: an open blocker closes when a branch commit carries its Review-Finding trailer (its exact ledger id, or its
|
||||
* fingerprint when no other open blocker shares it) and a later complete full review, bound to its own committed tree on this
|
||||
* branch and holding that commit in its range, left nothing open (the same open test as bindFixCheckRow: its status, findings_open
|
||||
* from a findings file, an inline open finding). Gate findings never close this way.
|
||||
*/
|
||||
export function clearByTrailer(cwd: string, o: { head: string; baseRef: string; rows: readonly Row[]; open: readonly OpenBlocker[] }): TrailerClearing[] {
|
||||
const log = git(cwd, ['log', '--no-merges', '--format=%H%x00%(trailers:key=Review-Finding,valueonly,separator=%x1f)%x1e', `${o.baseRef}..${o.head}`]);
|
||||
const trailers = (log ?? '').split('\x1e').flatMap(rec => { const [sha, values] = rec.trim().split('\0'); return sha && values ? parseFixTrailers(sha, values.split('\x1f').map(v => v.trim()).filter(Boolean)) : []; });
|
||||
return o.open.flatMap(b => {
|
||||
const id = nameOf(b), fp = typeof b === 'string' ? b : b.fingerprint;
|
||||
const raised = o.rows.flatMap(r => findingsOf(r).filter(f => f.action === 'open' && (f.ledger_id === id || (f.ledger_id === undefined && f.fingerprint === fp))).map(f => ({ r, f })));
|
||||
const alone = o.open.filter(c => (typeof c === 'string' ? c : c.fingerprint) === fp).length === 1;
|
||||
const t = trailers.find(x => x.finding === id || (alone && x.finding === fp));
|
||||
if (!t || !raised.length || raised.some(x => x.f.gate !== undefined) || isSecurityFinding(t.finding)) return [];
|
||||
const after = Math.max(...raised.map(x => rowTime(x.r)));
|
||||
const inRange = (from: unknown, fix: string) => from == null || (typeof from === 'string' && (b => !!b && !ancestor(cwd, fix, b))(git(cwd, ['rev-parse', '--verify', '--quiet', `${from}^{commit}`])?.trim()));
|
||||
const review = o.rows.find(r => r?.skill === 'review' && r.via === 'ship' && r.completed === true && r.scope !== 'fix-range' && r.scope !== 'scoped' && rowTime(r) > after
|
||||
&& r.converged === true && r.review_binding?.state === 'verified' && inRange(r.range_base, t.commit) && typeof r.tree === 'string' && r.review_binding.start_wtree === r.tree && r.review_binding.end_wtree === r.tree
|
||||
&& SHA.test(String(r.commit_full)) && treeOf(cwd, r.commit_full) === r.tree && ancestor(cwd, t.commit, r.commit_full) && ancestor(cwd, r.commit_full, o.head)
|
||||
&& r.status !== 'issues_found' && r.status !== 'issues_open' && Number(r.findings_open ?? 0) === 0 && !findingsOf(r).some(f => f.action === 'open'));
|
||||
return review ? [{ id, commit: t.commit, review: review.commit_full as string }] : [];
|
||||
});
|
||||
}
|
||||
@@ -126,12 +126,6 @@ export interface ShipReceipt {
|
||||
/** The gstack release that wrote the receipt (its VERSION file, never the newer policy-key version it reads policies as), and the review depth the reviewed head needs, recomputed at write (lib/ship-receipt-depth.ts receiptDepthAtHead). */
|
||||
gstack_version?: string;
|
||||
review_depth?: { depth: 'platform' | 'light' | 'standard' | 'full'; class: 'docs' | 'tests' | 'code' | 'gate'; runtime_lines: number; rules: string; base: string; registry: string | null; gate_scan: { tagged: number | null; head: string }; reasons: string[]; risk?: string[]; mode?: 'lean' | 'panel' | 'platform'; platform_review?: { id: string; head: string; reviewer: string }; declared?: string[]; detected?: string[] };
|
||||
/** The owner's acceptance of a stop after a fix-check edit under frozen scope (#3559); the PR body repeats it word for word. */
|
||||
review_loop_exception?: { accepted_by: string; date: string; via: string; reason: string; fix_check?: { head: string; findings: number; files?: string[] }; second_pass?: { head: string; deferred: string[] } };
|
||||
/** Review round grants the lane or its Captain recorded for this PR (gstack-approvals round-grant, lib/review-round-grant.ts; GST-2673): never the owner's, so never in review_loop_exception. */
|
||||
review_round_grants?: Array<{ kind: 'extra-round' | 'fix-check'; head: string; pr: number; by: string; reason: string; at: string; approval: string; stop_run?: string; findings?: string[] }>;
|
||||
/** The open blockers a granted fix-check closed at write (lib/fix-check-clearing.ts clearByGrant; GST-3260): the grant, the run that spent it and the ids it named. */
|
||||
cleared_by_grant?: { approval: string; run: string; ids: string[] };
|
||||
/** The open blockers a Review-Finding trailer's fix closed because a later full round read it clean (clearByTrailer, #4597). */
|
||||
cleared_by_trailer?: Array<{ id: string; commit: string; review: string }>;
|
||||
/** The owner's rulings that a finding ships as a disclosed note (gstack-approvals rule, lib/ruled-notes.ts); the PR body lists each one word for word (GST-1537). */
|
||||
@@ -292,9 +286,8 @@ export const ARTIFACT_SCHEMAS = {
|
||||
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 } },
|
||||
review_loop_exception: { type: 'object', required: ['accepted_by', 'date', 'via', 'reason'], properties: { accepted_by: str, date: str, via: str, reason: str, fix_check: { type: 'object', required: ['head', 'findings'], properties: { head: str, findings: { type: 'integer', minimum: 0 }, files: strList } }, second_pass: { type: 'object', required: ['head', 'deferred'], properties: { head: str, deferred: strList } } } },
|
||||
review_round_grants: { type: 'array', items: { type: 'object', required: ['kind', 'head', 'pr', 'by', 'reason', 'at', 'approval'], properties: { kind: { enum: ['extra-round', 'fix-check'] }, head: str, pr: { type: 'integer', minimum: 1 }, by: str, reason: str, at: str, approval: str, stop_run: str, findings: { type: 'array', items: str } } } },
|
||||
cleared_by_grant: { type: 'object', required: ['approval', 'run', 'ids'], properties: { approval: str, run: str, ids: strList } },
|
||||
// Legacy (GST-3562 part 4): receipts written before fix-check and round grants were removed may carry these; nothing reads them.
|
||||
review_loop_exception: { type: 'object' }, review_round_grants: { type: 'array' }, cleared_by_grant: { type: 'object' },
|
||||
cleared_by_trailer: { type: 'array', items: { type: 'object', required: ['id', 'commit', 'review'], properties: { id: str, commit: str, review: str } } },
|
||||
ruled_notes: { type: 'array', items: { type: 'object', required: ['finding', 'head', 'by', 'reason', 'at', 'approval'], properties: { finding: str, head: str, by: str, reason: str, at: str, approval: str, relayed: str, not_security: { const: true } } } },
|
||||
gate_dispositions: { type: 'array', items: { type: 'object', required: ['finding', 'gate_id', 'head', 'by', 'reason', 'words', 'at', 'approval'], properties: { finding: str, gate_id: str, head: str, by: str, reason: str, words: str, at: str, approval: str } } },
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
/**
|
||||
* own-lines: whether two heads on one line of history carry the pull request's own added and removed lines byte-identical, at
|
||||
* the same places, against the base (GST-2968). lib/pregate/run-check.ts uses it to accept a tested merge whose own lines are
|
||||
* the head's; it moved here from the round-grant module GST-3562 part 4 removed.
|
||||
*/
|
||||
import { spawnSync } from './spawn-sync';
|
||||
|
||||
interface Hunk { path: string; start: number; len: number; added: number }
|
||||
|
||||
/** A zero-context diff's hunks: the file (its old side, or its new side when created), the old-side start and length, and the added length. */
|
||||
function hunks(diff: string): Hunk[] {
|
||||
const out: Hunk[] = [];
|
||||
let minus = '', path = '';
|
||||
for (const l of diff.split('\n')) {
|
||||
if (l.startsWith('--- ')) minus = l.slice(4);
|
||||
else if (l.startsWith('+++ ')) path = minus === '/dev/null' ? l.slice(4) : minus;
|
||||
const m = /^@@ -(\d+)(?:,(\d+))? \+\d+(?:,(\d+))? @@/.exec(l);
|
||||
if (m) out.push({ path, start: +m[1]!, len: m[2] === undefined ? 1 : +m[2], added: m[3] === undefined ? 1 : +m[3] });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* The old-side line own hunk h starts at once the base's hunks have moved its file, or null when the base edited a line h changes or
|
||||
* inserted inside or right next to h, so its place can't be carried over. Spans are in half-line steps: 2n is line n, 2n+1 the gap after it.
|
||||
*/
|
||||
function carried(base: readonly Hunk[], h: Hunk): number | null {
|
||||
const span = (x: Hunk, pad: number): [number, number] => x.len ? [2 * x.start - pad, 2 * (x.start + x.len - 1) + pad] : [2 * x.start + 1 - pad, 2 * x.start + 1 + pad];
|
||||
const [lo, hi] = span(h, 1);
|
||||
let shift = 0;
|
||||
for (const b of base.filter(x => x.path === h.path)) {
|
||||
const [blo, bhi] = span(b, 0);
|
||||
if (blo <= hi && lo <= bhi) return null;
|
||||
if (bhi < lo) shift += b.added - b.len;
|
||||
}
|
||||
return h.start + shift;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a and b are on one line of history and carry byte-identical own lines against baseRef at the same places: equal
|
||||
* zero-context patch-ids, and each own hunk of a, carried through the base's changes between the two forks, starts where b's does.
|
||||
* Moving a line to another place in the same file changes no patch-id, so the places are compared too.
|
||||
*/
|
||||
export function ownLinesSame(repoRoot: string, baseRef: string, a: string, b: string): boolean {
|
||||
const git = (args: string[], input?: string) => spawnSync('git', ['-c', 'core.quotepath=off', ...args], { cwd: repoRoot, encoding: 'utf8', input, timeout: 120_000, maxBuffer: 256 * 1024 * 1024 });
|
||||
if (git(['merge-base', '--is-ancestor', a, b]).status !== 0 && git(['merge-base', '--is-ancestor', b, a]).status !== 0) return false;
|
||||
const fork = (c: string) => { const f = git(['merge-base', baseRef, c]); return f.status === 0 ? f.stdout.trim() : null; };
|
||||
const diff = (x: string, y: string) => { const d = git(['diff', '--no-color', '--no-ext-diff', '--no-textconv', '--no-renames', '--binary', '--full-index', '-U0', x, y]); return d.status === 0 ? d.stdout : null; };
|
||||
const id = (d: string) => { const p = git(['patch-id', '--verbatim'], d); return p.status === 0 ? p.stdout.trim().split(/\s+/)[0] || null : null; };
|
||||
const fa = fork(a), fb = fork(b);
|
||||
if (!fa || !fb) return false;
|
||||
const da = diff(fa, a), db = diff(fb, b), moved = fa === fb ? '' : diff(fa, fb);
|
||||
if (!da?.trim() || !db?.trim() || moved === null) return false;
|
||||
const x = id(da);
|
||||
if (x === null || x !== id(db)) return false;
|
||||
const base = hunks(moved), there = hunks(db), here = hunks(da);
|
||||
return here.length === there.length && here.every((h, i) => h.path === there[i]!.path && h.len === there[i]!.len && carried(base, h) === there[i]!.start);
|
||||
}
|
||||
@@ -11,7 +11,6 @@ import type { ShipReceipt } from './headless-artifacts';
|
||||
import { withAgentNotes, splitAgentNotes } from './agent-notes';
|
||||
import { extractReceipt, keptRuns, receiptRun, receiptRuns, RUNS_FENCE, RUNS_RE, type ReceiptRun } from './ship-receipt';
|
||||
import { FULL_PASS_CAP } from './review-depth';
|
||||
import type { ReviewRoundGrant } from './review-round-grant';
|
||||
|
||||
export interface PrReviewHistory {
|
||||
/** /ship runs that reviewed (stubs and carries excluded). */
|
||||
@@ -93,25 +92,23 @@ export const runStub = (o: { head: string; run: string; status: 'started' | 'voi
|
||||
|
||||
/**
|
||||
* A stop record (GST-2968): the review a /ship run stopped on, written by gstack-ship-receipt stop when the plan prints NEXT: stop.
|
||||
* head is the commit that review read, tree its tree; the review row bound to it (lib/ship-stop.ts). A grant marker records
|
||||
* that a run claimed a round grant before dispatching the round it buys. Markers count no round and are never trimmed. Both carry
|
||||
* when they were recorded, so a granted fix-check orders stop, claim and row from the PR body alone (lib/fix-check-clearing.ts).
|
||||
* head is the commit that review read, tree its tree; the review row bound to it (lib/ship-stop.ts). Markers count no round and
|
||||
* are never trimmed; a grant marker from a run before GST-3562 part 4 (a claimed round grant) stays readable and counts nothing.
|
||||
*/
|
||||
export const stopMarker = (o: { head: string; tree: string; run: string; at?: string }): ReceiptRun => ({ head: o.head, run: o.run, mark: 'stop', tree: o.tree, at: o.at ?? new Date().toISOString() });
|
||||
export const grantMarker = (o: { head: string; run: string; grant: string; at?: string }): ReceiptRun => ({ head: o.head, run: o.run, mark: 'grant', grant: o.grant, at: o.at ?? new Date().toISOString() });
|
||||
/** gstack-ship-run abandon's entry (GST-3260): who ended a run that stopped working, and why, at the head it was abandoned on. */
|
||||
export const abandonMarker = (o: { head: string; run: string; by: string; reason: string }): ReceiptRun => ({ head: o.head, run: o.run, mark: 'abandoned', by: o.by, reason: o.reason });
|
||||
/** The newest receipt a run id already wrote, in the runs block or current: a run id names one /ship run (gstack-evals#406). */
|
||||
export const receiptedRun = (body: string, run: string) => entries(body).filter(e => e.run === run && !e.mark && !e.status).at(-1);
|
||||
|
||||
/** The rows a /ship stop can follow: a full pass, a fix-check, or a Step 11 voice (#4591 stopped on its voices after a fix-check). */
|
||||
/** The rows a /ship stop can follow: a full pass or a Step 11 voice (#4591 stopped on its voices); a legacy fix-check row too. */
|
||||
const STOP_READERS = new Set(['review', 'review-fix-check', 'adversarial-review', 'codex-review']);
|
||||
|
||||
/**
|
||||
* The stop record for the newest via:ship reading row of this run (at or after since): a full pass, a fix-check or a Step 11 voice,
|
||||
* whichever read last, so the stop binds to the head that row read (#4591). Or why none binds: the row must be complete,
|
||||
* bound to one tree from start to end (verified, or incomplete because it stopped) that is its commit's own tree, read on a clean
|
||||
* worktree, and that commit must be HEAD or an ancestor of it. A read gstack can't tie to a commit gives a grant nothing to answer.
|
||||
* worktree, and that commit must be HEAD or an ancestor of it.
|
||||
*/
|
||||
export function stopFrom(rows: readonly Record<string, any>[], since: string, o: { treeOf: (commit: string) => string | undefined; onHead: (commit: string) => boolean }): { ok: true; head: string; tree: string } | { ok: false; why: string } {
|
||||
const sinceMs = Date.parse(since);
|
||||
@@ -125,44 +122,18 @@ export function stopFrom(rows: readonly Record<string, any>[], since: string, o:
|
||||
return { ok: true, head, tree: row.tree };
|
||||
}
|
||||
|
||||
export type GrantedStop = { ok: true; grant: ReviewRoundGrant; stop: ReceiptRun } | { ok: false; why: string };
|
||||
|
||||
/**
|
||||
* The fix-check grant that answers this PR's stop (GST-2968, GHOM-1): the newest stop record in the body, a fix-check grant naming
|
||||
* its run and head for this PR, not claimed by another run, and HEAD at or after the stop's head. A stop is stale once a later run
|
||||
* reviewed (a stub after it with a full pass, or a current receipt past its head): a grant then answers nothing.
|
||||
*/
|
||||
export function grantedStop(body: string, grants: readonly ReviewRoundGrant[], o: { pr: number; head: string; run?: string; isAncestor: (a: string, d: string) => boolean }): GrantedStop | null {
|
||||
const fixChecks = grants.filter(g => g.kind === 'fix-check' && g.pr === o.pr);
|
||||
if (!fixChecks.length) return null;
|
||||
const runs = receiptRuns(body);
|
||||
const at = runs.map(r => r.mark).lastIndexOf('stop');
|
||||
if (at < 0) return { ok: false, why: `no stop record in the PR body for grant ${fixChecks.at(-1)!.approval}; a fix-check grant answers the stop gstack-ship-receipt stop recorded` };
|
||||
const stop = runs[at]!;
|
||||
const current = extractReceipt(body).receipt;
|
||||
const later = runs.slice(at + 1).find(r => !r.mark && r.run !== stop.run && (r.review_loop?.passes ?? 0) > 0);
|
||||
if (later || (current && typeof current.head === 'string' && current.head !== stop.head && o.isAncestor(stop.head, current.head))) return { ok: false, why: `the stop at ${stop.head.slice(0, 12)} (run ${stop.run}) is stale: run ${later?.run ?? current?.run} reviewed after it` };
|
||||
const g = [...fixChecks].reverse().find(x => x.head === stop.head && x.stop_run === stop.run);
|
||||
if (!g) return { ok: false, why: `no fix-check grant names the newest stop (run ${stop.run} at ${stop.head.slice(0, 12)}): record one with gstack-approvals round-grant --kind fix-check --head ${stop.head} --stop-run ${stop.run}` };
|
||||
const claimed = runs.find(r => r.mark === 'grant' && r.grant === g.approval && r.run !== o.run);
|
||||
if (claimed) return { ok: false, why: `grant ${g.approval} was claimed by run ${claimed.run}: a grant buys one round` };
|
||||
if (!o.isAncestor(stop.head, o.head)) return { ok: false, why: `HEAD ${o.head.slice(0, 12)} does not contain the stop's head ${stop.head.slice(0, 12)}: a head move voids grant ${g.approval}` };
|
||||
return { ok: true, grant: g, stop };
|
||||
}
|
||||
|
||||
export type Route = { route: 'first' | 'final' | 'read-only' | 'fix-check'; reason: string };
|
||||
export type Route = { route: 'first' | 'final' | 'read-only'; reason: string };
|
||||
|
||||
/**
|
||||
* What review a head of the PR gets when carry can't keep its receipt (the PR's own lines changed; a head that only
|
||||
* merges in the base keeps it). Before any full round: the first review, as today. Below the cap: a fresh full review
|
||||
* of this head, the PR's last before merge. At the cap: one read-only full review of the final head, with no fix round,
|
||||
* whose blocker goes to the lane's Captain as a decision; an extra-round grant at this head buys a fix round instead.
|
||||
* whose blocker goes to the lane's Captain as a decision.
|
||||
* A scoped re-check is advice only and never stands in (GST-2673).
|
||||
*/
|
||||
export function reviewRoute(h: Pick<PrReviewHistory, 'full'>, o: { grant?: string } = {}): Route {
|
||||
export function reviewRoute(h: Pick<PrReviewHistory, 'full'>): Route {
|
||||
if (!h.full) return { route: 'first', reason: 'no full review round on this PR yet' };
|
||||
if (h.full < FULL_PASS_CAP) return { route: 'final', reason: `the PR had ${h.full} full review round${h.full === 1 ? '' : 's'}; this head gets a fresh full review, the PR's round ${h.full + 1} of ${FULL_PASS_CAP} and its last before merge (R51)` };
|
||||
if (o.grant && h.full === FULL_PASS_CAP) return { route: 'final', reason: `the PR had ${h.full} full review rounds; round grant ${o.grant} buys one more at this head, with its fix round` };
|
||||
return { route: 'read-only', reason: `the PR had ${h.full} full review rounds; this head gets one read-only full review: no fix round, a blocker goes to the lane's Captain as a decision, and the count does not reopen (R51)` };
|
||||
}
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ import * as fs from 'node:fs';
|
||||
import * as os from 'node:os';
|
||||
import * as path from 'node:path';
|
||||
import { ghArtifactDeps, ghRunDeps, runInventory, type BaseMove, type RunProfile } from '../run-evidence';
|
||||
import { ownLinesSame } from '../review-round-grant';
|
||||
import { ownLinesSame } from '../own-lines';
|
||||
import { classifyDocsOnly } from '../docs-only';
|
||||
import { wtreeFingerprint } from '../script-invocation';
|
||||
import { resolveBaseBranch } from '../ship-policy';
|
||||
|
||||
+10
-10
@@ -291,8 +291,8 @@ export const RELEASE_RESULT_CODES = {
|
||||
},
|
||||
QUEUE_RECEIPT_EXCEPTION_INVALID: {
|
||||
anchor: 'queue-receipt-exception-invalid',
|
||||
summary: 'the PR body’s /ship receipt records an owner exception (docs or review loop) that is malformed, lacks the fix-check it follows, or whose line the body no longer carries verbatim',
|
||||
fix: 'restore the exception line in the PR body word for word, or run /gstack-ship again and record the owner’s acceptance with --docs or --review-loop-exception',
|
||||
summary: 'the PR body’s /ship receipt records a documentation exception that is malformed or whose line the body no longer carries verbatim, or it still records a review-loop exception, which GST-3562 part 4 removed',
|
||||
fix: 'for a documentation exception, restore its line in the PR body word for word, or run /gstack-ship again and record the owner’s acceptance with --docs; for a review-loop exception, run /gstack-ship again for a fresh receipt, with any blocker it shipped recorded as a ruled note (gstack-approvals rule)',
|
||||
},
|
||||
QUEUE_RECEIPT_TARGETED_MISSING: {
|
||||
anchor: 'queue-receipt-targeted-missing',
|
||||
@@ -418,12 +418,12 @@ export const RELEASE_RESULT_CODES = {
|
||||
RECEIPT_BLOCKER_OPEN: {
|
||||
anchor: 'receipt-blocker-open',
|
||||
summary: 'the review loop stopped at this head with a blocking finding still open (a Step 9 or Step 11 finding, the second-model review included, whose newest review-log action is still open and no owner ruling closed), so no receipt is written',
|
||||
fix: 'fix the finding and run /gstack-ship again on the new head, or take the stop to the owner, whose ruled note or grant closes it; never write the receipt by hand or drop the finding from the review-log row',
|
||||
fix: 'fix the finding and run /gstack-ship again on the new head, or take the stop to the owner, whose ruled note closes it; never write the receipt by hand or drop the finding from the review-log row',
|
||||
},
|
||||
REVIEW_LOOP_EXCEPTION_INVALID: {
|
||||
anchor: 'review-loop-exception-invalid',
|
||||
summary: 'write --review-loop-exception got an exception that is malformed, accepts a stop the review loop does not show (a fix_check with review_loop.fix_checks 0 or missing, or a second_pass with fewer than two passes or no deferred finding), names a head that is not the receipt head or its ancestor, or is missing from the PR body',
|
||||
fix: 'pass { accepted_by, date, via, reason } plus fix_check: { head, findings } or second_pass: { head, deferred: [<finding id>] } with the owner’s words, the --review-loop summary that shows that stop, and the printed "Review-loop exception: …" line in the body',
|
||||
summary: '--review-loop-exception was removed with fix-check grants (GST-3562 part 4), so write and finish refuse it and write nothing',
|
||||
fix: 'drop the flag: an open finding at the round cap ships only as a ruled note the owner records with gstack-approvals rule',
|
||||
},
|
||||
CI_CARRY_TREE_LOG_UNBOUND: {
|
||||
anchor: 'ci-carry-tree-log-unbound',
|
||||
@@ -448,12 +448,12 @@ export const RELEASE_RESULT_CODES = {
|
||||
STOP_UNBOUND: {
|
||||
anchor: 'stop-unbound',
|
||||
summary: 'gstack-ship-receipt stop found no review of this run bound to one committed tree, so it recorded no stop record',
|
||||
fix: 'nothing for a grant to answer: the lane or its Captain ships with the open notes listed or parks; a fresh /ship run gives the head its review',
|
||||
fix: 'the lane or its Captain ships with the open notes listed or parks; a fresh /ship run gives the head its review',
|
||||
},
|
||||
GRANT_SPENT: {
|
||||
anchor: 'grant-spent',
|
||||
summary: 'another /ship run already claimed this round grant, and a grant buys one round',
|
||||
fix: 'the lane or its Captain records a new grant for the stop the PR is at now (gstack-ship-receipt stop prints the command)',
|
||||
summary: 'an older gstack’s claim found the round or fix-check grant spent or unknown; claim and grants were removed in GST-3562 part 4',
|
||||
fix: 'the lane’s Captain decides the stop as PR_ROUND_CAP says: ship with the open notes (a blocker only as a ruled note) or park',
|
||||
},
|
||||
SHIP_RUN_ABANDON_REFUSED: {
|
||||
anchor: 'ship-run-abandon-refused',
|
||||
@@ -467,8 +467,8 @@ export const RELEASE_RESULT_CODES = {
|
||||
},
|
||||
GRANT_UNKNOWN: {
|
||||
anchor: 'grant-unknown',
|
||||
summary: 'the branch approval record holds no approved review_round_grant row with this id',
|
||||
fix: 'pass the id gstack-approvals round-grant printed, from a checkout that sees the record or its mirror',
|
||||
summary: 'an older gstack’s claim found the round or fix-check grant spent or unknown; claim and grants were removed in GST-3562 part 4',
|
||||
fix: 'the lane’s Captain decides the stop as PR_ROUND_CAP says: ship with the open notes (a blocker only as a ruled note) or park',
|
||||
},
|
||||
RECEIPT_CARRY_SCOPED_REVIEW: {
|
||||
anchor: 'receipt-carry-scoped-review',
|
||||
|
||||
+19
-36
@@ -20,11 +20,12 @@ export type PathClass = 'docs' | 'tests' | 'code';
|
||||
export type Depth = 'light' | 'standard' | 'full';
|
||||
export type Effort = 'light' | 'medium' | 'full' | 'host';
|
||||
export type Role = 'specialist' | 'red-team' | 'adversarial-native' | 'outside-voice' | 'fix-check' | 'targeted';
|
||||
/** 'scoped' and 'fix-check' (with their Role) are replay-only: no table plans them since GST-3562, and planReview keeps their dispatch for the frozen no-loss replays (test/fixtures/review-depth-main). */
|
||||
export type Step = 'full' | 'scoped' | 'fix-check' | 'voices' | 'platform' | 'targeted' | 'done' | 'stop';
|
||||
|
||||
export const SPECIALISTS = ['testing', 'maintainability', 'security', 'performance', 'data-migration', 'api-contract', 'design', 'simplification', 'state-machines'] as const;
|
||||
export type Specialist = (typeof SPECIALISTS)[number];
|
||||
/** The review rounds one /ship invocation runs (R51): a full, scoped or fix-check step is a round. */
|
||||
/** The review rounds one /ship invocation runs (R51): a full step is a round (the scoped and fix-check steps are replay-only). */
|
||||
export const FULL_PASS_CAP = 2;
|
||||
export const SMALL_DIFF_LINES = 50;
|
||||
export const RED_TEAM_LINES = 200;
|
||||
@@ -371,7 +372,7 @@ export function scanNumbers(added: Record<string, readonly string[]>): NumbersRe
|
||||
export interface History {
|
||||
/** Full review passes already run in this invocation (0 before pass 1). */
|
||||
fullPasses: number;
|
||||
/** The step that just finished; none before pass 1. */
|
||||
/** The step that just finished; none before pass 1. 'fix-check' is replay-only, like the fields at the end. */
|
||||
last: 'none' | 'full' | 'fix-check';
|
||||
/** The finished step fixed at least one blocking finding. */
|
||||
fixedBlocking?: boolean;
|
||||
@@ -388,23 +389,23 @@ export interface History {
|
||||
gate?: boolean;
|
||||
/** Step 11's native adversarial pass already ran (planReview sets it from PlanInput.adversarialRan). */
|
||||
adversarialRan?: boolean;
|
||||
/** The approval id of the owner's recorded grant of one scoped fix-check after round 2 (review_loop_exception). */
|
||||
granted?: string;
|
||||
/** R65's lean table (planReview sets it from the base policy's review.panel): one reviewer, then at most one fix-check. */
|
||||
/** R65's lean table (planReview sets it from the base policy's review.panel): one reviewer, then at most one full round 2. */
|
||||
lean?: boolean;
|
||||
/** Fix-checks already run in this invocation (lean: the grant adds one only after the first). */
|
||||
fixChecks?: number;
|
||||
/** The Step 9 /ship Step 16 stage 2.1 inserted for edits after the review bound (gstack-review-plan --post-review). */
|
||||
postReview?: boolean;
|
||||
/** In the loop, the CLI bound `granted` to the last fix-check's own stop head, its commit (--range-base): a new grant, never the previous link's. */
|
||||
chained?: boolean;
|
||||
/** R51 rounds earlier /ship runs on this PR already spent, fix-checks and scoped passes included (--prior-rounds; GST-2673): printed as pr_rounds=. */
|
||||
/** R51 rounds earlier /ship runs on this PR already spent, earlier scoped passes and fix-checks included (--prior-rounds; GST-2673): printed as pr_rounds=. */
|
||||
priorRounds?: number;
|
||||
/** The full review rounds among them (--prior-full): the PR cap compares these plus this run's full passes with FULL_PASS_CAP, so a run's own fix rounds stay as the in-run table plans them. */
|
||||
priorFull?: number;
|
||||
/** The lane's or Captain's recorded round grant at this head (--round-grant): one more round for the PR, with its fix round, never the owner's. */
|
||||
/**
|
||||
* Replay-only (GST-3562 part 4): the fix-check and grant history main's frozen table at 0408128 reads
|
||||
* (test/fixtures/review-depth-main) for the no-loss replays. gstack-review-plan refuses the flags that set them and nextStep
|
||||
* ignores them.
|
||||
*/
|
||||
granted?: string;
|
||||
fixChecks?: number;
|
||||
chained?: boolean;
|
||||
roundGrant?: string;
|
||||
/** A fix-check round grant that answers the stop record at --stop (GST-2968): the stopped review's fix round, one scoped fix-check of the PR's own change since the stop's head, in this run or a new one. */
|
||||
grantedStop?: string;
|
||||
}
|
||||
/**
|
||||
@@ -423,39 +424,28 @@ export interface NextStep { step: Step; reason: string; keepReader?: true; readO
|
||||
* blocking finding earns a second full pass on the range, never a scoped pass (GST-3562 part 3); below full depth with at
|
||||
* most SCOPED_RANGE_LINES runtime lines in the fix range it keeps the readers main's scoped pass ran (keepReader,
|
||||
* rangeReaders); any other fix earns a full second pass on the range too, except a light pass whose fix range
|
||||
* changes no runtime lines (GST-3562 A: no new fix-check is planned, and the step's keepReader keeps the full-effort reader
|
||||
* changes no runtime lines (GST-3562 A: no fix-check is planned, and the step's keepReader keeps the full-effort reader
|
||||
* the fix-check was); two rounds is the cap (R51), and capStep says what a fix after the cap gets.
|
||||
* The cap limits fix rounds, not Step 11's voices: on gate class any stop waits for them (GST-967),
|
||||
* and the owner's recorded grant (`granted`) turns the stop after a round-2 fix-check that was the run's only one
|
||||
* (`fixChecks`, GEVA-223) into one more fix-check, for one release; a fix-check never earns another, so
|
||||
* the grant cannot repeat. Edits after the review bound (`postReview`) that follow a fix-check are a new stop, and a new grant
|
||||
* there adds one fix-check, the next link of the chain finish counts (GST-1676, docs/ship-policy.md#fix-check-chain). In the
|
||||
* loop, a grant the CLI bound to the last fix-check's own stop head (`chained`) adds one more the same way (GST-1681).
|
||||
* The cap limits fix rounds, not Step 11's voices: on gate class any stop waits for them (GST-967). Round grants and
|
||||
* fix-check grants are gone (GST-3562 part 4): at the cap a blocker goes to the lane's Captain.
|
||||
*/
|
||||
export function nextStep(h: History, depth?: Depth): NextStep {
|
||||
if (h.grantedStop && h.last !== 'fix-check') return h.rangeRuntimeLines == null
|
||||
? { step: 'stop', reason: `fix-check grant ${h.grantedStop} answers the stop, but there is no fix to read since its head: commit the fix (a base merge, an empty or reverted change is none), then ask again` }
|
||||
: { step: 'fix-check', reason: `fix-check grant ${h.grantedStop} buys the stopped review's fix round: one scoped fix-check of the PR's own change since the stop's head, never a new full review and never a second fix-check` };
|
||||
const n = prCapped(h, h.lean ? leanStep(h, depth) : loopStep(h, depth));
|
||||
if (n.step !== 'stop') return n;
|
||||
if (h.gate && !h.adversarialRan) return { step: 'voices', reason: `gate class: Step 11's ${h.lean ? 'one reader' : 'voices (adversarial, outside, targeted)'} run${h.lean ? 's' : ''} before the owner's exit, then ask again with --adversarial-ran (${n.reason})` };
|
||||
const afterFixCheck = h.last === 'fix-check' && h.fullPasses === FULL_PASS_CAP - 1 && h.fixChecks === 1;
|
||||
if (h.postReview && h.last === 'fix-check' && h.granted && !h.blockingOpen) return { step: 'fix-check', reason: `the owner's grant ${h.granted} adds one scoped fix-check for the edits after the last fix-check, a new link of the fix-check chain (docs/ship-policy.md#fix-check-chain); a later post-review edit needs a grant of its own` };
|
||||
if (h.chained && h.last === 'fix-check' && h.granted && !h.blockingOpen) return { step: 'fix-check', reason: `the owner's grant ${h.granted} adds one scoped fix-check at the last fix-check's stop, a new link of the fix-check chain (docs/ship-policy.md#fix-check-chain); another stop needs a grant of its own` };
|
||||
if (!h.lean && h.granted && !h.blockingOpen && afterFixCheck) return { step: 'fix-check', reason: `the owner's grant ${h.granted} adds one scoped fix-check after round ${FULL_PASS_CAP} (review_loop_exception), never a second` };
|
||||
return n;
|
||||
}
|
||||
|
||||
/**
|
||||
* R51 per pull request (GST-2673, docs/review-policy.md#rounds-per-pull-request): the rounds earlier /ship runs on this
|
||||
* PR spent count against FULL_PASS_CAP with this run's, and a recorded round grant at this head adds one. At the cap a
|
||||
* PR spent count against FULL_PASS_CAP with this run's. At the cap a
|
||||
* below-floor fix ships as notes and anything else stops with PR_ROUND_CAP for the lane or its Captain, never the owner.
|
||||
* A PR already at the cap gets one read-only full review of this head: no fix round, the count does not reopen, and a
|
||||
* blocker stops with PR_ROUND_CAP as the lane's Captain's decision.
|
||||
*/
|
||||
function prCapped(h: History, n: NextStep): NextStep {
|
||||
const prior = h.priorFull ?? 0;
|
||||
const cap = FULL_PASS_CAP + (h.roundGrant ? 1 : 0);
|
||||
const cap = FULL_PASS_CAP;
|
||||
if (prior >= cap) {
|
||||
if (h.last === 'none') return n.step === 'full' || n.step === 'scoped' ? { step: 'full', reason: `read-only final review (R51): this PR already had ${prior} full review rounds on earlier heads, so this head gets one full review with no fix round; a blocker goes to the lane's Captain as a decision and the count does not reopen`, keepReader: true, readOnly: true } : n;
|
||||
if (n.step === 'done') return n;
|
||||
@@ -466,11 +456,10 @@ function prCapped(h: History, n: NextStep): NextStep {
|
||||
if (!prior || (n.step !== 'full' && n.step !== 'scoped')) return n;
|
||||
const used = prior + h.fullPasses;
|
||||
if (used < cap) return { ...n, reason: `${n.reason}; this PR already had ${prior} full review round${prior === 1 ? '' : 's'} on earlier heads, so this is its full round ${used + 1} of ${cap}${used + 1 === cap ? ', the last' : ''}` };
|
||||
if (h.roundGrant && used === cap && prior === cap - 1 && h.fullPasses === 1 && h.last === 'full') return { ...n, reason: `${n.reason}; round grant ${h.roundGrant} bought pass 1 as this PR's full round ${cap}, and this is that round's fix round, its last` };
|
||||
if (h.last !== 'none' && !h.blockingOpen) return used === cap
|
||||
? { step: 'full', reason: `${READ_ONLY_REVIEW}; this PR already had ${prior} full review round${prior === 1 ? '' : 's'} on earlier heads`, keepReader: true, readOnly: true }
|
||||
: { step: 'stop', reason: `a fix followed the read-only final review: ${CAPTAIN_DECIDES}` };
|
||||
return { step: 'stop', reason: `PR_ROUND_CAP: this PR already had ${used} full review round${used === 1 ? '' : 's'} across its heads and /ship runs${h.roundGrant ? ` (round grant ${h.roundGrant} included)` : ''}; another needs a reason the lane or its Captain records with gstack-approvals round-grant, not an owner ask` };
|
||||
return { step: 'stop', reason: `PR_ROUND_CAP: this PR already had ${used} full review round${used === 1 ? '' : 's'} across its heads and /ship runs; a blocker goes to the lane's Captain (ship with it as a ruled note, or park), not an owner ask` };
|
||||
}
|
||||
|
||||
const READ_ONLY_REVIEW = 'read-only final review (R51): fixes changed code after the last round, so the final head gets one full review of the whole PR diff (the dispatcher stages it on the merge base) with no fix round (GST-3562 A)';
|
||||
@@ -494,11 +483,6 @@ function capStep(h: History, depth?: Depth): NextStep {
|
||||
*/
|
||||
function leanStep(h: History, depth?: Depth): NextStep {
|
||||
if (h.last === 'none') return { step: 'full', reason: 'pass 1: one reviewer reads the whole diff (R65)' };
|
||||
if (h.last === 'fix-check') {
|
||||
if (!h.blockingOpen && !h.fixedBlocking && !h.touchedGate) return { step: 'done', reason: h.fixedBelow ? 'round cap 2 reached: the below-floor fixes ship as notes in the PR body and receipt' : 'the fix-check found nothing blocking' };
|
||||
if (h.granted && !h.blockingOpen && h.fixChecks === 1) return { step: 'fix-check', reason: `the owner's grant ${h.granted} adds one scoped fix-check after round ${FULL_PASS_CAP} (review_loop_exception), never a second` };
|
||||
return { step: 'stop', reason: `the fix-check ${h.blockingOpen || h.fixedBlocking ? 'found a blocking finding' : 'edited a gate-class path'}: name it for the owner, whose grant may add one scoped fix-check, never a third round` };
|
||||
}
|
||||
if (h.blockingOpen) return { step: 'stop', reason: 'a blocking finding is still open in fix scope: name it for the owner' };
|
||||
if (!h.fixedBlocking && !h.fixedBelow && !h.touchedGate) return { step: 'done', reason: 'the step applied no edits' };
|
||||
if (depth === 'light' && !h.fixedBlocking && !h.touchedGate && h.rangeRuntimeLines === 0) return { step: 'done', reason: 'light depth: the below-floor fixes change no runtime lines, so they ship as notes in the PR body and receipt (R65)' };
|
||||
@@ -509,7 +493,6 @@ function leanStep(h: History, depth?: Depth): NextStep {
|
||||
function loopStep(h: History, depth?: Depth): NextStep {
|
||||
if (h.last === 'none') return { step: 'full', reason: 'pass 1 reviews the whole diff' };
|
||||
const fixed = !!(h.fixedBlocking || h.fixedBelow || h.touchedGate);
|
||||
if (h.last === 'fix-check') return h.blockingOpen || h.fixedBlocking || h.touchedGate ? { step: 'stop', reason: `the fix-check ${h.touchedGate && !h.blockingOpen && !h.fixedBlocking ? 'edited a gate-class path' : 'found a blocking finding'}: name it for the owner, whose grant may add one scoped fix-check, never a third round` } : { step: 'done', reason: fixed ? 'round cap 2 reached: the below-floor fixes ship as notes in the PR body and receipt' : 'the fix-check found nothing blocking' };
|
||||
if (h.blockingOpen && h.fullPasses >= FULL_PASS_CAP) return { step: 'stop', reason: `a blocking finding is open after ${FULL_PASS_CAP} rounds: name it for the owner` };
|
||||
if (h.blockingOpen) return { step: 'stop', reason: 'a blocking finding is still open in fix scope: name it for the owner' };
|
||||
if (!fixed) return { step: 'done', reason: 'the step applied no edits' };
|
||||
|
||||
+2
-64
@@ -4,7 +4,7 @@ import { closeSync, constants, fstatSync, lstatSync, mkdirSync, openSync, readFi
|
||||
import { join, resolve } from 'node:path';
|
||||
import { deriveReviewStatus, isCriticalFinding, isOpenByAction, readJsonl } from './headless-artifacts';
|
||||
import { resultLine, type ResultCodeName } from './result-codes';
|
||||
import { readRunRecord, thisRunOwner } from './ship-run-record';
|
||||
import { thisRunOwner } from './ship-run-record';
|
||||
|
||||
const DIFF_REVIEWS = new Set(['review', 'review-fix-check', 'adversarial-review', 'codex-review', 'design-review-lite', 'ship']);
|
||||
const SHARED_LIBS_COVERAGE_VERSION = 1;
|
||||
@@ -204,7 +204,6 @@ export function captureReviewStart(skill: string, env = process.env, fixRange =
|
||||
throw new Error('cannot capture a diff review without a working-tree fingerprint');
|
||||
}
|
||||
const fixBase = fixRange ? fixRangeBase(skill, env) : undefined;
|
||||
const claimed = skill === 'review-fix-check' ? (r => (r.kind === 'record' && r.record.state === 'open' ? r.record : undefined))(readRunRecord(env.GSTACK_REVIEW_REPO)) : undefined;
|
||||
const dir = join(env.GSTACK_REVIEW_DIR!, '.review-starts');
|
||||
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
||||
const token = crypto.randomUUID();
|
||||
@@ -212,7 +211,6 @@ export function captureReviewStart(skill: string, env = process.env, fixRange =
|
||||
skill, repo: env.GSTACK_REVIEW_REPO, branch: env.GSTACK_REVIEW_BRANCH,
|
||||
wtree: env.GSTACK_STAMP_WTREE, started_at: new Date().toISOString(), ...(o => (o ? { owner: o } : {}))(thisRunOwner()),
|
||||
...(fixBase ? { scope: 'fix-range', fix_base: fixBase } : {}),
|
||||
...(claimed?.claim ? { fix_check: { base: claimed.claim.stop_head, run: claimed.run, grant: claimed.claim.grant, pr: claimed.claim.pr ?? claimed.pr } } : {}),
|
||||
}), { mode: 0o600, flag: 'wx' });
|
||||
return fixBase ? `${token}\nFIX_BASE=${fixBase}` : token;
|
||||
}
|
||||
@@ -305,11 +303,7 @@ export function bindReview(rec: Record<string, any>, token: string, env = proces
|
||||
if (error.code !== 'ENOENT') console.error(`gstack-review-log: cannot consume review start: ${error.message}`);
|
||||
}
|
||||
}
|
||||
if (rec.skill === 'review-fix-check') {
|
||||
for (const key of ['fix_check_base', 'run', 'grant', 'pr', 'hunks']) delete rec[key];
|
||||
const fc = start?.fix_check;
|
||||
if (fc) Object.assign(rec, { fix_check_base: fc.base, run: fc.run, grant: fc.grant, ...(fc.pr ? { pr: fc.pr } : {}), ...(h => (h ? { hunks: h } : {}))(readFixCheckHunks(env.GSTACK_REVIEW_REPO!, start.started_at)) });
|
||||
}
|
||||
if (rec.skill === 'review-fix-check') for (const key of ['fix_check_base', 'run', 'grant', 'pr', 'hunks']) delete rec[key];
|
||||
const end = env.GSTACK_STAMP_WTREE;
|
||||
const state = !start || !end ? 'uncaptured'
|
||||
: start.wtree !== end ? 'changed'
|
||||
@@ -484,59 +478,3 @@ export function reviewFreshness(rec: Record<string, any>, currentWtree: string,
|
||||
return { status: 'CURRENT', reason: merged ? `completed clean pass; ${merged}` : 'completed clean pass on unchanged content' };
|
||||
}
|
||||
|
||||
/** The hunks a fix-check reader was given: the sha256 of the file's bytes and every path its diff headers name. */
|
||||
export function hunksDigest(text: string): { sha256: string; paths: string[] } {
|
||||
const paths = new Set<string>();
|
||||
for (const m of text.matchAll(/^diff --git a\/(.+?) b\/(.+)$/gm)) { paths.add(m[1]!); paths.add(m[2]!); }
|
||||
return { sha256: createHash('sha256').update(text).digest('hex'), paths: [...paths].sort() };
|
||||
}
|
||||
|
||||
const hunksFile = (cwd: string) => {
|
||||
const r = spawnSync('git', ['rev-parse', '--git-path', 'gstack-fix-check-hunks'], { cwd, encoding: 'utf8', timeout: 60_000 });
|
||||
return r.status === 0 && r.stdout.trim() ? resolve(cwd, r.stdout.trim()) : '';
|
||||
};
|
||||
|
||||
/**
|
||||
* The hunks a claimed fix-check reads, built by gstack (GST-3546): git diff <the claimed grant's head> HEAD, the exact bytes
|
||||
* bindFixCheckRow later compares, so a thread never hand-builds a partial or stale packet. Undefined when this checkout's run
|
||||
* record holds no open claim, or git cannot diff it (the caller's --hunks file stands then).
|
||||
*/
|
||||
export function claimedFixCheckHunks(cwd: string): { base: string; text: string } | undefined {
|
||||
const read = readRunRecord(cwd);
|
||||
const base = read.kind === 'record' && read.record.state === 'open' ? read.record.claim?.stop_head : undefined;
|
||||
if (!base) return undefined;
|
||||
const r = spawnSync('git', ['diff', base, 'HEAD'], { cwd, encoding: 'utf8', timeout: 60_000, maxBuffer: 256 * 1024 * 1024 });
|
||||
return r.status === 0 && r.stdout.trim() ? { base, text: r.stdout } : undefined;
|
||||
}
|
||||
|
||||
/** The ledger ids, path:line:category fingerprints and a-… approval ids a fix list names: the only grant ids its clean fix-check can close. */
|
||||
export function fixListNames(text: string): string[] {
|
||||
return [...new Set(text.split(/[\s`'"(),;]+/).map(t => t.replace(/[.:]+$/, '')).filter(t => t.includes('#') || /:\d+:/.test(t) || /^a-[0-9a-f]{12}$/.test(t)))].sort();
|
||||
}
|
||||
|
||||
/** gstack-review-plan --fix-check-prompt and the pass program's fix-check render record the hunks and fix list they rendered from; a failed write only leaves the row without hunks, so it closes nothing. */
|
||||
export function recordFixCheckHunks(cwd: string, text: string, ledger: string | undefined, fixList: string): void {
|
||||
try {
|
||||
const file = hunksFile(cwd);
|
||||
if (file) writeFileSync(file, JSON.stringify({ at: new Date().toISOString(), ...hunksDigest(text), fix_list: fixListNames(fixList), ...(ledger ? { ledger: resolve(ledger) } : {}) }) + '\n');
|
||||
} catch { /* the row carries no hunks and closes nothing */ }
|
||||
}
|
||||
|
||||
/** The pass program renders a fix-check brief before it takes the review-fix-check start (GST-3523): re-date that render's record, only while its digest still matches the hunks the brief carried, so the start's row attaches it. */
|
||||
export function restampFixCheckHunks(cwd: string, text: string): boolean {
|
||||
try {
|
||||
const file = hunksFile(cwd);
|
||||
const o = JSON.parse(readFileSync(file, 'utf8'));
|
||||
if (o.sha256 !== hunksDigest(text).sha256) return false;
|
||||
writeFileSync(file, JSON.stringify({ ...o, at: new Date().toISOString() }) + '\n');
|
||||
return true;
|
||||
} catch { return false; }
|
||||
}
|
||||
|
||||
/** The hunks record gstack-review-log stamps on a granted fix-check row: the newest render at or after the row's start. */
|
||||
export function readFixCheckHunks(cwd: string, since: string): { sha256: string; paths: string[]; fix_list: string[]; ledger?: string } | undefined {
|
||||
try {
|
||||
const o = JSON.parse(readFileSync(hunksFile(cwd), 'utf8'));
|
||||
return Date.parse(o.at) >= Date.parse(since) && typeof o.sha256 === 'string' && Array.isArray(o.paths) ? { sha256: o.sha256, paths: o.paths, fix_list: Array.isArray(o.fix_list) ? o.fix_list : [], ...(typeof o.ledger === 'string' ? { ledger: o.ledger } : {}) } : undefined;
|
||||
} catch { return undefined; }
|
||||
}
|
||||
+1
-3
@@ -19,7 +19,6 @@ import { newestModel } from './model-families';
|
||||
import { BriefError, briefFile, checkoutRoot, checkoutTree, promptHash, renderBrief, sliceDiff, sliceNote, withWorkspace, type BriefRole, type SectionTexts, type Slots } from './review-brief';
|
||||
import { REVIEW_DIFF_MAX_BYTES, disclosureDigest } from './review-exclude';
|
||||
import { appendEvent, readerKey } from './review-ledger';
|
||||
import { claimedFixCheckHunks, recordFixCheckHunks } from './review-evidence';
|
||||
import { policySelection, selectFor } from './review-selection';
|
||||
import { SPECIALISTS, diffCommand, type Dispatch } from './review-depth';
|
||||
import { TARGETED_RULES, parseClassList, targetedBriefSha, targetedRead } from './review-targeted';
|
||||
@@ -252,8 +251,7 @@ export function renderStage(m: Manifest, stage: Stage, t: SectionTexts, diffFor:
|
||||
if (role === 'fix-check') {
|
||||
const read = (f: string | undefined, what: string) => { if (!f) return undefined; try { return fs.readFileSync(f, 'utf8'); } catch { throw new BriefError(`cannot read the fix-check ${what} ${f}`); } };
|
||||
const fc = m.fix_check!;
|
||||
Object.assign(slots, { fix_list: read(fc.fix_list, 'fix list'), hunks: claimedFixCheckHunks(process.cwd())?.text ?? read(fc.hunks, 'hunks'), tests: read(fc.tests, 'tests'), callers: read(fc.callers, 'callers') });
|
||||
recordFixCheckHunks(process.cwd(), slots.hunks ?? '', m.ledger, slots.fix_list ?? '');
|
||||
Object.assign(slots, { fix_list: read(fc.fix_list, 'fix list'), hunks: read(fc.hunks, 'hunks'), tests: read(fc.tests, 'tests'), callers: read(fc.callers, 'callers') });
|
||||
}
|
||||
let targeted = {};
|
||||
if (role === 'targeted' || (role === 'adversarial-native' && r.classes?.length)) {
|
||||
|
||||
@@ -1,158 +0,0 @@
|
||||
/**
|
||||
* Review round grants (GST-2673, docs/review-policy.md#rounds-per-pull-request): a reason the lane or its Captain
|
||||
* records when a PR needs a review round its R51 count would not plan. kind=extra-round: one round, with its fix
|
||||
* round, past the PR's cap of two, at a head no review has stopped at. kind=fix-check (GST-2968): the fix round of a
|
||||
* review that already stopped, naming that stop (its run and head, lib/pr-review-history.ts stopRecord) and the
|
||||
* findings it is for. Each binds one head of one PR and is spent by the run that claims it. It is recorded with
|
||||
* gstack-approvals round-grant, is never an owner ask and never a plan approval (lib/plan-record.ts NOT_PLAN_ROW).
|
||||
* --by is recorded, not enforced.
|
||||
*/
|
||||
import { spawnSync } from './spawn-sync';
|
||||
import { locate, readRecord, type ApprovalRow, type Env } from './approval-record';
|
||||
import { isGstackActorName, publicRuledNote, type RuledNote } from './ruled-notes';
|
||||
import { isSecurityFinding, opaqueFindingId, REDACTED_FINDING, REDACTED_REASON } from './security-findings';
|
||||
|
||||
export const ROUND_GRANT_KINDS = ['extra-round', 'fix-check'] as const;
|
||||
export type RoundGrantKind = (typeof ROUND_GRANT_KINDS)[number];
|
||||
/** stop_run and findings: a fix-check grant's stop (the run that stopped at head) and the finding ids it is for. */
|
||||
/**
|
||||
* One grant kind (GST-3546): a fix-check grant names its head (a stop record's head, or the reviewed head a post-review edit
|
||||
* follows, with no stop) and buys one scoped fix-check from it. An owner's `review_loop_grant <head>` approval row reads as the
|
||||
* same grant (legacy, pr 0: it names no PR, so it binds to whichever PR claims it), so the planner, claim and write accept
|
||||
* either row.
|
||||
*/
|
||||
export interface ReviewRoundGrant { kind: RoundGrantKind; head: string; pr: number; by: string; reason: string; at: string; approval: string; stop_run?: string; findings?: string[]; legacy?: true }
|
||||
|
||||
export const STOP_RUN = /^[\w.:-]{1,120}$/;
|
||||
export const FINDING_ID = /^[\w.:/#@-]{1,200}$/;
|
||||
const SCOPE = /^review_round_grant ([0-9a-f]{40}) pr=([1-9]\d*) kind=(extra-round|fix-check)(?: stop=(\S+) findings=(\S+))?$/;
|
||||
export const LEGACY_GRANT = /\breview_loop_grant\s+([0-9a-f]{7,40})\b/;
|
||||
/** Scopes recorded by their own commands, whose text may mention a grant without being one. */
|
||||
export const OTHER_GRANT_ROW = /^\s*(ruled_note|gate_disposition|review_loop_exception|test_lane_exception|review_round_grant)\b/;
|
||||
const ASK = /^review_round_grant (extra-round|fix-check) at ([0-9a-f]{40}) for pr ([1-9]\d*): (\S(?:.*\S)?)$/;
|
||||
export const REVIEW_ROUND_GRANT_SCOPE = /^\s*review_round_grant\b/;
|
||||
|
||||
/** The ask's cap (lib/approval-record.ts CAPS.ask); a longer reason is cut with an ellipsis and its full words stay in --words. */
|
||||
export const ROUND_GRANT_ASK_MAX = 300;
|
||||
export function reviewRoundGrantRow(head: string, pr: number, kind: RoundGrantKind, reason: string, stop?: { run: string; findings: readonly string[] }) {
|
||||
const lead = `review_round_grant ${kind} at ${head} for pr ${pr}: `;
|
||||
const room = ROUND_GRANT_ASK_MAX - lead.length;
|
||||
const said = reason.length <= room ? reason : `${reason.slice(0, room - 1).trimEnd()}…`;
|
||||
return { scope: `review_round_grant ${head} pr=${pr} kind=${kind}${stop ? ` stop=${stop.run} findings=${stop.findings.join(',')}` : ''}`, ask: lead + said };
|
||||
}
|
||||
|
||||
export function reviewRoundGrants(rows: readonly ApprovalRow[], resolve?: (sha: string) => string | undefined): ReviewRoundGrant[] {
|
||||
const out: ReviewRoundGrant[] = [];
|
||||
for (const r of rows) {
|
||||
if (r.outcome !== 'approved' || isGstackActorName(r.by)) continue;
|
||||
const s = SCOPE.exec(r.scope), a = ASK.exec(r.ask);
|
||||
if (!s && !OTHER_GRANT_ROW.test(r.scope)) {
|
||||
const l = LEGACY_GRANT.exec(`${r.ask} ${r.scope}`);
|
||||
const head = l ? (l[1]!.length === 40 ? l[1]! : resolve?.(l[1]!)) : undefined;
|
||||
if (head) out.push({ kind: 'fix-check', head: head.toLowerCase(), pr: 0, by: r.by, reason: r.ask, at: r.recorded_at, approval: r.id, findings: [], legacy: true });
|
||||
continue;
|
||||
}
|
||||
if (!s || !a) continue;
|
||||
if (a[1] !== s[3] || a[2] !== s[1] || a[3] !== s[2]) continue;
|
||||
const findings = s[5]?.split(',');
|
||||
if ((s[3] !== 'fix-check' && s[4] !== undefined) || (s[4] !== undefined && (!STOP_RUN.test(s[4]) || !findings!.every(f => FINDING_ID.test(f))))) continue;
|
||||
out.push({ kind: s[3] as RoundGrantKind, head: s[1]!, pr: Number(s[2]), by: r.by, reason: a[4]!, at: r.recorded_at, approval: r.id, ...(s[4] ? { stop_run: s[4], findings } : s[3] === 'fix-check' ? { findings: [] } : {}) });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* A grant as the receipt in the PR body may carry it: a security-class finding it names leaves its fingerprint in the approval
|
||||
* record (lib/security-findings.ts). One the owner ruled not security class shows as that ruling's public text does, and any
|
||||
* other becomes an opaque id, so gstack-post never refuses the receipt over a grant's finding list (gbrain-evals#567). The grant's
|
||||
* reason is free text that can describe the finding, so it becomes REDACTED_REASON whenever a security finding stays hidden.
|
||||
*/
|
||||
export function publicRoundGrant(g: ReviewRoundGrant, ruled: readonly RuledNote[]): ReviewRoundGrant {
|
||||
if (!g.findings?.some(f => isSecurityFinding(f))) return g;
|
||||
const shown = (f: string) => { const n = ruled.find(r => r.finding === f && r.not_security); return n ? publicRuledNote(n).finding : undefined; };
|
||||
const hidden = g.findings.some(f => isSecurityFinding(f) && (shown(f) ?? REDACTED_FINDING) === REDACTED_FINDING);
|
||||
return { ...g, findings: g.findings.map(f => !isSecurityFinding(f) ? f : shown(f) ?? opaqueFindingId(f, `round grant ${g.approval}`)), ...(hidden ? { reason: REDACTED_REASON } : {}) };
|
||||
}
|
||||
|
||||
export function readReviewRoundGrants(cwd: string, env: Env = process.env): ReviewRoundGrant[] {
|
||||
const loc = locate({ cwd, env });
|
||||
if ('code' in loc) return [];
|
||||
return reviewRoundGrants(readRecord(loc).rows, sha => {
|
||||
const r = spawnSync('git', ['rev-parse', '--verify', '--quiet', `${sha}^{commit}`], { cwd, encoding: 'utf8', timeout: 10_000 });
|
||||
return r.status === 0 ? r.stdout.trim() : undefined;
|
||||
});
|
||||
}
|
||||
|
||||
/** Whether a grant binds this PR: its own PR, or any PR for a legacy review_loop_grant row, which names none. */
|
||||
export const grantForPr = (g: Pick<ReviewRoundGrant, 'pr'>, pr: number | undefined) => !g.pr || g.pr === pr;
|
||||
|
||||
/** The newest extra-round grant for this PR at exactly this head (a fix-check grant answers a stop instead: lib/pr-review-history.ts grantedStop). */
|
||||
export const grantAt = (grants: readonly ReviewRoundGrant[], pr: number, head: string) =>
|
||||
[...grants].reverse().find(g => g.kind === 'extra-round' && g.pr === pr && g.head === head.toLowerCase());
|
||||
|
||||
/**
|
||||
* The newest extra-round grant for this PR at this head, or at a head this one only merges the base into or out of (GST-2968): one is
|
||||
* the other's ancestor and the PR's own added and removed lines against baseRef are byte-identical, in the same places, at both.
|
||||
* Preflight merges the base before the review, so the head a grant names and the head the next run reads can differ that way.
|
||||
*/
|
||||
export function grantFor(repoRoot: string, grants: readonly ReviewRoundGrant[], pr: number, head: string, baseRef?: string): ReviewRoundGrant | undefined {
|
||||
const exact = grantAt(grants, pr, head);
|
||||
if (exact || !baseRef) return exact;
|
||||
return [...grants].reverse().find(g => g.kind === 'extra-round' && g.pr === pr && ownLinesSame(repoRoot, baseRef, g.head, head.toLowerCase()));
|
||||
}
|
||||
|
||||
interface Hunk { path: string; start: number; len: number; added: number }
|
||||
|
||||
/** A zero-context diff's hunks: the file (its old side, or its new side when created), the old-side start and length, and the added length. */
|
||||
function hunks(diff: string): Hunk[] {
|
||||
const out: Hunk[] = [];
|
||||
let minus = '', path = '';
|
||||
for (const l of diff.split('\n')) {
|
||||
if (l.startsWith('--- ')) minus = l.slice(4);
|
||||
else if (l.startsWith('+++ ')) path = minus === '/dev/null' ? l.slice(4) : minus;
|
||||
const m = /^@@ -(\d+)(?:,(\d+))? \+\d+(?:,(\d+))? @@/.exec(l);
|
||||
if (m) out.push({ path, start: +m[1]!, len: m[2] === undefined ? 1 : +m[2], added: m[3] === undefined ? 1 : +m[3] });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* The old-side line own hunk h starts at once the base's hunks have moved its file, or null when the base edited a line h changes or
|
||||
* inserted inside or right next to h, so its place can't be carried over. Spans are in half-line steps: 2n is line n, 2n+1 the gap after it.
|
||||
*/
|
||||
function carried(base: readonly Hunk[], h: Hunk): number | null {
|
||||
const span = (x: Hunk, pad: number): [number, number] => x.len ? [2 * x.start - pad, 2 * (x.start + x.len - 1) + pad] : [2 * x.start + 1 - pad, 2 * x.start + 1 + pad];
|
||||
const [lo, hi] = span(h, 1);
|
||||
let shift = 0;
|
||||
for (const b of base.filter(x => x.path === h.path)) {
|
||||
const [blo, bhi] = span(b, 0);
|
||||
if (blo <= hi && lo <= bhi) return null;
|
||||
if (bhi < lo) shift += b.added - b.len;
|
||||
}
|
||||
return h.start + shift;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a and b are on one line of history and carry byte-identical own lines against baseRef at the same places: equal
|
||||
* zero-context patch-ids, and each own hunk of a, carried through the base's changes between the two forks, starts where b's does.
|
||||
* Moving a line to another place in the same file changes no patch-id, so the places are compared too.
|
||||
*/
|
||||
export function ownLinesSame(repoRoot: string, baseRef: string, a: string, b: string): boolean {
|
||||
const git = (args: string[], input?: string) => spawnSync('git', ['-c', 'core.quotepath=off', ...args], { cwd: repoRoot, encoding: 'utf8', input, timeout: 120_000, maxBuffer: 256 * 1024 * 1024 });
|
||||
if (git(['merge-base', '--is-ancestor', a, b]).status !== 0 && git(['merge-base', '--is-ancestor', b, a]).status !== 0) return false;
|
||||
const fork = (c: string) => { const f = git(['merge-base', baseRef, c]); return f.status === 0 ? f.stdout.trim() : null; };
|
||||
const diff = (x: string, y: string) => { const d = git(['diff', '--no-color', '--no-ext-diff', '--no-textconv', '--no-renames', '--binary', '--full-index', '-U0', x, y]); return d.status === 0 ? d.stdout : null; };
|
||||
const id = (d: string) => { const p = git(['patch-id', '--verbatim'], d); return p.status === 0 ? p.stdout.trim().split(/\s+/)[0] || null : null; };
|
||||
const fa = fork(a), fb = fork(b);
|
||||
if (!fa || !fb) return false;
|
||||
const da = diff(fa, a), db = diff(fb, b), moved = fa === fb ? '' : diff(fa, fb);
|
||||
if (!da?.trim() || !db?.trim() || moved === null) return false;
|
||||
const x = id(da);
|
||||
if (x === null || x !== id(db)) return false;
|
||||
const base = hunks(moved), there = hunks(db), here = hunks(da);
|
||||
return here.length === there.length && here.every((h, i) => h.path === there[i]!.path && h.len === there[i]!.len && carried(base, h) === there[i]!.start);
|
||||
}
|
||||
|
||||
/** The text after "Review round grant: " in the PR body. */
|
||||
export const reviewRoundGrantText = (g: ReviewRoundGrant) =>
|
||||
`${g.kind} at ${g.head.slice(0, 12)} for PR #${g.pr}${g.stop_run ? ` (stop ${g.stop_run}, findings ${g.findings!.join(', ')})` : g.kind === 'fix-check' ? ' (no stop: the reviewed head)' : ''} recorded by ${g.by} at ${g.at}: ${g.reason} (approval ${g.approval})`;
|
||||
@@ -8,9 +8,7 @@
|
||||
* asks this module when the loop is done and the head has targeted classes the passed --targeted-ran no longer covers.
|
||||
* It dispatches one targeted reader on HEAD only when range_base is the commit that read happened on (its targeted
|
||||
* patch-id is --targeted-ran), every path the PR's own change moved since, release stamps aside, is docs class and not
|
||||
* binary, and that change is not plain docs. With the owner's review_loop_grant for a stop head inside range_base..HEAD
|
||||
* (`granted`, checked by the plan before it gets here), a code change since the read takes the same one reader (GST-1607, harness-evals #271: the
|
||||
* granted fix round moved the product patch the record names). Anything else keeps `done` with the reason.
|
||||
* binary, and that change is not plain docs. Anything else keeps `done` with the reason.
|
||||
*/
|
||||
import { spawnSync } from './spawn-sync';
|
||||
import { comparePath, touchedPaths } from './ship-patch';
|
||||
@@ -19,7 +17,7 @@ import { docsChangeSince } 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. */
|
||||
export function targetedDelta(root: string, base: string, rangeBase: string, ran: string, granted = false): TargetedDelta {
|
||||
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;
|
||||
@@ -43,7 +41,7 @@ export function targetedDelta(root: string, base: string, rangeBase: string, ran
|
||||
if (!paths.length) return skip(`the branch patch is unchanged since range_base ${read.slice(0, 12)}`);
|
||||
const change = docsChangeSince(root, read, head, base);
|
||||
if (!change) return skip(`git could not build the PR's own change since range_base ${read.slice(0, 12)}`);
|
||||
if (change.verdict === 'code' && !granted) return skip(`the change since range_base ${read.slice(0, 12)} is not docs-only (${change.paths.join(', ')}), so it takes the review loop`);
|
||||
if (change.verdict === 'code') return skip(`the change since range_base ${read.slice(0, 12)} is not docs-only (${change.paths.join(', ')}), so it takes the review loop`);
|
||||
if (change.verdict === 'plain') return skip(`the change since range_base ${read.slice(0, 12)} is ${change.paths.length ? 'plain docs' : 'release stamps'}${change.paths.length && change.stamps.length ? ' and release stamps' : ''}, which the targeted record carries (GST-1195, GST-1689)`, true);
|
||||
return { state: 'dispatch', range_base: read, paths: [...change.paths] };
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* review-trailer-clearing: when an open blocker closes without an owner ruling (#4597, docs/review-policy.md#what-closes-a-finding).
|
||||
* A fix commit carries the finding's Review-Finding trailer and a later complete full review of the branch read it clean;
|
||||
* gstack-ship-receipt write closes exactly those blockers through clearByTrailer and records them as cleared_by_trailer. Every
|
||||
* input is a record gstack's tools wrote (the review log and the branch's commits); the agent's --review-loop file only lists
|
||||
* which blockers are open. The granted fix-check route that shared this module was removed in GST-3562 part 4.
|
||||
*/
|
||||
import { spawnSync } from './spawn-sync';
|
||||
import { parseFixTrailers, rowTime } from './review-scope';
|
||||
import { isSecurityFinding } from './security-findings';
|
||||
|
||||
type Row = Record<string, any>;
|
||||
/** One entry of the loop summary's `open` list: a ledger id or fingerprint, or both. */
|
||||
export type OpenBlocker = string | { id: string; fingerprint: string };
|
||||
export interface TrailerClearing { id: string; commit: string; review: string }
|
||||
|
||||
const SHA = /^[0-9a-f]{40}$/;
|
||||
const git = (cwd: string, args: string[]) => {
|
||||
const r = spawnSync('git', args, { cwd, encoding: 'utf8', timeout: 60_000, maxBuffer: 64 * 1024 * 1024 });
|
||||
return r.status === 0 ? r.stdout ?? '' : null;
|
||||
};
|
||||
const ancestor = (cwd: string, a: string, d: string) => a === d || git(cwd, ['merge-base', '--is-ancestor', a, d]) !== null;
|
||||
const treeOf = (cwd: string, c: string) => git(cwd, ['rev-parse', '--verify', '--quiet', `${c}^{tree}`])?.trim();
|
||||
const findingsOf = (r: Row): Row[] => (Array.isArray(r?.findings) ? r.findings.filter((f: unknown) => !!f && typeof f === 'object') : []);
|
||||
const nameOf = (b: OpenBlocker) => (typeof b === 'string' ? b : b.id);
|
||||
|
||||
/**
|
||||
* The #4597 route: an open blocker closes when a branch commit carries its Review-Finding trailer (its exact ledger id, or its
|
||||
* fingerprint when no other open blocker shares it) and a later complete full review, bound to its own committed tree on this
|
||||
* branch and holding that commit in its range, left nothing open (its status, findings_open from a findings file, an inline open
|
||||
* finding). Gate findings never close this way.
|
||||
*/
|
||||
export function clearByTrailer(cwd: string, o: { head: string; baseRef: string; rows: readonly Row[]; open: readonly OpenBlocker[] }): TrailerClearing[] {
|
||||
const log = git(cwd, ['log', '--no-merges', '--format=%H%x00%(trailers:key=Review-Finding,valueonly,separator=%x1f)%x1e', `${o.baseRef}..${o.head}`]);
|
||||
const trailers = (log ?? '').split('\x1e').flatMap(rec => { const [sha, values] = rec.trim().split('\0'); return sha && values ? parseFixTrailers(sha, values.split('\x1f').map(v => v.trim()).filter(Boolean)) : []; });
|
||||
return o.open.flatMap(b => {
|
||||
const id = nameOf(b), fp = typeof b === 'string' ? b : b.fingerprint;
|
||||
const raised = o.rows.flatMap(r => findingsOf(r).filter(f => f.action === 'open' && (f.ledger_id === id || (f.ledger_id === undefined && f.fingerprint === fp))).map(f => ({ r, f })));
|
||||
const alone = o.open.filter(c => (typeof c === 'string' ? c : c.fingerprint) === fp).length === 1;
|
||||
const t = trailers.find(x => x.finding === id || (alone && x.finding === fp));
|
||||
if (!t || !raised.length || raised.some(x => x.f.gate !== undefined) || isSecurityFinding(t.finding)) return [];
|
||||
const after = Math.max(...raised.map(x => rowTime(x.r)));
|
||||
const inRange = (from: unknown, fix: string) => from == null || (typeof from === 'string' && (b => !!b && !ancestor(cwd, fix, b))(git(cwd, ['rev-parse', '--verify', '--quiet', `${from}^{commit}`])?.trim()));
|
||||
const review = o.rows.find(r => r?.skill === 'review' && r.via === 'ship' && r.completed === true && r.scope !== 'fix-range' && r.scope !== 'scoped' && rowTime(r) > after
|
||||
&& r.converged === true && r.review_binding?.state === 'verified' && inRange(r.range_base, t.commit) && typeof r.tree === 'string' && r.review_binding.start_wtree === r.tree && r.review_binding.end_wtree === r.tree
|
||||
&& SHA.test(String(r.commit_full)) && treeOf(cwd, r.commit_full) === r.tree && ancestor(cwd, t.commit, r.commit_full) && ancestor(cwd, r.commit_full, o.head)
|
||||
&& r.status !== 'issues_found' && r.status !== 'issues_open' && Number(r.findings_open ?? 0) === 0 && !findingsOf(r).some(f => f.action === 'open'));
|
||||
return review ? [{ id, commit: t.commit, review: review.commit_full as string }] : [];
|
||||
});
|
||||
}
|
||||
+3
-14
@@ -32,7 +32,7 @@ import { CHECKS, pregateMirrorPath, readPregateFile, verifyPregate, PREGATE_OUT_
|
||||
import { exceptionConsumerProblem, flakyExceptionLines } from './pregate/flaky-exception';
|
||||
import { ensureTmpExcluded, restamp, versionAtRef } from './restamp';
|
||||
import type { ResultCodeName } from './result-codes';
|
||||
import { extractReceipt, readyTailLines, type ReadyTail } from './ship-receipt';
|
||||
import { extractReceipt, readyTailLines } from './ship-receipt';
|
||||
import { bindShippedReceipt } from './ship-receipt-depth';
|
||||
import { isUnavailable, loadPolicyFromBase, type LoadedPolicy } from './ship-policy';
|
||||
import { finishPlanLine, readyPlan } from './plan-record';
|
||||
@@ -340,18 +340,7 @@ export function trialMergeLines(ctx: QueueContext, pr: string, head: string, cha
|
||||
});
|
||||
}
|
||||
|
||||
/** The newest row of a decision trail (gstack-decision-trail) whose phase is trail-read: its row number, the reader it names and its result, the reader's flags. */
|
||||
export function trailReadRow(file: string | undefined): ReadyTail['trailRead'] {
|
||||
if (!file) return { missing: 'ready got no --trail <decisions.tsv>' };
|
||||
let text: string;
|
||||
try { text = fs.readFileSync(file, 'utf8'); } catch (e: any) { return { missing: `cannot read --trail ${file} (${e?.code ?? 'unreadable'})` }; }
|
||||
const rows = text.split('\n').slice(1).filter(Boolean).map(l => l.split('\t'));
|
||||
for (let i = rows.length - 1; i >= 0; i--) if (rows[i]![1]?.trim().toLowerCase() === 'trail-read' && rows[i]![2]?.trim()) return { row: i + 1, reader: rows[i]![2]!.trim(), flags: rows[i]![5]?.trim() ?? '' };
|
||||
return { missing: `${file} has no trail-read row` };
|
||||
}
|
||||
|
||||
/** READY: one block, identifiers first, about the exact pushed PR head. */
|
||||
export function ready(ctx: QueueContext, o: { pr: string; pregate?: string; gateExit?: number; gateLog?: string; trail?: string }): StepOutput {
|
||||
export function ready(ctx: QueueContext, o: { pr: string; pregate?: string; gateExit?: number; gateLog?: string }): StepOutput {
|
||||
const run = PREGATE_OUT_REL;
|
||||
const unfetched = refreshBase(ctx);
|
||||
if (unfetched) return fail(unfetched, [], run);
|
||||
@@ -426,7 +415,7 @@ export function ready(ctx: QueueContext, o: { pr: string; pregate?: string; gate
|
||||
...(receipt.depthLine ? [receipt.depthLine] : []),
|
||||
...(receipt.targetedLine ? [receipt.targetedLine] : []),
|
||||
...(gates?.lines ?? []),
|
||||
...readyTailLines(receipt.ok ? { ...receipt.receipt, gate_dispositions: undefined } : undefined, { trialMerges: trials, trailRead: trailReadRow(o.trail) }),
|
||||
...readyTailLines(receipt.ok ? { ...receipt.receipt, gate_dispositions: undefined } : undefined, { trialMerges: trials }),
|
||||
];
|
||||
const gate = policy.policy.full_e2e ? gateEvidence(ctx, o.pr, head, attempt, o.gateExit, o.gateLog) : null;
|
||||
if (gate) lines.push(gate.line);
|
||||
|
||||
@@ -8,8 +8,6 @@
|
||||
* git objects, gstack-diff-scope on that range and the gate scan of the clean
|
||||
* checkout at that head), with the runtime lines, the rules hash, the base and
|
||||
* registry commits and the gate scan bound to the head.
|
||||
* `review_loop_exception`: the owner's acceptance of a stop after a
|
||||
* fix-check edit under frozen scope (#3559), shaped like the docs exception.
|
||||
* The queue recomputes the depth the head needs from git objects
|
||||
* (lib/review-collect.ts) and refuses a receipt below it.
|
||||
* `review_targeted`: the targeted pass on money, gate, auth and secret code
|
||||
@@ -42,7 +40,6 @@ import { READ_REASONS, docsAuditPacket, readDocsAuditRead, type DocsAuditRead }
|
||||
import { carriedAudits, docsExceptionLine, parseReceiptDocs, sameRun, type CarriedAudit } from './ship-receipt-docs';
|
||||
|
||||
export type ReceiptDepth = NonNullable<ShipReceipt['review_depth']>;
|
||||
export type ReviewLoopException = NonNullable<ShipReceipt['review_loop_exception']>;
|
||||
const RANK: Record<Depth | 'platform', number> = { platform: -1, light: 0, standard: 1, full: 2 };
|
||||
const text = (v: unknown): v is string => typeof v === 'string' && v.trim().length > 0 && !/[\x00-\x1f\x7f]/.test(v);
|
||||
const sha = (v: unknown): v is string => typeof v === 'string' && /^[0-9a-f]{40}$/.test(v);
|
||||
@@ -158,78 +155,21 @@ export function taggedPaths(jsonl: string): Set<string> {
|
||||
export const depthBelow = (have: Depth | 'platform', need: Depth | 'platform') => RANK[have] < RANK[need];
|
||||
export const deeper = <D extends Depth | 'platform'>(a: D, b: D): D => (RANK[a] >= RANK[b] ? a : b);
|
||||
|
||||
/**
|
||||
* `write --review-loop-exception` input and the queue's check: who accepted the stop, when, where, why, and the stop it accepts:
|
||||
* the fix-check it followed (`fix_check`), or the second full pass that left a finding open (`second_pass`, the deferred
|
||||
* finding ids; TRUT-7).
|
||||
*/
|
||||
export function parseReviewLoopException(value: unknown): { ok: true; exception: ReviewLoopException } | { ok: false; message: string } {
|
||||
const bad = (message: string) => ({ ok: false as const, message });
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) return bad('review_loop_exception must be { accepted_by, date, via, reason, fix_check: { head, findings[, files] } | second_pass: { head, deferred: [<finding id>] } }');
|
||||
const v = value as Record<string, unknown>;
|
||||
for (const key of Object.keys(v)) if (!['accepted_by', 'date', 'via', 'reason', 'fix_check', 'second_pass'].includes(key)) return bad(`review_loop_exception: unknown key ${JSON.stringify(key)}`);
|
||||
for (const key of ['accepted_by', 'date', 'via', 'reason']) if (!text(v[key])) return bad(`review_loop_exception.${key} must be a non-empty one-line string`);
|
||||
if (!/^\d{4}-\d{2}-\d{2}$/.test(v.date as string)) return bad('review_loop_exception.date must be YYYY-MM-DD');
|
||||
if ((v.fix_check === undefined) === (v.second_pass === undefined)) return bad('review_loop_exception names exactly one of fix_check or second_pass: the stop it accepts');
|
||||
const accepted = { accepted_by: (v.accepted_by as string).trim(), date: v.date as string, via: (v.via as string).trim(), reason: (v.reason as string).trim() };
|
||||
if (v.second_pass !== undefined) {
|
||||
const s = v.second_pass as Record<string, unknown> | null;
|
||||
if (!s || typeof s !== 'object' || Array.isArray(s)) return bad('review_loop_exception.second_pass must be { head, deferred: [<finding id>] }');
|
||||
for (const key of Object.keys(s)) if (!['head', 'deferred'].includes(key)) return bad(`review_loop_exception.second_pass: unknown key ${JSON.stringify(key)}`);
|
||||
if (!sha(s.head)) return bad('review_loop_exception.second_pass.head must be the full commit the second full pass reviewed');
|
||||
if (!Array.isArray(s.deferred) || !s.deferred.length || !s.deferred.every(text)) return bad('review_loop_exception.second_pass.deferred must name the open finding the owner accepted by id');
|
||||
return { ok: true, exception: { ...accepted, second_pass: { head: s.head, deferred: (s.deferred as string[]).slice(0, 20).map(d => d.trim()) } } };
|
||||
}
|
||||
const f = v.fix_check as Record<string, unknown> | null;
|
||||
if (!f || typeof f !== 'object' || Array.isArray(f)) return bad('review_loop_exception.fix_check must be { head, findings[, files] }');
|
||||
for (const key of Object.keys(f)) if (!['head', 'findings', 'files'].includes(key)) return bad(`review_loop_exception.fix_check: unknown key ${JSON.stringify(key)}`);
|
||||
if (!sha(f.head)) return bad('review_loop_exception.fix_check.head must be the full commit the fix-check reviewed');
|
||||
if (typeof f.findings !== 'number' || !Number.isInteger(f.findings) || f.findings < 0) return bad('review_loop_exception.fix_check.findings must be an integer >= 0 (what the fix-check reported)');
|
||||
if (f.files !== undefined && (!Array.isArray(f.files) || !f.files.every(text))) return bad('review_loop_exception.fix_check.files must be a list of paths');
|
||||
const files = (f.files as string[] | undefined)?.slice(0, 50);
|
||||
return { ok: true, exception: { ...accepted, fix_check: { head: f.head, findings: f.findings, ...(files?.length ? { files } : {}) } } };
|
||||
}
|
||||
|
||||
/** The commit the accepted stop reviewed: the fix-check's head or the second full pass's. */
|
||||
export const exceptionHead = (e: ReviewLoopException) => (e.fix_check ?? e.second_pass)!.head;
|
||||
|
||||
/** Whether the review loop shows the stop the exception accepts: a fix-check ran, or two full passes left a finding deferred. */
|
||||
export function exceptionLoopProblem(e: ReviewLoopException, loop: ShipReceipt['review_loop']): string | null {
|
||||
if (e.fix_check) return loop?.fix_checks ? null : 'needs --review-loop with fix_checks >= 1: the stop it accepts follows a fix-check';
|
||||
return (loop?.passes ?? 0) >= 2 && (loop?.deferred ?? 0) >= 1 ? null : 'second_pass needs --review-loop with passes >= 2 and deferred >= 1: the stop it accepts follows the second full pass with a finding left open';
|
||||
}
|
||||
|
||||
/** The line the PR body must carry, word for word, while the exception stands. */
|
||||
export function reviewLoopExceptionLine(e: ReviewLoopException): string {
|
||||
const stop = e.fix_check ? `fix-check at ${e.fix_check.head.slice(0, 12)}, ${e.fix_check.findings} finding${e.fix_check.findings === 1 ? '' : 's'}` : `second full pass at ${e.second_pass!.head.slice(0, 12)}, deferred ${e.second_pass!.deferred.join(', ')}`;
|
||||
return `Review-loop exception: accepted by ${e.accepted_by} ${e.date} via ${e.via}: ${e.reason} (${stop})`;
|
||||
}
|
||||
|
||||
const carries = (body: string, line: string) => body.split(/\r?\n/).some(l => l.trim() === line);
|
||||
|
||||
/**
|
||||
* The owner exceptions a receipt records, checked the same way: valid shape, and the body carries each line verbatim.
|
||||
* `isAncestor`, when given, also requires the review-loop exception's fix-check head to be the receipt head or its ancestor.
|
||||
* The owner exception a receipt records (the documentation exception): valid shape, and the body carries its line verbatim.
|
||||
* A legacy review-loop exception no longer stands: GST-3562 part 4 removed the check that kept its line in the body.
|
||||
*/
|
||||
export function exceptionProblems(body: string, r: ShipReceipt, isAncestor?: (commit: string) => boolean): string[] {
|
||||
export function exceptionProblems(body: string, r: ShipReceipt): string[] {
|
||||
const out: string[] = [];
|
||||
const raw = r as ShipReceipt & { docs?: unknown };
|
||||
const raw = r as ShipReceipt & { docs?: unknown; review_loop_exception?: unknown };
|
||||
if (raw.review_loop_exception !== undefined) out.push('the receipt records a review-loop exception, which GST-3562 part 4 removed');
|
||||
if (raw.docs !== undefined) {
|
||||
const d = parseReceiptDocs(raw.docs);
|
||||
if (!d.ok) out.push(`docs: ${d.message}`);
|
||||
else { const line = docsExceptionLine(d.docs); if (line && !carries(body, line)) out.push(`the body does not carry the documentation exception line verbatim: ${JSON.stringify(line)}`); }
|
||||
}
|
||||
if (r.review_loop_exception !== undefined) {
|
||||
const e = parseReviewLoopException(r.review_loop_exception);
|
||||
if (!e.ok) out.push(e.message);
|
||||
else {
|
||||
const loopProblem = exceptionLoopProblem(e.exception, r.review_loop);
|
||||
if (loopProblem) out.push(`review_loop_exception ${loopProblem.replace('--review-loop', 'review_loop')}`);
|
||||
if (isAncestor && !isAncestor(exceptionHead(e.exception))) out.push(`review_loop_exception's head ${exceptionHead(e.exception).slice(0, 12)} is not the receipt head or an ancestor of it`);
|
||||
const line = reviewLoopExceptionLine(e.exception);
|
||||
if (!carries(body, line)) out.push(`the body does not carry the review-loop exception line verbatim: ${JSON.stringify(line)}`);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
@@ -424,7 +364,7 @@ export function writeExcludeBinds(root: string, base: string, head: string, revi
|
||||
const index = path.join(gitDir, `gstack-receipt-${process.pid}-${randomBytes(4).toString('hex')}.index`);
|
||||
const env = { ...process.env, GIT_INDEX_FILE: index, GIT_AUTHOR_NAME: 'gstack-ship-receipt', GIT_AUTHOR_EMAIL: 'ship-receipt@gstack.local', GIT_COMMITTER_NAME: 'gstack-ship-receipt', GIT_COMMITTER_EMAIL: 'ship-receipt@gstack.local', GIT_AUTHOR_DATE: '2000-01-01T00:00:00Z', GIT_COMMITTER_DATE: '2000-01-01T00:00:00Z' };
|
||||
const run = (args: string[], input?: string) => { const r = spawnSync('git', args, { cwd: root, encoding: 'utf8', env, input, timeout: 60_000 }); return { ok: r.status === 0, out: (r.stdout ?? '').trim() }; };
|
||||
const treeEntry = (rev: string, p: string) => run(['ls-tree', '-z', '--full-tree', rev, '--', p]).out.split('\0').find(l => l.endsWith(`\t${p}`));
|
||||
const treeEntry = (rev: string, p: string) => run(['--literal-pathspecs', 'ls-tree', '-z', '--full-tree', rev, '--', p]).out.split('\0').find(l => l.endsWith(`\t${p}`));
|
||||
let reset: string;
|
||||
const befores = new Map<string, string | null>();
|
||||
try {
|
||||
@@ -531,8 +471,7 @@ export function bindShippedReceipt(root: string, baseRef: string, body: string,
|
||||
if (self) return { ok: false, code: 'BASE_CONTAINS_HEAD', message: self, line: b.line };
|
||||
const based = merged ? b : bindReceipt(body, pr, accepted, { base: baseRef });
|
||||
if (!based.ok) return based;
|
||||
const ancestor = (commit: string) => b.receipt.carry?.ancestry === 'rewritten' || git(root, ['merge-base', '--is-ancestor', commit, b.head]).ok;
|
||||
const problems = exceptionProblems(body, b.receipt, ancestor);
|
||||
const problems = exceptionProblems(body, b.receipt);
|
||||
if (problems.length) return { ok: false, code: 'QUEUE_RECEIPT_EXCEPTION_INVALID', message: `the receipt's owner exception does not stand: ${problems.join('; ')}`, line: b.line };
|
||||
const at = headInputs(root, baseRef, b.head, b.receipt, merged);
|
||||
if (at.x.state === 'refused') return { ok: false, code: at.x.code, message: at.x.lines.join('; '), line: b.line };
|
||||
|
||||
@@ -93,7 +93,7 @@ const HARNESS_PIN = /^scripts\/harness-pins\/(.+)\.json$/;
|
||||
function rederivedHarnessPin(repoRoot: string, from: string, to: string, p: string, extra: ProductRules['extra']): boolean {
|
||||
const pinned = HARNESS_PIN.exec(p)?.[1];
|
||||
if (!pinned || classifyCarryPath(pinned, extra) !== 'product') return false;
|
||||
if (![from, to].every(ref => git(['ls-tree', ref, '--', p], repoRoot)?.startsWith('100644 blob '))) return false;
|
||||
if (![from, to].every(ref => git(['--literal-pathspecs', 'ls-tree', ref, '--', p], repoRoot)?.startsWith('100644 blob '))) return false;
|
||||
const json = (ref: string, rel: string): any => { const r = spawnSync('git', ['show', `${ref}:${rel}`], { cwd: repoRoot, encoding: 'utf8', timeout: 30_000, maxBuffer: 16 * 1024 * 1024 }); try { return r.status === 0 ? JSON.parse(r.stdout) : null; } catch { return null; } };
|
||||
const [ma, mb] = [json(from, HARNESS_MANIFEST), json(to, HARNESS_MANIFEST)];
|
||||
if (!ma || !mb || ma.version !== mb.version || JSON.stringify(ma.patterns) !== JSON.stringify(mb.patterns)) return false;
|
||||
@@ -143,7 +143,7 @@ export function productSpec(repoRoot: string, rules: ProductRules, from: string,
|
||||
// after a changelog-fragment conversion, or only its version moved) holds none of the branch's product: whatever else
|
||||
// differs between the two heads came from the base (GST-1210).
|
||||
// The same `ls-tree` entry (mode and object id, empty when absent) is an unchanged side; a failed read never is.
|
||||
const entryAt = (ref: string, p: string) => git(['ls-tree', ref, '--', p], repoRoot);
|
||||
const entryAt = (ref: string, p: string) => git(['--literal-pathspecs', 'ls-tree', ref, '--', p], repoRoot);
|
||||
const sameEntry = (a: string, b: string, p: string) => { const x = entryAt(a, p); return x !== undefined && x === entryAt(b, p); };
|
||||
const ownStampOnly = (p: string) => !!branch?.touched.has(p) && stamped(p) && branch.sides.every(([a, b]) => sameEntry(a, b, p) || classify(p, a, b) === 'metadata');
|
||||
const changed = changedRaw.split('\n').filter(Boolean).map(p => ({ path: p, class: ownStampOnly(p) ? 'metadata' as const : branch && rederivedHarnessPin(repoRoot, from, to, p, rules.extra) ? 'generated' as const : classify(p, from, to) }));
|
||||
@@ -156,7 +156,7 @@ export function productSpec(repoRoot: string, rules: ProductRules, from: string,
|
||||
// `from`), a regular file with the reviewed mode at both heads (GST-980): never the whole-text version swap.
|
||||
const ownRows = demoted.filter(p => {
|
||||
const side = branch?.own(p);
|
||||
const mode = (ref: string) => /^(100644|100755) blob /.exec(git(['ls-tree', ref, '--', p], repoRoot) ?? '')?.[1];
|
||||
const mode = (ref: string) => /^(100644|100755) blob /.exec(git(['--literal-pathspecs', 'ls-tree', ref, '--', p], repoRoot) ?? '')?.[1];
|
||||
const before = blobAt(from, p), after = blobAt(to, p), oldVersion = version(from), newVersion = version(to);
|
||||
if (!side || before === null || after === null || !oldVersion || !newVersion || !mode(from) || mode(from) !== mode(to)) return false;
|
||||
const was = before.split('\n');
|
||||
|
||||
@@ -7,7 +7,6 @@
|
||||
*/
|
||||
import { APPROVALS_FOOTER_END, APPROVALS_TABLE_HEADER } from './approval-record';
|
||||
import { RECEIPT_FENCE } from './ship-receipt';
|
||||
import { parseReviewLoopException, reviewLoopExceptionLine } from './ship-receipt-depth';
|
||||
import { docsExceptionLine, parseReceiptDocs } from './ship-receipt-docs';
|
||||
import { ruledNoteText, type RuledNote } from './ruled-notes';
|
||||
import { gateDispositionText, type GateDisposition } from './gate-dispositions';
|
||||
@@ -112,16 +111,13 @@ function withoutApprovalsBlocks(body: string): string {
|
||||
}
|
||||
|
||||
/**
|
||||
* The body without the exception lines the receipt's own exceptions require: the `Review-loop exception: …` line
|
||||
* (GST-977), the `Documentation exception: …` line (GST-983) and each `Ruled note: …`, `Gate disposition: …`, `Mechanical retake: …` and `Test-lane exception: …` line (GST-1537, GST-2491, GST-1560, GST-1595). write and the receipt check want each word for word,
|
||||
* The body without the exception lines the receipt's own exceptions require: the `Documentation exception: …` line (GST-983) and each `Ruled note: …`, `Gate disposition: …`, `Mechanical retake: …` and `Test-lane exception: …` line (GST-1537, GST-2491, GST-1560, GST-1595). write and the receipt check want each word for word,
|
||||
* and each quotes the owner's reason (`outside 1 and 2 skip detector`), not this PR's counters. Only a line whose
|
||||
* trimmed text is a rendered line, the test write applies, is left out; the same words inside a longer line stay
|
||||
* prose. A marker line takes its place so the text on either side never joins into a claim.
|
||||
*/
|
||||
function withoutExceptionLines(body: string, receipt: Record<string, unknown>): string {
|
||||
const lines = new Set<string>();
|
||||
const loop = receipt.review_loop_exception === undefined ? undefined : parseReviewLoopException(receipt.review_loop_exception);
|
||||
if (loop?.ok) lines.add(reviewLoopExceptionLine(loop.exception));
|
||||
const docs = receipt.docs === undefined ? undefined : parseReceiptDocs(receipt.docs);
|
||||
const docsLine = docs?.ok ? docsExceptionLine(docs.docs) : null;
|
||||
if (docsLine) lines.add(docsLine);
|
||||
|
||||
+13
-19
@@ -25,7 +25,7 @@ const KEY_ORDER: Array<keyof ShipReceipt | 'docs'> = [
|
||||
'schema_version', 'pr', 'head', 'version', 'base', 'gated_tree', 'predecessor', 'tree', 'gate_reuse', 'gate', 'ci', 'ci_carried', 'spend_usd', 'calls',
|
||||
'session_kind', 'artifacts_consumed', 'run', 'thread', 'policy', 'queue_mode', 'preregistration', 'history',
|
||||
'head_tree', 'product_patch_id', 'gstack_version', 'review_depth', 'pregate', 'requires_remote', 'issues', 'approval', 'docs', 'review_loop',
|
||||
'review_loop_exception', 'review_round_grants', 'cleared_by_grant', 'cleared_by_trailer', 'ruled_notes', 'gate_dispositions', 'mechanical', 'review_targeted', 'design', 'review_exclude', 'review_exclude_fallback', 'docs_audit_read', 'carry', 'base_red', 'flaky_exception', 'no_stop',
|
||||
'cleared_by_trailer', 'ruled_notes', 'gate_dispositions', 'mechanical', 'review_targeted', 'design', 'review_exclude', 'review_exclude_fallback', 'docs_audit_read', 'carry', 'base_red', 'flaky_exception', 'no_stop',
|
||||
];
|
||||
|
||||
/** Keys in the fixed order so identifiers lead; undefined values are dropped. */
|
||||
@@ -133,7 +133,7 @@ export const RUNS_RE = /```gstack-receipt-runs[ \t]*\r?\n([\s\S]*?)\r?\n```[ \t]
|
||||
* carries), `carry` for any other hop. status: a /ship run that
|
||||
* started and wrote no receipt yet (`started`, its counters so far) or ended on an infrastructure failure (`voided`).
|
||||
*/
|
||||
export type ReceiptRun = Pick<ShipReceipt, 'head' | 'version' | 'gstack_version' | 'run' | 'review_loop' | 'review_loop_exception'> & { depth?: string; carried_from?: string; carry_kind?: 'carry' | 'recheck'; status?: 'started' | 'voided'; mark?: 'stop' | 'grant' | 'abandoned'; tree?: string; grant?: string; by?: string; reason?: string; at?: string };
|
||||
export type ReceiptRun = Pick<ShipReceipt, 'head' | 'version' | 'gstack_version' | 'run' | 'review_loop'> & { depth?: string; carried_from?: string; carry_kind?: 'carry' | 'recheck'; status?: 'started' | 'voided'; mark?: 'stop' | 'grant' | 'abandoned'; tree?: string; grant?: string; by?: string; reason?: string; at?: string };
|
||||
/** The runs block keeps the newest RECEIPT_RUNS_KEPT run entries and every stop, grant or abandoned marker (lib/pr-review-history.ts), in order. */
|
||||
export function keptRuns(runs: readonly ReceiptRun[]): ReceiptRun[] {
|
||||
const keep = new Set(runs.filter(r => !r.mark).slice(-RECEIPT_RUNS_KEPT));
|
||||
@@ -146,10 +146,10 @@ export function receiptRuns(body: string): ReceiptRun[] {
|
||||
/** Whether any hop of the receipt's carry was a scoped re-check: gstack before GST-2673 let one carry a receipt across a product change, so the code it covered never got a full review, and no later carry or land takes that receipt (GST-2706). */
|
||||
export const recheckCarried = (r: ShipReceipt): boolean => !!r.carry?.reason.split(' + ').some(hop => hop.includes('scoped re-check by '));
|
||||
export function receiptRun(r: ShipReceipt): ReceiptRun {
|
||||
const { head, version, gstack_version, run, review_loop, review_loop_exception } = r;
|
||||
const { head, version, gstack_version, run, review_loop } = r;
|
||||
const hop = r.carry ? r.carry.reason.split(' + ').pop()! : undefined;
|
||||
const carry_kind = hop === undefined ? undefined : hop.includes('scoped re-check by ') ? 'recheck' : 'carry';
|
||||
return JSON.parse(JSON.stringify({ head, version, gstack_version, run, review_loop, review_loop_exception, depth: r.review_depth?.depth, carried_from: r.carry?.from, carry_kind }));
|
||||
return JSON.parse(JSON.stringify({ head, version, gstack_version, run, review_loop, depth: r.review_depth?.depth, carried_from: r.carry?.from, carry_kind }));
|
||||
}
|
||||
|
||||
/** Every receipt and runs block with the blank lines after it. */
|
||||
@@ -226,27 +226,22 @@ export function receiptSummaryLine(r: ShipReceipt): string {
|
||||
return `SHIP_RECEIPT: ${oneLine(parts.join(' '))}`;
|
||||
}
|
||||
|
||||
/** A risk-class PR (R51): the receipt's review depth has class gate or a risk class. Only these get the cross-family trail read. */
|
||||
/** A risk-class PR (R51): the receipt's review depth has class gate or a risk class. */
|
||||
export const riskClassReceipt = (r: ShipReceipt | undefined) => r?.review_depth?.class === 'gate' || !!r?.review_depth?.risk?.length;
|
||||
|
||||
/** What ready found for the READY tail: its TRIAL_MERGES lines and the decision trail's cross-family read, or why there is none. */
|
||||
export interface ReadyTail { trialMerges: string[]; trailRead: { row: number; reader: string; flags?: string } | { missing: string } }
|
||||
/** What ready found for the READY tail: its TRIAL_MERGES lines. */
|
||||
export interface ReadyTail { trialMerges: string[] }
|
||||
|
||||
/**
|
||||
* The rest of the READY block (GSTA-258 E1: the ready output is the whole READY): the receipt's review loop, ready's trial
|
||||
* merges, and the Attention section, whose opening line follows the receipt's risk class and the trail's cross-family read
|
||||
* (docs/unattended.md): a risk-class PR with no trail-read row prints MISSING instead of a line to fill in. Its flags line is the
|
||||
* trail-read row's result, and with no such row there is none: the lane lists its own audit's flags, never a template line.
|
||||
* merges, and the Attention section, which opens with the receipt's risk class; the lane lists what needs a decision under it.
|
||||
*/
|
||||
export function readyTailLines(r: ShipReceipt | undefined, t: ReadyTail = { trialMerges: [], trailRead: { missing: 'ready did not look for one' } }): string[] {
|
||||
export function readyTailLines(r: ShipReceipt | undefined, t: ReadyTail = { trialMerges: [] }): string[] {
|
||||
const loop = parseReviewLoop(r?.review_loop);
|
||||
const opt = (k: keyof ReviewLoopReceipt) => (loop?.[k] ? ` ${k}=${loop[k]}` : '');
|
||||
const risk = riskClassReceipt(r);
|
||||
const legacy = !!r && !r.review_depth;
|
||||
const cls = legacy ? 'risk class unknown: the receipt records no review_depth' : `risk class: ${oneLine([r?.review_depth?.class === 'gate' ? 'gate' : '', ...(r?.review_depth?.risk ?? [])].filter(Boolean).join(', '))}`;
|
||||
const reviewer = !legacy && !risk ? 'self-audited (not a risk class: no cross-family trail read)'
|
||||
: 'row' in t.trailRead ? `reviewed by ${oneLine(t.trailRead.reader)} (${cls}; rule 27 cross-family trail read, trail row ${t.trailRead.row})`
|
||||
: `MISSING: cross-family trail read (${cls}; rule 27): ${oneLine(t.trailRead.missing)}; have a reader on another model family read the trail and transcript, record it with gstack-decision-trail <trail> trail-read "<reader model>" <why> <evidence> <flags>, then rerun ready with --trail <trail>`;
|
||||
const cls = r && !r.review_depth ? 'risk class unknown: the receipt records no review_depth'
|
||||
: riskClassReceipt(r) ? `risk class: ${oneLine([r?.review_depth?.class === 'gate' ? 'gate' : '', ...(r?.review_depth?.risk ?? [])].filter(Boolean).join(', '))}`
|
||||
: 'not a risk class';
|
||||
return [
|
||||
loop ? `REVIEW_LOOP: passes=${loop.passes} blocking_found=${loop.blocking_found} deferred=${loop.deferred} noted=${loop.noted ?? 0} fixed=${loop.fixed ?? 0}${opt('unrecorded')}${opt('unbound')}${opt('fix_checks')}` : 'REVIEW_LOOP: none in the receipt',
|
||||
...(r?.ruled_notes ?? []).map(n => `RULED_NOTE: ${oneLine(ruledNoteText(n))}`),
|
||||
@@ -254,8 +249,7 @@ export function readyTailLines(r: ShipReceipt | undefined, t: ReadyTail = { tria
|
||||
...laneExceptionBodyLines(r?.ci_carried).map(l => `TEST_LANE_EXCEPTION: ${oneLine(l.slice('Test-lane exception: '.length))}`),
|
||||
...(t.trialMerges.length ? t.trialMerges : ['TRIAL_MERGES: MISSING: ready did not check the open PRs that share a file (rule 14)']),
|
||||
'Attention:',
|
||||
reviewer,
|
||||
...((legacy || risk) && 'row' in t.trailRead ? [/^(none|no flags?)?\.?$/i.test(t.trailRead.flags?.trim() ?? '') ? `No flags (trail row ${t.trailRead.row})` : `Flags (trail row ${t.trailRead.row}): ${oneLine(t.trailRead.flags!)}`] : []),
|
||||
cls,
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
+25
-190
@@ -18,19 +18,12 @@ import { matchesAny } from './ship-policy';
|
||||
import { baseHolds, boundedPaths, comparePath, contextPacket, gateEditedPaths, isTestCode, PACKET_SECTION_CAP, readScopedReview, touchedPaths, type BoundedKind, type PatchSides } from './ship-patch';
|
||||
import { extractReceipt, heldBy, receiptRuns } from './ship-receipt';
|
||||
import { finishRun, readRunRecord } from './ship-run-record';
|
||||
import { bindFixCheckRow, type RowBinding } from './fix-check-clearing';
|
||||
import { locate, readRecord } from './approval-record';
|
||||
import { mechanicalPaths, writeMechanicalRecord } from './ship-mechanical';
|
||||
import { uidSidecars } from './ship-sidecar';
|
||||
import type { MechanicalConstant } from './ship-policy-mechanical';
|
||||
import { holdsOpen, reviewFreshness, RULABLE } from './review-evidence';
|
||||
import { isCriticalFinding, isOpenByAction } from './headless-artifacts';
|
||||
import { fingerprintPath, normalizePath } from './review-scope';
|
||||
import { forbidSpecs } from './review-fetch';
|
||||
import { readRuledNotes, ruledNoteText } from './ruled-notes';
|
||||
import { reviewRoundGrants } from './review-round-grant';
|
||||
import { dispositionedOn, gateDispositionText, gateKey, readGateDispositions } from './gate-dispositions';
|
||||
import { parseReviewLoopException, type ReviewLoopException } from './ship-receipt-depth';
|
||||
import { dispositionedOn, gateDispositionText, readGateDispositions } from './gate-dispositions';
|
||||
import { parseReceiptDocs, type ReceiptDocs } from './ship-receipt-docs';
|
||||
import { redactFindingSpans } from './redact-engine';
|
||||
import { resolveStateRoot } from './state-root';
|
||||
@@ -51,11 +44,10 @@ export const RELEASE_HELP = `gstack-ship-release — /ship Steps 12 and 15-17 (s
|
||||
--keep-current (or --version <current>) keeps VERSION; under bump ask a session no person answers needs --answer before a bump is written
|
||||
finish --base <base> --reviewed-tree <tree> [--reviewed-base <sha>] --docs-post <post.json> [--lane <label>=<command>]... [--build <command>]...
|
||||
[--trailer <text>] [--docs-rechecked] [--no-lanes-approved] [--context-reviewed <record.json>]
|
||||
[--docs-requested <path>... --docs-result <the audit's result JSON>] [--review-loop-exception <json|@file>]
|
||||
[--docs-requested <path>... --docs-result <the audit's result JSON>]
|
||||
Step 15's release commit, Step 16 stages 1-4 (your builds, the reviewed-tree route, docs freshness,
|
||||
each lane's receipt run once if stale) and the pregate on the stamped tree; --reviewed-base (the merge base
|
||||
saved with the reviewed tree, or a stack parent's head once the parent landed: REVIEWED_BASE:) routes paths only the base moved, or whose own hunks are unchanged next to moved base context, as base=, and a hunk the base merge spliced as context=;
|
||||
--review-loop-exception (the record write takes) routes paths the branch touched at fix_check.head (narrowed to fix_check.files when listed) and changed since as accepted=
|
||||
A lane the base branch maps in .gstack/pregate.json ship_lanes_from is carried from a verified CI run at this exact
|
||||
tree, else deferred (EVIDENCE: DEFERRED): the pregate then runs its preflight stage here and its tests stage in accept
|
||||
push --branch <branch-name> [--gate-open <n>] [--gate-open-approved] [--early [--base <base>]]
|
||||
@@ -211,18 +203,13 @@ function harnessRepin(cwd: string, from: string, to: string, p: string): boolean
|
||||
|
||||
/**
|
||||
* Step 16 stage 2's route. With --reviewed-base, a path whose branch patch is the reviewed one counts as base (lib/ship-patch.ts).
|
||||
* A code or test path a granted fix-check read counts as fix_checked (fixChecked: the newest completed clean review-fix-check
|
||||
* row, chained through earlier rows back to the reviewed tree, each under its own approved review_loop_grant): the owner's
|
||||
* granted fix-check after Step 11 is a review (GST-1130, GST-1627). A finding on a link the owner ruled a disclosed note (an
|
||||
* approved gstack-approvals rule row whose stop head lies inside that link's range_base..commit, never the row's own claim) is closed, and every ruling
|
||||
* prints as RULED_NOTE (GST-1537). An open gate finding the owner dispositioned (an approved gstack-approvals gate row at its
|
||||
* fingerprint, head in range, lib/gate-dispositions.ts) is closed the same way, and each prints as GATE_DISPOSITION (GST-2491).
|
||||
* Authored docs keep the stage 2.2 recheck.
|
||||
* Every ruling prints as RULED_NOTE (GST-1537), and every owner gate disposition (an approved gstack-approvals gate row at its
|
||||
* 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 FixCheckException = ReviewLoopException & { fix_check: NonNullable<ReviewLoopException['fix_check']> };
|
||||
type Routed = Record<'behavior' | 'docs' | 'metadata' | 'tests' | 'base' | 'context' | 'bounded' | 'mechanical' | 'accepted' | 'fix_checked' | 'fix_checked_exact' | 'sidecar', string[]>;
|
||||
type Routed = Record<'behavior' | 'docs' | 'metadata' | 'tests' | 'base' | 'context' | 'bounded' | 'mechanical' | 'sidecar', string[]>;
|
||||
type ReviewedBase = { commit: string; parent: boolean };
|
||||
type RouteOpts = { docsRechecked: boolean; contextReviewed?: string; loop?: FixCheckException; audited: Record<string, string | null> | null; bookkeeping: readonly string[]; mechanical: readonly MechanicalConstant[]; testCode: readonly string[]; excluded: readonly string[]; baseRelease?: string[] };
|
||||
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[] };
|
||||
|
||||
/**
|
||||
* The --reviewed-base commit: one on the base, or a landed stack parent (GST-1399). A child reviewed against its parent
|
||||
@@ -255,130 +242,14 @@ function patchBase(cwd: string, baseRef: string, commit: string, parent: string
|
||||
return parent && fork && holds(parent, commit) && holds(fork, parent) ? parent : fork;
|
||||
}
|
||||
|
||||
type FixLink = { row: Record<string, any>; commit: string; from: string; bound?: RowBinding };
|
||||
type BridgeOpts = { reviewed: string; baseRef: string; metadata: (p: string) => boolean; bookkeeping: readonly string[]; testCode: readonly string[] };
|
||||
|
||||
/**
|
||||
* A range_base that follows the reviewed tree's commit by docs and release metadata alone (GST-2294, harness-evals#361: the
|
||||
* fix-check range started at the Step 14.5 docs commit). Walks range_base's first parents off the base back to the nearest commit
|
||||
* holding the reviewed tree; every commit after it, range_base included, must be a single-parent commit whose every path finish
|
||||
* routes as release metadata (route's own per-path rule, so baseRelease on a landed stack parent) or authored docs, so the paths
|
||||
* outside the fix-check's read keep the docs route and its recheck.
|
||||
* A merge, a code or test path, or no reviewed commit behind range_base returns null.
|
||||
*/
|
||||
function docsBridge(cwd: string, from: string, o: BridgeOpts): { reviewedAt: string; commits: string[] } | null {
|
||||
const log = git(cwd, ['log', '--first-parent', '--format=%H %T %P', from, '--not', o.baseRef]);
|
||||
if (log.status !== 0) return null;
|
||||
const docsOnly = (p: string) => o.metadata(p) || (!isTestCode(p, o.testCode) && classifyPath(p, cwd) === 'docs' && !matchesAny(o.bookkeeping, p));
|
||||
const commits: string[] = [];
|
||||
for (const [commit, tree, ...parents] of log.stdout.trim().split('\n').filter(Boolean).map(l => l.split(' '))) {
|
||||
if (tree === o.reviewed) return commits.length ? { reviewedAt: commit!, commits: commits.reverse() } : null;
|
||||
const paths = parents.length === 1 ? touchedPaths(cwd, parents[0]!, commit!) : null;
|
||||
if (!paths || ![...paths].every(docsOnly)) return null;
|
||||
commits.push(commit!);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The granted fix-checks finish counts (GST-1130, GST-1627): the newest review-fix-check row and, while its range_base does
|
||||
* not hold the reviewed tree, the newest earlier row whose commit is that range_base, back to a row whose range_base holds
|
||||
* it. Every link must be a completed clean read on committed branch content with its own approved review_loop_grant, a stop
|
||||
* head inside its range_base..commit, its own commit included (the post-review flow grants each fix-check at the commit it
|
||||
* reads, GST-1676); a grant counts for one link only, assigned newest link first, so one grant naming the boundary or two
|
||||
* links' commits covers one, and the older link needs a grant of its own.
|
||||
* A range_base no earlier row ends at is a gap, and the chain does not count, unless docs and release metadata alone sit between
|
||||
* the reviewed tree's commit and it (docsBridge, GST-2294). A link before the newest may, instead of a clean
|
||||
* read, be a finished read bound to its own committed content that found issues (logged converged:false, GST-1973) when its
|
||||
* findings account for its counts and each open or blocking one names a file it read: it counts no path itself, and a path its
|
||||
* findings name counts only through a clean link after it, and a finding no later clean link's range touched refuses the chain. A path counts as fix_checked when a clean link's range touched it and it is unchanged since that link,
|
||||
* or its patch against the base is still the one the link read.
|
||||
*/
|
||||
function fixChecked(cwd: string, o: BridgeOpts & { now: string; parent?: string; currentBase?: string; candidates: string[] }, r: Report): { counted: boolean; paths: string[]; exact: string[] } | null {
|
||||
/** The owner's rulings and gate dispositions finish prints with stage 2's route (GST-1537, GST-2491). */
|
||||
function printRulings(cwd: string, r: Report): void {
|
||||
const reviewRows: Record<string, any>[] = bin(cwd, 'gstack-review-read', [], 60_000).stdout.split('\n---CONFIG---')[0].split('\n')
|
||||
.flatMap(l => { try { const v = JSON.parse(l); return v?.skill === 'review' || v?.skill === 'review-fix-check' ? [v] : []; } catch { return []; } });
|
||||
const rows = reviewRows.filter(v => v.skill === 'review-fix-check');
|
||||
const commitOf = (c: unknown) => typeof c === 'string' && /^[0-9a-f]{7,64}$/.test(c) ? git(cwd, ['rev-parse', '--verify', '--quiet', `${c}^{commit}`]).stdout.trim() : '';
|
||||
const ancestor = (a: string, d: string) => git(cwd, ['merge-base', '--is-ancestor', a, d]).status === 0;
|
||||
const onBranch = (c: string) => !!c && ancestor(c, 'HEAD');
|
||||
const commits = rows.map(row => commitOf(row.commit_full));
|
||||
const approvals = (loc => 'file' in loc ? readRecord(loc).rows : [])(locate({ cwd, env: process.env }));
|
||||
const chain: FixLink[] = [];
|
||||
let gap = '', bridged = '';
|
||||
for (let i = rows.length - 1; i >= 0;) {
|
||||
const row = rows[i]!, bound = row.fix_check_base !== undefined ? bindFixCheckRow(cwd, row, reviewRoundGrants(approvals)) : undefined;
|
||||
const link = { row, commit: commits[i]!, from: commitOf(bound ? row.fix_check_base : row.range_base), bound };
|
||||
chain.unshift(link);
|
||||
if (bound?.ok || !onBranch(link.from) || git(cwd, ['rev-parse', `${link.from}^{tree}`]).stdout.trim() === o.reviewed) break;
|
||||
i = commits.slice(0, i).lastIndexOf(link.from);
|
||||
const bridge = i < 0 ? docsBridge(cwd, link.from, o) : null;
|
||||
if (bridge) bridged = `FIX_CHECK_DOCS_BRIDGE: range_base ${link.from.slice(0, 12)} follows the reviewed commit ${bridge.reviewedAt.slice(0, 12)} by docs or release metadata only (${bridge.commits.map(c => c.slice(0, 12)).join(',')})`;
|
||||
else if (i < 0) gap = `range_base ${link.from.slice(0, 12)} does not hold the reviewed tree`;
|
||||
}
|
||||
const inRange = (l: FixLink, c: string) => !!l.from && !!l.commit && ancestor(l.from, c) && ancestor(c, l.commit);
|
||||
const rulings = readRuledNotes(cwd).map(n => ({ ...n, links: chain.filter(l => inRange(l, n.head)) }));
|
||||
for (const n of rulings) if (!n.finding.startsWith('edit:')) r.add(`RULED_NOTE: ${ruledNoteText(n)}${chain.length && !n.links.length ? ' (outside this fix-check\'s range; not applied)' : ''}`);
|
||||
const gates = readGateDispositions(cwd);
|
||||
for (const d of gates) r.add(`GATE_DISPOSITION: ${gateDispositionText(d)}${reviewRows.some(v => dispositionedOn(cwd, v, [d]).length) ? '' : ' (no open gate finding at this fingerprint on a review row whose range holds this head; not applied)'}`);
|
||||
const gatedOn = (l: FixLink) => new Set(dispositionedOn(cwd, l.row, gates).map(d => gateKey(d.finding, d.gate_id)));
|
||||
const grants = approvals.filter(g => g.outcome === 'approved' && (`${g.ask} ${g.scope}`.includes('review_loop_grant') || reviewRoundGrants([g]).some(x => x.kind === 'fix-check')));
|
||||
const granted: (typeof grants[number] | undefined)[] = [];
|
||||
const used = new Set<string>();
|
||||
for (let k = chain.length - 1; k >= 0; k--) {
|
||||
const l = chain[k]!;
|
||||
const g = l.bound?.ok ? (id => grants.find(x => x.id === id && !used.has(x.id)))(l.bound.grant.approval) : grants.filter(g => !used.has(g.id))
|
||||
.flatMap(g => { const fc = reviewRoundGrants([g]).find(x => x.kind === 'fix-check' && !x.legacy); return (fc ? (commitOf(fc.head) === l.from ? [fc.head] : []) : `${g.ask} ${g.scope}`.match(/\b[0-9a-f]{7,40}\b/g) ?? []).map(commitOf).filter(c => !!c && inRange(l, c)).map(stop => ({ g, stop })); })
|
||||
.reduce<{ g: typeof grants[number]; stop: string } | undefined>((best, c) => (!best || ancestor(best.stop, c.stop) ? c : best), undefined)?.g;
|
||||
if (g) used.add(g.id);
|
||||
granted[k] = g;
|
||||
}
|
||||
const ruledOn = (l: FixLink) => new Set(rulings.filter(n => n.links.includes(l)).map(n => n.finding));
|
||||
const why = (l: FixLink) => {
|
||||
const read = l.row.wtree ?? l.row.review_binding?.end_wtree;
|
||||
const fresh = reviewFreshness(l.row, read, ruledOn(l), gatedOn(l));
|
||||
return l.bound && !l.bound.ok ? `the granted fix-check row: ${l.bound.why}` : fresh?.status !== 'CURRENT' ? fresh?.reason ?? 'not a review row'
|
||||
: l.row.tree !== read || !onBranch(l.commit) ? 'the row was logged on content no branch commit holds'
|
||||
: !onBranch(l.from) ? 'the row names no range_base commit on this branch' : '';
|
||||
};
|
||||
const at = (l: FixLink) => (chain.length > 1 ? `; fix-check at ${l.commit.slice(0, 12)}, link ${chain.indexOf(l) + 1} of ${chain.length}` : '');
|
||||
const whys = new Map(chain.map(l => [l, why(l)]));
|
||||
const clean = new Set(chain.filter(l => !whys.get(l)));
|
||||
const flagged = (l: FixLink): string[] | null => {
|
||||
const b = l.row.review_binding, findings: Record<string, any>[] = Array.isArray(l.row.findings) ? l.row.findings.filter((f: unknown) => !!f && typeof f === 'object') : [];
|
||||
const paths = findings.filter(f => (f.blocking === true || isCriticalFinding(f) || isOpenByAction(f)) && !ruledOn(l).has(f.fingerprint) && !gatedOn(l).has(gateKey(f.fingerprint, f.gate_id)))
|
||||
.map(f => typeof f.path === 'string' ? f.path : fingerprintPath(f.fingerprint)).map(p => p && normalizePath(p));
|
||||
const bound = l.row.completed === true && l.row.scope !== 'fix-range' && (b?.state === 'incomplete' || b?.state === 'verified') && !!l.row.tree && b.start_wtree === l.row.tree && b.end_wtree === l.row.tree;
|
||||
const accounted = Array.isArray(l.row.findings) && findings.length >= Number(l.row.issues_found ?? 0) && findings.filter(isCriticalFinding).length >= Number(l.row.critical ?? 0);
|
||||
return bound && accounted && onBranch(l.commit) && onBranch(l.from) && paths.every(p => !!p && git(cwd, ['cat-file', '-e', `${l.commit}:${p}`]).status === 0) ? paths as string[] : null;
|
||||
};
|
||||
const handedOn = new Map<FixLink, string[]>(chain.slice(0, -1).filter(l => !clean.has(l)).flatMap(l => (p => p ? [[l, p] as const] : [])(flagged(l))));
|
||||
const newestFirst = [...chain].reverse();
|
||||
const stale = newestFirst.map(l => ({ l, w: handedOn.has(l) ? '' : whys.get(l)! })).find(x => x.w);
|
||||
const ungranted = newestFirst.find(l => !granted[chain.indexOf(l)]);
|
||||
const ranges = new Map(chain.filter(l => clean.has(l)).map(l => [l, touchedPaths(cwd, l.from, l.commit)]));
|
||||
const uncovered = [...handedOn].map(([d, ps]) => ({ d, p: ps.find(p => !chain.slice(chain.indexOf(d) + 1).some(j => ranges.get(j)?.has(p))) })).find(x => x.p);
|
||||
const notCounted = !chain.length ? '' : stale ? `${stale.w}${at(stale.l)}` : gap ? `${gap}${at(chain[0]!)}`
|
||||
: uncovered ? `a finding on ${uncovered.p} that no later clean fix-check's range touched${at(uncovered.d)}`
|
||||
: ungranted ? `no approved review_loop_grant names a stop head inside its range_base..commit${at(ungranted)}` : '';
|
||||
if (notCounted) r.add(`FIX_CHECK: not counted (${notCounted})`);
|
||||
const rulable = (l: FixLink) => (Array.isArray(l.row.findings) ? l.row.findings : []).filter((f: any) => !!f && !f.gate && RULABLE.has(f.action) && holdsOpen(f) && typeof f.fingerprint === 'string' && !ruledOn(l).has(f.fingerprint)).map((f: any) => f.fingerprint as string);
|
||||
for (const l of notCounted ? chain : []) if (rulable(l).length) r.add(`FIX_CHECK_OPEN: ${rulable(l).join(',')} on the fix-check at ${l.commit.slice(0, 12)}: the owner rules each one a disclosed note with gstack-approvals rule --finding <fingerprint> --head ${l.commit.slice(0, 12)} --reason '<why>' --words '<owner\'s exact words>' --by '<owner>'; a review-loop exception accepts edits after a fix-check, never its findings (docs/troubleshooting.md#fix-check-open)`);
|
||||
if (!chain.length || notCounted) return { counted: false, paths: [], exact: [] };
|
||||
if (bridged) r.add(bridged);
|
||||
const read: { any: (p: string) => boolean; exact: (p: string) => boolean }[] = [];
|
||||
for (const [k, l] of chain.entries()) {
|
||||
if (!clean.has(l)) continue;
|
||||
const later = new Set(chain.slice(k + 1).flatMap(d => handedOn.get(d) ?? []));
|
||||
const range = ranges.get(l), after = touchedPaths(cwd, l.commit, o.now);
|
||||
if (!range || !after) { r.stop(`git could not diff the fix-check range ${l.from.slice(0, 12)}..${l.commit.slice(0, 12)} against the reviewed and current trees: stage 2 is blocked`); return null; }
|
||||
const sides = { reviewedBase: patchBase(cwd, o.baseRef, l.commit, o.parent), reviewed: l.commit, currentBase: o.currentBase ?? git(cwd, ['merge-base', o.baseRef, 'HEAD']).stdout.trim(), current: o.now };
|
||||
read.push({ any: p => !later.has(p) && range.has(p) && (!after.has(p) || (!!sides.reviewedBase && !!sides.currentBase && comparePath(cwd, sides, p) === 'same')), exact: p => !later.has(p) && range.has(p) && !after.has(p) });
|
||||
}
|
||||
const paths = o.candidates.filter(p => read.some(f => f.any(p))).sort();
|
||||
const list = paths.length ? short(paths) : 'none';
|
||||
r.add(chain.length === 1 ? `FIX_CHECK: reviewed ${list} (fix-check at ${chain[0]!.commit.slice(0, 12)}, range from ${chain[0]!.from.slice(0, 12)}, grant ${granted[0]!.id})`
|
||||
: `FIX_CHECK: reviewed ${list} (fix-check chain of ${chain.length} from ${chain[0]!.from.slice(0, 12)}: ${chain.map((l, k) => `at ${l.commit.slice(0, 12)} grant ${granted[k]!.id}${clean.has(l) ? '' : ' (found issues)'}`).join('; ')})`);
|
||||
return { counted: true, paths, exact: paths.filter(p => read.some(f => f.exact(p))) };
|
||||
for (const n of readRuledNotes(cwd)) if (!n.finding.startsWith('edit:')) r.add(`RULED_NOTE: ${ruledNoteText(n)}`);
|
||||
for (const d of readGateDispositions(cwd)) r.add(`GATE_DISPOSITION: ${gateDispositionText(d)}${reviewRows.some(v => dispositionedOn(cwd, v, [d]).length) ? '' : ' (no open gate finding at this fingerprint on a review row whose range holds this head; not applied)'}`);
|
||||
}
|
||||
|
||||
function route(cwd: string, base: string, reviewed: string, reviewedBase: ReviewedBase | undefined, release: string[], opts: RouteOpts, r: Report): Routed | null {
|
||||
@@ -400,7 +271,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: [], accepted: [], fix_checked: [], fix_checked_exact: [], sidecar: [] };
|
||||
const by: Routed = { behavior: [], docs: [], metadata: [], tests: [], base: [], context: [], bounded: [], mechanical: [], sidecar: [] };
|
||||
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>();
|
||||
@@ -427,29 +298,8 @@ function route(cwd: string, base: string, reviewed: string, reviewedBase: Review
|
||||
by.behavior.push(...packetBody.over);
|
||||
for (const k of ['context', 'tests', 'bounded'] as const) by[k] = by[k].filter(p => !packetBody.over.includes(p));
|
||||
}
|
||||
const fix = fixChecked(cwd, { reviewed, now, baseRef, parent, currentBase: sides?.currentBase, metadata: isMetadata, bookkeeping: opts.bookkeeping, testCode: opts.testCode, candidates: [...by.behavior, ...by.tests, ...by.context, ...by.bounded] }, r);
|
||||
if (!fix) return null;
|
||||
const counted = fix.counted;
|
||||
by.fix_checked = fix.paths;
|
||||
by.fix_checked_exact = fix.exact;
|
||||
for (const k of ['behavior', 'tests', 'context', 'bounded'] as const) by[k] = by[k].filter(p => !by.fix_checked.includes(p));
|
||||
printRulings(cwd, r);
|
||||
const ancestor = (a: string, d: string) => git(cwd, ['merge-base', '--is-ancestor', a, d]).status === 0;
|
||||
const loop = opts.loop;
|
||||
if (loop) {
|
||||
const head = loop.fix_check.head;
|
||||
const since = touchedPaths(cwd, head, now);
|
||||
const fork = git(cwd, ['merge-base', baseRef, head]).stdout.trim();
|
||||
const own = fork ? touchedPaths(cwd, fork, head) : null;
|
||||
const fromParent = parent && ancestor(parent, head) ? touchedPaths(cwd, parent, head) : own;
|
||||
const atHead = own && fromParent ? new Set([...own].filter(p => fromParent.has(p))) : null;
|
||||
if (!since || !atHead) { r.stop(`git could not list the paths changed since fix-check ${head.slice(0, 12)} or the paths the branch touched at it against ${baseRef}: stage 2 is blocked`); return null; }
|
||||
const listed = loop.fix_check.files;
|
||||
const unscanned = [...by.behavior, ...by.docs].filter(p => isTestCode(p, opts.testCode));
|
||||
const forced = new Set([...gated, ...(packetBody?.over ?? []), ...(gateEditedPaths(cwd, reviewed, now, unscanned) ?? unscanned)]);
|
||||
by.accepted = [...by.behavior, ...by.docs].filter(p => since.has(p) && atHead.has(p) && (!listed || listed.includes(p)) && !forced.has(p)).sort();
|
||||
by.behavior = by.behavior.filter(p => !by.accepted.includes(p));
|
||||
by.docs = by.docs.filter(p => !by.accepted.includes(p));
|
||||
}
|
||||
const edits = readRuledNotes(cwd).filter(n => n.finding.startsWith('edit:'));
|
||||
const top = edits.length ? git(cwd, ['rev-parse', '--show-toplevel']).stdout.trim() : '';
|
||||
const entry = (tree: string, p: string) => { const ls = git(cwd, ['--literal-pathspecs', 'ls-tree', '-z', '--full-tree', tree, '--', p]); const rows = ls.stdout.split('\0').filter(Boolean);
|
||||
@@ -471,11 +321,10 @@ function route(cwd: string, base: string, reviewed: string, reviewedBase: Review
|
||||
if (ok) ruled.set(p, ok[0]); else if (why.length) refusedEdits.push(`${p} (${why.at(-1)![1]}; keep the edit and run /ship again, docs/ship-policy.md#ruled-edits)`);
|
||||
}
|
||||
by.behavior = by.behavior.filter(p => !ruled.has(p));
|
||||
const uid = uidSidecars(cwd, { sides, candidates: parent ? [] : by.behavior, accepted: by.accepted, excluded: opts.excluded });
|
||||
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));
|
||||
r.add(`ROUTE: reviewed=${reviewed.slice(0, 12)} current=${now.slice(0, 12)} behavior=${by.behavior.length} docs=${by.docs.length} metadata=${by.metadata.length} tests=${by.tests.length} base=${sides ? by.base.length : 'unknown'} context=${by.context.length}${by.bounded.length ? ` bounded=${by.bounded.length}` : ''}${by.mechanical.length ? ` mechanical=${by.mechanical.length}` : ''}${counted ? ` fix_checked=${by.fix_checked.length}` : ''}${loop ? ` accepted=${by.accepted.length}` : ''}${by.sidecar.length ? ` sidecar=${by.sidecar.length}` : ''}`);
|
||||
if (loop) r.add(`REVIEW_LOOP_EXCEPTION: accepted ${by.accepted.length ? short(by.accepted) : 'none'} (changed since fix-check ${loop.fix_check.head.slice(0, 12)}; accepted by ${loop.accepted_by} ${loop.date} via ${loop.via})`);
|
||||
r.add(`ROUTE: reviewed=${reviewed.slice(0, 12)} current=${now.slice(0, 12)} behavior=${by.behavior.length} docs=${by.docs.length} metadata=${by.metadata.length} tests=${by.tests.length} base=${sides ? by.base.length : 'unknown'} context=${by.context.length}${by.bounded.length ? ` bounded=${by.bounded.length}` : ''}${by.mechanical.length ? ` mechanical=${by.mechanical.length}` : ''}${by.sidecar.length ? ` sidecar=${by.sidecar.length}` : ''}`);
|
||||
for (const [p, n] of ruled) r.add(`RULED_EDIT: ${p} (ruled at ${n.head.slice(0, 12)} by ${n.by}, approval ${n.approval})`);
|
||||
for (const x of refusedEdits) r.add(`RULED_EDIT_REFUSED: ${x}`);
|
||||
for (const n of edits) r.add(`RULED_NOTE: ${ruledNoteText(n)}${[...ruled.values()].includes(n) ? '' : ' (no RULED_EDIT at this head; not applied)'}`);
|
||||
@@ -514,12 +363,12 @@ function route(cwd: string, base: string, reviewed: string, reviewedBase: Review
|
||||
}
|
||||
|
||||
/**
|
||||
* Step 16 stage 3. Test code, paths a counted fix-check read at their current bytes (stage 2's fix_checked, unchanged since that read, never by patch equivalence across a base merge; GST-3560), paths only the base or a stamp moved, a slot restamp after the audit (the CHANGELOG's heading
|
||||
* Step 16 stage 3. Test code, paths only the base or a stamp moved, a slot restamp after the audit (the CHANGELOG's heading
|
||||
* move or re-heading after the restamp writer's own merge of the base's CHANGELOG into the audited one, the version file's
|
||||
* 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, loopAccepted: readonly string[] | undefined, fixChecked: readonly string[], parent: string | undefined, testCode: readonly string[], r: Report): boolean {
|
||||
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 {
|
||||
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; }
|
||||
@@ -574,11 +423,9 @@ function docsFresh(cwd: string, base: string, postFile: string, moved: readonly
|
||||
});
|
||||
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[] };
|
||||
carried.accepted = stale.filter(p => loopAccepted?.includes(p) && !carried.tests.includes(p) && !carried.base.includes(p));
|
||||
carried.fix_checked = stale.filter(p => fixChecked.includes(p) && !carried.tests.includes(p) && !carried.base.includes(p) && !carried.accepted.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) && !carried.accepted.includes(q) && !carried.fix_checked.includes(q))) {
|
||||
for (const p of requested.filter(q => stale!.includes(q) && !carried.tests.includes(q) && !carried.base.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+/);
|
||||
@@ -593,8 +440,8 @@ function docsFresh(cwd: string, base: string, postFile: string, moved: readonly
|
||||
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) && !carried.accepted.includes(p) && !carried.fix_checked.includes(p));
|
||||
const note = left.length || stale.length === 0 ? '' : ` (carried: tests=${carried.tests.length} base=${carried.base.length} requested=${carried.requested.length}${loopAccepted ? ` accepted=${carried.accepted.length}` : ''}${fixChecked.length ? ` fix_checked=${carried.fix_checked.length}` : ''})`;
|
||||
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})`;
|
||||
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; }
|
||||
@@ -629,19 +476,7 @@ async function finishStages(argv: readonly string[], cwd: string): Promise<Repor
|
||||
const base = flag('--base')!;
|
||||
const r = new Report();
|
||||
const list = lanes(argv) as { label: string; command: string }[];
|
||||
let loop: FixCheckException | undefined;
|
||||
const loopArg = flag('--review-loop-exception');
|
||||
if (loopArg !== undefined) {
|
||||
let raw: unknown;
|
||||
try { raw = JSON.parse(loopArg.startsWith('@') ? fs.readFileSync(path.resolve(cwd, loopArg.slice(1)), 'utf8') : loopArg); } catch (e) { return r.stop(`--review-loop-exception: ${firstLine((e as Error).message)}`); }
|
||||
const parsed = parseReviewLoopException(raw);
|
||||
if (!parsed.ok) return r.stop(`--review-loop-exception: ${parsed.message}`);
|
||||
const fixCheck = parsed.exception.fix_check;
|
||||
if (!fixCheck) return r.stop('--review-loop-exception: finish routes edits made after a fix-check; a second_pass exception accepts an open finding, not edits, so run finish without it and pass it to gstack-ship-receipt write');
|
||||
if (Array.isArray((raw as { fix_check?: { files?: unknown } }).fix_check?.files) && !fixCheck.files) return r.stop('--review-loop-exception: fix_check.files lists no paths; omit it to accept the paths the branch touched at fix_check.head');
|
||||
if (git(cwd, ['merge-base', '--is-ancestor', fixCheck.head, 'HEAD']).status !== 0) return r.stop(`--review-loop-exception: fix_check.head ${fixCheck.head.slice(0, 12)} is not HEAD or an ancestor of it`);
|
||||
loop = { ...parsed.exception, fix_check: fixCheck };
|
||||
}
|
||||
if (flag('--review-loop-exception') !== undefined) return r.stop('--review-loop-exception was removed with fix-check grants (GST-3562 part 4): an edit after the review bound is behavior, so keep it and run /gstack-ship again, or the lane\'s Captain rules it a note (docs/ship-policy.md#ruled-edits)');
|
||||
const policy = shipPolicy(cwd, base);
|
||||
if (!commitRelease(cwd, releasePaths(policy, cwd, 'HEAD', base), flag('--trailer'), r)) return r;
|
||||
for (const cmd of all('--build')) {
|
||||
@@ -662,9 +497,9 @@ async function finishStages(argv: readonly string[], cwd: string): Promise<Repor
|
||||
const reviewedBase = reviewedBaseArg === undefined ? undefined : reviewedBaseCommit(cwd, `origin/${base.replace(/^origin\//, '')}`, reviewedBaseArg, [...releasePaths(policy, cwd, flag('--reviewed-tree')!, base, true).map(p => `:(top,exclude,literal)${p}`), ...fragments], r);
|
||||
if (reviewedBase === null) return r;
|
||||
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'), loop, audited, bookkeeping, mechanical, testCode: globs('test_code'), excluded: [...globs('review_exclude_paths'), ...forbidden], baseRelease }, r);
|
||||
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'), loop ? routed.accepted : undefined, routed.fix_checked_exact, 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)], 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;
|
||||
@@ -697,7 +532,7 @@ async function finishStages(argv: readonly string[], cwd: string): Promise<Repor
|
||||
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)`);
|
||||
if (!/^(pass|warn)/.test(verdict)) return r.stop(`pregate preflight ${verdict} on the stamped tree: fix it, then rerun finish`);
|
||||
return r.next(`Step 16 stage 5, then Step 17's guard block and gstack-ship-release push; then gstack-ship-release accept --base ${base} ${laneArgs} carries ${deferred.join(', ')} from CI at the pushed head${loop ? '; Step 18 records the same exception with gstack-ship-receipt write --review-loop-exception' : ''}`);
|
||||
return r.next(`Step 16 stage 5, then Step 17's guard block and gstack-ship-release push; then gstack-ship-release accept --base ${base} ${laneArgs} carries ${deferred.join(', ')} from CI at the pushed head`);
|
||||
}
|
||||
const v = bin(cwd, 'gstack-pregate', ['verify', '--base', base], 60_000);
|
||||
if (v.status === 0) r.add('PREGATE: verify ok on the stamped tree');
|
||||
@@ -709,7 +544,7 @@ async function finishStages(argv: readonly string[], cwd: string): Promise<Repor
|
||||
r.add(`PREGATE: ${verdict} (rerun on the stamped tree)`);
|
||||
if (!/^(pass|warn|requires-remote cleared)/.test(verdict)) return r.stop(`pregate ${verdict} on the stamped tree: fix it${/uncleared/.test(verdict) ? ', or gstack-pregate clear with the remote run URL' : ''}, then rerun finish`);
|
||||
}
|
||||
return r.next(`Step 16 stage 5: paste these results and the two-line honesty inventory, then run Step 17's guard block and gstack-ship-release push${loop ? '; Step 18 records the same exception with gstack-ship-receipt write --review-loop-exception' : ''}`);
|
||||
return r.next(`Step 16 stage 5: paste these results and the two-line honesty inventory, then run Step 17's guard block and gstack-ship-release push`);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+2
-5
@@ -7,8 +7,7 @@
|
||||
* a path as a sidecar, with no reader, only when every proof holds:
|
||||
* - the branch adds it after review: no such path at the reviewed tree or the current base (a changed UID re-identifies
|
||||
* the script for every uid:// reference to it);
|
||||
* - its sibling (the path without `.uid`) is a regular file now, and one the reviewed range added or modified, or one
|
||||
* the review-loop exception accepted;
|
||||
* - its sibling (the path without `.uid`) is a regular file now, and one the reviewed range added or modified;
|
||||
* - it is a regular, non-executable file whose whole content is exactly what Godot writes for one id, and no other file
|
||||
* in the current tree declares that uid:// as its own (a copied sidecar gives two resources one UID; a scene that
|
||||
* references the script by it is fine);
|
||||
@@ -23,8 +22,6 @@ export interface SidecarInput {
|
||||
sides?: PatchSides;
|
||||
/** Paths finish still routes as behavior; only those ending in `.uid` are candidates. */
|
||||
candidates: readonly string[];
|
||||
/** Paths the review-loop exception accepted. */
|
||||
accepted: readonly string[];
|
||||
/** The git glob pathspecs no reader saw: the base policy's review_exclude_paths and readers.forbid_paths. */
|
||||
excluded: readonly string[];
|
||||
}
|
||||
@@ -85,7 +82,7 @@ export function uidSidecars(cwd: string, i: SidecarInput): { proven: Record<stri
|
||||
const refuse = (reason: string) => refused.push({ path: p, reason });
|
||||
const sibling = p.slice(0, -'.uid'.length);
|
||||
const reviewed = range.has(sibling) && regular(entry(cwd, s.reviewed, sibling));
|
||||
if (!sibling || sibling.endsWith('/') || (!reviewed && !i.accepted.includes(sibling))) { refuse(`has no sibling ${sibling || '(none)'} that the reviewed range added or modified or the review-loop exception accepted`); continue; }
|
||||
if (!sibling || sibling.endsWith('/') || !reviewed) { refuse(`has no sibling ${sibling || '(none)'} that the reviewed range added or modified`); continue; }
|
||||
if (!regular(entry(cwd, s.current, sibling))) { refuse(`has no sibling ${sibling} at the current tree`); continue; }
|
||||
if (entry(cwd, s.reviewed, p) || entry(cwd, s.currentBase, p)) { refuse('existed at the reviewed tree or the current base (a changed UID re-identifies the script)'); continue; }
|
||||
const e = entry(cwd, s.current, p);
|
||||
|
||||
Reference in new issue
Block a user