Use Garry Tan's exact Claude Code setup: 23 opinionated tools that serve as CEO, Designer, Eng Manager, Release Manager, Doc Engineer, and QA
TypeScript
v1.91.77.0 feat(ship): two-stage `gstack-pregate`, `gstack-regen` generated-file registry, intent-based issue links (multi-agent wave C-pregate) (#3121)
Garry Tan8584d6ff49f4
diff --git a/.gitignore b/.gitignoreindex 813873f3b..0db200bfb 100644--- a/.gitignore+++ b/.gitignore@@ -26,6 +26,8 @@ lib/cso/images/gstack-cso-preparation.gstack/*!.gstack/ship-policy.json!.gstack/ship-policy.example.json+!.gstack/generated.json+!.gstack/pregate.json.claude/skills/.claude/gstack-rendered/.claude/scheduled_tasks.lockdiff --git a/.gstack/generated.json b/.gstack/generated.jsonnew file mode 100644index 000000000..012b7807a--- /dev/null+++ b/.gstack/generated.json@@ -0,0 +1,50 @@+{+ "$schema": "https://github.com/garrytan/gstack/docs/pregate.md#generated-v1",+ "entries": [+ {+ "id": "skill-docs",+ "command": "bun run gen:skill-docs --host all",+ "outputs": [+ "SKILL.md",+ "*/SKILL.md",+ "*/sections/*.md",+ "review/design-checklist.md",+ "qa/templates/functional-report-template.md",+ "openclaw/gstack-*-CLAUDE.md",+ "lib/dom-dump.js",+ "gstack/llms.txt",+ "agents-digest/gstack-AGENTS.md",+ "bin/gstack-doctor-components.sh"+ ],+ "inputs": [+ "SKILL.md.tmpl",+ "*/SKILL.md.tmpl",+ "*/sections/*.tmpl",+ "*/sections/manifest.json",+ "*/templates/*.tmpl",+ "openclaw/*.tmpl",+ "hosts/**",+ "model-overlays/**",+ "scripts/gen-skill-docs.ts",+ "scripts/gen-llms-txt.ts",+ "scripts/gen-agents-digest.ts",+ "scripts/gen-doctor-components.ts",+ "scripts/discover-skills.ts",+ "scripts/external-skill-names.ts",+ "scripts/models.ts",+ "scripts/resolvers/**",+ "lib/doctor-components.ts",+ "lib/dom-dump-script.ts",+ "VERSION"+ ],+ "note": "every host render plus the agents digest, llms.txt and the doctor component table"+ },+ {+ "id": "ship-goldens",+ "command": "bun scripts/gen-ship-goldens.ts",+ "outputs": ["test/fixtures/golden/*-ship-SKILL.md"],+ "inputs": ["ship/SKILL.md.tmpl", "ship/sections/manifest.json", "hosts/**", "scripts/resolvers/**", "scripts/gen-skill-docs.ts", "VERSION"],+ "note": "byte-pinned renders of /ship for the claude, codex, factory and agy hosts (test/host-config.test.ts)"+ }+ ]+}diff --git a/.gstack/pregate.json b/.gstack/pregate.jsonnew file mode 100644index 000000000..69573040e--- /dev/null+++ b/.gstack/pregate.json@@ -0,0 +1,23 @@+{+ "$schema": "https://github.com/garrytan/gstack/docs/pregate.md#pregate-v1",+ "runner": "bun test {files}",+ "dependencies": {+ ".github/workflows/**": ["test/pregate-selection.test.ts", "test/free-tests-workflow-wiring.test.ts"],+ "scripts/gen-ship-goldens.ts": ["test/host-config.test.ts"],+ "bun.lock": [],+ ".gitignore": [],+ ".gitattributes": [],+ "docs/**": [],+ "*.md": [],+ "LICENSE": [],+ "licenses/**": [],+ "contrib/**": [],+ "supabase/**": []+ },+ "selection": {+ "free-tests.yml/free-suite": "bun run scripts/test-free-shards.ts --list",+ "windows-free-tests.yml/windows-free-shard": "bun run scripts/test-free-shards.ts --windows-only --list"+ },+ "warn": [],+ "strays": { "allow": [] }+}diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ca85c4cca..40a97980f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,15 @@# Changelog+## [1.91.77.0] - 2026-10-11++**`/ship` now runs a two-stage pre-gate before anything paid, regenerates generated files from a committed registry, and links issues only on explicit intent (multi-agent wave C-pregate, plan items C4, C6, C8 tier 1).**++- **`gstack-pregate` (`lib/pregate/*`).** Stage 1 is the mechanical preflight (`regen`, `secrets`, `strays`, `literals`), stage 2 runs the test lanes the touched files select, with a separate clock each; results record the tree identity they ran against and go stale when the tree moves, so `gstack-ship-receipt write --pregate` refuses on `PREGATE_STALE`, `LANE_FAILED`, `INCOMPLETE` or `REMOTE_UNCLEARED` and writes nothing. Lanes come from the repo's own workflow files; a lane this machine cannot run becomes a persisted `requires-remote` obligation cleared with `gstack-pregate clear --run-url`. `secrets` and required lanes cannot be downgraded in `.gstack/pregate.json`; repo-declared commands run only from `/ship` or with `--allow-repo-commands`, otherwise the check is `incomplete`, never `pass`.+- **`gstack-regen` + `.gstack/generated.json`.** `check` runs each registered generator in a scratch worktree and diffs the outputs; `write` records sha256 pre/post; gstack registers `skill-docs` and `ship-goldens` (`scripts/gen-ship-goldens.ts`).+- **`gstack-issue-links`.** `Fixes #N` only from a `Fixes`/`Closes`/`Resolves` trailer or `--issue`; bare mentions, partial work and cross-repo references render as `Refs`; an unreadable closure issue downgrades to `Refs` with `ISSUE_UNREADABLE`; `--ci-run <id>` adds `Flake: #N (run <id>)`. Step 18 renders the `## Issues` section from it.+- **Step 5 lane example** collects every background lane's PID under `set -o pipefail` and fails on any non-zero exit, so a `| tail`-hidden failure can no longer pass.+- Tier 2 checks (`guards`, `ratchets`, `lint`, `links`, `hermetic`, `patches`, `integrator`) are named in `docs/pregate.md` as a follow-up; 14 new result codes with troubleshooting anchors.+## [1.91.75.0] - 2026-10-11**CSO paid producers no longer fail a successful audit because the final summary quoted the helper's own run ID. Credential-class text still withholds the output and fails the receipt, and the reason now names the matching redactor rules and counts.**diff --git a/VERSION b/VERSIONindex 023afaf52..2acb061ca 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-1.91.75.0+1.91.77.0diff --git a/agents-digest/gstack-AGENTS.md b/agents-digest/gstack-AGENTS.mdindex e0c372eb9..dbdf5664f 100644--- a/agents-digest/gstack-AGENTS.md+++ b/agents-digest/gstack-AGENTS.md@@ -1,4 +1,4 @@-# gstack digest v1.91.75.0 — regenerate/re-copy after upgrading gstack+# gstack digest v1.91.77.0 — regenerate/re-copy after upgrading gstackBehavioral rules from gstack (https://github.com/garrytan/gstack), compressedfor agent hosts without a full skill install. The full skills add workflows,diff --git a/bin/gstack-doctor-components.sh b/bin/gstack-doctor-components.shindex 39e109f0b..8236b66f5 100644--- a/bin/gstack-doctor-components.sh+++ b/bin/gstack-doctor-components.sh@@ -137,6 +137,20 @@ gstack_result_anchor() {SPEND_CAP_EXCEEDED) printf '%s' 'spend-cap-exceeded' ;;CONSENSUS_MISSING) printf '%s' 'consensus-missing' ;;OUTSIDE_RUNNER_UNAVAILABLE) printf '%s' 'outside-runner-unavailable' ;;+ REGEN_REGISTRY_INVALID) printf '%s' 'regen-registry-invalid' ;;+ REGEN_CONTAINMENT) printf '%s' 'regen-containment' ;;+ REGEN_STALE) printf '%s' 'regen-stale' ;;+ REGEN_COMMAND_FAILED) printf '%s' 'regen-command-failed' ;;+ PREGATE_CONFIG_INVALID) printf '%s' 'pregate-config-invalid' ;;+ PREGATE_SECRETS) printf '%s' 'pregate-secrets' ;;+ PREGATE_STRAYS) printf '%s' 'pregate-strays' ;;+ PREGATE_LITERALS) printf '%s' 'pregate-literals' ;;+ PREGATE_NO_LANE) printf '%s' 'pregate-no-lane' ;;+ PREGATE_LANE_FAILED) printf '%s' 'pregate-lane-failed' ;;+ PREGATE_INCOMPLETE) printf '%s' 'pregate-incomplete' ;;+ PREGATE_STALE) printf '%s' 'pregate-stale' ;;+ PREGATE_REMOTE_UNCLEARED) printf '%s' 'pregate-remote-uncleared' ;;+ ISSUE_UNREADABLE) printf '%s' 'issue-unreadable' ;;*) return 1 ;;esac}diff --git a/bin/gstack-issue-links b/bin/gstack-issue-linksnew file mode 100755index 000000000..afbaa07ec--- /dev/null+++ b/bin/gstack-issue-links@@ -0,0 +1,95 @@+#!/usr/bin/env bun+/**+ * gstack-issue-links — issue links by intent for /ship Step 18 (plan C6).+ *+ * gstack-issue-links [--base <ref>] [--issue <n>]... [--ci-run <id>]... [--repo <owner/repo>] [--out <issues.json>] [--json]+ *+ * Reads `git log origin/<base>..HEAD` and classifies every issue mention:+ * `Fixes #N` only on explicit closure intent (a Fixes/Closes/Resolves trailer+ * or --issue), `Refs #N` for everything else (bare mentions, partial fixes,+ * deferred asks, cross-repo ids). Each closure issue is read through+ * gstack-issue-guard; unreadable ones are downgraded to Refs+ * (ISSUE_UNREADABLE). Each --ci-run id is searched among open issues whose+ * body names it (bot flake issues) and rendered `Flake: #N (run <id>)`.+ * Prints the `## Issues` lines; --json / --out emit the receipt's `issues`+ * object for `gstack-ship-receipt write --issues @file`. Logic: lib/issue-links.ts.+ */+import { spawnSync } from 'node:child_process';+import * as fs from 'node:fs';+import * as path from 'node:path';+import { EXIT, exitTableHelp } from '../lib/headless-artifacts';+import { mentionsIn, receiptIssues, renderIssueLines, resolveLinks, type IssueMention } from '../lib/issue-links';+import { resultLine } from '../lib/result-codes';+import { resolveBaseBranch } from '../lib/ship-policy';++const HELP = `gstack-issue-links — Fixes only on explicit closure intent; everything else is Refs (docs/pregate.md#issue-links)++ --base <ref> base branch (default: origin/HEAD, else main); commits origin/<base>..HEAD are read+ --issue <n> explicit closure intent (repeatable); still read through gstack-issue-guard+ --ci-run <id> a failing CI run id (repeatable); open issues naming it become Flake: #N (run <id>)+ --repo <owner/repo> repository for gh (default: the current remote)+ --out <file> write the issues object (fixes, refs, flakes) for gstack-ship-receipt write --issues @file+ --json JSON only on stdout++Exit 0 with links or none; 1 when a closure issue was unreadable (its link is Refs); 2 usage.+${exitTableHelp()}`;++function flags(args: string[], name: string): string[] {+ const out: string[] = [];+ for (let i = 0; i < args.length; i++) if (args[i] === name && args[i + 1] !== undefined) out.push(args[++i]!);+ return out;+}+function git(args: string[], cwd: string): string | undefined {+ const r = spawnSync('git', args, { cwd, encoding: 'utf8', timeout: 30_000, maxBuffer: 64 * 1024 * 1024 });+ return r.status === 0 ? r.stdout : undefined;+}++function main(argv: string[]): number {+ if (argv.includes('--help') || argv.includes('-h')) { process.stdout.write(HELP + '\n'); return EXIT.ok; }+ const json = argv.includes('--json');+ const repoRoot = git(['rev-parse', '--show-toplevel'], process.cwd())?.trim() ?? process.cwd();+ const base = flags(argv, '--base')[0] ?? resolveBaseBranch(repoRoot);+ const explicit: number[] = [];+ for (const raw of flags(argv, '--issue')) {+ if (!/^\d+$/.test(raw)) { process.stderr.write(`gstack-issue-links: --issue must be a positive integer, got ${JSON.stringify(raw)}\n`); return EXIT.usage; }+ explicit.push(Number(raw));+ }+ const runs = flags(argv, '--ci-run');+ if (runs.some(r => !/^[A-Za-z0-9_.-]{1,64}$/.test(r))) { process.stderr.write('gstack-issue-links: --ci-run ids are alphanumeric\n'); return EXIT.usage; }+ const repoFlag = flags(argv, '--repo')[0];+ const repoArgs = repoFlag ? ['--repo', repoFlag] : [];+ const binDir = path.dirname(Bun.fileURLToPath(import.meta.url));++ const log = git(['log', '--format=%H%n%B%x00', `origin/${base}..HEAD`], repoRoot) ?? git(['log', '--format=%H%n%B%x00', `${base}..HEAD`], repoRoot);+ if (log === undefined) { process.stderr.write(`gstack-issue-links: cannot read commits ${base}..HEAD (fetch origin/${base} first)\n`); return EXIT.usage; }+ const mentions: IssueMention[] = [];+ for (const entry of log.split('\0')) {+ const nl = entry.indexOf('\n');+ if (nl < 0) continue;+ mentions.push(...mentionsIn(entry.slice(nl + 1), `commit ${entry.slice(0, nl).trim().slice(0, 12)}`));+ }+ const readable = (issue: number): boolean => {+ const r = spawnSync(path.join(binDir, 'gstack-issue-guard'), ['issue', String(issue)], { cwd: repoRoot, encoding: 'utf8', timeout: 60_000, maxBuffer: 16 * 1024 * 1024 });+ return r.status === 0 && r.stdout.length > 0;+ };+ const flakes: Array<{ issue: number; run: string }> = [];+ for (const run of runs) {+ const r = spawnSync('gh', ['issue', 'list', ...repoArgs, '--state', 'open', '--search', `"${run}" in:body`, '--limit', '20', '--json', 'number'], { cwd: repoRoot, encoding: 'utf8', timeout: 60_000 });+ if (r.status !== 0) { process.stderr.write(`gstack-issue-links: flake search for run ${run} failed: ${(r.stderr ?? '').trim()}\n`); continue; }+ try { for (const row of JSON.parse(r.stdout) as Array<{ number: number }>) flakes.push({ issue: row.number, run }); }+ catch { process.stderr.write(`gstack-issue-links: flake search for run ${run} returned no JSON\n`); }+ }+ const links = resolveLinks(mentions, explicit, readable, flakes);+ for (const n of links.unreadable) process.stderr.write(resultLine('gstack-issue-links', 'ISSUE_UNREADABLE', `#${n}`) + '\n');+ const out = flags(argv, '--out')[0];+ if (out) { fs.mkdirSync(path.dirname(out), { recursive: true }); fs.writeFileSync(out, JSON.stringify(receiptIssues(links), null, 2) + '\n'); }+ if (json) process.stdout.write(JSON.stringify({ ...receiptIssues(links), cross: links.cross, unreadable: links.unreadable, lines: renderIssueLines(links) }) + '\n');+ else {+ const lines = renderIssueLines(links);+ process.stdout.write(lines.length ? lines.join('\n') + '\n' : 'ISSUE_LINKS: none\n');+ for (const m of mentions) process.stderr.write(` ${m.intent === 'fixes' ? 'closure' : 'reference'} ${m.repo ? `${m.repo}#` : '#'}${m.issue} ← ${m.source}\n`);+ }+ return links.unreadable.length ? EXIT.fail : EXIT.ok;+}++process.exit(main(process.argv.slice(2)));diff --git a/bin/gstack-pregate b/bin/gstack-pregatenew file mode 100755index 000000000..b5c1a121c--- /dev/null+++ b/bin/gstack-pregate@@ -0,0 +1,167 @@+#!/usr/bin/env bun+/**+ * gstack-pregate — cheap checks before anything paid or remote (plan C8).+ *+ * gstack-pregate [run] [--stage preflight|tests|all] [--only <check,..>] [--base <ref>]+ * [--allow-repo-commands] [--policy-from base|head] [--out <pregate.json>]+ * [--timeout <s>] [--run <id>] [--explain] [--json]+ * gstack-pregate verify [--out <pregate.json>] [--json] publication check: current tree, no fail/incomplete, obligations cleared+ * gstack-pregate clear --remote <workflow.yml/job> --run-url <url> | --bundle-lane <label> [--out <pregate.json>]+ * gstack-pregate lanes [--explain] the lane list and platform tiers read from .github/workflows+ * gstack-pregate validate | init [--explain] [--force] the working-tree .gstack/pregate.json+ *+ * Runs at the entry of /ship Step 5 (before Step 6's paid evals and any+ * remote gate) under `set -o pipefail`, aggregates exit codes itself, prints+ * a table plus pregate.json (schema: gstack-artifact schema pregate). Two+ * stages with separate clocks: mechanical preflight, then test execution.+ * Pin files (.gstack/pregate.json, .gstack/generated.json) are read from+ * origin/<base>; their commands and the test runner run only with+ * --allow-repo-commands (what /ship passes). Logic: lib/pregate/*.+ */+import { spawnSync } from 'node:child_process';+import * as fs from 'node:fs';+import * as path from 'node:path';+import { EXIT, exitTableHelp, formatResult, type PregateFile } from '../lib/headless-artifacts';+import { PREGATE_CONFIG_PATH, exampleConfigJson, explainConfig, loadConfigFromHead } from '../lib/pregate/config';+import { buildContext } from '../lib/pregate/context';+import { CHECKS, CHECK_IDS, PREGATE_OUT_REL, PREGATE_TIER2, clearObligation, readPregateFile, renderTable, runPregate, verifyPregate, writePregateFile } from '../lib/pregate/index';+import { describeLane, discoverLanes } from '../lib/pregate/workflows';+import { ensureTmpExcluded } from '../lib/restamp';+import { resultLine, type ResultCodeName } from '../lib/result-codes';+import { policyUnavailableLine, resolveBaseBranch } from '../lib/ship-policy';++const HELP = `gstack-pregate — cheap checks before anything paid or remote (docs/pregate.md)++ run (default) stage 1 mechanical preflight (${CHECKS.filter(c => c.stage === 'preflight').map(c => c.id).join(', ')}), then stage 2 test execution (${CHECKS.filter(c => c.stage === 'tests').map(c => c.id).join(', ')})+ verify publication check against ${PREGATE_OUT_REL}: current tree, no fail or incomplete, every requires-remote obligation cleared+ clear record the receipt that clears one requires-remote obligation+ lanes print every CI lane with its platform tier (from .github/workflows/*.yml)+ validate | init the working-tree ${PREGATE_CONFIG_PATH}++ --stage preflight|tests|all default all+ --only <check,...> restrict to these checks (${CHECK_IDS.join(', ')}; tier 2 later: ${PREGATE_TIER2.join(', ')})+ --base <ref> base branch (default: origin/HEAD, else main)+ --allow-repo-commands run pin-file commands and the test runner (what /ship passes); without it those checks are incomplete+ --policy-from base|head base (default, reviewed) or head (unreviewed; needs --allow-repo-commands)+ --out <file> pregate.json path (default ${PREGATE_OUT_REL})+ --timeout <s> per-check timeout (default 600)+ --explain print each selected test's provenance and each uncertain mapping+ --json JSON only on stdout++A failing check blocks (exit 1); incomplete never passes; requires-remote lanes are persisted+obligations publication needs receipts for. Ends with GSTACK_RESULT: skill=pregate status=… run=<pregate.json>.+${exitTableHelp()}`;++function flag(args: string[], name: string): string | undefined { const i = args.indexOf(name); return i >= 0 ? args[i + 1] : undefined; }+function repoRoot(): string | null {+ const r = spawnSync('git', ['rev-parse', '--show-toplevel'], { encoding: 'utf8', timeout: 15_000 });+ return r.status === 0 && r.stdout.trim() ? r.stdout.trim() : null;+}+function outPath(root: string, rest: string[]): string { const o = flag(rest, '--out'); return o ? path.resolve(o) : path.join(root, PREGATE_OUT_REL); }++function cmdRun(root: string, rest: string[], json: boolean): number {+ const stage = (flag(rest, '--stage') ?? 'all') as 'preflight' | 'tests' | 'all';+ if (!['preflight', 'tests', 'all'].includes(stage)) { process.stderr.write('gstack-pregate: --stage needs preflight, tests or all\n'); return EXIT.usage; }+ const only = flag(rest, '--only')?.split(',').map(s => s.trim()).filter(Boolean);+ const unknown = (only ?? []).filter(id => !CHECK_IDS.includes(id));+ if (unknown.length) { process.stderr.write(`gstack-pregate: unknown check(s) ${unknown.join(', ')}${unknown.some(u => (PREGATE_TIER2 as readonly string[]).includes(u)) ? ' (tier 2, not in this gstack)' : ''}; known: ${CHECK_IDS.join(', ')}\n`); return EXIT.usage; }+ const policyFrom = (flag(rest, '--policy-from') ?? 'base') as 'base' | 'head';+ if (!['base', 'head'].includes(policyFrom)) { process.stderr.write('gstack-pregate: --policy-from needs base|head\n'); return EXIT.usage; }+ const allow = rest.includes('--allow-repo-commands');+ if (policyFrom === 'head' && !allow) { process.stderr.write('gstack-pregate: --policy-from head needs --allow-repo-commands (the working-tree pin files are unreviewed)\n'); return EXIT.refused; }+ const timeoutMs = Number(flag(rest, '--timeout') ?? 600) * 1000;+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) { process.stderr.write('gstack-pregate: --timeout needs a positive number of seconds\n'); return EXIT.usage; }+ const base = resolveBaseBranch(root, flag(rest, '--base'));+ const loaded = buildContext({ repoRoot: root, base, policyFrom, allowRepoCommands: allow, timeoutMs, knownChecks: [...CHECK_IDS, ...PREGATE_TIER2] });+ if ('refused' in loaded) {+ const { code, message } = loaded.refused;+ process.stderr.write((code === 'POLICY_SOURCE_UNAVAILABLE' ? policyUnavailableLine('gstack-pregate', base, message).replace('.gstack/ship-policy.json', 'pin files') : resultLine('gstack-pregate', code as ResultCodeName, message)) + '\n');+ process.stdout.write(formatResult('pregate', 'refused', `origin/${base}`) + '\n');+ return EXIT.refused;+ }+ const ctx = loaded.ctx;+ ensureTmpExcluded(root);+ const file = runPregate(ctx, { stage, only, run: flag(rest, '--run') });+ const out = outPath(root, rest);+ let written: string;+ try { written = writePregateFile(root, out, file); }+ catch (e: any) { process.stderr.write(resultLine('gstack-pregate', 'ARTIFACT_SCHEMA', e.message) + '\n'); return EXIT.fail; }+ const blocking = file.checks.some(c => c.status === 'fail' || c.status === 'incomplete' || c.status === 'not_installed');+ const status = file.checks.some(c => c.status === 'incomplete' || c.status === 'not_installed') && !file.checks.some(c => c.status === 'fail') ? 'incomplete' : 'complete';+ if (json) { process.stdout.write(JSON.stringify({ ...file, out: written, explain: rest.includes('--explain') ? ctx.explain : undefined, ok: !blocking }) + '\n'); return blocking ? EXIT.fail : EXIT.ok; }+ process.stdout.write(`pregate: policy ${ctx.configLabel}; registry ${ctx.registryLabel}; base ${ctx.baseRef}@${ctx.baseSha.slice(0, 12)}; ${ctx.touched.length} touched file(s); platform ${ctx.platform}\n`);+ process.stdout.write(renderTable(file));+ if (rest.includes('--explain')) { process.stdout.write('--- explain ---\n'); for (const line of ctx.explain) process.stdout.write(`${line}\n`); }+ for (const c of file.checks) if (c.status === 'fail' || c.status === 'incomplete') process.stderr.write(`gstack-pregate: ${c.id}: ${c.detail}; fix: ${c.fix ?? 'see the table'} (${c.code ?? 'PREGATE_INCOMPLETE'})\n`);+ process.stdout.write(`pregate.json: ${written}\n`);+ process.stdout.write(formatResult('pregate', status, written) + '\n');+ return blocking ? EXIT.fail : EXIT.ok;+}++function cmdVerify(root: string, rest: string[], json: boolean): number {+ const out = outPath(root, rest);+ if (!fs.existsSync(out)) { process.stderr.write(resultLine('gstack-pregate verify', 'PREGATE_STALE', `${out} does not exist; run gstack-pregate first`) + '\n'); return EXIT.fail; }+ const read = readPregateFile(out);+ if (!read.file) { for (const e of read.errors) process.stderr.write(resultLine('gstack-pregate verify', e.code, `${e.message} at ${e.path}`) + '\n'); return EXIT.fail; }+ const v = verifyPregate(root, read.file);+ if (json) { process.stdout.write(JSON.stringify({ ...v, verdict: read.file.verdict, tree: read.file.tree, head: read.file.head, out }) + '\n'); return v.ok ? EXIT.ok : EXIT.fail; }+ if (v.ok) { process.stdout.write(`PREGATE_VERIFY: ok ${v.message}\n`); return EXIT.ok; }+ process.stderr.write(resultLine('gstack-pregate verify', v.code!, v.message) + '\n');+ for (const r of v.uncleared) process.stdout.write(`requires-remote: ${r.lane} (${r.platform}) ${r.tests.length} test(s) uncleared\n`);+ process.stdout.write(`PREGATE_VERIFY: refused ${v.code}\n`);+ return EXIT.fail;+}++function cmdClear(root: string, rest: string[]): number {+ const lane = flag(rest, '--remote');+ const receipt = flag(rest, '--run-url') ?? (flag(rest, '--bundle-lane') ? `bundle-lane:${flag(rest, '--bundle-lane')}` : undefined);+ if (!lane || !receipt) { process.stderr.write(`gstack-pregate clear: --remote <workflow.yml/job> and --run-url <url> (or --bundle-lane <label>) are required\n`); return EXIT.usage; }+ const out = outPath(root, rest);+ const read = fs.existsSync(out) ? readPregateFile(out) : { file: null, errors: [] };+ if (!read.file) { process.stderr.write(resultLine('gstack-pregate clear', 'PREGATE_STALE', `${out} is missing or invalid; run gstack-pregate first`) + '\n'); return EXIT.fail; }+ let file: PregateFile;+ try { file = clearObligation(read.file, lane, receipt, `gstack-pregate clear ${new Date().toISOString()}`); }+ catch (e: any) { process.stderr.write(`gstack-pregate clear: ${e.message}\n`); return EXIT.usage; }+ writePregateFile(root, out, file);+ process.stdout.write(`PREGATE_CLEARED: ${lane} receipt=${receipt} verdict=${file.verdict}\n`);+ return EXIT.ok;+}++function main(argv: string[]): number {+ const cmd = argv[0] && !argv[0].startsWith('--') ? argv[0] : 'run';+ const rest = argv[0] && !argv[0].startsWith('--') ? argv.slice(1) : argv;+ const json = rest.includes('--json');+ if (argv.includes('--help') || argv.includes('-h') || cmd === 'help') { process.stdout.write(HELP + '\n'); return EXIT.ok; }+ const root = repoRoot();+ if (!root) { process.stderr.write('gstack-pregate: not inside a git repository\n'); return EXIT.usage; }+ if (cmd === 'run') return cmdRun(root, rest, json);+ if (cmd === 'verify') return cmdVerify(root, rest, json);+ if (cmd === 'clear') return cmdClear(root, rest);+ if (cmd === 'lanes') {+ const lanes = discoverLanes(root);+ if (json) { process.stdout.write(JSON.stringify(lanes) + '\n'); return EXIT.ok; }+ for (const l of lanes) process.stdout.write(describeLane(l) + '\n');+ process.stdout.write(`LANES: ${lanes.length} jobs; tests ${lanes.filter(l => l.runsTests).length}; platform ${lanes.filter(l => l.tier === 'platform').length}\n`);+ return EXIT.ok;+ }+ if (cmd === 'validate') {+ const loaded = loadConfigFromHead(root, [...CHECK_IDS, ...PREGATE_TIER2]);+ if ('unavailable' in loaded) return EXIT.refused;+ for (const e of loaded.errors) process.stderr.write(resultLine('gstack-pregate validate', e.code, `${e.message} at ${e.path || PREGATE_CONFIG_PATH}`) + '\n');+ process.stdout.write(loaded.errors.length ? `PREGATE_CONFIG_INVALID: ${loaded.errors.length} error(s)\n` : `PREGATE_CONFIG_VALID: ${loaded.present ? PREGATE_CONFIG_PATH : `no ${PREGATE_CONFIG_PATH} (defaults apply)`}\n`);+ return loaded.errors.length ? EXIT.fail : EXIT.ok;+ }+ if (cmd === 'init') {+ if (rest.includes('--explain')) { process.stdout.write(explainConfig()); if (rest.length === 1) return EXIT.ok; }+ const file = path.join(root, PREGATE_CONFIG_PATH);+ if (fs.existsSync(file) && !rest.includes('--force')) { process.stderr.write(resultLine('gstack-pregate init', 'POLICY_EXISTS', file) + '\n'); return EXIT.refused; }+ fs.mkdirSync(path.dirname(file), { recursive: true });+ fs.writeFileSync(file, exampleConfigJson());+ process.stdout.write(`PREGATE_CONFIG_WRITTEN: ${PREGATE_CONFIG_PATH} (edit it, then gstack-pregate validate; commit it on the base branch before /ship reads it)\n`);+ return EXIT.ok;+ }+ process.stderr.write(`gstack-pregate: unknown command ${cmd}\n${HELP}\n`);+ return EXIT.usage;+}++process.exitCode = main(process.argv.slice(2));diff --git a/bin/gstack-regen b/bin/gstack-regennew file mode 100755index 000000000..4281915f3--- /dev/null+++ b/bin/gstack-regen@@ -0,0 +1,132 @@+#!/usr/bin/env bun+/**+ * gstack-regen — the generated-file registry `.gstack/generated.json` (plan C4).+ *+ * gstack-regen check [--allow-repo-commands] [--base <ref>] [--registry-from base|head] [--only <id,..>] [--touched <path,..>] [--json]+ * gstack-regen write [--allow-repo-commands] [--base <ref>] [--registry-from base|head] [--only <id,..>] [--json]+ * gstack-regen list | validate | init [--explain] [--force]+ *+ * `check` regenerates every selected entry in a scratch `git worktree` seeded+ * from the working tree (node_modules linked, never copied) and reports stale+ * outputs without touching the tree; `write` regenerates in place. Commands+ * are read from the committed copy on origin/<base>; they run only with+ * --allow-repo-commands (what /ship passes). Standalone, `check`/`write` list+ * the commands and exit 3 (REPO_COMMANDS_NOT_ALLOWED). Workflow commands end+ * with the GSTACK_RESULT line. Logic: lib/regen.ts.+ */+import { spawnSync } from 'node:child_process';+import * as fs from 'node:fs';+import * as path from 'node:path';+import { EXIT, exitTableHelp, formatResult } from '../lib/headless-artifacts';+import {+ GENERATED_PATH, exampleRegistryJson, isRegistryUnavailable, loadRegistryFromBase, loadRegistryFromHead, renderEntry, runRegen,+ type RegistryLoad,+} from '../lib/regen';+import { RESULT_CODES, resultLine } from '../lib/result-codes';+import { policyUnavailableLine, resolveBaseBranch } from '../lib/ship-policy';++const HELP = `gstack-regen — generated files regenerate, never hand-merge (docs/pregate.md#generated)++ check regenerate in a scratch git worktree; report stale entries (exit 1) without touching the tree+ write regenerate in place (the restamp and the Step 3 conflict rule)+ list print every entry: id, command, outputs, inputs+ validate schema and containment check of the working-tree ${GENERATED_PATH}+ init [--explain] [--force] write an example registry++ --allow-repo-commands run the registry's commands (what /ship passes); without it, check/write list them and exit 3+ --registry-from base|head base (default, reviewed: origin/<base>) or head (unreviewed; needs --allow-repo-commands)+ --base <ref> base branch (default: origin/HEAD, else main)+ --only <id,...> restrict to these entries+ --touched <path,...> restrict to entries whose inputs or outputs intersect these paths+ --json JSON only on stdout++Prints one \`regen <id>: fresh|stale|failed|listed|written\` line per entry and+GSTACK_RESULT: skill=regen status=complete|incomplete|refused run=<wtree>.+${exitTableHelp()}`;++function flag(args: string[], name: string): string | undefined {+ const i = args.indexOf(name);+ return i >= 0 ? args[i + 1] : undefined;+}+function list(v: string | undefined): string[] | undefined {+ return v === undefined ? undefined : v.split(',').map(s => s.trim()).filter(Boolean);+}+function repoRoot(): string {+ const r = spawnSync('git', ['rev-parse', '--show-toplevel'], { encoding: 'utf8', timeout: 15_000 });+ return r.status === 0 && r.stdout.trim() ? r.stdout.trim() : process.cwd();+}++function load(root: string, rest: string[], defaultFrom: 'base' | 'head'): RegistryLoad | number {+ const from = flag(rest, '--registry-from') ?? defaultFrom;+ if (from !== 'base' && from !== 'head') { process.stderr.write(`gstack-regen: --registry-from needs base or head\n`); return EXIT.usage; }+ if (from === 'head') {+ if (defaultFrom === 'base' && !rest.includes('--allow-repo-commands')) { process.stderr.write('gstack-regen: --registry-from head needs --allow-repo-commands (the working-tree registry is unreviewed)\n'); return EXIT.refused; }+ return loadRegistryFromHead(root);+ }+ const base = resolveBaseBranch(root, flag(rest, '--base'));+ const loaded = loadRegistryFromBase(root, base);+ if (isRegistryUnavailable(loaded)) { process.stderr.write(policyUnavailableLine('gstack-regen', base, loaded.detail).replace('.gstack/ship-policy.json', GENERATED_PATH) + '\n'); return EXIT.refused; }+ return loaded;+}++function main(argv: string[]): number {+ const [cmd, ...rest] = argv;+ const json = rest.includes('--json');+ if (!cmd || cmd === '--help' || cmd === '-h' || cmd === 'help') { process.stdout.write(HELP + '\n'); return cmd ? EXIT.ok : EXIT.usage; }+ const root = repoRoot();++ if (cmd === 'init') {+ if (rest.includes('--explain')) {+ process.stdout.write('entries[].id: stable id ([a-z0-9][a-z0-9_.-]*), used by --only and the pre-gate\nentries[].command: the one command that regenerates the outputs; null lists outputs regenerated by hand\nentries[].outputs: repo-relative globs the command writes (non-empty)\nentries[].inputs: repo-relative globs that feed it; empty or absent means always regenerate\nentries[].note: free text shown in list and --explain\n');+ if (rest.length === 1) return EXIT.ok;+ }+ const file = path.join(root, GENERATED_PATH);+ if (fs.existsSync(file) && !rest.includes('--force')) { process.stderr.write(resultLine('gstack-regen init', 'POLICY_EXISTS', file) + '\n'); return EXIT.refused; }+ fs.mkdirSync(path.dirname(file), { recursive: true });+ fs.writeFileSync(file, exampleRegistryJson());+ process.stdout.write(`REGISTRY_WRITTEN: ${GENERATED_PATH} (edit it, then gstack-regen validate; commit it on the base branch before /ship reads it)\n`);+ return EXIT.ok;+ }++ if (cmd === 'validate' || cmd === 'list') {+ const fromBase = cmd === 'list' && flag(rest, '--registry-from') === 'base';+ const loaded = fromBase ? loadRegistryFromBase(root, resolveBaseBranch(root, flag(rest, '--base'))) : loadRegistryFromHead(root);+ if (isRegistryUnavailable(loaded)) { process.stderr.write(policyUnavailableLine('gstack-regen', loaded.base, loaded.detail).replace('.gstack/ship-policy.json', GENERATED_PATH) + '\n'); return EXIT.refused; }+ for (const e of loaded.errors) process.stderr.write(resultLine(`gstack-regen ${cmd}`, e.code, `${e.message} at ${e.path || GENERATED_PATH}`) + '\n');+ if (json) { process.stdout.write(JSON.stringify({ valid: loaded.errors.length === 0, present: loaded.present, source: loaded.source, entries: loaded.registry.entries, errors: loaded.errors }) + '\n'); return loaded.errors.length ? EXIT.fail : EXIT.ok; }+ if (cmd === 'validate') { process.stdout.write(loaded.errors.length ? `REGISTRY_INVALID: ${loaded.errors.length} error(s)\n` : `REGISTRY_VALID: ${loaded.present ? GENERATED_PATH : `no ${GENERATED_PATH} (nothing registered)`}\n`); return loaded.errors.length ? EXIT.fail : EXIT.ok; }+ process.stdout.write(`registry: ${loaded.source.label}\n`);+ for (const e of loaded.registry.entries) process.stdout.write(`${e.id}: command=${e.command === null ? 'null (by hand)' : JSON.stringify(e.command)} outputs=${e.outputs.join(',')} inputs=${e.inputs.join(',') || '(always)'}${e.note ? ` note=${JSON.stringify(e.note)}` : ''}\n`);+ return loaded.errors.length ? EXIT.fail : EXIT.ok;+ }++ if (cmd !== 'check' && cmd !== 'write') { process.stderr.write(`gstack-regen: unknown command ${cmd}\n${HELP}\n`); return EXIT.usage; }+ const loaded = load(root, rest, 'base');+ if (typeof loaded === 'number') return loaded;+ if (isRegistryUnavailable(loaded)) return EXIT.refused;+ if (loaded.errors.length) {+ for (const e of loaded.errors) process.stderr.write(resultLine(`gstack-regen ${cmd}`, e.code, `${e.message} at ${e.path || GENERATED_PATH} (${loaded.source.label})`) + '\n');+ process.stdout.write(formatResult('regen', 'refused', loaded.source.label) + '\n');+ return EXIT.refused;+ }+ const commands = loaded.registry.entries.filter(e => e.command);+ if (commands.length && !rest.includes('--allow-repo-commands')) {+ process.stderr.write(`gstack-regen ${cmd}: ${RESULT_CODES.REPO_COMMANDS_NOT_ALLOWED.summary.replace('the policy declares commands', `${GENERATED_PATH} declares ${commands.length} command(s)`)}; fix: pass --allow-repo-commands (what /ship does) (REPO_COMMANDS_NOT_ALLOWED)\n`);+ for (const e of commands) process.stdout.write(`COMMAND: ${e.id}=${JSON.stringify(e.command)} outputs=${e.outputs.join(',')}\n`);+ process.stdout.write(formatResult('regen', 'refused', loaded.source.label) + '\n');+ return EXIT.refused;+ }+ let outcome;+ try { outcome = runRegen({ repoRoot: root, registry: loaded.registry, mode: cmd, only: list(flag(rest, '--only')), touched: list(flag(rest, '--touched')) }); }+ catch (e: any) { process.stderr.write(resultLine(`gstack-regen ${cmd}`, 'PREGATE_INCOMPLETE', e.message) + '\n'); process.stdout.write(formatResult('regen', 'incomplete', loaded.source.label) + '\n'); return EXIT.fail; }+ const bad = outcome.results.filter(r => r.status === 'stale' || r.status === 'failed');+ const status = outcome.results.some(r => r.status === 'failed') ? 'incomplete' : 'complete';+ if (json) { process.stdout.write(JSON.stringify({ mode: cmd, registry: loaded.source.label, wtree: outcome.wtree, results: outcome.results, ok: bad.length === 0 }) + '\n'); return bad.length ? EXIT.fail : EXIT.ok; }+ process.stdout.write(`registry: ${loaded.source.label}\n`);+ for (const r of outcome.results) process.stdout.write(renderEntry(r) + '\n');+ process.stdout.write(`REGEN: ${cmd} ${bad.length ? `${bad.length} stale or failed` : 'fresh'} (${outcome.results.length} entries)\n`);+ process.stdout.write(formatResult('regen', status, outcome.wtree ?? loaded.source.label) + '\n');+ return bad.length ? EXIT.fail : EXIT.ok;+}++process.exitCode = main(process.argv.slice(2));diff --git a/bin/gstack-ship-receipt b/bin/gstack-ship-receiptindex 73932c6a2..237eb1c06 100755--- a/bin/gstack-ship-receipt+++ b/bin/gstack-ship-receipt@@ -6,7 +6,7 @@* [--predecessor <sha>] [--gate <json|@file>] [--ci <json|@file>] [--spend-usd <n>]* [--session-kind <k>] [--artifacts-consumed <n>/<m>] [--run <id>] [--thread <id>]* [--receipt <tree-receipt.json>] [--policy <label>] [--preregistration <text>] [--history <text>]- * [--out <file>] [--body <pr-body.md>] [--json]+ * [--pregate <pregate.json>] [--issues <json|@file>] [--out <file>] [--body <pr-body.md>] [--json]* gstack-ship-receipt read --pr <n> [--repo <owner/repo>] [--json]* gstack-ship-receipt read --body <file> [--json]* gstack-ship-receipt census --repo <owner/repo> --since <tag|YYYY-MM-DD> [--cohort <file>] [--limit <n>] [--json]@@ -22,6 +22,7 @@ import * as path from 'node:path';import { EXIT, exitTableHelp, type ShipReceipt } from '../lib/headless-artifacts';import { resultLine } from '../lib/result-codes';import { versionAtRef } from '../lib/restamp';+import { readPregateFile, verifyPregate } from '../lib/pregate/index';import { resolveBaseBranch } from '../lib/ship-policy';import {computeCensus, extractReceipt, orderReceipt, placeReceiptFirst, receiptSummaryLine, renderCensus, renderReceiptBlock, validateReceipt,@@ -38,7 +39,9 @@ const HELP = `gstack-ship-receipt — the \`\`\`gstack-ship-receipt\`\`\` blockwrite flags: --pr --head --base --version --gated-tree --predecessor --gate <json|@file> --ci <json|@file> --spend-usd--session-kind --artifacts-consumed <n>/<m> --run --thread --receipt <tree-receipt.json> --policy --preregistration- --history --queue-mode --out <file> --body <pr-body.md>. Defaults: head=HEAD, base=origin/HEAD's branch, version=the+ --history --queue-mode --pregate <pregate.json> (C8: refused unless current, green and every requires-remote obligation+ carries a receipt: PREGATE_STALE / PREGATE_LANE_FAILED / PREGATE_INCOMPLETE / PREGATE_REMOTE_UNCLEARED) --issues <json|@file>+ (C6: gstack-issue-links --json) --out <file> --body <pr-body.md>. Defaults: head=HEAD, base=origin/HEAD's branch, version=theversion source at HEAD, session_kind=$GSTACK_SESSION_KIND (gstack-session-kind), tree/gate_reuse/gated_tree/predecessorfrom --receipt when given.--json: JSON only on stdout.@@ -76,6 +79,19 @@ function cmdWrite(rest: string[], json: boolean): number {const r = spawnSync(path.join(path.dirname(Bun.fileURLToPath(import.meta.url)), 'gstack-session-kind'), [], { encoding: 'utf8', timeout: 15_000 });sessionKind = r.status === 0 ? r.stdout.trim() || undefined : undefined;}+ let pregate: { pregate: string; requires_remote?: string[] } | undefined;+ const pregateFile = flag(rest, '--pregate');+ if (pregateFile) {+ const read = readPregateFile(pregateFile);+ if (!read.file) {+ for (const e of read.errors) process.stderr.write(resultLine('gstack-ship-receipt write', e.code, `${e.message} at ${e.path}`) + '\n');+ return EXIT.fail;+ }+ const v = verifyPregate(repoRoot, read.file);+ if (!v.ok) { process.stderr.write(resultLine('gstack-ship-receipt write', v.code!, `${v.message}; nothing written`) + '\n'); return EXIT.fail; }+ const remote = read.file.requires_remote ?? [];+ pregate = { pregate: `${read.file.verdict ?? 'pass'} @${read.file.tree.slice(0, 12)} (${read.file.checks.length} checks, current for ${head.slice(0, 12)})`, requires_remote: remote.length ? remote.map(r => `${r.lane}: ${r.receipt}`) : undefined };+ }let input: Partial<ShipReceipt>;try {input = {@@ -87,6 +103,7 @@ function cmdWrite(rest: string[], json: boolean): number {spend_usd: flag(rest, '--spend-usd') !== undefined ? (Number.isFinite(Number(flag(rest, '--spend-usd'))) ? Number(flag(rest, '--spend-usd')) : flag(rest, '--spend-usd')) : undefined,session_kind: sessionKind, artifacts_consumed: flag(rest, '--artifacts-consumed'), run: flag(rest, '--run'), thread: flag(rest, '--thread'),policy: flag(rest, '--policy') ?? tree?.policy, queue_mode: flag(rest, '--queue-mode'), preregistration: flag(rest, '--preregistration'), history: flag(rest, '--history'),+ ...pregate, issues: jsonArg(flag(rest, '--issues')) as ShipReceipt['issues'],};} catch (e: any) { process.stderr.write(`gstack-ship-receipt write: ${e.message}\n`); return EXIT.usage; }if (input.pr !== undefined && !Number.isInteger(input.pr)) { process.stderr.write('gstack-ship-receipt write: --pr must be an integer\n'); return EXIT.usage; }diff --git a/docs/pregate.md b/docs/pregate.mdnew file mode 100644index 000000000..ebd2fd700--- /dev/null+++ b/docs/pregate.md@@ -0,0 +1,140 @@+# The pre-gate: generated files, cheap checks, issue links++`/ship` Step 5 opens with `gstack-pregate`: the free checks that catch what the+multi-agent wave kept paying remote gates to find (stale generated files, a+scratch script at the repo root, a nightly-only test still asserting an old+constant, a Windows-only change merged with its lane unrun, a `| tail`-hidden+failure). Plan: `docs/designs/MULTI_AGENT_WAVE_2026_10_10.md` C4, C6, C8.+Result codes: [docs/troubleshooting.md](troubleshooting.md#pre-gate-generated-file-registry-gstack-pregate-issue-links).++Three bins, all over `lib/`:++| Bin | Pin file (read from `origin/<base>`) | Does |+|---|---|---|+| `gstack-regen` | `.gstack/generated.json` | generated files regenerate, never hand-merge |+| `gstack-pregate` | `.gstack/pregate.json` | two-stage cheap gate, `pregate.json` record, publication check |+| `gstack-issue-links` | — | `Fixes #N` only on explicit closure intent |++## Trust boundary++A pin file names commands. Its presence never authorizes execution: both tools+read the committed copy on `origin/<base>` (a PR cannot smuggle a command into+its own gate) and run commands only with `--allow-repo-commands`, which `/ship`+passes. Standalone, `gstack-regen check` lists the commands and exits 3+(`REPO_COMMANDS_NOT_ALLOWED`); `gstack-pregate` marks `regen` and `lanes`+`incomplete`, never `pass`. `--policy-from head` (a PR that introduces or+changes a pin file) is accepted only with `--allow-repo-commands` and the record+says `policy head (unreviewed)`. An unresolvable base exits 3 with+`POLICY_SOURCE_UNAVAILABLE`. Globs are repo-relative (no `..`, no absolute+paths, at most 64 per list); commands are one line under 512 bytes.++<a id="generated"></a>+## `.gstack/generated.json` (generated-v1)++```json+{ "$schema": "https://github.com/garrytan/gstack/docs/pregate.md#generated-v1",+ "entries": [ { "id": "skill-docs", "command": "bun run gen:skill-docs --host all",+ "outputs": ["*/SKILL.md", "*/sections/*.md"], "inputs": ["*/SKILL.md.tmpl", "hosts/**"] } ] }+```++- `gstack-regen check` regenerates every entry (or `--only <id>`, or `--touched+ <paths>` for entries whose inputs or outputs intersect) in a scratch+ `git worktree` seeded from the working tree, with `node_modules` linked rather+ than copied, and reports stale outputs (`REGEN_STALE`, exit 1) without touching+ the tree. An entry with no `command` is tracked only (goldens regenerated by+ another entry).+- `gstack-regen write` regenerates in place: what `gstack-restamp` and the+ Step 3 conflict rule use. On a conflict in a registered output, take either+ side, then `gstack-regen write`; the agent never hand-merges a generated file.+- `list`, `validate`, `init [--explain] [--force]`.++gstack's entries: `skill-docs` (every host render, the agents digest, llms.txt,+the doctor component table) and `ship-goldens` (`bun scripts/gen-ship-goldens.ts`,+the byte-pinned `/ship` renders in `test/fixtures/golden/`).++<a id="pregate-v1"></a>+## `.gstack/pregate.json` (pregate-v1)++| Key | Meaning |+|---|---|+| `runner` | the local test command with `{files}` (gstack: `bun test {files}`); without it `lanes` is `incomplete` |+| `dependencies` | glob → test files for subprocess targets, runtime reads and generated inputs the import graph cannot see; `[]` declares "no lane needed" (docs, licences) |+| `selection` | `workflow.yml/job` → a command printing the lane's file list, for matrices a planner computes (gstack: `scripts/test-free-shards.ts --list`) |+| `warn` | check ids downgraded to warn; `secrets` and required lanes never |+| `strays.allow` | intentional root files or new top-level directories |++Only the `origin/<base>` copy is honoured, so a downgrade is reviewed before it+takes effect. `gstack-pregate validate` / `init` cover the working-tree file.++## `gstack-pregate`++```+gstack-pregate [--stage preflight|tests|all] [--only <check,..>] [--allow-repo-commands] [--policy-from base|head] [--explain] [--json]+gstack-pregate verify | clear --remote <workflow.yml/job> --run-url <url> | lanes | validate | init+```++Two stages with separate clocks, both printed:++**Stage 1, mechanical preflight** (the two-minute promise; gstack measured+~2.5 s for `regen` and under 200 ms for each of the others):++- `regen`: every registry entry whose inputs or outputs are touched is fresh+ (`gstack-regen check` in a scratch worktree).+- `secrets`: `gstack-redact` over the branch's added lines (merge-base to the+ working tree, untracked files included). HIGH, or MEDIUM in the `secret`+ category, fails; other MEDIUM findings warn. Cannot be downgraded.+- `strays`: a new file at the repository root, a new top-level directory, or a+ scratch name (`zz-*`, `tmp*`, `scratch*`) anywhere.+- `literals`: for every changed exported constant or named timeout/retry+ literal, the whole test tree (nightly- and Heavy-only files included) is+ searched for the old value; a consumer the branch did not update fails with+ `file:line`.++**Stage 2, test execution:**++- `lanes`: touched files map to tests through `lib/pregate/import-graph.ts`+ (static imports ∪ repo-path string literals ∪ the `bin/<name>` →+ `test/<name>*.test.ts` convention ∪ `dependencies`), transitively through+ non-test files; deleted and renamed files select the tests that named them.+ A touched file with no lane is `FAIL lanes — <file> has no test lane`, never+ a pass. Lanes and platform tiers come from `.github/workflows/*.yml`+ (`gstack-pregate lanes` prints them): local ones run through the runner under+ `set -o pipefail`, judged on the runner's summary line (zero tests ran is a+ failure, a `| tail`-hidden exit is still an exit); a platform lane this+ machine cannot run becomes a `requires-remote` obligation naming+ `workflow.yml/job`. `--explain` prints each test's provenance and every+ uncertain mapping (a planner-computed matrix without a `selection` manifest+ selects conservatively).++Every check records the input identity it ran against (the working-tree+fingerprint before and after, the selection, the command hash); a tree that+moved during a check, a timeout or a missing tool is `incomplete`, never `pass`.+The record is `.gstack/tmp/pregate.json` (`gstack-artifact validate --as pregate`).++**Publication.** `gstack-ship-receipt write --pregate .gstack/tmp/pregate.json`+(Step 18) refuses unless the record is current for the tree being published+(`PREGATE_STALE`: rerun after the final stamp), green (`PREGATE_LANE_FAILED`,+`PREGATE_INCOMPLETE`) and every `requires-remote` obligation carries a receipt+(`PREGATE_REMOTE_UNCLEARED`: dispatch the job, then+`gstack-pregate clear --remote <workflow.yml/job> --run-url <url>`). The ship+receipt then carries `pregate` and `requires_remote`. `gstack-pregate verify`+runs the same check standalone.++Tier 2 checks (`guards`, `ratchets`, `lint`, `links`, `hermetic`, `patches`,+`integrator`) are named in `--only`'s help and land in a follow-up pre-gate PR.++<a id="issue-links"></a>+## `gstack-issue-links`++```+gstack-issue-links [--base <ref>] [--issue <n>]... [--ci-run <id>]... [--out issues.json] [--json]+```++Reads `origin/<base>..HEAD`. `Fixes #N` only on explicit closure intent: a+`Fixes`/`Closes`/`Resolves #N` trailer line or `--issue N`. A bare mention, a+partial fix, a deferred ask and every cross-repo `owner/repo#N` are `Refs`. Each+closure issue is read through `gstack-issue-guard`; one that cannot be read is+`Refs #N (unreadable …)` with `ISSUE_UNREADABLE` (exit 1), never `Fixes`. Each+`--ci-run <id>` is searched among open issues whose body names it and rendered+`Flake: #N (run <id>)`. The printed lines go under `## Issues` in the PR body;+`--out` writes the object `gstack-ship-receipt write --issues @file` embeds.diff --git a/docs/troubleshooting.md b/docs/troubleshooting.mdindex b52bd4b2a..e2178b8ad 100644--- a/docs/troubleshooting.md+++ b/docs/troubleshooting.md@@ -1934,3 +1934,140 @@ runner, this is missing coverage.(unattended machines); or set the API key and pass `--runner api`; or run thereview on a cross-family subagent and submit its file with `--runnerhost-subagent --result <file> --model <id>`.++## Pre-gate: generated-file registry, gstack-pregate, issue links++Both tools read their pin file (`.gstack/generated.json`, `.gstack/pregate.json`)+from `origin/<base>`, never the working tree, and run repo-declared commands only+under `--allow-repo-commands` or inside `/ship`. Details: docs/pregate.md.++<a id="regen-registry-invalid"></a>+### `REGEN_REGISTRY_INVALID`++**Meaning.** `.gstack/generated.json` is not valid JSON, has an unknown key, a+missing `id`/`inputs`/`outputs`, or a duplicate id.++**Fix.** `gstack-regen validate` prints every error with its JSON path; compare+with `gstack-regen init --explain` and fix the file on the base branch.++<a id="regen-containment"></a>+### `REGEN_CONTAINMENT`++**Meaning.** A registry glob escapes the repository (`..`, absolute, more than 64+per list) or a command is not one line under 512 bytes.++**Fix.** Repo-relative globs only; one line per command.++<a id="regen-stale"></a>+### `REGEN_STALE`++**Meaning.** A registered output differs from what its command produces in a+scratch `git worktree` of the current tree: the output is stale or hand-edited.++**Fix.** Run the printed command (`gstack-regen write --only <id>` does it in+place) and commit the outputs. Never hand-merge a generated file: on a conflict+take either side, then regenerate.++<a id="regen-command-failed"></a>+### `REGEN_COMMAND_FAILED`++**Meaning.** A registered command exited non-zero in the scratch worktree.++**Fix.** Run it by hand in the repository and read its output; the scratch+worktree has no `node_modules` of its own, so a command that needs them must+reference the repository's (gstack's entries do through `bun run`).++<a id="pregate-config-invalid"></a>+### `PREGATE_CONFIG_INVALID`++**Meaning.** `.gstack/pregate.json` has an unknown key, a wrong type, a glob+that escapes the repository, a runner without `{files}`, or `secrets` in `warn`.++**Fix.** `gstack-pregate validate`. `secrets` and required-lane obligations+cannot be downgraded; every other check id in `warn` is honoured only from the+base branch's copy.++<a id="pregate-secrets"></a>+### `PREGATE_SECRETS`++**Meaning.** `gstack-redact` found a HIGH finding, or a MEDIUM finding in the+`secret` category, in the lines this branch adds.++**Fix.** Rotate the credential, remove it from the added lines (history+included), rerun. Not downgradable.++<a id="pregate-strays"></a>+### `PREGATE_STRAYS`++**Meaning.** A file was added at the repository root, in a new top-level+directory, or under a scratch name (`zz-*`, `tmp*`, `scratch*`).++**Fix.** Delete or move it. An intentional root file goes in `strays.allow`.++<a id="pregate-literals"></a>+### `PREGATE_LITERALS`++**Meaning.** A changed exported constant (or a named timeout/retry literal) still+appears with its old value in a test file the branch did not update — nightly-+and Heavy-only files included.++**Fix.** Update every listed `file:line`, or keep the old value.++<a id="pregate-no-lane"></a>+### `PREGATE_NO_LANE`++**Meaning.** A touched file maps to no test through static imports, repo-path+string literals, the `bin/<name>` → `test/<name>*.test.ts` convention or a+`dependencies` declaration. That is a failure, not a pass.++**Fix.** Add a test that names the file, or declare its lane (an explicit `[]`+for files with no behaviour, such as docs) in `.gstack/pregate.json`. `--explain`+prints every mapping and why.++<a id="pregate-lane-failed"></a>+### `PREGATE_LANE_FAILED`++**Meaning.** A local lane the touched files select exited non-zero under+`set -o pipefail`, or reported zero tests (ZERO-RUN).++**Fix.** Read the printed lane log, fix the failure, rerun+`gstack-pregate --stage tests`. A `| tail`-hidden exit is still an exit.++<a id="pregate-incomplete"></a>+### `PREGATE_INCOMPLETE`++**Meaning.** A check timed out, its tool is unavailable, repo commands were not+allowed, or the working tree changed while the check ran. Incomplete is never+pass and blocks publication.++**Fix.** Pass `--allow-repo-commands`, install the tool, raise `--timeout`, or+keep the tree still, then rerun.++<a id="pregate-stale"></a>+### `PREGATE_STALE`++**Meaning.** `pregate.json` was recorded against a different working-tree+fingerprint than the one being published (the final stamp, a regen, any edit).++**Fix.** Rerun `gstack-pregate` after the final generation and stamp; Step 18+refuses to write the ship receipt otherwise.++<a id="pregate-remote-uncleared"></a>+### `PREGATE_REMOTE_UNCLEARED`++**Meaning.** A `requires-remote` obligation (a platform lane this machine cannot+run, named by `workflow.yml/job`) has no receipt.++**Fix.** Dispatch that job, then+`gstack-pregate clear --remote <workflow.yml/job> --run-url <url>` (or+`--bundle-lane <label>` from an evidence bundle). The ship receipt carries each+obligation with its receipt.++<a id="issue-unreadable"></a>+### `ISSUE_UNREADABLE`++**Meaning.** An issue named by a `Fixes #N`/`Closes #N` trailer or `--issue N`+could not be read through `gstack-issue-guard`.++**Fix.** Check `gh auth status` and the number. Until it reads, the link is+rendered as `Refs #N`, never `Fixes`.diff --git a/lib/headless-artifacts.ts b/lib/headless-artifacts.tsindex 2c0cd2362..772775245 100644--- a/lib/headless-artifacts.ts+++ b/lib/headless-artifacts.ts@@ -58,14 +58,27 @@ export interface RunManifest {base?: string; host?: string; session_kind?: string; gate_rev?: number; gate?: Record<string, unknown>;consumed_by?: Array<{ consumer: string; at: string }>; deviations?: string[]; [extra: string]: unknown;}-export interface PregateCheck { id: string; status: 'pass' | 'fail' | 'warn' | 'incomplete' | 'requires-remote' | 'not_installed'; ms?: number; detail?: string }-export interface PregateFile { schema_version: 1; tree: string; checks: PregateCheck[]; run?: string; stage1_ms?: number; stage2_ms?: number }+export interface PregateCheck {+ id: string; status: 'pass' | 'fail' | 'warn' | 'incomplete' | 'requires-remote' | 'not_installed'; ms?: number; detail?: string;+ // C-pregate (C8): stage, the input identity the check ran against, the fix clause and result code, and per-item lines.+ stage?: 'preflight' | 'tests'; inputs?: Record<string, string>; fix?: string; code?: string; lines?: string[];+}+export interface PregateRemote { lane: string; platform: string; workflow: string; job: string; tests: string[]; receipt: string | null; cleared_by?: string }+export interface PregateFile {+ schema_version: 1; tree: string; checks: PregateCheck[]; run?: string; stage1_ms?: number; stage2_ms?: number;+ // C-pregate (C8): head/base identity, the policy sources, persisted requires-remote obligations and the one-line verdict.+ head?: string; base?: string; generated_at?: string; policy?: string; registry?: string; requires_remote?: PregateRemote[]; verdict?: string;+}export interface ShipReceipt {schema_version: 1; head: string; base: string; pr?: number; version?: string; gated_tree?: string;gate?: Record<string, unknown>; ci?: Record<string, unknown>; spend_usd?: number | string; predecessor?: string;session_kind?: string; artifacts_consumed?: string; run?: string;// C-stamp (C3/C5/C7): the tree receipt's verdicts and the policy provenance, all optional.thread?: string; tree?: string; gate_reuse?: string; policy?: string; queue_mode?: string; preregistration?: string; history?: string;+ // C-pregate (C8): the pre-gate's verdict against this head and its remote obligations (publication requires their receipts).+ pregate?: string; requires_remote?: string[];+ // C-pregate (C6): issue links the body carries, by intent.+ issues?: { fixes: number[]; refs: number[]; flakes: Array<{ issue: number; run: string }> };}export const RESULT_STATUSES: readonly ResultStatus[] = ['complete', 'gate_pending', 'incomplete', 'interrupted', 'refused'];@@ -165,7 +178,9 @@ export const ARTIFACT_SCHEMAS = {type: 'object', required: ['schema_version', 'tree', 'checks'],properties: {schema_version: { const: 1 }, run: str, tree: str, stage1_ms: num, stage2_ms: num,- checks: { type: 'array', items: { type: 'object', required: ['id', 'status'], properties: { id: str, status: { enum: ['pass', 'fail', 'warn', 'incomplete', 'requires-remote', 'not_installed'] }, ms: num, detail: str } } },+ checks: { type: 'array', items: { type: 'object', required: ['id', 'status'], properties: { id: str, status: { enum: ['pass', 'fail', 'warn', 'incomplete', 'requires-remote', 'not_installed'] }, ms: num, detail: str, stage: { enum: ['preflight', 'tests'] }, inputs: { type: 'object' }, fix: str, code: str, lines: strList } } },+ head: str, base: str, generated_at: str, policy: str, registry: str, verdict: str,+ requires_remote: { type: 'array', items: { type: 'object', required: ['lane', 'platform', 'tests', 'receipt'], properties: { lane: str, platform: str, workflow: str, job: str, tests: strList, receipt: nullableStr, cleared_by: str } } },},},'ship-receipt': {@@ -175,6 +190,8 @@ export const ARTIFACT_SCHEMAS = {gate: { type: 'object' }, ci: { type: 'object' }, spend_usd: { type: ['number', 'string'] }, predecessor: str,session_kind: str, artifacts_consumed: { ...str, description: '<n>/<m>' }, run: str,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,+ 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 } } } } },},},} as const satisfies Record<string, Schema>;diff --git a/lib/issue-links.ts b/lib/issue-links.tsnew file mode 100644index 000000000..df71ba4f1--- /dev/null+++ b/lib/issue-links.ts@@ -0,0 +1,76 @@+/**+ * Issue links for /ship Step 18 (plan C6). Pure classification over commit+ * messages and explicit flags; the bin (bin/gstack-issue-links) owns the+ * gh / gstack-issue-guard calls.+ *+ * Intent rules:+ * - `Fixes #N` is written only on explicit closure intent: a `Fixes|Closes|+ * Resolves #N` trailer line in a commit of the branch, or `--issue N`.+ * - A bare `#N` mention, a `Refs|See|Part of|Partially fixes|Related` line, a+ * deferred ask (`defer`, `follow-up`) and every cross-repo id+ * (`owner/repo#N`) are `Refs #N` — never auto-closed.+ * - A closure issue that cannot be read through gstack-issue-guard is+ * downgraded to `Refs #N` with ISSUE_UNREADABLE (never Fixes).+ * - Failing CI run ids map to bot-opened flake issues whose body names the+ * run id: `Flake: #N (run <id>)`.+ */++export type IssueIntent = 'fixes' | 'refs';+export interface IssueMention { issue: number; intent: IssueIntent; repo?: string; source: string }+export interface IssueLinks { fixes: number[]; refs: number[]; flakes: Array<{ issue: number; run: string }>; cross: string[]; unreadable: number[] }++const CLOSURE = /^\s*(?:fix(?:es|ed)?|close[sd]?|resolve[sd]?)\s*:?\s+(?:#|GH-)(\d+)\s*$/i;+const PARTIAL = /\b(?:partial(?:ly)?|part of|defer(?:red)?|follow-?up|related|refs?|see|context)\b/i;+const CROSS = /\b([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+)#(\d+)\b/g;+const BARE = /(?<![A-Za-z0-9_./-])#(\d+)\b/g;++/** Mentions in one commit message: trailer lines carry closure intent, everything else is a reference. */+export function mentionsIn(message: string, source = 'commit'): IssueMention[] {+ const out: IssueMention[] = [];+ const seen = new Set<string>();+ const add = (m: IssueMention) => { const k = `${m.repo ?? ''}#${m.issue}:${m.intent}`; if (!seen.has(k)) { seen.add(k); out.push(m); } };+ for (const raw of message.split('\n')) {+ const line = raw.replace(/\s+$/, '');+ const trailer = CLOSURE.exec(line);+ if (trailer && !PARTIAL.test(line)) { add({ issue: Number(trailer[1]), intent: 'fixes', source: `${source}: ${line.trim()}` }); continue; }+ for (const c of line.matchAll(CROSS)) add({ issue: Number(c[2]), intent: 'refs', repo: c[1], source: `${source}: ${line.trim()}` });+ const stripped = line.replace(CROSS, '');+ for (const b of stripped.matchAll(BARE)) add({ issue: Number(b[1]), intent: 'refs', source: `${source}: ${line.trim()}` });+ }+ return out;+}++/**+ * Resolve the final link set. `readable(n)` is the gstack-issue-guard probe+ * for a closure candidate; a false answer downgrades it to Refs.+ */+export function resolveLinks(mentions: IssueMention[], explicit: number[], readable: (issue: number) => boolean, flakes: Array<{ issue: number; run: string }> = []): IssueLinks {+ const fixes = new Set<number>(explicit);+ const refs = new Set<number>();+ const cross = new Set<string>();+ for (const m of mentions) {+ if (m.repo) { cross.add(`${m.repo}#${m.issue}`); continue; }+ if (m.intent === 'fixes') fixes.add(m.issue); else refs.add(m.issue);+ }+ const unreadable: number[] = [];+ for (const n of [...fixes]) if (!readable(n)) { fixes.delete(n); refs.add(n); unreadable.push(n); }+ for (const n of fixes) refs.delete(n);+ for (const f of flakes) refs.delete(f.issue);+ const asc = (a: number, b: number) => a - b;+ return { fixes: [...fixes].sort(asc), refs: [...refs].sort(asc), flakes: [...flakes].sort((a, b) => a.issue - b.issue), cross: [...cross].sort(), unreadable: unreadable.sort(asc) };+}++/** The `## Issues` lines for the PR body; an empty set renders nothing. */+export function renderIssueLines(links: IssueLinks): string[] {+ const lines: string[] = [];+ for (const n of links.fixes) lines.push(`Fixes #${n}`);+ for (const n of links.refs) lines.push(links.unreadable.includes(n) ? `Refs #${n} (unreadable through gstack-issue-guard; not auto-closed)` : `Refs #${n}`);+ for (const c of links.cross) lines.push(`Refs ${c}`);+ for (const f of links.flakes) lines.push(`Flake: #${f.issue} (run ${f.run})`);+ return lines;+}++/** The receipt's `issues` field (lib/headless-artifacts.ts ship-receipt schema). */+export function receiptIssues(links: IssueLinks): { fixes: number[]; refs: number[]; flakes: Array<{ issue: number; run: string }> } {+ return { fixes: links.fixes, refs: links.refs, flakes: links.flakes };+}diff --git a/lib/pregate/checks/lanes.ts b/lib/pregate/checks/lanes.tsnew file mode 100644index 000000000..e40849516--- /dev/null+++ b/lib/pregate/checks/lanes.ts@@ -0,0 +1,93 @@+/**+ * pregate check `lanes` (tier 1, tests stage): the touched files map to test+ * files (lib/pregate/lane-selection.ts); the local ones run under+ * `set -o pipefail` with the exit code and the runner's own summary judged+ * (zero tests ran is a failure, exit 0 or not); platform lanes this machine+ * cannot run become persisted `requires-remote` obligations. A touched file+ * with no lane is `FAIL lanes — <file> has no test lane`, never a pass.+ * Incidents: p0-4-pipe-hidden-failure (`false | tail` read as green),+ * p0-4-windows-lane-unrun (a Windows-only change merged with its lane unrun).+ */+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 { baseInputs, sha256 } from '../context';+import { selectLanes, type Selection } from '../lane-selection';+import type { CheckDef, CheckResult, PregateContext } from '../types';++/** The test command with `{files}`; detected from the repo when the config does not name one. */+export function detectRunner(ctx: PregateContext, files: readonly string[]): string | null {+ if (ctx.config.runner) return ctx.config.runner;+ const has = (f: string) => fs.existsSync(path.join(ctx.repoRoot, f));+ let pkg: { devDependencies?: Record<string, string>; dependencies?: Record<string, string>; scripts?: Record<string, string> } = {};+ try { pkg = JSON.parse(fs.readFileSync(path.join(ctx.repoRoot, 'package.json'), 'utf8')); } catch { /* no package.json */ }+ const deps = { ...pkg.dependencies, ...pkg.devDependencies };+ if (has('bunfig.toml') || has('bun.lock') || has('bun.lockb')) return 'bun test {files}';+ if (deps.vitest) return 'npx vitest run {files}';+ if (deps.jest) return 'npx jest {files}';+ if (files.every(f => /\.py$/.test(f)) && files.length) return 'python3 -m pytest {files}';+ if (files.every(f => /\.[cm]?js$/.test(f)) && files.length) return 'node --test {files}';+ if (files.every(f => /\.[cm]?[jt]sx?$/.test(f)) && files.length && Bun.which('bun')) return 'bun test {files}';+ return null;+}++export interface RunnerSummary { ran: number | null; failed: number | null }++/** The runner's own summary line: bun, node --test, vitest, jest, pytest. null when not recognised. */+export function parseSummary(output: string): RunnerSummary {+ let m: RegExpExecArray | null;+ if ((m = /^\s*(?:#|ℹ)\s*tests\s+(\d+)/m.exec(output))) return { ran: Number(m[1]), failed: Number(/^\s*(?:#|ℹ)\s*fail\s+(\d+)/m.exec(output)?.[1] ?? 0) };+ if ((m = /Ran\s+(\d+)\s+tests?\s+across/m.exec(output))) return { ran: Number(m[1]), failed: Number(/^\s*(\d+)\s+fail\b/m.exec(output)?.[1] ?? 0) };+ if ((m = /^\s*(\d+)\s+pass\s*$/m.exec(output))) return { ran: Number(m[1]) + Number(/^\s*(\d+)\s+fail\s*$/m.exec(output)?.[1] ?? 0), failed: Number(/^\s*(\d+)\s+fail\s*$/m.exec(output)?.[1] ?? 0) };+ if ((m = /Tests:\s+(?:(\d+)\s+failed,\s+)?(?:(\d+)\s+passed,\s+)?(\d+)\s+total/.exec(output))) return { ran: Number(m[3]), failed: Number(m[1] ?? 0) };+ if ((m = /Tests\s+(?:(\d+)\s+failed\s*\|\s*)?(\d+)\s+passed/.exec(output))) return { ran: Number(m[2]) + Number(m[1] ?? 0), failed: Number(m[1] ?? 0) };+ if (/no tests ran/.test(output) || /No tests found/i.test(output)) return { ran: 0, failed: 0 };+ if ((m = /(?:(\d+)\s+failed,?\s*)?(\d+)\s+passed/.exec(output))) return { ran: Number(m[2]) + Number(m[1] ?? 0), failed: Number(m[1] ?? 0) };+ return { ran: null, failed: null };+}++function runLocal(ctx: PregateContext, runner: string, files: string[]): { exit: number | null; ran: number | null; failed: number | null; log: string; tail: string[]; command: string } {+ const command = runner.replace('{files}', files.map(f => `'${f.replace(/'/g, `'\\''`)}'`).join(' '));+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-pregate-lanes-'));+ const log = path.join(dir, 'lanes.log');+ const r = spawnSync('bash', ['-c', `set -o pipefail; ${command}`], { cwd: ctx.repoRoot, encoding: 'utf8', timeout: ctx.timeoutMs, maxBuffer: 256 * 1024 * 1024, env: { ...ctx.env, CI: ctx.env.CI ?? '1' } });+ const output = `${r.stdout ?? ''}\n${r.stderr ?? ''}`;+ fs.writeFileSync(log, `$ ${command}\n${output}`);+ const summary = parseSummary(output);+ return { exit: r.status, ...summary, log, tail: output.trim().split('\n').slice(-25), command };+}++function describe(sel: Selection): string[] {+ const lines = sel.noLane.map(f => `FAIL lanes — ${f} has no test lane`);+ for (const r of sel.remote) lines.push(`requires-remote ${r.lane} (${r.platform}): ${r.tests.length} test(s) — ${r.tests.slice(0, 8).join(' ')}${r.tests.length > 8 ? ' …' : ''}`);+ lines.push(`Tiers ran: ${sel.tiersRan.join(' ') || '(none)'}; requires-remote: ${[...new Set(sel.remote.map(r => r.platform))].join(' ') || 'none'}`);+ return lines;+}++function run(ctx: PregateContext): CheckResult {+ const sel = selectLanes(ctx);+ ctx.explain.push(...sel.provenance);+ for (const [lane, set] of Object.entries(sel.laneSets)) ctx.explain.push(`lane ${lane}: ${set === '?' ? 'file set unknown' : `${set.length} files`}`);+ const inputs = baseInputs(ctx, { selection: sha256(sel.tests.join('\n')), localTests: sha256(sel.localTests.join('\n')), remote: sha256(sel.remote.map(r => `${r.lane}:${r.tests.join(',')}`).join('\n')) });+ const lines = describe(sel);+ const base: CheckResult = { id: 'lanes', stage: 'tests', status: 'pass', inputs, lines, remote: sel.remote };+ if (sel.noLane.length) {+ return { ...base, status: 'fail', code: 'PREGATE_NO_LANE', detail: `${sel.noLane.length} touched file(s) with no test lane: ${sel.noLane.join(' ')}`, fix: 'add a test that names the file, or declare its lane (or []) under dependencies in .gstack/pregate.json' };+ }+ if (sel.tests.length === 0) return { ...base, detail: ctx.touched.length ? 'nothing touched selects a test' : 'no touched files' };+ if (!ctx.allowRepoCommands) return { ...base, status: 'incomplete', code: 'REPO_COMMANDS_NOT_ALLOWED', detail: `${sel.localTests.length} local test file(s) selected but not run (pass --allow-repo-commands)`, fix: 'rerun with --allow-repo-commands (what /ship passes)' };+ if (sel.localTests.length === 0) return { ...base, status: sel.remote.length ? 'requires-remote' : 'pass', detail: `no local lane; ${sel.remote.length} requires-remote obligation(s)` };+ const runner = detectRunner(ctx, sel.localTests);+ if (!runner) return { ...base, status: 'incomplete', code: 'PREGATE_INCOMPLETE', detail: `no test runner detected for ${sel.localTests.length} selected file(s)`, fix: 'declare `runner` (with {files}) in .gstack/pregate.json' };+ const r = runLocal(ctx, runner, sel.localTests);+ const runLines = [...lines, `ran: ${r.command.length > 200 ? `${r.command.slice(0, 200)}…` : r.command}`, `log: ${r.log}`, ...r.tail.map(l => ` ${l}`)];+ const withRun = { ...base, lines: runLines, inputs: { ...inputs, command: sha256(r.command) } };+ if (r.exit === null) return { ...withRun, status: 'incomplete', code: 'PREGATE_INCOMPLETE', detail: `local lane timed out after ${ctx.timeoutMs} ms (${sel.localTests.length} files)`, fix: 'raise --timeout or split the selection; a timed-out lane never passes' };+ if (r.exit !== 0) return { ...withRun, status: 'fail', code: 'PREGATE_LANE_FAILED', detail: `local lane exited ${r.exit} (${r.failed ?? '?'} failed of ${r.ran ?? '?'} ran; ${sel.localTests.length} files; pipefail)`, fix: `read ${r.log}, fix the in-branch failure, rerun gstack-pregate --stage tests` };+ if (r.ran === 0) return { ...withRun, status: 'fail', code: 'PREGATE_LANE_FAILED', detail: `ZERO-RUN: the runner reported 0 tests for ${sel.localTests.length} selected file(s)`, fix: 'a bad selector, a missing file or a skipped describe; exit 0 is not a pass' };+ const detail = `${r.ran ?? 'count unavailable'} tests ran in ${sel.localTests.length} file(s), exit 0${sel.remote.length ? `; ${sel.remote.length} requires-remote obligation(s)` : ''}`;+ return { ...withRun, status: sel.remote.length ? 'requires-remote' : 'pass', detail };+}++export const lanesCheck: CheckDef = { id: 'lanes', stage: 'tests', tier: 1, downgradable: true, needsRepoCommands: true, run };diff --git a/lib/pregate/checks/literals.ts b/lib/pregate/checks/literals.tsnew file mode 100644index 000000000..bca67b438--- /dev/null+++ b/lib/pregate/checks/literals.ts@@ -0,0 +1,102 @@+/**+ * pregate check `literals` (tier 1, preflight): for every exported constant,+ * timeout, retry or delay literal the branch changed, grep the whole test+ * tree, nightly-only and Heavy-only files included, for the old value next to+ * the constant's name or its module. Incident p0-4-heavy-old-constant: a+ * nightly-only test still asserted the old number and went red a week after+ * the merge.+ */+import { spawnSync } from 'node:child_process';+import * as fs from 'node:fs';+import * as path from 'node:path';+import { baseInputs, sha256 } from '../context';+import { isTestFile, listRepoFiles, scansLiterals } from '../import-graph';+import type { CheckDef, CheckResult, PregateContext } from '../types';++export interface ChangedLiteral { name: string; old: string; new: string; file: string }++const CONST_PATTERNS: RegExp[] = [+ /^\s*export\s+(?:const|let|var)\s+([A-Z][A-Z0-9_]{1,})\s*(?::\s*[^=]+?)?\s*=\s*(.+?);?\s*$/,+ /^\s*(?:module\.)?exports\.([A-Z][A-Z0-9_]{1,})\s*=\s*(.+?);?\s*$/,+ /^\s*(?:export\s+)?(?:static\s+)?readonly\s+([A-Z][A-Z0-9_]{1,})\s*(?::\s*[^=]+?)?\s*=\s*(.+?);?\s*$/,+ /^([A-Z][A-Z0-9_]{2,})\s*=\s*(.+?)\s*$/,+ /^(?:export\s+|readonly\s+)?([A-Z][A-Z0-9_]{2,})=(\S+)\s*$/,+];+const CALL_PATTERN = /\b(timeout(?:Ms|_ms)?|retries|maxRetries|max_retries|attempts|maxAttempts|delay(?:Ms)?|interval(?:Ms)?|budget|cap|limit)\s*[:=]\s*(\d+(?:_\d+)*)\b/g;+const LITERAL = /^(?:-?\d+(?:_\d+)*(?:\.\d+)?|'[^']*'|"[^"]*"|`[^`$]*`|true|false|null|\[[^\]]*\])$/;++/** `NAME → literal` for one source text; only literal right-hand sides count. */+export function constantsIn(text: string): Map<string, string> {+ const out = new Map<string, string>();+ for (const line of text.split('\n')) {+ for (const re of CONST_PATTERNS) {+ const m = re.exec(line);+ if (!m) continue;+ const value = m[2]!.trim();+ if (LITERAL.test(value)) out.set(m[1]!, value);+ break;+ }+ }+ return out;+}++/** Named numeric call sites (`timeout: 5000`) keyed by name; the last value per name wins, which is enough to spot a change. */+export function callLiteralsIn(text: string): Map<string, string> {+ const out = new Map<string, string>();+ for (const m of text.matchAll(CALL_PATTERN)) out.set(m[1]!, m[2]!);+ return out;+}++export function changedLiterals(file: string, oldText: string, newText: string): ChangedLiteral[] {+ const out: ChangedLiteral[] = [];+ const oldC = constantsIn(oldText); const newC = constantsIn(newText);+ for (const [name, old] of oldC) { const now = newC.get(name); if (now !== undefined && now !== old) out.push({ name, old, new: now, file }); }+ const oldCall = callLiteralsIn(oldText); const newCall = callLiteralsIn(newText);+ for (const [name, old] of oldCall) { const now = newCall.get(name); if (now !== undefined && now !== old && !oldC.has(name)) out.push({ name, old, new: now, file }); }+ return out;+}++function escape(s: string): string { return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); }+function unquote(v: string): string { return /^['"`]/.test(v) ? v.slice(1, -1) : v; }++/** Test files that still carry the old literal beside the constant's name or its module stem. */+export function consumersOf(repoRoot: string, testFiles: readonly string[], change: ChangedLiteral): string[] {+ const value = unquote(change.old);+ const valueRe = /^-?\d/.test(value) ? new RegExp(`(?<![\\w.])${escape(value)}(?![\\w.])`) : new RegExp(`['"\`]${escape(value)}['"\`]`);+ const stem = path.basename(change.file).replace(/\.[^.]+$/, '');+ const nameRe = new RegExp(`\\b${escape(change.name)}\\b`);+ const hits: string[] = [];+ for (const rel of testFiles) {+ let text: string;+ try { text = fs.readFileSync(path.join(repoRoot, rel), 'utf8'); } catch { continue; }+ if (!(nameRe.test(text) || text.includes(stem))) continue;+ const lines = text.split('\n');+ for (let i = 0; i < lines.length; i++) if (valueRe.test(lines[i]!)) { hits.push(`${rel}:${i + 1}`); break; }+ }+ return hits;+}++function run(ctx: PregateContext): CheckResult {+ const candidates = ctx.touched.filter(t => (t.status === 'M' || t.status === 'R') && !isTestFile(t.path) && /\.(?:[cm]?[jt]sx?|py|rb|sh|bash)$/.test(t.path));+ const changes: ChangedLiteral[] = [];+ for (const t of candidates) {+ const old = spawnSync('git', ['show', `${ctx.mergeBase}:${t.renamedFrom ?? t.path}`], { cwd: ctx.repoRoot, encoding: 'utf8', timeout: 30_000, maxBuffer: 64 * 1024 * 1024, env: ctx.env });+ if (old.status !== 0) continue;+ let now = '';+ try { now = fs.readFileSync(path.join(ctx.repoRoot, t.path), 'utf8'); } catch { continue; }+ changes.push(...changedLiterals(t.path, old.stdout, now));+ }+ const inputs = baseInputs(ctx, { changes: sha256(changes.map(c => `${c.file}:${c.name}:${c.old}→${c.new}`).join('\n')) });+ if (!changes.length) return { id: 'literals', stage: 'preflight', status: 'pass', inputs, detail: `no exported constant or named timeout literal changed in ${candidates.length} modified source file(s)` };+ const testFiles = listRepoFiles(ctx.repoRoot).filter(f => scansLiterals(f) && !f.startsWith('bin/'));+ const lines: string[] = [];+ for (const c of changes) {+ const hits = consumersOf(ctx.repoRoot, testFiles, c);+ ctx.explain.push(`literals: ${c.file} ${c.name} ${c.old} → ${c.new}: ${hits.length} test file(s) still carry ${c.old}`);+ for (const h of hits) lines.push(`${h}: ${c.name} still ${c.old} (now ${c.new} in ${c.file})`);+ }+ if (lines.length) return { id: 'literals', stage: 'preflight', status: 'fail', inputs, lines, code: 'PREGATE_LITERALS', detail: `${lines.length} test location(s) still carry an old literal`, fix: 'update each listed test to the new value (nightly- and Heavy-only files included), or keep the old constant' };+ return { id: 'literals', stage: 'preflight', status: 'pass', inputs, detail: `${changes.length} changed literal(s), no test still carries an old value (${testFiles.length} test-tree files scanned)` };+}++export const literalsCheck: CheckDef = { id: 'literals', stage: 'preflight', tier: 1, downgradable: true, needsRepoCommands: false, run };diff --git a/lib/pregate/checks/regen.ts b/lib/pregate/checks/regen.tsnew file mode 100644index 000000000..510512230--- /dev/null+++ b/lib/pregate/checks/regen.ts@@ -0,0 +1,36 @@+/**+ * pregate check `regen` (tier 1, preflight): every `.gstack/generated.json`+ * entry whose inputs or outputs the branch touched is regenerated in a+ * scratch git worktree (lib/regen.ts) and compared with the working tree.+ * Incident p0-4-stale-goldens: a template changed, the committed render and+ * the golden did not, and the remote gate failed an hour later.+ */+import { renderEntry, runRegen, selectEntries } from '../../regen';+import { baseInputs } from '../context';+import type { CheckDef, CheckResult, PregateContext } from '../types';++function run(ctx: PregateContext): CheckResult {+ const inputs = baseInputs(ctx, { registry: ctx.registryLabel });+ const touched = ctx.touched.map(t => t.path).concat(ctx.touched.flatMap(t => (t.renamedFrom ? [t.renamedFrom] : [])));+ const selected = selectEntries(ctx.registry, touched);+ if (ctx.registry.entries.length === 0) return { id: 'regen', stage: 'preflight', status: 'pass', detail: `no ${ctx.registryLabel.includes('(no ') ? 'registry' : 'entries'} (${ctx.registryLabel})`, inputs };+ if (selected.length === 0) return { id: 'regen', stage: 'preflight', status: 'pass', detail: `no registered input or output touched (${ctx.registry.entries.length} entries)`, inputs };+ const commands = selected.filter(e => e.command);+ if (commands.length && !ctx.allowRepoCommands) {+ return {+ id: 'regen', stage: 'preflight', status: 'incomplete', inputs, code: 'REPO_COMMANDS_NOT_ALLOWED',+ detail: `repo commands not executed (pass --allow-repo-commands): ${commands.map(c => `${c.id}: ${c.command}`).join('; ')}`,+ fix: 'rerun with --allow-repo-commands (what /ship passes)', lines: commands.map(c => `COMMAND: ${c.id}=${JSON.stringify(c.command)} outputs=${c.outputs.join(',')}`),+ };+ }+ const { results } = runRegen({ repoRoot: ctx.repoRoot, registry: ctx.registry, mode: 'check', only: selected.map(e => e.id), env: ctx.env, timeoutMs: ctx.timeoutMs });+ const lines = results.map(renderEntry);+ const stale = results.filter(r => r.status === 'stale');+ const failed = results.filter(r => r.status === 'failed');+ ctx.explain.push(...results.map(r => `regen ${r.id}: selected because touched ∩ (${selected.find(e => e.id === r.id)?.inputs.join(',') || 'always'} ∪ outputs) ≠ ∅`));+ if (failed.length) return { id: 'regen', stage: 'preflight', status: 'incomplete', inputs, lines, code: 'REGEN_COMMAND_FAILED', detail: `${failed.length} regen command(s) failed: ${failed.map(f => f.id).join(', ')}`, fix: failed.map(f => f.fix).join('; ') };+ if (stale.length) return { id: 'regen', stage: 'preflight', status: 'fail', inputs, lines, code: 'REGEN_STALE', detail: `${stale.length} stale: ${stale.flatMap(s => s.changed.concat(s.outside)).join(' ')}`, fix: stale.map(s => s.fix).join('; ') };+ return { id: 'regen', stage: 'preflight', status: 'pass', inputs, lines, detail: `${results.length} entr${results.length === 1 ? 'y' : 'ies'} fresh${results.some(r => r.status === 'listed') ? ' (hand-regenerated outputs listed)' : ''}` };+}++export const regenCheck: CheckDef = { id: 'regen', stage: 'preflight', tier: 1, downgradable: true, needsRepoCommands: true, run };diff --git a/lib/pregate/checks/secrets.ts b/lib/pregate/checks/secrets.tsnew file mode 100644index 000000000..e04fc6637--- /dev/null+++ b/lib/pregate/checks/secrets.ts@@ -0,0 +1,56 @@+/**+ * pregate check `secrets` (tier 1, preflight, never downgradable): the+ * branch's added lines (merge-base → working tree, untracked files included)+ * go through bin/gstack-redact. Exit 0 is clean; 2 (MEDIUM) and 3 (HIGH)+ * fail; anything else is incomplete. Runs regardless of lint tools.+ */+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 { baseInputs, sha256 } from '../context';+import type { CheckDef, CheckResult, PregateContext } from '../types';++const BIN_DIR = path.resolve(path.dirname(Bun.fileURLToPath(import.meta.url)), '..', '..', '..', 'bin');++/** `+` lines of the diff from the merge-base to the working tree, plus every line of untracked files. */+export function addedLines(ctx: PregateContext): string {+ const diff = spawnSync('git', ['diff', '--no-color', '--unified=0', '--diff-filter=ACMR', ctx.mergeBase, '--'], { cwd: ctx.repoRoot, encoding: 'utf8', timeout: 60_000, maxBuffer: 256 * 1024 * 1024, env: ctx.env });+ const lines: string[] = [];+ for (const line of (diff.stdout ?? '').split('\n')) if (line.startsWith('+') && !line.startsWith('+++')) lines.push(line.slice(1));+ for (const t of ctx.touched) {+ if (!t.uncommitted || t.status === 'D') continue;+ const tracked = spawnSync('git', ['ls-files', '--error-unmatch', '--', t.path], { cwd: ctx.repoRoot, encoding: 'utf8', timeout: 15_000 }).status === 0;+ if (tracked) continue;+ try { const st = fs.statSync(path.join(ctx.repoRoot, t.path)); if (st.isFile() && st.size <= 4 * 1024 * 1024) lines.push(...fs.readFileSync(path.join(ctx.repoRoot, t.path), 'utf8').split('\n')); } catch { /* unreadable: skipped */ }+ }+ return lines.join('\n');+}++function run(ctx: PregateContext): CheckResult {+ const text = addedLines(ctx);+ const inputs = baseInputs(ctx, { added_lines: sha256(text) });+ if (!text.trim()) return { id: 'secrets', stage: 'preflight', status: 'pass', detail: 'no added lines', inputs };+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-pregate-secrets-'));+ const file = path.join(tmp, 'added.txt');+ try {+ fs.writeFileSync(file, text, { mode: 0o600 });+ const r = spawnSync(path.join(BIN_DIR, 'gstack-redact'), ['--from-file', file, '--json', '--max-bytes', String(64 * 1024 * 1024)], { cwd: ctx.repoRoot, encoding: 'utf8', timeout: Math.min(ctx.timeoutMs, 300_000), maxBuffer: 64 * 1024 * 1024, env: ctx.env });+ if (r.error || r.status === null) return { id: 'secrets', stage: 'preflight', status: 'incomplete', inputs, code: 'PREGATE_INCOMPLETE', detail: `gstack-redact did not finish (${r.error?.message ?? 'killed'})`, fix: 'rerun; raise --timeout for very large diffs' };+ let findings: Array<{ id?: string; description?: string; severity?: string; category?: string; line?: number }> = [];+ try { findings = JSON.parse(r.stdout).findings ?? []; } catch { /* non-JSON output below */ }+ const render = (f: typeof findings[number]) => `${f.severity} ${f.id ?? 'finding'} [${f.category ?? '?'}]: ${f.description ?? ''}${f.line ? ` (added line ${f.line})` : ''}`;+ // HIGH and any MEDIUM credential fail; a MEDIUM hygiene/internal/pii/legal+ // hit in code (a `.local` property reads as a hostname) is listed as warn:+ // there is no user to answer gstack-redact's per-finding question here.+ const blocking = findings.filter(f => f.severity === 'HIGH' || (f.severity === 'MEDIUM' && f.category === 'secret'));+ const advisory = findings.filter(f => f.severity === 'MEDIUM' && f.category !== 'secret');+ if (r.status === 0) return { id: 'secrets', stage: 'preflight', status: 'pass', inputs, detail: `${text.split('\n').length} added lines clean${findings.length ? ` (${findings.length} WARN)` : ''}` };+ if (blocking.length) return { id: 'secrets', stage: 'preflight', status: 'fail', inputs, lines: [...blocking, ...advisory].map(render), code: 'PREGATE_SECRETS', detail: `${blocking.length} credential finding(s) in added lines (${blocking.map(f => f.id).join(', ')})`, fix: 'rotate and remove the credential from the added lines (history included); secrets cannot be downgraded' };+ if (r.status === 2) return { id: 'secrets', stage: 'preflight', status: 'warn', inputs, lines: advisory.map(render), code: 'PREGATE_SECRETS', detail: `${advisory.length} MEDIUM non-credential finding(s) in added lines (${[...new Set(advisory.map(f => f.id))].join(', ')})`, fix: 'read each listed line; gstack-post asks about the same findings when the PR body quotes them' };+ if (r.status === 3) return { id: 'secrets', stage: 'preflight', status: 'fail', inputs, lines: findings.map(render), code: 'PREGATE_SECRETS', detail: 'HIGH finding(s) in added lines', fix: 'rotate and remove the credential from the added lines (history included); secrets cannot be downgraded' };+ return { id: 'secrets', stage: 'preflight', status: 'incomplete', inputs, code: 'PREGATE_INCOMPLETE', detail: `gstack-redact exited ${r.status}: ${(r.stderr ?? '').trim().split('\n').pop() ?? ''}`, fix: 'fix the scanner invocation; an incomplete scan never passes' };+ } finally { fs.rmSync(tmp, { recursive: true, force: true }); }+}++export const secretsCheck: CheckDef = { id: 'secrets', stage: 'preflight', tier: 1, downgradable: false, needsRepoCommands: false, run };diff --git a/lib/pregate/checks/strays.ts b/lib/pregate/checks/strays.tsnew file mode 100644index 000000000..b92b8c664--- /dev/null+++ b/lib/pregate/checks/strays.ts@@ -0,0 +1,39 @@+/**+ * pregate check `strays` (tier 1, preflight): files the branch added at the+ * repository root, in a top-level directory the base branch does not have,+ * or anywhere under a scratch name (`zz-*`, `tmp*`, `scratch*`, editor+ * leftovers). Incident p0-4-scratch-script: a `zz-probe.sh` shipped in a+ * release PR because nothing looked at the file list.+ */+import { spawnSync } from 'node:child_process';+import { matchesAny } from '../../ship-policy';+import { baseInputs } from '../context';+import type { CheckDef, CheckResult, PregateContext } from '../types';++/** Conventional root files a repo adds without a declaration. */+const ROOT_OK = /^(?:README|LICENSE|LICENCE|NOTICE|CHANGELOG|CONTRIBUTING|CODE_OF_CONDUCT|SECURITY|AUTHORS|VERSION|Makefile|Dockerfile|Procfile|Gemfile|Rakefile|Cargo\.(?:toml|lock)|go\.(?:mod|sum)|package(?:-lock)?\.json|bun\.lockb?|pnpm-lock\.yaml|yarn\.lock|tsconfig[\w.-]*\.json|bunfig\.toml|pyproject\.toml|requirements[\w.-]*\.txt|setup\.(?:py|cfg)|\.[\w.-]+|[\w.-]+\.config\.[cm]?[jt]s|[\w.-]+\.md)$/i;+export const STRAY_NAME = /^(?:zz-|tmp|temp|scratch|debug-|probe)|\.(?:orig|rej|swp|swo|bak|tmp)$|~$|^\.DS_Store$|^Thumbs\.db$/i;++function run(ctx: PregateContext): CheckResult {+ const inputs = baseInputs(ctx);+ const baseDirs = new Set(spawnSync('git', ['ls-tree', '--name-only', '-d', ctx.mergeBase], { cwd: ctx.repoRoot, encoding: 'utf8', timeout: 30_000, env: ctx.env }).stdout.split('\n').filter(Boolean));+ const allow = ctx.config.strays.allow;+ const lines: string[] = [];+ const warnings: string[] = [];+ for (const t of ctx.touched) {+ if (t.status !== 'A' && t.status !== 'R') continue;+ const file = t.path;+ const name = file.split('/').pop()!;+ if (matchesAny(allow, file) || matchesAny(allow, file.split('/')[0]!)) continue;+ if (STRAY_NAME.test(name)) { lines.push(`${file}: scratch name (${name})`); continue; }+ if (!file.includes('/')) { if (!ROOT_OK.test(name)) lines.push(`${file}: new file at the repository root`); continue; }+ const top = file.split('/')[0]!;+ if (!baseDirs.has(top)) warnings.push(`${file}: new top-level directory ${top}/ (not on ${ctx.baseRef})`);+ }+ ctx.explain.push(`strays: base directories ${[...baseDirs].join(',')}; allow ${allow.join(',') || '(none)'}`);+ if (lines.length) return { id: 'strays', stage: 'preflight', status: 'fail', inputs, lines: [...lines, ...warnings], code: 'PREGATE_STRAYS', detail: `${lines.length} stray file(s): ${lines.map(l => l.split(':')[0]).join(' ')}`, fix: 'delete or move the file; an intentional root file goes in .gstack/pregate.json strays.allow' };+ if (warnings.length) return { id: 'strays', stage: 'preflight', status: 'warn', inputs, lines: warnings, code: 'PREGATE_STRAYS', detail: `${warnings.length} file(s) in a new top-level directory`, fix: 'confirm the directory is intended, or allow it in .gstack/pregate.json strays.allow' };+ return { id: 'strays', stage: 'preflight', status: 'pass', inputs, detail: `${ctx.touched.filter(t => t.status === 'A').length} added file(s), none stray` };+}++export const straysCheck: CheckDef = { id: 'strays', stage: 'preflight', tier: 1, downgradable: true, needsRepoCommands: false, run };diff --git a/lib/pregate/config.ts b/lib/pregate/config.tsnew file mode 100644index 000000000..36c7373e3--- /dev/null+++ b/lib/pregate/config.ts@@ -0,0 +1,164 @@+/**+ * pregate/config — `.gstack/pregate.json` (plan C8): the repo's declarations+ * for the pre-gate. Read from the committed copy on origin/<base> under the+ * C1 trust boundary (lib/ship-policy.ts loaders are the model); file presence+ * never authorizes a command. Keys:+ *+ * runner the test command with a `{files}` placeholder (default: detected)+ * dependencies glob → test files for subprocess targets, runtime reads and+ * generated inputs the import graph cannot see; `[]` declares+ * "no lane needed" for docs and the like+ * selection `<workflow.yml>/<job>` → the runner-owned command that lists+ * the lane's test files when the matrix is planner-computed+ * warn check ids downgraded to warn (never `secrets`; `lanes` keeps+ * its required-lane and requires-remote verdicts)+ * strays.allow root files or new top-level directories that are intentional+ */+import * as fs from 'node:fs';+import * as path from 'node:path';+import { spawnSync } from 'node:child_process';+import type { ResultCodeName } from '../result-codes';+import { containedRelative, globToRegExp } from '../ship-policy';++export const PREGATE_CONFIG_PATH = '.gstack/pregate.json';+export const PREGATE_CONFIG_SCHEMA = 'https://github.com/garrytan/gstack/docs/pregate.md#pregate-v1';+export const NON_DOWNGRADABLE = ['secrets'] as const;++export interface PregateConfig {+ $schema?: string;+ runner: string | null;+ dependencies: Record<string, string[]>;+ selection: Record<string, string>;+ warn: string[];+ strays: { allow: string[] };+}+export const DEFAULT_CONFIG: PregateConfig = { runner: null, dependencies: {}, selection: {}, warn: [], strays: { allow: [] } };+export interface ConfigError { code: ResultCodeName; path: string; message: string }++const MAX_LIST = 256;+const MAX_COMMAND = 512;+const KEYS = ['runner', 'dependencies', 'selection', 'warn', 'strays'];++function globError(g: string): string | null {+ const why = containedRelative(g);+ if (why) return why;+ try { globToRegExp(g); } catch (e: any) { return e.message; }+ return null;+}+function commandError(c: unknown): string | null {+ if (typeof c !== 'string' || !c.trim()) return 'must be a non-empty string';+ if (c.length > MAX_COMMAND || /[\0\r\n]/.test(c)) return `must be one line under ${MAX_COMMAND} characters`;+ return null;+}++export function validateConfig(raw: unknown, knownChecks: readonly string[] = []): ConfigError[] {+ const errors: ConfigError[] = [];+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return [{ code: 'PREGATE_CONFIG_INVALID', path: '', message: 'config must be a JSON object' }];+ const obj = raw as Record<string, unknown>;+ for (const key of Object.keys(obj)) if (key !== '$schema' && !KEYS.includes(key)) errors.push({ code: 'PREGATE_CONFIG_INVALID', path: key, message: `unknown key; valid keys: ${KEYS.join(', ')}` });+ if ('runner' in obj && obj.runner !== null) {+ const why = commandError(obj.runner);+ if (why) errors.push({ code: 'PREGATE_CONFIG_INVALID', path: 'runner', message: why });+ else if (!(obj.runner as string).includes('{files}')) errors.push({ code: 'PREGATE_CONFIG_INVALID', path: 'runner', message: 'must contain the {files} placeholder' });+ }+ if ('dependencies' in obj) {+ const deps = obj.dependencies;+ if (!deps || typeof deps !== 'object' || Array.isArray(deps)) errors.push({ code: 'PREGATE_CONFIG_INVALID', path: 'dependencies', message: 'must be an object of glob → test file list' });+ else {+ const entries = Object.entries(deps as Record<string, unknown>);+ if (entries.length > MAX_LIST) errors.push({ code: 'PREGATE_CONFIG_INVALID', path: 'dependencies', message: `more than ${MAX_LIST} entries` });+ for (const [glob, tests] of entries) {+ const why = globError(glob);+ if (why) errors.push({ code: 'PREGATE_CONFIG_INVALID', path: `dependencies[${JSON.stringify(glob)}]`, message: `${JSON.stringify(glob)} ${why}` });+ if (!Array.isArray(tests) || tests.some(t => typeof t !== 'string')) { errors.push({ code: 'PREGATE_CONFIG_INVALID', path: `dependencies[${JSON.stringify(glob)}]`, message: 'must be an array of test file paths ([] declares no lane needed)' }); continue; }+ (tests as string[]).forEach((t, i) => { const w = containedRelative(t); if (w) errors.push({ code: 'PREGATE_CONFIG_INVALID', path: `dependencies[${JSON.stringify(glob)}][${i}]`, message: `${JSON.stringify(t)} ${w}` }); });+ }+ }+ }+ if ('selection' in obj) {+ const sel = obj.selection;+ if (!sel || typeof sel !== 'object' || Array.isArray(sel)) errors.push({ code: 'PREGATE_CONFIG_INVALID', path: 'selection', message: 'must be an object of <workflow.yml>/<job> → command' });+ else for (const [lane, command] of Object.entries(sel as Record<string, unknown>)) {+ if (!/^[A-Za-z0-9_.-]+\.ya?ml\/[A-Za-z0-9_-]+$/.test(lane)) errors.push({ code: 'PREGATE_CONFIG_INVALID', path: `selection[${JSON.stringify(lane)}]`, message: 'key must be <workflow file>/<job id>' });+ const why = commandError(command);+ if (why) errors.push({ code: 'PREGATE_CONFIG_INVALID', path: `selection[${JSON.stringify(lane)}]`, message: why });+ }+ }+ if ('warn' in obj) {+ if (!Array.isArray(obj.warn) || obj.warn.some(w => typeof w !== 'string')) errors.push({ code: 'PREGATE_CONFIG_INVALID', path: 'warn', message: 'must be an array of check ids' });+ else for (const w of obj.warn as string[]) {+ if ((NON_DOWNGRADABLE as readonly string[]).includes(w)) errors.push({ code: 'PREGATE_CONFIG_INVALID', path: 'warn', message: `${w} cannot be downgraded to warn` });+ else if (knownChecks.length && !knownChecks.includes(w)) errors.push({ code: 'PREGATE_CONFIG_INVALID', path: 'warn', message: `unknown check ${w}; known: ${knownChecks.join(', ')}` });+ }+ }+ if ('strays' in obj) {+ const s = obj.strays as Record<string, unknown> | null;+ if (!s || typeof s !== 'object' || Array.isArray(s)) errors.push({ code: 'PREGATE_CONFIG_INVALID', path: 'strays', message: 'must be { allow: [globs] }' });+ else {+ for (const k of Object.keys(s)) if (k !== 'allow') errors.push({ code: 'PREGATE_CONFIG_INVALID', path: `strays.${k}`, message: 'unknown key' });+ if ('allow' in s) {+ if (!Array.isArray(s.allow) || s.allow.some(a => typeof a !== 'string')) errors.push({ code: 'PREGATE_CONFIG_INVALID', path: 'strays.allow', message: 'must be an array of globs' });+ else (s.allow as string[]).forEach((g, i) => { const why = globError(g); if (why) errors.push({ code: 'PREGATE_CONFIG_INVALID', path: `strays.allow[${i}]`, message: `${JSON.stringify(g)} ${why}` }); });+ }+ }+ }+ return errors;+}++export function parseConfig(text: string, knownChecks: readonly string[] = []): { config: PregateConfig; errors: ConfigError[] } {+ let raw: unknown;+ try { raw = JSON.parse(text); }+ catch (e: any) { return { config: DEFAULT_CONFIG, errors: [{ code: 'PREGATE_CONFIG_INVALID', path: PREGATE_CONFIG_PATH, message: `not valid JSON: ${e.message}` }] }; }+ const errors = validateConfig(raw, knownChecks);+ if (errors.length) return { config: DEFAULT_CONFIG, errors };+ const o = raw as Partial<PregateConfig>;+ return { config: { $schema: o.$schema, runner: o.runner ?? null, dependencies: o.dependencies ?? {}, selection: o.selection ?? {}, warn: o.warn ?? [], strays: { allow: o.strays?.allow ?? [] } }, errors: [] };+}++export type ConfigLoad = { config: PregateConfig; errors: ConfigError[]; present: boolean; label: string; kind: 'base' | 'head' | 'none' } | { unavailable: true; base: string; detail: string };++function git(cwd: string, args: string[]): { ok: boolean; out: string } {+ const r = spawnSync('git', args, { cwd, encoding: 'utf8', timeout: 30_000 });+ return { ok: r.status === 0, out: (r.stdout ?? '').trim() };+}++export function loadConfigFromBase(repoRoot: string, base: string, knownChecks: readonly string[] = []): ConfigLoad {+ const ref = `origin/${base.replace(/^origin\//, '')}`;+ const sha = git(repoRoot, ['rev-parse', '--verify', '--quiet', `${ref}^{commit}`]);+ if (!sha.ok || !sha.out) return { unavailable: true, base: base.replace(/^origin\//, ''), detail: `${ref} is not a resolvable commit` };+ const show = git(repoRoot, ['show', `${sha.out}:${PREGATE_CONFIG_PATH}`]);+ if (!show.ok) return { config: DEFAULT_CONFIG, errors: [], present: false, label: `${ref}@${sha.out.slice(0, 12)} (no ${PREGATE_CONFIG_PATH})`, kind: 'none' };+ return { ...parseConfig(show.out, knownChecks), present: true, label: `${ref}@${sha.out.slice(0, 12)}:${PREGATE_CONFIG_PATH}`, kind: 'base' };+}++export function loadConfigFromHead(repoRoot: string, knownChecks: readonly string[] = []): ConfigLoad {+ const file = path.join(repoRoot, PREGATE_CONFIG_PATH);+ if (!fs.existsSync(file)) return { config: DEFAULT_CONFIG, errors: [], present: false, label: `head (no ${PREGATE_CONFIG_PATH})`, kind: 'none' };+ return { ...parseConfig(fs.readFileSync(file, 'utf8'), knownChecks), present: true, label: `head (unreviewed) ${PREGATE_CONFIG_PATH}`, kind: 'head' };+}++export function isConfigUnavailable(load: ConfigLoad): load is { unavailable: true; base: string; detail: string } {+ return (load as any).unavailable === true;+}++export function exampleConfigJson(): string {+ const example = {+ $schema: PREGATE_CONFIG_SCHEMA,+ runner: null,+ dependencies: { 'bin/example-tool': ['test/example-tool.test.ts'], 'docs/**': [] },+ selection: {},+ warn: [],+ strays: { allow: [] },+ };+ return JSON.stringify(example, null, 2) + '\n';+}++export function explainConfig(): string {+ return [+ 'runner: the test command with a {files} placeholder; null detects bun test / vitest / jest / pytest from the repo',+ 'dependencies: glob → test files the import graph cannot see (subprocess targets, runtime reads, generated inputs); [] declares no lane needed',+ 'selection: <workflow.yml>/<job> → the runner-owned command that lists that lane’s test files when its matrix is planner-computed',+ `warn: check ids downgraded to warn; never ${NON_DOWNGRADABLE.join(', ')}; lanes keeps its required-lane and requires-remote verdicts`,+ 'strays.allow: root files or new top-level directories that are intentional',+ ].join('\n') + '\n';+}diff --git a/lib/pregate/context.ts b/lib/pregate/context.tsnew file mode 100644index 000000000..dfbc592a1--- /dev/null+++ b/lib/pregate/context.ts@@ -0,0 +1,102 @@+/**+ * pregate/context — what every check reads (plan C8): the base, the touched+ * files (committed since the merge-base plus the working tree, renames and+ * deletions kept), the reviewed `.gstack/pregate.json` and+ * `.gstack/generated.json`, the workflow lanes and the starting fingerprint.+ * Fingerprinting follows bin/gstack-evidence: the working-tree content hash+ * (bin/gstack-wtree) before a check runs and again after; a tree that moved+ * during a check makes its result `incomplete`, never `pass`.+ */+import { spawnSync } from 'node:child_process';+import { createHash } from 'node:crypto';+import { wtreeFingerprint, isRegistryUnavailable, loadRegistryFromBase, loadRegistryFromHead, type Registry } from '../regen';+import { isConfigUnavailable, loadConfigFromBase, loadConfigFromHead, type ConfigError, type PregateConfig } from './config';+import type { CheckResult, PregateContext, TouchedFile } from './types';+import { discoverLanes } from './workflows';+import type { RegistryError } from '../regen';++export interface BuildContextOptions {+ repoRoot: string; base: string; policyFrom: 'base' | 'head'; allowRepoCommands: boolean;+ timeoutMs?: number; env?: NodeJS.ProcessEnv; platform?: NodeJS.Platform; knownChecks?: readonly string[];+}+export type ContextLoad = { ctx: PregateContext } | { refused: { code: 'POLICY_SOURCE_UNAVAILABLE' | 'PREGATE_CONFIG_INVALID' | 'REGEN_REGISTRY_INVALID'; message: string; errors?: Array<ConfigError | RegistryError> } };++function git(cwd: string, args: string[], env?: NodeJS.ProcessEnv): { ok: boolean; out: string; err: string } {+ const r = spawnSync('git', args, { cwd, encoding: 'utf8', timeout: 60_000, maxBuffer: 64 * 1024 * 1024, env });+ return { ok: r.status === 0, out: (r.stdout ?? '').replace(/\n$/, ''), err: (r.stderr ?? '').trim() };+}++/** Committed changes since the merge-base (renames detected) plus every working-tree change, untracked files included. */+export function touchedFiles(repoRoot: string, mergeBase: string): TouchedFile[] {+ const out = new Map<string, TouchedFile>();+ const committed = git(repoRoot, ['diff', '--name-status', '-M', '-z', mergeBase, 'HEAD']).out.split('\0').filter(Boolean);+ for (let i = 0; i < committed.length; i++) {+ const status = committed[i]![0] as string;+ if (status === 'R' || status === 'C') { const from = committed[++i]!; const to = committed[++i]!; out.set(to, { path: to, status: 'R', renamedFrom: from, uncommitted: false }); continue; }+ const file = committed[++i]!;+ out.set(file, { path: file, status: status === 'D' ? 'D' : status === 'A' ? 'A' : 'M', uncommitted: false });+ }+ const porcelain = git(repoRoot, ['status', '--porcelain', '-z', '--untracked-files=all']).out.split('\0').filter(Boolean);+ for (let i = 0; i < porcelain.length; i++) {+ const entry = porcelain[i]!;+ const xy = entry.slice(0, 2);+ const file = entry.slice(3);+ if (xy.includes('R')) { const from = porcelain[++i]!; out.set(file, { path: file, status: 'R', renamedFrom: from, uncommitted: true }); continue; }+ if (xy === '!!') continue;+ const prior = out.get(file);+ const status: TouchedFile['status'] = xy.includes('D') ? 'D' : xy === '??' || xy.includes('A') ? (prior?.status === 'M' ? 'M' : 'A') : (prior?.status ?? 'M');+ out.set(file, { path: file, status, renamedFrom: prior?.renamedFrom, uncommitted: true });+ }+ return [...out.values()].filter(t => t.path !== 'node_modules' && !t.path.startsWith('node_modules/')).sort((a, b) => a.path.localeCompare(b.path));+}++export function buildContext(o: BuildContextOptions): ContextLoad {+ const base = o.base.replace(/^origin\//, '');+ const baseRef = `origin/${base}`;+ const baseSha = git(o.repoRoot, ['rev-parse', '--verify', '--quiet', `${baseRef}^{commit}`]);+ if (!baseSha.ok || !baseSha.out) return { refused: { code: 'POLICY_SOURCE_UNAVAILABLE', message: `${baseRef} is not a resolvable commit` } };+ const head = git(o.repoRoot, ['rev-parse', 'HEAD']).out;+ const mergeBase = git(o.repoRoot, ['merge-base', baseSha.out, 'HEAD']).out || baseSha.out;+ const configLoad = o.policyFrom === 'head' ? loadConfigFromHead(o.repoRoot, o.knownChecks) : loadConfigFromBase(o.repoRoot, base, o.knownChecks);+ if (isConfigUnavailable(configLoad)) return { refused: { code: 'POLICY_SOURCE_UNAVAILABLE', message: configLoad.detail } };+ if (configLoad.errors.length) return { refused: { code: 'PREGATE_CONFIG_INVALID', message: `${configLoad.label}: ${configLoad.errors.map(e => `${e.message} at ${e.path}`).join('; ')}`, errors: configLoad.errors } };+ const registryLoad = o.policyFrom === 'head' ? loadRegistryFromHead(o.repoRoot) : loadRegistryFromBase(o.repoRoot, base);+ if (isRegistryUnavailable(registryLoad)) return { refused: { code: 'POLICY_SOURCE_UNAVAILABLE', message: registryLoad.detail } };+ if (registryLoad.errors.length) return { refused: { code: 'REGEN_REGISTRY_INVALID', message: `${registryLoad.source.label}: ${registryLoad.errors.map(e => `${e.message} at ${e.path}`).join('; ')}`, errors: registryLoad.errors } };+ const wtree = wtreeFingerprint(o.repoRoot);+ if (!wtree) return { refused: { code: 'POLICY_SOURCE_UNAVAILABLE', message: 'cannot fingerprint the working tree (gstack-wtree failed)' } };+ const platform = o.platform ?? process.platform;+ return {+ ctx: {+ repoRoot: o.repoRoot, base, baseRef, baseSha: baseSha.out, mergeBase, head, wtree, touched: touchedFiles(o.repoRoot, mergeBase),+ config: configLoad.config as PregateConfig, configLabel: configLoad.label, registry: registryLoad.registry as Registry, registryLabel: registryLoad.source.label,+ lanes: discoverLanes(o.repoRoot, platform), platform, allowRepoCommands: o.allowRepoCommands, timeoutMs: o.timeoutMs ?? 600_000, env: o.env ?? process.env, explain: [],+ },+ };+}++export function sha256(text: string): string { return createHash('sha256').update(text).digest('hex'); }++/** The common input identity every check records; checks add their own keys. */+export function baseInputs(ctx: PregateContext, extra: Record<string, string> = {}): Record<string, string> {+ return { tree: ctx.wtree, head: ctx.head, base: `${ctx.baseRef}@${ctx.baseSha.slice(0, 12)}`, touched: sha256(ctx.touched.map(t => `${t.status} ${t.path}`).join('\n')), ...extra };+}++/**+ * Run one check under the before/after fingerprint (bin/gstack-evidence:394):+ * a tree that changed while the check ran, a thrown error or a timeout is+ * `incomplete`. Wall time is measured here so every row carries `ms`.+ */+export function withFingerprint(ctx: PregateContext, id: string, stage: CheckResult['stage'], fn: () => CheckResult): CheckResult {+ const started = Date.now();+ let result: CheckResult;+ try { result = fn(); }+ catch (e: any) {+ result = { id, stage, status: 'incomplete', detail: `threw: ${e?.message ?? e}`, code: 'PREGATE_INCOMPLETE', fix: 'read the error and rerun the check', inputs: baseInputs(ctx) };+ }+ const after = wtreeFingerprint(ctx.repoRoot);+ if (after !== ctx.wtree) {+ result = { ...result, status: 'incomplete', detail: `working tree changed during the check (${ctx.wtree.slice(0, 12)} → ${(after ?? 'unknown').slice(0, 12)}); result not certified`, code: 'PREGATE_INCOMPLETE', fix: 'keep the tree still during the run, then rerun gstack-pregate' };+ }+ return { ...result, ms: Date.now() - started };+}diff --git a/lib/pregate/import-graph.ts b/lib/pregate/import-graph.tsnew file mode 100644index 000000000..8d0e7622e--- /dev/null+++ b/lib/pregate/import-graph.ts@@ -0,0 +1,165 @@+/**+ * pregate/import-graph — which test files depend on which repo files (plan+ * C8 `lanes`). The reverse graph unions four sources, each kept as provenance+ * for `--explain`:+ * 1. static imports and requires (Bun.Transpiler.scanImports);+ * 2. repo-path string literals, including `join('a', 'b')` segment runs+ * (a test that spawns `bin/gstack-doctor` names it in a string, never an+ * import) and literal directories (`test/fixtures/x` → `x/**`);+ * 3. the `bin/<name>` → `test/<name>*.test.*` convention (with and without+ * the `gstack-` prefix);+ * 4. explicit `.gstack/pregate.json` `dependencies` declarations.+ * Uncertainty selects more tests, never fewer: a dependency on a directory+ * selects every test under it; a touched file with no path to a test is the+ * caller's `no lane` failure, not a pass. test/helpers/touchfile-closure.ts+ * (helpers and fixtures only, a lower bound by its own words) is the precedent.+ */+import { spawnSync } from 'node:child_process';+import * as fs from 'node:fs';+import * as path from 'node:path';+import { matchesAny } from '../ship-policy';++export const SOURCE_EXT = /\.(?:[cm]?[jt]sx?|py|rb|sh|bash|go|rs)$/;+export const TEST_FILE_RE = /(?:^|\/)(?:test|tests|spec|__tests__)\/.*\.(?:test|spec)\.[cm]?[jt]sx?$|(?:^|\/)[^/]*\.(?:test|spec)\.[cm]?[jt]sx?$|(?:^|\/)test_[^/]*\.py$|_test\.(?:py|go|rb)$|_spec\.rb$/;++export interface Edge { from: string; via: 'import' | 'literal' | 'convention' | 'declared' | 'generated' }+export interface Graph {+ files: Set<string>;+ tests: Set<string>;+ /** dependency → dependents with the kind of edge. */+ reverse: Map<string, Edge[]>;+}++const scanner = new Bun.Transpiler({ loader: 'tsx' });+const QUOTED = /['"`]([A-Za-z0-9_@][A-Za-z0-9_./@-]*)['"`]/g;+const JOIN = /\bjoin\(([^()]*)\)/g;+const RESOLVE_EXT = ['', '.ts', '.tsx', '.js', '.mjs', '.cjs', '/index.ts', '/index.js'];++export function isTestFile(rel: string): boolean { return TEST_FILE_RE.test(rel); }++export function listRepoFiles(repoRoot: string): string[] {+ const r = spawnSync('git', ['ls-files', '-co', '--exclude-standard', '-z'], { cwd: repoRoot, encoding: 'utf8', timeout: 60_000, maxBuffer: 64 * 1024 * 1024 });+ return (r.stdout ?? '').split('\0').filter(p => p && !p.startsWith('node_modules/'));+}++function normalize(p: string): string { return path.posix.normalize(p.replace(/\\/g, '/')).replace(/^\.\//, ''); }++/** A module specifier or literal → the repo file it names, or a directory → `dir/**`, or null. */+function resolveRef(files: Set<string>, dirs: Set<string>, fromFile: string, ref: string, literal = false): string | null {+ if (!ref || ref.startsWith('node:') || ref.startsWith('bun:') || ref.startsWith('@') && !ref.includes('/')) return null;+ const candidates: string[] = [];+ if (ref.startsWith('.')) candidates.push(normalize(path.posix.join(path.posix.dirname(fromFile), ref)));+ else candidates.push(normalize(ref));+ for (const c of candidates) {+ if (c.startsWith('../') || c === '..' || c === '.' || c === '') continue;+ for (const ext of RESOLVE_EXT) if (files.has(c + ext)) return c + ext;+ // A directory literal needs two segments (`test/fixtures/x`): a bare word is a name, not a path.+ if (dirs.has(c) && (!literal || c.includes('/'))) return `${c}/**`;+ // A bare bin name in a test (spawned through PATH or a helper's bin dir) names bin/<name>.+ if (literal && !c.includes('/') && files.has(`bin/${c}`)) return `bin/${c}`;+ }+ return null;+}++function addEdge(graph: Graph, dependency: string, dependent: string, via: Edge['via']): void {+ if (dependency === dependent) return;+ const list = graph.reverse.get(dependency) ?? [];+ if (!list.some(e => e.from === dependent && e.via === via)) { list.push({ from: dependent, via }); graph.reverse.set(dependency, list); }+}++/** Every dependency reference one source file makes: imports, requires, quoted repo paths and join() segment runs. */+export function referencesIn(files: Set<string>, dirs: Set<string>, rel: string, source: string): Array<{ target: string; via: Edge['via'] }> {+ const out: Array<{ target: string; via: Edge['via'] }> = [];+ if (/\.[cm]?[jt]sx?$/.test(rel)) {+ let imports: Array<{ path: string }> = [];+ try { imports = scanner.scanImports(source); } catch { imports = []; }+ for (const { path: spec } of imports) { const t = resolveRef(files, dirs, rel, spec); if (t) out.push({ target: t, via: 'import' }); }+ // The transpiler erases type-only imports; a types module still binds its importers' contracts.+ for (const m of source.matchAll(/^\s*(?:import|export)\s+type\b[^;'"]*?\bfrom\s+['"]([^'"]+)['"]/gm)) { const t = resolveRef(files, dirs, rel, m[1]!); if (t) out.push({ target: t, via: 'import' }); }+ }+ // Literals carry dependencies only from the test tree and from bin/ and shell+ // sources (a test spawns a bin; a bash bin calls a sibling). Prose and+ // manifests name everything and would make every file a hub.+ if (!scansLiterals(rel)) return out;+ for (const m of source.matchAll(QUOTED)) { const t = resolveRef(files, dirs, rel, m[1]!, true); if (t) out.push({ target: t, via: 'literal' }); }+ for (const m of source.matchAll(JOIN)) {+ const segments = [...m[1]!.matchAll(/['"`]([^'"`]+)['"`]/g)].map(s => s[1]!);+ if (segments.length < 2) continue;+ const joined = segments.join('/');+ const t = resolveRef(files, dirs, rel, joined, true) ?? resolveRef(files, dirs, rel, './' + joined, true);+ if (t) out.push({ target: t, via: 'literal' });+ }+ return out;+}++/** Test-tree files (tests, helpers, fixtures), bin/ entrypoints and shell sources carry literal dependencies. */+export function scansLiterals(rel: string): boolean {+ return /(?:^|\/)(?:test|tests|spec|__tests__)\//.test(rel) || isTestFile(rel) || rel.startsWith('bin/') || /\.(?:sh|bash)$/.test(rel);+}++export interface BuildOptions {+ declarations?: Record<string, string[]>; maxBytes?: number;+ /** Paths that no longer exist (deleted or renamed-from) but that tests may still name; they resolve as dependencies so their consumers are found. */+ extraFiles?: string[];+}++/** The whole-repo reverse graph. Files over maxBytes (default 2 MiB) are skipped: generated bundles, not tests. */+export function buildGraph(repoRoot: string, opts: BuildOptions = {}): Graph {+ const all = listRepoFiles(repoRoot);+ const files = new Set([...all, ...(opts.extraFiles ?? [])]);+ const dirs = new Set<string>();+ for (const f of all) { let d = path.posix.dirname(f); while (d && d !== '.') { dirs.add(d); d = path.posix.dirname(d); } }+ const graph: Graph = { files, tests: new Set(all.filter(isTestFile)), reverse: new Map() };+ const maxBytes = opts.maxBytes ?? 2 * 1024 * 1024;+ for (const rel of all) {+ if (!SOURCE_EXT.test(rel) && !rel.startsWith('bin/')) continue;+ let source: string;+ try { const st = fs.statSync(path.join(repoRoot, rel)); if (!st.isFile() || st.size > maxBytes) continue; source = fs.readFileSync(path.join(repoRoot, rel), 'utf8'); } catch { continue; }+ for (const { target, via } of referencesIn(files, dirs, rel, source)) addEdge(graph, target, rel, via);+ }+ for (const test of graph.tests) {+ const m = /^(?:[\w.-]+\/)*?test\/([\w-]+)\.(?:test|spec)\./.exec(test);+ if (!m) continue;+ // test/gstack-ship-receipt-census.test.ts names bin/gstack-ship-receipt-census, then bin/gstack-ship-receipt, then bin/gstack-ship, …+ const parts = m[1]!.split('-');+ for (let n = parts.length; n >= 1; n--) {+ const name = parts.slice(0, n).join('-');+ for (const bin of [`bin/${name}`, `bin/gstack-${name}`, `bin/${name}.ts`, `bin/gstack-${name}.ts`]) if (files.has(bin)) addEdge(graph, bin, test, 'convention');+ }+ }+ for (const [glob, tests] of Object.entries(opts.declarations ?? {})) {+ for (const f of files) if (matchesAny([glob], f)) for (const t of tests) addEdge(graph, f, t, 'declared');+ }+ return graph;+}++export interface LaneMapping { file: string; tests: string[]; provenance: string[]; declaredNone: boolean }++/**+ * Tests that depend on `file`, transitively through non-test files and+ * through `dir/**` edges. `declarations` with an empty list declare "no lane+ * needed" and win when nothing else maps.+ */+export function testsFor(graph: Graph, file: string, declarations: Record<string, string[]> = {}, maxDepth = 12): LaneMapping {+ const tests = new Set<string>();+ const provenance: string[] = [];+ const seen = new Set<string>([file]);+ const queue: Array<{ node: string; chain: string[] }> = [{ node: file, chain: [file] }];+ const dirEdges = [...graph.reverse.keys()].filter(k => k.endsWith('/**'));+ while (queue.length) {+ const { node, chain } = queue.shift()!;+ if (chain.length > maxDepth) continue;+ const edges = [...(graph.reverse.get(node) ?? [])];+ for (const dir of dirEdges) if (node.startsWith(dir.slice(0, -3) + '/')) edges.push(...(graph.reverse.get(dir) ?? []).map(e => ({ ...e, via: e.via })));+ for (const e of edges) {+ if (seen.has(e.from)) continue;+ seen.add(e.from);+ if (graph.tests.has(e.from)) { tests.add(e.from); provenance.push(`${e.from} ← ${[...chain].reverse().join(' ← ')} (${e.via})`); }+ else queue.push({ node: e.from, chain: [...chain, e.from] });+ }+ }+ if (graph.tests.has(file)) { tests.add(file); provenance.push(`${file} (itself a test)`); }+ const declaredNone = tests.size === 0 && Object.entries(declarations).some(([glob, list]) => list.length === 0 && matchesAny([glob], file));+ if (declaredNone) provenance.push(`${file}: declared no lane needed (.gstack/pregate.json dependencies)`);+ return { file, tests: [...tests].sort(), provenance, declaredNone };+}diff --git a/lib/pregate/index.ts b/lib/pregate/index.tsnew file mode 100644index 000000000..4bb7cc365--- /dev/null+++ b/lib/pregate/index.ts@@ -0,0 +1,138 @@+/**+ * pregate — the cheap pre-gate (plan C8): the check registry, the two-stage+ * runner with separate clocks, the table, `pregate.json` and the publication+ * verdict. Stage 1 (mechanical preflight: regen, secrets, strays, literals,+ * …) is the two-minute promise and is timed per check; stage 2 (test+ * execution: lanes, …) has its own clock and is never folded into the first.+ * A failing check blocks; `.gstack/pregate.json` downgrades a named check to+ * warn except `secrets` and the required-lane verdicts; timeout or a missing+ * tool is `incomplete`, never `pass`. Tier 2 checks (guards, ratchets, lint,+ * links, hermetic, patches, integrator) register here as they land.+ */+import * as fs from 'node:fs';+import * as path from 'node:path';+import { ARTIFACT_SCHEMAS, checkSchema, type PregateFile, type PregateRemote, type ValidationError } from '../headless-artifacts';+import { wtreeFingerprint } from '../regen';+import { lanesCheck } from './checks/lanes';+import { literalsCheck } from './checks/literals';+import { regenCheck } from './checks/regen';+import { secretsCheck } from './checks/secrets';+import { straysCheck } from './checks/strays';+import { NON_DOWNGRADABLE } from './config';+import { withFingerprint } from './context';+import type { CheckDef, CheckResult, PregateContext, Stage } from './types';++export const CHECKS: readonly CheckDef[] = [regenCheck, secretsCheck, straysCheck, literalsCheck, lanesCheck];+export const CHECK_IDS = CHECKS.map(c => c.id);+export const PREGATE_OUT_REL = '.gstack/tmp/pregate.json';+export const PREGATE_TIER2 = ['guards', 'ratchets', 'lint', 'links', 'hermetic', 'patches', 'integrator'] as const;++export interface RunOptions { stage: Stage | 'all'; only?: string[]; run?: string }++/** Apply the repo's `warn` downgrades: never `secrets`, and never a lane that could run here and failed. */+export function applyDowngrades(ctx: PregateContext, result: CheckResult, def: CheckDef): CheckResult {+ if (result.status !== 'fail') return result;+ if (!def.downgradable || (NON_DOWNGRADABLE as readonly string[]).includes(def.id)) return result;+ if (!ctx.config.warn.includes(def.id)) return result;+ if (def.id === 'lanes' && result.code === 'PREGATE_LANE_FAILED') return { ...result, detail: `${result.detail} (required lane; warn downgrade does not apply)` };+ return { ...result, status: 'warn', detail: `${result.detail} (downgraded to warn by ${ctx.configLabel})` };+}++export function runPregate(ctx: PregateContext, o: RunOptions): PregateFile {+ const selected = CHECKS.filter(c => (o.stage === 'all' || c.stage === o.stage) && (!o.only || o.only.includes(c.id)));+ const checks: CheckResult[] = [];+ const clocks: Record<Stage, number> = { preflight: 0, tests: 0 };+ for (const def of selected) {+ const started = Date.now();+ const result = applyDowngrades(ctx, withFingerprint(ctx, def.id, def.stage, () => def.run(ctx)), def);+ clocks[def.stage] += Date.now() - started;+ checks.push({ ...result, stage: def.stage });+ }+ const remote: PregateRemote[] = checks.flatMap(c => c.remote ?? []).map(r => ({ ...r }));+ const file: PregateFile = {+ schema_version: 1, tree: ctx.wtree, head: ctx.head, base: `${ctx.baseRef}@${ctx.baseSha.slice(0, 12)}`, generated_at: new Date().toISOString(),+ policy: ctx.configLabel, registry: ctx.registryLabel, run: o.run,+ stage1_ms: o.stage === 'tests' ? undefined : clocks.preflight, stage2_ms: o.stage === 'preflight' ? undefined : clocks.tests,+ checks: checks.map(c => { const { remote: _r, ...rest } = c; return rest; }),+ requires_remote: remote,+ };+ file.verdict = verdictOf(file);+ return file;+}++/** `pass`, `warn`, `requires-remote`, `incomplete` or `fail`: the worst status across checks, with uncleared obligations counted. */+export function verdictOf(file: PregateFile): string {+ const statuses = new Set(file.checks.map(c => c.status));+ if (statuses.has('fail')) return 'fail';+ if (statuses.has('incomplete') || statuses.has('not_installed')) return 'incomplete';+ const uncleared = (file.requires_remote ?? []).filter(r => !r.receipt);+ if (uncleared.length) return `requires-remote (${uncleared.length} uncleared)`;+ if (statuses.has('requires-remote')) return 'requires-remote cleared';+ if (statuses.has('warn')) return 'warn';+ return 'pass';+}++/** The table: one row per check with its stage, status, wall time and detail, then the stage clocks. */+export function renderTable(file: PregateFile, opts: { lines?: boolean } = { lines: true }): string {+ const rows = file.checks.map(c => `${c.stage === 'tests' ? 'tests ' : 'preflight'} ${c.id.padEnd(9)} ${c.status.padEnd(15)} ${String(c.ms ?? 0).padStart(7)} ms ${c.detail ?? ''}${c.code && c.status !== 'pass' ? ` (${c.code})` : ''}`);+ const body = opts.lines ? file.checks.flatMap(c => (c.lines ?? []).map(l => ` ${c.id}: ${l}`).concat(c.fix && c.status !== 'pass' && c.status !== 'requires-remote' ? [` ${c.id}: fix: ${c.fix}`] : [])) : [];+ const clocks = [+ file.stage1_ms !== undefined ? `stage 1 (mechanical preflight): ${file.stage1_ms} ms` : null,+ file.stage2_ms !== undefined ? `stage 2 (test execution): ${file.stage2_ms} ms` : null,+ ].filter(Boolean);+ const remote = (file.requires_remote ?? []).map(r => `requires-remote: ${r.lane} (${r.platform}) ${r.tests.length} test(s) — ${r.receipt ? `cleared by ${r.receipt}` : 'uncleared; clear with gstack-pregate clear --remote ' + r.lane + ' --run-url <url>'}`);+ return [+ `stage check status time detail`,+ ...rows, ...body, ...clocks, ...remote,+ `PREGATE: ${file.verdict} tree=${file.tree.slice(0, 12)} head=${(file.head ?? '').slice(0, 12)} checks=${file.checks.length}`,+ ].join('\n') + '\n';+}++export function writePregateFile(repoRoot: string, rel: string, file: PregateFile): string {+ const abs = path.isAbsolute(rel) ? rel : path.join(repoRoot, rel);+ fs.mkdirSync(path.dirname(abs), { recursive: true });+ const errors: ValidationError[] = [];+ const plain = JSON.parse(JSON.stringify(file));+ checkSchema(plain, ARTIFACT_SCHEMAS.pregate, '', errors, rel);+ if (errors.length) throw new Error(`pregate.json does not validate: ${errors.map(e => `${e.path}: ${e.message}`).join('; ')}`);+ fs.writeFileSync(abs, JSON.stringify(plain, null, 2) + '\n');+ return abs;+}++export function readPregateFile(file: string): { file: PregateFile | null; errors: ValidationError[] } {+ const errors: ValidationError[] = [];+ let parsed: unknown;+ try { parsed = JSON.parse(fs.readFileSync(file, 'utf8')); }+ catch (e: any) { return { file: null, errors: [{ code: 'ARTIFACT_INVALID_JSON', path: file, message: e.message }] }; }+ checkSchema(parsed, ARTIFACT_SCHEMAS.pregate, '', errors, file);+ return { file: errors.length ? null : (parsed as PregateFile), errors };+}++export interface Verification { ok: boolean; code?: 'PREGATE_STALE' | 'PREGATE_REMOTE_UNCLEARED' | 'PREGATE_INCOMPLETE' | 'PREGATE_LANE_FAILED'; message: string; current: boolean; uncleared: PregateRemote[] }++/**+ * Publication check: the recorded tree must equal the tree now (results+ * current after final generation and stamping), no check may be fail or+ * incomplete, and every requires-remote obligation needs its receipt.+ */+export function verifyPregate(repoRoot: string, file: PregateFile, treeNow = wtreeFingerprint(repoRoot)): Verification {+ const uncleared = (file.requires_remote ?? []).filter(r => !r.receipt);+ const current = !!treeNow && treeNow === file.tree;+ if (!current) return { ok: false, code: 'PREGATE_STALE', message: `pregate.json was recorded against tree ${file.tree.slice(0, 12)}; the tree is now ${(treeNow ?? 'unknown').slice(0, 12)}`, current, uncleared };+ const failed = file.checks.filter(c => c.status === 'fail');+ if (failed.length) return { ok: false, code: 'PREGATE_LANE_FAILED', message: `${failed.length} check(s) failed: ${failed.map(c => c.id).join(', ')}`, current, uncleared };+ const incomplete = file.checks.filter(c => c.status === 'incomplete' || c.status === 'not_installed');+ if (incomplete.length) return { ok: false, code: 'PREGATE_INCOMPLETE', message: `${incomplete.length} check(s) incomplete: ${incomplete.map(c => c.id).join(', ')}`, current, uncleared };+ if (uncleared.length) return { ok: false, code: 'PREGATE_REMOTE_UNCLEARED', message: `${uncleared.length} requires-remote obligation(s) without a receipt: ${uncleared.map(r => r.lane).join(', ')}`, current, uncleared };+ return { ok: true, message: `pregate ${file.verdict} is current for tree ${file.tree.slice(0, 12)}`, current, uncleared };+}++/** Record the receipt that clears one obligation (a run URL or an evidence-bundle lane label). */+export function clearObligation(file: PregateFile, lane: string, receipt: string, by: string): PregateFile {+ const list = file.requires_remote ?? [];+ const target = list.find(r => r.lane === lane);+ if (!target) throw new Error(`no requires-remote obligation named ${lane}; obligations: ${list.map(r => r.lane).join(', ') || '(none)'}`);+ target.receipt = receipt; target.cleared_by = by;+ file.verdict = verdictOf(file);+ return file;+}diff --git a/lib/pregate/lane-selection.ts b/lib/pregate/lane-selection.tsnew file mode 100644index 000000000..02c4f846e--- /dev/null+++ b/lib/pregate/lane-selection.ts@@ -0,0 +1,105 @@+/**+ * pregate/lane-selection — from touched files to the tests that must run and+ * the platform lanes that must run them (plan C8 `lanes`). Mapping goes+ * through lib/pregate/import-graph.ts plus the generated-file registry (a+ * touched template selects the tests of its rendered outputs). Lane file+ * sets come from the workflow files: literal test paths in run steps, or the+ * runner-owned selection manifest `.gstack/pregate.json` declares for a+ * planner-computed matrix. Every uncertainty widens the selection.+ */+import { spawnSync } from 'node:child_process';+import { GENERATED_PATH } from '../regen';+import { matchesAny } from '../ship-policy';+import { PREGATE_CONFIG_PATH } from './config';+import { buildGraph, isTestFile, listRepoFiles, testsFor, type Graph } from './import-graph';+import type { PregateContext, RemoteObligation } from './types';+import type { Lane } from './workflows';++export interface Selection {+ /** Touched files with no lane and no `[]` declaration. */+ noLane: string[];+ /** Every test the touched files select, sorted. */+ tests: string[];+ /** Tests that run on this machine. */+ localTests: string[];+ /** Platform lanes this machine cannot run that select part of the set. */+ remote: RemoteObligation[];+ /** Tiers of the local lanes the selection touches. */+ tiersRan: string[];+ /** `lane id → files` for every lane whose set is known, plus `?` for planner-computed lanes without a manifest. */+ laneSets: Record<string, string[] | '?'>;+ provenance: string[];+}++/** Resolve one lane's test-file set: literal paths, then the declared selection manifest, else `?` when its matrix is an expression. */+export function laneFileSet(ctx: PregateContext, lane: Lane): string[] | '?' | 'all' {+ const files = new Set(lane.testFiles);+ const manifest = ctx.config.selection[lane.id];+ if (manifest) {+ if (!ctx.allowRepoCommands) { ctx.explain.push(`lane ${lane.id}: selection manifest \`${manifest}\` not run (pass --allow-repo-commands); treated as unknown`); return files.size ? [...files] : '?'; }+ const r = spawnSync('bash', ['-c', `set -o pipefail; ${manifest}`], { cwd: ctx.repoRoot, encoding: 'utf8', timeout: Math.min(ctx.timeoutMs, 300_000), maxBuffer: 64 * 1024 * 1024, env: ctx.env });+ if (r.status !== 0) { ctx.explain.push(`lane ${lane.id}: selection manifest exited ${r.status}; treated as unknown`); return '?'; }+ for (const line of (r.stdout ?? '').split('\n')) { const m = /((?:[\w.-]+\/)*[\w.-]+\.(?:test|spec)\.[cm]?[jt]sx?|(?:[\w.-]+\/)*test_[\w.-]+\.py)/.exec(line.trim()); if (m) files.add(m[1]!); }+ ctx.explain.push(`lane ${lane.id}: ${files.size} files from manifest \`${manifest}\``);+ return [...files];+ }+ if (lane.matrixExpression && files.size === 0) { ctx.explain.push(`lane ${lane.id}: unsupported workflow expression ${JSON.stringify(lane.matrixExpression)} and no selection manifest; treated as unknown`); return '?'; }+ return files.size ? [...files] : 'all';+}++/** Tracked files matching a registry entry's output globs. */+function outputsOf(all: readonly string[], globs: readonly string[]): string[] { return all.filter(f => matchesAny(globs, f)); }++export function selectLanes(ctx: PregateContext): Selection {+ const touched = ctx.touched;+ const gone = touched.flatMap(t => [t.status === 'D' ? t.path : null, t.renamedFrom ?? null]).filter((p): p is string => !!p);+ const graph: Graph = buildGraph(ctx.repoRoot, { declarations: ctx.config.dependencies, extraFiles: gone });+ const all = listRepoFiles(ctx.repoRoot);+ const provenance: string[] = [];+ const tests = new Set<string>();+ const noLane: string[] = [];+ const seeds = new Map<string, string>();+ for (const t of touched) { seeds.set(t.path, t.status === 'D' ? 'deleted' : 'touched'); if (t.renamedFrom) seeds.set(t.renamedFrom, `renamed to ${t.path}`); }+ for (const e of ctx.registry.entries) {+ if (!touched.some(t => matchesAny(e.inputs, t.path) || matchesAny(e.outputs, t.path))) continue;+ for (const out of outputsOf(all, e.outputs)) if (!seeds.has(out)) seeds.set(out, `generated by ${e.id}`);+ }+ for (const [file, why] of seeds) {+ const m = testsFor(graph, file, ctx.config.dependencies);+ for (const t of m.tests) tests.add(t);+ provenance.push(...m.provenance.map(p => `${p} [${why}]`));+ if (m.tests.length || m.declaredNone || why.startsWith('generated')) continue;+ // A renamed file keeps the lane its old name had: those tests run (and fail loudly if they still import the old path).+ const renamedFrom = touched.find(t => t.path === file && t.renamedFrom)?.renamedFrom;+ if (renamedFrom && testsFor(graph, renamedFrom, ctx.config.dependencies).tests.length) { provenance.push(`${file}: lane via its old name ${renamedFrom}`); continue; }+ // A registry input with a regen command is verified by the `regen` check (its outputs are compared fresh).+ const generator = ctx.registry.entries.find(e => e.command && matchesAny(e.inputs, file));+ if (generator) { provenance.push(`${file}: covered by regen ${generator.id} (registry input)`); continue; }+ // The pin files are validated by pregate itself (validateConfig / validateRegistry) on every run.+ if (file === PREGATE_CONFIG_PATH || file === GENERATED_PATH) { provenance.push(`${file}: pin file validated by pregate`); continue; }+ noLane.push(file);+ }+ const laneSets: Record<string, string[] | '?'> = {};+ const local = new Set<string>();+ const remote: RemoteObligation[] = [];+ const tiers = new Set<string>();+ const selected = [...tests].sort();+ let anyLocalAll = false;+ for (const lane of ctx.lanes.filter(l => l.runsTests && !l.manual)) {+ const set = laneFileSet(ctx, lane);+ if (set !== 'all') laneSets[lane.id] = set;+ const inLane = set === 'all' ? selected : set === '?' ? selected : selected.filter(t => set.includes(t));+ if (lane.tier === 'platform') {+ if (inLane.length) remote.push({ lane: lane.id, platform: lane.platform, workflow: lane.workflow, job: lane.job, tests: inLane, receipt: null });+ continue;+ }+ if (set === 'all') anyLocalAll = true;+ if (inLane.length) { tiers.add(lane.tier); for (const t of inLane) local.add(t); }+ }+ if (anyLocalAll || ctx.lanes.filter(l => l.runsTests && !l.manual && l.tier !== 'platform').length === 0) for (const t of selected) local.add(t);+ for (const t of selected) if (!local.has(t) && !remote.some(r => r.tests.includes(t))) local.add(t);+ if (local.size && tiers.size === 0) tiers.add('unit');+ return { noLane: noLane.sort(), tests: selected, localTests: [...local].sort(), remote, tiersRan: [...tiers].sort(), laneSets, provenance };+}++export function isTest(file: string): boolean { return isTestFile(file); }diff --git a/lib/pregate/types.ts b/lib/pregate/types.tsnew file mode 100644index 000000000..309e2a91b--- /dev/null+++ b/lib/pregate/types.ts@@ -0,0 +1,82 @@+/**+ * pregate/types — the shapes every pre-gate check shares (plan C8). One check+ * per file under lib/pregate/checks/, registered in lib/pregate/index.ts.+ */+import type { PregateCheck } from '../headless-artifacts';+import type { Registry } from '../regen';+import type { PregateConfig } from './config';+import type { Lane } from './workflows';++export type CheckStatus = PregateCheck['status'];+export type Stage = 'preflight' | 'tests';++export interface TouchedFile {+ path: string;+ /** A = added, M = modified, D = deleted, R = renamed (from `renamedFrom`). */+ status: 'A' | 'M' | 'D' | 'R';+ renamedFrom?: string;+ /** True when the change is only in the working tree (uncommitted or untracked). */+ uncommitted: boolean;+}++export interface PregateContext {+ repoRoot: string;+ /** Base branch name without `origin/`. */+ base: string;+ baseRef: string;+ baseSha: string;+ /** merge-base of origin/<base> and HEAD: the diff anchor. */+ mergeBase: string;+ head: string;+ /** Working-tree content fingerprint at the start of the run (bin/gstack-wtree). */+ wtree: string;+ touched: TouchedFile[];+ config: PregateConfig;+ configLabel: string;+ registry: Registry;+ registryLabel: string;+ lanes: Lane[];+ platform: NodeJS.Platform;+ allowRepoCommands: boolean;+ timeoutMs: number;+ env: NodeJS.ProcessEnv;+ /** `--explain`: checks append provenance lines here. */+ explain: string[];+}++export interface RemoteObligation {+ /** `<workflow file>/<job id>`. */+ lane: string;+ platform: string;+ workflow: string;+ job: string;+ /** Test files this machine cannot run that the touched files select. */+ tests: string[];+ /** What clears it: a run URL or an evidence-bundle lane label, recorded by `gstack-pregate clear`. */+ receipt: string | null;+ cleared_by?: string;+}++export interface CheckResult extends PregateCheck {+ stage: Stage;+ /** The input identity the check ran against (tree, selection, registry source). */+ inputs: Record<string, string>;+ /** Exact command or edit an author runs; present on fail/warn/incomplete. */+ fix?: string;+ /** Result code the detail line ends with. */+ code?: string;+ /** Per-file or per-item lines for the table body. */+ lines?: string[];+ remote?: RemoteObligation[];+}++export interface CheckDef {+ id: string;+ stage: Stage;+ tier: 1 | 2;+ /** `secrets` and required lanes can never be downgraded to warn. */+ downgradable: boolean;+ /** True when the check executes commands the repo declares (pin files or its test runner). */+ needsRepoCommands: boolean;+ run(ctx: PregateContext): CheckResult;+}diff --git a/lib/pregate/workflows.ts b/lib/pregate/workflows.tsnew file mode 100644index 000000000..1aa503e4c--- /dev/null+++ b/lib/pregate/workflows.ts@@ -0,0 +1,129 @@+/**+ * pregate/workflows — the lane list and platform tiers, read from the repo's+ * own `.github/workflows/*.yml` (plan C8): never a pre-gate-owned taxonomy,+ * so a changed CI matrix changes the pre-gate. The platform of a job comes+ * from `runs-on` through the same `laneOf` the doctor's project-pins row uses+ * (lib/runtime-pins.ts). A job whose `matrix:` is a workflow expression+ * (`${{ fromJSON(...) }}`) is planner-computed: its file list comes from the+ * runner-owned selection manifest `.gstack/pregate.json` declares for it, or+ * it is reported as an unsupported expression and treated conservatively.+ */+import * as fs from 'node:fs';+import * as path from 'node:path';+import { laneOf, type Lane as Platform } from '../runtime-pins';++export type LaneTier = 'unit' | 'serial' | 'e2e' | 'platform';++export interface Lane {+ /** `<workflow file>/<job id>`. */+ id: string;+ workflow: string;+ workflowName: string;+ job: string;+ jobName: string;+ runsOn: string;+ platform: Platform;+ /** Every `run:` step text, in order. */+ commands: string[];+ /** Test file paths named literally in the run steps. */+ testFiles: string[];+ /** The `matrix:` value when it is a workflow expression, else null. */+ matrixExpression: string | null;+ tier: LaneTier;+ /** True when a run step looks like a test command. */+ runsTests: boolean;+ /** True when the job's `if:` keys on a workflow_dispatch input: not a gate, never an obligation. */+ manual: boolean;+ source: string;+}++const TEST_COMMAND = /\b(?:bun test|bun run test\b|bun run test:|npm test|npm run test\b|pnpm test|yarn test|pytest|go test|cargo test|rspec|bin\/test-lane|node --test|vitest|jest|test-(?:free|paid)-shards\.ts(?![^\n]*--(?:ci-verify|ci-plan|list)\b))\b/;+const TEST_FILE = /(?<![\w/])((?:[\w.-]+\/)*(?:test|tests|spec|__tests__)\/[\w./-]*\.(?:test|spec)\.[a-z]+|(?:[\w.-]+\/)*[\w.-]+\.(?:test|spec)\.[cm]?[jt]sx?)(?![\w/])/g;++function indentOf(line: string): number { return line.length - line.trimStart().length; }++interface Block { key: string; value: string; indent: number; line: number; children: Block[] }++/** A minimal YAML outline: key/value pairs and list items by indentation; block scalars (`|`, `>`) are joined into the value. */+function outline(text: string): Block[] {+ const lines = text.split('\n');+ const root: Block[] = [];+ const stack: Array<{ indent: number; children: Block[] }> = [{ indent: -1, children: root }];+ for (let i = 0; i < lines.length; i++) {+ const raw = lines[i]!;+ if (!raw.trim() || raw.trim().startsWith('#')) continue;+ const indent = indentOf(raw);+ const body = raw.trim().replace(/^-\s+/, '');+ const m = /^([^:#]+?):(?:\s+(.*))?$/.exec(body);+ const key = m ? m[1]!.trim() : body;+ let value = m ? (m[2] ?? '').trim() : '';+ if (/^[|>][-+]?$/.test(value)) {+ const parts: string[] = [];+ while (i + 1 < lines.length && (!lines[i + 1]!.trim() || indentOf(lines[i + 1]!) > indent)) { i++; parts.push(lines[i]!.trim()); }+ value = parts.filter(Boolean).join('\n');+ }+ while (stack.length > 1 && stack[stack.length - 1]!.indent >= indent) stack.pop();+ const block: Block = { key, value, indent, line: i + 1, children: [] };+ stack[stack.length - 1]!.children.push(block);+ stack.push({ indent, children: block.children });+ }+ return root;+}++function find(blocks: Block[], key: string): Block | undefined { return blocks.find(b => b.key === key); }+function deepValues(blocks: Block[], key: string, out: string[] = []): string[] {+ for (const b of blocks) { if (b.key === key && b.value) out.push(b.value); deepValues(b.children, key, out); }+ return out;+}++/** `bun run x`, `npm run x`, `pnpm x`, `yarn x` → the package.json script text, one level deep, appended so its test files count. */+export function expandScripts(commands: string[], scripts: Record<string, string>): string[] {+ return commands.map(c => {+ const extra: string[] = [];+ for (const m of c.matchAll(/\b(?:bun|npm|pnpm|yarn)\s+(?:run\s+)?([A-Za-z0-9:_.-]+)/g)) if (scripts[m[1]!]) extra.push(scripts[m[1]!]!);+ return extra.length ? `${c}\n${extra.join('\n')}` : c;+ });+}++export function parseWorkflow(file: string, text: string, platform: NodeJS.Platform = process.platform, scripts: Record<string, string> = {}): Lane[] {+ const top = outline(text);+ const name = find(top, 'name')?.value ?? file;+ const jobs = find(top, 'jobs')?.children ?? [];+ const here = laneOf(platform === 'win32' ? 'windows' : platform === 'darwin' ? 'macos' : 'linux');+ return jobs.map(job => {+ const runsOn = find(job.children, 'runs-on')?.value ?? '';+ const condition = find(job.children, 'if')?.value ?? '';+ const manual = /inputs\.|workflow_dispatch/.test(condition);+ const commands = expandScripts(deepValues(find(job.children, 'steps')?.children ?? [], 'run'), scripts);+ const matrix = find(find(job.children, 'strategy')?.children ?? [], 'matrix');+ const matrixExpression = matrix && /\$\{\{/.test(matrix.value) ? matrix.value : null;+ const maxParallel = find(find(job.children, 'strategy')?.children ?? [], 'max-parallel')?.value;+ const jobPlatform = laneOf(runsOn);+ const jobName = find(job.children, 'name')?.value ?? job.key;+ const testFiles = [...new Set(commands.flatMap(c => [...c.matchAll(TEST_FILE)].map(m => m[1]!)))];+ let tier: LaneTier = 'unit';+ if (jobPlatform !== 'any' && jobPlatform !== here) tier = 'platform';+ else if (/\b(e2e|evals?)\b/i.test(`${name} ${job.key} ${jobName}`)) tier = 'e2e';+ else if (maxParallel === '1' || /serial/i.test(`${job.key} ${jobName}`)) tier = 'serial';+ return {+ id: `${file}/${job.key}`, workflow: file, workflowName: name, job: job.key, jobName, runsOn, platform: jobPlatform, commands, testFiles,+ matrixExpression, tier, runsTests: commands.some(c => TEST_COMMAND.test(c)), manual, source: `.github/workflows/${file}:${job.line}`,+ };+ });+}++/** Every job of every workflow, in file order. */+export function discoverLanes(repoRoot: string, platform: NodeJS.Platform = process.platform): Lane[] {+ const dir = path.join(repoRoot, '.github', 'workflows');+ let names: string[] = [];+ try { names = fs.readdirSync(dir).filter(n => /\.ya?ml$/.test(n)).sort(); } catch { return []; }+ let scripts: Record<string, string> = {};+ try { scripts = JSON.parse(fs.readFileSync(path.join(repoRoot, 'package.json'), 'utf8')).scripts ?? {}; } catch { /* no package scripts */ }+ return names.flatMap(n => { try { return parseWorkflow(n, fs.readFileSync(path.join(dir, n), 'utf8'), platform, scripts); } catch { return []; } });+}++/** One `--explain` line per lane. */+export function describeLane(l: Lane): string {+ const matrix = l.matrixExpression ? ` matrix=${JSON.stringify(l.matrixExpression)}` : '';+ return `${l.id}: tier=${l.tier} platform=${l.platform} runs-on=${l.runsOn || '?'} tests=${l.runsTests ? 'yes' : 'no'}${l.manual ? ' manual' : ''}${matrix}${l.testFiles.length ? ` files=${l.testFiles.join(',')}` : ''} (${l.source})`;+}diff --git a/lib/regen.ts b/lib/regen.tsnew file mode 100644index 000000000..8ad811591--- /dev/null+++ b/lib/regen.ts@@ -0,0 +1,270 @@+/**+ * regen — the generated-file registry `.gstack/generated.json` (plan C4).+ * Every generated file a repo tracks is an entry: the output globs, the one+ * command that regenerates them and (optionally) the input globs that feed+ * it. Two verbs: `check` regenerates in a scratch `git worktree` seeded from+ * the working tree's content fingerprint (never a copy of a tree with+ * node_modules) and reports stale entries without touching the tree; `write`+ * regenerates in place. The /ship Step 3 conflict rule, gstack-restamp and+ * the pre-gate (lib/pregate/regen.ts) consume it.+ *+ * Trust boundary (plan C1): file presence never authorizes execution. The+ * registry is read from the committed copy on origin/<base> by default; the+ * caller opts in to running its commands with --allow-repo-commands or by+ * running under /ship. Containment: outputs and inputs are repo-relative+ * globs (lib/ship-policy.ts rules), commands are single lines under 512+ * bytes, at most 64 entries. Docs: docs/pregate.md#generated.+ */+import { spawnSync } from 'node:child_process';+import { createHash } from 'node:crypto';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import { type ResultCodeName } from './result-codes';+import { containedRelative, globToRegExp, matchesAny } from './ship-policy';++export const GENERATED_PATH = '.gstack/generated.json';+export const GENERATED_SCHEMA = 'https://github.com/garrytan/gstack/docs/pregate.md#generated-v1';+const BIN_DIR = path.dirname(Bun.fileURLToPath(import.meta.url)).replace(/\/lib$/, '/bin');++export interface RegenEntry {+ /** Stable id used in `regen` results and `--only <id>`. */+ id: string;+ /** The one command that regenerates every output; null for outputs regenerated by hand (listed, never run). */+ command: string | null;+ /** Repo-relative globs of the files the command writes. */+ outputs: string[];+ /** Repo-relative globs of the files that feed the command; empty means "always regenerate". */+ inputs: string[];+ /** Free text shown in `list` and `--explain`. */+ note?: string;+}+export interface Registry { $schema?: string; entries: RegenEntry[] }+export interface RegistryError { code: ResultCodeName; path: string; message: string }++const MAX_ENTRIES = 64;+const MAX_COMMAND = 512;+const ID_RE = /^[a-z0-9][a-z0-9_.-]{0,63}$/;++export function validateRegistry(raw: unknown): RegistryError[] {+ const errors: RegistryError[] = [];+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return [{ code: 'REGEN_REGISTRY_INVALID', path: '', message: 'registry must be a JSON object with an `entries` array' }];+ const obj = raw as Record<string, unknown>;+ for (const key of Object.keys(obj)) if (key !== '$schema' && key !== 'entries') errors.push({ code: 'REGEN_REGISTRY_INVALID', path: key, message: 'unknown key; valid keys: entries' });+ if (!Array.isArray(obj.entries)) return [...errors, { code: 'REGEN_REGISTRY_INVALID', path: 'entries', message: 'must be an array' }];+ if (obj.entries.length > MAX_ENTRIES) errors.push({ code: 'REGEN_REGISTRY_INVALID', path: 'entries', message: `more than ${MAX_ENTRIES} entries` });+ const ids = new Set<string>();+ obj.entries.forEach((e: unknown, i: number) => {+ const at = `entries[${i}]`;+ if (!e || typeof e !== 'object' || Array.isArray(e)) { errors.push({ code: 'REGEN_REGISTRY_INVALID', path: at, message: 'must be an object' }); return; }+ const entry = e as Record<string, unknown>;+ for (const key of Object.keys(entry)) if (!['id', 'command', 'outputs', 'inputs', 'note'].includes(key)) errors.push({ code: 'REGEN_REGISTRY_INVALID', path: `${at}.${key}`, message: 'unknown key; valid keys: id, command, outputs, inputs, note' });+ if (typeof entry.id !== 'string' || !ID_RE.test(entry.id)) errors.push({ code: 'REGEN_REGISTRY_INVALID', path: `${at}.id`, message: 'must match [a-z0-9][a-z0-9_.-]{0,63}' });+ else if (ids.has(entry.id)) errors.push({ code: 'REGEN_REGISTRY_INVALID', path: `${at}.id`, message: `duplicate id ${entry.id}` });+ else ids.add(entry.id);+ if (entry.command !== null) {+ if (typeof entry.command !== 'string' || !entry.command.trim()) errors.push({ code: 'REGEN_REGISTRY_INVALID', path: `${at}.command`, message: 'must be a non-empty string or null' });+ else if (entry.command.length > MAX_COMMAND || /[\0\r\n]/.test(entry.command)) errors.push({ code: 'REGEN_CONTAINMENT', path: `${at}.command`, message: `must be one line under ${MAX_COMMAND} characters` });+ }+ for (const key of ['outputs', 'inputs'] as const) {+ const value = entry[key];+ if (value === undefined && key === 'inputs') continue;+ if (!Array.isArray(value) || (key === 'outputs' && value.length === 0)) { errors.push({ code: 'REGEN_REGISTRY_INVALID', path: `${at}.${key}`, message: key === 'outputs' ? 'must be a non-empty array of globs' : 'must be an array of globs' }); continue; }+ if (value.length > MAX_ENTRIES) errors.push({ code: 'REGEN_CONTAINMENT', path: `${at}.${key}`, message: `more than ${MAX_ENTRIES} globs` });+ value.forEach((g: unknown, j: number) => {+ if (typeof g !== 'string') { errors.push({ code: 'REGEN_REGISTRY_INVALID', path: `${at}.${key}[${j}]`, message: 'must be a string' }); return; }+ const why = containedRelative(g);+ if (why) { errors.push({ code: 'REGEN_CONTAINMENT', path: `${at}.${key}[${j}]`, message: `${JSON.stringify(g)} ${why}` }); return; }+ try { globToRegExp(g); } catch (err: any) { errors.push({ code: 'REGEN_CONTAINMENT', path: `${at}.${key}[${j}]`, message: err.message }); }+ });+ }+ if (entry.note !== undefined && typeof entry.note !== 'string') errors.push({ code: 'REGEN_REGISTRY_INVALID', path: `${at}.note`, message: 'must be a string' });+ });+ return errors;+}++export function parseRegistry(text: string): { registry: Registry; errors: RegistryError[] } {+ let raw: unknown;+ try { raw = JSON.parse(text); }+ catch (e: any) { return { registry: { entries: [] }, errors: [{ code: 'REGEN_REGISTRY_INVALID', path: GENERATED_PATH, message: `not valid JSON: ${e.message}` }] }; }+ const errors = validateRegistry(raw);+ if (errors.length) return { registry: { entries: [] }, errors };+ const obj = raw as { $schema?: string; entries: Array<Partial<RegenEntry>> };+ return { registry: { $schema: obj.$schema, entries: obj.entries.map(e => ({ id: e.id!, command: e.command ?? null, outputs: e.outputs!, inputs: e.inputs ?? [], note: e.note })) }, errors: [] };+}++function git(cwd: string, args: string[]): { ok: boolean; out: string; err: string } {+ const r = spawnSync('git', args, { cwd, encoding: 'utf8', timeout: 60_000, maxBuffer: 64 * 1024 * 1024 });+ return { ok: r.status === 0, out: (r.stdout ?? '').trim(), err: (r.stderr ?? '').trim() };+}++export interface RegistrySource { kind: 'base' | 'head' | 'none'; label: string; sha: string | null }+export type RegistryLoad = { registry: Registry; errors: RegistryError[]; present: boolean; source: RegistrySource } | { unavailable: true; base: string; detail: string };++/** The reviewed registry: `.gstack/generated.json` as committed on origin/<base>; unresolvable base is `unavailable` (never a silent fallback). */+export function loadRegistryFromBase(repoRoot: string, base: string): RegistryLoad {+ const ref = `origin/${base.replace(/^origin\//, '')}`;+ const sha = git(repoRoot, ['rev-parse', '--verify', '--quiet', `${ref}^{commit}`]);+ if (!sha.ok || !sha.out) return { unavailable: true, base: base.replace(/^origin\//, ''), detail: `${ref} is not a resolvable commit` };+ const show = git(repoRoot, ['show', `${sha.out}:${GENERATED_PATH}`]);+ if (!show.ok) return { registry: { entries: [] }, errors: [], present: false, source: { kind: 'none', label: `${ref}@${sha.out.slice(0, 12)} (no ${GENERATED_PATH})`, sha: sha.out } };+ return { ...parseRegistry(show.out), present: true, source: { kind: 'base', label: `${ref}@${sha.out.slice(0, 12)}:${GENERATED_PATH}`, sha: sha.out } };+}++/** The working-tree registry: unreviewed, labeled so in every record. */+export function loadRegistryFromHead(repoRoot: string): RegistryLoad {+ const file = path.join(repoRoot, GENERATED_PATH);+ if (!fs.existsSync(file)) return { registry: { entries: [] }, errors: [], present: false, source: { kind: 'none', label: `head (no ${GENERATED_PATH})`, sha: null } };+ return { ...parseRegistry(fs.readFileSync(file, 'utf8')), present: true, source: { kind: 'head', label: `head (unreviewed) ${GENERATED_PATH}`, sha: null } };+}++export function isRegistryUnavailable(load: RegistryLoad): load is { unavailable: true; base: string; detail: string } {+ return (load as any).unavailable === true;+}++/** Entries whose inputs or outputs intersect `touched`; every entry when `touched` is undefined or an entry declares no inputs. */+export function selectEntries(registry: Registry, touched?: readonly string[]): RegenEntry[] {+ if (!touched) return registry.entries;+ return registry.entries.filter(e => e.inputs.length === 0 || touched.some(t => matchesAny(e.inputs, t) || matchesAny(e.outputs, t)));+}++/** The working-tree content fingerprint (bin/gstack-wtree): tracked and untracked non-ignored files. */+export function wtreeFingerprint(repoRoot: string): string | null {+ const r = spawnSync(path.join(BIN_DIR, 'gstack-wtree'), [], { cwd: repoRoot, encoding: 'utf8', timeout: 60_000 });+ const out = (r.stdout ?? '').trim();+ return r.status === 0 && /^[0-9a-f]{40,64}$/.test(out) ? out : null;+}++export interface Scratch { dir: string; wtree: string; remove: () => void }++/**+ * A detached `git worktree` seeded from the working tree's content+ * fingerprint, with the repository's ignored node_modules linked in (a+ * symlink, never a copy). The caller removes it; a failure to create it is an+ * Error naming the step.+ */+export function scratchWorktree(repoRoot: string, prefix = 'gstack-regen-'): Scratch {+ const wtree = wtreeFingerprint(repoRoot);+ if (!wtree) throw new Error('cannot fingerprint the working tree (gstack-wtree failed)');+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));+ fs.rmSync(dir, { recursive: true, force: true });+ const add = git(repoRoot, ['worktree', 'add', '--detach', '-q', dir, 'HEAD']);+ if (!add.ok) throw new Error(`cannot create the scratch worktree: ${add.err}`);+ const remove = () => { git(repoRoot, ['worktree', 'remove', '--force', dir]); fs.rmSync(dir, { recursive: true, force: true }); git(repoRoot, ['worktree', 'prune']); };+ const seed = git(dir, ['read-tree', '--reset', '-u', wtree]);+ if (!seed.ok) { remove(); throw new Error(`cannot seed the scratch worktree: ${seed.err}`); }+ const nm = path.join(repoRoot, 'node_modules');+ if (fs.existsSync(nm) && !fs.existsSync(path.join(dir, 'node_modules')) && git(repoRoot, ['check-ignore', '-q', 'node_modules']).ok) {+ try { fs.symlinkSync(nm, path.join(dir, 'node_modules'), 'dir'); } catch { /* the command runs without deps */ }+ }+ return { dir, wtree, remove };+}++export interface EntryResult {+ id: string; command: string | null;+ status: 'fresh' | 'stale' | 'failed' | 'listed' | 'written' | 'skipped';+ /** Output files whose bytes changed (stale) or were written. */+ changed: string[];+ /** Files the command wrote outside its declared outputs (a refusal in `check`). */+ outside: string[];+ exit?: number | null; stderr?: string; ms: number;+ /** The exact command an author runs to refresh the entry. */+ fix: string;+}++/** Working tree vs the seeded index in a scratch worktree: modified tracked files plus new untracked ones. */+function changedPaths(dir: string): string[] {+ const modified = git(dir, ['diff', '--name-only', '-z']).out.split('\0');+ const deleted = git(dir, ['ls-files', '--deleted', '-z']).out.split('\0');+ const untracked = git(dir, ['ls-files', '--others', '--exclude-standard', '-z']).out.split('\0');+ return [...new Set([...modified, ...deleted, ...untracked])].filter(p => p && p !== 'node_modules').sort();+}++/** sha256 per tracked and untracked non-ignored file (write mode compares two of these). */+function snapshotFiles(root: string): Map<string, string> {+ const out = new Map<string, string>();+ for (const rel of git(root, ['ls-files', '-co', '--exclude-standard', '-z']).out.split('\0').filter(Boolean)) {+ try { out.set(rel, createHash('sha256').update(fs.readFileSync(path.join(root, rel))).digest('hex')); } catch { out.set(rel, 'missing'); }+ }+ return out;+}+function diffSnapshots(a: Map<string, string>, b: Map<string, string>): string[] {+ const changed = new Set<string>();+ for (const [k, v] of b) if (a.get(k) !== v) changed.add(k);+ for (const k of a.keys()) if (!b.has(k)) changed.add(k);+ return [...changed].filter(p => p !== 'node_modules').sort();+}++function runCommand(cwd: string, command: string, env: NodeJS.ProcessEnv, timeoutMs: number): { exit: number | null; stderr: string } {+ const r = spawnSync('bash', ['-c', `set -o pipefail; ${command}`], { cwd, encoding: 'utf8', timeout: timeoutMs, maxBuffer: 64 * 1024 * 1024, env: { ...env, GSTACK_REGEN_SCRATCH: cwd } });+ return { exit: r.status, stderr: ((r.stderr ?? '') + (r.error ? `\n${r.error.message}` : '')).trim().slice(-4000) };+}++export interface RunRegenOptions {+ repoRoot: string; registry: Registry; mode: 'check' | 'write';+ /** Restrict to these entry ids. */+ only?: string[];+ /** Restrict to entries whose inputs or outputs intersect these paths. */+ touched?: string[];+ env?: NodeJS.ProcessEnv; timeoutMs?: number;+}++/**+ * `check`: run every selected command in one scratch worktree and compare its+ * outputs with the working tree; `write`: run them in the repository. An+ * entry with `command: null` is `listed` (its fix line names the outputs an+ * author refreshes by hand). Never runs a command the caller did not opt into:+ * the bin enforces --allow-repo-commands before calling this.+ */+export function runRegen(o: RunRegenOptions): { results: EntryResult[]; wtree: string | null } {+ const entries = selectEntries(o.registry, o.touched).filter(e => !o.only || o.only.includes(e.id));+ const timeout = o.timeoutMs ?? 600_000;+ const results: EntryResult[] = [];+ let scratch: Scratch | null = null;+ const fixFor = (e: RegenEntry) => e.command ? `${e.command} # then commit ${e.outputs.join(' ')}` : `regenerate by hand: ${e.outputs.join(' ')}${e.note ? ` (${e.note})` : ''}`;+ try {+ if (o.mode === 'check' && entries.some(e => e.command)) scratch = scratchWorktree(o.repoRoot);+ for (const e of entries) {+ const started = Date.now();+ if (!e.command) { results.push({ id: e.id, command: null, status: 'listed', changed: [], outside: [], ms: 0, fix: fixFor(e) }); continue; }+ const cwd = o.mode === 'check' ? scratch!.dir : o.repoRoot;+ const before = o.mode === 'write' ? snapshotFiles(o.repoRoot) : null;+ const run = runCommand(cwd, e.command, o.env ?? process.env, timeout);+ const after = before ? diffSnapshots(before, snapshotFiles(o.repoRoot)) : changedPaths(cwd);+ const changed = after.filter(p => matchesAny(e.outputs, p));+ const outside = after.filter(p => !matchesAny(e.outputs, p) && !matchesAny(o.registry.entries.flatMap(x => x.outputs), p));+ const ms = Date.now() - started;+ if (run.exit !== 0) { results.push({ id: e.id, command: e.command, status: 'failed', changed, outside, exit: run.exit, stderr: run.stderr, ms, fix: fixFor(e) }); continue; }+ if (o.mode === 'check') {+ results.push({ id: e.id, command: e.command, status: changed.length || outside.length ? 'stale' : 'fresh', changed, outside, exit: 0, ms, fix: fixFor(e) });+ // Reset the scratch so the next entry's diff is its own.+ git(cwd, ['checkout', '-q', '--', '.']); git(cwd, ['clean', '-fdq']);+ } else results.push({ id: e.id, command: e.command, status: changed.length ? 'written' : 'fresh', changed, outside, exit: 0, ms, fix: fixFor(e) });+ }+ } finally { scratch?.remove(); }+ return { results, wtree: scratch?.wtree ?? wtreeFingerprint(o.repoRoot) };+}++/** One line per entry, the way `gstack-regen` and the pre-gate print them. */+export function renderEntry(r: EntryResult): string {+ const head = `regen ${r.id}: ${r.status}${r.ms ? ` (${r.ms} ms)` : ''}`;+ if (r.status === 'fresh' || r.status === 'skipped') return head;+ if (r.status === 'listed') return `${head} — ${r.fix}`;+ if (r.status === 'failed') return `${head} — exit ${r.exit}: ${(r.stderr ?? '').split('\n').pop() ?? ''}; fix: run \`${r.command}\` and read its output (REGEN_COMMAND_FAILED)`;+ const parts = [head];+ if (r.changed.length) parts.push(`stale: ${r.changed.join(' ')}`);+ if (r.outside.length) parts.push(`outside declared outputs: ${r.outside.join(' ')}`);+ parts.push(`fix: ${r.fix}${r.status === 'stale' ? ' (REGEN_STALE)' : ''}`);+ return parts.join(' — ');+}++/** The example `init` writes. */+export function exampleRegistryJson(): string {+ const example: Registry = {+ $schema: GENERATED_SCHEMA,+ entries: [+ { id: 'example', command: 'npm run generate', outputs: ['generated/**'], inputs: ['src/schema/**'], note: 'replace with the repo’s own generator; command: null lists outputs regenerated by hand' },+ ],+ };+ return JSON.stringify(example, null, 2) + '\n';+}diff --git a/lib/result-codes.ts b/lib/result-codes.tsindex 8f9bccd22..bda442681 100644--- a/lib/result-codes.ts+++ b/lib/result-codes.ts@@ -317,6 +317,77 @@ export const RESULT_CODES = {summary: 'the selected outside-voice runner cannot run here (CLI missing, no API key, or no result file for host-subagent)',fix: 'install or log in the CLI (`gstack-codex-login` from OPENAI_API_KEY), set an API key for `--runner api`, or pass `--result <file> --model <id>` for `--runner host-subagent`',},+ // C-pregate (plan C4, C6, C8): generated-file registry, issue links, the cheap pre-gate.+ REGEN_REGISTRY_INVALID: {+ anchor: 'regen-registry-invalid',+ summary: '.gstack/generated.json is not valid JSON, has an unknown key, a missing field or a duplicate id',+ fix: 'run `gstack-regen validate`, compare with `gstack-regen init --explain`, and fix the file on the base branch',+ },+ REGEN_CONTAINMENT: {+ anchor: 'regen-containment',+ summary: 'a registry glob escapes the repository or a command is not one line under 512 bytes',+ fix: 'use repo-relative globs without `..`, at most 64 per list, and a single-line command',+ },+ REGEN_STALE: {+ anchor: 'regen-stale',+ summary: 'a generated output differs from what its registered command produces (stale, or hand-edited)',+ fix: 'run the printed regen command and commit the outputs; never hand-merge a generated file',+ },+ REGEN_COMMAND_FAILED: {+ anchor: 'regen-command-failed',+ summary: 'a registered regen command exited non-zero in the scratch worktree',+ fix: 'run the command by hand in the repository, read its output, fix the generator or its inputs',+ },+ PREGATE_CONFIG_INVALID: {+ anchor: 'pregate-config-invalid',+ summary: '.gstack/pregate.json has an unknown key, a wrong type, a non-downgradable check in `warn`, or an uncontained glob',+ fix: 'run `gstack-pregate validate` and fix the file on the base branch (secrets and required lanes cannot be downgraded)',+ },+ PREGATE_SECRETS: {+ anchor: 'pregate-secrets',+ summary: 'gstack-redact found a HIGH or MEDIUM finding in the branch’s added lines',+ fix: 'rotate the credential, remove it from the added lines (git history included), then rerun; `secrets` cannot be downgraded',+ },+ PREGATE_STRAYS: {+ anchor: 'pregate-strays',+ summary: 'a file was added at the repository root or outside the usual directories (scratch, tmp, zz-*)',+ fix: 'delete the stray or move it under a tracked directory; declare an intentional root file in .gstack/pregate.json `strays.allow`',+ },+ PREGATE_LITERALS: {+ anchor: 'pregate-literals',+ summary: 'a changed exported constant’s old value still appears in the test tree (nightly- and Heavy-only files included)',+ fix: 'update every listed test to the new value, or keep the old constant; a nightly-only file is still a consumer',+ },+ PREGATE_NO_LANE: {+ anchor: 'pregate-no-lane',+ summary: 'a touched file maps to no test lane through imports, repo-path literals, the bin/<name> convention or a declaration',+ fix: 'add a test that names the file, or declare its lane (or an explicit empty lane) under `dependencies` in .gstack/pregate.json',+ },+ PREGATE_LANE_FAILED: {+ anchor: 'pregate-lane-failed',+ summary: 'a local test lane the touched files select failed or ran zero tests under pipefail',+ fix: 'read the lane log, fix the in-branch failure, rerun `gstack-pregate --stage tests`; a `| tail`-hidden exit is still a failure',+ },+ PREGATE_INCOMPLETE: {+ anchor: 'pregate-incomplete',+ summary: 'a check timed out, its tool is unavailable, or the tree changed while it ran; the result is incomplete, never pass',+ fix: 'install the named tool or raise --timeout, keep the tree still during the run, then rerun the check',+ },+ PREGATE_STALE: {+ anchor: 'pregate-stale',+ summary: 'pregate.json was recorded against a different tree than the one being published',+ fix: 'rerun `gstack-pregate` after the final generation and stamp; publication needs results that are current',+ },+ PREGATE_REMOTE_UNCLEARED: {+ anchor: 'pregate-remote-uncleared',+ summary: 'a requires-remote lane obligation (a platform lane this machine cannot run) has no matching receipt',+ fix: 'dispatch the named workflow job, then pass its run id with `gstack-pregate clear --remote <workflow/job> --run-url <url>` (or an evidence bundle lane) before publishing',+ },+ ISSUE_UNREADABLE: {+ anchor: 'issue-unreadable',+ summary: 'an issue a closure trailer or --issue names could not be read through gstack-issue-guard, so its link is Refs, never Fixes',+ fix: 'check `gh auth status` and the issue number; rerun gstack-issue-links once the issue reads',+ },} as const satisfies Record<string, ResultCode>;export type ResultCodeName = keyof typeof RESULT_CODES;diff --git a/lib/runtime-pins.ts b/lib/runtime-pins.tsindex 7f7652116..9eae9c67a 100644--- a/lib/runtime-pins.ts+++ b/lib/runtime-pins.ts@@ -112,7 +112,7 @@ export function classify(constraint: string): Pin['kind'] {return writtenParts(trimmed) === 3 ? 'exact' : 'range';}-function laneOf(runsOn: string): Lane {+export function laneOf(runsOn: string): Lane {const value = runsOn.toLowerCase();if (value.includes('windows')) return 'windows';if (value.includes('macos')) return 'macos';diff --git a/lib/ship-receipt.ts b/lib/ship-receipt.tsindex 63b08c08e..f4dcd3f7d 100644--- a/lib/ship-receipt.ts+++ b/lib/ship-receipt.ts@@ -12,6 +12,7 @@ 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',];/** Keys in the fixed order so identifiers lead; undefined values are dropped. */diff --git a/package.json b/package.jsonindex 4fb506e3a..8efc3d89e 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "gstack",- "version": "1.91.75",+ "version": "1.91.77","description": "Garry's Stack — Claude Code skills + fast headless browser. One repo, one install, entire AI engineering workflow.","license": "MIT","type": "module",diff --git a/scripts/gen-ship-goldens.ts b/scripts/gen-ship-goldens.tsnew file mode 100644index 000000000..374c11347--- /dev/null+++ b/scripts/gen-ship-goldens.ts@@ -0,0 +1,44 @@+/**+ * gen-ship-goldens — refresh the byte-pinned /ship renders under+ * test/fixtures/golden/ (test/host-config.test.ts compares a fresh render to+ * them). The claude golden is the tracked ship/SKILL.md; the codex, factory+ * and agy goldens come from a `--out-dir` render of each host. Registered in+ * .gstack/generated.json so `gstack-regen check` reports a stale golden+ * before any remote gate and `gstack-regen write` refreshes it.+ */+import { spawnSync } from 'node:child_process';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';++const ROOT = path.resolve(import.meta.dir, '..');+const GOLDEN_DIR = path.join(ROOT, 'test', 'fixtures', 'golden');+const HOSTS: Array<{ host: string; dir: string }> = [+ { host: 'codex', dir: '.agents' },+ { host: 'factory', dir: '.factory' },+ { host: 'agy', dir: '.agy' },+];++export function generateShipGoldens(): string[] {+ const written: string[] = [];+ const out = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-ship-goldens-'));+ try {+ const copy = (from: string, to: string) => {+ const bytes = fs.readFileSync(from);+ const dest = path.join(GOLDEN_DIR, to);+ if (!fs.existsSync(dest) || !fs.readFileSync(dest).equals(bytes)) { fs.writeFileSync(dest, bytes); written.push(path.relative(ROOT, dest)); }+ };+ copy(path.join(ROOT, 'ship', 'SKILL.md'), 'claude-ship-SKILL.md');+ for (const { host, dir } of HOSTS) {+ const r = spawnSync('bun', ['run', path.join(ROOT, 'scripts', 'gen-skill-docs.ts'), '--host', host, '--out-dir', out], { cwd: ROOT, encoding: 'utf8', timeout: 180_000 });+ if (r.status !== 0) throw new Error(`gen-skill-docs --host ${host} --out-dir failed (exit ${r.status}):\n${r.stderr}`);+ copy(path.join(out, dir, 'skills', 'gstack-ship', 'SKILL.md'), `${host}-ship-SKILL.md`);+ }+ } finally { fs.rmSync(out, { recursive: true, force: true }); }+ return written;+}++if (import.meta.main) {+ const written = generateShipGoldens();+ console.log(written.length ? `GENERATED: ${written.join(' ')}` : 'ship goldens: fresh');+}diff --git a/scripts/harness-version.json b/scripts/harness-version.jsonindex 383bd55dd..2dca53298 100644--- a/scripts/harness-version.json+++ b/scripts/harness-version.json@@ -16,7 +16,7 @@"scripts/lib/published-text.ts": {"blob":"3f2e4d616b5dd0204035710c66b64d49055c5714","since":4},"scripts/lib/shard-engine.ts": {"blob":"3cd0b1aaa84018b00bf9ea0ce48093f3c8492f66","since":4},"scripts/test-paid-shards.ts": {"blob":"8ddee5f11ed7856876135520dd8025ab989e2db9","since":4},- "scripts/test-pr-profile.ts": {"blob":"2adf1e8dbc1129169fa6dccf2e0b14d7b7fdb698","since":4,"nonBehavioral":"HONEST_WORK_GATE_INTEGRITY: PR_PROFILE_CASE_IDS and PR_PROFILE_TEST_FILES gain review-gate-integrity; selection only, no case verdict rule changes"},+ "scripts/test-pr-profile.ts": {"blob":"1b3c215f8f50901c16357665a585101eaa27ff31","since":4,"nonBehavioral":"C-pregate: FREE_ONLY_PR_FILES gains .gstack/generated.json and .gstack/pregate.json (gstack's own pin files, read by no paid case); selection only, no case verdict rule changes"},"scripts/test-strict-output.ts": {"blob":"01185d20dc9761b04b9b2f751ec98664fe0eaf93","since":4},"test/helpers/agent-sdk-runner.ts": {"blob":"210bba92d241a90df578b2c7fc943ac5755d0025","since":4},"test/helpers/auq-substance-panel.ts": {"blob":"4881260ef793668e4963a062db6d06a5e1f7a40f","since":4},diff --git a/scripts/lib/windows-curation.ts b/scripts/lib/windows-curation.tsindex ce59e885a..6339e0ed6 100644--- a/scripts/lib/windows-curation.ts+++ b/scripts/lib/windows-curation.ts@@ -51,6 +51,14 @@ const WINDOWS_FRAGILE_PATTERNS: Array<{ pattern: RegExp; reason: string }> = [// when possible; this list is for environment-/runtime-specific tests where// the failure mode is structural rather than detectable via source-file scan.export const KNOWN_WINDOWS_INCOMPATIBLE: Array<{ file: string; reason: string }> = [+ // C-pregate: these drive bin/gstack-regen, bin/gstack-pregate, bin/gstack-issue-links and+ // bin/gstack-ship-receipt through test/helpers/pregate-fixture.ts runBin (spawnSync on the+ // shebang file, which CreateProcess cannot exec) and run `node gen.js` / `node --test` fixture+ // commands through the pre-gate's POSIX `bash -o pipefail` runner. The pure parsers and the+ // import graph are covered by test/pregate-selection.test.ts, which the bin/ pattern excludes too.+ { file: 'test/gstack-regen.test.ts', reason: 'spawns bin/gstack-regen through test/helpers/pregate-fixture.ts runBin (shebang via CreateProcess) and POSIX fixture regen commands' },+ { file: 'test/pregate-invalidation.test.ts', reason: 'spawns bin/gstack-pregate and bin/gstack-ship-receipt through test/helpers/pregate-fixture.ts runBin (shebang via CreateProcess) and the pipefail lane runner' },+ { file: 'test/ship-issue-intent.test.ts', reason: 'spawns bin/gstack-issue-links and bin/gstack-ship-receipt through test/helpers/pregate-fixture.ts runBin (shebang via CreateProcess) with a `gh` shell shim on PATH' },{file: 'test/ship-measure-seeded-fixture.test.ts',reason: 'drives a POSIX shell stub project (`./evals.sh` with a shebang) that CreateProcess cannot exec; the measure runner itself is covered by ship-measure.test.ts with in-process fake runners',diff --git a/scripts/test-pr-profile.ts b/scripts/test-pr-profile.tsindex 2adf1e8db..1b3c215f8 100644--- a/scripts/test-pr-profile.ts+++ b/scripts/test-pr-profile.ts@@ -212,6 +212,8 @@ export const FREE_ONLY_PR_FILES = ['scripts/ubicloud/**','tsconfig.test.json', // Read only by `tsc -p tsconfig.test.json` (typecheck:test); Bun's runtime reads tsconfig.json.'.gitignore', // Changes which untracked files git reports, never tracked content a case reads.+ '.gstack/generated.json', // gstack's own regen registry: gstack-regen/gstack-pregate read it from origin/<base> of the repo they run in; paid cases run in fixture repos.+ '.gstack/pregate.json', // gstack's own pre-gate policy: same trust boundary, same reason.'scripts/retired-command.ts', // One-release stubs for retired package scripts; no paid case imports it.'careful/bin/check-careful.sh', // /careful PreToolUse hook: covered by test/hook-scripts.test.ts; no paid fixture copies or runs it.// Reporting and launch tools: they read CI history or start a lane, never run inside a paid case.diff --git a/ship/sections/pr-body.md b/ship/sections/pr-body.mdindex 5d4323028..5bcfe857e 100644--- a/ship/sections/pr-body.md+++ b/ship/sections/pr-body.md@@ -117,6 +117,11 @@ unavailable results as passing.>"Close #N manually after follow-up lands." Include archive filename and filed date.Without a valid match, omit this entire section.>+## Issues+<The lines `gstack-issue-links --base <base> [--issue <n>] [--ci-run <id>] --out .gstack/tmp/issues.json`+prints: Fixes only from a Fixes/Closes trailer or --issue, Refs otherwise,+Flake: #N for failing run ids. Omit when it prints none.>+## Verification Results<Step 8.1 obligations executed at Step 9: N PASS, M FAIL, K BLOCKED, J NOT RUN,not-applicable reasons, unresolved obligations and accepted deferrals.@@ -184,13 +189,15 @@ per-lane counts (`{"<lane>":{"pass":N,"fail":N,"skip":N}}`) to`.gstack/tmp/ship-gate.json` with your file-write tool, then:```bash-~/.claude/skills/gstack/bin/gstack-ship-receipt write --pr <pr-number> --base <base> --gate @.gstack/tmp/ship-gate.json --body "$PR_BODY_FILE"+~/.claude/skills/gstack/bin/gstack-ship-receipt write --pr <pr-number> --base <base> --gate @.gstack/tmp/ship-gate.json --pregate .gstack/tmp/pregate.json --issues @.gstack/tmp/issues.json --body "$PR_BODY_FILE"```Add `--receipt .gstack/tmp/tree-receipt.json` only when Step 16 wrote it (gate-ahead).New PR/MR: omit `--pr`, then rerun with the number after creation and repost the body.Its `SHIP_RECEIPT:` line opens the completion message. `RECEIPT_INVALID` names the bad-field: fix that input file and rerun; nothing was written.+field: fix that input file and rerun; nothing was written. `PREGATE_STALE` means rerun+`gstack-pregate` on the stamped tree; `PREGATE_REMOTE_UNCLEARED` needs+`gstack-pregate clear` with the run URL. Both stop publication.In each block below, restore the literal `PR_BODY_FILE` path and substitute Step 18'stitle file name; `gstack-post` detects GitHub or GitLab from the remote and the repo'sdiff --git a/ship/sections/pr-body.md.tmpl b/ship/sections/pr-body.md.tmplindex b9acdc969..7d4200e98 100644--- a/ship/sections/pr-body.md.tmpl+++ b/ship/sections/pr-body.md.tmpl@@ -108,6 +108,11 @@ unavailable results as passing.>"Close #N manually after follow-up lands." Include archive filename and filed date.Without a valid match, omit this entire section.>+## Issues+<The lines `gstack-issue-links --base <base> [--issue <n>] [--ci-run <id>] --out .gstack/tmp/issues.json`+prints: Fixes only from a Fixes/Closes trailer or --issue, Refs otherwise,+Flake: #N for failing run ids. Omit when it prints none.>+## Verification Results<Step 8.1 obligations executed at Step 9: N PASS, M FAIL, K BLOCKED, J NOT RUN,not-applicable reasons, unresolved obligations and accepted deferrals.@@ -167,13 +172,15 @@ per-lane counts (`{"<lane>":{"pass":N,"fail":N,"skip":N}}`) to`.gstack/tmp/ship-gate.json` with your file-write tool, then:```bash-~/.claude/skills/gstack/bin/gstack-ship-receipt write --pr <pr-number> --base <base> --gate @.gstack/tmp/ship-gate.json --body "$PR_BODY_FILE"+~/.claude/skills/gstack/bin/gstack-ship-receipt write --pr <pr-number> --base <base> --gate @.gstack/tmp/ship-gate.json --pregate .gstack/tmp/pregate.json --issues @.gstack/tmp/issues.json --body "$PR_BODY_FILE"```Add `--receipt .gstack/tmp/tree-receipt.json` only when Step 16 wrote it (gate-ahead).New PR/MR: omit `--pr`, then rerun with the number after creation and repost the body.Its `SHIP_RECEIPT:` line opens the completion message. `RECEIPT_INVALID` names the bad-field: fix that input file and rerun; nothing was written.+field: fix that input file and rerun; nothing was written. `PREGATE_STALE` means rerun+`gstack-pregate` on the stamped tree; `PREGATE_REMOTE_UNCLEARED` needs+`gstack-pregate clear` with the run URL. Both stop publication.In each block below, restore the literal `PR_BODY_FILE` path and substitute Step 18'stitle file name; `gstack-post` detects GitHub or GitLab from the remote and the repo'sdiff --git a/ship/sections/tests.md b/ship/sections/tests.mdindex b5c0da5cb..b243e4c5e 100644--- a/ship/sections/tests.md+++ b/ship/sections/tests.md@@ -207,6 +207,18 @@ Only commit if there are changes. Stage the bootstrap's own files by name (confi## Step 5: Run tests (on merged code)+**Pre-gate first** — free, before any lane, eval or remote gate:++```bash+~/.claude/skills/gstack/bin/gstack-pregate --allow-repo-commands+```++Stage 1 (regen, secrets, strays, literals) is the two-minute preflight; stage 2+runs the local lanes the touched files select under pipefail and prints+`requires-remote` for platform lanes this machine cannot run. `fail` or+`incomplete` blocks: fix, rerun (`--explain` shows each mapping). Step 18 refuses+a stale `pregate.json`, so rerun it after the final stamp.+Use the project's test commands discovered in Step 4 or documented in CLAUDE.md/AGENTS.md. Run every applicable suite; do not assume Rails or Vitest. The commands below are examples only for repositories that actually provide them. Use the same lane labels and exact commands again in Step 16.**If no applicable test suite exists:** Name the untested scope. AskUserQuestion:@@ -229,9 +241,10 @@ records `{command, exit, working-tree fingerprint, log path}` torecord instead of re-running when the content hasn't changed:```bash-~/.claude/skills/gstack/bin/gstack-evidence run --label tests -- 'bin/test-lane 2>&1' &-~/.claude/skills/gstack/bin/gstack-evidence run --label vitest -- 'npm run test 2>&1' &-wait+set -o pipefail; pids=()+~/.claude/skills/gstack/bin/gstack-evidence run --label tests -- 'bin/test-lane 2>&1' & pids+=($!)+~/.claude/skills/gstack/bin/gstack-evidence run --label vitest -- 'npm run test 2>&1' & pids+=($!)+fail=0; for p in "${pids[@]}"; do wait "$p" || fail=1; done; echo "lanes failed=$fail"```After all suites complete, check the `gstack-evidence: recorded label=... exit=...diff --git a/ship/sections/tests.md.tmpl b/ship/sections/tests.md.tmplindex 82ce967ea..9ff92a1a6 100644--- a/ship/sections/tests.md.tmpl+++ b/ship/sections/tests.md.tmpl@@ -6,6 +6,18 @@## Step 5: Run tests (on merged code)+**Pre-gate first** — free, before any lane, eval or remote gate:++```bash+~/.claude/skills/gstack/bin/gstack-pregate --allow-repo-commands+```++Stage 1 (regen, secrets, strays, literals) is the two-minute preflight; stage 2+runs the local lanes the touched files select under pipefail and prints+`requires-remote` for platform lanes this machine cannot run. `fail` or+`incomplete` blocks: fix, rerun (`--explain` shows each mapping). Step 18 refuses+a stale `pregate.json`, so rerun it after the final stamp.+Use the project's test commands discovered in Step 4 or documented in CLAUDE.md/AGENTS.md. Run every applicable suite; do not assume Rails or Vitest. The commands below are examples only for repositories that actually provide them. Use the same lane labels and exact commands again in Step 16.**If no applicable test suite exists:** Name the untested scope. AskUserQuestion:@@ -28,9 +40,10 @@ records `{command, exit, working-tree fingerprint, log path}` torecord instead of re-running when the content hasn't changed:```bash-~/.claude/skills/gstack/bin/gstack-evidence run --label tests -- 'bin/test-lane 2>&1' &-~/.claude/skills/gstack/bin/gstack-evidence run --label vitest -- 'npm run test 2>&1' &-wait+set -o pipefail; pids=()+~/.claude/skills/gstack/bin/gstack-evidence run --label tests -- 'bin/test-lane 2>&1' & pids+=($!)+~/.claude/skills/gstack/bin/gstack-evidence run --label vitest -- 'npm run test 2>&1' & pids+=($!)+fail=0; for p in "${pids[@]}"; do wait "$p" || fail=1; done; echo "lanes failed=$fail"```After all suites complete, check the `gstack-evidence: recorded label=... exit=...diff --git a/test/fixtures/module-size-ratchet.json b/test/fixtures/module-size-ratchet.jsonindex a3a636742..98f522ac1 100644--- a/test/fixtures/module-size-ratchet.json+++ b/test/fixtures/module-size-ratchet.json@@ -78,7 +78,21 @@{ "file": "lib/autoplan-export.ts", "movedFrom": "(new: the unattended export file set, B2/B12)" },{ "file": "lib/spec-review-cap.ts", "movedFrom": "(new: the spec-review loop at the cap: numbered gaps and deterministic fix verification, B8)" },{ "file": "bin/gstack-autoplan", "movedFrom": "(new: thin entrypoint over lib/autoplan-run.ts, B2)" },- { "file": "bin/gstack-outside-voice", "movedFrom": "(new: thin entrypoint over lib/outside-voice-runner.ts, B3)" }+ { "file": "bin/gstack-outside-voice", "movedFrom": "(new: thin entrypoint over lib/outside-voice-runner.ts, B3)" },+ { "file": "lib/regen.ts", "movedFrom": "(new: the generated-file registry, scratch-worktree freshness check and in-place write, C4)" },+ { "file": "lib/issue-links.ts", "movedFrom": "(new: issue closure intent, Refs/Fixes classification and flake-issue mapping for Step 18, C6)" },+ { "file": "lib/pregate/types.ts", "movedFrom": "(new: the pre-gate check and context contracts, C8)" },+ { "file": "lib/pregate/config.ts", "movedFrom": "(new: .gstack/pregate.json schema, containment and base-branch loader, C8)" },+ { "file": "lib/pregate/workflows.ts", "movedFrom": "(new: lane discovery from .github/workflows, C8)" },+ { "file": "lib/pregate/import-graph.ts", "movedFrom": "(new: imports ∪ repo-path literals ∪ bin convention ∪ declarations, C8)" },+ { "file": "lib/pregate/context.ts", "movedFrom": "(new: touched files, base inputs and before/after fingerprinting, C8)" },+ { "file": "lib/pregate/lane-selection.ts", "movedFrom": "(new: touched files to lanes, local vs requires-remote, C8)" },+ { "file": "lib/pregate/index.ts", "movedFrom": "(new: the check registry, two-stage runner, pregate.json writer and publication verifier, C8)" },+ { "file": "lib/pregate/checks/regen.ts", "movedFrom": "(new: pre-gate check, C8)" },+ { "file": "lib/pregate/checks/secrets.ts", "movedFrom": "(new: pre-gate check, C8)" },+ { "file": "lib/pregate/checks/strays.ts", "movedFrom": "(new: pre-gate check, C8)" },+ { "file": "lib/pregate/checks/literals.ts", "movedFrom": "(new: pre-gate check, C8)" },+ { "file": "lib/pregate/checks/lanes.ts", "movedFrom": "(new: pre-gate check with the pipefail runner and requires-remote obligations, C8)" }],"residualFiles": [{ "file": "scripts/test-free-shards.ts", "maxLines": 2361, "reason": "free lane policy after the shard engine took spawn, sandbox, logs, seeds and flags" },diff --git a/test/fixtures/multi-agent-wave/INCIDENTS.md b/test/fixtures/multi-agent-wave/INCIDENTS.mdindex 68216488e..578fca36f 100644--- a/test/fixtures/multi-agent-wave/INCIDENTS.md+++ b/test/fixtures/multi-agent-wave/INCIDENTS.md@@ -18,3 +18,10 @@ Later PRs of the wave append their rows; a row is never removed.| p0-2-gate-grammar: `d10 yes`, `1a 2a`, a 33-decision approve-all | B9 | reply strings | `test/gate-list.test.ts` || p0-2-timing: no wall-time record per phase, no pre-run estimate | B10 | analytics history | `test/autoplan-timing.test.ts` || p0-2-urgent-block: a security finding buried in a 400-line record | B12 | findings with `urgent: true` | `test/headless-artifacts.test.ts` "URGENT block" |+| p0-4-stale-goldens: a generated file (ship goldens, agents digest) hand-merged or left stale, caught only by CI | C4, C8 `regen` | `test/helpers/pregate-fixture.ts` repo: `src/version.js` bumped, `generated/digest.md` unchanged; registry on `origin/main` | `test/gstack-regen.test.ts` "stale"; `test/pregate-selection.test.ts` "p0-4-stale-goldens" |+| p0-4-scratch-script: `zz-probe.sh` committed at the repository root | C8 `strays` | fixture repo with `zz-probe.sh`, `notes.txt`, a new top-level directory and a conventional `CONTRIBUTING.md` | `test/pregate-selection.test.ts` "p0-4-scratch-script" |+| p0-4-heavy-old-constant: a nightly-only test kept asserting the old timeout literal | C8 `literals` | `test/nightly/retry-heavy.test.js` asserting `TIMEOUT_MS` 5000 after `lib/retry.js` moves to 9000 | `test/pregate-selection.test.ts` "p0-4-heavy-old-constant" |+| p0-4-windows-lane-unrun: a Windows-only test changed on a Linux box merged with that lane unrun | C8 `lanes` | `test/windows-paths.test.js` touched; `windows.yml/windows-shard` is a planner-computed matrix with a selection manifest | `test/pregate-selection.test.ts` "p0-4-windows-lane-unrun"; `test/pregate-invalidation.test.ts` "uncleared requires-remote" |+| p0-4-pipe-hidden-failure: a failing runner behind `\| tail` reported green; a zero-run lane reported green | C8 `lanes` (pipefail) | runner `node --test {files} 2>&1 \| tail -n 1` with a broken `lib/util.js`; runner that prints `# tests 0` | `test/pregate-selection.test.ts` "p0-4-pipe-hidden-failure" |+| p0-4-stale-pregate: a pre-gate record reused after the final stamp moved the tree | C8 publication | pregate.json recorded, then `README.md` edited | `test/pregate-invalidation.test.ts` "PREGATE_STALE for both" |+| p0-4-dropped-vendored-hunk: a `patchedDependencies` hunk silently dropped on regeneration | C8 `patches` (tier 2, deferred) | — | — (follow-up pre-gate PR) |diff --git a/test/gstack-regen.test.ts b/test/gstack-regen.test.tsnew file mode 100644index 000000000..5c527b24e--- /dev/null+++ b/test/gstack-regen.test.ts@@ -0,0 +1,179 @@+/**+ * C4: the generated-file registry. Pins the wire contract (exit codes, result+ * codes, the `regen <id>:` lines, the trust boundary) on fixture repos under+ * os.tmpdir(). Incident p0-4-stale-goldens: a generator input changed, the+ * committed output did not, and `check` catches it in a scratch worktree+ * without touching the tree.+ */+import { afterEach, describe, expect, test } from 'bun:test';+import * as fs from 'node:fs';+import * as path from 'node:path';+import { EXIT } from '../lib/headless-artifacts';+import { parseRegistry, selectEntries, validateRegistry } from '../lib/regen';+import { BASE_REGISTRY, cleanup, commit, makeFixtureRepo, readFile, runBin, write, type FixtureRepo } from './helpers/pregate-fixture';++const repos: FixtureRepo[] = [];+const fixture = (opts?: Parameters<typeof makeFixtureRepo>[0]) => { const r = makeFixtureRepo(opts); repos.push(r); return r; };+afterEach(() => { while (repos.length) cleanup(repos.pop()!); });++describe('validateRegistry (schema + containment, pure)', () => {+ test('the fixture registry validates; command null is a listed entry; inputs default to always', () => {+ expect(validateRegistry(BASE_REGISTRY)).toEqual([]);+ const parsed = parseRegistry(JSON.stringify({ entries: [{ id: 'a', command: 'x', outputs: ['out/**'] }] }));+ expect(parsed.errors).toEqual([]);+ expect(parsed.registry.entries[0]!.inputs).toEqual([]);+ expect(selectEntries(parsed.registry, ['anything']).map(e => e.id)).toEqual(['a']);+ });++ test('unknown keys, duplicate ids, empty outputs and bad commands are REGEN_REGISTRY_INVALID with the path named', () => {+ const codes = (r: unknown) => validateRegistry(r).map(e => `${e.code}:${e.path}`);+ expect(codes({ entries: [{ id: 'a', command: 'x', outputs: ['o'], extra: 1 }] })).toEqual(['REGEN_REGISTRY_INVALID:entries[0].extra']);+ expect(codes({ entries: [{ id: 'a', command: 'x', outputs: ['o'] }, { id: 'a', command: 'y', outputs: ['p'] }] })).toEqual(['REGEN_REGISTRY_INVALID:entries[1].id']);+ expect(codes({ entries: [{ id: 'a', command: 'x', outputs: [] }] })).toEqual(['REGEN_REGISTRY_INVALID:entries[0].outputs']);+ expect(codes({ entries: [{ id: 'A b', command: 'x', outputs: ['o'] }] })).toEqual(['REGEN_REGISTRY_INVALID:entries[0].id']);+ expect(codes({ entries: [{ id: 'a', command: '', outputs: ['o'] }] })).toEqual(['REGEN_REGISTRY_INVALID:entries[0].command']);+ expect(codes([])).toEqual(['REGEN_REGISTRY_INVALID:']);+ expect(codes({ entries: 'x' })).toEqual(['REGEN_REGISTRY_INVALID:entries']);+ });++ test('containment: `..`, absolute paths, newline commands, size and list caps are REGEN_CONTAINMENT', () => {+ const codes = (r: unknown) => validateRegistry(r).map(e => `${e.code}:${e.path}`);+ expect(codes({ entries: [{ id: 'a', command: 'x', outputs: ['../victim/**'] }] })).toEqual(['REGEN_CONTAINMENT:entries[0].outputs[0]']);+ expect(codes({ entries: [{ id: 'a', command: 'x', outputs: ['/etc/*'] }] })).toEqual(['REGEN_CONTAINMENT:entries[0].outputs[0]']);+ expect(codes({ entries: [{ id: 'a', command: 'x', outputs: ['o'], inputs: ['a/../../b'] }] })).toEqual(['REGEN_CONTAINMENT:entries[0].inputs[0]']);+ expect(codes({ entries: [{ id: 'a', command: 'x\nrm -rf /', outputs: ['o'] }] })).toEqual(['REGEN_CONTAINMENT:entries[0].command']);+ expect(codes({ entries: [{ id: 'a', command: 'x'.repeat(513), outputs: ['o'] }] })).toEqual(['REGEN_CONTAINMENT:entries[0].command']);+ expect(codes({ entries: [{ id: 'a', command: 'x', outputs: Array.from({ length: 65 }, (_, i) => `o${i}`) }] })).toEqual(['REGEN_CONTAINMENT:entries[0].outputs']);+ expect(codes({ entries: Array.from({ length: 65 }, (_, i) => ({ id: `e${i}`, command: 'x', outputs: ['o'] })) })).toEqual(['REGEN_REGISTRY_INVALID:entries']);+ });++ test('selectEntries: touched inputs or outputs select an entry; untouched entries with inputs are skipped', () => {+ const { registry } = parseRegistry(JSON.stringify(BASE_REGISTRY));+ expect(selectEntries(registry, ['src/version.js']).map(e => e.id)).toEqual(['digest', 'goldens']);+ expect(selectEntries(registry, ['generated/digest.md']).map(e => e.id)).toEqual(['digest']);+ expect(selectEntries(registry, ['README.md']).map(e => e.id)).toEqual([]);+ expect(selectEntries(registry).map(e => e.id)).toEqual(['digest', 'goldens']);+ });+});++describe('gstack-regen (bin)', () => {+ test('--help prints the exit table; no command and unknown commands are usage (2)', () => {+ const repo = fixture();+ expect(runBin(repo, 'gstack-regen', ['--help']).out).toContain('Exit codes: 0 ok · 1 fail · 2 usage · 3 refused or needs a flag');+ expect(runBin(repo, 'gstack-regen', []).status).toBe(EXIT.usage);+ expect(runBin(repo, 'gstack-regen', ['bogus']).status).toBe(EXIT.usage);+ });++ test('trust boundary: check lists the commands and exits 3 without --allow-repo-commands; nothing runs', () => {+ const repo = fixture();+ const r = runBin(repo, 'gstack-regen', ['check', '--base', 'main']);+ expect(r.status).toBe(EXIT.refused);+ expect(r.err).toContain('(REPO_COMMANDS_NOT_ALLOWED)');+ expect(r.out).toContain('COMMAND: digest="node gen.js" outputs=generated/**');+ expect(r.out).toContain('GSTACK_RESULT: skill=regen status=refused run=');+ expect(runBin(repo, 'gstack-regen', ['check', '--registry-from', 'head']).status).toBe(EXIT.refused);+ });++ test('the registry is read from origin/<base>: a command smuggled into the branch copy is not what runs', () => {+ const repo = fixture();+ commit(repo, { '.gstack/generated.json': JSON.stringify({ entries: [{ id: 'digest', command: 'node -e "require(\'fs\').writeFileSync(\'pwned\',\'x\')"', outputs: ['generated/**'] }] }) + '\n' });+ const r = runBin(repo, 'gstack-regen', ['check', '--base', 'main', '--allow-repo-commands']);+ expect(r.status).toBe(EXIT.ok);+ expect(r.out).toContain('registry: origin/main@');+ expect(r.out).toContain('regen digest: fresh');+ expect(fs.existsSync(path.join(repo.work, 'pwned'))).toBe(false);+ const head = runBin(repo, 'gstack-regen', ['check', '--registry-from', 'head', '--allow-repo-commands']);+ expect(head.out).toContain('registry: head (unreviewed)');+ });++ test('POLICY_SOURCE_UNAVAILABLE when origin/<base> does not resolve; never a silent working-tree fallback', () => {+ const repo = fixture();+ const r = runBin(repo, 'gstack-regen', ['check', '--base', 'nope', '--allow-repo-commands']);+ expect(r.status).toBe(EXIT.refused);+ expect(r.err).toContain('(POLICY_SOURCE_UNAVAILABLE)');+ expect(r.err).toContain('.gstack/generated.json');+ });++ test('p0-4-stale-goldens: a changed input with an unchanged output is stale, caught in a scratch worktree, tree untouched', () => {+ const repo = fixture();+ commit(repo, { 'src/version.js': "module.exports = { VERSION: '1.1.0' };\n" });+ const before = readFile(repo, 'generated/digest.md');+ const r = runBin(repo, 'gstack-regen', ['check', '--base', 'main', '--allow-repo-commands']);+ expect(r.status).toBe(EXIT.fail);+ expect(r.out).toMatch(/^regen digest: stale \(\d+ ms\) — stale: generated\/digest\.md — fix: node gen\.js # then commit generated\/\*\* \(REGEN_STALE\)$/m);+ expect(r.out).toContain('regen goldens: listed — regenerate by hand: test/golden/*.txt (copy the rendered output by hand)');+ expect(r.out).toContain('REGEN: check 1 stale or failed (2 entries)');+ expect(r.out).toMatch(/GSTACK_RESULT: skill=regen status=complete run=[0-9a-f]{40}/);+ expect(readFile(repo, 'generated/digest.md')).toBe(before);+ expect(repo.git('status', '--porcelain')).toBe('');+ expect(repo.git('worktree', 'list').split('\n')).toHaveLength(1);+ });++ test('write regenerates in place and reports the written outputs; a second run is fresh', () => {+ const repo = fixture();+ commit(repo, { 'src/version.js': "module.exports = { VERSION: '1.1.0' };\n" });+ const w = runBin(repo, 'gstack-regen', ['write', '--base', 'main', '--allow-repo-commands']);+ expect(w.status).toBe(EXIT.ok);+ expect(w.out).toContain('regen digest: written');+ expect(w.out).toContain('stale: generated/digest.md');+ expect(readFile(repo, 'generated/digest.md')).toBe('# digest v1.1.0\n');+ const again = runBin(repo, 'gstack-regen', ['check', '--base', 'main', '--allow-repo-commands', '--json']);+ expect(again.status).toBe(EXIT.ok);+ const parsed = JSON.parse(again.out);+ expect(parsed.results.map((x: any) => [x.id, x.status])).toEqual([['digest', 'fresh'], ['goldens', 'listed']]);+ expect(parsed.wtree).toMatch(/^[0-9a-f]{40}$/);+ });++ test('a failing command is failed (exit 1, REGEN_COMMAND_FAILED, status incomplete); an output outside the declared globs is stale', () => {+ const repo = fixture({ registry: { entries: [{ id: 'boom', command: 'node -e "process.exit(7)"', outputs: ['generated/**'] }, { id: 'leak', command: 'node -e "require(\'fs\').writeFileSync(\'docs/extra.md\',\'x\')"', outputs: ['generated/**'] }] } });+ const r = runBin(repo, 'gstack-regen', ['check', '--base', 'main', '--allow-repo-commands']);+ expect(r.status).toBe(EXIT.fail);+ expect(r.out).toMatch(/regen boom: failed .*exit 7.*\(REGEN_COMMAND_FAILED\)/);+ expect(r.out).toMatch(/regen leak: stale .*outside declared outputs: docs\/extra\.md/);+ expect(r.out).toContain('GSTACK_RESULT: skill=regen status=incomplete');+ expect(fs.existsSync(path.join(repo.work, 'docs', 'extra.md'))).toBe(false);+ });++ test('--only and --touched restrict the entries; untracked edits count through the wtree seed', () => {+ const repo = fixture();+ write(repo.work, 'src/version.js', "module.exports = { VERSION: '2.0.0' };\n");+ const only = runBin(repo, 'gstack-regen', ['check', '--base', 'main', '--allow-repo-commands', '--only', 'goldens']);+ expect(only.out).not.toContain('regen digest');+ expect(only.status).toBe(EXIT.ok);+ const touched = runBin(repo, 'gstack-regen', ['check', '--base', 'main', '--allow-repo-commands', '--touched', 'README.md']);+ expect(touched.out).toContain('REGEN: check fresh (0 entries)');+ const all = runBin(repo, 'gstack-regen', ['check', '--base', 'main', '--allow-repo-commands']);+ expect(all.status).toBe(EXIT.fail);+ expect(all.out).toContain('regen digest: stale');+ });++ test('validate, list and init: an invalid working-tree registry is REGEN_REGISTRY_INVALID; init refuses to overwrite', () => {+ const repo = fixture();+ expect(runBin(repo, 'gstack-regen', ['validate']).out).toContain('REGISTRY_VALID: .gstack/generated.json');+ expect(runBin(repo, 'gstack-regen', ['list']).out).toContain('digest: command="node gen.js" outputs=generated/** inputs=src/version.js,gen.js');+ write(repo.work, '.gstack/generated.json', '{"entries": [{"id": "x", "command": "y", "outputs": ["../z"]}]}\n');+ const v = runBin(repo, 'gstack-regen', ['validate']);+ expect(v.status).toBe(EXIT.fail);+ expect(v.err).toContain('(REGEN_CONTAINMENT)');+ expect(runBin(repo, 'gstack-regen', ['init']).status).toBe(EXIT.refused);+ fs.rmSync(path.join(repo.work, '.gstack/generated.json'));+ expect(runBin(repo, 'gstack-regen', ['init']).out).toContain('REGISTRY_WRITTEN: .gstack/generated.json');+ expect(runBin(repo, 'gstack-regen', ['validate']).status).toBe(EXIT.ok);+ // A branch registry that fails validation refuses before any command runs.+ const bad = fixture({ registry: { entries: [{ id: 'x', command: 'y', outputs: ['../z'] }] } });+ const r = runBin(bad, 'gstack-regen', ['check', '--base', 'main', '--allow-repo-commands']);+ expect(r.status).toBe(EXIT.refused);+ expect(r.err).toContain('(REGEN_CONTAINMENT)');+ });+});++describe("gstack's own registry", () => {+ test('.gstack/generated.json validates and names the renders, the doctor table, the digest and the ship goldens', () => {+ const { registry, errors } = parseRegistry(fs.readFileSync(path.join(path.resolve(import.meta.dir, '..'), '.gstack/generated.json'), 'utf8'));+ expect(errors).toEqual([]);+ const skill = registry.entries.find(e => e.id === 'skill-docs')!;+ expect(skill.command).toBe('bun run gen:skill-docs --host all');+ for (const out of ['bin/gstack-doctor-components.sh', 'agents-digest/gstack-AGENTS.md', 'gstack/llms.txt', '*/SKILL.md']) expect(skill.outputs).toContain(out);+ expect(registry.entries.find(e => e.id === 'ship-goldens')!.outputs).toEqual(['test/fixtures/golden/*-ship-SKILL.md']);+ });+});diff --git a/test/helpers/pregate-fixture.ts b/test/helpers/pregate-fixture.tsnew file mode 100644index 000000000..3226e90b5--- /dev/null+++ b/test/helpers/pregate-fixture.ts@@ -0,0 +1,186 @@+/**+ * Fixture repo for the C-pregate tests (gstack-regen, gstack-pregate,+ * gstack-issue-links): a bare origin plus a working clone with a generator+ * (`gen.js` → `generated/digest.md` from `src/version.js`), a `lib/` module+ * tree, a `test/` tree whose files reach `lib/` through imports, repo-path+ * literals and the `bin/<name>` convention, two GitHub workflows (a Linux+ * unit lane and a Windows lane whose matrix is planner-computed), a+ * committed `.gstack/generated.json` and `.gstack/pregate.json`. Everything+ * lives under os.tmpdir(), outside any checkout, with its own hermetic git+ * identity (never the operator's).+ */+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 { gitArgvIn } from './scratch-repo';++export const ROOT = path.resolve(import.meta.dir, '..', '..');+export const BIN = (name: string) => path.join(ROOT, 'bin', name);++export interface FixtureRepo { root: string; work: string; origin: string; home: string; git: (...args: string[]) => string; env: Record<string, string> }++export const BASE_REGISTRY = {+ $schema: 'https://github.com/garrytan/gstack/docs/pregate.md#generated-v1',+ entries: [+ { id: 'digest', command: 'node gen.js', outputs: ['generated/**'], inputs: ['src/version.js', 'gen.js'] },+ { id: 'goldens', command: null, outputs: ['test/golden/*.txt'], inputs: ['src/**'], note: 'copy the rendered output by hand' },+ ],+};++export const BASE_PREGATE = {+ $schema: 'https://github.com/garrytan/gstack/docs/pregate.md#pregate-v1',+ runner: 'node --test {files}',+ dependencies: {+ 'bin/tool': ['test/tool-cli.test.js'],+ 'docs/**': [],+ 'README.md': [],+ },+ selection: {+ 'windows.yml/windows-shard': 'node scripts/windows-list.js',+ },+ warn: ['strays'],+ strays: { allow: ['Makefile'] },+};++const WORKFLOW_UNIT = `name: Free Tests+on: [push]+jobs:+ unit:+ runs-on: ubuntu-24.04+ steps:+ - uses: actions/checkout@v4+ - uses: oven-sh/setup-bun@v2+ with:+ bun-version: 1.4.2+ - name: Run unit tests+ run: node --test test/*.test.js+`;+const WORKFLOW_WINDOWS = `name: Windows Free Tests+on: [push]+jobs:+ windows-plan:+ runs-on: ubuntu-24.04+ outputs:+ matrix: \${{ steps.plan.outputs.matrix }}+ steps:+ - id: plan+ run: node scripts/windows-list.js --matrix+ windows-shard:+ needs: windows-plan+ runs-on: windows-latest+ strategy:+ matrix: \${{ fromJSON(needs.windows-plan.outputs.matrix) }}+ steps:+ - uses: actions/setup-node@v4+ with:+ node-version: 24.18.0+ - name: Run the Windows-safe subset+ run: node --test \${{ matrix.files }}+`;++export function makeFixtureRepo(opts: { registry?: Record<string, unknown> | null; pregate?: Record<string, unknown> | null; prefix?: string } = {}): FixtureRepo {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), opts.prefix ?? 'gstack-pregate-fx-'));+ const origin = path.join(root, 'origin.git');+ const work = path.join(root, 'work');+ const home = path.join(root, 'home');+ fs.mkdirSync(home, { recursive: true });+ fs.mkdirSync(work, { recursive: true });+ const env = { GSTACK_HOME: home, GSTACK_STATE_DIR: home, HOME: home, GIT_CONFIG_GLOBAL: path.join(root, 'gitconfig'), GIT_CONFIG_NOSYSTEM: '1' };+ fs.writeFileSync(env.GIT_CONFIG_GLOBAL, '[user]\n\tname = t\n\temail = t@test\n[commit]\n\tgpgsign = false\n[init]\n\tdefaultBranch = main\n');+ const git = (...args: string[]): string => {+ const r = gitArgvIn(work, args, 30_000, { ...process.env, ...env });+ if (r.status !== 0) throw new Error(`git ${args.join(' ')} failed: ${r.stderr?.toString()}`);+ return r.stdout?.toString().trim() ?? '';+ };+ spawnSync('git', ['init', '-q', '--bare', origin], { timeout: 30_000, env: { ...process.env, ...env } });+ git('init', '-q', '-b', 'main');+ for (const dir of ['src', 'lib', 'bin', 'test', 'test/golden', 'test/nightly', 'generated', 'docs', 'scripts', '.gstack', '.github/workflows']) fs.mkdirSync(path.join(work, dir), { recursive: true });+ write(work, 'src/version.js', "module.exports = { VERSION: '1.0.0' };\n");+ write(work, 'gen.js', "const fs=require('fs');const {VERSION}=require('./src/version.js');fs.writeFileSync('generated/digest.md',`# digest v${VERSION}\\n`);\n");+ write(work, 'generated/digest.md', '# digest v1.0.0\n');+ write(work, 'test/golden/digest.txt', 'digest v1.0.0\n');+ write(work, 'lib/retry.js', "exports.MAX_RETRIES = 3;\nexports.TIMEOUT_MS = 5000;\nexports.retry = (fn) => fn();\n");+ write(work, 'lib/util.js', "exports.add = (a, b) => a + b;\n");+ write(work, 'lib/orphan.js', "exports.lonely = () => 1;\n");+ write(work, 'lib/config.json', '{"limit": 10}\n');+ write(work, 'bin/tool', "#!/usr/bin/env node\nconsole.log('tool');\n");+ fs.chmodSync(path.join(work, 'bin/tool'), 0o755);+ write(work, 'test/retry.test.js', "const test = require('node:test');\nconst assert = require('node:assert');\nconst { MAX_RETRIES } = require('../lib/retry.js');\ntest('retries three times', () => assert.strictEqual(MAX_RETRIES, 3));\n");+ write(work, 'test/util.test.js', "const test = require('node:test');\nconst assert = require('node:assert');\nconst { add } = require('../lib/util.js');\ntest('adds', () => assert.strictEqual(add(1, 2), 3));\n");+ write(work, 'test/config-read.test.js', "const test = require('node:test');\nconst assert = require('node:assert');\nconst fs = require('node:fs');\nconst path = require('node:path');\ntest('reads the config literal', () => assert.strictEqual(JSON.parse(fs.readFileSync(path.join(__dirname, '..', 'lib/config.json'), 'utf8')).limit, 10));\n");+ write(work, 'test/tool-cli.test.js', "const test = require('node:test');\nconst assert = require('node:assert');\nconst { spawnSync } = require('node:child_process');\ntest('tool prints', () => assert.strictEqual(spawnSync(process.execPath, [require('node:path').join(__dirname, '..', 'bin', 'tool')], { encoding: 'utf8', timeout: 10000 }).stdout.trim(), 'tool'));\n");+ write(work, 'test/nightly/retry-heavy.test.js', "const test = require('node:test');\nconst assert = require('node:assert');\ntest('heavy: timeout is 5000', () => assert.strictEqual(require('../../lib/retry.js').TIMEOUT_MS, 5000));\n");+ write(work, 'test/windows-paths.test.js', "const test = require('node:test');\ntest('windows paths', () => {});\n");+ write(work, 'scripts/windows-list.js', "if (process.argv.includes('--matrix')) console.log(JSON.stringify({ files: ['test/windows-paths.test.js'] }));\nelse console.log('test/windows-paths.test.js');\n");+ write(work, 'docs/README.md', '# docs\n');+ write(work, 'README.md', '# fixture\n');+ write(work, 'Makefile', 'all:\n\ttrue\n');+ write(work, 'package.json', JSON.stringify({ name: 'fixture', version: '1.0.0', scripts: { test: 'node --test test/*.test.js', generate: 'node gen.js' } }, null, 2) + '\n');+ write(work, '.gitignore', 'node_modules/\n.gstack/tmp/\n');+ write(work, '.github/workflows/free-tests.yml', WORKFLOW_UNIT);+ write(work, '.github/workflows/windows.yml', WORKFLOW_WINDOWS);+ if (opts.registry !== null) write(work, '.gstack/generated.json', JSON.stringify(opts.registry ?? BASE_REGISTRY, null, 2) + '\n');+ if (opts.pregate !== null) write(work, '.gstack/pregate.json', JSON.stringify(opts.pregate ?? BASE_PREGATE, null, 2) + '\n');+ git('add', '-A');+ git('commit', '-q', '-m', 'base');+ git('remote', 'add', 'origin', origin);+ git('push', '-q', 'origin', 'main');+ git('remote', 'set-head', 'origin', 'main');+ git('checkout', '-q', '-b', 'feature');+ return { root, work, origin, home, git, env };+}++export function write(work: string, rel: string, text: string): void {+ fs.mkdirSync(path.dirname(path.join(work, rel)), { recursive: true });+ fs.writeFileSync(path.join(work, rel), text);+}++export function readFile(repo: FixtureRepo, rel: string): string {+ return fs.readFileSync(path.join(repo.work, rel), 'utf8');+}++/** Edit files on the feature branch and commit them (the PR's own commits). */+export function commit(repo: FixtureRepo, files: Record<string, string | null>, message = 'feat'): string {+ for (const [rel, text] of Object.entries(files)) {+ if (text === null) fs.rmSync(path.join(repo.work, rel), { force: true });+ else write(repo.work, rel, text);+ }+ repo.git('add', '-A');+ repo.git('commit', '-q', '-m', message);+ return repo.git('rev-parse', 'HEAD');+}++export function runBin(repo: FixtureRepo, name: string, args: string[], extraEnv: Record<string, string> = {}, cwd = repo.work) {+ const r = spawnSync(BIN(name), args, { cwd, encoding: 'utf8', timeout: 180_000, maxBuffer: 64 * 1024 * 1024, env: { ...process.env, ...repo.env, ...extraEnv } });+ return { status: r.status, out: r.stdout ?? '', err: r.stderr ?? '' };+}++export function cleanup(repo: FixtureRepo): void {+ fs.rmSync(repo.root, { recursive: true, force: true });+}++/** A `gh` on PATH answering `gh issue view <n> --json ...` from a map and `gh issue list` / `gh run view` from fixed data. */+export function ghShim(repo: FixtureRepo, data: { issues?: Record<string, unknown>; issueList?: unknown[]; runs?: Record<string, unknown> }): { PATH: string } {+ const dir = path.join(repo.root, 'gh-shim');+ fs.mkdirSync(dir, { recursive: true });+ fs.writeFileSync(path.join(dir, 'data.json'), JSON.stringify({ issues: {}, issueList: [], runs: {}, ...data }));+ const script = [+ '#!/bin/sh',+ `DATA="${path.join(dir, 'data.json')}"`,+ 'if [ "$1" = "issue" ] && [ "$2" = "view" ]; then',+ ' node -e "const d=require(process.argv[1]);const p=d.issues[process.argv[2]];if(!p){console.error(\'GraphQL: Could not resolve to an Issue\');process.exit(1)}console.log(JSON.stringify(p))" "$DATA" "$3"',+ ' exit $?',+ 'fi',+ '# issue list: entries whose body contains the quoted --search token, numbers only (what gstack-issue-links asks for)',+ 'if [ "$1" = "issue" ] && [ "$2" = "list" ]; then node -e "const a=process.argv.slice(2);const q=(a[a.indexOf(\'--search\')+1]||\'\').replace(/^\\"|\\" in:body$/g,\'\');console.log(JSON.stringify(require(process.argv[1]).issueList.filter(i=>!q||String(i.body||\'\').includes(q)).map(i=>({number:i.number}))))" "$DATA" "$@"; exit $?; fi',+ 'if [ "$1" = "run" ] && [ "$2" = "view" ]; then',+ ' node -e "const d=require(process.argv[1]);const p=d.runs[process.argv[2]];if(!p){console.error(\'run not found\');process.exit(1)}console.log(JSON.stringify(p))" "$DATA" "$3"',+ ' exit $?',+ 'fi',+ 'echo "gh shim: unsupported $*" >&2; exit 1',+ '',+ ].join('\n');+ fs.writeFileSync(path.join(dir, 'gh'), script, { mode: 0o755 });+ return { PATH: `${dir}:${process.env.PATH ?? ''}` };+}diff --git a/test/pregate-invalidation.test.ts b/test/pregate-invalidation.test.tsnew file mode 100644index 000000000..e8581e321--- /dev/null+++ b/test/pregate-invalidation.test.ts@@ -0,0 +1,93 @@+/**+ * C8 invalidation: pregate.json is evidence only while it is current. A tree+ * that moved after the run, a failed or incomplete check, or a requires-remote+ * obligation without its receipt all reject publication — through+ * `gstack-pregate verify` and through `gstack-ship-receipt write --pregate`,+ * which is what /ship Step 18 calls. Pinned on result codes and exit codes.+ */+import { afterEach, describe, expect, test } from 'bun:test';+import * as fs from 'node:fs';+import * as path from 'node:path';+import { EXIT } from '../lib/headless-artifacts';+import { cleanup, commit, makeFixtureRepo, runBin, write, type FixtureRepo } from './helpers/pregate-fixture';++const repos: FixtureRepo[] = [];+const fixture = () => { const r = makeFixtureRepo(); repos.push(r); return r; };+afterEach(() => { while (repos.length) cleanup(repos.pop()!); });+const run = (repo: FixtureRepo, args: string[]) => runBin(repo, 'gstack-pregate', ['--base', 'main', '--allow-repo-commands', ...args]);+const outFile = (repo: FixtureRepo) => path.join(repo.work, '.gstack/tmp/pregate.json');+const receipt = (repo: FixtureRepo, extra: string[] = []) => runBin(repo, 'gstack-ship-receipt', ['write', '--pr', '7', '--base', 'main', '--version', '1.0.0', '--session-kind', 'interactive', '--pregate', outFile(repo), '--json', ...extra]);++describe('pregate invalidation', () => {+ test('a current green run verifies and lands in the ship receipt as pregate + requires_remote; a later edit makes it PREGATE_STALE for both', () => {+ const repo = fixture();+ commit(repo, { 'lib/util.js': "exports.add = (a, b) => a + b + 0;\n" });+ expect(run(repo, []).status).toBe(EXIT.ok);+ const v = runBin(repo, 'gstack-pregate', ['verify']);+ expect(v.status).toBe(EXIT.ok);+ expect(v.out).toMatch(/^PREGATE_VERIFY: ok pregate pass is current for tree [0-9a-f]{12}$/m);+ const ok = receipt(repo);+ expect(ok.status).toBe(EXIT.ok);+ const parsed = JSON.parse(ok.out);+ expect(parsed.pregate).toMatch(/^pass @[0-9a-f]{12} \(5 checks, current for [0-9a-f]{12}\)$/);+ expect(parsed.requires_remote).toBeUndefined();+ expect(Object.keys(parsed).indexOf('pregate')).toBeGreaterThan(Object.keys(parsed).indexOf('history') < 0 ? Object.keys(parsed).indexOf('session_kind') : Object.keys(parsed).indexOf('history'));+ // The stamp (or any edit) after the run moves the tree: the record is no longer evidence.+ write(repo.work, 'README.md', '# fixture 1.0.1\n');+ const stale = runBin(repo, 'gstack-pregate', ['verify']);+ expect(stale.status).toBe(EXIT.fail);+ expect(stale.err).toContain('(PREGATE_STALE)');+ expect(stale.out).toContain('PREGATE_VERIFY: refused PREGATE_STALE');+ const r = receipt(repo);+ expect(r.status).toBe(EXIT.fail);+ expect(r.err).toMatch(/nothing written.*\(PREGATE_STALE\)/);+ expect(r.out).toBe('');+ // Re-running on the moved tree makes it current again.+ expect(run(repo, []).status).toBe(EXIT.ok);+ expect(receipt(repo).status).toBe(EXIT.ok);+ });++ test('an uncleared requires-remote obligation is PREGATE_REMOTE_UNCLEARED until `clear` records a receipt, which the ship receipt then carries', () => {+ const repo = fixture();+ commit(repo, { 'test/windows-paths.test.js': "const test = require('node:test');\ntest('windows paths', () => { /* touched */ });\n" });+ expect(run(repo, []).status).toBe(EXIT.ok);+ const v = runBin(repo, 'gstack-pregate', ['verify']);+ expect(v.status).toBe(EXIT.fail);+ expect(v.err).toContain('(PREGATE_REMOTE_UNCLEARED)');+ expect(v.out).toContain('requires-remote: windows.yml/windows-shard (windows) 1 test(s) uncleared');+ const r = receipt(repo);+ expect(r.status).toBe(EXIT.fail);+ expect(r.err).toContain('(PREGATE_REMOTE_UNCLEARED)');+ expect(runBin(repo, 'gstack-pregate', ['clear', '--remote', 'nope.yml/job', '--run-url', 'https://example.invalid/runs/1']).status).toBe(EXIT.usage);+ const c = runBin(repo, 'gstack-pregate', ['clear', '--remote', 'windows.yml/windows-shard', '--run-url', 'https://github.com/o/r/actions/runs/42']);+ expect(c.status).toBe(EXIT.ok);+ expect(c.out).toContain('PREGATE_CLEARED: windows.yml/windows-shard receipt=https://github.com/o/r/actions/runs/42 verdict=requires-remote cleared');+ const persisted = JSON.parse(fs.readFileSync(outFile(repo), 'utf8'));+ expect(persisted.requires_remote[0]).toMatchObject({ lane: 'windows.yml/windows-shard', receipt: 'https://github.com/o/r/actions/runs/42' });+ expect(persisted.requires_remote[0].cleared_by).toMatch(/^gstack-pregate clear \d{4}-/);+ expect(runBin(repo, 'gstack-pregate', ['verify']).status).toBe(EXIT.ok);+ const ok = receipt(repo);+ expect(ok.status).toBe(EXIT.ok);+ expect(JSON.parse(ok.out)).toMatchObject({ pregate: expect.stringMatching(/^requires-remote cleared @/), requires_remote: ['windows.yml/windows-shard: https://github.com/o/r/actions/runs/42'] });+ });++ test('a failed check and an incomplete check both refuse publication; a missing or invalid pregate.json is not evidence', () => {+ const repo = fixture();+ commit(repo, { 'src/version.js': "module.exports = { VERSION: '1.1.0' };\n" });+ expect(run(repo, ['--stage', 'preflight']).status).toBe(EXIT.fail);+ expect(runBin(repo, 'gstack-pregate', ['verify']).err).toContain('(PREGATE_LANE_FAILED)');+ expect(receipt(repo).err).toContain('(PREGATE_LANE_FAILED)');+ const inc = fixture();+ commit(inc, { 'lib/util.js': "exports.add = (a, b) => a + b + 0;\n" });+ expect(runBin(inc, 'gstack-pregate', ['--base', 'main']).status).toBe(EXIT.fail);+ expect(runBin(inc, 'gstack-pregate', ['verify']).err).toContain('(PREGATE_INCOMPLETE)');+ expect(receipt(inc).err).toContain('(PREGATE_INCOMPLETE)');+ const none = fixture();+ expect(runBin(none, 'gstack-pregate', ['verify']).err).toContain('(PREGATE_STALE)');+ fs.mkdirSync(path.dirname(outFile(none)), { recursive: true });+ fs.writeFileSync(outFile(none), '{"schema_version": 1}\n');+ const bad = receipt(none);+ expect(bad.status).toBe(EXIT.fail);+ expect(bad.err).toContain('(ARTIFACT_SCHEMA)');+ });+});diff --git a/test/pregate-selection.test.ts b/test/pregate-selection.test.tsnew file mode 100644index 000000000..444bbc9ca--- /dev/null+++ b/test/pregate-selection.test.ts@@ -0,0 +1,301 @@+/**+ * C8 `lanes` selection and the mechanical preflight checks, pinned on tokens,+ * exit codes and the pregate.json contract. Fixture repos live under+ * os.tmpdir() (test/helpers/pregate-fixture.ts). Incident replays named in+ * the plan's P0-4 section, each caught locally before any remote gate:+ * p0-4-stale-goldens regen: a changed input, an unchanged output+ * p0-4-scratch-script strays: zz-probe.sh at the repository root+ * p0-4-heavy-old-constant literals: a nightly-only test keeps the old number+ * p0-4-windows-lane-unrun lanes: a Windows-only test file changes on Linux+ * p0-4-pipe-hidden-failure lanes: `false | tail` under pipefail is red+ */+import { afterEach, describe, expect, test } from 'bun:test';+import * as fs from 'node:fs';+import * as path from 'node:path';+import { EXIT } from '../lib/headless-artifacts';+import { changedLiterals, constantsIn } from '../lib/pregate/checks/literals';+import { parseSummary } from '../lib/pregate/checks/lanes';+import { validateConfig } from '../lib/pregate/config';+import { buildGraph, testsFor } from '../lib/pregate/import-graph';+import { CHECK_IDS } from '../lib/pregate/index';+import { parseWorkflow } from '../lib/pregate/workflows';+import { BASE_PREGATE, cleanup, commit, makeFixtureRepo, runBin, write, type FixtureRepo } from './helpers/pregate-fixture';++const repos: FixtureRepo[] = [];+const fixture = (opts?: Parameters<typeof makeFixtureRepo>[0]) => { const r = makeFixtureRepo(opts); repos.push(r); return r; };+afterEach(() => { while (repos.length) cleanup(repos.pop()!); });+const pregate = (repo: FixtureRepo, args: string[]) => runBin(repo, 'gstack-pregate', ['--base', 'main', '--allow-repo-commands', ...args]);+const readOut = (repo: FixtureRepo) => JSON.parse(fs.readFileSync(path.join(repo.work, '.gstack/tmp/pregate.json'), 'utf8'));+const check = (repo: FixtureRepo, id: string) => readOut(repo).checks.find((c: any) => c.id === id);++describe('workflow lanes (parser over .github/workflows)', () => {+ test('platform from runs-on, planner-computed matrix kept as an expression, test files from run steps and package scripts, manual jobs flagged', () => {+ const text = `name: CI\njobs:\n unit:\n runs-on: ubuntu-24.04\n steps:\n - run: bun test test/a.test.ts\n win:\n runs-on: windows-latest\n strategy:\n matrix: \${{ fromJSON(needs.plan.outputs.matrix) }}\n steps:\n - run: |\n bun run test:win\n record:\n if: \${{ inputs.record }}\n runs-on: windows-latest\n steps:\n - run: bun run test:win --record\n serial:\n runs-on: macos-latest\n strategy:\n max-parallel: 1\n steps:\n - run: npm test\n`;+ const lanes = parseWorkflow('ci.yml', text, 'linux', { 'test:win': 'bun test test/win.test.ts' });+ expect(lanes.map(l => [l.id, l.platform, l.tier, l.runsTests, l.manual])).toEqual([+ ['ci.yml/unit', 'linux', 'unit', true, false], ['ci.yml/win', 'windows', 'platform', true, false], ['ci.yml/record', 'windows', 'platform', true, true], ['ci.yml/serial', 'macos', 'platform', true, false],+ ]);+ expect(lanes[0]!.testFiles).toEqual(['test/a.test.ts']);+ expect(lanes[1]!.matrixExpression).toBe('${{ fromJSON(needs.plan.outputs.matrix) }}');+ expect(lanes[1]!.testFiles).toEqual(['test/win.test.ts']);+ expect(parseWorkflow('ci.yml', text, 'win32')[1]!.tier).toBe('unit');+ expect(parseWorkflow('ci.yml', text, 'win32')[0]!.tier).toBe('platform');+ });++ test('a verify-only shard step is not a test lane', () => {+ const lanes = parseWorkflow('w.yml', 'jobs:\n v:\n runs-on: ubuntu-24.04\n steps:\n - run: bun run scripts/test-free-shards.ts --windows-only --ci-verify x\n');+ expect(lanes[0]!.runsTests).toBe(false);+ });+});++describe('import graph (static imports ∪ repo-path literals ∪ bin convention ∪ declarations)', () => {+ test('imports, a joined literal read, the bin/<name> convention, a declared dependency and a deleted file all map; an orphan does not', () => {+ const repo = fixture();+ commit(repo, { 'lib/gone.js': null, 'test/gone.test.js': "const test = require('node:test');\ntest('reads a path', () => { require('node:fs').existsSync('lib/gone.js'); });\n" });+ const g = buildGraph(repo.work, { declarations: BASE_PREGATE.dependencies, extraFiles: ['lib/gone.js'] });+ expect(testsFor(g, 'lib/retry.js').tests).toEqual(['test/nightly/retry-heavy.test.js', 'test/retry.test.js']);+ expect(testsFor(g, 'lib/config.json').tests).toEqual(['test/config-read.test.js']);+ expect(testsFor(g, 'bin/tool').tests).toEqual(['test/tool-cli.test.js']);+ const declared = buildGraph(repo.work, { declarations: { 'lib/orphan.js': ['test/util.test.js'] } });+ expect(testsFor(declared, 'lib/orphan.js').provenance).toEqual(['test/util.test.js ← lib/orphan.js (declared)']);+ expect(testsFor(g, 'lib/gone.js').tests).toEqual(['test/gone.test.js']);+ expect(testsFor(g, 'lib/orphan.js')).toMatchObject({ tests: [], declaredNone: false });+ expect(testsFor(g, 'docs/README.md', BASE_PREGATE.dependencies)).toMatchObject({ tests: [], declaredNone: true });+ expect(testsFor(g, 'test/util.test.js').tests).toEqual(['test/util.test.js']);+ });+});++describe('literals (pure)', () => {+ test('exported constants with literal values are extracted; a changed one pairs old and new; functions are ignored', () => {+ expect([...constantsIn("export const MAX = 3;\nexport const NAME = 'x';\nexports.LIMIT = 10;\nexport const fn = () => 1;\nTIMEOUT_MS = 5000\n").entries()]).toEqual([['MAX', '3'], ['NAME', "'x'"], ['LIMIT', '10'], ['TIMEOUT_MS', '5000']]);+ expect(changedLiterals('f.ts', 'export const MAX = 3;\nconst x = { timeout: 5000 };', 'export const MAX = 4;\nconst x = { timeout: 9000 };')).toEqual([+ { name: 'MAX', old: '3', new: '4', file: 'f.ts' }, { name: 'timeout', old: '5000', new: '9000', file: 'f.ts' },+ ]);+ });+ test('runner summaries: bun, node --test, vitest, jest, pytest, zero-run', () => {+ expect(parseSummary(' 12 pass\n 1 fail\nRan 13 tests across 2 files.')).toEqual({ ran: 13, failed: 1 });+ expect(parseSummary('# tests 4\n# pass 4\n# fail 0')).toEqual({ ran: 4, failed: 0 });+ expect(parseSummary('Tests 2 failed | 8 passed (10)')).toEqual({ ran: 10, failed: 2 });+ expect(parseSummary('Tests: 1 failed, 7 passed, 8 total')).toEqual({ ran: 8, failed: 1 });+ expect(parseSummary('===== 3 passed in 0.1s =====')).toEqual({ ran: 3, failed: 0 });+ expect(parseSummary('No tests found')).toEqual({ ran: 0, failed: 0 });+ expect(parseSummary('ok')).toEqual({ ran: null, failed: null });+ });+ test('config: unknown keys, secrets in warn, a runner without {files} and an uncontained glob are PREGATE_CONFIG_INVALID', () => {+ const codes = (c: unknown) => validateConfig(c, CHECK_IDS).map(e => `${e.code}:${e.path}`);+ expect(codes(BASE_PREGATE)).toEqual([]);+ expect(codes({ warn: ['secrets'] })).toEqual(['PREGATE_CONFIG_INVALID:warn']);+ expect(codes({ warn: ['bogus'] })).toEqual(['PREGATE_CONFIG_INVALID:warn']);+ expect(codes({ runner: 'bun test' })).toEqual(['PREGATE_CONFIG_INVALID:runner']);+ expect(codes({ dependencies: { '../x': [] } })).toEqual(['PREGATE_CONFIG_INVALID:dependencies["../x"]']);+ expect(codes({ selection: { 'ci/job': 'x' } })).toEqual(['PREGATE_CONFIG_INVALID:selection["ci/job"]']);+ expect(codes({ extra: 1 })).toEqual(['PREGATE_CONFIG_INVALID:extra']);+ });+});++describe('gstack-pregate (bin)', () => {+ test('--help prints the exit table and both stages; unknown commands and checks are usage (2)', () => {+ const repo = fixture();+ const help = runBin(repo, 'gstack-pregate', ['--help']);+ expect(help.out).toContain('Exit codes: 0 ok · 1 fail · 2 usage · 3 refused or needs a flag');+ expect(help.out).toContain('stage 1 mechanical preflight (regen, secrets, strays, literals)');+ expect(help.out).toContain('stage 2 test execution (lanes)');+ expect(runBin(repo, 'gstack-pregate', ['bogus']).status).toBe(EXIT.usage);+ expect(pregate(repo, ['--only', 'hermetic']).status).toBe(EXIT.usage);+ });++ test('a clean branch passes every check, runs the selected local lane under pipefail and writes a valid pregate.json with both clocks', () => {+ const repo = fixture();+ commit(repo, { 'lib/util.js': "exports.add = (a, b) => a + b + 0;\n" });+ const r = pregate(repo, []);+ expect(r.status).toBe(EXIT.ok);+ expect(r.out).toMatch(/^preflight {2}regen {5}pass /m);+ expect(r.out).toMatch(/^preflight {2}secrets {3}pass /m);+ expect(r.out).toMatch(/^preflight {2}strays {4}pass /m);+ expect(r.out).toMatch(/^preflight {2}literals {2}pass /m);+ expect(r.out).toMatch(/^tests {6}lanes {5}pass .*1 tests ran in 1 file\(s\), exit 0/m);+ expect(r.out).toMatch(/^stage 1 \(mechanical preflight\): \d+ ms$/m);+ expect(r.out).toMatch(/^stage 2 \(test execution\): \d+ ms$/m);+ expect(r.out).toContain('Tiers ran: unit; requires-remote: none');+ expect(r.out).toMatch(/GSTACK_RESULT: skill=pregate status=complete run=.*pregate\.json/);+ const out = readOut(repo);+ expect(out.schema_version).toBe(1);+ expect(out.tree).toMatch(/^[0-9a-f]{40}$/);+ expect(out.checks.map((c: any) => [c.id, c.status, c.stage])).toEqual([['regen', 'pass', 'preflight'], ['secrets', 'pass', 'preflight'], ['strays', 'pass', 'preflight'], ['literals', 'pass', 'preflight'], ['lanes', 'pass', 'tests']]);+ for (const c of out.checks) { expect(c.inputs.tree).toBe(out.tree); expect(typeof c.ms).toBe('number'); }+ expect(check(repo, 'lanes').inputs.command).toMatch(/^[0-9a-f]{64}$/);+ expect(out.verdict).toBe('pass');+ expect(runBin(repo, 'gstack-artifact', ['validate', path.join(repo.work, '.gstack/tmp/pregate.json'), '--as', 'pregate']).status).toBe(EXIT.ok);+ });++ test('p0-4-stale-goldens: regen fails with the exact write command; the tree is untouched', () => {+ const repo = fixture();+ commit(repo, { 'src/version.js': "module.exports = { VERSION: '1.1.0' };\n" });+ const r = pregate(repo, ['--stage', 'preflight']);+ expect(r.status).toBe(EXIT.fail);+ expect(r.out).toMatch(/^preflight {2}regen {5}fail .*1 stale: generated\/digest\.md \(REGEN_STALE\)/m);+ expect(r.out).toContain('regen: regen digest: stale');+ expect(r.out).toContain('fix: node gen.js # then commit generated/**');+ expect(r.err).toContain('(REGEN_STALE)');+ expect(fs.readFileSync(path.join(repo.work, 'generated/digest.md'), 'utf8')).toBe('# digest v1.0.0\n');+ expect(readOut(repo).stage2_ms).toBeUndefined();+ });++ test('p0-4-scratch-script: zz-probe.sh at the root fails strays (downgraded to warn only when the base config says so); a conventional root file passes', () => {+ const strict = fixture({ pregate: { ...BASE_PREGATE, warn: [] } });+ commit(strict, { 'zz-probe.sh': '#!/bin/sh\necho hi\n', 'CONTRIBUTING.md': '# c\n', 'notes.txt': 'x\n', 'newtop/thing.js': 'module.exports = 1;\n' });+ const r = pregate(strict, ['--stage', 'preflight', '--only', 'strays']);+ expect(r.status).toBe(EXIT.fail);+ expect(r.out).toMatch(/^preflight {2}strays {4}fail .*2 stray file\(s\): notes\.txt zz-probe\.sh \(PREGATE_STRAYS\)/m);+ expect(r.out).toContain('strays: zz-probe.sh: scratch name (zz-probe.sh)');+ expect(r.out).toContain('strays: notes.txt: new file at the repository root');+ expect(r.out).toContain('newtop/thing.js: new top-level directory newtop/');+ expect(r.out).not.toContain('CONTRIBUTING.md:');+ const lenient = fixture();+ commit(lenient, { 'zz-probe.sh': '#!/bin/sh\n' });+ const w = pregate(lenient, ['--stage', 'preflight', '--only', 'strays']);+ expect(w.status).toBe(EXIT.ok);+ expect(w.out).toMatch(/^preflight {2}strays {4}warn .*downgraded to warn by origin\/main@/m);+ });++ test('p0-4-heavy-old-constant: a nightly-only test still asserting the old literal fails literals with file:line', () => {+ const repo = fixture();+ commit(repo, { 'lib/retry.js': "exports.MAX_RETRIES = 3;\nexports.TIMEOUT_MS = 9000;\nexports.retry = (fn) => fn();\n" });+ const r = pregate(repo, ['--stage', 'preflight', '--only', 'literals']);+ expect(r.status).toBe(EXIT.fail);+ expect(r.out).toContain('literals: test/nightly/retry-heavy.test.js:3: TIMEOUT_MS still 5000 (now 9000 in lib/retry.js)');+ expect(r.out).not.toContain('test/retry.test.js');+ expect(r.err).toContain('(PREGATE_LITERALS)');+ // Updating the consumer clears it.+ commit(repo, { 'test/nightly/retry-heavy.test.js': "const test = require('node:test');\nconst assert = require('node:assert');\ntest('heavy', () => assert.strictEqual(require('../../lib/retry.js').TIMEOUT_MS, 9000));\n" });+ expect(pregate(repo, ['--stage', 'preflight', '--only', 'literals']).status).toBe(EXIT.ok);+ });++ test('secrets: a credential in an added line fails and cannot be downgraded; a committed-then-removed line is clean', () => {+ const repo = fixture({ pregate: { ...BASE_PREGATE, warn: ['secrets'] } });+ const bad = pregate(repo, ['--stage', 'preflight', '--only', 'secrets']);+ expect(bad.status).toBe(EXIT.refused);+ expect(bad.err).toContain('secrets cannot be downgraded to warn');+ const ok = fixture();+ write(ok.work, 'lib/token.js', `exports.T = 'ghp_${'A'.repeat(36)}';\n`);+ const r = pregate(ok, ['--stage', 'preflight', '--only', 'secrets']);+ expect(r.status).toBe(EXIT.fail);+ expect(r.out).toMatch(/^preflight {2}secrets {3}fail .*credential finding\(s\) in added lines \(github\.pat\) \(PREGATE_SECRETS\)/m);+ expect(r.out).toContain('HIGH github.pat [secret]');+ fs.rmSync(path.join(ok.work, 'lib/token.js'));+ expect(pregate(ok, ['--stage', 'preflight', '--only', 'secrets']).status).toBe(EXIT.ok);+ });++ test('lanes: a touched file with no test lane is FAIL lanes — <file> has no test lane; a declaration or an explicit [] clears it', () => {+ const repo = fixture();+ commit(repo, { 'lib/orphan.js': "exports.lonely = () => 2;\n", 'docs/guide.md': '# guide\n' });+ const r = pregate(repo, ['--stage', 'tests']);+ expect(r.status).toBe(EXIT.fail);+ expect(r.out).toContain('lanes: FAIL lanes — lib/orphan.js has no test lane');+ expect(r.out).not.toContain('docs/guide.md has no test lane');+ expect(r.err).toContain('(PREGATE_NO_LANE)');+ // A declaration on the BASE branch maps it; a declaration only on the branch is unreviewed and ignored.+ commit(repo, { '.gstack/pregate.json': JSON.stringify({ ...BASE_PREGATE, dependencies: { ...BASE_PREGATE.dependencies, 'lib/orphan.js': ['test/util.test.js'] } }) + '\n' });+ expect(pregate(repo, ['--stage', 'tests']).status).toBe(EXIT.fail);+ const head = pregate(repo, ['--stage', 'tests', '--policy-from', 'head']);+ expect(head.status).toBe(EXIT.ok);+ expect(head.out).toContain('policy head (unreviewed) .gstack/pregate.json');+ expect(head.out).toMatch(/^tests {6}lanes {5}pass /m);+ });++ test('lanes: deleted and renamed files select the tests that named them; subprocess targets and computed reads map through declarations and joined literals', () => {+ const repo = fixture();+ repo.git('mv', 'lib/util.js', 'lib/maths.js');+ commit(repo, { 'lib/config.json': '{"limit": 11}\n', 'bin/tool': "#!/usr/bin/env node\nconsole.log('tool');\n// touched\n" });+ const r = pregate(repo, ['--stage', 'tests', '--explain']);+ expect(r.out).toContain('test/util.test.js ← lib/util.js (import) [renamed to lib/maths.js]');+ expect(r.out).toContain('test/config-read.test.js ← lib/config.json (literal) [touched]');+ expect(r.out).toContain('test/tool-cli.test.js ← bin/tool (literal) [touched]');+ expect(r.out).toMatch(/^tests {6}lanes {5}fail /m); // util.test.js still requires ../lib/util.js, which is gone: the lane ran and caught it+ expect(r.out).toContain('(PREGATE_LANE_FAILED)');+ const del = fixture();+ commit(del, { 'lib/config.json': null });+ const d = pregate(del, ['--stage', 'tests', '--explain']);+ expect(d.out).toContain('test/config-read.test.js ← lib/config.json (literal) [deleted]');+ });++ test('p0-4-windows-lane-unrun: a Windows-only test changed on Linux is a persisted requires-remote obligation named by workflow/job, and unsupported expressions are explained', () => {+ const repo = fixture();+ commit(repo, { 'test/windows-paths.test.js': "const test = require('node:test');\ntest('windows paths', () => { /* touched */ });\n" });+ const r = pregate(repo, ['--stage', 'tests', '--explain']);+ expect(r.status).toBe(EXIT.ok);+ expect(r.out).toMatch(/^tests {6}lanes {5}requires-remote .*1 requires-remote obligation\(s\)/m);+ expect(r.out).toContain('requires-remote windows.yml/windows-shard (windows): 1 test(s) — test/windows-paths.test.js');+ expect(r.out).toContain('Tiers ran: unit; requires-remote: windows');+ expect(r.out).toContain('lane windows.yml/windows-shard: 1 files from manifest `node scripts/windows-list.js`');+ expect(r.out).toContain('PREGATE: requires-remote (1 uncleared)');+ const out = readOut(repo);+ expect(out.requires_remote).toEqual([{ lane: 'windows.yml/windows-shard', platform: 'windows', workflow: 'windows.yml', job: 'windows-shard', tests: ['test/windows-paths.test.js'], receipt: null }]);+ // Without a manifest the planner-computed matrix is an unsupported expression: every selected test is conservatively in the lane.+ const bare = fixture({ pregate: { ...BASE_PREGATE, selection: {} } });+ commit(bare, { 'lib/util.js': "exports.add = (a, b) => a + b + 0;\n" });+ const b = pregate(bare, ['--stage', 'tests', '--explain']);+ expect(b.out).toContain('unsupported workflow expression "${{ fromJSON(needs.windows-plan.outputs.matrix) }}" and no selection manifest; treated as unknown');+ expect(b.out).toContain('requires-remote windows.yml/windows-shard (windows): 1 test(s) — test/util.test.js');+ });++ test('p0-4-pipe-hidden-failure: a runner whose failure hides behind | tail is red under pipefail; a zero-run lane is red with exit 0', () => {+ const piped = fixture({ pregate: { ...BASE_PREGATE, runner: 'node --test {files} 2>&1 | tail -n 1' } });+ commit(piped, { 'lib/util.js': "exports.add = (a, b) => a - b;\n" });+ const r = pregate(piped, ['--stage', 'tests']);+ expect(r.status).toBe(EXIT.fail);+ expect(r.out).toMatch(/^tests {6}lanes {5}fail .*local lane exited 1 .*pipefail\) \(PREGATE_LANE_FAILED\)/m);+ expect(r.out).toMatch(/lanes: log: .*lanes\.log/);+ const zero = fixture({ pregate: { ...BASE_PREGATE, runner: 'true {files} && echo "# tests 0"' } });+ commit(zero, { 'lib/util.js': "exports.add = (a, b) => a + b + 0;\n" });+ const z = pregate(zero, ['--stage', 'tests']);+ expect(z.status).toBe(EXIT.fail);+ expect(z.out).toMatch(/^tests {6}lanes {5}fail .*ZERO-RUN: the runner reported 0 tests/m);+ });++ test('trust boundary: without --allow-repo-commands the pin-file commands and the runner do not run; regen and lanes are incomplete, never pass', () => {+ const repo = fixture();+ commit(repo, { 'src/version.js': "module.exports = { VERSION: '1.1.0' };\n", 'lib/util.js': "exports.add = (a, b) => a + b + 0;\n" });+ const r = runBin(repo, 'gstack-pregate', ['--base', 'main']);+ expect(r.status).toBe(EXIT.fail);+ expect(r.out).toMatch(/^preflight {2}regen {5}incomplete .*repo commands not executed \(pass --allow-repo-commands\).*\(REPO_COMMANDS_NOT_ALLOWED\)/m);+ expect(r.out).toContain('regen: COMMAND: digest="node gen.js"');+ expect(r.out).toMatch(/^tests {6}lanes {5}incomplete .*1 local test file\(s\) selected but not run/m);+ expect(r.out).toContain('GSTACK_RESULT: skill=pregate status=incomplete');+ expect(fs.readFileSync(path.join(repo.work, 'generated/digest.md'), 'utf8')).toBe('# digest v1.0.0\n');+ expect(runBin(repo, 'gstack-pregate', ['--base', 'main', '--policy-from', 'head']).status).toBe(EXIT.refused);+ const gone = runBin(repo, 'gstack-pregate', ['--base', 'nope']);+ expect(gone.status).toBe(EXIT.refused);+ expect(gone.err).toContain('(POLICY_SOURCE_UNAVAILABLE)');+ });++ test('a working-tree change during a check makes it incomplete (the fingerprint moved), and --json carries the file', () => {+ const repo = fixture({ pregate: { ...BASE_PREGATE, runner: 'echo touched >> lib/util.js && node --test {files}' } });+ commit(repo, { 'lib/util.js': "exports.add = (a, b) => a + b + 0;\n" });+ const r = pregate(repo, ['--stage', 'tests', '--json']);+ expect(r.status).toBe(EXIT.fail);+ const parsed = JSON.parse(r.out);+ const lanes = parsed.checks.find((c: any) => c.id === 'lanes');+ expect(lanes.status).toBe('incomplete');+ expect(lanes.detail).toContain('working tree changed during the check');+ expect(lanes.code).toBe('PREGATE_INCOMPLETE');+ expect(parsed.ok).toBe(false);+ });++ test('lanes prints the lane list with platform tiers; validate and init cover the working-tree config', () => {+ const repo = fixture();+ const l = runBin(repo, 'gstack-pregate', ['lanes']);+ expect(l.out).toContain('free-tests.yml/unit: tier=unit platform=linux runs-on=ubuntu-24.04 tests=yes (.github/workflows/free-tests.yml:4)');+ expect(l.out).toContain('windows.yml/windows-shard: tier=platform platform=windows runs-on=windows-latest tests=yes matrix="${{ fromJSON(needs.windows-plan.outputs.matrix) }}"');+ expect(l.out).toMatch(/^LANES: 3 jobs; tests 2; platform 1$/m);+ expect(runBin(repo, 'gstack-pregate', ['validate']).out).toContain('PREGATE_CONFIG_VALID: .gstack/pregate.json');+ write(repo.work, '.gstack/pregate.json', '{"warn": ["secrets"]}\n');+ const v = runBin(repo, 'gstack-pregate', ['validate']);+ expect(v.status).toBe(EXIT.fail);+ expect(v.err).toContain('secrets cannot be downgraded to warn');+ expect(runBin(repo, 'gstack-pregate', ['init']).status).toBe(EXIT.refused);+ fs.rmSync(path.join(repo.work, '.gstack/pregate.json'));+ expect(runBin(repo, 'gstack-pregate', ['init']).out).toContain('PREGATE_CONFIG_WRITTEN');+ expect(runBin(repo, 'gstack-pregate', ['validate']).status).toBe(EXIT.ok);+ });+});diff --git a/test/ship-issue-intent.test.ts b/test/ship-issue-intent.test.tsnew file mode 100644index 000000000..e65b281ec--- /dev/null+++ b/test/ship-issue-intent.test.ts@@ -0,0 +1,66 @@+/**+ * C6: `Fixes #N` only on explicit closure intent. References, partial fixes,+ * deferred asks and cross-repo ids are `Refs`; an unreadable closure issue is+ * downgraded (ISSUE_UNREADABLE); failing CI run ids map to flake issues.+ * The bin reads issues only through gstack-issue-guard (a gh shim on PATH).+ */+import { afterEach, describe, expect, test } from 'bun:test';+import * as fs from 'node:fs';+import * as path from 'node:path';+import { EXIT } from '../lib/headless-artifacts';+import { mentionsIn, renderIssueLines, resolveLinks } from '../lib/issue-links';+import { cleanup, commit, ghShim, makeFixtureRepo, runBin, type FixtureRepo } from './helpers/pregate-fixture';++const repos: FixtureRepo[] = [];+const fixture = () => { const r = makeFixtureRepo(); repos.push(r); return r; };+afterEach(() => { while (repos.length) cleanup(repos.pop()!); });++describe('issue intent (pure)', () => {+ test('trailers carry closure; bare mentions, partial fixes, deferred asks and cross-repo ids are references', () => {+ const m = mentionsIn('fix: retry\n\nContext in #12. Partially fixes #13; deferring #17 to a follow-up.\nSee owner/other#9.\n\nFixes #14\nCloses: #15\nResolves GH-18\n');+ expect(m.map(x => [x.repo ? `${x.repo}#${x.issue}` : `#${x.issue}`, x.intent])).toEqual([+ ['#12', 'refs'], ['#13', 'refs'], ['#17', 'refs'], ['owner/other#9', 'refs'], ['#14', 'fixes'], ['#15', 'fixes'], ['#18', 'fixes'],+ ]);+ expect(mentionsIn('Fixes #14 and #15 together').map(x => x.intent)).toEqual(['refs', 'refs']);+ expect(mentionsIn('v1.2.3 (#301) release notes').map(x => x.issue)).toEqual([301]);+ });++ test('resolution: explicit --issue is closure, unreadable closure becomes Refs, a flake issue is never a plain Ref', () => {+ const links = resolveLinks(mentionsIn('Fixes #14\nFixes #15\nsee #40 and #16'), [16], n => n !== 15, [{ issue: 40, run: '7' }]);+ expect(links).toEqual({ fixes: [14, 16], refs: [15], flakes: [{ issue: 40, run: '7' }], cross: [], unreadable: [15] });+ expect(renderIssueLines(links)).toEqual(['Fixes #14', 'Fixes #16', 'Refs #15 (unreadable through gstack-issue-guard; not auto-closed)', 'Flake: #40 (run 7)']);+ expect(renderIssueLines(resolveLinks([], [], () => true))).toEqual([]);+ });+});++describe('gstack-issue-links (bin)', () => {+ test('reads origin/<base>..HEAD, probes closure issues through gstack-issue-guard, maps CI run ids to flake issues, writes the receipt object', () => {+ const repo = fixture();+ commit(repo, { 'lib/util.js': "exports.add = (a, b) => a + b + 0;\n" }, 'fix add\n\nSee #12 for context, partially fixes #13.\n\nFixes #14\nCloses #15\nRefs other/repo#9\n');+ const env = ghShim(repo, { issues: { '14': { title: 't', body: 'b', comments: [] }, '16': { title: 'u', body: '', comments: [] } }, issueList: [{ number: 40, body: 'Flake in run 123456' }, { number: 41, body: 'unrelated' }] });+ const out = path.join(repo.work, '.gstack/tmp/issues.json');+ const r = runBin(repo, 'gstack-issue-links', ['--base', 'main', '--ci-run', '123456', '--issue', '16', '--out', out], env);+ expect(r.status).toBe(EXIT.fail);+ expect(r.out).toBe(['Fixes #14', 'Fixes #16', 'Refs #12', 'Refs #13', 'Refs #15 (unreadable through gstack-issue-guard; not auto-closed)', 'Refs other/repo#9', 'Flake: #40 (run 123456)', ''].join('\n'));+ expect(r.err).toContain('(#15)');+ expect(r.err).toContain('(ISSUE_UNREADABLE)');+ expect(r.err).toContain('closure #14 ← commit ');+ expect(JSON.parse(fs.readFileSync(out, 'utf8'))).toEqual({ fixes: [14, 16], refs: [12, 13, 15], flakes: [{ issue: 40, run: '123456' }] });+ const receipt = runBin(repo, 'gstack-ship-receipt', ['write', '--base', 'main', '--version', '1.0.0', '--session-kind', 'interactive', '--issues', `@${out}`, '--json'], env);+ expect(receipt.status).toBe(EXIT.ok);+ expect(JSON.parse(receipt.out).issues).toEqual({ fixes: [14, 16], refs: [12, 13, 15], flakes: [{ issue: 40, run: '123456' }] });+ });++ test('no mentions prints ISSUE_LINKS: none with exit 0; a bare mention never closes; bad flags are usage', () => {+ const repo = fixture();+ commit(repo, { 'lib/util.js': "exports.add = (a, b) => a + b + 0;\n" }, 'tidy\n\nmentions #12 only\n');+ const env = ghShim(repo, { issues: { '12': { title: 't', body: 'b', comments: [] } } });+ const r = runBin(repo, 'gstack-issue-links', ['--base', 'main', '--json'], env);+ expect(r.status).toBe(EXIT.ok);+ expect(JSON.parse(r.out)).toMatchObject({ fixes: [], refs: [12], flakes: [] });+ const none = fixture();+ expect(runBin(none, 'gstack-issue-links', ['--base', 'main']).out).toBe('ISSUE_LINKS: none\n');+ expect(runBin(none, 'gstack-issue-links', ['--base', 'main', '--issue', 'abc']).status).toBe(EXIT.usage);+ expect(runBin(none, 'gstack-issue-links', ['--help']).out).toContain('Exit codes: 0 ok · 1 fail · 2 usage · 3 refused or needs a flag');+ });+});