@rightkit/release 0.6.56 → 0.6.61

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/README.md +4 -0
  2. package/acceptance-admission.mjs +104 -0
  3. package/acceptance-launch.mjs +234 -0
  4. package/acceptance-lines.mjs +1254 -0
  5. package/acceptance-result.mjs +77 -0
  6. package/acceptance-rows.mjs +47 -0
  7. package/admission-files.mjs +2 -0
  8. package/affected-units.mjs +17 -0
  9. package/app-check.mjs +6 -2
  10. package/app-closure.mjs +3 -1
  11. package/bin/rightkit-gate.mjs +546 -121
  12. package/broker-admission.mjs +45 -2
  13. package/broker-pins.mjs +11 -1
  14. package/broker-toolchain.mjs +113 -0
  15. package/cargo-profile-contract.mjs +7 -2
  16. package/class-a-cache-history.mjs +135 -0
  17. package/cli/right-release.mjs +0 -0
  18. package/code-closure.mjs +24 -0
  19. package/config-inspect.mjs +6 -0
  20. package/consumer-contracts.mjs +3 -1
  21. package/contract-nn.json +166 -0
  22. package/deterministic-scans.mjs +835 -112
  23. package/feature-coverage.mjs +109 -82
  24. package/feature-partition.mjs +76 -0
  25. package/forbidden-literals.mjs +78 -0
  26. package/gate/calls.mjs +121 -0
  27. package/gate/compile.mjs +190 -0
  28. package/gate/crate-results.mjs +127 -0
  29. package/gate/run-calls.mjs +241 -0
  30. package/gate/tests.mjs +234 -0
  31. package/gate-coverage.mjs +12 -3
  32. package/gate-release-admission.mjs +200 -0
  33. package/gate-seam.mjs +100 -4
  34. package/gate-serve.mjs +178 -32
  35. package/gate-stages.mjs +59 -0
  36. package/legacy-contract-receipt.mjs +809 -0
  37. package/local-publish.mjs +7 -5
  38. package/local-runtime.mjs +2 -2
  39. package/nsis-payload.mjs +4 -3
  40. package/ownership-applicability.mjs +5 -0
  41. package/ownership-class-rules.mjs +19 -8
  42. package/ownership-mandatory-set.json +15 -21
  43. package/ownership-mandatory-set.mjs +19 -4
  44. package/package.json +14 -8
  45. package/probe-memo.mjs +252 -0
  46. package/publication-artifacts.mjs +56 -2
  47. package/publish-local-npm.mjs +3 -0
  48. package/publish-update.mjs +2 -2
  49. package/receipt-signature.mjs +40 -0
  50. package/release.mjs +47 -29
  51. package/resident-answers.mjs +66 -0
  52. package/rightkit-ownership.json +20 -11
  53. package/rightkit-versions.json +349 -183
  54. package/runtime-bundle-stage.mjs +146 -0
  55. package/scan-digest.mjs +28 -4
  56. package/seam-broker.mjs +8 -1
  57. package/shell-contract.mjs +23 -2
  58. package/snapshot-changes.mjs +106 -0
  59. package/snapshot-check.mjs +17 -13
  60. package/snapshot-dependency-reuse.mjs +186 -14
  61. package/snapshot-git.mjs +17 -1
  62. package/snapshot-metadata.mjs +155 -3
  63. package/snapshot.mjs +90 -12
  64. package/spawn-ledger.mjs +21 -2
  65. package/stage-sidecar.mjs +231 -19
  66. package/suite-trust-roots.mjs +2 -2
  67. package/test-env.mjs +26 -0
  68. package/tool-version-memo.mjs +46 -0
  69. package/win-package-recipe.mjs +11 -0
  70. package/bin/darwin/rightkit-swap +0 -0
  71. package/gate-acceptance.mjs +0 -3362
@@ -0,0 +1,809 @@
1
+ // The reading of the old contract-test receipt (rightkit.contract-test-receipt/1), kept so results sealed before the twelve-line test stay readable
2
+ // (docs/GATE-CONTRACT.md GC-A27, rightkit#1514 step 9). Copied from the retired runner gate-acceptance.mjs (last at 1e478405c): the declarations
3
+ // gate-release-admission.mjs needs, and the ones they use, without the three that named the runner's own files (BUDGETS_FILE, RUNNER_FILE,
4
+ // runnerFileHashes): their hashes are `retiredRunner` in contract-nn.json. Nothing here runs a contract test.
5
+ import { createHash, randomBytes } from "node:crypto";
6
+ import { spawn, spawnSync } from "node:child_process";
7
+ import fs from "node:fs";
8
+ import path from "node:path";
9
+ import { fileURLToPath } from "node:url";
10
+ import { keyPath, repoKey } from "./snapshot.mjs";
11
+
12
+ const RECEIPT_SCHEMA = "rightkit.gate-receipt/1";
13
+
14
+ const SOURCE_IDENTITY_SCHEMA = "rightkit.source-identity.v1";
15
+
16
+ const RENDER_RECEIPT_SCHEMA = "rightkit.render-views/1";
17
+
18
+ const here = path.dirname(fileURLToPath(import.meta.url));
19
+
20
+ const sha256 = (data) => createHash("sha256").update(data).digest("hex");
21
+
22
+ const isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
23
+
24
+ const isSha = (v) => typeof v === "string" && /^[0-9a-f]{64}$/.test(v);
25
+
26
+ const isCommit = (v) => typeof v === "string" && /^[0-9a-f]{40}$/.test(v);
27
+
28
+ const NEEDS_FIXTURE = "needs fixture rows (criteria.md section 2, F1-F14) that do not exist in the witness fixture yet";
29
+
30
+ const NEEDS_INSTALL_APPROVAL = "needs install approval";
31
+
32
+ /** Unknown or missing keys of `obj` against `{ required, optional }`; fail closed on both. */
33
+ function strictKeys(obj, { required = [], optional = [] }, where) {
34
+ if (!isObject(obj)) return [`${where}: not an object`];
35
+ const problems = [];
36
+ for (const k of required) if (!(k in obj)) problems.push(`${where}: missing field "${k}"`);
37
+ const known = new Set([...required, ...optional]);
38
+ for (const k of Object.keys(obj)) if (!known.has(k)) problems.push(`${where}: unknown field "${k}"`);
39
+ return problems;
40
+ }
41
+
42
+ /** GC-A21: every non-JSON log line carries a UTC stamp; JSON and the one `verdict deterministic` marker line are exempt. */
43
+ const UTC_STAMP = /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?Z /;
44
+
45
+ function checkUtcStamps(text) {
46
+ const problems = [];
47
+ const lines = String(text).split(/\r?\n/);
48
+ let checked = 0;
49
+ for (const [i, line] of lines.entries()) {
50
+ if (!line.trim()) continue;
51
+ if (/^rightkit-gate: verdict deterministic/.test(line)) continue;
52
+ if (/^\s*[{}\[\]"]/.test(line)) continue; // pretty-printed JSON body
53
+ checked += 1;
54
+ if (!UTC_STAMP.test(line)) problems.push(`log line ${i + 1} has no UTC stamp: ${line.slice(0, 120)}`);
55
+ }
56
+ if (checked === 0) problems.push("the log has no lines to check");
57
+ return { ok: problems.length === 0, problems, checked };
58
+ }
59
+
60
+ /** `[stage] passed in N.Ns` and `failed in` lines of a log: [{ stage, ok, seconds }]. */
61
+ function stageTimings(text) {
62
+ const out = [];
63
+ for (const m of String(text).matchAll(/\[([a-z:]+)\] (passed|failed) in (\d+(?:\.\d+)?)s/g)) out.push({ stage: m[1], ok: m[2] === "passed", seconds: Number(m[3]) });
64
+ return out;
65
+ }
66
+
67
+ // `limitedEvidence`: the compile stage's list of type-check-only cross rows, which NN38 requires; the schema refused it until 2026-11-18, so NN38 could never pass.
68
+ const STAGE_FIELDS = ["ok", "at", "ruleTier", "direct", "qualifyOwed", "limitedEvidence", "outputs", "snapshot", "snapshotLock", "platform", "sealed", "manifestSha256", "voided", "track", "qaReceiptDigest", "tier"];
69
+
70
+ const BINDING_FIELDS = ["tree", "locks", "gate", "toolchain", "executor"];
71
+
72
+ /**
73
+ * GC-A04, GC-I05 (door half), GC-A05: the door receipt `--receipt-out` writes. `expectedTree` is `git rev-parse <commit>^{tree}`. Fail closed on unknown
74
+ * fields; `verdict` and `refreshed` must be absent (the broker never writes them into a gate receipt).
75
+ */
76
+ function validateDoorReceipt(receipt, { commit, expectedTree, stages = [] }) {
77
+ const problems = strictKeys(receipt, { required: ["schema", "commit", "app", "binding", "stages"], optional: ["brokerException"] }, "receipt");
78
+ if (!isObject(receipt)) return { ok: false, problems };
79
+ if (receipt.schema !== RECEIPT_SCHEMA) problems.push(`receipt.schema is ${JSON.stringify(receipt.schema)}, expected ${RECEIPT_SCHEMA}`);
80
+ if (receipt.commit !== commit) problems.push(`receipt.commit ${receipt.commit} != ${commit}`);
81
+ if ("brokerException" in receipt) problems.push("receipt.brokerException is set: the run was built outside the broker");
82
+ for (const banned of ["verdict", "refreshed"]) if (banned in receipt) problems.push(`receipt carries "${banned}" (refused by the gate)`);
83
+ problems.push(...strictKeys(receipt.binding, { required: BINDING_FIELDS }, "receipt.binding"));
84
+ if (isObject(receipt.binding)) {
85
+ if (receipt.binding.tree !== expectedTree) problems.push(`receipt.binding.tree ${receipt.binding.tree} != ${expectedTree} (commit^{tree})`);
86
+ if (!isSha(receipt.binding.gate)) problems.push("receipt.binding.gate is not a sha256");
87
+ }
88
+ if (!isObject(receipt.stages)) { problems.push("receipt.stages is not an object"); return { ok: false, problems }; }
89
+ for (const stage of stages) {
90
+ const s = receipt.stages[stage];
91
+ const where = `receipt.stages.${stage}`;
92
+ if (!isObject(s)) { problems.push(`${where}: missing`); continue; }
93
+ problems.push(...strictKeys(s, { required: ["ok", "at"], optional: STAGE_FIELDS.slice(2) }, where));
94
+ if (s.ok !== true) problems.push(`${where}.ok is ${JSON.stringify(s.ok)}`);
95
+ if ("voided" in s) problems.push(`${where}.voided is ${JSON.stringify(s.voided)}`);
96
+ if (!Number.isFinite(Date.parse(s.at))) problems.push(`${where}.at is not a timestamp`);
97
+ if (stage !== "check" && !isObject(s.snapshot)) problems.push(`${where}.snapshot is missing`);
98
+ if (isObject(s.snapshot)) {
99
+ if (s.snapshot.tree !== expectedTree) problems.push(`${where}.snapshot.tree ${s.snapshot.tree} != ${expectedTree}`);
100
+ if (s.snapshot.intactAfter !== true) problems.push(`${where}.snapshot.intactAfter is ${JSON.stringify(s.snapshot.intactAfter)} (the snapshot must still be exactly the commit's bytes at stage exit)`);
101
+ if (typeof s.snapshot.path !== "string" || !s.snapshot.path) problems.push(`${where}.snapshot.path is missing`);
102
+ }
103
+ }
104
+ return { ok: problems.length === 0, problems };
105
+ }
106
+
107
+ /**
108
+ * Whether the compile of a run really ran in that run. A recorded compile that "stands" is reused (`[compile] already passed ...`; the contract's E7
109
+ * says no redundant compile is required, and the receipt keeps the OLD stage `at`), so only a run whose log has `[compile] passed in` and no
110
+ * `already passed` line for the compile proves anything about ordering or about what a compile reads.
111
+ */
112
+ function compileRanFresh(log) {
113
+ const t = String(log ?? "");
114
+ return /\[compile\] passed in/.test(t) && !/\[compile\] already passed/.test(t);
115
+ }
116
+
117
+ /**
118
+ * GC-T05: Class A (stage check) is finished before the compile stage starts. With `log` (the run's own log) the proof is: the compile really ran in
119
+ * this run, the `[check] passed in` line's UTC stamp is not later than the receipt's compile `at` (the moment the compile stage began), and the check
120
+ * stage is ok. A reused compile is returned as `{ ok: false, skipped: true }`: nothing about ordering can be read from another run's `at`.
121
+ * Without `log` only the receipt timestamps are compared (kept for callers that hold no log).
122
+ */
123
+ function classABeforeCompile(receipt, log = null) {
124
+ const check = Date.parse(receipt?.stages?.check?.at);
125
+ const compile = Date.parse(receipt?.stages?.compile?.at);
126
+ if (!Number.isFinite(check) || !Number.isFinite(compile)) return { ok: false, problems: ["receipt.stages.check.at and receipt.stages.compile.at are both needed"] };
127
+ if (receipt.stages.check.ok !== true) return { ok: false, problems: [`receipt.stages.check.ok is ${JSON.stringify(receipt.stages.check.ok)}`] };
128
+ if (log === null) return check <= compile ? { ok: true, problems: [] } : { ok: false, problems: [`check at ${receipt.stages.check.at} is after compile at ${receipt.stages.compile.at}`] };
129
+ if (!compileRanFresh(log)) return { ok: false, skipped: true, problems: ["the compile was reused from an earlier run (`[compile] already passed`); its recorded `at` is not this run's, so no ordering can be read"] };
130
+ const m = /^(\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?Z) rightkit-gate: \[check\] passed in/m.exec(String(log));
131
+ if (!m) return { ok: false, problems: ["the log has no stamped `[check] passed in` line"] };
132
+ const checkEnd = Date.parse(m[1]);
133
+ return checkEnd <= compile ? { ok: true, problems: [] } : { ok: false, problems: [`Class A ended at ${m[1]}, after the compile stage began at ${receipt.stages.compile.at}`] };
134
+ }
135
+
136
+ /** GC-A15, GC-A07: the output dirs a receipt records (stage outputs.dirs) are one set across stages, and none is a debug dir. */
137
+ function outputDirsProblems(receipt) {
138
+ const problems = [];
139
+ const sets = [];
140
+ for (const [stage, s] of Object.entries(receipt?.stages ?? {})) {
141
+ const dirs = s?.outputs?.dirs;
142
+ if (dirs === undefined) continue;
143
+ if (!Array.isArray(dirs) || dirs.some((d) => typeof d !== "string")) { problems.push(`receipt.stages.${stage}.outputs.dirs is malformed`); continue; }
144
+ sets.push([stage, [...dirs].sort()]);
145
+ if (s.outputs.truncated === true) problems.push(`receipt.stages.${stage}.outputs.truncated is true`);
146
+ for (const d of dirs) if (/(^|[\\/])debug([\\/]|$)/.test(d)) problems.push(`receipt.stages.${stage}.outputs.dirs names a debug directory: ${d}`);
147
+ }
148
+ if (sets.length === 0) problems.push("no stage of the receipt records outputs.dirs");
149
+ for (const [stage, dirs] of sets.slice(1)) if (JSON.stringify(dirs) !== JSON.stringify(sets[0][1])) problems.push(`output dirs of ${stage} differ from ${sets[0][0]}`);
150
+ return { ok: problems.length === 0, problems };
151
+ }
152
+
153
+ /**
154
+ * The key GC-I01 names: sha256 of the canonical repository path, first 16 hex digits, over the path as the gate keys it. On Windows that is the
155
+ * verbatim `\\?\` spelling, so this imports the gate's own `keyPath` and `repoKey` (snapshot.mjs) instead of hashing the bare path.
156
+ */
157
+ const repositoryKey = (canonicalPath, platform = process.platform) => repoKey(keyPath(canonicalPath, platform));
158
+
159
+ /** GC-A23: the snapshot's `.rightkit-source-identity.json`. `trees` is `{ dir: tree id }` recomputed from git by the caller. */
160
+ function validateSourceIdentity(identity, { commit, trees }) {
161
+ const problems = strictKeys(identity, { required: ["schema", "commit", "trees"] }, "source-identity");
162
+ if (!isObject(identity)) return { ok: false, problems };
163
+ if (identity.schema !== SOURCE_IDENTITY_SCHEMA) problems.push(`source-identity.schema is ${JSON.stringify(identity.schema)}`);
164
+ if (identity.commit !== commit) problems.push(`source-identity.commit ${identity.commit} != ${commit}`);
165
+ if (!isObject(identity.trees)) return { ok: false, problems: [...problems, "source-identity.trees is not an object"] };
166
+ if (!("" in identity.trees)) problems.push('source-identity.trees has no "" (root) entry');
167
+ for (const [dir, tree] of Object.entries(trees)) if (identity.trees[dir] !== tree) problems.push(`source-identity.trees[${JSON.stringify(dir)}] is ${identity.trees[dir]}, git says ${tree}`);
168
+ for (const dir of Object.keys(identity.trees)) if (!(dir in trees)) problems.push(`source-identity.trees has an unexpected entry ${JSON.stringify(dir)}`);
169
+ return { ok: problems.length === 0, problems };
170
+ }
171
+
172
+ /** GC-A22 render: the receipt a `--to render` run stores. `png(name)` returns the PNG bytes of a case (or null). */
173
+ function validateRenderReceipt(receipt, { commit, png }) {
174
+ const problems = strictKeys(receipt, { required: ["schema", "commit", "tree", "appDir", "package", "bin", "features", "executable", "buildOutputDir", "host", "startedAt", "endedAt", "cases"], optional: ["buildRequestId"] }, "render-receipt");
175
+ if (!isObject(receipt)) return { ok: false, problems };
176
+ if (receipt.schema !== RENDER_RECEIPT_SCHEMA) problems.push(`render-receipt.schema is ${JSON.stringify(receipt.schema)}`);
177
+ if (receipt.commit !== commit) problems.push(`render-receipt.commit ${receipt.commit} != ${commit}`);
178
+ if (!isSha(receipt.executable?.sha256)) problems.push("render-receipt.executable.sha256 is not a sha256");
179
+ if (typeof receipt.executable?.path !== "string" || typeof receipt.buildOutputDir !== "string" || !receipt.executable.path.startsWith(receipt.buildOutputDir)) problems.push("render-receipt.executable.path does not lie inside buildOutputDir");
180
+ if (!Array.isArray(receipt.cases) || receipt.cases.length === 0) { problems.push("render-receipt.cases is empty"); return { ok: false, problems }; }
181
+ for (const c of receipt.cases) {
182
+ const where = `render-receipt.cases[${c?.name}]`;
183
+ problems.push(...strictKeys(c, { required: ["name", "png", "sha256", "bytes", "width", "height"] }, where));
184
+ const bytes = isObject(c) ? png(c.png) : null;
185
+ if (!bytes) { problems.push(`${where}: PNG ${c?.png} cannot be read`); continue; }
186
+ if (!(bytes.length > 24 && bytes.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])))) { problems.push(`${where}: not a PNG (bad magic)`); continue; }
187
+ if (sha256(bytes) !== c.sha256 || bytes.length !== c.bytes) problems.push(`${where}: sha256 or size differs from the receipt`);
188
+ if (bytes.readUInt32BE(16) !== c.width || bytes.readUInt32BE(20) !== c.height) problems.push(`${where}: PNG width/height differ from the receipt`);
189
+ }
190
+ return { ok: problems.length === 0, problems };
191
+ }
192
+
193
+ /** GC-I22: vendored vector files equal the sha256 their vectors-source.json pins and RustRight's own bytes; a missing upstream directory fails, it is not skipped. */
194
+ function vectorsProblems({ source, files, upstream = null, upstreamDir = null }) {
195
+ const problems = strictKeys(source, { required: ["schema", "note", "source", "files"] }, "vectors-source");
196
+ if (!isObject(source?.files)) return { ok: false, problems: [...problems, "vectors-source.files missing"] };
197
+ for (const [name, meta] of Object.entries(source.files)) {
198
+ const bytes = files[name];
199
+ if (!bytes) { problems.push(`${name}: pinned but not vendored`); continue; }
200
+ if (sha256(bytes) !== meta.sha256) problems.push(`${name}: vendored sha256 ${sha256(bytes).slice(0, 12)} != pinned ${String(meta.sha256).slice(0, 12)}`);
201
+ if (!upstream) continue;
202
+ if (!upstream[name]) problems.push(`${name}: RustRight's docs/contracts has no copy to compare with`);
203
+ else if (sha256(upstream[name]) !== sha256(bytes)) problems.push(`${name}: differs from RustRight's docs/contracts copy`);
204
+ }
205
+ if (!upstream) problems.push(`RustRight's docs/contracts${upstreamDir ? ` (${upstreamDir})` : ""} was not found: the vendored vectors cannot be compared with their source`);
206
+ for (const name of Object.keys(files)) if (name !== "vectors-source.json" && !(name in source.files)) problems.push(`${name}: vendored but not pinned`);
207
+ return { ok: problems.length === 0, problems };
208
+ }
209
+
210
+ /** GC-I18 (static half): the digest the gate pins is the installed runtime's. */
211
+ function brokerDigestProblems({ manifest, pins }) {
212
+ const problems = [];
213
+ if (!isObject(manifest) || !isSha(manifest.brokerDigest)) problems.push("runtime manifest has no brokerDigest sha256");
214
+ if (!isObject(pins) || !isSha(pins.brokerDigest)) problems.push("broker pins record has no brokerDigest sha256");
215
+ if (!problems.length && manifest.brokerDigest !== pins.brokerDigest) problems.push(`pins brokerDigest ${pins.brokerDigest.slice(0, 12)} != runtime manifest brokerDigest ${manifest.brokerDigest.slice(0, 12)}`);
216
+ return { ok: problems.length === 0, problems };
217
+ }
218
+
219
+ /**
220
+ * S2 (GC-A24, GC-A19, NN01): a warm rerun of the same commit. Against the first run `prev` (id -> row) and the rerun `next`:
221
+ * - every Class A scan of the rerun answered `hit` (a `ran` there is a failure, a skipped row is a failure). There is no uncached family any more:
222
+ * pnpm-lockfile and advisory-exceptions took GC-A19/GC-A24 keys (commit af0704a05, 2026-11-05), so NN01 ("any Class A row is ran") covers them too;
223
+ * - the key of every row equals the first run's key byte for byte.
224
+ */
225
+ function assertWarmRerun(prev, next) {
226
+ const problems = [];
227
+ let hits = 0;
228
+ for (const [id, row] of next) {
229
+ if (row.coverage === "skipped" && row.status === "not-in-pass") continue;
230
+ if (row.coverage === "skipped") { problems.push(`${id}: skipped (${row.reason}); a skipped row is never a pass`); continue; }
231
+ if (row.class === "A" && row.coverage !== "hit") problems.push(`${id}: Class A row ${row.coverage} on an unchanged commit, expected hit${row.key === null ? " (no cache key)" : ""}`);
232
+ if (row.class === "A" && row.coverage === "hit") hits += 1;
233
+ const before = prev.get(id);
234
+ if (row.class === "A" && before && before.key !== row.key) problems.push(`${id}: key changed between runs on one commit (${before.key} -> ${row.key})`);
235
+ if (row.class === "A" && !before) problems.push(`${id}: not present in the first run`);
236
+ }
237
+ if (hits === 0) problems.push("no Class A row hit: the rerun proves nothing about warmth");
238
+ return { ok: problems.length === 0, problems, hits };
239
+ }
240
+
241
+ /**
242
+ * S3 (GC-A24): one `.rs` edit. Exactly one `rustfmt` row `ran` (that file's), plus any per-file rows that read it (secret-scan, licence); every other
243
+ * Class A key equals the previous run. `perFile` is a RegExp of the row ids allowed to run besides rustfmt.
244
+ */
245
+ function assertOneFileEdit(prev, next, { perFile = /^(secret-scan|licen[cs]e)/ } = {}) {
246
+ const problems = [];
247
+ const ranA = [...next.values()].filter((r) => r.class === "A" && r.coverage === "ran");
248
+ const rustfmt = ranA.filter((r) => r.id.startsWith("rustfmt"));
249
+ if (rustfmt.length !== 1) problems.push(`${rustfmt.length} rustfmt rows ran, expected exactly 1 (${rustfmt.map((r) => r.id).join(", ")})`);
250
+ for (const r of ranA) if (!r.id.startsWith("rustfmt") && !perFile.test(r.id)) problems.push(`${r.id}: ran but does not read the edited file`);
251
+ // A row that ran because its input changed has a new key; a ran row that kept its key is an unexplained miss (and a row without a key cannot show a change).
252
+ for (const r of ranA) {
253
+ const before = prev.get(r.id);
254
+ if (!before) problems.push(`${r.id}: ran but is absent from the previous run, so no changed key can be shown`);
255
+ else if (r.key === null || before.key === r.key) problems.push(`${r.id}: ran with ${r.key === null ? "no cache key" : "the same key as the previous run"}: an edit changes the key of every row that reads it`);
256
+ }
257
+ for (const [id, row] of next) {
258
+ if (row.class !== "A" || row.coverage === "skipped") continue;
259
+ const before = prev.get(id);
260
+ if (row.coverage === "hit" && before && before.key !== row.key) problems.push(`${id}: key changed but the row answered hit`);
261
+ if (row.coverage === "hit" && !before) problems.push(`${id}: hit but absent from the previous run`);
262
+ }
263
+ return { ok: problems.length === 0, problems, ran: ranA.map((r) => r.id) };
264
+ }
265
+
266
+ const metadataLabel = (id) => (id === "cargo-metadata" ? "." : id.startsWith("cargo-metadata:") ? id.slice("cargo-metadata:".length) : null);
267
+
268
+ const packageListUnit = (id) => (id.startsWith("cargo-package-list:") ? id.slice("cargo-package-list:".length) : id === "cargo-package-list" ? "" : null);
269
+
270
+ /**
271
+ * S4 (GC-A19): a manifest edit reruns `cargo-metadata` and `cargo-package-list` for the edited manifest's workspace ONLY. `workspace` is that
272
+ * workspace's directory ("." for the root), `workspaces` every workspace directory of the commit and `crates` `{ workspaceDir: [crate names] }`.
273
+ * The workspace's own `cargo-metadata` row must have run with a new key; any `cargo-metadata` or `cargo-package-list` row of another workspace that
274
+ * ran, and any such row that cannot be attributed to a workspace, fails.
275
+ */
276
+ function assertManifestEdit(prev, next, { workspace, workspaces = [], crates = {} } = {}) {
277
+ const problems = [];
278
+ if (typeof workspace !== "string") return { ok: false, problems: ["the edited manifest's workspace is not known"], ran: [] };
279
+ const wsOfLabel = (label) => {
280
+ if (workspaces.includes(label)) return label;
281
+ const byCrate = workspaces.find((w) => w === `crates/${label}`);
282
+ return byCrate ?? null;
283
+ };
284
+ const crateWs = (unit) => {
285
+ const name = unit.includes(":") ? unit.slice(unit.lastIndexOf(":") + 1) : unit;
286
+ const owners = Object.entries(crates).filter(([, names]) => names.includes(name)).map(([w]) => w);
287
+ return owners.length === 1 ? owners[0] : null;
288
+ };
289
+ const ran = [];
290
+ let ownMetadata = false;
291
+ for (const row of next.values()) {
292
+ const label = metadataLabel(row.id);
293
+ const unit = packageListUnit(row.id);
294
+ if (label === null && unit === null) continue;
295
+ const ws = label !== null ? (workspaces.length === 0 && label === "." ? "." : wsOfLabel(label)) : crateWs(unit);
296
+ const own = ws === workspace;
297
+ if (row.coverage === "skipped" && row.status !== "not-in-pass") problems.push(`${row.id}: skipped (${row.reason}); a skipped row is never a pass`);
298
+ if (row.coverage === "ran") {
299
+ ran.push(row.id);
300
+ if (ws === null) problems.push(`${row.id}: ran but belongs to no known workspace`);
301
+ else if (!own) problems.push(`${row.id}: ran for workspace ${JSON.stringify(ws)}, which the edit (workspace ${JSON.stringify(workspace)}) does not touch`);
302
+ else {
303
+ const before = prev?.get(row.id);
304
+ if (!before || before.key === row.key) problems.push(`${row.id}: ran without a changed key (${before ? "same key as before" : "absent before"})`);
305
+ }
306
+ }
307
+ if (own && label !== null) {
308
+ ownMetadata = true;
309
+ if (row.coverage !== "ran") problems.push(`${row.id}: the edited workspace's cargo-metadata answered ${row.coverage}, expected ran`);
310
+ }
311
+ if (own && unit !== null && row.coverage === "hit") problems.push(`${row.id}: a cargo-package-list row of the edited workspace answered hit`);
312
+ }
313
+ if (!ownMetadata) problems.push(`no cargo-metadata row for workspace ${JSON.stringify(workspace)} exists in the run`);
314
+ return { ok: problems.length === 0, problems, ran };
315
+ }
316
+
317
+ /** S9: two git listings taken at different times must be byte equal. */
318
+ function sameListing(name, a, b) {
319
+ return a === b ? { ok: true, problems: [] } : { ok: false, problems: [`${name} changed: ${JSON.stringify(a).slice(0, 160)} -> ${JSON.stringify(b).slice(0, 160)}`] };
320
+ }
321
+
322
+ /** S9 and GC-A01: the one-worktree rule (`git worktree list --porcelain` has one `worktree ` row). */
323
+ const worktreeCount = (porcelain) => String(porcelain).split(/\r?\n/).filter((l) => l.startsWith("worktree ")).length;
324
+
325
+ /** GC-T20: no hook of the fixture's hooks directory (`.sample` files excepted) mentions the gate. `files` is `{ name: text }`. */
326
+ function hookProblems({ files, hooksPath = null }) {
327
+ const problems = [];
328
+ for (const [name, text] of Object.entries(files)) {
329
+ if (name.endsWith(".sample")) continue;
330
+ if (/rightkit-gate|rightkit-host-gate|rightkit_gate|gate\.mjs/i.test(String(text))) problems.push(`hook ${name} runs the gate`);
331
+ }
332
+ return { ok: problems.length === 0, problems };
333
+ }
334
+
335
+ /**
336
+ * How to start a gate launcher. A `.cmd`/`.bat` launcher cannot be spawned directly on Windows (Node refuses it): it goes through `cmd.exe /d /s /c`
337
+ * with verbatim arguments. Every argument and the launcher path must be free of cmd metacharacters (`" % ^ & | < > CR LF`); one that is not throws.
338
+ */
339
+ function launchSpec(gate, args, { platform = process.platform, comspec = process.env.ComSpec || "cmd.exe" } = {}) {
340
+ if (/\.mjs$/i.test(gate)) return { command: process.execPath, args: [gate, ...args], options: {} }; // as the host launcher starts a sealed gate: node <entry> <args>
341
+ if (platform !== "win32" || !/\.(cmd|bat)$/i.test(gate)) return { command: gate, args, options: {} };
342
+ const unsafe = /["%^&|<>\r\n]/;
343
+ for (const a of [gate, ...args]) if (unsafe.test(a)) throw new Error(`argument ${JSON.stringify(a)} is not safe to pass through cmd.exe`);
344
+ const quote = (a) => (a === "" || /\s/.test(a) ? `"${a}"` : a);
345
+ return { command: comspec, args: ["/d", "/s", "/c", `"${[gate, ...args].map(quote).join(" ")}"`], options: { windowsVerbatimArguments: true } };
346
+ }
347
+
348
+ // ---------------------------------------------------------------------------------------------------------------------------------------------
349
+ // The run sequence (criteria.md section 3) and the clauses each step asserts.
350
+ // ---------------------------------------------------------------------------------------------------------------------------------------------
351
+ // ---------------------------------------------------------------------------------------------------------------------------------------------
352
+ // Non-negotiables NN01-NN19 (GATE-CONTRACT [GC-A27]). Adrian, 2026-11-05: "each implement like cache etc should be written into part of an e2e test i.e.
353
+ // final state. so anything that breaks it next time fails"; "no reruns, no repeat calls. no going over things that haven't changed. fully optimizations".
354
+ // `steps` are the S-steps that produce each one's evidence. A non-negotiable is never "unchecked" on a host that can run it: when its step ran, missing
355
+ // evidence is a failure with the reason; when its step was not selected (a `--steps` subset) it is "not-evaluated" and the verdict says the run is partial.
356
+ // ---------------------------------------------------------------------------------------------------------------------------------------------
357
+ const NN = Object.freeze([
358
+ { id: "NN01", steps: ["S2"], title: "An unchanged commit runs no Class A row", evidence: "warm --to check and --to compile coverage, twice" },
359
+ { id: "NN02", steps: ["S2"], title: "An unchanged commit runs no Class B row", evidence: "warm --to compile coverage, twice" },
360
+ { id: "NN03", steps: ["S3"], title: "One edited .rs file reruns only the rows that read it", evidence: "S3 coverage" },
361
+ { id: "NN04", steps: ["S4"], title: "One edited manifest reruns only its workspace's rows", evidence: "S4 coverage" },
362
+ { id: "NN05", steps: ["S2"], title: "Keys are stable across identical runs", evidence: "coverage keys of two warm runs of check and of compile" },
363
+ { id: "NN06", steps: ["S1", "S2"], title: "Only executing rows carry the environment digest", evidence: "coverage keys, the log's env digest" },
364
+ { id: "NN07", steps: ["S1", "S2", "S3", "S4", "S10"], title: "No identical child process twice in one run", evidence: "spawn ledger" },
365
+ { id: "NN08", steps: ["S1", "S2", "S3", "S4", "S10"], title: "rustfmt is one process per bucket; no cargo fmt", evidence: "spawn ledger, coverage" },
366
+ { id: "NN09", steps: ["S1", "S2", "S3", "S4", "S10"], title: "Non-compiling cargo never goes through the broker", evidence: "spawn ledger" },
367
+ { id: "NN10", steps: ["S2"], title: "Inside a snapshot the resident gate answers cargo metadata", evidence: "spawn ledger of the warm runs" },
368
+ { id: "NN11", steps: ["S1", "S2"], title: "A warm run proves the snapshot from the resident index, without re-hashing it", evidence: "gate log (`snapshot proof:` line)" },
369
+ { id: "NN12", steps: ["S2"], title: "Installed dependencies are identified by pnpm's install record and reused", evidence: "gate log (reuse-match=hit), spawn ledger, env digest" },
370
+ { id: "NN13", steps: ["S1", "S2", "S3", "S4", "S10"], title: "Class A takes no exclusion of its own: one snapshot lock, no build-ownership lease", evidence: "gate log of every --to check" },
371
+ { id: "NN14", steps: ["S2"], title: "Preflight and app rules run once per tree", evidence: "gate log of the warm runs" },
372
+ { id: "NN15", steps: ["S2"], title: "Advice scans are cached per lock set and UTC day or hour", evidence: "warm coverage" },
373
+ { id: "NN16", steps: ["S10"], title: "A unit list shares one Class A and runs no per-unit format check", evidence: "--units-file log, spawn ledger" },
374
+ { id: "NN17", steps: ["S1", "S2"], title: "Class A lanes equal the host's cores; Class B batches compatible rows", evidence: "gate log, spawn ledger" },
375
+ { id: "NN18", steps: ["S2"], title: "Warm time stays inside the host's budget", evidence: "run wall time and stamped log lines against ci/gate-acceptance-budgets.json" },
376
+ { id: "NN19", steps: ["S0"], always: true, title: "The gate under test is the installed sealed gate", evidence: "--version, launcher" },
377
+ ]);
378
+
379
+ /** NN20-NN43 (GC-A27 as extended 2026-11-05). `post` ones are judged from the finished result (NN34, NN35). */
380
+ const NN_EXT = Object.freeze([
381
+ { id: "NN20", steps: ["S12"], title: "One edited crate recompiles only that crate and its dependents", evidence: "S12 crate-edit compile coverage" },
382
+ { id: "NN21", steps: ["S12"], title: "One edited lockfile reruns only the rows that read it", evidence: "S12 lock-edit coverage" },
383
+ { id: "NN22", steps: ["S2"], title: "A warm snapshot sync writes and removes nothing", evidence: "sync lines and spawn ledger of the warm runs" },
384
+ { id: "NN23", steps: ["S13"], title: "A gate upgrade that changes no key-relevant code keeps every hit", evidence: "coverage of the previous and the newest sealed gate" },
385
+ { id: "NN24", steps: ["S14"], title: "The cache survives the resident gate's restart and idle exit", evidence: "coverage of a run after the resident gate was killed" },
386
+ { id: "NN25", steps: ["S2"], title: "A warm run starts no git-after-proof, version probe, pnpm, process probe or real cargo", evidence: "spawn ledger of the warm runs" },
387
+ { id: "NN26", steps: ["S2"], title: "The gate asks the resident gate over its socket, in process", evidence: "spawn ledger" },
388
+ { id: "NN27", steps: ["S1"], title: "Never two compiler passes over one crate, target and feature set", evidence: "S1 compile coverage" },
389
+ { id: "NN28", steps: ["S2"], title: "Change detection comes from RightKit's file index and watcher", evidence: "gate log (change-source), spawn ledger" },
390
+ { id: "NN29", steps: ["S16"], title: "Per-run identities never enter a key or a reuse record", evidence: "coverage keys of a run with different identities" },
391
+ { id: "NN30", steps: ["S0"], always: true, title: "The releasing host passes (per host)", evidence: "this host's own run; another host's receipt is never required" },
392
+ { id: "NN31", steps: ["S0"], always: true, title: "No gate is released or installed as trusted without a passing contract test", evidence: "release and install tooling calls --verify-release" },
393
+ { id: "NN32", steps: ["S8"], title: "A killed run's snapshot lock is reclaimed by the next run on both hosts", evidence: "S8 kill cases" },
394
+ { id: "NN33", steps: ["S0"], always: true, title: "The contract and the test match", evidence: "docs/GATE-CONTRACT.md NN table" },
395
+ { id: "NN34", steps: ["S0"], always: true, post: true, title: "Missing evidence fails; a partial run never passes", evidence: "the finished result" },
396
+ { id: "NN35", steps: ["S0"], always: true, post: true, title: "The verdict shows coverage, and a release needs all of it", evidence: "the finished result, receipt" },
397
+ { id: "NN36", steps: ["S0"], always: true, title: "The test is locked", evidence: "git history of the runner, the contract table, the budgets" },
398
+ { id: "NN37", steps: ["S0"], always: true, title: "The test's author is not the implementer", evidence: "budgets.reviews" },
399
+ { id: "NN38", steps: ["S1"], title: "Cross-target rows built with stand-ins are limited evidence", evidence: "coverage and receipt of the compile" },
400
+ { id: "NN39", steps: ["S11"], title: "The parallelism is real, not configured", evidence: "spawn ledger start and end times of the cold runs" },
401
+ { id: "NN40", steps: ["S2"], title: "Docs build as one command per workspace and feature round, on every compile", evidence: "spawn ledger and doc coverage rows of every compile run" },
402
+ { id: "NN41", steps: ["S17"], title: "A deterministic failure is cached like a pass", evidence: "coverage of the failing commit run three times (same inputs twice, then a changed toolchain identity)" },
403
+ { id: "NN42", steps: ["S2"], title: "Cross targets of one stage go in one broker command naming every --target", evidence: "spawn ledger and log of every compile run" },
404
+ { id: "NN43", steps: ["S10"], title: "A unit-list run admits grouped rows by lockstep, not by whole-unit order", evidence: "S10 unit-list compile coverage (grouped rows) and log solo notes; per-unit receipts for blocked-whole" },
405
+ ]);
406
+
407
+ const NN_ALL = Object.freeze([...NN, ...NN_EXT]);
408
+
409
+ const NN_ALL_IDS = Object.freeze(NN_ALL.map((n) => n.id));
410
+
411
+ const LADDER = Object.freeze(["check", "compile", "test", "render", "dev", "package", "qualify"]);
412
+
413
+ const RECEIPT_STAGES = new Set(["check", "compile", "package", "qualify"]);
414
+
415
+ // ---------------------------------------------------------------------------------------------------------------------------------------------
416
+ // Clause assertions. Each CHECKS entry is `(ctx) => { status: "pass"|"fail"|"unchecked", evidence: [..], problems: [..] }` or a list of them. `ctx.runs`
417
+ // holds the runs of the sequence by label; a clause needing a run that is absent is "unchecked". The summary of a clause across checks is: any fail
418
+ // -> fail; else all real checks pass and no blocking "missing" part -> pass; else unchecked.
419
+ // ---------------------------------------------------------------------------------------------------------------------------------------------
420
+ const verdict = (res, evidence) => ({ status: res.ok ? "pass" : "fail", evidence, problems: res.problems });
421
+
422
+ const unchecked = (why) => ({ status: "unchecked", evidence: [], problems: [why] });
423
+
424
+ /** An unchecked part that keeps the clause from passing although other parts passed. */
425
+ const missing = (why) => ({ status: "unchecked", blocksPass: true, evidence: [], problems: [why] });
426
+
427
+ const needRun = (ctx, label) => ctx.runs[label] ?? null;
428
+
429
+ /** A run whose nonzero exit is the demanded outcome (a negative, a judged refusal, or an S17 cached-failure leg): clause checks judge its evidence, never its exit. */
430
+ const expectedFailure = (r) => Boolean(r.negative) || r.refusal !== undefined || r.expectedFailure === true;
431
+
432
+ const firstRows = (ctx, ...labels) => { for (const l of labels) if (ctx.runs[l]?.rows) return ctx.runs[l]; return null; };
433
+
434
+ /**
435
+ * The running broker's `{ pid, startedMs }` for GC-I15 (S0 and S9 compare it), or null when it cannot be established (fail safe). Mac: exactly one of the two launchd
436
+ * entries the broker alternates between at a cutover (`dev.rustright.broker`, `dev.rustright.broker.b`) is running. Windows: exactly one `rustright-broker` process.
437
+ * Linux has no broker. `run` and `uid` are test seams.
438
+ */
439
+ function runningBrokerProcess({ platform = process.platform, run = spawnSync, uid = process.getuid?.() } = {}) {
440
+ if (platform === "win32") {
441
+ try {
442
+ const script = "$p = @(Get-Process -Name rustright-broker -ErrorAction SilentlyContinue); if ($p.Count -eq 1) { \"$($p[0].Id) $($p[0].StartTime.ToUniversalTime().ToString('o'))\" }";
443
+ const r = run("powershell.exe", ["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(script, "utf16le").toString("base64")], { encoding: "utf8", timeout: 15000, windowsHide: true });
444
+ const m = /^(\d+) (\S+)\s*$/m.exec(String(r.stdout ?? ""));
445
+ if (!m) return null;
446
+ const pid = Number(m[1]); const startedMs = Date.parse(m[2]);
447
+ return Number.isInteger(pid) && pid > 0 && Number.isFinite(startedMs) ? { pid, startedMs } : null;
448
+ } catch { return null; }
449
+ }
450
+ if (platform !== "darwin") return null;
451
+ try {
452
+ const pids = ["dev.rustright.broker", "dev.rustright.broker.b"]
453
+ .map((label) => Number(/^\s*pid = (\d+)$/m.exec(String(run("launchctl", ["print", `gui/${uid}/${label}`], { encoding: "utf8", timeout: 5000 }).stdout ?? ""))?.[1]))
454
+ .filter((pid) => Number.isInteger(pid) && pid > 0);
455
+ if (pids.length !== 1) return null;
456
+ const pid = pids[0];
457
+ const ps = run("ps", ["-o", "lstart=", "-p", String(pid)], { encoding: "utf8", timeout: 5000, env: { ...process.env, LC_ALL: "C", LANG: "C" } });
458
+ const startedMs = Date.parse(String(ps.stdout ?? "").trim());
459
+ return Number.isFinite(startedMs) ? { pid, startedMs } : null;
460
+ } catch { return null; }
461
+ }
462
+
463
+ /** GC-I15: the broker process (pid and start) is the same at S0 and S9; the gate launched none. */
464
+ function brokerUnchanged(a, b) {
465
+ if (!a || !b) return { ok: false, problems: ["the broker process was not established at S0 or at S9"] };
466
+ return a.pid === b.pid && a.startedMs === b.startedMs ? { ok: true, problems: [] } : { ok: false, problems: [`broker pid/start changed: ${JSON.stringify(a)} -> ${JSON.stringify(b)}`] };
467
+ }
468
+
469
+ /** GC-T19: the check stage's recorded rule tier is the tier the stage owes (compile below qualify, release at qualify). */
470
+ function ruleTierProblems(receipt, stage) {
471
+ const tier = receipt?.stages?.check?.ruleTier;
472
+ const want = stage === "qualify" || stage === "release" ? "release" : "compile";
473
+ return tier === want ? { ok: true, problems: [] } : { ok: false, problems: [`receipt.stages.check.ruleTier is ${JSON.stringify(tier)}, expected ${JSON.stringify(want)} for --to ${stage}`] };
474
+ }
475
+
476
+ const CONTRACT_FILE = path.resolve(here, "..", "..", "docs", "GATE-CONTRACT.md");
477
+
478
+ // ---- NN19 / NN30 / NN31: the receipt ---------------------------------------------------------------------------------------------------------------
479
+ const CONTRACT_RECEIPT_SCHEMA = "rightkit.contract-test-receipt/1";
480
+
481
+ const validWaiver = (w) => isObject(w) && typeof w.clause === "string" && /^GC-/.test(w.clause) && w.by === "Adrian" && typeof w.words === "string" && w.words.trim().length > 0;
482
+
483
+ /** `--verify-release`: the receipt of the host that releases or installs passes, for the gate commit and sealed gate, with the contract and runner it was
484
+ * judged by. Per host (Adrian 2026-11-07: "why would both machines be tied to each other in such a way for anything?"): one host's receipt never
485
+ * stands for or blocks the other. `b` is optional; when given, each receipt is judged on its own. */
486
+ // The same bindings the installer's promotion makes (rustright-install trusted-gate promote, GB-98), so the two checks cannot disagree about a receipt:
487
+ // `budgetsSha256` the budgets it was judged against, `runnerFiles` every file of the runner ([{ name, sha256 }], exact set), `brokerRuntimeDigest` the
488
+ // broker installed on this host. Each is compared when given; the command line always gives all of them.
489
+ // `archive`: { sha256, integrity } of a package archive (archiveIdentity). When given, the receipt must be a candidate's and must name exactly that
490
+ // archive: this is the comparison a publication makes between the bytes it is about to publish and the bytes that were tested.
491
+ function verifyReleaseReceipts(a, b = null, { commit = null, contractSha256 = null, runnerSha256 = null, waivers = [], host = null, sealedSha256 = null, budgetsSha256 = null, runnerFiles = null, brokerRuntimeDigest = null, archive = null } = {}) {
492
+ const problems = [];
493
+ if (host && a?.host !== host) problems.push(`the receipt is from ${a?.host ?? "no host"}, this host is ${host}`);
494
+ for (const [name, r] of (b ? [["first", a], ["second", b]] : [["the", a]])) {
495
+ const w = `${name} receipt (${r?.host})`;
496
+ if (!isObject(r) || r.schema !== CONTRACT_RECEIPT_SCHEMA) { problems.push(`${w}: not a ${CONTRACT_RECEIPT_SCHEMA}`); continue; }
497
+ if (r.ok !== true || !/^PASS /.test(String(r.verdict))) problems.push(`${w}: verdict ${JSON.stringify(r.verdict)} is not a PASS`);
498
+ if (!isCommit(r.commit)) problems.push(`${w}: commit is not a 40-hex sha`);
499
+ // A candidate's receipt is what promotion keeps (NN31: tested as a candidate, then promoted), so both kinds are a sealed gate's receipt.
500
+ if (!["installed", "candidate"].includes(r.gate?.kind) || !isSha(r.gate?.sealedSha256)) problems.push(`${w}: not a sealed gate's receipt (kind ${JSON.stringify(r.gate?.kind)})`);
501
+ // The receipt must be for the very gate being released or installed, not for some other gate of the same commit.
502
+ else if (sealedSha256 !== null && r.gate.sealedSha256 !== sealedSha256) problems.push(`${w}: it is for the sealed gate ${r.gate.sealedSha256}, the gate in question is ${sealedSha256}`);
503
+ for (const id of Object.keys(r.nn ?? {})) if (r.nn[id] !== "pass") problems.push(`${w}: ${id} is ${r.nn[id]}`);
504
+ // The exact set, by name: a count let a receipt with other or fewer rules through (the list had grown to 42 while this line still said 38).
505
+ const have = Object.keys(isObject(r.nn) ? r.nn : {}); const missing = NN_ALL_IDS.filter((id) => !have.includes(id)); const unknown = have.filter((id) => !NN_ALL_IDS.includes(id));
506
+ if (missing.length || unknown.length) problems.push(`${w}: its non-negotiables are not the contract's ${NN_ALL_IDS.length}${missing.length ? `; missing ${missing.join(", ")}` : ""}${unknown.length ? `; unknown ${unknown.join(", ")}` : ""}`);
507
+ // The list must be there, as the installer's promotion requires: a receipt that leaves it out is not read as "nothing unchecked".
508
+ if (!Array.isArray(r.uncheckedClauses)) problems.push(`${w}: it does not state which operative clauses were left unchecked (uncheckedClauses is missing)`);
509
+ const open = (Array.isArray(r.uncheckedClauses) ? r.uncheckedClauses : []).filter((id) => !waivers.some((x) => validWaiver(x) && x.clause === id));
510
+ if (open.length) problems.push(`${w}: ${open.length} operative clause(s) unchecked and not waived by Adrian by name (${open.slice(0, 8).join(", ")}${open.length > 8 ? ", ..." : ""})`);
511
+ }
512
+ for (const r of (b ? [a, b] : [a]).filter(isObject)) {
513
+ if (commit && r.commit !== commit) problems.push(`the ${r.host} receipt is for commit ${r.commit}, the release is ${commit}`);
514
+ if (contractSha256 && r.contractSha256 !== contractSha256) problems.push(`the contract changed after the ${r.host} receipt was written`);
515
+ if (runnerSha256 && r.runnerSha256 !== runnerSha256) problems.push(`the runner changed after the ${r.host} receipt was written`);
516
+ if (budgetsSha256 && r.budgetsSha256 !== budgetsSha256) problems.push(`the ${r.host} receipt was judged against other budgets (${r.budgetsSha256 ?? "none stated"})`);
517
+ if (runnerFiles) {
518
+ const got = new Map((Array.isArray(r.runnerFiles) ? r.runnerFiles : []).filter(isObject).map((f) => [f.name, f.sha256])); const want = new Map(runnerFiles.map((f) => [f.name, f.sha256]));
519
+ const missing = [...want.keys()].filter((n) => !got.has(n)); const extra = [...got.keys()].filter((n) => !want.has(n)); const differ = [...want.keys()].filter((n) => got.has(n) && got.get(n) !== want.get(n));
520
+ if (missing.length || extra.length || differ.length) problems.push(`the ${r.host} receipt's runner files are not this runner's${missing.length ? `; not listed: ${missing.join(", ")}` : ""}${extra.length ? `; not part of this runner: ${extra.join(", ")}` : ""}${differ.length ? `; changed: ${differ.join(", ")}` : ""}`);
521
+ }
522
+ if (archive) {
523
+ if (!isSha(r.gate?.archiveSha256) || typeof r.gate?.archiveIntegrity !== "string") problems.push(`the ${r.host} receipt does not say which archive its gate was installed from, so it cannot be matched to the archive in question`);
524
+ else if (r.gate.archiveSha256 !== archive.sha256 || r.gate.archiveIntegrity !== archive.integrity) problems.push(`the ${r.host} receipt is for the archive ${r.gate.archiveSha256}, the archive in question is ${archive.sha256}`);
525
+ }
526
+ if (brokerRuntimeDigest && r.broker?.runtimeDigest !== brokerRuntimeDigest) problems.push(`the ${r.host} receipt was made with the broker ${r.broker?.runtimeDigest ?? "(not stated)"}, this host runs ${brokerRuntimeDigest}`);
527
+ }
528
+ return { ok: problems.length === 0, problems };
529
+ }
530
+
531
+ /**
532
+ * The launches that cannot be served from a cache, so a run that really happened shows broker jobs in them: the two S12 compiles of commits
533
+ * the runner has just made. S11, the run with the cache moved aside, is NOT one: by design it stops for approval before anything runs and
534
+ * sends no broker job. Sealed with the gate, with what the broker's signed claim for each must say (contract-nn.json `signedLaunches`). `label` is the launch's
535
+ * step label as the nonce carries it; `commands`: the stage words of which at least one job must have run in it; `exitCode`: the expected
536
+ * result of every job of the launch; `commit`: "any" means the runner made the commit for that launch (an edit): every job of the launch must
537
+ * name one same 40-hex commit, and it must not be the fixture commit the receipt states.
538
+ */
539
+ const CONTRACT_SIGNED_LAUNCHES = Object.freeze([
540
+ Object.freeze({ label: "S12:crate", commands: Object.freeze(["clippy", "test", "build", "check", "doc"]), exitCode: 0, commit: "any" }),
541
+ Object.freeze({ label: "S12:manifest", commands: Object.freeze(["clippy", "test", "build", "check", "doc"]), exitCode: 0, commit: "any" }),
542
+ ]);
543
+
544
+ /**
545
+ * Which package archive a sealed gate folder was installed from, worked out from the seal itself and not from anyone's statement.
546
+ * The seal is the sha256 of the folder's manifest (one line per file: path, a tab, kind, a tab, "-", a tab, sha256). The installer writes
547
+ * `trusted-gate-source.json` at the folder's root before sealing, so the manifest has a line for it. So: the manifest must hash to `sealedSha256`;
548
+ * it must list that file exactly once; `sourceBytes` must hash to the listed value; and the record must be for @rightkit/release.
549
+ * Returns { ok, problems, archive: { sha256, integrity, version } | null }.
550
+ */
551
+ function archiveOfSeal({ sealedSha256, manifestBytes, sourceBytes }) {
552
+ const problems = [];
553
+ if (!isSha(sealedSha256)) problems.push("no seal to check the manifest against");
554
+ else if (sha256(manifestBytes) !== sealedSha256) problems.push(`the manifest handed over hashes to ${sha256(manifestBytes)}, the tested gate's seal is ${sealedSha256}`);
555
+ const lines = String(manifestBytes).split("\n").filter((l) => l.split("\t")[0] === "./trusted-gate-source.json");
556
+ if (lines.length !== 1) problems.push(`the manifest lists trusted-gate-source.json ${lines.length} time(s); a gate sealed with its source record lists it once`);
557
+ const [, kind, , listed] = (lines[0] ?? "").split("\t");
558
+ if (lines.length === 1 && (kind !== "file" || !isSha(String(listed ?? "").trim()))) problems.push("the manifest's line for trusted-gate-source.json is not a file with a sha256");
559
+ else if (lines.length === 1 && sha256(sourceBytes) !== String(listed).trim()) problems.push("the source record handed over is not the one under the seal (sha256 differs from the manifest's line)");
560
+ let src = null; try { src = JSON.parse(String(sourceBytes)); } catch { problems.push("the source record is not JSON"); }
561
+ if (src && (src.schema !== "rustright.trusted-gate-source/1" || src.package !== "@rightkit/release" || !isSha(src.sha256) || typeof src.integrity !== "string" || !/^sha512-[A-Za-z0-9+/]+=*$/.test(src.integrity) || typeof src.version !== "string")) { problems.push("the source record is not a rustright.trusted-gate-source/1 for @rightkit/release with a sha256 and an integrity"); src = null; }
562
+ return { ok: problems.length === 0, problems, archive: problems.length === 0 ? { sha256: src.sha256, integrity: src.integrity, version: src.version } : null };
563
+ }
564
+
565
+ /** The identity of a package archive as a receipt states it: sha256 of its bytes (hex) and the npm integrity (sha512, base64). */
566
+ function archiveIdentity(bytes) {
567
+ return { sha256: createHash("sha256").update(bytes).digest("hex"), integrity: `sha512-${createHash("sha512").update(bytes).digest("base64")}` };
568
+ }
569
+
570
+ const bad = (label, problems, evidence = []) => ({ label, ok: false, problems, evidence });
571
+
572
+ const CHECKS = {
573
+ "GC-A21": (ctx) => {
574
+ const out = [];
575
+ for (const [label, run] of Object.entries(ctx.runs)) {
576
+ if (!run.ladder) continue;
577
+ if (run.args.includes("--route")) continue;
578
+ if (run.exit !== 0 && !expectedFailure(run)) out.push({ label, status: "fail", evidence: [run.logPath], problems: [`the run exited ${run.exit}${run.timedOut ? " (timed out)" : ""}`] });
579
+ const stamps = checkUtcStamps(run.log);
580
+ out.push({ label, ...verdict(stamps, [`${run.logPath} (every line)`]) });
581
+ if (run.exit === 0 && ["check", "compile", "package", "qualify"].includes(run.stage)) {
582
+ // A reused stage prints `[stage] already passed ...` instead of a timing line; only a stage that ran owes `passed in`.
583
+ const reused = new RegExp(`\\[${run.stage}\\] already passed`).test(run.log);
584
+ const timings = stageTimings(run.log).filter((t) => t.stage === run.stage);
585
+ if (!reused || timings.length) out.push({ label, ...verdict({ ok: timings.length > 0 && timings.every((t) => t.ok), problems: timings.length ? [] : [`no "[${run.stage}] passed in" line`] }, [`${run.logPath} ([${run.stage}] passed in)`]) });
586
+ }
587
+ if (run.coverageProblems.length) out.push({ label, status: "fail", evidence: run.coveragePaths, problems: run.coverageProblems });
588
+ else if (run.coveragePaths.length) out.push({ label, status: "pass", evidence: run.coveragePaths, problems: [] });
589
+ else if (run.exit === 0 && run.stage !== "render") out.push({ label, status: "fail", evidence: [run.logPath], problems: ["the log names no coverage report"] });
590
+ }
591
+ return out.length ? out : unchecked("no ladder run executed");
592
+ },
593
+ "GC-A04": (ctx) => {
594
+ const out = [];
595
+ for (const [label, run] of Object.entries(ctx.runs)) {
596
+ if (!run.receiptPath || expectedFailure(run)) continue;
597
+ if (run.exit !== 0) { out.push({ label, status: "fail", evidence: [run.logPath], problems: [`the run exited ${run.exit}${run.timedOut ? " (timed out)" : ""}: no receipt can stand for it`] }); continue; }
598
+ if (!run.receipt) { out.push({ label, status: "fail", evidence: [run.receiptPath], problems: ["the run exited 0 but wrote no readable receipt (--receipt-out)"] }); continue; }
599
+ const stages = LADDER.filter((s) => RECEIPT_STAGES.has(s) && run.stageIndex >= LADDER.indexOf(s)).filter((s) => run.receipt.stages?.[s]);
600
+ out.push({ label, ...verdict(validateDoorReceipt(run.receipt, { commit: run.commit, expectedTree: run.tree, stages }), [run.receiptPath]) });
601
+ }
602
+ if (ctx.s6) out.push(ctx.s6.fresh && ctx.s6.proof ? { label: "S6", ...verdict(ctx.s6.proof, ["the S6 snapshot file vs the commit's blob, the checkout's dirty file and its source identity"]) } : unchecked(`S6: ${ctx.s6.why ?? "the dirty-checkout proof was not made"}`));
603
+ return out.length ? out : unchecked("no run wrote a receipt (--receipt-out)");
604
+ },
605
+ "GC-T05": (ctx) => {
606
+ const out = []; let reused = 0;
607
+ for (const [label, run] of Object.entries(ctx.runs)) {
608
+ if (!run.receipt || run.exit !== 0 || !run.receipt.stages?.compile || expectedFailure(run)) continue;
609
+ const r = classABeforeCompile(run.receipt, run.log);
610
+ if (r.skipped) { reused += 1; continue; }
611
+ out.push({ label, ...verdict(r, [`${run.receiptPath} (stages.compile.at), ${run.logPath} ([check] passed in stamp)`]) });
612
+ }
613
+ for (const [label, run] of Object.entries(ctx.runs)) if (run.negative && ["N01", "N02"].includes(run.negative)) out.push({ label, ...verdict(run.negativeResult, [run.logPath]) });
614
+ return out.length ? out : unchecked(`no compile ran in a run of its own${reused ? ` (${reused} run(s) reused a recorded compile) ` : ""} and no Class A negative ran`);
615
+ },
616
+ "GC-A15": (ctx) => {
617
+ const run = [...Object.values(ctx.runs)].reverse().find((r) => r.receipt && r.exit === 0 && !expectedFailure(r) && Object.values(r.receipt.stages ?? {}).some((s) => s?.outputs));
618
+ const out = [];
619
+ if (run) out.push({ status: outputDirsProblems(run.receipt).ok ? "pass" : "fail", evidence: [run.receiptPath], problems: outputDirsProblems(run.receipt).problems });
620
+ const n15 = Object.values(ctx.runs).find((r) => r.negative === "N15");
621
+ if (n15) out.push({ ...verdict(n15.negativeResult, [n15.logPath]) });
622
+ return out.length ? out : unchecked("no receipt records stage outputs");
623
+ },
624
+ "GC-A23": (ctx) => {
625
+ // Read right after each run (the snapshot is re-synced by every later step), never at the end.
626
+ const out = [];
627
+ for (const [label, run] of Object.entries(ctx.runs)) {
628
+ if (!run.sourceIdentity) continue;
629
+ const si = run.sourceIdentity;
630
+ if (si.error) { out.push({ label, status: "fail", evidence: [si.file], problems: [si.error] }); continue; }
631
+ out.push({ label, ...verdict(validateSourceIdentity(si.identity, { commit: run.commit, trees: si.trees }), [`${si.file} (read right after ${label})`, "git rev-parse <commit>:<dir>"]) });
632
+ }
633
+ return out.length ? out : unchecked("no run produced a receipt that names a snapshot path");
634
+ },
635
+ "GC-A22-render": (ctx) => {
636
+ const run = needRun(ctx, "S1:render");
637
+ if (!run) return unchecked("--to render was not run");
638
+ if (run.exit !== 0) return { status: "fail", evidence: [run.logPath], problems: [`--to render exited ${run.exit}`] };
639
+ const dir = (/(?:render(?:ed)?|stored|wrote|receipt)[^\n]*?(\S*rightkit-gate-render\S*)/.exec(run.log) ?? [])[1]?.replace(/[,.;)]+$/, "");
640
+ if (!dir) return { status: "fail", evidence: [run.logPath], problems: ["the log names no rightkit-gate-render directory"] };
641
+ const file = path.join(dir.endsWith(".json") ? path.dirname(dir) : dir, "render-receipt.json");
642
+ let receipt;
643
+ try { receipt = JSON.parse(fs.readFileSync(file, "utf8")); } catch (e) { return { status: "fail", evidence: [file], problems: [`cannot read ${file}: ${e.message}`] }; }
644
+ return verdict(validateRenderReceipt(receipt, { commit: run.commit, png: (rel) => { try { return fs.readFileSync(path.join(path.dirname(file), rel)); } catch { return null; } } }), [file]);
645
+ },
646
+ "GC-I22": (ctx) => {
647
+ const dir = path.join(here, "test-support", "vectors");
648
+ let source; const files = {};
649
+ try { source = JSON.parse(fs.readFileSync(path.join(dir, "vectors-source.json"), "utf8")); for (const n of fs.readdirSync(dir)) if (n.endsWith(".json")) files[n] = fs.readFileSync(path.join(dir, n)); } catch (e) { return { status: "fail", evidence: [dir], problems: [e.message] }; }
650
+ const up = ctx.rustrightContracts;
651
+ let upstream = null;
652
+ // GC-I22 pins copies of RustRight's COMMITTED blobs; the working tree's bytes are the checkout's (CRLF on Windows), never the pin's.
653
+ if (up && fs.existsSync(up)) { upstream = {}; const repoRoot = path.resolve(up, "..", ".."); for (const n of Object.keys(source.files ?? {})) { const pin = source.files[n]?.commit ?? source.source?.commit; try { if (pin) upstream[n] = git(repoRoot, ["cat-file", "blob", `${pin}:docs/contracts/${n}`], { buffer: true }); } catch { /* reported as "no copy" by vectorsProblems */ } } }
654
+ return verdict(vectorsProblems({ source, files: { ...files }, upstream, upstreamDir: up }), [path.join(dir, "vectors-source.json"), up ?? "RustRight docs/contracts"]);
655
+ },
656
+ "GC-I18": (ctx) => {
657
+ const m = ctx.broker.manifest; const p = ctx.broker.pins;
658
+ if (!m || !p) return { status: "fail", evidence: [ctx.broker.manifestPath ?? "runtime-manifest.json", ctx.broker.pinsPath ?? "pins/broker-<platform>.json"], problems: [ctx.broker.problem ?? "runtime manifest or pins record unreadable"] };
659
+ return verdict(brokerDigestProblems({ manifest: m, pins: p }), [ctx.broker.manifestPath, ctx.broker.pinsPath]);
660
+ },
661
+ "GC-I01": (ctx) => {
662
+ const key = repositoryKey(ctx.git.canonical, ctx.platform);
663
+ const dir = path.join(ctx.managedRoot, "snapshots", key);
664
+ const out = [];
665
+ out.push({ ...verdict({ ok: fs.existsSync(dir), problems: fs.existsSync(dir) ? [] : [`${dir} does not exist`] }, [dir]) });
666
+ const run = Object.values(ctx.runs).find((r) => r.receipt?.stages?.check?.snapshot?.path);
667
+ if (run) { const sp = run.receipt.stages.check.snapshot.path; const ok = path.resolve(sp).startsWith(path.resolve(dir)); out.push({ ...verdict({ ok, problems: ok ? [] : [`receipt snapshot path ${sp} is not under ${dir}`] }, [run.receiptPath]) }); }
668
+ return out;
669
+ },
670
+ "GC-A01": (ctx) => {
671
+ const out = [];
672
+ const n13 = Object.values(ctx.runs).filter((r) => r.negative === "N13");
673
+ for (const r of n13) out.push({ ...verdict(r.negativeResult, [r.logPath]) });
674
+ if (ctx.s9) {
675
+ const wt = worktreeCount(ctx.s9.worktree);
676
+ out.push({ ...verdict({ ok: wt === 1, problems: wt === 1 ? [] : [`${wt} worktrees listed, expected 1`] }, ["git worktree list --porcelain"]) });
677
+ out.push({ ...verdict(ctx.s9.snapshotDirCheck, [path.join(ctx.managedRoot, "snapshots")]) });
678
+ }
679
+ return out.length ? out : unchecked("neither N13 nor S9 ran");
680
+ },
681
+ "GC-T14": (ctx) => CHECKS["GC-A01"](ctx),
682
+ "GC-A02": (ctx) => {
683
+ const out = [];
684
+ if (ctx.s9) out.push({ ...sameVerdict(sameListing("git stash list", ctx.s0?.stash, ctx.s9.stash), ["git stash list at S0 and S9"], ctx.s0) });
685
+ if (ctx.s6?.stash) out.push({ ...verdict(ctx.s6.stash, ["git stash list before and after S6"]) });
686
+ if (ctx.s6?.restore) out.push({ ...verdict(ctx.s6.restore, ["the S6 checkout restore"]) });
687
+ return out.length ? out : unchecked("S6 and S9 did not run");
688
+ },
689
+ "GC-T06": (ctx) => {
690
+ const out = [];
691
+ for (const [label, run] of Object.entries(ctx.runs)) if (run.recovery) out.push({ label, ...verdict(run.recovery, [run.logPath, run.lockPath ?? "snapshot.lock"]) });
692
+ if (ctx.s6?.fresh && ctx.s6.proof) out.push({ label: "S6", ...verdict(ctx.s6.proof, ["S6: a dirty tree and an unpushed commit build the commit's bytes"]) });
693
+ if (ctx.s9) out.push({ ...verdict(ctx.s9.lockClean, [ctx.s9.lockPath]) });
694
+ return out.length ? out : unchecked("S6, S8 and S9 did not run");
695
+ },
696
+ "GC-A19": (ctx) => {
697
+ const out = [];
698
+ const s4 = needRun(ctx, "S4:check");
699
+ const base = firstRows(ctx, "S2:check", "S1:check");
700
+ if (s4?.rows && base && s4.manifestInfo) out.push({ ...verdict(assertManifestEdit(base.rows, s4.rows, s4.manifestInfo), [...base.coveragePaths, ...s4.coveragePaths]) });
701
+ const s2 = needRun(ctx, "S2:check");
702
+ if (s2?.rows) {
703
+ const aud = [...s2.rows.values()].filter((r) => /^(cargo-deny|cargo-audit|pnpm-audit|ghsa-audit)/.test(r.id));
704
+ const bad = aud.filter((r) => r.coverage === "ran");
705
+ out.push({ ...verdict({ ok: aud.length > 0 && bad.length === 0, problems: aud.length === 0 ? ["no audit rows in the warm rerun"] : bad.map((r) => `${r.id}: ran on an unchanged commit (key ${r.key})`) }, s2.coveragePaths) });
706
+ }
707
+ return out.length ? out : unchecked("S2 and S4 did not run");
708
+ },
709
+ "GC-A24": (ctx) => {
710
+ const out = [];
711
+ const s1 = needRun(ctx, "S1:check"); const s2 = needRun(ctx, "S2:check"); const s3 = needRun(ctx, "S3:check");
712
+ if (s1?.rows && s2?.rows) out.push({ ...verdict(assertWarmRerun(s1.rows, s2.rows), [...s1.coveragePaths, ...s2.coveragePaths]) });
713
+ if (s2?.rows && s3?.rows) out.push({ ...verdict(assertOneFileEdit(s2.rows, s3.rows), [...s2.coveragePaths, ...s3.coveragePaths]) });
714
+ for (const [label, run] of Object.entries(ctx.runs)) if (run.kill === "K02") out.push({ label, ...verdict(run.recovery, [run.logPath]) });
715
+ return out.length ? out : unchecked("S1/S2/S3 coverage pairs are missing");
716
+ },
717
+ "GC-T04": (ctx) => {
718
+ const out = [];
719
+ for (const [label, run] of Object.entries(ctx.runs)) {
720
+ if (!run.receipt || run.exit !== 0 || expectedFailure(run)) continue;
721
+ const problems = [];
722
+ if (run.receipt.binding?.executor !== "broker") problems.push(`receipt.binding.executor is ${JSON.stringify(run.receipt.binding?.executor)}, expected "broker"`);
723
+ if ("brokerException" in run.receipt) problems.push("receipt.brokerException is set");
724
+ out.push({ label, ...verdict({ ok: problems.length === 0, problems }, [`${run.receiptPath} (binding.executor)`]) });
725
+ }
726
+ return out.length ? out : unchecked("no run wrote a receipt");
727
+ },
728
+ "GC-T19": (ctx) => {
729
+ const out = []; let release = false;
730
+ for (const [label, run] of Object.entries(ctx.runs)) {
731
+ if (!run.ladder || expectedFailure(run) && run.refusal === undefined) continue;
732
+ if (run.refusal !== undefined) { if (run.refusal.ok) { release = true; out.push({ label, status: "pass", evidence: [run.logPath], problems: [] }); } else out.push({ label, ...verdict(run.refusal, [run.logPath]) }); continue; }
733
+ if (!run.receipt || run.exit !== 0 || !run.receipt.stages?.check) continue;
734
+ if (run.stage === "qualify") release = true;
735
+ out.push({ label, ...verdict(ruleTierProblems(run.receipt, run.stage), [`${run.receiptPath} (stages.check.ruleTier)`]) });
736
+ }
737
+ if (!out.length) return unchecked("no run recorded a check stage");
738
+ if (!release) out.push(missing(ctx.allowInstall ? "no --to qualify run: the release-tier half is unchecked" : `release-tier half (--to qualify): ${NEEDS_INSTALL_APPROVAL}`));
739
+ return out;
740
+ },
741
+ "GC-A22-classA": (ctx) => {
742
+ const src = firstRows(ctx, "S1:check", "S1:compile", "S2:check");
743
+ const out = [];
744
+ if (src) {
745
+ const find = (re) => [...src.rows.values()].filter((r) => re.test(r.id));
746
+ for (const [name, re, need] of [["ghsa-audit", /^ghsa-audit(:|$)/, true], ["secret-scan", /^secret-scan$/, true], ["feature-coverage", /^feature-coverage$/, false]]) {
747
+ const rows = find(re);
748
+ if (!rows.length) { out.push(need ? { status: "fail", evidence: src.coveragePaths, problems: [`no ${name} row in the coverage report`] } : missing(`no ${name} row: the fixture has no crate with declared features (${NEEDS_FIXTURE})`)); continue; }
749
+ const bad = rows.filter((r) => !(["hit", "ran"].includes(r.coverage) && r.status === "pass")).map((r) => `${r.id}: ${r.coverage}/${r.status}${r.reason ? ` (${r.reason})` : ""}`);
750
+ out.push({ status: bad.length ? "fail" : "pass", evidence: src.coveragePaths, problems: bad });
751
+ }
752
+ } else out.push(unchecked("no coverage report (S1 check did not run)"));
753
+ const n02 = Object.values(ctx.runs).find((r) => r.negative === "N02");
754
+ if (n02) out.push({ ...verdict(n02.negativeResult, [n02.logPath]) });
755
+ return out;
756
+ },
757
+ "GC-I03": (ctx) => {
758
+ const out = [];
759
+ for (const [label, run] of Object.entries(ctx.runs)) {
760
+ if (!run.receipt || run.exit !== 0 || expectedFailure(run)) continue;
761
+ const problems = [];
762
+ for (const stage of ["check", "compile"]) {
763
+ const sn = run.receipt.stages?.[stage]?.snapshot;
764
+ if (stage === "check" && !run.receipt.stages?.check) { problems.push("receipt.stages.check is missing"); continue; }
765
+ if (run.receipt.stages?.[stage] === undefined) continue;
766
+ if (!isObject(sn)) problems.push(`receipt.stages.${stage}.snapshot is missing`);
767
+ else { if (sn.tree !== run.tree) problems.push(`${stage}: snapshot tree ${sn.tree} != commit^{tree} ${run.tree}`); if (sn.intactAfter !== true) problems.push(`${stage}: snapshot.intactAfter is ${JSON.stringify(sn.intactAfter)}`); }
768
+ }
769
+ out.push({ label, ...verdict({ ok: problems.length === 0, problems }, [`${run.receiptPath} (door half: snapshot tree at stage exit vs commit^{tree})`]) });
770
+ }
771
+ return out.length ? out : unchecked("no run wrote a receipt");
772
+ },
773
+ "GC-I05": (ctx) => {
774
+ const out = [];
775
+ for (const [label, run] of Object.entries(ctx.runs)) {
776
+ if (!run.receipt || run.exit !== 0 || expectedFailure(run) || !run.receiptPath) continue;
777
+ const stages = LADDER.filter((s) => RECEIPT_STAGES.has(s) && run.stageIndex >= LADDER.indexOf(s)).filter((s) => run.receipt.stages?.[s]);
778
+ out.push({ label, ...verdict(validateDoorReceipt(run.receipt, { commit: run.commit, expectedTree: run.tree, stages }), [`${run.receiptPath} (door half: no verdict/refreshed, strict fields; the broker's receipt fields are not read)`]) });
779
+ }
780
+ return out.length ? out : unchecked("no run wrote a receipt");
781
+ },
782
+ "GC-I15": (ctx) => {
783
+ if (!ctx.s0 || !ctx.s9) return unchecked("S0 and S9 did not both run");
784
+ return verdict(brokerUnchanged(ctx.s0.broker, ctx.s9.broker), ["runningBrokerProcess() at S0 and at S9 (pid and start time)"]);
785
+ },
786
+ "GC-T20": (ctx) => (ctx.hooks ? verdict(hookProblems(ctx.hooks), [`${ctx.hooks.dir} (the hooks half only; the no-gate-process-on-commit half is not run)`]) : unchecked("the fixture's hooks were not read")),
787
+ };
788
+
789
+ const sameVerdict = (res, evidence, s0) => (s0 ? verdict(res, evidence) : unchecked("S0 listing missing"));
790
+
791
+ function git(cwd, args, { env = {}, input, buffer = false } = {}) {
792
+ const r = spawnSync("git", args, { cwd, encoding: buffer ? "buffer" : "utf8", env: { ...process.env, ...env }, input, maxBuffer: 1 << 28 });
793
+ if (r.status !== 0) throw new Error(`git ${args.join(" ")}: ${String(r.stderr || r.stdout || "").trim() || `exit ${r.status}`}`);
794
+ return r.stdout;
795
+ }
796
+
797
+ let liveCandidateOutput = false;
798
+
799
+ function launch({ gate, args, cwd, env }) {
800
+ const spec = launchSpec(gate, args);
801
+ const child = spawn(spec.command, spec.args, { cwd, env, stdio: ["ignore", "pipe", "pipe"], detached: process.platform !== "win32", windowsHide: true, ...spec.options });
802
+ if (liveCandidateOutput) {
803
+ child.stdout.pipe(process.stdout, { end: false });
804
+ child.stderr.pipe(process.stdout, { end: false });
805
+ }
806
+ return child;
807
+ }
808
+
809
+ export { CONTRACT_FILE, archiveIdentity, archiveOfSeal, validWaiver, verifyReleaseReceipts, NN_ALL_IDS, CONTRACT_RECEIPT_SCHEMA, CONTRACT_SIGNED_LAUNCHES };