feat(ship): review loop converges (frozen finding scope, 3-pass cap, NO FINDINGS first-class) and receipts carry across conflict-only merges

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
This commit is contained in:
garrytanandcapy-ai[bot] committed 2026-10-26 15:04:09 +00:00
1 parent 5755601dac
commit 0d5c0f6fbf
35 files changed
+1734 -130

No files matched your search

+5
View File
@@ -91,6 +91,9 @@ export interface ShipReceipt {
// C-pregate (C6): issue links the body carries, by intent.
// Related open PRs by other authors (Lane D): `supersedes` / `credit` only on the owner's confirmation.
issues?: { fixes: number[]; refs: number[]; flakes: Array<{ issue: number; run: string }>; related?: Array<{ pr: number; repo?: string; author: string; closes: number[]; supersedes?: boolean; credit?: boolean }> };
/** Harness lane E: the review loop's counters (gstack-review-scope summary) and the carry record when the receipt followed a head whose product diff was unchanged (gstack-ship-receipt carry). */
review_loop?: { passes: number; blocking_found: number; deferred: number; noted?: number; fixed?: number; scope?: string };
carry?: { from: string; reason: string; product_patch_id: string; changed_paths: string[]; merge_commits: number; range_diff: string; covers: string[]; reruns: string[] };
}
export const RESULT_STATUSES: readonly ResultStatus[] = ['complete', 'gate_pending', 'amend_pending', 'incomplete', 'interrupted', 'refused'];
@@ -206,6 +209,8 @@ export const ARTIFACT_SCHEMAS = {
thread: str, tree: { enum: ['same-modulo-stamps', 'changed', 'not-compared'] }, gate_reuse: str, policy: str, queue_mode: str, preregistration: str, history: str,
pregate: { ...str, description: 'pass|warn|requires-remote cleared … @<tree> from pregate.json, current for this head' }, requires_remote: strList,
approval: { type: 'object', description: 'approval classes: { source, status: checked|unavailable, classes: [{ class, scope, effects, citation: verified|unverified, approved_by, date, via, binding, evidence }], report_only }' },
review_loop: { type: 'object', required: ['passes', 'blocking_found', 'deferred'], properties: { passes: { type: 'integer', minimum: 0 }, blocking_found: { type: 'integer', minimum: 0 }, deferred: { type: 'integer', minimum: 0 }, noted: { type: 'integer', minimum: 0 }, fixed: { type: 'integer', minimum: 0 }, scope: str } },
carry: { type: 'object', required: ['from', 'reason', 'product_patch_id'], properties: { from: str, reason: str, product_patch_id: str, changed_paths: strList, merge_commits: { type: 'integer', minimum: 0 }, range_diff: str, covers: strList, reruns: strList } },
issues: { type: 'object', properties: { fixes: { type: 'array', items: { type: 'integer' } }, refs: { type: 'array', items: { type: 'integer' } }, flakes: { type: 'array', items: { type: 'object', required: ['issue', 'run'], properties: { issue: { type: 'integer' }, run: str } } }, related: { type: 'array', items: { type: 'object', required: ['pr', 'author', 'closes'], properties: { pr: { type: 'integer' }, repo: str, author: str, closes: { type: 'array', items: { type: 'integer' } }, supersedes: { type: 'boolean' }, credit: { type: 'boolean' } } } } } },
},
},
+21
View File
@@ -197,4 +197,25 @@ export const RELEASE_RESULT_CODES = {
summary: 'a regen command exited 0 with different outputs while package.json declares dependencies and node_modules is missing, so the outputs were not verified',
fix: 'install the dependencies (the printed command, such as bun install), then rerun the check',
},
// The /ship review loop's finding scope (gstack-review-scope) and the receipt carry (gstack-ship-receipt carry).
REVIEW_SCOPE_INPUT: {
anchor: 'review-scope-input',
summary: 'gstack-review-scope was given input it cannot classify: findings that are not a JSON array of objects, a --pass or --policy outside its values, or a pass 2+ call without --range-base',
fix: 'pass the Step 9.3 findings as a JSON array (--findings <file> or stdin), --pass <n> from the invocation record, and from pass 2 on --range-base <sha> (HEAD at the start of the previous pass)',
},
REVIEW_SCOPE_RANGE: {
anchor: 'review-scope-range',
summary: 'gstack-review-scope could not read the diff it scopes findings against: the base or the range base does not resolve, or the range base is not an ancestor of HEAD',
fix: 'fetch origin/<base>, check --range-base against the saved pass heads, and start a full pass (--pass 1) when history was rewritten',
},
RECEIPT_CARRY_REFUSED: {
anchor: 'receipt-carry-refused',
summary: 'gstack-ship-receipt carry could not carry the /ship receipt to HEAD: the PR body has no receipt, the receipt head is not an ancestor of HEAD (rebase or force-push), or the product diff could not be compared',
fix: 'merge the base in instead of rebasing, keep the reviewed head in HEAD\'s history, then rerun carry; otherwise run /ship on the new head',
},
RECEIPT_CARRY_PRODUCT_CHANGED: {
anchor: 'receipt-carry-product-changed',
summary: 'the product diff against the base changed between the receipt\'s head and HEAD (a product file differs beyond a base merge, a test-only fix or release metadata), so the reviewed verdict does not cover HEAD',
fix: 'run /ship on the new head; the receipt carries only when every changed path is a test, release metadata or the base merge and the product patch-id is unchanged',
},
} as const satisfies Record<string, ResultCode>;
+240
View File
@@ -0,0 +1,240 @@
/**
* review-scope — the finding scope of /ship's pre-landing review loop
* (ship/sections/review-army.md, Step 9.4; docs/ship-policy.md#review-scope).
*
* Five Captains hit the same loop: every pass re-read the whole diff, found
* new neighbours in pre-existing code, fixed them, and the fixes drew another
* pass until the cycle cap. Under `review_scope: frozen` (the default) the
* scope is fixed after pass 1: findings in the diff are fixed, findings in
* code the PR did not change are filed as issues (deferred), and later passes
* read only the range since the previous pass and fix only blocking findings.
* Everything below the blocking floor is a named note in the PR body and never
* triggers a pass. `review_scope: all` keeps the old behaviour.
*
* Pure functions here; bin/gstack-review-scope runs git and gh.
*/
export type Locus = 'diff' | 'fix-range' | 'outside';
export type Kind = 'defect' | 'test-gap' | 'advisory';
export type ReviewScopePolicy = 'frozen' | 'diff-plus-blocking' | 'all';
export const REVIEW_SCOPE_POLICIES: readonly ReviewScopePolicy[] = ['frozen', 'diff-plus-blocking', 'all'];
export type ScopeAction = 'fix' | 'defer' | 'note';
/** Lines around a changed hunk that still count as the diff (a missing check right after an added line is the diff's fault). */
export const HUNK_CONTEXT_LINES = 3;
export interface ScopeFinding {
fingerprint?: string; path?: string; line?: number; severity?: string; category?: string; summary?: string;
problem?: string; fix?: string; specialist?: string; advisory?: boolean; test_stub?: string;
[key: string]: unknown;
}
export interface ScopedFinding extends ScopeFinding { locus: Locus; kind: Kind; blocking: boolean; scope: ScopeAction }
/** Per path, the new-side line ranges a diff touched; `'whole'` for an added or untracked file. */
export type HunkMap = Record<string, Array<[number, number]> | 'whole'>;
/** Parse `git diff -U0` output (plus untracked paths as whole files) into a hunk map. */
export function parseHunks(diff: string, untracked: readonly string[] = []): HunkMap {
const map: HunkMap = {};
let current: string | null = null;
let added = false;
for (const raw of diff.split('\n')) {
const line = raw.replace(/\r$/, '');
if (line.startsWith('diff --git ')) { current = null; added = false; continue; }
if (line.startsWith('--- ')) { added = line === '--- /dev/null'; continue; }
if (line.startsWith('+++ ')) {
if (line === '+++ /dev/null') { current = null; continue; }
current = line.replace(/^\+\+\+ (?:b\/)?/, '').replace(/\t.*$/, '');
if (added) map[current] = 'whole';
else if (!(current in map)) map[current] = [];
continue;
}
if (!current || map[current] === 'whole') continue;
const m = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/.exec(line);
if (!m) continue;
const start = Number(m[1]);
const count = m[2] === undefined ? 1 : Number(m[2]);
// A pure deletion (+N,0) still marks the line where the code used to be.
(map[current] as Array<[number, number]>).push([start, count === 0 ? start : start + count - 1]);
}
for (const p of untracked) if (p) map[normalizePath(p)] = 'whole';
return map;
}
function normalizePath(p: string): string {
return p.replace(/\\/g, '/').replace(/^\.\//, '');
}
function inHunks(hunks: HunkMap, path: string, line: number | undefined, context: number): boolean {
const ranges = hunks[normalizePath(path)];
if (ranges === undefined) return false;
if (ranges === 'whole' || line === undefined || !Number.isFinite(line)) return true;
return ranges.some(([a, b]) => line >= a - context && line <= b + context);
}
/** Where a finding sits: in the range since the previous pass, in the branch diff, or in code the PR did not change. */
export function locusOf(finding: ScopeFinding, diffHunks: HunkMap, rangeHunks: HunkMap | null, context = HUNK_CONTEXT_LINES): Locus {
const path = typeof finding.path === 'string' ? finding.path : fingerprintPath(finding.fingerprint);
if (!path) return 'outside';
const line = typeof finding.line === 'number' ? finding.line : fingerprintLine(finding.fingerprint);
if (rangeHunks && inHunks(rangeHunks, path, line, context)) return 'fix-range';
if (inHunks(diffHunks, path, line, context)) return 'diff';
return 'outside';
}
function fingerprintPath(fp: unknown): string | undefined {
if (typeof fp !== 'string' || fp.startsWith('shared-libs:')) return undefined;
const [path] = fp.split(':');
return path || undefined;
}
function fingerprintLine(fp: unknown): number | undefined {
if (typeof fp !== 'string') return undefined;
const n = Number(fp.split(':')[1]);
return Number.isInteger(n) && n > 0 ? n : undefined;
}
/** A finding's kind: optional advice, a missing test, or a defect. */
export function kindOf(finding: ScopeFinding): Kind {
if (finding.advisory === true) return 'advisory';
const category = String(finding.category ?? '').toLowerCase();
if (/^(test-gap|test-coverage|coverage|missing-test|untested)$/.test(category)) return 'test-gap';
return 'defect';
}
/**
* The blocking floor: a CRITICAL defect (a test that would fail, a production
* break, a security or data-loss defect). Advisories, test gaps, wording and
* INFORMATIONAL items are below it and never trigger another pass.
*/
export function isBlocking(finding: ScopeFinding, kind = kindOf(finding)): boolean {
return kind === 'defect' && String(finding.severity ?? '').toUpperCase() === 'CRITICAL';
}
export interface ScopeInput { policy: ReviewScopePolicy; pass: number; diffHunks: HunkMap; rangeHunks: HunkMap | null; context?: number }
/**
* The scope decision per finding. `all`: fix everything (today's loop).
* `frozen` pass 1: fix the diff, defer blocking findings in unchanged code,
* note the rest. `frozen` pass 2+: fix blocking findings in the range since
* the previous pass or in the diff; defer blocking findings outside; note
* everything else.
*/
export function scopeFindings(findings: readonly ScopeFinding[], input: ScopeInput): ScopedFinding[] {
return findings.map(finding => {
const kind = kindOf(finding);
const blocking = isBlocking(finding, kind);
const locus = locusOf(finding, input.diffHunks, input.pass > 1 ? input.rangeHunks : null, input.context);
let scope: ScopeAction;
if (input.policy === 'all') scope = 'fix';
else if (locus === 'outside') scope = !blocking ? 'note' : input.policy === 'diff-plus-blocking' ? 'fix' : 'defer';
else if (input.pass <= 1) scope = 'fix';
else scope = blocking ? 'fix' : 'note';
return { ...finding, locus, kind, blocking, scope };
});
}
export function scopeCounts(scoped: readonly ScopedFinding[]): { fix: number; defer: number; note: number; blocking: number } {
return {
fix: scoped.filter(f => f.scope === 'fix').length, defer: scoped.filter(f => f.scope === 'defer').length,
note: scoped.filter(f => f.scope === 'note').length, blocking: scoped.filter(f => f.blocking).length,
};
}
export function scopeLine(policy: ReviewScopePolicy, pass: number, scoped: readonly ScopedFinding[]): string {
const c = scopeCounts(scoped);
return `REVIEW_SCOPE: policy=${policy} pass=${pass} findings=${scoped.length} fix=${c.fix} defer=${c.defer} note=${c.note} blocking=${c.blocking}`;
}
// ---------------------------------------------------------------------------
// deferral: one issue per blocking finding in code the PR did not change
// ---------------------------------------------------------------------------
export const DEFERRED_MARKER = 'gstack-deferred-finding';
const oneLine = (s: unknown) => String(s ?? '').replace(/[\x00-\x1f\x7f\u2028\u2029]+/g, ' ').trim();
export function findingIdentity(f: ScopeFinding): string {
if (typeof f.fingerprint === 'string' && f.fingerprint) return f.fingerprint;
return [f.path ?? '?', f.line ?? '', f.category ?? ''].join(':');
}
export function findingWhere(f: ScopeFinding): string {
return f.path ? `${f.path}${typeof f.line === 'number' ? `:${f.line}` : ''}` : fingerprintPath(f.fingerprint) ?? '(no path)';
}
function findingText(f: ScopeFinding): string {
return oneLine(f.summary ?? f.problem ?? f.category ?? 'review finding');
}
export interface DeferContext { repo?: string; pr?: number; branch?: string; head?: string }
/** Issue title and body for a deferred finding; the marker keeps a rerun from filing it twice. */
export function renderDeferredIssue(f: ScopedFinding, ctx: DeferContext): { title: string; body: string; marker: string } {
const text = findingText(f);
const title = `Deferred review finding: ${findingWhere(f)} — ${text}`.slice(0, 120);
const origin = ctx.pr ? `${ctx.repo ? `${ctx.repo}#${ctx.pr}` : `PR #${ctx.pr}`}` : ctx.branch ? `branch \`${ctx.branch}\`` : 'a /ship run';
const marker = `<!-- ${DEFERRED_MARKER}: ${oneLine(findingIdentity(f))} -->`;
const body = [
`Filed by /ship's pre-landing review of ${origin}${ctx.head ? ` (head ${ctx.head.slice(0, 12)})` : ''}. The finding is in code that PR did not change, so it was deferred here instead of being fixed there (review scope frozen after pass 1).`,
'',
`- **Severity:** ${oneLine(f.severity ?? 'unrated')}`,
`- **Where:** \`${findingWhere(f)}\``,
`- **Finding:** ${text}`,
...(f.fix ? [`- **Suggested fix:** ${oneLine(f.fix)}`] : []),
...(f.specialist ? [`- **Found by:** ${oneLine(f.specialist)}`] : []),
'',
marker,
'',
].join('\n');
return { title, body, marker };
}
export interface DeferredRecord { fingerprint: string; path: string; severity: string; summary: string; issue: number | null; url?: string; reason?: string }
/** The PR-body section for deferred findings: references, never closing keywords, so a merge closes nothing. */
export function renderDeferredSection(deferred: readonly DeferredRecord[], noted: readonly ScopeFinding[] = [], policy: ReviewScopePolicy = 'frozen'): string {
const out: string[] = [];
if (deferred.length) {
out.push('## Deferred findings', '', `Blocking findings in code this PR did not change (review scope: ${policy}); filed as issues and not closed by this PR.`, '');
for (const d of deferred) {
const ref = d.issue ? `#${d.issue}` : `unfiled${d.reason ? ` (${oneLine(d.reason)})` : ''}`;
out.push(`- Deferred: ${ref} — ${oneLine(d.severity)} \`${oneLine(d.path)}\` ${oneLine(d.summary)}`);
}
out.push('');
}
if (noted.length) {
out.push('## Review notes', '', 'Below the blocking floor (advisory, informational, test-gap or wording items); recorded here and not fixed in this PR.', '');
for (const n of noted) out.push(`- ${oneLine(n.severity ?? 'INFORMATIONAL')}${n.advisory ? ' [ADVISORY]' : ''} \`${findingWhere(n)}\` ${findingText(n)}`);
out.push('');
}
return out.join('\n');
}
// ---------------------------------------------------------------------------
// loop summary: what the ship receipt carries for the factory scorecard
// ---------------------------------------------------------------------------
export interface ReviewLoopSummary { passes: number; blocking_found: number; deferred: number; noted: number; fixed: number; scope: ReviewScopePolicy | 'unknown' }
/** Review-log rows of one /ship invocation (skill review, via ship, at or after `since`) → the loop summary. */
export function summarizeReviewLoop(rows: readonly Record<string, any>[], since: string): ReviewLoopSummary {
const sinceMs = Date.parse(since);
const passes = rows.filter(r => r && r.skill === 'review' && r.via === 'ship' && typeof r.timestamp === 'string'
&& Number.isFinite(Date.parse(r.timestamp)) && (!Number.isFinite(sinceMs) || Date.parse(r.timestamp) >= sinceMs));
const blocking = new Set<string>();
const deferred = new Set<string>();
const noted = new Set<string>();
const fixed = new Set<string>();
let scope: ReviewLoopSummary['scope'] = 'unknown';
for (const row of passes) {
if (REVIEW_SCOPE_POLICIES.includes(row.review_scope)) scope = row.review_scope;
for (const f of Array.isArray(row.findings) ? row.findings : []) {
if (!f || typeof f !== 'object') continue;
const id = findingIdentity(f);
if (f.blocking === true) blocking.add(id);
if (f.action === 'deferred') deferred.add(id);
if (f.action === 'noted') noted.add(id);
if (f.action === 'fixed' || f.action === 'auto-fixed') fixed.add(id);
}
}
return { passes: passes.length, blocking_found: blocking.size, deferred: deferred.size, noted: noted.size, fixed: fixed.size, scope };
}
export function reviewLoopLine(s: ReviewLoopSummary): string {
return `REVIEW_LOOP: passes=${s.passes} blocking_found=${s.blocking_found} deferred=${s.deferred} noted=${s.noted} fixed=${s.fixed} scope=${s.scope}`;
}
+14 -1
View File
@@ -24,6 +24,8 @@ export const SHIP_POLICY_SCHEMA = 'https://github.com/garrytan/gstack/docs/ship-
export type BumpPolicy = 'patch' | 'ask';
export type QueueMode = 'claim-at-open' | 'stamp-at-merge';
export type HistoryPolicy = 'merge-only' | 'squash-ok';
/** `frozen`: /ship fixes the diff in pass 1, defers unchanged code to issues and reviews only the range after; `all`: every finding is fixed now. */
export type ReviewScope = 'frozen' | 'diff-plus-blocking' | 'all';
export interface ShipPolicy {
$schema?: string;
@@ -47,6 +49,8 @@ export interface ShipPolicy {
preregistration_shas: string[];
/** Evidence labels that consume VERSION or generated bytes and always rerun on the stamped tree. */
stamp_sensitive_gates: string[];
/** The /ship review loop's finding scope (docs/ship-policy.md#review-scope). */
review_scope: ReviewScope;
/** Consumed by the plan reviews (D1). */
pr_count: { default_pr_count: number; split_requires_owner: boolean };
/** Maintainer logins for contributor-PR mode (E3); empty means "use push permission". */
@@ -100,6 +104,7 @@ export const DEFAULT_POLICY: ShipPolicy = {
history: 'squash-ok',
preregistration_shas: [],
stamp_sensitive_gates: [],
review_scope: 'frozen',
pr_count: { default_pr_count: 1, split_requires_owner: true },
maintainers: [],
stamp_files: [],
@@ -127,6 +132,7 @@ export const POLICY_EXPLANATIONS: Record<PolicyKey, string> = {
history: 'merge-only | squash-ok. merge-only makes /ship refuse a squash or rebase plan.',
preregistration_shas: 'Commits that must be ancestors of HEAD before push (preregistered evals); checked by `gstack-evidence ancestor`.',
stamp_sensitive_gates: 'Evidence labels (gstack-evidence --label) that read VERSION or generated bytes; the tree receipt never marks them reusable.',
review_scope: 'frozen | diff-plus-blocking | all. frozen (default): /ship Step 9 fixes findings in the diff on pass 1, files blocking findings in code the PR did not change as issues, and later passes read only the range since the previous pass and fix only blocking findings; diff-plus-blocking: the same, but a blocking finding in code the PR did not change is fixed in this PR instead of filed; all: every finding is fixed now (the pre-1.91.249 loop).',
pr_count: '{ default_pr_count, split_requires_owner }: the PR-count row in plan reviews.',
maintainers: 'GitHub logins treated as maintainers by /review contributor mode; empty uses repository push permission.',
stamp_files: 'The repo’s stamp rule: globs of the only files that may differ by a stamp (version file, manifests, plugin trees, the PR’s own since: rows). Empty keeps gstack’s per-file rules; set, it applies before every rule.',
@@ -149,12 +155,13 @@ export const POLICY_EXPLANATIONS: Record<PolicyKey, string> = {
export const POLICY_COMPAT_FLOOR = '1.91.98.0';
export const SHIP_QUEUE_KEYS_VERSION = '1.91.108.0';
export const TRAIN_KEYS_VERSION = '1.91.146.0';
export const REVIEW_SCOPE_KEY_VERSION = '1.91.249.0';
export const POLICY_KEY_INTRODUCED: Record<PolicyKey, string> = {
bump: '1.91.73.0', queue_mode: '1.91.73.0', release_tool: '1.91.73.0', release_outputs: '1.91.73.0', stamp_paths: '1.91.73.0',
changelog: '1.91.73.0', mirror: '1.91.73.0', history: '1.91.73.0', preregistration_shas: '1.91.73.0', stamp_sensitive_gates: '1.91.73.0',
pr_count: '1.91.73.0', maintainers: '1.91.73.0', stamp_files: '1.91.98.0', stamp_patterns: '1.91.98.0', restamp_command: '1.91.98.0',
migrations: '1.91.98.0', gate_command: SHIP_QUEUE_KEYS_VERSION, full_e2e: SHIP_QUEUE_KEYS_VERSION, min_gstack_version: SHIP_QUEUE_KEYS_VERSION,
train: TRAIN_KEYS_VERSION,
train: TRAIN_KEYS_VERSION, review_scope: REVIEW_SCOPE_KEY_VERSION,
};
const newer = (a: string, b: string): boolean => cmpVersion(parseVersion(a)!, parseVersion(b)!) > 0;
@@ -309,6 +316,7 @@ export function validatePolicy(raw: unknown, opts: { gstackVersion?: string } =
oneOf('bump', ['patch', 'ask']);
oneOf('queue_mode', ['claim-at-open', 'stamp-at-merge']);
oneOf('history', ['merge-only', 'squash-ok']);
oneOf('review_scope', ['frozen', 'diff-plus-blocking', 'all']);
if ('release_tool' in obj && obj.release_tool !== null) {
const t = obj.release_tool;
if (typeof t !== 'string' || !t.trim()) errors.push({ code: 'POLICY_INVALID', path: 'release_tool', message: 'must be a non-empty string or null' });
@@ -511,6 +519,11 @@ export function shipConsequences(policy: ShipPolicy, base: string): string[] {
out.push('gate-ahead: with .gstack/tmp/gate-ahead.json present, Step 16 reuses only the lanes `gstack-tree-receipt --from .gstack/tmp/gate-ahead.json --predecessor-pr <pr> --bundle <bundle> --json > .gstack/tmp/tree-receipt.json` marks reusable; stamp-sensitive and not-eligible lanes run live; `--force-gate <reason>` is the coordinator\'s call');
} else out.push('queue_mode claim-at-open: Step 12 runs as written (claims through gstack-next-version)');
out.push(policy.bump === 'patch' ? 'bump patch: Step 12 never asks for MINOR or MAJOR; PATCH or MICRO by size' : 'bump ask: Step 12 asks for MINOR and MAJOR as written');
out.push(policy.review_scope === 'all'
? 'review_scope all: Step 9.4 fixes every finding on every pass (gstack-review-scope classify --policy all)'
: policy.review_scope === 'diff-plus-blocking'
? 'review_scope diff-plus-blocking: Step 9.4 runs `gstack-review-scope classify --policy diff-plus-blocking` each pass; pass 1 fixes the diff and every blocking finding, in unchanged code too, later passes read only the range since the previous pass and fix only blocking findings; notes go to the PR body'
: 'review_scope frozen: Step 9.4 runs `gstack-review-scope classify` each pass; pass 1 fixes the diff and defers blocking findings in unchanged code to issues, later passes read only the range since the previous pass and fix only blocking findings; notes go to the PR body');
if (policy.preregistration_shas.length) out.push(`preregistration: \`gstack-evidence ancestor --from-policy --base ${base}\` must print only ANCESTOR: ok before push; the ship receipt records the result`);
if (policy.release_tool) out.push(`release_tool: \`${policy.release_tool}\` runs only inside gstack-restamp (staging worktree, outputs confined to release_outputs)`);
return out;
+97 -1
View File
@@ -9,12 +9,13 @@
import { ARTIFACT_SCHEMAS, checkSchema, type ShipReceipt, type ValidationError } from './headless-artifacts';
import { approvalSummary } from './approval-citations';
import { renderIssueLines } from './issue-links';
import { matchesAny } from './ship-policy';
export const RECEIPT_FENCE = 'gstack-ship-receipt';
const KEY_ORDER: Array<keyof ShipReceipt> = [
'schema_version', 'pr', 'head', 'version', 'base', 'gated_tree', 'predecessor', 'tree', 'gate_reuse', 'gate', 'ci', 'spend_usd',
'session_kind', 'artifacts_consumed', 'run', 'thread', 'policy', 'queue_mode', 'preregistration', 'history',
'pregate', 'requires_remote', 'issues', 'approval',
'pregate', 'requires_remote', 'issues', 'approval', 'review_loop', 'carry',
];
/** Keys in the fixed order so identifiers lead; undefined values are dropped. */
@@ -116,9 +117,104 @@ export function receiptSummaryLine(r: ShipReceipt): string {
if (r.session_kind) parts.push(`session_kind=${r.session_kind}`);
if (r.artifacts_consumed) parts.push(`artifacts_consumed=${r.artifacts_consumed}`);
if (r.approval) parts.push(`approval=${approvalSummary(r.approval)}`);
const loop = parseReviewLoop(r.review_loop);
if (loop) parts.push(`passes=${loop.passes} blocking_found=${loop.blocking_found} deferred=${loop.deferred}`);
if (r.carry && typeof r.carry.from === 'string') parts.push(`carried_from=${r.carry.from.slice(0, 12)}`);
return `SHIP_RECEIPT: ${oneLine(parts.join(' '))}`;
}
// ---------------------------------------------------------------------------
// carry: the receipt follows a head whose product diff is unchanged
// ---------------------------------------------------------------------------
/**
* Paths whose change never invalidates a /ship verdict on its own: tests (the
* reviewed product code is what the verdict covers; CI at the new head reruns
* them) and release metadata (stamps, lockfiles, the agents digest). A repo
* extends the lists through its ship policy (`stamp_files`, `stamp_paths`,
* `release_outputs`, `changelog`).
*/
export const CARRY_TEST_GLOBS: readonly string[] = [
'test/**', 'tests/**', 'spec/**', '__tests__/**', 'e2e/**', 'cypress/**', '**/__tests__/**', '**/*.test.*', '**/*.spec.*',
'**/*_test.go', '**/test_*.py', '**/*_test.py', '**/*_spec.rb', '**/*Test.java', '**/*Tests.swift',
];
export const CARRY_METADATA_GLOBS: readonly string[] = [
'VERSION', 'CHANGELOG.md', 'package.json', 'package-lock.json', 'bun.lock', 'bun.lockb', 'yarn.lock', 'pnpm-lock.yaml',
'Cargo.lock', 'Gemfile.lock', 'agents-digest/**',
];
export type CarryClass = 'product' | 'test' | 'metadata';
export interface CarryPlanInput {
/** The reviewed head the receipt names. */
from: string; head: string;
/** Merge base of origin/<base> with `from` and with `head`. */
fromBase: string; headBase: string;
/** Paths changed between from and head, classified. */
changed: Array<{ path: string; class: CarryClass }>;
/** Product patch-ids at both heads (empty string for no product diff). */
productPatchId: { from: string; head: string };
testPatchId: { from: string; head: string };
/** Product paths whose patch against the base differs between the two heads. */
changedProduct: string[];
mergeCommits: number;
rangeDiff: string;
}
export interface CarryRecord { from: string; reason: string; product_patch_id: string; changed_paths: string[]; merge_commits: number; range_diff: string; covers: string[]; reruns: string[] }
export type CarryPlan = { ok: true; carry: CarryRecord } | { ok: false; code: 'RECEIPT_CARRY_PRODUCT_CHANGED' | 'RECEIPT_CARRY_REFUSED'; message: string };
export function classifyCarryPath(rel: string, extra: { tests?: readonly string[]; metadata?: readonly string[] } = {}): CarryClass {
if (matchesAny([...CARRY_METADATA_GLOBS, ...(extra.metadata ?? [])], rel)) return 'metadata';
if (matchesAny([...CARRY_TEST_GLOBS, ...(extra.tests ?? [])], rel)) return 'test';
return 'product';
}
/**
* The carry decision: the receipt follows `head` when the product diff
* against the base has the same patch-id at both heads, which is what a
* conflict-only base merge, a test-only fix or a release-metadata change
* leaves behind. A product patch that differs is RECEIPT_CARRY_PRODUCT_CHANGED,
* whatever else changed.
*/
export function planCarry(input: CarryPlanInput): CarryPlan {
if (input.productPatchId.from !== input.productPatchId.head) {
const named = input.changedProduct.slice(0, 20);
return { ok: false, code: 'RECEIPT_CARRY_PRODUCT_CHANGED', message: `product diff changed between ${input.from.slice(0, 12)} and ${input.head.slice(0, 12)}: ${named.join(', ') || 'patch-id differs'}${input.changedProduct.length > named.length ? ` (+${input.changedProduct.length - named.length} more)` : ''}` };
}
const reasons: string[] = [];
if (input.mergeCommits > 0) reasons.push(input.mergeCommits === 1 ? 'base merge' : `${input.mergeCommits} base merges`);
if (input.testPatchId.from !== input.testPatchId.head) reasons.push('test-only change');
if (input.changed.some(c => c.class === 'metadata')) reasons.push('release metadata');
if (!reasons.length) reasons.push(input.changed.length ? 'no product change' : 'no content change');
return {
ok: true,
carry: {
from: input.from, reason: reasons.join(' + '), product_patch_id: input.productPatchId.head || 'none',
changed_paths: input.changed.slice(0, 50).map(c => `${c.class}:${c.path}`), merge_commits: input.mergeCommits, range_diff: input.rangeDiff,
covers: ['pre-landing review', 'adversarial review', 'gate integrity', 'documentation audit'], reruns: ['CI at head (gstack-ship-queue ready requires it)'],
},
};
}
/** The carried receipt: the same evidence, bound to the new head, with the carry recorded. */
export function carryReceipt(receipt: ShipReceipt, head: string, carry: CarryRecord): ShipReceipt {
return orderReceipt({ ...receipt, head, carry });
}
/** The loop counters the factory scorecard reads (passes, blocking_found, deferred), as `write --review-loop` records them. */
export interface ReviewLoopReceipt { passes: number; blocking_found: number; deferred: number; noted?: number; fixed?: number; scope?: string }
export function parseReviewLoop(value: unknown): ReviewLoopReceipt | undefined {
if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined;
const v = value as Record<string, unknown>;
const n = (k: string) => (typeof v[k] === 'number' && Number.isInteger(v[k]) && (v[k] as number) >= 0 ? (v[k] as number) : undefined);
const passes = n('passes'); const blocking = n('blocking_found'); const deferred = n('deferred');
if (passes === undefined || blocking === undefined || deferred === undefined) return undefined;
const out: ReviewLoopReceipt = { passes, blocking_found: blocking, deferred };
if (n('noted') !== undefined) out.noted = n('noted');
if (n('fixed') !== undefined) out.fixed = n('fixed');
if (typeof v.scope === 'string') out.scope = v.scope.slice(0, 20);
return out;
}
// ---------------------------------------------------------------------------
// census (P7)
// ---------------------------------------------------------------------------