Merge remote-tracking branch 'origin/main' into fix/context-bill-symlinked-skills

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
This commit is contained in:
garrytan committed 2026-10-26 10:45:23 +00:00
commit 9694686cbb
283 files changed
+13043 -1441

No files matched your search

+6 -4
View File
@@ -4,10 +4,12 @@
* variables, and a `bunfig.toml` preload runs code before the entry point.
* gstack runs inside the user's repository, so that directory belongs to the
* code under review. Every Bun gstack starts passes --no-env-file and an empty
* --config: shebangs and shell callers spell it
* `bun --no-env-file --config=/dev/null`, TypeScript spawns use
* bunIsolationArgs(). test/bun-entry-isolation.test.ts holds every entry point
* to that form.
* --config: shebangs and skill prose spell it
* `bun --no-env-file --config=/dev/null`, shipped shell files spell
* `--config="${GSTACK_BUN_CONFIG:-/dev/null}"` (NUL when OSTYPE is msys or
* cygwin and cygpath is on PATH, #3415), TypeScript spawns use
* bunIsolationArgs().
* test/bun-entry-isolation.test.ts holds every entry point to that form.
*
* POSIX passes /dev/null. Native Windows has no /dev/null and `--config=NUL`
* panicked Bun 1.3.10 while parsing the flag (#3085), so a TypeScript spawn on
+30 -8
View File
@@ -2,8 +2,9 @@
* changelog-check — CHANGELOG re-heading and checks for gstack-restamp (C2)
* and the tree receipt (C3). A restamp moves the PR's section (`[Unreleased]`
* or the version currently stamped on the branch) to the top under the new
* version, above its predecessor's entry. Duplicate version headings and a
* top entry that is not VERSION are errors. The tree receipt uses
* version, above its predecessor's entry. Duplicate version headings beyond
* those the base branch already carries, and a top entry that is not VERSION,
* are errors. The tree receipt uses
* `normalizeChangelog` to accept a heading move as a stamp, never a change.
*/
import type { ResultCodeName } from './result-codes';
@@ -44,15 +45,36 @@ export function parseChangelog(text: string): ParsedChangelog {
return { header, sections };
}
/** Duplicate headings, and (when `expectedTop` is given) the top entry equals VERSION. */
export function checkChangelog(text: string, expectedTop: string | null, file = 'CHANGELOG.md'): ChangelogError[] {
/**
* Duplicate headings, and (when `expectedTop` is given) the top entry equals
* VERSION. `base` holds readings of the base branch's CHANGELOG (the base tip,
* and the commit the PR's own lines are counted from): a heading it already carries N
* times may appear N times here (history the PR inherited and may not
* rewrite); only an occurrence beyond that count is a duplicate the PR
* introduced. The count is per heading, not per section body: an inherited
* copy the PR edits or replaces is caught by the train's released-history
* checks (`ownEntryAboveMain`, `changelogDamage`), not here.
*/
export function checkChangelog(text: string, expectedTop: string | null, file = 'CHANGELOG.md', base: string[] = []): ChangelogError[] {
const errors: ChangelogError[] = [];
const parsed = parseChangelog(text);
const seen = new Map<string, number>();
const key = (s: ChangelogSection) => (s.unreleased ? 'Unreleased' : s.version!);
const inherited = new Map<string, number>();
for (const reading of base) {
const counts = new Map<string, number>();
for (const s of parseChangelog(reading).sections) counts.set(key(s), (counts.get(key(s)) ?? 0) + 1);
for (const [k, n] of counts) inherited.set(k, Math.max(inherited.get(k) ?? 0, n));
}
const seen = new Map<string, number[]>();
for (const s of parsed.sections) {
const key = s.unreleased ? 'Unreleased' : s.version!;
if (seen.has(key)) errors.push({ code: 'CHANGELOG_DUPLICATE_HEADING', path: `${file}:${s.start + 1}`, message: `${key} already headed at line ${seen.get(key)! + 1}` });
else seen.set(key, s.start);
const k = key(s);
const starts = seen.get(k) ?? [];
const allowed = Math.max(1, inherited.get(k) ?? 0);
if (starts.length >= allowed) {
const where = allowed > 1 ? `headed ${starts.length + 1} times (the base carries it ${allowed} times; first at line ${starts[0]! + 1})` : `already headed at line ${starts[0]! + 1}`;
errors.push({ code: 'CHANGELOG_DUPLICATE_HEADING', path: `${file}:${s.start + 1}`, message: `${k} ${where}` });
}
seen.set(k, [...starts, s.start]);
}
if (expectedTop) {
const top = parsed.sections[0];
+144
View File
@@ -0,0 +1,144 @@
/**
* Free craft check for a generated page (design-html Step 4). Counts the tells
* that make a page read as generated or unfinished: placeholder content, AI
* cliché copy, scroll listeners, 100vh, dead links, and the missing ship-floor
* tags. Copy checks read the visible text only (script, style and tags
* removed); code checks read the source. Head checks run only on a full
* document. Adapted from Elaya's landing-page-design and redesign-skill
* (MIT); see NOTICE.md. Buzzwords report under the catalog's
* `marketing-buzzword` id, and BUZZWORDS covers every word its heuristic
* names (test-enforced), so the two lists cannot drift.
*/
/** The catalog's marketing-buzzword words plus Elaya's AI cliché words. */
export const BUZZWORDS: readonly string[] = [
'seamless', 'effortless', 'supercharge', 'streamline', 'revolutionize', 'unlock', 'empower', 'elevate',
'unleash', 'next-gen', 'game-changer', 'delve', 'tapestry', 'in the world of',
];
function buzzwordPattern(): RegExp {
const stem = (w: string) => w.replace(/-/g, '[- ]').replace(/e$/, '');
return new RegExp(`\\b(?:${BUZZWORDS.map(stem).join('|')})(?:e|es|ed|ing|ly|er|ers|s|d|eration)?\\b`, 'gi');
}
export interface CraftFinding {
id: string;
count: number;
fix: string;
}
interface CountRule {
id: string;
on: 'source' | 'text' | 'script';
pattern: RegExp;
fix: string;
}
interface PresenceRule {
id: string;
pattern: RegExp;
fix: string;
}
const COUNT_RULES: CountRule[] = [
{ id: 'placeholder-name', on: 'text', pattern: /\b(?:John|Jane) Doe\b/gi, fix: 'use a supplied name, or one that fits the product in sample data' },
{ id: 'placeholder-brand', on: 'text', pattern: /\b(?:Acme|Nexus|SmartFlow)\b/g, fix: 'use a supplied customer, or a fitting name in sample data' },
{ id: 'lorem', on: 'text', pattern: /\blorem ipsum\b/gi, fix: 'write real copy' },
{ id: 'marketing-buzzword', on: 'text', pattern: buzzwordPattern(), fix: 'say the specific thing' },
{ id: 'round-number', on: 'text', pattern: /(?<![\d.])(?:99\.9+|[1-9]0|100)%\s+(?:uptime|faster|more|less|fewer|better|growth|increase|reduction|of (?:teams|users|customers|companies))\b|\b(?:\d+0|\d+(?:,\d{3})+)\+?\s+(?:happy |active )?(?:users|customers|teams|companies)\b|(?<![\d.])10x\s+(?:faster|more|better)\b/gi, fix: 'use the supplied figure, or drop the claim' },
{ id: 'needs-proof', on: 'text', pattern: /\[Needs proof:/g, fix: 'supply the proof or remove the claim before publishing' },
{ id: 'oops', on: 'text', pattern: /\boops\b/gi, fix: 'say what happened and what to do' },
{ id: 'scroll-listener', on: 'source', pattern: /addEventListener\(\s*['"`]scroll['"`]/g, fix: 'use IntersectionObserver; read scroll inside requestAnimationFrame for a scroll-linked effect' },
{ id: 'transition-all', on: 'source', pattern: /\btransition\s*:\s*all\b|\btransition-all\b/g, fix: 'list the transitioned properties' },
{ id: 'dead-link', on: 'source', pattern: /\bhref\s*=\s*["']#["']/g, fix: 'link it, or render the control disabled' },
{ id: 'alert', on: 'script', pattern: /(?<![\w.$])(?:window\.)?alert\s*\(/g, fix: 'show the message inline' },
{ id: 'img-no-alt', on: 'source', pattern: /<img\b(?![^>]*(?<![\w-])alt\s*=)[^>]*>/gi, fix: 'add alt text (alt="" when decorative)' },
];
const HEAD_RULES: PresenceRule[] = [
{ id: 'missing-title', pattern: /<title>\s*[^<\s][^<]*<\/title>/i, fix: 'add a <title>' },
{ id: 'missing-meta-description', pattern: /<meta\b[^>]*\bname\s*=\s*["']description["']/i, fix: 'add <meta name="description">' },
{ id: 'missing-favicon', pattern: /<link\b[^>]*\brel\s*=\s*["'][^"']*\bicon\b/i, fix: 'add a favicon <link rel="icon">' },
];
export function visibleText(html: string): string {
return html
.replace(/<!--[\s\S]*?-->/g, ' ')
.replace(/<(script|style|template)\b[\s\S]*?<\/\1>/gi, ' ')
.replace(/<[^>]+>/g, ' ')
.replace(/&#(\d+);/g, (_, n) => String.fromCodePoint(Number(n)))
.replace(/&#x([0-9a-f]+);/gi, (_, n) => String.fromCodePoint(parseInt(n, 16)))
.replace(/&(nbsp|lt|gt|quot|apos|amp);/g, (_, e) => ({ nbsp: ' ', lt: '<', gt: '>', quot: '"', apos: "'", amp: '&' })[e as string] as string)
.replace(/\s+/g, ' ');
}
export function checkCraft(html: string): CraftFinding[] {
const text = visibleText(html);
const scripts = [...html.matchAll(/<script\b[^>]*>([\s\S]*?)<\/script>/gi), ...html.matchAll(/\bon[a-z]+\s*=\s*"([^"]*)"/gi)].map(m => m[1]).join('\n');
const findings: CraftFinding[] = [];
for (const rule of COUNT_RULES) {
const count = (rule.on === 'text' ? text : rule.on === 'script' ? scripts : html).match(rule.pattern)?.length ?? 0;
if (count > 0) findings.push({ id: rule.id, count, fix: rule.fix });
}
const vh = [...html.matchAll(/\b((?:min-|max-)?height)\s*:\s*100vh\b(\s*!important)?([^}]*)/g)]
.filter(m => m[2] || !new RegExp(`(?<![\\w-])${m[1]}\\s*:\\s*100[dsl]vh\\b`).test(m[3])).length
+ (html.match(/\b(?:min-)?h-screen\b/g)?.length ?? 0);
if (vh > 0) findings.push({ id: 'vh-height', count: vh, fix: 'use min-height: 100dvh (a 100vh line followed by a 100dvh fallback is fine)' });
if (!/<head\b/i.test(html)) return findings;
for (const rule of HEAD_RULES) {
if (!rule.pattern.test(html)) findings.push({ id: rule.id, count: 1, fix: rule.fix });
}
const body = html.slice(html.search(/<body\b/i) + 1);
const firstFocusable = body.match(/<(?:a\b[^>]*\bhref|button|input|select|textarea)\b[^>]*>/i)?.[0] ?? '';
const skipTarget = firstFocusable.match(/^<a\b[^>]*\bhref\s*=\s*["']#([^"']+)["']/i)?.[1];
const main = html.match(/<main\b[^>]*(?<![\w-])id\s*=\s*["']([^"']+)["']/i)?.[1]
?? html.match(/<[a-z]+\b[^>]*\brole\s*=\s*["']main["'][^>]*(?<![\w-])id\s*=\s*["']([^"']+)["']/i)?.[1];
if (!skipTarget || skipTarget !== main) {
findings.push({ id: 'missing-skip-link', count: 1, fix: 'add a "Skip to content" link first in <body> whose #id exists on <main>' });
}
const routeLinks = html.match(/<nav\b[\s\S]*?<\/nav>/gi)?.join('').match(/<a\b[^>]*\bhref\s*=\s*["'](?!#)[^"']+["']/gi)?.length ?? 0;
if (routeLinks >= 2 && !/\baria-current\s*=\s*["']page["']/i.test(html)) {
findings.push({ id: 'missing-aria-current', count: 1, fix: 'mark the current nav link aria-current="page"' });
}
return findings;
}
/** An accepted finding recorded in finalized.json's `craft_exceptions`. */
export interface CraftException {
id: string;
count: number;
reason: string;
}
/** Reads `craft_exceptions` from a finalized.json; a record without one has none. Throws on a malformed record. */
export function parseCraftExceptions(json: string): CraftException[] {
const record = JSON.parse(json);
if (typeof record !== 'object' || record === null || Array.isArray(record)) throw new Error('not a finalized.json object');
const list = record.craft_exceptions ?? [];
const valid = (e: any) => typeof e?.id === 'string' && Number.isInteger(e.count) && e.count > 0 && typeof e.reason === 'string' && e.reason.trim() !== '';
if (!Array.isArray(list) || !list.every(valid)) throw new Error('craft_exceptions must be a list of { id, count, reason } with a positive count and a reason');
return list.map(({ id, count, reason }) => ({ id, count, reason: reason.replace(/\s+/g, ' ').trim() }));
}
/** A finding is accepted when an exception names its id with at least its count; a higher count stays an issue and says how many were accepted. */
export function acceptFindings(findings: CraftFinding[], exceptions: CraftException[]): { issues: CraftFinding[]; accepted: CraftException[] } {
const issues: CraftFinding[] = [];
const accepted: CraftException[] = [];
for (const finding of findings) {
const exception = exceptions.filter(e => e.id === finding.id).sort((a, b) => b.count - a.count)[0];
if (!exception) issues.push(finding);
else if (finding.count <= exception.count) accepted.push({ id: finding.id, count: finding.count, reason: exception.reason });
else issues.push({ ...finding, fix: `${finding.fix} (${exception.count} accepted earlier: ${exception.reason})` });
}
return { issues, accepted };
}
export function formatCraft(findings: CraftFinding[], accepted: CraftException[] = []): string {
const lines = [
...findings.map(f => `CRAFT_CHECK: ${f.id} ${f.count} ${f.fix}`),
...accepted.map(a => `CRAFT_ACCEPTED: ${a.id} ${a.count} ${a.reason}`),
];
const note = accepted.length === 0 ? '' : findings.length === 0 ? ` (${accepted.length} accepted)` : `, ${accepted.length} accepted`;
lines.push(`${findings.length === 0 ? 'CRAFT_RESULT: clean' : `CRAFT_RESULT: ${findings.length} issue(s)`}${note}`);
return lines.join('\n');
}
+8
View File
@@ -14,6 +14,8 @@ The built page is **committed** (eng-review D2): rendering works with zero
network at install time and render time, and there is no npm supply-chain
surface in `./setup`. The drift test (`test/diagram-render-drift.test.ts`)
fails CI if `dist/` is edited by hand or falls out of sync with `BUILD_INFO.json`.
It also checks that the bundled DOMPurify is the `package.json` override and that
the bundle carries no Google API key.
## Page API (window functions)
@@ -41,6 +43,12 @@ bun run build
# 3. commit package.json + bun.lock + dist/ together
```
`scripts/build.ts` empties the one `VITE_APP_FIREBASE_CONFIG` literal in
`@excalidraw/excalidraw`'s npm bundle (a public Firebase client key the offline page
never uses), because a key-shaped literal fails the pre-gate secret scan. The build
fails if that literal is not matched exactly once or an `AIza…` key survives, so an
excalidraw bump that changes its shape needs the strip rule updated.
Render contract details (securityLevel strict, htmlLabels false, print-css font
lock, `<base href>` + `</scri` escaping) are documented in `src/entry.ts` and
`scripts/build.ts` — read both before touching either.
+2 -2
View File
@@ -15,7 +15,7 @@
},
"overrides": {
"chokidar": "4.0.3",
"dompurify": "3.4.16",
"dompurify": "3.4.17",
"lodash-es": "4.18.1",
"nanoid": "5.1.16",
"source-map-js": "1.2.2",
@@ -281,7 +281,7 @@
"detect-node-es": ["detect-node-es@1.1.0", "", {}, "sha512-ypdmJU/TbBby2Dxibuv7ZLW3Bs1QEmM7nHjEANfohJLvE0XVujisn1qPJcZxg+qDucsr+bP6fLD1rPS3AhJ7EQ=="],
"dompurify": ["dompurify@3.4.16", "", { "optionalDependencies": { "@types/trusted-types": "^2.0.7" } }, "sha512-sqo+pNp3qRhCIpbgRi1y8Tgk27Bo2Ry7w0dC1NBeNTdZChWjz9Xb/KOoZbRP/R6pQZ80Qw8YhXw13hWWBbMRnQ=="],
"dompurify": ["dompurify@3.4.17", "", { "optionalDependencies": { "@types/trusted-types": "^2.0.7" } }, "sha512-B/pSlYVHQ58kqISD/yDjuJ1yfzI34m1gF4lAod2bwSRhiN4K5Cl3H8Af7hqB2PmTL911tdEudnnXn5FnhRoz0w=="],
"es-toolkit": ["es-toolkit@1.52.0", "", {}, "sha512-XTNEJQh1tY1ZJVcf6ayP/2n4ZPyaHlW2FWs7xvw5ddPuhUVjLD3olQVQS7kf58JbAB48iL0uL/jerTrjtV3lDA=="],
+3 -3
View File
@@ -1,8 +1,8 @@
{
"name": "gstack-diagram-render",
"sha256": "ec759ca41239ff888acdd0654c3f6ef505e3314b87c6e5de11903f804fc8a859",
"srcSha256": "07238fae312bc0444f62b0a0a3404a8a38c45cef505aa1528c60a0ded17cbe06",
"bytes": 7884089,
"sha256": "c2d37f9f924baae2a146bc109bf9b4c308d89f49e08b1c35793edc310b579444",
"srcSha256": "17d8921086e091252425c63f06cab01b4626d8e0fa9fe8738267e1ac4ade52e8",
"bytes": 7884979,
"bunVersion": "1.4.2",
"deps": {
"@excalidraw/excalidraw": "0.18.1",
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -15,7 +15,7 @@
},
"overrides": {
"chokidar": "4.0.3",
"dompurify": "3.4.16",
"dompurify": "3.4.17",
"nanoid": "5.1.16",
"source-map-js": "1.2.2",
"lodash-es": "4.18.1"
+19 -1
View File
@@ -42,8 +42,26 @@ if (!result.success) {
}
const js = await result.outputs[0].text();
// @excalidraw/excalidraw's npm bundle carries excalidraw.com's public Firebase
// client config (an `AIza…` key) in an env literal nothing in the package
// reads. The offline page never opens a collab session, and a key-shaped
// literal in a committed file fails the pre-gate secret scan on every rebuild,
// so the literal is emptied. Exactly one match is expected: a bump that changes
// the shape must fail here rather than put the key back silently.
const FIREBASE_CONFIG = /VITE_APP_FIREBASE_CONFIG:'\{[^']*\}'/g;
const firebaseHits = js.match(FIREBASE_CONFIG)?.length ?? 0;
if (firebaseHits !== 1) {
console.error(`expected exactly one VITE_APP_FIREBASE_CONFIG literal in the excalidraw bundle, found ${firebaseHits}; update the strip rule in scripts/build.ts`);
process.exit(1);
}
const strippedJs = js.replace(FIREBASE_CONFIG, "VITE_APP_FIREBASE_CONFIG:'{}'");
if (/AIza[0-9A-Za-z_-]{35}/.test(strippedJs)) {
console.error("a Google API key literal survived the strip; update the strip rule in scripts/build.ts");
process.exit(1);
}
// Escape inline-script terminators (see header note).
const inlineJs = js.replaceAll("</scri", "<\\/scri");
const inlineJs = strippedJs.replaceAll("</scri", "<\\/scri");
const head = `<!doctype html>
<html>
+68 -9
View File
@@ -46,12 +46,35 @@ export function resolvesToCommit(ref: string, cwd: string): string | null {
return gitText(['rev-parse', '--verify', '-q', `${ref}^{commit}`], cwd);
}
/** origin/HEAD's target → `main` → `master` (the gstack-diff-scope chain), as a ref name. */
/**
* A ref that could be a branch name: not a sha, not relative or symbolic
* (`HEAD~1`, `main^2`, `@{u}`, `HEAD`, `FETCH_HEAD`), not a full `refs/` path.
* Only such a ref has a remote-tracking twin (`origin/<ref>`) worth trying, and
* only such a ref goes into a fix-line refspec; `origin/HEAD~1` would resolve
* to a different commit than the `HEAD~1` the caller named.
*/
function isBranchName(ref: string): boolean {
return !/^[0-9a-f]{7,64}$/.test(ref) && !/[~^]|@\{/.test(ref) && !/^(?:[A-Z_]*HEAD)$/.test(ref) && !ref.startsWith('refs/');
}
function remoteNames(cwd: string): string[] {
const remotes = (gitText(['remote'], cwd) ?? '').split('\n').filter(Boolean);
return remotes.includes('origin') ? ['origin', ...remotes.filter((r) => r !== 'origin')] : remotes;
}
/**
* The remote's HEAD target → `main` → `master` (the gstack-diff-scope chain),
* as a ref name; the remotes are walked in resolveBase's order, so the default
* and the fix line come from the same remote.
*/
export function defaultBase(cwd: string): string {
const head = gitText(['symbolic-ref', '-q', 'refs/remotes/origin/HEAD'], cwd);
if (head) return head.replace(/^refs\/remotes\//, '');
const remotes = remoteNames(cwd);
for (const remote of remotes) {
const head = gitText(['symbolic-ref', '-q', `refs/remotes/${remote}/HEAD`], cwd);
if (head) return head.replace(/^refs\/remotes\//, '');
}
for (const name of ['main', 'master']) {
if (resolvesToCommit(name, cwd) || resolvesToCommit(`origin/${name}`, cwd)) return name;
if (resolvesToCommit(name, cwd) || remotes.some((remote) => resolvesToCommit(`${remote}/${name}`, cwd))) return name;
}
return 'main';
}
@@ -60,14 +83,50 @@ export function isShallow(cwd: string): boolean {
return gitText(['rev-parse', '--is-shallow-repository'], cwd) === 'true';
}
/** The concrete recovery for an unresolvable base: fetch it from the detected remote, unshallowing when needed. */
/**
* The base as a ref that resolves here and, when `head` is given, shares
* history with it: the ref itself, else its remote-tracking branch
* (`origin/main` for `main`). A clone that checked out only the feature
* branch has no local `main`, and the merge-base against `origin/main` is the
* same commit; a stale local `main` that shares no history with HEAD (a
* fetched-over clone) yields to the twin too, so the fix line's fetch into the
* tracking ref is a fix and not a loop.
*/
export function resolveBase(ref: string, cwd: string, head?: string): { ref: string; sha: string; local?: 'missing' | 'unrelated' } | null {
const related = (sha: string) => !head || mergeBase(sha, head, cwd) !== null;
const direct = resolvesToCommit(ref, cwd);
if (direct && related(direct)) return { ref, sha: direct };
if (!isBranchName(ref)) return direct ? { ref, sha: direct } : null;
for (const remote of remoteNames(cwd)) {
const tracking = `${remote}/${ref}`;
const sha = resolvesToCommit(tracking, cwd);
if (sha && related(sha)) return { ref: tracking, sha, local: direct ? 'unrelated' : 'missing' };
}
return direct ? { ref, sha: direct } : null;
}
/** A word for a printed shell line: as is when it is plain, single-quoted otherwise (ref names may hold `;`, `$`, `(`, `{1,2}`). */
function shellWord(s: string): string {
return /^[A-Za-z0-9._\/@^~+:-]+$/.test(s) ? s : `'${s.replace(/'/g, "'\\''")}'`;
}
/**
* The concrete recovery for an unresolvable base: fetch it from the detected
* remote into its remote-tracking ref (which resolveBase then finds; a bare
* `git fetch origin main` only updates FETCH_HEAD in a single-branch clone),
* unshallowing when needed. The refspec is forced (`+`) so the line also
* repairs a tracking ref that exists but shares no history with HEAD. A sha
* or a relative ref (`HEAD~1`, `main^2`, `@{u}`) is not a refspec: that gets a
* plain fetch (deepened when shallow).
*/
export function noBaseFix(ref: string, cwd: string): string {
const remotes = (gitText(['remote'], cwd) ?? '').split('\n').filter(Boolean);
const remotes = remoteNames(cwd);
const m = /^([^/]+)\/(.+)$/.exec(ref);
const remote = m && remotes.includes(m[1]) ? m[1] : remotes.includes('origin') ? 'origin' : remotes[0] ?? 'origin';
const remote = m && remotes.includes(m[1]) ? m[1] : remotes[0] ?? 'origin';
const branch = m && remotes.includes(m[1]) ? m[2] : ref;
if (/^[0-9a-f]{7,64}\^?$/.test(ref) || ref.endsWith('^')) return isShallow(cwd) ? `git fetch --deepen=50 ${remote}` : `git fetch ${remote}`;
return isShallow(cwd) ? `git fetch --unshallow ${remote} ${branch}` : `git fetch ${remote} ${branch}`;
if (!isBranchName(ref)) return isShallow(cwd) ? `git fetch --deepen=50 ${shellWord(remote)}` : `git fetch ${shellWord(remote)}`;
const refspec = shellWord(`+${branch}:refs/remotes/${remote}/${branch}`);
return isShallow(cwd) ? `git fetch --unshallow ${shellWord(remote)} ${refspec}` : `git fetch ${shellWord(remote)} ${refspec}`;
}
export function mergeBase(a: string, b: string, cwd: string): string | null {
+56 -3
View File
@@ -16,6 +16,8 @@
import { createHash } from "crypto";
import { scan, type Finding, type RepoVisibility } from "./redact-engine";
import { canonicalRemote } from "./remote-identity";
import { parseChangelog } from "./changelog-check";
import { versionWidth } from "./version-source";
export const OPS = ["pr-comment", "issue-comment", "reply", "pr-title", "pr-body", "pr-create", "issue-create"] as const;
export type Op = (typeof OPS)[number];
@@ -198,11 +200,61 @@ function visibility(env: PostEnv, req: Request, kind: HostKind, configBin: strin
type Part = "title" | "body";
interface Located { part: Part; finding: Finding }
function scanParts(parts: Array<[Part, string]>, vis: RepoVisibility, selfEmail: string | undefined) {
/**
* The repository's own four-part release versions: the root VERSION file's
* value and every version in a root CHANGELOG.md release heading, read with
* the same parser gstack-restamp uses (`## [1.2.3.4]`, `## v1.2.3.4`, an
* optional `- date`; a heading that only mentions a quad is not one). A
* four-part version is byte-for-byte a dotted quad, and `1.91.191.0` is a
* public address, so "(1.91.191.0)" in a PR body raised pii.ip_public
* (MEDIUM), which an unattended /ship cannot confirm. The engine's own version
* exemption reads only the declaration right before the span, so prose that
* merely names a release gets no help from it. These exact strings are
* allowlisted for the scan wherever they appear (the allowlist is exact-string
* and context-free, so `host: <released quad>` is exempt too, a trade the
* repo's own release set is small enough to carry); any other dotted quad
* (8.8.8.8, 203.0.113.7, a version this repo never released) still reports.
* The files are read from the checked-out tree, so a branch that adds a
* four-part heading widens the set for posts made from that checkout.
*/
function repoReleaseVersions(env: PostEnv): string[] {
const top = env.run("git", ["rev-parse", "--show-toplevel"]);
const root = top.status === 0 ? top.stdout.trim() : "";
if (!root) return [];
const read = (name: string) => { try { return env.readFile(`${root}/${name}`); } catch { return ""; } };
const versions = new Set<string>();
const current = read("VERSION").trim();
if (versionWidth(current) === 4) versions.add(current);
for (const s of parseChangelog(read("CHANGELOG.md")).sections) if (s.version && versionWidth(s.version) === 4) versions.add(s.version);
return [...versions];
}
/**
* All-digit identifiers a ship receipt or a CI link names, which pii.phone.e164
* reads as phone numbers: a 12-hex receipt sha that happens to be all digits
* (`tree=704992822996`, `tree 704992822996`, and the receipt's `head=`,
* `gated_tree=` and `predecessor=` keys) and an 11-digit GitHub Actions
* run id as prose or link text (`run 19368712345`, `[run 19368712345](…/actions/runs/19368712345)`;
* the engine already exempts the id inside the URL itself). Only the exact
* tokens found in those positions are allowlisted, so a bare 11-digit number,
* a 10-digit national number and an E.164 `+14155551234` still report.
*/
function receiptDigitTokens(texts: string[]): string[] {
const tokens = new Set<string>();
for (const text of texts) {
for (const m of text.matchAll(/(?:^|[^\w])(?:tree|gated_tree|head|predecessor)[= ](\d{12})\b/g)) tokens.add(m[1]!);
for (const m of text.matchAll(/\brun #?(\d{11})\b/g)) tokens.add(m[1]!);
for (const m of text.matchAll(/\/actions\/runs\/(\d{11})\b/g)) tokens.add(m[1]!);
}
return [...tokens];
}
function scanParts(parts: Array<[Part, string]>, vis: RepoVisibility, selfEmail: string | undefined, releaseVersions: string[]) {
const found: Located[] = [];
let oversize = false;
const allowlist = [...releaseVersions, ...receiptDigitTokens(parts.map(([, text]) => text))];
for (const [part, text] of parts) {
const result = scan(text, { repoVisibility: vis, ...(selfEmail ? { selfEmail } : {}) });
const result = scan(text, { repoVisibility: vis, allowlist, ...(selfEmail ? { selfEmail } : {}) });
oversize ||= result.oversize;
for (const finding of result.findings) found.push({ part, finding });
}
@@ -303,7 +355,8 @@ export function runPost(argv: string[], env: PostEnv, configBin = "gstack-config
const vis = visibility(env, req, remote.kind, configBin);
const email = env.run("git", ["config", "user.email"]);
const { found, oversize } = scanParts(parts, vis, email.status === 0 ? email.stdout.trim() || undefined : undefined);
const hasQuad = parts.some(([, text]) => /\b\d{1,3}(?:\.\d{1,3}){3}\b/.test(text));
const { found, oversize } = scanParts(parts, vis, email.status === 0 ? email.stdout.trim() || undefined : undefined, hasQuad ? repoReleaseVersions(env) : []);
env.out(`REPO_VISIBILITY: ${vis}\n`);
const line = (m: Located) => `RULE: ${m.finding.id} LINE: ${m.finding.line} PART: ${m.part}\n`;
const high = found.filter(m => m.finding.severity === "HIGH");
+5 -1
View File
@@ -141,7 +141,11 @@ export function verdictProblem(skill: string, gstackRoot: string, env: Env, bunP
const file = findInstallVerdict(src, project, env);
const v = readInstallVerdict(file);
const problem = (detail: string): VerdictProblem => ({ detail, code: 'INSTALL_UNVERIFIED' });
if (!v) return problem(`no install verdict at ${file} for ${src}`);
if (!v && fs.existsSync(file)) return problem(`the install verdict at ${file} is unreadable or has an unsupported schema_version; rerun the installer`);
if (!v) {
return { ...problem(`no install verdict at ${file} for ${src}`),
fix: `run the Capy skill installer (scripts/install.sh --for ${skill}) from ${project ?? 'this directory'}: the verdict is keyed by the project directory the installer runs in, so a run from the skill's own folder does not cover ${project ?? 'it'}; then launch with the GSTACK_LAUNCH line it prints` };
}
if (!v.ok) return problem(`the install verdict says: ${v.trailer}`);
if (v.checkout !== src) return problem(`the install verdict is for checkout ${v.checkout}, not ${src}`);
const head = spawnSync('git', ['-C', src, 'rev-parse', 'HEAD'], { encoding: 'utf8', timeout: 10_000 }).stdout?.trim() ?? '';
+13 -3
View File
@@ -380,9 +380,19 @@ function runStages(o: RestampOptions, plan: Plan, staging: string, since: string
const r = reheadChangelog(fs.readFileSync(clPath, 'utf8'), { from, to: plan.newVersion, date, file: clRel! });
if (r.error) { cl.status = 'failed'; cl.detail = r.error.message; throw new Refusal(r.error.code, `${clRel}: ${r.error.message}; nothing written to the branch`); }
if (r.moved) fs.writeFileSync(clPath, r.text);
const check = checkChangelog(fs.readFileSync(clPath, 'utf8'), plan.newVersion, clRel!);
if (check.length) { cl.status = 'failed'; cl.detail = check[0]!.message; throw new Refusal(check[0]!.code, `${check[0]!.path}: ${check[0]!.message}; nothing written to the branch`); }
cl.status = 'done'; cl.detail = r.moved ? `${r.from} -> ${r.to}` : `already headed ${plan.newVersion}`;
// Inherited duplicates are allowed at the larger count of two base readings: the base tip and
// `since`, the commit the branch's own lines are counted from (its fork point, or the predecessor's
// head in a gate-ahead stamp), so neither a duplicate main collapsed after the fork nor one it
// gained since refuses the PR. A reading the base cannot show (the PR adds the file) is named.
const readings = [...new Set([plan.baseSha, since])].map(sha => ({ sha, cl: git(o.repoRoot, ['show', `${sha}:${clRel}`]) }));
const readable = readings.filter(x => x.cl.ok);
const unreadable = readings.filter(x => !x.cl.ok).map(x => `${x.sha.slice(0, 12)}:${clRel}`);
const baseNote = unreadable.length === 0 ? '' : readable.length === 0
? `; base ${clRel} unreadable at ${unreadable.join(', ')}, so every duplicate heading counts`
: `; base ${clRel} unreadable at ${unreadable.join(', ')}, inherited headings counted at ${readable.map(x => x.sha.slice(0, 12)).join(', ')} only`;
const check = checkChangelog(fs.readFileSync(clPath, 'utf8'), plan.newVersion, clRel!, readable.map(x => x.cl.out + '\n'));
if (check.length) { cl.status = 'failed'; cl.detail = check[0]!.message + baseNote; throw new Refusal(check[0]!.code, `${check[0]!.path}: ${check[0]!.message}${baseNote}; nothing written to the branch`); }
cl.status = 'done'; cl.detail = (r.moved ? `${r.from} -> ${r.to}` : `already headed ${plan.newVersion}`) + baseNote;
} else { cl.status = 'skipped'; cl.detail = clRel ? `${clRel} absent` : 'changelog: null'; }
injected('changelog');
+16
View File
@@ -132,6 +132,22 @@ export const RELEASE_RESULT_CODES = {
summary: 'a train stopped partway through publication, so main holds a prefix no gate covered on its own; ordinary trains are refused until a repair lands',
fix: 'admit one repair PR at its exact head (train build --repair --prs <n>@<sha>); the freeze clears when verify finds main’s tree after that merge in a green record',
},
// CREW rule 22 (Garry, 2026-10-25): /ship runs before every READY; the queue refuses a PR whose body has no current receipt.
QUEUE_RECEIPT_MISSING: {
anchor: 'queue-receipt-missing',
summary: 'the PR body carries no valid /ship receipt, so the PR was never shipped through gstack and cannot be READY’d, admitted to a train or merged',
fix: 'run /ship on the branch (unattended it writes the receipt into an open PR at HEAD with gstack-ship-receipt write --pr <n> --body …, else leaves it in .gstack/tmp/ship-receipt.md for the parent to post), then gstack-ship-queue ready again; there is no flag to skip this',
},
QUEUE_RECEIPT_STALE: {
anchor: 'queue-receipt-stale',
summary: 'the PR body’s /ship receipt is for another head than the one being READY’d or merged (a push after /ship, or a receipt copied from another PR)',
fix: 'rerun /ship on the current head so the receipt names it, then gstack-ship-queue ready again; a slot’s stamp commit keeps the receipt written for its pinned head',
},
QUEUE_SCREEN_STALE_REF: {
anchor: 'queue-screen-stale-ref',
summary: 'GitHub’s refs/pull/<n>/merge is missing or still merges an older head than the PR’s: the PR conflicts with the base (a CHANGELOG-only conflict counts), so a screen dispatched on it would plan no cases and report success',
fix: 'resolve the conflict with the base branch (or wait for GitHub to recompute the merge ref), push, then gstack-ship-queue ready --pr <n> --screen again; a lane never READYs on a screen that planned nothing',
},
READY_SCREEN_CHOICE_REQUIRED: {
anchor: 'ready-screen-choice-required',
summary: 'the base policy turns trains on, so READY needs an explicit screen choice: --screen (pay for a diff-relevant screen now) or --no-screen',
+2 -2
View File
@@ -226,8 +226,8 @@ export const RESULT_CODES = {
},
CHANGELOG_DUPLICATE_HEADING: {
anchor: 'changelog-duplicate-heading',
summary: 'two CHANGELOG sections carry the same version heading',
fix: 'merge the duplicate sections into one entry under the new version',
summary: 'two CHANGELOG sections carry the same version heading, beyond any duplicate the base branch already carries',
fix: 'merge the duplicate sections the PR introduced into one entry under the new version',
},
CHANGELOG_TOP_MISMATCH: {
anchor: 'changelog-top-mismatch',
+39 -7
View File
@@ -5,11 +5,12 @@
* full-gate check run. Dispatch itself goes through scripts/eval-bg.ts.
*/
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import type { Exec, RunSummary } from '../scripts/eval-bg';
import type { QueueContext } from './ship-queue';
export interface PrInfo { headRefOid: string; isCrossRepository: boolean; state: string; headRefName: string }
export interface PrInfo { headRefOid: string; isCrossRepository: boolean; state: string; headRefName: string; body: string }
export interface RunInfo { databaseId: number; status: string; conclusion: string | null; url: string; headSha: string; event: string; displayTitle: string }
export interface CheckInfo { status: string; conclusion: string | null }
@@ -33,10 +34,10 @@ export function repoSlug(ctx: QueueContext): string | null {
}
export function prInfo(ctx: QueueContext, pr: string): PrInfo | { error: string } {
const r = ctx.gh(['pr', 'view', pr, '--json', 'headRefOid,isCrossRepository,state,headRefName']);
const r = ctx.gh(['pr', 'view', pr, '--json', 'headRefOid,isCrossRepository,state,headRefName,body']);
const p = json<Partial<PrInfo>>(r);
if (!p?.headRefOid) return { error: `cannot read PR #${pr} through gh (${(r.err ?? r.out).trim().slice(0, 120) || 'no headRefOid'})` };
return { headRefOid: p.headRefOid, isCrossRepository: p.isCrossRepository !== false, state: p.state ?? 'OPEN', headRefName: p.headRefName ?? '' };
return { headRefOid: p.headRefOid, isCrossRepository: p.isCrossRepository !== false, state: p.state ?? 'OPEN', headRefName: p.headRefName ?? '', body: p.body ?? '' };
}
const RUN_FIELDS = 'databaseId,status,conclusion,url,headSha,event,displayTitle';
@@ -56,18 +57,49 @@ export function asRun(summary: RunSummary): { id: number; url: string } {
return { id: summary.databaseId, url: summary.url };
}
/** One JSON artifact of a run (the first .json file it holds); null when it is missing or unreadable. */
export function downloadJson(ctx: QueueContext, slug: string, run: number, name: string, scratch: string): unknown {
/** One JSON artifact of a run (the named file, else the first .json file it holds); null when it is missing or unreadable. */
export function downloadJson(ctx: QueueContext, slug: string, run: number, name: string, scratch: string, file?: string): unknown {
const dir = path.join(scratch, `${run}-${name}`);
fs.rmSync(dir, { recursive: true, force: true });
fs.mkdirSync(dir, { recursive: true });
try {
if (!ctx.gh(['run', 'download', String(run), '--repo', slug, '-n', name, '-D', dir]).ok) return null;
const file = fs.readdirSync(dir).find(f => f.endsWith('.json'));
return file ? JSON.parse(fs.readFileSync(path.join(dir, file), 'utf8')) : null;
const pick = file ?? fs.readdirSync(dir).find(f => f.endsWith('.json'));
return pick && fs.existsSync(path.join(dir, pick)) ? JSON.parse(fs.readFileSync(path.join(dir, pick), 'utf8')) : null;
} catch { return null; } finally { fs.rmSync(dir, { recursive: true, force: true }); }
}
/**
* A finished screen run that planned no cases is not a screen: when the merge
* ref it was dispatched for was superseded, evals.yml skips plan-slices and
* concludes success (GSTA-95 on #3431). A screen run uploads no train record,
* so the evidence is the plan itself: no `paid-plan` artifact, or a manifest
* with nothing planned. `hollow` carries the reason; `live` is a screen that
* planned cases or is still running; `unknown` names what could not be read
* (the caller decides, and says, how it counts).
*/
export type ScreenPlan = { kind: 'hollow'; reason: string } | { kind: 'live' } | { kind: 'unknown'; reason: string };
export function hollowScreen(ctx: QueueContext, slug: string, run: number): ScreenPlan {
if (!Number.isSafeInteger(run) || run <= 0) return { kind: 'unknown', reason: `screen run id ${String(run).slice(0, 40)} is not a run number` };
const view = runView(ctx, slug, run);
if (!view) return { kind: 'unknown', reason: `run ${run} is unreadable` };
if (view.status !== 'completed') return { kind: 'live' };
const list = json<{ artifacts?: Array<{ name?: string; expired?: boolean }> }>(ctx.gh(['api', `repos/${slug}/actions/runs/${run}/artifacts?name=${PLAN_ARTIFACT}&per_page=10`]));
if (!Array.isArray(list?.artifacts)) return { kind: 'unknown', reason: `run ${run}'s artifact list is unreadable` };
const plan = list.artifacts.find(a => a.name === PLAN_ARTIFACT);
if (!plan) return { kind: 'hollow', reason: `run ${run} planned no cases (no ${PLAN_ARTIFACT} artifact; concluded ${view.conclusion ?? 'unknown'})` };
if (plan.expired) return { kind: 'unknown', reason: `run ${run}'s ${PLAN_ARTIFACT} artifact has expired` };
const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-screen-'));
let manifest: { entries?: Array<{ status?: unknown }> } | null;
try { manifest = downloadJson(ctx, slug, run, PLAN_ARTIFACT, scratch, 'manifest.json') as typeof manifest; } finally { fs.rmSync(scratch, { recursive: true, force: true }); }
if (!Array.isArray(manifest?.entries)) return { kind: 'unknown', reason: `run ${run}'s ${PLAN_ARTIFACT} manifest.json is unreadable` };
const planned = manifest.entries.filter(e => e?.status === 'planned').length;
return planned === 0 ? { kind: 'hollow', reason: `run ${run} planned no cases (an empty plan manifest; concluded ${view.conclusion ?? 'unknown'})` } : { kind: 'live' };
}
/** The plan manifest every evals.yml run that planned anything uploads (plan-slices); a superseded screen never reaches that job. */
const PLAN_ARTIFACT = 'paid-plan';
/** The named check run on a commit (the newest when several); null when absent or unreadable. */
export function checkRun(ctx: QueueContext, sha: string, name: string): CheckInfo | null {
const r = json<{ check_runs?: Array<{ name?: string; status?: string; conclusion?: string | null }> }>(
+13 -5
View File
@@ -16,7 +16,7 @@ import { EXIT } from './headless-artifacts';
import { ready, type QueueContext } from './ship-queue';
import { classifyTrainHead } from './version-gate-train';
import { git } from './ship-queue-gate';
import { execFor, repoSlug } from './ship-queue-train-github';
import { execFor, hollowScreen, repoSlug } from './ship-queue-train-github';
import { loadReady, nowIso, persist, readyPath, type ReadyReceipt, type ScreenChoice } from './ship-queue-train-record';
import { outOk, outPending, outRefused, trainEnv, type TrainEnv, type TrainOut } from './ship-queue-train';
@@ -85,10 +85,12 @@ async function dispatchScreen(env: TrainEnv, o: ReadyOptions, mergeSha: string,
if (!slug) return outRefused({ code: 'QUEUE_PROOF_MISSING', message: 'gh repo view could not name the repository' }, [], `${Q} ready --pr ${o.pr} --screen`, 'none');
const exec = execFor(env.ctx);
const existing = findDuplicateRun(listDispatchRuns(dispatch.workflow, exec, slug) ?? [], dedupeKey('pr', mergeSha, baseSha, scope));
if (existing) return { choice: { choice: 'screen', policy, nonce: /eval-bg (\S+?)\]/.exec(existing.displayTitle)?.[1] ?? nonce, run: existing.databaseId, merge_sha: mergeSha }, line: `SCREEN_DISPATCH: following run ${existing.databaseId} (same merge SHA, base and policy; no duplicate)` };
const plan = existing ? hollowScreen(env.ctx, slug, existing.databaseId) : null;
const hollow = plan?.kind === 'hollow' ? plan.reason : null;
if (existing && !hollow) return { choice: { choice: 'screen', policy, nonce: /eval-bg (\S+?)\]/.exec(existing.displayTitle)?.[1] ?? nonce, run: existing.databaseId, merge_sha: mergeSha }, line: `SCREEN_DISPATCH: following run ${existing.databaseId} (same merge SHA, base and policy; no duplicate)` };
const found = dispatchWorkflow(dispatch, env.ctx.base, exec, slug) ? await awaitNonceRun(dispatch.workflow, nonce, exec, slug) : null;
if (!found) return outPending({ code: 'QUEUE_TRAIN_DISPATCH_UNKNOWN', message: `no ${dispatch.workflow} run named ${nonce} appeared after the screen dispatch` }, [], `${Q} ready --pr ${o.pr} --screen${o.broad ? ' --broad' : ''} (adopts the run by its key once it appears)`, 'none');
return { choice: { choice: 'screen', policy, nonce, run: found.databaseId, merge_sha: mergeSha }, line: `SCREEN_DISPATCH: ${dispatch.workflow} run ${found.databaseId} ${found.url} nonce ${nonce}` };
return { choice: { choice: 'screen', policy, nonce, run: found.databaseId, merge_sha: mergeSha }, line: `SCREEN_DISPATCH: ${dispatch.workflow} run ${found.databaseId} ${found.url} nonce ${nonce}${hollow ? ` (not following ${hollow}: a screen that planned nothing is not a screen)` : ''}` };
}
export async function trainReady(ctx: QueueContext, o: ReadyOptions): Promise<TrainOut> {
@@ -113,8 +115,14 @@ export async function trainReady(ctx: QueueContext, o: ReadyOptions): Promise<Tr
let choice: ScreenChoice = { choice: 'no-screen', policy: null, nonce: null, run: null, merge_sha: null };
if (o.screen === 'screen') {
const ls = git(ctx.repoRoot, ['ls-remote', env.remote, `refs/pull/${o.pr}/merge`]);
const mergeSha = ls.ok ? ls.out.split(/\s/)[0] ?? '' : '';
if (!/^[0-9a-f]{40,64}$/.test(mergeSha)) return outRefused({ code: 'QUEUE_NOT_READY', message: `${env.remote} has no refs/pull/${o.pr}/merge (the PR conflicts with ${ctx.base}, or GitHub has not computed it yet)` }, lines, `merge ${ctx.base} into the branch, push, then ${Q} ready --pr ${o.pr} --screen`, 'none');
if (!ls.ok) return outRefused({ code: 'QUEUE_SCREEN_STALE_REF', message: `could not list ${env.remote}'s refs: ${(ls.err || ls.out).trim().replace(/\s+/g, ' ').slice(0, 200) || 'git ls-remote failed'}` }, lines, `check the remote, then ${Q} ready --pr ${o.pr} --screen`, 'none');
const mergeSha = ls.out.split(/\s/)[0] ?? '';
const again = `resolve the conflict with ${ctx.base} (or wait for GitHub to recompute refs/pull/${o.pr}/merge), push, then ${Q} ready --pr ${o.pr} --screen; a screen dispatched on a stale merge ref plans no cases`;
if (!/^[0-9a-f]{40,64}$/.test(mergeSha)) return outRefused({ code: 'QUEUE_SCREEN_STALE_REF', message: `${env.remote} has no refs/pull/${o.pr}/merge (the PR conflicts with ${ctx.base}, or GitHub has not computed it yet)` }, lines, again, 'none');
const fetched = git(ctx.repoRoot, ['fetch', '-q', env.remote, `refs/pull/${o.pr}/merge`]);
if (!fetched.ok) return outRefused({ code: 'QUEUE_SCREEN_STALE_REF', message: `could not fetch refs/pull/${o.pr}/merge from ${env.remote}: ${(fetched.err || fetched.out).trim().replace(/\s+/g, ' ').slice(0, 200) || 'git fetch failed'}` }, lines, `check the remote, then ${Q} ready --pr ${o.pr} --screen`, 'none');
const mergeParent = git(ctx.repoRoot, ['rev-parse', '--verify', '--quiet', `${mergeSha}^2`]).out;
if (mergeParent !== head) return outRefused({ code: 'QUEUE_SCREEN_STALE_REF', message: `${env.remote}'s refs/pull/${o.pr}/merge (${mergeSha.slice(0, 12)}) merges ${mergeParent ? mergeParent.slice(0, 12) : 'no PR head'}, not the PR head ${head.slice(0, 12)}: GitHub has not recomputed it, which is what a conflicting PR looks like (CHANGELOG-only conflicts included)` }, lines, again, 'none');
const d = await dispatchScreen(env, o, mergeSha, baseSha);
if ('exit' in d) return { ...d, lines: [...lines, ...d.lines] };
choice = d.choice;
+7 -2
View File
@@ -17,7 +17,8 @@ import { randomBytes } from 'node:crypto';
import { DISPATCH_INPUTS, awaitNonceRun, dispatchWorkflow, makeNonce } from '../scripts/eval-bg';
import type { QueueContext } from './ship-queue';
import { git } from './ship-queue-gate';
import { checkRun, execFor, repoSlug } from './ship-queue-train-github';
import { bindReceipt } from './ship-receipt';
import { checkRun, execFor, prInfo, repoSlug } from './ship-queue-train-github';
import { activeFreeze, attemptsOf, nowIso, persist, trainFile, type FreezeRecord, type TrainRecord } from './ship-queue-train-record';
import {
effect, fetchBase, fetchTrainBranch, findTrain, frozenLines, nextFor, outFailed, outOk, outRefused, pinList, prsArgs, save, trainEnv, type TrainEnv, type TrainOut,
@@ -132,7 +133,11 @@ export async function verifyTrain(ctx: QueueContext, o: { pr: string; train: str
const pinned = head === t.slots[i]!.head ? { same: true, detail: 'the pinned head' } : sameModuloStamps(env, t.slots[i]!.head, head);
const stampOnly = pinned.same ? pinned : mergedIn(env, t, i, head, main);
if (!stampOnly.same) return stopped(env, t, 'QUEUE_TRAIN_MOVED', `#${o.pr} moved past its pinned head ${t.slots[i]!.head.slice(0, 12)} and is not T${after.index} modulo stamps (${head.slice(0, 12)}: ${stampOnly.detail}; against the pin it ${pinned.detail})`, main, lines);
return outOk([...lines, `main: ${main} = T${before.index} (${pre.detail})`, `head: ${head} (${stampOnly.detail})`,
const info = prInfo(ctx, o.pr);
if ('error' in info) return outRefused({ code: 'QUEUE_PROOF_MISSING', message: info.error }, lines, `${Q} verify --pr ${o.pr} --train ${t.nonce}`, run);
const shipped = bindReceipt(info.body, o.pr, [t.slots[i]!.head, head]);
if (!shipped.ok) return outRefused({ code: shipped.code, message: shipped.message }, [...lines, shipped.line], `#${o.pr}'s lane runs /ship and READYs again; then ${Q} train build --prs <pins>`, run);
return outOk([...lines, `main: ${main} = T${before.index} (${pre.detail})`, `head: ${head} (${stampOnly.detail})`, `${shipped.line} (binds ${shipped.head === t.slots[i]!.head ? 'the pinned head' : 'the current head'})`,
`VERIFY_TRAIN: #${o.pr} may merge as slot ${i + 1} of train ${t.nonce} (green run ${gate.run?.id ?? '-'}, ${env.train.full_gate_check} success)`, `MERGE_CONDITION: sha=${head}`],
`merge #${o.pr} with expected head ${head.slice(0, 12)} (gstack-restamp stamps at merge), then ${Q} verify --pr ${o.pr} --train ${t.nonce}`, run);
}
+14 -3
View File
@@ -21,8 +21,9 @@ import type { ResultStatus } from './headless-artifacts';
import { versionAtRef, versionFiles } from './restamp';
import type { LoadedPolicy, ShipPolicy, TrainPolicy } from './ship-policy';
import { loadBasePolicy, type QueueContext } from './ship-queue';
import { bindReceipt } from './ship-receipt';
import { git, sha256, withIndex, type QueueFailure } from './ship-queue-gate';
import { asRun, execFor, newestBranchRun, prInfo, remoteBranchSha, repoSlug, runView, checkRun } from './ship-queue-train-github';
import { asRun, execFor, hollowScreen, newestBranchRun, prInfo, remoteBranchSha, repoSlug, runView, checkRun } from './ship-queue-train-github';
import {
TERMINAL_STATES, activeFreeze, attemptsOf, listTrains, loadBisect, loadReady, loadTrain, nowIso, persist, rebuildFromNotes, repoIdentity, trainFile,
type AttemptPurpose, type AttemptRecord, type TrainRecord, type TrainSlot,
@@ -284,6 +285,8 @@ function admitSlots(env: TrainEnv, pins: Array<{ pr: string; sha: string }>): {
const f = git(ctx.repoRoot, ['fetch', '--no-tags', '-q', env.remote, ...specs]);
if (!f.ok) return outRefused({ code: 'QUEUE_PROOF_MISSING', message: `git fetch of the PR heads failed: ${f.err.slice(0, 160)}` }, [], 'none', 'none');
const slots: TrainSlot[] = [];
const lines: string[] = [];
let slug: string | null | undefined;
for (const p of pins) {
const info = prInfo(ctx, p.pr);
if ('error' in info) return outRefused({ code: 'QUEUE_PROOF_MISSING', message: info.error }, [], 'none', 'none');
@@ -293,11 +296,18 @@ function admitSlots(env: TrainEnv, pins: Array<{ pr: string; sha: string }>): {
if (!info.headRefOid.startsWith(p.sha) || fetched !== info.headRefOid) {
return outRefused({ code: 'QUEUE_TRAIN_MOVED', message: `PR #${p.pr} moved: pinned ${p.sha.slice(0, 12)}, head is now ${info.headRefOid.slice(0, 12)}` }, [], `ask #${p.pr}'s lane for READY on ${info.headRefOid.slice(0, 12)}, then ${Q} train build --prs <pins>`, 'none');
}
const shipped = bindReceipt(info.body, p.pr, [info.headRefOid]);
if (!shipped.ok) return outRefused({ code: shipped.code, message: shipped.message }, [shipped.line], `#${p.pr}'s lane runs /ship, then ${Q} ready --pr ${p.pr} --screen|--no-screen; then ${Q} train build --prs <pins>`, 'none');
const ready = loadReady(env.repo.keys, p.pr, info.headRefOid);
if (!ready) return outRefused({ code: 'QUEUE_NOT_READY', message: `no READY receipt for #${p.pr} at ${info.headRefOid.slice(0, 12)} (local state or ${'refs/notes/gstack-trains'})` }, [], `the lane runs ${Q} ready --pr ${p.pr} --screen|--no-screen`, 'none');
slots.push({ pr: p.pr, head: info.headRefOid, ready_at: ready.ready_at, screen: ready.screen });
let screen = ready.screen;
if (screen.choice === 'screen' && screen.run && slug === undefined) slug = repoSlug(ctx);
const plan = screen.choice === 'screen' && screen.run ? (slug ? hollowScreen(ctx, slug, screen.run) : { kind: 'unknown' as const, reason: 'the repository slug is unreadable' }) : null;
if (plan?.kind === 'hollow') { lines.push(`SCREEN: #${p.pr} ${plan.reason}; counted as not-run, the slot rides unscreened`); screen = { ...screen, choice: 'no-screen' }; }
else if (plan?.kind === 'unknown') lines.push(`SCREEN: #${p.pr} ${plan.reason}; counted as screened, unverified`);
slots.push({ pr: p.pr, head: info.headRefOid, ready_at: ready.ready_at, screen });
}
return { slots, lines: [] };
return { slots, lines };
}
/** Start a new train from --prs, or find the live train with the same pins and base. */
@@ -315,6 +325,7 @@ async function newTrain(env: TrainEnv, o: BuildOptions): Promise<{ t: TrainRecor
if ('exit' in admitted) return admitted;
const order = orderSlots(admitted.slots, o.repair ? 1 : env.train.max_size, explicit);
const lines = [
...admitted.lines,
`ORDER: ${order.train.map((s, i) => `${i + 1}:#${s.pr}(${s.screen.choice === 'screen' ? 'screened' : 'unscreened'})`).join(' ')}${explicit ? ' (explicit --order)' : ''}`,
...(order.held.length ? [`HELD: ${order.held.map(s => '#' + s.pr).join(',')} (${order.split ? 'unscreened PRs form their own train' : `over the train size ${env.train.max_size}`})`] : []),
];
+38 -5
View File
@@ -5,8 +5,9 @@
* so every step ends in a line a coordinator can act on:
*
* ready READY #<pr> <head> STAMP_VERSION=<X|unstamped> plus head, base,
* CI at that exact head, the PREGATE line and the gate state;
* refused when the tree is not the pushed PR head.
* CI at that exact head, the PREGATE line, the gate state and the
* /ship receipt; refused when the tree is not the pushed PR head
* or the PR body carries no receipt for it (QUEUE_RECEIPT_*).
* stamp preflight (gated head equals HEAD modulo stamps, base, policy,
* gate record under full_e2e), restamp, commit, tree receipt,
* each stage journaled; QUEUE_STAMP: <pr> <version> head= gated=
@@ -23,7 +24,7 @@ import * as path from 'node:path';
import { readPregateFile, verifyPregate, PREGATE_OUT_REL } from './pregate/index';
import { ensureTmpExcluded, restamp, versionAtRef } from './restamp';
import type { ResultCodeName } from './result-codes';
import { extractReceipt, receiptSummaryLine } from './ship-receipt';
import { bindReceipt, extractReceipt } from './ship-receipt';
import { isUnavailable, loadPolicyFromBase, type LoadedPolicy } from './ship-policy';
import {
QUEUE_DIR_REL, applyStampPatch, commitForTree, currentAttempt, git, listAttempts, recomputeMergeTree, sha256, writeJsonAtomic,
@@ -59,6 +60,37 @@ function treeReceipt(ctx: QueueContext, policy: LoadedPolicy, gated: string, cur
return 'error' in r ? { code: 'QUEUE_PROOF_MISSING', message: r.error } : r;
}
/**
* The heads a READY accepts a /ship receipt for: HEAD, plus the receipt's own
* head when HEAD is that commit with only stamp files changed on top (the
* slot's stamp commit, docs/ship-policy.md#ship-before-ready), or, from slot
* 2 on, the stamp over a merge of the base into it: /ship ran on the pin, the
* stamp changes nothing it checked, and verify --train binds the same pair
* against the train's own prefix. A merge with no stamp on top is a lane's
* own push (rule 14), so it reruns /ship like any other head. Any other
* receipt head stays QUEUE_RECEIPT_STALE.
*/
function acceptedReceiptHeads(ctx: QueueContext, policy: LoadedPolicy, head: string, body: string): string[] {
const ex = extractReceipt(body);
const r = ex.receipt;
if (!r || ex.errors.length || typeof r.head !== 'string' || !/^[0-9a-f]{12,64}$/i.test(r.head) || head.startsWith(r.head)) return [head];
const root = ctx.repoRoot;
const full = git(root, ['rev-parse', '--verify', '--quiet', `${r.head}^{commit}`]);
if (!full.ok || !git(root, ['merge-base', '--is-ancestor', full.out, head]).ok) return [head];
const stampOnly = (from: string, to: string) => { const t = from === to ? null : treeReceipt(ctx, policy, from, to); return !t || (!('message' in t) && t.tree === 'same-modulo-stamps'); };
if (stampOnly(full.out, head)) return [full.out, head];
const baseSha = git(root, ['rev-parse', `origin/${ctx.base}`]).out;
const onBase = (sha: string) => !!sha && git(root, ['merge-base', '--is-ancestor', sha, baseSha]).ok;
const merge = git(root, ['rev-parse', '--verify', '--quiet', `${head}^1`]).out;
const stamp = merge && merge !== head ? treeReceipt(ctx, policy, merge, head) : null;
if (!stamp || 'message' in stamp || stamp.tree !== 'same-modulo-stamps' || stamp.files.length === 0) return [head];
const parents = git(root, ['rev-list', '--parents', '-n', '1', merge]).out.split(' ').slice(1);
if (parents.length !== 2) return [head];
const pinSide = onBase(parents[0]!) ? parents[1]! : onBase(parents[1]!) ? parents[0]! : '';
if (pinSide && git(root, ['merge-base', '--is-ancestor', full.out, pinSide]).ok && stampOnly(full.out, pinSide)) return [full.out, head];
return [head];
}
const CI_PAGE = 100;
const CI_MAX_PAGES = 10;
@@ -141,7 +173,7 @@ export function ready(ctx: QueueContext, o: { pr: string; pregate?: string; gate
pregateLine = `PREGATE: ${read.file.verdict} tree=${read.file.tree.slice(0, 12)} head=${(read.file.head ?? '').slice(0, 12)} checks=${read.file.checks.length}${v.ok ? '' : ` — ${v.message} (${v.code})`}`;
} else pregateLine = `PREGATE: unreadable (${read.errors[0]?.message ?? 'invalid'})`;
}
const receipt = extractReceipt(info.body ?? '');
const receipt = bindReceipt(info.body ?? '', o.pr, acceptedReceiptHeads(ctx, policy, head, info.body ?? ''));
const attempt = currentAttempt(ctx.repoRoot, o.pr);
const lines = [
`READY #${o.pr} ${head} STAMP_VERSION=${version}`,
@@ -152,13 +184,14 @@ export function ready(ctx: QueueContext, o: { pr: string; pregate?: string; gate
`ci: ${ci.line}`,
pregateLine,
gateLine(policy, attempt),
receipt.found && receipt.receipt && !receipt.errors.length ? receiptSummaryLine(receipt.receipt) : `SHIP_RECEIPT: ${receipt.found ? 'invalid' : 'none'} in the PR body`,
receipt.line,
];
const gate = policy.policy.full_e2e ? gateEvidence(ctx, o.pr, head, attempt, o.gateExit, o.gateLog) : null;
if (gate) lines.push(gate.line);
if (!ci.green) return fail({ code: 'QUEUE_NOT_READY', message: `CI is not green at ${head.slice(0, 12)}: ${ci.line}` }, lines, run);
if (!pregateOk) return fail({ code: 'QUEUE_NOT_READY', message: `the pregate result is not a current pass: ${pregateLine}` }, lines, run);
if (gate && !gate.ok) return fail({ code: 'QUEUE_GATE_MISSING', message: `full_e2e is set and no passing gate is bound to ${head.slice(0, 12)}: ${gate.line}` }, lines, run);
if (!receipt.ok) return fail({ code: receipt.code, message: receipt.message }, lines, run);
return { ok: true, lines, run };
}
+37 -1
View File
@@ -49,6 +49,39 @@ export function extractReceipt(body: string): { found: boolean; receipt?: ShipRe
}
}
export type ReceiptBindingCode = 'QUEUE_RECEIPT_MISSING' | 'QUEUE_RECEIPT_STALE';
export type ReceiptBinding =
| { ok: true; receipt: ShipReceipt; head: string; line: string }
| { ok: false; code: ReceiptBindingCode; message: string; line: string };
/**
* The /ship receipt a PR body must carry before READY, train build or a train
* merge (CREW rule 22; docs/ship-policy.md#ship-before-ready): a valid block
* whose `head` is one of the accepted heads. `accepted` is the head being
* READY'd, or the slot's pinned head beside the current head when the current
* head is the pin's stamp commit (the stamp changes only stamp files, so the
* receipt written for the pin stays the binding one). `line` is the
* informational `SHIP_RECEIPT:` line the READY block prints either way.
*/
export function bindReceipt(body: string, pr: string | undefined, accepted: readonly string[]): ReceiptBinding {
const subject = pr === undefined ? "the receipt's" : `PR #${pr}'s`;
const ex = extractReceipt(body);
if (!ex.found) return { ok: false, code: 'QUEUE_RECEIPT_MISSING', message: `${subject} body carries no ship receipt`, line: 'SHIP_RECEIPT: none in the PR body' };
if (!ex.receipt || ex.errors.length) {
const why = ex.errors[0] ? oneLine(`${ex.errors[0].message} at ${ex.errors[0].path}`).slice(0, 200) : 'invalid';
return { ok: false, code: 'QUEUE_RECEIPT_MISSING', message: `${subject} ship receipt is invalid (${why})`, line: 'SHIP_RECEIPT: invalid in the PR body' };
}
const r = ex.receipt;
const line = receiptSummaryLine(r);
const head = accepted.find(h => h === r.head || (r.head.length >= 12 && h.startsWith(r.head)));
if (!head) {
const want = accepted.map(h => h.slice(0, 12)).join(' or ');
return { ok: false, code: 'QUEUE_RECEIPT_STALE', message: `${subject} ship receipt is for ${oneLine(r.head.slice(0, 12))}, not the head ${want} being merged`, line };
}
if (pr !== undefined && r.pr !== undefined && String(r.pr) !== pr) return { ok: false, code: 'QUEUE_RECEIPT_STALE', message: `${subject} ship receipt names pr=${r.pr}, not this PR`, line };
return { ok: true, receipt: r, head, line };
}
/** The block becomes the first section of the body: an existing block is replaced in place at the top, prose follows. */
export function placeReceiptFirst(body: string, receipt: ShipReceipt): string {
const block = renderReceiptBlock(receipt);
@@ -70,6 +103,9 @@ export function missingIssueLines(body: string, issues: NonNullable<ShipReceipt[
return expected.filter(e => !have.some(l => l === e || l.startsWith(`${e} `)));
}
/** Receipt fields come from the PR body, so anything printed from one stays on its own line, control characters included. */
const oneLine = (s: string) => s.replace(/[\x00-\x1f\x7f\u0080-\u009f\u2028\u2029]+/g, ' ');
/** The first lines of the completion message to the coordinator: identifiers only. */
export function receiptSummaryLine(r: ShipReceipt): string {
const parts = [`pr=${r.pr ?? '-'}`, `head=${r.head.slice(0, 12)}`, `version=${r.version ?? '-'}`, `base=${r.base}`];
@@ -80,7 +116,7 @@ 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)}`);
return `SHIP_RECEIPT: ${parts.join(' ')}`;
return `SHIP_RECEIPT: ${oneLine(parts.join(' '))}`;
}
// ---------------------------------------------------------------------------
+70 -2
View File
@@ -8,6 +8,9 @@
* stamped one to the version the restamp allocates (base + the policy bump).
*/
import { spawnSync } from 'node:child_process';
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import { parseChangelog } from './changelog-check';
import { matchesAny } from './ship-policy';
@@ -30,6 +33,62 @@ export function bumpVersion(version: string, level: string): string | null {
return v.map((n, i) => (i < at ? n : i === at ? n + 1 : 0)).join('.');
}
/**
* An unstamped head may regenerate a release output (a generator change, for
* example) as long as what it committed is exactly what the policy's
* release_tool produces at its merge base's VERSION (the head's own, since
* VERSION is unchanged on this path; the base tip may have stamped since):
* the slot's restamp regenerates it anyway. Runs the head's tool in a
* throwaway worktree with that VERSION and compares each changed output byte
* for byte, reading the tool's output from a file (first 4 KB) so a lingering
* child cannot hold the gate open, and killing a tool that outlives the limit
* with SIGKILL so one that ignores TERM cannot either. A stamp (new
* VERSION inside the output) differs, so it still classifies as stamped, and
* so does an output the tool never writes (it is removed before the run).
* The tool is head code: it runs with a bare environment (no tokens), no
* node_modules link, and a short timeout, and its outputs are read only from
* the staging worktree.
*/
const TOOL_ENV_KEYS = ['PATH', 'HOME', 'TMPDIR', 'LANG', 'LC_ALL', 'BUN_INSTALL', 'SystemRoot', 'TEMP', 'TMP'];
export function regeneratedAtBase(o: { repoRoot: string; head: string; baseVersion: string; tool: string; outputs: string[]; timeoutMs?: number }): { kind: 'same' } | { kind: 'differs'; files: string[] } | { kind: 'error'; reason: string } {
const timeoutMs = o.timeoutMs ?? 120_000;
if (!o.baseVersion.trim()) return { kind: 'error', reason: 'the merge base has no VERSION to regenerate the release outputs at' };
let staging: string;
try { staging = fs.mkdtempSync(path.join(os.tmpdir(), 'version-gate-regen-')); } catch (e) { return { kind: 'error', reason: `cannot create a staging directory to regenerate the release outputs: ${e instanceof Error ? e.message : String(e)}` }; }
try {
const add = spawnSync('git', ['worktree', 'add', '--detach', '-q', staging, o.head], { cwd: o.repoRoot, encoding: 'utf8', timeout: 30_000 });
if (add.status !== 0) return { kind: 'error', reason: `cannot stage ${o.head.slice(0, 12)} to regenerate its release outputs: ${(add.stderr || '').trim().slice(0, 200)}` };
fs.rmSync(path.join(staging, 'VERSION'), { force: true });
fs.writeFileSync(path.join(staging, 'VERSION'), o.baseVersion);
for (const f of o.outputs) fs.rmSync(path.join(staging, f), { force: true });
const env: NodeJS.ProcessEnv = { GSTACK_RESTAMP_VERSION: o.baseVersion.trim(), GSTACK_RESTAMP_STAGING: '1' };
for (const key of TOOL_ENV_KEYS) if (process.env[key] !== undefined) env[key] = process.env[key];
const logPath = path.join(os.tmpdir(), path.basename(staging) + '.log');
const log = fs.openSync(logPath, 'w');
let run: ReturnType<typeof spawnSync>;
try { run = spawnSync('sh', ['-c', o.tool], { cwd: staging, stdio: ['ignore', log, log], timeout: timeoutMs, killSignal: 'SIGKILL', env }); } finally { fs.closeSync(log); }
const output = (() => {
try { const fd = fs.openSync(logPath, 'r'); try { const buf = Buffer.alloc(4096); return buf.subarray(0, fs.readSync(fd, buf)).toString('utf8'); } finally { fs.closeSync(fd); } } catch { return ''; } finally { fs.rmSync(logPath, { force: true }); }
})();
if (run.status !== 0) {
const timedOut = run.signal !== null || (run.error as NodeJS.ErrnoException | undefined)?.code === 'ETIMEDOUT';
const how = run.status !== null ? `exited ${run.status}` : timedOut ? `was killed at the ${Math.round(timeoutMs / 1000)}s limit` : (run.error?.message ?? 'did not exit');
return { kind: 'error', reason: `release_tool \`${o.tool}\` ${how} at ${o.head.slice(0, 12)} with its merge base's VERSION, so its release outputs cannot be told from a stamp: ${output.trim().slice(0, 200)}` };
}
const files = o.outputs.filter(f => {
const committed = spawnSync('git', ['show', `${o.head}:${f}`], { cwd: o.repoRoot, timeout: 30_000, maxBuffer: 64 * 1024 * 1024 });
let generated: Buffer | null = null;
try { generated = fs.readFileSync(path.join(staging, f)); } catch { generated = null; }
return committed.status !== 0 || generated === null || !committed.stdout.equals(generated);
});
return files.length ? { kind: 'differs', files } : { kind: 'same' };
} finally {
spawnSync('git', ['worktree', 'remove', '--force', staging], { cwd: o.repoRoot, timeout: 30_000 });
fs.rmSync(staging, { recursive: true, force: true });
spawnSync('git', ['worktree', 'prune'], { cwd: o.repoRoot, timeout: 30_000 });
}
}
export function classifyTrainHead(o: { repoRoot: string; baseRef: string; head: string }): TrainHead {
const base = `origin/${o.baseRef.replace(/^origin\//, '')}`;
const show = (rev: string, file: string) => git(o.repoRoot, ['show', `${rev}:${file}`]);
@@ -42,10 +101,19 @@ export function classifyTrainHead(o: { repoRoot: string; baseRef: string; head:
const npmVersion = (rev: string) => { try { return JSON.parse(show(rev, 'package.json') ?? '{}').version ?? null; } catch { return null; } };
const changed = (git(o.repoRoot, ['diff', '--name-only', mergeBase, o.head]) ?? '').split('\n').filter(Boolean);
const releaseOutputs: string[] = Array.isArray(policy.release_outputs) ? policy.release_outputs : [];
const touched = changed.filter(f => f === 'VERSION' || matchesAny(releaseOutputs, f));
// touched: what marks the head as stamped (the labels only feed the length check below)
const touched: string[] = changed.filter(f => f === 'VERSION');
if (npmVersion(mergeBase) !== npmVersion(o.head)) touched.push('package.json version');
const outputs = changed.filter(f => matchesAny(releaseOutputs, f));
const baseVersion = show(base, 'VERSION') ?? '';
if (!touched.length && outputs.length && typeof policy.release_tool === 'string') {
// the head's VERSION is its merge base's (unchanged on this path); the base tip may have stamped since
const regen = regeneratedAtBase({ repoRoot: o.repoRoot, head: o.head, baseVersion: show(mergeBase, 'VERSION') ?? '', tool: policy.release_tool, outputs });
if (regen.kind === 'error') return { kind: 'invalid', reason: regen.reason };
if (regen.kind === 'differs') touched.push(...regen.files);
} else touched.push(...outputs);
if (touched.length) {
const expected = bumpVersion(show(base, 'VERSION') ?? '', policy.bump ?? 'patch');
const expected = bumpVersion(baseVersion, policy.bump ?? 'patch');
return expected ? { kind: 'stamped', expected } : { kind: 'invalid', reason: `${base}:VERSION is not a 4-part version` };
}