@rightkit/release 0.6.57 → 0.6.61

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/README.md +4 -0
  2. package/acceptance-admission.mjs +104 -0
  3. package/acceptance-launch.mjs +234 -0
  4. package/acceptance-lines.mjs +1254 -0
  5. package/acceptance-result.mjs +77 -0
  6. package/acceptance-rows.mjs +47 -0
  7. package/admission-files.mjs +2 -0
  8. package/affected-units.mjs +17 -0
  9. package/app-check.mjs +6 -2
  10. package/app-closure.mjs +3 -1
  11. package/bin/rightkit-gate.mjs +546 -121
  12. package/broker-admission.mjs +45 -2
  13. package/broker-pins.mjs +11 -1
  14. package/broker-toolchain.mjs +113 -0
  15. package/cargo-profile-contract.mjs +7 -2
  16. package/class-a-cache-history.mjs +135 -0
  17. package/cli/right-release.mjs +0 -0
  18. package/code-closure.mjs +24 -0
  19. package/config-inspect.mjs +6 -0
  20. package/consumer-contracts.mjs +3 -1
  21. package/contract-nn.json +166 -0
  22. package/deterministic-scans.mjs +835 -112
  23. package/feature-coverage.mjs +109 -82
  24. package/feature-partition.mjs +76 -0
  25. package/forbidden-literals.mjs +78 -0
  26. package/gate/calls.mjs +121 -0
  27. package/gate/compile.mjs +190 -0
  28. package/gate/crate-results.mjs +127 -0
  29. package/gate/run-calls.mjs +241 -0
  30. package/gate/tests.mjs +234 -0
  31. package/gate-coverage.mjs +12 -3
  32. package/gate-release-admission.mjs +200 -0
  33. package/gate-seam.mjs +100 -4
  34. package/gate-serve.mjs +178 -32
  35. package/gate-stages.mjs +59 -0
  36. package/legacy-contract-receipt.mjs +809 -0
  37. package/local-publish.mjs +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 +90 -12
  64. package/spawn-ledger.mjs +21 -2
  65. package/stage-sidecar.mjs +231 -19
  66. package/suite-trust-roots.mjs +2 -2
  67. package/test-env.mjs +26 -0
  68. package/tool-version-memo.mjs +46 -0
  69. package/win-package-recipe.mjs +11 -0
  70. package/bin/darwin/rightkit-swap +0 -0
  71. package/gate-acceptance.mjs +0 -3362
@@ -0,0 +1,190 @@
1
+ // The compile stage for a set of crates, built together (design sections 6 to 11 and 17). Glue only: it reads the crates from the
2
+ // snapshot, plans the calls (calls.mjs), runs them through the broker seam (run-calls.mjs), runs the test programs (tests.mjs) and
3
+ // returns one result per crate. The caller holds the snapshot lock and has already written the Class A verdict.
4
+ import crypto from "node:crypto";
5
+ import fs from "node:fs";
6
+ import path from "node:path";
7
+ import { fileURLToPath } from "node:url";
8
+ import { spawnSync as nodeSpawnSync } from "node:child_process";
9
+ import { DOC_DENY, osOfTriple, planCalls, planNotes } from "./calls.mjs";
10
+ import { fileStore, resultsByCrate, runCalls } from "./run-calls.mjs";
11
+ import { runTests } from "./tests.mjs";
12
+ import { CROSS_TARGETS, hostTarget } from "../cross-targets.mjs";
13
+ import { resolveBrokerClient } from "../broker-client.mjs";
14
+ import { runSeamCargoCall } from "../seam-broker.mjs";
15
+ import { codeClosure } from "../code-closure.mjs";
16
+
17
+ export const UNIT_RESULT_SCHEMA = "rightkit.unit-result/1";
18
+ const HERE = path.dirname(fileURLToPath(import.meta.url));
19
+
20
+ /** What the call planner needs to know about one crate, read from its manifest in the snapshot and from ci/gate.config.json. */
21
+ export function crateInfo(snapshot, name, rustConfig = {}, { readFile = (f) => fs.readFileSync(f, "utf8"), exists = fs.existsSync } = {}) {
22
+ const dir = path.join(snapshot, "crates", name);
23
+ const manifest = readFile(path.join(dir, "Cargo.toml"));
24
+ const features = /^\[features\]\s*$([\s\S]*?)(?=^\[|(?![\s\S]))/m.exec(manifest)?.[1] ?? "";
25
+ const declaresFeatures = features.split(/\r?\n/).some((l) => /^\s*[A-Za-z0-9_-]+\s*=/.test(l) && !/^\s*default\s*=/.test(l));
26
+ const cfg = rustConfig[name];
27
+ return { name, dir, hasLib: exists(path.join(dir, "src", "lib.rs")) || /^\[lib\]/m.test(manifest), declaresFeatures, platforms: cfg?.platforms, config: cfg, quiet: cfg?.quietTests === true, serialToo: cfg?.alsoSerial === true, // Named only by a written reason, as on the per-crate rows: `true` or an empty string names nothing.
28
+ allowIgnored: typeof cfg?.allowIgnored === "string" && cfg.allowIgnored.trim() !== "" };
29
+ }
30
+
31
+ /**
32
+ * Every file of this package the build-together path loads: the files of `dir` (tests excluded) and every file they import by a
33
+ * relative path, followed to the end. A change to any of them (the broker seam, the test environment) must void remembered passes.
34
+ * An import that cannot be read throws: a pass is never remembered under a hash that skipped a file.
35
+ */
36
+ export function gateCodeFiles(dir = HERE, { readFile = (f) => fs.readFileSync(f, "utf8"), list = (d) => fs.readdirSync(d) } = {}) {
37
+ return codeClosure(list(dir).filter((n) => n.endsWith(".mjs") && !n.endsWith(".test.mjs")).map((n) => path.join(dir, n)), dir, { readFile });
38
+ }
39
+
40
+ /**
41
+ * The identity a passed call is remembered under: the commit, the toolchain the snapshot pins, the host, the installed broker and this gate code.
42
+ * The broker is named by its exact build (`brokerDigest` of the runtime manifest beside the client), never by a version label, which two builds
43
+ * can share. `brokerKnown` is false when that digest cannot be read; then nothing is remembered and nothing remembered is reused.
44
+ */
45
+ export function gateIdentity({ commit, snapshot, platform, client, readFile = (f) => fs.readFileSync(f, "utf8") }) {
46
+ let toolchain = "unpinned";
47
+ for (const file of ["rust-toolchain.toml", "rust-toolchain"]) { try { toolchain = crypto.createHash("sha256").update(readFile(path.join(snapshot, file))).digest("hex").slice(0, 16); break; } catch { /* next */ } }
48
+ let broker = "none";
49
+ if (client) { try { const m = JSON.parse(readFile(path.join(path.dirname(client), "runtime-manifest.json"))); broker = typeof m.brokerDigest === "string" && /^[0-9a-f]{64}$/.test(m.brokerDigest) ? m.brokerDigest : "unknown"; } catch { broker = "unknown"; } }
50
+ const code = crypto.createHash("sha256");
51
+ for (const f of gateCodeFiles(HERE)) code.update(f.name).update("\0").update(f.text).update("\0");
52
+ return { commit, toolchain, host: platform, broker, brokerKnown: /^[0-9a-f]{64}$/.test(broker), gate: code.digest("hex").slice(0, 16) };
53
+ }
54
+
55
+ /**
56
+ * The build of the broker that is RUNNING and that this run's jobs will reach, asked once through the client's read-only health command
57
+ * (`<client> doctor --json --no-scan`: a STATUS probe) with the same environment the jobs are sent with, so it is the broker those jobs meet.
58
+ * The answering broker's handshake digest, or null when the client cannot be run, prints no JSON, or no broker answered. The command's exit
59
+ * code is not read (it is non-zero for unrelated health findings), and what the manifest on disk expects is not read as "running".
60
+ */
61
+ export function runningBrokerDigest({ client, env, spawnSync = nodeSpawnSync }) {
62
+ if (!client) return null;
63
+ let r; try { r = spawnSync(client, ["doctor", "--json", "--no-scan"], { encoding: "utf8", timeout: 60_000, windowsHide: true, env }); } catch { return null; }
64
+ if (!r || r.error) return null;
65
+ let doctor; try { doctor = JSON.parse(String(r.stdout)); } catch { return null; }
66
+ const a = doctor?.answeringBroker; const d = a?.handshakeRuntime?.brokerDigest;
67
+ return a?.answered === true && typeof d === "string" && /^[0-9a-f]{64}$/.test(d) ? d : null;
68
+ }
69
+
70
+ /**
71
+ * The environment one call is sent with. A docs call denies rustdoc warnings, as CI does: the broker adds nothing itself and admits exactly this
72
+ * value on doc calls. Every other call is sent without RUSTDOCFLAGS, whatever the launching session had set.
73
+ */
74
+ export function callEnv(env, call) {
75
+ const out = { ...env }; delete out.RUSTDOCFLAGS;
76
+ if (call.stage === "docs") out.RUSTDOCFLAGS = DOC_DENY;
77
+ return out;
78
+ }
79
+
80
+ /** The targets linted on this host: its own triple and the other operating systems' cross targets. */
81
+ export function targetsFor(platform = process.platform, arch = process.arch) {
82
+ const hostTriple = hostTarget(platform, arch);
83
+ return { hostTriple, otherTriples: Object.entries(CROSS_TARGETS).filter(([os]) => os !== platform).map(([, triple]) => triple).filter((t) => osOfTriple(t) !== platform) };
84
+ }
85
+
86
+ const STAGES = ["lint", "test-build", "docs"];
87
+
88
+ /**
89
+ * Compiles `crates` (names) of the snapshot together and runs their tests.
90
+ * `send`: optional replacement for the broker call (tests). `onUnsettled`: called for a broker job that ended without a settled outcome (the caller keeps the snapshot lock).
91
+ * Returns { code, byCrate: { name: { result, stages: { lint, "test-build", docs, tests } } }, counts, notes, calls }.
92
+ */
93
+ export async function compileTogether({ snapshot, commit, crates, rustConfig = {}, platform = process.platform, arch = process.arch, client = "rustright", env = process.env, verdictFile, storeDir, out = () => {}, onUnsettled = () => {}, send = null, runTestsWith = runTests, identityOf = gateIdentity, askBroker = runningBrokerDigest }) {
94
+ // The client as it is spawned (broker-client.mjs): a win32 `.cmd` shim resolves to its target `.exe` here, once, so the identity's manifest,
95
+ // the running-broker probe and every seam call name the `.exe`; an unresolvable shim refuses before anything is looked up or sent.
96
+ if (client) client = resolveBrokerClient(client, { platform }).file;
97
+ // ci/asset-gated.json of the commit: a listed crate runs its tests with RIGHTKIT_REQUIRE_ASSETS=0, every other with 1, as on the per-crate rows.
98
+ let gated = {};
99
+ try { gated = JSON.parse(fs.readFileSync(path.join(snapshot, "ci", "asset-gated.json"), "utf8")).crates ?? {}; } catch { gated = {}; }
100
+ const infos = crates.map((name) => ({ ...crateInfo(snapshot, name, rustConfig), assetGated: Object.hasOwn(gated, name) }));
101
+ const { hostTriple, otherTriples } = targetsFor(platform, arch);
102
+ const calls = planCalls({ crates: infos, host: platform, hostTriple, otherTriples });
103
+ const notes = planNotes({ crates: infos, host: platform });
104
+ const identity = identityOf({ commit, snapshot, platform, client });
105
+ // Without the broker's exact build there is nothing sound to remember a pass under, and no remembered pass can be shown to be this broker's.
106
+ const seamEnv = { ...env, RUSTRIGHT_GATE_COMMIT: commit, RUSTRIGHT_CLASS_A: verdictFile };
107
+ // Once per run, before anything is looked up: the broker that is running must be the installed build the key names. The key's digest is read
108
+ // from disk; a broker replaced or started from elsewhere answers with another one. Unknown or different: no store for this run.
109
+ let storeOff = !storeDir ? "no store was asked for" : !identity.brokerKnown ? "the installed broker's build (brokerDigest of its runtime manifest) cannot be read" : null;
110
+ if (!storeOff) { const live = askBroker({ client, env: seamEnv }); if (live !== identity.broker) storeOff = live ? `the running broker is ${live}, the installed runtime is ${identity.broker}` : "the running broker did not state its build"; }
111
+ let store = storeOff ? null : fileStore(storeDir);
112
+ if (storeDir && storeOff) out(`nothing is remembered or reused in this run: ${storeOff}`);
113
+ // What a remembered test pass belongs to: this commit on this toolchain, host, broker and gate code, the same identity a remembered call has.
114
+ const testScope = crypto.createHash("sha256").update(JSON.stringify(["commit", "toolchain", "host", "broker", "gate"].map((k) => identity[k]))).digest("hex");
115
+ const sendCall = send ?? ((call) => {
116
+ const { result, ledger } = runSeamCargoCall(call.args, { cwd: path.join(snapshot, call.cwd ?? "."), env: callEnv(seamEnv, call), client });
117
+ if (ledger?.settled === false) onUnsettled(call, ledger);
118
+ return result;
119
+ });
120
+ out(`together compile: ${infos.length} crate(s), ${calls.length} call(s) planned (${calls.filter((c) => c.crates.length > 1).length} name more than one crate; the largest names ${Math.max(0, ...calls.map((c) => c.crates.length))})`);
121
+ const started = Date.now();
122
+ const tests = {}; const testCounts = { programs: 0, ran: 0, cached: 0, unreaped: 0 };
123
+ // Test programs: from the receipt of a test-build call's evidence job, for the crates that passed that call. They run as soon as that call
124
+ // ends and before the next call is sent: a test that starts its crate's own binary (CARGO_BIN_EXE_<name>) reads it from the shared target
125
+ // directory, where the next test build of the same crate with other features replaces it (Dell, 2026-11-11: rightkit-agent-tools'
126
+ // default-build test ran against the binary of the later `demo` build and failed).
127
+ const runTestsOf = async (o) => {
128
+ const green = o.results.filter((r) => r.result === "passed").map((r) => infos.find((i) => i.name === r.crate));
129
+ if (!green.length) return;
130
+ let executables = null;
131
+ try { executables = JSON.parse(fs.readFileSync(o.evidence.receipt, "utf8")).testExecutables ?? null; } catch { executables = null; }
132
+ const ran = await runTestsWith({ executables, crates: green, env, store, scope: testScope });
133
+ for (const [name, r] of Object.entries(ran.byCrate)) {
134
+ const cur = tests[name];
135
+ if (!cur || (cur.result === "passed" && r.result !== "passed")) tests[name] = { ...r, round: o.call.round };
136
+ else if (cur.result === "passed") tests[name] = { ...cur, programs: cur.programs + r.programs, passed: cur.passed + r.passed, ignored: cur.ignored + r.ignored };
137
+ }
138
+ for (const k of Object.keys(testCounts)) testCounts[k] += ran.counts[k] ?? 0;
139
+ // A test program that could not be proven stopped may still write in the snapshot: the caller keeps the snapshot lock, as for an unsettled broker job.
140
+ if (ran.counts.unreaped) onUnsettled(o.call, { settled: false, reason: `${ran.counts.unreaped} test program(s) timed out and are not proven stopped` });
141
+ };
142
+ const outcomes = []; const counts = { calls: calls.length, ran: 0, skipped: 0, jobs: 0, greenReruns: 0, notRemembered: 0 };
143
+ let stopped = null;
144
+ for (const call of calls) {
145
+ const one = runCalls({
146
+ calls: [call], send: sendCall, store, identity, hostTriple, env: (c) => callEnv(seamEnv, c),
147
+ onCall: (o) => {
148
+ if (o.notRemembered) out(`not remembered ${o.call.id}: ${o.notRemembered}`);
149
+ const red = o.results.filter((r) => r.result !== "passed");
150
+ out(`${o.state === "skipped" ? "skipped" : red.length ? "red " : "passed "} ${o.call.id} (${o.call.crates.length} crate(s)${o.jobs.length > 1 ? ", green rerun sent" : ""})${red.length ? `: ${red.slice(0, 8).map((r) => `${r.crate} ${r.result}`).join(", ")}${red.length > 8 ? `, +${red.length - 8} more` : ""}` : ""}`);
151
+ },
152
+ });
153
+ outcomes.push(...one.outcomes);
154
+ for (const k of ["ran", "skipped", "jobs", "greenReruns", "notRemembered"]) counts[k] += one.counts[k];
155
+ // A job of this run was signed by another broker build than the key names: the broker changed under the run. Nothing more is remembered or reused.
156
+ if (store && one.outcomes.some((o) => o.brokerChanged)) { store = null; out("the broker's build changed during this run: nothing further is remembered or reused"); }
157
+ if (call.stage === "test-build") for (const o of one.outcomes) await runTestsOf(o);
158
+ // A test program not proven stopped may still be reading or writing the shared build folder: no further Cargo call is sent into it.
159
+ if (testCounts.unreaped) { stopped = `stopped after ${call.id}: ${testCounts.unreaped} test program(s) timed out and are not proven stopped; ${calls.length - calls.indexOf(call) - 1} call(s) not sent`; out(stopped); break; }
160
+ }
161
+ const perStage = resultsByCrate(outcomes);
162
+
163
+ const byCrate = {};
164
+ for (const info of infos) {
165
+ const stages = {};
166
+ for (const s of STAGES) if (perStage[info.name]?.[s]) stages[s] = perStage[info.name][s];
167
+ if (stages["test-build"]) stages.tests = stages["test-build"].result === "passed" ? (tests[info.name] ?? { result: "unknown", detail: "its tests were not run" }) : { result: "not-built", detail: "the test build did not pass" };
168
+ const words = Object.values(stages).map((s) => s.result);
169
+ const planned = words.length > 0;
170
+ // A stopped run did not send every call: a crate with nothing red is unknown, never passed.
171
+ if (stopped && planned && !words.includes("failed")) { byCrate[info.name] = { result: "unknown", detail: stopped, stages }; continue; }
172
+ byCrate[info.name] = { result: !planned ? (notes.notOnThisHost.includes(info.name) ? "not-on-this-host" : "unknown") : words.every((w) => w === "passed") ? "passed" : words.includes("failed") ? "failed" : words.includes("not-built") ? "not-built" : "unknown", stages };
173
+ }
174
+ const allCounts = { ...counts, tests: testCounts, seconds: Math.round((Date.now() - started) / 1000) };
175
+ out(`together compile: calls ${counts.ran} ran, ${counts.skipped} skipped, ${counts.jobs} broker job(s), ${counts.greenReruns} green rerun(s); test programs ${testCounts.ran} ran, ${testCounts.cached} cached; ${allCounts.seconds} s`);
176
+ const owed = Object.entries(byCrate).filter(([, v]) => v.result !== "not-on-this-host");
177
+ const code = owed.length > 0 && owed.every(([, v]) => v.result === "passed") ? 0 : 1;
178
+ return { code, byCrate, counts: allCounts, notes, calls: outcomes.map((o) => ({ id: o.call.id, stage: o.call.stage, cwd: o.call.cwd ?? ".", args: o.call.args, state: o.state, jobs: o.jobs, evidence: o.evidence, crates: o.results })) };
179
+ }
180
+
181
+ /** The result file of one unit: what a publisher or CI admission reads. A unit that passed has one even when another unit of the run failed. */
182
+ export function unitResult({ selector, commit, tree, platform, crate, run }) {
183
+ const mine = run.byCrate[crate];
184
+ return {
185
+ schema: UNIT_RESULT_SCHEMA, unit: selector, commit, tree, host: platform, stage: "compile",
186
+ result: mine?.result ?? "unknown",
187
+ stages: mine?.stages ?? {},
188
+ calls: run.calls.filter((c) => c.crates.some((r) => r.crate === crate)).map((c) => ({ id: c.id, stage: c.stage, cwd: c.cwd, args: c.args, state: c.state, result: c.crates.find((r) => r.crate === crate).result, evidence: c.evidence })),
189
+ };
190
+ }
@@ -0,0 +1,127 @@
1
+ // Per-crate results of ONE together Cargo call, read from Cargo's own JSON message stream (design section 8,
2
+ // docs/design/2026-11-10-gate-fresh-design.md). Pure: text in, verdicts out. No cache, no grouping, no projection onto other keys:
3
+ // a crate's result here is how it compiled in the call that named it, nothing more.
4
+ //
5
+ // Cargo's stream (`--message-format=json`), one JSON object per stdout line:
6
+ // compiler-message { package_id, target, message: { level, rendered } } no target triple in the record
7
+ // compiler-artifact { package_id, target: { kind, name }, filenames: [...], fresh }
8
+ // build-script-executed, build-finished { success }
9
+ // Facts this file relies on and nothing else:
10
+ // - an artifact's file path holds `<target-dir>/<triple>/<profile>/...` when the call named `--target <triple>`;
11
+ // - a build-script failure and a link failure are plain stderr text: "failed to run custom build command for `name vX`",
12
+ // "could not compile `name` (...)";
13
+ // - `build-finished` is the last record of a call that reached the build; a stream without it was cut short or never started.
14
+
15
+ /** The crate name inside a Cargo package id, for every spelling Cargo has used. */
16
+ export function packageNameOf(id) {
17
+ const text = String(id ?? "");
18
+ // Cargo >= 1.77: `path+file:///abs/crates/foo#0.1.0`, `path+file:///abs/dir#name@0.1.0`, `registry+https://...#serde@1.0.200`.
19
+ const hash = text.lastIndexOf("#");
20
+ if (/^[a-z]+\+/.test(text) && hash >= 0) {
21
+ const tail = text.slice(hash + 1);
22
+ const at = tail.lastIndexOf("@");
23
+ if (at > 0) return tail.slice(0, at);
24
+ const base = text.slice(0, hash).replace(/[?].*$/, "").replace(/\/+$/, "");
25
+ return base.slice(base.lastIndexOf("/") + 1);
26
+ }
27
+ // Older: `name 0.1.0 (path+file:///...)`.
28
+ const space = text.indexOf(" ");
29
+ return space > 0 ? text.slice(0, space) : text;
30
+ }
31
+
32
+ /** The target triple an artifact was built for: the first path segment that is one of `targets`; `host` when the path names none. */
33
+ export function tripleOfArtifact(filenames, targets, host) {
34
+ for (const file of Array.isArray(filenames) ? filenames : []) {
35
+ const parts = String(file).split(/[\\/]+/);
36
+ for (const t of targets) if (parts.includes(t)) return t;
37
+ }
38
+ return host;
39
+ }
40
+
41
+ const STDERR_FAILURES = [
42
+ /failed to run custom build command for `([^`\s]+)(?: v[^`]*)?`/g,
43
+ /could not compile `([^`\s]+)`/g,
44
+ /could not document `([^`\s]+)`/g,
45
+ ];
46
+
47
+ /**
48
+ * Reads one call's output.
49
+ * `stdout`: the call's stdout (Cargo's JSON lines, other lines ignored). `stderr`: its stderr.
50
+ * Returns { finished, success, records, errors: { crate: { count, rendered[] } }, artifacts: { crate: { triple: n } }, named: Set<crate> }.
51
+ */
52
+ export function readCargoStream({ stdout = "", stderr = "", targets = [], host = null } = {}) {
53
+ const out = { finished: false, success: null, records: 0, malformed: 0, errors: {}, artifacts: {}, named: new Set() };
54
+ const fail = (name, rendered) => {
55
+ const e = (out.errors[name] ??= { count: 0, rendered: [] });
56
+ e.count += 1;
57
+ if (rendered && e.rendered.length < 4) e.rendered.push(String(rendered).trimEnd().slice(0, 700));
58
+ };
59
+ for (const raw of String(stdout).split(/\r?\n/)) {
60
+ const line = raw.trim();
61
+ if (!line.startsWith("{")) continue;
62
+ let v;
63
+ try { v = JSON.parse(line); } catch { out.malformed += 1; continue; }
64
+ if (!v || typeof v.reason !== "string") continue;
65
+ out.records += 1;
66
+ if (v.reason === "build-finished") { out.finished = true; out.success = v.success === true; continue; }
67
+ if (v.reason === "compiler-message") {
68
+ if (v.message?.level === "error") fail(packageNameOf(v.package_id), v.message.rendered ?? v.message.message);
69
+ continue;
70
+ }
71
+ if (v.reason === "compiler-artifact") {
72
+ const kinds = Array.isArray(v.target?.kind) ? v.target.kind : [];
73
+ if (kinds.includes("custom-build")) continue;
74
+ const name = packageNameOf(v.package_id);
75
+ const triple = tripleOfArtifact(v.filenames, targets, host);
76
+ const per = (out.artifacts[name] ??= {});
77
+ per[triple] = (per[triple] ?? 0) + 1;
78
+ }
79
+ }
80
+ for (const pattern of STDERR_FAILURES) {
81
+ for (const m of String(stderr).matchAll(pattern)) { out.named.add(m[1]); if (!out.errors[m[1]]) fail(m[1], m[0]); }
82
+ }
83
+ return out;
84
+ }
85
+
86
+ /**
87
+ * The result of every crate the call named.
88
+ * `crates`: [{ name, targets: [triple...] }] (the triples this call asked of that crate; one entry, the host, for a call with no cross target).
89
+ * `exit`: the call's exit code (null when it never ran). `refusal`: a one-line cause when the call did not reach Cargo (broker refusal, no result line).
90
+ * Each result: { crate, result: "passed" | "failed" | "not-built" | "unknown", detail }.
91
+ * passed no error for the crate and an artifact for every triple asked of it
92
+ * failed an error of the crate's own (compiler, build script, link)
93
+ * not-built no error of its own and an artifact missing: something it depends on failed, or Cargo stopped before it
94
+ * unknown the call gave no usable stream (refused, cut short, no JSON): nothing is known, nothing passes
95
+ */
96
+ export function crateResults({ crates, stdout, stderr, exit = null, refusal = null, host = null }) {
97
+ const targets = [...new Set(crates.flatMap((c) => c.targets))];
98
+ if (refusal) return crates.map((c) => ({ crate: c.name, result: "unknown", detail: refusal }));
99
+ const s = readCargoStream({ stdout, stderr, targets, host });
100
+ if (!s.finished) {
101
+ const why = s.records ? "Cargo's output ended without a build-finished record (cut short)" : "the call produced no Cargo JSON";
102
+ // A crate Cargo named as failed before the stream ended still failed; the rest are unknown.
103
+ return crates.map((c) => (s.errors[c.name] ? { crate: c.name, result: "failed", detail: s.errors[c.name].rendered.join(" | ") } : { crate: c.name, result: "unknown", detail: why }));
104
+ }
105
+ const failedNames = Object.keys(s.errors);
106
+ return crates.map((c) => {
107
+ const err = s.errors[c.name];
108
+ if (err) return { crate: c.name, result: "failed", detail: `${err.count} error(s): ${err.rendered.join(" | ")}` };
109
+ const missing = c.targets.filter((t) => !(s.artifacts[c.name]?.[t] > 0));
110
+ if (missing.length === 0) {
111
+ // Every artifact is there. A non-zero exit with this crate complete is someone else's failure.
112
+ return { crate: c.name, result: "passed", detail: "" };
113
+ }
114
+ const because = failedNames.length ? `failed in this call: ${failedNames.slice(0, 6).join(", ")}${failedNames.length > 6 ? ", ..." : ""}` : s.success === false || (exit !== null && exit !== 0) ? "the call failed with no error attributed to a crate (see its output)" : "Cargo reported success but no artifact for it";
115
+ return { crate: c.name, result: "not-built", detail: `no artifact for ${missing.join(", ")}; ${because}` };
116
+ });
117
+ }
118
+
119
+ /** One crate's result over every call that named it: passed only when it passed them all; the first non-pass decides the word. */
120
+ export function combineResults(perCall) {
121
+ const order = ["failed", "not-built", "unknown"];
122
+ for (const word of order) {
123
+ const hit = perCall.find((r) => r.result === word);
124
+ if (hit) return { result: word, detail: hit.detail };
125
+ }
126
+ return perCall.length ? { result: "passed", detail: "" } : { result: "unknown", detail: "no call named this crate" };
127
+ }
@@ -0,0 +1,241 @@
1
+ // Runs the call list of one run (design sections 6, 9 and 17). One call after another, because the broker runs one Cargo process per app.
2
+ //
3
+ // Three rules and nothing else:
4
+ // 1. Skip: a call that already passed for this exact commit, command, toolchain, host, broker and gate version is not sent again.
5
+ // The key has no per-crate input. Of the environment it carries exactly the variables the broker passes on to Cargo that can change a
6
+ // result (CALL_KEY_ENV); the whole environment in a key was the cache-miss loop. A call is remembered only when its signed receipt shows
7
+ // the broker forwarded nothing outside the names this file knows, so a broker that starts forwarding more cannot be keyed too narrowly.
8
+ // 2. Result: each crate's result is read from the call's own Cargo output (crate-results.mjs).
9
+ // 3. Green rerun: when a call ends with some crates red, the same call is sent once more naming only the crates that passed.
10
+ // That job exits 0 and is the signed evidence for them (CI admits only a job that exited 0); it compiles nothing new.
11
+ // One red crate never voids the others.
12
+ import crypto from "node:crypto";
13
+ import fs from "node:fs";
14
+ import path from "node:path";
15
+ import { crateResults, readCargoStream } from "./crate-results.mjs";
16
+
17
+ const sha256 = (text) => crypto.createHash("sha256").update(text).digest("hex");
18
+
19
+ /** The same call naming only `names` (its `-p` list reduced). A call with no `-p` list (a consumer manifest) is returned unchanged. */
20
+ export function restrictCall(call, names) {
21
+ const keep = new Set(names);
22
+ const args = [];
23
+ let had = false;
24
+ for (let i = 0; i < call.args.length; i += 1) {
25
+ if (call.args[i] === "--") { args.push(...call.args.slice(i)); break; }
26
+ if (call.args[i] === "-p") { had = true; if (keep.has(call.args[i + 1])) args.push("-p", call.args[i + 1]); i += 1; continue; }
27
+ args.push(call.args[i]);
28
+ }
29
+ return had ? { ...call, id: `${call.id}:green`, args, crates: call.crates.filter((c) => keep.has(c.name)) } : call;
30
+ }
31
+
32
+ /**
33
+ * The variables the broker passes on to Cargo (rustright-policy environment.rs MANAGED_REQUEST_ENVIRONMENT_KEYS, read 2026-11-17), in two parts.
34
+ * CALL_KEY_ENV can change what is built or linted and is in the key. CALL_DISPLAY_ENV only changes how output looks and is not: TERM in a key
35
+ * makes every terminal a miss. The broker refuses any other name, and forwards cargo-ndk's compiler entries only when an NDK root is set; a
36
+ * call that forwarded one of those, or any name not listed here, is never remembered (see `unrememberable`).
37
+ */
38
+ // RUSTDOCFLAGS is the broker's one value-pinned extra: it admits exactly "-D warnings", on doc calls only, and only when the request carries it.
39
+ // It is in the key, so a doc call that passed without it is never reused for one sent with it.
40
+ export const CALL_KEY_ENV = Object.freeze(["ANDROID_NDK_HOME", "CI", "IPHONEOS_DEPLOYMENT_TARGET", "NDK_HOME", "RUSTDOCFLAGS", "RUST_BACKTRACE", "RUST_LOG", "SOURCE_DATE_EPOCH", "TZ"]);
41
+ export const CALL_DISPLAY_ENV = Object.freeze(["CARGO_TERM_COLOR", "NO_COLOR", "TERM", "__CF_USER_TEXT_ENCODING"]);
42
+
43
+ /** The names the broker forwarded for `job`, from its signed receipt (`environment.forwarded`); null when the receipt does not say. */
44
+ export function forwardedOf(job, { readFile = (f) => fs.readFileSync(f, "utf8") } = {}) {
45
+ try { const f = JSON.parse(readFile(job.receipt)).environment?.forwarded; return Array.isArray(f) && f.every((n) => typeof n === "string") ? f : null; } catch { return null; }
46
+ }
47
+ /**
48
+ * Whether the output the client handed back for `job` is all of it. The broker drops the middle of a large job's output and says how much in its
49
+ * receipt (`outputDroppedBytes`). The job log the receipt names (`diagnosticsPath`) is written before anything is dropped, but it is usable as the
50
+ * whole output only when the receipt shows it is complete and it can be read as Cargo's records (rustright-broker job.rs, read 2026-11-17):
51
+ * - `output.log.truncated` is false (the log has its own cap), `output.log.bytes` equals `output.bytes`, and the file holds at least that many
52
+ * bytes; only the first `output.log.bytes` bytes are read (late output is appended after them);
53
+ * - the log holds stdout and stderr interleaved chunk by chunk with no tag, so a Cargo record can have other text written into it. A line that
54
+ * carries the start of a record and is not valid JSON means records cannot be trusted from this log: it is not repaired, it is refused.
55
+ * A newer broker also keeps the first stream alone (`output.stdout.log`); that file is preferred and needs no such refusal (see below).
56
+ * Returns { dropped: <bytes, 0 when none, null when the receipt does not say>, full: <the whole output, or null>, why: <why there is no full output> }.
57
+ */
58
+ export function fullOutputOf(job, { readFile = (f) => fs.readFileSync(f, "utf8"), readBytes = (f) => fs.readFileSync(f) } = {}) {
59
+ let receipt; try { receipt = JSON.parse(readFile(job.receipt)); } catch { return { dropped: null, full: null, why: "the receipt cannot be read" }; }
60
+ const dropped = Number.isSafeInteger(receipt?.outputDroppedBytes) && receipt.outputDroppedBytes >= 0 ? receipt.outputDroppedBytes : null;
61
+ if (!dropped) return { dropped, full: null, why: null };
62
+ const no = (why) => ({ dropped, full: null, why });
63
+ // A broker that keeps a log of the first output stream alone says so in `output.stdout` (rustright GB-100). That file holds Cargo's records whole
64
+ // and in order, so no record can have other text in it. When the receipt has `output.stdout` it is the only log used: whole, or the result is unknown.
65
+ const so = receipt.output?.stdout;
66
+ if (so !== undefined && so !== null) {
67
+ const sl = so.log;
68
+ if (!sl || typeof sl.path !== "string" || !sl.path) return no("the broker kept no log of the build's own output stream");
69
+ if (sl.truncated !== false) return no("the log of the build's own output stream was cut at its size limit");
70
+ if (!Number.isSafeInteger(sl.bytes) || sl.bytes !== so.bytes) return no("the log of the build's own output stream does not hold every byte of it");
71
+ let sb; try { sb = readBytes(sl.path); } catch { return no("the log of the build's own output stream cannot be read (logs are removed after 7 days)"); }
72
+ if (sb.length < sl.bytes) return no("the log of the build's own output stream is shorter on disk than the receipt says");
73
+ return { dropped, full: Buffer.from(sb).subarray(0, sl.bytes).toString("utf8"), why: null };
74
+ }
75
+ const log = receipt.output?.log;
76
+ if (typeof receipt.diagnosticsPath !== "string" || !receipt.diagnosticsPath || !log) return no("the receipt names no job log");
77
+ if (log.truncated !== false) return no("the job log was itself cut at its size limit");
78
+ if (!Number.isSafeInteger(log.bytes) || log.bytes !== receipt.output?.bytes) return no("the job log does not hold every byte the job wrote");
79
+ let bytes; try { bytes = readBytes(receipt.diagnosticsPath); } catch { return no("the job log cannot be read (logs are removed after 7 days)"); }
80
+ if (bytes.length < log.bytes) return no("the job log on disk is shorter than the receipt says");
81
+ const full = Buffer.from(bytes).subarray(0, log.bytes).toString("utf8");
82
+ for (const raw of full.split(/\r?\n/)) {
83
+ if (!raw.includes('{"reason":')) continue;
84
+ try { JSON.parse(raw.trim()); } catch { return no("the job log has other output written into one of Cargo's records (the log mixes both output streams)"); }
85
+ }
86
+ return { dropped, full, why: null };
87
+ }
88
+
89
+ /** The build of the broker that ran `job`, from the signed part of its receipt (`provenance.payload.broker.brokerDigest`); null when the receipt does not say. */
90
+ export function signedBrokerOf(job, { readFile = (f) => fs.readFileSync(f, "utf8") } = {}) {
91
+ try { const d = JSON.parse(readFile(job.receipt)).provenance?.payload?.broker?.brokerDigest; return typeof d === "string" && d ? d : null; } catch { return null; }
92
+ }
93
+ /** Why a passed job must not be remembered, or null. Fails closed: no statement of what was forwarded is a reason. */
94
+ export function unrememberable(forwarded) {
95
+ if (!Array.isArray(forwarded)) return "its receipt does not say which environment variables the broker forwarded";
96
+ const odd = forwarded.filter((n) => !CALL_KEY_ENV.includes(n) && !CALL_DISPLAY_ENV.includes(n));
97
+ return odd.length ? `the broker forwarded ${odd.slice(0, 6).join(", ")}${odd.length > 6 ? `, +${odd.length - 6} more` : ""}, which the remembered-call key does not carry` : null;
98
+ }
99
+
100
+ /** The skip key of a call. `identity`: { commit, toolchain, host, broker, gate } (every field a string; a missing one refuses the run). `env`: the environment the call is sent with. */
101
+ export function callKey(call, identity, env = {}) {
102
+ for (const field of ["commit", "toolchain", "host", "broker", "gate"]) {
103
+ if (typeof identity?.[field] !== "string" || !identity[field]) throw new TypeError(`callKey: identity.${field} is missing; a call cannot be remembered without it`);
104
+ }
105
+ return sha256(JSON.stringify({ v: 2, commit: identity.commit, toolchain: identity.toolchain, host: identity.host, broker: identity.broker, gate: identity.gate, cwd: call.cwd ?? ".", args: call.args, env: CALL_KEY_ENV.map((n) => [n, typeof env?.[n] === "string" ? env[n] : null]) }));
106
+ }
107
+
108
+ /** A store of passed calls: one small JSON file per key under `dir`. Only a call whose every crate passed is ever written. */
109
+ export function fileStore(dir) {
110
+ const file = (key) => path.join(dir, `${key}.json`);
111
+ return {
112
+ get(key) { try { const v = JSON.parse(fs.readFileSync(file(key), "utf8")); return v?.schema === "rightkit.gate-call/1" && v.key === key ? v : null; } catch { return null; } },
113
+ put(key, record) {
114
+ fs.mkdirSync(dir, { recursive: true });
115
+ const tmp = `${file(key)}.${process.pid}.tmp`;
116
+ fs.writeFileSync(tmp, `${JSON.stringify({ schema: "rightkit.gate-call/1", key, ...record }, null, 1)}\n`);
117
+ fs.renameSync(tmp, file(key));
118
+ },
119
+ };
120
+ }
121
+
122
+ const refusalOf = (sent) => (sent.refusal && sent.refusal.code !== "EXIT" ? sent.refusal : null);
123
+ const allPassed = (results) => results.length > 0 && results.every((r) => r.result === "passed");
124
+ const jobOf = (sent) => ({ exit: sent.status ?? null, requestId: sent.requestId ?? null, receipt: sent.receipt ?? null, receiptSha256: sent.receiptSha256 ?? null });
125
+
126
+ /**
127
+ * Runs `calls` in order.
128
+ * `send(call)`: sends one call and returns { status, stdout, stderr, requestId?, receipt?, receiptSha256?, refusal?: { code, message } }
129
+ * (seam-broker.mjs runSeamCargoCall's `result` on the Mac and the Dell; the direct wrapper on Linux).
130
+ * `store`: fileStore(dir) or null (nothing remembered). `identity`: see callKey. `hostTriple`: this host's target.
131
+ * `output(job)`: see fullOutputOf. When the broker dropped part of a job's output, the crates are judged from the whole job log; when that log
132
+ * cannot be read, no crate is passed or called not built from the partial stream (a crate with an error that was seen still failed).
133
+ * `signedBroker(job)`: see signedBrokerOf. A pass is remembered only when the job's signed receipt names the broker build the key names.
134
+ * `env`: the environment `send` sends a call with, or a function (call) => that environment when calls differ (a doc call carries RUSTDOCFLAGS).
135
+ * Its CALL_KEY_ENV values are in the key, read before the store is looked up. `forwarded(job)`: see forwardedOf.
136
+ * Returns { outcomes: [{ call, state: "skipped"|"ran", results, jobs, evidence, notRemembered? }], counts: { calls, ran, skipped, jobs, greenReruns, notRemembered } }.
137
+ * `evidence` is the job that proves each passed crate: for a clean call its one job, after a green rerun the second job.
138
+ */
139
+ export function runCalls({ calls, send, store = null, identity, hostTriple, onCall = () => {}, env = {}, forwarded = forwardedOf, output = fullOutputOf, signedBroker = signedBrokerOf }) {
140
+ const outcomes = [];
141
+ const counts = { calls: calls.length, ran: 0, skipped: 0, jobs: 0, greenReruns: 0, notRemembered: 0 };
142
+ const envOf = (which) => (typeof env === "function" ? env(which) : env);
143
+ let brokerChanged = false;
144
+ // Remembers a passed job, unless its receipt shows the key is too narrow for what the broker forwarded. Returns the reason it was not remembered, or null.
145
+ const remember = (which, job) => {
146
+ if (!store) return null;
147
+ // The key names a broker build; the pass is filed under it only when the job's own signed receipt says that build ran it.
148
+ const ranBy = signedBroker(job, identity);
149
+ if (ranBy !== identity.broker) { counts.notRemembered += 1; brokerChanged = true; return `its receipt says broker ${ranBy ?? "(not stated)"} ran it, the key names ${identity.broker}`; }
150
+ const why = unrememberable(forwarded(job));
151
+ if (why) { counts.notRemembered += 1; return why; }
152
+ store.put(callKey(which, identity, envOf(which)), { call: { id: which.id, cwd: which.cwd ?? ".", args: which.args }, job, crates: which.crates.map((c) => c.name) });
153
+ return null;
154
+ };
155
+ const judge = (call, sent0) => {
156
+ // The stream the client handed back may have a hole in it. Judge from the whole job log, or say plainly that the result is not known.
157
+ let sent = sent0; let hole = null;
158
+ if (sent0.receipt) {
159
+ const o = output(jobOf(sent0));
160
+ if (o.dropped > 0 && typeof o.full === "string") sent = { ...sent0, stdout: o.full };
161
+ else if (o.dropped > 0) hole = `the broker dropped ${o.dropped} bytes of this job's output and its log cannot stand in for it (${o.why}); this crate's result is not known`;
162
+ }
163
+ const judged = judgeWhole(call, sent);
164
+ return hole ? judged.map((r) => (r.result === "failed" ? r : { crate: r.crate, result: "unknown", detail: hole })) : judged;
165
+ };
166
+ const judgeWhole = (call, sent) => {
167
+ // The seam marks every non-passing call with a code. "EXIT" means Cargo ran and exited non-zero: that is a build result to read, not a refusal
168
+ // (Dell planted-failure run, 2026-11-10: treating it as a refusal made every crate of a red call unknown and sent no green rerun).
169
+ const refusal = refusalOf(sent) ? `${sent.refusal.code}: ${sent.refusal.message}` : null;
170
+ if (call.consumer) {
171
+ // A consumer manifest's own package is not one of the named crates: the call is judged whole. It passes for every crate that declares it
172
+ // only when Cargo finished successfully and the job exited 0; any failure in it fails them all, with the errors it reported.
173
+ if (refusal) return call.crates.map((c) => ({ crate: c.name, result: "unknown", detail: refusal }));
174
+ const s = readCargoStream({ stdout: sent.stdout ?? "", stderr: sent.stderr ?? "", targets: [hostTriple], host: hostTriple });
175
+ const ok = s.finished && s.success === true && sent.status === 0;
176
+ const why = ok ? "" : Object.entries(s.errors).slice(0, 4).map(([name, e]) => `${name}: ${e.rendered[0] ?? "error"}`).join(" | ") || (s.finished ? `the consumer call exited ${sent.status}` : "the consumer call produced no complete Cargo output");
177
+ return call.crates.map((c) => ({ crate: c.name, result: ok ? "passed" : s.finished ? "failed" : "unknown", detail: why }));
178
+ }
179
+ return crateResults({ crates: call.crates, stdout: sent.stdout ?? "", stderr: sent.stderr ?? "", exit: sent.status ?? null, refusal, host: hostTriple });
180
+ };
181
+ for (const call of calls) {
182
+ const key = callKey(call, identity, envOf(call));
183
+ const remembered = store?.get(key) ?? null;
184
+ let notRemembered = null; brokerChanged = false;
185
+ if (remembered) {
186
+ counts.skipped += 1;
187
+ const outcome = { call, state: "skipped", results: call.crates.map((c) => ({ crate: c.name, result: "passed", detail: "" })), jobs: [], evidence: remembered.job };
188
+ outcomes.push(outcome); onCall(outcome); continue;
189
+ }
190
+ counts.ran += 1; counts.jobs += 1;
191
+ const first = send(call);
192
+ let results = judge(call, first);
193
+ const jobs = [jobOf(first)];
194
+ let evidence = null;
195
+ // A job that exited 0 with every crate passed is its own evidence, and the only kind that is remembered.
196
+ if (allPassed(results) && first.status === 0 && !refusalOf(first)) {
197
+ evidence = jobs[0];
198
+ notRemembered = remember(call, evidence);
199
+ } else {
200
+ const green = results.filter((r) => r.result === "passed").map((r) => r.crate);
201
+ const reduced = green.length ? restrictCall(call, green) : null;
202
+ if (reduced && reduced !== call && reduced.crates.length < call.crates.length) {
203
+ counts.jobs += 1; counts.greenReruns += 1;
204
+ const second = send(reduced);
205
+ const again = judge(reduced, second);
206
+ jobs.push(jobOf(second));
207
+ const proven = allPassed(again) && second.status === 0 && !refusalOf(second);
208
+ if (proven) {
209
+ evidence = jobs[1];
210
+ notRemembered = remember(reduced, evidence);
211
+ } else {
212
+ // The crates looked green in the first call but the call naming only them did not pass: nothing is proven for them.
213
+ const byName = new Map(again.map((r) => [r.crate, r]));
214
+ results = results.map((r) => (r.result !== "passed" ? r : byName.get(r.crate)?.result === "passed" ? { crate: r.crate, result: "unknown", detail: "passed in the together call, but the call naming only the passing crates did not exit 0" } : byName.get(r.crate) ?? r));
215
+ }
216
+ } else if (green.length) {
217
+ // Every crate passed by its artifacts yet the job did not exit 0, or the call cannot be reduced: no signed evidence, so no pass.
218
+ results = results.map((r) => (r.result === "passed" ? { crate: r.crate, result: "unknown", detail: `the job exited ${first.status} with no failure attributed to a crate; nothing is proven` } : r));
219
+ }
220
+ }
221
+ const outcome = { call, state: "ran", results, jobs, evidence, ...(notRemembered ? { notRemembered } : {}), ...(brokerChanged ? { brokerChanged: true } : {}) };
222
+ outcomes.push(outcome); onCall(outcome);
223
+ }
224
+ return { outcomes, counts };
225
+ }
226
+
227
+ /** Every selected crate's result per stage over the whole run: { crate: { lint, "test-build", docs } }, each { result, detail, evidence: [job...] }. */
228
+ export function resultsByCrate(outcomes) {
229
+ const out = {};
230
+ const rank = { failed: 3, "not-built": 2, unknown: 1, passed: 0 };
231
+ for (const o of outcomes) {
232
+ for (const r of o.results) {
233
+ const per = (out[r.crate] ??= {});
234
+ const cur = (per[o.call.stage] ??= { result: "passed", detail: "", evidence: [], calls: [] });
235
+ cur.calls.push({ id: o.call.id, result: r.result });
236
+ if (rank[r.result] > rank[cur.result]) { cur.result = r.result; cur.detail = r.detail; }
237
+ if (r.result === "passed" && o.evidence) cur.evidence.push({ call: o.call.id, ...o.evidence });
238
+ }
239
+ }
240
+ return out;
241
+ }