@rightkit/release 0.6.45 → 0.6.47

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.
@@ -80,6 +80,7 @@ import path from "node:path";
80
80
  import { hostTarget } from "../cross-targets.mjs";
81
81
  import { FOREIGN_PRE_COMMIT, retireHooksIn } from "../hook-retirement.mjs";
82
82
  import { fileURLToPath } from "node:url";
83
+ import { installIdentity, installStateBytes } from "../dependency-identity.mjs";
83
84
  import { BIOME_CONFIG_FILES, CHECKER_IDENTITY, ESLINT_CONFIG_FILES, LOCAL_CLASS_B_JOBS, WORKSPACE_RUST_FILE, ancestorConfigChanged, ancestorDirsOf, canonicalJson, defaultSpawn, defaultSpawnAsync, digestScanSet, fileScanCache, findRustfmt, metadataArgs, planScans, runScans, scanToolPolicyFromPipeline, scanDeferrals, scanFailures } from "../deterministic-scans.mjs";
84
85
  import { changedLockNames, parseLock, reach } from "../lock-graph.mjs";
85
86
  import { resolveExecutor } from "../gate-executor.mjs";
@@ -95,14 +96,27 @@ import { LINUX_BROKER_ROUTE, NO_BROKER_ENV, directCargoPath, directPlatform, lin
95
96
  import { createBrokerLive } from "../broker-admission.mjs";
96
97
  import { bindingOf, compileOutputsRecord, compileReuseProblem, endRun, readReceipt, RECEIPT_SCHEMA, receiptKey, sameBinding, sameSource, sealedFor, stagesTo, startRun, STAGES, STAGE_SOURCES, writeReceipt } from "../gate-stages.mjs";
97
98
  import { spawnSync as spawnInherit } from "../background-process.mjs";
99
+ // GC-A21: a run that stamps its own lines also stamps its inherited-output children's lines, through stamp-relay.mjs in front of the child
100
+ // (the launch stays synchronous and the output still streams). Set by main() when the run stamps; off for machine-readable runs.
101
+ let stampChildLines = false;
102
+ const STAMP_RELAY = fileURLToPath(new URL("../stamp-relay.mjs", import.meta.url));
103
+ const inheritLaunch = (cmd, a, opts) => (stampChildLines
104
+ ? spawnInherit(process.execPath, [STAMP_RELAY, cmd, ...a], { ...opts, stdio: "inherit" })
105
+ : spawnInherit(cmd, a, { ...opts, stdio: "inherit" }));
98
106
  import { readDiskPolicy, scratchRoots } from "../disk-policy.mjs";
99
107
  import { buildDirectReceipt, directVerdict, resolveTargetDirectory, verifyDirectReceipt, writeDirectDiagnostics } from "../direct-receipt.mjs";
100
108
  import { createFreshnessCensus } from "../freshness-census.mjs";
101
109
  import { platformDirOf } from "../platform-dir.mjs";
110
+ import { buildInventory, classifyUnitResults, dependencyFirstOrder, selectAffectedAcrossInventories, unitListReport } from "../affected-units.mjs";
111
+ import { createRequire } from "node:module";
102
112
  import { nativeToolRefusal, nativeToolUses } from "../native-tool-planning.mjs";
103
113
  import { BUILD_CONTROL_PROTOCOL, HANDSHAKE_PROBE_ID, RUNTIME_MANIFEST_FILE, mergeCapabilityViews, parseRuntimeIdentity, queryBrokerHandshake } from "../broker-handshake.mjs";
104
114
  import net from "node:net";
115
+ import { cargoWidthRouteProblem, cargoWidthScanProblem, cargoWidthUnitsProblem, parseCargoWidth, validateCargoWidthPool } from "../cargo-width.mjs";
105
116
 
117
+ const PRIVATE_SCOPED_COMPILE = Symbol("private scoped compile");
118
+ const UNIT_LIST_UNION = Symbol("unit list union");
119
+ const CARGO_WIDTH = Symbol("Cargo width");
106
120
  const ZERO = /^0+$/;
107
121
  const SAFE_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
108
122
  const posix = (p) => String(p).replaceAll("\\", "/");
@@ -117,6 +131,51 @@ export const PLATFORMS = Object.freeze(["mac", "win", "ios", "android"]);
117
131
  export const MOBILE_PLATFORMS = Object.freeze(new Set(["ios", "android"]));
118
132
  // The gate's code identity for result keys: the checker (deterministic-scans and scan-digest, CHECKER_IDENTITY) and this file, where
119
133
  // the keys are built. An unidentifiable checker gets a per-process value, so nothing is reused across runs.
134
+ // The identity a class B (compile) result key carries (GC-A24): a key-schema version, bumped by hand whenever what a key covers changes,
135
+ // and the code of the runtime cargo wrapper and broker carrier, which decides what a carried compile ran and how its receipt is verified.
136
+ // The gate's own file and the checker are not in it: the verdict is cargo's, the command and tool versions are in every key already, and
137
+ // an edit elsewhere in the gate must not discard every compile result (rightkit#1506: Pulse, RK, RustRight and Legion kept 0 class B hits).
138
+ const CLASS_B_KEY_SCHEMA = "rightkit.class-b-key/2";
139
+ // GC-A24: passing rule-engine verdicts (app rules, RightKit's preflight) of a snapshot, under the checkout's git common directory.
140
+ const RULE_VERDICT_SCHEMA = "rightkit.rule-verdict/1";
141
+ function ruleVerdictCache({ checkout, spawn }) {
142
+ try {
143
+ const common = spawn("git", ["rev-parse", "--path-format=absolute", "--git-common-dir"], { cwd: checkout });
144
+ if (failed(common) || !text(common).trim()) return null;
145
+ const dir = path.join(text(common).trim(), "rightkit-gate-cache", "rule-verdicts");
146
+ const file = (k) => path.join(dir, `${k}.json`);
147
+ return {
148
+ key: (parts) => createHash("sha256").update(canonicalJson({ schema: RULE_VERDICT_SCHEMA, node: process.version, platform: `${process.platform}-${process.arch}`, ...parts })).digest("hex"),
149
+ passed: (k) => { try { return JSON.parse(fs.readFileSync(file(k), "utf8"))?.status === "pass"; } catch { return false; } },
150
+ pass: (k) => { try { fs.mkdirSync(dir, { recursive: true }); const tmp = `${file(k)}.${process.pid}.tmp`; fs.writeFileSync(tmp, JSON.stringify({ schema: RULE_VERDICT_SCHEMA, status: "pass", at: new Date().toISOString() })); fs.renameSync(tmp, file(k)); } catch { /* a cache */ } },
151
+ };
152
+ } catch { return null; }
153
+ }
154
+ /** sha256 over every file of the gate package (the rule code a rule verdict depends on). */
155
+ const gatePackageMemo = new Map();
156
+ function gatePackageIdentity(gatePackage = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..")) {
157
+ if (!gatePackageMemo.has(gatePackage)) {
158
+ const h = createHash("sha256");
159
+ const walk = (d) => fs.readdirSync(d, { withFileTypes: true }).sort((a, b) => (a.name < b.name ? -1 : 1)).forEach((e) => { if (e.name === "node_modules" || e.name.startsWith(".")) return; const p = path.join(d, e.name); if (e.isDirectory()) walk(p); else if (e.isFile()) { h.update(path.relative(gatePackage, p)); h.update("\0"); h.update(fs.readFileSync(p)); } });
160
+ walk(gatePackage);
161
+ gatePackageMemo.set(gatePackage, h.digest("hex"));
162
+ }
163
+ return gatePackageMemo.get(gatePackage);
164
+ }
165
+ // GC-A24: the class A key schema a standalone-tool row carries in place of the environment digest; bumped when what a class A key covers changes.
166
+ const CLASS_A_KEY_SCHEMA = "rightkit.class-a-key/2";
167
+ /** Whether a class A row's verdict depends on the installed dependencies (GC-A24): it executes repository code, or its tool is pnpm. */
168
+ function classAEnvironmentBound(scan) { return scan.executes === true || scan.tool === "pnpm"; }
169
+ let classBKeyIdentityMemo = null;
170
+ function classBKeyIdentity() {
171
+ if (classBKeyIdentityMemo === null) {
172
+ const h = createHash("sha256");
173
+ h.update(CLASS_B_KEY_SCHEMA);
174
+ for (const f of ["cargo-target-shim.mjs", "snapshot-broker.mjs", "snapshot-request.mjs", "snapshot-metadata.mjs", "provenance-verify.mjs", "cargo-ledger.mjs"]) { h.update(`\0${f}\0`); h.update(fs.readFileSync(new URL(`../${f}`, import.meta.url))); }
175
+ classBKeyIdentityMemo = h.digest("hex").slice(0, 24);
176
+ }
177
+ return classBKeyIdentityMemo;
178
+ }
120
179
  let gateCodeIdentityMemo = null;
121
180
  function gateCodeIdentity() {
122
181
  if (gateCodeIdentityMemo === null) {
@@ -144,7 +203,7 @@ function directCargoBinOf(o) {
144
203
  return null;
145
204
  }
146
205
 
147
- const USAGE = `usage: rightkit-gate --to check|compile|package|qualify|release [--platform mac|win|ios|android] [--tier patch|update] [--receipt-in <file>] [--receipt-out <file>] | rightkit-gate --to check|compile|package|qualify|release --unit npm:@rightkit/<name>|cargo:rightkit-<name> [--receipt-out <file>] | rightkit-gate --to tool --unit cargo:rightkit-qa|cargo:rightkit-credentials [--no-broker <exception-id>] [--receipt-out <file>] [--commit <rev>] (builds the unit's release binary from the commit and enrols it: cargo:rightkit-qa as the managed rightkit-qa runner, cargo:rightkit-credentials as the managed OS credential provider updater signing runs; Mac and Windows) | rightkit-gate --to check|compile|package|qualify --units-file <json {"units":[<selector>,...]} written for this run> | rightkit-gate --to check|compile|package|qualify --all-units-exception <id> (RightKit only: its unit is named on every run, or every unit by Adrian's entry in ci/all-units-exceptions.json of the commit) | rightkit-gate --to check|compile|package|qualify [--unit <selector>] --no-broker <exception-id> (Mac and Dell only; Adrian's recorded exception in .rightkit/broker-exceptions.json of the commit) | rightkit-gate --to dev|test [--commit <rev>] [-- <right-release args>] | rightkit-gate --to render [--commit <rev>] (builds the app's declared renderViews target from ci/gate.config.json through the carrier, runs it headless and stores the PNGs and a hashed receipt) | rightkit-gate --to check|compile|package|qualify|dev|test --route [--platform mac|win|ios|android] [--commit <rev>] | rightkit-gate stage --platform mac|win [--tier patch|update] | rightkit-gate [--base <ref>] [--plan] | rightkit-gate install-hook | rightkit-gate env-digest | rightkit-gate snapshot [--commit <rev>] [--verify [--env <sha256>]] [--json] | rightkit-gate live-scans --repo <root> | rightkit-gate clippy [<cargo clippy args>] | rightkit-gate env-digest [--snapshot <dir> --commit <sha>] | rightkit-gate check [--repo <dir>] [--commit <rev> | --worktree] [--rule-tier compile|release] [--only <rule,...>] [--list] [--print-baseline] [--baseline <file>] | rightkit-gate check --commit <sha> --full-a --snapshot <dir> | --version`;
206
+ const USAGE = `usage: rightkit-gate --to check|compile|package|qualify|release [--platform mac|win|ios|android] [--tier patch|update] [--receipt-in <file>] [--receipt-out <file>] | rightkit-gate --to check|compile|package|qualify|release --unit npm:@rightkit/<name>|cargo:rightkit-<name> [--receipt-out <file>] | rightkit-gate --to tool --unit cargo:rightkit-qa|cargo:rightkit-credentials [--no-broker <exception-id>] [--receipt-out <file>] [--commit <rev>] (builds the unit's release binary from the commit and enrols it: cargo:rightkit-qa as the managed rightkit-qa runner, cargo:rightkit-credentials as the managed OS credential provider updater signing runs; Mac and Windows) | rightkit-gate --to check|compile|package|qualify --changed [--base <ref>] [--receipt-dir <absolute dir>] | rightkit-gate --to check|compile|package|qualify --units-file <json {"units":[<selector>,...]} written for this run> [--receipt-dir <absolute dir>] | rightkit-gate --to check|compile|package|qualify --all-units-exception <id> (RightKit only: its unit is named on every run, or every unit by Adrian's entry in ci/all-units-exceptions.json of the commit) | rightkit-gate --to check|compile|package|qualify [--unit <selector>] --no-broker <exception-id> (Mac and Dell only; Adrian's recorded exception in .rightkit/broker-exceptions.json of the commit) | rightkit-gate --to dev|test [--commit <rev>] [-- <right-release args>] | rightkit-gate --to render [--commit <rev>] (builds the app's declared renderViews target from ci/gate.config.json through the carrier, runs it headless and stores the PNGs and a hashed receipt) | rightkit-gate --to check|compile|package|qualify|dev|test --route [--platform mac|win|ios|android] [--commit <rev>] | rightkit-gate stage --platform mac|win [--tier patch|update] | rightkit-gate [--base <ref>] [--plan] | rightkit-gate install-hook | rightkit-gate env-digest | rightkit-gate snapshot [--commit <rev>] [--verify [--env <sha256>]] [--json] | rightkit-gate live-scans --repo <root> | rightkit-gate clippy [<cargo clippy args>] | rightkit-gate env-digest [--snapshot <dir> --commit <sha>] | rightkit-gate check [--repo <dir>] [--commit <rev> | --worktree] [--rule-tier compile|release] [--only <rule,...>] [--list] [--print-baseline] [--baseline <file>] | rightkit-gate check --commit <sha> --full-a --snapshot <dir> | --version`;
148
207
  /** The host platform (process.platform) that constructs each platform's artifact; a platform missing here (android) builds on any host. */
149
208
  const STAGE_NATIVE_HOST = Object.freeze({ mac: "darwin", ios: "darwin", win: "win32" });
150
209
 
@@ -321,6 +380,7 @@ export function gateTmpRoot({ env = process.env, platform = process.platform, ex
321
380
  export const PNPM_PROBE_TIMEOUT_MS = 60_000;
322
381
  export const PNPM_PIN_REFUSAL = "RK_PNPM_VERSION_MISMATCH";
323
382
  export const TOOL_CACHE_DIRS = new Set([".vite", ".vite-temp", ".vitest-cache", ".cache"]);
383
+ export { installStateBytes };
324
384
  export const INSTALL_STATE_NOT_COVERED = new Set([".pnpm-task-run-state-v1"]);
325
385
  const nodeModulesDirs = (root, files) => [...new Set(files.filter((f) => /(^|\/)package\.json$/.test(f)).map((f) => path.join(path.dirname(path.join(root, f)), "node_modules")))].sort();
326
386
  function isLink(p) { try { return fs.lstatSync(p).isSymbolicLink(); } catch { return false; } }
@@ -392,66 +452,13 @@ export function toolCacheDrift(before, after) {
392
452
  * entry, or more than `maxFiles` files throws. Tool caches (TOOL_CACHE_DIRS) leave no trace. Bytes that change while it hashes are caught by comparing the digest at the start
393
453
  * and end of the run and again at START.
394
454
  */
395
- export function installedDependencyDigest({ root, files, maxFiles = 400000, includeCaches = true }) {
396
- const h = createHash("sha256");
397
- const realRoot = fs.realpathSync(root);
398
- const walkedRoots = nodeModulesDirs(root, files);
399
- const realWalked = walkedRoots.map((d) => { try { return fs.realpathSync(d); } catch (error) { if (error?.code === "ENOENT") return null; throw error; } }).filter(Boolean);
400
- const inside = (p, dir) => p === dir || p.startsWith(dir + path.sep);
401
- const rel = (p) => (inside(p, realRoot) ? path.relative(realRoot, p).split(path.sep).join("/") : p);
402
- const seen = new Set(); const pending = []; let count = 0;
403
- const fail = (what, error) => { throw new Error(`cannot read ${what} for the class A environment (${error?.code ?? error?.message ?? error})`); };
404
- const entry = (p, name, parentIsNodeModules, fromLink) => {
405
- const st = (() => { try { return fs.lstatSync(p); } catch (error) { return fail(rel(p), error); } })();
406
- if (st.isSymbolicLink()) {
407
- let target; let real;
408
- try { target = fs.readlinkSync(p); } catch (error) { return fail(`the link ${rel(p)}`, error); }
409
- // A dangling link (pnpm hoists optional packages for other platforms that were never installed) resolves nothing, so it
410
- // supplies no bytes; it is bound as dangling, and a target that later appears changes the digest.
411
- try { real = fs.realpathSync(p); } catch (error) { if (error?.code === "ENOENT") { h.update(`${rel(p)}\tdangling\t${target}\n`); return; } return fail(`the link ${rel(p)}`, error); }
412
- h.update(`${rel(p)}\tlink\t${target}\n`);
413
- if (!realWalked.some((d) => inside(real, d))) pending.push(real);
414
- return;
415
- }
416
- // pnpm's task-run state holds only completion markers, never code, and leaves no trace. Tool caches are bound byte for byte
417
- // unless `includeCaches` is false (only for the start/end comparison inside one run, which writes them itself).
418
- if (parentIsNodeModules && !fromLink && INSTALL_STATE_NOT_COVERED.has(name)) return;
419
- if (parentIsNodeModules && !fromLink && TOOL_CACHE_DIRS.has(name) && !includeCaches) return;
420
- if (st.isDirectory()) return walk(p, fromLink);
421
- if (st.isFile()) {
422
- if (++count > maxFiles) throw new Error(`more than ${maxFiles} installed dependency files; refusing an unbounded class A environment`);
423
- let bytes; try { bytes = fs.readFileSync(p); } catch (error) { return fail(rel(p), error); }
424
- h.update(`${rel(p)}\tfile\t${st.mode & 0o111 ? "x" : "-"}\t${createHash("sha256").update(bytes).digest("hex")}\n`);
425
- return;
426
- }
427
- throw new Error(`unsupported entry ${rel(p)} in the installed dependencies`);
428
- };
429
- const walk = (dir, fromLink) => {
430
- let names; try { names = fs.readdirSync(dir).sort(); } catch (error) { return fail(rel(dir), error); }
431
- const nm = path.basename(dir) === "node_modules";
432
- for (const name of names) {
433
- const p = path.join(dir, name);
434
- if (fromLink && (name === ".git" || (name === "node_modules" && walkedRoots.includes(p)))) continue;
435
- entry(p, name, nm, fromLink);
436
- }
437
- };
438
- for (const d of walkedRoots) {
439
- h.update(`root\t${rel(d)}\n`);
440
- try { fs.lstatSync(d); } catch (error) { if (error?.code === "ENOENT" || error?.code === "ENOTDIR") { h.update("absent\n"); continue; } fail(rel(d), error); }
441
- walk(d, false);
442
- }
443
- while (pending.length) {
444
- const real = pending.shift();
445
- if (seen.has(real)) continue;
446
- seen.add(real);
447
- if (real === path.parse(real).root || inside(realRoot, real)) throw new Error(`a dependency link resolves to ${real}, the repository or one of its ancestors; refusing to bind it`);
448
- h.update(`target\t${rel(real)}\n`);
449
- const st = fs.lstatSync(real);
450
- // A linked package outside the walked node_modules trees (a workspace package, or one elsewhere on disk) is hashed whole:
451
- // any of its files can be executed by a consumer (an ignored dist/, an implicit index.js, a file its entry imports).
452
- if (st.isDirectory()) walk(real, true); else entry(real, path.basename(real), false, true);
453
- }
454
- return h.digest("hex");
455
+ export function installedDependencyDigest({ root, files, includeCaches = true }) {
456
+ // GC-A24 (Adrian, 2026-11-05): the installed dependencies are identified by pnpm's own install record (dependency-identity.mjs
457
+ // installIdentity: install-state files with their timestamps removed, .pnpm/lock.yaml, top-level links, and whole bytes only of linked
458
+ // packages from outside the repository), not by reading every installed file. `includeCaches` no longer applies: tool caches are
459
+ // not part of the install record. The roots are the node_modules directories of every committed package.json (nodeModulesDirs).
460
+ void includeCaches;
461
+ return installIdentity(root, nodeModulesDirs(root, files));
455
462
  }
456
463
 
457
464
  /**
@@ -477,7 +484,7 @@ export function classAEnvironmentDigest({ root, files, spawn = defaultSpawn, inc
477
484
  if (failed(r) || !text(r).trim()) throw new Error(`cannot identify pnpm for the class A environment (${r?.error ? `could not run pnpm: ${r.error.code ?? r.error.message}` : why(r)})`);
478
485
  return text(r).trim();
479
486
  })();
480
- const installState = files.filter((f) => /(^|\/)package\.json$/.test(f)).map((f) => path.join(path.dirname(path.join(root, f)), "node_modules", ".modules.yaml")).map((m) => `${path.relative(root, m)}:${fileDigest(m, { optional: true })}`);
487
+ const installState = files.filter((f) => /(^|\/)package\.json$/.test(f)).map((f) => path.join(path.dirname(path.join(root, f)), "node_modules", ".modules.yaml")).map((m) => { let d; try { d = createHash("sha256").update(installStateBytes(".modules.yaml", fs.readFileSync(m))).digest("hex"); } catch (error) { d = fileDigest(m, { optional: true }); } return `${path.relative(root, m)}:${d}`; });
481
488
  return createHash("sha256").update([`node ${process.version}`, `pnpm ${pnpmVersion}`, `platform ${process.platform}-${process.arch}`, ...gateFiles, ...installState, `installed ${installedDependencyDigest({ root, files, includeCaches })}`].join("\n")).digest("hex");
482
489
  }
483
490
 
@@ -998,7 +1005,7 @@ function shardSoloOf(o, repo) {
998
1005
  } catch { return []; }
999
1006
  }
1000
1007
 
1001
- export function buildCacheDigest({ objectId, headTree, rustUnits = [], npmUnits = [], cargoDir = ".", rustLock = null, rustLocks = null, crateFeatures = {}, listFiles = null, readBlob = null, today = () => new Date().toISOString().slice(0, 10) }) {
1008
+ export function buildCacheDigest({ objectId, headTree, rustUnits = [], npmUnits = [], cargoDir = ".", rustLock = null, rustLocks = null, crateFeatures = {}, listFiles = null, readBlob = null, today = () => new Date().toISOString().slice(0, 10), onKeyError = null }) {
1002
1009
  const memo = new Map(); const reachMemos = new Map(); const externalMemo = new Map();
1003
1010
  const idOf = (p) => { if (!memo.has(p)) memo.set(p, p === "." ? headTree : objectId(p)); return memo.get(p); };
1004
1011
  // npm: a package's test, tsc and eslint scans read the package, every workspace package it depends on (package.json
@@ -1066,7 +1073,8 @@ export function buildCacheDigest({ objectId, headTree, rustUnits = [], npmUnits
1066
1073
  // projection and its own lock entry; anything else (cargo metadata, licence, ownership catalog, secret scan) on the whole tree,
1067
1074
  // so it is reused for a rerun of the same commit and nothing else.
1068
1075
  const liveScan = (id) => /^(cargo-deny|cargo-audit|pnpm-audit|pnpm-lockfile|advisory-exceptions)(:|$)/.test(id);
1069
- const ADVISORY_SCAN = /^(cargo-deny|cargo-audit|pnpm-audit)(:|$)/;
1076
+ // GC-A24: pnpm-lockfile asks the registry as pnpm-audit does, so it takes the same day-bounded key (GC-A19).
1077
+ const ADVISORY_SCAN = /^(cargo-deny|cargo-audit|pnpm-audit|pnpm-lockfile)(:|$)/;
1070
1078
  // The key of an advisory scan (rightkit#1464), or null when an input cannot be identified (the scan then runs). Every input that decides the
1071
1079
  // verdict and is not in the scan's id, command or environment is here; the advisory database's commit (cargo) is in the scan's own environment
1072
1080
  // (RK_ADVISORY_DB_COMMIT) and its pin object, the gate's code and advisory-db.json are in the environment digest the caller appends.
@@ -1075,7 +1083,7 @@ export function buildCacheDigest({ objectId, headTree, rustUnits = [], npmUnits
1075
1083
  const dir = typeof scan.cwd === "string" && scan.cwd !== "" ? scan.cwd : ".";
1076
1084
  const idsOf = (paths) => [...new Set(paths)].sort().map((p) => [p, idOf(p) ?? null]);
1077
1085
  const all = listFiles(".");
1078
- if (/^pnpm-audit(:|$)/.test(scan.id)) {
1086
+ if (/^pnpm-(audit|lockfile)(:|$)/.test(scan.id)) {
1079
1087
  const lock = inWs(dir, "pnpm-lock.yaml");
1080
1088
  if (idOf(lock) === null || idOf(lock) === undefined) return null;
1081
1089
  const manifests = all.filter((f) => /(^|\/)package\.json$/.test(f) && (dir === "." || f === inWs(dir, "package.json") || f.startsWith(`${dir}/`)));
@@ -1091,11 +1099,18 @@ export function buildCacheDigest({ objectId, headTree, rustUnits = [], npmUnits
1091
1099
  const fileList = (scan) => {
1092
1100
  if (Array.isArray(scan.files) && scan.files.length) return scan.files;
1093
1101
  const args = Array.isArray(scan.args) ? scan.args : [];
1094
- if (/^rustfmt:/.test(scan.id)) return args.filter((x) => /\.rs$/.test(x));
1095
- if (/^node-check:/.test(scan.id)) return [scan.id.slice("node-check:".length)];
1102
+ if (/^rustfmt:/.test(scan.id)) {
1103
+ const rs = args.filter((x) => /\.rs$/.test(x));
1104
+ const configs = new Set(); for (const f of rs) for (const d of ancestorDirsOf(path.posix.dirname(f))) for (const c of ["rustfmt.toml", ".rustfmt.toml"]) configs.add(inWs(d, c));
1105
+ return [...rs, ...configs];
1106
+ }
1107
+ if (/^node-check:/.test(scan.id)) { const f = scan.id.slice("node-check:".length); return [f, ...ancestorDirsOf(path.posix.dirname(f)).map((d) => inWs(d, "package.json"))]; }
1108
+ if (scan.internal === "secret-scan" && Array.isArray(scan.dirs) && typeof listFiles === "function") return [...new Set(scan.dirs.flatMap((d) => listFiles(d)))];
1109
+ if (scan.id === "shellcheck") return [...args.filter((x) => /\.(sh|bash)$/.test(x)), ".shellcheckrc"];
1096
1110
  if (scan.id === "actionlint") return [...args.filter((x) => /\.ya?ml$/.test(x)), ".github/actionlint.yaml"];
1097
1111
  return null;
1098
1112
  };
1113
+ const unitKeyMemo = new Map();
1099
1114
  return (scan) => {
1100
1115
  if (scan.class === "A") {
1101
1116
  if (liveScan(scan.id) && !ADVISORY_SCAN.test(scan.id)) return null;
@@ -1114,7 +1129,7 @@ export function buildCacheDigest({ objectId, headTree, rustUnits = [], npmUnits
1114
1129
  return canonicalJson({ kind: "package-list", unit, dir: [head.dir, idOf(head.dir)], manifest, lock: [[crateOf(head), lock.get(crateOf(head))?.signatures ?? []]] });
1115
1130
  }
1116
1131
  return whole();
1117
- } catch { return null; }
1132
+ } catch (error) { onKeyError?.(scan, error); return null; }
1118
1133
  }
1119
1134
  if (scan.class !== "B") return null;
1120
1135
  try {
@@ -1140,12 +1155,12 @@ export function buildCacheDigest({ objectId, headTree, rustUnits = [], npmUnits
1140
1155
  }
1141
1156
  const keyed = rustUnitKey(unit, scan);
1142
1157
  return keyed === undefined ? whole() : keyed;
1143
- } catch { return null; }
1158
+ } catch (error) { onKeyError?.(scan, error); return null; }
1144
1159
  };
1145
1160
  // The cache key of one Rust unit's compile or test scan, or undefined when the scan must fall back to the whole tree.
1146
1161
  // A unit's key is a function of the unit, whether the scan is a test scan and the commit; it never names the scan, so the 5 to 10 scans of one
1147
1162
  // crate share one computation (B7: per-job prep, one git read of the manifest and one closure walk per scan before).
1148
- const unitKeyMemo = new Map();
1163
+ // (unitKeyMemo is declared before the returned key function; declared here it was never initialised and every Rust key threw.)
1149
1164
  function rustUnitKey(unit, scan) {
1150
1165
  const memoKey = `${unit}\0${/^test:rust(?:-serial)?:/.test(scan.id) ? "test" : "compile"}`;
1151
1166
  if (unitKeyMemo.has(memoKey)) return unitKeyMemo.get(memoKey);
@@ -1405,11 +1420,196 @@ export function readUnitList(readFile, file) {
1405
1420
  return units;
1406
1421
  }
1407
1422
 
1423
+ const unitDirOfSelector = (sel) => { const m = /^(?:npm:@rightkit\/([a-z0-9-]+)|cargo:(rightkit-[a-z0-9-]+))$/.exec(sel); return m ? (m[1] ? `packages/${m[1]}` : `crates/${m[2]}`) : null; };
1424
+
1425
+ /**
1426
+ * The fixed unit inventory of one commit, read from its object database alone (never the checkout): every
1427
+ * `crates/<x>/Cargo.toml` and `packages/<x>/package.json`, with sibling path dependencies (crate-workspaces.mjs) and
1428
+ * `@rightkit/*` npm dependencies. Throws when the commit's tree or a manifest cannot be read: a selection computed
1429
+ * from a partial inventory would silently skip units.
1430
+ */
1431
+ export function inventoryAtCommit({ git, commit }) {
1432
+ const listed = git("ls-tree", "-r", "--name-only", "-z", commit);
1433
+ if (failed(listed)) throw new Error(`cannot list the tree of ${commit.slice(0, 12)}: ${why(listed)}`);
1434
+ const files = new Set(text(listed).split("\0").filter(Boolean));
1435
+ const show = (file) => { const r = git("show", `${commit}:${file}`); if (failed(r)) throw new Error(`cannot read ${file} at ${commit.slice(0, 12)}: ${why(r)}`); return text(r); };
1436
+ const parse = createRequire(import.meta.url)("smol-toml").parse;
1437
+ const manifests = new Map();
1438
+ for (const file of [...files].filter((f) => f === "Cargo.toml" || /^crates\/[^/]+\/Cargo\.toml$/.test(f)).sort()) {
1439
+ try { manifests.set(path.posix.dirname(file), parse(show(file))); }
1440
+ catch (e) { throw new Error(`cannot parse ${file}: ${e.message}`); }
1441
+ }
1442
+ const crates = [...manifests].filter(([dir, m]) => dir.startsWith("crates/") && m.package);
1443
+ const byDir = new Map(crates.map(([dir, m]) => [dir, m.package.name]));
1444
+ const byName = new Set(byDir.values());
1445
+ const cargo = crates.map(([dir, m]) => {
1446
+ if (typeof m.package.name !== "string") throw new Error(`${dir}/Cargo.toml has no package name`);
1447
+ let workspaceDir = typeof m.package.workspace === "string" ? path.posix.normalize(path.posix.join(dir, m.package.workspace)) : dir;
1448
+ if (typeof m.package.workspace !== "string") while (workspaceDir !== "." && !manifests.get(workspaceDir)?.workspace) workspaceDir = path.posix.dirname(workspaceDir);
1449
+ const workspace = manifests.get(workspaceDir)?.workspace;
1450
+ const tables = [];
1451
+ for (const holder of [m, ...Object.values(m.target ?? {})]) for (const key of ["dependencies", "dev-dependencies", "build-dependencies"]) if (holder?.[key]) tables.push(holder[key]);
1452
+ const deps = new Set();
1453
+ for (const table of tables) for (const [alias, original] of Object.entries(table)) {
1454
+ let spec = original; let base = dir;
1455
+ if (spec && typeof spec === "object" && spec.workspace === true) {
1456
+ spec = workspace?.dependencies?.[alias]; base = workspaceDir;
1457
+ if (!spec) throw new Error(`${dir}/Cargo.toml cannot resolve workspace dependency ${alias}`);
1458
+ }
1459
+ const name = typeof spec === "object" ? (spec.package ?? alias) : alias;
1460
+ if (typeof spec === "object" && spec.path !== undefined) {
1461
+ if (typeof spec.path !== "string") throw new Error(`${dir}: invalid path for ${alias}`);
1462
+ const target = path.posix.normalize(path.posix.join(base, spec.path));
1463
+ if (target.startsWith("crates/") && !byDir.has(target)) throw new Error(`${dir}: dependency ${alias} points to unknown crate ${target}`);
1464
+ if (byDir.has(target)) { if (byDir.get(target) !== name) throw new Error(`${dir}: dependency ${alias} names ${name} but ${target} is ${byDir.get(target)}`); deps.add(name); }
1465
+ } else if (byName.has(name) || name.startsWith("rightkit-")) deps.add(name);
1466
+ }
1467
+ return { dir, name: m.package.name, deps: [...deps] };
1468
+ });
1469
+ const npm = [];
1470
+ for (const file of [...files].filter((f) => /^packages\/[^/]+\/package\.json$/.test(f)).sort()) {
1471
+ let parsed;
1472
+ try { parsed = JSON.parse(show(file)); } catch (e) { throw new Error(`cannot parse ${file}: ${e.message}`); }
1473
+ if (typeof parsed?.name !== "string") throw new Error(`${file} has no package name`);
1474
+ const names = [];
1475
+ for (const key of ["dependencies", "devDependencies", "optionalDependencies", "peerDependencies"]) {
1476
+ const table = parsed[key] ?? {};
1477
+ if (!table || typeof table !== "object" || Array.isArray(table)) throw new Error(`${file}: invalid ${key}`);
1478
+ for (const [name, version] of Object.entries(table)) {
1479
+ const alias = typeof version === "string" && version.match(/^npm:(@rightkit\/[^@]+)(?:@|$)/)?.[1];
1480
+ const target = alias || name;
1481
+ if (target.startsWith("@rightkit/")) names.push(target);
1482
+ else if (typeof version === "string" && version.startsWith("workspace:")) throw new Error(`${file}: unsupported workspace dependency ${name}`);
1483
+ }
1484
+ }
1485
+ npm.push({ dir: file.slice(0, -"/package.json".length), name: parsed.name, deps: names });
1486
+ }
1487
+ return buildInventory({ cargo, npm });
1488
+ }
1489
+
1490
+ /** The paths changed between `base` and `commit` (three-dot: what the commit side changed since the merge base). */
1491
+ /** Classify a committed private unit without publication-only version rules. */
1492
+ export function privateUnitManifest({ selector, content }) {
1493
+ const match = /^(?:npm:(@rightkit\/[a-z0-9-]+)|cargo:(rightkit-[a-z0-9-]+))$/.exec(selector);
1494
+ if (!match) throw new Error(`invalid unit selector ${selector}`);
1495
+ const kind = match[1] ? "npm" : "cargo";
1496
+ let parsed;
1497
+ try { parsed = kind === "npm" ? JSON.parse(content) : createRequire(import.meta.url)("smol-toml").parse(content); }
1498
+ catch (error) { throw new Error(`${selector}: cannot parse manifest: ${error.message}`); }
1499
+ const pkg = kind === "npm" ? parsed : parsed.package;
1500
+ const name = match[1] ?? match[2];
1501
+ if (pkg?.name !== name) throw new Error(`${selector}: manifest name does not match`);
1502
+ return { kind, name, private: kind === "npm" ? pkg.private === true : pkg.publish === false || (Array.isArray(pkg.publish) && pkg.publish.length === 0) };
1503
+ }
1504
+
1505
+ export function changedPathsAt({ git, base, commit }) {
1506
+ const diff = git("diff", "--name-status", "-z", "--find-renames", `${base}...${commit}`);
1507
+ if (failed(diff)) throw new Error(`cannot diff ${base}...${commit.slice(0, 12)}: ${why(diff)}; pass --base <ref>`);
1508
+ const fields = text(diff).split("\0"); if (fields.at(-1) === "") fields.pop();
1509
+ const paths = [];
1510
+ while (fields.length) {
1511
+ const status = fields.shift();
1512
+ if (!/^(?:[ACDMRT]|R[0-9]+|C[0-9]+)$/.test(status) || !fields.length) throw new Error(`invalid diff status ${status}`);
1513
+ paths.push(fields.shift());
1514
+ if (/^[RC][0-9]+$/.test(status)) { if (!fields.length) throw new Error(`missing rename path for ${status}`); paths.push(fields.shift()); }
1515
+ }
1516
+ return [...new Set(paths)];
1517
+ }
1518
+
1519
+ /**
1520
+ * One shared execution for a selected unit list (rightkit#1505): dependency-first order, one shared Class A (the
1521
+ * first unit's, scoped to every selected directory and remembered for the rest), every independent unit run even
1522
+ * when another fails, a unit whose selected dependency failed recorded blocked and not run, one receipt per unit
1523
+ * (with `--receipt-dir`) plus one aggregate report. Returns the exit the door run ends with: 0 only when every
1524
+ * selected unit passed, else the first failing unit's code (1 when only blocked units failed the run).
1525
+ */
1526
+ export async function runSharedUnitList({ o, io, stage, commit, selected, inventory, receiptDir = undefined, base = null, unmatched = [], runUnit = null }) {
1527
+ const tag = "rightkit-gate:";
1528
+ if (io[CARGO_WIDTH] !== undefined) {
1529
+ const problem = cargoWidthUnitsProblem(selected);
1530
+ if (problem) { o.err(`${tag} BLOCKED: ${problem}`); return 2; }
1531
+ }
1532
+ const bySelector = new Map((inventory?.units ?? []).map((u) => [u.selector, u]));
1533
+ const rows = selected.map((s) => ({ dir: unitDirOfSelector(s.selector), reason: "listed", ...bySelector.get(s.selector), ...s }));
1534
+ const order = inventory ? dependencyFirstOrder(inventory, new Set(rows.map((r) => r.selector))) : rows.map((r) => r.selector);
1535
+ const ordered = order.map((sel) => rows.find((r) => r.selector === sel));
1536
+ const unitListClassA = { dirs: [...new Set(ordered.map((r) => r.dir).filter(Boolean))], memo: new Map() };
1537
+ if (receiptDir !== undefined) {
1538
+ try { o.mkdir(receiptDir); } catch (e) { o.err(`${tag} BLOCKED: receipt directory must be new: ${receiptDir} (${e.message}); nothing ran`); return 2; }
1539
+ }
1540
+ if (stage === "compile" && !runUnit && !io.runUnitForList && ordered.length) {
1541
+ const union = { selected: ordered, inventory, rows: null, coverage: null, internal: [], commands: [], commit, runId: randomUUID() };
1542
+ const exit = await main(["--to", "compile", "--unit", ordered[0].selector, "--commit", commit], { ...io, unitListClassA, [UNIT_LIST_UNION]: union });
1543
+ const results = ordered.map((unit) => {
1544
+ const evidence = union.coverage?.filter((r) => r.selector === unit.selector) ?? [];
1545
+ const internal = union.internal.filter((r) => r.selector === unit.selector);
1546
+ const expected = union.expected?.get(unit.selector);
1547
+ const all = [...internal, ...evidence];
1548
+ const failed = !expected || all.length !== expected || all.some((r) => r.status === "failed" || r.status === "fail");
1549
+ const blocked = !failed && all.some((r) => r.status === "blocked" || r.status === "not-run");
1550
+ const status = failed ? "failed" : blocked ? "blocked" : union.verified && all.every((r) => r.status === "passed" || r.status === "pass") ? "passed" : "failed";
1551
+ return { selector: unit.selector, status, ...(status === "failed" ? { code: exit || 1 } : {}) };
1552
+ });
1553
+ const report = unitListReport({ commit, stage, base, selected: ordered, results, unmatched }); report.runId = union.runId;
1554
+ for (const row of report.units) {
1555
+ const evidence = { schema: "rightkit.unit-list-compile/1", runId: union.runId, commit, unit: row.selector, status: row.status, requirements: [...union.internal.filter((r) => r.selector === row.selector), ...(union.coverage?.filter((r) => r.selector === row.selector) ?? [])], cwdProofs: (union.cwdProofs ?? []).filter((r) => union.owner?.get(r.id) === row.selector), commands: union.commands.filter((r) => r.selector === row.selector), scans: (union.rows ?? []).filter((r) => r.publisherUnit === row.selector || r.sharedOrigin === true) };
1556
+ if (receiptDir === undefined) row.receipt = { status: "not-requested" };
1557
+ else {
1558
+ const name = `gate-${row.selector.replace(/^npm:@rightkit\//, "npm-").replace(/^cargo:/, "")}.json`;
1559
+ const data = `${JSON.stringify(evidence, null, 2)}\n`; o.writeFile(path.join(receiptDir, name), data);
1560
+ row.receipt = { status: "written", file: name, sha256: createHash("sha256").update(data).digest("hex") };
1561
+ }
1562
+ o.out(`${tag} unit ${row.selector}: ${row.status}`);
1563
+ }
1564
+ o.out(`${tag} unit report: ${report.counts.passed} passed, ${report.counts.failed} failed, ${report.counts.blocked} blocked, ${report.counts["not-run"]} not-run of ${ordered.length} on ${commit.slice(0, 12)}`);
1565
+ if (receiptDir !== undefined) o.writeFile(path.join(receiptDir, "units-report.json"), `${JSON.stringify(report, null, 2)}\n`);
1566
+ return report.ok ? 0 : (exit || 1);
1567
+ }
1568
+ const run = runUnit ?? io.runUnitForList ?? (async (selector, receipt) => main(["--to", stage, "--unit", selector, "--commit", commit, ...receipt], { ...io, unitListClassA }));
1569
+ const outcomes = new Map();
1570
+ const receiptEvidence = new Map();
1571
+ const runId = randomUUID();
1572
+ const bad = new Set(); // failed or blocked selectors, for the dependency check of later units
1573
+ for (const [i, row] of ordered.entries()) {
1574
+ const blocker = (bySelector.get(row.selector)?.deps ?? []).find((d) => bad.has(d));
1575
+ if (blocker) {
1576
+ bad.add(row.selector);
1577
+ o.err(`${tag} unit list ${i + 1}/${ordered.length}: ${row.selector} blocked: its dependency ${blocker} did not pass; not run`);
1578
+ continue;
1579
+ }
1580
+ o.out(`${tag} unit list ${i + 1}/${ordered.length}: ${row.selector} (${row.reason}${row.via ? ` via ${row.via}` : ""}) on commit ${commit.slice(0, 12)}`);
1581
+ const receipt = receiptDir === undefined ? [] : ["--receipt-out", path.join(receiptDir, `gate-${row.selector.replace(/^npm:@rightkit\//, "npm-").replace(/^cargo:/, "")}.json`)];
1582
+ let code = await run(row.selector, receipt, unitListClassA);
1583
+ if (receiptDir !== undefined) {
1584
+ const file = receipt[1];
1585
+ try {
1586
+ const bytes = (o.readFile ?? fs.readFileSync)(file);
1587
+ receiptEvidence.set(row.selector, { status: "written", file: path.basename(file), sha256: createHash("sha256").update(bytes).digest("hex") });
1588
+ } catch (error) {
1589
+ receiptEvidence.set(row.selector, { status: "missing", file: path.basename(file) });
1590
+ if (code === 0) { o.err(`${tag} ${row.selector}: successful run did not produce a readable receipt (${error.message})`); code = 1; }
1591
+ }
1592
+ }
1593
+ outcomes.set(row.selector, { ran: true, code });
1594
+ if (code !== 0) bad.add(row.selector);
1595
+ }
1596
+ const results = classifyUnitResults({ selected: ordered, inventory: inventory ?? { units: rows }, outcomes });
1597
+ const report = unitListReport({ commit, stage, base, selected: ordered, results, unmatched });
1598
+ report.runId = runId;
1599
+ for (const row of report.units) row.receipt = receiptDir === undefined ? { status: "not-requested" } : (receiptEvidence.get(row.selector) ?? { status: "not-run" });
1600
+ for (const r of report.units) o.out(`${tag} unit ${r.selector}: ${r.status}${r.status === "failed" ? ` (exit ${r.code})` : ""}${r.blockedBy ? ` (dependency ${r.blockedBy} did not pass)` : ""}`);
1601
+ o.out(`${tag} unit report: ${report.counts.passed} passed, ${report.counts.failed} failed, ${report.counts.blocked} blocked, ${report.counts["not-run"]} not-run of ${ordered.length} on ${commit.slice(0, 12)}`);
1602
+ if (receiptDir !== undefined) o.writeFile(path.join(receiptDir, "units-report.json"), `${JSON.stringify(report, null, 2)}\n`);
1603
+ if (report.ok) return 0;
1604
+ return results.find((r) => r.status === "failed")?.code || 1;
1605
+ }
1606
+
1408
1607
  /**
1409
1608
  * RightKit names its unit on every run (#1325, Adrian 2026-10-31: "the unit has to be mentioned. Okay, so either it is one specific unit, or it is
1410
1609
  * a JSON file that is created at that time, or all with my exception"). A door run with no `--unit` is accepted in RightKit only with
1411
- * `--units-file` (each listed unit runs as its own unit run, in order, on the one selected commit, stopping at the first that fails) or
1412
- * `--all-units-exception <id>` (the whole-repository run, by Adrian's entry in the commit's ci/all-units-exceptions.json). Both flags name RightKit
1610
+ * `--changed [--base <ref>]` (the changed units plus their dependents, planned from the commit's fixed inventory: the routine
1611
+ * route, no handwritten list), `--units-file` (an explicit list, parsed into the same shared run) or
1612
+ * `--all-units-exception <id>` (the whole-repository run, by Adrian's entry in the commit's ci/all-units-exceptions.json). All flags name RightKit
1413
1613
  * units, so a repository that is not RightKit refuses them. Returns `{ exit }` when the run ends here, or `{}` to go on as a whole door run (the
1414
1614
  * all-units flag and its id are removed from `args`). An unresolvable commit is runStages' own refusal, so it goes on.
1415
1615
  */
@@ -1424,35 +1624,59 @@ export function sampleAppOf({ o, root, git, commit }) {
1424
1624
  return apps.find((dir) => typeof dir === "string" && dir && !dir.includes("..") && (rel === dir || rel.startsWith(`${dir}/`))) ?? null;
1425
1625
  }
1426
1626
 
1427
- export async function rightkitDoorRule(o, args, root, git, io, { unitsFileFlag, allUnitsFlag, unitList }) {
1627
+ export async function rightkitDoorRule(o, args, root, git, io, { unitsFileFlag, allUnitsFlag, unitList, changedFlag = false }) {
1428
1628
  const tag = "rightkit-gate:";
1429
1629
  const option = (name) => { const i = args.indexOf(name); return i < 0 ? undefined : args[i + 1]; };
1430
1630
  let pinned;
1431
1631
  try { pinned = (await import("../snapshot.mjs")).resolveCommit(root, option("--commit") ?? "HEAD"); } catch { return {}; }
1432
1632
  const inRightKit = rightkitIdentityAt(git, pinned.commit);
1433
1633
  if (!inRightKit) {
1434
- if (!unitsFileFlag && !allUnitsFlag) return {};
1435
- o.err(`${tag} BLOCKED: ${unitsFileFlag ? "--units-file" : "--all-units-exception"} names RightKit units and ${pinned.commit.slice(0, 12)} is not RightKit; every other repository is built whole from the ${CARGO_WORKSPACE_LIST_KEY} list committed in ${CARGO_WORKSPACE_LIST_FILE}, with no unit named; nothing ran`);
1634
+ if (!unitsFileFlag && !allUnitsFlag && !changedFlag) return {};
1635
+ const flag = unitsFileFlag ? "--units-file" : changedFlag ? "--changed" : "--all-units-exception";
1636
+ o.err(`${tag} BLOCKED: ${flag} names RightKit units and ${pinned.commit.slice(0, 12)} is not RightKit; every other repository is built whole from the ${CARGO_WORKSPACE_LIST_KEY} list committed in ${CARGO_WORKSPACE_LIST_FILE}, with no unit named; nothing ran`);
1436
1637
  return { exit: 1 };
1437
1638
  }
1438
- if (unitsFileFlag) {
1639
+ if (unitsFileFlag || changedFlag) {
1439
1640
  const stage = option("--to");
1440
- const given = args.filter((a, i) => a.startsWith("--") && args[i - 1] !== "--units-file" && a !== "--units-file");
1441
- if (given.some((a) => a !== "--to" && a !== "--commit" && a !== "--receipt-dir")) { o.err(`${tag} a unit list run takes only --to, --units-file and optional --commit and --receipt-dir (one receipt file per unit is written into the directory)`); return { exit: 2 }; }
1641
+ const ownFlag = unitsFileFlag ? "--units-file" : "--changed";
1642
+ const allowed = unitsFileFlag ? ["--to", "--commit", "--receipt-dir"] : ["--to", "--commit", "--receipt-dir", "--base", "--changed"];
1643
+ const given = args.filter((a, i) => a.startsWith("--") && !(unitsFileFlag && args[i - 1] === ownFlag) && a !== ownFlag);
1644
+ if (given.some((a) => !allowed.includes(a))) { o.err(`${tag} a unit list run takes only --to, ${ownFlag} and optional --commit and --receipt-dir${changedFlag ? " and --base" : ""} (one receipt file per unit is written into the directory)`); return { exit: 2 }; }
1442
1645
  const receiptDir = option("--receipt-dir");
1443
1646
  if (receiptDir !== undefined && (receiptDir.startsWith("--") || !path.isAbsolute(receiptDir))) { o.err(`${tag} --receipt-dir needs an absolute directory`); return { exit: 2 }; }
1444
- // One Class A for the whole list (rightkit#1505; Adrian, 2026-10-31: "a JSON file that is created at that time"): the first unit's Class A is scoped to
1445
- // every listed unit's directory (the repeatable --scope), and a pass is remembered for the commit and rule tier, so the other units do not run it again.
1446
- // Before this, each unit ran its own Class A: 145 s median of a 206 s unit run on 2026-11-04, the same scans on the same commit 168 times.
1447
- const dirOf = (sel) => { const m = /^(?:npm:@rightkit\/([a-z0-9-]+)|cargo:(rightkit-[a-z0-9-]+))$/.exec(sel); return m ? (m[1] ? `packages/${m[1]}` : `crates/${m[2]}`) : null; };
1448
- const unitListClassA = { dirs: [...new Set(unitList.map(dirOf).filter(Boolean))], memo: new Map() };
1449
- for (const [i, selector] of unitList.entries()) {
1450
- o.out(`${tag} unit list ${i + 1}/${unitList.length}: ${selector} on commit ${pinned.commit.slice(0, 12)}`);
1451
- const receipt = receiptDir === undefined ? [] : ["--receipt-out", path.join(receiptDir, `gate-${selector.replace(/^npm:@rightkit\//, "npm-").replace(/^cargo:/, "")}.json`)];
1452
- const code = await main(["--to", stage, "--unit", selector, "--commit", pinned.commit, ...receipt], { ...io, unitListClassA });
1453
- if (code !== 0) { o.err(`${tag} BLOCKED: unit ${selector} ended with exit ${code}; ${unitList.length - i - 1} unit(s) of the list did not run`); return { exit: code }; }
1647
+ // A complete inventory is required for both selection and dependency blocking.
1648
+ let inventory = null;
1649
+ try { inventory = inventoryAtCommit({ git, commit: pinned.commit }); }
1650
+ catch (e) {
1651
+ o.err(`${tag} BLOCKED: cannot plan ${ownFlag} on ${pinned.commit.slice(0, 12)}: ${e.message}; nothing ran`); return { exit: 2 };
1454
1652
  }
1455
- return { exit: 0 };
1653
+ if (unitsFileFlag) {
1654
+ const unknown = unitList.filter((selector) => !inventory.units.some((u) => u.selector === selector));
1655
+ if (unknown.length) { o.err(`${tag} BLOCKED: units missing from inventory: ${unknown.join(", ")}; nothing ran`); return { exit: 2 }; }
1656
+ const selected = unitList.map((selector) => ({ selector, reason: "listed" }));
1657
+ return { exit: await runSharedUnitList({ o, io, stage, commit: pinned.commit, selected, inventory, receiptDir }) };
1658
+ }
1659
+ // --changed (rightkit#1505): no handwritten list for routine work. Changed paths against the base select their
1660
+ // units plus every transitive dependent (affected-units.mjs); the plan is printed before anything runs.
1661
+ const base = option("--base") ?? "origin/main";
1662
+ let selection;
1663
+ try {
1664
+ const mergeBase = git("merge-base", base, pinned.commit);
1665
+ if (failed(mergeBase)) throw new Error(`cannot resolve merge base: ${why(mergeBase)}`);
1666
+ const oldInventory = inventoryAtCommit({ git, commit: text(mergeBase).trim() });
1667
+ const changedPaths = changedPathsAt({ git, base, commit: pinned.commit });
1668
+ selection = selectAffectedAcrossInventories({ changedPaths, oldInventory, inventory });
1669
+ if (selection.unmatched.length) throw new Error(`unclassified changed inputs: ${selection.unmatched.join(", ")}; classify their ownership before running`);
1670
+ }
1671
+ catch (e) { o.err(`${tag} BLOCKED: cannot plan --changed on ${pinned.commit.slice(0, 12)}: ${e.message}; nothing ran`); return { exit: 2 }; }
1672
+ o.out(`${tag} changed plan: ${selection.selected.length} unit(s) affected by ${base}...${pinned.commit.slice(0, 12)}${selection.unmatched.length ? `; ${selection.unmatched.length} changed path(s) select no unit (${selection.unmatched.slice(0, 5).join(", ")}${selection.unmatched.length > 5 ? ", ..." : ""})` : ""}`);
1673
+ for (const s of selection.selected) o.out(`${tag} planned ${s.selector} (${s.reason}${s.via ? ` via ${s.via}` : ""})`);
1674
+ if (!selection.selected.length) {
1675
+ if (receiptDir !== undefined) { try { o.mkdir(receiptDir); } catch (e) { o.err(`${tag} BLOCKED: receipt directory must be new: ${receiptDir} (${e.message}); nothing ran`); return { exit: 2 }; } o.writeFile(path.join(receiptDir, "units-report.json"), `${JSON.stringify({ ...unitListReport({ commit: pinned.commit, stage, base, selected: [], results: [], unmatched: selection.unmatched }), runId: randomUUID() }, null, 2)}\n`); }
1676
+ o.out(`${tag} unit report: 0 passed, 0 failed, 0 blocked, 0 not-run of 0 on ${pinned.commit.slice(0, 12)}`);
1677
+ return { exit: 0 };
1678
+ }
1679
+ return { exit: await runSharedUnitList({ o, io, stage, commit: pinned.commit, selected: selection.selected, inventory, receiptDir, base, unmatched: selection.unmatched }) };
1456
1680
  }
1457
1681
  if (allUnitsFlag) {
1458
1682
  const id = option("--all-units-exception");
@@ -1476,7 +1700,7 @@ export async function rightkitDoorRule(o, args, root, git, io, { unitsFileFlag,
1476
1700
  o.out(`${tag} RightKit sample app ${sample}: built as an app, scoped to ${sample} (ci/sample-apps.json)`);
1477
1701
  return {};
1478
1702
  }
1479
- o.err(`${tag} BLOCKED: RK_UNIT_NOT_NAMED: RightKit names its unit on every run: --unit <cargo:rightkit-name|npm:@rightkit/name>, --units-file <json written for this run>, or --all-units-exception <id> (Adrian's entry in ${ALL_UNITS_EXCEPTIONS_FILE}); a whole-repository run is never the default; nothing ran`);
1703
+ o.err(`${tag} BLOCKED: RK_UNIT_NOT_NAMED: RightKit names its unit on every run: --unit <cargo:rightkit-name|npm:@rightkit/name>, --changed [--base <ref>] (changed units plus dependents, planned from the commit), --units-file <json written for this run>, or --all-units-exception <id> (Adrian's entry in ${ALL_UNITS_EXCEPTIONS_FILE}); a whole-repository run is never the default; nothing ran`);
1480
1704
  return { exit: 1 };
1481
1705
  }
1482
1706
 
@@ -1641,7 +1865,7 @@ async function runStages(o, args, root, git, io) {
1641
1865
  let childOk = false;
1642
1866
  try {
1643
1867
  o.out(`${tag} [${stage}] right-release ${cliArgs.join(" ")}${sourceOf ? ` (from the snapshot ${ds.path})` : ""}`);
1644
- const r = (o.spawnInherit ?? ((cmd, a, opts) => spawnInherit(cmd, a, { ...opts, stdio: "inherit" })))(process.execPath, [cli, ...cliArgs], { cwd: sourceOf ? snapshotAppRootOf(ds.path, appDir) : appRoot, env: carriedEnv(carrier, { ...o.env, ...run.env }, extraEnv) });
1868
+ const r = (o.spawnInherit ?? inheritLaunch)(process.execPath, [cli, ...cliArgs], { cwd: sourceOf ? snapshotAppRootOf(ds.path, appDir) : appRoot, env: carriedEnv(carrier, { ...o.env, ...run.env }, extraEnv) });
1645
1869
  childOk = r.status === 0;
1646
1870
  } finally { endRun(run); }
1647
1871
  const carriedOk = await carrier.finish({ stage });
@@ -2252,7 +2476,7 @@ export async function stageWebBuildOnce({ o, ds, root, git = null, appDir, cli,
2252
2476
  let r = restored ? { status: 0 } : null;
2253
2477
  if (!restored) try {
2254
2478
  o.out(`${tag} [${stage}] right-release web-build --config ${path.join(ds.path, config)} (from the snapshot ${ds.path}; declared input(s) ${absent().join(", ")} are absent)`);
2255
- r = (o.spawnInherit ?? ((cmd, a, opts) => spawnInherit(cmd, a, { ...opts, stdio: "inherit" })))(process.execPath, [cli, "web-build", "--config", path.join(ds.path, config)], { cwd: snapshotAppRootOf(ds.path, appDir), env: carriedEnv(carrier, { ...cleanEnv, ...run.env }) });
2479
+ r = (o.spawnInherit ?? inheritLaunch)(process.execPath, [cli, "web-build", "--config", path.join(ds.path, config)], { cwd: snapshotAppRootOf(ds.path, appDir), env: carriedEnv(carrier, { ...cleanEnv, ...run.env }) });
2256
2480
  } finally { endRun(run); }
2257
2481
  const carriedOk = await carrier.finish({ stage });
2258
2482
  if (!r || r.status !== 0) { o.err(`${tag} [${stage}] web-build for ${config} failed${r?.error ? ` (${r.error.message})` : ""}`); return false; }
@@ -2515,6 +2739,7 @@ async function runUnitSnapshot(o, args, root, git, io, option) {
2515
2739
  const which = (cmd) => { const r = o.spawn(o.platform === "win32" ? "where" : "which", [cmd]); return failed(r) ? [] : text(r).split(/\r?\n/).map((l) => l.trim()).filter(Boolean); };
2516
2740
  const executor = (o.resolveExecutor ?? gateResolveExecutor)({ env: o.env, platform: o.platform, exists: o.exists, which, readFile: o.readFile }); applyExecutorEnv(o, executor);
2517
2741
  if (executor.kind === "refuse") { o.err(`${tag} BLOCKED: ${executor.problem}`); return 1; }
2742
+ if (option("--ci-proof-out") && executor.kind !== "broker") { o.err(`${tag} BLOCKED: --ci-proof-out requires the managed snapshot broker`); return 1; }
2518
2743
  { const decided = routePlan(o, { to: option("--to"), stages: [], devTest: true, executor, capabilities: await brokerCapabilityStateWithHandshake(o, { to: option("--to"), executor }) });
2519
2744
  if (decided.refusal?.code === "RK_BROKER_CAPABILITY_MISSING") { o.err(`${tag} BLOCKED: ${decided.refusal.code}: ${decided.refusal.message}; nothing ran`); return 1; } }
2520
2745
  if (executor.kind === "broker" && !o.snapshotBroker) { o.err(`${tag} BLOCKED: RK_SNAPSHOT_CARRIER_NOT_WIRED: a broker host builds a unit snapshot only through the snapshot carrier; nothing ran`); return 1; }
@@ -2525,7 +2750,7 @@ async function runUnitSnapshot(o, args, root, git, io, option) {
2525
2750
  let own;
2526
2751
  try { own = (o.acquireOwnership ?? acquireBuildOwnership)({ file: ownershipFile({ platform: o.platform, beside: o.snapshotRoot, repository: snap.repositoryOf(root).key }), stage: `door:unit:${option("--to")}`, snapshot: path.join(snapshotsAt, snap.repositoryOf(root).key), commit, platform: o.platform, env: o.env }); }
2527
2752
  catch (e) { if (e.code !== "busy" && e.code !== "refused") throw e; o.err(`${tag} BLOCKED: ${e.message}; nothing ran${e.code === "refused" ? ", nothing created" : ""}`); return 1; }
2528
- o.out(`${tag} build ownership ${own.joined ? "joined" : "held"} ${own.handle}`);
2753
+ o.out(`${tag} build ownership ${own.joined ? "joined" : "held"} ${own.handle}${own.reclaimed ? ` (reclaimed from ${own.reclaimed.from}: ${own.reclaimed.proofs.join("; ")})` : ""}`);
2529
2754
  try {
2530
2755
  let synced;
2531
2756
  try { synced = (o.syncSnapshot ?? snap.syncSnapshot)({ checkout: root, rev: commit, root: snapshotsAt }); }
@@ -2533,17 +2758,22 @@ async function runUnitSnapshot(o, args, root, git, io, option) {
2533
2758
  o.out(`${tag} snapshot ${synced.path} is commit ${synced.commit} tree ${synced.tree} (written=${synced.written} removed=${synced.removed} unchanged=${synced.unchanged})`);
2534
2759
  if (synced.identity) o.out(`${tag} source identity ${synced.identity.file}: ${synced.identity.written ? "written" : synced.identity.kept ? "kept" : `not written (${synced.identity.reason})`}`);
2535
2760
  const ds = { own, path: synced.path, commit: synced.commit, tree: synced.tree, root: snapshotsAt, ledger: { entries: [] } };
2761
+ if (io[UNIT_LIST_UNION]) return await runUnionSnapshot({ o, io, root, git, ds, union: io[UNIT_LIST_UNION], unitListClassA: io.unitListClassA });
2536
2762
  // A unit's test or pack that reaches Cargo must never write `target/` into the snapshot (npm units included): see bindUnitCargo.
2537
2763
  // A check starts no unit command: its own Class A path binds read-only Cargo calls. Resolving every unit's compile output
2538
2764
  // here would run unrelated metadata before the scoped check even begins.
2539
2765
  // A crate's consumer rows (ci/gate.config.json rust.<crate>.consumerRows, local-publish.mjs) build their own Cargo workspaces under ci/consumers/: they
2540
2766
  // are part of this unit's compile, so they are bound beside the crate's workspace (read from the snapshot, which is the commit's tree).
2767
+ let privateUnit;
2768
+ try { privateUnit = privateUnitManifest({ selector, content: o.readFile(path.join(ds.path, manifest)) }); }
2769
+ catch (e) { o.err(`${tag} BLOCKED: ${e.message}; nothing ran`); return 1; }
2770
+ if (privateUnit.private && !["check", "compile"].includes(option("--to"))) { o.err(`${tag} BLOCKED: ${selector} is private and cannot be packaged, qualified or published`); return 1; }
2541
2771
  let consumerScope = [];
2542
2772
  if (match[2] && !toolRun) {
2543
2773
  try { consumerScope = [...new Set((JSON.parse(fs.readFileSync(path.join(ds.path, "ci", "gate.config.json"), "utf8")).rust?.[match[2]]?.consumerRows ?? []).map((row) => path.posix.dirname(String(row.manifestPath))))]; }
2544
2774
  catch { consumerScope = []; }
2545
2775
  }
2546
- const bound = option("--to") === "check" ? { env: {}, cleanup() {} } : await bindUnitCargo({ o, git, root, ds, executor, which, scopeDirs: [path.posix.dirname(manifest)], extraWorkspaces: consumerScope, ...(toolRun ? { onlyWorkspaces: [path.posix.dirname(manifest)] } : {}) });
2776
+ const bound = option("--to") === "check" || privateUnit.private ? { env: {}, cleanup() {} } : await bindUnitCargo({ o, git, root, ds, executor, which, scopeDirs: [path.posix.dirname(manifest)], extraWorkspaces: consumerScope, ...(toolRun ? { onlyWorkspaces: [path.posix.dirname(manifest)] } : {}) });
2547
2777
  if (bound.refusal) { o.err(`${tag} BLOCKED: RK_SNAPSHOT_OUTPUT_UNPINNED: ${bound.refusal}; nothing ran`); return 1; }
2548
2778
  if (bound.note) o.out(`${tag} ${bound.note}`);
2549
2779
  const envExtra = bound.env;
@@ -2564,12 +2794,41 @@ async function runUnitSnapshot(o, args, root, git, io, option) {
2564
2794
  const shared = io.unitListClassA?.dirs?.includes(unitDir) ? io.unitListClassA : null;
2565
2795
  const runCheck = async (tier) => {
2566
2796
  const memoKey = `${ds.commit}:${tier}`;
2567
- if (shared && shared.memo.get(memoKey) === 0) { o.out(`${tag} class A (${tier} tier) of this unit list already passed on ${ds.commit.slice(0, 12)}: not run again`); return 0; }
2797
+ // One Class A verdict per commit and tier for the whole list, pass or fail: the scope is every listed unit's
2798
+ // directory, so re-running it per unit after a failure would repeat the same red scans once per unit.
2799
+ if (shared && shared.memo.has(memoKey)) { const remembered = shared.memo.get(memoKey); o.out(`${tag} class A (${tier} tier) of this unit list already ${remembered === 0 ? "passed" : `failed (exit ${remembered})`} on ${ds.commit.slice(0, 12)}: not run again`); return remembered; }
2568
2800
  const scopes = shared ? shared.dirs : [unitDir];
2569
2801
  const code = await (o.runCheck ?? (() => main(["check", "--commit", ds.commit, "--full-a", "--snapshot", ds.path, "--rule-tier", tier, ...scopes.flatMap((d) => ["--scope", d])], { ...io, cwd: root, buildOwnership: own })))(tier);
2570
- if (shared && code === 0) shared.memo.set(memoKey, 0);
2802
+ if (shared) shared.memo.set(memoKey, code);
2571
2803
  return code;
2572
2804
  };
2805
+ if (privateUnit.private) {
2806
+ if (!localBuildGrantedAt(source)) { o.err(`${tag} BLOCKED: ${selector} requires the committed local-build grant`); return 1; }
2807
+ if (option("--to") === "compile") {
2808
+ try {
2809
+ const { knownRedEntry } = await import("../unit-gate.mjs");
2810
+ const red = knownRedEntry({ unit: privateUnit, root: ds.path, platform: o.platform });
2811
+ if (red) { o.err(`${tag} BLOCKED: ${selector} is known red (${red.host}: ${red.reason}); nothing compiled`); return 1; }
2812
+ } catch (e) { o.err(`${tag} BLOCKED: ${e.message}; nothing compiled`); return 1; }
2813
+ }
2814
+ const report = { schema: "rightkit.unit-gate-report/1", unit: privateUnit, commit: ds.commit, tree: ds.tree, executor: executor.kind, stages: {} };
2815
+ const save = () => { if (reportOut) o.writeFile(path.resolve(o.cwd, reportOut), `${JSON.stringify(report, null, 2)}\n`); };
2816
+ for (const stage of option("--to") === "compile" ? ["check", "compile"] : ["check"]) {
2817
+ let code = 1;
2818
+ if (await openSnapshotStage({ o, ds, root, stage, tag })) {
2819
+ try {
2820
+ code = stage === "check" ? await runCheck("compile") : await main(["--all", "--commit", ds.commit, "--snapshot", ds.path, "--scope", unitDir], {
2821
+ ...io, cwd: root, readStdin: () => "", buildOwnership: own, classAEarlier: true, snapshotLedger: ds.ledger?.entries ?? [],
2822
+ onCompileLedger: (entries) => { ds.compileAdmitted = entries; }, [PRIVATE_SCOPED_COMPILE]: { selector, unitDir },
2823
+ });
2824
+ } catch (e) { o.err(`${tag} ${selector} ${stage}: ${e.message}`); code = 1; }
2825
+ if (!(await closeSnapshotStage({ o, ds, root, stage, step: `unit:${stage}`, tag })).ok) code = 1;
2826
+ }
2827
+ report.stages[stage] = { ok: code === 0, code }; save();
2828
+ if (code !== 0) return code;
2829
+ }
2830
+ return 0;
2831
+ }
2573
2832
  if (toolRun) {
2574
2833
  const { runUnitTool } = await import("../tool-build.mjs");
2575
2834
  return await runUnitTool({ selector, root: ds.path, commonDir: path.resolve(root, text(common).trim()), commit: ds.commit, tree: ds.tree, executor, env: o.env, platform: o.platform, source, envExtra, targetDirs: bound.targetDirs ?? {},
@@ -2579,7 +2838,7 @@ async function runUnitSnapshot(o, args, root, git, io, option) {
2579
2838
  ...(reportOut ? { writeReport: (report) => o.writeFile(path.resolve(o.cwd, reportOut), `${JSON.stringify(o.brokerException ? { ...report, brokerException: o.brokerException } : report, null, 2)}\n`) } : {}),
2580
2839
  });
2581
2840
  }
2582
- return await runUnitGate({ selector, to: option("--to"), root: ds.path, commonDir: path.resolve(root, text(common).trim()), commit: ds.commit, tree: ds.tree, executor, env: o.env, platform: o.platform, source, envExtra,
2841
+ return await runUnitGate({ selector, to: option("--to"), root: ds.path, commonDir: path.resolve(root, text(common).trim()), commit: ds.commit, tree: ds.tree, executor, env: o.env, platform: o.platform, source, envExtra, ciProofOut: option("--ci-proof-out") ?? null,
2583
2842
  resolve: (sel, r) => resolveUnit(sel, r, { granted: () => localBuildGrantedAt(source) }),
2584
2843
  ...(o.loadUnitOwner ? { loadOwner: o.loadUnitOwner } : {}),
2585
2844
  ...(o.unitGateDeps ?? {}), // test seam: fetchReceipt, stageCommands, verifyReceipts, selfGit
@@ -2593,6 +2852,50 @@ async function runUnitSnapshot(o, args, root, git, io, option) {
2593
2852
  }
2594
2853
  }
2595
2854
 
2855
+ /** One owner, one snapshot and one shared Class A before a unit-list compile. */
2856
+ async function runUnionSnapshot({ o, io, root, git, ds, union, unitListClassA }) {
2857
+ const tag = "rightkit-gate:";
2858
+ const { localBuildGrantedAt, consumerRows } = await import("../local-publish.mjs");
2859
+ const { knownRedEntry } = await import("../unit-gate.mjs");
2860
+ const source = { checkout: root, commit: ds.commit, tree: ds.tree };
2861
+ if (!localBuildGrantedAt(source)) { o.err(`${tag} BLOCKED: unit list requires the committed local-build grant`); return 1; }
2862
+ let config;
2863
+ try {
2864
+ config = JSON.parse(o.readFile(path.join(ds.path, "ci/gate.config.json")));
2865
+ union.consumerDirs = [];
2866
+ for (const row of union.selected) {
2867
+ const file = row.selector.startsWith("cargo:") ? `${row.dir}/Cargo.toml` : `${row.dir}/package.json`;
2868
+ if (failed(git("cat-file", "-e", `${ds.commit}:${file}`))) throw new Error(`${file} is absent from the selected commit`);
2869
+ const unit = privateUnitManifest({ selector: row.selector, content: o.readFile(path.join(ds.path, file)) });
2870
+ const red = knownRedEntry({ unit, root: ds.path, platform: o.platform });
2871
+ if (red) throw new Error(`${row.selector} is known red (${red.host}: ${red.reason})`);
2872
+ if (unit.kind === "cargo") for (const consumer of consumerRows(unit.name, config.rust?.[unit.name] ?? {})) {
2873
+ for (const required of [consumer.manifestPath, consumer.manifestPath.replace(/Cargo\.toml$/, "Cargo.lock")]) if (failed(git("cat-file", "-e", `${ds.commit}:${required}`))) throw new Error(`${required} is absent from the selected commit`);
2874
+ const dir = path.posix.dirname(consumer.manifestPath);
2875
+ union.consumerDirs.push(dir); unitListClassA.dirs.push(dir);
2876
+ }
2877
+ }
2878
+ unitListClassA.dirs = [...new Set(unitListClassA.dirs)];
2879
+ } catch (error) { o.err(`${tag} BLOCKED: cannot prepare unit-list scope: ${error.message}`); return 1; }
2880
+ if (!await openSnapshotStage({ o, ds, root, stage: "check", tag })) return 1;
2881
+ let check = 1;
2882
+ try { check = await (o.runCheck ?? (() => main(["check", "--commit", ds.commit, "--full-a", "--snapshot", ds.path, "--rule-tier", "compile", ...unitListClassA.dirs.flatMap((dir) => ["--scope", dir])], { ...io, cwd: root, buildOwnership: ds.own, [UNIT_LIST_UNION]: union })))("compile"); }
2883
+ catch (error) { o.err(`${tag} unit-list check: ${error.message}`); }
2884
+ if (!(await closeSnapshotStage({ o, ds, root, stage: "check", tag })).ok || check !== 0) return check || 1;
2885
+ if (!await openSnapshotStage({ o, ds, root, stage: "compile", tag })) return 1;
2886
+ let code = 1;
2887
+ try {
2888
+ code = await main(["--all", "--commit", ds.commit, "--snapshot", ds.path, ...unitListClassA.dirs.flatMap((dir) => ["--scope", dir])], {
2889
+ ...io, cwd: root, readStdin: () => "", buildOwnership: ds.own, classAEarlier: true, snapshotLedger: ds.ledger?.entries ?? [],
2890
+ onCompileLedger: (entries) => { ds.compileAdmitted = entries; }, [UNIT_LIST_UNION]: union,
2891
+ verifyUnionSnapshot: async () => { await verifyDoorSnapshot(o, ds, root, { ledger: ds.ledger?.entries ?? [] }); return true; },
2892
+ });
2893
+ } catch (error) { o.err(`${tag} unit-list compile: ${error.message}`); }
2894
+ const closed = await closeSnapshotStage({ o, ds, root, stage: "compile", tag });
2895
+ union.verified = closed.ok && union.completed === true && union.sharedClean === true;
2896
+ return closed.ok ? code : 1;
2897
+ }
2898
+
2596
2899
  /**
2597
2900
  * Whether the door takes the snapshot route on this host: every host but hosted CI, whose runner checkout is the commit. Linux
2598
2901
  * compiles it directly; Mac and Dell compile it through the RustRight snapshot carrier. There is no other route and no flag or
@@ -3185,7 +3488,7 @@ async function runDevTest(o, args, root, git, io, to, appRoot, appDir) {
3185
3488
  if (ds && !(await closeSnapshotStage({ o, ds, root, stage: to, step: to, tag })).ok) { o.err(`${tag} --to ${to} stopped: the result covers no known bytes`); return 2; }
3186
3489
  return rendered === 0 && carriedRendered ? 0 : 1;
3187
3490
  }
3188
- const r = (o.spawnInherit ?? ((cmd, a, opts) => spawnInherit(cmd, a, { ...opts, stdio: "inherit" })))(process.execPath, [cli, to, ...passthrough], { cwd: source ? snapshotAppRootOf(ds.path, appDir) : appRoot, env: childEnv });
3491
+ const r = (o.spawnInherit ?? inheritLaunch)(process.execPath, [cli, to, ...passthrough], { cwd: source ? snapshotAppRootOf(ds.path, appDir) : appRoot, env: childEnv });
3189
3492
  const carriedOk = await carrier.finish({ stage: to });
3190
3493
  if (ds && !(await closeSnapshotStage({ o, ds, root, stage: to, step: to, tag })).ok) { o.err(`${tag} --to ${to} stopped: the result covers no known bytes`); return 2; }
3191
3494
  return r.status === 0 && carriedOk ? 0 : 1;
@@ -3219,8 +3522,8 @@ export function doorPath(o, gateFile = o.gateFile ?? fileURLToPath(import.meta.u
3219
3522
  * lookup of a usable rustfmt, which the deferred Rust gate needs).
3220
3523
  */
3221
3524
  /** The gate flags a `--to <stage>` invocation takes (before a `--` separator, after which the arguments belong to right-release), and whether each takes a value. */
3222
- const STAGE_VALUE_FLAGS = Object.freeze(["--to", "--platform", "--tier", "--commit", "--receipt-in", "--receipt-out", "--unit", "--units-file", "--all-units-exception", "--receipt-dir"]);
3223
- const STAGE_BOOLEAN_FLAGS = Object.freeze(["--route"]);
3525
+ const STAGE_VALUE_FLAGS = Object.freeze(["--to", "--platform", "--tier", "--commit", "--receipt-in", "--receipt-out", "--unit", "--units-file", "--all-units-exception", "--receipt-dir", "--base", "--ci-proof-out"]);
3526
+ const STAGE_BOOLEAN_FLAGS = Object.freeze(["--route", "--changed"]);
3224
3527
 
3225
3528
  /**
3226
3529
  * Why `args` (a `--to <stage>` invocation) is not a well-formed request, or null. Every value flag needs a value that is not another flag and may be
@@ -3253,14 +3556,49 @@ export async function main(argv, io = {}) {
3253
3556
  gateFile: fileURLToPath(import.meta.url), ...io,
3254
3557
  };
3255
3558
  const args = [...argv];
3559
+ if (args.includes("--ci-proof-out")) {
3560
+ try {
3561
+ const problem = stageArgsProblem(args);
3562
+ if (problem) throw new Error(problem);
3563
+ const value = (flag) => { const i = args.indexOf(flag); return i < 0 ? null : args[i + 1]; };
3564
+ if (args.some((arg, i) => i % 2 === 0 && !["--to", "--unit", "--commit", "--receipt-out", "--ci-proof-out"].includes(arg)) || value("--to") !== "compile" || value("--unit") !== "cargo:rightkit-decimal" || args.includes("--cargo-jobs")) throw new Error("--ci-proof-out requires the single cargo:rightkit-decimal snapshot compile route");
3565
+ if (o.doorSnapshot || !snapshotRouteSelected(o) || !["darwin", "win32"].includes(o.platform)) throw new Error("--ci-proof-out requires the managed Mac or Windows snapshot broker route");
3566
+ const paths = o.platform === "win32" ? path.win32 : path.posix;
3567
+ const scratch = o.platform === "win32" ? "D:\\scratch" : "/Volumes/D/scratch";
3568
+ const file = value("--ci-proof-out");
3569
+ if (!file || !paths.isAbsolute(file)) throw new Error("--ci-proof-out needs an absolute path inside D scratch");
3570
+ const scratchReal = fs.realpathSync.native(scratch);
3571
+ const parentReal = fs.realpathSync.native(paths.dirname(file));
3572
+ const relative = paths.relative(scratchReal, parentReal);
3573
+ if (relative === ".." || relative.startsWith(`..${paths.sep}`) || paths.isAbsolute(relative)) throw new Error("--ci-proof-out parent is outside D scratch");
3574
+ try { fs.lstatSync(file); throw new Error("--ci-proof-out already exists"); }
3575
+ catch (error) { if (error.code !== "ENOENT") throw error; }
3576
+ } catch (error) { o.err(`rightkit-gate: ${error.message}`); return 2; }
3577
+ }
3578
+ const widthFlags = args.reduce((found, arg, i) => arg === "--cargo-jobs" ? [...found, i] : found, []);
3579
+ if (widthFlags.length) {
3580
+ try {
3581
+ if (widthFlags.length !== 1 || io[CARGO_WIDTH] !== undefined) throw new Error("--cargo-jobs may be given once");
3582
+ const index = widthFlags[0];
3583
+ if (args.includes("--") && index > args.indexOf("--")) throw new Error("--cargo-jobs must precede --");
3584
+ const width = parseCargoWidth(args[index + 1]);
3585
+ const routeProblem = cargoWidthRouteProblem(args);
3586
+ if (routeProblem) throw new Error(routeProblem);
3587
+ args.splice(index, 2);
3588
+ io = { ...io, [CARGO_WIDTH]: width };
3589
+ o[CARGO_WIDTH] = width;
3590
+ } catch (error) { o.err(`rightkit-gate: ${error.message}`); return 2; }
3591
+ }
3256
3592
  // rightkit#1463: a run that does work (a door stage, or a class A / full pass) stamps every log line with its UTC time, so phase times no longer have to be
3257
3593
  // rebuilt from broker receipts. Machine-readable output is never stamped: the --route JSON, a list or baseline, --json, the version, and the one
3258
3594
  // `verdict deterministic` marker line other tools read.
3259
3595
  const stampsLines = (args.includes("--to") || args.includes("--full-a") || args.includes("--all"))
3260
3596
  && !args.some((a) => ["--route", "--list", "--print-baseline", "--json", "--plan", "--version", "-v", "--help", "-h"].includes(a));
3261
3597
  if (stampsLines) {
3262
- const stamped = (write) => (m) => write(/^rightkit-gate: verdict deterministic/.test(String(m)) ? m : `${new Date().toISOString()} ${m}`);
3598
+ // Every line of a multi-line message carries the stamp, not only its first.
3599
+ const stamped = (write) => (m) => { if (/^rightkit-gate: verdict deterministic/.test(String(m))) return write(m); const at = new Date().toISOString(); return write(String(m).split("\n").map((l) => `${at} ${l}`).join("\n")); };
3263
3600
  o.out = stamped(o.out); o.err = stamped(o.err);
3601
+ stampChildLines = true;
3264
3602
  }
3265
3603
  // The cache bypass is retired (GC-T14; workspace rule: never write or run a no-cache option). Refused by name so an old caller learns why.
3266
3604
  if (args.includes("--no-cache") || (io.env ?? process.env).RK_GATE_CACHE === "0") {
@@ -3383,7 +3721,13 @@ export async function main(argv, io = {}) {
3383
3721
  const withoutScope = args.slice(1).filter((a, i, list) => a !== "--scope" && list[i - 1] !== "--scope");
3384
3722
  const appArgs = stripSnapshot(withoutScope.filter((a) => a !== "--full-a"));
3385
3723
  if (fullAdmission && !appArgs.includes("--rule-tier")) appArgs.push("--rule-tier", requestedTier);
3386
- const appCheck = await (o.appCheck ?? (await import("../app-check.mjs")).main)(appArgs, { out: o.out, err: o.err, label: "check", cwd: o.cwd, ...(snapshotDir && !args.includes("--worktree") ? { snapshot: snapshotDir } : {}) });
3724
+ // GC-A24: a passing app-rule verdict of a snapshot is reused for the same commit tree, rule code, tier and arguments (ruleVerdictCache).
3725
+ const ruleCache = snapshotDir && snapshotCommit && !args.includes("--worktree") && !o.appCheck ? ruleVerdictCache({ checkout: snapshotCheckout, spawn: o.spawn }) : null;
3726
+ const appKey = ruleCache ? ruleCache.key({ rule: "app-check", tree: snapshotCommit.tree, args: appArgs, gate: gatePackageIdentity(o.gatePackage) }) : null;
3727
+ const appCheck = appKey && ruleCache.passed(appKey)
3728
+ ? (o.out(`check: ${snapshotCommit.commit.slice(0, 12)} app rules: cached pass (tree ${snapshotCommit.tree.slice(0, 12)})`), 0)
3729
+ : await (o.appCheck ?? (await import("../app-check.mjs")).main)(appArgs, { out: o.out, err: o.err, label: "check", cwd: o.cwd, ...(snapshotDir && !args.includes("--worktree") ? { snapshot: snapshotDir } : {}) });
3730
+ if (appKey && appCheck === 0) ruleCache.pass(appKey);
3387
3731
  if (args.includes("--list") || args.includes("--print-baseline") || args.includes("--only") || o.classA === false) {
3388
3732
  // A view of the app rules, never a class A verdict: say so, so no caller can take its exit 0 for a full check.
3389
3733
  // A green partial view exits PARTIAL_EXIT (3), never 0, so a caller that admits only exit 0 rejects it by status alone.
@@ -3423,18 +3767,25 @@ export async function main(argv, io = {}) {
3423
3767
  if (root && selfRules === 0 && snapshotDir && rightkitRepository && appCheck === 0 && classA === 0) {
3424
3768
  // The commit's own preflight reads the commit from the checkout's object database; its exports probe imports from the snapshot,
3425
3769
  // whose dependencies class A installed, and reports beside (never over) the commit-bound report publication reads.
3426
- const launch = o.spawnInherit ?? ((cmd, a, opts) => spawnInherit(cmd, a, { ...opts, stdio: "inherit" }));
3427
- const r = launch(process.execPath, [path.join(snapshotDir, "scripts", "preflight.mjs"), "--repo", root, "--commit", snapshotCommit.commit], { cwd: root, env: o.env });
3428
- selfRules = r.status === 0 ? 0 : 1;
3770
+ const launch = o.spawnInherit ?? inheritLaunch;
3771
+ // GC-A24: RightKit's own preflight and exports probe execute the commit's code with its installed dependencies; a pass is reused
3772
+ // for the same commit tree, installed-dependency bytes, node and platform (and scope), and only a pass.
3429
3773
  const effects = path.join(snapshotDir, "scripts", "ci", "exports-import-effects.mjs");
3430
- if (selfRules === 0 && o.exists(effects) && scopeForward.length === 0) {
3774
+ let selfKey = null;
3775
+ if (ruleCache) { try { selfKey = ruleCache.key({ rule: "rightkit-self-rules", tree: snapshotCommit.tree, scope: scopeForward, installed: installedDependencyDigest({ root: snapshotDir, files: sc.commitFiles(snapshotCheckout, snapshotCommit.commit, o.spawn).files, includeCaches: false }), effects: o.exists(effects) }); } catch { selfKey = null; } }
3776
+ const selfCached = Boolean(selfKey && ruleCache.passed(selfKey));
3777
+ if (selfCached) o.out(`preflight: ${snapshotCommit.commit.slice(0, 12)} cached pass (tree ${snapshotCommit.tree.slice(0, 12)}, same installed dependencies)`);
3778
+ const r = selfCached ? { status: 0 } : launch(process.execPath, [path.join(snapshotDir, "scripts", "preflight.mjs"), "--repo", root, "--commit", snapshotCommit.commit], { cwd: root, env: o.env });
3779
+ selfRules = r.status === 0 ? 0 : 1;
3780
+ if (!selfCached && selfRules === 0 && o.exists(effects) && scopeForward.length === 0) {
3431
3781
  const common = o.spawn("git", ["rev-parse", "--path-format=absolute", "--git-common-dir"], { cwd: root });
3432
3782
  const report = path.join(failed(common) ? path.join(root, ".git") : text(common).trim(), "rightkit-gate", "import-effects", `snapshot-${snapshotCommit.commit}.json`);
3433
3783
  const e = launch(process.execPath, [effects, "--root", snapshotDir, "--no-export", "--report", report], { cwd: snapshotDir, env: o.env });
3434
3784
  if (e.status !== 0) selfRules = 1;
3435
3785
  }
3786
+ if (selfKey && !selfCached && selfRules === 0) ruleCache.pass(selfKey);
3436
3787
  } else if (root && selfRules === 0 && !snapshotDir && (rightkitRepository || canon(self).startsWith(canon(root) + path.sep)) && o.exists(path.join(root, "scripts", "preflight.mjs")) && appCheck === 0 && classA === 0) {
3437
- const launch = o.spawnInherit ?? ((cmd, a, opts) => spawnInherit(cmd, a, { ...opts, stdio: "inherit" }));
3788
+ const launch = o.spawnInherit ?? inheritLaunch;
3438
3789
  const selector = args.includes("--worktree") ? ["--worktree"] : ["--commit", option("--commit") ?? "HEAD"];
3439
3790
  const r = launch(process.execPath, [path.join(root, "scripts", "preflight.mjs"), "--repo", root, ...selector], { cwd: root, env: o.env });
3440
3791
  selfRules = r.status === 0 ? 0 : 1;
@@ -3522,7 +3873,7 @@ export async function main(argv, io = {}) {
3522
3873
  // Full Class A needs a snapshot or the committed hosted checkout. The content pass (`check --commit <sha> --scope <dir>`: publication
3523
3874
  // admission, GC-A03) reads the commit the same way it always did (the warm snapshot, or the runner checkout proven to be that commit
3524
3875
  // in place) and only narrows which executing workspace scans run, so it is the one other form --scope accepts; never the live tree.
3525
- const scopeForm = fullA ? Boolean(snapshotA || hostedCommitA) : classAOnly && !args.includes("--worktree");
3876
+ const scopeForm = fullA ? Boolean(snapshotA || hostedCommitA) : (classAOnly && !args.includes("--worktree")) || Boolean(snapshotB && (o[PRIVATE_SCOPED_COMPILE] || o[UNIT_LIST_UNION]) && o.classAEarlier && o.buildOwnership);
3526
3877
  if (!scopeForm || bad !== undefined || scopeDirs.some((d) => d === undefined)) { o.err("rightkit-gate: --scope needs full Class A of a snapshot or committed hosted CI checkout & repository-relative directories"); return 2; }
3527
3878
  }
3528
3879
  if (args.includes("--base") && (!option("--base") || option("--base").startsWith("--"))) { o.err("rightkit-gate: --base needs a ref"); return 2; }
@@ -3567,18 +3918,19 @@ export async function main(argv, io = {}) {
3567
3918
  // RightKit names its unit on every run (rightkitDoorRule): `--unit <selector>`, `--units-file <json written for this run>` or
3568
3919
  // `--all-units-exception <id>`; exactly one. The unit list is read here, before anything runs, so a bad file is a usage error (exit 2).
3569
3920
  const gateFlag = (name) => args.includes(name) && (separator < 0 || args.indexOf(name) < separator);
3570
- const unitsFileFlag = gateFlag("--units-file"); const allUnitsFlag = gateFlag("--all-units-exception");
3921
+ const unitsFileFlag = gateFlag("--units-file"); const allUnitsFlag = gateFlag("--all-units-exception"); const changedFlag = gateFlag("--changed");
3571
3922
  let unitList = null;
3572
- if (unitsFileFlag || allUnitsFlag) {
3573
- const flag = unitsFileFlag ? "--units-file" : "--all-units-exception";
3923
+ if (unitsFileFlag || allUnitsFlag || changedFlag) {
3924
+ const flag = unitsFileFlag ? "--units-file" : changedFlag ? "--changed" : "--all-units-exception";
3574
3925
  if (option("--to") === undefined) { o.err(`rightkit-gate: ${flag} applies to a --to stage\n${USAGE}`); return 2; }
3575
- if ([unitFlag, unitsFileFlag, allUnitsFlag].filter(Boolean).length > 1) { o.err("rightkit-gate: name the unit once: --unit, --units-file or --all-units-exception, not several"); return 2; }
3576
- if (!option(flag) || option(flag).startsWith("--")) { o.err(`rightkit-gate: ${flag} needs a value\n${USAGE}`); return 2; }
3926
+ if ([unitFlag, unitsFileFlag, allUnitsFlag, changedFlag].filter(Boolean).length > 1) { o.err("rightkit-gate: name the unit once: --unit, --changed, --units-file or --all-units-exception, not several"); return 2; }
3927
+ if (!changedFlag && (!option(flag) || option(flag).startsWith("--"))) { o.err(`rightkit-gate: ${flag} needs a value\n${USAGE}`); return 2; }
3577
3928
  if (unitsFileFlag) {
3578
3929
  try { unitList = readUnitList((f) => o.readFile(path.resolve(o.cwd, f)), option("--units-file")); }
3579
3930
  catch (e) { o.err(`rightkit-gate: ${e.message}`); return 2; }
3580
3931
  }
3581
3932
  }
3933
+ if (option("--to") !== undefined && gateFlag("--base") && !changedFlag) { o.err("rightkit-gate: --base on a --to stage selects the diff base of --changed; pass --changed or drop --base"); return 2; }
3582
3934
  // `--no-broker <exception-id>`: the one documented exception to the mandatory broker on Mac and Dell (broker-exception.mjs). The record is
3583
3935
  // read from the selected commit, never the working tree; every refusal is typed and nothing runs. The run then takes the same stages
3584
3936
  // with the direct executor, and prints and records the exception.
@@ -3622,7 +3974,7 @@ export async function main(argv, io = {}) {
3622
3974
  const gateArgs = separator < 0 ? args : args.slice(0, separator);
3623
3975
  if (gateArgs.includes("--route")) {
3624
3976
  const routeTo = option("--to");
3625
- const clash = ["--unit", "--units-file", "--all-units-exception", "--receipt-in", "--receipt-out"].filter((f) => gateArgs.includes(f));
3977
+ const clash = ["--unit", "--units-file", "--all-units-exception", "--changed", "--receipt-in", "--receipt-out"].filter((f) => gateArgs.includes(f));
3626
3978
  if (routeTo === undefined) { o.err(`rightkit-gate: --route needs --to ${ROUTE_PROBE_STAGES.join("|")}\n${USAGE}`); return 2; }
3627
3979
  if (routeTo === "release") { o.err("rightkit-gate: --route answers for --to check|compile|package|qualify|dev|test; release uploads and has no route of its own"); return 2; }
3628
3980
  if (clash.length) { o.err(`rightkit-gate: --route runs nothing and takes no ${clash.join(" or ")}`); return 2; }
@@ -3630,9 +3982,9 @@ export async function main(argv, io = {}) {
3630
3982
  }
3631
3983
  if (option("--to") !== undefined && unitFlag) {
3632
3984
  const selector = option("--unit");
3633
- const validArgs = args.length % 2 === 0 && args.every((a, i) => i % 2 ? !a.startsWith("--") : ["--to", "--unit", "--receipt-out", "--commit"].includes(a)) && ["--to", "--unit", "--receipt-out", "--commit"].every((flag) => args.filter((a) => a === flag).length <= 1);
3985
+ const validArgs = args.length % 2 === 0 && args.every((a, i) => i % 2 ? !a.startsWith("--") : ["--to", "--unit", "--receipt-out", "--commit", "--ci-proof-out"].includes(a)) && ["--to", "--unit", "--receipt-out", "--commit", "--ci-proof-out"].every((flag) => args.filter((a) => a === flag).length <= 1);
3634
3986
  if (!validArgs || !selector) {
3635
- o.err("rightkit-gate: unit stages take only --to, --unit and optional --receipt-out and --commit"); return 2;
3987
+ o.err("rightkit-gate: unit stages take only --to, --unit and optional --receipt-out, --commit and --ci-proof-out"); return 2;
3636
3988
  }
3637
3989
  // Row 7.06a: on every host but hosted CI a unit stage builds the selected commit's snapshot (Linux direct, Mac and Dell through the carrier).
3638
3990
  if (!o.doorSnapshot && snapshotRouteSelected(o)) return await runUnitSnapshot(o, args, root, git, io, option);
@@ -3664,8 +4016,9 @@ export async function main(argv, io = {}) {
3664
4016
  if (unitFlag) { o.err("rightkit-gate: --unit requires --to"); return 2; }
3665
4017
  if (option("--to") !== undefined) {
3666
4018
  // A door run that names no unit: RightKit refuses it unless Adrian's exception or a unit list names what runs (rightkitDoorRule).
3667
- const door = await rightkitDoorRule(o, args, root, git, io, { unitsFileFlag, allUnitsFlag, unitList });
4019
+ const door = await rightkitDoorRule(o, args, root, git, io, { unitsFileFlag, allUnitsFlag, unitList, changedFlag });
3668
4020
  if (door.exit !== undefined) return door.exit;
4021
+ if (o[CARGO_WIDTH] !== undefined) { o.err("rightkit-gate: BLOCKED: --cargo-jobs requires the controlled unit-list route"); return 2; }
3669
4022
  return await runStages(o, args, root, git, io);
3670
4023
  }
3671
4024
  if (sub === "stage") return stageForPublisher(o, args, root, git);
@@ -3708,6 +4061,16 @@ export async function main(argv, io = {}) {
3708
4061
  const executor = (o.resolveExecutor ?? gateResolveExecutor)({ env: o.env, platform: o.platform, exists: o.exists, which, readFile: o.readFile }); applyExecutorEnv(o, executor);
3709
4062
  // A broker-managed host whose broker is unreachable refuses the moment a Cargo manifest is in the snapshot (below): a repository
3710
4063
  // with no Rust owes nothing to the broker (a git hook's minimal PATH, a JS-only app), and the class A scans never compile.
4064
+ if (o[CARGO_WIDTH] !== undefined && !classAOnly) {
4065
+ try {
4066
+ if (executor.kind !== "broker") throw new Error("--cargo-jobs requires a broker reporting its compile-token pool");
4067
+ const client = executor.client ?? "rustright";
4068
+ const result = spawnBrokerClient(o.spawn, client, ["list"], { env: brokerEnvOf(o, executor), encoding: "utf8", timeout: 20_000, windowsHide: true }, { platform: o.platform, readFile: o.readFile });
4069
+ if (failed(result)) throw new Error("cannot read broker compile-token pool");
4070
+ const size = validateCargoWidthPool(o[CARGO_WIDTH], JSON.parse(text(result)));
4071
+ o.out(`rightkit-gate: Cargo width ${o[CARGO_WIDTH]} (broker token pool ${size})`);
4072
+ } catch (error) { o.err(`rightkit-gate: BLOCKED: ${error.message}`); return 1; }
4073
+ }
3711
4074
  const cargoCommand = executor.cargo ?? ["cargo"];
3712
4075
  // The declared Linux broker route's cargo is `[<absolute validated client>, "cargo"]`, which the scan planner (planScans: `["rustright","cargo"]` or
3713
4076
  // `["cargo"]`) refuses, and a PATH `rustright` is never the client. So the scans are PLANNED with the logical `["rustright","cargo"]` and every spawn the
@@ -3739,7 +4102,9 @@ export async function main(argv, io = {}) {
3739
4102
  let cargoShimDir = null;
3740
4103
  const cleanup = () => {
3741
4104
  if (cargoShimDir) fs.rmSync(cargoShimDir, { recursive: true, force: true });
3742
- if (snapshotGitConfig) { fs.rmSync(snapshotGitConfig, { force: true }); try { fs.rmdirSync(path.dirname(snapshotGitConfig)); } catch { /* not empty: leave it, the next exact sync prunes it */ } }
4105
+ // GC-A24: the config-only origin file stays (snapshotProblem admits exactly it, and the sync keeps exactly it), so an unchanged
4106
+ // snapshot is not rewritten on every run; a snapshot of a checkout whose origin changed gets it pruned by the next sync.
4107
+ void snapshotGitConfig;
3743
4108
  };
3744
4109
  const signals = [];
3745
4110
  try {
@@ -3796,6 +4161,8 @@ export async function main(argv, io = {}) {
3796
4161
  // consumer rows of the crates they exercise (CI treats them the same), never as units.
3797
4162
  let fixtures = [];
3798
4163
  try { const f = JSON.parse(o.readFile(path.join(repo, GATE_CONFIG))).fixtures; if (Array.isArray(f)) fixtures = f.filter((d) => typeof d === "string"); } catch { /* no config: no fixtures */ }
4164
+ // Selected publisher consumer workspaces must participate in discovery, scoped Class A and target binding.
4165
+ if (o[UNIT_LIST_UNION]?.consumerDirs?.length) fixtures = fixtures.filter((d) => !o[UNIT_LIST_UNION].consumerDirs.some((c) => c === d.replace(/\/$/, "") || c.startsWith(`${d.replace(/\/$/, "")}/`)));
3799
4166
  // A snapshot has nothing untracked; the working tree (--plan, check --worktree) names its untracked manifests as skipped.
3800
4167
  const untracked = () => {
3801
4168
  if (snapshot) return [];
@@ -4057,6 +4424,7 @@ export async function main(argv, io = {}) {
4057
4424
  fullPlan = planScans({
4058
4425
  // Class A of a commit or tree reads only that snapshot: every scan, cargo's included, runs in the snapshot, never in the live
4059
4426
  // checkout (which may hold other bytes). Compiles (class B) use the live checkout, whose tree the dirty check pinned to HEAD.
4427
+ cargoJobs: classAOnly ? null : (o[CARGO_WIDTH] ?? null),
4060
4428
  changed, contentRoot: repo, liveRoot: (classAOnly && snapshot) || snapshotB ? repo : root, trustedRoot: snapshotA ?? snapshotB ?? root, includeTests: true, rustScope, cargoCommand: planCargoCommand, targetDirs, cargoShim: Boolean(cargoShim),
4061
4429
  tier: fullA ? "release" : (option("--rule-tier") ?? "compile"), cargoLiveRoot,
4062
4430
  // The quiet tests (port, pipe, desktop and wall-clock bound) are proven by the CI shards, one crate per runner, unless
@@ -4069,7 +4437,7 @@ export async function main(argv, io = {}) {
4069
4437
  rustUnits: rust.units, npmUnits: npm, npmRoots, cargoDir: ".", rustLocks, crateFeatures, crateDependents, externalInputs,
4070
4438
  // B1 (rightkit#1458): compile scans of one Cargo workspace run as one cargo invocation per configuration; ci/shards.json `solo` crates never join one.
4071
4439
  // Batching is on (RK_GATE_CLASS_B_BATCH=0 turns it off): the batch-equivalence run (GATE-CONTRACT GC-I11; Pulse 3b31b4ca, 2026-11-03) gave the same verdict on all 193 scans batched and per crate.
4072
- classBBatching: o.env.RK_GATE_CLASS_B_BATCH !== "0", shardSolo: shardSoloOf(o, repo),
4440
+ classBBatching: !o[PRIVATE_SCOPED_COMPILE] && o.env.RK_GATE_CLASS_B_BATCH !== "0", shardSolo: shardSoloOf(o, repo),
4073
4441
  // The broker (or, on a direct host, the gate itself) admits compiles; no separate grant file decides it here.
4074
4442
  localCompile: true,
4075
4443
  exists: o.exists, readFile: o.readFile, platform: o.platform,
@@ -4083,10 +4451,24 @@ export async function main(argv, io = {}) {
4083
4451
  if (closure) {
4084
4452
  let kept;
4085
4453
  try {
4454
+ if (o[PRIVATE_SCOPED_COMPILE] && fullPlan.scans.some((scan) => scan.class === "B" && Array.isArray(scan.batch?.units))) throw new Error("scoped private compilation cannot admit pre-grouped Class B scans; use ungrouped planning");
4086
4455
  kept = closureTools.scopeScans(fullPlan.scans, closure, { rustUnits: rust.units, npmUnits: npm });
4087
4456
  plan = closureTools.scopedPlan(fullPlan, kept.scans, closure);
4457
+ if (o[PRIVATE_SCOPED_COMPILE]) {
4458
+ const { selector, unitDir } = o[PRIVATE_SCOPED_COMPILE];
4459
+ const npmUnit = npm.find((u) => u.dir === unitDir);
4460
+ const rustUnit = rust.units.find((u) => u.dir === unitDir);
4461
+ const owner = selector.startsWith("npm:") ? npmUnit?.name : rustUnit?.name;
4462
+ const names = selector.startsWith("npm:") ? [`test:npm:${owner}`] : [`check:${owner}`, `check-features:${owner}`, `clippy:${owner}`];
4463
+ if (!owner || !plan.scans.some((scan) => scan.class === "B" && names.some((prefix) => scan.id === prefix || scan.id.startsWith(`${prefix}:`)))) throw new Error(`${selector}: no unit-specific Class B compile or test scan was planned; declare an executable unit test or compile route`);
4464
+ }
4088
4465
  } catch (error) { o.err(`${tag} BLOCKED: ${error.message}`); return 1; }
4089
- plan.notes = plan.notes.filter((n) => !n.includes("every Rust unit is in scope"));
4466
+ plan.notes = plan.notes.filter((n) => !n.includes("every Rust unit is in scope") && !n.startsWith("class B batching:"));
4467
+ const batchCandidates = plan.scans.filter((scan) => scan.class === "B" && scan.batchable);
4468
+ const batchCounts = new Map();
4469
+ for (const scan of batchCandidates) batchCounts.set(scan.batchable.key, (batchCounts.get(scan.batchable.key) ?? 0) + 1);
4470
+ const sharedGroups = [...batchCounts.values()].filter((count) => count > 1);
4471
+ if (batchCandidates.length) plan.notes.push(`class B batching: scoped plan has ${batchCandidates.length} eligible scan(s), including ${sharedGroups.reduce((sum, count) => sum + count, 0)} in ${sharedGroups.length} compatible group(s); actual batches depend on readiness and execution`);
4090
4472
  const classA = plan.scans.filter((s) => s.class === "A");
4091
4473
  // What actually executes: tests, executing rows and every Cargo scan (metadata, package list, deny, audit run cargo, through the broker
4092
4474
  // on a broker host), never only the rows that carry `executes`. The Cargo counts are named so a scoped run shows how much cargo it starts.
@@ -4095,10 +4477,87 @@ export async function main(argv, io = {}) {
4095
4477
  const cargoExcluded = kept.dropped.filter((s) => closureTools.isCargoScan(s)).length;
4096
4478
  o.out(`${tag} scope ${closure.dirs.join(", ")}: dependency directories ${closure.dependencyDirs.join(", ")}; ${closure.npm.size} npm & ${closure.rust.size} Rust unit(s); Class A ${executing} executing scan(s) (${cargoRun} Cargo), ${classA.length - executing} repository file-only scan(s); ${kept.dropped.length} unrelated executing scan(s) excluded (${cargoExcluded} Cargo); ${plan.scans.length - classA.length} closure Class B scan(s) do not run in this check; install roots ${installRoots.join(", ") || "none"}; scope digest ${plan.scopeDigest}`);
4097
4479
  }
4480
+ if (o[CARGO_WIDTH] !== undefined && !classAOnly) {
4481
+ const uncontrolled = plan.scans.find((scan) => scan.class === "B" && cargoWidthScanProblem(scan, planCargoCommand, o[CARGO_WIDTH]));
4482
+ if (uncontrolled) { o.err(`${tag} BLOCKED: --cargo-jobs cannot control Class B scan ${uncontrolled.id}`); return 1; }
4483
+ }
4484
+ let unionScheduler = null;
4485
+ const unionContext = o[UNIT_LIST_UNION];
4486
+ if (unionContext && snapshotB) {
4487
+ try {
4488
+ const { publisherRequirementsForUnits, planUnitListCompile, publisherUnionScheduler, runPublisherSecretRequirement, proveWorkspaceCwd } = await import("../unit-list-compile.mjs");
4489
+ const { publisherRequirementScan } = await import("../deterministic-scans.mjs");
4490
+ const requirements = await publisherRequirementsForUnits({ selected: unionContext.selected, snapshot: repo, rustUnits: rust.units, npmUnits: npm, platform: o.platform, env: o.env });
4491
+ unionContext.expected = new Map(requirements.map((entry) => [entry.selector, entry.requirements.length]));
4492
+ if (o[CARGO_WIDTH] !== undefined && requirements.some((entry) => entry.requirements.some((r) => r.executable !== "cargo" && r.internal !== "scanCrateForSecrets"))) throw new Error("--cargo-jobs cannot control a nested non-Cargo publisher requirement");
4493
+ const external = []; const scoped = []; const owner = new Map(); const verdicts = new Map(); const initialFailures = new Set();
4494
+ const { directReadSpawn } = await import("../snapshot-metadata.mjs");
4495
+ const pathKey = o.platform === "win32" ? (Object.keys(o.env).find((k) => k.toUpperCase() === "PATH") ?? "Path") : "PATH";
4496
+ const direct = directCargoPath({ env: { ...o.env, PATH: o.env[pathKey] }, exists: o.exists, platform: o.platform, gateWrappers: true });
4497
+ const directSpawn = directReadSpawn({ spawn: withDeclaredClient((c, a, opts) => o.spawn(c, a, opts)), cargoCommand: planCargoCommand, snapshotRoot: repo, directPath: direct.path, pathKey, tmpRoot: gateTmpRoot({ env: o.env, platform: o.platform, exists: o.exists }), env: o.env, err: o.err });
4498
+ for (const entry of requirements) {
4499
+ const rows = []; verdicts.set(entry.selector, entry.verdict);
4500
+ for (const requirement of entry.requirements) {
4501
+ owner.set(requirement.id, entry.selector);
4502
+ if (requirement.internal === "scanCrateForSecrets") {
4503
+ const evidence = await runPublisherSecretRequirement({ requirement, snapshot: repo, commit: snapshotBCommit.commit, tree: snapshotBCommit.tree, verifySnapshot: o.verifyUnionSnapshot });
4504
+ unionContext.internal.push({ selector: entry.selector, id: requirement.id, coverageKey: requirement.coverageKey, status: evidence.status, evidenceHash: evidence.evidenceHash, ...(evidence.findings.length ? { findings: evidence.findings } : {}) });
4505
+ if (evidence.status !== "pass") { initialFailures.add(entry.selector); o.err(`${tag} ${entry.selector}: publisher secret scan failed (${evidence.findings.join(", ")})`); }
4506
+ } else if (requirement.executable === "cargo" && requirement.argv[0] === "fmt") {
4507
+ if (!await o.verifyUnionSnapshot()) throw new Error("snapshot changed before publisher fmt");
4508
+ const result = directSpawn(planCargoCommand[0], [...planCargoCommand.slice(1), ...requirement.argv], { cwd: path.join(repo, requirement.cwd), env: requirement.env });
4509
+ if (!await o.verifyUnionSnapshot()) throw new Error("snapshot changed after publisher fmt");
4510
+ const status = failed(result) ? "fail" : "pass";
4511
+ const evidence = { id: requirement.id, coverageKey: requirement.coverageKey, commit: snapshotBCommit.commit, tree: snapshotBCommit.tree, status };
4512
+ unionContext.internal.push({ selector: entry.selector, ...evidence, evidenceHash: createHash("sha256").update(JSON.stringify(evidence)).digest("hex") });
4513
+ if (status !== "pass") { initialFailures.add(entry.selector); o.err(`${tag} ${entry.selector}: publisher fmt failed: ${why(result)}`); }
4514
+ } else { external.push(requirement); rows.push(requirement); }
4515
+ }
4516
+ if (!rows.length) throw new Error(`${entry.selector}: no executable publisher compile requirements`);
4517
+ scoped.push({ selector: entry.selector, requirements: rows });
4518
+ }
4519
+ const normalizedCwds = new Map(); const cwdProofs = [];
4520
+ const toolchains = new Map();
4521
+ const toolchainOf = (dir) => {
4522
+ if (!toolchains.has(dir)) {
4523
+ const result = o.spawn("rustup", ["show", "active-toolchain"], { cwd: dir, env: { ...o.env, [pathKey]: direct.path } });
4524
+ toolchains.set(dir, failed(result) ? { error: result?.error ? "spawn-error" : `exit-${Number.isInteger(result?.status) ? result.status : "unknown"}` } : { toolchain: text(result).trim().split(/\s+/)[0] });
4525
+ }
4526
+ return toolchains.get(dir);
4527
+ };
4528
+ for (const requirement of external) if (requirement.executable === "cargo" && requirement.phase === "compile" && ["check", "clippy"].includes(requirement.argv[0])) {
4529
+ const proof = proveWorkspaceCwd({ requirement, snapshot: repo, checkout: root, toolchainOf, exists: o.exists });
4530
+ if (proof.normalized) normalizedCwds.set(requirement.id, proof.cwd);
4531
+ cwdProofs.push({ id: requirement.id, cwd: proof.cwd, normalized: proof.normalized, reason: proof.reason });
4532
+ }
4533
+ unionContext.cwdProofs = cwdProofs;
4534
+ const jobs = planUnitListCompile(scoped, { normalizedCwds });
4535
+ const config = JSON.parse(o.readFile(path.join(repo, "ci/gate.config.json")));
4536
+ const adapt = (requirement) => {
4537
+ const sel = owner.get(requirement.id) ?? jobs.find((job) => job.members.some((member) => member.coverageKey === requirement.coverageKey))?.members[0]?.selector;
4538
+ const unit = sel?.replace(/^cargo:/, "");
4539
+ const quiet = sel?.startsWith("cargo:") ? config.rust?.[unit]?.quietTests === true : false;
4540
+ return publisherRequirementScan(requirement, { platform: o.platform, cargoCommand: planCargoCommand, cargoLiveRoot, targetDirs, quiet, allowIgnored: verdicts.get(sel)?.allowIgnored === true, cargoJobs: o[CARGO_WIDTH] ?? null });
4541
+ };
4542
+ for (const requirement of external) plan.scans.push(adapt(requirement));
4543
+ const dependencies = Object.fromEntries(unionContext.selected.map((unit) => [unit.selector, (unit.deps ?? []).filter((dep) => unionContext.selected.some((u) => u.selector === dep))]));
4544
+ unionScheduler = publisherUnionScheduler({ jobs, dependencies, initialFailures, requirements: external, adapt, signal: ac.signal, onCoverage: (coverage) => { unionContext.coverage = coverage; }, verify: async ({ row, member, attempts, requirement }) => {
4545
+ const verdict = verdicts.get(member.selector);
4546
+ const proof = { commit: snapshotBCommit.commit, tree: snapshotBCommit.tree, requirement: member.coverageKey, command: row?.command ?? null, attempts, snapshotEvidence: row?.snapshotEvidence ?? null, testRun: row?.testRun ?? null, results: row?.results ?? null };
4547
+ unionContext.commands.push({ selector: member.selector, id: member.id, ...proof });
4548
+ if (!row || row.status !== "pass" || (requirement.phase === "test" && (row.testRun?.outputTruncated || (!verdict.allowMissingAssets && (row.testRun?.skipMarkers ?? 0) > 0) || (!verdict.allowIgnored && (row.results?.skipped ?? 0) > 0)))) return { ok: false };
4549
+ if (executor.kind === "broker" && requirement.executable === "cargo" && !/^[0-9a-f]{64}$/.test(row.snapshotEvidence?.receiptSha256 ?? "")) return { ok: false };
4550
+ return { ok: true, evidenceHash: createHash("sha256").update(JSON.stringify(proof)).digest("hex") };
4551
+ } });
4552
+ unionContext.owner = owner;
4553
+ } catch (error) { o.err(`${tag} BLOCKED: cannot prepare canonical unit-list compile: ${error.message}`); return 1; }
4554
+ }
4098
4555
  // What the plan leaves to the qualify stage (end-to-end crates, declared Swift packages): handed to the door, which records it in the compile
4099
4556
  // receipt and refuses to qualify without a declared run route (rightkit#1332, #1333). Never dropped silently.
4100
4557
  o.onQualifyOwed?.((plan.qualifyOwed ?? []).filter((x) => x.kind !== "e2e-crate" || plan.scans.some((s) => s.id === x.id)));
4101
- const jobs = Math.max(1, Number(o.env.RK_GATE_JOBS ?? 4) || 4);
4558
+ // GC-A24: class A lanes default to the host's cores (measured, Mac, cold RK class A rows: 4 lanes 14.4 s, 8 lanes 7.0 s, 12 lanes 5.9 s).
4559
+ const defaultJobs = typeof os.availableParallelism === "function" ? os.availableParallelism() : os.cpus().length;
4560
+ const jobs = Math.max(1, Number(o.env.RK_GATE_JOBS ?? defaultJobs) || defaultJobs);
4102
4561
  const testJobs = Math.max(1, Number(o.env.RK_GATE_TEST_JOBS ?? jobs) || jobs);
4103
4562
  // A broker host has no gate-side build count: the broker decides it. What remains is the local limit on class B processes the broker never sees.
4104
4563
  const brokerHost = executor.kind === "broker";
@@ -4138,8 +4597,18 @@ export async function main(argv, io = {}) {
4138
4597
  }
4139
4598
  // The result cache keys on the gated commit's object ids; the stdin check above made HEAD the pushed commit.
4140
4599
  let cache = null;
4600
+ const nodeCheckRejects = new Map();
4601
+ let nodeCheckDiagnosticId = null; let nodeCheckDiagnosticState = "not-seen";
4602
+ const countNodeCheckRejection = (reason, scanId) => {
4603
+ if (!["setup-error", "row-shape", "runtime-path", "source-path", "shim-proof", "node-options", "node-environment", "loader-environment", "runtime-config-environment", "row-error"].includes(reason)) return;
4604
+ nodeCheckRejects.set(reason, (nodeCheckRejects.get(reason) ?? 0) + 1);
4605
+ if (scanId === nodeCheckDiagnosticId) nodeCheckDiagnosticState = `rejected:${reason}`;
4606
+ };
4141
4607
  // rightkit#1463: the input key each scan was looked up under, for the coverage report (gate-coverage.mjs).
4142
4608
  const scanKeys = new Map();
4609
+ // Why a scan got no cache key (a key builder that threw, or a cache that could not open): reported, never hidden (GC-A24).
4610
+ const keyErrors = new Map(); let cacheDisabled = null;
4611
+ const keyError = (scan, error) => keyErrors.set(scan.id, String(error?.message ?? error).slice(0, 300));
4143
4612
  // Full class A on the working tree (the door, and broker admission of the live checkout) caches on the LIVE bytes: every
4144
4613
  // tracked and untracked (not ignored) file is hashed raw, so the door's run and a repeat admission of the same bytes hit the
4145
4614
  // cache, and any edit misses it.
@@ -4235,15 +4704,23 @@ export async function main(argv, io = {}) {
4235
4704
  // A6: the digest bound at the start of this run is this very computation (same root, gate package, files and tool-cache setting), so it is
4236
4705
  // reused: each call walks every installed dependency file, and the run made three of these walks before its first scan.
4237
4706
  const environment = envAtStart ?? classAEnvironmentDigest({ root: liveBase, gatePackage: o.gatePackage, files, spawn: o.spawn, includeCaches: false });
4238
- const digest = buildCacheDigest({ objectId, headTree: digestOf(files), rustUnits: rust.units, npmUnits: npm, cargoDir: ".", rustLocks, crateFeatures, listFiles, readBlob });
4707
+ const digest = buildCacheDigest({ objectId, headTree: digestOf(files), rustUnits: rust.units, npmUnits: npm, cargoDir: ".", rustLocks, crateFeatures, listFiles, readBlob, onKeyError: keyError });
4239
4708
  // A row's key is its own inputs plus the environment; the run's scope and scan set are not inputs of one row, and keying on them
4240
4709
  // missed every row whenever one file joined or left the plan. build-helpers is never reused: it reads the host's trace list,
4241
4710
  // which is outside every key (and takes seconds).
4242
4711
  // A row field that shapes what the scan checks without changing its id or command is part of its key: a tsc row's tscWorkspace
4243
4712
  // (the sibling packages its check project maps; scopeScans narrows it per scope) changes the verdict on the same tree.
4244
4713
  const rowShape = (scan) => (scan.tscWorkspace ? `:tscws=${createHash("sha256").update(canonicalJson([...scan.tscWorkspace].sort())).digest("hex")}` : "");
4245
- cache = { ...store, digest: (scan) => { if (/^build-helpers(:|$)/.test(scan.id)) return null; const key = digest(scan); const full = key === null ? null : `${key}:${environment}${rowShape(scan)}`; scanKeys.set(scan.id, full); return full; } };
4246
- } catch { cache = null; }
4714
+ nodeCheckDiagnosticId = plan.scans.filter((scan) => scan.class === "A" && scan.id.startsWith("node-check:")).map((scan) => scan.id).sort()[0];
4715
+ const nodeCheckModule = null; // GC-A24: node-check rows use the generic file key (file, ancestor package.json, node identity)
4716
+ const nodeCheckDigest = nodeCheckModule ? nodeCheckModule.createNodeCheckCacheDigest({ snapshot: liveBase, tree: digestOf(files), files, gateIdentity: gateCodeIdentity(), gatePackage: o.gatePackage, nodePath: process.execPath, onReject: countNodeCheckRejection, ...(o.env.RIGHTKIT_PREPARATION_DIAGNOSTIC_DIR && nodeCheckDiagnosticId ? { onDiagnostic: (record) => { nodeCheckDiagnosticState = "eligible"; nodeCheckModule.writeNodeCheckDiagnostic(o.env.RIGHTKIT_PREPARATION_DIAGNOSTIC_DIR, record); }, diagnosticScanId: nodeCheckDiagnosticId } : {}) }) : null;
4717
+ cache = { ...store, narrowNodeCheck: false, digest: (scan, context) => {
4718
+ if (/^build-helpers(:|$)/.test(scan.id)) return null;
4719
+ // This narrow key applies only to the helper's proven plain snapshot node --check.
4720
+ // Uncertain rows miss rather than falling back to a less specific key.
4721
+ const key = digest(scan); const full = key === null ? null : `${key}:${classAEnvironmentBound(scan) ? environment : CLASS_A_KEY_SCHEMA}${rowShape(scan)}`; scanKeys.set(scan.id, full); return full;
4722
+ } };
4723
+ } catch (error) { cache = null; cacheDisabled = `class A result cache disabled: ${error?.message ?? error}`; o.err(`${tag} note: ${cacheDisabled}`); }
4247
4724
  }
4248
4725
  if (!classAOnly) {
4249
4726
  try {
@@ -4268,12 +4745,15 @@ export async function main(argv, io = {}) {
4268
4745
  if (failed(r)) throw new Error(`git show failed: ${why(r)}`);
4269
4746
  return text(r);
4270
4747
  };
4271
- // The gate's identity is part of every class B key: a changed check or key logic never reuses an older verdict.
4272
- const rowDigest = buildCacheDigest({ objectId, headTree: treeId, rustUnits: rust.units, npmUnits: npm, cargoDir: ".", rustLocks, crateFeatures, listFiles, readBlob });
4273
- const gateIdentity = gateCodeIdentity();
4274
- cache = { ...store, digest: (scan) => { const key = rowDigest(scan); const full = key === null ? null : `${key}:${gateIdentity}`; scanKeys.set(scan.id, full); return full; } };
4748
+ // The class B key identity (key schema and carrier code, classBKeyIdentity) is part of every class B key.
4749
+ const rowDigest = buildCacheDigest({ objectId, headTree: treeId, rustUnits: rust.units, npmUnits: npm, cargoDir: ".", rustLocks, crateFeatures, listFiles, readBlob, onKeyError: keyError });
4750
+ const gateIdentity = classBKeyIdentity();
4751
+ cache = { ...store, digest: (scan) => { const key = rowDigest(scan); const full = key === null ? null : `${key}:${gateIdentity}`; scanKeys.set(scan.id, full); for (const member of scan.batch?.members ?? []) scanKeys.set(member, full); return full; } };
4752
+ } else {
4753
+ cacheDisabled = `class B result cache disabled: ${!headSha ? "no commit" : !treeId ? "no tree id" : `git common dir unreadable (${why(common)})`}`;
4754
+ o.err(`${tag} note: ${cacheDisabled}`);
4275
4755
  }
4276
- } catch { cache = null; }
4756
+ } catch (error) { cache = null; cacheDisabled = `class B result cache disabled: ${error?.message ?? error}`; o.err(`${tag} note: ${cacheDisabled}`); }
4277
4757
  }
4278
4758
  // The scan-tool policy (RA-18 / L9-03): the analyzers class A accepts (shellcheck, actionlint, cargo-deny, cargo-audit) run only from an enrolled
4279
4759
  // executable. It comes from this host's enrolment record under the managed data root, else (RightKit's own checkout only) from the RUNNING
@@ -4299,7 +4779,7 @@ export async function main(argv, io = {}) {
4299
4779
  const scanResult = await (o.runScans ?? runScans)(plan, {
4300
4780
  // The commit's own files (rightkit#1393): a snapshot is not a git toplevel, so the secret scan needs this list to judge tracked files only and never what a stage wrote there.
4301
4781
  ...(snapshot ? { trackedFiles: files } : {}),
4302
- classes: classAOnly ? ["A"] : classAEarlier ? ["B"] : ["A", "B"], ...(classAEarlier ? { classAEarlier: true } : {}), jobs, testJobs, classBJobs, classBBatching: o.env.RK_GATE_CLASS_B_BATCH !== "0", classBPipeline: Math.max(1, Number(o.env.RK_GATE_CLASS_B_PIPELINE ?? 2) || 2), ...(brokerHost ? { brokerHost: true } : {}), ...(brokerLive ? { brokerLive } : {}), signal: ac.signal, ...(cache ? { cache } : {}),
4782
+ classes: classAOnly ? ["A"] : classAEarlier ? ["B"] : ["A", "B"], ...(classAEarlier ? { classAEarlier: true } : {}), jobs, testJobs, classBJobs, classBBatching: !o[PRIVATE_SCOPED_COMPILE] && o.env.RK_GATE_CLASS_B_BATCH !== "0", classBPipeline: Math.max(1, Number(o.env.RK_GATE_CLASS_B_PIPELINE ?? 2) || 2), ...(brokerHost ? { brokerHost: true } : {}), ...(brokerLive ? { brokerLive } : {}), signal: ac.signal, ...(cache ? { cache } : {}),
4303
4783
  ...(census ? { spawn: census.wrapSpawn(defaultSpawnAsync) } : {}),
4304
4784
  // The declared Linux broker route: the scans are planned with the logical `rustright`, which this spawn (and scanSpawn's pass-through below) starts as the
4305
4785
  // executor's validated client, never a PATH lookup (withDeclaredClient).
@@ -4317,7 +4797,7 @@ export async function main(argv, io = {}) {
4317
4797
  ...(!scanSpawn ? { cargoReadTargetRoot: gateTmpRoot({ env: o.env, platform: o.platform, exists: o.exists }) } : {}),
4318
4798
  // The runtime cargo wrapper is first on PATH and named in CARGO for every scan of a snapshot compile; CARGO (a path named by the
4319
4799
  // wrapper's identity) is in every scan's cache key, so no result cached without the wrapper or with another map is reused.
4320
- ...(cargoShim ? { env: cargoShim.scanEnv, ...(cargoShim.sentinel ? { cargoSentinel: cargoShim.sentinel } : {}), cargoLedger: { dir: cargoShim.ledgerDir } } : {}),
4800
+ ...(cargoShim ? { env: cargoShim.scanEnv, nodeCheckShimContext: { shim: cargoShim.shim, bin: cargoShim.bin, sentinel: cargoShim.sentinel, originalEnv: o.env }, ...(cargoShim.sentinel ? { cargoSentinel: cargoShim.sentinel } : {}), cargoLedger: { dir: cargoShim.ledgerDir } } : {}),
4321
4801
  // The broker snapshot compile's seam (item 7 rows 7.20 to 7.24): the commit, snapshot, ownership, enrolled pins and receipt reader.
4322
4802
  ...(snapshotBroker ? { snapshotBroker } : {}),
4323
4803
  // `check` (and the broker's compile admission, which runs it on a captured copy of the tree without node_modules) judges the
@@ -4337,8 +4817,20 @@ export async function main(argv, io = {}) {
4337
4817
  return path.join(base, "rightkit-gate-scan-logs", `${path.basename(root)}-${stamp}-${process.pid}`);
4338
4818
  } catch { return null; }
4339
4819
  })(),
4820
+ ...(unionScheduler ? { scheduleClassB: unionScheduler } : {}),
4340
4821
  onResult: (row, p) => o.out(`${tag} [${p.done}/${p.total}] ${(row.cached ? "cached" : row.status).padEnd(7)} ${row.id} (${p.seconds}s)${row.batchedWith ? ` [batch of ${row.batchedWith.units.length}]` : ""}${row.status === "fail" ? ` :: ${String(row.detail ?? "").slice(0, 300)}` : row.advice ? ` :: ${String(row.advice).slice(0, 300)}` : ""}`),
4341
4822
  });
4823
+ if (nodeCheckRejects.size) o.out(`${tag} node-check cache misses: ${[...nodeCheckRejects].sort(([a], [b]) => a.localeCompare(b)).map(([reason, count]) => `${reason}=${count}`).join(", ")}`);
4824
+ if (snapFullA && o.env.RIGHTKIT_PREPARATION_DIAGNOSTIC_DIR && nodeCheckDiagnosticId) o.out(`${tag} node-check diagnostic row: ${nodeCheckDiagnosticState}`);
4825
+ if (unionContext) {
4826
+ const scanById = new Map(plan.scans.map((scan) => [scan.id, scan]));
4827
+ unionContext.rows = scanResult.scans.filter((row) => row.class === "B").map((row) => {
4828
+ const scan = scanById.get(row.id);
4829
+ const command = scan?.tool ? [scan.tool, ...(scan.args ?? [])].join(" ") : null;
4830
+ return { id: row.id, status: row.status, ...(command ? { command } : {}), ...(row.batchCommand ? { batchCommand: row.batchCommand } : {}), ...(row.batchedWith ? { batchedWith: row.batchedWith } : {}), ...(row.batchFailure ? { batchFailure: row.batchFailure } : {}), ...(row.batchAttempts ? { batchAttempts: row.batchAttempts } : {}), ...(row.individualStatus ? { individualStatus: row.individualStatus, ...(row.individualCode ? { individualCode: row.individualCode } : {}) } : {}), ...(row.authenticatedFailure ? { authenticatedFailure: row.authenticatedFailure } : {}), ...(row.snapshotEvidence ? { snapshotEvidence: row.snapshotEvidence } : {}), ...(row.testRun ? { testRun: row.testRun } : {}), ...(row.results ? { results: row.results } : {}), ...(unionContext.owner?.has(row.id) ? { publisherUnit: unionContext.owner.get(row.id) } : { sharedOrigin: true }) };
4831
+ });
4832
+ }
4833
+ if (unionContext) unionContext.sharedClean = unionContext.rows.filter((row) => row.sharedOrigin).every((row) => row.status === "pass");
4342
4834
  directTiming.cargoEnd = Date.now();
4343
4835
  const freshness = census ? census.finish() : null;
4344
4836
  directTiming.diagnostics = Date.now() - directTiming.cargoEnd;
@@ -4355,7 +4847,7 @@ export async function main(argv, io = {}) {
4355
4847
  for (const note of scanResult.notes) o.out(`${tag} ${note}`);
4356
4848
  // rightkit#1463: the per-scan coverage report (hit / ran / skipped, with the cache key and the reason), written beside the scan logs; a cache that never hits shows here.
4357
4849
  try {
4358
- const report = buildCoverageReport({ plan, scanResult, keys: scanKeys, classes: classAOnly ? ["A"] : classAEarlier ? ["B"] : ["A", "B"], commit: snapshotBCommit?.commit ?? snapshotCommitId?.commit ?? hostedCommitA?.commit ?? null, startedAt: new Date(directTiming.cargoStart).toISOString(), endedAt: new Date(directTiming.cargoEnd).toISOString() });
4850
+ const report = buildCoverageReport({ plan, scanResult, keys: scanKeys, keyErrors, cacheDisabled, classes: classAOnly ? ["A"] : classAEarlier ? ["B"] : ["A", "B"], commit: snapshotBCommit?.commit ?? snapshotCommitId?.commit ?? hostedCommitA?.commit ?? null, startedAt: new Date(directTiming.cargoStart).toISOString(), endedAt: new Date(directTiming.cargoEnd).toISOString() });
4359
4851
  const base = gateRunsRoot({ env: o.env, platform: o.platform });
4360
4852
  const file = (o.writeCoverage ?? writeCoverageReport)({ dir: path.join(base, "rightkit-gate-coverage"), name: `${path.basename(root)}-${new Date().toISOString().replace(/[:.]/g, "-")}-${process.pid}`, report });
4361
4853
  o.out(`${tag} coverage report ${file}: ${report.totals.planned} planned scan(s), ${report.totals.hit} hit, ${report.totals.ran} ran, ${report.totals.skipped} skipped; scans took ${seconds(directTiming.cargoEnd - directTiming.cargoStart)}`);
@@ -4461,6 +4953,7 @@ export async function main(argv, io = {}) {
4461
4953
  o.out(`${tag} direct receipt ${JSON.stringify(directReceipt)}`);
4462
4954
  }
4463
4955
  }
4956
+ if (unionContext) unionContext.completed = true;
4464
4957
  if (failures.length) {
4465
4958
  o.err(`${tag} BLOCKED (${failures.length})`);
4466
4959
  for (const f of failures) o.err(` - ${f}`);
@@ -4496,6 +4989,10 @@ export async function main(argv, io = {}) {
4496
4989
  const tracked = new Set(snapFullA || hostedFullA ? live.files : text(trackedList).split("\0").filter(Boolean).map(posix));
4497
4990
  o.out(`${tag} class A bytes tracked=${live.digestOf(live.files.filter((f) => tracked.has(f)))} all=${live.digest}${envStartWithCaches ? ` env-at-start=${envStartWithCaches}` : ""} env=${plan.scopeDigest ? createHash("sha256").update(`${binding.env}:${plan.scopeDigest}:${plan.scanSetDigest}`).digest("hex") : binding.env}${plan.scopeDigest ? ` scope=${plan.scopeDigest} scans=${plan.scanSetDigest}` : ""}`);
4498
4991
  }
4992
+ if (snapshotA && snapshotCommitId && o.env.RIGHTKIT_PREPARATION_DIAGNOSTIC_DIR) {
4993
+ try { await (await import("../snapshot-dependency-reuse.mjs")).capturePostClassADiagnostics({ checkout: root, snapshot: snapshotA, commit: snapshotCommitId.commit, roots: installRoots, diagnosticDir: o.env.RIGHTKIT_PREPARATION_DIAGNOSTIC_DIR }); }
4994
+ catch { /* Optional diagnostics never change the gate verdict. */ }
4995
+ }
4499
4996
  o.out(`${tag} class A ${plan.scopeDigest ? "scoped" : "full"} pass: ${scanResult.scans.length} deterministic check(s), the ones that execute repository code included, over ${changed.length} file(s) of ${base}`);
4500
4997
  return 0;
4501
4998
  }