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.98.0 fix: plan obligations meet repo gates; priced paid gates; machine-proved restamps (field wave C, items 14-17) (#3166)
Garry Tan7edaf4f50af7
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c87cb4048..9cef95b96 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,25 @@# Changelog+## [1.91.98.0] - 2026-10-13++**A lane's plan obligations now meet the repo's own gates before it reports done. Paid gates get a price before approval, a restamp is proved stamp-only by machine, and sealed eval output can't ride a push into a public repo.**++### What this means for you++- **Repo guards run in `gstack-pregate`.** `.gstack/pregate.json` takes `guards`: `{id, when: [globs], command, fix}`. When a changed file matches `when`, the guard runs in its own process with a timeout, and a failure names the guard and its fix. Guards cover the checks an import graph can't see, such as a serial-test manifest row or CLI goldens that spawn the binary. Required guards can't be downgraded, and without `--allow-repo-commands` the run is `incomplete`, never a pass. The lanes check runs on the verified Bun from the install's launch directory and runs serial test files one process each. Unknown flags exit 2 instead of being ignored.+- **`gstack-eval-plan price-gate` prices a paid gate without running it.** It reads a versioned call-plan file (`--plan-file`, or `price_file` in the base branch's policy) that is bound to the gate command, head and inputs, and prints `GATE_PRICE:` with every precondition the file declares. Nothing runs before approval. A gate that declares no plan is `EVAL_GATE_UNPRICED`; `--allow-unpriced "<reason>"` approves it as a recorded owner override, never as permission to spend. A stale or malformed plan file refuses. The new `reservation-fits-cap` check catches a single call whose reservation can't fit under the smoke cap. `/eval-plan` prices every paid gate this way at approval, passing the gate command as a file (`--gate-file`) so a command with quotes or `$` never goes through a shell string. The wire format and a reference emitter are in `docs/eval-calls.md`.+- **Current prices.** Claude Sonnet 5.5, Gemini 3.x Flash and the gbrain embedding models are priced from the providers' pages (source and date in the table), and Claude Opus 4.7 is at its current list price ($5/$25 per million tokens).+- **`gstack-pregate regate --against <gated-head>` says whether a restamped head needs a new gate.** It computes a fresh tree receipt and prints `STAMP_ONLY:`, one `LANE:` line per gate lane (reusable, rerun or not-reusable), `MIGRATION_COLLISION:` against the base and every other open PR, and `REGATE: needed|not-needed`. `not-needed` requires gate evidence for the gated head, an unchanged execution identity, no stamp-sensitive rerun and no unknown collision lookup. Bare `--against` is an alias.+- **The repo's stamp rule is the stamp rule.** Ship policy takes `stamp_files` (the files allowed to differ) and literal `stamp_patterns` with one `{version}` slot, such as `since: '{version}'`. A pure restamp of a repo whose versions sit in quoted `since:` rows, package manifests or stamp comments now classifies as stamps. `restamp_command` runs the repo's own restamp inside restamp's staging worktree with the target version, on a clean tree; a failure or a wrong-version output writes nothing. The `migrations` key (directory and id pattern) feeds the collision check.+- **A sealed-output guard runs before a push.** In a repo whose `.gstack/pregate.json` has a `sealed` key, the managed pre-push hook and `gstack-pregate sealed` check every commit the push publishes: forbidden paths (binary, empty, renamed and add-then-deleted files included), transcripts, quoted answer markers, seeds and machine-local paths. In a public repo a match refuses with the file, line and rule (`SEALED_OUTPUT_REFUSED`); in a private one it warns. The effective policy is the union of the base branch's and the pushed one, so a push can tighten the policy but never relax it. A malformed policy refuses, and unknown visibility counts as public. Waivers come only from a base-branch allow file. Repos without a `sealed` key see no change.+- **Lane handoffs carry the install and pregate lines.** The coordinator contract now asks a lane to run `gstack-pregate run --allow-repo-commands` (and `gstack-pregate sealed` where configured) before reporting done. Its handoff lists `GSTACK_RESULT`, then `gstack: ok|fail <rev>`, then `PREGATE:`, then the gate summary.++### For contributors++- `scripts/pr-dependencies.ts` traces breadth-first, so a trace names the shortest chain from a case's touchfiles to a file (selection is unchanged).+- New: `lib/pregate/checks/guards.ts`, `lib/pregate/regate.ts`, `lib/pregate/runtime.ts`, `lib/sealed-guard.ts`; docs `docs/eval-calls.md`, `docs/pregate.md#regate` and `#gbrain-worked-configs`.+- New result codes with troubleshooting anchors include `EVAL_GATE_UNPRICED`, `PREGATE_GUARD_FAILED`, `SEALED_OUTPUT_REFUSED` and `MIGRATION_COLLISION`.+- Pregate and ship-policy validators still refuse unknown keys, so a repo should commit `guards`, `sealed`, `price_file`, `stamp_files`, `stamp_patterns`, `restamp_command` or `migrations` only after its machines run this release.## [1.91.97.0] - 2026-10-13**An unattended `/autoplan` run on Capy now closes in its own run directory. Reviews done by Capy subagents bind with one command, a revised plan is reviewed in the same run, and the gate asks fewer, better questions.**diff --git a/VERSION b/VERSIONindex 1b3816353..0a3f874a1 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-1.91.97.0+1.91.98.0diff --git a/agents-digest/gstack-AGENTS.md b/agents-digest/gstack-AGENTS.mdindex 9c0e1f510..6f0e18552 100644--- a/agents-digest/gstack-AGENTS.md+++ b/agents-digest/gstack-AGENTS.md@@ -1,4 +1,4 @@-# gstack digest v1.91.97.0 — regenerate/re-copy after upgrading gstack+# gstack digest v1.91.98.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/autoplan/DRIVER.md b/autoplan/DRIVER.mdindex a5f81fc02..c84124c5d 100644--- a/autoplan/DRIVER.md+++ b/autoplan/DRIVER.md@@ -116,4 +116,6 @@ Behavior-change notices. Every user-visible behavior change outside the plan's oSpend caps. Each lane runs under the `--spend-cap` the coordinator names; a lane that reaches it stops with `status=budget_exhausted` and reports spent, reserved and unknown charges. Paid evals are never retried to change a verdict; a rerun needs a named repair. Host-subagent spend is reported as `unknown`, never zero.-Handoff format. A lane reports in this order, identifiers first: PR URL (or `no PR` with branch and SHA), `GSTACK_RESULT` line, gate summary (lanes passed/failed/skipped), behavior changes (or `none`), spend (spent/reserved/unknown), then what it could not verify. Full thread ids (`jam_…`), never short codes, in every cross-thread message. Prose after the identifiers may be truncated; nothing before them may be.+Before done. A lane runs `gstack-pregate run --allow-repo-commands` on its branch (the unit tier on the changed files plus the repo's guards) and reports done only after it passes. In a repo whose `.gstack/pregate.json` has a `sealed` key, it runs `gstack-pregate sealed` before any push or PR creation; a refusal stops the push, because a PR tool may not run local hooks.++Handoff format. A lane reports in this order, identifiers first: PR URL (or `no PR` with branch and SHA), `GSTACK_RESULT` line, the `gstack: ok|fail <rev>` line, the `PREGATE:` line, gate summary (lanes passed/failed/skipped), behavior changes (or `none`), spend (spent/reserved/unknown), then what it could not verify. Full thread ids (`jam_…`), never short codes, in every cross-thread message. Prose after the identifiers may be truncated; nothing before them may be.diff --git a/bin/gstack-doctor-components.sh b/bin/gstack-doctor-components.shindex 1af3c3904..a109f5863 100644--- a/bin/gstack-doctor-components.sh+++ b/bin/gstack-doctor-components.sh@@ -174,6 +174,12 @@ gstack_result_anchor() {CONTRIBUTOR_SOURCE_UNAVAILABLE) printf '%s' 'contributor-source-unavailable' ;;BRIEF_INPUT_MISSING) printf '%s' 'brief-input-missing' ;;DRAFT_DIRECTION_UNRESOLVED) printf '%s' 'draft-direction-unresolved' ;;+ PREGATE_GUARD_FAILED) printf '%s' 'pregate-guard-failed' ;;+ MIGRATION_COLLISION) printf '%s' 'migration-collision' ;;+ SEALED_OUTPUT_REFUSED) printf '%s' 'sealed-output-refused' ;;+ EVAL_GATE_UNPRICED) printf '%s' 'eval-gate-unpriced' ;;+ EVAL_GATE_OVER_CAP) printf '%s' 'eval-gate-over-cap' ;;+ EVAL_PLAN_STALE) printf '%s' 'eval-plan-stale' ;;PLAN_SECTIONS_INVALID) printf '%s' 'plan-sections-invalid' ;;PLAN_AMEND_PENDING) printf '%s' 'plan-amend-pending' ;;AMENDMENT_UNKNOWN) printf '%s' 'amendment-unknown' ;;diff --git a/bin/gstack-eval-plan b/bin/gstack-eval-planindex 2d5701bf8..accf81c5b 100755--- a/bin/gstack-eval-plan+++ b/bin/gstack-eval-plan@@ -10,20 +10,29 @@* gstack-eval-plan pilot settle --out <dir> --attempt <id> --usd <n|unknown>* gstack-eval-plan pilot release --out <dir> --attempt <id>* gstack-eval-plan pilot report --out <dir> --total <items> [--workers W] [--json]+ * gstack-eval-plan price-gate --gate-file <file> | --gate "<exact gate command>" [--plan-file <file>] [--base <branch>] [--cap-usd N]+ * [--smoke-cap-usd N] [--allow-unpriced "<reason>"] [--out <dir>] [--json]** The dry run spends nothing (stub model) and prints the checklist: price-table* entry per arm, output budget sized for reasoning models, the retry prompt's* exact text. The pilot reserves through lib/spend-ledger.ts (estimated admission,* lock-shared refusal), settles actual cost, and `report` prints the spend table* (spent, reserved, unknown charges, worst-case overrun) and the extrapolation- * with its error band before the approval ask. Exit 0 ok, 1 fail (incomplete- * prereg, failed check, exceeded cap), 2 usage, 3 refused. Logic: lib/eval-plan.ts.+ * with its error band before the approval ask. `price-gate` prices a paid gate+ * from the repo's call-plan DATA file (`--plan-file`, else `price_file` in the+ * base branch's .gstack/pregate.json read from the HEAD commit) after checking+ * its binding (exact gate command, head, input hashes); it executes nothing and+ * writes a receipt (docs/eval-calls.md). Exit 0 ok, 1 fail (incomplete+ * prereg, failed check, exceeded cap, unpriced or stale gate), 2 usage, 3 refused.+ * Logic: lib/eval-plan.ts.*/import * as fs from 'node:fs';import * as path from 'node:path';-import { checkPrereg, DEFAULT_TOKENS, dryRun, pilotReport, preregTemplate, releasePilot, renderArms, renderDryRun, renderPilotReport, resolveArms, settlePilot, startPilot } from '../lib/eval-plan';+import { spawnSync } from 'node:child_process';+import { checkPrereg, DEFAULT_TOKENS, dryRun, pilotReport, preregTemplate, priceGate, releasePilot, renderArms, renderDryRun, renderGatePrice, renderPilotReport, resolveArms, resolvePlanSource, settlePilot, startPilot } from '../lib/eval-plan';import { EXIT, exitTableHelp } from '../lib/headless-artifacts';import { resultLine } from '../lib/result-codes';+import { resolveBaseBranch } from '../lib/ship-policy';import { SpendCapExceeded } from '../lib/spend-ledger';const HELP = `gstack-eval-plan — preregistration, priced arms, $0 dry run, priced pilot (eval-plan/SKILL.md)@@ -32,11 +41,16 @@ const HELP = `gstack-eval-plan — preregistration, priced arms, $0 dry run, priprereg --init <file> [--title <t>] write the templatearms [--arms m,m] [--policy-doc f] [--input-tokens N] [--output-tokens N] [--json]arms from \`gstack-models resolve --role eval-arms\`, else the repo policy doc, each priced per item- dry-run --input rows.jsonl --arms m,m [--fields a,b] [--output-budget N] [--retry-prompt f] [--max-rows N] [--out dir] [--json]- stub model over the real rows; checklist: price table, output budget, retry prompt text+ dry-run --input rows.jsonl --arms m,m [--fields a,b] [--output-budget N] [--retry-prompt f] [--max-rows N] [--cap usd] [--out dir] [--json]+ stub model over the real rows; checklist: price table, output budget, retry prompt text,+ and with --cap reservation-fits-cap (one call: largest row + output budget, priced)pilot start --out dir --cap usd --arms m,m --dry-run dry-run.json [--n 3]pilot settle --out dir --attempt id --usd <n|unknown> pilot release --out dir --attempt idpilot report --out dir --total items [--workers W] [--json] spend table + extrapolation with a 95% band, then the approval ask+ price-gate --gate-file <file> | --gate "<exact gate command>" [--plan-file f] [--base b] [--cap-usd N] [--smoke-cap-usd N] [--allow-unpriced "<reason>"] [--out dir] [--json]+ price a paid gate from its GSTACK_EVAL_CALLS v1 call-plan file (--plan-file, else the base+ policy's price_file at HEAD); checks the gate/head/input binding, executes nothing, writes a+ receipt (default .gstack/tmp/price-gate/); docs/eval-calls.md${exitTableHelp()}`;@@ -85,13 +99,13 @@ function doDryRun(rest: string[]): number {const arms = csv(flag(rest, '--arms'));if (!input || !fs.existsSync(input)) return usage('dry-run needs --input <existing rows.jsonl>');if (!arms.length) return usage('dry-run needs --arms <model,model>');- const r = dryRun({ input, arms, fields: csv(flag(rest, '--fields')), outputBudget: num(rest, '--output-budget'), retryPrompt: flag(rest, '--retry-prompt'), maxRows: num(rest, '--max-rows') });+ const r = dryRun({ input, arms, fields: csv(flag(rest, '--fields')), outputBudget: num(rest, '--output-budget'), retryPrompt: flag(rest, '--retry-prompt'), maxRows: num(rest, '--max-rows'), cap: num(rest, '--cap') });const out = flag(rest, '--out');if (out) { fs.mkdirSync(out, { recursive: true }); fs.writeFileSync(path.join(out, 'dry-run.json'), JSON.stringify(r, null, 2) + '\n'); }if (rest.includes('--json')) process.stdout.write(JSON.stringify(r) + '\n'); else process.stdout.write(renderDryRun(r));if (out) process.stdout.write(`DRY_RUN_RECORD: ${path.join(out, 'dry-run.json')}\n`);if (!r.pass) {- const why = [r.rows === 0 ? 'no rows' : '', r.bad_rows.length ? `${r.bad_rows.length} bad rows` : '', !r.checks.price_table.ok ? `price missing: ${r.checks.price_table.missing.join(',') || 'no arms'}` : '', !r.checks.output_budget.ok ? 'output budget below the reasoning floor' : '', !r.checks.retry_prompt.ok ? 'retry prompt missing' : ''].filter(Boolean).join('; ');+ const why = [r.rows === 0 ? 'no rows' : '', r.bad_rows.length ? `${r.bad_rows.length} bad rows` : '', !r.checks.price_table.ok ? `price missing: ${r.checks.price_table.missing.join(',') || 'no arms'}` : '', !r.checks.output_budget.ok ? 'output budget below the reasoning floor' : '', !r.checks.retry_prompt.ok ? 'retry prompt missing' : '', r.checks.reservation_fits_cap && !r.checks.reservation_fits_cap.ok ? `one call exceeds --cap $${r.checks.reservation_fits_cap.cap}` : ''].filter(Boolean).join('; ');process.stderr.write(resultLine('gstack-eval-plan dry-run', r.checks.price_table.ok ? 'EVAL_DRY_RUN_FAILED' : 'EVAL_PRICE_MISSING', why) + '\n');return EXIT.fail;}@@ -136,6 +150,39 @@ function doPilot(rest: string[]): number {return usage(`unknown pilot command ${sub ?? ''}`);}+const PRICE_GATE_FLAGS = new Set(['--gate', '--gate-file', '--plan-file', '--base', '--cap-usd', '--smoke-cap-usd', '--allow-unpriced', '--out']);++function doPriceGate(rest: string[]): number {+ for (let i = 0; i < rest.length; i++) {+ if (rest[i] === '--json') continue;+ if (!PRICE_GATE_FLAGS.has(rest[i]!) || rest[i + 1] === undefined) return usage(`price-gate: unknown flag or missing value ${rest[i]}`);+ i++;+ }+ const gateFile = flag(rest, '--gate-file');+ if (gateFile && flag(rest, '--gate') !== undefined) return usage('price-gate takes --gate or --gate-file, not both');+ if (gateFile && !fs.existsSync(gateFile)) return usage(`--gate-file ${gateFile} does not exist`);+ const gate = gateFile ? fs.readFileSync(gateFile, 'utf8').replace(/\r?\n$/, '') : flag(rest, '--gate');+ if (!gate?.trim()) return usage('price-gate needs the exact gate command: --gate-file <file> (written with your file-write tool) or --gate "<command>"');+ const top = spawnSync('git', ['rev-parse', '--show-toplevel'], { encoding: 'utf8' });+ if (top.status !== 0) return usage('price-gate runs inside the git repository whose gate it prices');+ const repoRoot = top.stdout.trim();+ const planFile = flag(rest, '--plan-file');+ if (planFile && !fs.existsSync(planFile)) return usage(`--plan-file ${planFile} does not exist`);+ const plan = resolvePlanSource(repoRoot, { planFile, base: resolveBaseBranch(repoRoot, flag(rest, '--base')) });+ if ('code' in plan) { process.stderr.write(resultLine('gstack-eval-plan price-gate', plan.code, plan.message) + '\n'); return plan.refused ? EXIT.refused : EXIT.fail; }+ const r = priceGate({ repoRoot, gate, plan, capUsd: num(rest, '--cap-usd'), smokeCapUsd: num(rest, '--smoke-cap-usd'), allowUnpriced: flag(rest, '--allow-unpriced') });+ if (r.receipt) {+ const out = path.resolve(flag(rest, '--out') ?? path.join(repoRoot, '.gstack', 'tmp', 'price-gate'));+ const file = path.join(out, `price-gate-${r.receipt.gate_sha256.slice(0, 12)}-${r.receipt.head_sha.slice(0, 12)}.json`);+ fs.mkdirSync(out, { recursive: true });+ fs.writeFileSync(file, JSON.stringify(r.receipt, null, 2) + '\n');+ if (rest.includes('--json')) process.stdout.write(JSON.stringify({ ...r.receipt, receipt_path: file }) + '\n');+ else process.stdout.write([...r.lines, renderGatePrice(r.receipt, file)].join('\n') + '\n');+ }+ if (r.error) { process.stderr.write(resultLine('gstack-eval-plan price-gate', r.error.code, r.error.message) + '\n'); return EXIT.fail; }+ return EXIT.ok;+}+function main(argv: string[]): number {const [cmd, ...rest] = argv;if (!cmd || cmd === '--help' || cmd === '-h') { process.stdout.write(HELP + '\n'); return cmd ? EXIT.ok : EXIT.usage; }@@ -144,6 +191,7 @@ function main(argv: string[]): number {if (cmd === 'arms') return doArms(rest);if (cmd === 'dry-run') return doDryRun(rest);if (cmd === 'pilot') return doPilot(rest);+ if (cmd === 'price-gate') return doPriceGate(rest);return usage(`unknown command ${cmd}`);} catch (e: any) {if (e instanceof SpendCapExceeded) { process.stderr.write(resultLine(`gstack-eval-plan ${cmd}`, 'EVAL_BUDGET_EXHAUSTED', e.message) + '\n'); return EXIT.fail; }diff --git a/bin/gstack-pregate b/bin/gstack-pregateindex b5c1a121c..3f1272690 100755--- a/bin/gstack-pregate+++ b/bin/gstack-pregate@@ -9,6 +9,11 @@* 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+ * gstack-pregate sealed [--range <a..b>] [--remote <name>] [--base <branch>] [--json]+ * gstack-pregate regate --against <gated-head> --bundle <evidence-bundle.json> [--require <lanes>] [--pr <n>]+ * [--from <gate-ahead.json>] [--predecessor-pr <n> | --predecessor-ref <ref>] [--base <branch>] [--json]+ * does the gated head's evidence still cover HEAD (lib/pregate/regate.ts)+ * the sealed-output guard (lib/sealed-guard.ts) before any push or PR creation** 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@@ -28,7 +33,11 @@ import { CHECKS, CHECK_IDS, PREGATE_OUT_REL, PREGATE_TIER2, clearObligation, reaimport { 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';+import { defaultGh, evaluateRegate, renderRegate } from '../lib/pregate/regate';+import { GATE_AHEAD_REL } from '../lib/restamp';+import { evaluateSealed, publishedCommits, rangeCommits, renderSealed } from '../lib/sealed-guard';+import { isUnavailable, loadPolicyFromBase, policyUnavailableLine, resolveBaseBranch } from '../lib/ship-policy';+import { fromGateAhead } from '../lib/tree-receipt';const HELP = `gstack-pregate — cheap checks before anything paid or remote (docs/pregate.md)@@ -37,6 +46,12 @@ const HELP = `gstack-pregate — cheap checks before anything paid or remote (doclear record the receipt that clears one requires-remote obligationlanes print every CI lane with its platform tier (from .github/workflows/*.yml)validate | init the working-tree ${PREGATE_CONFIG_PATH}+ sealed [--range <a..b>] [--remote <name>] [--base <branch>]+ the sealed-output guard (docs/pregate.md#sealed) over the commits <remote> lacks, or the range:+ run it before any push or PR creation in a repo with a \`sealed\` config; exit 1 refuses (SEALED_OUTPUT_REFUSED)+ regate --against <gated-head> --bundle <file> [--require <lanes>] [--pr <n>] [--predecessor-pr <n> | --predecessor-ref <ref>]+ a fresh tree receipt, each lane's reuse verdict, migration collisions (base branch and open PRs), then+ REGATE: needed|not-needed (docs/pregate.md#regate); \`gstack-pregate --against <head>\` is the same verb; exit 1 = needed--stage preflight|tests|all default all--only <check,...> restrict to these checks (${CHECK_IDS.join(', ')}; tier 2 later: ${PREGATE_TIER2.join(', ')})@@ -53,6 +68,33 @@ obligations publication needs receipts for. Ends with GSTACK_RESULT: skill=prega${exitTableHelp()}`;function flag(args: string[], name: string): string | undefined { const i = args.indexOf(name); return i >= 0 ? args[i + 1] : undefined; }++/** Flags each verb accepts: `[flags that take a value, bare flags]`. Anything else is usage (exit 2), never a silent default run. */+const VERB_FLAGS: Record<string, [string[], string[]]> = {+ run: [['--stage', '--only', '--base', '--policy-from', '--out', '--timeout', '--run'], ['--allow-repo-commands', '--explain', '--json']],+ verify: [['--out'], ['--json']],+ clear: [['--remote', '--run-url', '--bundle-lane', '--out'], []],+ lanes: [[], ['--explain', '--json']],+ validate: [[], ['--json']],+ init: [[], ['--explain', '--force']],+ sealed: [['--range', '--base', '--remote'], ['--json']],+ regate: [['--against', '--bundle', '--require', '--pr', '--from', '--predecessor', '--predecessor-pr', '--predecessor-ref', '--base', '--current'], ['--json']],+};+const HINTS: Record<string, string> = { '--sealed': 'the sealed-output guard is the verb `gstack-pregate sealed`' };++function flagError(cmd: string, rest: string[]): string | null {+ const spec = VERB_FLAGS[cmd];+ if (!spec) return null;+ const [valued, bare] = spec;+ for (let i = 0; i < rest.length; i++) {+ const a = rest[i]!;+ if (valued.includes(a)) { if (rest[i + 1] === undefined || rest[i + 1]!.startsWith('--')) return `${a} needs a value`; i += 1; continue; }+ if (bare.includes(a)) continue;+ if (a.startsWith('-')) return `unknown flag ${a} for \`${cmd}\`${HINTS[a] ? ` (${HINTS[a]})` : ''}`;+ return `unexpected argument ${JSON.stringify(a)} for \`${cmd}\``;+ }+ return null;+}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;@@ -127,16 +169,72 @@ function cmdClear(root: string, rest: string[]): number {return EXIT.ok;}+function gitOut(root: string, args: string[]): string | null {+ const r = spawnSync('git', args, { cwd: root, encoding: 'utf8', timeout: 30_000 });+ return r.status === 0 ? r.stdout.trim() : null;+}++/** The sealed-output guard before any push or PR creation: the commits `--remote` lacks (or `--range a..b`), under base ∪ pushed policy. */+function cmdSealed(root: string, rest: string[], json: boolean): number {+ const base = resolveBaseBranch(root, flag(rest, '--base'));+ const remote = flag(rest, '--remote') ?? 'origin';+ const range = flag(rest, '--range');+ const end = range ? (range.split(/\.\.\.?/)[1] || 'HEAD') : 'HEAD';+ const pushedSha = gitOut(root, ['rev-parse', '--verify', '--quiet', `${end}^{commit}`]);+ if (!pushedSha) { process.stderr.write(`gstack-pregate sealed: ${end} is not a commit\n`); return EXIT.usage; }+ const listed = range ? rangeCommits(root, range) : publishedCommits(root, { localSha: pushedSha, remoteName: remote });+ const baseRef = gitOut(root, ['rev-parse', '--verify', '--quiet', `refs/remotes/${remote}/${base}^{commit}`]) ? `refs/remotes/${remote}/${base}` : null;+ const remoteUrl = gitOut(root, ['remote', 'get-url', remote]);+ const report = 'error' in listed+ ? { status: 'error' as const, error: listed.error, policyLabels: [], commits: 0, findings: [], waived: [], visibility: 'unknown' as const, visibilitySource: '', target: remoteUrl ?? remote }+ : evaluateSealed({ repoRoot: root, targets: [{ commits: listed.commits, pushedSha }], baseRef, baseLabel: `${remote}/${base}`, remoteUrl, target: remoteUrl ?? remote });+ const blocks = report.status === 'refused' || report.status === 'error';+ if (json) { process.stdout.write(JSON.stringify({ ...report, ok: !blocks }) + '\n'); return blocks ? EXIT.fail : EXIT.ok; }+ process.stderr.write(renderSealed(report, 'gstack-pregate sealed'));+ const policy = report.policyLabels.length ? report.policyLabels.join(' + ') : `no sealed key on ${baseRef ?? `${remote}/${base}`} or ${end}`;+ process.stdout.write(`SEALED: ${report.status} findings=${report.findings.length} commits=${report.commits} visibility=${report.visibility}${report.visibility === 'unknown' ? ' (counted public)' : ''} waived=${report.waived.length} policy=${policy}\n`);+ return blocks ? EXIT.fail : EXIT.ok;+}++function cmdRegate(root: string, rest: string[], json: boolean): number {+ const against = flag(rest, '--against');+ if (!against) { process.stderr.write('gstack-pregate regate: --against <gated-head> is required; see gstack-pregate --help\n'); return EXIT.usage; }+ const base = resolveBaseBranch(root, flag(rest, '--base'));+ const loaded = loadPolicyFromBase(root, base);+ if (isUnavailable(loaded)) { process.stderr.write(policyUnavailableLine('gstack-pregate regate', base, loaded.detail) + '\n'); return EXIT.refused; }+ if (loaded.errors.length) { for (const e of loaded.errors) process.stderr.write(resultLine('gstack-pregate regate', e.code, `${e.message} at ${e.path}`) + '\n'); return EXIT.refused; }+ const fromFile = flag(rest, '--from') ?? (fs.existsSync(path.join(root, GATE_AHEAD_REL)) ? path.join(root, GATE_AHEAD_REL) : undefined);+ const rec = fromFile ? fromGateAhead(fromFile) : null;+ const gated = spawnSync('git', ['rev-parse', '--verify', '--quiet', `${against}^{commit}`], { cwd: root, encoding: 'utf8', timeout: 15_000 }).stdout?.trim();+ const fromRec = rec && rec.gated_head === gated ? rec : null;+ const predPr = flag(rest, '--predecessor-pr') ?? fromRec?.predecessor_pr ?? null;+ const predRef = flag(rest, '--predecessor-ref') ?? null;+ const predHead = flag(rest, '--predecessor') ?? fromRec?.predecessor_head ?? null;+ const report = evaluateRegate({+ repoRoot: root, gated: against, current: flag(rest, '--current'), policy: loaded.policy, policyLabel: loaded.source.label,+ predecessor: predPr || predRef || predHead ? { pr: predPr, recordedHead: predHead, ref: predRef } : undefined,+ bundlePath: flag(rest, '--bundle'), baseRef: `origin/${base}`, require: (flag(rest, '--require') ?? '').split(',').map(s => s.trim()).filter(Boolean),+ self: flag(rest, '--pr') ?? fromRec?.pr ?? null, gh: defaultGh(root),+ });+ process.stdout.write(json ? JSON.stringify(report) + '\n' : renderRegate(report));+ if (report.migration.status === 'collision') process.stderr.write(resultLine('gstack-pregate regate', 'MIGRATION_COLLISION', report.migration.collisions.map(c => `${c.id} ${c.file} vs ${c.where} ${c.other}`).join('; ')) + '\n');+ return report.verdict === 'not-needed' ? EXIT.ok : EXIT.fail;+}+function main(argv: string[]): number {- const cmd = argv[0] && !argv[0].startsWith('--') ? argv[0] : 'run';+ const cmd = argv[0] && !argv[0].startsWith('--') ? argv[0] : argv.includes('--against') ? 'regate' : '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 bad = flagError(cmd, rest);+ if (bad) { process.stderr.write(`gstack-pregate: ${bad}; see gstack-pregate --help\n`); return EXIT.usage; }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 === 'sealed') return cmdSealed(root, rest, json);+ if (cmd === 'regate') return cmdRegate(root, rest, json);if (cmd === 'lanes') {const lanes = discoverLanes(root);if (json) { process.stdout.write(JSON.stringify(lanes) + '\n'); return EXIT.ok; }diff --git a/bin/gstack-redact-prepush b/bin/gstack-redact-prepushindex b3ccdd7fa..5cf65b097 100755--- a/bin/gstack-redact-prepush+++ b/bin/gstack-redact-prepush@@ -29,6 +29,10 @@* line, `#` comments. Only a finding whose matched text equals an entry is* suppressed; every push that carries entries lists what they suppressed.* - GSTACK_REDACT_PREPUSH=skip → log + exit 0 (escape valve).+ * - A repo with a `sealed` key in .gstack/pregate.json (base branch ∪ pushed+ * commit): lib/sealed-guard.ts checks every commit the push publishes for+ * sealed or eval output; a public (or unknown) destination refuses+ * (SEALED_OUTPUT_REFUSED), a private one warns.** Installed/uninstalled via `gstack-redact install-prepush-hook` (see the* gstack-redact CLI), which chains any pre-existing hook.@@ -39,6 +43,7 @@ import * as path from "path";import { normalizeWithMap, scan, type Finding, type ScanOptions } from "../lib/redact-engine";import { mkdirpSync } from "../lib/fs-utils";import { resolveStateRoot } from "../lib/state-root";+import { evaluateSealed, publishedCommits, renderSealed, type SealedReport } from "../lib/sealed-guard";const ZERO = /^0+$/;let emptyTree: string | undefined;@@ -594,6 +599,21 @@ function mediumLine(f: Finding, part: AddedFile): string {return ` MEDIUM ${f.id} ${where} fix: ${fix}\n`;}+/** The sealed-output guard over every commit this push publishes (lib/sealed-guard.ts); null when nothing is pushed. */+function sealedForPush(refs: Array<{ localSha: string; remoteSha: string }>): SealedReport | null {+ if (!refs.length) return null;+ const target = pushTarget();+ const remoteName = target.kind === "remote" ? target.name : target.kind === "unknown" && git(["remote"]).split("\n").includes("origin") ? "origin" : null;+ const remoteUrl = process.argv[3] || (remoteName ? git(["remote", "get-url", remoteName]).trim() : "") || null;+ const targets: Array<{ commits: string[]; pushedSha: string }> = [];+ for (const ref of refs) {+ const published = publishedCommits(".", { localSha: ref.localSha, remoteSha: ref.remoteSha, remoteName });+ if ("error" in published) return { status: "error", error: published.error, policyLabels: [], commits: 0, findings: [], waived: [], visibility: "unknown", visibilitySource: "", target: remoteUrl ?? "the push target" };+ targets.push({ commits: published.commits, pushedSha: ref.localSha });+ }+ return evaluateSealed({ repoRoot: ".", targets, baseRef: defaultRemoteBranch(), remoteUrl, target: remoteUrl ?? remoteName ?? "the push target" });+}+function main() {if ((process.env.GSTACK_REDACT_PREPUSH || "").toLowerCase() === "skip") {logSkip(process.env.GSTACK_REDACT_PREPUSH_REASON || "env-skip");@@ -612,6 +632,7 @@ function main() {const allowEntries = new Set<string>();const historyRevs = new Set<string>();let trackingRemote: string | null = null;+ const pushedRefs: Array<{ localSha: string; remoteSha: string }> = [];for (const fields of refs) {// Fail CLOSED on a ref line we cannot parse (#2498): git hands pre-push@@ -630,6 +651,7 @@ function main() {process.exit(1);}if (ZERO.test(localSha!)) continue; // branch delete → nothing pushed+ pushedRefs.push({ localSha: localSha!, remoteSha: remoteSha! });let added: AddedFile[];try {added = addedLinesFor(localSha, remoteSha || "0");@@ -710,6 +732,11 @@ function main() {}}+ const sealed = sealedForPush(pushedRefs);+ const sealedText = sealed ? renderSealed(sealed, "gstack sealed-output guard") : "";+ if (sealedText) process.stderr.write(sealedText);+ const sealedBlocks = !!sealed && (sealed.status === "refused" || sealed.status === "error");+if (allHigh.length > 0) {// A scan that could not RUN is not a scan that FOUND something. Reporting// "credential(s) in the pushed diff — rotate the credential" for an@@ -757,7 +784,7 @@ function main() {process.exit(1);}- process.exit(0);+ process.exit(sealedBlocks ? 1 : 0);}main();diff --git a/docs/eval-calls.md b/docs/eval-calls.mdnew file mode 100644index 000000000..fb7f9101e--- /dev/null+++ b/docs/eval-calls.md@@ -0,0 +1,192 @@+# Eval call plans: pricing a paid gate without running it++A paid gate (a benchmark, an eval smoke, any command that calls a model+provider for money) is priced before anyone approves it. gstack does not run+the gate, or any other repository command, to learn its cost. The repository+commits a **call-plan file**: plain data that names the exact gate command, the+commit and inputs it was computed from, and one line per call purpose with its+model and token counts. `gstack-eval-plan price-gate` reads that file, checks+that it still describes what is being approved, prices it from+`lib/pricing.ts`, and writes a receipt. Plan: field wave CD2+(`docs/designs/GSTACK_FIELD_WAVE_2026_10_12.md`, gate decision d5b as amended).++```bash+gstack-eval-plan price-gate --gate-file <file> --cap-usd 20 [--smoke-cap-usd 2] [--plan-file <file>]+```++`--gate-file` reads the exact gate command from a file (one trailing newline is+dropped), so a command with quotes or `$` never passes through a shell string;+`--gate "<command>"` takes it inline. Give one of the two.++## Where the file comes from++1. `--plan-file <file>`: an operator-given file, read from disk.+2. Otherwise `price_file` in `.gstack/pregate.json` as committed on+ `origin/<base>` (`--base`, default origin/HEAD's branch): a repo-relative+ path whose bytes are read from the **HEAD commit** (`git show HEAD:<path>`),+ never from the working tree.++Nothing in the file is executed: not the gate command, not a precondition,+not an input path. The file is parsed as text.++## File format, wire version v1++```+# gstack eval call plan, wire format v1 (docs/eval-calls.md); priced by `gstack-eval-plan price-gate`, never executed+GSTACK_EVAL_GATE v1: bun run eval:synopsis --questions 50 --arms opus,sol+GSTACK_EVAL_HEAD v1: 0123456789abcdef0123456789abcdef01234567+GSTACK_EVAL_INPUT v1: sha256=<64 hex> path=evals/synopsis/questions.jsonl+GSTACK_EVAL_PRECONDITION: ANTHROPIC_API_KEY and OPENAI_API_KEY set at run time+GSTACK_EVAL_CALLS v1: purpose=answer model=anthropic/claude-opus-5-5 calls=100 in_tokens=400000 out_tokens=200000 max_out_tokens=8192 scope=full+GSTACK_EVAL_CALLS v1: purpose=judge model=gpt-6.1-sol calls=100 in_tokens=300000 out_tokens=50000 max_out_tokens=2048 scope=full+GSTACK_EVAL_CALLS v1 end: lines=2+```++| Line | Count | Meaning |+|---|---|---|+| `GSTACK_EVAL_GATE v1: <command>` | exactly 1 | the exact gate command this plan prices; compared to `--gate` by string equality |+| `GSTACK_EVAL_HEAD v1: <sha>` | exactly 1 | the full commit sha the plan was computed at |+| `GSTACK_EVAL_INPUT v1: sha256=<hex> path=<path>` | 0 or more | each input the counts came from (rows, datasets, prompts), repo-relative, no `..` |+| `GSTACK_EVAL_PRECONDITION: <text>` | 0 or more | what must hold at run time; every one is echoed as `GATE_PRECONDITION:` |+| `GSTACK_EVAL_CALLS v1: …` | 0 or more | one line per call purpose (unique `purpose` + `model`) |+| `GSTACK_EVAL_CALLS v1 end: lines=<n>` | exactly 1, last | `n` = the number of call lines; a missing or miscounted end line means a partial producer and refuses |++Blank lines and lines starting with `#` are ignored. Every other line must be+one of the above; an unknown kind, an unknown version (`v2`), a missing or+extra key, a duplicate key, a non-integer count, `calls=0`, or any content+after the end line refuses with `EVAL_DRY_RUN_FAILED`, naming the line.++### Call line keys++| Key | Meaning |+|---|---|+| `purpose` | name of the call purpose (`[A-Za-z0-9._:-]+`), for example `answer`, `judge`, `embed` |+| `model` | model id; a provider prefix (`anthropic/`, `openai:`, `voyage:`) is accepted |+| `calls` | number of calls for this purpose (at least 1) |+| `in_tokens` | **aggregate** input tokens across all of this purpose's calls |+| `out_tokens` | **aggregate** expected output tokens across all of this purpose's calls |+| `max_out_tokens` | the **per-call** output reservation (the `max_tokens` the call sends) |+| `scope` | `full` (the counted run) or `smoke` (a small pre-run check) |++The aggregate totals are what the purpose is expected to cost:+`usd = price(in_tokens, out_tokens)`. The per-call reservation is what one call+can cost at most, which is what a provider or a spend ledger reserves:+`reservation_usd = price(ceil(in_tokens / calls), max_out_tokens)`.++## Binding checks (`EVAL_PLAN_STALE`)++The plan refuses, with no receipt, when it no longer describes what is being+approved:++- the `GSTACK_EVAL_GATE` command differs from `--gate` by even one character;+- the `GSTACK_EVAL_HEAD` commit is not HEAD and any file other than the plan+ file itself changed between them (a committed plan file sits one commit on+ top of the head it was computed at, so its own commit is allowed);+- an input's sha256 of its bytes in the HEAD commit differs from its+ `GSTACK_EVAL_INPUT` line, or the input is not in HEAD;+- the base policy declares a `price_file` that is not in the HEAD commit.++`--allow-unpriced` never overrides these: only a gate with no plan declared at+all, or a plan with zero call lines, is unpriced.++## Pricing outcomes++```+GATE_PLAN: file=evals/gate.calls source=price_file sha256=<hex> head=<sha12> inputs=1 verified+GATE_PRECONDITION: ANTHROPIC_API_KEY and OPENAI_API_KEY set at run time+GATE_CALLS: purpose=answer model=anthropic/claude-opus-5-5 calls=100 usd=5.6 reservation_usd=0.17984 scope=full+GATE_CALLS: purpose=judge model=gpt-6.1-sol calls=100 usd=1.1 reservation_usd=0.02648 scope=full+CHECK: reservation-fits-cap ok (largest one-call reservation $0.1798)+GATE_PRICE: total=6.7 calls=200 purposes=answer,judge receipt=.gstack/tmp/price-gate/price-gate-<gate12>-<head12>.json+```++| Outcome | Exit | Code |+|---|---|---|+| priced, under the caps | 0 | — |+| a model with no row in `lib/pricing.ts`: that row and the total print `unknown`, never zero | 1 | `EVAL_PRICE_MISSING` |+| total above `--cap-usd` | 1 | `EVAL_GATE_OVER_CAP` |+| one call's reservation above `--cap-usd`, or above `--smoke-cap-usd` for a `scope=smoke` row (`CHECK: reservation-fits-cap exceeds (…)`) | 1 | `EVAL_GATE_OVER_CAP` |+| no plan declared (no `--plan-file` and no `price_file` key) or a file with zero call lines | 1 | `EVAL_GATE_UNPRICED` |+| the same with `--allow-unpriced "<reason>"` | 0 | prints `GATE_UNPRICED_OVERRIDE: <reason> (owner-authorized override; not authorization to spend)` and records it |+| malformed or partial file | 1 | `EVAL_DRY_RUN_FAILED` |+| stale binding, or a declared `price_file` missing from HEAD (not overridable) | 1 | `EVAL_PLAN_STALE` |+| `origin/<base>` unresolvable while reading `price_file` | 3 | `POLICY_SOURCE_UNAVAILABLE` |+| `.gstack/pregate.json` on the base is invalid | 3 | `PREGATE_CONFIG_INVALID` |+| unknown flag or missing `--gate` | 2 | usage |++The price is an estimate: the table prices standard text tokens and excludes+the billing categories listed in `lib/pricing.ts` (cache writes, tool fees,+service tiers and long-context surcharges, media tokens, seat-metered runs).++## Receipt++Every outcome past the binding checks writes a JSON receipt to `--out`+(default `<repo>/.gstack/tmp/price-gate/`), named+`price-gate-<gate sha256 12>-<head 12>.json`, and prints its path on the+`GATE_PRICE:` line. `--json` prints the receipt (plus `receipt_path`) instead+of the lines.++| Field | Meaning |+|---|---|+| `schema_version` | `1` |+| `kind` | `gstack-eval-price-gate` |+| `created_at`, `gstack_revision` | when, and which gstack (VERSION and commit) priced it |+| `gate_command`, `gate_sha256` | the approved command and its sha256 |+| `head_sha` | HEAD when priced |+| `plan` | `file`, `source` (`flag`, `price_file`, `none`), `sha256` of the plan file bytes, `declared_head` |+| `inputs` | each `{ path, sha256 }`, verified at HEAD |+| `preconditions` | every precondition line |+| `rows` | each call line plus `usd` and `reservation_usd` (`null` when unpriced) |+| `total_usd`, `calls`, `purposes` | the totals; `total_usd` is `null` when unknown |+| `cap_usd`, `smoke_cap_usd` | the caps passed, or `null` |+| `result`, `code` | `priced`, `price_missing`, `over_cap`, `unpriced`, `unpriced_override`, and the result code |+| `unpriced_reason`, `unpriced_override` | why the gate is unpriced, and the owner's override reason |+| `excluded_billing` | the billing categories the estimate leaves out |++## Reference emitter++A consuming repo writes the file from the same code that builds its calls, so+the counts cannot drift from the run. `formatEvalCalls` in `lib/eval-plan.ts`+is the reference; copy it:++```ts+import { createHash } from 'node:crypto';+import { execFileSync } from 'node:child_process';+import { readFileSync } from 'node:fs';++const KEYS = ['purpose', 'model', 'calls', 'in_tokens', 'out_tokens', 'max_out_tokens', 'scope'] as const;+type Row = { purpose: string; model: string; calls: number; in_tokens: number; out_tokens: number; max_out_tokens: number; scope: 'full' | 'smoke' };++export function formatEvalCalls(p: { gate: string; head: string; inputs: { path: string; sha256: string }[]; preconditions: string[]; rows: Row[] }): string {+ return [+ '# gstack eval call plan, wire format v1 (docs/eval-calls.md); priced by `gstack-eval-plan price-gate`, never executed',+ `GSTACK_EVAL_GATE v1: ${p.gate}`,+ `GSTACK_EVAL_HEAD v1: ${p.head}`,+ ...p.inputs.map(i => `GSTACK_EVAL_INPUT v1: sha256=${i.sha256} path=${i.path}`),+ ...p.preconditions.map(t => `GSTACK_EVAL_PRECONDITION: ${t}`),+ ...p.rows.map(r => `GSTACK_EVAL_CALLS v1: ${KEYS.map(k => `${k}=${r[k]}`).join(' ')}`),+ `GSTACK_EVAL_CALLS v1 end: lines=${p.rows.length}`,+ ].join('\n') + '\n';+}++// Count tokens the way the run will, without calling a provider, then:+const head = execFileSync('git', ['rev-parse', 'HEAD'], { encoding: 'utf8' }).trim();+const input = 'evals/synopsis/questions.jsonl';+const sha256 = createHash('sha256').update(readFileSync(input)).digest('hex');+// writeFileSync('evals/gate.calls', formatEvalCalls({ gate, head, inputs: [{ path: input, sha256 }], preconditions, rows }));+```++Hash the inputs as committed (the file at HEAD), produce the plan at a clean+HEAD, commit the plan file on its own commit, and set+`"price_file": "evals/gate.calls"` in `.gstack/pregate.json`.++## Related++- `gstack-eval-plan dry-run --cap <usd>` runs the same reservation-fits-cap+ check for an eval's arms: one call (the largest row's input plus the output+ budget), priced, must fit under the cap.+- Result codes: [EVAL_GATE_UNPRICED](troubleshooting.md#eval-gate-unpriced),+ [EVAL_GATE_OVER_CAP](troubleshooting.md#eval-gate-over-cap),+ [EVAL_PLAN_STALE](troubleshooting.md#eval-plan-stale),+ [EVAL_PRICE_MISSING](troubleshooting.md#eval-price-missing),+ [EVAL_DRY_RUN_FAILED](troubleshooting.md#eval-dry-run-failed).diff --git a/docs/pregate.md b/docs/pregate.mdindex ebd2fd700..7d96e44c6 100644--- a/docs/pregate.md+++ b/docs/pregate.md@@ -62,6 +62,10 @@ the byte-pinned `/ship` renders in `test/fixtures/golden/`).| `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 |+| `guards` | `[{ id, when: [globs], command, fix?, timeout_s? }]`: repo commands a lane must pass when a touched file matches `when` (manifest checks, subprocess goldens the import graph cannot see); see [guards](#guards) |+| `serial_patterns` | test-file globs the `lanes` check runs one process per file, apart from the unit files (default `**/*.serial.test.*`) |+| `sealed` | sealed or eval output that must never reach a public destination; read by the pre-push hook and `gstack-pregate sealed` (see [sealed output](#sealed)) |+| `price_file` | repo-relative path of the paid gate's call-plan data file (`GSTACK_EVAL_CALLS v1`); `gstack-eval-plan price-gate` prices from it and never executes anything ([docs/eval-calls.md](eval-calls.md)) |Only the `origin/<base>` copy is honoured, so a downgrade is reviewed before ittakes effect. `gstack-pregate validate` / `init` cover the working-tree file.@@ -90,6 +94,15 @@ Two stages with separate clocks, both printed:searched for the old value; a consumer the branch did not update fails with`file:line`.+- `guards`: each guard in `.gstack/pregate.json` whose `when` globs match a+ touched file (renames included) runs its `command` in its own process, under+ the verified launch Bun, with its own `timeout_s` (default `--timeout`). A+ non-zero exit fails pregate naming the guard and its `fix`+ (`PREGATE_GUARD_FAILED`); a timeout is `incomplete`; without+ `--allow-repo-commands` the selected guards are listed and the check is+ `incomplete`. Guards are read from the base branch's copy and cannot be+ downgraded to warn. See [guards](#guards).+**Stage 2, test execution:**- `lanes`: touched files map to tests through `lib/pregate/import-graph.ts`@@ -104,7 +117,12 @@ Two stages with separate clocks, both printed:machine cannot run becomes a `requires-remote` obligation naming`workflow.yml/job`. `--explain` prints each test's provenance and everyuncertain mapping (a planner-computed matrix without a `selection` manifest- selects conservatively).+ selects conservatively). Test files matching `serial_patterns` (default+ `**/*.serial.test.*`) run one process per file after the unit files. The+ runner and every guard run with the verified launch Bun first on PATH: the+ first of `$BUN_INSTALL/bin` and `~/.bun/bin` whose Bun satisfies gstack's and+ the project's `engines.bun` (the row prints `runtime: bun <v> from <dir>`),+ so a Capy host's older image Bun cannot flip the verdict.Every check records the input identity it ran against (the working-treefingerprint before and after, the selection, the command hash); a tree that@@ -120,8 +138,202 @@ The record is `.gstack/tmp/pregate.json` (`gstack-artifact validate --as pregatereceipt 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.+Unknown flags exit 2 with usage on every verb (an agent told to run a flag this+gstack lacks never gets a green it did not ask for). Tier 2 checks still to come+(`ratchets`, `lint`, `links`, `hermetic`, `patches`, `integrator`) are named in+`--only`'s help.++<a id="guards"></a>+## Guards and the lane-done rule++A lane runs `gstack-pregate run --allow-repo-commands` on its branch before it+reports done, and its handoff carries the `PREGATE:` line (the coordinator+contract says so word for word). The unit tier covers the changed files'+tests; guards cover the repo's mechanical gates the import graph cannot see:++```json+{ "guards": [+ { "id": "serial-manifest", "when": ["test/**/*.serial.test.ts", "scripts/serial-files.tsv"],+ "command": "bun test test/scripts/serial-files.test.ts",+ "fix": "add the file's row to scripts/serial-files.tsv" } ] }+```++`dependencies` still maps globs to extra *tests* the lanes check selects; a+guard is a *command* with its own fix line. Older gstack refuses unknown keys+(`PREGATE_CONFIG_INVALID`), so a repo commits `guards` only after the gstack+that reads them ships. The worked gbrain configuration is in+[gbrain worked configs](#gbrain-worked-configs).++<a id="sealed"></a>+## Sealed output: the pre-push hook and `gstack-pregate sealed`++```json+{ "sealed": {+ "paths": ["heldout/**"],+ "transcripts": ["runs/**/transcript*.jsonl"],+ "answer_markers": ["SEALED ANSWER:"],+ "seed_patterns": ["shuffle_seed=\\d+"],+ "local_paths": true } }+```++A repo with a `sealed` key gets a configured local check against accidental+publication whenever the managed pre-push hook (`gstack-redact+install-prepush-hook`, no reinstall needed) or the standalone preflight runs:++```+gstack-pregate sealed [--range <a..b>] [--remote origin] [--base <branch>] [--json]+```++- **Boundary.** Every commit the push publishes: `git rev-list <local sha>+ --not --remotes=<remote>` (and the remote tip when the ref exists); a+ destination with no refs means everything reachable. `--range` names the+ commits explicitly.+- **Rules.** `sealed.path` and `sealed.transcript` check every path a commit+ adds, renames or copies, whatever its content (binary, empty, deleted again+ in a later commit); `sealed.answer`, `sealed.seed` and `sealed.local_path`+ (`/home/<user>/`, `/Users/<user>/`, `C:\Users\<user>\`) check each commit's added+ lines. Findings print rule, `file[:line]` and commit, never the text.+- **Policy.** The union of the destination base branch's `sealed` and the+ pushed commit's: a push can tighten it, never relax it. A malformed or+ unreadable policy refuses. Waivers come only from the base branch's+ `.gstack/sealed-allow.tsv` (`rule<TAB>path<TAB>sha<TAB>reason`) and are+ listed on every push.+- **Visibility.** `sealed.visibility` from the base branch, else a cache under+ the state root (`sealed-visibility.json`: a `public` answer for 24 hours, a+ `private` one for 1 hour before it may turn a refusal into a warning), else+ `gh repo view --json visibility` (5 s). Unknown, unreadable or newly created+ counts as public. Public refuses (`SEALED_OUTPUT_REFUSED`, exit 1); private+ warns.++Capy's pull-request tool may not run local git hooks, so an agent runs+`gstack-pregate sealed` before any push or PR creation in a repo with a+`sealed` config (the coordinator contract says so). Hosted CI on the public+repository only detects a bypass after the upload.++<a id="regate"></a>+## `gstack-pregate regate`: does the gate still cover HEAD++```+gstack-pregate regate --against <gated-head> --bundle <evidence-bundle.json> [--require <lane,...>]+ [--pr <n>] [--from <gate-ahead.json>] [--predecessor-pr <n> | --predecessor-ref <ref>]+ [--base <branch>] [--json]+gstack-pregate --against <gated-head> ... the same verb+```++It evaluates a tree receipt now (never a stored one) between the gated head+and HEAD under the base branch's ship policy, so the repo's `stamp_files` and+`stamp_patterns` decide what a stamp is ([ship-policy](ship-policy.md#tree-receipt)).+Reuse needs an evidence bundle produced on the gated tree, the same execution+identity, and a predecessor head that is still the recorded one (read from+`--from`, default `.gstack/tmp/gate-ahead.json` when it names this gated+head). It prints each differing file (a non-stamp difference with its first+line), then:++```+STAMP_ONLY: yes|no files=<n> [changed=<n>]+LANE: <label> reusable|rerun|not-reusable (<reason>) one per bundle lane and per --require lane+MIGRATION_COLLISION: none (...) | unknown (...) | <id> <file> vs <origin/main|PR #n> <file>+REGATE: not-needed | needed (<every reason>)+```++`REGATE: not-needed` (exit 0) only when the tree is stamp-only, every lane in+the bundle and in `--require` is reusable (a stamp-sensitive lane reruns, so it+needs a regate), the predecessor head is known and unmoved, and the migration+lookup finished with no collision. Anything else is `needed` (exit 1); no+bundle prints `REGATE: needed (no gate evidence for <head> ...)`.++Migrations come from the ship policy's `migrations` (`dir`, `id` regex with+one capture group). The numbers this branch adds under `dir` are compared with+the base branch's tree and with every other open PR+(`gh pr list --state open --limit 1000 --json number,headRefOid,files`; the PR+itself is skipped by head sha or `--pr`). A PR listing 100 files is truncated+by GitHub, so its full list is fetched with `gh api --paginate`. A failed+query, 1000 listed PRs or an unfetchable file list is+`MIGRATION_COLLISION: unknown (...)`, which blocks `not-needed`+([`MIGRATION_COLLISION`](troubleshooting.md#migration-collision)).++<a id="gbrain-worked-configs"></a>+## gbrain worked configs++gbrain commits these on master after the gstack that reads the new keys ships+(older gstack refuses unknown keys). Its `.gitignore` ignores `.gstack/*`+today, so the change also adds `!.gstack/pregate.json` and+`!.gstack/ship-policy.json`; both changes are gbrain's.++`.gstack/pregate.json`: guards for the gates the import graph cannot see.++```json+{+ "dependencies": {+ "test/**/*.serial.test.ts": ["test/scripts/serial-files.test.ts"],+ "scripts/serial-files.tsv": ["test/scripts/serial-files.test.ts"],+ "src/cli.ts": ["test/cli-goldens.test.ts"],+ "src/commands/**": ["test/cli-goldens.test.ts"],+ "src/core/operations*.ts": ["test/cli-goldens.test.ts"]+ },+ "guards": [+ { "id": "serial-manifest", "when": ["test/**/*.serial.test.ts", "scripts/serial-files.tsv", "scripts/run-serial-tests.sh"],+ "command": "bun test test/scripts/serial-files.test.ts",+ "fix": "add the serial file's row to scripts/serial-files.tsv" },+ { "id": "cli-goldens", "when": ["src/cli.ts", "src/cli/**", "src/commands/**", "src/core/operations*.ts", "src/core/ops/**"],+ "command": "bun test --timeout=60000 test/cli-goldens.test.ts test/cli-dispatch-phase.test.ts test/export-surface-golden.test.ts",+ "fix": "bun run regen:all, then justify each changed golden in the PR body" },+ { "id": "regen-check", "when": ["src/**", "skills/**", "templates/**", "plugin/**"],+ "command": "bun scripts/regen-all.ts --check",+ "fix": "bun run regen:all and commit the regenerated files" },+ { "id": "migration-order", "when": ["src/core/schema-migrations/**"],+ "command": "bun scripts/check-schema-migration-order.ts",+ "fix": "renumber the migration to the next free number on master" }+ ]+}+```++`.gstack/ship-policy.json`: the stamp rule and migrations. On a pure restamp+of a gbrain master tree from 0.60.188.0 to 0.60.189.0 the tree receipt+classifies all 16 changed files as stamps under this policy; an added line in+`src/core/behavior-change-notice.ts` stays a change.++```json+{+ "bump": "patch",+ "queue_mode": "stamp-at-merge",+ "changelog": "CHANGELOG.md",+ "stamp_files": [+ "VERSION", "package.json", "CHANGELOG.md", "openclaw.plugin.json",+ ".claude-plugin/plugin.json", ".codex-plugin/plugin.json",+ "plugin-variants/*/.claude-plugin/plugin.json", "plugin-variants/*/.codex-plugin/plugin.json",+ "plugin-variants/*/README.md", "plugin/README.md",+ "BOOTSTRAP_FOR_AGENTS.md", "templates/bootstrap/template-repo/README.md",+ "src/core/behavior-change-notice.ts"+ ],+ "stamp_patterns": [+ "\"version\": \"{version}\"",+ "since: '{version}'",+ "<!-- gbrain-plugin-tree-stamp: {version} -->",+ "<!-- gbrain-template-stamp: {version} -->",+ "<!-- gbrain-runbook-stamp: {version} -->"+ ],+ "migrations": { "dir": "src/core/schema-migrations", "id": "^v(\\d+)-" }+}+```++gbrain's `bun run release:restamp` fetches master, picks its own version,+refuses a dirty tree and commits, so it cannot be `restamp_command` as it+stands; the stamp rule above lets gstack's own restamp writer do the work.+A gbrain mode that takes the version and writes only stamps would make it one.++gbrain-evals `.gstack/pregate.json`: the sealed paths. The globs below are+placeholders in the shape the guard reads; gbrain-evals fills in its own+held-out and transcript layout.++```json+{ "sealed": {+ "paths": ["heldout/**"],+ "transcripts": ["runs/**/transcript*.jsonl"],+ "answer_markers": ["SEALED ANSWER:"],+ "seed_patterns": ["shuffle_seed=\\d+"],+ "local_paths": true } }+```<a id="issue-links"></a>## `gstack-issue-links`diff --git a/docs/ship-policy.md b/docs/ship-policy.mdindex e1e7ef715..10bc6eb9c 100644--- a/docs/ship-policy.md+++ b/docs/ship-policy.md@@ -43,6 +43,10 @@ prints this table. JSON carries no comments, so examples live in| `stamp_sensitive_gates` | evidence labels | `[]` | Gates that read VERSION or generated bytes (gstack's own `tests` lane does, through the agents-digest freshness test). The tree receipt never marks them reusable. || `pr_count` | `{ default_pr_count, split_requires_owner }` | `{1, true}` | The PR-count row in plan reviews. || `maintainers` | GitHub logins | `[]` | Maintainer set for `/review` contributor mode; empty means repository push permission. |+| `stamp_files` | globs | `[]` | The repo's stamp rule: when set, only these files may differ by a stamp (list the version file, manifests, plugin trees and the files holding the PR's own `since:` rows). It applies before every other stamp rule, so a doc `vX` mention outside it is a difference. |+| `stamp_patterns` | literal templates | `[]` | At most 16 templates of at most 128 characters, each with exactly one `{version}` slot (`"version": "{version}"`, `since: '{version}'`, `<!-- x-stamp: {version} -->`); matched literally at a version boundary, never as a regex. The restamp writer and the tree receipt use them beside the built-in forms. |+| `restamp_command` | command or `null` | `null` | The repo's own restamp, run first in the staging worktree; see [restamp_command](#restamp-command). |+| `migrations` | `{ dir, id }` or `null` | `null` | The migration directory and a regex with exactly one capture group for the number in a file name (`"^v(\\d+)-"`); `gstack-pregate regate` reports `MIGRATION_COLLISION`. |Containment, checked by `validate` and again at write time: paths and globs arerepo-relative with no `..` segment, under 256 characters, at most 64 per list,@@ -161,10 +165,11 @@ or the order moved, the result is `QUEUE_STALE` (exit 3) with the exactStages, each journaled in `.gstack/tmp/restamp-journal.json`:-1. **version**: `gstack-version-bump write --version <X>` in the staging worktree (VERSION, the manifest, npm lockfiles).+0. **restamp_command** (only when the policy sets it): the repo's own restamp, see [restamp_command](#restamp-command).+1. **version**: `gstack-version-bump write --version <X>` in the staging worktree (VERSION, the manifest, npm lockfiles); skipped when `restamp_command` owns the version.2. **release_tool**: the policy command, under the contract below.3. **changelog**: the PR's `[Unreleased]` or old-version section moves to the top under `<X>`, above its predecessor's entry. Duplicate headings (`CHANGELOG_DUPLICATE_HEADING`) and a top entry that is not `<X>` (`CHANGELOG_TOP_MISMATCH`) are errors.-4. **stamp_paths**: exact `(was X)`, `since: X` and `vX` rewrites within the declared globs. `X` is the branch's own tentative stamp (its VERSION when it moved past base), else `--was <X>`, else the version an unstamped branch would have taken next (`base + bump`); mentions of a version the base never released (not a CHANGELOG heading at base, not a tag) are rewritten too, so a queue reorder that moves the base under a branch still finds its `since:` fields. Only the repo's own version width counts, so a 3-digit dependency pin in a 4-digit repo is never a candidate.+4. **stamp_paths**: exact `(was X)`, `since: X` and `vX` rewrites, plus every `stamp_patterns` template, within `stamp_paths` and `stamp_files`. `X` is the branch's own tentative stamp (its VERSION when it moved past base), else `--was <X>`, else the version an unstamped branch would have taken next (`base + bump`); mentions of a version the base never released (not a CHANGELOG heading at base, not a tag) are rewritten too, so a queue reorder that moves the base under a branch still finds its `since:` fields. Only the repo's own version width counts, so a 3-digit dependency pin in a 4-digit repo is never a candidate.5. **mirror**: tier 2; declared and validated, reported as not run.6. **apply**: every changed file is written to the branch only after all stages validated, each against the fingerprinted preimage; a file edited meanwhile is `RESTAMP_CONFLICT` and the applied writes roll back (rollback refuses to overwrite a file whose bytes differ from the recorded postimage).@@ -199,6 +204,26 @@ implementation (`bun run release:restamp` still runs the PR's package script),so the receipt names the policy revision, the command, its working directoryand the trust scope (`policy: base origin/main@<sha>` or `head (unreviewed)`).+<a id="restamp-command"></a>+### `restamp_command`: the repo owns the stamp++A repo whose own tool knows its stamp locations sets `restamp_command`.+`gstack-restamp` runs it as the first stage inside its staging worktree, a+clean checkout of HEAD, with the allocated version as the last argument and in+`GSTACK_RESTAMP_VERSION`. The caller's HEAD, index and worktree must be clean+first (`RESTAMP_CONFLICT`, nothing written); the generic path keeps its+working-tree fingerprint seed. Anything the command stages or commits in the+staging worktree is folded back into plain edits; then output confinement+applies as for the release tool (`RESTAMP_OUTPUT_OUTSIDE_ALLOWED`), the+version file must hold the target version (`RESTAMP_VERSION_SOURCE`), and a+non-zero exit is `RESTAMP_RELEASE_TOOL_FAILED`. In every failure nothing+reaches the branch. gstack's version writer is skipped; the CHANGELOG and+`stamp_paths` stages still run (a no-op when the tool already did the work).+Read from the base branch and run only with `--allow-repo-commands`, like+`release_tool`. A tool that fetches, merges the base branch or needs a version+of its own choosing cannot run here; give it a mode that takes the version and+writes only stamps.+<a id="tree-receipt"></a>## The tree receipt@@ -225,7 +250,10 @@ the CHANGELOG (a heading move or re-heading, compared as an order-independentmultiset of entries), `stamp_paths` and `release_outputs` (everyremoved/added pair must be an exact `(was X)` / `since: X` / `vX` rewrite withX the gated version and the replacement the current one, so a dependency pin-that happens to equal the old version is `changed`). Any other byte is a change.+that happens to equal the old version is `changed`; `stamp_patterns`+templates count as stamp forms too). With `stamp_files` set, a file outside it+is `changed (stamp_files: not in the repo's stamp_files allowlist)` whatever+its diff. Any other byte is a change.Equivalence is decided per gate. A lane in `stamp_sensitive_gates` always`rerun`s; a verified lane is `reusable` only when the tree is same-modulo-stampsdiff --git a/docs/troubleshooting.md b/docs/troubleshooting.mdindex 0af8541c9..fe26c07f3 100644--- a/docs/troubleshooting.md+++ b/docs/troubleshooting.md@@ -2543,6 +2543,99 @@ and rewrites every file. Use your install directory if it is not`~/.claude/skills/gstack` (`./setup --status` prints it). Expected result: thenext `./setup` prints no CRLF warning.+## Field wave lane CD: pregate guards, regate, sealed output++<a id="pregate-guard-failed"></a>+### `PREGATE_GUARD_FAILED`++**Meaning.** A guard from the base branch's `.gstack/pregate.json` (a repo+command such as a serial-test manifest check or a CLI golden test) matched a+file the branch touched and exited non-zero. Guards cover what the import graph+cannot see: manifests, subprocess goldens, registries. They cannot be+downgraded to warn.++**Fix.** Read the guard's lines in the table (exit code, output tail, log path)+and do what its `fix` line says, commit, then rerun+`gstack-pregate run --allow-repo-commands`. A lane reports done only after this+passes and carries the `PREGATE:` line in its handoff.++<a id="migration-collision"></a>+### `MIGRATION_COLLISION`++**Meaning.** `gstack-pregate regate` read `migrations` (`dir`, `id`) from the+base branch's `.gstack/ship-policy.json` and found a migration number this+branch adds that the base branch already has, or that another open PR adds+under a different file name. Both PRs would pass their own gates and the+second merge would break the schema order. When the open-PR lookup cannot+finish (`gh` missing or failing, 1000 open PRs, a PR whose file list GitHub+truncates and cannot be fetched in full) the line says+`MIGRATION_COLLISION: unknown (...)` and `REGATE: not-needed` is withheld.++**Fix.** Take the next free migration number when this PR is next to merge,+rename the file and its id, commit, then rerun+`gstack-pregate regate --against <gated-head> --bundle <file>`. The renamed+migration is a code change, so the gate reruns.++<a id="sealed-output-refused"></a>+### `SEALED_OUTPUT_REFUSED`++**Meaning.** The repo declares a `sealed` policy in `.gstack/pregate.json`+(base branch ∪ the pushed commit) and a commit this push publishes adds a+sealed path or transcript (binary, empty and later-deleted files included), or+adds a line with a sealed-answer marker, a seed or a local home path, and the+destination is public or its visibility is unknown (a new or unreadable+repository counts as public). An unreadable or malformed sealed policy refuses+too. The managed pre-push hook and `gstack-pregate sealed` print one line per+finding: rule, `file[:line]`, commit. They never print the matched text.++**Fix.** Remove the output from every published commit before the branch+reaches the public repository (a later commit that deletes it still publishes+it). A reviewed false positive gets one line in the base branch's+`.gstack/sealed-allow.tsv`: `rule<TAB>path<TAB>sha<TAB>reason`. A private+destination sets `"visibility": "private"` under `sealed` in the base branch's+`.gstack/pregate.json`. Capy's pull-request tool may not run local hooks, so+run `gstack-pregate sealed` yourself before any push or PR creation.++<a id="eval-gate-unpriced"></a>+### `EVAL_GATE_UNPRICED`++**Meaning.** `gstack-eval-plan price-gate` found no call-plan file for the paid+gate: no `--plan-file`, no `price_file` in the base branch's+`.gstack/pregate.json`, or the file has no `GSTACK_EVAL_CALLS` lines. (A+declared `price_file` missing from HEAD is `EVAL_PLAN_STALE`, not this.) A gate whose cost is unknown cannot+be approved as priced.++**Fix.** The consuming repo commits a call-plan file in the format of+[docs/eval-calls.md](eval-calls.md) and names it in `price_file`. Only when the+owner accepts an unpriced gate, rerun with `--allow-unpriced "<reason>"`: it+exits 0, prints `GATE_UNPRICED_OVERRIDE: <reason> (owner-authorized override;+not authorization to spend)` and records the reason in the receipt.++<a id="eval-gate-over-cap"></a>+### `EVAL_GATE_OVER_CAP`++**Meaning.** The gate's priced total is above `--cap-usd`, or one call's+reservation (its share of the input plus `max_out_tokens`) is above `--cap-usd`,+or above `--smoke-cap-usd` for a `scope=smoke` row. A provider refuses a+reservation the cap cannot hold, so the run would fail after spending.++**Fix.** Cut questions, arms or `max_out_tokens` in the call plan and+regenerate it, or raise the cap deliberately with the owner. Never split calls+to slip under it.++<a id="eval-plan-stale"></a>+### `EVAL_PLAN_STALE`++**Meaning.** The call-plan file prices something other than what is being+approved: its `GSTACK_EVAL_GATE` command is not the exact `--gate` string, its+`GSTACK_EVAL_HEAD` is behind HEAD with files other than the plan file changed+since, an input's sha256 at HEAD differs from its `GSTACK_EVAL_INPUT` line, or+the base policy's `price_file` is not in the HEAD commit. `--allow-unpriced`+does not override it.++**Fix.** Regenerate the plan file at HEAD for the exact gate command (the+repo's own producer), commit it, and rerun `gstack-eval-plan price-gate`.+<a id="plan-sections-invalid"></a>### `PLAN_SECTIONS_INVALID`diff --git a/docs/unattended.md b/docs/unattended.mdindex e566bdf49..70a76fc74 100644--- a/docs/unattended.md+++ b/docs/unattended.md@@ -323,6 +323,17 @@ lines whose decision is still pending stay and are reported as`DRAFT_DIRECTION_UNRESOLVED` (exit 1). `gstack-autoplan answer` runs the samerewrite when a reply completes the gate (journal event `draft_directions_closed`).+## Lane done: pregate, the sealed guard and the handoff lines++A lane under a coordinator runs `gstack-pregate run --allow-repo-commands` on+its branch before it reports done (the unit tier on the changed files plus+the repo's guards, [docs/pregate.md#guards](pregate.md#guards)). In a repo+whose `.gstack/pregate.json` has a `sealed` key it runs `gstack-pregate sealed`+before any push or PR creation, since a PR tool may not run local hooks. Its+handoff carries, right after the `GSTACK_RESULT` line, the `gstack: ok|fail+<rev>` line and then the `PREGATE:` line. The coordinator contract+(`gstack-autoplan contract`) states the same rule word for word.+## Timing`/autoplan` prints `ESTIMATE: ...` at Phase 0 (`gstack-autoplan-timingdiff --git a/eval-plan/SKILL.md b/eval-plan/SKILL.mdindex e4a390ff6..2e8d741c0 100644--- a/eval-plan/SKILL.md+++ b/eval-plan/SKILL.md@@ -428,6 +428,8 @@ the budget the run will use. The checklist printed must be all `ok`:spends output tokens thinking, and a smaller budget truncates the answer the scorer reads.- `CHECK: retry-prompt` — the exact text the run sends on a retry, printed verbatim; a retrywith no text is a repeat of the same failure at the same price.+- `CHECK: reservation-fits-cap` (with `--cap <cap-usd>`) — one call, the largest row plus the+ output budget, priced, fits under the cap; a provider refuses a reservation the cap cannot hold.- `DRY_RUN_ROW:` lines name rows missing a field; fix the rows, not the prompt.`DRY_RUN_RESULT: pass` writes `dry-run.json` to `--out`; the pilot refuses to start on@@ -459,8 +461,32 @@ the preregistration, when `status=budget_exhausted`, or when `verdict=exceeds`.## Step 4: The approval ask+Price every paid gate the plan names (a benchmark or eval command that spends) from the+repo's call-plan file; nothing is executed (`docs/eval-calls.md` in gstack). The gate+command is free text, so it reaches the pricer only as a file:++```bash+_GT="$(git rev-parse --show-toplevel 2>/dev/null || pwd)/.gstack/tmp"+mkdir -p "$_GT" && chmod 700 "$_GT" || { echo "Not sent: cannot create $_GT for the text file." >&2; exit 1; }+_EX=$(git rev-parse --git-path info/exclude 2>/dev/null) && mkdir -p "$(dirname "$_EX")" && { grep -qxF '/.gstack/tmp/' "$_EX" 2>/dev/null || echo '/.gstack/tmp/' >> "$_EX"; }+GATE_FILE=$(mktemp "${_GT:?}/gate-command.XXXXXX") || { echo "Not sent: mktemp failed in $_GT." >&2; exit 1; }; echo "GATE_FILE: $GATE_FILE (name: ${GATE_FILE##*/})"+```++Write the text into each printed file with your file-write tool (Claude Code's Write tool needs a Read of the empty file first), exactly as it should appear. The text never goes into a shell command, heredoc or quoted argument. If a write fails or is refused, do not send: print the cause, the file path and the command below for sending by hand.++Write the exact gate command, one line, into the printed file, then price it:++```bash+GATE_FILE="$(git rev-parse --show-toplevel 2>/dev/null || pwd)/.gstack/tmp/<gate-file-name>"+~/.claude/skills/gstack/bin/gstack-eval-plan price-gate --gate-file "$GATE_FILE" --cap-usd <cap-usd>+```++Each `GATE_PRICE:` line goes into the ask. `EVAL_GATE_UNPRICED`, `EVAL_PLAN_STALE`,+`EVAL_PRICE_MISSING` or `EVAL_GATE_OVER_CAP` means that gate is not approvable as priced;+`--allow-unpriced "<reason>"` only on the owner's word.+Present, in this order and nothing before it: the `PILOT_PROJECTION:` line, the spend-table, the pilot's per-bar results, and the preregistration's stop rules. Then ask one+table, each gate's `GATE_PRICE:` line, the pilot's per-bar results, and the preregistration's stop rules. Then ask onequestion with the projection as the recommended option only when `verdict=within`:- A) Run `<total-items>` items at the projected cost (recommended when within the cap)diff --git a/eval-plan/SKILL.md.tmpl b/eval-plan/SKILL.md.tmplindex 584ce2b45..2dcf76aed 100644--- a/eval-plan/SKILL.md.tmpl+++ b/eval-plan/SKILL.md.tmpl@@ -100,6 +100,8 @@ the budget the run will use. The checklist printed must be all `ok`:spends output tokens thinking, and a smaller budget truncates the answer the scorer reads.- `CHECK: retry-prompt` — the exact text the run sends on a retry, printed verbatim; a retrywith no text is a repeat of the same failure at the same price.+- `CHECK: reservation-fits-cap` (with `--cap <cap-usd>`) — one call, the largest row plus the+ output budget, priced, fits under the cap; a provider refuses a reservation the cap cannot hold.- `DRY_RUN_ROW:` lines name rows missing a field; fix the rows, not the prompt.`DRY_RUN_RESULT: pass` writes `dry-run.json` to `--out`; the pilot refuses to start on@@ -131,8 +133,25 @@ the preregistration, when `status=budget_exhausted`, or when `verdict=exceeds`.## Step 4: The approval ask+Price every paid gate the plan names (a benchmark or eval command that spends) from the+repo's call-plan file; nothing is executed (`docs/eval-calls.md` in gstack). The gate+command is free text, so it reaches the pricer only as a file:++{{FREE_TEXT_FILE:GATE_FILE=gate-command}}++Write the exact gate command, one line, into the printed file, then price it:++```bash+GATE_FILE="$(git rev-parse --show-toplevel 2>/dev/null || pwd)/.gstack/tmp/<gate-file-name>"+~/.claude/skills/gstack/bin/gstack-eval-plan price-gate --gate-file "$GATE_FILE" --cap-usd <cap-usd>+```++Each `GATE_PRICE:` line goes into the ask. `EVAL_GATE_UNPRICED`, `EVAL_PLAN_STALE`,+`EVAL_PRICE_MISSING` or `EVAL_GATE_OVER_CAP` means that gate is not approvable as priced;+`--allow-unpriced "<reason>"` only on the owner's word.+Present, in this order and nothing before it: the `PILOT_PROJECTION:` line, the spend-table, the pilot's per-bar results, and the preregistration's stop rules. Then ask one+table, each gate's `GATE_PRICE:` line, the pilot's per-bar results, and the preregistration's stop rules. Then ask onequestion with the projection as the recommended option only when `verdict=within`:- A) Run `<total-items>` items at the projected cost (recommended when within the cap)diff --git a/lib/coordinator-contract.ts b/lib/coordinator-contract.tsindex 702c31dac..86243b453 100644--- a/lib/coordinator-contract.ts+++ b/lib/coordinator-contract.ts@@ -19,4 +19,6 @@ Behavior-change notices. Every user-visible behavior change outside the plan's oSpend caps. Each lane runs under the \`--spend-cap\` the coordinator names; a lane that reaches it stops with \`status=budget_exhausted\` and reports spent, reserved and unknown charges. Paid evals are never retried to change a verdict; a rerun needs a named repair. Host-subagent spend is reported as \`unknown\`, never zero.-Handoff format. A lane reports in this order, identifiers first: PR URL (or \`no PR\` with branch and SHA), \`GSTACK_RESULT\` line, gate summary (lanes passed/failed/skipped), behavior changes (or \`none\`), spend (spent/reserved/unknown), then what it could not verify. Full thread ids (\`jam_…\`), never short codes, in every cross-thread message. Prose after the identifiers may be truncated; nothing before them may be.`;+Before done. A lane runs \`gstack-pregate run --allow-repo-commands\` on its branch (the unit tier on the changed files plus the repo's guards) and reports done only after it passes. In a repo whose \`.gstack/pregate.json\` has a \`sealed\` key, it runs \`gstack-pregate sealed\` before any push or PR creation; a refusal stops the push, because a PR tool may not run local hooks.++Handoff format. A lane reports in this order, identifiers first: PR URL (or \`no PR\` with branch and SHA), \`GSTACK_RESULT\` line, the \`gstack: ok|fail <rev>\` line, the \`PREGATE:\` line, gate summary (lanes passed/failed/skipped), behavior changes (or \`none\`), spend (spent/reserved/unknown), then what it could not verify. Full thread ids (\`jam_…\`), never short codes, in every cross-thread message. Prose after the identifiers may be truncated; nothing before them may be.`;diff --git a/lib/eval-plan.ts b/lib/eval-plan.tsindex 162bc27e7..3cfd12eba 100644--- a/lib/eval-plan.ts+++ b/lib/eval-plan.ts@@ -9,9 +9,12 @@* (lib/pricing.ts), so the spend table always shows `unknown` charges and the* worst-case overrun (one in-flight call per worker) beside `spent`.*/+import { spawnSync } from 'node:child_process';+import { createHash } from 'node:crypto';import * as fs from 'node:fs';import * as path from 'node:path';import { modelsMain } from './model-policy-cli';+import { isConfigUnavailable, loadConfigFromBase } from './pregate/config';import { EXCLUDED_BILLING_CATEGORIES, estimateCostUsd, hasPricing, PRICING, pricingRow } from './pricing';import type { ResultCodeName } from './result-codes';import { readLedger, release, reserve, settle, SpendCapExceeded, summarize, type SpendLedger, type SpendSummary } from './spend-ledger';@@ -129,10 +132,15 @@ export const REASONING_OUTPUT_FLOOR = 8_192;export interface DryRunRow { line: number; ok: boolean; missing: string[]; input_tokens: number }export interface DryRunResult {schema_version: 1; input: string; rows: number; bad_rows: DryRunRow[]; est_input_tokens: number; est_output_tokens: number;- arms: string[]; checks: { price_table: { ok: boolean; missing: string[] }; output_budget: { ok: boolean; budget: number; floor: number }; retry_prompt: { ok: boolean; text: string | null } };+ arms: string[];+ checks: {+ price_table: { ok: boolean; missing: string[] }; output_budget: { ok: boolean; budget: number; floor: number }; retry_prompt: { ok: boolean; text: string | null };+ /** Present with `cap`: one call per arm (the largest row's input plus the output budget), priced, fits under the cap. */+ reservation_fits_cap?: { ok: boolean; cap: number; max_input_tokens: number; per_arm: Record<string, number | null> };+ };per_item_usd: Record<string, number | null>; excluded_billing: readonly string[]; pass: boolean; stub: 'stub-model (no network, $0)';}-export interface DryRunOptions { input: string; arms: string[]; fields?: string[]; outputBudget?: number; retryPrompt?: string; maxRows?: number }+export interface DryRunOptions { input: string; arms: string[]; fields?: string[]; outputBudget?: number; retryPrompt?: string; maxRows?: number; cap?: number }/** Four bytes per token, the estimator every gstack admission uses. */export const estimateTokens = (text: string) => Math.ceil(Buffer.byteLength(text, 'utf8') / 4);@@ -142,7 +150,7 @@ export function dryRun(o: DryRunOptions): DryRunResult {const budget = o.outputBudget ?? REASONING_OUTPUT_FLOOR;const text = fs.readFileSync(o.input, 'utf8');const lines = text.split('\n');- const bad: DryRunRow[] = []; let rows = 0; let inputTokens = 0;+ const bad: DryRunRow[] = []; let rows = 0; let inputTokens = 0; let maxInput = 0;lines.forEach((line, i) => {if (!line.trim()) return;if (o.maxRows && rows >= o.maxRows) return;@@ -153,6 +161,7 @@ export function dryRun(o: DryRunOptions): DryRunResult {const missing = fields.filter(f => parsed![f] === undefined || parsed![f] === null || parsed![f] === '');const t = estimateTokens(fields.map(f => typeof parsed![f] === 'string' ? parsed![f] as string : JSON.stringify(parsed![f] ?? '')).join('\n'));inputTokens += t;+ maxInput = Math.max(maxInput, t);if (missing.length) bad.push({ line: i + 1, ok: false, missing, input_tokens: t });});const retryText = o.retryPrompt && fs.existsSync(o.retryPrompt) ? fs.readFileSync(o.retryPrompt, 'utf8').trim() : null;@@ -164,10 +173,15 @@ export function dryRun(o: DryRunOptions): DryRunResult {price_table: { ok: missingPrice.length === 0 && o.arms.length > 0, missing: missingPrice },output_budget: { ok: budget >= REASONING_OUTPUT_FLOOR, budget, floor: REASONING_OUTPUT_FLOOR },retry_prompt: { ok: !!retryText, text: retryText },- };+ } as DryRunResult['checks'];+ if (o.cap !== undefined) {+ const perArm: Record<string, number | null> = {};+ for (const a of o.arms) perArm[a] = hasPricing(a) ? estimateCostUsd({ input: maxInput, output: budget }, a) : null;+ checks.reservation_fits_cap = { ok: Object.values(perArm).every(v => v === null || v <= o.cap!), cap: o.cap, max_input_tokens: maxInput, per_arm: perArm };+ }return {schema_version: 1, input: o.input, rows, bad_rows: bad, est_input_tokens: inputTokens, est_output_tokens: rows * budget, arms: o.arms, checks, per_item_usd: perItem,- excluded_billing: EXCLUDED_BILLING_CATEGORIES, pass: rows > 0 && bad.length === 0 && checks.price_table.ok && checks.output_budget.ok && checks.retry_prompt.ok, stub: 'stub-model (no network, $0)',+ excluded_billing: EXCLUDED_BILLING_CATEGORIES, pass: rows > 0 && bad.length === 0 && checks.price_table.ok && checks.output_budget.ok && checks.retry_prompt.ok && (checks.reservation_fits_cap?.ok ?? true), stub: 'stub-model (no network, $0)',};}@@ -178,12 +192,18 @@ export function renderDryRun(r: DryRunResult): string {`CHECK: price-table ${r.checks.price_table.ok ? 'ok' : `missing ${r.checks.price_table.missing.join(',') || '(no arms)'}`}`,`CHECK: output-budget ${r.checks.output_budget.ok ? 'ok' : 'too small'} (${r.checks.output_budget.budget} tokens; reasoning floor ${r.checks.output_budget.floor})`,`CHECK: retry-prompt ${r.checks.retry_prompt.ok ? `ok — ${JSON.stringify(r.checks.retry_prompt.text)}` : 'missing (pass --retry-prompt <file> with the exact text the run will send)'}`,+ ...(r.checks.reservation_fits_cap ? [renderReservationCheck(r.checks.reservation_fits_cap, r.checks.output_budget.budget)] : []),...Object.entries(r.per_item_usd).map(([m, usd]) => `ESTIMATE: ${m} per_item=${usd === null ? 'unknown (no price)' : `$${usd.toFixed(4)}`} (estimate: excludes ${r.excluded_billing.length} billing categories, see lib/pricing.ts)`),`DRY_RUN_RESULT: ${r.pass ? 'pass' : 'fail'}`,];return lines.join('\n') + '\n';}+function renderReservationCheck(c: NonNullable<DryRunResult['checks']['reservation_fits_cap']>, budget: number): string {+ const worst = Math.max(0, ...Object.values(c.per_arm).filter((v): v is number => v !== null));+ return `CHECK: reservation-fits-cap ${c.ok ? 'ok' : 'exceeds'} ($${worst.toFixed(4)} ${c.ok ? '<=' : '>'} cap $${c.cap.toFixed(2)}) one call = ${c.max_input_tokens} in + ${budget} out tokens`;+}+// ---------------------------------------------------------------------------// priced pilot over lib/spend-ledger.ts// ---------------------------------------------------------------------------@@ -275,3 +295,237 @@ export function renderPilotReport(r: PilotReport): string {p.verdict === 'unknown' ? `APPROVAL: not ready — ${r.settled_known < 2 ? 'settle at least 2 pilot attempts with actual cost' : 'unknown charges make the band meaningless'}; settle, then rerun report` : `APPROVAL: run ${p.total} items at projected ${usd(p.projected_usd)} (95% band ${usd(p.band_usd![0])}–${usd(p.band_usd![1])}) under cap $${r.record.cap_usd.toFixed(2)}: ${p.verdict === 'within' ? 'fits; ask the owner before any further priced call' : 'EXCEEDS the cap; stop, raise the cap on purpose or cut arms or items'}`,].join('\n') + '\n';}++// ---------------------------------------------------------------------------+// paid gates priced from a call-plan data file (docs/eval-calls.md)+// ---------------------------------------------------------------------------+/**+ * The plan file is DATA: `price-gate` reads it, checks its binding (the exact+ * gate command, the head it was produced at, each input's sha256 at HEAD) and+ * prices its `GSTACK_EVAL_CALLS v1` rows. Nothing in it is ever executed.+ */+export const EVAL_CALL_KEYS = ['purpose', 'model', 'calls', 'in_tokens', 'out_tokens', 'max_out_tokens', 'scope'] as const;+export interface EvalCallRow { purpose: string; model: string; calls: number; in_tokens: number; out_tokens: number; max_out_tokens: number; scope: 'full' | 'smoke' }+export interface EvalPlanInput { path: string; sha256: string }+export interface EvalCallPlan { gate: string; head: string; inputs: EvalPlanInput[]; preconditions: string[]; rows: EvalCallRow[] }++/** The reference emitter a consuming repo copies: binding lines, preconditions, one line per call purpose, the end line. */+export function formatEvalCalls(p: EvalCallPlan): string {+ return [+ '# gstack eval call plan, wire format v1 (docs/eval-calls.md); priced by `gstack-eval-plan price-gate`, never executed',+ `GSTACK_EVAL_GATE v1: ${p.gate}`,+ `GSTACK_EVAL_HEAD v1: ${p.head}`,+ ...p.inputs.map(i => `GSTACK_EVAL_INPUT v1: sha256=${i.sha256} path=${i.path}`),+ ...p.preconditions.map(t => `GSTACK_EVAL_PRECONDITION: ${t}`),+ ...p.rows.map(r => `GSTACK_EVAL_CALLS v1: ${EVAL_CALL_KEYS.map(k => `${k}=${r[k]}`).join(' ')}`),+ `GSTACK_EVAL_CALLS v1 end: lines=${p.rows.length}`,+ ].join('\n') + '\n';+}++const INT_KEYS = ['calls', 'in_tokens', 'out_tokens', 'max_out_tokens'] as const;++function parseCallRow(body: string, at: string): EvalCallRow | string {+ const fields: Record<string, string> = {};+ for (const tok of body.trim().split(/ +/)) {+ const eq = tok.indexOf('=');+ if (eq <= 0) return `${at}: ${JSON.stringify(tok)} is not key=value`;+ const key = tok.slice(0, eq);+ if (!(EVAL_CALL_KEYS as readonly string[]).includes(key)) return `${at}: unknown key ${key}`;+ if (key in fields) return `${at}: duplicate key ${key}`;+ fields[key] = tok.slice(eq + 1);+ }+ for (const key of EVAL_CALL_KEYS) if (!(key in fields)) return `${at}: missing key ${key}`;+ for (const key of INT_KEYS) if (!/^\d+$/.test(fields[key]!)) return `${at}: ${key} must be a non-negative integer (got ${JSON.stringify(fields[key])})`;+ if (Number(fields.calls) < 1) return `${at}: calls must be at least 1`;+ if (fields.scope !== 'full' && fields.scope !== 'smoke') return `${at}: scope must be full or smoke (got ${JSON.stringify(fields.scope)})`;+ if (!/^[A-Za-z0-9._:-]+$/.test(fields.purpose!)) return `${at}: purpose must match [A-Za-z0-9._:-]+`;+ if (!fields.model) return `${at}: model is empty`;+ return { purpose: fields.purpose!, model: fields.model, calls: Number(fields.calls), in_tokens: Number(fields.in_tokens), out_tokens: Number(fields.out_tokens), max_out_tokens: Number(fields.max_out_tokens), scope: fields.scope };+}++/** Strict v1 parser: a malformed line, an unknown kind or version, a missing binding or a missing or miscounted end line refuses, naming the line. */+export function parseEvalCalls(text: string): { plan: EvalCallPlan } | { error: string } {+ const plan: EvalCallPlan = { gate: '', head: '', inputs: [], preconditions: [], rows: [] };+ const seen = new Set<string>();+ let gate: string | null = null; let head: string | null = null; let ended = false;+ const lines = text.split('\n');+ for (let i = 0; i < lines.length; i++) {+ const raw = lines[i]!.replace(/\r$/, ''); const at = `line ${i + 1}`;+ if (!raw.trim() || raw.startsWith('#')) continue;+ if (ended) return { error: `${at}: content after the end line` };+ const m = /^(GSTACK_EVAL_[A-Z_]+?)(?: (v\d+))?( end)?: (.*)$/.exec(raw);+ if (!m) return { error: `${at}: not a GSTACK_EVAL_ line (${JSON.stringify(raw.slice(0, 80))})` };+ const [, kind, version, end, body] = m as unknown as [string, string, string | undefined, string | undefined, string];+ if (kind === 'GSTACK_EVAL_PRECONDITION' && !version && !end) { plan.preconditions.push(body.trim()); continue; }+ if (!['GSTACK_EVAL_GATE', 'GSTACK_EVAL_HEAD', 'GSTACK_EVAL_INPUT', 'GSTACK_EVAL_CALLS'].includes(kind)) return { error: `${at}: unknown line kind ${kind}` };+ if (version !== 'v1') return { error: `${at}: ${kind} version ${version ?? '(none)'} is not supported (this gstack reads v1)` };+ if (end) {+ const n = kind === 'GSTACK_EVAL_CALLS' ? /^lines=(\d+)$/.exec(body.trim()) : null;+ if (!n) return { error: `${at}: malformed end line (expected GSTACK_EVAL_CALLS v1 end: lines=<n>)` };+ if (Number(n[1]) !== plan.rows.length) return { error: `${at}: end line says lines=${n[1]} but the file has ${plan.rows.length} call lines` };+ ended = true; continue;+ }+ if (kind === 'GSTACK_EVAL_GATE') {+ if (gate !== null) return { error: `${at}: second GSTACK_EVAL_GATE line` };+ if (!body.trim()) return { error: `${at}: empty gate command` };+ gate = body; continue;+ }+ if (kind === 'GSTACK_EVAL_HEAD') {+ if (head !== null) return { error: `${at}: second GSTACK_EVAL_HEAD line` };+ if (!/^([0-9a-f]{40}|[0-9a-f]{64})$/.test(body.trim())) return { error: `${at}: head must be a full commit sha` };+ head = body.trim(); continue;+ }+ if (kind === 'GSTACK_EVAL_INPUT') {+ const inp = /^sha256=([0-9a-f]{64}) path=(.+)$/.exec(body);+ if (!inp) return { error: `${at}: expected GSTACK_EVAL_INPUT v1: sha256=<64 hex> path=<repo-relative path>` };+ if (path.isAbsolute(inp[2]!) || inp[2]!.split(/[\\/]/).includes('..')) return { error: `${at}: input path must be repo-relative without .. (${inp[2]})` };+ plan.inputs.push({ path: inp[2]!, sha256: inp[1]! }); continue;+ }+ const row = parseCallRow(body, at);+ if (typeof row === 'string') return { error: row };+ if (seen.has(`${row.purpose}\0${row.model}`)) return { error: `${at}: duplicate purpose=${row.purpose} model=${row.model}` };+ seen.add(`${row.purpose}\0${row.model}`);+ plan.rows.push(row);+ }+ if (gate === null) return { error: 'missing GSTACK_EVAL_GATE v1 line (the exact gate command this plan prices)' };+ if (head === null) return { error: 'missing GSTACK_EVAL_HEAD v1 line (the commit the plan was produced at)' };+ if (!ended) return { error: 'missing end line (GSTACK_EVAL_CALLS v1 end: lines=<n>); a partial file is refused' };+ return { plan: { ...plan, gate, head } };+}++export interface PricedCallRow extends EvalCallRow { usd: number | null; reservation_usd: number | null }+export interface GateReceipt {+ schema_version: 1; kind: 'gstack-eval-price-gate'; created_at: string; gstack_revision: string;+ gate_command: string; gate_sha256: string; head_sha: string;+ plan: { file: string | null; source: 'flag' | 'price_file' | 'none'; sha256: string | null; declared_head: string | null };+ inputs: EvalPlanInput[]; preconditions: string[]; rows: PricedCallRow[];+ total_usd: number | null; calls: number; purposes: string[]; cap_usd: number | null; smoke_cap_usd: number | null;+ result: 'priced' | 'price_missing' | 'over_cap' | 'unpriced' | 'unpriced_override'; code: ResultCodeName | null;+ unpriced_reason: string | null; unpriced_override: string | null; excluded_billing: readonly string[];+}+export interface PlanSource { text: Buffer | null; file: string | null; source: GateReceipt['plan']['source']; repoPath: string | null; why: string | null }+export interface PriceGateOptions { repoRoot: string; gate: string; plan: PlanSource; capUsd?: number; smokeCapUsd?: number; allowUnpriced?: string; now?: Date }+export interface PriceGateResult { lines: string[]; receipt: GateReceipt | null; error?: { code: ResultCodeName; message: string } }++const sha256 = (b: Buffer | string) => createHash('sha256').update(b).digest('hex');+function gitOut(repoRoot: string, args: string[]): Buffer | null {+ const r = spawnSync('git', args, { cwd: repoRoot, timeout: 30_000 });+ return r.status === 0 ? r.stdout : null;+}++export interface PlanSourceRefusal { code: ResultCodeName; message: string; refused: boolean }++/**+ * `--plan-file` wins; else the base policy's `price_file`, read from the HEAD+ * commit's bytes. Only "no plan declared" is unpriced (overridable); a declared+ * file missing at HEAD is stale, an unresolvable base or an invalid policy refuses.+ */+export function resolvePlanSource(repoRoot: string, o: { planFile?: string; base: string }): PlanSource | PlanSourceRefusal {+ if (o.planFile) {+ const file = path.resolve(o.planFile);+ const rel = path.relative(repoRoot, file);+ return { text: fs.readFileSync(file), file, source: 'flag', repoPath: rel && !rel.startsWith('..') && !path.isAbsolute(rel) ? rel.split(path.sep).join('/') : null, why: null };+ }+ const load = loadConfigFromBase(repoRoot, o.base);+ if (isConfigUnavailable(load)) return { code: 'POLICY_SOURCE_UNAVAILABLE', message: `no --plan-file and the base policy cannot be read (${load.detail})`, refused: true };+ if (load.errors.length) return { code: 'PREGATE_CONFIG_INVALID', message: `${load.label}: ${load.errors.map(e => `${e.path}: ${e.message}`).join('; ')}`, refused: true };+ const rel = load.config.price_file;+ if (!rel) return { text: null, file: null, source: 'none', repoPath: null, why: `no --plan-file and ${load.label} declares no price_file` };+ const text = gitOut(repoRoot, ['show', `HEAD:${rel}`]);+ if (!text) return { code: 'EVAL_PLAN_STALE', message: `price_file ${rel} (declared in ${load.label}) is not in the HEAD commit`, refused: false };+ return { text, file: rel, source: 'price_file', repoPath: rel, why: null };+}++/** Stale binding: the gate command, the head (only the plan file itself may change after it) and every input hash at HEAD. */+function checkBinding(o: PriceGateOptions, plan: EvalCallPlan, headSha: string): string | null {+ if (plan.gate !== o.gate) return `gate command differs: --gate ${JSON.stringify(o.gate)} vs plan ${JSON.stringify(plan.gate)}`;+ if (plan.head !== headSha) {+ const diff = gitOut(o.repoRoot, ['diff', '--name-only', plan.head, headSha]);+ if (diff === null) return `declared head ${plan.head.slice(0, 12)} is not a commit in this repository (HEAD ${headSha.slice(0, 12)})`;+ const changed = diff.toString('utf8').split('\n').filter(Boolean);+ if (changed.some(f => f !== o.plan.repoPath)) return `declared head ${plan.head.slice(0, 12)} is behind HEAD ${headSha.slice(0, 12)}: ${changed.length} file(s) changed since (${changed.slice(0, 3).join(', ')})`;+ }+ for (const input of plan.inputs) {+ const bytes = gitOut(o.repoRoot, ['show', `HEAD:${input.path}`]);+ if (!bytes) return `input ${input.path} is not in the HEAD commit`;+ const got = sha256(bytes);+ if (got !== input.sha256) return `input ${input.path} sha256 ${got.slice(0, 12)} at HEAD != declared ${input.sha256.slice(0, 12)}`;+ }+ return null;+}++export function gstackRevision(): string {+ const root = path.resolve(import.meta.dir, '..');+ const version = fs.existsSync(path.join(root, 'VERSION')) ? fs.readFileSync(path.join(root, 'VERSION'), 'utf8').trim() : 'unknown';+ const sha = gitOut(root, ['rev-parse', '--short', 'HEAD'])?.toString('utf8').trim();+ return sha ? `${version} (${sha})` : version;+}++const amount = (v: number | null) => (v === null ? 'unknown' : String(+v.toFixed(6)));++function priceRows(rows: EvalCallRow[]): PricedCallRow[] {+ return rows.map(r => {+ if (!hasPricing(r.model)) return { ...r, usd: null, reservation_usd: null };+ return { ...r, usd: estimateCostUsd({ input: r.in_tokens, output: r.out_tokens }, r.model), reservation_usd: estimateCostUsd({ input: Math.ceil(r.in_tokens / r.calls), output: r.max_out_tokens }, r.model) };+ });+}++/** Price a paid gate from its call-plan file. Malformed or stale files return an error and no receipt; every other outcome returns a receipt. */+export function priceGate(o: PriceGateOptions): PriceGateResult {+ const headSha = gitOut(o.repoRoot, ['rev-parse', 'HEAD'])?.toString('utf8').trim() ?? '';+ let plan: EvalCallPlan | null = null;+ if (o.plan.text) {+ const parsed = parseEvalCalls(o.plan.text.toString('utf8'));+ if ('error' in parsed) return { lines: [], receipt: null, error: { code: 'EVAL_DRY_RUN_FAILED', message: `${o.plan.file}: ${parsed.error}` } };+ const stale = checkBinding(o, parsed.plan, headSha);+ if (stale) return { lines: [], receipt: null, error: { code: 'EVAL_PLAN_STALE', message: `${o.plan.file}: ${stale}` } };+ plan = parsed.plan;+ }+ const rows = priceRows(plan?.rows ?? []);+ const total = rows.some(r => r.usd === null) ? null : +rows.reduce((s, r) => s + r.usd!, 0).toFixed(6);+ const lines = [+ ...(plan ? [`GATE_PLAN: file=${o.plan.file} source=${o.plan.source} sha256=${sha256(o.plan.text!)} head=${plan.head.slice(0, 12)}${plan.head === headSha ? '' : ` (HEAD ${headSha.slice(0, 12)}; only the plan file changed since)`} inputs=${plan.inputs.length} verified`] : []),+ ...(plan?.preconditions ?? []).map(t => `GATE_PRECONDITION: ${t}`),+ ...rows.map(r => `GATE_CALLS: purpose=${r.purpose} model=${r.model} calls=${r.calls} usd=${amount(r.usd)} reservation_usd=${amount(r.reservation_usd)} scope=${r.scope}`),+ ];+ let error: PriceGateResult['error'];+ let result: GateReceipt['result'] = 'priced';+ const unpricedWhy = !plan ? o.plan.why ?? 'no call-plan file' : rows.length === 0 ? `${o.plan.file} has no GSTACK_EVAL_CALLS lines` : null;+ if (unpricedWhy) {+ result = o.allowUnpriced ? 'unpriced_override' : 'unpriced';+ if (o.allowUnpriced) lines.push(`GATE_UNPRICED_OVERRIDE: ${o.allowUnpriced} (owner-authorized override; not authorization to spend)`);+ else error = { code: 'EVAL_GATE_UNPRICED', message: unpricedWhy };+ } else if (total === null) {+ result = 'price_missing';+ error = { code: 'EVAL_PRICE_MISSING', message: `no price row for ${rows.filter(r => r.usd === null).map(r => r.model).join(', ')}; the total is unknown, never zero` };+ } else {+ const over: string[] = [];+ if (o.capUsd !== undefined || o.smokeCapUsd !== undefined) {+ for (const r of rows) {+ const smoke = r.scope === 'smoke' && o.smokeCapUsd !== undefined && r.reservation_usd! > o.smokeCapUsd;+ const full = o.capUsd !== undefined && r.reservation_usd! > o.capUsd;+ if (!smoke && !full) continue;+ const why = `$${r.reservation_usd!.toFixed(4)} > ${smoke ? `smoke cap $${o.smokeCapUsd!.toFixed(2)}` : `cap $${o.capUsd!.toFixed(2)}`}`;+ lines.push(`CHECK: reservation-fits-cap exceeds (${why}) purpose=${r.purpose}`);+ over.push(`reservation-fits-cap: purpose=${r.purpose} one call ${why}`);+ }+ if (!over.length) lines.push(`CHECK: reservation-fits-cap ok (largest one-call reservation $${Math.max(0, ...rows.map(r => r.reservation_usd!)).toFixed(4)})`);+ }+ if (o.capUsd !== undefined && total > o.capUsd) over.unshift(`total $${total.toFixed(4)} > cap $${o.capUsd.toFixed(2)}`);+ if (over.length) { result = 'over_cap'; error = { code: 'EVAL_GATE_OVER_CAP', message: over.join('; ') }; }+ }+ const receipt: GateReceipt = {+ schema_version: 1, kind: 'gstack-eval-price-gate', created_at: (o.now ?? new Date()).toISOString(), gstack_revision: gstackRevision(),+ gate_command: o.gate, gate_sha256: sha256(o.gate), head_sha: headSha,+ plan: { file: o.plan.file, source: o.plan.source, sha256: o.plan.text ? sha256(o.plan.text) : null, declared_head: plan?.head ?? null },+ inputs: plan?.inputs ?? [], preconditions: plan?.preconditions ?? [], rows,+ total_usd: unpricedWhy ? null : total, calls: rows.reduce((s, r) => s + r.calls, 0), purposes: rows.map(r => r.purpose),+ cap_usd: o.capUsd ?? null, smoke_cap_usd: o.smokeCapUsd ?? null, result, code: error?.code ?? (unpricedWhy ? 'EVAL_GATE_UNPRICED' : null),+ unpriced_reason: unpricedWhy, unpriced_override: unpricedWhy ? o.allowUnpriced ?? null : null, excluded_billing: EXCLUDED_BILLING_CATEGORIES,+ };+ return { lines, receipt, error };+}++export function renderGatePrice(r: GateReceipt, receiptPath: string): string {+ return `GATE_PRICE: total=${amount(r.total_usd)} calls=${r.calls} purposes=${r.purposes.join(',') || 'none'} receipt=${receiptPath}`;+}diff --git a/lib/pregate/checks/guards.ts b/lib/pregate/checks/guards.tsnew file mode 100644index 000000000..b74d964a7--- /dev/null+++ b/lib/pregate/checks/guards.ts@@ -0,0 +1,64 @@+/**+ * pregate check `guards` (tier 2, preflight; field wave CD1): the repo's own+ * mechanical gates a lane must pass before it reports done. Each+ * `.gstack/pregate.json` guard `{ id, when, command, fix?, timeout_s? }`+ * whose `when` globs match a touched file runs in its own process (bash,+ * under the verified launch Bun, with its own timeout). A failing guard+ * fails pregate naming the guard and its fix; a timed-out one is+ * `incomplete`; without --allow-repo-commands the selected guards are listed+ * and the check is `incomplete`. Guards are never downgradable. Field+ * incident: a gbrain serial test landed without its manifest row and+ * passed both the isolation check and pregate; `test/cli-goldens.test.ts`+ * spawns the CLI as a subprocess, so no import graph selects 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';+import { matchesAny } from '../../ship-policy';+import type { Guard } from '../config';+import { baseInputs, sha256 } from '../context';+import { launchRuntime } from '../runtime';+import type { CheckDef, CheckResult, PregateContext } from '../types';++interface GuardRun { guard: Guard; exit: number | null; timedOut: boolean; tail: string[]; log: string }++function runGuard(ctx: PregateContext, guard: Guard, env: NodeJS.ProcessEnv, dir: string): GuardRun {+ const timeoutMs = guard.timeout_s ? guard.timeout_s * 1000 : ctx.timeoutMs;+ const r = spawnSync('bash', ['-c', `set -o pipefail; ${guard.command}`], { cwd: ctx.repoRoot, encoding: 'utf8', timeout: timeoutMs, killSignal: 'SIGKILL', maxBuffer: 64 * 1024 * 1024, env: { ...env, CI: env.CI ?? '1' } });+ const output = `${r.stdout ?? ''}\n${r.stderr ?? ''}`.trim();+ const log = path.join(dir, `${guard.id}.log`);+ fs.writeFileSync(log, `$ ${guard.command}\n${output}\n`);+ const timedOut = r.status === null;+ return { guard, exit: r.status, timedOut, tail: output ? output.split('\n').slice(-15) : [], log };+}++function run(ctx: PregateContext): CheckResult {+ const touched = ctx.touched.flatMap(t => (t.renamedFrom ? [t.path, t.renamedFrom] : [t.path]));+ const selected = ctx.config.guards.filter(g => touched.some(f => matchesAny(g.when, f)));+ const inputs = baseInputs(ctx, { guards: sha256(selected.map(g => `${g.id}\0${g.command}`).join('\n')) });+ const base: CheckResult = { id: 'guards', stage: 'preflight', status: 'pass', inputs };+ if (ctx.config.guards.length === 0) return { ...base, detail: `no guards declared (${ctx.configLabel})` };+ if (selected.length === 0) return { ...base, detail: `no guard's files touched (${ctx.config.guards.length} declared)` };+ const listed = selected.map(g => `COMMAND: ${g.id}=${JSON.stringify(g.command)} when=${g.when.join(',')}`);+ if (!ctx.allowRepoCommands) {+ return { ...base, status: 'incomplete', code: 'REPO_COMMANDS_NOT_ALLOWED', lines: listed, detail: `${selected.length} guard(s) not run (pass --allow-repo-commands): ${selected.map(g => g.id).join(', ')}`, fix: 'rerun with --allow-repo-commands (what a lane runs before reporting done, and what /ship passes)' };+ }+ const runtime = launchRuntime(ctx.repoRoot, ctx.env);+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-pregate-guards-'));+ const runs = selected.map(g => runGuard(ctx, g, runtime.env, dir));+ const lines = [`runtime: ${runtime.label}`];+ for (const r of runs) {+ lines.push(r.timedOut ? `GUARD: ${r.guard.id} timed out after ${r.guard.timeout_s ?? ctx.timeoutMs / 1000} s (log ${r.log})` : `GUARD: ${r.guard.id} exit=${r.exit} (log ${r.log})`);+ if (r.exit !== 0) lines.push(...r.tail.map(l => ` ${l}`));+ }+ const failed = runs.filter(r => !r.timedOut && r.exit !== 0);+ const timedOut = runs.filter(r => r.timedOut);+ const withRuns = { ...base, lines, inputs: { ...inputs, runtime: runtime.label } };+ const fixOf = (rs: GuardRun[]) => rs.map(r => `${r.guard.id}: ${r.guard.fix ?? `read ${r.log}, fix the failure, rerun gstack-pregate --only guards`}`).join('; ');+ if (failed.length) return { ...withRuns, status: 'fail', code: 'PREGATE_GUARD_FAILED', detail: `${failed.length} guard(s) failed: ${failed.map(r => r.guard.id).join(', ')}${timedOut.length ? `; timed out: ${timedOut.map(r => r.guard.id).join(', ')}` : ''}`, fix: fixOf(failed) };+ if (timedOut.length) return { ...withRuns, status: 'incomplete', code: 'PREGATE_INCOMPLETE', detail: `${timedOut.length} guard(s) timed out: ${timedOut.map(r => r.guard.id).join(', ')}`, fix: 'raise the guard\'s timeout_s or --timeout; a timed-out guard never passes' };+ return { ...withRuns, detail: `${runs.length} guard(s) passed: ${runs.map(r => r.guard.id).join(', ')}` };+}++export const guardsCheck: CheckDef = { id: 'guards', stage: 'preflight', tier: 2, downgradable: false, needsRepoCommands: true, run };diff --git a/lib/pregate/checks/lanes.ts b/lib/pregate/checks/lanes.tsindex e40849516..5d8b13944 100644--- a/lib/pregate/checks/lanes.ts+++ b/lib/pregate/checks/lanes.ts@@ -14,6 +14,8 @@ 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 { launchRuntime } from '../runtime';+import { matchesAny } from '../../ship-policy';import type { CheckDef, CheckResult, PregateContext } from '../types';/** The test command with `{files}`; detected from the repo when the config does not name one. */@@ -47,17 +49,34 @@ export function parseSummary(output: string): RunnerSummary {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 } {+interface LocalRun { exit: number | null; ran: number | null; failed: number | null; log: string; tail: string[]; command: string }++function runOnce(ctx: PregateContext, env: NodeJS.ProcessEnv, runner: string, files: string[], log: string): LocalRun {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 r = spawnSync('bash', ['-c', `set -o pipefail; ${command}`], { cwd: ctx.repoRoot, encoding: 'utf8', timeout: ctx.timeoutMs, maxBuffer: 256 * 1024 * 1024, env: { ...env, CI: env.CI ?? '1' } });const output = `${r.stdout ?? ''}\n${r.stderr ?? ''}`;- fs.writeFileSync(log, `$ ${command}\n${output}`);+ fs.appendFileSync(log, `$ ${command}\n${output}\n`);const summary = parseSummary(output);return { exit: r.status, ...summary, log, tail: output.trim().split('\n').slice(-25), command };}+/**+ * Unit files in one runner process, then each serial-pattern file in its+ * own (a serial file shares process-wide state: a module mock, an env+ * mutation). The first non-zero or timed-out run decides the exit; counts+ * add up only when every run reported a summary.+ */+function runLocal(ctx: PregateContext, env: NodeJS.ProcessEnv, runner: string, files: string[]): LocalRun & { serial: number } {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-pregate-lanes-'));+ const log = path.join(dir, 'lanes.log');+ const serial = files.filter(f => matchesAny(ctx.config.serial_patterns, f));+ const unit = files.filter(f => !serial.includes(f));+ const runs = [...(unit.length ? [unit] : []), ...serial.map(f => [f])].map(group => runOnce(ctx, env, runner, group, log));+ const bad = runs.find(r => r.exit === null) ?? runs.find(r => r.exit !== 0);+ const sum = (k: 'ran' | 'failed') => (runs.some(r => r[k] === null) ? null : runs.reduce((n, r) => n + (r[k] as number), 0));+ return { exit: bad ? bad.exit : 0, ran: sum('ran'), failed: sum('failed'), log, tail: (bad ?? runs[runs.length - 1]!).tail, command: runs.map(r => r.command).join(' && '), serial: serial.length };+}+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 ? ' …' : ''}`);@@ -80,13 +99,14 @@ function run(ctx: PregateContext): CheckResult {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) } };+ const runtime = launchRuntime(ctx.repoRoot, ctx.env);+ const r = runLocal(ctx, runtime.env, runner, sel.localTests);+ const runLines = [...lines, `runtime: ${runtime.label}`, `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), runtime: runtime.label } };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)` : ''}`;+ const detail = `${r.ran ?? 'count unavailable'} tests ran in ${sel.localTests.length} file(s)${r.serial ? ` (${r.serial} serial)` : ''}, exit 0${sel.remote.length ? `; ${sel.remote.length} requires-remote obligation(s)` : ''}`;return { ...withRun, status: sel.remote.length ? 'requires-remote' : 'pass', detail };}diff --git a/lib/pregate/config.ts b/lib/pregate/config.tsindex 36c7373e3..af6dd4bd5 100644--- a/lib/pregate/config.ts+++ b/lib/pregate/config.ts@@ -13,16 +13,27 @@* 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+ * guards `{ id, when: [globs], command, fix?, timeout_s? }`: a repo+ * command that must pass when a touched file matches `when`+ * (manifest checks, CLI goldens); never downgradable+ * serial_patterns globs of test files the lanes check runs one process each+ * (default: every `*.serial.test.*` file)+ * sealed the sealed-output guard's rules (lib/sealed-guard.ts; read by+ * the pre-push hook and `gstack-pregate sealed`, not by `run`)+ * price_file the call-plan data file `gstack-eval-plan price-gate` prices+ * a paid gate from (GSTACK_EVAL_CALLS v1; never executed)*/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 { sealedErrors } from '../sealed-guard';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 const NON_DOWNGRADABLE = ['secrets', 'guards'] as const;+export const DEFAULT_SERIAL_PATTERNS = ['**/*.serial.test.*'];export interface PregateConfig {$schema?: string;@@ -31,13 +42,19 @@ export interface PregateConfig {selection: Record<string, string>;warn: string[];strays: { allow: string[] };+ guards: Guard[];+ serial_patterns: string[];+ price_file: string | null;}-export const DEFAULT_CONFIG: PregateConfig = { runner: null, dependencies: {}, selection: {}, warn: [], strays: { allow: [] } };+export interface Guard { id: string; when: string[]; command: string; fix?: string; timeout_s?: number }+export const DEFAULT_CONFIG: PregateConfig = { runner: null, dependencies: {}, selection: {}, warn: [], strays: { allow: [] }, guards: [], serial_patterns: DEFAULT_SERIAL_PATTERNS, price_file: null };export interface ConfigError { code: ResultCodeName; path: string; message: string }const MAX_LIST = 256;const MAX_COMMAND = 512;-const KEYS = ['runner', 'dependencies', 'selection', 'warn', 'strays'];+const KEYS = ['runner', 'dependencies', 'selection', 'warn', 'strays', 'guards', 'serial_patterns', 'price_file', 'sealed'];+const MAX_GUARDS = 32;+const GUARD_KEYS = ['id', 'when', 'command', 'fix', 'timeout_s'];function globError(g: string): string | null {const why = containedRelative(g);@@ -51,6 +68,28 @@ function commandError(c: unknown): string | null {return null;}+function guardErrors(raw: unknown, errors: ConfigError[]): void {+ const bad = (p: string, message: string) => errors.push({ code: 'PREGATE_CONFIG_INVALID', path: p, message });+ if (!Array.isArray(raw)) { bad('guards', 'must be an array of { id, when, command, fix?, timeout_s? }'); return; }+ if (raw.length > MAX_GUARDS) bad('guards', `more than ${MAX_GUARDS} guards`);+ const seen = new Set<string>();+ raw.forEach((g, i) => {+ const at = `guards[${i}]`;+ if (!g || typeof g !== 'object' || Array.isArray(g)) { bad(at, 'must be an object { id, when, command, fix?, timeout_s? }'); return; }+ const o = g as Record<string, unknown>;+ for (const k of Object.keys(o)) if (!GUARD_KEYS.includes(k)) bad(`${at}.${k}`, `unknown key; valid keys: ${GUARD_KEYS.join(', ')}`);+ if (typeof o.id !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(o.id)) bad(`${at}.id`, 'must match [A-Za-z0-9][A-Za-z0-9._-]{0,63}');+ else if (seen.has(o.id)) bad(`${at}.id`, `duplicate guard id ${o.id}`);+ else seen.add(o.id);+ if (!Array.isArray(o.when) || o.when.length === 0 || o.when.some(w => typeof w !== 'string')) bad(`${at}.when`, 'must be a non-empty array of globs');+ else (o.when as string[]).forEach((w, j) => { const why = globError(w); if (why) bad(`${at}.when[${j}]`, `${JSON.stringify(w)} ${why}`); });+ const cmd = commandError(o.command);+ if (cmd) bad(`${at}.command`, cmd);+ if ('fix' in o && commandError(o.fix)) bad(`${at}.fix`, commandError(o.fix)!);+ if ('timeout_s' in o && (!Number.isInteger(o.timeout_s) || (o.timeout_s as number) < 1 || (o.timeout_s as number) > 3600)) bad(`${at}.timeout_s`, 'must be an integer number of seconds from 1 to 3600');+ });+}+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' }];@@ -61,6 +100,17 @@ export function validateConfig(raw: unknown, knownChecks: readonly string[] = []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 ('price_file' in obj && obj.price_file !== null) {+ const why = typeof obj.price_file === 'string' ? containedRelative(obj.price_file) : 'must be a repo-relative path or null';+ if (why) errors.push({ code: 'PREGATE_CONFIG_INVALID', path: 'price_file', message: why });+ }+ if ('guards' in obj) guardErrors(obj.guards, errors);+ if ('sealed' in obj) for (const e of sealedErrors(obj.sealed)) errors.push({ code: 'PREGATE_CONFIG_INVALID', path: e.path, message: e.message });+ if ('serial_patterns' in obj) {+ const list = obj.serial_patterns;+ if (!Array.isArray(list) || list.some(g => typeof g !== 'string')) errors.push({ code: 'PREGATE_CONFIG_INVALID', path: 'serial_patterns', message: 'must be an array of globs' });+ else (list as string[]).forEach((g, i) => { const why = globError(g); if (why) errors.push({ code: 'PREGATE_CONFIG_INVALID', path: `serial_patterns[${i}]`, message: `${JSON.stringify(g)} ${why}` }); });+ }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' });@@ -112,7 +162,7 @@ export function parseConfig(text: string, knownChecks: readonly string[] = []):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: [] };+ return { config: { $schema: o.$schema, runner: o.runner ?? null, dependencies: o.dependencies ?? {}, selection: o.selection ?? {}, warn: o.warn ?? [], strays: { allow: o.strays?.allow ?? [] }, guards: o.guards ?? [], serial_patterns: o.serial_patterns ?? DEFAULT_SERIAL_PATTERNS, price_file: o.price_file ?? null }, errors: [] };}export type ConfigLoad = { config: PregateConfig; errors: ConfigError[]; present: boolean; label: string; kind: 'base' | 'head' | 'none' } | { unavailable: true; base: string; detail: string };@@ -160,5 +210,9 @@ export function explainConfig(): string {'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',+ 'guards: [{ id, when: [globs], command, fix?, timeout_s? }]: each guard whose globs match a touched file runs in its own process (--allow-repo-commands); a failure fails pregate with the guard id and fix; never downgradable',+ `serial_patterns: test-file globs the lanes check runs one process per file, apart from the unit files (default ${DEFAULT_SERIAL_PATTERNS.join(', ')})`,+ 'sealed: { paths, transcripts, answer_markers, seed_patterns, local_paths, visibility }: sealed or eval output the pre-push hook and `gstack-pregate sealed` refuse to publish to a public destination (docs/pregate.md#sealed)',+ 'price_file: repo-relative path of the GSTACK_EVAL_CALLS v1 call-plan file `gstack-eval-plan price-gate` prices a paid gate from; never executed (docs/eval-calls.md)',].join('\n') + '\n';}diff --git a/lib/pregate/index.ts b/lib/pregate/index.tsindex 4bb7cc365..f54bd0353 100644--- a/lib/pregate/index.ts+++ b/lib/pregate/index.ts@@ -6,13 +6,15 @@* 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.+ * tool is `incomplete`, never `pass`. Tier 2 checks register here as they+ * land: `guards` (field wave CD1); ratchets, lint, links, hermetic, patches+ * and integrator later.*/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 { guardsCheck } from './checks/guards';import { lanesCheck } from './checks/lanes';import { literalsCheck } from './checks/literals';import { regenCheck } from './checks/regen';@@ -22,10 +24,10 @@ 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 CHECKS: readonly CheckDef[] = [regenCheck, secretsCheck, straysCheck, literalsCheck, guardsCheck, 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 const PREGATE_TIER2 = ['ratchets', 'lint', 'links', 'hermetic', 'patches', 'integrator'] as const;export interface RunOptions { stage: Stage | 'all'; only?: string[]; run?: string }diff --git a/lib/pregate/regate.ts b/lib/pregate/regate.tsnew file mode 100644index 000000000..83b160b63--- /dev/null+++ b/lib/pregate/regate.ts@@ -0,0 +1,134 @@+/**+ * regate — does a gated head's evidence still cover HEAD (field wave CD3),+ * behind `gstack-pregate regate --against <head>`. Reuse is derived only from+ * a tree receipt evaluated now (lib/tree-receipt.ts) with a valid evidence+ * bundle produced on the gated tree, the current predecessor head and the+ * current execution identity; a stored receipt is never read. Migration+ * numbers the branch adds are compared with the base branch and every open+ * PR; any lookup that cannot finish is `unknown`, which blocks `not-needed`.+ */+import { spawnSync } from 'node:child_process';+import * as path from 'node:path';+import type { ResultCodeName } from '../result-codes';+import type { ShipPolicy } from '../ship-policy';+import { buildReceipt, type GateVerdict, type ReceiptOptions, type TreeReceipt } from '../tree-receipt';++export type Gh = (args: string[]) => { ok: boolean; out: string; err?: string };+export interface MigrationCollision { id: string; file: string; other: string; where: string }+export interface MigrationReport { status: 'none' | 'collision' | 'unknown'; collisions: MigrationCollision[]; detail: string }+export interface RegateReport {+ against: string; receipt: TreeReceipt | null; error: { code: ResultCodeName; message: string } | null;+ lanes: GateVerdict[]; migration: MigrationReport; verdict: 'needed' | 'not-needed'; reasons: string[];+}++const PR_LIST_LIMIT = 1000;+const GRAPHQL_FILES_CAP = 100;+const REST_FILES_CAP = 3000;++function git(cwd: string, args: string[]): string | null {+ const r = spawnSync('git', args, { cwd, encoding: 'utf8', timeout: 60_000, maxBuffer: 64 * 1024 * 1024 });+ return r.status === 0 ? (r.stdout ?? '').replace(/\n$/, '') : null;+}+const lines = (s: string | null): string[] => (s ?? '').split('\n').filter(Boolean);+export const defaultGh = (cwd: string): Gh => (args) => {+ const r = spawnSync('gh', args, { cwd, encoding: 'utf8', timeout: 120_000, maxBuffer: 64 * 1024 * 1024 });+ return { ok: r.status === 0, out: r.stdout ?? '', err: (r.stderr ?? r.error?.message ?? '').trim() };+};++/** Migration numbers HEAD adds under `migrations.dir`, checked against the base tree and every other open PR. */+export function migrationReport(o: { repoRoot: string; head: string; baseRef: string; migrations: ShipPolicy['migrations']; gh: Gh; self?: string | null }): MigrationReport {+ if (!o.migrations) return { status: 'none', collisions: [], detail: 'no migrations key in the ship policy' };+ const dir = o.migrations.dir.replace(/\/+$/, '');+ const re = new RegExp(o.migrations.id);+ const idOf = (file: string): string | null => {+ if (!file.startsWith(dir + '/')) return null;+ const m = re.exec(path.posix.basename(file));+ return m?.[1] ? String(Number.isNaN(Number(m[1])) ? m[1] : Number(m[1])) : null;+ };+ const mergeBase = git(o.repoRoot, ['merge-base', o.baseRef, o.head]);+ if (!mergeBase) return { status: 'unknown', collisions: [], detail: `no merge base between ${o.baseRef} and ${o.head}` };+ const ours = new Map<string, string>();+ for (const f of lines(git(o.repoRoot, ['diff', '--name-only', '--no-renames', '--diff-filter=A', mergeBase, o.head, '--', dir]))) {+ const id = idOf(f);+ if (id) ours.set(id, f);+ }+ if (ours.size === 0) return { status: 'none', collisions: [], detail: `this branch adds no migration under ${dir}/` };+ const collisions: MigrationCollision[] = [];+ const check = (file: string, where: string) => {+ const id = idOf(file);+ const mine = id ? ours.get(id) : undefined;+ if (id && mine && mine !== file && !collisions.some(c => c.where === where && c.other === file)) collisions.push({ id, file: mine, other: file, where });+ };+ const baseFiles = git(o.repoRoot, ['ls-tree', '-r', '--name-only', o.baseRef, '--', dir + '/']);+ if (baseFiles === null) return { status: 'unknown', collisions, detail: `cannot list ${dir}/ on ${o.baseRef}` };+ for (const f of lines(baseFiles)) check(f, o.baseRef);++ const listed = o.gh(['pr', 'list', '--state', 'open', '--limit', String(PR_LIST_LIMIT), '--json', 'number,headRefOid,files']);+ if (!listed.ok) return { status: 'unknown', collisions, detail: `gh pr list failed${listed.err ? `: ${listed.err.split('\n')[0]}` : ''}` };+ let prs: Array<{ number: number; headRefOid?: string; files?: Array<{ path: string }> | null }>;+ try { prs = JSON.parse(listed.out); if (!Array.isArray(prs)) throw new Error('not a list'); }+ catch (e: any) { return { status: 'unknown', collisions, detail: `gh pr list output unreadable: ${e.message}` }; }+ if (prs.length >= PR_LIST_LIMIT) return { status: 'unknown', collisions, detail: `${prs.length} open PRs listed, the list may be truncated at ${PR_LIST_LIMIT}` };+ const headSha = git(o.repoRoot, ['rev-parse', o.head]);+ let checked = 0;+ for (const pr of prs) {+ if (pr.headRefOid === headSha || (o.self && String(pr.number) === String(o.self))) continue;+ let files = (pr.files ?? []).map(f => f.path);+ if (files.length >= GRAPHQL_FILES_CAP) {+ const all = o.gh(['api', '--paginate', `repos/{owner}/{repo}/pulls/${pr.number}/files?per_page=100`, '--jq', '.[].filename']);+ if (!all.ok) return { status: 'unknown', collisions, detail: `PR #${pr.number} lists ${files.length} files (truncated) and its full file list could not be fetched` };+ files = lines(all.out);+ if (files.length >= REST_FILES_CAP) return { status: 'unknown', collisions, detail: `PR #${pr.number} changes ${files.length}+ files, past what GitHub lists` };+ }+ for (const f of files) check(f, `PR #${pr.number}`);+ checked += 1;+ }+ return collisions.length+ ? { status: 'collision', collisions, detail: `${collisions.length} collision(s)` }+ : { status: 'none', collisions, detail: `${[...ours.keys()].join(',')} checked against ${o.baseRef} and ${checked} open PR(s)` };+}++/** The regate verdict: `not-needed` only when every required lane's evidence is reusable as is and no migration lookup is open. */+export function evaluateRegate(o: ReceiptOptions & { baseRef: string; require: string[]; self?: string | null; gh: Gh }): RegateReport {+ const built = buildReceipt(o);+ const receipt = 'error' in built ? null : built;+ const error = 'error' in built ? { code: built.code, message: built.error } : null;+ const migration = migrationReport({ repoRoot: o.repoRoot, head: o.current ?? 'HEAD', baseRef: o.baseRef, migrations: o.policy.migrations, gh: o.gh, self: o.self });+ const reasons: string[] = [];+ let lanes: GateVerdict[] = [];+ if (error) reasons.push(error.message);+ if (receipt) {+ if (receipt.tree === 'changed') reasons.push(`not stamp-only: ${receipt.residual.join(', ')}`);+ const p = receipt.predecessor;+ if (p?.moved) reasons.push(`PREDECESSOR MOVED ${p.recorded_head!.slice(0, 12)} -> ${p.current_head!.slice(0, 12)}`);+ else if (p?.recorded_head && !p.current_head) reasons.push(`predecessor ${p.pr ? `#${p.pr}` : 'head'} current head unknown`);+ if (!receipt.identity.gated) reasons.push(`no gate evidence for ${receipt.gated_head.slice(0, 12)} (${receipt.identity.source})`);+ else {+ const global = reasons.join('; ');+ lanes = receipt.gates.map(g => g.verdict === 'reusable' && global ? { ...g, verdict: 'not-reusable' as const, reason: global } : g);+ for (const label of o.require) if (!lanes.some(g => g.label === label)) lanes.push({ label, verdict: 'not-reusable', reason: 'required lane has no record in the bundle' });+ if (lanes.length === 0) reasons.push('the bundle lists no lanes');+ for (const g of lanes) if (g.verdict !== 'reusable' && g.reason !== global) reasons.push(`${g.label} ${g.verdict === 'rerun' ? 'reruns' : 'not reusable'} (${g.reason})`);+ }+ }+ if (migration.status === 'collision') reasons.push(`migration collision: ${migration.collisions.map(c => c.id).join(', ')}`);+ if (migration.status === 'unknown') reasons.push(`migration lookup unknown (${migration.detail})`);+ return { against: o.gated, receipt, error, lanes, migration, verdict: reasons.length ? 'needed' : 'not-needed', reasons };+}++export function renderRegate(r: RegateReport): string {+ const out: string[] = [];+ const rc = r.receipt;+ if (rc) {+ out.push(`against: ${rc.gated_head} (tree ${rc.gated_tree.slice(0, 12)})`, `head: ${rc.current_head} (tree ${rc.current_tree.slice(0, 12)})`, `version: ${rc.old_version ?? '-'} -> ${rc.new_version ?? '-'}`, `policy: ${rc.policy}`, `evidence: ${rc.identity.source}`);+ for (const f of rc.files) out.push(f.verdict === 'stamp' ? ` stamp ${f.path} (${f.rule})` : ` changed ${f.path}${f.line ? `:${f.line}` : ''} (${f.rule}: ${f.residual})`);+ out.push(`STAMP_ONLY: ${rc.tree === 'changed' ? 'no' : 'yes'} files=${rc.files.length}${rc.residual.length ? ` changed=${rc.residual.length}` : ''}`);+ }+ for (const g of r.lanes) out.push(`LANE: ${g.label} ${g.verdict} (${g.reason})`);+ const m = r.migration;+ out.push(m.status === 'collision'+ ? m.collisions.map(c => `MIGRATION_COLLISION: ${c.id} ${c.file} vs ${c.where} ${c.other}`).join('\n')+ : `MIGRATION_COLLISION: ${m.status} (${m.detail})`);+ out.push(r.verdict === 'not-needed' ? 'REGATE: not-needed' : `REGATE: needed (${r.reasons.join('; ')})`);+ return out.join('\n') + '\n';+}diff --git a/lib/pregate/runtime.ts b/lib/pregate/runtime.tsnew file mode 100644index 000000000..491bf7e56--- /dev/null+++ b/lib/pregate/runtime.ts@@ -0,0 +1,38 @@+/**+ * pregate/runtime — the Bun a repo command runs under (field wave CD1, the+ * TypeScript side of `gstack_bun_launch_dir` in bin/gstack-bun-version.sh).+ * On a Capy cloud host the image's Bun is first on PATH and older than both+ * gstack's minimum and most project pins, while the verified Bun the+ * installer left in `$BUN_INSTALL/bin` or `~/.bun/bin` is off PATH; the same+ * tree then passes or fails its lanes depending on the shell. The launch dir+ * is the first of those two holding a Bun that satisfies gstack's own+ * `engines.bun` and the project's `engines.bun`; when there is one, the+ * lanes runner and every guard run with it first on PATH.+ */+import { spawnSync } from 'node:child_process';+import * as fs from 'node:fs';+import * as path from 'node:path';+import { satisfies } from '../runtime-pins';++const GSTACK_PACKAGE = path.resolve(import.meta.dir, '..', '..', 'package.json');++function enginesBun(file: string): string | null {+ try { const v = JSON.parse(fs.readFileSync(file, 'utf8'))?.engines?.bun; return typeof v === 'string' && v.trim() ? v.trim() : null; } catch { return null; }+}++export interface LaunchRuntime { dir: string | null; version: string | null; env: NodeJS.ProcessEnv; label: string }++/** The launch dir and the env with it first on PATH; the env is unchanged when no candidate qualifies. */+export function launchRuntime(repoRoot: string, env: NodeJS.ProcessEnv): LaunchRuntime {+ const pins = [enginesBun(GSTACK_PACKAGE), enginesBun(path.join(repoRoot, 'package.json'))].filter((p): p is string => !!p);+ const candidates = [env.BUN_INSTALL ? path.join(env.BUN_INSTALL, 'bin') : null, env.HOME ? path.join(env.HOME, '.bun', 'bin') : null].filter((d): d is string => !!d);+ for (const dir of [...new Set(candidates)]) {+ const bun = path.join(dir, 'bun');+ try { fs.accessSync(bun, fs.constants.X_OK); } catch { continue; }+ const r = spawnSync(bun, ['--version'], { encoding: 'utf8', timeout: 15_000, env });+ const version = r.status === 0 ? (r.stdout ?? '').trim() : '';+ if (!version || pins.some(pin => satisfies(version, pin) !== true)) continue;+ return { dir, version, env: { ...env, PATH: [dir, env.PATH ?? ''].filter(Boolean).join(path.delimiter) }, label: `bun ${version} from ${dir}` };+ }+ return { dir: null, version: null, env, label: 'PATH (no verified Bun in $BUN_INSTALL/bin or ~/.bun/bin)' };+}diff --git a/lib/pricing.ts b/lib/pricing.tsindex 3bf6a0bb2..c3d547399 100644--- a/lib/pricing.ts+++ b/lib/pricing.ts@@ -20,7 +20,8 @@* start a priced run on such a model (bin/gstack-eval-plan dry-run).* - Anthropic: https://www.anthropic.com/pricing#api* - OpenAI: https://openai.com/api/pricing/- * - Google AI: https://ai.google.dev/pricing+ * - Google AI: https://ai.google.dev/gemini-api/docs/pricing+ * - Voyage AI (embeddings): https://docs.voyageai.com/docs/pricing*/export interface ModelPricing {@@ -45,7 +46,10 @@ export const PRICING: Record<string, ModelPricing> = {'claude-fable-5-1': { input_per_mtok: 10.00, output_per_mtok: 50.00, cached_input_per_mtok: 0.25, as_of: '2026-09' },// https://platform.claude.com/docs/en/models/opus-5-5/overview#pricing (list prices effective 2026-10-07)'claude-opus-5-5': { input_per_mtok: 4.00, output_per_mtok: 20.00, cached_input_per_mtok: 0.20, as_of: '2026-10' },- 'claude-opus-4-7': { input_per_mtok: 15.00, output_per_mtok: 75.00, as_of: '2026-04' },+ // https://platform.claude.com/docs/en/about-claude/pricing (fetched 2026-10-12)+ 'claude-opus-4-7': { input_per_mtok: 5.00, output_per_mtok: 25.00, cached_input_per_mtok: 0.50, as_of: '2026-10' },+ // https://platform.claude.com/docs/en/about-claude/pricing (fetched 2026-10-12)+ 'claude-sonnet-5-5': { input_per_mtok: 2.00, output_per_mtok: 10.00, cached_input_per_mtok: 0.10, as_of: '2026-10' },'claude-sonnet-4-6': { input_per_mtok: 3.00, output_per_mtok: 15.00, as_of: '2026-04' },'claude-haiku-4-5': { input_per_mtok: 1.00, output_per_mtok: 5.00, as_of: '2026-04' },@@ -60,14 +64,46 @@ export const PRICING: Record<string, ModelPricing> = {'o4-mini': { input_per_mtok: 1.10, output_per_mtok: 4.40, as_of: '2026-04' },+ // https://ai.google.dev/gemini-api/docs/pricing (fetched 2026-10-12; standard tier through 2026-12-31,+ // the page lists $1.50 / $7.50 / $0.15 cached starting 2027-01-01)+ 'gemini-3.8-flash': { input_per_mtok: 0.75, output_per_mtok: 3.75, cached_input_per_mtok: 0.075, as_of: '2026-10' },+ // https://ai.google.dev/gemini-api/docs/pricing (fetched 2026-10-12; same schedule as gemini-3.8-flash)+ 'gemini-3.6-flash': { input_per_mtok: 0.75, output_per_mtok: 3.75, cached_input_per_mtok: 0.075, as_of: '2026-10' },+ // https://ai.google.dev/gemini-api/docs/pricing (fetched 2026-10-12; prompts <= 200k tokens, the long-context rate is excluded)+ 'gemini-3.1-pro-preview': { input_per_mtok: 2.00, output_per_mtok: 12.00, cached_input_per_mtok: 0.20, as_of: '2026-10' },'gemini-2.5-pro': { input_per_mtok: 1.25, output_per_mtok: 5.00, as_of: '2026-04' },'gemini-2.5-flash': { input_per_mtok: 0.30, output_per_mtok: 1.20, as_of: '2026-04' },};-/** A provider-prefixed id (`openai/gpt-6-astra`, `anthropic/claude-fable-5-1`) resolves to its table row. */+/**+ * Embedding models bill input tokens only (output_per_mtok 0), so they live+ * beside PRICING rather than in it: eval arms never resolve to an embedding+ * model, but a call plan (docs/eval-calls.md) prices gbrain's embedding calls.+ */+export const EMBEDDING_PRICING: Record<string, ModelPricing> = {+ // https://docs.voyageai.com/docs/pricing (fetched 2026-10-12; list price after the free-token allowance)+ 'voyage-4': { input_per_mtok: 0.06, output_per_mtok: 0, as_of: '2026-10' },+ 'voyage-4-large': { input_per_mtok: 0.12, output_per_mtok: 0, as_of: '2026-10' },+ 'voyage-4-lite': { input_per_mtok: 0.02, output_per_mtok: 0, as_of: '2026-10' },+ 'voyage-code-4': { input_per_mtok: 0.12, output_per_mtok: 0, as_of: '2026-10' },+ 'voyage-code-3': { input_per_mtok: 0.18, output_per_mtok: 0, as_of: '2026-10' },+ 'voyage-3-large': { input_per_mtok: 0.18, output_per_mtok: 0, as_of: '2026-10' },+ 'voyage-multimodal-3': { input_per_mtok: 0.12, output_per_mtok: 0, as_of: '2026-10' }, // text tokens; pixels excluded+ // https://developers.openai.com/api/docs/pricing (fetched 2026-10-12)+ 'text-embedding-3-large': { input_per_mtok: 0.13, output_per_mtok: 0, as_of: '2026-10' },+ 'text-embedding-3-small': { input_per_mtok: 0.02, output_per_mtok: 0, as_of: '2026-10' },+ // https://ai.google.dev/gemini-api/docs/pricing (fetched 2026-10-12; text input, standard tier)+ 'gemini-embedding-2': { input_per_mtok: 0.20, output_per_mtok: 0, as_of: '2026-10' },+};++/**+ * A provider-prefixed id (`openai/gpt-6-astra`, `anthropic/claude-fable-5-1`,+ * or gbrain's `voyage:voyage-4`) resolves to its table row.+ */export function pricingRow(model: string | undefined): ModelPricing | undefined {if (!model) return undefined;- return PRICING[model] ?? PRICING[model.replace(/^[a-z-]+\//, '')];+ const bare = model.replace(/^[a-z-]+[/:]/, '');+ return PRICING[model] ?? PRICING[bare] ?? EMBEDDING_PRICING[model] ?? EMBEDDING_PRICING[bare];}export function hasPricing(model: string | undefined): boolean {diff --git a/lib/restamp.ts b/lib/restamp.tsindex 4f03bf22c..673653f40 100644--- a/lib/restamp.ts+++ b/lib/restamp.ts@@ -6,7 +6,10 @@* (bin/gstack-version-bump write, composed, never grown), the policy's* release_tool under its contract (enumerated allowed outputs, pre/post* images), the CHANGELOG re-heading (lib/changelog-check.ts), the exact- * `(was X)` / `since: X` / `vX` rewrites inside `stamp_paths`. The branch is+ * `(was X)` / `since: X` / `vX` rewrites inside `stamp_paths`. A policy+ * `restamp_command` (the repo's own restamp) runs first instead of the+ * version writer, on a clean checkout of HEAD (the caller's tree must be+ * clean), under the same output confinement. The branch is* written only after every stage validated, file by file against the* fingerprinted preimage, with every write journaled in* .gstack/tmp/restamp-journal.json so a failure after any stage rolls back@@ -24,7 +27,7 @@ import * as path from 'node:path';import { checkChangelog, mergeChangelogs, parseChangelog, reheadChangelog } from './changelog-check';import { type ResultCodeName } from './result-codes';import {- SHIP_POLICY_PATH, assertInsideRoot, declaredCommands, isUnavailable, loadPolicyFromBase, loadPolicyFromHead, matchesAny,+ SHIP_POLICY_PATH, VERSION_SLOT, assertInsideRoot, declaredCommands, isUnavailable, loadPolicyFromBase, loadPolicyFromHead, matchesAny,type LoadedPolicy, type QueueMode, type ShipPolicy,} from './ship-policy';import { bumpVersion, cmpVersion, extractVersion, fmtVersion, parseVersion, versionWidth, type Bump } from './version-source';@@ -34,7 +37,7 @@ export const GATE_AHEAD_REL = '.gstack/tmp/gate-ahead.json';const BIN_DIR = path.resolve(import.meta.dir, '..', 'bin');const NPM_LOCKFILES = ['package-lock.json', 'npm-shrinkwrap.json'];-export type StageName = 'version' | 'release_tool' | 'changelog' | 'stamp_paths' | 'mirror' | 'apply';+export type StageName = 'restamp_command' | 'version' | 'release_tool' | 'changelog' | 'stamp_paths' | 'mirror' | 'apply';export interface JournalWrite { path: string; pre_sha256: string | null; post_sha256: string | null; applied: boolean }export interface StageRecord { name: StageName; status: 'pending' | 'done' | 'skipped' | 'failed'; detail?: string; writes?: JournalWrite[] }export interface Journal {@@ -197,10 +200,10 @@ function allowedOutput(plan: Plan, root: string, rel: string): boolean {const p = plan.policy;if (versionFiles(root, plan.versionRel).includes(rel)) return true;if (p.changelog && rel === p.changelog) return true;- return matchesAny(p.stamp_paths, rel) || matchesAny(p.release_outputs, rel);+ return matchesAny(p.stamp_paths, rel) || matchesAny(p.stamp_files, rel) || matchesAny(p.release_outputs, rel);}-interface Hunk { removed: string[]; added: string[] }+interface Hunk { removed: string[]; added: string[]; at: number }export interface FileDiff { path: string; binary: boolean; hunks: Hunk[]; status: 'M' | 'A' | 'D' | 'R' }/** Parse `git diff --unified=0` into per-file hunks of removed/added lines (shared with lib/tree-receipt.ts). */@@ -219,7 +222,7 @@ export function parseUnifiedDiff(text: string): FileDiff[] {else if (line.startsWith('deleted file mode')) cur.status = 'D';else if (line.startsWith('rename to ')) cur.status = 'R';else if (line.startsWith('Binary files')) cur.binary = true;- else if (line.startsWith('@@')) { hunk = { removed: [], added: [] }; cur.hunks.push(hunk); }+ else if (line.startsWith('@@')) { hunk = { removed: [], added: [], at: Number(/^@@ -\d+(?:,\d+)? \+(\d+)/.exec(line)?.[1] ?? 0) }; cur.hunks.push(hunk); }else if (hunk && line.startsWith('-') && !line.startsWith('---')) hunk.removed.push(line.slice(1));else if (hunk && line.startsWith('+') && !line.startsWith('+++')) hunk.added.push(line.slice(1));}@@ -272,13 +275,19 @@ export function forkVersion(repoRoot: string, baseRef: string, fallback: string)return 'version' in v ? v.version : fallback;}-/** Exact `(was X)`, `since: X`, `vX` rewrites; anything else in the file stays. */-export function rewriteStamps(text: string, oldVersion: string, newVersion: string): { text: string; count: number } {- const esc = oldVersion.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');+/**+ * Exact `(was X)`, `since: X`, `vX` rewrites plus the policy's literal+ * `stamp_patterns` templates (one `{version}` slot, matched at a version+ * boundary); anything else in the file stays.+ */+export function rewriteStamps(text: string, oldVersion: string, newVersion: string, templates: readonly string[] = []): { text: string; count: number } {+ const esc = (t: string) => t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');+ const v = esc(oldVersion);const patterns: Array<[RegExp, string]> = [- [new RegExp(`\\(was ${esc}\\)`, 'g'), `(was ${newVersion})`],- [new RegExp(`(since:\\s*)${esc}(?![0-9.])`, 'g'), `$1${newVersion}`],- [new RegExp(`(?<![A-Za-z0-9.])v${esc}(?![0-9.])`, 'g'), `v${newVersion}`],+ [new RegExp(`\\(was ${v}\\)`, 'g'), `(was ${newVersion})`],+ [new RegExp(`(since:\\s*)${v}(?![0-9.])`, 'g'), `$1${newVersion}`],+ [new RegExp(`(?<![A-Za-z0-9.])v${v}(?![0-9.])`, 'g'), `v${newVersion}`],+ ...templates.map(t => { const [pre, post] = t.split(VERSION_SLOT) as [string, string]; return [new RegExp(`${esc(pre)}(?<![0-9.])${v}(?![0-9.])${esc(post)}`, 'g'), `${pre}${newVersion}${post}`.replace(/\$/g, '$$$$')] as [RegExp, string]; }),];let count = 0;let out = text;@@ -304,16 +313,41 @@ function linkIgnoredDeps(repoRoot: string, staging: string): void {try { fs.symlinkSync(nm, path.join(staging, 'node_modules'), 'dir'); } catch {}}+/**+ * The repo's own restamp (`restamp_command`), first in the staging worktree:+ * the target version as `$1` and in GSTACK_RESTAMP_VERSION. Whatever it+ * stages or commits there is folded back into worktree edits against the+ * seeded tree; its outputs are confined like release_tool's, and the+ * version file must hold the target version. Any failure writes nothing.+ */+function runRestampCommand(command: string, plan: Plan, staging: string, env: NodeJS.ProcessEnv, before: Set<string>, s: StageRecord): void {+ const seeded = git(staging, ['write-tree']).out;+ const r = spawnSync('sh', ['-c', `${command} "$1"`, 'sh', plan.newVersion], { cwd: staging, encoding: 'utf8', timeout: 600_000, env: { ...env, GSTACK_RESTAMP_VERSION: plan.newVersion } });+ git(staging, ['read-tree', seeded]);+ if (r.status !== 0) { s.status = 'failed'; s.detail = `${r.stderr ?? ''}${r.stdout ?? ''}`.trim().slice(0, 300); throw new Refusal('RESTAMP_RELEASE_TOOL_FAILED', `restamp_command exited ${r.status}: ${s.detail}; nothing written to the branch`); }+ const outside = changedPaths(staging).filter(p => !before.has(p) && !allowedOutput(plan, staging, p));+ if (outside.length) { s.status = 'failed'; s.detail = outside.join(', '); throw new Refusal('RESTAMP_OUTPUT_OUTSIDE_ALLOWED', `restamp_command wrote outside the allowed set: ${outside.join(', ')}; nothing written to the branch`); }+ const file = path.join(staging, plan.versionRel);+ const got = fs.existsSync(file) ? extractVersion(fs.readFileSync(file, 'utf8'), plan.versionRel) : '';+ if (got !== plan.newVersion) { s.status = 'failed'; s.detail = `${plan.versionRel}=${got || '(missing)'}`; throw new Refusal('RESTAMP_VERSION_SOURCE', `restamp_command left ${plan.versionRel} at ${got || '(missing)'}, expected ${plan.newVersion}; nothing written`); }+ s.status = 'done'; s.detail = `${command} ${plan.newVersion}`;+}+function runStages(o: RestampOptions, plan: Plan, staging: string, since: string, stages: StageRecord[]): void {const stage = (name: StageName): StageRecord => { const s: StageRecord = { name, status: 'pending' }; stages.push(s); return s; };const injected = (name: string) => { if (o.failAfter === name) throw new Error(`injected failure after ${name}`); };const env = { ...(o.env ?? process.env), GSTACK_RESTAMP_STAGING: '1' };const before = new Set(changedPaths(staging));+ const command = plan.policy.restamp_command;+ if (command) runRestampCommand(command, plan, staging, env, before, stage('restamp_command'));const v = stage('version');- const w = spawnSync('bun', [path.join(BIN_DIR, 'gstack-version-bump'), 'write', '--version', plan.newVersion], { cwd: staging, encoding: 'utf8', timeout: 120_000, env });- if (w.status !== 0) { v.status = 'failed'; v.detail = (w.stderr ?? '').trim().slice(0, 300); throw new Refusal('RESTAMP_VERSION_SOURCE', `gstack-version-bump write failed: ${v.detail}; nothing written`); }- v.status = 'done'; v.detail = `wrote ${plan.newVersion}`;+ if (command) { v.status = 'skipped'; v.detail = 'restamp_command owns the version'; }+ else {+ const w = spawnSync('bun', [path.join(BIN_DIR, 'gstack-version-bump'), 'write', '--version', plan.newVersion], { cwd: staging, encoding: 'utf8', timeout: 120_000, env });+ if (w.status !== 0) { v.status = 'failed'; v.detail = (w.stderr ?? '').trim().slice(0, 300); throw new Refusal('RESTAMP_VERSION_SOURCE', `gstack-version-bump write failed: ${v.detail}; nothing written`); }+ v.status = 'done'; v.detail = `wrote ${plan.newVersion}`;+ }injected('version');const rt = stage('release_tool');@@ -342,9 +376,11 @@ function runStages(o: RestampOptions, plan: Plan, staging: string, since: stringinjected('changelog');const sp = stage('stamp_paths');- if (plan.policy.stamp_paths.length === 0) { sp.status = 'skipped'; sp.detail = 'no stamp_paths in policy'; }+ const stampGlobs = [...plan.policy.stamp_paths, ...plan.policy.stamp_files];+ const templates = plan.policy.stamp_patterns;+ if (stampGlobs.length === 0) { sp.status = 'skipped'; sp.detail = 'no stamp_paths in policy'; }else {- const files = git(staging, ['ls-files', '-z']).out.split('\0').filter(f => f && matchesAny(plan.policy.stamp_paths, f));+ const files = git(staging, ['ls-files', '-z']).out.split('\0').filter(f => f && matchesAny(stampGlobs, f));for (const rel of files) {const why = assertInsideRoot(staging, rel);if (why) throw new Refusal('POLICY_CONTAINMENT', `${why}; nothing written`);@@ -362,8 +398,8 @@ function runStages(o: RestampOptions, plan: Plan, staging: string, since: stringlet count = 0;const out = fs.readFileSync(abs, 'utf8').split('\n').map(line => {let text = line;- for (const old of explicit) { const r = rewriteStamps(text, old, plan.newVersion); text = r.text; count += r.count; }- if (own?.has(line)) for (const old of tentative) { const r = rewriteStamps(text, old, plan.newVersion); text = r.text; count += r.count; }+ for (const old of explicit) { const r = rewriteStamps(text, old, plan.newVersion, templates); text = r.text; count += r.count; }+ if (own?.has(line)) for (const old of tentative) { const r = rewriteStamps(text, old, plan.newVersion, templates); text = r.text; count += r.count; }return text;}).join('\n');if (count) { fs.writeFileSync(abs, out); touched += 1; total += count; }@@ -468,6 +504,10 @@ export function restamp(o: RestampOptions): RestampResult {}if (o.after) return gateAhead(o, plan, stages, common);+ if (plan.policy.restamp_command) {+ const dirty = git(o.repoRoot, ['status', '--porcelain', '--untracked-files=all']).out.split('\n').filter(Boolean).map(l => l.slice(3));+ if (dirty.length) throw new Refusal('RESTAMP_CONFLICT', `restamp_command needs a clean HEAD, index and worktree (it runs on a clean checkout of HEAD); commit or remove: ${dirty.slice(0, 10).join(', ')}${dirty.length > 10 ? ' …' : ''}; nothing written`);+ }const wt = spawnSync(path.join(BIN_DIR, 'gstack-wtree'), [], { cwd: o.repoRoot, encoding: 'utf8', timeout: 60_000 });const wtree = (wt.stdout ?? '').trim();diff --git a/lib/result-codes.ts b/lib/result-codes.tsindex 0ae353e76..16bcf8001 100644--- a/lib/result-codes.ts+++ b/lib/result-codes.ts@@ -466,6 +466,36 @@ export const RESULT_CODES = {summary: 'a `draft direction stands until the owner decides` line names a decision that is still pending',fix: 'answer the gate (`gstack-autoplan answer`) before closing; the close rewrites only decided lines',},+ PREGATE_GUARD_FAILED: {+ anchor: 'pregate-guard-failed',+ summary: 'a repo guard from .gstack/pregate.json whose files the branch touched exited non-zero',+ fix: 'run the guard command printed in the table, apply the guard\'s fix line, commit, then rerun `gstack-pregate run --allow-repo-commands`',+ },+ MIGRATION_COLLISION: {+ anchor: 'migration-collision',+ summary: 'a migration number this branch adds is already used on the base branch or by another open PR',+ fix: 'take the next free migration number when this PR is next to merge (rename the file and its id), commit, then rerun `gstack-pregate regate --against <gated-head> --bundle <file>`',+ },+ SEALED_OUTPUT_REFUSED: {+ anchor: 'sealed-output-refused',+ summary: 'a push or PR would publish sealed or eval output (a sealed path, a transcript, a quoted answer, a seed or a local home path) to a public or unknown destination, or the sealed policy is unreadable',+ fix: 'remove it from every published commit, or add one reviewed `rule<TAB>path<TAB>sha<TAB>reason` line to the base branch\'s .gstack/sealed-allow.tsv; a private destination sets sealed.visibility "private" in the base branch\'s .gstack/pregate.json',+ },+ EVAL_GATE_UNPRICED: {+ anchor: 'eval-gate-unpriced',+ summary: 'the paid gate has no call-plan file (no `--plan-file`, no base-policy `price_file`) or the file has no GSTACK_EVAL_CALLS lines, so its cost is unknown',+ fix: 'have the repo commit a call-plan file (docs/eval-calls.md) and set `price_file` in .gstack/pregate.json, or pass `--allow-unpriced "<reason>"` only on the owner\'s say-so',+ },+ EVAL_GATE_OVER_CAP: {+ anchor: 'eval-gate-over-cap',+ summary: 'the paid gate\'s priced total, or one call\'s reservation (input plus maximum output), is above the cap',+ fix: 'cut questions, arms or `max_out_tokens` in the call plan, or raise `--cap-usd` / `--smoke-cap-usd` deliberately with the owner; never split calls to slip under it',+ },+ EVAL_PLAN_STALE: {+ anchor: 'eval-plan-stale',+ summary: 'the call-plan file\'s binding does not match (a different gate command, a head behind HEAD, an input whose sha256 at HEAD differs) or the declared price_file is not in HEAD',+ fix: 'regenerate the call-plan file at HEAD for the exact gate command you are approving, commit it, and rerun `gstack-eval-plan price-gate`',+ },PLAN_SECTIONS_INVALID: {anchor: 'plan-sections-invalid',summary: 'the plan does not have exactly one non-empty `## Implementation plan` section followed by one `## Review record` section',diff --git a/lib/sealed-guard.ts b/lib/sealed-guard.tsnew file mode 100644index 000000000..e10c08a6a--- /dev/null+++ b/lib/sealed-guard.ts@@ -0,0 +1,276 @@+/**+ * sealed-guard — the sealed-output guard (field wave CD4), shared by the+ * managed pre-push hook (bin/gstack-redact-prepush) and the standalone+ * preflight `gstack-pregate sealed [--range <a..b>]`.+ *+ * A repo opts in with a `sealed` key in `.gstack/pregate.json`:+ * paths globs that may never be published (held-out sets, cells)+ * transcripts globs of per-cell transcripts+ * answer_markers regexes for a quoted sealed answer in added text+ * seed_patterns regexes for a sampling seed in added text+ * local_paths true: a local home path (/home/<u>/, /Users/<u>/) in added text+ * visibility "public" | "private": the destination override (reviewed on the base branch)+ *+ * The publication boundary is every commit the push publishes: the local sha+ * minus everything the destination remote already has (`git rev-list <local>+ * --not --remotes=<remote> ^<remote sha>`); a destination with no refs means+ * everything reachable. Path rules see every path a commit adds, renames or+ * copies, independent of content (binary, empty, add-then-delete); text rules+ * see each commit's added lines. The effective policy is the union of the+ * destination base branch's `sealed` and the pushed one (a push can tighten,+ * never relax); waivers come only from the base branch's+ * `.gstack/sealed-allow.tsv`. A malformed or unreadable policy refuses (fail+ * closed). Visibility: the base override, else a cache under the state root+ * (a `public` answer for 24 h, a `private` one for 1 h before it may+ * downgrade a refusal), else `gh repo view` (5 s); unknown counts as public.+ * Findings name file, line, rule and commit, never the matched text.+ */+import { spawnSync } from 'node:child_process';+import * as fs from 'node:fs';+import * as path from 'node:path';+import { containedRelative, globToRegExp, matchesAny } from './ship-policy';+import { resolveStateRoot } from './state-root';++export const SEALED_CONFIG_PATH = '.gstack/pregate.json';+export const SEALED_ALLOW_PATH = '.gstack/sealed-allow.tsv';+export const VISIBILITY_OVERRIDE_KEY = 'sealed.visibility';+export type SealedRule = 'sealed.path' | 'sealed.transcript' | 'sealed.answer' | 'sealed.seed' | 'sealed.local_path';+export interface SealedPolicy { paths: string[]; transcripts: string[]; answer_markers: string[]; seed_patterns: string[]; local_paths: boolean; visibility?: 'public' | 'private' }+export interface SealedFinding { rule: SealedRule; file: string; line?: number; commit: string }+export interface AllowEntry { rule: string; path: string; sha: string; reason: string }+export type Visibility = 'public' | 'private' | 'unknown';++const KEYS = ['paths', 'transcripts', 'answer_markers', 'seed_patterns', 'local_paths', 'visibility'];+const MAX_ENTRIES = 64;+const MAX_REGEX = 256;+const LOCAL_PATH_RE = /(?:^|[^A-Za-z0-9_.~-])(?:\/home\/[^/\s'"`]+\/|\/Users\/[^/\s'"`]+\/|[A-Za-z]:\\+Users\\+[^\\\s'"`]+\\)/;+const PUBLIC_TTL_MS = 24 * 3600_000;+const PRIVATE_TTL_MS = 3600_000;++/** `<key>: <message>` errors for a `sealed` value; empty when valid. Shared with lib/pregate/config.ts. */+export function sealedErrors(raw: unknown): Array<{ path: string; message: string }> {+ const errors: Array<{ path: string; message: string }> = [];+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return [{ path: 'sealed', message: 'must be an object { paths, transcripts, answer_markers, seed_patterns, local_paths, visibility }' }];+ const o = raw as Record<string, unknown>;+ for (const k of Object.keys(o)) if (!KEYS.includes(k)) errors.push({ path: `sealed.${k}`, message: `unknown key; valid keys: ${KEYS.join(', ')}` });+ const list = (key: string, check: (s: string) => string | null) => {+ if (!(key in o)) return;+ const v = o[key];+ if (!Array.isArray(v) || v.some(s => typeof s !== 'string')) { errors.push({ path: `sealed.${key}`, message: 'must be an array of strings' }); return; }+ if (v.length > MAX_ENTRIES) errors.push({ path: `sealed.${key}`, message: `more than ${MAX_ENTRIES} entries` });+ (v as string[]).forEach((s, i) => { const why = check(s); if (why) errors.push({ path: `sealed.${key}[${i}]`, message: `${JSON.stringify(s)} ${why}` }); });+ };+ const glob = (g: string) => { const why = containedRelative(g); if (why) return why; try { globToRegExp(g); return null; } catch (e: any) { return e.message; } };+ const regex = (r: string) => { if (!r || r.length > MAX_REGEX) return `must be 1-${MAX_REGEX} characters`; try { new RegExp(r); return null; } catch (e: any) { return `is not a valid regex (${e.message})`; } };+ list('paths', glob); list('transcripts', glob); list('answer_markers', regex); list('seed_patterns', regex);+ if ('local_paths' in o && typeof o.local_paths !== 'boolean') errors.push({ path: 'sealed.local_paths', message: 'must be true or false' });+ if ('visibility' in o && o.visibility !== 'public' && o.visibility !== 'private') errors.push({ path: 'sealed.visibility', message: 'must be "public" or "private"' });+ return errors;+}++function git(repoRoot: string, args: string[], input?: string): { ok: boolean; out: string; err: string } {+ const r = spawnSync('git', args, { cwd: repoRoot, encoding: 'utf8', input, timeout: 120_000, maxBuffer: 256 * 1024 * 1024 });+ return { ok: r.status === 0, out: r.stdout ?? '', err: (r.stderr ?? '').trim() };+}++export type PolicyRead = { policy: SealedPolicy | null; label: string } | { error: string; label: string };++/** The `sealed` key of `.gstack/pregate.json` at a commit; null when absent; an error when present but unreadable. */+export function sealedPolicyAt(repoRoot: string, treeish: string, label: string): PolicyRead {+ const spec = `${treeish}:${SEALED_CONFIG_PATH}`;+ if (!git(repoRoot, ['cat-file', '-e', spec]).ok) return { policy: null, label };+ const show = git(repoRoot, ['cat-file', 'blob', spec]);+ if (!show.ok) return { error: `cannot read ${SEALED_CONFIG_PATH} (${show.err})`, label };+ let raw: any;+ try { raw = JSON.parse(show.out); }+ catch (e: any) { return /"sealed"/.test(show.out) ? { error: `${SEALED_CONFIG_PATH} is not valid JSON (${e.message})`, label } : { policy: null, label }; }+ if (!raw || typeof raw !== 'object' || !('sealed' in raw)) return { policy: null, label };+ const errors = sealedErrors(raw.sealed);+ if (errors.length) return { error: errors.map(e => `${e.path}: ${e.message}`).join('; '), label };+ const s = raw.sealed;+ return { policy: { paths: s.paths ?? [], transcripts: s.transcripts ?? [], answer_markers: s.answer_markers ?? [], seed_patterns: s.seed_patterns ?? [], local_paths: s.local_paths === true, visibility: s.visibility }, label };+}++/** Base ∪ pushed: lists concatenate, `local_paths` ORs; visibility stays private only when the base says so and the push does not say public. */+export function unionPolicies(base: SealedPolicy | null, pushed: SealedPolicy | null): SealedPolicy | null {+ if (!base && !pushed) return null;+ const u = (k: 'paths' | 'transcripts' | 'answer_markers' | 'seed_patterns') => [...new Set([...(base?.[k] ?? []), ...(pushed?.[k] ?? [])])];+ const visibility = pushed?.visibility === 'public' || base?.visibility === 'public' ? 'public' : base?.visibility === 'private' ? 'private' : undefined;+ return { paths: u('paths'), transcripts: u('transcripts'), answer_markers: u('answer_markers'), seed_patterns: u('seed_patterns'), local_paths: !!(base?.local_paths || pushed?.local_paths), visibility };+}++/** Reviewed waivers: `rule<TAB>path<TAB>sha<TAB>reason` lines in the base branch's allow file. */+export function allowEntriesAt(repoRoot: string, treeish: string | null): AllowEntry[] {+ if (!treeish) return [];+ const show = git(repoRoot, ['cat-file', 'blob', `${treeish}:${SEALED_ALLOW_PATH}`]);+ if (!show.ok) return [];+ return show.out.split('\n').filter(l => l.trim() && !l.startsWith('#')).map(l => l.split('\t')).filter(f => f.length >= 4 && /^[0-9a-f]{7,64}$/.test(f[2]!) && f[3]!.trim())+ .map(f => ({ rule: f[0]!.trim(), path: f[1]!.trim(), sha: f[2]!, reason: f.slice(3).join('\t').trim() }));+}++/** Commits a push publishes: local minus the remote's refs (and its tip for this ref); null remote and no tip → everything reachable. */+export function publishedCommits(repoRoot: string, o: { localSha: string; remoteSha?: string | null; remoteName?: string | null }): { commits: string[] } | { error: string } {+ const not: string[] = [];+ if (o.remoteName) not.push(`--remotes=${o.remoteName}/*`);+ if (o.remoteSha && !/^0+$/.test(o.remoteSha) && git(repoRoot, ['cat-file', '-e', `${o.remoteSha}^{commit}`]).ok) not.push(o.remoteSha);+ const r = git(repoRoot, ['rev-list', o.localSha, ...(not.length ? ['--not', ...not] : [])]);+ if (!r.ok) return { error: `git rev-list failed: ${r.err.slice(0, 200)}` };+ return { commits: r.out.split('\n').filter(Boolean) };+}++export function rangeCommits(repoRoot: string, range: string): { commits: string[] } | { error: string } {+ const r = git(repoRoot, ['rev-list', range]);+ if (!r.ok) return { error: `git rev-list ${range} failed: ${r.err.slice(0, 200)}` };+ return { commits: r.out.split('\n').filter(Boolean) };+}++const HEX = /^[0-9a-f]{40,64}$/;++/** Path rules over every added, renamed or copied path, per commit (merges: paths new against every parent). */+function pathFindings(repoRoot: string, commits: string[], p: SealedPolicy): SealedFinding[] {+ if (!p.paths.length && !p.transcripts.length) return [];+ const r = git(repoRoot, ['-c', 'core.quotePath=false', 'diff-tree', '--stdin', '-r', '--root', '-M', '-C', '--cc', '--name-status', '-z'], commits.join('\n') + '\n');+ if (!r.ok) throw new Error(`git diff-tree failed: ${r.err.slice(0, 200)}`);+ const out: SealedFinding[] = [];+ const tokens = r.out.split('\0');+ let commit = '';+ for (let i = 0; i < tokens.length; i++) {+ const t = tokens[i]!;+ if (!t) continue;+ if (HEX.test(t)) { commit = t; continue; }+ const renamed = /^[RC]\d*$/.test(t);+ const file = renamed ? tokens[i += 2]! : tokens[++i]!;+ if (!renamed && !t.includes('A')) continue;+ if (matchesAny(p.transcripts, file)) out.push({ rule: 'sealed.transcript', file, commit });+ else if (matchesAny(p.paths, file)) out.push({ rule: 'sealed.path', file, commit });+ }+ return out;+}++/** Text rules over each commit's added lines (`--cc` for merges: only the resolution's own lines). */+function textFindings(repoRoot: string, commits: string[], p: SealedPolicy): SealedFinding[] {+ const rules: Array<[SealedRule, RegExp]> = [+ ...p.answer_markers.map(r => ['sealed.answer', new RegExp(r)] as [SealedRule, RegExp]),+ ...p.seed_patterns.map(r => ['sealed.seed', new RegExp(r)] as [SealedRule, RegExp]),+ ...(p.local_paths ? [['sealed.local_path', LOCAL_PATH_RE] as [SealedRule, RegExp]] : []),+ ];+ if (!rules.length) return [];+ const r = git(repoRoot, ['-c', 'core.quotePath=false', 'diff-tree', '--stdin', '-r', '--root', '-M', '-C', '--cc', '-p', '--unified=0', '--no-color', '--no-ext-diff', '--no-textconv'], commits.join('\n') + '\n');+ if (!r.ok) throw new Error(`git diff-tree -p failed: ${r.err.slice(0, 200)}`);+ const out: SealedFinding[] = [];+ let commit = ''; let file = ''; let inHunk = false; let parents = 1; let next = 0;+ for (const line of r.out.split('\n')) {+ if (HEX.test(line)) { commit = line; inHunk = false; continue; }+ if (line.startsWith('diff --')) { inHunk = false; file = ''; continue; }+ if (line.startsWith('@@')) { inHunk = true; parents = (/^@+/.exec(line)?.[0].length ?? 2) - 1; next = Number(/ \+(\d+)(?:,\d+)? @+/.exec(line)?.[1] ?? 0); continue; }+ if (!inHunk) { if (line.startsWith('+++ ')) file = line.startsWith('+++ b/') ? line.slice(6) : ''; continue; }+ const prefix = line.slice(0, parents);+ if (line.startsWith('\\') || prefix.includes('-')) continue;+ const n = next++;+ if (!prefix.includes('+')) continue;+ const text = line.slice(parents);+ for (const [rule, re] of rules) if (re.test(text)) out.push({ rule, file, line: n, commit });+ }+ return out;+}++export function scanCommits(repoRoot: string, commits: string[], policy: SealedPolicy): SealedFinding[] {+ if (!commits.length) return [];+ const seen = new Set<string>();+ return [...pathFindings(repoRoot, commits, policy), ...textFindings(repoRoot, commits, policy)].filter(f => {+ const key = `${f.rule}\0${f.file}\0${f.line ?? ''}\0${f.commit}`;+ if (seen.has(key)) return false;+ seen.add(key);+ return true;+ });+}++/** `owner/repo` for a GitHub remote URL; null for anything else (a local path, another host). */+export function githubSlug(url: string | null | undefined): string | null {+ const m = /^(?:https?:\/\/(?:[^@/]+@)?github\.com\/|ssh:\/\/git@github\.com\/|git@github\.com:)([A-Za-z0-9-]+)\/([A-Za-z0-9._-]+?)(?:\.git)?\/?$/.exec((url ?? '').trim());+ return m ? `${m[1]}/${m[2]}` : null;+}++export interface VisibilityOptions { env?: NodeJS.ProcessEnv; gh?: (args: string[]) => { ok: boolean; out: string }; now?: number }++/** Destination visibility: cache (public 24 h, private 1 h), else `gh repo view` (5 s); unknown on any failure or a non-GitHub remote. */+export function resolveVisibility(url: string | null, o: VisibilityOptions = {}): { visibility: Visibility; source: string } {+ const slug = githubSlug(url);+ if (!slug) return { visibility: 'unknown', source: 'not a GitHub remote' };+ const now = o.now ?? Date.now();+ const file = path.join(resolveStateRoot(o.env ?? process.env), 'sealed-visibility.json');+ let cache: Record<string, { visibility: Visibility; checked_at: number }> = {};+ try { cache = JSON.parse(fs.readFileSync(file, 'utf8')).entries ?? {}; } catch { cache = {}; }+ const hit = cache[slug];+ if (hit && ((hit.visibility === 'public' && now - hit.checked_at < PUBLIC_TTL_MS) || (hit.visibility === 'private' && now - hit.checked_at < PRIVATE_TTL_MS))) return { visibility: hit.visibility, source: `cache ${new Date(hit.checked_at).toISOString()}` };+ const gh = o.gh ?? ((args: string[]) => { const r = spawnSync('gh', args, { encoding: 'utf8', timeout: 5_000, env: o.env ?? process.env }); return { ok: r.status === 0, out: r.stdout ?? '' }; });+ const r = gh(['repo', 'view', slug, '--json', 'visibility']);+ let v: string | undefined;+ try { v = r.ok ? String(JSON.parse(r.out).visibility ?? '').toLowerCase() : undefined; } catch { v = undefined; }+ if (v !== 'public' && v !== 'private' && v !== 'internal') return { visibility: 'unknown', source: `gh repo view ${slug} failed (a new or unreadable repository counts as public)` };+ const visibility: Visibility = v === 'public' ? 'public' : 'private';+ cache[slug] = { visibility, checked_at: now };+ try { fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, JSON.stringify({ entries: cache }, null, 2) + '\n'); } catch { /* an unwritable cache only costs a lookup */ }+ return { visibility, source: `gh repo view ${slug}` };+}++export interface SealedReport {+ status: 'no-policy' | 'clear' | 'refused' | 'warned' | 'error';+ policyLabels: string[]; commits: number; findings: SealedFinding[]; waived: Array<SealedFinding & { reason: string }>;+ visibility: Visibility; visibilitySource: string; target: string; error?: string;+}++export interface EvaluateOptions {+ repoRoot: string; targets: Array<{ commits: string[]; pushedSha: string }>; baseRef: string | null; baseLabel?: string; remoteUrl: string | null; target: string;+ env?: NodeJS.ProcessEnv; gh?: VisibilityOptions['gh'];+}++/** The whole guard for one push (or range): policies, commits, findings, waivers, visibility, verdict. */+export function evaluateSealed(o: EvaluateOptions): SealedReport {+ const blank = { policyLabels: [] as string[], commits: 0, findings: [] as SealedFinding[], waived: [] as Array<SealedFinding & { reason: string }>, visibility: 'unknown' as Visibility, visibilitySource: '', target: o.target };+ const base = o.baseRef ? sealedPolicyAt(o.repoRoot, o.baseRef, o.baseLabel ?? o.baseRef) : { policy: null, label: '(no destination base branch)' };+ if ('error' in base) return { ...blank, status: 'error', error: `the sealed policy on ${base.label} is unreadable: ${base.error}` };+ let policy: SealedPolicy | null = base.policy;+ const labels = base.policy ? [base.label] : [];+ for (const t of o.targets) {+ const pushed = sealedPolicyAt(o.repoRoot, t.pushedSha, `pushed ${t.pushedSha.slice(0, 12)}`);+ if ('error' in pushed) return { ...blank, status: 'error', error: `the sealed policy in ${pushed.label} is unreadable: ${pushed.error}` };+ if (pushed.policy) labels.push(pushed.label);+ policy = unionPolicies(policy, pushed.policy);+ }+ if (!policy) return { ...blank, status: 'no-policy' };+ const commits = [...new Set(o.targets.flatMap(t => t.commits))];+ let found: SealedFinding[];+ try { found = scanCommits(o.repoRoot, commits, policy); }+ catch (e: any) { return { ...blank, policyLabels: labels, commits: commits.length, status: 'error', error: `could not read the published commits: ${e.message}` }; }+ const allow = allowEntriesAt(o.repoRoot, o.baseRef);+ const waived: SealedReport['waived'] = [];+ const findings = found.filter(f => {+ const entry = allow.find(a => a.rule === f.rule && a.path === f.file && f.commit.startsWith(a.sha));+ if (entry) waived.push({ ...f, reason: entry.reason });+ return !entry;+ });+ const vis = policy.visibility ? { visibility: policy.visibility as Visibility, source: `${VISIBILITY_OVERRIDE_KEY} override` } : resolveVisibility(o.remoteUrl, { env: o.env, gh: o.gh });+ const status = findings.length === 0 ? 'clear' : vis.visibility === 'private' ? 'warned' : 'refused';+ return { status, policyLabels: labels, commits: commits.length, findings, waived, visibility: vis.visibility, visibilitySource: vis.source, target: o.target };+}++const where = (f: SealedFinding) => `${f.file || '(unknown file)'}${f.line ? `:${f.line}` : ''}`;++/** stderr text for a report: findings one per line (`<rule> <file[:line]> commit <sha12>`), never the matched text. */+export function renderSealed(r: SealedReport, context: string): string {+ const lines: string[] = [];+ for (const w of r.waived) lines.push(`${context}: waived ${w.rule} ${where(w)} commit ${w.commit.slice(0, 12)} (${SEALED_ALLOW_PATH}: ${w.reason})`);+ const vis = `visibility: ${r.visibility}${r.visibility === 'unknown' ? ', counted public' : ''}; ${r.visibilitySource}`;+ const body = r.findings.map(f => ` ${f.rule} ${where(f)} commit ${f.commit.slice(0, 12)}`);+ if (r.status === 'error') {+ lines.push(`\n⛔ ${context} BLOCKED the publication of ${r.target} — ${r.error}.`);+ lines.push(`Fix the sealed policy (gstack-pregate validate), then retry; an unreadable policy never passes (SEALED_OUTPUT_REFUSED)`);+ } else if (r.status === 'refused') {+ lines.push(`\n⛔ ${context} BLOCKED the publication of ${r.target} (${vis}) — sealed or eval output in ${r.commits} published commit(s):`, ...body);+ lines.push(`Remove it from every published commit before this branch reaches a public repository, or waive one reviewed finding with a \`rule<TAB>path<TAB>sha<TAB>reason\` line in the base branch's ${SEALED_ALLOW_PATH}. A private destination: set ${VISIBILITY_OVERRIDE_KEY} "private" in the base branch's ${SEALED_CONFIG_PATH} (SEALED_OUTPUT_REFUSED)`);+ } else if (r.status === 'warned') {+ lines.push(`${context}: warning — sealed or eval output in a push to a private destination (${vis}); it would be refused for a public one:`, ...body);+ }+ return lines.length ? lines.join('\n') + '\n' : '';+}diff --git a/lib/ship-policy.ts b/lib/ship-policy.tsindex 1765ac23f..d34c8a07d 100644--- a/lib/ship-policy.ts+++ b/lib/ship-policy.ts@@ -50,6 +50,14 @@ export interface ShipPolicy {pr_count: { default_pr_count: number; split_requires_owner: boolean };/** Maintainer logins for contributor-PR mode (E3); empty means "use push permission". */maintainers: string[];+ /** The repo's stamp rule: when non-empty, only these files can be stamps (the allowlist applies before every stamp rule). */+ stamp_files: string[];+ /** Literal stamp templates with one `{version}` slot, beside the built-in `(was X)`, `since: X`, `vX`; writer and classifier share them. */+ stamp_patterns: string[];+ /** The repo's own restamp, run first in the staging worktree with the target version; gstack's version writer is skipped. */+ restamp_command: string | null;+ /** Migration numbering: `{ dir, id }` where `id` is a regex with one capture group over the file name. */+ migrations: { dir: string; id: string } | null;}export const DEFAULT_POLICY: ShipPolicy = {@@ -65,6 +73,10 @@ export const DEFAULT_POLICY: ShipPolicy = {stamp_sensitive_gates: [],pr_count: { default_pr_count: 1, split_requires_owner: true },maintainers: [],+ stamp_files: [],+ stamp_patterns: [],+ restamp_command: null,+ migrations: null,};export type PolicyKey = Exclude<keyof ShipPolicy, '$schema'>;@@ -84,6 +96,10 @@ export const POLICY_EXPLANATIONS: Record<PolicyKey, string> = {stamp_sensitive_gates: 'Evidence labels (gstack-evidence --label) that read VERSION or generated bytes; the tree receipt never marks them reusable.',pr_count: '{ default_pr_count, split_requires_owner }: the PR-count row in plan reviews.',maintainers: 'GitHub logins treated as maintainers by /review contributor mode; empty uses repository push permission.',+ stamp_files: 'The repo’s stamp rule: globs of the only files that may differ by a stamp (version file, manifests, plugin trees, the PR’s own since: rows). Empty keeps gstack’s per-file rules; set, it applies before every rule.',+ stamp_patterns: 'Literal templates with exactly one {version} slot (at most 16, 128 characters each), for example `"version": "{version}"` or `since: \'{version}\'`; the restamp writer and the tree receipt use them beside (was X), since: X and vX.',+ restamp_command: 'The repo’s own restamp, run first in gstack-restamp’s staging worktree (a clean checkout of HEAD) with the target version as its argument and in GSTACK_RESTAMP_VERSION; gstack’s version writer is skipped, output confinement still applies. Needs a clean caller tree and --allow-repo-commands.',+ migrations: '{ dir, id }: the migration directory and a regex with one capture group for the number in a file name; `gstack-pregate regate` reports MIGRATION_COLLISION against the base branch and every open PR.',};export interface PolicyError { code: ResultCodeName; path: string; message: string }@@ -93,6 +109,9 @@ const MAX_PATTERN = 256;const MAX_REGEX = 512;const MAX_COMMAND = 512;const SHA_RE = /^[0-9a-f]{7,64}$/;+const MAX_TEMPLATES = 16;+const MAX_TEMPLATE = 128;+export const VERSION_SLOT = '{version}';function hasDotDot(p: string): boolean {return p.split(/[\\/]+/).some(seg => seg === '..');@@ -149,6 +168,30 @@ function globError(g: string): string | null {return null;}+function templateErrors(value: unknown, out: PolicyError[]): void {+ if (!Array.isArray(value)) { out.push({ code: 'POLICY_INVALID', path: 'stamp_patterns', message: 'must be an array of literal templates' }); return; }+ if (value.length > MAX_TEMPLATES) out.push({ code: 'POLICY_CONTAINMENT', path: 'stamp_patterns', message: `more than ${MAX_TEMPLATES} templates` });+ value.forEach((t, i) => {+ const at = `stamp_patterns[${i}]`;+ if (typeof t !== 'string') { out.push({ code: 'POLICY_INVALID', path: at, message: 'must be a string' }); return; }+ if (t.split(VERSION_SLOT).length !== 2) out.push({ code: 'POLICY_INVALID', path: at, message: `${JSON.stringify(t)} must contain exactly one ${VERSION_SLOT}` });+ else if (t.length > MAX_TEMPLATE || /[\0\r\n]/.test(t)) out.push({ code: 'POLICY_CONTAINMENT', path: at, message: `must be one line of at most ${MAX_TEMPLATE} characters` });+ });+}++function migrationErrors(value: unknown, out: PolicyError[]): void {+ const m = value as Record<string, unknown> | null;+ if (!m || typeof m !== 'object' || Array.isArray(m)) { out.push({ code: 'POLICY_INVALID', path: 'migrations', message: 'must be { dir, id } or null' }); return; }+ for (const k of Object.keys(m)) if (k !== 'dir' && k !== 'id') out.push({ code: 'POLICY_INVALID', path: `migrations.${k}`, message: 'unknown key' });+ const dirWhy = typeof m.dir === 'string' ? containedRelative(m.dir) : 'must be a repo-relative directory';+ if (dirWhy) out.push({ code: 'POLICY_CONTAINMENT', path: 'migrations.dir', message: dirWhy });+ if (typeof m.id !== 'string' || !m.id || m.id.length > MAX_PATTERN) { out.push({ code: 'POLICY_INVALID', path: 'migrations.id', message: `must be a regex of 1-${MAX_PATTERN} characters` }); return; }+ try {+ const groups = new RegExp(`${m.id}|`).exec('')!.length - 1;+ if (groups !== 1) out.push({ code: 'POLICY_INVALID', path: 'migrations.id', message: `needs exactly one capture group for the migration number (has ${groups})` });+ } catch (e: any) { out.push({ code: 'POLICY_INVALID', path: 'migrations.id', message: `not a valid regex: ${e.message}` }); }+}+/** Schema and containment check of a parsed policy object. Unknown keys are errors (a typo must not silently mean "default"). */export function validatePolicy(raw: unknown): PolicyError[] {const errors: PolicyError[] = [];@@ -170,6 +213,14 @@ export function validatePolicy(raw: unknown): PolicyError[] {else if (/[\0\r\n]/.test(t)) errors.push({ code: 'POLICY_CONTAINMENT', path: 'release_tool', message: 'contains a newline or NUL' });}if ('release_outputs' in obj) listErrors('release_outputs', obj.release_outputs, errors, globError);+ if ('stamp_files' in obj) listErrors('stamp_files', obj.stamp_files, errors, globError);+ if ('stamp_patterns' in obj) templateErrors(obj.stamp_patterns, errors);+ if ('restamp_command' in obj && obj.restamp_command !== null) {+ const t = obj.restamp_command;+ if (typeof t !== 'string' || !t.trim()) errors.push({ code: 'POLICY_INVALID', path: 'restamp_command', message: 'must be a non-empty string or null' });+ else if (t.length > MAX_COMMAND || /[\0\r\n]/.test(t)) errors.push({ code: 'POLICY_CONTAINMENT', path: 'restamp_command', message: `must be one line under ${MAX_COMMAND} characters` });+ }+ if ('migrations' in obj && obj.migrations !== null) migrationErrors(obj.migrations, errors);if ('stamp_paths' in obj) listErrors('stamp_paths', obj.stamp_paths, errors, globError);for (const key of ['changelog', 'mirror'] as const) {if (!(key in obj) || obj[key] === null) continue;@@ -294,6 +345,7 @@ export function declaredCommands(policy: ShipPolicy): Array<{ key: string; commaconst out: Array<{ key: string; command: string; cwd: string }> = [];if (policy.release_tool) out.push({ key: 'release_tool', command: policy.release_tool, cwd: '.' });if (policy.release_tool && policy.mirror) out.push({ key: 'mirror.release_tool', command: policy.release_tool, cwd: policy.mirror });+ if (policy.restamp_command) out.push({ key: 'restamp_command', command: policy.restamp_command, cwd: '.' });return out;}diff --git a/lib/tree-receipt.ts b/lib/tree-receipt.tsindex f549aabfe..5f0df9911 100644--- a/lib/tree-receipt.ts+++ b/lib/tree-receipt.ts@@ -4,7 +4,9 @@* tree: its fingerprint can name objects unreachable once the gate VM is* gone), classifies the diff hunk by hunk with per-file-type rules, decides* per gate whether its evidence is reusable, and refuses `eligible` when the- * recorded predecessor head moved. Tree identity alone is not gate evidence:+ * recorded predecessor head moved. The repo's stamp rule wins: with+ * `stamp_files` set, only those files can be stamps, and `stamp_patterns`+ * (literal `{version}` templates) join the built-in stamp forms. Tree identity alone is not gate evidence:* the receipt also compares the execution identity the gate ran under (from* a `gstack-evidence bundle`) with the current one.*/@@ -18,7 +20,7 @@ import type { ResultCodeName } from './result-codes';import { matchesAny, type ShipPolicy } from './ship-policy';export type HunkClass = 'stamp' | 'changed';-export interface FileVerdict { path: string; rule: string; verdict: HunkClass; residual?: string }+export interface FileVerdict { path: string; rule: string; verdict: HunkClass; residual?: string; line?: number }export interface GateVerdict { label: string; verdict: 'reusable' | 'rerun' | 'not-reusable'; reason: string; cmd_sha256?: string; command?: string }export interface TreeReceipt {schema_version: 1;@@ -48,14 +50,14 @@ function blob(cwd: string, treeish: string, rel: string): string | null {}/** Every removed/added pair differs only by the exact stamp rewrites (old -> new). */-function stampOnlyHunks(hunks: FileDiff['hunks'], oldV: string, newV: string): string | null {+function stampOnlyHunks(hunks: FileDiff['hunks'], oldV: string, newV: string, templates: readonly string[]): { why: string; line: number } | null {for (const h of hunks) {- if (h.removed.length !== h.added.length) return `${h.removed.length} line(s) removed, ${h.added.length} added`;+ if (h.removed.length !== h.added.length) return { why: `${h.removed.length} line(s) removed, ${h.added.length} added`, line: h.at };for (let i = 0; i < h.removed.length; i++) {const r = h.removed[i]!;const a = h.added[i]!;- const rewritten = rewriteStamps(r, oldV, newV);- if (rewritten.count === 0 || rewritten.text !== a) return `${JSON.stringify(r.trim().slice(0, 60))} -> ${JSON.stringify(a.trim().slice(0, 60))}`;+ const rewritten = rewriteStamps(r, oldV, newV, templates);+ if (rewritten.count === 0 || rewritten.text !== a) return { why: `${JSON.stringify(r.trim().slice(0, 60))} -> ${JSON.stringify(a.trim().slice(0, 60))}`, line: h.at + i };}}return null;@@ -67,10 +69,11 @@ function jsonEqualModuloVersion(a: string | null, b: string | null, name: string}function classifyFile(repoRoot: string, f: FileDiff, gated: string, current: string, policy: ShipPolicy, versionRel: string, oldV: string | null, newV: string | null): FileVerdict {- const changed = (rule: string, residual: string): FileVerdict => ({ path: f.path, rule, verdict: 'changed', residual });+ const changed = (rule: string, residual: string, line = f.hunks[0]?.at): FileVerdict => ({ path: f.path, rule, verdict: 'changed', residual, line });const stamp = (rule: string): FileVerdict => ({ path: f.path, rule, verdict: 'stamp' });if (f.binary) return changed('binary', 'binary content differs');if (f.status !== 'M') return changed('path', `${f.status === 'A' ? 'added' : f.status === 'D' ? 'deleted' : 'renamed'}`);+ if (policy.stamp_files.length && !matchesAny(policy.stamp_files, f.path)) return changed('stamp_files', 'not in the repo\'s stamp_files allowlist');const before = blob(repoRoot, gated, f.path);const after = blob(repoRoot, current, f.path);const base = path.basename(f.path);@@ -93,10 +96,10 @@ function classifyFile(repoRoot: string, f: FileDiff, gated: string, current: strif (policy.changelog && f.path === policy.changelog) {return before !== null && after !== null && normalizeChangelog(before) === normalizeChangelog(after) ? stamp('changelog-heading') : changed('changelog', 'entry text changed (only a heading move or re-heading is a stamp)');}- if (oldV && newV && oldV !== newV && (matchesAny(policy.stamp_paths, f.path) || matchesAny(policy.release_outputs, f.path))) {- const rule = matchesAny(policy.stamp_paths, f.path) ? 'stamp_paths' : 'release_outputs';- const why = stampOnlyHunks(f.hunks, oldV, newV);- return why ? changed(rule, why) : stamp(rule);+ const rule = matchesAny(policy.stamp_paths, f.path) ? 'stamp_paths' : matchesAny(policy.release_outputs, f.path) ? 'release_outputs' : matchesAny(policy.stamp_files, f.path) ? 'stamp_files' : null;+ if (oldV && newV && oldV !== newV && rule) {+ const bad = stampOnlyHunks(f.hunks, oldV, newV, policy.stamp_patterns);+ return bad ? changed(rule, bad.why, bad.line) : stamp(rule);}return changed('other', `${f.hunks.length} hunk(s) outside every stamp rule`);}diff --git a/package.json b/package.jsonindex 038bf314a..726b20b28 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "gstack",- "version": "1.91.97",+ "version": "1.91.98","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/lib/windows-curation.ts b/scripts/lib/windows-curation.tsindex 1e6e63fe2..e3faa362b 100644--- a/scripts/lib/windows-curation.ts+++ b/scripts/lib/windows-curation.ts@@ -57,6 +57,9 @@ export const KNOWN_WINDOWS_INCOMPATIBLE: Array<{ file: string; reason: string }>// 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-guards.test.ts', reason: 'spawns bin/gstack-pregate through test/helpers/pregate-fixture.ts runBin (shebang via CreateProcess) and runs node guard and lane fixture commands through the POSIX runner' },+ { file: 'test/pregate-regate.test.ts', reason: 'spawns bin/gstack-pregate regate through test/helpers/restamp-fixture.ts runBin (shebang via CreateProcess)' },+ { file: 'test/stamp-templates.test.ts', reason: 'spawns bin/gstack-tree-receipt through test/helpers/restamp-fixture.ts runBin (shebang via CreateProcess)' },{ 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' },// PR E2: lane ownership and evidence verification run bin/gstack-lane-check and bin/gstack-evidencediff --git a/scripts/pr-dependencies.ts b/scripts/pr-dependencies.tsindex 070da473e..b2ddcc93d 100644--- a/scripts/pr-dependencies.ts+++ b/scripts/pr-dependencies.ts@@ -201,9 +201,9 @@ export function deriveDependencies(maps: DependencyMaps, root: string): DerivedD};const closure = (entries: Iterable<string>, parents?: Map<string, string>): Set<string> => {const seen = new Set<string>();- const queue = [...entries].filter(file => trackedSet.has(file));- while (queue.length) {- const file = queue.pop()!;+ const queue = [...entries].filter(file => trackedSet.has(file)).reverse();+ for (let head = 0; head < queue.length; head++) {+ const file = queue[head]!;if (seen.has(file)) continue;seen.add(file);for (const next of refs(file)) if (!seen.has(next) && !/\.test\.tsx?$/.test(next)) { queue.push(next); if (parents && !parents.has(next)) parents.set(next, file); }diff --git a/spec/sections/gate-and-file.md b/spec/sections/gate-and-file.mdindex 6c6585356..8dde3becd 100644--- a/spec/sections/gate-and-file.md+++ b/spec/sections/gate-and-file.md@@ -445,7 +445,9 @@ Behavior-change notices. Every user-visible behavior change outside the plan's oSpend caps. Each lane runs under the `--spend-cap` the coordinator names; a lane that reaches it stops with `status=budget_exhausted` and reports spent, reserved and unknown charges. Paid evals are never retried to change a verdict; a rerun needs a named repair. Host-subagent spend is reported as `unknown`, never zero.-Handoff format. A lane reports in this order, identifiers first: PR URL (or `no PR` with branch and SHA), `GSTACK_RESULT` line, gate summary (lanes passed/failed/skipped), behavior changes (or `none`), spend (spent/reserved/unknown), then what it could not verify. Full thread ids (`jam_…`), never short codes, in every cross-thread message. Prose after the identifiers may be truncated; nothing before them may be.+Before done. A lane runs `gstack-pregate run --allow-repo-commands` on its branch (the unit tier on the changed files plus the repo's guards) and reports done only after it passes. In a repo whose `.gstack/pregate.json` has a `sealed` key, it runs `gstack-pregate sealed` before any push or PR creation; a refusal stops the push, because a PR tool may not run local hooks.++Handoff format. A lane reports in this order, identifiers first: PR URL (or `no PR` with branch and SHA), `GSTACK_RESULT` line, the `gstack: ok|fail <rev>` line, the `PREGATE:` line, gate summary (lanes passed/failed/skipped), behavior changes (or `none`), spend (spent/reserved/unknown), then what it could not verify. Full thread ids (`jam_…`), never short codes, in every cross-thread message. Prose after the identifiers may be truncated; nothing before them may be.```bash[ -r "${ARCHIVE_PATH:?ARCHIVE_PATH is not set: substitute the archived spec path}" ] || { echo "ERROR: cannot read $ARCHIVE_PATH; nothing was spawned." >&2; exit 1; }diff --git a/test/benchmark-runner.test.ts b/test/benchmark-runner.test.tsindex 993de4759..f8e627960 100644--- a/test/benchmark-runner.test.ts+++ b/test/benchmark-runner.test.ts@@ -23,10 +23,10 @@ test('estimateCostUsd returns 0 for unknown model (no crash)', () => {});test('estimateCostUsd computes correctly for known Claude model', () => {- // claude-opus-4-7: $15/MTok input, $75/MTok output- // 1M input + 0.5M output = $15 + $37.50 = $52.50+ // claude-opus-4-7: $5/MTok input, $25/MTok output (platform.claude.com pricing, fetched 2026-10-12)+ // 1M input + 0.5M output = $5 + $12.50 = $17.50const cost = estimateCostUsd({ input: 1_000_000, output: 500_000 }, 'claude-opus-4-7');- expect(cost).toBeCloseTo(52.50, 2);+ expect(cost).toBeCloseTo(17.50, 2);});for (const model of [CLAUDE_FRONTIER_EVAL_MODEL, CODEX_FRONTIER_MODEL]) {@@ -48,12 +48,12 @@ test('Astra cache reads use its standard cached-input rate', () => {test('estimateCostUsd applies cached input discount alongside uncached input', () => {// tokens.input is uncached-only; tokens.cached is disjoint cache-reads at 10%.- // 0 uncached input, 1M cached → 10% of 15 = $1.50+ // 0 uncached input, 1M cached → 10% of 5 = $0.50const cost1 = estimateCostUsd({ input: 0, output: 0, cached: 1_000_000 }, 'claude-opus-4-7');- expect(cost1).toBeCloseTo(1.50, 2);- // 500K uncached input + 500K cached → $7.50 + $0.75 = $8.25+ expect(cost1).toBeCloseTo(0.50, 2);+ // 500K uncached input + 500K cached → $2.50 + $0.25 = $2.75const cost2 = estimateCostUsd({ input: 500_000, output: 0, cached: 500_000 }, 'claude-opus-4-7');- expect(cost2).toBeCloseTo(8.25, 2);+ expect(cost2).toBeCloseTo(2.75, 2);});test('PRICING table covers the key model families', () => {diff --git a/test/fixtures/module-size-ratchet.json b/test/fixtures/module-size-ratchet.jsonindex 917da852a..7f4f96a95 100644--- a/test/fixtures/module-size-ratchet.json+++ b/test/fixtures/module-size-ratchet.json@@ -108,6 +108,10 @@{ "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)" },+ { "file": "lib/pregate/checks/guards.ts", "movedFrom": "(new: pre-gate repo guards, field wave CD1)" },+ { "file": "lib/pregate/runtime.ts", "movedFrom": "(new: the verified launch Bun for repo commands, field wave CD1)" },+ { "file": "lib/sealed-guard.ts", "movedFrom": "(new: the sealed-output guard shared by the pre-push hook and gstack-pregate sealed, field wave CD4)" },+ { "file": "lib/pregate/regate.ts", "movedFrom": "(new: the regate verdict from a fresh tree receipt plus migration collisions, field wave CD3)" },{ "file": "lib/autoplan-scope.ts", "movedFrom": "(new: UI evidence from rendered surfaces and the plan scope marker, shared by the runner and the snapshot tool, field wave B2c)" },{ "file": "lib/source-root.ts", "movedFrom": "(new: the source checkout behind an install root, from its recorded .source-path, field wave B2e)" },{ "file": "scripts/resolvers/autoplan-driver.ts", "movedFrom": "(new: renders autoplan/DRIVER.md from the runner's constants, field wave B2e)" }diff --git a/test/helpers/placeholder-allowlist.ts b/test/helpers/placeholder-allowlist.tsindex 6d1b86564..d6ceca179 100644--- a/test/helpers/placeholder-allowlist.ts+++ b/test/helpers/placeholder-allowlist.ts@@ -102,6 +102,7 @@ export const IDENTIFIER_PLACEHOLDERS: Record<string, IdentifierGrammar> = {// Paths printed by earlier gstack blocks or chosen by the skill.'<body-file-name>': { grammar: ID, what: 'basename of the mktemp body file printed by the previous block' },'<title-file-name>': { grammar: ID, what: 'basename of the mktemp title file printed by the previous block' },+ '<gate-file-name>': { grammar: ID, what: 'basename of the mktemp gate-command file printed by the previous block (/eval-plan price-gate)' },'<reply-file-name>': { grammar: ID, what: 'basename of the mktemp reply file printed by the previous block' },'<redact-file-name>': { grammar: ID, what: 'basename of the mktemp draft file printed by the free-text block' },'<approach-file-name>': { grammar: ID, what: 'basename of the mktemp approach file printed by the free-text block' },diff --git a/test/lane-coordination.test.ts b/test/lane-coordination.test.tsindex fb52eec44..89816a51a 100644--- a/test/lane-coordination.test.ts+++ b/test/lane-coordination.test.ts@@ -129,6 +129,15 @@ describe('coordinator contract', () => {expect(rendered).toContain('gstack-autoplan contract) || {');});+ test('field wave CD: a lane runs pregate (and the sealed guard where configured) before done; the handoff carries the gstack trailer and the PREGATE: line after GSTACK_RESULT', () => {+ expect(COORDINATOR_CONTRACT).toContain('`gstack-pregate run --allow-repo-commands`');+ expect(COORDINATOR_CONTRACT).toContain('`gstack-pregate sealed` before any push or PR creation');+ const handoff = COORDINATOR_CONTRACT.slice(COORDINATOR_CONTRACT.indexOf('Handoff format.'));+ const order = ['`GSTACK_RESULT` line', '`gstack: ok|fail <rev>` line', '`PREGATE:` line', 'gate summary'].map(t => handoff.indexOf(t));+ expect(order.every(i => i > 0)).toBe(true);+ expect([...order].sort((a, b) => a - b)).toEqual(order);+ });+test('both reviewer prompts carry the contract after the plan, labelled as data', async () => {const { writePrompts } = await import('../lib/autoplan-prompts');const dir = fs.mkdtempSync(path.join(require('node:os').tmpdir(), 'gstack-contract-'));diff --git a/test/pr-dependencies.test.ts b/test/pr-dependencies.test.tsindex 27016c06d..2470405e9 100644--- a/test/pr-dependencies.test.ts+++ b/test/pr-dependencies.test.ts@@ -77,6 +77,17 @@ describe('reference derivation on a fixture tree', () => {expect(referenceText('data.json', '{"a":"lib/x.ts"}')).toBe('');});+ test('trace names the shortest chain: a template that invokes a bin directly wins over a long import path to it', () => {+ const repo = fixtureRepo({+ 'test/skill-e2e-gamma.test.ts': '', 'gamma/SKILL.md.tmpl': 'Run bin/gstack-target.\n', 'gamma/sections/a.md.tmpl': 'See lib/one.ts.\n',+ 'lib/one.ts': "import './two';\n", 'lib/two.ts': "import './three';\n", 'lib/three.ts': "export const x = 'bin/gstack-target';\n",+ 'bin/gstack-target': '#!/bin/sh\n', 'package.json': '{}',+ });+ const traced = deriveDependencies({ e2eTouchfiles: { gamma: ['test/skill-e2e-gamma.test.ts', 'gamma/**'] }, judgeTouchfiles: {}, globalTouchfiles: [] }, repo);+ expect(traced.trace('gamma', 'bin/gstack-target')).toEqual(['gamma/SKILL.md.tmpl', 'bin/gstack-target']);+ expect(traced.trace('gamma', 'lib/three.ts')).toEqual(['gamma/sections/a.md.tmpl', 'lib/one.ts', 'lib/two.ts', 'lib/three.ts']);+ });+test('a host config feeds only cases whose test names the host', () => {const named = deriveDependencies({ ...maps, e2eTouchfiles: { ...maps.e2eTouchfiles, beta: ['test/skill-e2e-beta.test.ts'] } },fixtureRepo({ 'test/skill-e2e-beta.test.ts': "run({ host: 'acme' });\n", 'hosts/acme.ts': '', 'hosts/zeta.ts': '', 'scripts/build.sh': '', 'scripts/resolvers/index.ts': '', 'package.json': '{}' }));diff --git a/test/pregate-guards.test.ts b/test/pregate-guards.test.tsnew file mode 100644index 000000000..9b70a6c03--- /dev/null+++ b/test/pregate-guards.test.ts@@ -0,0 +1,177 @@+/**+ * Field wave CD1/CD2 config keys in `.gstack/pregate.json`: the repo's guards+ * (commands a lane must pass before it reports done), the serial-test+ * patterns the lanes check runs in their own process, and the non-executing+ * call-plan command a paid gate is priced from. Validation stays strict:+ * every key is typed, globs are contained, commands are one line.+ */+import { describe, expect, test } from 'bun:test';+import { parseConfig, validateConfig } from '../lib/pregate/config';+import { CHECK_IDS } from '../lib/pregate/index';++const codes = (c: unknown) => validateConfig(c, CHECK_IDS).map(e => `${e.code}:${e.path}`);++describe('pregate config: price_file', () => {+ test('a contained price_file is valid and parsed; an absolute, escaping or non-string one is PREGATE_CONFIG_INVALID', () => {+ expect(codes({ price_file: 'evals/gate-calls.txt' })).toEqual([]);+ expect(parseConfig(JSON.stringify({ price_file: 'evals/gate-calls.txt' })).config.price_file).toBe('evals/gate-calls.txt');+ expect(parseConfig('{}').config.price_file).toBeNull();+ expect(codes({ price_file: '/etc/passwd' })).toEqual(['PREGATE_CONFIG_INVALID:price_file']);+ expect(codes({ price_file: '../x' })).toEqual(['PREGATE_CONFIG_INVALID:price_file']);+ expect(codes({ price_file: 3 })).toEqual(['PREGATE_CONFIG_INVALID:price_file']);+ });+});++// ---------------------------------------------------------------------------+// CD1: guards, unknown flags, the lanes check's Bun and serial files+// ---------------------------------------------------------------------------+import * as fs from 'node:fs';+import * as path from 'node:path';+import { afterEach } from 'bun:test';+import { EXIT } from '../lib/headless-artifacts';+import { capyHost, type CapyHost } from './helpers/capy-host';+import { BASE_PREGATE, cleanup, commit, makeFixtureRepo, runBin, write, type FixtureRepo } from './helpers/pregate-fixture';++const repos: FixtureRepo[] = [];+const hosts: CapyHost[] = [];+afterEach(() => { while (repos.length) cleanup(repos.pop()!); while (hosts.length) hosts.pop()!.cleanup(); });+const readOut = (repo: FixtureRepo) => JSON.parse(fs.readFileSync(path.join(repo.work, '.gstack/tmp/pregate.json'), 'utf8'));+const checkRow = (repo: FixtureRepo, id: string) => readOut(repo).checks.find((c: any) => c.id === id);++const CHECK_SERIAL = [+ "const fs = require('node:fs');",+ "const rows = new Set(fs.readFileSync('scripts/serial-files.tsv', 'utf8').split('\\n').map(l => l.split('\\t')[0]).filter(Boolean));",+ "const missing = fs.readdirSync('test').filter(f => f.endsWith('.serial.test.js')).map(f => `test/${f}`).filter(f => !rows.has(f));",+ "for (const f of missing) console.log(`${f} is a serial test file with no row in scripts/serial-files.tsv.`);",+ 'process.exit(missing.length ? 1 : 0);',+].join('\n') + '\n';+const SERIAL_GUARD = { id: 'serial-manifest', when: ['test/**/*.serial.test.js', 'scripts/serial-files.tsv'], command: 'node scripts/check-serial.js', fix: 'add a row for the file to scripts/serial-files.tsv' };+const SERIAL_TEST = "const test = require('node:test');\ntest('serial', () => {});\n";++/** The base branch gains the manifest, its check script and the given pregate config. */+function guardedFixture(pregate: Record<string, unknown>): FixtureRepo {+ const repo = makeFixtureRepo({ pregate });+ repos.push(repo);+ repo.git('checkout', '-q', 'main');+ write(repo.work, 'scripts/check-serial.js', CHECK_SERIAL);+ write(repo.work, 'scripts/serial-files.tsv', 'path\treason\n');+ repo.git('add', '-A');+ repo.git('commit', '-q', '-m', 'serial manifest');+ repo.git('push', '-q', 'origin', 'main');+ repo.git('checkout', '-q', 'feature');+ repo.git('merge', '-q', '--ff-only', 'main');+ return repo;+}+const pregate = (repo: FixtureRepo, args: string[], env: Record<string, string> = {}) => runBin(repo, 'gstack-pregate', ['--base', 'main', ...args], env);++describe('guards (CD1)', () => {+ test('a serial test that lands without its manifest row fails pregate naming the guard and its fix; adding the row clears it', () => {+ const repo = guardedFixture({ ...BASE_PREGATE, guards: [SERIAL_GUARD] });+ commit(repo, { 'test/widget-env.serial.test.js': SERIAL_TEST });+ const r = pregate(repo, ['--allow-repo-commands', '--stage', 'preflight']);+ expect(r.status).toBe(EXIT.fail);+ expect(r.out).toMatch(/^preflight {2}guards {4}fail .*serial-manifest.*\(PREGATE_GUARD_FAILED\)/m);+ expect(r.out).toContain('guards: GUARD: serial-manifest exit=1');+ expect(r.out).toContain('test/widget-env.serial.test.js is a serial test file with no row in scripts/serial-files.tsv.');+ expect(r.out).toContain('guards: fix: serial-manifest: add a row for the file to scripts/serial-files.tsv');+ expect(r.err).toContain('(PREGATE_GUARD_FAILED)');+ commit(repo, { 'scripts/serial-files.tsv': 'path\treason\ntest/widget-env.serial.test.js\tglobal-state\n' });+ const ok = pregate(repo, ['--allow-repo-commands', '--stage', 'preflight']);+ expect(ok.status).toBe(EXIT.ok);+ expect(ok.out).toMatch(/^preflight {2}guards {4}pass .*1 guard\(s\) passed: serial-manifest/m);+ });++ test('without --allow-repo-commands a selected guard is incomplete and lists its command; an unmatched guard does not run', () => {+ const repo = guardedFixture({ ...BASE_PREGATE, guards: [SERIAL_GUARD, { id: 'never', when: ['nothing/**'], command: 'false' }] });+ commit(repo, { 'test/widget-env.serial.test.js': SERIAL_TEST });+ const r = pregate(repo, ['--stage', 'preflight', '--only', 'guards']);+ expect(r.status).toBe(EXIT.fail);+ expect(r.out).toMatch(/^preflight {2}guards {4}incomplete .*\(REPO_COMMANDS_NOT_ALLOWED\)/m);+ expect(r.out).toContain('guards: COMMAND: serial-manifest="node scripts/check-serial.js"');+ expect(r.out).not.toContain('COMMAND: never=');+ expect(r.out).toContain('GSTACK_RESULT: skill=pregate status=incomplete');+ });++ test('each guard runs in its own process with its timeout: a failing guard does not stop the next, a timed-out guard is incomplete, never pass', () => {+ const repo = guardedFixture({ ...BASE_PREGATE, guards: [+ { id: 'first', when: ['lib/**'], command: 'echo first-ran; exit 3' },+ { id: 'second', when: ['lib/**'], command: 'touch ../second-ran' },+ { id: 'slow', when: ['lib/**'], command: 'sleep 20', timeout_s: 1 },+ ] });+ commit(repo, { 'lib/util.js': "exports.add = (a, b) => a + b + 0;\n" });+ const r = pregate(repo, ['--allow-repo-commands', '--stage', 'preflight', '--only', 'guards']);+ expect(r.status).toBe(EXIT.fail);+ expect(fs.existsSync(path.join(repo.root, 'second-ran'))).toBe(true);+ expect(r.out).toContain('guards: GUARD: first exit=3');+ expect(r.out).toContain('guards: GUARD: slow timed out after 1 s');+ const row = checkRow(repo, 'guards');+ expect(row.status).toBe('fail');+ expect(row.detail).toContain('first');+ expect(row.detail).not.toContain('second');+ const slowOnly = guardedFixture({ ...BASE_PREGATE, guards: [{ id: 'slow', when: ['lib/**'], command: 'sleep 20', timeout_s: 1 }] });+ commit(slowOnly, { 'lib/util.js': "exports.add = (a, b) => a + b + 0;\n" });+ expect(pregate(slowOnly, ['--allow-repo-commands', '--stage', 'preflight', '--only', 'guards']).status).toBe(EXIT.fail);+ expect(checkRow(slowOnly, 'guards')).toMatchObject({ status: 'incomplete', code: 'PREGATE_INCOMPLETE' });+ });++ test('guards cannot be downgraded to warn; a guard needs an id, globs and a one-line command', () => {+ expect(codes({ guards: [SERIAL_GUARD] })).toEqual([]);+ expect(codes({ guards: [SERIAL_GUARD], warn: ['guards'] })).toEqual(['PREGATE_CONFIG_INVALID:warn']);+ expect(codes({ guards: [{ id: 'bad id!', when: ['x'], command: 'true' }] })).toEqual(['PREGATE_CONFIG_INVALID:guards[0].id']);+ expect(codes({ guards: [{ id: 'g', when: ['../x'], command: 'true' }] })).toEqual(['PREGATE_CONFIG_INVALID:guards[0].when[0]']);+ expect(codes({ guards: [{ id: 'g', when: ['x'], command: 'a\nb' }] })).toEqual(['PREGATE_CONFIG_INVALID:guards[0].command']);+ expect(codes({ guards: [{ id: 'g', when: ['x'], command: 'true', extra: 1 }] })).toEqual(['PREGATE_CONFIG_INVALID:guards[0].extra']);+ expect(codes({ guards: [{ id: 'g', when: ['x'], command: 'true' }, { id: 'g', when: ['y'], command: 'true' }] })).toEqual(['PREGATE_CONFIG_INVALID:guards[1].id']);+ expect(codes({ serial_patterns: ['**/*.serial.test.*'] })).toEqual([]);+ expect(codes({ serial_patterns: ['/abs/**'] })).toEqual(['PREGATE_CONFIG_INVALID:serial_patterns[0]']);+ });+});++describe('pregate config: sealed (CD4)', () => {+ test('`gstack-pregate validate` accepts a sealed policy and names each bad field', () => {+ expect(codes({ sealed: { paths: ['heldout/**'], transcripts: ['runs/**/transcript*.jsonl'], answer_markers: ['SEALED ANSWER:'], seed_patterns: ['seed=\\d+'], local_paths: true, visibility: 'private' } })).toEqual([]);+ expect(codes({ sealed: { paths: 'heldout/**' } })).toEqual(['PREGATE_CONFIG_INVALID:sealed.paths']);+ expect(codes({ sealed: { seed_patterns: ['('] } })).toEqual(['PREGATE_CONFIG_INVALID:sealed.seed_patterns[0]']);+ expect(codes({ sealed: { visibility: 'internal' } })).toEqual(['PREGATE_CONFIG_INVALID:sealed.visibility']);+ expect(codes({ sealed: { block: true } })).toEqual(['PREGATE_CONFIG_INVALID:sealed.block']);+ });+});++describe('gstack-pregate flags (CD1)', () => {+ test('an unknown flag is usage (exit 2) on every verb instead of a silent normal run', () => {+ const repo = makeFixtureRepo(); repos.push(repo);+ const bogus = runBin(repo, 'gstack-pregate', ['run', '--base', 'main', '--bogus']);+ expect(bogus.status).toBe(EXIT.usage);+ expect(bogus.err).toContain('unknown flag --bogus');+ const sealedFlag = pregate(repo, ['--sealed']);+ expect(sealedFlag.status).toBe(EXIT.usage);+ expect(sealedFlag.err).toContain('gstack-pregate sealed');+ expect(runBin(repo, 'gstack-pregate', ['verify', '--nope']).status).toBe(EXIT.usage);+ expect(fs.existsSync(path.join(repo.work, '.gstack/tmp/pregate.json'))).toBe(false);+ });+});++describe('lanes runtime and serial files (CD1)', () => {+ const recordingRunner = `bash -c 'echo "RUN: $*" >> ../runs.log; echo "bun=$(bun --version)"; node --test "$@"' _ {files}`;++ test('on a Capy-shaped host the lanes runner gets the verified Bun from $HOME/.bun/bin, not the older PATH Bun', () => {+ const host = capyHost({ verifiedBun: '1.4.2' }); hosts.push(host);+ const repo = makeFixtureRepo({ pregate: { ...BASE_PREGATE, runner: recordingRunner } }); repos.push(repo);+ commit(repo, { 'lib/util.js': "exports.add = (a, b) => a + b + 0;\n" });+ const r = pregate(repo, ['--allow-repo-commands', '--stage', 'tests'], host.env);+ expect(r.status).toBe(EXIT.ok);+ expect(r.out).toContain('lanes: bun=1.4.2');+ expect(r.out).not.toContain('bun=1.3.14');+ expect(r.out).toContain(`lanes: runtime: bun 1.4.2 from ${host.bunInstallBin}`);+ });++ test('serial-pattern test files run in their own process, apart from the unit files', () => {+ const repo = makeFixtureRepo({ pregate: { ...BASE_PREGATE, runner: recordingRunner } }); repos.push(repo);+ commit(repo, { 'lib/util.js': "exports.add = (a, b) => a + b + 0;\n", 'test/widget-env.serial.test.js': "const test = require('node:test');\ntest('serial', () => {});\n" });+ const r = pregate(repo, ['--allow-repo-commands', '--stage', 'tests']);+ expect(r.status).toBe(EXIT.ok);+ const runs = fs.readFileSync(path.join(repo.root, 'runs.log'), 'utf8').trim().split('\n');+ expect(runs).toEqual(['RUN: test/util.test.js', 'RUN: test/widget-env.serial.test.js']);+ expect(r.out).toMatch(/^tests {6}lanes {5}pass .*2 tests ran in 2 file\(s\) \(1 serial\), exit 0/m);+ });+});diff --git a/test/pregate-invalidation.test.ts b/test/pregate-invalidation.test.tsindex e8581e321..067d58011 100644--- a/test/pregate-invalidation.test.ts+++ b/test/pregate-invalidation.test.ts@@ -29,7 +29,7 @@ describe('pregate invalidation', () => {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.pregate).toMatch(/^pass @[0-9a-f]{12} \(6 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.diff --git a/test/pregate-regate.test.ts b/test/pregate-regate.test.tsnew file mode 100644index 000000000..2e31a4c5f--- /dev/null+++ b/test/pregate-regate.test.ts@@ -0,0 +1,191 @@+/**+ * Field wave CD3: `gstack-pregate regate --against <gated-head>` decides+ * whether a gated head's evidence still covers HEAD. Reuse comes only from a+ * tree receipt evaluated now with a bundle produced on the gated tree; each+ * lane gets a verdict; a migration number the branch adds is checked against+ * the base branch and every other open PR, and a lookup that cannot finish is+ * `unknown`, which withholds `REGATE: not-needed`.+ */+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 { BASE_POLICY, cleanup, makeFixtureRepo, makePr, recordAndBundle, restamp, runBin, type FixtureRepo } from './helpers/restamp-fixture';++const repos: FixtureRepo[] = [];+afterEach(() => { while (repos.length) cleanup(repos.pop()!); });++const POLICY = { ...BASE_POLICY, stamp_sensitive_gates: ['digest'], migrations: { dir: 'migrations', id: '^v(\\d+)-' } };++interface GhData { list?: unknown; listFail?: boolean; api?: Record<string, string[] | null> }+/** A gh stand-in: `pr list` answers from data (or fails), `api .../pulls/<n>/files` prints one filename per line (or fails). */+function ghShim(repo: FixtureRepo, data: GhData): Record<string, string> {+ const dir = path.join(repo.root, 'gh-regate');+ fs.mkdirSync(dir, { recursive: true });+ const file = path.join(dir, 'data.json');+ fs.writeFileSync(file, JSON.stringify(data));+ fs.writeFileSync(path.join(dir, 'calls.log'), '');+ fs.writeFileSync(path.join(dir, 'gh'), [+ '#!/bin/sh',+ `echo "$*" >> "${path.join(dir, 'calls.log')}"`,+ `exec node -e '+const d=require(process.argv[1]); const a=process.argv.slice(2);+if(a[0]==="pr"&&a[1]==="list"){ if(d.listFail){console.error("gh: HTTP 502");process.exit(1)} console.log(JSON.stringify(d.list??[])); process.exit(0) }+if(a[0]==="api"){ const n=/pulls\\/(\\d+)\\/files/.exec(a.join(" "))?.[1]; const f=d.api?.[n]; if(!f){console.error("gh: HTTP 403");process.exit(1)} console.log(f.join("\\n")); process.exit(0) }+console.error("gh shim: unsupported "+a.join(" ")); process.exit(1)' "${file}" "$@"`,+ '',+ ].join('\n'), { mode: 0o755 });+ return { PATH: `${dir}:${process.env.PATH ?? ''}` };+}+const ghCalls = (repo: FixtureRepo) => fs.readFileSync(path.join(repo.root, 'gh-regate', 'calls.log'), 'utf8');++/** pr-a adds migration v240, is stamped 1.2.4.0 and gated (lanes recorded and bundled); then restamped to 1.2.5.0. */+function gatedThenRestamped(lanes: Array<{ label: string; command: string }> = [{ label: 'tests', command: 'true' }]) {+ const repo = makeFixtureRepo({ prefix: 'pregate-regate-', policy: POLICY });+ repos.push(repo);+ makePr(repo, 'pr-a', { expects: '1.2.4.0' });+ fs.mkdirSync(path.join(repo.work, 'migrations'), { recursive: true });+ fs.writeFileSync(path.join(repo.work, 'migrations', 'v240-add-index.sql'), 'create index a;\n');+ repo.git('add', '-A'); repo.git('commit', '-q', '-m', 'migration v240');+ expect(restamp(repo, ['--version', '1.2.4.0']).status).toBe(EXIT.ok);+ repo.git('commit', '-qam', 'stamp 1.2.4.0');+ const bundle = path.join(repo.root, 'bundle.json');+ recordAndBundle(repo, repo.work, lanes, bundle);+ const head = repo.git('rev-parse', 'HEAD');+ expect(restamp(repo, ['--version', '1.2.5.0']).status).toBe(EXIT.ok);+ repo.git('commit', '-qam', 'stamp 1.2.5.0');+ return { repo, head, bundle, current: repo.git('rev-parse', 'HEAD') };+}+const regate = (repo: FixtureRepo, args: string[], env: Record<string, string>) => runBin(repo, 'gstack-pregate', ['regate', '--base', 'main', ...args], env);++describe('gstack-pregate regate: evidence, stamps and lane verdicts', () => {+ test('a pure restamp with a bundle from the gated tree and no other migration is not-needed; the --against alias is the same verb', () => {+ const { repo, head, bundle, current } = gatedThenRestamped();+ const env = ghShim(repo, { list: [{ number: 7, headRefOid: current, files: [{ path: 'migrations/v240-add-index.sql' }] }, { number: 8, headRefOid: 'f'.repeat(40), files: [{ path: 'migrations/v241-other.sql' }] }] });+ const r = regate(repo, ['--against', head, '--bundle', bundle], env);+ expect(r.err).toBe('');+ expect(r.status).toBe(EXIT.ok);+ expect(r.out).toMatch(/^ stamp docs\/pr-a\.md \(stamp_paths\)$/m);+ expect(r.out).toMatch(/^STAMP_ONLY: yes files=\d+$/m);+ expect(r.out).toMatch(/^LANE: tests reusable \(identity matches; tree same modulo stamps\)$/m);+ expect(r.out).toMatch(/^MIGRATION_COLLISION: none \(240 checked against origin\/main and 1 open PR\(s\)\)$/m);+ expect(r.out.trimEnd().split('\n').at(-1)).toBe('REGATE: not-needed');+ expect(ghCalls(repo)).toContain('pr list --state open --limit 1000 --json number,headRefOid,files');+ const alias = runBin(repo, 'gstack-pregate', ['--against', head, '--bundle', bundle, '--base', 'main'], env);+ expect(alias.status).toBe(EXIT.ok);+ expect(alias.out).toBe(r.out);+ });++ test('without gate evidence, or with a bundle from another tree, the verdict is needed even when the tree is stamp-only', () => {+ const { repo, head, bundle } = gatedThenRestamped();+ const env = ghShim(repo, { list: [] });+ const none = regate(repo, ['--against', head], env);+ expect(none.status).toBe(EXIT.fail);+ expect(none.out).toMatch(/^STAMP_ONLY: yes /m);+ expect(none.out).toMatch(new RegExp(`^REGATE: needed \\(no gate evidence for ${head.slice(0, 12)} \\(none \\(no evidence bundle; execution identity unknown\\)\\)\\)$`, 'm'));+ const other = path.join(repo.root, 'other.json');+ recordAndBundle(repo, repo.work, [{ label: 'tests', command: 'true' }], other);+ const wrong = regate(repo, ['--against', head, '--bundle', other], env);+ expect(wrong.status).toBe(EXIT.fail);+ expect(wrong.out).toMatch(/^REGATE: needed \(no gate evidence for [0-9a-f]{12} \(bundle .*other\.json was produced on tree [0-9a-f]{12}, not the gated tree [0-9a-f]{12}\)\)$/m);+ expect(wrong.out).not.toContain('LANE: tests reusable');+ const required = regate(repo, ['--against', head, '--bundle', bundle, '--require', 'tests,e2e'], env);+ expect(required.status).toBe(EXIT.fail);+ expect(required.out).toMatch(/^LANE: tests reusable /m);+ expect(required.out).toMatch(/^LANE: e2e not-reusable \(required lane has no record in the bundle\)$/m);+ expect(required.out).toMatch(/^REGATE: needed \(e2e not reusable \(required lane has no record in the bundle\)\)$/m);+ });++ test('a stamp-sensitive lane reruns, so a regate is needed; a code edit is not stamp-only and names the file and line', () => {+ const { repo, head, bundle } = gatedThenRestamped([{ label: 'tests', command: 'true' }, { label: 'digest', command: 'cat generated/digest.md' }]);+ const env = ghShim(repo, { list: [] });+ const r = regate(repo, ['--against', head, '--bundle', bundle], env);+ expect(r.status).toBe(EXIT.fail);+ expect(r.out).toMatch(/^LANE: tests reusable /m);+ expect(r.out).toMatch(/^LANE: digest rerun \(stamp-sensitive/m);+ expect(r.out).toMatch(/^REGATE: needed \(digest reruns \(stamp-sensitive/m);+ fs.writeFileSync(path.join(repo.work, 'pr-a.txt'), 'pr-a\nmore code\n');+ repo.git('commit', '-qam', 'code edit');+ const edited = regate(repo, ['--against', head, '--bundle', bundle], env);+ expect(edited.status).toBe(EXIT.fail);+ expect(edited.out).toMatch(/^ changed pr-a\.txt:2 \(other: 1 hunk\(s\) outside every stamp rule\)$/m);+ expect(edited.out).toMatch(/^STAMP_ONLY: no files=\d+ changed=1$/m);+ expect(edited.out).toMatch(/^LANE: tests not-reusable \(not stamp-only: pr-a\.txt\)$/m);+ expect(edited.out).toMatch(/^REGATE: needed \(not stamp-only: pr-a\.txt; digest reruns \(stamp-sensitive/m);+ });++ test('a moved or unknown predecessor head withholds not-needed', () => {+ const { repo, head, bundle, current } = gatedThenRestamped();+ const env = ghShim(repo, { list: [] });+ repo.git('branch', 'pred', current);+ const moved = regate(repo, ['--against', head, '--bundle', bundle, '--predecessor', head, '--predecessor-ref', 'pred'], env);+ expect(moved.status).toBe(EXIT.fail);+ expect(moved.out).toMatch(new RegExp(`^REGATE: needed \\(PREDECESSOR MOVED ${head.slice(0, 12)} -> ${current.slice(0, 12)}\\)$`, 'm'));+ const unknown = regate(repo, ['--against', head, '--bundle', bundle, '--predecessor', head, '--predecessor-pr', '41'], env);+ expect(unknown.status).toBe(EXIT.fail);+ expect(unknown.out).toMatch(/^REGATE: needed \(predecessor #41 current head unknown\)$/m);+ });+});++describe('gstack-pregate regate: migration collisions', () => {+ test('two open PRs adding the same migration number collide; the PR itself is excluded', () => {+ const { repo, head, bundle, current } = gatedThenRestamped();+ const env = ghShim(repo, { list: [+ { number: 7, headRefOid: current, files: [{ path: 'migrations/v240-add-index.sql' }] },+ { number: 9, headRefOid: 'a'.repeat(40), files: [{ path: 'src/x.ts' }, { path: 'migrations/v240-add-column.sql' }] },+ ] });+ const r = regate(repo, ['--against', head, '--bundle', bundle], env);+ expect(r.status).toBe(EXIT.fail);+ expect(r.out).toMatch(/^MIGRATION_COLLISION: 240 migrations\/v240-add-index\.sql vs PR #9 migrations\/v240-add-column\.sql$/m);+ expect(r.out).toMatch(/^REGATE: needed \(migration collision: 240\)$/m);+ expect(r.err).toContain('(MIGRATION_COLLISION)');+ });++ test('a number the base branch took meanwhile collides', () => {+ const { repo, head, bundle } = gatedThenRestamped();+ const env = ghShim(repo, { list: [] });+ repo.git('checkout', '-q', 'origin/main', '-b', 'other');+ fs.mkdirSync(path.join(repo.work, 'migrations'), { recursive: true });+ fs.writeFileSync(path.join(repo.work, 'migrations', 'v240-landed.sql'), 'alter table b;\n');+ repo.git('add', '-A'); repo.git('commit', '-q', '-m', 'landed v240');+ repo.git('push', '-q', 'origin', 'HEAD:main');+ repo.git('checkout', '-q', 'pr-a');+ repo.git('fetch', '-q', 'origin');+ const r = regate(repo, ['--against', head, '--bundle', bundle], env);+ expect(r.status).toBe(EXIT.fail);+ expect(r.out).toMatch(/^MIGRATION_COLLISION: 240 migrations\/v240-add-index\.sql vs origin\/main migrations\/v240-landed\.sql$/m);+ });++ test('a lookup that cannot finish is unknown and blocks not-needed: gh failing, a truncated PR list, a 100-file PR whose files cannot be fetched', () => {+ const { repo, head, bundle } = gatedThenRestamped();+ const failing = regate(repo, ['--against', head, '--bundle', bundle], ghShim(repo, { listFail: true }));+ expect(failing.status).toBe(EXIT.fail);+ expect(failing.out).toMatch(/^MIGRATION_COLLISION: unknown \(gh pr list failed: gh: HTTP 502\)$/m);+ expect(failing.out).toMatch(/^REGATE: needed \(migration lookup unknown \(gh pr list failed: gh: HTTP 502\)\)$/m);++ const many = Array.from({ length: 1000 }, (_, i) => ({ number: 1000 + i, headRefOid: 'b'.repeat(40), files: [] }));+ const truncated = regate(repo, ['--against', head, '--bundle', bundle], ghShim(repo, { list: many }));+ expect(truncated.status).toBe(EXIT.fail);+ expect(truncated.out).toMatch(/^MIGRATION_COLLISION: unknown \(1000 open PRs listed, the list may be truncated at 1000\)$/m);++ const hundred = Array.from({ length: 100 }, (_, i) => ({ path: `src/f${i}.ts` }));+ const big = [{ number: 12, headRefOid: 'c'.repeat(40), files: hundred }];+ const unfetched = regate(repo, ['--against', head, '--bundle', bundle], ghShim(repo, { list: big }));+ expect(unfetched.status).toBe(EXIT.fail);+ expect(unfetched.out).toMatch(/^MIGRATION_COLLISION: unknown \(PR #12 lists 100 files \(truncated\) and its full file list could not be fetched\)$/m);++ const env = ghShim(repo, { list: big, api: { '12': [...hundred.map(f => f.path), 'migrations/v240-late.sql'] } });+ const fetched = regate(repo, ['--against', head, '--bundle', bundle], env);+ expect(ghCalls(repo)).toContain('api --paginate repos/{owner}/{repo}/pulls/12/files?per_page=100 --jq .[].filename');+ expect(fetched.out).toMatch(/^MIGRATION_COLLISION: 240 migrations\/v240-add-index\.sql vs PR #12 migrations\/v240-late\.sql$/m);+ });++ test('regate takes only its own flags (exit 2) and needs --against', () => {+ const { repo, head } = gatedThenRestamped();+ const env = ghShim(repo, { list: [] });+ expect(regate(repo, ['--against', head, '--bogus'], env).status).toBe(EXIT.usage);+ const missing = regate(repo, [], env);+ expect(missing.status).toBe(EXIT.usage);+ expect(missing.err).toContain('--against <gated-head> is required');+ });+});diff --git a/test/pregate-selection.test.ts b/test/pregate-selection.test.tsindex 444bbc9ca..764076ace 100644--- a/test/pregate-selection.test.ts+++ b/test/pregate-selection.test.ts@@ -98,7 +98,7 @@ describe('gstack-pregate (bin)', () => {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 1 mechanical preflight (regen, secrets, strays, literals, guards)');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);@@ -113,6 +113,7 @@ describe('gstack-pregate (bin)', () => {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(/^preflight {2}guards {4}pass .*no guards declared/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);@@ -121,7 +122,7 @@ describe('gstack-pregate (bin)', () => {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']]);+ 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'], ['guards', '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');diff --git a/test/pricing-eval-plan.test.ts b/test/pricing-eval-plan.test.tsindex d6e8e413a..bba955cc5 100644--- a/test/pricing-eval-plan.test.ts+++ b/test/pricing-eval-plan.test.ts@@ -3,16 +3,19 @@* /eval-plan machinery in lib/eval-plan.ts: preregistration check, priced arms,* the $0 dry run, and the priced pilot ledger with its spend table.*/-import { afterEach, describe, expect, test } from 'bun:test';+import { afterEach, beforeEach, describe, expect, test } from 'bun:test';+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 { EXCLUDED_BILLING_CATEGORIES, PRICING, estimateCostUsd, hasPricing, pricingRow } from '../lib/pricing';import * as helperPricing from './helpers/pricing';import {- PREREG_SECTIONS, checkPrereg, dryRun, pilotReport, preregTemplate, renderArms, renderDryRun, renderPilotReport, renderSpendTable,+ PREREG_SECTIONS, checkPrereg, dryRun, formatEvalCalls, parseEvalCalls, pilotReport, preregTemplate, renderArms, renderDryRun, renderPilotReport, renderSpendTable,resolveArms, settlePilot, startPilot,} from '../lib/eval-plan';+import { capyHost, type CapyHost } from './helpers/capy-host';const dirs: string[] = [];const tmp = () => { const d = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-eval-plan-')); dirs.push(d); return d; };@@ -156,3 +159,293 @@ describe('priced pilot', () => {expect(r.projection.verdict).toBe('unknown');});});++// ---------------------------------------------------------------------------+// CD2 (field wave item 15): paid gates priced from a call-plan DATA file.+// `price-gate` never executes anything: it validates the file's binding (gate+// command, head, input hashes at HEAD) and prices the GSTACK_EVAL_CALLS v1 rows.+// ---------------------------------------------------------------------------+const ROOT = path.resolve(import.meta.dir, '..');+const BIN = path.join(ROOT, 'bin', 'gstack-eval-plan');++function scratchRepo(env: Record<string, string>): { repo: string; head: string; rowsSha: string } {+ const repo = path.join(env.TMPDIR!, 'repo');+ fs.mkdirSync(repo, { recursive: true });+ const git = (...args: string[]) => {+ const r = spawnSync('git', args, { cwd: repo, env, encoding: 'utf8', timeout: 30_000 });+ if (r.status !== 0) throw new Error(`git ${args.join(' ')}: ${r.stderr}`);+ return r.stdout.trim();+ };+ git('init', '-q', '-b', 'main');+ fs.writeFileSync(path.join(repo, 'rows.jsonl'), JSON.stringify({ prompt: 'q1' }) + '\n');+ git('add', 'rows.jsonl');+ git('commit', '-q', '-m', 'rows');+ return { repo, head: git('rev-parse', 'HEAD'), rowsSha: createHash('sha256').update(fs.readFileSync(path.join(repo, 'rows.jsonl'))).digest('hex') };+}++const GATE = 'bun run eval:synopsis --questions 50 --arms opus,sol';+const twoRows = [+ { purpose: 'answer', model: 'anthropic/claude-opus-5-5', calls: 100, in_tokens: 400_000, out_tokens: 200_000, max_out_tokens: 8_192, scope: 'full' as const },+ { purpose: 'judge', model: 'gpt-6.1-sol', calls: 100, in_tokens: 300_000, out_tokens: 50_000, max_out_tokens: 2_048, scope: 'full' as const },+];++function runGate(host: CapyHost, cwd: string, args: string[], extraEnv: Record<string, string> = {}) {+ const r = spawnSync(BIN, ['price-gate', ...args], { cwd, env: { ...host.env, ...extraEnv }, encoding: 'utf8', timeout: 30_000 });+ return { code: r.status, out: r.stdout ?? '', err: r.stderr ?? '' };+}++describe('price-gate: the call-plan file format (formatEvalCalls / parseEvalCalls)', () => {+ test('the reference emitter round-trips: binding lines, preconditions, call lines and the end line', () => {+ const plan = { gate: GATE, head: 'a'.repeat(40), inputs: [{ path: 'rows.jsonl', sha256: 'b'.repeat(64) }], preconditions: ['ANTHROPIC_API_KEY set at run time'], rows: twoRows };+ const text = formatEvalCalls(plan);+ expect(text).toContain(`GSTACK_EVAL_GATE v1: ${GATE}\n`);+ expect(text).toContain('GSTACK_EVAL_CALLS v1: purpose=answer model=anthropic/claude-opus-5-5 calls=100 in_tokens=400000 out_tokens=200000 max_out_tokens=8192 scope=full\n');+ expect(text.trimEnd().split('\n').at(-1)).toBe('GSTACK_EVAL_CALLS v1 end: lines=2');+ const parsed = parseEvalCalls(text);+ expect('plan' in parsed && parsed.plan).toEqual(plan);+ });++ test('a malformed, partial or unknown-version file refuses and names the line', () => {+ const good = formatEvalCalls({ gate: GATE, head: 'a'.repeat(40), inputs: [], preconditions: [], rows: twoRows });+ const err = (text: string) => { const r = parseEvalCalls(text); return 'error' in r ? r.error : ''; };+ expect(err(good.replace(/\nGSTACK_EVAL_CALLS v1 end: lines=2\n$/, '\n'))).toMatch(/end line/);+ expect(err(good.replace('end: lines=2', 'end: lines=3'))).toMatch(/lines=3.*2 call lines/);+ expect(err(good.replace('calls=100 in_tokens=400000', 'calls=1e2 in_tokens=400000'))).toMatch(/line 4.*calls/);+ expect(err(good.replace('scope=full\nGSTACK_EVAL_CALLS v1: purpose=judge', 'scope=full extra=1\nGSTACK_EVAL_CALLS v1: purpose=judge'))).toMatch(/line 4.*extra/);+ expect(err(good.replace(' max_out_tokens=8192', ''))).toMatch(/line 4.*max_out_tokens/);+ expect(err(good.replace('GSTACK_EVAL_CALLS v1: purpose=judge', 'GSTACK_EVAL_CALLS v2: purpose=judge'))).toMatch(/line 5.*version/);+ expect(err(good + 'GSTACK_EVAL_PRECONDITION: after the end\n')).toMatch(/after the end line/);+ expect(err(good.replace(/^GSTACK_EVAL_HEAD.*\n/m, ''))).toMatch(/GSTACK_EVAL_HEAD/);+ });+});++describe('price-gate: binding, pricing and the receipt (bin, simulated Capy host)', () => {+ let host: CapyHost;+ beforeEach(() => { host = capyHost(); });+ afterEach(() => host.cleanup());++ function writePlan(repo: string, plan: Parameters<typeof formatEvalCalls>[0]): string {+ const file = path.join(host.base, 'plan.calls');+ fs.writeFileSync(file, formatEvalCalls(plan));+ return file;+ }++ test('two call lines and one precondition are priced and listed, and the receipt binds price to gate, head, inputs and plan bytes', () => {+ const { repo, head, rowsSha } = scratchRepo(host.env);+ const file = writePlan(repo, { gate: GATE, head, inputs: [{ path: 'rows.jsonl', sha256: rowsSha }], preconditions: ['ANTHROPIC_API_KEY and OPENAI_API_KEY set at run time'], rows: twoRows });+ const out = path.join(host.base, 'receipts');+ const r = runGate(host, repo, ['--plan-file', file, '--gate', GATE, '--cap-usd', '20', '--out', out]);+ expect(r.err).toBe('');+ expect(r.code).toBe(0);+ // opus-5-5: 0.4 MTok × $4 + 0.2 MTok × $20 = $5.60; sol: 0.3 × $2 + 0.05 × $10 = $1.10+ expect(r.out).toContain('GATE_CALLS: purpose=answer model=anthropic/claude-opus-5-5 calls=100 usd=5.6 reservation_usd=0.17984 scope=full');+ expect(r.out).toContain('GATE_CALLS: purpose=judge model=gpt-6.1-sol calls=100 usd=1.1 reservation_usd=0.02648 scope=full');+ expect(r.out).toContain('GATE_PRECONDITION: ANTHROPIC_API_KEY and OPENAI_API_KEY set at run time');+ const price = r.out.split('\n').find(l => l.startsWith('GATE_PRICE: '))!;+ expect(price).toMatch(/^GATE_PRICE: total=6\.7 calls=200 purposes=answer,judge receipt=\S+$/);+ const receiptPath = price.split('receipt=')[1]!;+ expect(path.dirname(receiptPath)).toBe(out);+ const receipt = JSON.parse(fs.readFileSync(receiptPath, 'utf8'));+ expect(receipt).toMatchObject({+ schema_version: 1, result: 'priced', code: null, gate_command: GATE, gate_sha256: createHash('sha256').update(GATE).digest('hex'),+ head_sha: head, plan: { file, source: 'flag', declared_head: head, sha256: createHash('sha256').update(fs.readFileSync(file)).digest('hex') },+ inputs: [{ path: 'rows.jsonl', sha256: rowsSha }], total_usd: 6.7, calls: 200, cap_usd: 20, unpriced_override: null,+ });+ expect(typeof receipt.gstack_revision).toBe('string');+ });++ test('--gate-file prices the gate command the agent wrote to a file, byte for byte as --gate does; empty, missing or both refuse', () => {+ const { repo, head, rowsSha } = scratchRepo(host.env);+ const quoted = `${GATE} --label "it's \\"quoted\\" \\$HOME"`;+ const file = writePlan(repo, { gate: quoted, head, inputs: [{ path: 'rows.jsonl', sha256: rowsSha }], preconditions: [], rows: twoRows });+ const gateFile = path.join(host.base, 'gate-command.txt');+ fs.writeFileSync(gateFile, quoted + '\n');+ const viaFile = runGate(host, repo, ['--plan-file', file, '--gate-file', gateFile, '--out', path.join(host.base, 'a')]);+ expect(viaFile.err).toBe('');+ expect(viaFile.code).toBe(0);+ const viaFlag = runGate(host, repo, ['--plan-file', file, '--gate', quoted, '--out', path.join(host.base, 'b')]);+ const total = (out: string) => out.split('\n').find(l => l.startsWith('GATE_PRICE: '))!.replace(/ receipt=.*/, '');+ expect(total(viaFile.out)).toBe(total(viaFlag.out));+ const receipt = JSON.parse(fs.readFileSync(viaFile.out.split('receipt=')[1]!.split('\n')[0]!, 'utf8'));+ expect(receipt.gate_command).toBe(quoted);+ fs.writeFileSync(gateFile, '\n');+ expect(runGate(host, repo, ['--plan-file', file, '--gate-file', gateFile]).code).toBe(2);+ expect(runGate(host, repo, ['--plan-file', file, '--gate-file', path.join(host.base, 'absent')]).code).toBe(2);+ expect(runGate(host, repo, ['--plan-file', file, '--gate', quoted, '--gate-file', gateFile]).code).toBe(2);+ });++ test('the base policy price_file is read from the HEAD commit; a plan committed on top of its own head stays fresh until another file changes', () => {+ const { repo, rowsSha } = scratchRepo(host.env);+ const git = (...args: string[]) => spawnSync('git', args, { cwd: repo, env: host.env, encoding: 'utf8', timeout: 30_000 }).stdout.trim();+ fs.mkdirSync(path.join(repo, '.gstack'), { recursive: true });+ fs.writeFileSync(path.join(repo, '.gstack', 'pregate.json'), JSON.stringify({ price_file: 'evals/gate.calls' }));+ git('add', '.gstack/pregate.json'); git('commit', '-q', '-m', 'policy');+ const produced = git('rev-parse', 'HEAD');+ git('update-ref', 'refs/remotes/origin/main', produced);+ fs.mkdirSync(path.join(repo, 'evals'));+ fs.writeFileSync(path.join(repo, 'evals', 'gate.calls'), formatEvalCalls({ gate: GATE, head: produced, inputs: [{ path: 'rows.jsonl', sha256: rowsSha }], preconditions: [], rows: twoRows }));+ git('add', 'evals/gate.calls'); git('commit', '-q', '-m', 'call plan');+ const out = path.join(host.base, 'receipts');+ let r = runGate(host, repo, ['--gate', GATE, '--base', 'main', '--out', out]);+ expect(r.err).toBe('');+ expect(r.code).toBe(0);+ expect(r.out).toContain(`GATE_PLAN: file=evals/gate.calls source=price_file`);+ expect(r.out).toContain('only the plan file changed since');+ const receipt = JSON.parse(fs.readFileSync(r.out.split('receipt=')[1]!.split('\n')[0]!, 'utf8'));+ expect(receipt).toMatchObject({ plan: { source: 'price_file', declared_head: produced }, head_sha: git('rev-parse', 'HEAD'), total_usd: 6.7 });+ fs.writeFileSync(path.join(repo, 'README.md'), 'later\n');+ git('add', 'README.md'); git('commit', '-q', '-m', 'later');+ r = runGate(host, repo, ['--gate', GATE, '--base', 'main', '--out', out]);+ expect(r.code).toBe(1);+ expect(r.err).toMatch(/behind HEAD.*README\.md.*\(EVAL_PLAN_STALE\)/);+ });++ test('a declared price_file missing at HEAD refuses EVAL_PLAN_STALE (not overridable); an unresolvable base or an invalid pregate.json exits 3', () => {+ const { repo } = scratchRepo(host.env);+ const git = (...args: string[]) => spawnSync('git', args, { cwd: repo, env: host.env, encoding: 'utf8', timeout: 30_000 }).stdout.trim();+ const out = path.join(host.base, 'receipts');+ let r = runGate(host, repo, ['--gate', GATE, '--base', 'main', '--out', out, '--allow-unpriced', 'owner said so']);+ expect(r.code).toBe(3);+ expect(r.err).toContain('(POLICY_SOURCE_UNAVAILABLE)');+ fs.mkdirSync(path.join(repo, '.gstack'), { recursive: true });+ fs.writeFileSync(path.join(repo, '.gstack', 'pregate.json'), JSON.stringify({ price_file: 'evals/missing.calls' }));+ git('add', '.gstack/pregate.json'); git('commit', '-q', '-m', 'policy');+ git('update-ref', 'refs/remotes/origin/main', git('rev-parse', 'HEAD'));+ r = runGate(host, repo, ['--gate', GATE, '--base', 'main', '--out', out, '--allow-unpriced', 'owner said so']);+ expect(r.code).toBe(1);+ expect(r.err).toMatch(/evals\/missing\.calls.*\(EVAL_PLAN_STALE\)/);+ expect(r.out).not.toContain('GATE_UNPRICED_OVERRIDE');+ fs.writeFileSync(path.join(repo, '.gstack', 'pregate.json'), JSON.stringify({ price_file: '../outside.calls' }));+ git('add', '.gstack/pregate.json'); git('commit', '-q', '-m', 'bad policy');+ git('update-ref', 'refs/remotes/origin/main', git('rev-parse', 'HEAD'));+ r = runGate(host, repo, ['--gate', GATE, '--base', 'main', '--out', out, '--allow-unpriced', 'owner said so']);+ expect(r.code).toBe(3);+ expect(r.err).toContain('(PREGATE_CONFIG_INVALID)');+ expect(fs.existsSync(out)).toBe(false);+ });++ test('an unknown or misspelled flag exits 2 instead of pricing without it', () => {+ const { repo } = scratchRepo(host.env);+ expect(runGate(host, repo, ['--gate', GATE, '--cap', '5']).code).toBe(2);+ expect(runGate(host, repo, ['--cap-usd', '5']).code).toBe(2);+ });++ test('nothing in the plan file is executed: a gate command and precondition that would create markers leave none', () => {+ const { repo, head, rowsSha } = scratchRepo(host.env);+ const marker = path.join(host.base, 'gate-ran');+ const gate = `touch ${marker}`;+ const file = writePlan(repo, { gate, head, inputs: [{ path: 'rows.jsonl', sha256: rowsSha }], preconditions: [`$(touch ${marker}-pre)`], rows: twoRows });+ const r = runGate(host, repo, ['--plan-file', file, '--gate', gate]);+ expect(r.code).toBe(0);+ expect(fs.existsSync(marker)).toBe(false);+ expect(fs.existsSync(`${marker}-pre`)).toBe(false);+ });++ test('a stale head, an input-hash mismatch and a gate-command mismatch each refuse EVAL_PLAN_STALE with no receipt', () => {+ const { repo, head, rowsSha } = scratchRepo(host.env);+ const out = path.join(host.base, 'receipts');+ const staleHead = writePlan(repo, { gate: GATE, head: 'f'.repeat(40), inputs: [{ path: 'rows.jsonl', sha256: rowsSha }], preconditions: [], rows: twoRows });+ let r = runGate(host, repo, ['--plan-file', staleHead, '--gate', GATE, '--out', out]);+ expect(r.code).toBe(1);+ expect(r.err).toMatch(/head .*ffffffffffff.*\(EVAL_PLAN_STALE\)/);+ const badInput = writePlan(repo, { gate: GATE, head, inputs: [{ path: 'rows.jsonl', sha256: '0'.repeat(64) }], preconditions: [], rows: twoRows });+ r = runGate(host, repo, ['--plan-file', badInput, '--gate', GATE, '--out', out]);+ expect(r.code).toBe(1);+ expect(r.err).toMatch(/rows\.jsonl.*sha256.*\(EVAL_PLAN_STALE\)/);+ const good = writePlan(repo, { gate: GATE, head, inputs: [{ path: 'rows.jsonl', sha256: rowsSha }], preconditions: [], rows: twoRows });+ r = runGate(host, repo, ['--plan-file', good, '--gate', `${GATE} --questions 500`, '--out', out]);+ expect(r.code).toBe(1);+ expect(r.err).toMatch(/gate command.*\(EVAL_PLAN_STALE\)/);+ expect(fs.existsSync(out)).toBe(false);+ });++ test('malformed, partial (no end line) and empty-of-binding files refuse EVAL_DRY_RUN_FAILED naming the line', () => {+ const { repo, head } = scratchRepo(host.env);+ const file = writePlan(repo, { gate: GATE, head, inputs: [], preconditions: [], rows: twoRows });+ fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace(/GSTACK_EVAL_CALLS v1 end: lines=2\n$/, ''));+ let r = runGate(host, repo, ['--plan-file', file, '--gate', GATE]);+ expect(r.code).toBe(1);+ expect(r.err).toMatch(/end line.*\(EVAL_DRY_RUN_FAILED\)/);+ fs.writeFileSync(file, formatEvalCalls({ gate: GATE, head, inputs: [], preconditions: [], rows: twoRows }).replace('calls=100', 'calls=lots'));+ r = runGate(host, repo, ['--plan-file', file, '--gate', GATE]);+ expect(r.code).toBe(1);+ expect(r.err).toMatch(/line \d+.*calls.*\(EVAL_DRY_RUN_FAILED\)/);+ });++ test('no plan file, or a file with no call lines, is EVAL_GATE_UNPRICED exit 1; --allow-unpriced exits 0 with a recorded override', () => {+ const { repo, head, rowsSha } = scratchRepo(host.env);+ spawnSync('git', ['update-ref', 'refs/remotes/origin/main', head], { cwd: repo, env: host.env, timeout: 30_000 });+ const out = path.join(host.base, 'receipts');+ let r = runGate(host, repo, ['--gate', GATE, '--base', 'main', '--out', out]);+ expect(r.code).toBe(1);+ expect(r.err).toContain('(EVAL_GATE_UNPRICED)');+ const empty = writePlan(repo, { gate: GATE, head, inputs: [{ path: 'rows.jsonl', sha256: rowsSha }], preconditions: [], rows: [] });+ r = runGate(host, repo, ['--plan-file', empty, '--gate', GATE, '--out', out]);+ expect(r.code).toBe(1);+ expect(r.err).toContain('(EVAL_GATE_UNPRICED)');+ expect(r.out).toContain('GATE_PRICE: total=unknown calls=0 purposes=none');+ r = runGate(host, repo, ['--plan-file', empty, '--gate', GATE, '--out', out, '--allow-unpriced', 'owner accepts a bounded smoke on a seat']);+ expect(r.code).toBe(0);+ expect(r.out).toContain('GATE_UNPRICED_OVERRIDE: owner accepts a bounded smoke on a seat (owner-authorized override; not authorization to spend)');+ const receipt = JSON.parse(fs.readFileSync(r.out.split('receipt=')[1]!.split('\n')[0]!, 'utf8'));+ expect(receipt).toMatchObject({ result: 'unpriced_override', code: 'EVAL_GATE_UNPRICED', unpriced_override: 'owner accepts a bounded smoke on a seat', total_usd: null });+ });++ test('an unpriced model makes its row and the total unknown, never zero, and fails EVAL_PRICE_MISSING', () => {+ const { repo, head } = scratchRepo(host.env);+ const file = writePlan(repo, { gate: GATE, head, inputs: [], preconditions: [], rows: [twoRows[0]!, { ...twoRows[1]!, model: 'acme/made-up-model' }] });+ const r = runGate(host, repo, ['--plan-file', file, '--gate', GATE]);+ expect(r.code).toBe(1);+ expect(r.out).toContain('GATE_CALLS: purpose=judge model=acme/made-up-model calls=100 usd=unknown reservation_usd=unknown scope=full');+ expect(r.out).toMatch(/GATE_PRICE: total=unknown calls=200 /);+ expect(r.err).toContain('(EVAL_PRICE_MISSING)');+ });++ test('a total above --cap-usd is EVAL_GATE_OVER_CAP; a single-call reservation above the cap or the smoke cap fails reservation-fits-cap', () => {+ const { repo, head } = scratchRepo(host.env);+ const file = writePlan(repo, { gate: GATE, head, inputs: [], preconditions: [], rows: twoRows });+ let r = runGate(host, repo, ['--plan-file', file, '--gate', GATE, '--cap-usd', '5']);+ expect(r.code).toBe(1);+ expect(r.err).toMatch(/6\.7.*cap \$5.*\(EVAL_GATE_OVER_CAP\)/);+ const smoke = writePlan(repo, { gate: GATE, head, inputs: [], preconditions: [], rows: [{ purpose: 'smoke-answer', model: 'claude-opus-5-5', calls: 2, in_tokens: 20_000, out_tokens: 4_000, max_out_tokens: 64_000, scope: 'smoke' }] });+ // one call: 10,000 in × $4 + 64,000 out × $20 per MTok = $1.32, under the $10 cap but over the $1 smoke cap+ r = runGate(host, repo, ['--plan-file', smoke, '--gate', GATE, '--cap-usd', '10', '--smoke-cap-usd', '1']);+ expect(r.code).toBe(1);+ expect(r.out).toContain('CHECK: reservation-fits-cap exceeds ($1.3200 > smoke cap $1.00) purpose=smoke-answer');+ expect(r.err).toContain('(EVAL_GATE_OVER_CAP)');+ r = runGate(host, repo, ['--plan-file', smoke, '--gate', GATE, '--cap-usd', '1.2']);+ expect(r.code).toBe(1);+ expect(r.out).toContain('CHECK: reservation-fits-cap exceeds ($1.3200 > cap $1.20) purpose=smoke-answer');+ });+});++describe('dry-run reservation-fits-cap', () => {+ test('with --cap, one call per arm (largest row input + output budget), priced, must fit under the cap', () => {+ const d = tmp();+ const rows = path.join(d, 'rows.jsonl');+ fs.writeFileSync(rows, [JSON.stringify({ prompt: 'x'.repeat(4_000) }), JSON.stringify({ prompt: 'x'.repeat(40_000) })].join('\n') + '\n');+ const retry = path.join(d, 'retry.txt'); fs.writeFileSync(retry, 'retry\n');+ // largest row 10,000 tokens; one gpt-6-astra call = 10,000 × $10 + 8,192 × $50 per MTok = $0.5096+ const tight = dryRun({ input: rows, arms: ['gpt-6-astra'], retryPrompt: retry, cap: 0.5 });+ expect(tight.checks.reservation_fits_cap).toMatchObject({ ok: false, cap: 0.5, max_input_tokens: 10_000 });+ expect(tight.checks.reservation_fits_cap!.per_arm['gpt-6-astra']).toBeCloseTo(0.5096, 6);+ expect(tight.pass).toBe(false);+ expect(renderDryRun(tight)).toContain('CHECK: reservation-fits-cap exceeds ($0.5096 > cap $0.50)');+ const roomy = dryRun({ input: rows, arms: ['gpt-6-astra'], retryPrompt: retry, cap: 1 });+ expect(roomy.checks.reservation_fits_cap!.ok).toBe(true);+ expect(roomy.pass).toBe(true);+ expect(dryRun({ input: rows, arms: ['gpt-6-astra'], retryPrompt: retry }).checks.reservation_fits_cap).toBeUndefined();+ });+});++describe('pricing rows with fetched sources (2026-10-12)', () => {+ test('the newest Sonnet, the newest Gemini Flash and gbrain embedding models are priced; Opus 4.7 is at its current list price', () => {+ expect(hasPricing('anthropic/claude-sonnet-5-5')).toBe(true);+ expect(estimateCostUsd({ input: 1_000_000, output: 1_000_000 }, 'claude-sonnet-5-5')).toBe(12);+ expect(estimateCostUsd({ input: 1_000_000, output: 1_000_000 }, 'claude-opus-4-7')).toBe(30);+ expect(hasPricing('google/gemini-3.8-flash')).toBe(true);+ for (const m of ['voyage:voyage-4', 'openai:text-embedding-3-large', 'text-embedding-3-small', 'gemini-embedding-2']) expect(hasPricing(m)).toBe(true);+ expect(estimateCostUsd({ input: 1_000_000, output: 0 }, 'voyage:voyage-4')).toBe(0.06);+ expect(hasPricing('voyage-4-nano')).toBe(false);+ });+});diff --git a/test/restamp-command-boundary.test.ts b/test/restamp-command-boundary.test.tsindex ca26b5ac2..475a0d665 100644--- a/test/restamp-command-boundary.test.ts+++ b/test/restamp-command-boundary.test.ts@@ -134,3 +134,72 @@ describe('release-tool contract', () => {expect(repo.git('worktree', 'list').split('\n')).toHaveLength(1);});});++describe('restamp_command (field wave CD3): the repo owns the stamp inside the staging worktree', () => {+ const RESTAMP_JS = [+ "const fs = require('fs'); const { execSync } = require('child_process');",+ "if (execSync('git status --porcelain', { encoding: 'utf8', timeout: 30000 }).trim()) { console.error('FAIL: the working tree is not clean'); process.exit(1); }",+ "const v = process.argv[2];",+ "if (!v || v !== process.env.GSTACK_RESTAMP_VERSION) { console.error('version argument and GSTACK_RESTAMP_VERSION disagree'); process.exit(2); }",+ "if (process.env.FIXTURE_FAIL) process.exit(7);",+ "fs.writeFileSync('VERSION', (process.env.FIXTURE_WRONG_VERSION ? '9.9.9.9' : v) + '\\n');",+ "const pkg = JSON.parse(fs.readFileSync('package.json', 'utf8')); pkg.version = v.split('.').slice(0, 3).join('.'); fs.writeFileSync('package.json', JSON.stringify(pkg, null, 2) + '\\n');",+ "fs.writeFileSync('generated/digest.md', '# digest v' + v + '\\nbody\\n');",+ "if (process.env.FIXTURE_STRAY) fs.writeFileSync('stray.txt', 'x\\n');",+ "execSync('git add -A', { timeout: 30000 }); execSync('git -c user.name=r -c [email protected] -c commit.gpgsign=false commit -q -m restamp', { timeout: 30000 });",+ ].join('\n') + '\n';+ const POLICY = { ...BASE_POLICY, release_tool: null, restamp_command: 'node restamp.js' };++ function delegated(): FixtureRepo {+ const repo = fixture({ policy: POLICY });+ fs.writeFileSync(path.join(repo.work, 'restamp.js'), RESTAMP_JS);+ repo.git('add', 'restamp.js'); repo.git('commit', '-q', '-m', 'repo restamp tool'); repo.git('push', '-q', 'origin', 'main');+ makePr(repo, 'feat-a');+ return repo;+ }++ test('it runs first, on a clean checkout of HEAD, with the allocated version as argument and GSTACK_RESTAMP_VERSION; gstack\'s version writer is skipped', () => {+ const repo = delegated();+ const r = runBin(repo, 'gstack-restamp', ['--next', '--base', 'main', '--allow-repo-commands']);+ expect(r.status).toBe(EXIT.ok);+ expect(r.out).toContain('STAMP_VERSION: 1.2.4.0');+ expect(r.out).toContain('stage restamp_command: done (node restamp.js 1.2.4.0)');+ expect(r.out).toContain('stage version: skipped (restamp_command owns the version)');+ expect(r.out.indexOf('stage restamp_command:')).toBeLessThan(r.out.indexOf('stage version:'));+ expect(fs.readFileSync(path.join(repo.work, 'VERSION'), 'utf8')).toBe('1.2.4.0\n');+ expect(fs.readFileSync(path.join(repo.work, 'generated', 'digest.md'), 'utf8')).toBe('# digest v1.2.4.0\nbody\n');+ expect(repo.git('worktree', 'list').split('\n')).toHaveLength(1);+ });++ test('a failure, a wrong version, an output outside the allowed set or a dirty caller tree writes nothing to the branch', () => {+ const cases: Array<[Record<string, string>, RegExp, number]> = [+ [{ FIXTURE_FAIL: '1' }, /restamp_command exited 7.*nothing written to the branch.*\(RESTAMP_RELEASE_TOOL_FAILED\)/, EXIT.refused],+ [{ FIXTURE_WRONG_VERSION: '1' }, /restamp_command left VERSION at 9\.9\.9\.9, expected 1\.2\.4\.0.*nothing written.*\(RESTAMP_VERSION_SOURCE\)/, EXIT.refused],+ [{ FIXTURE_STRAY: '1' }, /restamp_command wrote outside the allowed set: stray\.txt.*\(RESTAMP_OUTPUT_OUTSIDE_ALLOWED\)/, EXIT.refused],+ ];+ for (const [env, err, status] of cases) {+ const repo = delegated();+ const before = treeOf(repo);+ const r = runBin(repo, 'gstack-restamp', ['--next', '--base', 'main', '--allow-repo-commands'], env);+ expect(r.status).toBe(status);+ expect(r.err).toMatch(err);+ expect(treeOf(repo)).toBe(before);+ expect(fs.readFileSync(path.join(repo.work, 'VERSION'), 'utf8')).toBe('1.2.3.0\n');+ }+ const dirty = delegated();+ fs.writeFileSync(path.join(dirty.work, 'notes.txt'), 'uncommitted\n');+ const before = treeOf(dirty);+ const d = runBin(dirty, 'gstack-restamp', ['--next', '--base', 'main', '--allow-repo-commands']);+ expect(d.status).toBe(EXIT.fail);+ expect(d.err).toMatch(/restamp_command needs a clean HEAD, index and worktree.*notes\.txt.*nothing written.*\(RESTAMP_CONFLICT\)/);+ expect(treeOf(dirty)).toBe(before);+ expect(fs.existsSync(journal(dirty))).toBe(false);+ });++ test('without --allow-repo-commands it is listed and refused like release_tool', () => {+ const repo = delegated();+ const r = runBin(repo, 'gstack-restamp', ['--next', '--base', 'main']);+ expect(r.status).toBe(EXIT.refused);+ expect(r.out).toContain('COMMAND: restamp_command="node restamp.js" cwd=.');+ });+});diff --git a/test/sealed-guard.test.ts b/test/sealed-guard.test.tsnew file mode 100644index 000000000..1fff7c24f--- /dev/null+++ b/test/sealed-guard.test.ts@@ -0,0 +1,223 @@+/**+ * Field wave CD4: the sealed-output guard. A repo that declares `sealed` in+ * `.gstack/pregate.json` cannot push sealed or eval output to a public+ * destination by accident: the managed pre-push hook and+ * `gstack-pregate sealed` enumerate every commit the push publishes (local+ * sha minus everything the destination remote already has), apply path+ * rules to every added, renamed or copied path (binary and empty files,+ * add-then-delete) and text rules to each commit's added lines. The policy+ * is the union of the base branch's and the pushed one; waivers come only+ * from the base branch's allow file; an unknown visibility counts as public.+ * Field incident: a per-cell transcript, a quoted sealed answer, a seed and a+ * /home/user path were pushed to a public eval repo with exit 0 and no output.+ */+import { afterEach, describe, expect, test } from 'bun:test';+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 { resolveVisibility } from '../lib/sealed-guard';++const ROOT = path.resolve(import.meta.dir, '..');+const PREPUSH = path.join(ROOT, 'bin', 'gstack-redact-prepush');+const PREGATE = path.join(ROOT, 'bin', 'gstack-pregate');+const ZERO = '0'.repeat(40);+const SEALED = {+ paths: ['heldout/**'],+ transcripts: ['runs/**/transcript*.jsonl'],+ answer_markers: ['SEALED ANSWER:'],+ seed_patterns: ['shuffle_seed=\\d+'],+ local_paths: true,+};++interface Scratch { root: string; work: string; origin: string; state: string; env: Record<string, string> }+const scratches: Scratch[] = [];+afterEach(() => { while (scratches.length) fs.rmSync(scratches.pop()!.root, { recursive: true, force: true }); });++function sh(cwd: string, env: Record<string, string>, args: string[]): string {+ const r = spawnSync('git', args, { cwd, encoding: 'utf8', timeout: 30_000, env: { ...process.env, ...env } });+ if (r.status !== 0) throw new Error(`git ${args.join(' ')}: ${r.stderr}`);+ return (r.stdout ?? '').trim();+}++/** A bare origin with main carrying the given base files, and a clone on branch `results`. */+function scratch(baseFiles: Record<string, string | Buffer>): Scratch {+ const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'sealed-guard-')));+ const work = path.join(root, 'work'); const origin = path.join(root, 'origin.git'); const state = path.join(root, 'state');+ fs.mkdirSync(work); fs.mkdirSync(state);+ const env = { HOME: root, GSTACK_HOME: state, GSTACK_STATE_ROOT: state, GIT_CONFIG_GLOBAL: path.join(root, 'gitconfig'), GIT_CONFIG_NOSYSTEM: '1' };+ fs.writeFileSync(env.GIT_CONFIG_GLOBAL, '[user]\n\tname = t\n\temail = [email protected]\n[commit]\n\tgpgsign = false\n[init]\n\tdefaultBranch = main\n');+ spawnSync('git', ['init', '-q', '--bare', origin], { env: { ...process.env, ...env }, timeout: 30_000 });+ sh(work, env, ['init', '-q', '-b', 'main']);+ write(work, { 'README.md': '# evals\n', ...baseFiles });+ sh(work, env, ['add', '-A']); sh(work, env, ['commit', '-q', '-m', 'base']);+ sh(work, env, ['remote', 'add', 'origin', origin]);+ sh(work, env, ['push', '-q', 'origin', 'main']);+ sh(work, env, ['remote', 'set-head', 'origin', 'main']);+ sh(work, env, ['checkout', '-q', '-b', 'results']);+ const s = { root, work, origin, state, env };+ scratches.push(s);+ return s;+}+function write(work: string, files: Record<string, string | Buffer | null>): void {+ for (const [rel, body] of Object.entries(files)) {+ const abs = path.join(work, rel);+ if (body === null) { fs.rmSync(abs, { force: true }); continue; }+ fs.mkdirSync(path.dirname(abs), { recursive: true });+ fs.writeFileSync(abs, body);+ }+}+function commit(s: Scratch, files: Record<string, string | Buffer | null>, msg = 'results'): string {+ write(s.work, files);+ sh(s.work, s.env, ['add', '-A']); sh(s.work, s.env, ['commit', '-q', '-m', msg]);+ return sh(s.work, s.env, ['rev-parse', 'HEAD']);+}+const policy = (sealed: unknown) => JSON.stringify({ sealed }, null, 2) + '\n';++/** Drive the hook exactly as git does for `git push origin results` (a new remote branch). */+function hook(s: Scratch, extraEnv: Record<string, string> = {}) {+ const head = sh(s.work, s.env, ['rev-parse', 'HEAD']);+ const r = spawnSync('bun', [PREPUSH, 'origin', s.origin], { cwd: s.work, input: `refs/heads/results ${head} refs/heads/results ${ZERO}\n`, encoding: 'utf8', timeout: 60_000, env: { ...process.env, ...s.env, ...extraEnv } });+ return { code: r.status, err: r.stderr ?? '' };+}++describe('pre-push hook: public destination refuses each kind of sealed output', () => {+ test('a transcript, a sealed answer, a seed and a local home path each refuse, naming file, line and rule, never the matched text', () => {+ const cases: Array<[Record<string, string | Buffer>, string, RegExp]> = [+ [{ 'runs/cat40/cell-07/transcript.jsonl': '{"q":"x"}\n' }, 'sealed.transcript', /sealed\.transcript\s+runs\/cat40\/cell-07\/transcript\.jsonl/],+ [{ 'runs/cat40/summary.md': 'intro\nSEALED ANSWER: fund-a led the round\n' }, 'sealed.answer', /sealed\.answer\s+runs\/cat40\/summary\.md:2/],+ [{ 'runs/cat40/summary.md': 'run with shuffle_seed=42\n' }, 'sealed.seed', /sealed\.seed\s+runs\/cat40\/summary\.md:1/],+ [{ 'runs/cat40/summary.md': 'raw at /home/user/.capy/work/evals/raw.jsonl\n' }, 'sealed.local_path', /sealed\.local_path\s+runs\/cat40\/summary\.md:1/],+ ];+ for (const [files, rule, where] of cases) {+ const s = scratch({ '.gstack/pregate.json': policy(SEALED) });+ commit(s, files);+ const r = hook(s);+ expect(r.code).toBe(1);+ expect(r.err).toMatch(where);+ expect(r.err).toContain(rule);+ expect(r.err).toContain('(SEALED_OUTPUT_REFUSED)');+ expect(r.err).toContain('sealed.visibility');+ expect(r.err).not.toContain('fund-a led');+ }+ });++ test('path rules ignore content: a binary file, an empty transcript, an add-then-delete and a rename into a sealed path all refuse', () => {+ const binary = scratch({ '.gstack/pregate.json': policy(SEALED) });+ commit(binary, { 'heldout/questions.bin': Buffer.from([0, 1, 2, 0, 255, 0]) });+ expect(hook(binary).err).toMatch(/sealed\.path\s+heldout\/questions\.bin/);+ const empty = scratch({ '.gstack/pregate.json': policy(SEALED) });+ commit(empty, { 'runs/c1/transcript.jsonl': '' });+ expect(hook(empty).code).toBe(1);+ const gone = scratch({ '.gstack/pregate.json': policy(SEALED) });+ const added = commit(gone, { 'runs/c1/transcript.jsonl': '{"q":1}\n' });+ commit(gone, { 'runs/c1/transcript.jsonl': null }, 'remove it again');+ const g = hook(gone);+ expect(g.code).toBe(1);+ expect(g.err).toContain(`sealed.transcript runs/c1/transcript.jsonl commit ${added.slice(0, 12)}`);+ const moved = scratch({ '.gstack/pregate.json': policy(SEALED) });+ commit(moved, { 'scratch/t.jsonl': '{"q":1}\n{"q":2}\n{"q":3}\n' });+ fs.mkdirSync(path.join(moved.work, 'heldout'));+ sh(moved.work, moved.env, ['mv', 'scratch/t.jsonl', 'heldout/t.jsonl']);+ sh(moved.work, moved.env, ['commit', '-q', '-m', 'move']);+ expect(hook(moved).err).toMatch(/sealed\.path\s+heldout\/t\.jsonl/);+ });++ test('commits the destination already has are not this push: a branch from main that only adds a doc passes', () => {+ const s = scratch({ 'runs/old/transcript.jsonl': '{"q":"published before the policy"}\n', '.gstack/pregate.json': policy(SEALED) });+ commit(s, { 'docs/notes.md': 'notes\n' });+ const r = hook(s);+ expect(r.code).toBe(0);+ expect(r.err).not.toContain('sealed.');+ });+});++describe('policy union, waivers, private destinations and fail-closed parsing', () => {+ test('a push can tighten the policy but never relax it: dropping the base sealed config does not let a transcript through', () => {+ const s = scratch({ '.gstack/pregate.json': policy(SEALED) });+ commit(s, { '.gstack/pregate.json': '{}\n', 'runs/c1/transcript.jsonl': '{}\n' });+ expect(hook(s).code).toBe(1);+ const tighten = scratch({ '.gstack/pregate.json': policy(SEALED) });+ commit(tighten, { '.gstack/pregate.json': policy({ ...SEALED, paths: ['heldout/**', 'cells/**'] }), 'cells/c1.json': '{}\n' });+ expect(hook(tighten).err).toMatch(/sealed\.path\s+cells\/c1\.json/);+ });++ test('a waiver counts only from the base branch allow file and is listed; the same line committed in the push is ignored', () => {+ const s = scratch({ '.gstack/pregate.json': policy(SEALED) });+ const sha = commit(s, { 'runs/c1/transcript.jsonl': '{}\n' });+ const allow = `# rule\tpath\tsha\treason\nsealed.transcript\truns/c1/transcript.jsonl\t${sha.slice(0, 12)}\tsynthetic fixture, no sealed content\n`;+ commit(s, { '.gstack/sealed-allow.tsv': allow });+ expect(hook(s).code).toBe(1);+ sh(s.work, s.env, ['checkout', '-q', 'main']);+ write(s.work, { '.gstack/sealed-allow.tsv': allow });+ sh(s.work, s.env, ['add', '-A']); sh(s.work, s.env, ['commit', '-q', '-m', 'allow']); sh(s.work, s.env, ['push', '-q', 'origin', 'main']);+ sh(s.work, s.env, ['checkout', '-q', 'results']);+ const r = hook(s);+ expect(r.code).toBe(0);+ expect(r.err).toContain('waived sealed.transcript runs/c1/transcript.jsonl');+ });++ test('a private destination (base override) warns and passes; a repo without the key sees no change; a malformed sealed policy refuses', () => {+ const priv = scratch({ '.gstack/pregate.json': policy({ ...SEALED, visibility: 'private' }) });+ commit(priv, { 'runs/c1/transcript.jsonl': '{}\n' });+ const p = hook(priv);+ expect(p.code).toBe(0);+ expect(p.err).toMatch(/warning.*sealed\.transcript\s+runs\/c1\/transcript\.jsonl/s);+ const none = scratch({});+ commit(none, { 'runs/c1/transcript.jsonl': '{}\n' });+ const n = hook(none);+ expect(n.code).toBe(0);+ expect(n.err).not.toContain('sealed');+ const bad = scratch({ '.gstack/pregate.json': policy(SEALED) });+ commit(bad, { '.gstack/pregate.json': policy({ paths: 'heldout/**' }), 'docs/x.md': 'x\n' });+ const b = hook(bad);+ expect(b.code).toBe(1);+ expect(b.err).toContain('(SEALED_OUTPUT_REFUSED)');+ expect(b.err).toContain('sealed policy');+ });+});++describe('gstack-pregate sealed (the standalone preflight before any push or PR creation)', () => {+ test('--range refuses the same findings with exit 1; the default range is what origin does not have yet', () => {+ const s = scratch({ '.gstack/pregate.json': policy(SEALED) });+ commit(s, { 'runs/c1/transcript.jsonl': '{}\n' });+ const run = (args: string[]) => spawnSync(PREGATE, ['sealed', ...args], { cwd: s.work, encoding: 'utf8', timeout: 60_000, env: { ...process.env, ...s.env } });+ const ranged = run(['--range', 'origin/main..HEAD', '--base', 'main']);+ expect(ranged.status).toBe(1);+ expect(ranged.stderr).toMatch(/sealed\.transcript\s+runs\/c1\/transcript\.jsonl/);+ expect(ranged.stdout).toMatch(/^SEALED: refused findings=1 commits=1 visibility=unknown \(counted public\)/m);+ const dflt = run(['--base', 'main']);+ expect(dflt.status).toBe(1);+ sh(s.work, s.env, ['push', '-q', 'origin', 'results']);+ const after = run(['--base', 'main']);+ expect(after.status).toBe(0);+ expect(after.stdout).toMatch(/^SEALED: clear findings=0 commits=0/m);+ });+});++describe('visibility (cache under the state root; unknown counts as public)', () => {+ test('a public answer is cached; a cached private answer older than an hour is re-queried before it can downgrade; a failed lookup is unknown', () => {+ const state = fs.mkdtempSync(path.join(os.tmpdir(), 'sealed-vis-'));+ try {+ let calls = 0;+ let answer: string | null = 'PUBLIC';+ const gh = () => { calls += 1; return answer === null ? { ok: false, out: '' } : { ok: true, out: JSON.stringify({ visibility: answer }) }; };+ const env = { GSTACK_STATE_ROOT: state };+ const t0 = Date.parse('2026-10-12T00:00:00Z');+ expect(resolveVisibility('https://github.com/acme-example/evals.git', { env, gh, now: t0 }).visibility).toBe('public');+ expect(resolveVisibility('https://github.com/acme-example/evals.git', { env, gh, now: t0 + 60_000 }).visibility).toBe('public');+ expect(calls).toBe(1);+ answer = 'PRIVATE';+ expect(resolveVisibility('[email protected]:acme-example/private-evals.git', { env, gh, now: t0 }).visibility).toBe('private');+ expect(resolveVisibility('[email protected]:acme-example/private-evals.git', { env, gh, now: t0 + 30 * 60_000 }).visibility).toBe('private');+ expect(calls).toBe(2);+ answer = null;+ const stale = resolveVisibility('[email protected]:acme-example/private-evals.git', { env, gh, now: t0 + 2 * 3600_000 });+ expect(calls).toBe(3);+ expect(stale.visibility).toBe('unknown');+ expect(resolveVisibility('/srv/git/evals.git', { env, gh, now: t0 }).visibility).toBe('unknown');+ expect(calls).toBe(3);+ expect(fs.existsSync(path.join(state, 'sealed-visibility.json'))).toBe(true);+ } finally { fs.rmSync(state, { recursive: true, force: true }); }+ });+});diff --git a/test/stamp-templates.test.ts b/test/stamp-templates.test.tsnew file mode 100644index 000000000..25aa244de--- /dev/null+++ b/test/stamp-templates.test.ts@@ -0,0 +1,80 @@+/**+ * Field wave CD3: which files count as stamps is the repo's rule. Ship policy+ * `stamp_files` is an explicit allowlist applied before any stamp rule;+ * `stamp_patterns` are literal templates with one `{version}` slot (no free+ * regex), shared by the restamp writer and the tree-receipt classifier.+ * Field incident: a pure gbrain restamp from 0.60.188.0 to 0.60.189.0 read+ * `TREE: changed` for 13 of 16 files because `since: '…'`, `"version": "…"`+ * and `<!-- …-stamp: … -->` were outside gstack's three built-in forms.+ */+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 { rewriteStamps } from '../lib/restamp';+import { validatePolicy } from '../lib/ship-policy';+import { BASE_POLICY, cleanup, makeFixtureRepo, makePr, runBin, type FixtureRepo } from './helpers/restamp-fixture';++const repos: FixtureRepo[] = [];+afterEach(() => { while (repos.length) cleanup(repos.pop()!); });++const TEMPLATES = ['"version": "{version}"', '<!-- x-plugin-tree-stamp: {version} -->', "since: '{version}'"];+const STAMP_POLICY = { ...BASE_POLICY, release_tool: null, stamp_paths: ['docs/**'], stamp_files: ['VERSION', 'package.json', 'plugin/**', 'src/notice.ts'], stamp_patterns: TEMPLATES };++function stampedFiles(v: string, docs = 'Added in v1.2.4.0.\n'): Record<string, string> {+ return {+ VERSION: `${v}\n`,+ 'plugin/.claude-plugin/plugin.json': `{\n "name": "x",\n "version": "${v}",\n "description": "d"\n}\n`,+ 'plugin/README.md': `# plugin\n<!-- x-plugin-tree-stamp: ${v} -->\n`,+ 'src/notice.ts': `export const ROWS = [\n { since: '${v}', key: 'k' },\n];\n`,+ 'docs/guide.md': docs,+ };+}+function commitFiles(repo: FixtureRepo, files: Record<string, string>, msg: string): string {+ for (const [rel, body] of Object.entries(files)) { fs.mkdirSync(path.dirname(path.join(repo.work, rel)), { recursive: true }); fs.writeFileSync(path.join(repo.work, rel), body); }+ const pkg = JSON.parse(fs.readFileSync(path.join(repo.work, 'package.json'), 'utf8'));+ pkg.version = files.VERSION!.trim().split('.').slice(0, 3).join('.');+ fs.writeFileSync(path.join(repo.work, 'package.json'), JSON.stringify(pkg, null, 2) + '\n');+ repo.git('add', '-A'); repo.git('commit', '-q', '-m', msg);+ return repo.git('rev-parse', 'HEAD');+}++describe('stamp templates (pure)', () => {+ test('rewriteStamps applies literal {version} templates beside the three built-in forms, at version boundaries only', () => {+ expect(rewriteStamps("{ since: '1.2.3.0', x }", '1.2.3.0', '1.2.4.0', ["since: '{version}'"])).toEqual({ text: "{ since: '1.2.4.0', x }", count: 1 });+ expect(rewriteStamps('"version": "1.2.3.0",', '1.2.3.0', '1.2.4.0', ['"version": "{version}"']).count).toBe(1);+ expect(rewriteStamps('<!-- x-plugin-tree-stamp: 1.2.3.0 -->', '1.2.3.0', '1.2.4.0', ['<!-- x-plugin-tree-stamp: {version} -->']).text).toBe('<!-- x-plugin-tree-stamp: 1.2.4.0 -->');+ expect(rewriteStamps("since: '1.2.3.01'", '1.2.3.0', '1.2.4.0', ["since: '{version}'"]).count).toBe(0);+ expect(rewriteStamps("since: '1.2.3.0'", '1.2.3.0', '1.2.4.0').count).toBe(0);+ });++ test('policy: stamp_patterns are bounded literal templates with exactly one {version}; stamp_files are contained globs', () => {+ const codes = (p: unknown) => validatePolicy(p).map(e => `${e.code}:${e.path}`);+ expect(codes(STAMP_POLICY)).toEqual([]);+ expect(codes({ stamp_patterns: ['no slot'] })).toEqual(['POLICY_INVALID:stamp_patterns[0]']);+ expect(codes({ stamp_patterns: ['{version} and {version}'] })).toEqual(['POLICY_INVALID:stamp_patterns[0]']);+ expect(codes({ stamp_patterns: ['x'.repeat(130) + '{version}'] })).toEqual(['POLICY_CONTAINMENT:stamp_patterns[0]']);+ expect(codes({ stamp_patterns: Array.from({ length: 17 }, (_, i) => `k${i}: {version}`) })).toEqual(['POLICY_CONTAINMENT:stamp_patterns']);+ expect(codes({ stamp_files: ['../VERSION'] })).toEqual(['POLICY_CONTAINMENT:stamp_files[0]']);+ });+});++describe('tree receipt under the repo stamp rule', () => {+ test('a pure restamp across a manifest, a stamp comment and a since row is same-modulo-stamps; a doc vX mention outside stamp_files is a difference', () => {+ const repo = makeFixtureRepo({ prefix: 'stamp-templates-', policy: STAMP_POLICY }); repos.push(repo);+ makePr(repo, 'pr-a', { changelog: false });+ const gated = commitFiles(repo, stampedFiles('1.2.4.0'), 'stamp 1.2.4.0');+ commitFiles(repo, stampedFiles('1.2.5.0'), 'restamp 1.2.5.0');+ const r = runBin(repo, 'gstack-tree-receipt', ['--base', 'main', '--gated', gated]);+ expect(r.out).toMatch(/^ {2}stamp {3}plugin\/\.claude-plugin\/plugin\.json \(stamp_files\)$/m);+ expect(r.out).toMatch(/^ {2}stamp {3}plugin\/README\.md \(stamp_files\)$/m);+ expect(r.out).toMatch(/^ {2}stamp {3}src\/notice\.ts \(stamp_files\)$/m);+ expect(r.out).toMatch(/^ {2}stamp {3}VERSION \(version-file\)$/m);+ expect(r.out).toMatch(/^TREE: same-modulo-stamps$/m);+ commitFiles(repo, stampedFiles('1.2.5.0', 'Added in v1.2.5.0.\n'), 'doc mention');+ const d = runBin(repo, 'gstack-tree-receipt', ['--base', 'main', '--gated', gated]);+ expect(d.status).toBe(EXIT.fail);+ expect(d.out).toMatch(/^ {2}changed docs\/guide\.md \(stamp_files: not in the repo's stamp_files allowlist\)$/m);+ expect(d.out).toMatch(/^TREE: changed \(docs\/guide\.md\)$/m);+ });+});