@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
package/gate-seam.mjs CHANGED
@@ -15,6 +15,42 @@ import path from "node:path";
15
15
  export const CLASS_A_VERDICT_SCHEMA = "rightkit.class-a-verdict/1";
16
16
  export const GATE_COMMIT_ENV = "RUSTRIGHT_GATE_COMMIT";
17
17
  export const CLASS_A_ENV = "RUSTRIGHT_CLASS_A";
18
+
19
+ // ---- a contract-test run tags its broker jobs (loop matrix G26; rustright GB-101) -----------------------------------------------------------------
20
+ // The contract test (the retired gate-acceptance.mjs; the twelve-line launcher acceptance-launch.mjs does not use these) launches the gate with these four variables. Every broker job the gate then sends carries a nonce the
21
+ // broker signs into the job's receipt, computed from the run, the gate under test, the test step and a random value per call:
22
+ // nonce = sha256( UTF-8 of runId + "\n" + sealedSha256 + "\n" + step + "\n" + call ), lowercase hex.
23
+ // A verifier that holds the contract receipt (which lists runId, sealedSha256 and, per job, step and call) recomputes it and requires it to be
24
+ // the nonce the broker signed, so a job receipt from another run or for another gate cannot be passed off as this run's. The names start with
25
+ // RK_GATE_ so that no cache key takes them in (deterministic-scans.mjs BUILD_ENV_EXCLUDED): a tagged run hits the same cache as an untagged one.
26
+ export const CONTRACT_RUN_ID_ENV = "RK_GATE_CONTRACT_RUN_ID"; // 64 lowercase hex, fresh per contract-test run
27
+ export const CONTRACT_SEALED_ENV = "RK_GATE_CONTRACT_SEALED"; // 64 lowercase hex: the sealed gate under test
28
+ export const CONTRACT_STEP_ENV = "RK_GATE_CONTRACT_STEP"; // the step label of this gate launch
29
+ export const CONTRACT_JOBS_ENV = "RK_GATE_CONTRACT_JOBS"; // absolute path of the file each tagged job is appended to, one JSON line each
30
+ export const RECEIPT_NONCE_ENV = "RUSTRIGHT_RECEIPT_NONCE"; // what the broker client reads and the broker signs (GB-101)
31
+ const HEX64 = /^[0-9a-f]{64}$/; const STEP = /^[A-Za-z0-9][A-Za-z0-9:._-]{0,63}$/;
32
+ /** The nonce of one job of a contract-test run; the single definition both the gate and every verifier use. */
33
+ export function contractJobNonce({ runId, sealedSha256, step, call }) {
34
+ if (typeof runId !== "string" || !HEX64.test(runId) || typeof sealedSha256 !== "string" || !HEX64.test(sealedSha256) || typeof step !== "string" || !STEP.test(step) || typeof call !== "string" || !/^[0-9a-f]{32}$/.test(call)) throw new TypeError("contractJobNonce: runId and sealedSha256 are 64 hex, step is a label, call is 32 hex");
35
+ return crypto.createHash("sha256").update(Buffer.from([runId, sealedSha256, step, call].join("\n"), "utf8")).digest("hex");
36
+ }
37
+ /**
38
+ * The tag for the next broker job when `env` is a contract-test run's: { runId, sealedSha256, step, call, nonce, jobsFile }. null when the run id is
39
+ * not set (an ordinary gate run: nothing changes). A run id with any of the other three missing or malformed throws: a contract-test run never
40
+ * sends an untagged job.
41
+ */
42
+ export function contractJobTag(env, { random = () => crypto.randomBytes(16).toString("hex") } = {}) {
43
+ const runId = env?.[CONTRACT_RUN_ID_ENV];
44
+ if (runId === undefined || runId === "") return null;
45
+ const sealedSha256 = env[CONTRACT_SEALED_ENV]; const step = env[CONTRACT_STEP_ENV]; const jobsFile = env[CONTRACT_JOBS_ENV];
46
+ if (!HEX64.test(String(runId)) || !HEX64.test(String(sealedSha256)) || typeof step !== "string" || !STEP.test(step) || typeof jobsFile !== "string" || !path.isAbsolute(jobsFile)) throw new Error(`a contract-test run must name its run id, the sealed gate, the step and an absolute jobs file (${CONTRACT_RUN_ID_ENV}, ${CONTRACT_SEALED_ENV}, ${CONTRACT_STEP_ENV}, ${CONTRACT_JOBS_ENV})`);
47
+ const call = random();
48
+ return { runId, sealedSha256, step, call, nonce: contractJobNonce({ runId, sealedSha256, step, call }), jobsFile };
49
+ }
50
+ /** Files one tagged job for the contract test to list: appended as one JSON line. `sent` is what was sent (argv, cwd); `outcome` what came back. */
51
+ export function recordContractJob(tag, { argv, cwd, requestId = null, receipt = null, receiptSha256 = null, status = null }, { fsApi = fs } = {}) {
52
+ fsApi.appendFileSync(tag.jobsFile, `${JSON.stringify({ schema: "rightkit.contract-job/1", step: tag.step, call: tag.call, nonce: tag.nonce, argv, cwd, requestId, receipt, receiptSha256, status })}\n`);
53
+ }
18
54
  export const RESULT_LINE_PREFIX = "rustright-result ";
19
55
  /** The exit the client reports when nothing was executed (a refusal, a client failure); an executed command keeps its own exit. */
20
56
  export const NOT_EXECUTED_EXIT = 125;
@@ -153,12 +189,53 @@ export function parseResultLine(stderr) {
153
189
  if (!nullableString(r.outputDir) || (typeof r.outputDir === "string" && !path.isAbsolute(r.outputDir))) bad.push("outputDir");
154
190
  if (!nullableString(r.receipt) || (typeof r.receipt === "string" && !path.isAbsolute(r.receipt))) bad.push("receipt");
155
191
  if (typeof r.receiptPersisted !== "boolean") bad.push("receiptPersisted");
156
- if (r.code !== undefined && (typeof r.code !== "string" || !/^[A-Z]{2,3}_[A-Z0-9_]+$/.test(r.code))) bad.push("code"); // RK_ today; any short upper-case prefix the broker documents
192
+ if (r.code !== undefined && (typeof r.code !== "string" || !BROKER_CODE.test(r.code))) bad.push("code");
157
193
  if (r.message !== undefined && typeof r.message !== "string") bad.push("message");
158
194
  if (bad.length) throw new SeamError("BAD_RESULT_LINE", `the rustright-result line has invalid field(s): ${bad.join(", ")}`);
159
195
  return r;
160
196
  }
161
197
 
198
+ /**
199
+ * A code as the broker writes one: upper-case words joined by underscores (RK_SNAPSHOT_LOCK, CACHE_ADMISSION_BLOCKED, TOOL_CHANGED). The
200
+ * earlier pattern allowed a two or three letter first word only, so a result line carrying either of the last two was rejected whole.
201
+ */
202
+ export const BROKER_CODE = /^[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+$/;
203
+
204
+ /**
205
+ * What the broker recorded about a job, from the receipt fields its producer writes (rustright finish_impl.rs): `status`, `reason`,
206
+ * `error`, `code`, `postChecks.failed` and `reap`. Returns { status, reason, error, code, failed, unreaped, reap }; every field is null,
207
+ * empty or false when the receipt does not carry it. `code` is the receipt's own code, or its reason when the reason is a code (a job
208
+ * refused after admission carries its code only there: service.rs Details::rejected).
209
+ */
210
+ export function brokerVerdict(receipt) {
211
+ const text = (v) => (typeof v === "string" && v.trim() ? v.split(/\r?\n/).join(" ").trim().slice(0, 600) : null);
212
+ const reap = receipt?.reap && typeof receipt.reap === "object" ? receipt.reap : null;
213
+ const reason = text(receipt?.reason);
214
+ const own = text(receipt?.code);
215
+ return {
216
+ status: text(receipt?.status), reason, error: text(receipt?.error),
217
+ code: own && BROKER_CODE.test(own) ? own : reason && BROKER_CODE.test(reason) ? reason : null,
218
+ failed: Array.isArray(receipt?.postChecks?.failed) ? receipt.postChecks.failed.filter((x) => typeof x === "string") : [],
219
+ unreaped: reap?.reaped === false, reap,
220
+ };
221
+ }
222
+
223
+ const ENDED_BY_BROKER = new Set(["CANCELLED", "TIMED_OUT", "REJECTED"]);
224
+ const brokerWords = (v) => [v.error, v.reason && v.reason !== v.error ? `reason ${v.reason}` : null].filter(Boolean).join("; ");
225
+
226
+ /**
227
+ * Why `gate.snapshotUnchanged` is not true, in the broker's own terms. The broker clears that flag in three cases and only one of them is
228
+ * a changed snapshot: it could not prove the job's process tree stopped (so it did not look), it ended the job itself (cancelled, timed
229
+ * out, rejected), or the tree really differs. The gate used to say "the snapshot changed" for all three (Mac, 2026-11-17: a failed process
230
+ * listing after a compile that exited 0 was reported that way for 1,232 rows).
231
+ */
232
+ export function snapshotNotConfirmed(receipt) {
233
+ const v = brokerVerdict(receipt); const said = brokerWords(v);
234
+ if (v.unreaped) return { code: "RK_PROCESS_REAP_PENDING", detail: `the broker could not prove the job's process tree stopped (reap ${typeof v.reap.status === "string" ? v.reap.status : "not complete"}${typeof v.reap.reason === "string" && v.reap.reason ? `: ${v.reap.reason}` : ""}), so it did not verify the snapshot; nothing here says the snapshot changed${said ? ` (broker: ${said})` : ""}` };
235
+ if (ENDED_BY_BROKER.has(v.status)) return { code: v.code ?? `RK_JOB_${v.status}`, detail: `the broker ended the job ${v.status}${said ? ` (${said})` : ""} and did not verify the snapshot` };
236
+ return { code: "RK_SNAPSHOT_CHANGED", detail: `the broker found the snapshot changed during the job${said ? ` (broker: ${said})` : ""}` };
237
+ }
238
+
162
239
  /**
163
240
  * The receipt the result line names, read directly, with its postconditions judged against this request: `gate.commit`, `gate.tree`
164
241
  * and `gate.classA` must be this run's, `gate.snapshotUnchanged` must be true. Returns { receipt, sha256, problems }.
@@ -176,7 +253,7 @@ export function readSeamReceipt(file, { commit, tree, classA = null, expect = nu
176
253
  // `tree: null` means the caller does not know the tree (a stage child that has only the commit): the commit binding stands, the tree is not compared.
177
254
  if (tree !== null && g.tree !== tree) problems.push(`receipt gate.tree ${JSON.stringify(g.tree)} is not this run's ${tree}`);
178
255
  if (classA !== null && !samePath(g.classA, classA)) problems.push(`receipt gate.classA ${JSON.stringify(g.classA)} is not the verdict this request named`);
179
- if (g.snapshotUnchanged !== true) problems.push("the broker found the snapshot changed during the job (gate.snapshotUnchanged is not true)");
256
+ if (g.snapshotUnchanged !== true) problems.push(`${snapshotNotConfirmed(receipt).detail} (gate.snapshotUnchanged is not true)`);
180
257
  }
181
258
  if (receipt && Object.hasOwn(receipt, "testExecutables") && receipt.testExecutables !== null && !Array.isArray(receipt.testExecutables)) problems.push("receipt testExecutables is neither a list nor null");
182
259
  // The request the broker admitted, from the fields its producer already writes (provenance.payload: jobId and request.{requestedArgv, workspace, adapter}; no second copy
@@ -206,7 +283,22 @@ export function readSeamReceipt(file, { commit, tree, classA = null, expect = nu
206
283
  export function judgeSeamOutcome({ child, stderr, commit, tree, classA = null, expect = null, fsApi = fs }) {
207
284
  let result;
208
285
  try { result = parseResultLine(stderr); } catch (e) { return { status: "fail", code: e.code, detail: e.message, result: null, evidence: null }; }
209
- if (result.code) return { status: "fail", code: result.code, detail: result.requestId === null ? `the broker refused or the client failed before anything was admitted: ${result.message ?? result.code}` : `the client failed after request ${result.requestId} was admitted (${result.message ?? result.code}); the job's state in the broker is unknown`, result, evidence: null };
286
+ if (result.code) {
287
+ if (result.requestId === null) return { status: "fail", code: result.code, detail: `the broker refused or the client failed before anything was admitted: ${result.message ?? result.code}`, result, evidence: null };
288
+ // Admitted, then ended without an executed command. The client puts a code on the line only when the terminal event or the receipt has a
289
+ // `code` field, and falls back to RK_CLIENT_ERROR otherwise (rustright-cli cli.rs gate_result); the broker writes the code of a job it
290
+ // refused after admission into the receipt's `reason`. So the receipt is read here: it names the real code, and when it is the terminal
291
+ // record of this request the job is over and the caller may release what it holds.
292
+ if (result.receiptPersisted && typeof result.receipt === "string") {
293
+ const named = readSeamReceipt(result.receipt, { commit, tree: null, fsApi });
294
+ if (named.receipt) {
295
+ const v = brokerVerdict(named.receipt); const said = brokerWords(v);
296
+ const receiptRead = receiptIsTerminalFor(named.receipt, result.requestId) && receiptProvesTreeGone(named.receipt);
297
+ return { status: "fail", code: v.code ?? result.code, detail: `the broker ended request ${result.requestId}${v.status ? ` ${v.status}` : ""} without running the command: ${said || (result.message ?? result.code)}`, result, evidence: null, receiptRead };
298
+ }
299
+ }
300
+ return { status: "fail", code: result.code, detail: `the client failed after request ${result.requestId} was admitted (${result.message ?? result.code}); the job's state in the broker is unknown`, result, evidence: null };
301
+ }
210
302
  if (result.exit === NOT_EXECUTED_EXIT && result.requestId === null) return { status: "fail", code: "RK_NOT_EXECUTED", detail: "the client reported exit 125 with no request admitted and no code", result, evidence: null };
211
303
  // A client the gate killed (its own timeout, a cancel) proves nothing whatever its line says: the line may predate the kill or belong to a job the broker went on to cancel.
212
304
  if (child && typeof child.signal === "string" && child.signal) return { status: "fail", code: "CLIENT_KILLED", detail: `the client was stopped by ${child.signal} before the row completed`, result, evidence: null };
@@ -215,8 +307,12 @@ export function judgeSeamOutcome({ child, stderr, commit, tree, classA = null, e
215
307
  // `receiptRead`: the receipt is the terminal record of THIS request's job (receiptIsTerminalFor): then the job is over even when its postconditions fail (the evidence
216
308
  // is withheld, the row is settled). A receipt that merely parses, or names another job, proves nothing about the job this client submitted.
217
309
  const receiptRead = receiptIsTerminalFor(read.receipt, result.requestId) && receiptProvesTreeGone(read.receipt);
218
- if (read.problems.length) return { status: "fail", code: read.receipt?.gate && read.receipt.gate.snapshotUnchanged === false ? "RK_SNAPSHOT_CHANGED" : "RECEIPT_MISMATCH", detail: read.problems.join("; "), result, evidence: null, receiptRead };
310
+ if (read.problems.length) return { status: "fail", code: read.receipt?.gate && read.receipt.gate.snapshotUnchanged === false ? snapshotNotConfirmed(read.receipt).code : "RECEIPT_MISMATCH", detail: read.problems.join("; "), result, evidence: null, receiptRead };
219
311
  const evidence = { receiptSha256: read.sha256, receiptPath: result.receipt, requestId: result.requestId, outputDir: result.outputDir, targetTriple: typeof read.receipt.targetTriple === "string" && read.receipt.targetTriple ? read.receipt.targetTriple : null, testExecutables: Array.isArray(read.receipt.testExecutables) ? read.receipt.testExecutables : null, testExecutablesReason: typeof read.receipt.testExecutablesReason === "string" ? read.receipt.testExecutablesReason : null, receiptStatus: typeof read.receipt.status === "string" ? read.receipt.status : null, gate: read.receipt.gate };
312
+ // A job the broker failed on a check of its own after the command exited (its toolchain identity, for one) keeps the command's exit in
313
+ // the receipt while the client exits 125. That is the broker's verdict, not a disagreement between the client and its line.
314
+ const post = brokerVerdict(read.receipt);
315
+ if (post.failed.length) return { status: "fail", code: post.code ?? "RK_BROKER_POST_CHECK", detail: `the broker failed the job on its own check(s) ${post.failed.join(", ")} after the command exited ${result.exit}${brokerWords(post) ? `: ${brokerWords(post)}` : ""}`, result, evidence: null, receiptRead };
220
316
  if (child && Number.isInteger(child.status) && result.exit !== null && child.status !== result.exit) return { status: "fail", code: "RESULT_EXIT_MISMATCH", detail: `the client exited ${child.status} but its result line says ${result.exit}`, result, evidence, receiptRead };
221
317
  if (result.exit !== 0 || result.signal) return { status: "fail", code: "EXIT", detail: result.signal ? `the command was stopped by signal ${result.signal}` : `exit ${result.exit}`, result, evidence, receiptRead };
222
318
  // An exit 0 is a pass only for a job the broker finished as SUCCEEDED: a job cancelled or timed out after its process exited 0 keeps that observed exit in its receipt
package/gate-serve.mjs CHANGED
@@ -22,29 +22,47 @@ import net from "node:net";
22
22
  import os from "node:os";
23
23
  import path from "node:path";
24
24
  import { spawn, spawnSync } from "node:child_process";
25
+ import { MessageChannel, Worker, receiveMessageOnPort } from "node:worker_threads";
25
26
  import { fileURLToPath } from "node:url";
26
27
  import { resolveManagedRoots } from "./managed-roots.mjs";
28
+ import { createChangeLedger } from "./snapshot-changes.mjs";
27
29
 
28
30
  const SELF = fileURLToPath(import.meta.url);
29
31
  const SCHEMA = "rightkit.gate-serve/1";
30
32
  const COOKIE_PREFIX = "0000000000000000.gate-serve-cookie-";
31
- // The server's identity covers every local module it runs (this file and managed-roots.mjs, its only local import), so a client never
33
+ // The server's identity covers every local module it runs (this file, managed-roots.mjs and snapshot-changes.mjs, its local imports), so a client never
32
34
  // takes answers from a server whose code differs from its own, e.g. one started from an edited checkout answering a sealed gate.
33
- const SERVER_MODULES = [SELF, fileURLToPath(new URL("./managed-roots.mjs", import.meta.url))];
35
+ /**
36
+ * NN28: the native change source the package ships for this platform (`bin/<platform>/rightkit-gate-watch`, built from RightKit's
37
+ * rightkit-file-watch and rightkit-fsindex crates; crates/rightkit-gate-watch), or null when this package has none for it.
38
+ */
39
+ export function changeHelperPath({ platform = process.platform, exists = fs.existsSync } = {}) {
40
+ const file = fileURLToPath(new URL(`./bin/${platform}/rightkit-gate-watch${platform === "win32" ? ".exe" : ""}`, import.meta.url));
41
+ return exists(file) ? file : null;
42
+ }
43
+ // The helper's bytes are part of the server's identity: another helper is another server.
44
+ const SERVER_MODULES = [SELF, fileURLToPath(new URL("./managed-roots.mjs", import.meta.url)), fileURLToPath(new URL("./snapshot-changes.mjs", import.meta.url)), ...(changeHelperPath() ? [changeHelperPath()] : [])];
34
45
  const IDENTITY = (() => { try { const h = crypto.createHash("sha256"); for (const f of SERVER_MODULES) { h.update(path.basename(f)); h.update("\0"); h.update(fs.readFileSync(f)); h.update("\0"); } return h.digest("hex").slice(0, 16); } catch { return "unknown"; } })();
35
46
 
36
47
  function dataRoot(env = process.env) { return resolveManagedRoots({ env, platform: process.platform }).gateRoot; }
37
48
  export function socketPath(env = process.env) {
38
- if (process.platform === "win32") return `\\\\.\\pipe\\rightkit-gate-serve-${(os.userInfo().username || "user").replace(/[^A-Za-z0-9_-]/g, "_")}`;
39
- return path.join(dataRoot(env), "gate-serve", "serve.sock");
49
+ // The name carries the server's code identity (Dell 2026-11-19): every gate of this user shared one name, and a server asked by a gate of
50
+ // other code exits ("gate code changed"). Two gates in use on one machine (a sealed gate and a candidate under test, or two agents' gates)
51
+ // therefore ended each other's server at every question, and each lost its proofs each time. Each gate code now has its own server.
52
+ if (process.platform === "win32") return `\\\\.\\pipe\\rightkit-gate-serve-${(os.userInfo().username || "user").replace(/[^A-Za-z0-9_-]/g, "_")}-${IDENTITY}`;
53
+ return path.join(dataRoot(env), "gate-serve", `serve-${IDENTITY.slice(0, 8)}.sock`); // a socket path is limited to about 104 characters
40
54
  }
41
55
 
42
56
  // ---- server ---------------------------------------------------------------------------------------------------------------------------
43
57
 
44
- export async function serve({ root, idleMs = Number(process.env.RK_GATE_SERVE_IDLE_MS ?? 30 * 60 * 1000), log = () => {} } = {}) {
58
+ /** `listenOn`: another socket than this gate code's own (a test's private one). */
59
+ export async function serve({ root, idleMs = Number(process.env.RK_GATE_SERVE_IDLE_MS ?? 30 * 60 * 1000), log = () => {}, listenOn = null, helper = (() => { const file = changeHelperPath(); return file ? { command: file, args: [] } : null; })() } = {}) {
45
60
  const watchedRoot = fs.realpathSync(root);
46
61
  const generation = new Map(); // snapshot key -> change count
47
62
  const proven = new Map(); // snapshot key -> { tree, generation }
63
+ // NN11: the tree a snapshot was last proven to hold, with every path that changed since (snapshot-changes.mjs). `proven` answers "nothing
64
+ // changed"; this answers "these paths changed", so a later proof checks those files and does not hash the whole tree again.
65
+ const treeBase = new Map(); // snapshot key -> { tree, ledger }
48
66
  // GC-A11 non-compiling cargo answers (cargo metadata), keyed on the request and the snapshot's change count: an unchanged snapshot is answered
49
67
  // from memory, any change to it (or a restart) runs cargo again. Bounded: oldest dropped past 64 entries.
50
68
  const cargoAnswers = new Map(); // request digest -> { key, generation, status, stdout, stderr }
@@ -53,25 +71,87 @@ export async function serve({ root, idleMs = Number(process.env.RK_GATE_SERVE_ID
53
71
  // Only entries inside a snapshot directory (`<16 hex>/...`) are snapshot content; `<key>.tree-index`, `<key>.state.json` and the like
54
72
  // beside it are the gate's own metadata, and the cookie is `0000000000000000.gate-serve-cookie-*` (a name the snapshot root accepts).
55
73
  const keyOf = (rel) => { const base = String(rel ?? "").split(/[\\/]/)[0]; return /^[0-9a-f]{16}$/.test(base) ? base : null; };
56
- const bumpAll = () => { for (const k of new Set([...generation.keys(), ...proven.keys()])) generation.set(k, (generation.get(k) ?? 0) + 1); proven.clear(); };
74
+ // The change count a proof is taken at and recorded against: the snapshot's own events plus `floor`, which rises whenever something may
75
+ // have changed anywhere without being named (an event without a name, a watcher error, dropped events, the helper ending). Review
76
+ // 2026-11-19: the count used to rise only for snapshots that already had an entry, so a snapshot with no event since this process started
77
+ // stayed at 0 through such a moment, and a proof begun before it was recorded after it.
78
+ let floor = 0;
79
+ const genOf = (key) => floor + (generation.get(key) ?? 0);
80
+ const bumpAll = () => { floor += 1; proven.clear(); treeBase.clear(); };
81
+ // One change under the watched root, from either source: "change" (content or metadata) or "rename" (appeared, disappeared, renamed).
82
+ const onEvent = (type, filename) => {
83
+ if (filename == null) { bumpAll(); return; } // an event without a name: anything may have changed
84
+ const name = String(filename);
85
+ const base = name.split(/[\\/]/)[0];
86
+ if (base.startsWith(COOKIE_PREFIX)) { const r = cookies.get(base); if (r) { cookies.delete(base); r(); } return; }
87
+ const key = keyOf(name);
88
+ // The watched root's own entry (its listing changed) carries no content: the entry that changed reports under its own name.
89
+ if (key === null) { if (/^[0-9a-f]{16}\./.test(base) || name === path.basename(watchedRoot)) return; bumpAll(); return; } // gate metadata beside a snapshot; anything else: drop every proof
90
+ generation.set(key, (generation.get(key) ?? 0) + 1);
91
+ proven.delete(key);
92
+ treeBase.get(key)?.ledger.touch(type, name.split(/[\\/]/).slice(1).join("/"));
93
+ };
94
+ // How this process learns of changes, as it reports it (NN28): the helper's own word, or Node's watcher.
95
+ let changeSource = helper ? "starting" : "node-fs-watch";
57
96
  const startWatch = () => {
58
97
  try {
59
- watcher = fs.watch(watchedRoot, { recursive: true, persistent: true }, (_event, filename) => {
60
- if (filename == null) { bumpAll(); return; } // an event without a name: anything may have changed
61
- const name = String(filename);
62
- const base = name.split(/[\\/]/)[0];
63
- if (base.startsWith(COOKIE_PREFIX)) { const r = cookies.get(base); if (r) { cookies.delete(base); r(); } return; }
64
- const key = keyOf(name);
65
- // The watched root's own entry (its listing changed) carries no content: the entry that changed reports under its own name.
66
- if (key === null) { if (/^[0-9a-f]{16}\./.test(base) || name === path.basename(watchedRoot)) return; bumpAll(); return; } // gate metadata beside a snapshot; anything else: drop every proof
67
- generation.set(key, (generation.get(key) ?? 0) + 1);
68
- proven.delete(key);
69
- });
98
+ watcher = fs.watch(watchedRoot, { recursive: true, persistent: true }, onEvent);
70
99
  watcher.on("error", (error) => { log(`watcher error: ${error?.message ?? error}; every proof dropped, restarting the watch`); healthy = false; bumpAll(); try { watcher.close(); } catch { /* closed */ } setTimeout(startWatch, 200); });
71
100
  healthy = true;
72
101
  } catch (error) { healthy = false; log(`cannot watch ${watchedRoot}: ${error?.message ?? error}`); setTimeout(startWatch, 1000); }
73
102
  };
74
- startWatch();
103
+ // NN28: the native helper (crates/rightkit-gate-watch) names each change from rightkit-file-watch and keeps a rightkit-fsindex listing of
104
+ // every snapshot this process holds a proof of. When events are dropped it lists those snapshots again and reports each difference as an
105
+ // ordinary change. So after an overflow no snapshot is answered "nothing changed" until it is proven again, but a listed snapshot keeps its
106
+ // record of what changed (the next proof walks it and compares those files; the tree is not hashed again). Of a snapshot the helper has
107
+ // not listed nothing is known then.
108
+ // It is this process's own child for as long as this process lives (it ends when its input closes); no gate run starts it.
109
+ let helperChild = null; let helperStarts = 0;
110
+ const helperListed = new Set(); const listWaiters = new Map();
111
+ // Events were dropped. No snapshot may be answered "nothing changed" on the strength of an earlier proof, and no proof begun before this
112
+ // moment may be recorded (the floor rises for all). What survives is the change record of a snapshot the helper has listed: the helper
113
+ // lists it again and reports every difference, so "these paths changed" stays true for it. Of any other snapshot nothing is known.
114
+ const dropUnlisted = () => { floor += 1; proven.clear(); for (const k of [...treeBase.keys()]) if (!helperListed.has(k)) treeBase.delete(k); };
115
+ const onHelper = (m) => {
116
+ if (!m || typeof m.t !== "string") return;
117
+ if (m.t === "ready") { healthy = true; changeSource = typeof m.source === "string" && m.source ? m.source : "fsindex,file-watch"; return; }
118
+ if (m.t === "change" || m.t === "rename") { if (typeof m.p === "string" && m.p) onEvent(m.t, m.p); return; }
119
+ if (m.t === "indexed") { if (typeof m.key === "string") { helperListed.add(m.key); for (const r of listWaiters.get(m.key) ?? []) r(true); listWaiters.delete(m.key); } return; }
120
+ if (m.t === "overflow") { dropUnlisted(); return; }
121
+ if (m.t === "error") log(`change helper: ${m.message}`);
122
+ };
123
+ const startHelper = () => {
124
+ helperStarts += 1;
125
+ let child;
126
+ try { child = spawn(helper.command, [...(helper.args ?? []), watchedRoot], { stdio: ["pipe", "pipe", "ignore"], windowsHide: true }); }
127
+ catch (error) { log(`cannot start the change helper: ${error?.message ?? error}; using Node's watcher`); changeSource = "node-fs-watch"; startWatch(); return; }
128
+ helperChild = child; let buf = "";
129
+ const lost = (why) => {
130
+ if (helperChild !== child) return;
131
+ helperChild = null; healthy = false; helperListed.clear();
132
+ for (const w of listWaiters.values()) for (const r of w) r(false);
133
+ listWaiters.clear(); bumpAll();
134
+ // A helper that keeps ending is not waited for: Node's watcher takes over, and the process says so (change-source=node-fs-watch).
135
+ if (helperStarts >= 3) { log(`change helper ended (${why}) ${helperStarts} times; every proof dropped; using Node's watcher`); changeSource = "node-fs-watch"; startWatch(); }
136
+ else { log(`change helper ended (${why}); every proof dropped; starting it again`); setTimeout(startHelper, 300); }
137
+ };
138
+ child.stdout.setEncoding("utf8");
139
+ child.stdout.on("data", (d) => { buf += d; for (let nl = buf.indexOf("\n"); nl >= 0; nl = buf.indexOf("\n")) { const text = buf.slice(0, nl); buf = buf.slice(nl + 1); let m = null; try { m = JSON.parse(text); } catch { m = null; } if (helperChild === child) onHelper(m); } });
140
+ child.stdin.on("error", () => {});
141
+ child.on("error", (error) => lost(error?.message ?? "error"));
142
+ child.on("exit", (code, signal) => lost(signal ? `signal ${signal}` : `exit ${code}`));
143
+ };
144
+ /** Resolves true once the helper holds a listing of snapshot `key` (at once with Node's watcher, which keeps none). */
145
+ const listed = (key) => {
146
+ if (!helperChild) return Promise.resolve(changeSource === "node-fs-watch");
147
+ if (helperListed.has(key)) return Promise.resolve(true);
148
+ return new Promise((resolve) => {
149
+ const waiting = listWaiters.get(key) ?? []; waiting.push(resolve); listWaiters.set(key, waiting);
150
+ if (waiting.length === 1) { try { helperChild.stdin.write(`${key}\n`); } catch { resolve(false); } }
151
+ setTimeout(() => resolve(false), 30_000).unref?.();
152
+ });
153
+ };
154
+ if (helper) startHelper(); else startWatch();
75
155
  // Every change made before this call has been delivered once the cookie's own event arrives (events of one watch are ordered).
76
156
  const cookieSync = (timeoutMs = 2000) => new Promise((resolve) => {
77
157
  if (!healthy) { resolve(false); return; }
@@ -82,30 +162,49 @@ export async function serve({ root, idleMs = Number(process.env.RK_GATE_SERVE_ID
82
162
  try { fs.writeFileSync(file, String(Date.now())); } catch { clearTimeout(timer); cookies.delete(name); resolve(false); }
83
163
  });
84
164
  let lastRequest = Date.now();
165
+ const answers = new Map(); const ANSWER_MAX_ENTRIES = 512; const ANSWER_MAX_BYTES = 1 << 20;
85
166
  const handle = async (req) => {
86
167
  lastRequest = Date.now();
87
168
  if (req?.schema !== SCHEMA) return { ok: false, why: "schema" };
88
169
  if (req.identity !== IDENTITY) { setTimeout(() => process.exit(0), 50); return { ok: false, why: "gate code changed; the server exits" }; }
89
- if (req.op === "status") return { ok: true, healthy, root: watchedRoot, proven: [...proven].map(([k, v]) => ({ key: k, tree: v.tree })), pid: process.pid, identity: IDENTITY };
170
+ if (req.op === "status") return { ok: true, healthy, changeSource, root: watchedRoot, proven: [...proven].map(([k, v]) => ({ key: k, tree: v.tree })), pid: process.pid, identity: IDENTITY };
171
+ // Answers kept for later runs (resident-answers.mjs): an opaque string under a sha256 key. The caller stores each answer with the files it
172
+ // depends on and checks them itself before it uses one; this process only holds the bytes, in memory, oldest out first.
173
+ if (req.op === "answer-get" || req.op === "answer-put") {
174
+ if (typeof req.key !== "string" || !/^[0-9a-f]{64}$/.test(req.key)) return { ok: false, why: "bad answer key" };
175
+ if (req.op === "answer-get") return { ok: true, value: answers.get(req.key) ?? null };
176
+ if (typeof req.value !== "string" || req.value.length > ANSWER_MAX_BYTES) return { ok: false, why: "bad answer value" };
177
+ answers.delete(req.key);
178
+ if (answers.size >= ANSWER_MAX_ENTRIES) answers.delete(answers.keys().next().value);
179
+ answers.set(req.key, req.value);
180
+ return { ok: true };
181
+ }
90
182
  const dir = typeof req.dir === "string" ? req.dir : "";
91
183
  let real; try { real = fs.realpathSync(dir); } catch { return { ok: false, why: "no such directory" }; }
92
184
  if (path.dirname(real) !== watchedRoot) return { ok: false, why: "not a snapshot of the watched root" };
93
185
  const key = keyOf(path.basename(real));
94
186
  if (key === null) return { ok: false, why: "not a snapshot directory name" };
95
187
  if (!(await cookieSync())) return { ok: false, why: "watcher not current" };
96
- if (req.op === "begin") return { ok: true, generation: generation.get(key) ?? 0 };
188
+ if (req.op === "begin") return { ok: true, generation: genOf(key), source: changeSource };
97
189
  if (req.op === "cargo-metadata") return cargoMetadataOp(req, key, real);
98
- if (req.op === "record") {
190
+ if (req.op === "record" || req.op === "tree-record") {
99
191
  if (typeof req.tree !== "string" || !Number.isInteger(req.generation)) return { ok: false, why: "bad record" };
100
- if ((generation.get(key) ?? 0) !== req.generation) return { ok: false, why: "changed during the proof" };
101
- proven.set(key, { tree: req.tree, generation: req.generation });
192
+ if (genOf(key) !== req.generation) return { ok: false, why: "changed during the proof" };
193
+ // With the helper, a proof is kept only for a snapshot it has listed (that listing is what an overflow is recovered from).
194
+ if (!(await listed(key))) return { ok: false, why: "the change helper has no listing of this snapshot" };
195
+ if (genOf(key) !== req.generation) return { ok: false, why: "changed during the proof" };
196
+ // "tree-record": the commit's files are this tree (a proof that admitted stage outputs beside them). "record": that, and nothing else is there.
197
+ if (req.op === "record") proven.set(key, { tree: req.tree, generation: req.generation });
198
+ treeBase.set(key, { tree: req.tree, ledger: createChangeLedger() });
102
199
  return { ok: true };
103
200
  }
104
201
  if (req.op === "check") {
105
202
  const p = proven.get(key);
106
- const now = generation.get(key) ?? 0;
203
+ const now = genOf(key);
107
204
  const clean = Boolean(p && p.tree === req.tree && p.generation === now);
108
- return { ok: true, clean, generation: now };
205
+ // `base`: the tree last proven here and what changed since, when that is known; absent otherwise (the caller hashes the tree).
206
+ const tb = treeBase.get(key); const changes = tb && tb.tree === req.tree ? tb.ledger.list() : null;
207
+ return { ok: true, clean, generation: now, source: changeSource, ...(changes ? { base: { tree: tb.tree, ...changes } } : {}) };
109
208
  }
110
209
  return { ok: false, why: "unknown op" };
111
210
  };
@@ -119,7 +218,7 @@ export async function serve({ root, idleMs = Number(process.env.RK_GATE_SERVE_ID
119
218
  let cargoId; try { const st = fs.statSync(req.cargo); cargoId = `${st.size}:${st.mtimeMs}:${st.ino}`; } catch { return { ok: false, why: "no such cargo" }; }
120
219
  const digest = crypto.createHash("sha256").update(JSON.stringify({ key, cwd, args, cargo: req.cargo, cargoId, env: Object.entries(env).sort() })).digest("hex");
121
220
  const hit = cargoAnswers.get(digest);
122
- const now = generation.get(key) ?? 0;
221
+ const now = genOf(key);
123
222
  if (hit && hit.generation === now) return { ok: true, cached: true, status: hit.status, stdout: hit.stdout, stderr: hit.stderr };
124
223
  const before = now;
125
224
  const result = await new Promise((resolve) => {
@@ -130,13 +229,13 @@ export async function serve({ root, idleMs = Number(process.env.RK_GATE_SERVE_ID
130
229
  child.on("close", (status) => resolve({ status: status ?? -1, stdout: Buffer.concat(out).toString("utf8"), stderr: Buffer.concat(err).toString("utf8") }));
131
230
  });
132
231
  // Cached only when cargo succeeded and nothing in the snapshot changed while it ran (the cookie makes every earlier event visible first).
133
- if (result.status === 0 && (await cookieSync()) && (generation.get(key) ?? 0) === before) {
232
+ if (result.status === 0 && (await cookieSync()) && genOf(key) === before) {
134
233
  cargoAnswers.set(digest, { key, generation: before, ...result });
135
234
  while (cargoAnswers.size > 64) cargoAnswers.delete(cargoAnswers.keys().next().value);
136
235
  }
137
236
  return { ok: true, cached: false, ...result };
138
237
  }
139
- const sock = socketPath();
238
+ const sock = listenOn ?? socketPath();
140
239
  // One server per host: a second one started in the same instant must not steal the socket from a live first one (seen 2026-11-05).
141
240
  const live = await new Promise((resolve) => { const c = net.connect(sock); c.on("connect", () => { c.destroy(); resolve(true); }); c.on("error", () => resolve(false)); });
142
241
  if (live) { log("another server already answers on the socket; exiting"); process.exit(0); }
@@ -180,17 +279,62 @@ async function ask(req, timeoutMs) {
180
279
  });
181
280
  }
182
281
 
282
+ // The caller is synchronous (verifySnapshotDir), and Node has no synchronous socket. Until 2026-11-17 each question therefore started a whole
283
+ // `node gate-serve.mjs ask` process: six per check, against the contract's rule that the gate asks the resident gate over its socket in process
284
+ // (NN26, and NN07 for the repeats). The question is now sent by one worker THREAD of this process, kept for its life, while the caller waits on
285
+ // a shared flag: no process is started. The thread speaks the same line protocol as `ask` below.
286
+ const ASK_THREAD = `
287
+ const { parentPort } = require("node:worker_threads"); const net = require("node:net");
288
+ parentPort.on("message", ({ sock, line, timeoutMs, port, flag }) => {
289
+ let out = ""; let done = false; let conn = null;
290
+ const finish = (res) => { if (done) return; done = true; clearTimeout(timer); try { conn && conn.destroy(); } catch {} port.postMessage(res); port.close(); Atomics.store(flag, 0, 1); Atomics.notify(flag, 0); };
291
+ const timer = setTimeout(() => finish({ ok: false, why: "timeout" }), timeoutMs);
292
+ try {
293
+ conn = net.connect(sock);
294
+ conn.on("connect", () => conn.write(line + "\\n"));
295
+ conn.on("data", (d) => { out += d; });
296
+ conn.on("end", () => { try { finish(JSON.parse(out)); } catch { finish({ ok: false, why: "bad reply" }); } });
297
+ conn.on("error", (error) => finish({ ok: false, why: (error && error.code) || "error", unreachable: true }));
298
+ } catch (error) { finish({ ok: false, why: String((error && error.message) || error), unreachable: true }); }
299
+ });
300
+ `;
301
+ let askThread = null;
302
+ /** One request over the server's socket from this process, synchronously. Returns the server's reply, or { ok: false, why } as `ask` does. */
303
+ export function askInProcess(req, timeoutMs, { sock = socketPath() } = {}) {
304
+ if (!askThread) { askThread = new Worker(ASK_THREAD, { eval: true }); askThread.unref(); askThread.on("error", () => { askThread = null; }); askThread.on("exit", () => { askThread = null; }); }
305
+ const { port1, port2 } = new MessageChannel(); const flag = new Int32Array(new SharedArrayBuffer(4));
306
+ askThread.postMessage({ sock, line: JSON.stringify({ schema: SCHEMA, identity: IDENTITY, ...req }), timeoutMs, port: port2, flag }, [port2]);
307
+ Atomics.wait(flag, 0, 0, timeoutMs + 2000);
308
+ const got = receiveMessageOnPort(port1); port1.close();
309
+ return got?.message ?? { ok: false, why: "timeout" };
310
+ }
311
+
183
312
  /** One synchronous request to the resident server; null when it is disabled, unreachable or did not answer. Starts it when absent. */
184
- export function serveRequest(req, { env = process.env, root = null, timeoutMs = 3000 } = {}) {
313
+ export function serveRequest(req, { env = process.env, root = null, timeoutMs = 3000, sock = socketPath(env) } = {}) {
185
314
  if (env.RK_GATE_SERVE === "0") return null;
186
- const r = spawnSync(process.execPath, [SELF, "ask", JSON.stringify(req), String(timeoutMs)], { encoding: "utf8", timeout: timeoutMs + 2000, maxBuffer: 1 << 28, env: { ...env } });
187
- let res = null; try { res = JSON.parse(String(r.stdout ?? "").trim().split("\n").pop()); } catch { res = null; }
315
+ let res = null;
316
+ try { res = askInProcess(req, timeoutMs, { sock }); }
317
+ catch {
318
+ // A host where a worker thread cannot be made: the old way, one process per question, rather than no resident proof at all.
319
+ const r = spawnSync(process.execPath, [SELF, "ask", JSON.stringify(req), String(timeoutMs)], { encoding: "utf8", timeout: timeoutMs + 2000, maxBuffer: 1 << 28, env: { ...env } });
320
+ try { res = JSON.parse(String(r.stdout ?? "").trim().split("\n").pop()); } catch { res = null; }
321
+ }
188
322
  // Start a server only when none is listening; a bad reply or a timeout from a live one never starts a second.
189
323
  if (res?.unreachable && root) startServer({ root, env });
190
324
  return res && res.ok ? res : null;
191
325
  }
192
326
 
327
+ /** Whether `root` is this host's own snapshot root (snapshot.mjs snapshotRoot: `<managed root>/snapshots` on Mac and Windows). */
328
+ export function isHostSnapshotRoot(root, { platform = process.platform } = {}) {
329
+ if (platform !== "darwin" && platform !== "win32") return true; // elsewhere the root comes from the host's configuration file
330
+ // Both hosts' file systems fold case: another spelling of the same root is the same root.
331
+ try { return path.resolve(root).toLowerCase() === path.resolve(path.join(resolveManagedRoots({ env: {}, platform }).gateRoot, "snapshots")).toLowerCase(); } catch { return false; }
332
+ }
333
+
193
334
  function startServer({ root, env }) {
335
+ // One server per gate code, and it watches one root. A server started for any other directory (a test's temporary snapshot root) would hold
336
+ // the name and answer every real snapshot "not a snapshot of the watched root" for as long as it is asked. Only the host's root starts one.
337
+ if (!isHostSnapshotRoot(root)) return;
194
338
  try {
195
339
  const logDir = path.join(dataRoot(env), "gate-serve");
196
340
  fs.mkdirSync(logDir, { recursive: true });
@@ -252,7 +396,9 @@ export function snapshotCargoMetadata({ cwd, args, cargo, env, snapshotRootDir,
252
396
 
253
397
  // ---- entry --------------------------------------------------------------------------------------------------------------------------------
254
398
 
255
- if (process.argv[1] && fs.realpathSync(process.argv[1]) === fs.realpathSync(SELF)) {
399
+ // Importing this module must never throw: a `-e` helper (the gate's bounded probe) passes its payload as argv[1], not a file.
400
+ const isServeEntry = (() => { try { return Boolean(process.argv[1]) && fs.realpathSync(process.argv[1]) === fs.realpathSync(SELF); } catch { return false; } })();
401
+ if (isServeEntry) {
256
402
  const [cmd, a, b] = process.argv.slice(2);
257
403
  if (cmd === "serve") {
258
404
  serve({ root: a, log: (m) => console.log(`${new Date().toISOString()} gate-serve: ${m}`) }).catch((error) => { console.log(`${new Date().toISOString()} gate-serve: cannot serve: ${error?.message ?? error}`); process.exit(1); });
package/gate-stages.mjs CHANGED
@@ -268,6 +268,65 @@ export function compiledBinaries(builtBins = {}, { platform = process.platform,
268
268
  return out;
269
269
  }
270
270
 
271
+ /** What is remembered beside a passed test row that linked programs: where they were written and each one's digest. */
272
+ export const BUILT_BINS_RECORD = "rightkit.built-bins/1";
273
+
274
+ /**
275
+ * The programs a compile run can vouch for: `{ [output dir]: { profile, bins } }`, the input of compiledBinaries.
276
+ *
277
+ * A program is linked only by a PASSED `cargo test -p <crate>` row of a package with a selected integration test. A row that RAN in this run vouches
278
+ * for its unit's programs where the broker's signed receipt says they were written (`placeOf(row)`: { dir, profile }).
279
+ *
280
+ * A row answered from the cache built nothing in this run. Until 2026-11-17 it therefore vouched for nothing, and a receipt whose unit was cached
281
+ * could not be installed from: an installer that needs four programs found three (RustRight, the watchdog's unit; every install after a commit that
282
+ * did not touch that unit was blocked). The row's pass is for the same key, so the same inputs: the programs it linked when it ran are the programs of
283
+ * this commit. So when a row runs, each program's digest is remembered under the row's key (`store.write`), and when the row is later answered from
284
+ * the cache its programs are vouched for only if every one of them is still on disk with exactly that digest. A program that is missing or has
285
+ * other bytes (another commit built over it) is not vouched for, and `note` says so; nothing is guessed.
286
+ *
287
+ * `rows`: the run's scan rows. `unitOf(row)`: the unit ({ bins, testLinksBins }) or undefined. `keyOf(row)`: the 64-hex name the record is filed
288
+ * under, or null when the row has no cache key. `store`: { read(key), write(key, record) } (the result cache). A directory two rows name with
289
+ * different profiles vouches for nothing, as before.
290
+ */
291
+ export function builtBinsOfRun({ rows = [], unitOf, placeOf, keyOf = () => null, store = null, binaries = compiledBinaries, note = () => {} }) {
292
+ const built = {};
293
+ const add = (dir, bins, profile) => {
294
+ const prior = built[dir];
295
+ if (prior && prior.profile !== profile) { built[dir] = { profile: null, bins: [] }; return; }
296
+ built[dir] = { profile, bins: [...new Set([...(prior?.bins ?? []), ...bins])].sort() };
297
+ };
298
+ for (const row of rows) {
299
+ if (row?.status !== "pass" || !/^test:rust(?:-serial)?:/.test(String(row.id))) continue;
300
+ const unit = unitOf(row);
301
+ if (!unit?.testLinksBins || !unit.bins?.length) continue;
302
+ const key = keyOf(row);
303
+ if (row.cached !== true) {
304
+ const place = placeOf(row) ?? {};
305
+ if (!place.dir || !place.profile) continue;
306
+ add(place.dir, unit.bins, place.profile);
307
+ if (!key || !store) continue;
308
+ const digests = binaries({ [place.dir]: { profile: place.profile, bins: unit.bins } });
309
+ // Only a complete set is remembered: a program that is not there now cannot be recognised later.
310
+ if (digests.length === new Set(unit.bins).size && digests.every((d) => typeof d.sha256 === "string")) {
311
+ store.write(key, { schema: BUILT_BINS_RECORD, id: String(row.id), dir: place.dir, profile: place.profile, bins: [...new Set(unit.bins)].sort(), sha256: Object.fromEntries(digests.map((d) => [d.name, d.sha256])) });
312
+ }
313
+ continue;
314
+ }
315
+ const record = key && store ? store.read(key)?.row : null;
316
+ if (record?.schema !== BUILT_BINS_RECORD || typeof record.dir !== "string" || typeof record.profile !== "string" || !Array.isArray(record.bins)) {
317
+ note(`${row.id} was answered from the cache and no record of the programs it linked is stored: its programs are not vouched for in this run`);
318
+ continue;
319
+ }
320
+ // The unit's programs today must be the ones the record names: a program added since is not covered by it.
321
+ if ([...new Set(unit.bins)].sort().join("\n") !== [...record.bins].sort().join("\n")) { note(`${row.id}: the stored record names other programs than the unit has now; not vouched for`); continue; }
322
+ const now = binaries({ [record.dir]: { profile: record.profile, bins: record.bins } });
323
+ const changed = now.filter((d) => typeof d.sha256 !== "string" || d.sha256 !== record.sha256?.[d.name]);
324
+ if (now.length !== record.bins.length || changed.length) { note(`${row.id} was answered from the cache and ${changed.map((d) => d.name).join(", ") || "a program"} in ${record.dir} is missing or is not the bytes it linked; not vouched for`); continue; }
325
+ add(record.dir, record.bins, record.profile);
326
+ }
327
+ return built;
328
+ }
329
+
271
330
  /** What a passed compile stage records about its outputs: the directories, their census, the built binaries' digests and the key of the compile environment. */
272
331
  export function compileOutputsRecord({ dirs = [], env = {}, builtBins = null, census = outputCensus, binaries = compiledBinaries }) {
273
332
  const c = census(dirs);