@rightkit/release 0.6.63 → 0.6.65

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.
@@ -0,0 +1,394 @@
1
+ // The twelve-line acceptance test decided by cases (GATE-CONTRACT GC-A27; rightkit#1514).
2
+ // Adrian, 2026-11-24: "Unlock the judge files; adopt the 12-line evidence table and its 4 named limits, the 10.1 reading of D20, and the 7 fixture cases + 1 real build
3
+ // as the acceptance run."
4
+ //
5
+ // A line is decided from records made outside the gate: the launcher's own record of each run (exit, times, listings of folders before and after), the operating
6
+ // system's record of the programs the gate started, and the broker's signed receipts. Where the gate's own statement is read (its output, its Class A decision record),
7
+ // that is said in the reason. Each line has one function. Every function answers pass or fail, never "not measured": evidence that is missing is a fail with its reason.
8
+ //
9
+ // The four named limits (they are the only ones):
10
+ // 1. NN03: rows that run inside the gate take milliseconds and are not judged for lanes.
11
+ // 2. NN04: the order of the forecast and the first lookup inside the gate is not witnessed; that the forecast does not come from the cache is.
12
+ // 3. NN06: a check inside the gate that was silently repeated without writing anything shows only as lost time against the case's limit.
13
+ // 4. NN10: the test program file at the instant it was started is not witnessed.
14
+ //
15
+ // Pure: `facts` in, verdicts out. Gathering the facts of a run folder is `factsOfRun` at the end; running the cases is acceptance-run.mjs.
16
+ import crypto from "node:crypto";
17
+ import fs from "node:fs";
18
+ import path from "node:path";
19
+ import { cargoVerb, dirKey, isProbe, programName, readRunDir, runFacts, valuesOf } from "./acceptance-lines.mjs";
20
+
21
+ export const PASS = "pass"; export const FAIL = "fail";
22
+ const verdict = (fails, passWhy) => (fails.length ? { verdict: FAIL, why: fails.slice(0, 6).join("; ") + (fails.length > 6 ? `; and ${fails.length - 6} more` : "") } : { verdict: PASS, why: passWhy });
23
+ const plain = (p) => dirKey(String(p ?? "").replace(/^\\\\\?\\/, ""));
24
+ // The lines the evidence table holds every case to, whatever the case lists: every receipt names the commit (NN01), a run that reached the broker did so after
25
+ // Class A (NN02), nothing repeats (NN08), the run is inside its limit (NN11) and ends clean (NN12).
26
+ const ALWAYS = Object.freeze(["NN01", "NN02", "NN08", "NN11", "NN12"]);
27
+ export const LINE_IDS = Object.freeze(["NN01", "NN02", "NN03", "NN04", "NN05", "NN06", "NN07", "NN08", "NN09", "NN10", "NN11", "NN12"]);
28
+
29
+ // ---- reading a run's facts ------------------------------------------------------------------------------------------------------------------------------
30
+ /** A Class A row's own program: a tool the gate starts for a row, not a version probe. Rows that run inside the gate start none (limit 1). */
31
+ export function isClassAProgram(start) {
32
+ const name = programName(start.program); const args = (start.args ?? []).map(String);
33
+ if (isProbe(args)) return false;
34
+ if (["rustfmt", "actionlint", "shellcheck", "cargo-deny", "cargo-audit", "oxlint", "tsc"].includes(name)) return true;
35
+ const absolute = (a) => /^([a-z]:[\\/]|[\\/])/i.test(a);
36
+ if (name === "node" && args.includes("--check")) return args.filter((a) => !a.startsWith("-")).every((a) => !absolute(a)); // a tracked file, named relative to the snapshot; never a build output
37
+ if (name === "node") return args.some((a) => /[\\/]pnpm\.(c|m)?js$/i.test(a) && args.some((b) => ["audit", "exec"].includes(b)));
38
+ if (name === "pnpm") return args.some((a) => ["audit", "exec"].includes(a));
39
+ if (name === "cargo") return ["deny", "audit"].includes(cargoVerb(args));
40
+ return false;
41
+ }
42
+ /** The workspace, verb, feature flags and targets of a broker job: what NN09 holds against the cases file's exact list. A command that names no --target builds for the host. */
43
+ export function groupOf(job, hostTarget) {
44
+ const args = job.args ?? []; const snap = plain(job.gate?.snapshot); const cwd = plain(job.cwd);
45
+ const workspace = snap && cwd.startsWith(snap) ? cwd.slice(snap.length).replace(/^\//, "") || "." : cwd;
46
+ const named = valuesOf(args, "--target"); const feats = valuesOf(args, "--features", "-F");
47
+ const features = args.includes("--all-features") ? "--all-features" : feats.length ? `--features ${feats.join(",")}` : "";
48
+ return { workspace, verb: job.sub, targets: (named.length ? [...new Set(named)] : [hostTarget]).sort(), features, crates: valuesOf(args, "--package", "-p") };
49
+ }
50
+ const groupKey = (g) => `${g.workspace} | ${g.verb} | ${g.features || "default features"} | ${g.targets.join(" + ")}`;
51
+ /** The cases file's exact command list as keys; `prerequisite` commands (a sidecar build other commands need first) are returned apart. */
52
+ export function expectedCommands(bc) {
53
+ const out = new Map();
54
+ for (const c of bc.commands ?? []) { const targets = (c.targets === "each target" ? bc.targets : c.targets === "host" ? [bc.hostTarget] : [c.targets]).slice().sort(); out.set(groupKey({ workspace: c.workspace, verb: c.verb, features: c.features, targets }), c); }
55
+ return out;
56
+ }
57
+ const jobName = (j) => `broker job ${j.jobId ?? "(no id)"}`;
58
+ const firstSubmission = (run) => Math.min(...run.jobs.map((j) => j.submitted).filter(Number.isFinite));
59
+
60
+ // ---- the checks one run can be given, whatever the case ---------------------------------------------------------------------------------------------------
61
+ /** NN01, every run: each broker receipt verifies, names the selected commit and its tree, and says the snapshot was unchanged. */
62
+ export function receiptsNameTheCommit(run) {
63
+ const fails = [];
64
+ for (const j of run.jobs) {
65
+ if (!j.verified) { fails.push(`${jobName(j)}: its receipt does not verify (${(j.problems ?? []).join("; ") || "no reason given"})`); continue; }
66
+ if (j.gate?.commit !== run.commit) fails.push(`${jobName(j)} is signed for commit ${String(j.gate?.commit).slice(0, 12)}, not the selected ${String(run.commit).slice(0, 12)}`);
67
+ if (!run.tree || j.gate?.tree !== run.tree) fails.push(`${jobName(j)} is signed for tree ${String(j.gate?.tree).slice(0, 12)}, not the selected commit's ${String(run.tree).slice(0, 12)}`);
68
+ if (j.gate?.snapshotUnchanged !== true) fails.push(`${jobName(j)}: the broker did not sign that the snapshot was unchanged`);
69
+ }
70
+ return fails;
71
+ }
72
+ /** NN02, a run that reached the broker: the Class A verdict file the receipts name is older than the first signed submission, and every Class A program ended before it. */
73
+ export function classABeforeBroker(run) {
74
+ const fails = []; if (!run.jobs.length) return ["no broker receipt exists, so the order of Class A and the first submission cannot be shown"];
75
+ const first = firstSubmission(run); if (!Number.isFinite(first)) return ["no broker receipt signs a usable start time and waits, so the first submission time is not known"];
76
+ // Each job against the verdict file its own receipt names: that file, as the launcher lists it after the run, must be older than the job's signed submission.
77
+ // A file written later was not this run's verdict when the job was sent (an older run's file of the same name was what the broker read).
78
+ for (const j of run.jobs) {
79
+ if (!j.gate?.classA) continue; const name = path.basename(plain(j.gate.classA)); const at = run.verdicts?.[name.toLowerCase()];
80
+ if (!Number.isFinite(at)) fails.push(`the Class A verdict file ${name} that ${jobName(j)} names is not in the launcher's listing`);
81
+ else if (!Number.isFinite(j.submitted) || at >= j.submitted) fails.push(`${jobName(j)} (cargo ${j.sub}) was submitted at ${new Date(j.submitted).toISOString()}, before the Class A verdict file it names was written (${name}, ${new Date(at).toISOString()})`);
82
+ }
83
+ if (run.jobs.some((j) => !j.gate?.classA)) fails.push("a broker receipt names no Class A verdict file");
84
+ const late = run.starts.filter(isClassAProgram).filter((s) => s.end === null || s.end > first);
85
+ if (late.length) fails.push(`${late.length} Class A program(s) had not ended at the first submission (first: ${programName(late[0].program)})`);
86
+ if (run.processGaps.length) fails.push(`the process record is incomplete (${run.processGaps[0]})`);
87
+ return fails;
88
+ }
89
+ /**
90
+ * The programs the gate itself started: children of the gate process, and the program a shell wrapper of the gate's ran (the wrapper is not counted beside it).
91
+ * What a tool starts for itself (cargo's rustc probes, pnpm's node) is that tool's work, not a call the gate made. Approved for the earlier judge on 21 November
92
+ * ("cargo's own rustc target-info probe [is] not [a program] the run chose to start"); the same rule, stated once for every tool.
93
+ */
94
+ export function startedByGate(run) {
95
+ if (!Number.isInteger(run.rootPid)) return run.starts;
96
+ const isShell = (s) => /(^|[\\/])cmd\.exe$/i.test(String(s.exe));
97
+ const mine = run.starts.filter((s) => s.ppid === run.rootPid);
98
+ const shells = mine.filter(isShell);
99
+ const wrapped = run.starts.filter((s) => shells.some((w) => w.pid === s.ppid && s.at >= w.at && (w.end === null || s.at <= w.end)));
100
+ const withChild = new Set(wrapped.map((s) => s.ppid));
101
+ return [...mine.filter((s) => !(isShell(s) && withChild.has(s.pid))), ...wrapped];
102
+ }
103
+ /** NN08, every run: no program starts twice with the same arguments and no broker command is sent twice, beyond the pinned legitimate repeats. */
104
+ export function repeats(run, legitimate = []) {
105
+ const fails = []; if (run.processGaps.length) fails.push(`the process record is incomplete (${run.processGaps[0]})`);
106
+ const groups = new Map();
107
+ for (const s of startedByGate(run)) { if (!s.argsKnown || s.ambiguous) continue; const k = JSON.stringify([programName(s.program), s.args]); groups.set(k, (groups.get(k) ?? 0) + 1); }
108
+ for (const [k, n] of groups) {
109
+ if (n < 2) continue; const [name, args] = JSON.parse(k);
110
+ const line = args.join(" ");
111
+ const allowed = legitimate.find((l) => (l.programPattern ? new RegExp(l.programPattern).test(name) : l.program === name) && (l.argsPattern ? new RegExp(l.argsPattern).test(line) : JSON.stringify(l.args) === JSON.stringify(args)))?.count ?? 1;
112
+ if (n > allowed) fails.push(`${name} ${args.join(" ").slice(0, 80)} started ${n} times (${allowed} allowed)`);
113
+ }
114
+ const sent = new Map();
115
+ for (const j of run.jobs) { const k = `${plain(j.cwd)}\u0000${(j.argv ?? []).join("\u0000")}`; sent.set(k, (sent.get(k) ?? 0) + 1); }
116
+ for (const [k, n] of sent) if (n > 1) fails.push(`the broker command ${k.split("\u0000").slice(1, 6).join(" ")} was sent ${n} times`);
117
+ return fails;
118
+ }
119
+ /** NN10, a run that built tests: the broker compiled them without running them and signed each program's hash; the gate started exactly those programs, after they were built. */
120
+ export function testsBuiltByBrokerRunByGate(run) {
121
+ const fails = []; const tests = run.jobs.filter((j) => j.sub === "test");
122
+ if (!tests.length) return ["no broker receipt is a test build, so that the broker compiled the tests is not shown"];
123
+ const signed = new Map();
124
+ for (const j of tests) {
125
+ if (!j.verified) { fails.push(`${jobName(j)}: its receipt does not verify`); continue; }
126
+ if (!(j.effectiveArgv ?? j.argv ?? []).includes("--no-run")) fails.push(`${jobName(j)} is a cargo test the broker ran without --no-run: the broker ran the tests`);
127
+ if (!Array.isArray(j.testExecutables)) { fails.push(`${jobName(j)} signs no list of test programs`); continue; }
128
+ for (const exe of j.testExecutables) {
129
+ const file = typeof exe === "string" ? exe : exe?.path; const digest = typeof exe === "object" ? exe?.sha256 : null;
130
+ if (typeof file !== "string" || typeof digest !== "string") { fails.push(`${jobName(j)} lists a test program with no path or no hash`); continue; }
131
+ signed.set(plain(file), { file, digest, ended: j.ended });
132
+ }
133
+ }
134
+ if (!signed.size && !fails.length) fails.push("the test builds sign no test program at all, so there was nothing for the gate to run");
135
+ for (const [key, s] of signed) {
136
+ const ran = run.starts.filter((p) => plain(p.exe) === key);
137
+ if (ran.length !== 1) fails.push(`${path.basename(s.file)} was started ${ran.length} times by the gate, not once`);
138
+ if (ran.some((p) => Number.isFinite(s.ended) && p.at < s.ended)) fails.push(`${path.basename(s.file)} was started before the broker finished building it`);
139
+ const now = run.imageNow?.[key];
140
+ if (now !== s.digest) fails.push(`${path.basename(s.file)} does not have the signed hash after the run (${String(now).slice(0, 12)} against ${s.digest.slice(0, 12)})`);
141
+ }
142
+ // A test program the gate started that no receipt signs was not built by the broker (cargo puts test programs under deps/).
143
+ const unsigned = run.starts.filter((p) => /[\\/]deps[\\/][^\\/]+-[0-9a-f]{16}(\.exe)?$/i.test(String(p.exe)) && !signed.has(plain(p.exe)));
144
+ if (unsigned.length) fails.push(`the gate started ${unsigned.length} test program(s) no receipt signs (first: ${path.basename(unsigned[0].exe)})`);
145
+ if (run.processGaps.length) fails.push(`the process record is incomplete (${run.processGaps[0]})`);
146
+ return fails;
147
+ }
148
+ /** NN11, every run: it finished inside the limit pinned for it. */
149
+ export function insideLimit(run, limitMs, label) {
150
+ if (!Number.isFinite(limitMs)) return [`no time limit is pinned for ${label} (the first clean measured time x 1.25 goes into the cases file)`];
151
+ if (!Number.isFinite(run.durationMs)) return [`${label}: the launcher did not record when the run ended`];
152
+ return run.durationMs <= limitMs ? [] : [`${label} took ${Math.round(run.durationMs / 1000)} s; its limit is ${Math.round(limitMs / 1000)} s`];
153
+ }
154
+ /** NN12, a run that was not killed: no lock of its snapshot and no program of it is left. */
155
+ export function endsClean(run, label) {
156
+ const fails = [];
157
+ if (run.rootAlive) fails.push(`${label}: the gate process was still alive when the launcher looked`);
158
+ if (run.locksKnown !== true) fails.push(`${label}: the launcher could not read the snapshot folder for locks`);
159
+ if (!run.snapshot) fails.push(`${label}: which snapshot the run used is not shown, so its lock cannot be looked for`);
160
+ else if ((run.locksAfter ?? []).some((l) => plain(l) === `${plain(run.snapshot)}.lock`)) fails.push(`${label}: the snapshot lock was left behind`);
161
+ const open = run.starts.filter((s) => s.end === null);
162
+ if (open.length) fails.push(`${label}: ${open.length} program(s) of the run have no recorded exit (first: ${programName(open[0].program)})`);
163
+ if (run.processGaps.length) fails.push(`${label}: the process record is incomplete (${run.processGaps[0]})`);
164
+ return fails;
165
+ }
166
+ const exited = (run) => Number.isInteger(run.exit) && !run.killed;
167
+ const failedRun = (run, label) => (exited(run) && run.exit !== 0 ? [] : [`${label} did not end with a failing exit (exit ${run.exit}${run.killed ? ", killed" : ""})`]);
168
+ const passedRun = (run, label) => (exited(run) && run.exit === 0 ? [] : [`${label} did not pass (exit ${run.exit}${run.killed ? ", killed" : ""})`]);
169
+ const noReceipt = (run, label) => (run.jobs.length ? [`${label} left ${run.jobs.length} broker receipt(s)`] : []);
170
+ const noClassAProgram = (run, label) => { const a = run.starts.filter(isClassAProgram); return [...(a.length ? [`${label} started ${a.length} Class A program(s) (first: ${programName(a[0].program)})`] : []), ...(run.processGaps.length ? [`${label}: the process record is incomplete (${run.processGaps[0]})`] : [])]; };
171
+ const noCacheWrite = (run, label) => (!Array.isArray(run.cacheWritten) ? [`${label}: the launcher could not list the scan store`] : run.cacheWritten.length ? [`${label} wrote ${run.cacheWritten.length} scan store file(s)`] : []);
172
+
173
+ // ---- the twelve lines, each by the cases that decide it ---------------------------------------------------------------------------------------------------
174
+ const LINES = {
175
+ // Only the selected commit is built.
176
+ NN01(c, cases) {
177
+ const fails = c.runs.flatMap(receiptsNameTheCommit);
178
+ if (c.id === 1) fails.push(...passedRun(c.runs[0], "the run with an error planted in the checkout that the commit does not hold"));
179
+ if (c.id === 5) c.runs.forEach((r, i) => fails.push(...failedRun(r, `run ${i + 1} of the commit that holds the error, with a clean checkout`)));
180
+ return verdict(fails, c.id === 1 ? "an error in the checkout that is not in the commit did not fail the run, and every receipt names the selected commit and tree with the snapshot unchanged" : c.id === 5 ? "an error in the commit failed the run with a clean checkout" : `${c.runs.reduce((n, r) => n + r.jobs.length, 0)} receipt(s), each naming the selected commit and tree with the snapshot unchanged`);
181
+ },
182
+ // Class A finishes before anything goes to the broker. If it fails, nothing goes.
183
+ NN02(c) {
184
+ if (c.id === 5) return verdict(c.runs.flatMap((r, i) => [...failedRun(r, `run ${i + 1}`), ...noReceipt(r, `run ${i + 1}`)]), "a failing Class A check ended the run with a failing exit and no broker receipt, twice");
185
+ return verdict(c.runs.filter((r) => r.jobs.length).flatMap(classABeforeBroker), "the Class A verdict file is older than the first signed submission, and every Class A program had ended by then");
186
+ },
187
+ // Class A starts ready, independent work whenever an eligible lane is free.
188
+ NN03(c, cases) {
189
+ const run = c.runs[0]; const fails = []; const lanes = run.lanes;
190
+ if (!Number.isInteger(lanes) || lanes < 1) return verdict(["the launcher recorded no lane count"], "");
191
+ if (run.processGaps.length) fails.push(`the process record is incomplete (${run.processGaps[0]})`);
192
+ const progs = run.starts.filter(isClassAProgram).sort((a, b) => a.at - b.at);
193
+ const rows = Object.values(cases.classA?.programRows ?? {}).flat().length;
194
+ if (progs.length < 2) return verdict([...fails, `${progs.length} Class A program(s) started in a run from nothing; the cases file lists ${rows} rows that start one`], "");
195
+ const runningAt = (t) => progs.filter((p) => p.at <= t && (p.end === null || p.end > t)).length;
196
+ const peak = Math.max(...progs.map((p) => runningAt(p.at)));
197
+ const need = Math.min(lanes, progs.length);
198
+ // A later program is a row that was still waiting at the earlier start. If a lane was free after that earlier start and the waiting row started more than
199
+ // `slackMs` later, a row waited beside an idle lane.
200
+ const slackMs = cases.nn03SlackMs ?? 2000; let idle = 0; let worst = null;
201
+ for (let i = 1; i < progs.length; i += 1) {
202
+ const gap = progs[i].at - progs[i - 1].at; const free = runningAt(progs[i - 1].at) < lanes;
203
+ if (free && gap > slackMs) { idle += 1; if (!worst || gap > worst.gap) worst = { gap, name: programName(progs[i].program) }; }
204
+ }
205
+ if (idle) fails.push(`${idle} Class A program(s) started more than ${slackMs} ms after the one before while a lane was free (longest: ${programName(worst.name)} after ${worst.gap} ms)`);
206
+ if (peak < Math.min(need, 2)) fails.push(`at most ${peak} Class A program(s) ran at a time on ${lanes} lanes`);
207
+ return verdict(fails, `${progs.length} Class A programs on ${lanes} lanes, up to ${peak} at a time; none waited more than ${slackMs} ms beside a free lane`);
208
+ },
209
+ // Before the first cache lookup, the gate records the expected rows and which will be reused and which will run.
210
+ NN04(c, cases) {
211
+ const run = c.runs[0]; const row = c.expect?.outputNames?.[0] ?? "license"; const fails = [...failedRun(run, "the run with one cache file deleted")];
212
+ const recs = run.decisions ?? [];
213
+ if (!recs.length) fails.push("the gate wrote no Class A decision record for the run, so no forecast is on record");
214
+ const f = recs.flatMap((d) => (Array.isArray(d.forecast) ? d.forecast : [])).filter((x) => x.id === row);
215
+ if (recs.length && !f.length) fails.push(`the decision record's forecast does not hold the row ${row}`);
216
+ else if (f.some((x) => x.expected !== "hit")) fails.push(`with its cache file deleted, the forecast expected ${row} to ${f.find((x) => x.expected !== "hit").expected}: the forecast came from what is in the cache`);
217
+ return verdict(fails, `the gate's own decision record expected ${row} to be reused although its cache file was gone, and the run stopped: the forecast does not come from the cache`);
218
+ },
219
+ // If lookup disagrees with that record, the gate stops before sending work and names the row and the cause. Otherwise the work that ran matches it.
220
+ NN05(c, cases) {
221
+ const run = c.runs[0];
222
+ if (c.id === 4) {
223
+ const row = c.expect?.outputNames?.[0] ?? "license";
224
+ const fails = [...failedRun(run, "the run with one cache file deleted"), ...noReceipt(run, "it"), ...noClassAProgram(run, "it")];
225
+ const lines = String(run.log ?? "").split(/\r?\n/).filter((l) => l.includes(row));
226
+ if (!lines.length) fails.push(`the gate's output does not name the row ${row}`);
227
+ else if (!lines.some((l) => /expected|forecast|missing|absent|lost|no longer|not in the store|deleted/i.test(l))) fails.push(`the gate's output names ${row} with no cause`);
228
+ return verdict(fails, `the run stopped with a failing exit, no receipt and no Class A program, and its output names ${row} and the cause`);
229
+ }
230
+ return verdict(workMatches(c, cases), "the broker commands and the scan store files written are exactly the rows the cases file expects");
231
+ },
232
+ // A row whose inputs did not change is never run again, including one that failed before.
233
+ NN06(c) {
234
+ if (c.id === 2) { const r = c.runs[0]; return verdict([...passedRun(r, "the second run of the same commit"), ...noReceipt(r, "it"), ...noClassAProgram(r, "it"), ...noCacheWrite(r, "it")], "the same commit again: no broker receipt, no Class A program, no scan store file written"); }
235
+ const r = c.runs[1]; if (!r) return verdict(["the failing commit was not run a second time"], "");
236
+ return verdict([...failedRun(r, "the second run of the failing commit"), ...noReceipt(r, "it"), ...noClassAProgram(r, "it"), ...noCacheWrite(r, "it")], "the failing commit again: it still fails, with no Class A program started and nothing written");
237
+ },
238
+ // A row whose inputs did change is always run again, and does only the work the change needs.
239
+ NN07(c, cases) {
240
+ const run = c.runs[0]; const fails = [...passedRun(run, "the run of the one-file edit"), ...workMatches(c, cases)];
241
+ const want = new Set(c.expect?.classAPrograms ?? []); const got = new Set(run.starts.filter(isClassAProgram).map((s) => programName(s.program)));
242
+ for (const p of want) if (!got.has(p)) fails.push(`the Class A program ${p} did not run although its input changed`);
243
+ for (const p of got) if (!want.has(p)) fails.push(`the Class A program ${p} ran although no input of it changed`);
244
+ return verdict(fails, `the edit ran exactly ${[...want].join(", ")} in Class A and sent the broker only ${(c.expect?.brokerCrates ?? []).join(", ")}`);
245
+ },
246
+ // No repeat calls: nothing is started twice in one run.
247
+ NN08(c, cases) { return verdict(c.runs.flatMap((r) => repeats(r, cases.legitimateRepeats ?? [])), `${c.runs.reduce((n, r) => n + r.starts.length, 0)} program start(s) and ${c.runs.reduce((n, r) => n + r.jobs.length, 0)} broker command(s), none repeated beyond the pinned list`); },
248
+ // Compatible compiles are combined per workspace and stage. Every split has a reason the check can verify. Independent groups run at the same time when there is capacity.
249
+ NN09(c, cases) {
250
+ const run = c.runs[0]; const fails = [...passedRun(run, "the run from nothing")]; const bc = cases.brokerCommands ?? {};
251
+ const expected = expectedCommands(bc); const seen = new Map(); const prerequisite = new Set();
252
+ for (const j of run.jobs) {
253
+ if (!j.verified) { fails.push(`${jobName(j)}: its receipt does not verify`); continue; }
254
+ const k = groupKey(groupOf(j, bc.hostTarget)); seen.set(k, (seen.get(k) ?? 0) + 1);
255
+ if (expected.get(k)?.why === "the sidecar binary") prerequisite.add(j);
256
+ }
257
+ for (const k of expected.keys()) if (!seen.has(k)) fails.push(`no broker command for ${k}`);
258
+ for (const [k, n] of seen) {
259
+ if (!expected.has(k)) fails.push(`a broker command for ${k}, which the cases file does not list`);
260
+ else if (n > 1) fails.push(`${n} broker commands for ${k}: the cases file lists it once`);
261
+ }
262
+ // Early submission. The broker runs one build of a repository at a time and owns the order; what the gate owes is not to hold a command back. A command
263
+ // submitted when every earlier command of the run had already ended was held until then: the gate waited for a job before sending the next. The sidecar
264
+ // build is the one command others need first, so it is left out on both sides.
265
+ const rest = run.jobs.filter((j) => !prerequisite.has(j));
266
+ const byTime = rest.filter((j) => Number.isFinite(j.submitted) && Number.isFinite(j.ended)).sort((a, b) => a.submitted - b.submitted);
267
+ if (byTime.length !== rest.length) fails.push("a broker receipt signs no usable submission or end time");
268
+ let lastEnd = -Infinity; const held = [];
269
+ byTime.forEach((j, i) => { if (i > 0 && j.submitted >= lastEnd) held.push(j); lastEnd = Math.max(lastEnd, j.ended); });
270
+ if (held.length) fails.push(`${held.length} of ${byTime.length - 1} later command(s) were submitted only after every earlier one had ended (first: cargo ${held[0].sub} in ${groupOf(held[0], bc.hostTarget).workspace} at ${new Date(held[0].submitted).toISOString()}): the gate waited for a job before sending the next`);
271
+ return verdict(fails, `${run.jobs.length} broker commands, exactly the cases file's list, each sent once, none held back until earlier jobs had ended`);
272
+ },
273
+ // Tests are compiled by the broker and run by the gate.
274
+ NN10(c) {
275
+ if (c.id === 6) { const run = c.runs[0]; const name = c.expect?.outputNames?.[0]; return verdict([...failedRun(run, "the commit with a failing unit test"), ...(name && !String(run.log ?? "").includes(name) ? [`the gate's output does not name the failing test ${name}`] : [])], "a failing unit test failed the run, and the output names it"); }
276
+ return verdict([...passedRun(c.runs[0], "the run"), ...testsBuiltByBrokerRunByGate(c.runs[0])], "the broker compiled the tests without running them and signed each program; the gate started exactly those programs, once each, and each still has its signed hash");
277
+ },
278
+ // The run finishes inside its time limit.
279
+ NN11(c, cases) { const limit = cases.limitsMs?.[c.limitKey ?? `case${c.id}`]; return verdict(c.runs.filter((r) => !r.killed).flatMap((r, i) => insideLimit(r, limit, `${c.label ?? `case ${c.id}`} run ${i + 1}`)), `every run finished inside ${Math.round((limit ?? 0) / 1000)} s`); },
280
+ // The run ends clean, even if killed: the next ordinary run starts safely by itself.
281
+ NN12(c) {
282
+ const fails = [];
283
+ if (c.id === 7) {
284
+ const [first, second] = c.runs;
285
+ if (!first?.killed) fails.push("the first run was not killed midway");
286
+ if (!second) fails.push("no ordinary run followed the killed one");
287
+ else fails.push(...passedRun(second, "the ordinary run after the kill"), ...endsClean(second, "the ordinary run after the kill"));
288
+ return verdict(fails, "the run was killed midway; the next ordinary run started by itself, passed, and left no lock and no program");
289
+ }
290
+ c.runs.forEach((r, i) => { if (!r.killed) fails.push(...endsClean(r, `run ${i + 1}`)); });
291
+ return verdict(fails, "no lock and no program was left behind");
292
+ },
293
+ };
294
+ /** Case 3: the broker commands and the scan store files written equal what the cases file expects for the edit. */
295
+ function workMatches(c, cases) {
296
+ const run = c.runs[0]; const e = c.expect ?? {}; const fails = []; const bc = cases.brokerCommands ?? {};
297
+ const wantCrates = new Set(e.brokerCrates ?? []); const want = e.brokerCommands ?? {};
298
+ const counts = { clippy: 0, test: 0, doc: 0, check: 0 };
299
+ for (const j of run.jobs) {
300
+ if (!j.verified) { fails.push(`${jobName(j)}: its receipt does not verify`); continue; }
301
+ const g = groupOf(j, bc.hostTarget);
302
+ if (g.workspace !== want.workspace) fails.push(`${jobName(j)} ran in workspace ${g.workspace}; only ${want.workspace} holds the edit`);
303
+ for (const crate of g.crates) if (!wantCrates.has(crate)) fails.push(`${jobName(j)} names ${crate}, which the edit does not need`);
304
+ if (!g.crates.length) fails.push(`${jobName(j)} names no crate, so it built the whole workspace`);
305
+ if (g.verb in counts) counts[g.verb] += 1; else fails.push(`${jobName(j)} is a cargo ${g.verb}, which the cases file does not expect`);
306
+ }
307
+ delete counts.check;
308
+ for (const v of Object.keys(counts)) if (counts[v] !== (want[v] ?? 0)) fails.push(`${counts[v]} ${v} command(s) for the edit; the cases file expects ${want[v] ?? 0}`);
309
+ if (!Array.isArray(run.cacheWritten)) fails.push("the launcher could not list the scan store");
310
+ else {
311
+ const expected = new Set([...(e.classARows ?? []), ...(e.compileRows ?? [])]);
312
+ const index = new Map([...expected].map((id) => [crypto.createHash("sha256").update(`rk-row-index/1\0${id}`).digest("hex"), id]));
313
+ const written = new Set();
314
+ // A combined command stores one result under its own id (clippy:batch:<hash>) and the planner stores which targets it combined (feature-partition-targets);
315
+ // each names its crates, and stands for the expected rows of that verb and those crates. A rule verdict of the new commit names no row and is expected.
316
+ const verbOf = (id) => (/^test:rust/.test(id) ? "test" : String(id).split(":")[0]); const crateOf = (id) => String(id).split(":").pop().split("@")[0];
317
+ for (const f of run.cacheWritten) {
318
+ const id = f.row ?? index.get(path.basename(f.name, ".json")) ?? null;
319
+ if (/^rule-verdicts\//.test(String(f.name).replaceAll("\\", "/"))) continue;
320
+ if (id === null) { fails.push(`the scan store file ${f.name} was written and names no row`); continue; }
321
+ const combined = /^([a-z]+):batch:/.exec(id)?.[1] ?? (/^feature-partition/.test(id) ? "plan" : null);
322
+ if (combined) {
323
+ const extra = (f.crates ?? []).filter((x) => !wantCrates.has(x));
324
+ if (!Array.isArray(f.crates) || !f.crates.length) fails.push(`the combined result ${id} was written and the launcher could not read which crates it names`);
325
+ else if (extra.length) fails.push(`the combined result ${id} names ${extra.join(", ")}, which the edit does not touch`);
326
+ else if (combined !== "plan") for (const e of expected) if (verbOf(e) === combined && f.crates.includes(crateOf(e))) written.add(e);
327
+ continue;
328
+ }
329
+ if (!expected.has(id)) fails.push(`a result for ${id} was written, a row the edit does not touch`); else written.add(id);
330
+ }
331
+ for (const id of expected) if (!written.has(id)) fails.push(`no result was written for ${id}, a row the edit changes`);
332
+ }
333
+ return fails;
334
+ }
335
+
336
+ /** The lines one case is judged on: the ones it lists, plus the ones the evidence table says every case is held to. */
337
+ export const linesOf = (caseDef) => LINE_IDS.filter((id) => (caseDef.decides ?? []).includes(id) || ALWAYS.includes(id));
338
+ /** One case: { id, decides, expect, runs: [facts] } -> { NNxx: { verdict, why } } for its lines. A check that throws is a fail. */
339
+ export function decideCase(c, cases) {
340
+ const out = {};
341
+ for (const id of linesOf(c)) { try { out[id] = LINES[id](c, cases); } catch (e) { out[id] = { verdict: FAIL, why: `the check itself failed: ${e.message}` }; } }
342
+ return out;
343
+ }
344
+ /** The real build: judged on the lines that need no expected rows. */
345
+ export function decideRealBuild(run, cases) {
346
+ const c = { id: "real", label: "the real build", limitKey: "realBuild", runs: [run] }; const out = {};
347
+ const checks = {
348
+ NN01: () => verdict([...passedRun(run, "the real build"), ...(run.jobs.length ? [] : ["the real build left no broker receipt"]), ...receiptsNameTheCommit(run)], "every receipt names the selected commit and tree with the snapshot unchanged"),
349
+ NN02: () => verdict(classABeforeBroker(run), "the Class A verdict file is older than the first signed submission, and every Class A program had ended by then"),
350
+ NN08: () => LINES.NN08(c, cases), NN10: () => verdict(testsBuiltByBrokerRunByGate(run), "tests compiled by the broker, run by the gate"), NN11: () => LINES.NN11(c, cases), NN12: () => LINES.NN12(c, cases),
351
+ };
352
+ for (const id of cases.realBuild?.lines ?? Object.keys(checks)) { try { out[id] = checks[id](); } catch (e) { out[id] = { verdict: FAIL, why: `the check itself failed: ${e.message}` }; } }
353
+ return out;
354
+ }
355
+ /**
356
+ * The counting rule: a line passes when every case that is judged on it passes it, and every line must be judged by at least one case. Twelve of twelve is all twelve
357
+ * passing by that rule and the real build passing its lines. A case that was not run fails every line it lists.
358
+ */
359
+ export function decideAll({ cases, results, realBuild = null }) {
360
+ const lines = LINE_IDS.map((id) => {
361
+ const from = [];
362
+ for (const def of cases.cases) { if (!linesOf(def).includes(id)) continue; const r = results[def.id]?.[id]; from.push({ case: def.id, verdict: r?.verdict ?? FAIL, why: r?.why ?? "the case was not run" }); }
363
+ const failed = from.filter((f) => f.verdict !== PASS);
364
+ return { id, verdict: from.length && !failed.length ? PASS : FAIL, why: !from.length ? "no case decides this line" : failed.length ? failed.map((f) => `case ${f.case}: ${f.why}`).join(" | ") : from.map((f) => `case ${f.case}: ${f.why}`).join(" | "), cases: from };
365
+ });
366
+ const real = (cases.realBuild?.lines ?? []).map((id) => ({ id, verdict: realBuild?.[id]?.verdict ?? FAIL, why: realBuild?.[id]?.why ?? "the real build was not run" }));
367
+ const passed = lines.filter((l) => l.verdict === PASS).length;
368
+ return { lines, realBuild: real, passed, of: LINE_IDS.length, pass: passed === LINE_IDS.length && real.every((l) => l.verdict === PASS) };
369
+ }
370
+
371
+ // ---- gathering the facts of one run folder ------------------------------------------------------------------------------------------------------------------
372
+ /** The facts of a launched run, from its folder (acceptance-launch.mjs) and the broker's receipts. `killed` is the caller's: the launcher knows a kill only as a signal. */
373
+ export function factsOfRun(dir, { repo, receiptsDir, verify = null, killed = false, imageNow = null } = {}) {
374
+ const read = readRunDir(dir, { repo, receiptsDir, verify }); const f = runFacts(read); const launch = read.launch ?? {};
375
+ const json = (p) => { try { return JSON.parse(fs.readFileSync(p, "utf8")); } catch { return null; } };
376
+ const sideBefore = json(path.join(dir, "before", "side-folders.json")); const sideAfter = json(path.join(dir, "side-folders-after.json"));
377
+ const verdicts = {}; for (const [name, v] of Object.entries(sideAfter?.verdicts ?? {})) verdicts[String(name).toLowerCase()] = v[1];
378
+ const newDecisions = Object.keys(sideAfter?.decisions ?? {}).filter((n) => !sideBefore?.decisions?.[n]);
379
+ const decisions = newDecisions.map((n) => json(path.join(sideAfter.decisionDir, n))).filter((d) => d && (!d.commit || d.commit === launch.commit));
380
+ let log = ""; try { log = fs.readFileSync(path.join(dir, "gate.log"), "utf8"); } catch { log = ""; }
381
+ const start = Date.parse(launch.startedAt); const end = Date.parse(launch.endedAt);
382
+ const inRun = f.jobs.filter((j) => !Number.isFinite(j.submitted) || ((!Number.isFinite(start) || j.submitted >= start - 1000) && (!Number.isFinite(end) || j.submitted <= end + 1000)));
383
+ // This run's jobs: the ones signed for its commit, or run in its snapshot (another repository's builds share the broker and the receipts folder).
384
+ const logSnap = snapshotIn(log) ? plain(snapshotIn(log)) : null;
385
+ const mine = inRun.filter((j) => j.gate?.commit === launch.commit || (logSnap !== null && (plain(j.gate?.snapshot) === logSnap || plain(j.cwd).startsWith(logSnap))));
386
+ const snapshot = mine.map((j) => j.gate?.snapshot).find(Boolean) ?? snapshotIn(log);
387
+ return {
388
+ dir, commit: launch.commit ?? null, tree: read.git?.tree ?? null, exit: launch.exit ?? null, signal: launch.signal ?? null, killed: killed || !!launch.signal,
389
+ durationMs: Number.isFinite(start) && Number.isFinite(end) ? end - start : NaN, lanes: launch.lanes ?? null, log,
390
+ jobs: mine, starts: f.starts, rootPid: f.root?.pid ?? null, processGaps: f.gaps, cacheWritten: json(path.join(dir, "cache-written.json")), verdicts, decisions,
391
+ locksAfter: launch.afterRun?.locks ?? [], locksKnown: launch.afterRun?.locksKnown === true, rootAlive: launch.afterRun?.rootAlive === true, snapshot, imageNow,
392
+ };
393
+ }
394
+ const snapshotIn = (log) => /snapshot (\S+?) is commit [0-9a-f]{40}/.exec(String(log))?.[1] ?? null;
@@ -5,7 +5,7 @@
5
5
  // gate code, tools and environment that git cannot show). It keeps the gate's output for people. After the gate ends it exports the operating
6
6
  // system's record of every program that started and exited in the run's window.
7
7
  //
8
- // node acceptance-launch.mjs --out <run dir> --commit <sha> --receipts <broker receipts dir> [--kind <stage>] [--limits <file>] [--lanes <n>]
8
+ // node acceptance-launch.mjs --out <run dir> --commit <sha> --receipts <broker receipts dir> [--kind <stage>] [--limits <file>]
9
9
  // [--repo <dir>] [--gate <bin/rightkit-gate.mjs>] [--lock <file>] -- <gate arguments>
10
10
  //
11
11
  // The run folder holds launch.json (this record), before/receipts.txt, processes.json and gate.log. Beside the run folder: acceptance-launch.lock
@@ -139,9 +139,8 @@ export function listFolder(dir, { cap = 200_000 } = {}) {
139
139
  try { walk(dir, ""); } catch { return null; }
140
140
  return out;
141
141
  }
142
- /** The gate's scan-result store, as the gate would choose it (RK_GATE_CACHE_DIR, else <git common dir>/rightkit-gate-cache), or null when the common dir cannot be found. */
143
- export function cacheStoreDir(repo, env = process.env, run = execFileSync) {
144
- if (env.RK_GATE_CACHE_DIR) return path.resolve(repo, env.RK_GATE_CACHE_DIR);
142
+ /** The gate's scan-result store: the folder rightkit-gate-cache in the repository's git folder, its one fixed place (no variable chooses it), or null when the git folder cannot be found. */
143
+ export function cacheStoreDir(repo, _env = null, run = execFileSync) {
145
144
  try { const common = String(run("git", ["-C", repo, "rev-parse", "--git-common-dir"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], windowsHide: true })).trim(); return common ? path.join(path.resolve(repo, common), "rightkit-gate-cache") : null; } catch { return null; }
146
145
  }
147
146
  /** The folders of the snapshot root that came into being or changed since `sinceMs`, each listed (the stat record of the snapshots at the gate's exit). */
@@ -159,7 +158,7 @@ export function statSnapshots(root, sinceMs, { cap = 200_000, entries = null } =
159
158
  }
160
159
 
161
160
  /** Starts one gate run and records it. Resolves with the gate's exit (or 128 + signal number). */
162
- export async function launch({ out, commit, kind = null, receiptsDir, limits = null, lanes = null, repo = process.cwd(), gate = path.join(here, "bin", "rightkit-gate.mjs"), lock = null, gateArgs = [], env = process.env, spawnImpl = spawn, host = os.hostname(), exportProcesses = null, platform = process.platform, fingerprint = null, snapshotsRoot = null }) {
161
+ export async function launch({ out, commit, kind = null, receiptsDir, limits = null, lanes = null, repo = process.cwd(), gate = path.join(here, "bin", "rightkit-gate.mjs"), lock = null, gateArgs = [], env = process.env, spawnImpl = spawn, host = os.hostname(), exportProcesses = null, platform = process.platform, fingerprint = null, snapshotsRoot = null, onStart = null, managedRoot = null }) {
163
162
  if (!out || !/^[0-9a-f]{40}$/.test(String(commit ?? "")) || !receiptsDir) throw new Error("launch needs --out, a full --commit sha and --receipts");
164
163
  const derived = kindOf(gateArgs);
165
164
  if (kind !== null && kind !== derived) throw new Error(`--kind ${kind} does not match the stage the gate is asked for (--to ${derived}); the time limit is chosen by what is run`);
@@ -171,7 +170,9 @@ export async function launch({ out, commit, kind = null, receiptsDir, limits = n
171
170
  // The limit and the lanes are pinned now, before the gate runs, never chosen afterwards.
172
171
  let limitMs = null; let limitsSha256 = null;
173
172
  if (limits) { const body = fs.readFileSync(limits); limitsSha256 = sha256(body); const v = JSON.parse(body.toString("utf8"))[`${host}/${derived}`]; limitMs = Number.isFinite(v) ? v : null; }
174
- const laneCount = Number.isInteger(lanes) && lanes > 0 ? lanes : (typeof os.availableParallelism === "function" ? os.availableParallelism() : os.cpus().length);
173
+ // The lanes are the gate's own default, this host's cores: the launcher hands the gate no lane count and no cache folder (Adrian, 2026-11-24: no agent chooses either).
174
+ if (lanes !== null) throw new Error("the launcher no longer sets the gate's lanes: they are this host's cores");
175
+ const laneCount = typeof os.availableParallelism === "function" ? os.availableParallelism() : os.cpus().length;
175
176
  // The previous launched run, from the launcher's own record: its identity (whether or not the lock was released), the baseline commit, and whether
176
177
  // this run is the same kind of baseline (gate code, tools, node and platform equal).
177
178
  let last = null; try { last = JSON.parse(fs.readFileSync(lastFile, "utf8")); } catch { last = null; }
@@ -183,18 +184,26 @@ export async function launch({ out, commit, kind = null, receiptsDir, limits = n
183
184
  // The gate's scan-result store as the file system shows it before the run, the launcher's own listing (nothing in it is read).
184
185
  // A run folder reused after a crash must not offer the earlier run's listings.
185
186
  for (const stale of ["cache-store-after.json", "snapshot-stat.json"]) fs.rmSync(path.join(out, stale), { force: true });
186
- const storeDir = cacheStoreDir(repo, env); const storeBefore = listFolder(storeDir);
187
+ const storeDir = cacheStoreDir(repo); const storeBefore = listFolder(storeDir);
188
+ // Two folders of the managed data root, listed before and after by the launcher: the Class A verdict files the broker requires before it admits a compile, and
189
+ // the gate's Class A decision records (its forecast). The listings are the launcher's; what a decision record says is the gate's own statement and is read as that.
190
+ let snapRootEarly = snapshotsRoot; if (snapRootEarly === null) { try { snapRootEarly = (await import("./snapshot.mjs")).snapshotRoot({ platform, env }); } catch { snapRootEarly = null; } }
191
+ const managed = managedRoot ?? (snapRootEarly ? path.dirname(snapRootEarly) : null);
192
+ const verdictDir = managed ? path.join(managed, "class-a-verdicts") : null; const decisionDir = managed ? path.join(managed, "runs", "rightkit-class-a-decisions") : null;
193
+ const sideBefore = { verdicts: listFolder(verdictDir), decisions: listFolder(decisionDir) };
194
+ fs.writeFileSync(path.join(before, "side-folders.json"), `${JSON.stringify({ verdictDir, decisionDir, ...sideBefore })}\n`);
187
195
  fs.writeFileSync(path.join(before, "cache-store.json"), `${JSON.stringify({ dir: storeDir, files: storeBefore })}\n`);
188
196
  const files = { log: path.join(out, "gate.log"), launch: path.join(out, "launch.json") };
189
197
  const args = [gate, ...gateArgs, "--commit", commit];
190
- let snapRoot = snapshotsRoot; if (snapRoot === null) { try { snapRoot = (await import("./snapshot.mjs")).snapshotRoot({ platform, env }); } catch { snapRoot = null; } }
191
- const record = { schema: LAUNCH_SCHEMA, runId, commit, kind: derived, host, gate: { path: path.resolve(repo, gate), args }, launcherPid: process.pid, gatePid: null, lanes: laneCount, lanesSource: lanes ? "--lanes, handed to the gate as RK_GATE_JOBS" : "this host's cores, handed to the gate as RK_GATE_JOBS", limitMs, limitsSha256, receiptsDir: path.resolve(receiptsDir), snapshotsRoot: snapRoot, fingerprint: fp, baseline, startedAt: null, startMono: null, endedAt: null, endMono: null, exit: null, signal: null, previous };
198
+ const snapRoot = snapRootEarly;
199
+ const record = { schema: LAUNCH_SCHEMA, runId, commit, kind: derived, host, gate: { path: path.resolve(repo, gate), args }, launcherPid: process.pid, gatePid: null, lanes: laneCount, lanesSource: "this host's cores, the gate's own default; nothing is handed to the gate", limitMs, limitsSha256, receiptsDir: path.resolve(receiptsDir), snapshotsRoot: snapRoot, fingerprint: fp, baseline, startedAt: null, startMono: null, endedAt: null, endMono: null, exit: null, signal: null, previous };
192
200
  const save = () => fs.writeFileSync(files.launch, `${JSON.stringify(record, null, 2)}\n`);
193
201
  const logFd = fs.openSync(files.log, "a");
194
202
  record.startedAt = new Date().toISOString(); record.startMono = mono();
195
- const child = spawnImpl(process.execPath, args, { cwd: repo, windowsHide: true, stdio: ["ignore", logFd, logFd], env: { ...env, RK_GATE_JOBS: String(laneCount) } });
203
+ const child = spawnImpl(process.execPath, args, { cwd: repo, windowsHide: true, stdio: ["ignore", logFd, logFd], env: (() => { const e = { ...env }; for (const k of Object.keys(e)) if (/^(RK_GATE_JOBS|RK_GATE_CACHE_DIR)$/i.test(k)) delete e[k]; return e; })() });
196
204
  record.gatePid = Number.isInteger(child.pid) ? child.pid : null;
197
205
  save();
206
+ if (typeof onStart === "function") { try { onStart({ child, record: { ...record }, out }); } catch { /* the hook is the caller's */ } }
198
207
  const forward = (sig) => { try { child.kill(sig); } catch { /* already gone */ } };
199
208
  process.on("SIGINT", forward); process.on("SIGTERM", forward);
200
209
  const [code, signal] = await new Promise((resolve) => { child.once("error", () => resolve([null, null])); child.once("exit", (c, s) => resolve([c, s])); });
@@ -209,6 +218,14 @@ export async function launch({ out, commit, kind = null, receiptsDir, limits = n
209
218
  // At the gate's exit, before anything can change: the store listed again, and the stat record of the snapshots this run made or touched.
210
219
  const storeAfter = listFolder(storeDir);
211
220
  fs.writeFileSync(path.join(out, "cache-store-after.json"), `${JSON.stringify({ dir: storeDir, files: storeAfter })}\n`);
221
+ // The same two folders after the run, and which store files this run wrote with the row each names (read at the gate's exit, before a later run can change them).
222
+ const sideAfter = { verdicts: listFolder(verdictDir), decisions: listFolder(decisionDir) };
223
+ fs.writeFileSync(path.join(out, "side-folders-after.json"), `${JSON.stringify({ verdictDir, decisionDir, ...sideAfter })}\n`);
224
+ const changed = storeBefore && storeAfter ? Object.keys(storeAfter).filter((k) => !storeBefore[k] || storeBefore[k][0] !== storeAfter[k][0] || storeBefore[k][1] !== storeAfter[k][1]).sort() : null;
225
+ const rowOfFile = (name) => { try { const d = JSON.parse(fs.readFileSync(path.join(storeDir, name), "utf8")); return typeof d?.row?.id === "string" ? d.row.id : typeof d?.id === "string" ? d.id : null; } catch { return null; } };
226
+ // A combined result names its crates in its own record, or in the command it stores (`-p <crate>`).
227
+ const cratesOfFile = (name) => { try { const d = JSON.parse(fs.readFileSync(path.join(storeDir, name), "utf8")); if (Array.isArray(d?.row?.crates)) return d.row.crates.map(String); const words = String(d?.row?.command ?? "").split(/\s+/); const out = []; words.forEach((w, i) => { if ((w === "-p" || w === "--package") && words[i + 1]) out.push(words[i + 1]); }); return out.length ? [...new Set(out)] : null; } catch { return null; } };
228
+ fs.writeFileSync(path.join(out, "cache-written.json"), `${JSON.stringify(changed === null ? null : changed.map((name) => ({ name, row: rowOfFile(name), crates: cratesOfFile(name) })))}\n`);
212
229
  const snaps = rootEntries === null ? { root: snapRoot, dirs: {}, known: false } : statSnapshots(snapRoot, Date.parse(record.startedAt), { entries: rootEntries });
213
230
  fs.writeFileSync(path.join(out, "snapshot-stat.json"), `${JSON.stringify(snaps)}\n`);
214
231
  record.cacheStore = { dir: storeDir, beforeKnown: storeBefore !== null, afterKnown: storeAfter !== null }; record.snapshotStat = { root: snaps.root, folders: Object.keys(snaps.dirs), known: snaps.known };
@@ -229,6 +246,6 @@ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.me
229
246
  const own = cut < 0 ? argv : argv.slice(0, cut); const gateArgs = cut < 0 ? [] : argv.slice(cut + 1);
230
247
  const opt = (name) => { const i = own.indexOf(name); return i < 0 ? null : own[i + 1]; };
231
248
  if (gateArgs.includes("--commit")) { console.error("acceptance-launch: the launcher owns --commit; give it before --"); process.exit(2); }
232
- launch({ out: opt("--out"), commit: opt("--commit"), kind: opt("--kind"), receiptsDir: opt("--receipts"), limits: opt("--limits"), lanes: opt("--lanes") ? Number(opt("--lanes")) : null, repo: opt("--repo") ?? process.cwd(), gate: opt("--gate") ?? undefined, lock: opt("--lock"), gateArgs })
249
+ launch({ out: opt("--out"), commit: opt("--commit"), kind: opt("--kind"), receiptsDir: opt("--receipts"), limits: opt("--limits"), repo: opt("--repo") ?? process.cwd(), gate: opt("--gate") ?? undefined, lock: opt("--lock"), gateArgs })
233
250
  .then((code) => process.exit(code), (e) => { console.error(`acceptance-launch: ${e.message}`); process.exit(2); });
234
251
  }
@@ -1205,6 +1205,19 @@ export function readRunDir(dir, { repo = null, receiptsDir = null, verify = null
1205
1205
  return { cacheStore, snapshotStat, launch, processes, witness: proc ? { kind: proc.kind, from: proc.from, to: proc.to, newest: proc.newest, continuous: proc.continuous === true, problems: proc.problems ?? [] } : null, receipts, inventory, priorInventory, inventoryUncovered, prior, git };
1206
1206
  }
1207
1207
 
1208
+ /**
1209
+ * The outside facts of one run, for the case-based decision (acceptance-cases.mjs; Adrian, 2026-11-24, rightkit#1514: "adopt the 12-line evidence table"):
1210
+ * the programs of the gate's own process tree as the operating system recorded them, and each broker job from its signed receipt. Nothing the gate wrote is read.
1211
+ */
1212
+ export function runFacts(run) {
1213
+ const tree = runTree(run?.launch ?? null, run?.processes ?? null, run?.witness ?? null);
1214
+ const starts = tree.procs.map((p) => ({ ...decodeStart({ cmd: p.exe, args: p.args, cwd: p.cwd ?? "" }), exe: p.exe, pid: p.pid, ppid: p.ppid, at: p.start, end: p.end, exit: p.exit, argsKnown: p.argsKnown !== false }));
1215
+ // The signed command as the broker ran it (the broker adds --no-run to a test build itself), beside the one the gate asked for.
1216
+ const ran = (r) => { const a = r?.doc?.provenance?.payload?.request?.effectiveArgv; return Array.isArray(a) ? a.map(String) : null; };
1217
+ return { root: tree.root, gaps: tree.gaps, starts, jobs: (run?.receipts ?? []).map((r) => ({ ...jobOf(r), effectiveArgv: ran(r), status: r?.doc?.provenance?.payload?.result?.status ?? null })) };
1218
+ }
1219
+ export { programName, cargoVerb, valuesOf, dirKey, isProbe };
1220
+
1208
1221
  // ---- command line -----------------------------------------------------------------------------------------------------------------------------------
1209
1222
  if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
1210
1223
  const opt = (name) => { const i = process.argv.indexOf(name); return i < 0 ? null : process.argv[i + 1]; };