@rightkit/release 0.6.57 → 0.6.62

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 +552 -124
  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 +170 -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 +179 -34
  35. package/gate-stages.mjs +59 -0
  36. package/legacy-contract-receipt.mjs +809 -0
  37. package/local-publish.mjs +2 -4
  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 +89 -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
@@ -1,3362 +0,0 @@
1
- #!/usr/bin/env node
2
- // End-to-end acceptance runner for the gate (rightkit#1514). It drives the real gate against the witness fixture and asserts every operative clause of
3
- // docs/GATE-CONTRACT.md from that run's OWN artifacts: the door receipt (--receipt-out), the per-scan coverage reports, the log, the snapshot lock and
4
- // git. Spec: /Volumes/D/scratch/gate-acceptance/criteria.md (clause table, run sequence S0-S9, negatives, kill-and-recover).
5
- //
6
- // node gate-acceptance.mjs --fixture <dir> [--host mac|dell] [--steps S0,S1,...] [--out <dir>] [--plan] [--gate <path>] [--commit <sha>] [--allow-install]
7
- //
8
- // Rules this file keeps:
9
- // * Three states per clause: "pass", "fail", "unchecked". A clause with no evidence available is "unchecked", never "pass". A skipped scan row is never a pass.
10
- // * Fail closed: an unknown field, a missing artifact or a malformed value is a "fail" with the reason, never skipped over.
11
- // * Every assertion names its clause id and the evidence path (or evidence source) it read.
12
- // * No cache bypass flag is ever passed to do work (N13 passes the two retired bypasses only to prove the gate refuses them) and nothing is pushed or published. Nothing is installed by default: `--to dev` and `--to qualify` install
13
- // apps, so they run only with `--allow-install` (which needs Adrian's approval); without it their clauses are "unchecked: needs install approval".
14
- // Negative inputs are ephemeral `git commit-tree` commits under refs/witness/<case> (no branch, no worktree, no checkout write); the refs are deleted
15
- // at the end. The one checkout write is S6's dirty-checkout setup, which refuses a dirty fixture and restores it exactly.
16
- // * The verdict is PASS only when no clause, step or step-only check failed and every step ran as specified; it is always printed with the
17
- // count of unchecked clauses ("PASS (N of 67 asserted, M unchecked)"), never as a bare PASS.
18
- // * The 19 non-negotiables NN01-NN19 (GATE-CONTRACT [GC-A27]) are asserted on every run from the run's own evidence (coverage, log, spawn ledger, budgets
19
- // file). Every gate invocation is started with RK_GATE_SPAWN_LEDGER naming a per-run file under --out. A selected non-negotiable with missing evidence
20
- // FAILS; it is never "unchecked". Wall time is judged only by NN18 against ci/gate-acceptance-budgets.json (a null budget fails: "no budget measured").
21
- // The pure assertion functions are exported and tested by gate-acceptance.test.mjs; `--plan` prints the steps and clause mapping and runs nothing.
22
- import { createHash } from "node:crypto";
23
- import { spawn, spawnSync } from "node:child_process";
24
- import fs from "node:fs";
25
- import os from "node:os";
26
- import path from "node:path";
27
- import { fileURLToPath } from "node:url";
28
- import { keyPath, repoKey } from "./snapshot.mjs";
29
- import { RUNTIME_MANIFEST_FILE } from "./seam-broker.mjs";
30
- import { resolveBrokerClient } from "./broker-client.mjs";
31
- import { managedRuntimeClient } from "./managed-roots.mjs";
32
-
33
- export const RESULT_SCHEMA = "rightkit.gate-acceptance/1";
34
- export const COVERAGE_SCHEMA = "rightkit.gate-coverage/1";
35
- export const RECEIPT_SCHEMA = "rightkit.gate-receipt/1";
36
- export const SOURCE_IDENTITY_SCHEMA = "rightkit.source-identity.v1";
37
- export const RENDER_RECEIPT_SCHEMA = "rightkit.render-views/1";
38
-
39
- const here = path.dirname(fileURLToPath(import.meta.url));
40
- const sha256 = (data) => createHash("sha256").update(data).digest("hex");
41
- const isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
42
- const isSha = (v) => typeof v === "string" && /^[0-9a-f]{64}$/.test(v);
43
- const isCommit = (v) => typeof v === "string" && /^[0-9a-f]{40}$/.test(v);
44
-
45
- // ---------------------------------------------------------------------------------------------------------------------------------------------
46
- // Clause registry: the 67 operative rows of criteria.md section 1 (id, evidence tag, title). `implemented` clauses have an assertion in CHECKS below;
47
- // every other clause is reported "unchecked" with the reason from UNCHECKED_WHY (the gate writes no evidence the runner may read, or the fixture
48
- // rows the case needs do not exist yet).
49
- // ---------------------------------------------------------------------------------------------------------------------------------------------
50
- const ROWS = [
51
- ["GC-A01", "M", "warm only; one snapshot dir; one worktree; no cache bypass"], ["GC-A02", "M", "stash never a build source, never left behind"],
52
- ["GC-A03", "P", "Class A covers the closure plus file-only scans"], ["GC-A04", "M", "build is from the selected commit via the snapshot"],
53
- ["GC-A05", "M", "broker runs no gate"], ["GC-A06", "P", "runs on the real broker of the host"], ["GC-A07", "P", "no debug build; QA marker only in dev"],
54
- ["GC-A08", "M", "cargo test compiles in the broker, runs outside"], ["GC-A09", "M", "no test-mode feature"], ["GC-A10", "P", "QA journeys with mandatory [snapshot]"],
55
- ["GC-A11", "P", "Class A and non-compiling cargo run direct"], ["GC-A12", "G", "tsc once in Class A"], ["GC-A13", "M", "unexplained rebuild never fails; cause evidence recorded"],
56
- ["GC-A14", "M", "every crate clippy-checked for all three OS targets"], ["GC-A15", "M", "one output and one warm cache per app per host; release profile"],
57
- ["GC-A16", "G", "dev builds signed, not notarized"], ["GC-A18", "P", "Class B batched per workspace, bisected"], ["GC-A19", "M", "audit scans cached by lock+config+advisory+day"],
58
- ["GC-A21", "M", "UTC-stamped log, stage timings, per-scan coverage JSON"], ["GC-A22-render", "M", "--to render builds and runs the declared target, PNGs and receipt"],
59
- ["GC-A22-classA", "M", "ghsa-audit, freshness advice, feature-coverage, secret-scan, store proof"], ["GC-A23", "M", "deterministic .rightkit-source-identity.json"],
60
- ["GC-A24", "M", "Class A is change-driven, rows keyed on own inputs"],
61
- ["GC-T01", "P", "origin host compile proves only what it compiled"], ["GC-T02", "P", "Mac and Windows artifacts built natively"], ["GC-T03", "G", "private qualification runs locally"],
62
- ["GC-T04", "M", "compile only through the broker, no direct fallback"], ["GC-T05", "M", "Class A completes before the first compile"], ["GC-T06", "M", "commit-only build, exact snapshot, per-repository lock"],
63
- ["GC-T07", "G", "qualification policy pinned by digest"], ["GC-T10", "P", "product manifest declares target kinds"], ["GC-T11", "P", "sign once, qualify sealed bytes"],
64
- ["GC-T12", "P", "one signing identity per product"], ["GC-T13", "P", "same gate for human and agent callers"], ["GC-T14", "M", "one checkout, one snapshot dir, one output dir; no bypass"],
65
- ["GC-T16", "M", "every cargo call keeps going"], ["GC-T17", "G", "broker trusts a published gate (contract conflict, unreconciled)"], ["GC-T18", "M", "fixture-files.json skips only per-file format scans"],
66
- ["GC-T19", "M", "rule tier by stage"], ["GC-T20", "M", "commit and push run no gate and no hook"], ["GC-T24", "M", "unit-list plans, dependency-first, broker argv shapes"],
67
- ["GC-I01", "M", "snapshot root and repository key"], ["GC-I02", "M", "gate creates no output dir; broker-pinned target"], ["GC-I03", "M", "Class A check route, tree id before and after"],
68
- ["GC-I04", "M", "request carries commit, snapshot, declaredInputs, ownership"], ["GC-I05", "M", "receipt fields"], ["GC-I06", "P", "broker lease from admission to reap"],
69
- ["GC-I08", "P", "native tool adapters"], ["GC-I11", "M", "clippy route keeps scope and aggregates FAILED"], ["GC-I12", "M", "broker admits only <data root>/snapshots/<repo-key>"],
70
- ["GC-I13", "P", "refusal at admission leaves a durable REAPED completion"], ["GC-I14", "M", "absent declared input recorded"], ["GC-I15", "P", "installed broker executable path rule"],
71
- ["GC-I16", "M", "broker config path"], ["GC-I17", "M", "answering broker's roots on the wire"], ["GC-I18", "M", "pinned digest is the answering broker's"],
72
- ["GC-I19", "M", "lease status shape and aggregate rule"], ["GC-I20", "P", "scan tools only from enrolled executables"], ["GC-I21", "P", "gate-owned dirs registered in the census"],
73
- ["GC-I22", "M", "vendored vectors are byte copies"],
74
- ["GC-Q01", "P", "origin record fields"], ["GC-Q02", "P", "compile digests apart from artifact identity"], ["GC-Q03", "G", "native build record"], ["GC-Q04", "G", "final sealed digest bound to coverage"],
75
- ["GC-Q05", "G", "private qualification evidence"], ["GC-1A-R2", "M", "build outside broker only with a recorded exception"], ["GC-1A-R4", "M", "committed build definition lists every Cargo workspace"],
76
- ].map(([id, ev, title]) => Object.freeze({ id, ev, title }));
77
- export const CLAUSES = Object.freeze(Object.fromEntries(ROWS.map((r) => [r.id, r])));
78
-
79
- const NO_EVIDENCE = "the gate writes no artifact the runner may read for this clause (criteria.md section 5)";
80
- const NEEDS_BROKER_RECEIPTS = "needs broker receipts (argv, transformations, testExecutables); the door receipt does not carry them and the receipt-dir path of a stage run is not named by the contract";
81
- const NEEDS_HOST_TOOL = "needs a host tool (codesign, signtool, stapler, find) or the installed app; not read by this runner";
82
- const NEEDS_FIXTURE = "needs fixture rows (criteria.md section 2, F1-F14) that do not exist in the witness fixture yet";
83
- export const NEEDS_INSTALL_APPROVAL = "needs install approval";
84
- /** Clauses whose evidence comes from `--to dev` or `--to qualify`, both of which install an app: unchecked unless `--allow-install` ran them. */
85
- export const INSTALL_CLAUSES = Object.freeze(["GC-A07", "GC-A10", "GC-A16", "GC-T03", "GC-T07", "GC-T11", "GC-T12", "GC-Q04", "GC-Q05"]);
86
- export const UNCHECKED_WHY = Object.freeze({
87
- "GC-A03": NEEDS_FIXTURE, "GC-A05": NEEDS_BROKER_RECEIPTS, "GC-A06": "needs HANDSHAKE and STATUS from a live broker query; the runner reads the runtime manifest and pins only (see GC-I18)", "GC-A07": NEEDS_HOST_TOOL,
88
- "GC-A08": NEEDS_BROKER_RECEIPTS, "GC-A09": NEEDS_FIXTURE, "GC-A10": NEEDS_FIXTURE, "GC-A11": NO_EVIDENCE, "GC-A12": NO_EVIDENCE, "GC-A13": "needs the compile freshness object, which sits in broker receipts not in the door receipt",
89
- "GC-A14": NEEDS_BROKER_RECEIPTS, "GC-A16": NO_EVIDENCE, "GC-A18": NEEDS_BROKER_RECEIPTS, "GC-T01": "needs executor/target fields of a per-stage broker receipt",
90
- "GC-T02": NEEDS_HOST_TOOL, "GC-T03": NO_EVIDENCE, "GC-T07": NO_EVIDENCE, "GC-T10": NEEDS_FIXTURE, "GC-T11": "needs sealed digests at seal, qualify and promote points",
91
- "GC-T12": NEEDS_HOST_TOOL, "GC-T13": "needs a second run under an agent environment", "GC-T16": NEEDS_BROKER_RECEIPTS, "GC-T17": "contract conflict with BROKER BR30/item 18; no assertion until reconciled",
92
- "GC-T18": NEEDS_FIXTURE, "GC-T24": "needs a --changed or --units-file run and its receipt-dir; not part of S0-S9", "GC-I02": NEEDS_BROKER_RECEIPTS,
93
- "GC-I04": NEEDS_BROKER_RECEIPTS, "GC-I06": NO_EVIDENCE, "GC-I08": NEEDS_FIXTURE, "GC-I11": "needs a `rightkit-gate clippy` run and its receipt",
94
- "GC-I12": "needs `rustright doctor --json`; not run by this runner (read-only, but an agent hook forbids it here)", "GC-I13": "needs a refusal the gate does not pre-empt (fixture N14) and a SNAPSHOT_LEASE_STATUS query", "GC-I14": NEEDS_FIXTURE,
95
- "GC-I16": "needs `rustright doctor --json`; not run by this runner", "GC-I17": "needs a live STATUS query", "GC-I19": "needs a live SNAPSHOT_LEASE_STATUS query", "GC-I20": NEEDS_FIXTURE, "GC-I21": NO_EVIDENCE,
96
- "GC-Q01": NO_EVIDENCE, "GC-Q02": NO_EVIDENCE, "GC-Q03": NO_EVIDENCE, "GC-Q04": NO_EVIDENCE, "GC-Q05": NO_EVIDENCE, "GC-1A-R2": NEEDS_FIXTURE, "GC-1A-R4": "covered by negative N26 when --steps S7 runs",
97
- });
98
-
99
- // ---------------------------------------------------------------------------------------------------------------------------------------------
100
- // Pure assertion helpers. Each returns { ok, problems[] } (or a richer record); `problems` is empty on success.
101
- // ---------------------------------------------------------------------------------------------------------------------------------------------
102
-
103
- /** Unknown or missing keys of `obj` against `{ required, optional }`; fail closed on both. */
104
- export function strictKeys(obj, { required = [], optional = [] }, where) {
105
- if (!isObject(obj)) return [`${where}: not an object`];
106
- const problems = [];
107
- for (const k of required) if (!(k in obj)) problems.push(`${where}: missing field "${k}"`);
108
- const known = new Set([...required, ...optional]);
109
- for (const k of Object.keys(obj)) if (!known.has(k)) problems.push(`${where}: unknown field "${k}"`);
110
- return problems;
111
- }
112
-
113
- const ROW_REQUIRED = ["id", "class", "coverage", "status", "key", "reason"];
114
- const ROW_OPTIONAL = ["code", "timing", "scanElapsedMs", "retryTiming", "batchAttempts", "batchedWith", "evidence", "filesRead"];
115
- const COVERAGE_VALUES = new Set(["hit", "ran", "skipped"]);
116
-
117
- /** GC-A21: the schema of one coverage report (gate-coverage.mjs buildCoverageReport). Fail closed on any unknown field. */
118
- export function validateCoverage(report) {
119
- const problems = strictKeys(report, { required: ["schema", "commit", "startedAt", "endedAt", "totals", "scans"], optional: ["cacheDisabled"] }, "coverage");
120
- if (problems.length && !isObject(report)) return { ok: false, problems };
121
- if (report.schema !== COVERAGE_SCHEMA) problems.push(`coverage.schema is ${JSON.stringify(report.schema)}, expected ${COVERAGE_SCHEMA}`);
122
- if ("cacheDisabled" in report) problems.push(`coverage.cacheDisabled is set (${JSON.stringify(report.cacheDisabled)}): the run bypassed the cache`);
123
- if (!Array.isArray(report.scans)) { problems.push("coverage.scans is not an array"); return { ok: false, problems }; }
124
- problems.push(...strictKeys(report.totals, { required: ["planned", "hit", "ran", "skipped"] }, "coverage.totals"));
125
- const count = { hit: 0, ran: 0, skipped: 0 };
126
- const seen = new Set();
127
- for (const [i, row] of report.scans.entries()) {
128
- const where = `coverage.scans[${i}]${isObject(row) && typeof row.id === "string" ? ` (${row.id})` : ""}`;
129
- const bad = strictKeys(row, { required: ROW_REQUIRED, optional: ROW_OPTIONAL }, where);
130
- problems.push(...bad);
131
- if (!isObject(row)) continue;
132
- if (typeof row.id !== "string" || !row.id) problems.push(`${where}: id is not a non-empty string`);
133
- else if (seen.has(row.id)) problems.push(`${where}: duplicate scan id`);
134
- else seen.add(row.id);
135
- if (!COVERAGE_VALUES.has(row.coverage)) { problems.push(`${where}: coverage ${JSON.stringify(row.coverage)} is not hit|ran|skipped`); continue; }
136
- count[row.coverage] += 1;
137
- if (typeof row.status !== "string" || !row.status) problems.push(`${where}: status is not a non-empty string`);
138
- if (typeof row.reason !== "string" || !row.reason) problems.push(`${where}: reason is not a non-empty string`);
139
- if (!(row.key === null || (typeof row.key === "string" && row.key))) problems.push(`${where}: key is neither null nor a string`);
140
- // A member whose own result is a cached pass still fails when its grouped invocation failed (rightkit#1458: BATCH_REQUIREMENT_FAILED keeps
141
- // the grouped failure as evidence), so hit + fail is valid exactly when a batch attempt of that row failed.
142
- const batchFailed = Array.isArray(row.batchAttempts) && row.batchAttempts.some((a) => a?.status === "fail");
143
- if (row.coverage === "hit" && row.status !== "pass" && !(row.status === "fail" && (batchFailed || row.class === "B"))) problems.push(`${where}: a hit row has status ${JSON.stringify(row.status)}, expected pass`);
144
- if (row.coverage === "ran" && row.status !== "pass" && row.status !== "fail") problems.push(`${where}: a ran row has status ${JSON.stringify(row.status)}, expected pass|fail`);
145
- }
146
- if (isObject(report.totals)) {
147
- if (report.totals.planned !== report.scans.length) problems.push(`coverage.totals.planned ${report.totals.planned} != ${report.scans.length} rows`);
148
- for (const k of ["hit", "ran", "skipped"]) if (report.totals[k] !== count[k]) problems.push(`coverage.totals.${k} ${report.totals[k]} != ${count[k]} rows`);
149
- if (report.totals.hit + report.totals.ran + report.totals.skipped !== report.totals.planned) problems.push("coverage.totals: hit+ran+skipped != planned");
150
- }
151
- return { ok: problems.length === 0, problems };
152
- }
153
-
154
- /**
155
- * Merges the reports of one run (a stage may write one per pass) into a map id -> row. A row that was really answered (hit or ran) wins over a
156
- * "not-in-pass" skip of the same scan in another pass; two real answers for one id keep the later one.
157
- */
158
- export function mergeCoverage(reports) {
159
- const rows = new Map();
160
- const notInPass = (r) => r.coverage === "skipped" && r.status === "not-in-pass";
161
- for (const report of reports) for (const row of report.scans) {
162
- const prev = rows.get(row.id);
163
- if (!prev || notInPass(prev) || !notInPass(row)) rows.set(row.id, row);
164
- }
165
- return rows;
166
- }
167
-
168
- /** Rows of a pass that carry no answer: skipped for any reason except "class not part of this pass". They are never counted as a pass. */
169
- export function skippedRows(rows) {
170
- return [...rows.values()].filter((r) => r.coverage === "skipped" && r.status !== "not-in-pass");
171
- }
172
-
173
- /** GC-A21: every non-JSON log line carries a UTC stamp; JSON and the one `verdict deterministic` marker line are exempt. */
174
- const UTC_STAMP = /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?Z /;
175
- export function checkUtcStamps(text) {
176
- const problems = [];
177
- const lines = String(text).split(/\r?\n/);
178
- let checked = 0;
179
- for (const [i, line] of lines.entries()) {
180
- if (!line.trim()) continue;
181
- if (/^rightkit-gate: verdict deterministic/.test(line)) continue;
182
- if (/^\s*[{}\[\]"]/.test(line)) continue; // pretty-printed JSON body
183
- checked += 1;
184
- if (!UTC_STAMP.test(line)) problems.push(`log line ${i + 1} has no UTC stamp: ${line.slice(0, 120)}`);
185
- }
186
- if (checked === 0) problems.push("the log has no lines to check");
187
- return { ok: problems.length === 0, problems, checked };
188
- }
189
-
190
- /** `[stage] passed in N.Ns` and `failed in` lines of a log: [{ stage, ok, seconds }]. */
191
- export function stageTimings(text) {
192
- const out = [];
193
- 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]) });
194
- return out;
195
- }
196
-
197
- /** Coverage report paths a log names: "coverage report <file>: N planned scan(s), ...". */
198
- export function coveragePaths(text) {
199
- return [...String(text).matchAll(/coverage report (.+?): \d+ planned scan/g)].map((m) => m[1]);
200
- }
201
-
202
- /** The reclaim line of a gate: "snapshot lock held <token> (reclaimed from <owner>: <proof>)". null when the run reclaimed nothing. */
203
- export function reclaimLine(text) {
204
- const m = /snapshot lock held (\S+) \(reclaimed from (.+?): (.*)\)\s*$/m.exec(String(text));
205
- return m ? { token: m[1], from: m[2].trim(), proof: m[3] } : null;
206
- }
207
-
208
- const STAGE_FIELDS = ["ok", "at", "ruleTier", "direct", "qualifyOwed", "outputs", "snapshot", "snapshotLock", "platform", "sealed", "manifestSha256", "voided", "track", "qaReceiptDigest", "tier"];
209
- const BINDING_FIELDS = ["tree", "locks", "gate", "toolchain", "executor"];
210
-
211
- /**
212
- * 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
213
- * fields; `verdict` and `refreshed` must be absent (the broker never writes them into a gate receipt).
214
- */
215
- export function validateDoorReceipt(receipt, { commit, expectedTree, stages = [] }) {
216
- const problems = strictKeys(receipt, { required: ["schema", "commit", "app", "binding", "stages"], optional: ["brokerException"] }, "receipt");
217
- if (!isObject(receipt)) return { ok: false, problems };
218
- if (receipt.schema !== RECEIPT_SCHEMA) problems.push(`receipt.schema is ${JSON.stringify(receipt.schema)}, expected ${RECEIPT_SCHEMA}`);
219
- if (receipt.commit !== commit) problems.push(`receipt.commit ${receipt.commit} != ${commit}`);
220
- if ("brokerException" in receipt) problems.push("receipt.brokerException is set: the run was built outside the broker");
221
- for (const banned of ["verdict", "refreshed"]) if (banned in receipt) problems.push(`receipt carries "${banned}" (refused by the gate)`);
222
- problems.push(...strictKeys(receipt.binding, { required: BINDING_FIELDS }, "receipt.binding"));
223
- if (isObject(receipt.binding)) {
224
- if (receipt.binding.tree !== expectedTree) problems.push(`receipt.binding.tree ${receipt.binding.tree} != ${expectedTree} (commit^{tree})`);
225
- if (!isSha(receipt.binding.gate)) problems.push("receipt.binding.gate is not a sha256");
226
- }
227
- if (!isObject(receipt.stages)) { problems.push("receipt.stages is not an object"); return { ok: false, problems }; }
228
- for (const stage of stages) {
229
- const s = receipt.stages[stage];
230
- const where = `receipt.stages.${stage}`;
231
- if (!isObject(s)) { problems.push(`${where}: missing`); continue; }
232
- problems.push(...strictKeys(s, { required: ["ok", "at"], optional: STAGE_FIELDS.slice(2) }, where));
233
- if (s.ok !== true) problems.push(`${where}.ok is ${JSON.stringify(s.ok)}`);
234
- if ("voided" in s) problems.push(`${where}.voided is ${JSON.stringify(s.voided)}`);
235
- if (!Number.isFinite(Date.parse(s.at))) problems.push(`${where}.at is not a timestamp`);
236
- if (stage !== "check" && !isObject(s.snapshot)) problems.push(`${where}.snapshot is missing`);
237
- if (isObject(s.snapshot)) {
238
- if (s.snapshot.tree !== expectedTree) problems.push(`${where}.snapshot.tree ${s.snapshot.tree} != ${expectedTree}`);
239
- 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)`);
240
- if (typeof s.snapshot.path !== "string" || !s.snapshot.path) problems.push(`${where}.snapshot.path is missing`);
241
- }
242
- }
243
- return { ok: problems.length === 0, problems };
244
- }
245
-
246
- /**
247
- * 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
248
- * 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
249
- * `already passed` line for the compile proves anything about ordering or about what a compile reads.
250
- */
251
- export function compileRanFresh(log) {
252
- const t = String(log ?? "");
253
- return /\[compile\] passed in/.test(t) && !/\[compile\] already passed/.test(t);
254
- }
255
-
256
- /**
257
- * 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
258
- * 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
259
- * stage is ok. A reused compile is returned as `{ ok: false, skipped: true }`: nothing about ordering can be read from another run's `at`.
260
- * Without `log` only the receipt timestamps are compared (kept for callers that hold no log).
261
- */
262
- export function classABeforeCompile(receipt, log = null) {
263
- const check = Date.parse(receipt?.stages?.check?.at);
264
- const compile = Date.parse(receipt?.stages?.compile?.at);
265
- if (!Number.isFinite(check) || !Number.isFinite(compile)) return { ok: false, problems: ["receipt.stages.check.at and receipt.stages.compile.at are both needed"] };
266
- if (receipt.stages.check.ok !== true) return { ok: false, problems: [`receipt.stages.check.ok is ${JSON.stringify(receipt.stages.check.ok)}`] };
267
- 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}`] };
268
- 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"] };
269
- 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));
270
- if (!m) return { ok: false, problems: ["the log has no stamped `[check] passed in` line"] };
271
- const checkEnd = Date.parse(m[1]);
272
- 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}`] };
273
- }
274
-
275
- /** GC-A15, GC-A07: the output dirs a receipt records (stage outputs.dirs) are one set across stages, and none is a debug dir. */
276
- export function outputDirsProblems(receipt) {
277
- const problems = [];
278
- const sets = [];
279
- for (const [stage, s] of Object.entries(receipt?.stages ?? {})) {
280
- const dirs = s?.outputs?.dirs;
281
- if (dirs === undefined) continue;
282
- if (!Array.isArray(dirs) || dirs.some((d) => typeof d !== "string")) { problems.push(`receipt.stages.${stage}.outputs.dirs is malformed`); continue; }
283
- sets.push([stage, [...dirs].sort()]);
284
- if (s.outputs.truncated === true) problems.push(`receipt.stages.${stage}.outputs.truncated is true`);
285
- for (const d of dirs) if (/(^|[\\/])debug([\\/]|$)/.test(d)) problems.push(`receipt.stages.${stage}.outputs.dirs names a debug directory: ${d}`);
286
- }
287
- if (sets.length === 0) problems.push("no stage of the receipt records outputs.dirs");
288
- 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]}`);
289
- return { ok: problems.length === 0, problems };
290
- }
291
-
292
- /**
293
- * 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
294
- * verbatim `\\?\` spelling, so this imports the gate's own `keyPath` and `repoKey` (snapshot.mjs) instead of hashing the bare path.
295
- */
296
- export const repositoryKey = (canonicalPath, platform = process.platform) => repoKey(keyPath(canonicalPath, platform));
297
-
298
- /** GC-A23: the snapshot's `.rightkit-source-identity.json`. `trees` is `{ dir: tree id }` recomputed from git by the caller. */
299
- export function validateSourceIdentity(identity, { commit, trees }) {
300
- const problems = strictKeys(identity, { required: ["schema", "commit", "trees"] }, "source-identity");
301
- if (!isObject(identity)) return { ok: false, problems };
302
- if (identity.schema !== SOURCE_IDENTITY_SCHEMA) problems.push(`source-identity.schema is ${JSON.stringify(identity.schema)}`);
303
- if (identity.commit !== commit) problems.push(`source-identity.commit ${identity.commit} != ${commit}`);
304
- if (!isObject(identity.trees)) return { ok: false, problems: [...problems, "source-identity.trees is not an object"] };
305
- if (!("" in identity.trees)) problems.push('source-identity.trees has no "" (root) entry');
306
- 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}`);
307
- for (const dir of Object.keys(identity.trees)) if (!(dir in trees)) problems.push(`source-identity.trees has an unexpected entry ${JSON.stringify(dir)}`);
308
- return { ok: problems.length === 0, problems };
309
- }
310
-
311
- /** GC-A22 render: the receipt a `--to render` run stores. `png(name)` returns the PNG bytes of a case (or null). */
312
- export function validateRenderReceipt(receipt, { commit, png }) {
313
- const problems = strictKeys(receipt, { required: ["schema", "commit", "tree", "appDir", "package", "bin", "features", "executable", "buildOutputDir", "host", "startedAt", "endedAt", "cases"], optional: ["buildRequestId"] }, "render-receipt");
314
- if (!isObject(receipt)) return { ok: false, problems };
315
- if (receipt.schema !== RENDER_RECEIPT_SCHEMA) problems.push(`render-receipt.schema is ${JSON.stringify(receipt.schema)}`);
316
- if (receipt.commit !== commit) problems.push(`render-receipt.commit ${receipt.commit} != ${commit}`);
317
- if (!isSha(receipt.executable?.sha256)) problems.push("render-receipt.executable.sha256 is not a sha256");
318
- 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");
319
- if (!Array.isArray(receipt.cases) || receipt.cases.length === 0) { problems.push("render-receipt.cases is empty"); return { ok: false, problems }; }
320
- for (const c of receipt.cases) {
321
- const where = `render-receipt.cases[${c?.name}]`;
322
- problems.push(...strictKeys(c, { required: ["name", "png", "sha256", "bytes", "width", "height"] }, where));
323
- const bytes = isObject(c) ? png(c.png) : null;
324
- if (!bytes) { problems.push(`${where}: PNG ${c?.png} cannot be read`); continue; }
325
- 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; }
326
- if (sha256(bytes) !== c.sha256 || bytes.length !== c.bytes) problems.push(`${where}: sha256 or size differs from the receipt`);
327
- if (bytes.readUInt32BE(16) !== c.width || bytes.readUInt32BE(20) !== c.height) problems.push(`${where}: PNG width/height differ from the receipt`);
328
- }
329
- return { ok: problems.length === 0, problems };
330
- }
331
-
332
- /** 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. */
333
- export function vectorsProblems({ source, files, upstream = null, upstreamDir = null }) {
334
- const problems = strictKeys(source, { required: ["schema", "note", "source", "files"] }, "vectors-source");
335
- if (!isObject(source?.files)) return { ok: false, problems: [...problems, "vectors-source.files missing"] };
336
- for (const [name, meta] of Object.entries(source.files)) {
337
- const bytes = files[name];
338
- if (!bytes) { problems.push(`${name}: pinned but not vendored`); continue; }
339
- if (sha256(bytes) !== meta.sha256) problems.push(`${name}: vendored sha256 ${sha256(bytes).slice(0, 12)} != pinned ${String(meta.sha256).slice(0, 12)}`);
340
- if (!upstream) continue;
341
- if (!upstream[name]) problems.push(`${name}: RustRight's docs/contracts has no copy to compare with`);
342
- else if (sha256(upstream[name]) !== sha256(bytes)) problems.push(`${name}: differs from RustRight's docs/contracts copy`);
343
- }
344
- if (!upstream) problems.push(`RustRight's docs/contracts${upstreamDir ? ` (${upstreamDir})` : ""} was not found: the vendored vectors cannot be compared with their source`);
345
- for (const name of Object.keys(files)) if (name !== "vectors-source.json" && !(name in source.files)) problems.push(`${name}: vendored but not pinned`);
346
- return { ok: problems.length === 0, problems };
347
- }
348
-
349
- /** GC-I18 (static half): the digest the gate pins is the installed runtime's. */
350
- export function brokerDigestProblems({ manifest, pins }) {
351
- const problems = [];
352
- if (!isObject(manifest) || !isSha(manifest.brokerDigest)) problems.push("runtime manifest has no brokerDigest sha256");
353
- if (!isObject(pins) || !isSha(pins.brokerDigest)) problems.push("broker pins record has no brokerDigest sha256");
354
- if (!problems.length && manifest.brokerDigest !== pins.brokerDigest) problems.push(`pins brokerDigest ${pins.brokerDigest.slice(0, 12)} != runtime manifest brokerDigest ${manifest.brokerDigest.slice(0, 12)}`);
355
- return { ok: problems.length === 0, problems };
356
- }
357
-
358
- /**
359
- * S2 (GC-A24, GC-A19, NN01): a warm rerun of the same commit. Against the first run `prev` (id -> row) and the rerun `next`:
360
- * - 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:
361
- * 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;
362
- * - the key of every row equals the first run's key byte for byte.
363
- */
364
- export function assertWarmRerun(prev, next) {
365
- const problems = [];
366
- let hits = 0;
367
- for (const [id, row] of next) {
368
- if (row.coverage === "skipped" && row.status === "not-in-pass") continue;
369
- if (row.coverage === "skipped") { problems.push(`${id}: skipped (${row.reason}); a skipped row is never a pass`); continue; }
370
- 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)" : ""}`);
371
- if (row.class === "A" && row.coverage === "hit") hits += 1;
372
- const before = prev.get(id);
373
- if (row.class === "A" && before && before.key !== row.key) problems.push(`${id}: key changed between runs on one commit (${before.key} -> ${row.key})`);
374
- if (row.class === "A" && !before) problems.push(`${id}: not present in the first run`);
375
- }
376
- if (hits === 0) problems.push("no Class A row hit: the rerun proves nothing about warmth");
377
- return { ok: problems.length === 0, problems, hits };
378
- }
379
-
380
- /**
381
- * 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
382
- * Class A key equals the previous run. `perFile` is a RegExp of the row ids allowed to run besides rustfmt.
383
- */
384
- export function assertOneFileEdit(prev, next, { perFile = /^(secret-scan|licen[cs]e)/ } = {}) {
385
- const problems = [];
386
- const ranA = [...next.values()].filter((r) => r.class === "A" && r.coverage === "ran");
387
- const rustfmt = ranA.filter((r) => r.id.startsWith("rustfmt"));
388
- if (rustfmt.length !== 1) problems.push(`${rustfmt.length} rustfmt rows ran, expected exactly 1 (${rustfmt.map((r) => r.id).join(", ")})`);
389
- 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`);
390
- // 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).
391
- for (const r of ranA) {
392
- const before = prev.get(r.id);
393
- if (!before) problems.push(`${r.id}: ran but is absent from the previous run, so no changed key can be shown`);
394
- 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`);
395
- }
396
- for (const [id, row] of next) {
397
- if (row.class !== "A" || row.coverage === "skipped") continue;
398
- const before = prev.get(id);
399
- if (row.coverage === "hit" && before && before.key !== row.key) problems.push(`${id}: key changed but the row answered hit`);
400
- if (row.coverage === "hit" && !before) problems.push(`${id}: hit but absent from the previous run`);
401
- }
402
- return { ok: problems.length === 0, problems, ran: ranA.map((r) => r.id) };
403
- }
404
-
405
- const metadataLabel = (id) => (id === "cargo-metadata" ? "." : id.startsWith("cargo-metadata:") ? id.slice("cargo-metadata:".length) : null);
406
- const packageListUnit = (id) => (id.startsWith("cargo-package-list:") ? id.slice("cargo-package-list:".length) : id === "cargo-package-list" ? "" : null);
407
-
408
- /**
409
- * S4 (GC-A19): a manifest edit reruns `cargo-metadata` and `cargo-package-list` for the edited manifest's workspace ONLY. `workspace` is that
410
- * workspace's directory ("." for the root), `workspaces` every workspace directory of the commit and `crates` `{ workspaceDir: [crate names] }`.
411
- * 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
412
- * ran, and any such row that cannot be attributed to a workspace, fails.
413
- */
414
- export function assertManifestEdit(prev, next, { workspace, workspaces = [], crates = {} } = {}) {
415
- const problems = [];
416
- if (typeof workspace !== "string") return { ok: false, problems: ["the edited manifest's workspace is not known"], ran: [] };
417
- const wsOfLabel = (label) => {
418
- if (workspaces.includes(label)) return label;
419
- const byCrate = workspaces.find((w) => w === `crates/${label}`);
420
- return byCrate ?? null;
421
- };
422
- const crateWs = (unit) => {
423
- const name = unit.includes(":") ? unit.slice(unit.lastIndexOf(":") + 1) : unit;
424
- const owners = Object.entries(crates).filter(([, names]) => names.includes(name)).map(([w]) => w);
425
- return owners.length === 1 ? owners[0] : null;
426
- };
427
- const ran = [];
428
- let ownMetadata = false;
429
- for (const row of next.values()) {
430
- const label = metadataLabel(row.id);
431
- const unit = packageListUnit(row.id);
432
- if (label === null && unit === null) continue;
433
- const ws = label !== null ? (workspaces.length === 0 && label === "." ? "." : wsOfLabel(label)) : crateWs(unit);
434
- const own = ws === workspace;
435
- if (row.coverage === "skipped" && row.status !== "not-in-pass") problems.push(`${row.id}: skipped (${row.reason}); a skipped row is never a pass`);
436
- if (row.coverage === "ran") {
437
- ran.push(row.id);
438
- if (ws === null) problems.push(`${row.id}: ran but belongs to no known workspace`);
439
- else if (!own) problems.push(`${row.id}: ran for workspace ${JSON.stringify(ws)}, which the edit (workspace ${JSON.stringify(workspace)}) does not touch`);
440
- else {
441
- const before = prev?.get(row.id);
442
- if (!before || before.key === row.key) problems.push(`${row.id}: ran without a changed key (${before ? "same key as before" : "absent before"})`);
443
- }
444
- }
445
- if (own && label !== null) {
446
- ownMetadata = true;
447
- if (row.coverage !== "ran") problems.push(`${row.id}: the edited workspace's cargo-metadata answered ${row.coverage}, expected ran`);
448
- }
449
- if (own && unit !== null && row.coverage === "hit") problems.push(`${row.id}: a cargo-package-list row of the edited workspace answered hit`);
450
- }
451
- if (!ownMetadata) problems.push(`no cargo-metadata row for workspace ${JSON.stringify(workspace)} exists in the run`);
452
- return { ok: problems.length === 0, problems, ran };
453
- }
454
-
455
- /**
456
- * A negative case: exit non-zero, every named signal in the output, and "zero later work": no stage after the failing one passed. `signals` are
457
- * the exact rule codes the gate emits (RegExp or string; every one must match). `expectRows` name coverage rows the gate must have reported for the
458
- * scan that refused: `{ id: string|RegExp, coverage, status }`; they are read from `rows` (the run's merged coverage report, id -> row), and no report
459
- * is a failure. `laterStages` are stage names that must not have `passed in` lines. A bare word in the log is never a signal.
460
- */
461
- export function assertNegative({ exit, text, signals = [], laterStages = [], receipt = null, rows = null, expectRows = [] }) {
462
- const problems = [];
463
- if (exit === 0) problems.push("exit 0: the gate accepted a broken input");
464
- if (exit === null) problems.push("the gate did not exit (killed or timed out)");
465
- for (const s of signals) if (!(s instanceof RegExp ? s.test(text) : text.includes(s))) problems.push(`output does not name ${s}`);
466
- if (expectRows.length) {
467
- if (!rows || rows.size === 0) problems.push("no coverage report was read, so the scan that refused cannot be named");
468
- else for (const want of expectRows) {
469
- const hit = [...rows.values()].find((r) => (want.id instanceof RegExp ? want.id.test(r.id) : r.id === want.id) && r.coverage === want.coverage && r.status === want.status);
470
- if (!hit) problems.push(`no coverage row ${want.id} ${want.coverage}/${want.status}: ${[...rows.values()].filter((r) => (want.id instanceof RegExp ? want.id.test(r.id) : r.id === want.id)).map((r) => `${r.id} ${r.coverage}/${r.status}`).join(", ") || "none with that id"}`);
471
- }
472
- }
473
- const passed = new Set(stageTimings(text).filter((t) => t.ok).map((t) => t.stage));
474
- for (const stage of laterStages) {
475
- if (passed.has(stage)) problems.push(`stage ${stage} passed after the failure`);
476
- if (receipt?.stages?.[stage]?.ok === true) problems.push(`receipt.stages.${stage}.ok is true after the failure`);
477
- }
478
- return { ok: problems.length === 0, problems };
479
- }
480
-
481
- /** The release-tier app-check rules (app-check.mjs: tierOf) and the baseline-growth finding; each prints `FAIL <rule> (<gap>): ...` / `UNAPPROVED baseline entry`. */
482
- export const RELEASE_TIER_RULES = Object.freeze(["mandatory-foundation", "ownership-exceptions", "trust-policy-exclude", "commit-citations"]);
483
-
484
- /** S1: a refused `--to qualify` must name a release-tier rule by the exact line the check prints, and record no ok qualify stage. */
485
- export function qualifyRefusal({ exit, text, receipt = null }) {
486
- const problems = [];
487
- if (exit === 0) problems.push("exit 0: not a refusal");
488
- if (exit === null) problems.push("the gate did not exit (killed or timed out)");
489
- const named = RELEASE_TIER_RULES.filter((id) => new RegExp(`\\bFAIL ${id} \\(`).test(text));
490
- if (/\bUNAPPROVED baseline entry\b/.test(text)) named.push("UNAPPROVED");
491
- if (!named.length) problems.push("the refusal names no release-tier rule (expected a `FAIL <rule> (<gap>)` line for one of " + `${RELEASE_TIER_RULES.join(", ")}` + " or `UNAPPROVED baseline entry`)");
492
- if (receipt?.stages?.qualify?.ok === true) problems.push("the receipt records qualify ok after a refusal");
493
- return { ok: problems.length === 0, problems, named };
494
- }
495
-
496
- const SIGNUM = Object.freeze({ SIGINT: 2, SIGKILL: 9, SIGTERM: 15 });
497
- /** Whether a stopped gate was stopped by `killSignal`: the signal itself, or 128+n (a shell wrapper); on Windows the code `taskkill /F` gives (1). */
498
- export function exitedBySignal({ signal, exit, killSignal, platform = process.platform }) {
499
- if (platform === "win32") return exit === 1 && (signal === null || signal === undefined);
500
- if (signal) return signal === killSignal;
501
- return exit !== null && exit === 128 + (SIGNUM[killSignal] ?? -1000);
502
- }
503
-
504
- /**
505
- * Kill-and-recover (K01, SIGKILL; also the SIGINT variant): `before` is the snapshot lock read right after the kill (or null when none), `next` the following gate
506
- * run `{ exit, text }`, `after` the lock read after it (null: released). Pass when the next run starts without any operator step and either reclaims the dead owner's
507
- * lock on the stale-owner rule (the log names the reclaim, the token is replaced) or finds nothing held (SIGINT released it). A lock that survives a SIGKILL stays
508
- * until the next run: its body names the dead owner (`pid`, `token`), and nothing but that run's reclaim removes it.
509
- */
510
- export function assertRecovery({ signal, before, next, after, exitedBySignal = true }) {
511
- const problems = [];
512
- if (!exitedBySignal) problems.push(`the gate was not stopped by ${signal}`);
513
- if (signal === "SIGKILL" && !before) problems.push("no snapshot lock stood after SIGKILL: the gate released nothing, so it must have been killed before taking it; the case proved nothing");
514
- if (before) {
515
- if (!isObject(before) || typeof before.token !== "string" || !Number.isInteger(before.pid)) problems.push("the snapshot lock is malformed (no token or pid)");
516
- const claim = reclaimLine(next?.text ?? "");
517
- if (!claim) problems.push("the next run's log has no 'reclaimed from' line");
518
- else if (isObject(before) && claim.token === before.token) problems.push("the next run holds the dead owner's own token: the lock was not replaced");
519
- if (isObject(before) && isObject(after) && after.token === before.token) problems.push("the snapshot lock still carries the dead token after the next run");
520
- }
521
- if (next?.exit !== 0) problems.push(`the next run exited ${next?.exit}`);
522
- return { ok: problems.length === 0, problems };
523
- }
524
-
525
- /** S9: two git listings taken at different times must be byte equal. */
526
- export function sameListing(name, a, b) {
527
- return a === b ? { ok: true, problems: [] } : { ok: false, problems: [`${name} changed: ${JSON.stringify(a).slice(0, 160)} -> ${JSON.stringify(b).slice(0, 160)}`] };
528
- }
529
-
530
- /** S9 and GC-A01: the one-worktree rule (`git worktree list --porcelain` has one `worktree ` row). */
531
- export const worktreeCount = (porcelain) => String(porcelain).split(/\r?\n/).filter((l) => l.startsWith("worktree ")).length;
532
-
533
- /** GC-A01 and N13: a bypass refusal names the retired option and ran nothing. */
534
- export function bypassRefused({ exit, text }) {
535
- const problems = [];
536
- if (exit === 0 || exit === null) problems.push(`exit ${exit}: the bypass was not refused`);
537
- if (!/retired/.test(text)) problems.push("the refusal text does not say the option is retired");
538
- if (/\[(check|compile)\] (passed|failed) in/.test(text)) problems.push("a stage ran under a refused bypass");
539
- return { ok: problems.length === 0, problems };
540
- }
541
-
542
- /** S9: no publish or upload happened (GC-T22 negative): log markers of an upload that completed. */
543
- export function publicationMarkers(text) {
544
- return String(text).split(/\r?\n/).filter((l) => /\b(uploaded to|upload complete|published release|gh release create|r2 put)\b/i.test(l)).slice(0, 5);
545
- }
546
-
547
- /**
548
- * GC-A01, GC-T14: every directory of the snapshot root that belongs to this repository (its name starts with the repository key: the snapshot, a
549
- * leftover `.staging`, any second spelling) must be exactly `<key>`; and no directory that was not there at S0 may have appeared besides it.
550
- * `before` and `after` are directory-name listings of `<managed root>/snapshots` (`before` null: S0 did not run).
551
- */
552
- export function snapshotDirProblems({ key, before = null, after }) {
553
- const problems = [];
554
- const ours = after.filter((n) => n.startsWith(key));
555
- if (!ours.includes(key)) problems.push(`the snapshot dir ${key} does not exist`);
556
- for (const n of ours) if (n !== key) problems.push(`a second snapshot dir for the repository: ${n}`);
557
- if (before) for (const n of after) if (!before.includes(n) && !n.startsWith(key)) problems.push(`a new snapshot dir appeared during the run: ${n}`);
558
- return { ok: problems.length === 0, problems, dirs: ours };
559
- }
560
-
561
- /** GC-T20: no hook of the fixture's hooks directory (`.sample` files excepted) mentions the gate. `files` is `{ name: text }`. */
562
- export function hookProblems({ files, hooksPath = null }) {
563
- const problems = [];
564
- for (const [name, text] of Object.entries(files)) {
565
- if (name.endsWith(".sample")) continue;
566
- if (/rightkit-gate|rightkit-host-gate|rightkit_gate|gate\.mjs/i.test(String(text))) problems.push(`hook ${name} runs the gate`);
567
- }
568
- return { ok: problems.length === 0, problems };
569
- }
570
-
571
- /**
572
- * S6 (GC-A04, GC-A02, GC-T06): proof, read while the checkout is dirty, that the snapshot of the compile holds the COMMIT's bytes and not the
573
- * checkout's. `commitBytes` is the edited file as the commit has it, `checkoutBytes` as the dirty checkout has it, `snapshotBytes` as the snapshot
574
- * has it (null: absent), `untrackedInSnapshot` whether the untracked file reached the snapshot, `identityProblems` the source-identity check of the
575
- * snapshot against the commit's trees, and `receiptTree`/`expectedTree` the tree the compile bound against `commit^{tree}`.
576
- */
577
- export function dirtyProof({ commitBytes, checkoutBytes, snapshotBytes, untrackedInSnapshot, identityProblems = [], receiptTree, expectedTree }) {
578
- const problems = [...identityProblems];
579
- if (!Buffer.isBuffer(commitBytes) || !Buffer.isBuffer(checkoutBytes)) problems.push("the commit's or the checkout's bytes of the edited file are missing");
580
- else if (commitBytes.equals(checkoutBytes)) problems.push("the checkout file equals the commit's: the checkout was not dirty, so the case proves nothing");
581
- if (!Buffer.isBuffer(snapshotBytes)) problems.push("the snapshot does not hold the edited file");
582
- else {
583
- if (Buffer.isBuffer(commitBytes) && !snapshotBytes.equals(commitBytes)) problems.push("the snapshot's file differs from the commit's bytes");
584
- if (Buffer.isBuffer(checkoutBytes) && snapshotBytes.equals(checkoutBytes)) problems.push("the snapshot's file carries the dirty checkout's bytes");
585
- }
586
- if (untrackedInSnapshot) problems.push("the untracked checkout file reached the snapshot");
587
- if (receiptTree !== expectedTree) problems.push(`the compile's tree ${receiptTree} != commit^{tree} ${expectedTree}`);
588
- return { ok: problems.length === 0, problems };
589
- }
590
-
591
- /**
592
- * 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`
593
- * with verbatim arguments. Every argument and the launcher path must be free of cmd metacharacters (`" % ^ & | < > CR LF`); one that is not throws.
594
- */
595
- export function launchSpec(gate, args, { platform = process.platform, comspec = process.env.ComSpec || "cmd.exe" } = {}) {
596
- if (platform !== "win32" || !/\.(cmd|bat)$/i.test(gate)) return { command: gate, args, options: {} };
597
- const unsafe = /["%^&|<>\r\n]/;
598
- 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`);
599
- const quote = (a) => (a === "" || /\s/.test(a) ? `"${a}"` : a);
600
- return { command: comspec, args: ["/d", "/s", "/c", `"${[gate, ...args].map(quote).join(" ")}"`], options: { windowsVerbatimArguments: true } };
601
- }
602
-
603
- // ---------------------------------------------------------------------------------------------------------------------------------------------
604
- // The run sequence (criteria.md section 3) and the clauses each step asserts.
605
- // ---------------------------------------------------------------------------------------------------------------------------------------------
606
- // ---------------------------------------------------------------------------------------------------------------------------------------------
607
- // 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.
608
- // 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".
609
- // `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
610
- // 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.
611
- // ---------------------------------------------------------------------------------------------------------------------------------------------
612
- export const NN = Object.freeze([
613
- { id: "NN01", steps: ["S2"], title: "An unchanged commit runs no Class A row", evidence: "warm --to check and --to compile coverage, twice" },
614
- { id: "NN02", steps: ["S2"], title: "An unchanged commit runs no Class B row", evidence: "warm --to compile coverage, twice" },
615
- { id: "NN03", steps: ["S3"], title: "One edited .rs file reruns only the rows that read it", evidence: "S3 coverage" },
616
- { id: "NN04", steps: ["S4"], title: "One edited manifest reruns only its workspace's rows", evidence: "S4 coverage" },
617
- { id: "NN05", steps: ["S2"], title: "Keys are stable across identical runs", evidence: "coverage keys of two warm runs of check and of compile" },
618
- { id: "NN06", steps: ["S1", "S2"], title: "Only executing rows carry the environment digest", evidence: "coverage keys, the log's env digest" },
619
- { id: "NN07", steps: ["S1", "S2", "S3", "S4", "S10"], title: "No identical child process twice in one run", evidence: "spawn ledger" },
620
- { id: "NN08", steps: ["S1", "S2", "S3", "S4", "S10"], title: "rustfmt is one process per bucket; no cargo fmt", evidence: "spawn ledger, coverage" },
621
- { id: "NN09", steps: ["S1", "S2", "S3", "S4", "S10"], title: "Non-compiling cargo never goes through the broker", evidence: "spawn ledger" },
622
- { id: "NN10", steps: ["S2"], title: "Inside a snapshot the resident gate answers cargo metadata", evidence: "spawn ledger of the warm runs" },
623
- { 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)" },
624
- { 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" },
625
- { 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" },
626
- { id: "NN14", steps: ["S2"], title: "Preflight and app rules run once per tree", evidence: "gate log of the warm runs" },
627
- { id: "NN15", steps: ["S2"], title: "Advice scans are cached per lock set and UTC day or hour", evidence: "warm coverage" },
628
- { 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" },
629
- { id: "NN17", steps: ["S1", "S2"], title: "Class A lanes equal the host's cores; Class B batches compatible rows", evidence: "gate log, spawn ledger" },
630
- { 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" },
631
- { id: "NN19", steps: ["S0"], always: true, title: "The gate under test is the installed sealed gate", evidence: "--version, launcher" },
632
- ]);
633
- export const NN_IDS = Object.freeze(NN.map((n) => n.id));
634
- /** NN20-NN42 (GC-A27 as extended 2026-11-05). `post` ones are judged from the finished result (NN34, NN35). */
635
- export const NN_EXT = Object.freeze([
636
- { id: "NN20", steps: ["S12"], title: "One edited crate recompiles only that crate and its dependents", evidence: "S12 crate-edit compile coverage" },
637
- { id: "NN21", steps: ["S12"], title: "One edited lockfile reruns only the rows that read it", evidence: "S12 lock-edit coverage" },
638
- { id: "NN22", steps: ["S2"], title: "A warm snapshot sync writes and removes nothing", evidence: "sync lines and spawn ledger of the warm runs" },
639
- { 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" },
640
- { 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" },
641
- { 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" },
642
- { id: "NN26", steps: ["S2"], title: "The gate asks the resident gate over its socket, in process", evidence: "spawn ledger" },
643
- { id: "NN27", steps: ["S1"], title: "Never two compiler passes over one crate, target and feature set", evidence: "S1 compile coverage" },
644
- { id: "NN28", steps: ["S2"], title: "Change detection comes from RightKit's file index and watcher", evidence: "gate log (change-source), spawn ledger" },
645
- { 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" },
646
- { 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" },
647
- { 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" },
648
- { id: "NN32", steps: ["S8"], title: "A killed run's snapshot lock is reclaimed by the next run on both hosts", evidence: "S8 kill cases" },
649
- { id: "NN33", steps: ["S0"], always: true, title: "The contract and the test match", evidence: "docs/GATE-CONTRACT.md NN table" },
650
- { id: "NN34", steps: ["S0"], always: true, post: true, title: "Missing evidence fails; a partial run never passes", evidence: "the finished result" },
651
- { 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" },
652
- { id: "NN36", steps: ["S0"], always: true, title: "The test is locked", evidence: "git history of the runner, the contract table, the budgets" },
653
- { id: "NN37", steps: ["S0"], always: true, title: "The test's author is not the implementer", evidence: "budgets.reviews" },
654
- { id: "NN38", steps: ["S1"], title: "Cross-target rows built with stand-ins are limited evidence", evidence: "coverage and receipt of the compile" },
655
- { id: "NN39", steps: ["S11"], title: "The parallelism is real, not configured", evidence: "spawn ledger start and end times of the cold runs" },
656
- { 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" },
657
- { 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)" },
658
- { 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" },
659
- ]);
660
- export const NN_ALL = Object.freeze([...NN, ...NN_EXT]);
661
- export const NN_ALL_IDS = Object.freeze(NN_ALL.map((n) => n.id));
662
- export const nnForStep = (stepId) => NN.filter((n) => n.steps.includes(stepId)).map((n) => n.id);
663
- export const nnForStepAll = (stepId) => NN_ALL.filter((n) => n.steps.includes(stepId)).map((n) => n.id);
664
- /** The labels of the four warm runs of S2 (two of check, two of compile), in run order. */
665
- export const WARM_LABELS = Object.freeze(["S2:check", "S2:compile", "S2:check2", "S2:compile2"]);
666
- export const BUDGETS_SCHEMA = "rightkit.gate-acceptance-budgets/1";
667
- export const BUDGETS_FILE = path.resolve(here, "..", "..", "ci", "gate-acceptance-budgets.json");
668
-
669
- export const LADDER = Object.freeze(["check", "compile", "test", "render", "dev", "package", "qualify"]);
670
- /** Stages that install an app on the host; they run only with `--allow-install` (Adrian's approval), never by default. */
671
- export const INSTALL_STAGES = Object.freeze(["dev", "qualify"]);
672
- export const ladderStages = ({ allowInstall = false } = {}) => LADDER.filter((s) => allowInstall || !INSTALL_STAGES.includes(s));
673
- const RECEIPT_STAGES = new Set(["check", "compile", "package", "qualify"]);
674
-
675
- export const NEGATIVES = Object.freeze([
676
- { id: "N01", title: "misformatted .rs", signals: [], expectRows: [{ id: /^rustfmt:/, coverage: "ran", status: "fail" }], later: ["compile"], clauses: ["GC-T05"], build: "misformat-rs" },
677
- { id: "N02", title: "secret-shaped string in a tracked file", signals: [], expectRows: [{ id: "secret-scan", coverage: "ran", status: "fail" }], later: ["compile"], clauses: ["GC-T05", "GC-A22-classA"], build: "secret-file" },
678
- { id: "N13", title: "--no-cache and RK_GATE_CACHE=0 refused", signals: [], later: ["check"], clauses: ["GC-A01", "GC-T14"], build: "bypass" },
679
- { id: "N15", title: "[profile.dev] in a Cargo.toml", signals: [/\[profile-extra\]/, "[profile.dev] is not allowed"], later: ["compile"], clauses: ["GC-A15"], build: "profile-dev" },
680
- { id: "N26", title: "extra Cargo workspace not in ci/gate.config.json", signals: [/RK_CARGO_WORKSPACE_LIST_DIFFERS/], later: ["compile"], clauses: ["GC-1A-R4"], build: "extra-workspace" },
681
- { id: "N27", title: "--no-broker x with no exception entry", signals: [/RK_BROKER_EXCEPTION_MISSING/], later: ["compile"], clauses: ["GC-1A-R2"], build: "no-broker", args: ["--no-broker", "acceptance-no-such-exception"] },
682
- ]);
683
- export const NEGATIVES_UNCHECKED = Object.freeze({
684
- N03: "needs a Cargo.toml/Cargo.lock pair edit the fixture's resolver must agree with", N04: NEEDS_FIXTURE, N05: NEEDS_FIXTURE, N06: NEEDS_FIXTURE, N07: NEEDS_FIXTURE, N08: NEEDS_FIXTURE, N09: NEEDS_FIXTURE,
685
- N10: "snapshot tamper is a write into the gate's snapshot dir; run by hand under the lead's approval", N11: "covered by S6", N12: "needs a build window (the `slow` crate, F2)", N14: NEEDS_FIXTURE, N16: NEEDS_FIXTURE,
686
- N17: NEEDS_FIXTURE, N18: "needs a broker endpoint override the runner does not set", N19: NEEDS_FIXTURE, N20: NEEDS_FIXTURE, N21: NEEDS_FIXTURE, N22: NEEDS_FIXTURE, N23: NEEDS_FIXTURE, N24: NEEDS_FIXTURE,
687
- N25: NEEDS_FIXTURE, N28: NEEDS_FIXTURE, N29: NEEDS_FIXTURE, N30: NEEDS_FIXTURE, N31: NEEDS_FIXTURE, N33: NEEDS_FIXTURE, N34: NEEDS_FIXTURE, N35: NEEDS_FIXTURE, N36: NEEDS_FIXTURE, N37: NEEDS_FIXTURE,
688
- });
689
- export const KILLS = Object.freeze([
690
- { id: "K01", signal: "SIGKILL", at: "snapshot lock exists (held) plus --kill-after-ms, during --to compile", clauses: ["GC-T06"] },
691
- { id: "K01-int", signal: "SIGINT", at: "same point as K01", clauses: ["GC-T06"] },
692
- { id: "K02", signal: "SIGKILL", at: "during --to check, after the snapshot lock exists (the lock is held across Class A by design, reset plan section 3)", clauses: ["GC-A24"] },
693
- { id: "K02-int", signal: "SIGINT", at: "same point as K02", clauses: ["GC-A24"] },
694
- ]);
695
- export const KILLS_UNCHECKED = Object.freeze({
696
- K03: "no defined kill point inside the snapshot sync is observable from outside the gate", K04: "the resident gate-serve process is not identifiable by the runner", K05: "needs a hook between broker submit and acknowledgement", K06: NEEDS_FIXTURE,
697
- });
698
-
699
- export const STEPS = Object.freeze([
700
- { id: "S0", nn: nnForStep("S0"), title: "preflight (static)", runs: [], clauses: ["GC-I22", "GC-I18", "GC-I01", "GC-I15", "GC-T20"], note: "fixture clean, listings recorded, vector hashes, broker digest manifest vs pins" },
701
- { id: "S1", nn: nnForStep("S1"), title: "baseline ladder on C0", runs: ladderStages().map((s) => `--to ${s}`), clauses: ["GC-A04", "GC-A15", "GC-A21", "GC-A22-render", "GC-A22-classA", "GC-A23", "GC-T04", "GC-T05", "GC-T19", "GC-I01", "GC-I03", "GC-I05"], note: "--to dev and --to qualify install an app: only with --allow-install (Adrian's approval); with it, --to qualify may refuse with a named release-tier rule, asserted as such" },
702
- { id: "S2", nn: nnForStep("S2"), title: "warm rerun, same commit (twice)", runs: ["--to check", "--to compile", "--to check", "--to compile"], clauses: ["GC-A24", "GC-A19", "GC-A21"], note: "every Class A row hits with its first-run key; no Class B row runs; the second pair of runs is the identical rerun NN05 compares" },
703
- { id: "S3", nn: nnForStep("S3"), title: "one-file edit (ephemeral commit)", runs: ["--to check"], clauses: ["GC-A24"], note: "needs a tracked rk/**/src/lib.rs (or --leaf-file); else unchecked" },
704
- { id: "S4", nn: nnForStep("S4"), title: "manifest edit (ephemeral commit)", runs: ["--to check"], clauses: ["GC-A19"], note: "needs a tracked Cargo.toml (or --manifest-file); else unchecked" },
705
- { id: "S5", nn: nnForStep("S5"), title: "lock edit", runs: [], clauses: ["GC-A19", "GC-A24"], note: "unchecked by design: a lock edit needs the fixture's own resolver; not generated by this runner", byDesignUnchecked: true },
706
- { id: "S6", nn: nnForStep("S6"), title: "dirty checkout", runs: ["--to compile"], clauses: ["GC-A02", "GC-A04", "GC-T06"], note: "refuses a dirty fixture; ephemeral commit (a compile not yet recorded) built while the checkout has a dirty tracked edit, an untracked file and a pushed stash; the snapshot is compared with the commit; the checkout and the stash list are restored exactly" },
707
- { id: "S7", nn: nnForStep("S7"), title: "negatives", runs: NEGATIVES.map((n) => n.id), clauses: ["GC-T05", "GC-A01", "GC-T14", "GC-A15", "GC-1A-R2", "GC-1A-R4"], note: "ephemeral commits under refs/witness/*; the rest listed unchecked with their reason" },
708
- { id: "S8", nn: nnForStep("S8"), title: "kill and recover", runs: KILLS.map((k) => k.id), clauses: ["GC-T06", "GC-A24"], note: "SIGKILL (during compile and during Class A) and SIGINT; the lock stays after SIGKILL; the next run reclaims it on the stale-owner rule and passes" },
709
- { id: "S10", nn: nnForStep("S10"), title: "unit list (--units-file, two fixture units)", runs: ["--to check --units-file"], clauses: [], note: "NN16: the list shares one Class A and runs no cargo fmt -p; needs two units of the gate's unit grammar (crates/rightkit-<x>, packages/<x>) in the fixture, else NN16 fails naming the gap" },
710
- { id: "S11", nn: nnForStepAll("S11"), title: "cold run (the gate's cache dir moved aside under scratch, then restored)", runs: ["--to check", "--to compile"], clauses: [], note: "NN18 cold budgets; real-condition controls that NN01, NN02, NN03, NN04, NN14, NN15, NN20, NN21, NN24, NN29 fail on a run where every row really ran" },
711
- { id: "S12", nn: nnForStepAll("S12"), title: "compile-side edits: one crate, one lockfile, one manifest", runs: ["--to compile (crate edit)", "--to check (lock edit)", "--to compile (manifest edit)"], clauses: [], note: "ephemeral commits under refs/witness/*; NN20, NN21, NN04 on --to compile" },
712
- { id: "S13", nn: nnForStepAll("S13"), title: "gate upgrade: the two newest sealed gates run the same commit", runs: ["--to check (previous gate)", "--to check (newest gate)"], clauses: [], note: "NN23; with fewer than two sealed versions it FAILS: needs two installed versions" },
713
- { id: "S14", nn: nnForStepAll("S14"), title: "resident gate restart", runs: ["--to check"], clauses: [], note: "kills the resident gate (SIGTERM, a plain process stop), then a warm check must run no row (NN24)" },
714
- { id: "S15", nn: nnForStepAll("S15"), title: "workloads: RightKit and HeardRight warm check (read-only), Pulse compile with --pulse-compile", runs: ["--to check (rightkit)", "--to check (heardright)"], clauses: [], note: "NN18 per-workload budgets; no compile unless --pulse-compile" },
715
- { id: "S16", nn: nnForStepAll("S16"), title: "per-run identities differ", runs: ["--to check"], clauses: [], note: "NN29: a fake tool-call id, terminal session, temp dir and RK_GATE_* value; every key equals the warm run's" },
716
- { id: "S17", nn: nnForStepAll("S17"), title: "cached failure: a commit with a real compile error, run twice, then with another toolchain", runs: ["--to compile (failing commit)", "--to compile (same commit again)", "--to compile (RUSTUP_TOOLCHAIN changed)"], clauses: [], note: "NN41; ephemeral commit under refs/witness/* that adds compile_error! to one fixture crate; the second run's failing rows must be hit, the third (another installed toolchain) must run them again" },
717
- { id: "S9", nn: nnForStep("S9"), title: "end invariants", runs: [], clauses: ["GC-A01", "GC-A02", "GC-T14", "GC-T06", "GC-I15", "GC-T20"], note: "listings equal S0; one snapshot dir and no new one; one worktree; no upload; broker pid and start unchanged" },
718
- ]);
719
-
720
- /** The plan `--plan` prints (and tests read): steps, runs and the clause mapping, with implemented vs unchecked. */
721
- export function buildPlan({ steps = STEPS.map((s) => s.id), allowInstall = false } = {}) {
722
- const chosen = STEPS.filter((s) => steps.includes(s.id));
723
- const implemented = new Set(Object.keys(CHECKS));
724
- const clauses = Object.values(CLAUSES).map((c) => ({ id: c.id, ev: c.ev, title: c.title, implemented: implemented.has(c.id), steps: chosen.filter((s) => s.clauses.includes(c.id)).map((s) => s.id), ...(implemented.has(c.id) ? {} : { unchecked: installReason(c.id, allowInstall) ?? UNCHECKED_WHY[c.id] ?? NO_EVIDENCE }) }));
725
- const nonNegotiables = NN.map((n) => ({ id: n.id, title: n.title, steps: n.steps, evidence: n.evidence, selected: Boolean(n.always) || n.steps.every((x) => chosen.some((c) => c.id === x)) }));
726
- return { schema: "rightkit.gate-acceptance-plan/1", allowInstall, installStagesSkipped: allowInstall ? [] : [...INSTALL_STAGES], steps: chosen, nonNegotiables, negativesUnchecked: NEGATIVES_UNCHECKED, killsUnchecked: KILLS_UNCHECKED, clauses };
727
- }
728
-
729
- /** The reason a clause that needs `--to dev` / `--to qualify` evidence is unchecked while installs are not approved; null otherwise. */
730
- export const installReason = (id, allowInstall) => (!allowInstall && INSTALL_CLAUSES.includes(id) ? NEEDS_INSTALL_APPROVAL : null);
731
-
732
- export function formatPlan(plan) {
733
- const out = [];
734
- for (const s of plan.steps) out.push(`${s.id} ${s.title}${s.runs.length ? ` [${s.runs.join(", ")}]` : ""}`, ` clauses: ${s.clauses.join(" ") || "-"}`, ` non-negotiables: ${s.nn?.join(" ") || "-"}${s.nn?.includes("NN19") ? " (evaluated in every run)" : ""}`, ` ${s.note}`);
735
- const impl = plan.clauses.filter((c) => c.implemented);
736
- const un = plan.clauses.filter((c) => !c.implemented);
737
- out.push("", `clauses: ${plan.clauses.length} total, ${impl.length} asserted, ${un.length} unchecked by design`);
738
- out.push(`asserted: ${impl.map((c) => `${c.id}(${c.ev})`).join(" ")}`);
739
- out.push(`unchecked: ${un.map((c) => `${c.id}(${c.ev})`).join(" ")}`);
740
- if (plan.installStagesSkipped?.length) out.push(`install stages not run: --to ${plan.installStagesSkipped.join(", --to ")} (they install an app; pass --allow-install only with Adrian's approval); clauses needing them: ${INSTALL_CLAUSES.join(" ")}`);
741
- out.push(`negatives not built: ${Object.keys(plan.negativesUnchecked).join(" ")}`, `kills not built: ${Object.keys(plan.killsUnchecked).join(" ")}`);
742
- out.push("", `non-negotiables (${(plan.nonNegotiables ?? []).length}; never unchecked on a host that can run them: missing evidence fails the run):`);
743
- for (const n of plan.nonNegotiables ?? []) out.push(` ${n.id} steps ${n.steps.join("+")}${n.selected ? "" : " (not selected)"} ${n.title} [${n.evidence}]`);
744
- out.push("", `extended non-negotiables NN20-NN42 (${NN_EXT.length}):`);
745
- for (const n of NN_EXT) out.push(` ${n.id} steps ${n.steps.join("+")}${n.always ? " (every run)" : ""} ${n.title} [${n.evidence}]`);
746
- return out.join("\n");
747
- }
748
-
749
- // ---------------------------------------------------------------------------------------------------------------------------------------------
750
- // Clause assertions. Each CHECKS entry is `(ctx) => { status: "pass"|"fail"|"unchecked", evidence: [..], problems: [..] }` or a list of them. `ctx.runs`
751
- // 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
752
- // -> fail; else all real checks pass and no blocking "missing" part -> pass; else unchecked.
753
- // ---------------------------------------------------------------------------------------------------------------------------------------------
754
- const verdict = (res, evidence) => ({ status: res.ok ? "pass" : "fail", evidence, problems: res.problems });
755
- const unchecked = (why) => ({ status: "unchecked", evidence: [], problems: [why] });
756
- /** An unchecked part that keeps the clause from passing although other parts passed. */
757
- const missing = (why) => ({ status: "unchecked", blocksPass: true, evidence: [], problems: [why] });
758
- const needRun = (ctx, label) => ctx.runs[label] ?? null;
759
- const expectedFailure = (r) => Boolean(r.negative) || r.refusal !== undefined;
760
- const firstRows = (ctx, ...labels) => { for (const l of labels) if (ctx.runs[l]?.rows) return ctx.runs[l]; return null; };
761
-
762
- /**
763
- * 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
764
- * entries the broker alternates between at a cutover (`dev.rustright.broker`, `dev.rustright.broker.b`) is running. Windows: exactly one `rustright-broker` process.
765
- * Linux has no broker. `run` and `uid` are test seams.
766
- */
767
- export function runningBrokerProcess({ platform = process.platform, run = spawnSync, uid = process.getuid?.() } = {}) {
768
- if (platform === "win32") {
769
- try {
770
- const script = "$p = @(Get-Process -Name rustright-broker -ErrorAction SilentlyContinue); if ($p.Count -eq 1) { \"$($p[0].Id) $($p[0].StartTime.ToUniversalTime().ToString('o'))\" }";
771
- const r = run("powershell.exe", ["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(script, "utf16le").toString("base64")], { encoding: "utf8", timeout: 15000, windowsHide: true });
772
- const m = /^(\d+) (\S+)\s*$/m.exec(String(r.stdout ?? ""));
773
- if (!m) return null;
774
- const pid = Number(m[1]); const startedMs = Date.parse(m[2]);
775
- return Number.isInteger(pid) && pid > 0 && Number.isFinite(startedMs) ? { pid, startedMs } : null;
776
- } catch { return null; }
777
- }
778
- if (platform !== "darwin") return null;
779
- try {
780
- const pids = ["dev.rustright.broker", "dev.rustright.broker.b"]
781
- .map((label) => Number(/^\s*pid = (\d+)$/m.exec(String(run("launchctl", ["print", `gui/${uid}/${label}`], { encoding: "utf8", timeout: 5000 }).stdout ?? ""))?.[1]))
782
- .filter((pid) => Number.isInteger(pid) && pid > 0);
783
- if (pids.length !== 1) return null;
784
- const pid = pids[0];
785
- const ps = run("ps", ["-o", "lstart=", "-p", String(pid)], { encoding: "utf8", timeout: 5000, env: { ...process.env, LC_ALL: "C", LANG: "C" } });
786
- const startedMs = Date.parse(String(ps.stdout ?? "").trim());
787
- return Number.isFinite(startedMs) ? { pid, startedMs } : null;
788
- } catch { return null; }
789
- }
790
-
791
- /** GC-I15: the broker process (pid and start) is the same at S0 and S9; the gate launched none. */
792
- export function brokerUnchanged(a, b) {
793
- if (!a || !b) return { ok: false, problems: ["the broker process was not established at S0 or at S9"] };
794
- 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)}`] };
795
- }
796
-
797
- /** GC-T19: the check stage's recorded rule tier is the tier the stage owes (compile below qualify, release at qualify). */
798
- export function ruleTierProblems(receipt, stage) {
799
- const tier = receipt?.stages?.check?.ruleTier;
800
- const want = stage === "qualify" || stage === "release" ? "release" : "compile";
801
- return tier === want ? { ok: true, problems: [] } : { ok: false, problems: [`receipt.stages.check.ruleTier is ${JSON.stringify(tier)}, expected ${JSON.stringify(want)} for --to ${stage}`] };
802
- }
803
-
804
- // ---------------------------------------------------------------------------------------------------------------------------------------------
805
- // Non-negotiable assertions (pure). Each returns { ok, problems[] } and fails closed: evidence that is missing is a problem, never a pass.
806
- // ---------------------------------------------------------------------------------------------------------------------------------------------
807
-
808
- /** One ledger line per child process (spawn-ledger.mjs): {pid, at, ms, sync, cmd, args[], cwd, status}. Malformed lines are problems. */
809
- export function parseLedger(text) {
810
- const entries = []; const problems = [];
811
- String(text ?? "").split(/\r?\n/).forEach((line, i) => {
812
- if (!line.trim()) return;
813
- try {
814
- const e = JSON.parse(line);
815
- if (!isObject(e) || typeof e.cmd !== "string" || !Array.isArray(e.args) || typeof e.cwd !== "string") throw new Error("not a ledger entry {cmd, args[], cwd}");
816
- entries.push(e);
817
- } catch (err) { problems.push(`ledger line ${i + 1}: ${err.message}`); }
818
- });
819
- return { entries, problems };
820
- }
821
-
822
- /** The program name of a ledger command: its basename without a Windows launcher suffix. */
823
- export const programOf = (cmd) => String(cmd).replace(/\\/g, "/").split("/").pop().replace(/\.(exe|cmd|bat)$/i, "");
824
-
825
- /** `{ program, args, cwd }` of an entry. A shell-string start (execSync: cmd holds the whole line, args is empty) is split on whitespace. */
826
- export function normalizeSpawn(e) {
827
- const args = e.args.map(String);
828
- if (args.length === 0 && /\s/.test(String(e.cmd).trim())) { const [first, ...rest] = String(e.cmd).trim().split(/\s+/); return { program: programOf(first), args: rest, cwd: e.cwd, shim: false }; }
829
- return { program: programOf(e.cmd), args, cwd: e.cwd, shim: /rk-cargo-shim/.test(String(e.cmd)) };
830
- }
831
-
832
- const CARGO_VALUE_FLAGS = new Set(["-C", "-Z", "--config", "--color", "--manifest-path"]);
833
- /** The cargo subcommand a start carries and how it is routed: `{ via: "cargo"|"shim"|"rustright", sub }`, or null when the start is no cargo call. */
834
- export function cargoCall(entry) {
835
- const n = entry.program ? entry : normalizeSpawn(entry);
836
- let rest;
837
- let via;
838
- if (n.program === "cargo-fmt") return { via: "cargo", sub: "fmt" };
839
- if (n.program === "rustright") { const i = n.args.indexOf("cargo"); if (i < 0) return null; rest = n.args.slice(i + 1); via = "rustright"; }
840
- else if (n.program === "cargo") { rest = n.args; via = n.shim ? "shim" : "cargo"; }
841
- else return null;
842
- for (let i = 0; i < rest.length; i += 1) {
843
- const a = rest[i];
844
- if (a.startsWith("+")) continue;
845
- if (CARGO_VALUE_FLAGS.has(a)) { i += 1; continue; }
846
- if (a.startsWith("-")) continue;
847
- return { via, sub: a };
848
- }
849
- return { via, sub: null };
850
- }
851
-
852
- /** The allowlist of NN07: probes that truly must repeat inside one gate invocation. Each entry names its program, its exact args and a reason. Empty by decision: nothing in the code needs a repeat. */
853
- // EMPTY by decision: any entry needs Adrian's approval by name (GC-A27 NN07/NN25). Do not add one without it.
854
- export const NN07_ALLOWLIST = Object.freeze([]);
855
-
856
- /** NN07: per-run parts of an argument or directory (temp dirs of probes and shims, the temp root, pid values) are normalised before two starts are compared. */
857
- export const normalizeRunPart = (s) => String(s).replace(/(rk-probe-|rk-gate-shim-|rk-cargo-shim-)[A-Za-z0-9_-]+/g, "$1*").replace(/\/var\/folders\/[^/]+\/[^/]+\/T\//g, "$TMP/").replace(/\b(pid|PID)([= :]?)\d+/g, "$1$2*");
858
- const spawnKey = (n) => `${n.program}\u0000${n.args.map(normalizeRunPart).join("\u0000")}\u0000${normalizeRunPart(n.cwd)}`;
859
- const shortArgs = (args) => args.join(" ").replace(/\s+/g, " ").slice(0, 150);
860
-
861
- /** NN07: the same program basename with the same arguments in the same directory starts once per gate invocation (parent and children together). */
862
- export function assertNoDuplicateSpawns(entries, { allow = NN07_ALLOWLIST } = {}) {
863
- const problems = [];
864
- for (const a of allow) if (!isObject(a) || typeof a.program !== "string" || !Array.isArray(a.args) || typeof a.reason !== "string" || !a.reason.trim()) problems.push(`NN07 allowlist entry without program, args and a reason: ${JSON.stringify(a)}`);
865
- const allowed = new Set(allow.filter((a) => isObject(a) && typeof a.reason === "string" && a.reason.trim()).map((a) => `${a.program}\u0000${(a.args ?? []).join("\u0000")}`));
866
- const seen = new Map();
867
- for (const e of entries) {
868
- const n = normalizeSpawn(e);
869
- if (allowed.has(`${n.program}\u0000${n.args.join("\u0000")}`)) continue;
870
- const k = spawnKey(n);
871
- const prev = seen.get(k);
872
- if (prev) prev.count += 1; else seen.set(k, { count: 1, n });
873
- }
874
- const repeats = [...seen.values()].filter((v) => v.count > 1).sort((a, b) => b.count - a.count);
875
- for (const v of repeats.slice(0, 25)) problems.push(`${v.count}x ${v.n.program} ${shortArgs(v.n.args)} (cwd ${v.n.cwd})`);
876
- if (repeats.length > 25) problems.push(`... and ${repeats.length - 25} more repeated start(s)`);
877
- if (repeats.length) problems.unshift(`${repeats.length} identical child process(es) started more than once (${repeats.reduce((s, v) => s + v.count - 1, 0)} redundant start(s) of ${entries.length})`);
878
- return { ok: problems.length === 0, problems, distinct: seen.size, starts: entries.length, repeats: repeats.length };
879
- }
880
-
881
- const RUSTFMT_PROBE = /^(--version|-V|-v|--help|-h)$/;
882
- /** NN08: no `cargo fmt` (through cargo, the shim or rustright), and rustfmt formats once per bucket that ran (a `--version` probe is not a format). `rows` is the run's coverage map. */
883
- export function assertRustfmtSpawns(entries, rows) {
884
- const problems = [];
885
- if (!rows) problems.push("no coverage rows: the rustfmt buckets that ran cannot be counted");
886
- const ns = entries.map(normalizeSpawn);
887
- const fmt = ns.filter((n) => cargoCall(n)?.sub === "fmt");
888
- for (const n of fmt.slice(0, 5)) problems.push(`cargo fmt started: ${n.program} ${shortArgs(n.args)} (cwd ${n.cwd})`);
889
- const buckets = rows ? [...rows.values()].filter((r) => /^rustfmt(:|$)/.test(r.id) && r.coverage === "ran").length : 0;
890
- const formats = ns.filter((n) => n.program === "rustfmt" && !(n.args.length === 1 && RUSTFMT_PROBE.test(n.args[0])));
891
- if (rows && formats.length > buckets) problems.push(`${formats.length} rustfmt process(es) formatted for ${buckets} rustfmt bucket(s) that ran: ${formats.slice(0, 3).map((n) => shortArgs(n.args)).join(" | ")}`);
892
- return { ok: problems.length === 0, problems, formats: formats.length, buckets };
893
- }
894
-
895
- export const BROKER_FORBIDDEN_CARGO = Object.freeze(["metadata", "fetch", "tree", "locate-project", "pkgid", "verify-project", "read-manifest"]);
896
- /** NN09: `rustright cargo <non-compiling subcommand>` (or the gate's shim, which carries into the broker) never starts. */
897
- export function assertNoBrokerNonCompiling(entries) {
898
- const problems = [];
899
- for (const e of entries) {
900
- const n = normalizeSpawn(e); const c = cargoCall(n);
901
- if (c && c.via !== "cargo" && c.sub && BROKER_FORBIDDEN_CARGO.includes(c.sub)) problems.push(`${c.via === "rustright" ? "rustright cargo" : "shim cargo"} ${c.sub} went through the broker: ${shortArgs(n.args)} (cwd ${n.cwd})`);
902
- }
903
- return { ok: problems.length === 0, problems };
904
- }
905
-
906
- /** NN10: a warm run starts no real `cargo metadata` (direct, shim or broker) for the unchanged snapshot: the resident gate answers it. */
907
- export function assertNoRealCargoMetadata(entries) {
908
- const problems = [];
909
- const hits = entries.map(normalizeSpawn).filter((n) => cargoCall(n)?.sub === "metadata");
910
- if (hits.length) problems.push(`${hits.length} real cargo metadata start(s) in a warm run: ${[...new Set(hits.map((n) => n.cwd))].slice(0, 6).join(", ")}`);
911
- return { ok: problems.length === 0, problems, starts: hits.length };
912
- }
913
-
914
- /** `snapshot proof: tree-hashes=<n> verify-walks=<n> resident-proofs=<n>`: the line the gate must print once per run that touches a snapshot (the evidence NN11 needs). */
915
- export const SNAPSHOT_PROOF = /snapshot proof: tree-hashes=(\d+) verify-walks=(\d+) resident-proofs=(\d+)/;
916
- /** NN11: the snapshot tree is hashed at most once per run, and a warm run walks it never (the resident index proves it). */
917
- export function assertSnapshotProof(log, { warm }) {
918
- const problems = [];
919
- const m = SNAPSHOT_PROOF.exec(String(log));
920
- if (!m) return { ok: false, problems: ["the log has no `snapshot proof: tree-hashes=<n> verify-walks=<n> resident-proofs=<n>` line: the gate does not report how often it hashed or walked the snapshot, so NN11 cannot be judged"] };
921
- const [hashes, walks, resident] = [Number(m[1]), Number(m[2]), Number(m[3])];
922
- if (hashes > 1) problems.push(`the snapshot tree was hashed ${hashes} times in one run, at most 1 is allowed`);
923
- if (warm && walks > 0) problems.push(`a warm run walked the snapshot ${walks} time(s) to verify it (${resident} resident proof(s)); the resident index must prove it`);
924
- if (warm && resident < 1) problems.push("a warm run reports no resident proof of the snapshot");
925
- return { ok: problems.length === 0, problems, hashes, walks, resident };
926
- }
927
-
928
- const DEP_LINE = /snapshot dependencies root=(\S+)(.*)$/gm;
929
- /** The `env=` digest of the log's `class A bytes ...` line, and `env-at-start=`; null when the line is absent. */
930
- export function envDigestOf(log) {
931
- const line = /class A bytes [^\n]*/.exec(String(log))?.[0];
932
- if (!line) return null;
933
- return { env: /\benv=([0-9a-f]{64})/.exec(line)?.[1] ?? null, start: /\benv-at-start=([0-9a-f]{64})/.exec(line)?.[1] ?? null };
934
- }
935
- /** NN12: every installed root's record matched (`reuse-match=hit`), no `pnpm install` started, and the dependency digest did not change inside the run. */
936
- export function assertDependencyReuse(log, entries) {
937
- const problems = [];
938
- const roots = [...String(log).matchAll(DEP_LINE)].filter((m) => !/ not installed:/.test(m[2]));
939
- if (roots.length === 0) problems.push("the log has no `snapshot dependencies root=...` line for an installed root");
940
- for (const m of roots) { const v = /reuse-match=(\S+)/.exec(m[2])?.[1]; if (v !== "hit") problems.push(`root ${m[1]}: reuse-match=${v ?? "(absent)"}, expected hit`); }
941
- const installs = entries.map(normalizeSpawn).filter((n) => n.program === "pnpm" && n.args.includes("install"));
942
- for (const n of installs.slice(0, 3)) problems.push(`pnpm install started on a warm run (cwd ${n.cwd})`);
943
- const d = envDigestOf(log);
944
- if (!d || !d.env || !d.start) problems.push("the log has no `class A bytes ... env-at-start=<digest> env=<digest>` line");
945
- else if (d.env !== d.start) problems.push(`the dependency digest changed during the run (env-at-start ${d.start.slice(0, 12)} -> env ${d.env.slice(0, 12)})`);
946
- return { ok: problems.length === 0, problems };
947
- }
948
- /** NN12 (two identical runs): the dependency digest is the same. */
949
- export function assertDigestStable(a, b) {
950
- const da = envDigestOf(a); const db = envDigestOf(b);
951
- if (!da?.env || !db?.env) return { ok: false, problems: ["a warm run's log has no `class A bytes ... env=<digest>` line"] };
952
- return da.env === db.env ? { ok: true, problems: [] } : { ok: false, problems: [`the dependency digest differs between identical runs: ${da.env.slice(0, 12)} vs ${db.env.slice(0, 12)}`] };
953
- }
954
-
955
- /**
956
- * NN13: a `--to check` log takes exactly one exclusion, the snapshot lock (one `snapshot lock held` line, the door's), and never reports the retired build ownership
957
- * (`build ownership held|joined`); a nested check joins the door's lock silently and takes none of its own.
958
- */
959
- export function assertOneExclusionOnCheck(log) {
960
- const lines = String(log).split(/\r?\n/);
961
- const retired = lines.filter((l) => /build ownership (held|joined) /.test(l));
962
- const locks = lines.filter((l) => /snapshot lock held /.test(l));
963
- const problems = [];
964
- if (retired.length) problems.push(`--to check took a build-ownership lease, which the gate no longer has: ${retired[0].replace(/^\S+ /, "").slice(0, 120)}`);
965
- if (locks.length !== 1) problems.push(`--to check took ${locks.length} snapshot lock(s), expected exactly the door's one${locks[1] ? `: ${locks[1].replace(/^\S+ /, "").slice(0, 100)}` : ""}`);
966
- return problems.length === 0 ? { ok: true, problems: [] } : { ok: false, problems };
967
- }
968
-
969
- /** NN14: a warm run reports the app rules cached, and any preflight line it prints says cached too. */
970
- export function assertRulesCached(log) {
971
- const problems = [];
972
- const text = String(log);
973
- if (!/app rules: cached pass/.test(text)) problems.push("the log has no `app rules: cached pass` line: the app rules ran again on an unchanged tree");
974
- for (const l of text.split(/\r?\n/)) if (/\bpreflight: /.test(l) && !/cached pass/.test(l)) problems.push(`preflight ran again on an unchanged tree: ${l.replace(/^\S+ /, "").slice(0, 120)}`);
975
- return { ok: problems.length === 0, problems };
976
- }
977
-
978
- export const ADVICE_ROW = /^(dependency-freshness|ghsa-audit|pnpm-audit|cargo-deny|cargo-audit)(:|$)/;
979
- const utcDay = (iso) => String(iso).slice(0, 10); const utcHour = (iso) => String(iso).slice(0, 13);
980
- /**
981
- * NN15: no advice scan runs on a warm run of the same UTC day. The one exception is a row whose key moved while the two runs straddle a UTC day or hour
982
- * boundary (the key carries the day or hour). `startedAt`/`prevStartedAt` are the coverage reports' own timestamps.
983
- */
984
- export function assertAdviceCached(prev, next, { startedAt, prevStartedAt } = {}) {
985
- const problems = [];
986
- const advice = [...next.values()].filter((r) => ADVICE_ROW.test(r.id));
987
- if (advice.length === 0) problems.push("no advice rows (dependency-freshness, ghsa-audit, pnpm-audit, cargo-deny, cargo-audit) in the warm run's coverage");
988
- const crossed = Boolean(startedAt && prevStartedAt && (utcDay(startedAt) !== utcDay(prevStartedAt) || utcHour(startedAt) !== utcHour(prevStartedAt)));
989
- for (const r of advice) {
990
- if (r.coverage === "skipped" && r.status !== "not-in-pass") problems.push(`${r.id}: skipped (${r.reason})`);
991
- if (r.coverage !== "ran") continue;
992
- const before = prev?.get(r.id);
993
- if (crossed && before && before.key !== r.key) continue;
994
- problems.push(`${r.id}: ran on a warm run of the same UTC day${r.key === null ? " (no cache key)" : before && before.key === r.key ? " with the key it already had" : ""}`);
995
- }
996
- return { ok: problems.length === 0, problems, advice: advice.length };
997
- }
998
-
999
- /** NN16: a unit list runs Class A once (one coverage report; the later units say it is not run again) and starts no `cargo fmt`. */
1000
- export function assertUnitListShare(log, entries, { units }) {
1001
- const problems = [];
1002
- if (!Number.isInteger(units) || units < 2) problems.push(`the unit list names ${units} unit(s), NN16 needs two`);
1003
- const reports = coveragePaths(log).length;
1004
- if (reports !== 1) problems.push(`Class A produced ${reports} coverage report(s) for the unit list, expected exactly 1`);
1005
- const memo = String(log).split(/\r?\n/).filter((l) => /class A \(\w+ tier\) of this unit list already (passed|failed)[^\n]*not run again/.test(l)).length;
1006
- if (units >= 2 && memo < units - 1) problems.push(`${memo} later unit(s) reused the shared Class A, expected ${units - 1}`);
1007
- for (const n of entries.map(normalizeSpawn)) { const c = cargoCall(n); if (c?.sub === "fmt") problems.push(`cargo fmt started for a unit list: ${n.program} ${shortArgs(n.args)}`); }
1008
- return { ok: problems.length === 0, problems, reports, memo };
1009
- }
1010
-
1011
- /** NN17 lanes: every Class A plan line reports as many lanes as the host has cores. */
1012
- export function assertLanes(log, { cores, jobsOverride = undefined }) {
1013
- const problems = [];
1014
- if (jobsOverride !== undefined && jobsOverride !== "") problems.push(`RK_GATE_JOBS=${jobsOverride} is set in the runner's environment: the lane count is not the default`);
1015
- const lanes = [...String(log).matchAll(/class A scans (\d+) at a time/g)].map((m) => Number(m[1]));
1016
- if (lanes.length === 0) problems.push("the log has no `class A scans N at a time` line");
1017
- for (const n of lanes) if (n !== cores) problems.push(`class A ran ${n} lane(s) on a ${cores}-core host`);
1018
- return { ok: problems.length === 0, problems, lanes };
1019
- }
1020
- const COMPILING_CARGO = new Set(["check", "clippy", "build", "test", "doc", "rustc", "nextest", "run", "bench"]);
1021
- /** NN17 batching: the compile log reports shared groups, and the number of compiling cargo starts stays within the groups plus the named solo scans. */
1022
- export function assertBatching(log, entries, { exit }) {
1023
- const problems = [];
1024
- const text = String(log);
1025
- const note = /class B batching: (\d+) compile scan\(s\) in (\d+) configuration group\(s\)[^\n]*?\((\d+) scan\(s\) in (\d+) shared group\(s\)\)/.exec(text);
1026
- if (!note) return { ok: false, problems: ["the compile log has no `class B batching: N compile scan(s) in G configuration group(s) ... (M scan(s) in K shared group(s))` note"] };
1027
- const [scans, groups, shared, sharedGroups] = note.slice(1).map(Number);
1028
- const solo = [...text.matchAll(/class B batching: (\d+) compile scan\(s\) stay their own invocation/g)].reduce((s, m) => s + Number(m[1]), 0);
1029
- if (scans >= 2 && (shared === 0 || sharedGroups === 0)) problems.push(`${scans} Class B scans planned and no compatible group was batched (${shared} scan(s) in ${sharedGroups} shared group(s))`);
1030
- if (exit === 0) {
1031
- const invocations = entries.map(normalizeSpawn).filter((n) => { const c = cargoCall(n); return c && c.via !== "cargo" && COMPILING_CARGO.has(c.sub); });
1032
- if (invocations.length > groups + solo) problems.push(`${invocations.length} compiling cargo invocation(s) for ${groups} configuration group(s) and ${solo} solo scan(s): a compatible group ran as separate invocations`);
1033
- }
1034
- return { ok: problems.length === 0, problems, scans, groups, shared, sharedGroups, solo };
1035
- }
1036
-
1037
- const EXECUTING_ROW = /^(tsc|eslint|biome|vitest|test|generated-docs|swift-typecheck|pnpm-lockfile|pnpm-audit|pnpm)(:|$)/;
1038
- /** Whether a Class A row executes repository code or installed dependencies and may therefore carry the environment digest (gate: `executes` or tool pnpm). */
1039
- export const isExecutingRow = (id) => EXECUTING_ROW.test(id);
1040
- /** Whether a coverage key carries one of the environment digests (verbatim, or as the value of a property named like env). */
1041
- export function keyCarriesEnvironment(key, digests) {
1042
- if (typeof key !== "string") return false;
1043
- for (const d of digests) if (key.includes(d) || key.includes(d.slice(0, 32))) return true;
1044
- try {
1045
- const walk = (v, name) => {
1046
- if (typeof v === "string") return /env/i.test(name) && /^[0-9a-f]{32,64}$/.test(v);
1047
- if (Array.isArray(v)) return v.some((x) => walk(x, name));
1048
- if (isObject(v)) return Object.entries(v).some(([k, x]) => walk(x, k));
1049
- return false;
1050
- };
1051
- return walk(JSON.parse(key), "");
1052
- } catch { return false; }
1053
- }
1054
- /** NN06: no non-executing row's key carries the environment digest. `digests` are the env digests the runs' logs print. */
1055
- export function assertEnvDigestScope(rows, digests) {
1056
- const problems = [];
1057
- if (digests.length === 0) return { ok: false, problems: ["no run log prints a class A `env=<digest>`: the digest a non-executing key must not carry cannot be identified"] };
1058
- for (const r of rows.values()) {
1059
- if (r.class !== "A" || r.coverage === "skipped" || isExecutingRow(r.id)) continue;
1060
- if (keyCarriesEnvironment(r.key, digests)) problems.push(`${r.id}: a non-executing row's key carries the environment digest`);
1061
- }
1062
- return { ok: problems.length === 0, problems };
1063
- }
1064
-
1065
- /** NN05: two identical runs give every row the same key. A scan answered in only one run, or one without a key, cannot show stability and fails. */
1066
- export function assertKeysStable(a, b) {
1067
- const problems = [];
1068
- const answered = (r) => r && !(r.coverage === "skipped" && r.status === "not-in-pass");
1069
- for (const id of new Set([...a.keys(), ...b.keys()])) {
1070
- const x = a.get(id); const y = b.get(id);
1071
- if (!answered(x) && !answered(y)) continue;
1072
- if (!answered(x) || !answered(y)) { problems.push(`${id}: present in only one of the two runs`); continue; }
1073
- if (x.coverage === "skipped" && y.coverage === "skipped") continue;
1074
- if (x.key === null || y.key === null) { problems.push(`${id}: no cache key in ${x.key === null ? "the first" : "the second"} run, so its stability cannot be shown`); continue; }
1075
- if (x.key !== y.key) problems.push(`${id}: key differs between identical runs`);
1076
- }
1077
- return { ok: problems.length === 0, problems };
1078
- }
1079
-
1080
- /** NN01: no Class A row ran on an unchanged commit. */
1081
- export function assertNoClassARan(rows) {
1082
- const ran = [...rows.values()].filter((r) => r.class === "A" && r.coverage === "ran");
1083
- return { ok: ran.length === 0, problems: ran.map((r) => `${r.id}: Class A row ran on an unchanged commit (${r.reason})`), ran: ran.map((r) => r.id) };
1084
- }
1085
- /** NN02: no Class B row ran on an unchanged commit. A row that failed in `prev` and fails again is reported in `reported`, never counted as a pass of the run. */
1086
- export function assertNoClassBRan(rows, prev = null, { strict = false } = {}) {
1087
- const problems = []; const reported = [];
1088
- const b = [...rows.values()].filter((r) => r.class === "B");
1089
- if (b.length === 0) problems.push("the compile coverage has no Class B row");
1090
- for (const r of b) {
1091
- if (r.coverage !== "ran") continue;
1092
- const before = prev?.get(r.id);
1093
- if (!strict && r.status === "fail" && before?.status === "fail") { reported.push(`${r.id}: failed before and still fails (reported, not re-run silently)`); continue; }
1094
- problems.push(`${r.id}: Class B row ran on an unchanged commit (${r.status})`);
1095
- }
1096
- return { ok: problems.length === 0, problems, reported };
1097
- }
1098
-
1099
- const WORKSPACE_FAMILY = /^(cargo-metadata|cargo-deny|cargo-audit|ghsa-audit|cargo-package-list|clippy|check)(:|$)/;
1100
- /** NN04: after a manifest edit no workspace-scoped row of another workspace ran. */
1101
- export function assertOtherWorkspacesIdle(next, { workspace, workspaces = [], crates = {} }) {
1102
- const problems = [];
1103
- if (typeof workspace !== "string") return { ok: false, problems: ["the edited manifest's workspace is not known"] };
1104
- const wsOf = (label) => (workspaces.includes(label) ? label : workspaces.find((w) => w === `crates/${label}`) ?? Object.entries(crates).find(([, names]) => names.includes(label.includes(":") ? label.slice(label.lastIndexOf(":") + 1) : label))?.[0] ?? null);
1105
- let seenOwn = false;
1106
- for (const r of next.values()) {
1107
- const m = WORKSPACE_FAMILY.exec(r.id);
1108
- if (!m) continue;
1109
- const label = r.id.slice(m[0].length);
1110
- const ws = m[1] === "cargo-metadata" && r.id === "cargo-metadata" ? "." : wsOf(label);
1111
- if (ws === workspace) seenOwn = true;
1112
- if (r.coverage !== "ran") continue;
1113
- if (ws === null) problems.push(`${r.id}: ran and belongs to no known workspace`);
1114
- else if (ws !== workspace) problems.push(`${r.id}: a row of workspace ${JSON.stringify(ws)} ran for an edit in workspace ${JSON.stringify(workspace)}`);
1115
- }
1116
- if (!seenOwn) problems.push(`no workspace-scoped row of ${JSON.stringify(workspace)} exists in the run`);
1117
- return { ok: problems.length === 0, problems };
1118
- }
1119
-
1120
- // ---- NN18: budgets and stage timings -------------------------------------------------------------------------------------------------------
1121
-
1122
- const stampOf = (line) => { const m = /^(\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?Z) /.exec(line); return m ? Date.parse(m[1]) : null; };
1123
- /**
1124
- * Stage durations from the stamped log. The line pairs (also written into ci/gate-acceptance-budgets.json):
1125
- * ownership (the key keeps its budget name) run start (the runner's launch time) -> first `snapshot lock held` line; 0 when the run takes no lock
1126
- * snapshotSync lock line (else run start) -> `snapshot <dir> is commit <sha> tree <sha> (written=...` line
1127
- * planning `rightkit-gate: --to <stage> for <sha12>: ...` line -> `<n> scan(s) for <m> changed file(s) vs <sha12>; class A scans <j> at a time` line
1128
- * dependencyStep that plan line -> the first `snapshot dependencies root=` line (a compile prints a second one later, after Class A)
1129
- * A named line that is missing is a problem (the stage cannot be timed), except the lock line, whose absence is the stage being 0.
1130
- */
1131
- export function stageMarks(log, startedMs) {
1132
- const lines = String(log).split(/\r?\n/);
1133
- const first = (re) => lines.find((l) => re.test(l));
1134
- const last = (re) => [...lines].reverse().find((l) => re.test(l));
1135
- const problems = [];
1136
- const t = (line, what) => { const ms = line ? stampOf(line) : null; if (ms === null) problems.push(`no stamped \`${what}\` line`); return ms; };
1137
- const own = first(/snapshot lock held /);
1138
- const ownT = own ? stampOf(own) : null;
1139
- const sync = t(first(/snapshot \S+ is commit [0-9a-f]{40} tree [0-9a-f]{40} \(written=/), "snapshot ... is commit ... (written=");
1140
- const stageStart = t(first(/rightkit-gate: --to \w+ for [0-9a-f]{12}/), "--to <stage> for <sha>");
1141
- const plan = t(first(/\d+ scan\(s\) for \d+ changed file\(s\) vs [0-9a-f]{12}; class A scans \d+ at a time/), "<n> scan(s) for <m> changed file(s) ...; class A scans <j> at a time");
1142
- const deps = t(first(/snapshot dependencies root=/), "snapshot dependencies root=");
1143
- const span = (a, b, what) => { if (a === null || b === null) return null; if (b < a) { problems.push(`${what}: the closing line is stamped before the opening line`); return null; } return b - a; };
1144
- const marks = {
1145
- ownership: own ? span(startedMs, ownT, "ownership") : 0,
1146
- snapshotSync: span(ownT ?? startedMs, sync, "snapshotSync"),
1147
- planning: span(stageStart, plan, "planning"),
1148
- dependencyStep: span(plan, deps, "dependencyStep"),
1149
- };
1150
- return { marks, problems };
1151
- }
1152
-
1153
- export const BUDGET_STAGES = Object.freeze(["ownership", "snapshotSync", "dependencyStep", "planning"]);
1154
- /** Validates the budgets file: schema, a hosts object with mac and dell, every number positive or null. */
1155
- export function validateBudgets(b) {
1156
- const problems = [];
1157
- if (!isObject(b)) return { ok: false, problems: ["budgets file is not an object"] };
1158
- if (b.schema !== BUDGETS_SCHEMA) problems.push(`budgets.schema is ${JSON.stringify(b.schema)}, expected ${BUDGETS_SCHEMA}`);
1159
- if (!isObject(b.hosts)) problems.push("budgets.hosts is not an object");
1160
- else for (const host of ["mac", "dell"]) {
1161
- const h = b.hosts[host];
1162
- if (!isObject(h)) { problems.push(`budgets.hosts.${host} is missing`); continue; }
1163
- const num = (v, where) => { if (v !== null && !(Number.isFinite(v) && v > 0)) problems.push(`${where} is neither null nor a positive number`); };
1164
- num(h.warmCheckMs, `hosts.${host}.warmCheckMs`); num(h.warmCompileMs, `hosts.${host}.warmCompileMs`);
1165
- if (!isObject(h.stages)) problems.push(`hosts.${host}.stages is missing`); else for (const s of BUDGET_STAGES) { if (!(s in h.stages)) problems.push(`hosts.${host}.stages.${s} is missing`); else num(h.stages[s], `hosts.${host}.stages.${s}`); }
1166
- }
1167
- return { ok: problems.length === 0, problems };
1168
- }
1169
- export function loadBudgets(file = BUDGETS_FILE) {
1170
- let parsed; try { parsed = JSON.parse(fs.readFileSync(file, "utf8")); } catch (e) { return { budgets: null, problem: `cannot read ${file}: ${e.message}` }; }
1171
- const v = validateBudgets(parsed);
1172
- return v.ok ? { budgets: parsed, problem: null } : { budgets: null, problem: `${file}: ${v.problems.join("; ")}` };
1173
- }
1174
- /**
1175
- * NN18: each warm run's wall time and fixed-stage durations stay inside the host's budget. `runs` is `[{ label, kind: "check"|"compile", ms, marks }]`.
1176
- * A null budget FAILS ("no budget measured"): a host with no measurement is never passed.
1177
- */
1178
- export function assertBudget({ host, budgets, runs }) {
1179
- const problems = [];
1180
- const h = budgets?.hosts?.[host];
1181
- if (!h) return { ok: false, problems: [`no budget for host ${host} in ${BUDGETS_FILE}`] };
1182
- const need = (v, what) => { if (v === null || v === undefined) { problems.push(`no budget measured for ${host}: ${what}`); return false; } return true; };
1183
- for (const r of runs) {
1184
- const total = r.kind === "compile" ? h.warmCompileMs : h.warmCheckMs;
1185
- if (need(total, r.kind === "compile" ? "warmCompileMs" : "warmCheckMs") && r.ms > total) problems.push(`${r.label}: warm --to ${r.kind} took ${r.ms} ms, budget ${total} ms`);
1186
- for (const s of BUDGET_STAGES) {
1187
- const v = r.marks?.[s];
1188
- if (v === null || v === undefined) { problems.push(`${r.label}: stage ${s} could not be timed`); continue; }
1189
- if (need(h.stages?.[s], `stages.${s}`) && v > h.stages[s]) problems.push(`${r.label}: stage ${s} took ${v} ms, budget ${h.stages[s]} ms`);
1190
- }
1191
- }
1192
- if (runs.length === 0) problems.push("no warm run to measure");
1193
- return { ok: problems.length === 0, problems };
1194
- }
1195
-
1196
- // ---- NN19: the gate under test ----------------------------------------------------------------------------------------------------------------
1197
-
1198
- /** The newest sealed install under `<managed root>/trusted-gates` (a folder named by the sha256 of its manifest, as agent-bin/rightkit-host-gate trusts it): `{ version, entry }` or null. */
1199
- export function findInstalledGate(managedRoot, io = {}) { return listInstalledGates(managedRoot, io)[0] ?? null; }
1200
- /** Every sealed install, newest version first. */
1201
- export function listInstalledGates(managedRoot, { read = (f) => fs.readFileSync(f), list = (d) => fs.readdirSync(d) } = {}) {
1202
- const root = path.join(managedRoot, "trusted-gates");
1203
- let names; try { names = list(root); } catch { return []; }
1204
- const found = [];
1205
- for (const name of names) {
1206
- if (!/^[a-f0-9]{64}$/.test(name)) continue;
1207
- try {
1208
- if (sha256(read(path.join(root, `${name}.manifest.txt`))) !== name) continue;
1209
- const pkgDir = path.join(root, name, "node_modules", "@rightkit", "release");
1210
- const pkg = JSON.parse(String(read(path.join(pkgDir, "package.json"))));
1211
- if (pkg?.name === "@rightkit/release" && /^\d+\.\d+\.\d+$/.test(pkg.version)) found.push({ version: pkg.version, sealedSha256: name, entry: path.join(pkgDir, "bin", "rightkit-gate.mjs") });
1212
- } catch { /* not a sealed install */ }
1213
- }
1214
- const key = (v) => v.split(".").map(Number);
1215
- found.sort((a, b) => { const x = key(a.version); const y = key(b.version); for (let i = 0; i < 3; i += 1) if (x[i] !== y[i]) return y[i] - x[i]; return 0; });
1216
- return found;
1217
- }
1218
- /**
1219
- * NN19: the gate that runs is the installed sealed gate. Without `--gate` the default launcher must exist, report the newest sealed install's version
1220
- * and not exec the checkout's gate; a checkout gate is accepted only when `--gate` names it (and the result then says so: `kind: "named"`).
1221
- */
1222
- export function gateIdentityProblems({ gateArg, defaultGate, launcherExists, launcherVersion, launcherText = "", installed, checkoutRoot }) {
1223
- const problems = [];
1224
- const named = gateArg !== undefined && gateArg !== null && path.normalize(gateArg) !== path.normalize(defaultGate);
1225
- if (!launcherExists) problems.push(`the launcher ${named ? gateArg : defaultGate} does not exist`);
1226
- if (!launcherVersion) problems.push("`--version` of the launcher printed no version");
1227
- if (!named) {
1228
- const entry = path.join(checkoutRoot, "packages", "release", "bin", "rightkit-gate.mjs");
1229
- if (String(launcherText).includes(entry)) problems.push(`the default launcher runs the checkout gate ${entry} and no --gate names it`);
1230
- if (!installed) problems.push("no sealed installed gate under trusted-gates, so the installed gate's identity cannot be established");
1231
- else if (launcherVersion && launcherVersion !== installed.version) problems.push(`the launcher reports ${launcherVersion}, the newest sealed install is ${installed.version}: not the installed gate`);
1232
- }
1233
- return { ok: problems.length === 0, problems, kind: named ? "named" : "installed" };
1234
- }
1235
-
1236
- // ---- Evaluation over a run's evidence --------------------------------------------------------------------------------------------------------
1237
-
1238
- // ---------------------------------------------------------------------------------------------------------------------------------------------
1239
- // GC-A27 extension: NN20-NN38 and the tightened NN01-NN19. Every assertion below is an e2e judgement over the run's OWN evidence (coverage, log,
1240
- // spawn ledger, receipt, git history); none reads a synthetic input in production. That each one CAN fail is shown by `--prove` (control runs
1241
- // of real conditions and mutant gates), never by a unit test. Evidence the gate does not emit makes its check FAIL, naming the evidence to add.
1242
- // ---------------------------------------------------------------------------------------------------------------------------------------------
1243
-
1244
- /** NN33: the NN table rows of the contract: `| NNxx | property | fails when |`. */
1245
- export function parseContractNN(text) {
1246
- const rows = [];
1247
- for (const line of String(text ?? "").split(/\r?\n/)) {
1248
- const m = /^\|\s*(NN\d\d)\s*\|(.*)\|\s*$/.exec(line);
1249
- if (!m) continue;
1250
- const cells = m[2].split("|").map((s) => s.trim());
1251
- rows.push({ id: m[1], property: cells[0] ?? "", fails: cells.slice(1).join(" | ") });
1252
- }
1253
- return rows;
1254
- }
1255
-
1256
- /** NN33: every contract id has a check and every check id is in the contract (both directions, and the registry equals both). */
1257
- export function assertContractMatch({ contractRows, checkIds, registryIds }) {
1258
- const problems = [];
1259
- const contract = contractRows.map((r) => r.id);
1260
- if (contract.length === 0) problems.push("the contract has no NN table rows (`| NNxx | ... |`): nothing to match");
1261
- const dup = contract.filter((id, i) => contract.indexOf(id) !== i);
1262
- for (const id of new Set(dup)) problems.push(`${id} appears more than once in the contract table`);
1263
- const checks = new Set(checkIds); const registry = new Set(registryIds); const inContract = new Set(contract);
1264
- for (const id of contract) { if (!checks.has(id)) problems.push(`${id} is in the contract and has no check in the runner`); if (!registry.has(id)) problems.push(`${id} is in the contract and not in the runner's registry`); }
1265
- for (const id of checks) if (!inContract.has(id)) problems.push(`${id} has a check in the runner and is not in the contract`);
1266
- for (const id of registry) if (!inContract.has(id)) problems.push(`${id} is in the runner's registry and not in the contract`);
1267
- return { ok: problems.length === 0, problems };
1268
- }
1269
-
1270
- export const CONTRACT_FILE = path.resolve(here, "..", "..", "docs", "GATE-CONTRACT.md");
1271
- export const RUNNER_FILE = fileURLToPath(import.meta.url);
1272
- const fileSha = (f) => { try { return sha256(fs.readFileSync(f)); } catch { return null; } };
1273
-
1274
- // ---- NN25 / NN07 allowlists: EMPTY by decision. An entry needs Adrian's approval (GC-A27 NN25: "a probe that must run names its reason in the runner's
1275
- // allowlist, which Adrian approves"; NN07 likewise). Do not add one without his approval by name in the commit message.
1276
- export const NN25_ALLOWLIST = Object.freeze([]);
1277
- const PROCESS_PROBES = new Set(["ps", "lsof", "launchctl", "sysctl"]);
1278
- const VERSION_ARG = /^(--version|-V|-v|version)$/;
1279
- const TREE_WALKERS = new Set(["find", "rsync", "du"]);
1280
- const GIT_TREE_VERBS = new Set(["ls-files", "ls-tree", "archive", "status", "diff", "diff-files", "diff-index", "update-index"]);
1281
-
1282
- /** NN25: no child of the forbidden families on a warm run (git after the resident proof, version probes, pnpm, process probes, real cargo). */
1283
- export function assertWarmNoFamilies(entries, { log = "", allow = NN25_ALLOWLIST } = {}) {
1284
- const problems = [];
1285
- const proofLine = String(log).split(/\r?\n/).find((l) => /snapshot proof:|resident proof|\(verified before/.test(l));
1286
- const proofAt = proofLine ? stampOf(proofLine) : null;
1287
- const allowed = new Set(allow.filter((a) => isObject(a) && a.reason && a.program).map((a) => `${a.program}\u0000${(a.args ?? []).join("\u0000")}`));
1288
- const found = new Map();
1289
- for (const e of entries) {
1290
- const n = normalizeSpawn(e);
1291
- if (allowed.has(`${n.program}\u0000${n.args.join("\u0000")}`)) continue;
1292
- const at = Date.parse(e.at);
1293
- const call = cargoCall(n);
1294
- let fam = null;
1295
- if (n.args.length <= 2 && n.args.some((a) => VERSION_ARG.test(a))) fam = "tool version probe";
1296
- else if (n.program === "git" && (proofAt === null || at >= proofAt)) fam = proofAt === null ? "git (the log carries no resident-proof time, so every git start counts)" : "git after the resident proof";
1297
- else if (n.program === "pnpm") fam = "pnpm";
1298
- else if (PROCESS_PROBES.has(n.program)) fam = `process probe (${n.program})`;
1299
- else if (call && call.via !== "rustright") fam = "real cargo";
1300
- if (fam) { const k = `${fam}\u0000${n.program} ${shortArgs(n.args)}`; found.set(k, (found.get(k) ?? 0) + 1); }
1301
- }
1302
- for (const [k, c] of [...found].slice(0, 20)) { const [fam, cmd] = k.split("\u0000"); problems.push(`${fam}: ${c}x ${cmd}`); }
1303
- if (found.size > 20) problems.push(`... and ${found.size - 20} more`);
1304
- return { ok: problems.length === 0, problems };
1305
- }
1306
-
1307
- /** NN22: every sync line of a warm run is written=0 removed=0 and the ledger shows no tree walk. */
1308
- export function assertWarmSync(log, entries) {
1309
- const problems = [];
1310
- const syncs = [...String(log).matchAll(/snapshot \S+ is commit [0-9a-f]{40} tree [0-9a-f]{40} \(written=(\d+) removed=(\d+)/g)];
1311
- if (!syncs.length) problems.push("the log has no `snapshot <dir> is commit <sha> tree <sha> (written=N removed=N` line");
1312
- for (const m of syncs) if (m[1] !== "0" || m[2] !== "0") problems.push(`the snapshot sync wrote ${m[1]} and removed ${m[2]} on an unchanged commit`);
1313
- for (const n of entries.map(normalizeSpawn)) if (TREE_WALKERS.has(n.program) || (n.program === "git" && n.args.some((a) => GIT_TREE_VERBS.has(a)))) problems.push(`a tree walk started on a warm run: ${n.program} ${shortArgs(n.args)} (cwd ${n.cwd})`);
1314
- return { ok: problems.length === 0, problems };
1315
- }
1316
-
1317
- /** NN26: no `node gate-serve.mjs ask` process (the gate asks the resident gate in process over its socket). */
1318
- export function assertNoServeAskSpawn(entries) {
1319
- const problems = [];
1320
- for (const n of entries.map(normalizeSpawn)) if (n.args.some((a) => /gate-serve\.mjs$/.test(a)) && n.args.includes("ask")) problems.push(`a process was started to ask the resident gate: ${n.program} ${shortArgs(n.args)}`);
1321
- return { ok: problems.length === 0, problems };
1322
- }
1323
-
1324
- const cargoBFamily = (id) => {
1325
- const bare = id.replace(/@[^@:]+$/, ""); const target = /@([^@:]+)$/.exec(id)?.[1] ?? "host"; const p = bare.split(":");
1326
- if (p[0] === "test" && p[1] === "rust") return { fam: "test", ws: p[2], crate: p[3], idx: p[4] ?? "0", target };
1327
- if (p[0] === "clippy") return { fam: "clippy", ws: p[1], crate: p[2], idx: p[3] ?? "0", target };
1328
- if (p[0] === "check-features") return { fam: "check", ws: p[1], crate: p[2], idx: p[3] ?? "0", target };
1329
- if (p[0] === "doc") return { fam: "doc", ws: p[1], crate: p[2], idx: "0", target };
1330
- return null;
1331
- };
1332
- /** NN27: no check row runs where a clippy row covers the same configuration, and no two rows run the same compiler pass over one crate, target and feature set. */
1333
- export function assertNoDoublePass(rows) {
1334
- const problems = [];
1335
- const seen = new Map();
1336
- for (const r of rows.values()) {
1337
- if (r.class !== "B" || r.coverage !== "ran") continue;
1338
- const f = cargoBFamily(r.id); if (!f || (f.fam !== "check" && f.fam !== "clippy")) continue;
1339
- const key = `${f.ws}|${f.crate}|${f.idx}|${f.target}`;
1340
- (seen.get(key) ?? seen.set(key, []).get(key)).push({ id: r.id, fam: f.fam });
1341
- }
1342
- for (const [key, list] of seen) if (list.length > 1) problems.push(`${list.length} compiler passes ran over ${key.split("|").join(" ")}: ${list.map((x) => x.id).join(", ")}`);
1343
- return { ok: problems.length === 0, problems };
1344
- }
1345
-
1346
- /** NN28: the resident gate learns changes from RightKit's file index and watcher; the gate must say so, and no polling child starts. */
1347
- export function assertChangeSource(log, entries) {
1348
- const problems = [];
1349
- const m = /snapshot proof:[^\n]*\bchange-source=(\S+)/.exec(String(log));
1350
- if (!m) problems.push("the log has no `snapshot proof: ... change-source=fsindex,file-watch` field: the gate must report which change source the resident gate used (rightkit-fsindex, rightkit-file-watch), so NN28 cannot be judged");
1351
- else if (m[1] !== "fsindex,file-watch") problems.push(`the resident gate's change source is ${m[1]}, expected fsindex,file-watch`);
1352
- for (const n of entries.map(normalizeSpawn)) if (TREE_WALKERS.has(n.program) || (n.program === "git" && n.args.some((a) => GIT_TREE_VERBS.has(a)))) problems.push(`a change was learned by polling: ${n.program} ${shortArgs(n.args)}`);
1353
- return { ok: problems.length === 0, problems };
1354
- }
1355
-
1356
- /** NN23: every row the previous gate answered stays a hit, with its key, under the upgraded gate. */
1357
- export function assertUpgradeKeepsHits(prev, next) {
1358
- const problems = [];
1359
- let kept = 0;
1360
- for (const [id, p] of prev) {
1361
- if (p.coverage === "skipped") continue;
1362
- const n = next.get(id);
1363
- if (!n) { problems.push(`${id}: answered by the previous gate and absent after the upgrade`); continue; }
1364
- if (n.coverage !== "hit") problems.push(`${id}: ${p.coverage} under the previous gate, ${n.coverage} after the upgrade`);
1365
- else if (n.key !== p.key) problems.push(`${id}: its key changed across the upgrade`);
1366
- else kept += 1;
1367
- }
1368
- if (kept === 0 && problems.length === 0) problems.push("no row was answered by the previous gate: the upgrade cannot be judged");
1369
- return { ok: problems.length === 0, problems, kept };
1370
- }
1371
-
1372
- /** NN24: a warm run after the resident gate was killed ran no row. */
1373
- export function assertRestartWarm(rows, restart) {
1374
- const problems = [];
1375
- if (!restart?.killed) problems.push(restart?.why ?? "the resident gate was not restarted, so the case proves nothing");
1376
- const ran = [...rows.values()].filter((r) => r.coverage === "ran");
1377
- for (const r of ran.slice(0, 20)) problems.push(`${r.id}: ran after the resident gate restarted`);
1378
- return { ok: problems.length === 0, problems };
1379
- }
1380
-
1381
- /** NN29: a run whose per-run identities differ gets the same keys and no miss. */
1382
- export function assertIdentityIndependent(base, other) {
1383
- const keys = assertKeysStable(base, other);
1384
- const problems = [...keys.problems];
1385
- for (const r of other.values()) if (r.class === "A" && r.coverage === "ran") problems.push(`${r.id}: a reuse miss on a run that differs only in per-run identities`);
1386
- return { ok: problems.length === 0, problems };
1387
- }
1388
-
1389
- // ---- NN20 / NN21 / NN04 (compile) ----------------------------------------------------------------------------------------------------------------
1390
- /** Crate dependency map of one workspace from its manifests: `{ name: [workspace crates it names as dependencies] }`. */
1391
- export function crateDeps(manifestTexts) {
1392
- const names = Object.keys(manifestTexts); const deps = {};
1393
- for (const name of names) deps[name] = names.filter((o) => o !== name && new RegExp(`^\\s*${o.replace(/[-]/g, "\\-")}\\s*(=|\\.)`, "m").test(manifestTexts[name]));
1394
- return deps;
1395
- }
1396
- /** `crate` and every crate that (transitively) depends on it. */
1397
- export function affectedCrates(crate, deps) {
1398
- const out = new Set([crate]); let grew = true;
1399
- while (grew) { grew = false; for (const [c, ds] of Object.entries(deps)) if (!out.has(c) && ds.some((d) => out.has(d))) { out.add(c); grew = true; } }
1400
- return out;
1401
- }
1402
- /** NN20: after a one-crate edit no Class B row of a crate the edit cannot affect ran. */
1403
- export function assertCrateEditScope(rows, { workspace, crate, deps }) {
1404
- const problems = [];
1405
- const affected = affectedCrates(crate, deps);
1406
- let b = 0;
1407
- for (const r of rows.values()) {
1408
- if (r.class !== "B" || r.coverage === "skipped") continue;
1409
- b += 1;
1410
- if (r.coverage !== "ran") continue;
1411
- const f = cargoBFamily(r.id);
1412
- if (!f) problems.push(`${r.id}: a Class B row that is no crate's row ran for a one-crate edit`);
1413
- else if (f.ws !== workspace || !affected.has(f.crate)) problems.push(`${r.id}: crate ${f.crate} (${f.ws}) cannot be affected by an edit of ${crate} (affected: ${[...affected].join(", ")})`);
1414
- }
1415
- if (b === 0) problems.push("the compile run answered no Class B row: nothing shows what the edit recompiled");
1416
- return { ok: problems.length === 0, problems };
1417
- }
1418
- /** Whether a row reads the lockfile of Cargo workspace `lockDir`. */
1419
- export function rowReadsLock(id, lockDir) {
1420
- const wsRe = lockDir.replace(/[.*+?^${}()|[\]\\/]/g, "\\const PREV_WARM = Object.freeze(");
1421
- if (new RegExp(`^(cargo-metadata|cargo-deny|cargo-audit|ghsa-audit|cargo-package-list):${wsRe}(:|$)`).test(id)) return true;
1422
- const f = cargoBFamily(id); return Boolean(f && f.ws === lockDir);
1423
- }
1424
- /** NN21: after a lockfile edit only rows that read that lockfile (and the per-file scans that read the edited file) ran. */
1425
- export function assertLockEditScope(rows, { lockDir }) {
1426
- const problems = [];
1427
- for (const r of rows.values()) {
1428
- if (r.coverage !== "ran") continue;
1429
- if (rowReadsLock(r.id, lockDir) || /^(secret-scan|licen[cs]e)/.test(r.id)) continue;
1430
- problems.push(`${r.id}: ran after an edit of ${lockDir}/Cargo.lock and does not read it`);
1431
- }
1432
- if (![...rows.values()].some((r) => r.coverage === "ran" && rowReadsLock(r.id, lockDir))) problems.push("no row that reads the edited lockfile ran: the edit was not seen");
1433
- return { ok: problems.length === 0, problems };
1434
- }
1435
- /** NN04 on any stage: no workspace-scoped row of another workspace ran (Class A families and Class B crate rows). */
1436
- export function assertOtherWorkspacesIdleAny(rows, { workspace }) {
1437
- const problems = []; let own = false;
1438
- for (const r of rows.values()) {
1439
- const m = /^(cargo-metadata|cargo-deny|cargo-audit|ghsa-audit|cargo-package-list):(.+)$/.exec(r.id); const b = cargoBFamily(r.id);
1440
- const ws = m ? m[2].split(":")[0] : b ? b.ws : null;
1441
- if (r.id === "cargo-metadata") { own = own || workspace === "."; if (r.coverage === "ran" && workspace !== ".") problems.push(`${r.id}: ran for an edit in ${workspace}`); continue; }
1442
- if (ws === null) continue;
1443
- if (ws === workspace && r.coverage !== "skipped") own = true;
1444
- if (r.coverage === "ran" && ws !== workspace) problems.push(`${r.id}: a row of workspace ${JSON.stringify(ws)} ran for a manifest edit in ${JSON.stringify(workspace)}`);
1445
- }
1446
- if (!own) problems.push(`no row of workspace ${JSON.stringify(workspace)} exists in the run`);
1447
- return { ok: problems.length === 0, problems };
1448
- }
1449
-
1450
- // ---- tightened NN01 / NN02 / NN03 / NN09 / NN11 / NN13 ---------------------------------------------------------------------------------------------
1451
- const ROW_TOOL = [[/^rustfmt/, "rustfmt"], [/^shellcheck/, "shellcheck"], [/^actionlint/, "actionlint"], [/^cargo-deny/, "cargo-deny"], [/^cargo-audit/, "cargo-audit"], [/^oxlint/, "oxlint"], [/^tsc:/, "tsc"]];
1452
- /** NN01 (ledger half): a row reported `hit` never started its tool. */
1453
- export function assertHitRowsStartedNoTool(rows, entries) {
1454
- const problems = [];
1455
- const started = new Set(entries.map(normalizeSpawn).map((n) => n.program));
1456
- for (const r of rows.values()) {
1457
- if (r.coverage !== "hit") continue;
1458
- const tool = ROW_TOOL.find(([re]) => re.test(r.id))?.[1];
1459
- if (tool && started.has(tool)) problems.push(`${r.id}: reported hit and ${tool} started in the same run (ledger)`);
1460
- }
1461
- return { ok: problems.length === 0, problems };
1462
- }
1463
- /** NN03 (files-read half): rustfmt formats exactly the edited files; secret scan and licence report exactly them. */
1464
- export function assertEditedFilesRead(rows, entries, { files }) {
1465
- const problems = [];
1466
- const fmt = entries.map(normalizeSpawn).filter((n) => n.program === "rustfmt" && !(n.args.length === 1 && RUSTFMT_PROBE.test(n.args[0])));
1467
- const want = [...files].sort().join("\u0000");
1468
- for (const n of fmt) {
1469
- const got = n.args.filter((a) => !a.startsWith("-")).map((a) => files.find((f) => a.endsWith(f)) ?? a).sort().join("\u0000");
1470
- if (got !== want) problems.push(`rustfmt read ${shortArgs(n.args)}, expected exactly ${files.join(", ")}`);
1471
- }
1472
- for (const id of ["secret-scan", "license"]) {
1473
- const r = [...rows.values()].find((x) => x.id === id || (id === "license" && /^licen[cs]e/.test(x.id)));
1474
- if (!r) { problems.push(`no ${id} row in the run`); continue; }
1475
- if (!Array.isArray(r.filesRead)) problems.push(`${r.id}: the coverage row has no \`filesRead\`; the gate must list the files each scan read, so reading more than the edited files cannot be ruled out`);
1476
- else if ([...r.filesRead].sort().join("\u0000") !== want) problems.push(`${r.id}: read ${r.filesRead.length} file(s), expected exactly ${files.join(", ")}`);
1477
- }
1478
- return { ok: problems.length === 0, problems };
1479
- }
1480
- /** NN09 (--version half): `rustright cargo --version` also never starts. */
1481
- export function assertNoBrokerVersion(entries) {
1482
- const problems = [];
1483
- for (const n of entries.map(normalizeSpawn)) if (n.program === "rustright" && n.args.includes("cargo") && n.args.some((a) => VERSION_ARG.test(a))) problems.push(`rustright cargo ${n.args.filter((a) => VERSION_ARG.test(a))[0]} started: ${shortArgs(n.args)}`);
1484
- return { ok: problems.length === 0, problems };
1485
- }
1486
- /** NN11 (agreement half): a log that says the tree was not walked is contradicted by a ledger that shows a walk. */
1487
- export function assertLedgerAgreesWithProof(log, entries) {
1488
- const m = SNAPSHOT_PROOF.exec(String(log)); const problems = [];
1489
- if (!m) return { ok: false, problems: ["no `snapshot proof:` line to compare the ledger with"] };
1490
- const walks = Number(m[2]);
1491
- const seen = entries.map(normalizeSpawn).filter((n) => TREE_WALKERS.has(n.program) || (n.program === "git" && n.args.some((a) => ["ls-files", "ls-tree", "archive"].includes(a)))).length;
1492
- if (walks === 0 && seen > 0) problems.push(`the log says verify-walks=0 and the ledger shows ${seen} tree-walking start(s)`);
1493
- return { ok: problems.length === 0, problems };
1494
- }
1495
- /** NN13 (probe half): a `--to check` run starts no process probe (ps, lsof, launchctl, sysctl). */
1496
- export function assertNoProcessProbe(entries) {
1497
- const problems = [];
1498
- for (const n of entries.map(normalizeSpawn)) if (PROCESS_PROBES.has(n.program)) problems.push(`--to check started a process probe: ${n.program} ${shortArgs(n.args)}`);
1499
- return { ok: problems.length === 0, problems };
1500
- }
1501
-
1502
- // ---- NN18: windows from launch to exit, per workload and kind --------------------------------------------------------------------------------------
1503
- export const WINDOWS = Object.freeze(["startup", "ownership", "snapshotSync", "stageStart", "snapshotVerify", "appRules", "planning", "dependencyStep", "scans", "finish"]);
1504
- export const WORKLOADS = Object.freeze(["fixture", "rightkit", "heardright", "pulse"]);
1505
- export const PROFILES = Object.freeze(["warm-check", "warm-compile", "edited-check", "edited-compile", "cold-check", "cold-compile"]);
1506
- /**
1507
- * Consecutive windows that tile the run from the runner's launch to the gate's exit, each named by the log line that closes it:
1508
- * startup (launch -> first stamped line), ownership (-> `snapshot lock held`; 0 when the run takes no lock), snapshotSync (-> the sync line),
1509
- * stageStart (-> `--to <stage> for <sha>`), snapshotVerify (-> `(verified before`), appRules (-> `app rules:`), planning (-> the plan line),
1510
- * dependencyStep (-> `snapshot dependencies root=`), scans (-> the last `[n/N]` result line) and finish (-> exit). Optional markers that are absent
1511
- * fold into the next window; a required marker that is absent or stamped out of order makes the run untimeable.
1512
- */
1513
- export function windowMarks(log, startedMs, endMs) {
1514
- const lines = String(log).split(/\r?\n/);
1515
- const find = (re, last = false) => (last ? [...lines].reverse() : lines).find((l) => re.test(l));
1516
- const problems = [];
1517
- const stamp = (re, what, required, last) => { const line = find(re, last); if (!line) { if (required) problems.push(`no \`${what}\` line`); return undefined; } const t = stampOf(line); if (t === null) { problems.push(`the \`${what}\` line carries no UTC stamp`); return undefined; } return t; };
1518
- const firstLine = lines.map(stampOf).find((t) => t !== null);
1519
- const seq = [
1520
- ["startup", firstLine, true],
1521
- ["ownership", stamp(/snapshot lock held /, "snapshot lock", false), false],
1522
- ["snapshotSync", stamp(/snapshot \S+ is commit [0-9a-f]{40} tree [0-9a-f]{40} \(written=/, "snapshot ... (written=", true), true],
1523
- ["stageStart", stamp(/rightkit-gate: --to \w+ for [0-9a-f]{12}/, "--to <stage> for <sha>", true), true],
1524
- ["snapshotVerify", stamp(/snapshot \S+ is commit [0-9a-f]{40} tree [0-9a-f]{40} \(verified/, "snapshot ... (verified", false), false],
1525
- ["appRules", stamp(/app rules: /, "app rules:", false), false],
1526
- ["planning", stamp(/\d+ scan\(s\) for \d+ changed file\(s\) vs [0-9a-f]{12}; class A scans \d+ at a time/, "plan line", true), true],
1527
- ["dependencyStep", stamp(/snapshot dependencies root=/, "snapshot dependencies root=", true), true],
1528
- ["scans", stamp(/\[(\d+)\/\1\] /, "[N/N] scan result", true, true), true],
1529
- ["finish", endMs, true],
1530
- ];
1531
- if (firstLine === undefined) problems.push("the log has no stamped line");
1532
- const windows = Object.fromEntries(WINDOWS.map((w) => [w, null]));
1533
- let prev = startedMs;
1534
- for (const [name, t, required] of seq) {
1535
- if (t === undefined || t === null) { if (name === "ownership") windows.ownership = 0; else if (required) windows[name] = null; continue; }
1536
- if (t < prev) { problems.push(`${name}: closing line stamped ${prev - t} ms before the previous marker; the run cannot be tiled`); continue; }
1537
- windows[name] = t - prev; prev = t;
1538
- }
1539
- return { windows, problems };
1540
- }
1541
- export const budgetKeyOf = (label) => (/^S2:/.test(label) ? "warm" : /^S11:/.test(label) ? "cold" : "edited");
1542
- /**
1543
- * NN18 over the windows: `runs` is `[{ label, workload, profile, ms, windows, rows }]`. A missing or null budget fails ("no budget measured"); an
1544
- * snapshot-lock window is budgeted on compile profiles only (a check's lock is counted by NN13, and its time is inside the total). A cargo-metadata row that hit must
1545
- * report `scanElapsedMs` within `metadataHitMs`.
1546
- */
1547
- export function assertWindowBudgets({ host, budgets, runs }) {
1548
- const problems = [];
1549
- if (!runs.length) return { ok: false, problems: ["no run to measure"] };
1550
- for (const r of runs) {
1551
- const prof = budgets?.hosts?.[host]?.workloads?.[r.workload]?.[r.profile];
1552
- const where = `${r.label} (${r.workload} ${r.profile})`;
1553
- if (!prof) { problems.push(`${where}: no budget entry for host ${host}`); continue; }
1554
- if (prof.totalMs === null || prof.totalMs === undefined) problems.push(`${where}: no budget measured for the whole run`);
1555
- else if (r.ms > prof.totalMs) problems.push(`${where}: took ${r.ms} ms, budget ${prof.totalMs} ms`);
1556
- const unbudgeted = [];
1557
- for (const w of WINDOWS) {
1558
- const v = r.windows?.[w];
1559
- if (w === "ownership" && r.profile.endsWith("-check")) continue; // a check takes the door's one snapshot lock like a compile; NN13 judges that count, and the sync and total budgets bound its time
1560
- if (v === null || v === undefined) { problems.push(`${where}: window ${w} could not be timed`); continue; }
1561
- const b = prof.windows?.[w];
1562
- if (b === null || b === undefined) unbudgeted.push(w); else if (v > b) problems.push(`${where}: window ${w} took ${v} ms, budget ${b} ms`);
1563
- }
1564
- if (unbudgeted.length) problems.push(`${where}: no budget measured for window(s) ${unbudgeted.join(", ")}`);
1565
- if (r.profile.startsWith("warm") && r.rows) for (const row of r.rows.values()) if (/^cargo-metadata(:|$)/.test(row.id) && row.coverage === "hit") {
1566
- if (prof.metadataHitMs === null || prof.metadataHitMs === undefined) { problems.push(`${where}: no budget measured for a cargo-metadata hit`); break; }
1567
- if (typeof row.scanElapsedMs !== "number") { problems.push(`${row.id}: the coverage row has no scanElapsedMs, so the metadata hit time cannot be judged`); break; }
1568
- if (row.scanElapsedMs > prof.metadataHitMs) problems.push(`${row.id}: a metadata hit took ${row.scanElapsedMs} ms, budget ${prof.metadataHitMs} ms`);
1569
- }
1570
- }
1571
- return { ok: problems.length === 0, problems };
1572
- }
1573
- /** The required (workload, profile) cells of a full run: the fixture warm/edited/cold, RightKit and HeardRight warm check, the Pulse compile. */
1574
- // The fixture's cold cells are not measured here: a cold run stops for Adrian's approval and the test proves that stop (Adrian 2026-11-07: "Test checks
1575
- // the stop"); cold budgets are measured from cold runs he approves.
1576
- export const REQUIRED_CELLS = Object.freeze([["fixture", "warm-check"], ["fixture", "warm-compile"], ["fixture", "edited-check"], ["fixture", "edited-compile"], ["rightkit", "warm-check"], ["heardright", "warm-check"], ["pulse", "cold-compile"]]);
1577
-
1578
- // ---- NN19 / NN30 / NN31: the receipt ---------------------------------------------------------------------------------------------------------------
1579
- export const CONTRACT_RECEIPT_SCHEMA = "rightkit.contract-test-receipt/1";
1580
- export function buildContractReceipt({ host, commit, gate, contractSha256, runnerSha256, budgetsSha256, fixtureCommit, result }) {
1581
- return { schema: CONTRACT_RECEIPT_SCHEMA, host, commit, gate, contractSha256, runnerSha256, budgetsSha256, fixtureCommit, startedAt: result.startedAt, endedAt: result.endedAt, verdict: result.verdict, ok: result.ok, nn: Object.fromEntries(result.nonNegotiables.map((n) => [n.id, n.status])), uncheckedClauses: result.clauses.filter((c) => c.status === "unchecked").map((c) => c.id), waivers: result.waivers ?? [] };
1582
- }
1583
- export 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;
1584
- /** `--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
1585
- * 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
1586
- * stands for or blocks the other. `b` is optional; when given, each receipt is judged on its own. */
1587
- export function verifyReleaseReceipts(a, b = null, { commit = null, contractSha256 = null, runnerSha256 = null, waivers = [], host = null } = {}) {
1588
- const problems = [];
1589
- if (host && a?.host !== host) problems.push(`the receipt is from ${a?.host ?? "no host"}, this host is ${host}`);
1590
- for (const [name, r] of (b ? [["first", a], ["second", b]] : [["the", a]])) {
1591
- const w = `${name} receipt (${r?.host})`;
1592
- if (!isObject(r) || r.schema !== CONTRACT_RECEIPT_SCHEMA) { problems.push(`${w}: not a ${CONTRACT_RECEIPT_SCHEMA}`); continue; }
1593
- if (r.ok !== true || !/^PASS /.test(String(r.verdict))) problems.push(`${w}: verdict ${JSON.stringify(r.verdict)} is not a PASS`);
1594
- if (!isCommit(r.commit)) problems.push(`${w}: commit is not a 40-hex sha`);
1595
- if (r.gate?.kind !== "installed" || !isSha(r.gate?.sealedSha256)) problems.push(`${w}: not the installed sealed gate (kind ${JSON.stringify(r.gate?.kind)})`);
1596
- for (const id of Object.keys(r.nn ?? {})) if (r.nn[id] !== "pass") problems.push(`${w}: ${id} is ${r.nn[id]}`);
1597
- if (!r.nn || Object.keys(r.nn).length < 38) problems.push(`${w}: covers ${Object.keys(r.nn ?? {}).length} non-negotiables, expected 38`);
1598
- const open = (r.uncheckedClauses ?? []).filter((id) => !waivers.some((x) => validWaiver(x) && x.clause === id));
1599
- 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 ? ", ..." : ""})`);
1600
- }
1601
- for (const r of (b ? [a, b] : [a]).filter(isObject)) {
1602
- if (commit && r.commit !== commit) problems.push(`the ${r.host} receipt is for commit ${r.commit}, the release is ${commit}`);
1603
- if (contractSha256 && r.contractSha256 !== contractSha256) problems.push(`the contract changed after the ${r.host} receipt was written`);
1604
- if (runnerSha256 && r.runnerSha256 !== runnerSha256) problems.push(`the runner changed after the ${r.host} receipt was written`);
1605
- }
1606
- return { ok: problems.length === 0, problems };
1607
- }
1608
- /** NN31: release, upload and trusted-gate install tooling must call `gate-acceptance.mjs --verify-release`. Reads the tooling's own files. */
1609
- export function releaseToolingCallsVerify(files) {
1610
- const calling = Object.entries(files).filter(([, text]) => /gate-acceptance(\.mjs)?\b[^\n]*--verify-release|--verify-release[^\n]*gate-acceptance/.test(text)).map(([f]) => f);
1611
- return { calling };
1612
- }
1613
-
1614
- // ---- NN36 / NN37: the lock and the review ----------------------------------------------------------------------------------------------------------
1615
- const numbersOf = (v, p = "") => (typeof v === "number" ? [[p, v]] : Array.isArray(v) ? v.flatMap((x, i) => numbersOf(x, `${p}[${i}]`)) : isObject(v) ? Object.entries(v).flatMap(([k, x]) => numbersOf(x, `${p}.${k}`)) : []);
1616
- /** Budgets that rose between two versions of the file (a null becoming a number is a new measurement, not a rise). A number becoming null is a change too (it removes a measured ceiling), so it needs Adrian's approval like a rise. */
1617
- export function risenBudgets(before, after) {
1618
- const was = new Map(numbersOf(before?.hosts ?? {}));
1619
- const is = new Map(numbersOf(after?.hosts ?? {}));
1620
- const nullAt = (obj, p) => { try { return p.split(/\.|(?=\[)/).filter(Boolean).reduce((o, k) => o?.[k.replace(/^\[(\d+)\]$/, "$1")], obj) === null; } catch { return false; } };
1621
- const out = [...is].filter(([p, v]) => was.has(p) && v > was.get(p)).map(([p, v]) => `${p}: ${was.get(p)} -> ${v}`);
1622
- for (const [p, v] of was) if (!is.has(p) && nullAt(after?.hosts ?? {}, p.replace(/^\./, ""))) out.push(`${p}: ${v} -> null (a measured budget removed)`);
1623
- return out;
1624
- }
1625
- export function lockProblems({ rootDir, paths, budgetsRel, contractRel, fixtureCommit, pin, run = (args) => git(rootDir, args) }) {
1626
- const problems = [];
1627
- const tableOf = (t) => parseContractNN(t).map((r) => `${r.id}|${r.property}|${r.fails}`).join("\n");
1628
- const safe = (args) => { try { return run(args); } catch { return null; } };
1629
- const dirty = (safe(["status", "--porcelain", "--", ...paths]) ?? "").split("\n").filter(Boolean).filter((l) => !l.includes(contractRel));
1630
- for (const l of dirty) problems.push(`a locked file has uncommitted changes (${l.trim()}): the commit must cite Adrian's approval`);
1631
- const headContract = safe(["show", `HEAD:${contractRel}`]); let nowContract = null; try { nowContract = fs.readFileSync(path.join(rootDir, contractRel), "utf8"); } catch { /* reported below */ }
1632
- if (headContract !== null && nowContract !== null && tableOf(headContract) !== tableOf(nowContract)) problems.push("the contract's NN table has uncommitted changes: the commit must cite Adrian's approval");
1633
- const base = (safe(["log", "--grep=Gate-Acceptance-Locked:", "--format=%H", "-n", "1"]) ?? "").trim();
1634
- if (!base) problems.push("the test is not locked: no commit carries a `Gate-Acceptance-Locked: <Adrian's words>` line, so there is no baseline to judge changes against");
1635
- else {
1636
- const commits = (safe(["log", `${base}..HEAD`, "--format=%H", "--", ...paths]) ?? "").split("\n").filter(Boolean);
1637
- for (const c of commits) {
1638
- const msg = safe(["show", "-s", "--format=%B", c]) ?? "";
1639
- const touchedContract = (safe(["diff-tree", "--no-commit-id", "--name-only", "-r", c]) ?? "").split("\n").includes(contractRel);
1640
- const onlyContractNoTable = touchedContract && !(paths.filter((p) => p !== contractRel).some((p) => (safe(["diff-tree", "--no-commit-id", "--name-only", "-r", c]) ?? "").split("\n").includes(p))) && tableOf(safe(["show", `${c}:${contractRel}`]) ?? "") === tableOf(safe(["show", `${c}~1:${contractRel}`]) ?? "");
1641
- if (onlyContractNoTable) continue;
1642
- if (!/^Adrian-approved: .+/m.test(msg)) problems.push(`commit ${c.slice(0, 12)} changed a locked file without \`Adrian-approved: <his words>\` in its message`);
1643
- let was = null; let is = null; try { was = JSON.parse(safe(["show", `${c}~1:${budgetsRel}`]) ?? "null"); is = JSON.parse(safe(["show", `${c}:${budgetsRel}`]) ?? "null"); } catch { /* not json at that commit */ }
1644
- for (const rise of risenBudgets(was, is)) problems.push(`commit ${c.slice(0, 12)} raised a budget: ${rise}`);
1645
- }
1646
- }
1647
- if (pin && fixtureCommit && pin !== fixtureCommit) problems.push(`the fixture is at ${fixtureCommit}, the pin is ${pin}`);
1648
- if (!pin) problems.push("the budgets file has no fixture pin (`fixture.commit`)");
1649
- return { ok: problems.length === 0, problems };
1650
- }
1651
- export function reviewProblems({ budgets, runnerSha256, contractSha256 }) {
1652
- const reviews = Array.isArray(budgets?.reviews) ? budgets.reviews : [];
1653
- const good = reviews.find((r) => isObject(r) && r.runnerSha256 === runnerSha256 && r.contractSha256 === contractSha256 && typeof r.reviewer === "string" && r.reviewer && typeof r.author === "string" && r.author && r.reviewer !== r.author && typeof r.adrianWords === "string" && r.adrianWords.trim() && r.verdict === "pass");
1654
- return good ? { ok: true, problems: [] } : { ok: false, problems: [`no independent review is recorded for this runner (sha256 ${String(runnerSha256).slice(0, 12)}) and contract (${String(contractSha256).slice(0, 12)}): budgets.reviews needs { runnerSha256, contractSha256, reviewer, author (different), adrianWords, verdict: "pass" }`] };
1655
- }
1656
- /** NN38: every cross-target row built with stand-ins says `evidence: "type-check-only"` in coverage and in the receipt. */
1657
- export function assertLimitedEvidence(runs) {
1658
- const problems = []; let cross = 0;
1659
- for (const [label, run] of Object.entries(runs)) {
1660
- if (!run.rows) continue;
1661
- const rows = [...run.rows.values()].filter((r) => /@[^@:]+$/.test(r.id) && r.coverage !== "skipped");
1662
- cross += rows.length;
1663
- const bad = rows.filter((r) => r.evidence !== "type-check-only");
1664
- if (bad.length) problems.push(`${label}: ${bad.length} cross-target row(s) lack evidence "type-check-only" in coverage (${bad.slice(0, 3).map((r) => r.id).join(", ")})`);
1665
- if (rows.length && run.receipt) {
1666
- const listed = new Set((run.receipt.stages?.compile?.limitedEvidence ?? []).filter((x) => x?.evidence === "type-check-only").map((x) => x.id));
1667
- const missing = rows.filter((r) => !listed.has(r.id));
1668
- if (missing.length) problems.push(`${label}: the receipt's stages.compile.limitedEvidence does not list ${missing.length} cross-target row(s) as type-check-only (the gate must write that list)`);
1669
- }
1670
- }
1671
- if (cross === 0) problems.push("no cross-target row was answered in any run: nothing shows the limited-evidence marking");
1672
- return { ok: problems.length === 0, problems };
1673
- }
1674
-
1675
-
1676
- /**
1677
- * NN39 tolerance: an idle-lane-while-queued window shorter than this is start-up jitter (one lane finishing and the next queued row being picked up,
1678
- * process spawn and the ledger's own write). Measured scheduling gaps between consecutive starts are tens of milliseconds; 250 ms is five times that.
1679
- * A longer window is a lane that sat idle while work waited.
1680
- */
1681
- export const NN39_TOLERANCE_MS = 250;
1682
- /** Intervals `[{ s, e }]` (ms) where fewer than `lanes` run while a later-starting interval is still queued: contiguous windows longer than `toleranceMs`. */
1683
- export function idleLaneWindows(intervals, lanes, toleranceMs = NN39_TOLERANCE_MS) {
1684
- const iv = intervals.filter((x) => Number.isFinite(x.s) && Number.isFinite(x.e)).sort((a, b) => a.s - b.s);
1685
- const points = [...new Set(iv.flatMap((x) => [x.s, x.e]))].sort((a, b) => a - b);
1686
- const idle = [];
1687
- for (let i = 0; i + 1 < points.length; i += 1) {
1688
- const [a, b] = [points[i], points[i + 1]];
1689
- const running = iv.filter((x) => x.s <= a && x.e > a).length;
1690
- const queued = iv.filter((x) => x.s >= b).length;
1691
- if (queued > 0 && running < lanes) {
1692
- const last = idle[idle.length - 1];
1693
- if (last && last.end === a) { last.end = b; last.minRunning = Math.min(last.minRunning, running); last.queued = Math.max(last.queued, queued); } else idle.push({ start: a, end: b, minRunning: running, queued });
1694
- }
1695
- }
1696
- return idle.filter((w) => w.end - w.start > toleranceMs).map((w) => ({ ...w, ms: w.end - w.start }));
1697
- }
1698
- /** NN39: the ledger's Class A lane processes (async children that are not probes or compiles) and Class B carried compiles keep `lanes` busy while work is queued. */
1699
- export function assertRealParallelism(entries, { lanes, ranA = 0, label = "" }) {
1700
- const problems = [];
1701
- const ns = entries.map((e) => ({ e, n: normalizeSpawn(e) }));
1702
- const at = ({ e }) => { const s = Date.parse(e.at); return { s, e: s + (Number(e.ms) || 0) }; };
1703
- const A = ns.filter(({ e, n }) => e.sync === false && typeof e.ms === "number" && !["git", "ps", "lsof", "launchctl", "sysctl"].includes(n.program) && !(cargoCall(n)?.via === "rustright") && !/rustright/.test(n.program)).map(at);
1704
- const B = ns.filter(({ n }) => { const c = cargoCall(n); return c && c.via !== "cargo" && COMPILING_CARGO.has(c.sub); }).map(at);
1705
- if (ranA >= 2 && A.length < 2) problems.push(`${ranA} Class A rows ran and the ledger shows ${A.length} lane process(es): the lanes cannot be judged`);
1706
- for (const [name, iv] of [["Class A lane", A], ["Class B carried compile", B]]) {
1707
- if (iv.length < 2) continue;
1708
- const idle = idleLaneWindows(iv, lanes);
1709
- for (const w of idle.slice(0, 3)) problems.push(`${label}${name}: idle lane while work waited: only ${w.minRunning} of ${lanes} lanes busy for ${w.ms} ms with ${w.queued} start(s) still queued (tolerance ${NN39_TOLERANCE_MS} ms)`);
1710
- }
1711
- return { ok: problems.length === 0, problems };
1712
- }
1713
-
1714
-
1715
- /** Cargo argv without the unit selectors (`-p x`, `--package x`, `-px`, `--package=x`): the feature round and configuration of an invocation. */
1716
- const withoutUnits = (args) => { const out = []; for (let i = 0; i < args.length; i += 1) { const a = args[i]; if (a === "-p" || a === "--package") { i += 1; continue; } if (/^(-p.+|--package=.*)$/.test(a)) continue; out.push(a); } return out; };
1717
- const cargoArgsOf = (n) => { const i = n.args.indexOf("cargo"); return n.program === "rustright" ? n.args.slice(i + 1) : n.args; };
1718
- /** The rows of a coverage map that belong to the doc stage (`doc:<workspace>:<crate>`). */
1719
- const docRowsOf = (rows) => [...rows.values()].filter((r) => cargoBFamily(r.id)?.fam === "doc");
1720
- /**
1721
- * NN40: docs are one command per workspace and feature round, on every compile. Fails on a `cargo rustdoc` start, on doc invocations of one
1722
- * workspace and configuration (the argv without its `-p` units) running more than once, on doc rows that ran with no doc invocation in the
1723
- * ledger, and on a compile run that answers no doc row at all (the doc stage was skipped).
1724
- */
1725
- export function assertDocOneCommand(rows, entries, { label = "" } = {}) {
1726
- const problems = []; const p = label ? `${label}: ` : "";
1727
- const calls = entries.map(normalizeSpawn).map((n) => ({ n, c: cargoCall(n) })).filter(({ c }) => c && (c.sub === "doc" || c.sub === "rustdoc"));
1728
- for (const { n, c } of calls) if (c.sub === "rustdoc") problems.push(`${p}a cargo rustdoc started (${n.program} ${shortArgs(n.args)}, cwd ${n.cwd}): docs must be one \`cargo doc\` per workspace and feature round`);
1729
- const groups = new Map();
1730
- for (const { n, c } of calls) { if (c.sub !== "doc") continue; const key = `${normalizeRunPart(n.cwd)}\u0000${withoutUnits(cargoArgsOf(n)).map(normalizeRunPart).join(" ")}`; (groups.get(key) ?? groups.set(key, []).get(key)).push(n); }
1731
- for (const [key, list] of groups) if (list.length > 1) problems.push(`${p}${list.length} doc invocations for one workspace and configuration (${key.replace("\u0000", " | ")}): ${list.slice(0, 3).map((n) => shortArgs(n.args)).join(" ;; ")}`);
1732
- const docRows = docRowsOf(rows).filter((r) => r.coverage !== "skipped");
1733
- if (docRows.length === 0) problems.push(`${p}the compile answered no doc row (every doc row is skipped or absent): the doc stage was skipped`);
1734
- const ranDoc = docRows.filter((r) => r.coverage === "ran");
1735
- if (ranDoc.length && !calls.some(({ c }) => c.sub === "doc")) problems.push(`${p}${ranDoc.length} doc row(s) ran (${ranDoc.slice(0, 3).map((r) => r.id).join(", ")}) and the ledger has no \`cargo doc\` start: the doc stage is not one command`);
1736
- return { ok: problems.length === 0, problems, docRows: docRows.length, ranDoc: ranDoc.length, invocations: calls.length };
1737
- }
1738
-
1739
- /** The `--target` values of a cargo argv. */
1740
- const targetsOf = (args) => { const t = []; for (let i = 0; i < args.length; i += 1) { if (args[i] === "--target" && args[i + 1]) { t.push(args[i + 1]); i += 1; } else if (/^--target=./.test(args[i])) t.push(args[i].slice(9)); } return t; };
1741
- const withoutTargets = (args) => { const out = []; for (let i = 0; i < args.length; i += 1) { if (args[i] === "--target") { i += 1; continue; } if (/^--target=/.test(args[i])) continue; out.push(args[i]); } return out; };
1742
- export const NN42_MISSING = "installed broker refuses several --target per invocation (RK_TARGET_INVALID)";
1743
- /**
1744
- * NN42: the cross targets of one stage go in one broker command naming every `--target`. Fails when the log carries RK_TARGET_INVALID (the broker
1745
- * refused several), or when one stage sends one command per cross target (same unit selection and configuration, a different single target each).
1746
- * Both name the missing broker capability. A run that built no cross-target row is no evidence either way (`crossRan` 0).
1747
- */
1748
- export function assertCrossTargetsOneCommand(log, entries, rows, { label = "" } = {}) {
1749
- const problems = []; const p = label ? `${label}: ` : "";
1750
- const crossRan = rows ? [...rows.values()].filter((r) => /@[^@:]+$/.test(r.id) && r.coverage === "ran").length : 0;
1751
- if (/RK_TARGET_INVALID/.test(String(log))) problems.push(`${p}${NN42_MISSING}: the log carries RK_TARGET_INVALID; the broker needs a capability to accept several --target in one command`);
1752
- const groups = new Map();
1753
- for (const n of entries.map(normalizeSpawn)) {
1754
- const c = cargoCall(n); if (!c || c.via === "cargo" || (!COMPILING_CARGO.has(c.sub) && c.sub !== "rustdoc")) continue;
1755
- const a = cargoArgsOf(n); const t = targetsOf(a); if (!t.length) continue;
1756
- const key = `${normalizeRunPart(n.cwd)}\u0000${c.sub}\u0000${withoutTargets(withoutUnits(a)).map(normalizeRunPart).join(" ")}`;
1757
- (groups.get(key) ?? groups.set(key, []).get(key)).push(t);
1758
- }
1759
- for (const [key, list] of groups) {
1760
- const all = [...new Set(list.flat())];
1761
- if (list.length > 1 && all.length > 1 && list.every((t) => t.length === 1)) problems.push(`${p}${NN42_MISSING}: the stage sent ${list.length} commands for the cross targets ${all.join(", ")} (${key.split("\u0000")[1]} in ${key.split("\u0000")[0]}), one per target; one broker command naming every --target is missing`);
1762
- }
1763
- return { ok: problems.length === 0, problems, crossRan, groups: groups.size };
1764
- }
1765
-
1766
- /**
1767
- * NN41: run 1 and run 2 are the same commit; every row that really failed in run 1 must be a cache hit that still says fail in run 2. Run 3 changes the
1768
- * toolchain identity; every such row must run again (a cached failure is never reused after the identity changed, an environment fix must rerun it).
1769
- */
1770
- /** The miss report a gate run names when it stops on RK_CACHE_MISS (its log line "report <file> (digest ...)"), parsed; null when none. */
1771
- export function missReportOf(log, read = (f) => JSON.parse(fs.readFileSync(f, "utf8"))) {
1772
- const m = /cache lookup: [^\n]*?report (\S+\.json) \(digest [0-9a-f]{64}\)/.exec(String(log ?? ""));
1773
- if (!m) return null;
1774
- try { return { file: m[1], ...read(m[1]) }; } catch (e) { return { file: m[1], error: e.message }; }
1775
- }
1776
- /**
1777
- * Adrian 2026-11-07 ("Test checks the stop"): a cold run (S11) and a run after a toolchain change (S17's third run) must stop on RK_CACHE_MISS before
1778
- * anything runs, every miss with the expected cause, and the rows named in `ids` must be in the report (a failure reused across a toolchain change would
1779
- * be a hit instead). `cause` is "new" (no stored result) or "changed" (inputs or environment changed).
1780
- */
1781
- export function assertMissStop(run, report, { cause, ids = [] } = {}) {
1782
- const problems = []; const log = String(run?.log ?? "");
1783
- if (!run) return { ok: false, problems: ["the run did not happen"] };
1784
- if (run.exit === 0) problems.push("the run exited 0: it did not stop for Adrian's approval");
1785
- if (!/BLOCKED: RK_CACHE_MISS/.test(log)) problems.push("the run did not stop on RK_CACHE_MISS");
1786
- if (/\] (pass|fail) +\S+ \(\d+s\)/.test(log)) problems.push("rows ran before or despite the stop");
1787
- if (!report) problems.push("no miss report is named in the run's output");
1788
- else if (report.error) problems.push(`the miss report ${report.file} cannot be read (${report.error})`);
1789
- else {
1790
- const want = cause === "new" ? /^no stored result/ : /^inputs or environment changed/;
1791
- const wrong = (report.rows ?? []).filter((r) => !want.test(String(r.cause)));
1792
- if (cause === "new" && wrong.length) problems.push(`${wrong.length} miss(es) are not "no stored result" on a cold run (first: ${wrong[0].id}: ${wrong[0].cause})`);
1793
- const named = new Set((report.rows ?? []).filter((r) => want.test(String(r.cause))).map((r) => r.id));
1794
- for (const id of ids) if (!named.has(id)) problems.push(`${id}: not in the stop report with cause ${cause}: the gate would have reused it`);
1795
- if (cause === "new" && (report.hit ?? 0) > 0) problems.push(`${report.hit} row(s) hit on a run whose cache was moved aside`);
1796
- }
1797
- return { ok: problems.length === 0, problems };
1798
- }
1799
-
1800
- export function assertCachedFailure(first, second, third, { identity = "", thirdStop = null } = {}) {
1801
- const problems = [];
1802
- const failed = first ? [...first.values()].filter((r) => r.class === "B" && r.coverage === "ran" && r.status === "fail") : [];
1803
- if (failed.length === 0) problems.push("the failing commit's first run has no Class B row that ran and failed: the fixture did not fail deterministically, so no cached failure can be judged");
1804
- for (const f of failed) {
1805
- const r = second?.get(f.id);
1806
- if (!r) problems.push(`${f.id}: absent from the second run of the same commit`);
1807
- else if (r.coverage !== "hit") problems.push(`${f.id}: failed, and with unchanged inputs, toolchain and broker identity it ${r.coverage === "ran" ? "ran again" : `is ${r.coverage}`} (a failure must be a cache hit)`);
1808
- else if (r.status !== "fail") problems.push(`${f.id}: a cached failure came back with status ${r.status}`);
1809
- else if (f.key && r.key && f.key !== r.key) problems.push(`${f.id}: the key changed between two identical runs`);
1810
- }
1811
- if (thirdStop) { if (!thirdStop.ok) problems.push(...thirdStop.problems.map((p) => `third run (${identity}): ${p}`)); }
1812
- else if (!third) problems.push(`no third run with a changed toolchain identity (${identity || "none chosen"}): the reuse after an identity change cannot be judged; the evidence needed is a second installed toolchain the gate keys on (RUSTUP_TOOLCHAIN)`);
1813
- else for (const f of failed) {
1814
- const r = third.get(f.id);
1815
- if (!r) problems.push(`${f.id}: absent from the run with a changed toolchain identity`);
1816
- else if (r.coverage === "hit") problems.push(`${f.id}: a cached failure was reused after the toolchain identity changed (${identity}): an environment fix must rerun it`);
1817
- }
1818
- return { ok: problems.length === 0, problems, failed: failed.map((f) => f.id) };
1819
- }
1820
-
1821
- /** The NN a step-less (release-level or structural) check cannot judge from a run: names the evidence the gate or the tooling must add. */
1822
- const NN_EVAL_EXT = {
1823
- NN20: (ctx) => { const r = usableRun(ctx, "S12:crate", { red: true }); if (r.fail) return [r.fail]; if (!ctx.crateEdit) return [bad("S12:crate", ["the edited crate's workspace and dependencies are not known"])]; return [checkFor("S12:crate", assertCrateEditScope(r.run.rows, ctx.crateEdit), r.run.coveragePaths)]; },
1824
- NN21: (ctx) => { const r = usableRun(ctx, "S12:lock", { red: true }); if (r.fail) return [r.fail]; return [checkFor("S12:lock", assertLockEditScope(r.run.rows, { lockDir: ctx.lockDir ?? "rk" }), r.run.coveragePaths)]; },
1825
- NN22: (ctx) => warmRuns(ctx, RED).map((w) => { if (w.fail) return w.fail; const l = ledgerOf(w.run, w.label); return l.fail ?? checkFor(w.label, assertWarmSync(w.run.log, l.entries), [w.run.logPath, w.run.ledgerPath]); }),
1826
- NN23: (ctx) => {
1827
- if (ctx.upgradeWhy) return [bad("S13", [ctx.upgradeWhy])];
1828
- const a = usableRun(ctx, "S13:prev", RED); const b = usableRun(ctx, "S13:next", RED); if (a.fail || b.fail) return [a.fail ?? b.fail];
1829
- return [checkFor("S13", assertUpgradeKeepsHits(a.run.rows, b.run.rows), [...a.run.coveragePaths, ...b.run.coveragePaths])];
1830
- },
1831
- NN24: (ctx) => { const r = usableRun(ctx, "S14:check", RED); if (r.fail) return [r.fail]; return [checkFor("S14:check", assertRestartWarm(r.run.rows, ctx.restart), r.run.coveragePaths)]; },
1832
- NN25: (ctx) => warmRuns(ctx, RED).map((w) => { if (w.fail) return w.fail; const l = ledgerOf(w.run, w.label); return l.fail ?? checkFor(w.label, assertWarmNoFamilies(l.entries, { log: w.run.log }), [w.run.ledgerPath]); }),
1833
- NN26: (ctx) => ledgerRuns(ctx).map(([label, run]) => { const l = ledgerOf(run, label); return l.fail ?? checkFor(label, assertNoServeAskSpawn(l.entries), [run.ledgerPath]); }),
1834
- NN27: (ctx) => { const out = []; for (const label of ["S1:compile", "S11:compile"].filter((l) => ctx.runs[l])) { const r = usableRun(ctx, label, RED); out.push(r.fail ?? checkFor(label, assertNoDoublePass(r.run.rows), r.run.coveragePaths)); } return out.length ? out : [bad("S1:compile", ["no compile run"])]; },
1835
- NN28: (ctx) => warmRuns(ctx, RED).map((w) => { if (w.fail) return w.fail; const l = ledgerOf(w.run, w.label); return l.fail ?? checkFor(w.label, assertChangeSource(w.run.log, l.entries), [w.run.logPath, w.run.ledgerPath]); }),
1836
- NN29: (ctx) => { const a = usableRun(ctx, "S2:check2", RED); const b = usableRun(ctx, "S16:ident", RED); if (a.fail || b.fail) return [a.fail ?? b.fail]; return [checkFor("S16:ident", assertIdentityIndependent(a.run.rows, b.run.rows), [...a.run.coveragePaths, ...b.run.coveragePaths])]; },
1837
- // Per host (Adrian 2026-11-07: "why would both machines be tied to each other in such a way for anything?"): this run IS the host's evidence;
1838
- // its verdict is the receipt --verify-release reads on this host. No other host's receipt is asked for.
1839
- NN30: (ctx) => [{ label: `${ctx.host} (this run)`, ok: true, problems: [], evidence: ["this run's own receipt"] }],
1840
- NN31: (ctx) => {
1841
- const calling = ctx.tooling?.calling ?? [];
1842
- if (calling.length) return [{ label: "tooling", ok: true, problems: [], evidence: calling }];
1843
- return [bad("tooling", [`no release, upload or trusted-gate install tooling calls \`node packages/release/gate-acceptance.mjs --verify-release <receipt-mac> <receipt-dell>\` (searched: ${(ctx.tooling?.searched ?? []).length} file(s)). Release/upload tooling (right-release upload, build-release, the publish path) and the trusted-gate promotion (installing a candidate beside the trusted gate, testing it, then promoting) must call it and refuse on a non-zero exit`], ctx.tooling?.searched?.slice(0, 3) ?? [])];
1844
- },
1845
- NN32: (ctx) => {
1846
- const kills = Object.entries(ctx.runs).filter(([, r]) => r.kill);
1847
- if (!kills.length) return [bad("S8", ["no kill case ran"])];
1848
- const out = kills.map(([label, r]) => checkFor(label, r.recovery ?? { ok: false, problems: ["no recovery verdict"] }, [r.logPath]));
1849
- const have = new Set(kills.map(([, r]) => r.killSignal ?? r.signalName));
1850
- const need = ctx.host === "dell" ? ["terminate"] : ["SIGKILL", "SIGINT"];
1851
- const lacking = need.filter((s) => !have.has(s) && !(s === "terminate" && [...have].some((x) => x === "SIGKILL" || x === "terminate")));
1852
- if (lacking.length) out.push(bad("signals", [`the host's kill signal(s) not exercised: ${lacking.join(", ")}`]));
1853
- return out;
1854
- },
1855
- NN33: (ctx) => {
1856
- const registryIds = (ctx.nnSet ?? NN_ALL).map((n) => n.id);
1857
- const checkIds = [...Object.keys(NN_EVAL), ...Object.keys(NN_EVAL_EXT), ...(ctx.postIds ?? [])];
1858
- return [{ label: "contract", ...assertContractMatch({ contractRows: parseContractNN(ctx.contractText), checkIds, registryIds }), evidence: [ctx.contractFile ?? CONTRACT_FILE] }];
1859
- },
1860
- NN34: () => [],
1861
- NN35: () => [],
1862
- NN36: (ctx) => [{ label: "lock", ...lockProblems({ rootDir: ctx.rootDir, paths: ["packages/release/gate-acceptance.mjs", "ci/gate-acceptance-budgets.json", "docs/GATE-CONTRACT.md"], budgetsRel: "ci/gate-acceptance-budgets.json", contractRel: "docs/GATE-CONTRACT.md", fixtureCommit: ctx.fixtureCommit, pin: ctx.budgets?.fixture?.commit }), evidence: ["git history of the runner, the contract table, the budgets file"] }],
1863
- NN37: (ctx) => [{ label: "review", ...reviewProblems({ budgets: ctx.budgets, runnerSha256: ctx.runnerSha256, contractSha256: ctx.contractSha256 }), evidence: [BUDGETS_FILE] }],
1864
- NN39: (ctx) => {
1865
- const out = [];
1866
- for (const label of ["S1:check", "S11:check", "S1:compile", "S11:compile"].filter((l) => ctx.runs[l])) {
1867
- const w = usableRun(ctx, label, RED); if (w.fail) { out.push(w.fail); continue; }
1868
- const l = ledgerOf(w.run, label); if (l.fail) { out.push(l.fail); continue; }
1869
- const ranA = [...w.run.rows.values()].filter((r) => r.class === "A" && r.coverage === "ran").length;
1870
- out.push(checkFor(label, assertRealParallelism(l.entries, { lanes: ctx.cores, ranA }), [w.run.ledgerPath]));
1871
- }
1872
- return out;
1873
- },
1874
- NN40: (ctx) => {
1875
- const labels = Object.keys(ctx.runs).filter((l) => ctx.runs[l].stage === "compile" && ctx.runs[l].ladder && !ctx.runs[l].kill && /^(S1|S2|S11):compile\d?$/.test(l));
1876
- if (!labels.length) return [bad("S2:compile", ["no compile run exists, so no doc evidence exists (a run with --checks-only has none)"])];
1877
- return labels.map((label) => { const w = usableRun(ctx, label, RED); if (w.fail) return w.fail; const l = ledgerOf(w.run, label); return l.fail ?? checkFor(label, assertDocOneCommand(w.run.rows, l.entries, { label }), [w.run.ledgerPath, ...w.run.coveragePaths]); });
1878
- },
1879
- NN41: (ctx) => {
1880
- const a = usableRun(ctx, "S17:fail1", RED); const b = usableRun(ctx, "S17:fail2", RED); if (a.fail || b.fail) return [a.fail ?? b.fail];
1881
- const c = ctx.runs["S17:fail3"] ? usableRun(ctx, "S17:fail3", RED) : null; if (c?.fail) return [c.fail];
1882
- // The third run stops for Adrian's approval (a toolchain change); its miss report must name every failing row (none reused).
1883
- const stop = ctx.runs["S17:fail3-stop"];
1884
- const failedIds = [...(a.run.rows?.values() ?? [])].filter((r) => r.class === "B" && r.coverage === "ran" && r.status === "fail").map((r) => r.id);
1885
- const thirdStop = stop ? assertMissStop(stop, missReportOf(stop.log), { cause: "changed", ids: failedIds }) : null;
1886
- return [checkFor("S17", assertCachedFailure(a.run.rows, b.run.rows, c?.run.rows ?? null, { identity: ctx.identityChange ?? "", thirdStop }), [...a.run.coveragePaths, ...b.run.coveragePaths, ...(c?.run.coveragePaths ?? [])])];
1887
- },
1888
- NN42: (ctx) => {
1889
- const labels = Object.keys(ctx.runs).filter((l) => ctx.runs[l].stage === "compile" && ctx.runs[l].ladder && !ctx.runs[l].kill && /^(S1|S2|S11):compile\d?$/.test(l));
1890
- if (!labels.length) return [bad("S2:compile", ["no compile run exists, so no cross-target evidence exists"])];
1891
- return labels.map((label) => { const w = usableRun(ctx, label, RED); if (w.fail) return w.fail; const l = ledgerOf(w.run, label); return l.fail ?? checkFor(label, assertCrossTargetsOneCommand(w.run.log, l.entries, w.run.rows, { label }), [w.run.ledgerPath, w.run.logPath]); });
1892
- },
1893
- NN38: (ctx) => [{ label: "limited evidence", ...assertLimitedEvidence(ctx.runs), evidence: Object.values(ctx.runs).flatMap((r) => r.coveragePaths ?? []).slice(0, 3) }],
1894
- };
1895
-
1896
- const PREV_WARM = Object.freeze({ "S2:check": "S1:check", "S2:compile": "S1:compile", "S2:check2": "S2:check", "S2:compile2": "S2:compile" });
1897
- const kindOf = (label) => (/compile/.test(label) ? "compile" : "check");
1898
- const bad = (label, problems, evidence = []) => ({ label, ok: false, problems, evidence });
1899
- const checkFor = (label, res, evidence) => ({ label, ok: res.ok, problems: res.problems, evidence });
1900
-
1901
- /** A run usable as warm or edit evidence: it executed, exited 0 and wrote coverage rows; otherwise a failing check names why. */
1902
- function usableRun(ctx, label, { rows = true, red = false } = {}) {
1903
- const run = ctx.runs[label];
1904
- if (!run) return { fail: bad(label, [`run ${label} did not execute, so its evidence does not exist`]) };
1905
- // `red`: Class A coverage, keys, ledger and log lines of a compile that failed in Class B are still evidence of the Class A properties (NN01, 05, 06, 10, 12, 14, 15).
1906
- if (run.exit !== 0 && !(red && run.rows)) return { fail: bad(label, [`run ${label} exited ${run.exit}${run.timedOut ? " (timed out)" : ""}: its evidence cannot stand for a passing run`], [run.logPath]) };
1907
- if (rows && !run.rows) return { fail: bad(label, [`run ${label} wrote no readable coverage report`], [run.logPath]) };
1908
- return { run };
1909
- }
1910
- /** The run's spawn ledger entries, or a failing check: the gate under test must emit it (RK_GATE_SPAWN_LEDGER). */
1911
- function ledgerOf(run, label) {
1912
- if (!run.ledgerPath) return { fail: bad(label, [`run ${label} was not started with RK_GATE_SPAWN_LEDGER`]) };
1913
- if (!run.ledger) return { fail: bad(label, [`run ${label} wrote no spawn ledger at ${run.ledgerPath}: the gate under test does not emit RK_GATE_SPAWN_LEDGER (spawn-ledger.mjs installed by the gate entry)`], [run.ledgerPath]) };
1914
- if (run.ledger.problems.length) return { fail: bad(label, run.ledger.problems.slice(0, 5), [run.ledgerPath]) };
1915
- if (run.ledger.entries.length === 0) return { fail: bad(label, [`the spawn ledger ${run.ledgerPath} is empty: a gate run starts child processes, so it was not recorded`], [run.ledgerPath]) };
1916
- return { entries: run.ledger.entries };
1917
- }
1918
- const warmRuns = (ctx, opts = {}) => (ctx.warmLabels ?? WARM_LABELS).map((label) => ({ label, ...usableRun(ctx, label, opts) }));
1919
- const RED = { red: true };
1920
- const ledgerRuns = (ctx) => Object.entries(ctx.runs).filter(([, r]) => r.ledgerPath !== undefined && !r.kill);
1921
-
1922
- const NN_EVAL = {
1923
- NN01: (ctx) => warmRuns(ctx, RED).flatMap((w) => {
1924
- if (w.fail) return [w.fail];
1925
- const out = [checkFor(w.label, assertNoClassARan(w.run.rows), w.run.coveragePaths)];
1926
- if (ctx.extended) { const l = ledgerOf(w.run, w.label); out.push(l.fail ?? checkFor(`${w.label} ledger`, assertHitRowsStartedNoTool(w.run.rows, l.entries), [w.run.ledgerPath])); }
1927
- return out;
1928
- }),
1929
- NN02: (ctx) => ["S2:compile", "S2:compile2"].map((label) => {
1930
- const w = usableRun(ctx, label); if (w.fail) return w.fail;
1931
- const prev = ctx.runs["S1:compile"]?.rows ?? null;
1932
- const r = assertNoClassBRan(w.run.rows, prev, { strict: Boolean(ctx.extended) });
1933
- return { ...checkFor(label, r, w.run.coveragePaths), reported: r.reported };
1934
- }),
1935
- NN03: (ctx) => {
1936
- const s3 = usableRun(ctx, "S3:check"); if (s3.fail) return [{ ...s3.fail, problems: [...s3.fail.problems, ctx.s3Why ?? ""].filter(Boolean) }];
1937
- const prev = ctx.runs["S2:check2"]?.rows ?? ctx.runs["S2:check"]?.rows ?? ctx.runs["S1:check"]?.rows;
1938
- if (!prev) return [bad("S3:check", ["no earlier check run to compare the edit against"])];
1939
- const out = [checkFor("S3:check", assertOneFileEdit(prev, s3.run.rows), [...s3.run.coveragePaths])];
1940
- if (ctx.extended) { const l = ledgerOf(s3.run, "S3:check"); out.push(l.fail ?? checkFor("S3:check files read", assertEditedFilesRead(s3.run.rows, l.entries, { files: [ctx.s3File] }), [s3.run.ledgerPath, ...s3.run.coveragePaths])); }
1941
- return out;
1942
- },
1943
- NN04: (ctx) => {
1944
- const s4 = usableRun(ctx, "S4:check"); if (s4.fail) return [{ ...s4.fail, problems: [...s4.fail.problems, ctx.s4Why ?? ""].filter(Boolean) }];
1945
- if (!s4.run.manifestInfo) return [bad("S4:check", ["the edited manifest's workspace is not known"])];
1946
- const out = [checkFor("S4:check", assertOtherWorkspacesIdle(s4.run.rows, s4.run.manifestInfo), s4.run.coveragePaths)];
1947
- if (ctx.extended) { const c = usableRun(ctx, "S12:manifest", RED); out.push(c.fail ?? checkFor("S12:manifest (--to compile)", assertOtherWorkspacesIdleAny(c.run.rows, { workspace: s4.run.manifestInfo.workspace }), c.run.coveragePaths)); }
1948
- return out;
1949
- },
1950
- NN05: (ctx) => [["S2:check", "S2:check2"], ["S2:compile", "S2:compile2"]].map(([a, b]) => {
1951
- const x = usableRun(ctx, a, RED); const y = usableRun(ctx, b, RED);
1952
- if (x.fail || y.fail) return x.fail ?? y.fail;
1953
- return checkFor(`${a} vs ${b}`, assertKeysStable(x.run.rows, y.run.rows), [...x.run.coveragePaths, ...y.run.coveragePaths]);
1954
- }),
1955
- NN06: (ctx) => {
1956
- const labels = ["S1:check", "S1:compile", ...WARM_LABELS, "S3:check", "S4:check"].filter((l) => ctx.runs[l]);
1957
- const digests = new Set();
1958
- for (const l of labels) { const d = envDigestOf(ctx.runs[l].log); if (d?.env) digests.add(d.env); if (d?.start) digests.add(d.start); }
1959
- const out = [];
1960
- for (const l of labels) { const w = usableRun(ctx, l, RED); if (w.fail) { out.push(w.fail); continue; } out.push(checkFor(l, assertEnvDigestScope(w.run.rows, [...digests]), w.run.coveragePaths)); }
1961
- return out.length ? out : [bad("S1/S2", ["no check or compile run produced coverage keys"])];
1962
- },
1963
- NN07: (ctx) => ledgerRuns(ctx).map(([label, run]) => { const l = ledgerOf(run, label); return l.fail ?? checkFor(label, assertNoDuplicateSpawns(l.entries), [run.ledgerPath]); }),
1964
- NN08: (ctx) => ledgerRuns(ctx).filter(([, r]) => r.exit === 0).map(([label, run]) => { const l = ledgerOf(run, label); return l.fail ?? checkFor(label, assertRustfmtSpawns(l.entries, run.rows), [run.ledgerPath, ...run.coveragePaths]); }),
1965
- NN09: (ctx) => ledgerRuns(ctx).map(([label, run]) => { const l = ledgerOf(run, label); if (l.fail) return l.fail; const a = assertNoBrokerNonCompiling(l.entries); const v = ctx.extended ? assertNoBrokerVersion(l.entries) : { problems: [] }; return checkFor(label, { ok: a.ok && !v.problems.length, problems: [...a.problems, ...v.problems] }, [run.ledgerPath]); }),
1966
- NN10: (ctx) => warmRuns(ctx, RED).map((w) => { if (w.fail) return w.fail; const l = ledgerOf(w.run, w.label); return l.fail ?? checkFor(w.label, assertNoRealCargoMetadata(l.entries), [w.run.ledgerPath]); }),
1967
- NN11: (ctx) => {
1968
- const cold = ["S1:check", "S1:compile"].filter((l) => ctx.runs[l]);
1969
- const out = cold.map((label) => checkFor(label, assertSnapshotProof(ctx.runs[label].log, { warm: false }), [ctx.runs[label].logPath]));
1970
- for (const w of warmRuns(ctx, RED)) {
1971
- if (w.fail) { out.push(w.fail); continue; }
1972
- out.push(checkFor(w.label, assertSnapshotProof(w.run.log, { warm: true }), [w.run.logPath]));
1973
- if (ctx.extended) { const l = ledgerOf(w.run, w.label); out.push(l.fail ?? checkFor(`${w.label} ledger`, assertLedgerAgreesWithProof(w.run.log, l.entries), [w.run.logPath, w.run.ledgerPath])); }
1974
- }
1975
- return out;
1976
- },
1977
- NN12: (ctx) => {
1978
- const out = warmRuns(ctx, RED).map((w) => { if (w.fail) return w.fail; const l = ledgerOf(w.run, w.label); return l.fail ?? checkFor(w.label, assertDependencyReuse(w.run.log, l.entries), [w.run.logPath, w.run.ledgerPath]); });
1979
- for (const [a, b] of [["S2:check", "S2:check2"], ["S2:compile", "S2:compile2"]]) {
1980
- const x = ctx.runs[a]; const y = ctx.runs[b];
1981
- if (x && y) out.push(checkFor(`${a} vs ${b}`, assertDigestStable(x.log, y.log), [x.logPath, y.logPath]));
1982
- }
1983
- return out;
1984
- },
1985
- NN13: (ctx) => {
1986
- const out = Object.entries(ctx.runs).filter(([, r]) => r.stage === "check" && r.ledgerPath !== undefined && !r.kill).flatMap(([label, r]) => {
1987
- const a = checkFor(label, assertOneExclusionOnCheck(r.log), [r.logPath]);
1988
- if (!ctx.extended) return [a];
1989
- const l = ledgerOf(r, label);
1990
- return [a, l.fail ?? checkFor(`${label} ledger`, assertNoProcessProbe(l.entries), [r.ledgerPath])];
1991
- });
1992
- return out;
1993
- },
1994
- NN14: (ctx) => warmRuns(ctx, RED).map((w) => w.fail ?? checkFor(w.label, assertRulesCached(w.run.log), [w.run.logPath])),
1995
- NN15: (ctx) => warmRuns(ctx, RED).map((w) => {
1996
- if (w.fail) return w.fail;
1997
- const prevRun = ctx.runs[PREV_WARM[w.label]];
1998
- return checkFor(w.label, assertAdviceCached(prevRun?.rows ?? null, w.run.rows, { startedAt: w.run.coverageStarts?.[0], prevStartedAt: prevRun?.coverageStarts?.[0] }), w.run.coveragePaths);
1999
- }),
2000
- NN16: (ctx) => {
2001
- const run = ctx.runs["S10:units"];
2002
- if (!run) return [bad("S10:units", [ctx.unitsWhy ?? "the unit-list run did not execute"])];
2003
- const l = ledgerOf(run, "S10:units"); if (l.fail) return [run.exit !== 0 ? bad("S10:units", [`the unit-list run exited ${run.exit}`, ...l.fail.problems], [run.logPath]) : l.fail];
2004
- const a = assertUnitListShare(run.log, l.entries, { units: run.units?.length ?? 0 });
2005
- return [checkFor("S10:units", { ok: a.ok && run.exit === 0, problems: [...a.problems, ...(run.exit === 0 ? [] : [`the unit-list run exited ${run.exit}`])] }, [run.logPath, run.ledgerPath])];
2006
- },
2007
- NN17: (ctx) => {
2008
- const labels = Object.keys(ctx.runs).filter((l) => /^S[12]:/.test(l) && ctx.runs[l].ledgerPath !== undefined && /class A scans \d+ at a time/.test(ctx.runs[l].log));
2009
- const out = labels.map((l) => checkFor(`lanes ${l}`, assertLanes(ctx.runs[l].log, { cores: ctx.cores, jobsOverride: ctx.jobsEnv }), [ctx.runs[l].logPath]));
2010
- if (!out.length) out.push(bad("lanes", ["no run's log has a `class A scans N at a time` line"]));
2011
- const compiles = ["S1:compile", "S2:compile", "S2:compile2"].filter((l) => ctx.runs[l]);
2012
- if (!compiles.length) out.push(bad("batching", ["no compile run to read the class B batching note from"]));
2013
- for (const l of compiles) { const run = ctx.runs[l]; const le = ledgerOf(run, l); out.push(le.fail ?? checkFor(`batching ${l}`, assertBatching(run.log, le.entries, { exit: run.exit }), [run.logPath, run.ledgerPath])); }
2014
- return out;
2015
- },
2016
- NN18: (ctx) => {
2017
- const runs = []; const out = [];
2018
- if (ctx.budgetProblem) out.push(bad("budgets", [ctx.budgetProblem], [BUDGETS_FILE]));
2019
- for (const w of warmRuns(ctx)) {
2020
- if (w.fail) { out.push(w.fail); continue; }
2021
- const m = stageMarks(w.run.log, w.run.startedMs);
2022
- if (m.problems.length) out.push(bad(w.label, m.problems, [w.run.logPath]));
2023
- runs.push({ label: w.label, kind: kindOf(w.label), ms: w.run.ms, marks: m.marks });
2024
- }
2025
- if (!ctx.budgetProblem) out.push(checkFor("budget", assertBudget({ host: ctx.host, budgets: ctx.budgets, runs }), [BUDGETS_FILE]));
2026
- out.measured = runs;
2027
- if (ctx.extended) out.push(...windowChecks(ctx));
2028
- return out;
2029
- },
2030
- NN19: (ctx) => {
2031
- const id = ctx.gateIdentity ?? { ok: false, problems: ["the gate's identity was not established"] };
2032
- const dev = id.kind === "named" ? { ok: false, problems: ["development run: the gate under test is a named gate, not the newest sealed trusted gate; its results are development evidence and never count"] } : { ok: true, problems: [] };
2033
- return [checkFor("gate", { ok: id.ok && dev.ok, problems: [...id.problems, ...dev.problems] }, [ctx.gateIdentityEvidence ?? "--version, launcher"])];
2034
- },
2035
- };
2036
-
2037
- /** NN18 over every run that has a workload profile: windows tile launch to exit; every required (workload, profile) cell must have a run. */
2038
- function windowChecks(ctx) {
2039
- const out = []; const runs = [];
2040
- for (const [label, run] of Object.entries(ctx.runs)) {
2041
- if (!run.profile || run.kill) continue;
2042
- const m = windowMarks(run.log, run.startedMs, run.startedMs + run.ms);
2043
- if (m.problems.length) { out.push(bad(label, m.problems, [run.logPath])); continue; }
2044
- runs.push({ label, workload: run.workload, profile: run.profile, ms: run.ms, windows: m.windows, rows: run.rows });
2045
- }
2046
- for (const [wl, pr] of REQUIRED_CELLS) if (!runs.some((r) => r.workload === wl && r.profile === pr) && !out.some((o) => o.label?.startsWith?.(`${wl}:${pr}`))) out.push(bad(`${wl}:${pr}`, [ctx.cellWhy?.[`${wl}:${pr}`] ?? "no run measured this workload and profile"]));
2047
- if (runs.length) out.push(checkFor("windows", assertWindowBudgets({ host: ctx.host, budgets: ctx.budgets, runs }), [BUDGETS_FILE]));
2048
- return out;
2049
- }
2050
-
2051
- /** One result per non-negotiable: `{ id, title, steps, status: "pass"|"fail"|"not-evaluated", problems[], checks[], evidence[] }`. A selected NN with no evidence fails. */
2052
- export function evaluateNonNegotiables(ctx) {
2053
- const wanted = new Set(ctx.wanted ?? []);
2054
- const set = ctx.nnSet ?? NN;
2055
- const done = []; ctx.nnSoFar = done;
2056
- return set.map((nn) => { const res = evalOne(nn); done.push(res); return res; });
2057
- function evalOne(nn) {
2058
- const base = { id: nn.id, title: nn.title, steps: nn.steps, evidenceSource: nn.evidence };
2059
- // Evaluated only when every step that produces its evidence was selected: a subset run cannot judge it, and says so (the verdict marks the run partial).
2060
- if (ctx.forceNN ? !ctx.forceNN.includes(nn.id) : (!nn.always && !nn.steps.every((s) => wanted.has(s)))) return { ...base, status: "not-evaluated", problems: [`steps ${nn.steps.filter((x) => !wanted.has(x)).join(", ")} not selected`], checks: [], evidence: [] };
2061
- let checks;
2062
- if (nn.post) return { ...base, status: "pass", problems: [], checks: [], evidence: [], pending: true };
2063
- try { checks = (NN_EVAL[nn.id] ?? NN_EVAL_EXT[nn.id])(ctx); } catch (e) { checks = [bad("assertion", [`assertion threw: ${e.stack ?? e.message}`])]; }
2064
- const measured = checks.measured;
2065
- if (!checks.length) checks = [bad("evidence", [`no evidence for ${nn.id}: ${nn.evidence}`])];
2066
- const failed = checks.filter((c) => !c.ok);
2067
- return { ...base, status: failed.length ? "fail" : "pass", problems: failed.flatMap((c) => c.problems.map((p) => (c.label ? `${c.label}: ${p}` : p))), checks: checks.map((c) => ({ label: c.label, ok: c.ok, ...(c.reported?.length ? { reported: c.reported } : {}) })), evidence: [...new Set(checks.flatMap((c) => c.evidence ?? []))], ...(measured ? { measured } : {}) };
2068
- }
2069
- }
2070
-
2071
- export const CHECKS = {
2072
- "GC-A21": (ctx) => {
2073
- const out = [];
2074
- for (const [label, run] of Object.entries(ctx.runs)) {
2075
- if (!run.ladder) continue;
2076
- if (run.args.includes("--route")) continue;
2077
- if (run.exit !== 0 && !expectedFailure(run)) out.push({ label, status: "fail", evidence: [run.logPath], problems: [`the run exited ${run.exit}${run.timedOut ? " (timed out)" : ""}`] });
2078
- const stamps = checkUtcStamps(run.log);
2079
- out.push({ label, ...verdict(stamps, [`${run.logPath} (every line)`]) });
2080
- if (run.exit === 0 && ["check", "compile", "package", "qualify"].includes(run.stage)) {
2081
- // A reused stage prints `[stage] already passed ...` instead of a timing line; only a stage that ran owes `passed in`.
2082
- const reused = new RegExp(`\\[${run.stage}\\] already passed`).test(run.log);
2083
- const timings = stageTimings(run.log).filter((t) => t.stage === run.stage);
2084
- 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)`]) });
2085
- }
2086
- if (run.coverageProblems.length) out.push({ label, status: "fail", evidence: run.coveragePaths, problems: run.coverageProblems });
2087
- else if (run.coveragePaths.length) out.push({ label, status: "pass", evidence: run.coveragePaths, problems: [] });
2088
- else if (run.exit === 0 && run.stage !== "render") out.push({ label, status: "fail", evidence: [run.logPath], problems: ["the log names no coverage report"] });
2089
- }
2090
- return out.length ? out : unchecked("no ladder run executed");
2091
- },
2092
- "GC-A04": (ctx) => {
2093
- const out = [];
2094
- for (const [label, run] of Object.entries(ctx.runs)) {
2095
- if (!run.receiptPath || expectedFailure(run)) continue;
2096
- 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; }
2097
- if (!run.receipt) { out.push({ label, status: "fail", evidence: [run.receiptPath], problems: ["the run exited 0 but wrote no readable receipt (--receipt-out)"] }); continue; }
2098
- const stages = LADDER.filter((s) => RECEIPT_STAGES.has(s) && run.stageIndex >= LADDER.indexOf(s)).filter((s) => run.receipt.stages?.[s]);
2099
- out.push({ label, ...verdict(validateDoorReceipt(run.receipt, { commit: run.commit, expectedTree: run.tree, stages }), [run.receiptPath]) });
2100
- }
2101
- 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"}`));
2102
- return out.length ? out : unchecked("no run wrote a receipt (--receipt-out)");
2103
- },
2104
- "GC-T05": (ctx) => {
2105
- const out = []; let reused = 0;
2106
- for (const [label, run] of Object.entries(ctx.runs)) {
2107
- if (!run.receipt || run.exit !== 0 || !run.receipt.stages?.compile || expectedFailure(run)) continue;
2108
- const r = classABeforeCompile(run.receipt, run.log);
2109
- if (r.skipped) { reused += 1; continue; }
2110
- out.push({ label, ...verdict(r, [`${run.receiptPath} (stages.compile.at), ${run.logPath} ([check] passed in stamp)`]) });
2111
- }
2112
- 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]) });
2113
- 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`);
2114
- },
2115
- "GC-A15": (ctx) => {
2116
- 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));
2117
- const out = [];
2118
- if (run) out.push({ status: outputDirsProblems(run.receipt).ok ? "pass" : "fail", evidence: [run.receiptPath], problems: outputDirsProblems(run.receipt).problems });
2119
- const n15 = Object.values(ctx.runs).find((r) => r.negative === "N15");
2120
- if (n15) out.push({ ...verdict(n15.negativeResult, [n15.logPath]) });
2121
- return out.length ? out : unchecked("no receipt records stage outputs");
2122
- },
2123
- "GC-A23": (ctx) => {
2124
- // Read right after each run (the snapshot is re-synced by every later step), never at the end.
2125
- const out = [];
2126
- for (const [label, run] of Object.entries(ctx.runs)) {
2127
- if (!run.sourceIdentity) continue;
2128
- const si = run.sourceIdentity;
2129
- if (si.error) { out.push({ label, status: "fail", evidence: [si.file], problems: [si.error] }); continue; }
2130
- out.push({ label, ...verdict(validateSourceIdentity(si.identity, { commit: run.commit, trees: si.trees }), [`${si.file} (read right after ${label})`, "git rev-parse <commit>:<dir>"]) });
2131
- }
2132
- return out.length ? out : unchecked("no run produced a receipt that names a snapshot path");
2133
- },
2134
- "GC-A22-render": (ctx) => {
2135
- const run = needRun(ctx, "S1:render");
2136
- if (!run) return unchecked("--to render was not run");
2137
- if (run.exit !== 0) return { status: "fail", evidence: [run.logPath], problems: [`--to render exited ${run.exit}`] };
2138
- const dir = (/(?:render(?:ed)?|stored|wrote|receipt)[^\n]*?(\S*rightkit-gate-render\S*)/.exec(run.log) ?? [])[1]?.replace(/[,.;)]+$/, "");
2139
- if (!dir) return { status: "fail", evidence: [run.logPath], problems: ["the log names no rightkit-gate-render directory"] };
2140
- const file = path.join(dir.endsWith(".json") ? path.dirname(dir) : dir, "render-receipt.json");
2141
- let receipt;
2142
- try { receipt = JSON.parse(fs.readFileSync(file, "utf8")); } catch (e) { return { status: "fail", evidence: [file], problems: [`cannot read ${file}: ${e.message}`] }; }
2143
- return verdict(validateRenderReceipt(receipt, { commit: run.commit, png: (rel) => { try { return fs.readFileSync(path.join(path.dirname(file), rel)); } catch { return null; } } }), [file]);
2144
- },
2145
- "GC-I22": (ctx) => {
2146
- const dir = path.join(here, "test-support", "vectors");
2147
- let source; const files = {};
2148
- 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] }; }
2149
- const up = ctx.rustrightContracts;
2150
- let upstream = null;
2151
- if (up && fs.existsSync(up)) { upstream = {}; for (const n of Object.keys(files)) { try { upstream[n] = fs.readFileSync(path.join(up, n)); } catch { /* reported as "no copy" by vectorsProblems */ } } }
2152
- return verdict(vectorsProblems({ source, files: { ...files }, upstream, upstreamDir: up }), [path.join(dir, "vectors-source.json"), up ?? "RustRight docs/contracts"]);
2153
- },
2154
- "GC-I18": (ctx) => {
2155
- const m = ctx.broker.manifest; const p = ctx.broker.pins;
2156
- 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"] };
2157
- return verdict(brokerDigestProblems({ manifest: m, pins: p }), [ctx.broker.manifestPath, ctx.broker.pinsPath]);
2158
- },
2159
- "GC-I01": (ctx) => {
2160
- const key = repositoryKey(ctx.git.canonical, ctx.platform);
2161
- const dir = path.join(ctx.managedRoot, "snapshots", key);
2162
- const out = [];
2163
- out.push({ ...verdict({ ok: fs.existsSync(dir), problems: fs.existsSync(dir) ? [] : [`${dir} does not exist`] }, [dir]) });
2164
- const run = Object.values(ctx.runs).find((r) => r.receipt?.stages?.check?.snapshot?.path);
2165
- 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]) }); }
2166
- return out;
2167
- },
2168
- "GC-A01": (ctx) => {
2169
- const out = [];
2170
- const n13 = Object.values(ctx.runs).filter((r) => r.negative === "N13");
2171
- for (const r of n13) out.push({ ...verdict(r.negativeResult, [r.logPath]) });
2172
- if (ctx.s9) {
2173
- const wt = worktreeCount(ctx.s9.worktree);
2174
- out.push({ ...verdict({ ok: wt === 1, problems: wt === 1 ? [] : [`${wt} worktrees listed, expected 1`] }, ["git worktree list --porcelain"]) });
2175
- out.push({ ...verdict(ctx.s9.snapshotDirCheck, [path.join(ctx.managedRoot, "snapshots")]) });
2176
- }
2177
- return out.length ? out : unchecked("neither N13 nor S9 ran");
2178
- },
2179
- "GC-T14": (ctx) => CHECKS["GC-A01"](ctx),
2180
- "GC-A02": (ctx) => {
2181
- const out = [];
2182
- 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) });
2183
- if (ctx.s6?.stash) out.push({ ...verdict(ctx.s6.stash, ["git stash list before and after S6"]) });
2184
- if (ctx.s6?.restore) out.push({ ...verdict(ctx.s6.restore, ["the S6 checkout restore"]) });
2185
- return out.length ? out : unchecked("S6 and S9 did not run");
2186
- },
2187
- "GC-T06": (ctx) => {
2188
- const out = [];
2189
- for (const [label, run] of Object.entries(ctx.runs)) if (run.recovery) out.push({ label, ...verdict(run.recovery, [run.logPath, run.lockPath ?? "snapshot.lock"]) });
2190
- 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"]) });
2191
- if (ctx.s9) out.push({ ...verdict(ctx.s9.lockClean, [ctx.s9.lockPath]) });
2192
- return out.length ? out : unchecked("S6, S8 and S9 did not run");
2193
- },
2194
- "GC-A19": (ctx) => {
2195
- const out = [];
2196
- const s4 = needRun(ctx, "S4:check");
2197
- const base = firstRows(ctx, "S2:check", "S1:check");
2198
- if (s4?.rows && base && s4.manifestInfo) out.push({ ...verdict(assertManifestEdit(base.rows, s4.rows, s4.manifestInfo), [...base.coveragePaths, ...s4.coveragePaths]) });
2199
- const s2 = needRun(ctx, "S2:check");
2200
- if (s2?.rows) {
2201
- const aud = [...s2.rows.values()].filter((r) => /^(cargo-deny|cargo-audit|pnpm-audit|ghsa-audit)/.test(r.id));
2202
- const bad = aud.filter((r) => r.coverage === "ran");
2203
- 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) });
2204
- }
2205
- return out.length ? out : unchecked("S2 and S4 did not run");
2206
- },
2207
- "GC-A24": (ctx) => {
2208
- const out = [];
2209
- const s1 = needRun(ctx, "S1:check"); const s2 = needRun(ctx, "S2:check"); const s3 = needRun(ctx, "S3:check");
2210
- if (s1?.rows && s2?.rows) out.push({ ...verdict(assertWarmRerun(s1.rows, s2.rows), [...s1.coveragePaths, ...s2.coveragePaths]) });
2211
- if (s2?.rows && s3?.rows) out.push({ ...verdict(assertOneFileEdit(s2.rows, s3.rows), [...s2.coveragePaths, ...s3.coveragePaths]) });
2212
- for (const [label, run] of Object.entries(ctx.runs)) if (run.kill === "K02") out.push({ label, ...verdict(run.recovery, [run.logPath]) });
2213
- return out.length ? out : unchecked("S1/S2/S3 coverage pairs are missing");
2214
- },
2215
- "GC-T04": (ctx) => {
2216
- const out = [];
2217
- for (const [label, run] of Object.entries(ctx.runs)) {
2218
- if (!run.receipt || run.exit !== 0 || expectedFailure(run)) continue;
2219
- const problems = [];
2220
- if (run.receipt.binding?.executor !== "broker") problems.push(`receipt.binding.executor is ${JSON.stringify(run.receipt.binding?.executor)}, expected "broker"`);
2221
- if ("brokerException" in run.receipt) problems.push("receipt.brokerException is set");
2222
- out.push({ label, ...verdict({ ok: problems.length === 0, problems }, [`${run.receiptPath} (binding.executor)`]) });
2223
- }
2224
- return out.length ? out : unchecked("no run wrote a receipt");
2225
- },
2226
- "GC-T19": (ctx) => {
2227
- const out = []; let release = false;
2228
- for (const [label, run] of Object.entries(ctx.runs)) {
2229
- if (!run.ladder || expectedFailure(run) && run.refusal === undefined) continue;
2230
- 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; }
2231
- if (!run.receipt || run.exit !== 0 || !run.receipt.stages?.check) continue;
2232
- if (run.stage === "qualify") release = true;
2233
- out.push({ label, ...verdict(ruleTierProblems(run.receipt, run.stage), [`${run.receiptPath} (stages.check.ruleTier)`]) });
2234
- }
2235
- if (!out.length) return unchecked("no run recorded a check stage");
2236
- 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}`));
2237
- return out;
2238
- },
2239
- "GC-A22-classA": (ctx) => {
2240
- const src = firstRows(ctx, "S1:check", "S1:compile", "S2:check");
2241
- const out = [];
2242
- if (src) {
2243
- const find = (re) => [...src.rows.values()].filter((r) => re.test(r.id));
2244
- for (const [name, re, need] of [["ghsa-audit", /^ghsa-audit(:|$)/, true], ["secret-scan", /^secret-scan$/, true], ["feature-coverage", /^feature-coverage$/, false]]) {
2245
- const rows = find(re);
2246
- 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; }
2247
- 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})` : ""}`);
2248
- out.push({ status: bad.length ? "fail" : "pass", evidence: src.coveragePaths, problems: bad });
2249
- }
2250
- } else out.push(unchecked("no coverage report (S1 check did not run)"));
2251
- const n02 = Object.values(ctx.runs).find((r) => r.negative === "N02");
2252
- if (n02) out.push({ ...verdict(n02.negativeResult, [n02.logPath]) });
2253
- return out;
2254
- },
2255
- "GC-I03": (ctx) => {
2256
- const out = [];
2257
- for (const [label, run] of Object.entries(ctx.runs)) {
2258
- if (!run.receipt || run.exit !== 0 || expectedFailure(run)) continue;
2259
- const problems = [];
2260
- for (const stage of ["check", "compile"]) {
2261
- const sn = run.receipt.stages?.[stage]?.snapshot;
2262
- if (stage === "check" && !run.receipt.stages?.check) { problems.push("receipt.stages.check is missing"); continue; }
2263
- if (run.receipt.stages?.[stage] === undefined) continue;
2264
- if (!isObject(sn)) problems.push(`receipt.stages.${stage}.snapshot is missing`);
2265
- 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)}`); }
2266
- }
2267
- out.push({ label, ...verdict({ ok: problems.length === 0, problems }, [`${run.receiptPath} (door half: snapshot tree at stage exit vs commit^{tree})`]) });
2268
- }
2269
- return out.length ? out : unchecked("no run wrote a receipt");
2270
- },
2271
- "GC-I05": (ctx) => {
2272
- const out = [];
2273
- for (const [label, run] of Object.entries(ctx.runs)) {
2274
- if (!run.receipt || run.exit !== 0 || expectedFailure(run) || !run.receiptPath) continue;
2275
- const stages = LADDER.filter((s) => RECEIPT_STAGES.has(s) && run.stageIndex >= LADDER.indexOf(s)).filter((s) => run.receipt.stages?.[s]);
2276
- 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)`]) });
2277
- }
2278
- return out.length ? out : unchecked("no run wrote a receipt");
2279
- },
2280
- "GC-I15": (ctx) => {
2281
- if (!ctx.s0 || !ctx.s9) return unchecked("S0 and S9 did not both run");
2282
- return verdict(brokerUnchanged(ctx.s0.broker, ctx.s9.broker), ["runningBrokerProcess() at S0 and at S9 (pid and start time)"]);
2283
- },
2284
- "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")),
2285
- };
2286
- const negativeCheck = (negId) => (ctx) => {
2287
- const run = Object.values(ctx.runs).find((r) => r.negative === negId);
2288
- return run ? { ...verdict(run.negativeResult, [run.logPath]) } : unchecked(`negative ${negId} was not run`);
2289
- };
2290
- CHECKS["GC-1A-R2"] = negativeCheck("N27");
2291
- CHECKS["GC-1A-R4"] = negativeCheck("N26");
2292
- const sameVerdict = (res, evidence, s0) => (s0 ? verdict(res, evidence) : unchecked("S0 listing missing"));
2293
-
2294
- /** The per-clause verdict out of its checks: any fail -> fail; all real checks pass and nothing blocks -> pass; otherwise unchecked (never pass without evidence). */
2295
- export function summarizeClause(id, checks, { allowInstall = true } = {}) {
2296
- const list = checks ?? [];
2297
- const ev = list.flatMap((c) => c.evidence ?? []);
2298
- const problems = list.flatMap((c) => (c.problems ?? []).map((p) => (c.label ? `${c.label}: ${p}` : p)));
2299
- const real = list.filter((c) => c.status !== "unchecked");
2300
- const blockers = list.filter((c) => c.status === "unchecked" && c.blocksPass);
2301
- let status = "unchecked";
2302
- if (list.some((c) => c.status === "fail")) status = "fail";
2303
- else if (real.length > 0 && real.every((c) => c.status === "pass") && blockers.length === 0) status = "pass";
2304
- let reason = null;
2305
- if (status === "unchecked") reason = installReason(id, allowInstall) ?? (list.length ? problems.join("; ") : (UNCHECKED_WHY[id] ?? NO_EVIDENCE));
2306
- return { id, ev: CLAUSES[id]?.ev ?? null, status, evidence: [...new Set(ev)], problems: status === "unchecked" ? [] : problems, ...(reason ? { reason } : {}), assertions: real.length };
2307
- }
2308
-
2309
- /** Steps a PASS tolerates as unchecked: unchecked by design (S5). Any other selected step that did not pass blocks the verdict. */
2310
- const BY_DESIGN_UNCHECKED = new Set(STEPS.filter((s) => s.byDesignUnchecked).map((s) => s.id));
2311
-
2312
- export function buildResult({ host, gate, broker, commit, steps, clauseChecks, startedAt, endedAt, notes = [], allowInstall = true, stepChecks = [], nonNegotiables = [], nnIds = NN_IDS, development = false, waivers = [] }) {
2313
- const clauses = Object.keys(CLAUSES).map((id) => summarizeClause(id, clauseChecks[id], { allowInstall }));
2314
- const counts = { pass: 0, fail: 0, unchecked: 0 };
2315
- for (const c of clauses) counts[c.status] += 1;
2316
- const stepsOut = steps.map((s) => ({ ...s, status: s.checks.some((c) => c === "fail") ? "fail" : s.checks.length && s.checks.every((c) => c === "pass") ? "pass" : "unchecked" }));
2317
- const blockers = [
2318
- ...clauses.filter((c) => c.status === "fail").map((c) => `clause ${c.id} failed`),
2319
- ...stepsOut.filter((s) => s.status === "fail").map((s) => `step ${s.id} failed`),
2320
- ...stepsOut.filter((s) => s.status === "unchecked" && !BY_DESIGN_UNCHECKED.has(s.id)).map((s) => `step ${s.id} did not run as specified`),
2321
- ...stepChecks.filter((c) => !c.ok).map((c) => `${c.step} check "${c.name}" failed`),
2322
- ];
2323
- const partial = stepsOut.length < STEPS.length;
2324
- // Non-negotiables (GC-A27): any failure blocks; in a full run every one must be present and passing (never unchecked, never absent).
2325
- const nnById = new Map(nonNegotiables.map((n) => [n.id, n]));
2326
- const nnCounts = { pass: 0, fail: 0, notEvaluated: 0 };
2327
- for (const id of nnIds) {
2328
- const n = nnById.get(id);
2329
- if (n?.status === "pass") nnCounts.pass += 1;
2330
- else if (n?.status === "not-evaluated" && partial) nnCounts.notEvaluated += 1;
2331
- else { nnCounts.fail += 1; blockers.push(n ? (n.status === "fail" ? `non-negotiable ${id} failed` : `non-negotiable ${id} was not evaluated in a full run`) : `non-negotiable ${id} has no result`); }
2332
- }
2333
- if (counts.pass === 0) blockers.push("no clause passed");
2334
- // NN34: a run of some steps never prints PASS. NN19: a run of a gate that is not the newest sealed trusted gate is a development run.
2335
- if (partial) blockers.push(`partial run (steps ${stepsOut.map((s) => s.id).join(",")} only): a partial run never passes`);
2336
- if (development) blockers.push("development run: the gate under test is not the newest sealed trusted gate; the run prints results and never passes");
2337
- const ok = blockers.length === 0;
2338
- const asserted = counts.pass + counts.fail;
2339
- const nnText = `non-negotiables ${nnCounts.pass} of ${nnIds.length} passed${nnCounts.notEvaluated ? `, ${nnCounts.notEvaluated} not evaluated (steps not selected)` : ""}${nnCounts.fail ? `, ${nnCounts.fail} failed` : ""}`;
2340
- const tail = `${asserted} of ${clauses.length} asserted, ${counts.unchecked} unchecked; ${nnText}`;
2341
- const verdictText = ok ? `PASS (${tail})` : `NOT PASSED (${development ? "development run; " : ""}${tail}${partial && stepsOut.length ? `; partial run: steps ${stepsOut.map((s) => s.id).join(",")} only` : ""}; ${counts.fail} failed clause(s); ${blockers.length} blocker(s))`;
2342
- return { schema: RESULT_SCHEMA, host, gate, broker, fixtureCommit: commit, startedAt, endedAt, steps: stepsOut, stepChecks, clauses, nonNegotiables, totals: { clauses: clauses.length, ...counts, nonNegotiables: nnCounts }, ok, verdict: verdictText, blockers, partial, development, waivers, notes };
2343
- }
2344
-
2345
- export function formatSummary(result) {
2346
- const lines = [`gate acceptance ${result.verdict} host ${result.host} commit ${String(result.fixtureCommit).slice(0, 12)}`, `clauses: ${result.totals.pass} pass, ${result.totals.fail} fail, ${result.totals.unchecked} unchecked of ${result.totals.clauses}`];
2347
- for (const b of result.blockers) lines.push(` BLOCKER ${b}`);
2348
- for (const c of result.clauses.filter((x) => x.status === "fail")) lines.push(` FAIL ${c.id}: ${c.problems.slice(0, 2).join(" | ").slice(0, 200)} [${c.evidence.slice(0, 2).join(", ")}]`);
2349
- for (const n of (result.nonNegotiables ?? [])) lines.push(` ${n.id} ${n.status}${n.status === "fail" ? `: ${n.problems.slice(0, 2).join(" | ").slice(0, 220)}` : ""}`);
2350
- for (const sc of (result.stepChecks ?? []).filter((x) => !x.ok)) lines.push(` FAIL ${sc.step} ${sc.name}: ${sc.problems.slice(0, 2).join(" | ").slice(0, 200)}`);
2351
- for (const s of result.steps) lines.push(` ${s.id} ${s.status} ${s.title}`);
2352
- return lines.join("\n");
2353
- }
2354
-
2355
- // ---------------------------------------------------------------------------------------------------------------------------------------------
2356
- // Runtime: git, the gate, the kill cases. Nothing below runs during `--plan` or in the pure tests (the dirty-checkout helpers are exported and tested
2357
- // against a temporary repository).
2358
- // ---------------------------------------------------------------------------------------------------------------------------------------------
2359
- const IDENT = Object.freeze({ GIT_AUTHOR_NAME: "gate-acceptance", GIT_AUTHOR_EMAIL: "gate-acceptance@invalid", GIT_COMMITTER_NAME: "gate-acceptance", GIT_COMMITTER_EMAIL: "gate-acceptance@invalid" });
2360
-
2361
- function git(cwd, args, { env = {}, input, buffer = false } = {}) {
2362
- const r = spawnSync("git", args, { cwd, encoding: buffer ? "buffer" : "utf8", env: { ...process.env, ...env }, input, maxBuffer: 1 << 28 });
2363
- if (r.status !== 0) throw new Error(`git ${args.join(" ")}: ${String(r.stderr || r.stdout || "").trim() || `exit ${r.status}`}`);
2364
- return r.stdout;
2365
- }
2366
-
2367
- /** Workspace directory a Cargo manifest belongs to: the nearest ancestor directory in `wsDirs`, else the manifest's own directory (a standalone package). */
2368
- /** Up to `n` unit selectors of the gate's grammar (crate and npm units named by a commit's tracked files), in sorted order. */
2369
- export function unitSelectorsOf(tracked, n = 2) {
2370
- const out = [];
2371
- for (const f of [...tracked].sort()) {
2372
- const c = /^crates\/(rightkit-[a-z0-9-]+)\/Cargo\.toml$/.exec(f); const p = /^packages\/([a-z0-9-]+)\/package\.json$/.exec(f);
2373
- if (c) out.push(`cargo:${c[1]}`); else if (p) out.push(`npm:@rightkit/${p[1]}`);
2374
- }
2375
- return out.slice(0, n);
2376
- }
2377
-
2378
- export function cargoWorkspaceOf(file, wsDirs) {
2379
- const dir = path.posix.dirname(file);
2380
- for (let d = dir; ; d = path.posix.dirname(d)) {
2381
- if (wsDirs.includes(d)) return d;
2382
- if (d === "." || d === "/") break;
2383
- }
2384
- return dir;
2385
- }
2386
-
2387
- function gitTools(fixture, scratch) {
2388
- const canonical = fs.realpathSync.native(fixture);
2389
- const created = [];
2390
- const self = {
2391
- canonical,
2392
- run: (args, o) => git(canonical, args, o),
2393
- head: () => git(canonical, ["rev-parse", "HEAD"]).trim(),
2394
- tree: (commit) => git(canonical, ["rev-parse", `${commit}^{tree}`]).trim(),
2395
- stash: () => git(canonical, ["stash", "list"]),
2396
- worktrees: () => git(canonical, ["worktree", "list", "--porcelain"]),
2397
- status: () => git(canonical, ["status", "--short"]),
2398
- tracked: (commit) => git(canonical, ["ls-tree", "-r", "--name-only", commit]).split("\n").filter(Boolean),
2399
- sourceTrees(commit) {
2400
- const dirs = new Set([""]);
2401
- for (const f of self.tracked(commit)) if (/(^|\/)(Cargo\.toml|Package\.swift|package\.json)$/.test(f)) dirs.add(path.posix.dirname(f) === "." ? "" : path.posix.dirname(f));
2402
- const trees = {};
2403
- for (const d of dirs) trees[d] = git(canonical, ["rev-parse", d === "" ? `${commit}^{tree}` : `${commit}:${d}`]).trim();
2404
- return trees;
2405
- },
2406
- show: (commit, file) => git(canonical, ["show", `${commit}:${file}`]),
2407
- blob: (commit, file) => git(canonical, ["cat-file", "blob", `${commit}:${file}`], { buffer: true }),
2408
- /** The Cargo layout of `commit`: workspace directories and `{ workspaceDir: [crate names] }` (for S4's "that workspace only"). */
2409
- cargoLayout(commit, tracked = self.tracked(commit)) {
2410
- const manifests = tracked.filter((f) => /(^|\/)Cargo\.toml$/.test(f));
2411
- const texts = new Map(manifests.map((f) => [f, self.show(commit, f)]));
2412
- const wsDirs = manifests.filter((f) => /^\s*\[workspace\]/m.test(texts.get(f))).map((f) => path.posix.dirname(f));
2413
- const crates = {};
2414
- for (const f of manifests) {
2415
- const name = /\[package\][^[]*?\bname\s*=\s*"([^"]+)"/s.exec(texts.get(f))?.[1];
2416
- if (!name) continue;
2417
- (crates[cargoWorkspaceOf(f, wsDirs)] ??= []).push(name);
2418
- }
2419
- return { manifests, wsDirs, crates, texts };
2420
- },
2421
- /** An ephemeral commit on `base` with `edits` ({path, content}); referenced under refs/witness/<name>; no branch, no checkout, no worktree. The temporary index lives under the scratch root. */
2422
- witnessCommit(base, name, edits) {
2423
- fs.mkdirSync(scratch, { recursive: true });
2424
- const idx = path.join(fs.mkdtempSync(path.join(scratch, "idx-")), "index");
2425
- const env = { GIT_INDEX_FILE: idx };
2426
- try {
2427
- git(canonical, ["read-tree", base], { env });
2428
- for (const e of edits) {
2429
- const blob = git(canonical, ["hash-object", "-w", "--stdin"], { input: e.content }).trim();
2430
- git(canonical, ["update-index", "--add", "--cacheinfo", `100644,${blob},${e.path}`], { env });
2431
- }
2432
- const tree = git(canonical, ["write-tree"], { env }).trim();
2433
- const commit = git(canonical, ["commit-tree", tree, "-p", base, "-m", `gate-acceptance ${name}`], { env: IDENT }).trim();
2434
- git(canonical, ["update-ref", `refs/witness/${name}`, commit]);
2435
- created.push(name);
2436
- return commit;
2437
- } finally { fs.rmSync(path.dirname(idx), { recursive: true, force: true }); }
2438
- },
2439
- /** Deletes every refs/witness/<name> this run created; returns the problems (empty when all are gone). */
2440
- dropWitnessRefs() {
2441
- const problems = [];
2442
- for (const name of created.splice(0)) { try { git(canonical, ["update-ref", "-d", `refs/witness/${name}`]); } catch (e) { problems.push(e.message); } }
2443
- return problems;
2444
- },
2445
- };
2446
- return self;
2447
- }
2448
-
2449
- // --- S6: the dirty checkout ---------------------------------------------------------------------------------------------------------------------
2450
- const stashEntries = (repo) => git(repo, ["stash", "list", "--format=%H %gd"]).split("\n").filter(Boolean).map((l) => { const [sha, gd] = l.split(" "); return { sha, gd }; });
2451
-
2452
- /** A checkout is clean when `git status --porcelain --untracked-files=all` prints nothing. */
2453
- export function assertCleanCheckout(repo) {
2454
- const st = git(repo, ["status", "--porcelain", "--untracked-files=all"]);
2455
- return st.trim() === "" ? { ok: true, problems: [] } : { ok: false, problems: [`the checkout is not clean: ${st.trim().split("\n")[0]}${st.trim().split("\n").length > 1 ? ` (+${st.trim().split("\n").length - 1} more)` : ""}`] };
2456
- }
2457
-
2458
- /**
2459
- * Makes `repo` dirty for S6: refuses a dirty checkout; edits tracked `file`, adds the untracked file, pushes both into a new stash, then edits and adds
2460
- * them again so the checkout is dirty AND a stash of ours stands. Returns the state `restoreDirtyCheckout` needs. A failure part-way restores before throwing.
2461
- */
2462
- export function makeDirtyCheckout(repo, { file, untracked }) {
2463
- const clean = assertCleanCheckout(repo);
2464
- if (!clean.ok) throw new Error(`refusing to make a dirty checkout: ${clean.problems[0]}`);
2465
- const abs = path.join(repo, file); const absU = path.join(repo, untracked);
2466
- if (fs.existsSync(absU)) throw new Error(`refusing: ${untracked} exists`);
2467
- const state = { repo, file, untracked, original: fs.readFileSync(abs), stashBefore: stashEntries(repo).map((e) => e.sha), stashSha: null };
2468
- try {
2469
- fs.writeFileSync(abs, Buffer.concat([state.original, Buffer.from("\ngate-acceptance dirty edit\n")]));
2470
- fs.writeFileSync(absU, "untracked\n");
2471
- git(repo, ["stash", "push", "--include-untracked", "-m", "gate-acceptance-s6"], { env: IDENT });
2472
- const after = stashEntries(repo);
2473
- if (after.length !== state.stashBefore.length + 1) throw new Error("git stash push did not create a stash");
2474
- state.stashSha = after[0].sha;
2475
- fs.writeFileSync(abs, Buffer.concat([state.original, Buffer.from("\ngate-acceptance second dirty edit\n")]));
2476
- fs.writeFileSync(absU, "untracked again\n");
2477
- return state;
2478
- } catch (e) {
2479
- const r = restoreDirtyCheckout(repo, state);
2480
- e.message += r.ok ? " (the checkout was restored)" : ` (the restore also failed: ${r.problems.join("; ")})`;
2481
- throw e;
2482
- }
2483
- }
2484
-
2485
- /**
2486
- * Restores what `makeDirtyCheckout` changed: removes the untracked file, restores the tracked file from the index, drops OUR stash only (found by its
2487
- * hash, so a stash that stood before is never touched), then verifies the checkout is clean, the stash list holds exactly the hashes it held before
2488
- * and the tracked file's bytes are the original ones.
2489
- */
2490
- export function restoreDirtyCheckout(repo, state) {
2491
- const problems = [];
2492
- const attempt = (what, fn) => { try { fn(); } catch (e) { problems.push(`${what}: ${e.message}`); } };
2493
- attempt("remove the untracked file", () => fs.rmSync(path.join(repo, state.untracked), { force: true }));
2494
- attempt("restore the tracked file", () => git(repo, ["checkout", "--", state.file]));
2495
- if (state.stashSha) attempt("drop the gate-acceptance stash", () => {
2496
- const entry = stashEntries(repo).find((e) => e.sha === state.stashSha);
2497
- if (!entry) throw new Error("it is not in the stash list");
2498
- git(repo, ["stash", "drop", entry.gd]);
2499
- });
2500
- attempt("verify", () => {
2501
- const clean = assertCleanCheckout(repo);
2502
- if (!clean.ok) problems.push(...clean.problems);
2503
- const now = stashEntries(repo).map((e) => e.sha);
2504
- if (JSON.stringify(now) !== JSON.stringify(state.stashBefore)) problems.push(`the stash list is ${JSON.stringify(now)}, it held ${JSON.stringify(state.stashBefore)}`);
2505
- if (!fs.readFileSync(path.join(repo, state.file)).equals(state.original)) problems.push(`${state.file} differs from its original bytes`);
2506
- });
2507
- return { ok: problems.length === 0, problems };
2508
- }
2509
-
2510
- const managedRootOf = (host) => (host === "dell" ? "D:\\.rightkit-managed" : "/Volumes/D/.rightkit-managed");
2511
- const scratchRootOf = (host) => (host === "dell" ? "D:\\scratch" : "/Volumes/D/scratch");
2512
- const defaultGate = (host) => (host === "dell" ? "D:\\.rightkit-managed\\agent-bin\\rightkit-host-gate.cmd" : "/Volumes/D/.rightkit-managed/agent-bin/rightkit-host-gate");
2513
- /** The workspace root that holds rightkit/ and rustright/ (this file is rightkit/packages/release/gate-acceptance.mjs). */
2514
- export const workspaceRootOf = (dir = here) => path.resolve(dir, "..", "..", "..");
2515
-
2516
- const listDirs = (dir) => { try { return fs.readdirSync(dir, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name).sort(); } catch { return []; } };
2517
-
2518
- function launch({ gate, args, cwd, env }) {
2519
- const spec = launchSpec(gate, args);
2520
- return spawn(spec.command, spec.args, { cwd, env, stdio: ["ignore", "pipe", "pipe"], detached: process.platform !== "win32", windowsHide: true, ...spec.options });
2521
- }
2522
-
2523
- /** Signals the launcher and everything it started (its process group; taskkill /T on Windows, where only the kill variant exists). */
2524
- function signalGroup(child, signal) {
2525
- try {
2526
- if (process.platform === "win32") spawnSync("taskkill", ["/T", "/F", "/PID", String(child.pid)]);
2527
- else process.kill(-child.pid, signal);
2528
- } catch { try { child.kill(signal); } catch { /* already gone */ } }
2529
- }
2530
-
2531
- /** Runs the gate to completion: `{ exit, signal, log, ms, timedOut }`. The environment is the caller's own; no flag or variable weakens the gate. A timeout kills the whole process group. */
2532
- function runGate({ gate, cwd, args, env = process.env, timeoutMs = 3_600_000 }) {
2533
- return new Promise((resolve) => {
2534
- const t0 = Date.now(); let log = ""; let timedOut = false; let child;
2535
- try { child = launch({ gate, args, cwd, env }); } catch (e) { resolve({ exit: null, signal: null, log: `spawn error: ${e.message}`, ms: 0, startedMs: t0, timedOut: false }); return; }
2536
- const timer = setTimeout(() => { timedOut = true; signalGroup(child, "SIGKILL"); }, timeoutMs);
2537
- child.stdout.on("data", (d) => { log += d; }); child.stderr.on("data", (d) => { log += d; });
2538
- child.on("close", (exit, signal) => { clearTimeout(timer); resolve({ exit, signal, log: timedOut ? `${log}\ngate-acceptance: timed out after ${timeoutMs} ms; the process group was killed` : log, ms: Date.now() - t0, startedMs: t0, timedOut }); });
2539
- child.on("error", (e) => { clearTimeout(timer); resolve({ exit: null, signal: null, log: `${log}\nspawn error: ${e.message}`, ms: Date.now() - t0, startedMs: t0, timedOut }); });
2540
- });
2541
- }
2542
-
2543
- /** Starts the gate, waits for `waitFor()` to return truthy (the snapshot lock) plus `afterMs`, then signals its process group. */
2544
- function killDuring({ gate, cwd, args, signal, waitFor, afterMs }) {
2545
- return new Promise((resolve) => {
2546
- let log = ""; let done = false; let child;
2547
- try { child = launch({ gate, args, cwd, env: process.env }); } catch (e) { resolve({ exit: null, signal: null, log: `spawn error: ${e.message}` }); return; }
2548
- child.stdout.on("data", (d) => { log += d; }); child.stderr.on("data", (d) => { log += d; });
2549
- child.on("close", (exit, sig) => { done = true; clearInterval(poll); clearTimeout(cap); resolve({ exit, signal: sig, log }); });
2550
- child.on("error", (e) => { done = true; clearInterval(poll); clearTimeout(cap); resolve({ exit: null, signal: null, log: `${log}\nspawn error: ${e.message}` }); });
2551
- let armedAt = null;
2552
- const poll = setInterval(() => {
2553
- if (done) return;
2554
- if (armedAt === null && waitFor()) armedAt = Date.now();
2555
- if (armedAt !== null && Date.now() - armedAt >= afterMs) { clearInterval(poll); signalGroup(child, signal); }
2556
- }, 100);
2557
- const cap = setTimeout(() => { if (!done) signalGroup(child, "SIGKILL"); }, 30 * 60_000); // the snapshot lock never appeared: the case proves nothing
2558
- });
2559
- }
2560
-
2561
- function readJson(file) { try { return { value: JSON.parse(fs.readFileSync(file, "utf8")) }; } catch (e) { return { error: `${file}: ${e.message}` }; } }
2562
- const readOrNull = (file) => { try { return fs.readFileSync(file); } catch { return null; } };
2563
-
2564
- /** The installed broker's runtime manifest and the gate's pins record. The client and its manifest are found the way the gate finds them (seam-broker.mjs brokerControlTarget): `managedRuntimeClient`, the agent shim resolved, the manifest beside the real client. */
2565
- function brokerIdentity(host, managedRoot) {
2566
- const platform = host === "dell" ? "win32" : "darwin";
2567
- const pinsPath = path.join(managedRoot, "pins", `broker-${platform}.json`);
2568
- const pins = readJson(pinsPath);
2569
- let manifestPath = null; const problems = [];
2570
- try {
2571
- const client = managedRuntimeClient(process.env, platform);
2572
- if (!client) throw new Error("no installed RustRight client was found");
2573
- const exe = resolveBrokerClient(client, { platform }).file;
2574
- const real = platform === "win32" ? exe : fs.realpathSync.native(exe);
2575
- const paths = platform === "win32" ? path.win32 : path.posix;
2576
- manifestPath = paths.join(paths.dirname(real), RUNTIME_MANIFEST_FILE);
2577
- } catch (e) { problems.push(`cannot locate the installed client's runtime manifest: ${e.message}`); }
2578
- const manifest = manifestPath ? readJson(manifestPath) : { error: problems.join("; ") };
2579
- return { pinsPath, pins: pins.value ?? null, manifestPath, manifest: manifest.value ?? null, problem: [pins.error, manifest.error].filter(Boolean).join("; ") || undefined };
2580
- }
2581
-
2582
- /** The fixture's hooks as GC-T20 reads them: `{ dir, hooksPath, files }`. */
2583
- function readHooks(g) {
2584
- let hooksPath = null; let dir = null; const files = {};
2585
- try { hooksPath = g.run(["config", "--get", "core.hooksPath"]).trim() || null; } catch { /* not set */ }
2586
- try { dir = path.resolve(g.canonical, g.run(["rev-parse", "--git-path", "hooks"]).trim()); } catch { /* unreadable: reported by the empty dir */ }
2587
- const read = hooksPath ? path.resolve(g.canonical, hooksPath) : dir;
2588
- if (read) for (const e of (() => { try { return fs.readdirSync(read, { withFileTypes: true }); } catch { return []; } })()) if (e.isFile()) { try { files[e.name] = fs.readFileSync(path.join(read, e.name), "utf8").slice(0, 1 << 20); } catch { files[e.name] = ""; } }
2589
- return { dir: read ?? "<git hooks dir>", hooksPath, files };
2590
- }
2591
-
2592
- /** The snapshot's `.rightkit-source-identity.json`, read at the moment of the run (every later step re-syncs the snapshot). */
2593
- function readSourceIdentity(snapshotPath, commit, g) {
2594
- const file = path.join(snapshotPath, ".rightkit-source-identity.json");
2595
- try { return { file, identity: JSON.parse(fs.readFileSync(file, "utf8")), trees: g.sourceTrees(commit) }; } catch (e) { return { file, error: `cannot read ${file}: ${e.message}` }; }
2596
- }
2597
-
2598
- /** The resident gate's script for the gate under test. */
2599
- function gateServeScriptFor({ gateArg, kind, installed }) {
2600
- if (gateArg && /\.mjs$/.test(gateArg)) return path.join(path.dirname(path.dirname(path.resolve(gateArg))), "gate-serve.mjs");
2601
- if (kind === "installed" && installed) return path.join(path.dirname(path.dirname(installed.entry)), "gate-serve.mjs");
2602
- return path.join(here, "gate-serve.mjs");
2603
- }
2604
-
2605
- /** The crate a one-crate edit changes in workspace `ws`: one with dependencies and no dependents (a leaf), its file and the workspace's dependency map. */
2606
- export function crateEditInfo({ layout, tracked, ws = "rk" }) {
2607
- const texts = {}; const fileOf = {};
2608
- for (const f of layout.manifests) {
2609
- const name = /\[package\][^[]*?\bname\s*=\s*"([^"]+)"/s.exec(layout.texts.get(f))?.[1];
2610
- if (!name || cargoWorkspaceOf(f, layout.wsDirs) !== ws) continue;
2611
- texts[name] = layout.texts.get(f); fileOf[name] = f;
2612
- }
2613
- const deps = crateDeps(texts);
2614
- const dependents = (c) => Object.entries(deps).filter(([, ds]) => ds.includes(c)).map(([n]) => n);
2615
- const leaf = Object.keys(deps).sort().find((c) => deps[c].length > 0 && dependents(c).length === 0);
2616
- if (!leaf) return { why: `workspace ${ws} has no crate with a dependency and no dependents (a leaf to edit)` };
2617
- const dir = path.posix.dirname(fileOf[leaf]);
2618
- const file = [`${dir}/src/lib.rs`, `${dir}/src/main.rs`].find((f) => tracked.includes(f));
2619
- return file ? { workspace: ws, crate: leaf, deps, file } : { why: `crate ${leaf} has no tracked src/lib.rs or src/main.rs` };
2620
- }
2621
-
2622
- /** NN31: the text of every file that could release, upload or promote a gate. */
2623
- export function collectTooling(rootDir, managedRoot) {
2624
- const dirs = [path.join(rootDir, "packages", "release"), path.join(rootDir, "packages", "release", "bin"), path.join(rootDir, "scripts"), path.join(rootDir, ".github", "workflows"), path.join(managedRoot, "agent-bin")];
2625
- const files = {}; const searched = [];
2626
- for (const d of dirs) {
2627
- let names; try { names = fs.readdirSync(d, { withFileTypes: true }); } catch { continue; }
2628
- for (const e of names) {
2629
- if (!e.isFile() || /^gate-acceptance/.test(e.name) || /\.(png|jpg|zip|gz|dmg)$/.test(e.name)) continue;
2630
- const f = path.join(d, e.name); searched.push(f);
2631
- try { const st = fs.statSync(f); if (st.size < 2_000_000) files[f] = fs.readFileSync(f, "utf8"); } catch { /* unreadable: not searched */ }
2632
- }
2633
- }
2634
- return { ...releaseToolingCallsVerify(files), searched };
2635
- }
2636
-
2637
- /** Real-condition controls (--prove): assertions applied to the cold run and the real edits, where the violation really happened. Each returns true when the assertion CAUGHT it. */
2638
- export function coldControls({ cold, warmPrev, warmRows, crate, ws, coldCompileRows }) {
2639
- const caught = {};
2640
- if (cold?.rows) {
2641
- caught.NN01 = !assertNoClassARan(cold.rows).ok;
2642
- if (warmPrev) caught.NN03 = !assertOneFileEdit(warmPrev, cold.rows).ok;
2643
- caught.NN04 = !assertOtherWorkspacesIdleAny(cold.rows, { workspace: ws ?? "rk" }).ok;
2644
- caught.NN21 = !assertLockEditScope(cold.rows, { lockDir: ws ?? "rk" }).ok;
2645
- caught.NN14 = !assertRulesCached(cold.log).ok;
2646
- caught.NN15 = !assertAdviceCached(warmPrev ?? new Map(), cold.rows, {}).ok;
2647
- caught.NN24 = !assertRestartWarm(cold.rows, { killed: true }).ok;
2648
- if (warmRows) caught.NN29 = !assertIdentityIndependent(warmRows, cold.rows).ok;
2649
- }
2650
- if (coldCompileRows) {
2651
- caught.NN02 = !assertNoClassBRan(coldCompileRows, null, { strict: true }).ok;
2652
- if (crate) caught.NN20 = !assertCrateEditScope(coldCompileRows, crate).ok;
2653
- }
2654
- return caught;
2655
- }
2656
-
2657
- async function main(argv) {
2658
- const opt = (name) => { const i = argv.indexOf(name); return i < 0 ? undefined : argv[i + 1]; };
2659
- const known = new Set(["--fixture", "--host", "--steps", "--out", "--plan", "--gate", "--commit", "--leaf-file", "--manifest-file", "--kill-after-ms", "--allow-install", "--budgets", "--help", "--prove", "--verify-release", "--other-receipt", "--contract-file", "--pulse-compile", "--prove-out", "--nn", "--checks-only", "--s11-checks-only", "--kills"]);
2660
- for (const a of argv) if (a.startsWith("--") && !known.has(a)) { console.error(`gate-acceptance: unknown option ${a} (no cache bypass or other gate flag is ever passed)`); return 64; }
2661
- if (argv.includes("--verify-release")) return verifyReleaseCli(argv);
2662
- const host = opt("--host") ?? (process.platform === "win32" ? "dell" : "mac");
2663
- if (!["mac", "dell"].includes(host)) { console.error("gate-acceptance: --host must be mac or dell"); return 64; }
2664
- const wanted = (opt("--steps") ?? STEPS.map((s) => s.id).join(",")).split(",").map((s) => s.trim()).filter(Boolean);
2665
- for (const s of wanted) if (!STEPS.some((x) => x.id === s)) { console.error(`gate-acceptance: unknown step ${s}`); return 64; }
2666
- const allowInstall = argv.includes("--allow-install");
2667
- if (allowInstall) console.error("gate-acceptance: --allow-install: --to dev and --to qualify INSTALL an app on this host. Installs need Adrian's approval; this flag is not that approval.");
2668
- if (argv.includes("--plan")) { console.log(formatPlan(buildPlan({ steps: wanted, allowInstall }))); return 0; }
2669
- const fixture = opt("--fixture");
2670
- if (argv.includes("--prove")) return proveMain({ fixture, host, out: opt("--prove-out"), argv });
2671
- if (!fixture) { console.error("usage: node gate-acceptance.mjs --fixture <dir> [--host mac|dell] [--steps S0,S1,...] [--out <dir>] [--plan] [--gate <path>] [--commit <sha>] [--allow-install]"); return 64; }
2672
- return execute({ fixture, host, wanted, gate: opt("--gate") ?? defaultGate(host), gateArg: opt("--gate"), budgetsFile: opt("--budgets"), out: opt("--out"), commitArg: opt("--commit"), leafFile: opt("--leaf-file"), manifestFile: opt("--manifest-file"), killAfterMs: Number(opt("--kill-after-ms") ?? 3000), allowInstall, otherReceiptFile: opt("--other-receipt"), contractFile: opt("--contract-file"), pulseCompile: argv.includes("--pulse-compile"), forceNN: opt("--nn")?.split(",").filter(Boolean), checksOnly: argv.includes("--checks-only"), s11ChecksOnly: argv.includes("--s11-checks-only"), killsFilter: opt("--kills")?.split(",").filter(Boolean) });
2673
- }
2674
-
2675
- async function execute(options) {
2676
- const scratch = path.join(scratchRootOf(options.host), "gate-acceptance");
2677
- fs.mkdirSync(scratch, { recursive: true });
2678
- const g = gitTools(options.fixture, scratch);
2679
- try { return await executeRun({ ...options, g, scratch }); } finally {
2680
- const problems = g.dropWitnessRefs();
2681
- if (problems.length) console.error(`gate-acceptance: could not delete a refs/witness ref: ${problems.join("; ")}`);
2682
- }
2683
- }
2684
-
2685
- async function executeRun({ fixture, host, wanted, gate, gateArg, budgetsFile, out, commitArg, leafFile, manifestFile, killAfterMs, allowInstall, otherReceiptFile, contractFile, pulseCompile, forceNN, checksOnly, s11ChecksOnly, killsFilter, g, scratch }) {
2686
- const startedAt = new Date().toISOString();
2687
- const platform = host === "dell" ? "win32" : "darwin";
2688
- const managedRoot = managedRootOf(host);
2689
- const outDir = out ?? path.join(scratch, "runs", `${host}-${startedAt.replace(/[:.]/g, "-")}`);
2690
- fs.mkdirSync(outDir, { recursive: true });
2691
- const budgetLoad = loadBudgets(budgetsFile ?? BUDGETS_FILE);
2692
- const commit = commitArg ?? budgetLoad.budgets?.fixture?.commit ?? g.head();
2693
- if (!isCommit(commit)) throw new Error(`commit ${commit} is not a 40 hex sha`);
2694
- const clauseChecks = Object.fromEntries(Object.keys(CLAUSES).map((id) => [id, []]));
2695
- const runs = {};
2696
- const stepChecks = [];
2697
- const stepRecords = STEPS.filter((s) => wanted.includes(s.id)).map((s) => ({ id: s.id, title: s.title, checks: [], notes: [] }));
2698
- const stepOf = (id) => stepRecords.find((s) => s.id === id);
2699
- const ctx = { runs, git: g, managedRoot, platform, allowInstall, broker: brokerIdentity(host, managedRoot), rustrightContracts: path.join(workspaceRootOf(), "rustright", "docs", "contracts"), hooks: readHooks(g), s0: null, s6: null, s9: null };
2700
- const stages = ladderStages({ allowInstall });
2701
-
2702
- const gateFile = path.join(here, "bin", "rightkit-gate.mjs");
2703
- const gateIdentity = { launcher: gate, launcherSha256: (() => { try { return sha256(fs.readFileSync(gate)); } catch { return null; } })(), runnerPackageVersion: readJson(path.join(here, "package.json")).value?.version ?? null, packageGateSha256: (() => { try { return sha256(fs.readFileSync(gateFile)); } catch { return null; } })(), receiptGateSha256: null };
2704
-
2705
- // NN19: the gate under test. `--version` of the launcher is its only output and carries no stamp.
2706
- const launcherProbe = () => {
2707
- const exists = fs.existsSync(gate); let version = null; let text = "";
2708
- if (exists) {
2709
- try { text = fs.readFileSync(gate, "utf8").slice(0, 65536); } catch { /* a binary launcher: no text to read */ }
2710
- try { const spec = launchSpec(gate, ["--version"]); const r = spawnSync(spec.command, spec.args, { encoding: "utf8", timeout: 60_000, windowsHide: true, ...spec.options }); if (r.status === 0) version = String(r.stdout).trim().split(/\r?\n/).pop() || null; } catch { /* reported as no version */ }
2711
- }
2712
- return { exists, version, text };
2713
- };
2714
- const probe = launcherProbe();
2715
- const installedGate = findInstalledGate(managedRoot);
2716
- ctx.gateIdentity = gateIdentityProblems({ gateArg, defaultGate: defaultGate(host), launcherExists: probe.exists, launcherVersion: probe.version, launcherText: probe.text, installed: installedGate, checkoutRoot: workspaceRootOf() });
2717
- ctx.gateIdentityEvidence = `${gate} --version -> ${probe.version ?? "(none)"}; newest sealed install ${installedGate ? installedGate.version : "(none)"}`;
2718
- gateIdentity.kind = ctx.gateIdentity.kind; gateIdentity.version = probe.version; gateIdentity.installedVersion = installedGate?.version ?? null;
2719
- Object.assign(ctx, { wanted, host, budgets: budgetLoad.budgets, budgetProblem: budgetLoad.problem, cores: typeof os.availableParallelism === "function" ? os.availableParallelism() : os.cpus().length, jobsEnv: process.env.RK_GATE_JOBS });
2720
-
2721
- const key = repositoryKey(g.canonical, platform);
2722
- const snapRoot = path.join(managedRoot, "snapshots");
2723
- // The snapshot lock of the fixture repository (snapshot.mjs): `<snapshots>/<repo-key>.lock`, its body `{ pid, identity, commit, token }` (broker host) or `{ pid, host, startedAt, token }`.
2724
- const lockFile = path.join(snapRoot, `${key}.lock`);
2725
- const readLock = () => { try { return JSON.parse(fs.readFileSync(lockFile, "utf8")); } catch { return null; } };
2726
-
2727
- /** A step-only check: it feeds the step status AND the verdict (stepChecks), so it can never be dropped. */
2728
- const check = (step, name, res) => {
2729
- stepOf(step)?.checks.push(res.ok ? "pass" : "fail");
2730
- stepChecks.push({ step, name, ok: res.ok, problems: res.problems });
2731
- if (!res.ok) stepOf(step)?.notes.push(`${name}: ${res.problems[0]}`);
2732
- };
2733
- const exitOk = (r) => ({ ok: r.exit === 0, problems: r.exit === 0 ? [] : [`exit ${r.exit}${r.timedOut ? " (timed out)" : ""}`] });
2734
-
2735
- async function doRun({ label, stage, commit: c = commit, args = [], ladder = false, step, extra = {}, receipt = true, cwd = g.canonical, env = {}, gateCmd = gate, gateArgs = [], profile, workload = "fixture" }) {
2736
- const receiptPath = receipt && RECEIPT_STAGES.has(stage) ? path.join(outDir, `${label.replace(/[^\w.-]/g, "_")}.receipt.json`) : null;
2737
- const full = ["--to", stage, "--commit", c, ...(receiptPath ? ["--receipt-out", receiptPath] : []), ...args];
2738
- // Every gate invocation writes its own spawn ledger (GC-A27 NN07-NN12, NN16). RK_GATE_* never enters a cache key, so this changes no result.
2739
- const ledgerPath = path.join(outDir, `${label.replace(/[^\w.-]/g, "_")}.ledger.jsonl`);
2740
- fs.rmSync(ledgerPath, { force: true });
2741
- const res = await runGate({ gate: gateCmd, cwd, args: [...gateArgs, ...full], env: { ...process.env, ...env, RK_GATE_SPAWN_LEDGER: ledgerPath } });
2742
- return finishRun({ label, stage, commit: c, full, res, receiptPath, ladder, step, extra: { ledgerPath, workload, ...(profile ? { profile } : {}), ...(cwd !== g.canonical ? { noTree: true } : {}), ...extra } });
2743
- }
2744
- function finishRun({ label, stage, commit: c, full, res, receiptPath, ladder = false, step, extra = {} }) {
2745
- const logPath = path.join(outDir, `${label.replace(/[^\w.-]/g, "_")}.log`);
2746
- fs.writeFileSync(logPath, res.log);
2747
- const cov = coveragePaths(res.log); const reports = []; const coverageProblems = [];
2748
- for (const p of cov) { const j = readJson(p); if (j.error) { coverageProblems.push(`cannot read coverage ${j.error}`); continue; } const v = validateCoverage(j.value); if (!v.ok) coverageProblems.push(...v.problems.map((x) => `${p}: ${x}`)); reports.push(j.value); }
2749
- let receipt = null;
2750
- if (receiptPath && fs.existsSync(receiptPath)) { const j = readJson(receiptPath); if (j.value) receipt = j.value; else coverageProblems.push(`cannot read receipt ${j.error}`); }
2751
- if (receipt?.binding?.gate) gateIdentity.receiptGateSha256 = receipt.binding.gate;
2752
- const snapPath = receipt?.stages?.check?.snapshot?.path ?? receipt?.stages?.compile?.snapshot?.path;
2753
- const sourceIdentity = res.exit === 0 && snapPath ? readSourceIdentity(snapPath, c, g) : null;
2754
- let ledger = null;
2755
- if (extra.ledgerPath && fs.existsSync(extra.ledgerPath)) ledger = parseLedger(fs.readFileSync(extra.ledgerPath, "utf8"));
2756
- const run = { label, stage, commit: c, tree: extra.noTree ? null : g.tree(c), args: full, exit: res.exit, signal: res.signal, timedOut: res.timedOut === true, ms: res.ms, startedMs: res.startedMs, ledger, coverageStarts: reports.map((r) => r.startedAt), log: res.log, logPath, receipt, receiptPath, coveragePaths: cov, coverageProblems, rows: reports.length ? mergeCoverage(reports) : null, ladder, stageIndex: LADDER.indexOf(stage), timings: stageTimings(res.log), sourceIdentity, ...extra };
2757
- runs[label] = run; if (step) stepOf(step)?.notes.push(`${label}: exit ${res.exit}, ${(res.ms / 1000).toFixed(1)}s`);
2758
- return run;
2759
- }
2760
-
2761
- // S0 -------------------------------------------------------------------------------------------------------------------------------------
2762
- if (wanted.includes("S0") || wanted.includes("S9")) {
2763
- const brokerNow = runningBrokerProcess() ?? null;
2764
- ctx.s0 = { stash: g.stash(), status: g.status(), worktree: g.worktrees(), broker: brokerNow, lock: readLock(), snapshots: listDirs(snapRoot) };
2765
- }
2766
- if (wanted.includes("S0")) {
2767
- for (const id of ["GC-I22", "GC-I18", "GC-I01"]) { const r = CHECKS[id](ctx); for (const c of Array.isArray(r) ? r : [r]) { clauseChecks[id].push(c); if (id !== "GC-I01") { stepOf("S0").checks.push(c.status === "unchecked" ? "unchecked" : c.status); stepChecks.push({ step: "S0", name: id, ok: c.status === "pass", problems: c.problems }); } } }
2768
- check("S0", "the fixture checkout is clean", ctx.s0.status.trim() === "" ? { ok: true, problems: [] } : { ok: false, problems: [`fixture checkout is not clean: ${ctx.s0.status.trim().split("\n")[0]}`] });
2769
- check("S0", "no snapshot lock stands before the run", ctx.s0.lock ? { ok: false, problems: [`a snapshot lock stands before the run: ${JSON.stringify({ token: ctx.s0.lock.token, pid: ctx.s0.lock.pid })}`] } : { ok: true, problems: [] });
2770
- }
2771
-
2772
- // S1 --------------------------------------------------------------------------------------------------------------------------------------
2773
- if (wanted.includes("S1")) {
2774
- for (const stage of stages) {
2775
- const r = await doRun({ label: `S1:${stage}`, stage, ladder: true, step: "S1" });
2776
- if (stage === "qualify" && r.exit !== 0) {
2777
- r.refusal = qualifyRefusal({ exit: r.exit, text: r.log, receipt: r.receipt });
2778
- check("S1", "--to qualify refuses by naming a release-tier rule", r.refusal);
2779
- } else check("S1", `--to ${stage} exits 0`, exitOk(r));
2780
- if (r.exit !== 0 && stage !== "qualify") { stepOf("S1").notes.push(`ladder stopped at ${stage}: exit ${r.exit}`); break; }
2781
- }
2782
- if (!allowInstall) stepOf("S1").notes.push(`--to ${INSTALL_STAGES.join(" and --to ")} not run: ${NEEDS_INSTALL_APPROVAL}`);
2783
- }
2784
- // S2 --------------------------------------------------------------------------------------------------------------------------------------
2785
- // Two warm pairs on the same commit: NN01/NN02 judge every one of them, NN05 compares the keys of the first pair with the second.
2786
- if (wanted.includes("S2")) for (const [label, stage] of [["S2:check", "check"], ["S2:compile", "compile"], ["S2:check2", "check"], ["S2:compile2", "compile"]].filter(([, s]) => !checksOnly || s === "check")) { const r = await doRun({ label, stage, ladder: true, step: "S2", profile: `warm-${stage}` }); check("S2", `${label}: --to ${stage} exits 0`, exitOk(r)); }
2787
-
2788
- // S3, S4 (ephemeral edits) ----------------------------------------------------------------------------------------------------------------
2789
- const tracked = g.tracked(commit);
2790
- const layout = (wanted.includes("S4") || wanted.includes("S7") || wanted.includes("S11") || wanted.includes("S12") || wanted.includes("S17")) ? g.cargoLayout(commit, tracked) : null;
2791
- const editStep = async (id, name, file, edit, label, extraOf = () => ({})) => {
2792
- if (!wanted.includes(id)) return;
2793
- if (!file) { stepOf(id).notes.push(`unchecked: ${NEEDS_FIXTURE}`); ctx[`${id.toLowerCase()}Why`] = `${id} made no run: the fixture has no tracked ${id === "S3" ? "rk/**/src/lib.rs (or pass --leaf-file)" : "rk/**/Cargo.toml of a non-workspace-root crate (or pass --manifest-file)"}`; return; }
2794
- const c = g.witnessCommit(commit, name, [{ path: file, content: edit(g.show(commit, file)) }]);
2795
- const r = await doRun({ label, stage: "check", commit: c, ladder: true, step: id, extra: extraOf(file), profile: "edited-check" });
2796
- check(id, `--to check on the edited commit exits 0`, exitOk(r));
2797
- };
2798
- // A fresh nonce per run: the same edit bytes as an earlier acceptance run would hit that run's cache entries, so "the edited row ran" could not be judged.
2799
- const editNonce = `${Date.now()}-${process.pid}`;
2800
- ctx.s3File = leafFile ?? tracked.find((f) => /^rk\/.*\/src\/lib\.rs$/.test(f));
2801
- await editStep("S3", "s3-one-file", leafFile ?? tracked.find((f) => /^rk\/.*\/src\/lib\.rs$/.test(f)), (t) => `${t}${t.endsWith("\n") ? "" : "\n"}// gate-acceptance one-file edit ${editNonce}\n`, "S3:check");
2802
- const manifest = manifestFile ?? (layout ? layout.manifests.find((f) => /^rk\/.*\/Cargo\.toml$/.test(f) && !layout.wsDirs.includes(path.posix.dirname(f))) : undefined);
2803
- await editStep("S4", "s4-manifest", manifest, (t) => `${t}${t.endsWith("\n") ? "" : "\n"}\n[package.metadata.gate-acceptance]\nedit = "manifest ${editNonce}"\n`, "S4:check", (file) => {
2804
- const ws = cargoWorkspaceOf(file, layout.wsDirs);
2805
- return { manifestInfo: { workspace: ws, workspaces: [...new Set([...layout.wsDirs, ws])], crates: layout.crates } };
2806
- });
2807
- if (wanted.includes("S5")) stepOf("S5").notes.push("unchecked by design: a lock edit needs the fixture's own resolver; not generated by this runner");
2808
-
2809
- // S6 dirty checkout ------------------------------------------------------------------------------------------------------------------------
2810
- if (wanted.includes("S6")) {
2811
- const s6 = { fresh: false, proof: null, why: null, stash: null, restore: null };
2812
- ctx.s6 = s6;
2813
- const file = tracked.includes("README.md") ? "README.md" : tracked.find((f) => /\.(md|txt)$/.test(f));
2814
- const untrackedName = ".gate-acceptance-untracked";
2815
- const clean = assertCleanCheckout(g.canonical);
2816
- if (!file) { s6.why = "no tracked README.md or text file to make dirty"; stepOf("S6").notes.push(`unchecked: ${s6.why}`); }
2817
- else if (!clean.ok) { s6.why = clean.problems[0]; check("S6", "the fixture is clean before S6 (S6 refuses to start otherwise)", clean); }
2818
- else {
2819
- const stashBefore = g.stash(); let state = null;
2820
- try {
2821
- // A commit whose compile is not recorded yet, so the dirty checkout meets a REAL compile (a recorded compile would be reused, not run).
2822
- const c6 = g.witnessCommit(commit, "s6-dirty", [{ path: "docs/gate-acceptance-s6.txt", content: "gate-acceptance S6: a commit whose compile is not recorded\n" }]);
2823
- state = makeDirtyCheckout(g.canonical, { file, untracked: untrackedName });
2824
- const r = await doRun({ label: "S6:compile", stage: "compile", commit: c6, ladder: true, step: "S6" });
2825
- s6.fresh = r.exit === 0 && compileRanFresh(r.log);
2826
- const snapPath = r.receipt?.stages?.compile?.snapshot?.path;
2827
- if (r.exit === 0 && snapPath) {
2828
- const si = r.sourceIdentity;
2829
- const identityProblems = si?.error ? [si.error] : si ? validateSourceIdentity(si.identity, { commit: c6, trees: si.trees }).problems : ["no source identity was read"];
2830
- s6.proof = dirtyProof({ commitBytes: g.blob(c6, file), checkoutBytes: readOrNull(path.join(g.canonical, file)), snapshotBytes: readOrNull(path.join(snapPath, file)), untrackedInSnapshot: fs.existsSync(path.join(snapPath, untrackedName)), identityProblems, receiptTree: r.receipt?.binding?.tree, expectedTree: g.tree(c6) });
2831
- }
2832
- s6.why = s6.fresh ? null : r.exit !== 0 ? `the compile exited ${r.exit}` : "the compile was already recorded for this commit (`[compile] already passed`): no compile ran on the dirty checkout";
2833
- check("S6", "--to compile on the dirty checkout exits 0", exitOk(r));
2834
- if (s6.proof) check("S6", "the snapshot holds the commit's bytes, not the dirty checkout's", s6.proof);
2835
- if (r.exit === 0 && !s6.fresh) stepOf("S6").checks.push("unchecked");
2836
- } catch (e) { s6.why = e.message; check("S6", "dirty-checkout setup and run", { ok: false, problems: [e.message] }); }
2837
- finally {
2838
- if (state) { s6.restore = restoreDirtyCheckout(g.canonical, state); check("S6", "the checkout and stash list are restored exactly", s6.restore); }
2839
- s6.stash = sameListing("git stash list", stashBefore, g.stash());
2840
- if (!s6.stash.ok) check("S6", "git stash list is unchanged by S6", s6.stash);
2841
- }
2842
- }
2843
- }
2844
-
2845
- // S7 negatives ----------------------------------------------------------------------------------------------------------------------------
2846
- if (wanted.includes("S7")) for (const n of NEGATIVES) {
2847
- const rs = tracked.find((f) => /\.rs$/.test(f)); const toml = (layout?.manifests ?? tracked.filter((f) => /(^|\/)Cargo\.toml$/.test(f))).find((f) => !/\[workspace\]/.test(g.show(commit, f)));
2848
- const recipes = {
2849
- "misformat-rs": rs && [{ path: rs, content: `${g.show(commit, rs)}\nfn gate_acceptance_misformatted ( ) {let x=1;}\n` }],
2850
- "secret-file": [{ path: "docs/gate-acceptance-secret.txt", content: `token = "${["gh", "p_"].join("")}${"A1b2C3d4E5f6G7h8I9j0K1l2M3n4O5p6Q7r8"}"\n` }],
2851
- "profile-dev": toml && [{ path: toml, content: `${g.show(commit, toml)}\n[profile.dev]\nopt-level = 1\n` }],
2852
- "extra-workspace": [{ path: "gate-acceptance-extra/Cargo.toml", content: "[workspace]\nmembers = []\n" }],
2853
- bypass: null, "no-broker": null,
2854
- };
2855
- const recipe = recipes[n.build];
2856
- let c = commit;
2857
- if (n.build === "bypass") {
2858
- const a = await runGate({ gate, cwd: g.canonical, args: ["--to", "check", "--commit", commit, "--no-cache"] });
2859
- const envRun = await runGate({ gate, cwd: g.canonical, args: ["--to", "check", "--commit", commit], env: { ...process.env, RK_GATE_CACHE: "0" } });
2860
- const r1 = finishRun({ label: "N13:flag", stage: "check", commit, full: ["--no-cache"], res: a, receiptPath: null, step: "S7", extra: { negative: "N13", negativeResult: bypassRefused({ exit: a.exit, text: a.log }) } });
2861
- const r2 = finishRun({ label: "N13:env", stage: "check", commit, full: ["RK_GATE_CACHE=0"], res: envRun, receiptPath: null, step: "S7", extra: { negative: "N13", negativeResult: bypassRefused({ exit: envRun.exit, text: envRun.log }) } });
2862
- check("S7", "N13 --no-cache refused", r1.negativeResult); check("S7", "N13 RK_GATE_CACHE=0 refused", r2.negativeResult);
2863
- continue;
2864
- }
2865
- if (recipe === undefined || recipe === null && n.build !== "no-broker") { stepOf("S7").notes.push(`${n.id}: unchecked: no tracked file to edit (${NEEDS_FIXTURE})`); stepOf("S7").checks.push("unchecked"); continue; }
2866
- if (recipe) c = g.witnessCommit(commit, n.id.toLowerCase(), recipe);
2867
- const r = await doRun({ label: `${n.id}`, stage: "compile", commit: c, args: n.args ?? [], ladder: false, step: "S7", extra: { negative: n.id } });
2868
- r.negativeResult = assertNegative({ exit: r.exit, text: r.log, signals: n.signals, laterStages: n.later, receipt: r.receipt, rows: r.rows, expectRows: n.expectRows ?? [] });
2869
- check("S7", `${n.id} ${n.title}`, r.negativeResult);
2870
- }
2871
-
2872
- // S8 kill and recover ---------------------------------------------------------------------------------------------------------------------
2873
- // The snapshot lock is held across Class A by design (reset plan section 3), so a SIGKILL during --to check leaves the lock exactly like one
2874
- // during --to compile: every case asserts that the NEXT run reclaims it on the stale-owner rule (the log's reclaim line) and passes.
2875
- if (wanted.includes("S8")) for (const k of KILLS.filter((x) => !killsFilter || killsFilter.includes(x.id))) {
2876
- const label = `S8:${k.id}`; const logPath = path.join(outDir, `${label.replace(/[^\w.-]/g, "_")}.log`);
2877
- const stage = k.id.startsWith("K02") ? "check" : "compile"; const receiptPath = path.join(outDir, `${label.replace(/[^\w.-]/g, "_")}.receipt.json`);
2878
- const killed = await killDuring({ gate, cwd: g.canonical, args: ["--to", stage, "--commit", commit, "--receipt-out", receiptPath], signal: k.signal, waitFor: readLock, afterMs: killAfterMs });
2879
- fs.writeFileSync(logPath, killed.log);
2880
- const before = readLock();
2881
- const next = await doRun({ label: `${label}:next`, stage, ladder: true, step: "S8" });
2882
- const after = readLock();
2883
- // A fixture compile exits 1 for reasons that are not the lock (its Class B rows fail); a compile that reclaimed the dead owner's lock and reached planning passed the recovery.
2884
- const reached = stage === "compile" && /class A scans \d+ at a time/.test(next.log) && !/snapshot lock [^\n]*(busy|is held|refused)|RK_CHECK_ERROR|BLOCKED: snapshot/.test(next.log);
2885
- const recovery = assertRecovery({ signal: k.signal, before, next: { exit: reached ? 0 : next.exit, text: next.log }, after, exitedBySignal: exitedBySignal({ signal: killed.signal, exit: killed.exit, killSignal: k.signal, platform: process.platform }) || (k.signal === "SIGINT" && !killed.signal && killed.exit !== null && killed.exit !== 0) });
2886
- runs[label] = { label, kill: k.id, killSignal: process.platform === "win32" ? "terminate" : k.signal, stage, recovery, logPath, lockPath: lockFile, exit: killed.exit, signal: killed.signal, log: killed.log, ladder: false, args: [] };
2887
- check("S8", `${k.id} ${k.signal}: dead owner reclaimed by the next run, which passes`, recovery);
2888
- }
2889
-
2890
- // S10 unit list (NN16) ----------------------------------------------------------------------------------------------------------------------
2891
- // `--units-file` names units in the gate's own grammar (crates/rightkit-<x>, packages/<x>). The run shares one Class A and starts no per-unit format check.
2892
- if (wanted.includes("S10")) {
2893
- // The gate accepts --units-file only for the RightKit repository itself ("--units-file names RightKit units ... every other repository is built whole"), so the unit-list run is a read-only --to check of the RightKit checkout.
2894
- const rkDir = path.join(workspaceRootOf(), "rightkit");
2895
- let rkTracked = []; try { rkTracked = git(rkDir, ["ls-tree", "-r", "--name-only", "HEAD"]).split("\n").filter(Boolean); } catch { /* reported below */ }
2896
- const units = unitSelectorsOf(rkTracked, 2);
2897
- if (units.length < 2) {
2898
- ctx.unitsWhy = `the RightKit checkout has ${units.length} unit(s) in the gate's unit grammar (crates/rightkit-<x>/Cargo.toml, packages/<x>/package.json); --units-file needs two`;
2899
- check("S10", "the fixture names two units for --units-file", { ok: false, problems: [ctx.unitsWhy] });
2900
- } else {
2901
- const unitsFile = path.join(outDir, "units.json");
2902
- fs.writeFileSync(unitsFile, `${JSON.stringify({ units })}\n`);
2903
- const r = await doRun({ label: "S10:units", stage: "check", commit: "HEAD", cwd: rkDir, args: ["--units-file", unitsFile], ladder: false, step: "S10", extra: { units }, receipt: false });
2904
- check("S10", "--to check --units-file exits 0", exitOk(r));
2905
- }
2906
- }
2907
-
2908
- // S11 cold run ----------------------------------------------------------------------------------------------------------------------------
2909
- // The gate's scan-result cache (<git common dir>/rightkit-gate-cache, rule verdicts inside) is MOVED ASIDE under scratch (never deleted) and put back afterwards.
2910
- ctx.cellWhy = {}; ctx.proofs = {};
2911
- const crateInfo = layout && (wanted.includes("S11") || wanted.includes("S12") || wanted.includes("S17")) ? crateEditInfo({ layout, tracked, ws: "rk" }) : null;
2912
- if (crateInfo && !crateInfo.why) ctx.crateEdit = { workspace: crateInfo.workspace, crate: crateInfo.crate, deps: crateInfo.deps };
2913
- if (wanted.includes("S11")) {
2914
- const common = path.resolve(g.canonical, g.run(["rev-parse", "--git-common-dir"]).trim());
2915
- const cacheDir = path.join(common, "rightkit-gate-cache");
2916
- const asideRoot = path.join(scratch, `cold-aside-${Date.now()}`);
2917
- fs.mkdirSync(asideRoot, { recursive: true });
2918
- const aside = path.join(asideRoot, "rightkit-gate-cache");
2919
- let moved = false;
2920
- try {
2921
- if (fs.existsSync(cacheDir)) { fs.renameSync(cacheDir, aside); moved = true; }
2922
- check("S11", `the gate cache dir ${cacheDir} was moved aside to ${aside}`, { ok: moved, problems: moved ? [] : [`${cacheDir} does not exist: the run is not proven cold`] });
2923
- // Adrian 2026-11-07 ("Test checks the stop"): a cold run is a miss nothing explains, so the gate stops it for his approval before anything runs;
2924
- // the test proves that stop (every row "no stored result", nothing ran). Cold budgets and cold parallelism are measured from cold runs he approves.
2925
- for (const stage of (s11ChecksOnly ? ["check"] : ["check", "compile"])) {
2926
- const r = await doRun({ label: `S11:${stage}-stop`, stage, ladder: false, step: "S11" });
2927
- check("S11", `cold --to ${stage} stops on RK_CACHE_MISS with every row "no stored result" and nothing run`, assertMissStop(r, missReportOf(r.log), { cause: "new" }));
2928
- ctx.cellWhy[`fixture:cold-${stage}`] = "a cold run stops for Adrian's approval (Adrian 2026-11-07: \"Test checks the stop\"); its budget is measured from a cold run he approves, not from this test";
2929
- }
2930
- } finally {
2931
- let restored = !moved;
2932
- if (moved) { try { if (fs.existsSync(cacheDir)) fs.renameSync(cacheDir, path.join(asideRoot, "created-during-the-cold-run")); fs.renameSync(aside, cacheDir); restored = true; } catch (e) { check("S11", "the gate cache dir is restored", { ok: false, problems: [e.message] }); } }
2933
- check("S11", "the original gate cache dir is back in place", { ok: restored && (!moved || fs.existsSync(cacheDir)), problems: ["the cache dir was not restored"] });
2934
- }
2935
- Object.assign(ctx.proofs, Object.fromEntries(Object.entries(coldControls({ cold: runs["S11:check"], warmPrev: runs["S2:check2"]?.rows ?? runs["S1:check"]?.rows ?? null, warmRows: runs["S2:check2"]?.rows ?? null, crate: ctx.crateEdit, ws: "rk", coldCompileRows: runs["S11:compile"]?.rows ?? null })).map(([k, v]) => [k, { kind: "real-condition control: the cold run (every row really ran)", caught: v }])));
2936
- }
2937
-
2938
- // S12 compile-side edits ------------------------------------------------------------------------------------------------------------------
2939
- if (wanted.includes("S12")) {
2940
- const nonce2 = `${Date.now()}-${process.pid}`;
2941
- if (!crateInfo || crateInfo.why) { ctx.cellWhy["fixture:edited-compile"] = crateInfo?.why ?? "no layout"; check("S12", "a crate to edit exists", { ok: false, problems: [crateInfo?.why ?? "no cargo layout"] }); }
2942
- else {
2943
- const c1 = g.witnessCommit(commit, "s12-crate", [{ path: crateInfo.file, content: `${g.show(commit, crateInfo.file)}\n// gate-acceptance crate edit ${nonce2}\n` }]);
2944
- const r1 = await doRun({ label: "S12:crate", stage: "compile", commit: c1, ladder: true, step: "S12", profile: "edited-compile" });
2945
- check("S12", "the crate-edit compile wrote coverage", { ok: r1.rows !== null, problems: [`exit ${r1.exit}, no readable coverage`] });
2946
- }
2947
- const lockFile = tracked.find((f) => f === "rk/Cargo.lock") ?? tracked.find((f) => /(^|\/)Cargo\.lock$/.test(f) && !/^app\//.test(f));
2948
- if (!lockFile) check("S12", "a lockfile to edit exists", { ok: false, problems: ["the fixture tracks no Cargo.lock outside app/"] });
2949
- else {
2950
- ctx.lockDir = path.posix.dirname(lockFile);
2951
- const c2 = g.witnessCommit(commit, "s12-lock", [{ path: lockFile, content: `${g.show(commit, lockFile)}\n# gate-acceptance lock edit ${nonce2}\n` }]);
2952
- const r2 = await doRun({ label: "S12:lock", stage: "check", commit: c2, ladder: true, step: "S12", profile: "edited-check" });
2953
- check("S12", "the lock-edit check wrote coverage", { ok: r2.rows !== null, problems: [`exit ${r2.exit}, no readable coverage`] });
2954
- }
2955
- const mf = manifestFile ?? (layout ? layout.manifests.find((f) => /^rk\/.*\/Cargo\.toml$/.test(f) && !layout.wsDirs.includes(path.posix.dirname(f))) : undefined);
2956
- if (!mf) check("S12", "a manifest to edit exists", { ok: false, problems: [NEEDS_FIXTURE] });
2957
- else {
2958
- const c3 = g.witnessCommit(commit, "s12-manifest", [{ path: mf, content: `${g.show(commit, mf)}\n[package.metadata.gate-acceptance-compile]\nedit = "manifest ${nonce2}"\n` }]);
2959
- const r3 = await doRun({ label: "S12:manifest", stage: "compile", commit: c3, ladder: true, step: "S12", profile: "edited-compile", extra: { manifestInfo: { workspace: cargoWorkspaceOf(mf, layout.wsDirs), workspaces: [...new Set([...layout.wsDirs, cargoWorkspaceOf(mf, layout.wsDirs)])], crates: layout.crates } } });
2960
- check("S12", "the manifest-edit compile wrote coverage", { ok: r3.rows !== null, problems: [`exit ${r3.exit}, no readable coverage`] });
2961
- }
2962
- }
2963
-
2964
- // S13 gate upgrade ------------------------------------------------------------------------------------------------------------------------
2965
- if (wanted.includes("S13")) {
2966
- const gates = listInstalledGates(managedRoot);
2967
- const older = gates.find((x) => x.version !== gates[0]?.version);
2968
- if (!older) {
2969
- ctx.upgradeWhy = `needs two installed versions: ${gates.length} sealed gate(s) under ${path.join(managedRoot, "trusted-gates")} (${gates.map((x) => x.version).join(", ") || "none"})`;
2970
- check("S13", "two sealed gate versions are installed", { ok: false, problems: [ctx.upgradeWhy] });
2971
- } else {
2972
- for (const [label, gt] of [["S13:prev", older], ["S13:next", gates[0]]]) { const r = await doRun({ label, stage: "check", ladder: true, step: "S13", gateCmd: process.execPath, gateArgs: [gt.entry], extra: { gateVersion: gt.version } }); check("S13", `${label} (${gt.version}) wrote coverage`, { ok: r.rows !== null, problems: [`exit ${r.exit}, no readable coverage`] }); }
2973
- }
2974
- }
2975
-
2976
- // S14 resident restart --------------------------------------------------------------------------------------------------------------------
2977
- if (wanted.includes("S14")) {
2978
- const script = gateServeScriptFor({ gateArg, kind: ctx.gateIdentity.kind, installed: installedGate });
2979
- const st = spawnSync(process.execPath, [script, "status"], { encoding: "utf8", timeout: 30_000 });
2980
- const text = `${st.stdout ?? ""}${st.stderr ?? ""}`;
2981
- const pid = Number(/"?\bpid"?\s*[:=]\s*(\d+)/.exec(text)?.[1]);
2982
- ctx.restart = { killed: false, why: `the resident gate's \`status\` printed no pid (${script}): ${text.trim().slice(0, 160) || "no output"}` };
2983
- if (Number.isInteger(pid) && pid > 1) {
2984
- try {
2985
- process.kill(pid, "SIGTERM");
2986
- const until = Date.now() + 10_000;
2987
- while (Date.now() < until) { try { process.kill(pid, 0); } catch { break; } await new Promise((r) => setTimeout(r, 100)); }
2988
- let alive = true; try { process.kill(pid, 0); } catch { alive = false; }
2989
- ctx.restart = alive ? { killed: false, why: `the resident gate (pid ${pid}) did not exit within 10 s of SIGTERM` } : { killed: true, pid };
2990
- } catch (e) { ctx.restart = { killed: false, why: `cannot stop the resident gate: ${e.message}` }; }
2991
- }
2992
- check("S14", "the resident gate was stopped before the run", { ok: ctx.restart.killed, problems: [ctx.restart.why ?? ""] });
2993
- const r = await doRun({ label: "S14:check", stage: "check", ladder: true, step: "S14" });
2994
- check("S14", "the run after the restart wrote coverage", { ok: r.rows !== null, problems: [`exit ${r.exit}, no readable coverage`] });
2995
- }
2996
-
2997
- // S15 workloads ---------------------------------------------------------------------------------------------------------------------------
2998
- if (wanted.includes("S15")) {
2999
- for (const [wl, dir] of [["rightkit", workspaceRootOf() + "/rightkit"], ["heardright", workspaceRootOf() + "/heardright"]]) {
3000
- if (!fs.existsSync(dir)) { ctx.cellWhy[`${wl}:warm-check`] = `${dir} does not exist`; check("S15", `${wl} checkout exists`, { ok: false, problems: [`${dir} does not exist`] }); continue; }
3001
- // RightKit names its unit on every run (RK_UNIT_NOT_NAMED); the warm check names one small, stable crate so the measured window is the same each time.
3002
- const r = await doRun({ label: `S15:${wl}`, stage: "check", commit: "HEAD", cwd: dir, receipt: false, ladder: false, step: "S15", profile: "warm-check", workload: wl, args: wl === "rightkit" ? ["--unit", "cargo:rightkit-time"] : [] });
3003
- check("S15", `${wl} --to check exits 0`, exitOk(r));
3004
- }
3005
- if (pulseCompile) {
3006
- const dir = workspaceRootOf() + "/pulse";
3007
- const r = await doRun({ label: "S15:pulse", stage: "compile", commit: "HEAD", cwd: dir, receipt: false, ladder: false, step: "S15", profile: "cold-compile", workload: "pulse" });
3008
- check("S15", "pulse --to compile exits 0", exitOk(r));
3009
- } else ctx.cellWhy["pulse:cold-compile"] = "the Pulse compile did not run: it is a real compile of another repository and runs only with --pulse-compile (Adrian's approval to compile)";
3010
- }
3011
-
3012
- // S16 per-run identities ------------------------------------------------------------------------------------------------------------------
3013
- if (wanted.includes("S16")) {
3014
- const tmp = fs.mkdtempSync(path.join(scratch, "ident-tmp-"));
3015
- const r = await doRun({ label: "S16:ident", stage: "check", ladder: true, step: "S16", env: { CODEX_TOOL_CALL_ID: `fake-call-${Date.now()}`, TERM_SESSION_ID: `fake-session-${process.pid}`, TMPDIR: tmp, RK_GATE_RUN_NOTE: `identity-${Date.now()}`,
3016
- // A restarted app or a changed shell (Mac 2026-11-07: PNPM_HOME, CLAUDE_*, BAGGAGE and PATH order moved and every stored pass missed): none of these is an input of a row.
3017
- PNPM_HOME: path.join(tmp, "pnpm-home"), CLAUDE_PID: String(process.pid + 1), CLAUDE_CODE_MESSAGING_SOCKET: path.join(tmp, "claude.sock"), CLAUDE_CODE_ACCOUNT_UUID: `fake-account-${Date.now()}`, BAGGAGE: `fake=${Date.now()}`, LC_CTYPE: "C",
3018
- PATH: String(process.env.PATH ?? "").split(path.delimiter).reverse().join(path.delimiter) } });
3019
- check("S16", "the run with different per-run identities wrote coverage", { ok: r.rows !== null, problems: [`exit ${r.exit}, no readable coverage`] });
3020
- }
3021
-
3022
- // S17 cached failure ----------------------------------------------------------------------------------------------------------------------
3023
- // One witness commit that adds a real compile error to one fixture crate; the same commit runs twice (the failing rows must be hits the second
3024
- // time), then once more with RUSTUP_TOOLCHAIN naming another installed toolchain (a keyed environment input: the failing rows must run again).
3025
- if (wanted.includes("S17")) {
3026
- if (!crateInfo || crateInfo.why) check("S17", "a crate to break exists", { ok: false, problems: [crateInfo?.why ?? "no cargo layout"] });
3027
- else {
3028
- const cf = g.witnessCommit(commit, "s17-fail", [{ path: crateInfo.file, content: `${g.show(commit, crateInfo.file)}\ncompile_error!("gate-acceptance NN41: a deterministic compile failure");\n` }]);
3029
- const f1 = await doRun({ label: "S17:fail1", stage: "compile", commit: cf, ladder: true, step: "S17", profile: "edited-compile" });
3030
- check("S17", "the failing commit's first compile wrote coverage", { ok: f1.rows !== null, problems: [`exit ${f1.exit}, no readable coverage`] });
3031
- const f2 = await doRun({ label: "S17:fail2", stage: "compile", commit: cf, ladder: true, step: "S17", profile: "edited-compile" });
3032
- check("S17", "the failing commit's second compile wrote coverage", { ok: f2.rows !== null, problems: [`exit ${f2.exit}, no readable coverage`] });
3033
- const other = otherToolchain(f1.receipt?.binding?.toolchain?.rustc);
3034
- if (!other) { ctx.identityChange = "no second installed toolchain found under RUSTUP_HOME/toolchains"; check("S17", "a second installed toolchain exists to change the identity", { ok: false, problems: [ctx.identityChange] }); }
3035
- else {
3036
- ctx.identityChange = `RUSTUP_TOOLCHAIN=${other}`;
3037
- // A toolchain change is not the run's own files: the gate stops it for Adrian's approval (Adrian 2026-11-07: "Test checks the stop").
3038
- const f3 = await doRun({ label: "S17:fail3-stop", stage: "compile", commit: cf, ladder: false, step: "S17", env: { RUSTUP_TOOLCHAIN: other } });
3039
- check("S17", "the run with a changed toolchain stops on RK_CACHE_MISS before anything runs", { ok: f3.exit !== 0 && /BLOCKED: RK_CACHE_MISS/.test(String(f3.log ?? "")), problems: [`exit ${f3.exit}; the run did not stop on RK_CACHE_MISS`] });
3040
- }
3041
- }
3042
- }
3043
-
3044
- // S9 ---------------------------------------------------------------------------------------------------------------------------------------
3045
- if (wanted.includes("S9")) {
3046
- const brokerEnd = runningBrokerProcess() ?? null; const lock = readLock();
3047
- const snapshotDirCheck = snapshotDirProblems({ key, before: ctx.s0?.snapshots ?? null, after: listDirs(snapRoot) });
3048
- ctx.s9 = { stash: g.stash(), status: g.status(), worktree: g.worktrees(), snapshotDirCheck, broker: brokerEnd, lockPath: lockFile, lockClean: { ok: lock === null, problems: lock === null ? [] : [`a snapshot lock stands after the run: token ${lock.token}, pid ${lock.pid}`] } };
3049
- check("S9", "git status --short equals S0", sameListing("git status --short", ctx.s0.status, ctx.s9.status));
3050
- check("S9", "git worktree list equals S0", sameListing("git worktree list", ctx.s0.worktree, ctx.s9.worktree));
3051
- check("S9", "git stash list equals S0", sameListing("git stash list", ctx.s0.stash, ctx.s9.stash));
3052
- check("S9", "no snapshot lock stands", ctx.s9.lockClean);
3053
- check("S9", "one snapshot dir for the repository and no new one", snapshotDirCheck);
3054
- check("S9", "the broker process is the one of S0", brokerUnchanged(ctx.s0.broker, brokerEnd));
3055
- const markers = Object.values(runs).flatMap((r) => publicationMarkers(r.log ?? ""));
3056
- check("S9", "no upload or publish marker in any log", { ok: markers.length === 0, problems: markers.map((m) => `upload or publish marker in a log: ${m.slice(0, 120)}`) });
3057
- }
3058
-
3059
- // clause evaluation -----------------------------------------------------------------------------------------------------------------------
3060
- for (const id of Object.keys(CHECKS)) {
3061
- if (["GC-I22", "GC-I18"].includes(id) && wanted.includes("S0")) continue; // already evaluated at S0
3062
- let r; try { r = CHECKS[id](ctx); } catch (e) { r = { status: "fail", evidence: [], problems: [`assertion threw: ${e.message}`] }; }
3063
- clauseChecks[id].push(...(Array.isArray(r) ? r : [r]));
3064
- }
3065
- const contractPath = contractFile ?? CONTRACT_FILE;
3066
- let contractText = ""; try { contractText = fs.readFileSync(contractPath, "utf8"); } catch { /* NN33 reports an empty contract */ }
3067
- const rootDir = path.resolve(here, "..", "..");
3068
- let gateCommit = null; try { gateCommit = git(rootDir, ["rev-parse", "HEAD"]).trim(); } catch { /* NN30 reports it */ }
3069
- let otherReceipt = null; if (otherReceiptFile) { const j = readJson(otherReceiptFile); otherReceipt = j.value ?? { error: j.error }; }
3070
- Object.assign(ctx, { forceNN, warmLabels: checksOnly ? ["S2:check", "S2:check2"] : undefined, extended: true, nnSet: NN_ALL, contractText, contractFile: contractPath, rootDir, runnerSha256: fileSha(RUNNER_FILE), contractSha256: fileSha(contractPath), fixtureCommit: commit, gateCommit, otherReceipt, otherReceiptPath: otherReceiptFile, tooling: collectTooling(rootDir, managedRoot) });
3071
- let nonNegotiables = evaluateNonNegotiables(ctx);
3072
- const notes = [`out ${outDir}`, "wall time is judged only by the NN18 budgets in ci/gate-acceptance-budgets.json"];
3073
- if (ctx.gateIdentity.kind === "named") notes.push(`the gate under test is ${gate}, named by --gate: NOT the installed sealed gate; acceptance of the installed gate is still owed`);
3074
- if (!allowInstall) notes.push(`--to ${INSTALL_STAGES.join(" and --to ")} not run: ${NEEDS_INSTALL_APPROVAL}`);
3075
- const development = ctx.gateIdentity.kind === "named";
3076
- const waivers = (Array.isArray(budgetLoad.budgets?.waivers) ? budgetLoad.budgets.waivers : []).filter(validWaiver);
3077
- const build = (nn) => buildResult({ host, gate: gateIdentity, broker: { runtimeManifest: ctx.broker.manifest ? { path: ctx.broker.manifestPath, brokerDigest: ctx.broker.manifest.brokerDigest, version: ctx.broker.manifest.version } : null, pinsBrokerDigest: ctx.broker.pins?.brokerDigest ?? null, processAtStart: ctx.s0?.broker ?? null }, commit, steps: stepRecords, clauseChecks, startedAt, endedAt: new Date().toISOString(), notes, allowInstall, stepChecks, nonNegotiables: nn, nnIds: NN_ALL_IDS, development, waivers });
3078
- let result = build(nonNegotiables);
3079
- // NN34 and NN35 are judged from the finished result (a first build with their placeholders, then the real verdict).
3080
- const post = (id, problems, evidence) => { const i = nonNegotiables.findIndex((n) => n.id === id); const base = nonNegotiables[i]; nonNegotiables[i] = { ...base, pending: undefined, status: problems.length ? "fail" : "pass", problems, checks: [{ label: "result", ok: problems.length === 0 }], evidence }; };
3081
- const noEvidence = nonNegotiables.filter((n) => n.status === "pass" && !n.pending && (n.checks.length === 0 || n.evidence.length === 0)).map((n) => `${n.id} passed with no evidence`);
3082
- const bareClause = result.clauses.filter((c) => c.status === "pass" && (c.assertions === 0 || c.evidence.length === 0)).map((c) => `clause ${c.id} passed with no evidence`);
3083
- post("NN34", [...noEvidence, ...bareClause, ...(result.partial && /^PASS/.test(result.verdict) ? ["a partial run printed PASS"] : [])], ["the finished result"]);
3084
- const unwaived = result.clauses.filter((c) => c.status === "unchecked" && !waivers.some((w) => w.clause === c.id)).map((c) => c.id);
3085
- const badWaivers = (Array.isArray(budgetLoad.budgets?.waivers) ? budgetLoad.budgets.waivers : []).filter((w) => !validWaiver(w)).map((w) => `waiver ${JSON.stringify(w).slice(0, 80)} is not by Adrian by name with his words`);
3086
- post("NN35", [...(/\d+ of \d+ asserted/.test(result.verdict) && /non-negotiables \d+ of \d+/.test(result.verdict) ? [] : ["the verdict omits `N of M` coverage"]), ...badWaivers], [`verdict: ${result.verdict.slice(0, 120)}`, `${unwaived.length} operative clause(s) unchecked and not waived: a release needs 0`]);
3087
- result = build(nonNegotiables);
3088
- result.releaseEligible = result.ok && !development && unwaived.length === 0;
3089
- result.unwaivedUnchecked = unwaived;
3090
- result.proofs = { ...ctx.proofs, ...(development ? { NN19: { kind: "real-condition control: a checkout gate run is a development run", caught: nonNegotiables.find((n) => n.id === "NN19")?.status === "fail" && !result.ok } } : {}), ...(result.partial ? { NN34: { kind: "real-condition control: a partial run", caught: !result.ok } } : {}) };
3091
- let receiptPath = null;
3092
- if (result.ok && !development) {
3093
- const entry = findInstalledGate(managedRoot);
3094
- const receipt = buildContractReceipt({ host, commit: gateCommit, gate: { kind: "installed", version: entry?.version ?? probe.version, sealedPath: entry?.entry ?? null, sealedSha256: entry?.sealedSha256 ?? null }, contractSha256: ctx.contractSha256, runnerSha256: ctx.runnerSha256, budgetsSha256: fileSha(budgetsFile ?? BUDGETS_FILE), fixtureCommit: commit, result });
3095
- receiptPath = path.join(outDir, `contract-test-receipt.${host}.json`); fs.writeFileSync(receiptPath, `${JSON.stringify(receipt, null, 2)}\n`);
3096
- }
3097
- result.receipt = receiptPath ?? (development ? "none: a development run writes no receipt" : "none: the run did not pass");
3098
- result.timings = Object.fromEntries(Object.entries(runs).map(([k, v]) => [k, { ms: v.ms, stages: v.timings }]));
3099
- fs.writeFileSync(path.join(outDir, "result.json"), `${JSON.stringify(result, null, 2)}\n`);
3100
- const summary = formatSummary(result); fs.writeFileSync(path.join(outDir, "summary.txt"), `${summary}\n`);
3101
- console.log(summary); console.log(`result: ${path.join(outDir, "result.json")}`);
3102
- return result.ok ? 0 : 1;
3103
- }
3104
-
3105
- // ---------------------------------------------------------------------------------------------------------------------------------------------
3106
- // --verify-release and --prove
3107
- // ---------------------------------------------------------------------------------------------------------------------------------------------
3108
- /** `node gate-acceptance.mjs --verify-release <receipt> [--host mac|dell|linux] [--commit <gate commit>]`: exit 0 only when THIS host's receipt passes for the
3109
- * gate commit (NN30, NN31, NN35, per host). Release, upload and trusted-gate install tooling must call this. */
3110
- function verifyReleaseCli(argv) {
3111
- const i = argv.indexOf("--verify-release");
3112
- const files = [argv[i + 1]];
3113
- if (!files[0] || files[0].startsWith("--")) { console.error("usage: node gate-acceptance.mjs --verify-release <receipt> [--host mac|dell|linux] [--commit <sha>]"); return 64; }
3114
- const read = files.map((f) => readJson(f));
3115
- const problems = read.filter((r) => r.error).map((r) => r.error);
3116
- const j = argv.indexOf("--commit");
3117
- if (!problems.length) {
3118
- const budgets = loadBudgets().budgets;
3119
- const waivers = (Array.isArray(budgets?.waivers) ? budgets.waivers : []).filter(validWaiver);
3120
- const h = argv.indexOf("--host");
3121
- problems.push(...verifyReleaseReceipts(read[0].value, null, { commit: j < 0 ? null : argv[j + 1], contractSha256: fileSha(CONTRACT_FILE), runnerSha256: fileSha(RUNNER_FILE), waivers, host: h < 0 ? null : argv[h + 1] }).problems);
3122
- }
3123
- console.log(problems.length ? `verify-release REFUSED (${problems.length} problem(s))` : "verify-release OK: this host's receipt passes for the gate commit");
3124
- for (const p of problems) console.log(` ${p}`);
3125
- return problems.length ? 1 : 0;
3126
- }
3127
-
3128
- const GATE_INJECT_ANCHOR = " installSpawnLedger();\n";
3129
- const spawnLine = (prog, args, opt = "{ cwd: process.cwd() }") => `__cp.spawnSync(${JSON.stringify(prog)}, ${JSON.stringify(args)}, ${opt});`;
3130
- const CARGO = ["car", "go"].join("");
3131
- /**
3132
- * Mutant gates (--prove): a copy of the checkout's packages/release with ONE regression that reintroduces the violation of one non-negotiable. The
3133
- * runner is run with --gate at the mutant; the NN must fail with a problem matching `expect` that the unmutated gate's run does not show.
3134
- */
3135
- export const MUTANTS = Object.freeze([
3136
- { nn: "NN07", steps: "S2", what: "the gate starts the same `git rev-parse --show-toplevel` twice", inject: [spawnLine("git", ["rev-parse", "--show-toplevel"]), spawnLine("git", ["rev-parse", "--show-toplevel"])], expect: /identical child process/ },
3137
- { nn: "NN08", steps: "S2", what: "the gate runs the whole-workspace format check through cargo", inject: [spawnLine(CARGO, ["fmt", "--all", "--check"])], expect: /cargo fmt started/ },
3138
- { nn: "NN09", steps: "S2", what: "the gate asks the broker for a metadata read (`rustright cargo metadata`)", inject: [spawnLine("rustright", [CARGO, "metadata", "--no-deps"])], expect: /went through the broker/ },
3139
- { nn: "NN10", steps: "S2", what: "the gate starts a real metadata read on a warm run", inject: [spawnLine(CARGO, ["metadata", "--no-deps", "--format-version", "1"])], expect: /real cargo metadata/ },
3140
- { nn: "NN13", steps: "S2", what: "a --to check starts a process probe (`ps`)", inject: [spawnLine("ps", ["-p", "1"])], expect: /process probe/ },
3141
- { nn: "NN16", steps: "S10", what: "a unit-list run starts the per-unit format check through cargo", inject: [spawnLine(CARGO, ["fmt", "-p", "rk-core", "--check"])], expect: /cargo fmt started for a unit list/ },
3142
- { nn: "NN22", steps: "S2", what: "a warm run walks the tree with `find`", inject: [spawnLine("find", [".", "-maxdepth", "1"])], expect: /tree walk/ },
3143
- { nn: "NN25", steps: "S2", what: "a warm run starts `pnpm --version`", inject: [spawnLine("pnpm", ["--version"])], expect: /pnpm|version probe/ },
3144
- { nn: "NN26", steps: "S2", what: "the gate starts `node gate-serve.mjs ask` to ask the resident gate", inject: ['__cp.spawnSync(process.execPath, [process.getBuiltinModule("node:url").fileURLToPath(new URL("../gate-serve.mjs", import.meta.url)), "ask"], { timeout: 2000 });'], expect: /ask the resident gate/ },
3145
- { nn: "NN39", steps: "S11", extra: ["--s11-checks-only"], what: "the Class A lane count is forced to 1 in the code path (not an environment override)", patch: { find: "const jobs = Math.max(1, Number(o.env.RK_GATE_JOBS ?? defaultJobs) || defaultJobs);", replace: "const jobs = 1;" }, expect: /idle lane while work waited/ },
3146
- { nn: "NN17", steps: "S2", what: "the Class A lane count is forced to 1 in the code path", patch: { find: "const jobs = Math.max(1, Number(o.env.RK_GATE_JOBS ?? defaultJobs) || defaultJobs);", replace: "const jobs = 1;" }, expect: /lane\(s\) on a/ },
3147
- { nn: "NN05", steps: "S2", what: "a per-run value (a high-resolution clock reading) enters every Class A row key", patch: { find: "${rowShape(scan)}`; scanKeys.set(scan.id, full);", replace: "${rowShape(scan)}:${process.hrtime.bigint()}`; scanKeys.set(scan.id, full);" }, expect: /key differs between identical runs/ },
3148
- { nn: "NN06", steps: "S2", what: "every Class A row is environment-bound, so non-executing keys carry the environment digest", patch: { find: "function classAEnvironmentBound(scan) { return scan.executes === true || scan.tool === \"pnpm\"; }", replace: "function classAEnvironmentBound(scan) { return true; }" }, expect: /carries the environment digest/ },
3149
- { nn: "NN12", steps: "S2", what: "a warm run starts `pnpm install`", inject: [spawnLine("pnpm", ["install", "--offline"])], expect: /pnpm install started/ },
3150
- { nn: "NN29", steps: "S2,S16", what: "the tool-call id of the environment enters every Class A row key", patch: { find: "${rowShape(scan)}`; scanKeys.set(scan.id, full);", replace: "${rowShape(scan)}:${process.env.CODEX_TOOL_CALL_ID ?? \"\"}`; scanKeys.set(scan.id, full);" }, expect: /key differs between identical runs|reuse miss/ },
3151
- { nn: "NN32", steps: "S8", extra: ["--kills", "K02,K02-int"], what: "a dead owner's snapshot lock is never judged reclaimable (the stale-owner rule always refuses)", patch: { file: "snapshot.mjs", find: "if (probe !== \"ESRCH\") throw busy(`snapshot lock holder pid ${holder.pid} cannot be proven gone (${probe})`);", replace: "if (true) throw busy(`snapshot lock holder pid ${holder.pid} is gone (MUTANT: a dead owner is never judged reclaimable)`);" }, expect: /reclaimed from|exited/ },
3152
- { nn: "NN40", steps: "S2", compile: true, control: true, what: "the gate starts per-crate `cargo rustdoc` again (two crates of the fixture workspace, two starts)", inject: [spawnLine("rustright", ["cargo", "rustdoc", "-p", "rk-core", "--lib", "--help"]), spawnLine("rustright", ["cargo", "rustdoc", "-p", "rk-util", "--lib", "--help"])], expect: /a cargo rustdoc started/ },
3153
- { nn: "NN41", steps: "S17", control: true, what: "the gate refuses to reuse a cached failure (every failing cache entry is dropped before the run)", inject: ['try { const __fs = process.getBuiltinModule("node:fs"); const __p = process.getBuiltinModule("node:path"); const __d = __p.join(process.cwd(), ".git", "rightkit-gate-cache"); for (const __f of __fs.readdirSync(__d)) { const __x = __p.join(__d, __f); try { if (JSON.parse(__fs.readFileSync(__x, "utf8"))?.row?.status === "fail") __fs.rmSync(__x); } catch { /* not an entry */ } } } catch { /* no cache dir */ }'], expect: /^S17: (clippy|check|check-features|doc):\S+: failed, .*ran again \(a failure must be a cache hit\)/ },
3154
- { nn: "NN42", steps: "S2", compile: true, control: true, what: "the stage sends one broker command per cross target (two single-target commands of one configuration)", inject: [spawnLine("rustright", ["cargo", "check", "--help", "--target", "aarch64-unknown-linux-gnu"]), spawnLine("rustright", ["cargo", "check", "--help", "--target", "x86_64-pc-windows-msvc"])], expect: /one per target/ },
3155
- { nn: "NN28", steps: "S2", what: "the gate polls for changes with `git status`", inject: [spawnLine("git", ["status", "--short"])], expect: /polling/ },
3156
- ]);
3157
-
3158
- function copyRelease(dest) {
3159
- const src = here;
3160
- fs.mkdirSync(dest, { recursive: true });
3161
- const a = spawnSync("rsync", ["-a", "--exclude", "node_modules", `${src}/`, `${dest}/`], { encoding: "utf8" });
3162
- if (a.status !== 0) throw new Error(`rsync of ${src}: ${a.stderr}`);
3163
- const nm = path.join(src, "node_modules");
3164
- if (fs.existsSync(nm) && !fs.existsSync(path.join(dest, "node_modules"))) { const c = spawnSync("cp", ["-cRL", nm, path.join(dest, "node_modules")], { encoding: "utf8" }); if (c.status !== 0) throw new Error(`cp node_modules: ${c.stderr}`); }
3165
- }
3166
- /** Writes the mutant copy and returns `{ dir, entry, diff }`; the checkout is never touched. */
3167
- export function makeMutant(root, m) {
3168
- const dir = path.join(root, m.nn ?? "baseline"); const rel = path.join(dir, "release");
3169
- copyRelease(rel);
3170
- const entry = path.join(rel, "bin", "rightkit-gate.mjs");
3171
- let diff = "(unmutated copy)";
3172
- if (m.patch) {
3173
- const target = path.join(rel, m.patch.file ?? path.join("bin", "rightkit-gate.mjs"));
3174
- const text = fs.readFileSync(target, "utf8");
3175
- if (text.split(m.patch.find).length !== 2) throw new Error(`mutant ${m.nn}: the patch anchor is not unique in ${path.basename(target)}`);
3176
- fs.writeFileSync(target, text.replace(m.patch.find, () => m.patch.replace));
3177
- diff = `--- ${m.patch.find}\n+++ ${m.patch.replace}`;
3178
- }
3179
- if (m.inject) {
3180
- const text = fs.readFileSync(entry, "utf8");
3181
- if (text.split(GATE_INJECT_ANCHOR).length !== 2) throw new Error(`mutant ${m.nn}: the anchor \`installSpawnLedger();\` is not unique in the gate`);
3182
- const add = ` const __cp = process.getBuiltinModule("node:child_process"); // MUTANT ${m.nn}: ${m.what}\n${m.inject.map((l) => ` ${l}`).join("\n")}\n`;
3183
- fs.writeFileSync(entry, text.replace(GATE_INJECT_ANCHOR, () => GATE_INJECT_ANCHOR + add));
3184
- diff = `+++ bin/rightkit-gate.mjs (after installSpawnLedger();)\n${add.replace(/^/gm, "+")}`;
3185
- }
3186
- fs.chmodSync(entry, 0o755);
3187
- fs.writeFileSync(path.join(dir, "mutation.diff"), `${diff}\n`);
3188
- return { dir, entry, diff };
3189
- }
3190
-
3191
- /** An installed rustup toolchain other than the one the gate recorded (`rustc 1.96.1 (...)`): the newest remaining one, or null. */
3192
- function otherToolchain(recordedRustc) {
3193
- const home = process.env.RUSTUP_HOME || path.join(os.homedir(), ".rustup");
3194
- let names = []; try { names = fs.readdirSync(path.join(home, "toolchains")); } catch { return null; }
3195
- const rec = /rustc (\d+\.\d+\.\d+)/.exec(String(recordedRustc ?? ""))?.[1] ?? null;
3196
- const ver = (n) => (/^(\d+)\.(\d+)\.(\d+)/.exec(n) ?? []).slice(1).map(Number);
3197
- const cmp = (a, b) => { for (let i = 0; i < 3; i += 1) if ((a[i] ?? 0) !== (b[i] ?? 0)) return (b[i] ?? 0) - (a[i] ?? 0); return 0; };
3198
- const cands = names.filter((n) => /^\d+\.\d+\.\d+/.test(n) && (!rec || !n.startsWith(`${rec}-`))).sort((a, b) => cmp(ver(a), ver(b)));
3199
- return cands[0] ?? null;
3200
- }
3201
- const spawnRunner = (file, args) => runRunner(args, { cwd: path.dirname(file), file });
3202
- function runRunner(args, { cwd, file = RUNNER_FILE }) {
3203
- return new Promise((resolve) => {
3204
- let out = "";
3205
- const child = spawn(process.execPath, [file, ...args], { cwd, stdio: ["ignore", "pipe", "pipe"] });
3206
- child.stdout.on("data", (d) => { out += d; }); child.stderr.on("data", (d) => { out += d; });
3207
- child.on("close", (code) => resolve({ code, out }));
3208
- child.on("error", (e) => resolve({ code: null, out: `${out}\n${e.message}` }));
3209
- });
3210
- }
3211
-
3212
- /** `--prove`: every NN is shown to be able to fail, by a real-condition control, a mutant gate, or a real altered contract. Fails unless every NN is caught. */
3213
- async function proveMain({ fixture, host, out }) {
3214
- if (!fixture) { console.error("usage: node gate-acceptance.mjs --prove --fixture <dir> [--host mac|dell] [--prove-out <dir>]"); return 64; }
3215
- const scratch = path.join(scratchRootOf(host), "gate-acceptance");
3216
- const root = out ?? path.join(scratch, "prove", new Date().toISOString().replace(/[:.]/g, "-"));
3217
- const mutRoot = path.join(scratch, "mutants");
3218
- fs.mkdirSync(root, { recursive: true }); fs.mkdirSync(mutRoot, { recursive: true });
3219
- const proofs = {}; const log = []; const controls = [];
3220
- const note = (id, how, caught, detail) => { (proofs[id] ??= []).push({ how, caught, detail }); log.push(`${id} ${caught ? "CAUGHT" : "not caught"} by ${how}${detail ? `: ${detail}` : ""}`); };
3221
- const resultOf = (dir) => { try { return JSON.parse(fs.readFileSync(path.join(dir, "result.json"), "utf8")); } catch { return null; } };
3222
- const common = ["--fixture", fixture, "--host", host];
3223
-
3224
- // NN33: the real runner against a real altered contract (a row removed; a row added).
3225
- const real = fs.readFileSync(CONTRACT_FILE, "utf8");
3226
- const variants = { "a row removed": real.split("\n").filter((l) => !/^\| NN20 \|/.test(l)).join("\n"), "a row added": real.replace(/^(\| NN38 \|.*)$/m, "$1\n| NN99 | An invented property | never |") };
3227
- for (const [name, text] of Object.entries(variants)) {
3228
- const f = path.join(root, `contract-${name.replace(/\s/g, "-")}.md`); fs.writeFileSync(f, text);
3229
- const o = path.join(root, `nn33-${name.replace(/\s/g, "-")}`);
3230
- await runRunner([...common, "--steps", "S0", "--nn", "NN33", "--contract-file", f, "--out", o], { cwd: here });
3231
- const r = resultOf(o)?.nonNegotiables?.find((n) => n.id === "NN33");
3232
- note("NN33", `the runner against a contract with ${name}`, r?.status === "fail" && /NN(20|99)/.test(r.problems.join()), r?.problems?.[0]);
3233
- }
3234
- // Controls: the real runner against an unmutated copy of the checkout gate, with the cache moved aside (S11) after warm runs (S2).
3235
- const base = makeMutant(mutRoot, { nn: "baseline" });
3236
- const co = path.join(root, "controls");
3237
- const cr = await runRunner([...common, "--steps", "S2,S11", "--checks-only", "--nn", "NN19,NN11,NN27,NN38", "--gate", base.entry, "--out", co], { cwd: here });
3238
- const cres = resultOf(co);
3239
- if (!cres) log.push(`controls run produced no result (exit ${cr.code})`);
3240
- for (const [id, p] of Object.entries(cres?.proofs ?? {})) note(id, p.kind, p.caught === true, p.caught ? "the assertion flagged the real violation" : "the assertion did NOT flag it");
3241
- // Mutants.
3242
- for (const m of MUTANTS) {
3243
- let mm; try { mm = makeMutant(mutRoot, m); } catch (e) { note(m.nn, `mutant gate (${m.what})`, false, e.message); continue; }
3244
- const o = path.join(root, `mutant-${m.nn}`);
3245
- const args = [...common, "--steps", m.steps, "--nn", m.nn, "--gate", mm.entry, "--out", o]; if (m.steps === "S2" && !m.compile) args.push("--checks-only");
3246
- if (m.extra) args.push(...m.extra);
3247
- await runRunner(args, { cwd: here });
3248
- const r = resultOf(o)?.nonNegotiables?.find((n) => n.id === m.nn);
3249
- const hit = r?.status === "fail" && r.problems.some((p) => m.expect.test(p));
3250
- if (m.control) {
3251
- // The unmutated control: the same run against the unmutated copy of the gate must NOT show the mutant's failure.
3252
- const oc = path.join(root, `control-${m.nn}`);
3253
- await runRunner([...args.slice(0, args.indexOf("--gate")), "--gate", base.entry, "--out", oc, ...(m.extra ?? [])], { cwd: here });
3254
- const cr2 = resultOf(oc)?.nonNegotiables?.find((n) => n.id === m.nn);
3255
- const shown = cr2?.problems?.find((x) => m.expect.test(x));
3256
- controls.push({ id: m.nn, ok: Boolean(cr2) && !shown, detail: !cr2 ? "no result" : shown ? `the unmutated gate SHOWS the failure: ${shown.slice(0, 200)}` : `the unmutated gate does not show it (verdict ${cr2.status}${cr2.status === "fail" ? `: ${cr2.problems[0]?.slice(0, 160)}` : ""})`, out: oc });
3257
- log.push(`${m.nn} control (unmutated gate, same run): ${controls[controls.length - 1].ok ? "does not show the failure" : "SHOWS the failure"}: ${controls[controls.length - 1].detail}`);
3258
- }
3259
- note(m.nn, `mutant gate: ${m.what} (${mm.dir}/mutation.diff)`, hit, hit ? r.problems.find((p) => m.expect.test(p)).slice(0, 140) : r ? `verdict ${r.status}; ${r.problems.slice(0, 2).join(" | ").slice(0, 200)}` : "no result");
3260
- }
3261
- // Real gate evidence from the controls run (the unmutated checkout gate): a check that fails there on a violation or on missing evidence is shown to be able to fail.
3262
- for (const id of ["NN11", "NN27", "NN38"]) {
3263
- const r = cres?.nonNegotiables?.find((n) => n.id === id);
3264
- const missing = id === "NN11";
3265
- note(id, missing ? "the real gate lacks the evidence the check needs (missing evidence fails; weaker than a violation)" : "a real violation by the unmutated checkout gate", r?.status === "fail", r?.problems?.[0]?.slice(0, 200));
3266
- }
3267
- // NN18: the real runner against a real budgets file with a 1 ms budget.
3268
- {
3269
- const tight = JSON.parse(fs.readFileSync(BUDGETS_FILE, "utf8"));
3270
- tight.hosts.mac.warmCheckMs = 1; tight.hosts.mac.stages.dependencyStep = 1;
3271
- const f = path.join(root, "budgets-1ms.json"); fs.writeFileSync(f, `${JSON.stringify(tight, null, 2)}\n`);
3272
- const o = path.join(root, "nn18-tight");
3273
- await runRunner([...common, "--steps", "S2", "--checks-only", "--nn", "NN18", "--budgets", f, "--gate", base.entry, "--out", o], { cwd: here });
3274
- const r = resultOf(o)?.nonNegotiables?.find((n) => n.id === "NN18");
3275
- const hit = r?.status === "fail" && r.problems.find((p) => /took \d+ ms, budget 1 ms/.test(p));
3276
- note("NN18", "the real runner against a budgets file with a 1 ms budget", Boolean(hit), hit ? hit.slice(0, 200) : r?.problems?.[0]);
3277
- }
3278
- // NN23: needs two distinct sealed versions; without them the check's own failure message is the proof.
3279
- {
3280
- const gates = listInstalledGates(managedRootOf(host));
3281
- const distinct = new Set(gates.map((x) => x.version)).size;
3282
- const o = path.join(root, "nn23");
3283
- await runRunner([...common, "--steps", "S13", "--nn", "NN23", "--out", o], { cwd: here });
3284
- const r = resultOf(o)?.nonNegotiables?.find((n) => n.id === "NN23");
3285
- if (distinct < 2) note("NN23", `the failure message itself: ${distinct} distinct sealed version(s) installed, so a real upgrade cannot be run (weaker than a violation)`, r?.status === "fail" && /needs two installed versions/.test(r.problems.join()), r?.problems?.[0]?.slice(0, 200));
3286
- else note("NN23", "a real upgrade between the two newest sealed gates", r?.status === "fail", r?.problems?.[0]?.slice(0, 200) ?? `the check passed on a real upgrade: it can fail only when keys change, so it is unproven`);
3287
- }
3288
- // NN30, NN31, NN35: real --verify-release refusals on receipts built from the real run's result.
3289
- if (cres) {
3290
- const inst = listInstalledGates(managedRootOf(host))[0] ?? null;
3291
- const budgets = loadBudgets().budgets;
3292
- const mk = (h, over = {}) => ({ ...buildContractReceipt({ host: h, commit: "a".repeat(40), gate: { kind: "installed", version: inst?.version ?? "0", sealedPath: inst?.entry ?? null, sealedSha256: inst?.sealedSha256 ?? "b".repeat(64) }, contractSha256: fileSha(CONTRACT_FILE), runnerSha256: fileSha(RUNNER_FILE), budgetsSha256: fileSha(BUDGETS_FILE), fixtureCommit: budgets?.fixture?.commit ?? "c".repeat(40), result: cres }), ...over });
3293
- const w = (name, r) => { const f = path.join(root, `receipt-${name}.json`); fs.writeFileSync(f, `${JSON.stringify(r, null, 2)}\n`); return f; };
3294
- const verify = async (a) => runRunner(["--verify-release", a, "--host", "mac"], { cwd: here });
3295
- const real1 = await verify(w("dell-for-mac", mk("dell")));
3296
- note("NN30", "--verify-release on the mac with a receipt from another host", real1.code === 1 && /this host is mac/.test(real1.out), real1.out.split("\n").slice(0, 2).join(" | ").slice(0, 200));
3297
- const real2 = await verify(w("mac-fail", mk("mac")));
3298
- note("NN30", "--verify-release with this host's failing receipt (the real run's NOT PASSED result)", real2.code === 1 && /not a PASS/.test(real2.out), (real2.out.split("\n")[1] ?? "").trim().slice(0, 200));
3299
- note("NN31", "--verify-release refuses a release whose receipts are not passes (what release, upload and promotion must call)", real2.code === 1 && /REFUSED/.test(real2.out), (real2.out.split("\n")[0] ?? "").slice(0, 200));
3300
- const allPass = Object.fromEntries(NN_ALL_IDS.map((id) => [id, "pass"]));
3301
- const unw = await verify(w("mac-unchecked", mk("mac", { ok: true, verdict: "PASS (forced for the proof)", nn: allPass })));
3302
- note("NN35", "--verify-release with passing receipts that leave operative clauses unchecked and unwaived", unw.code === 1 && /unchecked and not waived by Adrian/.test(unw.out), (unw.out.split("\n")[1] ?? "").trim().slice(0, 200));
3303
- }
3304
- // NN36 and NN37: real commits in a scratch clone of rightkit.
3305
- {
3306
- const lp = path.join(scratch, "lockproof"); const clone = path.join(lp, `clone-${Date.now()}`);
3307
- fs.mkdirSync(lp, { recursive: true });
3308
- const sh = (args, cwd = clone) => { const r = spawnSync("git", args, { cwd, encoding: "utf8" }); if (r.status !== 0) throw new Error(`git ${args.join(" ")}: ${r.stderr || r.stdout}`); return r.stdout; };
3309
- try {
3310
- sh(["clone", "--quiet", path.resolve(here, "..", ".."), clone], lp);
3311
- const cp = spawnSync("cp", ["-cRL", path.join(here, "node_modules"), path.join(clone, "packages", "release", "node_modules")], { encoding: "utf8" });
3312
- if (cp.status !== 0) throw new Error(`cp node_modules: ${cp.stderr}`);
3313
- const cRunner = path.join(clone, "packages", "release", "gate-acceptance.mjs");
3314
- const cBudgets = path.join(clone, "ci", "gate-acceptance-budgets.json");
3315
- const judge = async (name) => { const o = path.join(root, `lock-${name}`); await spawnRunner(cRunner, [...common, "--steps", "S0", "--nn", "NN36,NN37", "--out", o]); return resultOf(o)?.nonNegotiables ?? []; };
3316
- sh(["commit", "--allow-empty", "-q", "-m", "lock the contract test\n\nGate-Acceptance-Locked: lockproof baseline"]);
3317
- const base36 = (await judge("1-locked")).find((n) => n.id === "NN36");
3318
- log.push(`NN36 control (not a proof): locked baseline, nothing changed since: ${base36?.status} ${base36?.problems?.[0]?.slice(0, 160) ?? ""}`);
3319
- fs.appendFileSync(cRunner, "\n// lockproof: a change to the runner with no approval line\n");
3320
- sh(["commit", "-q", "-am", "runner: an unapproved change"]);
3321
- const u36 = (await judge("2-unapproved")).find((n) => n.id === "NN36");
3322
- note("NN36", "scratch clone: a real commit changes the runner without the approval line", u36?.status === "fail" && /without `Adrian-approved:/.test(u36.problems.join()), u36?.problems?.find((p) => /Adrian-approved/.test(p))?.slice(0, 200) ?? u36?.problems?.[0]);
3323
- const b = JSON.parse(fs.readFileSync(cBudgets, "utf8")); b.hosts.mac.warmCheckMs = (b.hosts.mac.warmCheckMs ?? 1000) * 2;
3324
- fs.writeFileSync(cBudgets, `${JSON.stringify(b, null, 2)}\n`);
3325
- sh(["commit", "-q", "-am", "budgets: raise warmCheckMs\n\nAdrian-approved: lockproof (the approval line is present; the rise is the violation)"]);
3326
- const r36 = (await judge("3-raised")).find((n) => n.id === "NN36");
3327
- note("NN36", "scratch clone: a commit that cites approval but raises a budget", r36?.status === "fail" && /raised a budget/.test(r36.problems.join()), r36?.problems?.find((p) => /raised a budget/.test(p))?.slice(0, 200) ?? r36?.problems?.[0]);
3328
- const n37a = (await judge("4-noreview")).find((n) => n.id === "NN37");
3329
- note("NN37", "scratch clone: no independent review recorded", n37a?.status === "fail" && /no independent review/.test(n37a.problems.join()), n37a?.problems?.[0]?.slice(0, 200));
3330
- const rs = fileSha(cRunner); const cs = fileSha(path.join(clone, "docs", "GATE-CONTRACT.md"));
3331
- const b2 = JSON.parse(fs.readFileSync(cBudgets, "utf8")); b2.reviews = [{ runnerSha256: rs, contractSha256: cs, reviewer: "same", author: "same", adrianWords: "lockproof", verdict: "pass" }];
3332
- fs.writeFileSync(cBudgets, `${JSON.stringify(b2, null, 2)}\n`); sh(["commit", "-q", "-am", "budgets: self review\n\nAdrian-approved: lockproof"]);
3333
- const n37b = (await judge("5-selfreview")).find((n) => n.id === "NN37");
3334
- note("NN37", "scratch clone: the reviewer is the author", n37b?.status === "fail" && /no independent review/.test(n37b.problems.join()), n37b?.problems?.[0]?.slice(0, 200));
3335
- b2.reviews = [{ runnerSha256: rs, contractSha256: cs, reviewer: "other", author: "same", adrianWords: "lockproof", verdict: "pass" }];
3336
- fs.writeFileSync(cBudgets, `${JSON.stringify(b2, null, 2)}\n`); sh(["commit", "-q", "-am", "budgets: independent review\n\nAdrian-approved: lockproof"]);
3337
- const n37c = (await judge("6-review")).find((n) => n.id === "NN37");
3338
- log.push(`NN37 control: with an independent review recorded the check is ${n37c?.status}`);
3339
- } catch (e) { log.push(`lockproof failed: ${e.message}`); note("NN36", "scratch clone", false, e.message.slice(0, 200)); note("NN37", "scratch clone", false, e.message.slice(0, 200)); }
3340
- }
3341
- // NN32: the unmutated gate recovers real kills (information), after the mutant above left a stale lock: reclaimed by this run.
3342
- {
3343
- const o = path.join(root, "kills-real");
3344
- await runRunner([...common, "--steps", "S8", "--nn", "NN32", "--gate", base.entry, "--kills", "K01,K01-int,K02,K02-int", "--out", o], { cwd: here });
3345
- const r = resultOf(o)?.nonNegotiables?.find((n) => n.id === "NN32");
3346
- log.push(`NN32 real kills on the unmutated gate (SIGKILL compile, SIGINT compile, SIGKILL check, SIGINT check): ${r?.status} ${r?.problems?.[0]?.slice(0, 200) ?? ""}`);
3347
- }
3348
- const rows = NN_ALL_IDS.map((id) => ({ id, proven: (proofs[id] ?? []).some((p) => p.caught), proofs: proofs[id] ?? [] }));
3349
- const unproven = rows.filter((r) => !r.proven).map((r) => r.id);
3350
- const badControls = controls.filter((c) => !c.ok);
3351
- const summary = { schema: "rightkit.gate-acceptance-prove/1", host, ok: unproven.length === 0 && badControls.length === 0, unproven, controls, rows, log };
3352
- fs.writeFileSync(path.join(root, "prove-result.json"), `${JSON.stringify(summary, null, 2)}\n`);
3353
- console.log(`prove ${summary.ok ? "OK" : "FAILED"}: ${rows.length - unproven.length} of ${rows.length} non-negotiables have a proof that they can fail; ${controls.length - badControls.length} of ${controls.length} unmutated controls are clean`);
3354
- for (const c of controls) console.log(` control ${c.id} ${c.ok ? "clean" : "SHOWS THE FAILURE"}: ${c.detail}`);
3355
- for (const r of rows) console.log(` ${r.id} ${r.proven ? "proven" : "UNPROVEN"}${r.proofs.filter((p) => p.caught).map((p) => ` [${p.how.slice(0, 70)}]`).join("")}`);
3356
- console.log(`result: ${path.join(root, "prove-result.json")}`);
3357
- return summary.ok ? 0 : 1;
3358
- }
3359
-
3360
- if (process.argv[1] && fs.realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)) {
3361
- main(process.argv.slice(2)).then((code) => process.exit(code), (e) => { console.error(`gate-acceptance: ${e.stack ?? e}`); process.exit(2); });
3362
- }