@rightkit/release 0.6.44 → 0.6.46

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";
@@ -99,10 +100,16 @@ import { readDiskPolicy, scratchRoots } from "../disk-policy.mjs";
99
100
  import { buildDirectReceipt, directVerdict, resolveTargetDirectory, verifyDirectReceipt, writeDirectDiagnostics } from "../direct-receipt.mjs";
100
101
  import { createFreshnessCensus } from "../freshness-census.mjs";
101
102
  import { platformDirOf } from "../platform-dir.mjs";
103
+ import { buildInventory, classifyUnitResults, dependencyFirstOrder, selectAffectedAcrossInventories, unitListReport } from "../affected-units.mjs";
104
+ import { createRequire } from "node:module";
102
105
  import { nativeToolRefusal, nativeToolUses } from "../native-tool-planning.mjs";
103
106
  import { BUILD_CONTROL_PROTOCOL, HANDSHAKE_PROBE_ID, RUNTIME_MANIFEST_FILE, mergeCapabilityViews, parseRuntimeIdentity, queryBrokerHandshake } from "../broker-handshake.mjs";
104
107
  import net from "node:net";
108
+ import { cargoWidthRouteProblem, cargoWidthScanProblem, cargoWidthUnitsProblem, parseCargoWidth, validateCargoWidthPool } from "../cargo-width.mjs";
105
109
 
110
+ const PRIVATE_SCOPED_COMPILE = Symbol("private scoped compile");
111
+ const UNIT_LIST_UNION = Symbol("unit list union");
112
+ const CARGO_WIDTH = Symbol("Cargo width");
106
113
  const ZERO = /^0+$/;
107
114
  const SAFE_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
108
115
  const posix = (p) => String(p).replaceAll("\\", "/");
@@ -117,6 +124,51 @@ export const PLATFORMS = Object.freeze(["mac", "win", "ios", "android"]);
117
124
  export const MOBILE_PLATFORMS = Object.freeze(new Set(["ios", "android"]));
118
125
  // The gate's code identity for result keys: the checker (deterministic-scans and scan-digest, CHECKER_IDENTITY) and this file, where
119
126
  // the keys are built. An unidentifiable checker gets a per-process value, so nothing is reused across runs.
127
+ // The identity a class B (compile) result key carries (GC-A24): a key-schema version, bumped by hand whenever what a key covers changes,
128
+ // and the code of the runtime cargo wrapper and broker carrier, which decides what a carried compile ran and how its receipt is verified.
129
+ // 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
130
+ // an edit elsewhere in the gate must not discard every compile result (rightkit#1506: Pulse, RK, RustRight and Legion kept 0 class B hits).
131
+ const CLASS_B_KEY_SCHEMA = "rightkit.class-b-key/2";
132
+ // GC-A24: passing rule-engine verdicts (app rules, RightKit's preflight) of a snapshot, under the checkout's git common directory.
133
+ const RULE_VERDICT_SCHEMA = "rightkit.rule-verdict/1";
134
+ function ruleVerdictCache({ checkout, spawn }) {
135
+ try {
136
+ const common = spawn("git", ["rev-parse", "--path-format=absolute", "--git-common-dir"], { cwd: checkout });
137
+ if (failed(common) || !text(common).trim()) return null;
138
+ const dir = path.join(text(common).trim(), "rightkit-gate-cache", "rule-verdicts");
139
+ const file = (k) => path.join(dir, `${k}.json`);
140
+ return {
141
+ key: (parts) => createHash("sha256").update(canonicalJson({ schema: RULE_VERDICT_SCHEMA, node: process.version, platform: `${process.platform}-${process.arch}`, ...parts })).digest("hex"),
142
+ passed: (k) => { try { return JSON.parse(fs.readFileSync(file(k), "utf8"))?.status === "pass"; } catch { return false; } },
143
+ 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 */ } },
144
+ };
145
+ } catch { return null; }
146
+ }
147
+ /** sha256 over every file of the gate package (the rule code a rule verdict depends on). */
148
+ const gatePackageMemo = new Map();
149
+ function gatePackageIdentity(gatePackage = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..")) {
150
+ if (!gatePackageMemo.has(gatePackage)) {
151
+ const h = createHash("sha256");
152
+ 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)); } });
153
+ walk(gatePackage);
154
+ gatePackageMemo.set(gatePackage, h.digest("hex"));
155
+ }
156
+ return gatePackageMemo.get(gatePackage);
157
+ }
158
+ // 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.
159
+ const CLASS_A_KEY_SCHEMA = "rightkit.class-a-key/2";
160
+ /** Whether a class A row's verdict depends on the installed dependencies (GC-A24): it executes repository code, or its tool is pnpm. */
161
+ function classAEnvironmentBound(scan) { return scan.executes === true || scan.tool === "pnpm"; }
162
+ let classBKeyIdentityMemo = null;
163
+ function classBKeyIdentity() {
164
+ if (classBKeyIdentityMemo === null) {
165
+ const h = createHash("sha256");
166
+ h.update(CLASS_B_KEY_SCHEMA);
167
+ 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))); }
168
+ classBKeyIdentityMemo = h.digest("hex").slice(0, 24);
169
+ }
170
+ return classBKeyIdentityMemo;
171
+ }
120
172
  let gateCodeIdentityMemo = null;
121
173
  function gateCodeIdentity() {
122
174
  if (gateCodeIdentityMemo === null) {
@@ -144,7 +196,7 @@ function directCargoBinOf(o) {
144
196
  return null;
145
197
  }
146
198
 
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`;
199
+ 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
200
  /** The host platform (process.platform) that constructs each platform's artifact; a platform missing here (android) builds on any host. */
149
201
  const STAGE_NATIVE_HOST = Object.freeze({ mac: "darwin", ios: "darwin", win: "win32" });
150
202
 
@@ -321,6 +373,7 @@ export function gateTmpRoot({ env = process.env, platform = process.platform, ex
321
373
  export const PNPM_PROBE_TIMEOUT_MS = 60_000;
322
374
  export const PNPM_PIN_REFUSAL = "RK_PNPM_VERSION_MISMATCH";
323
375
  export const TOOL_CACHE_DIRS = new Set([".vite", ".vite-temp", ".vitest-cache", ".cache"]);
376
+ export { installStateBytes };
324
377
  export const INSTALL_STATE_NOT_COVERED = new Set([".pnpm-task-run-state-v1"]);
325
378
  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
379
  function isLink(p) { try { return fs.lstatSync(p).isSymbolicLink(); } catch { return false; } }
@@ -392,66 +445,13 @@ export function toolCacheDrift(before, after) {
392
445
  * 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
446
  * and end of the run and again at START.
394
447
  */
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");
448
+ export function installedDependencyDigest({ root, files, includeCaches = true }) {
449
+ // GC-A24 (Adrian, 2026-11-05): the installed dependencies are identified by pnpm's own install record (dependency-identity.mjs
450
+ // installIdentity: install-state files with their timestamps removed, .pnpm/lock.yaml, top-level links, and whole bytes only of linked
451
+ // packages from outside the repository), not by reading every installed file. `includeCaches` no longer applies: tool caches are
452
+ // not part of the install record. The roots are the node_modules directories of every committed package.json (nodeModulesDirs).
453
+ void includeCaches;
454
+ return installIdentity(root, nodeModulesDirs(root, files));
455
455
  }
456
456
 
457
457
  /**
@@ -477,7 +477,7 @@ export function classAEnvironmentDigest({ root, files, spawn = defaultSpawn, inc
477
477
  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
478
  return text(r).trim();
479
479
  })();
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 })}`);
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) => { 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
481
  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
482
  }
483
483
 
@@ -998,7 +998,7 @@ function shardSoloOf(o, repo) {
998
998
  } catch { return []; }
999
999
  }
1000
1000
 
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) }) {
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), onKeyError = null }) {
1002
1002
  const memo = new Map(); const reachMemos = new Map(); const externalMemo = new Map();
1003
1003
  const idOf = (p) => { if (!memo.has(p)) memo.set(p, p === "." ? headTree : objectId(p)); return memo.get(p); };
1004
1004
  // npm: a package's test, tsc and eslint scans read the package, every workspace package it depends on (package.json
@@ -1066,7 +1066,8 @@ export function buildCacheDigest({ objectId, headTree, rustUnits = [], npmUnits
1066
1066
  // projection and its own lock entry; anything else (cargo metadata, licence, ownership catalog, secret scan) on the whole tree,
1067
1067
  // so it is reused for a rerun of the same commit and nothing else.
1068
1068
  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)(:|$)/;
1069
+ // GC-A24: pnpm-lockfile asks the registry as pnpm-audit does, so it takes the same day-bounded key (GC-A19).
1070
+ const ADVISORY_SCAN = /^(cargo-deny|cargo-audit|pnpm-audit|pnpm-lockfile)(:|$)/;
1070
1071
  // 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
1072
  // 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
1073
  // (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 +1076,7 @@ export function buildCacheDigest({ objectId, headTree, rustUnits = [], npmUnits
1075
1076
  const dir = typeof scan.cwd === "string" && scan.cwd !== "" ? scan.cwd : ".";
1076
1077
  const idsOf = (paths) => [...new Set(paths)].sort().map((p) => [p, idOf(p) ?? null]);
1077
1078
  const all = listFiles(".");
1078
- if (/^pnpm-audit(:|$)/.test(scan.id)) {
1079
+ if (/^pnpm-(audit|lockfile)(:|$)/.test(scan.id)) {
1079
1080
  const lock = inWs(dir, "pnpm-lock.yaml");
1080
1081
  if (idOf(lock) === null || idOf(lock) === undefined) return null;
1081
1082
  const manifests = all.filter((f) => /(^|\/)package\.json$/.test(f) && (dir === "." || f === inWs(dir, "package.json") || f.startsWith(`${dir}/`)));
@@ -1091,11 +1092,18 @@ export function buildCacheDigest({ objectId, headTree, rustUnits = [], npmUnits
1091
1092
  const fileList = (scan) => {
1092
1093
  if (Array.isArray(scan.files) && scan.files.length) return scan.files;
1093
1094
  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)];
1095
+ if (/^rustfmt:/.test(scan.id)) {
1096
+ const rs = args.filter((x) => /\.rs$/.test(x));
1097
+ 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));
1098
+ return [...rs, ...configs];
1099
+ }
1100
+ 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"))]; }
1101
+ if (scan.internal === "secret-scan" && Array.isArray(scan.dirs) && typeof listFiles === "function") return [...new Set(scan.dirs.flatMap((d) => listFiles(d)))];
1102
+ if (scan.id === "shellcheck") return [...args.filter((x) => /\.(sh|bash)$/.test(x)), ".shellcheckrc"];
1096
1103
  if (scan.id === "actionlint") return [...args.filter((x) => /\.ya?ml$/.test(x)), ".github/actionlint.yaml"];
1097
1104
  return null;
1098
1105
  };
1106
+ const unitKeyMemo = new Map();
1099
1107
  return (scan) => {
1100
1108
  if (scan.class === "A") {
1101
1109
  if (liveScan(scan.id) && !ADVISORY_SCAN.test(scan.id)) return null;
@@ -1114,7 +1122,7 @@ export function buildCacheDigest({ objectId, headTree, rustUnits = [], npmUnits
1114
1122
  return canonicalJson({ kind: "package-list", unit, dir: [head.dir, idOf(head.dir)], manifest, lock: [[crateOf(head), lock.get(crateOf(head))?.signatures ?? []]] });
1115
1123
  }
1116
1124
  return whole();
1117
- } catch { return null; }
1125
+ } catch (error) { onKeyError?.(scan, error); return null; }
1118
1126
  }
1119
1127
  if (scan.class !== "B") return null;
1120
1128
  try {
@@ -1140,12 +1148,12 @@ export function buildCacheDigest({ objectId, headTree, rustUnits = [], npmUnits
1140
1148
  }
1141
1149
  const keyed = rustUnitKey(unit, scan);
1142
1150
  return keyed === undefined ? whole() : keyed;
1143
- } catch { return null; }
1151
+ } catch (error) { onKeyError?.(scan, error); return null; }
1144
1152
  };
1145
1153
  // 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
1154
  // 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
1155
  // 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();
1156
+ // (unitKeyMemo is declared before the returned key function; declared here it was never initialised and every Rust key threw.)
1149
1157
  function rustUnitKey(unit, scan) {
1150
1158
  const memoKey = `${unit}\0${/^test:rust(?:-serial)?:/.test(scan.id) ? "test" : "compile"}`;
1151
1159
  if (unitKeyMemo.has(memoKey)) return unitKeyMemo.get(memoKey);
@@ -1405,11 +1413,196 @@ export function readUnitList(readFile, file) {
1405
1413
  return units;
1406
1414
  }
1407
1415
 
1416
+ 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; };
1417
+
1418
+ /**
1419
+ * The fixed unit inventory of one commit, read from its object database alone (never the checkout): every
1420
+ * `crates/<x>/Cargo.toml` and `packages/<x>/package.json`, with sibling path dependencies (crate-workspaces.mjs) and
1421
+ * `@rightkit/*` npm dependencies. Throws when the commit's tree or a manifest cannot be read: a selection computed
1422
+ * from a partial inventory would silently skip units.
1423
+ */
1424
+ export function inventoryAtCommit({ git, commit }) {
1425
+ const listed = git("ls-tree", "-r", "--name-only", "-z", commit);
1426
+ if (failed(listed)) throw new Error(`cannot list the tree of ${commit.slice(0, 12)}: ${why(listed)}`);
1427
+ const files = new Set(text(listed).split("\0").filter(Boolean));
1428
+ 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); };
1429
+ const parse = createRequire(import.meta.url)("smol-toml").parse;
1430
+ const manifests = new Map();
1431
+ for (const file of [...files].filter((f) => f === "Cargo.toml" || /^crates\/[^/]+\/Cargo\.toml$/.test(f)).sort()) {
1432
+ try { manifests.set(path.posix.dirname(file), parse(show(file))); }
1433
+ catch (e) { throw new Error(`cannot parse ${file}: ${e.message}`); }
1434
+ }
1435
+ const crates = [...manifests].filter(([dir, m]) => dir.startsWith("crates/") && m.package);
1436
+ const byDir = new Map(crates.map(([dir, m]) => [dir, m.package.name]));
1437
+ const byName = new Set(byDir.values());
1438
+ const cargo = crates.map(([dir, m]) => {
1439
+ if (typeof m.package.name !== "string") throw new Error(`${dir}/Cargo.toml has no package name`);
1440
+ let workspaceDir = typeof m.package.workspace === "string" ? path.posix.normalize(path.posix.join(dir, m.package.workspace)) : dir;
1441
+ if (typeof m.package.workspace !== "string") while (workspaceDir !== "." && !manifests.get(workspaceDir)?.workspace) workspaceDir = path.posix.dirname(workspaceDir);
1442
+ const workspace = manifests.get(workspaceDir)?.workspace;
1443
+ const tables = [];
1444
+ 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]);
1445
+ const deps = new Set();
1446
+ for (const table of tables) for (const [alias, original] of Object.entries(table)) {
1447
+ let spec = original; let base = dir;
1448
+ if (spec && typeof spec === "object" && spec.workspace === true) {
1449
+ spec = workspace?.dependencies?.[alias]; base = workspaceDir;
1450
+ if (!spec) throw new Error(`${dir}/Cargo.toml cannot resolve workspace dependency ${alias}`);
1451
+ }
1452
+ const name = typeof spec === "object" ? (spec.package ?? alias) : alias;
1453
+ if (typeof spec === "object" && spec.path !== undefined) {
1454
+ if (typeof spec.path !== "string") throw new Error(`${dir}: invalid path for ${alias}`);
1455
+ const target = path.posix.normalize(path.posix.join(base, spec.path));
1456
+ if (target.startsWith("crates/") && !byDir.has(target)) throw new Error(`${dir}: dependency ${alias} points to unknown crate ${target}`);
1457
+ 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); }
1458
+ } else if (byName.has(name) || name.startsWith("rightkit-")) deps.add(name);
1459
+ }
1460
+ return { dir, name: m.package.name, deps: [...deps] };
1461
+ });
1462
+ const npm = [];
1463
+ for (const file of [...files].filter((f) => /^packages\/[^/]+\/package\.json$/.test(f)).sort()) {
1464
+ let parsed;
1465
+ try { parsed = JSON.parse(show(file)); } catch (e) { throw new Error(`cannot parse ${file}: ${e.message}`); }
1466
+ if (typeof parsed?.name !== "string") throw new Error(`${file} has no package name`);
1467
+ const names = [];
1468
+ for (const key of ["dependencies", "devDependencies", "optionalDependencies", "peerDependencies"]) {
1469
+ const table = parsed[key] ?? {};
1470
+ if (!table || typeof table !== "object" || Array.isArray(table)) throw new Error(`${file}: invalid ${key}`);
1471
+ for (const [name, version] of Object.entries(table)) {
1472
+ const alias = typeof version === "string" && version.match(/^npm:(@rightkit\/[^@]+)(?:@|$)/)?.[1];
1473
+ const target = alias || name;
1474
+ if (target.startsWith("@rightkit/")) names.push(target);
1475
+ else if (typeof version === "string" && version.startsWith("workspace:")) throw new Error(`${file}: unsupported workspace dependency ${name}`);
1476
+ }
1477
+ }
1478
+ npm.push({ dir: file.slice(0, -"/package.json".length), name: parsed.name, deps: names });
1479
+ }
1480
+ return buildInventory({ cargo, npm });
1481
+ }
1482
+
1483
+ /** The paths changed between `base` and `commit` (three-dot: what the commit side changed since the merge base). */
1484
+ /** Classify a committed private unit without publication-only version rules. */
1485
+ export function privateUnitManifest({ selector, content }) {
1486
+ const match = /^(?:npm:(@rightkit\/[a-z0-9-]+)|cargo:(rightkit-[a-z0-9-]+))$/.exec(selector);
1487
+ if (!match) throw new Error(`invalid unit selector ${selector}`);
1488
+ const kind = match[1] ? "npm" : "cargo";
1489
+ let parsed;
1490
+ try { parsed = kind === "npm" ? JSON.parse(content) : createRequire(import.meta.url)("smol-toml").parse(content); }
1491
+ catch (error) { throw new Error(`${selector}: cannot parse manifest: ${error.message}`); }
1492
+ const pkg = kind === "npm" ? parsed : parsed.package;
1493
+ const name = match[1] ?? match[2];
1494
+ if (pkg?.name !== name) throw new Error(`${selector}: manifest name does not match`);
1495
+ return { kind, name, private: kind === "npm" ? pkg.private === true : pkg.publish === false || (Array.isArray(pkg.publish) && pkg.publish.length === 0) };
1496
+ }
1497
+
1498
+ export function changedPathsAt({ git, base, commit }) {
1499
+ const diff = git("diff", "--name-status", "-z", "--find-renames", `${base}...${commit}`);
1500
+ if (failed(diff)) throw new Error(`cannot diff ${base}...${commit.slice(0, 12)}: ${why(diff)}; pass --base <ref>`);
1501
+ const fields = text(diff).split("\0"); if (fields.at(-1) === "") fields.pop();
1502
+ const paths = [];
1503
+ while (fields.length) {
1504
+ const status = fields.shift();
1505
+ if (!/^(?:[ACDMRT]|R[0-9]+|C[0-9]+)$/.test(status) || !fields.length) throw new Error(`invalid diff status ${status}`);
1506
+ paths.push(fields.shift());
1507
+ if (/^[RC][0-9]+$/.test(status)) { if (!fields.length) throw new Error(`missing rename path for ${status}`); paths.push(fields.shift()); }
1508
+ }
1509
+ return [...new Set(paths)];
1510
+ }
1511
+
1512
+ /**
1513
+ * One shared execution for a selected unit list (rightkit#1505): dependency-first order, one shared Class A (the
1514
+ * first unit's, scoped to every selected directory and remembered for the rest), every independent unit run even
1515
+ * when another fails, a unit whose selected dependency failed recorded blocked and not run, one receipt per unit
1516
+ * (with `--receipt-dir`) plus one aggregate report. Returns the exit the door run ends with: 0 only when every
1517
+ * selected unit passed, else the first failing unit's code (1 when only blocked units failed the run).
1518
+ */
1519
+ export async function runSharedUnitList({ o, io, stage, commit, selected, inventory, receiptDir = undefined, base = null, unmatched = [], runUnit = null }) {
1520
+ const tag = "rightkit-gate:";
1521
+ if (io[CARGO_WIDTH] !== undefined) {
1522
+ const problem = cargoWidthUnitsProblem(selected);
1523
+ if (problem) { o.err(`${tag} BLOCKED: ${problem}`); return 2; }
1524
+ }
1525
+ const bySelector = new Map((inventory?.units ?? []).map((u) => [u.selector, u]));
1526
+ const rows = selected.map((s) => ({ dir: unitDirOfSelector(s.selector), reason: "listed", ...bySelector.get(s.selector), ...s }));
1527
+ const order = inventory ? dependencyFirstOrder(inventory, new Set(rows.map((r) => r.selector))) : rows.map((r) => r.selector);
1528
+ const ordered = order.map((sel) => rows.find((r) => r.selector === sel));
1529
+ const unitListClassA = { dirs: [...new Set(ordered.map((r) => r.dir).filter(Boolean))], memo: new Map() };
1530
+ if (receiptDir !== undefined) {
1531
+ try { o.mkdir(receiptDir); } catch (e) { o.err(`${tag} BLOCKED: receipt directory must be new: ${receiptDir} (${e.message}); nothing ran`); return 2; }
1532
+ }
1533
+ if (stage === "compile" && !runUnit && !io.runUnitForList && ordered.length) {
1534
+ const union = { selected: ordered, inventory, rows: null, coverage: null, internal: [], commands: [], commit, runId: randomUUID() };
1535
+ const exit = await main(["--to", "compile", "--unit", ordered[0].selector, "--commit", commit], { ...io, unitListClassA, [UNIT_LIST_UNION]: union });
1536
+ const results = ordered.map((unit) => {
1537
+ const evidence = union.coverage?.filter((r) => r.selector === unit.selector) ?? [];
1538
+ const internal = union.internal.filter((r) => r.selector === unit.selector);
1539
+ const expected = union.expected?.get(unit.selector);
1540
+ const all = [...internal, ...evidence];
1541
+ const failed = !expected || all.length !== expected || all.some((r) => r.status === "failed" || r.status === "fail");
1542
+ const blocked = !failed && all.some((r) => r.status === "blocked" || r.status === "not-run");
1543
+ const status = failed ? "failed" : blocked ? "blocked" : union.verified && all.every((r) => r.status === "passed" || r.status === "pass") ? "passed" : "failed";
1544
+ return { selector: unit.selector, status, ...(status === "failed" ? { code: exit || 1 } : {}) };
1545
+ });
1546
+ const report = unitListReport({ commit, stage, base, selected: ordered, results, unmatched }); report.runId = union.runId;
1547
+ for (const row of report.units) {
1548
+ 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) };
1549
+ if (receiptDir === undefined) row.receipt = { status: "not-requested" };
1550
+ else {
1551
+ const name = `gate-${row.selector.replace(/^npm:@rightkit\//, "npm-").replace(/^cargo:/, "")}.json`;
1552
+ const data = `${JSON.stringify(evidence, null, 2)}\n`; o.writeFile(path.join(receiptDir, name), data);
1553
+ row.receipt = { status: "written", file: name, sha256: createHash("sha256").update(data).digest("hex") };
1554
+ }
1555
+ o.out(`${tag} unit ${row.selector}: ${row.status}`);
1556
+ }
1557
+ 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)}`);
1558
+ if (receiptDir !== undefined) o.writeFile(path.join(receiptDir, "units-report.json"), `${JSON.stringify(report, null, 2)}\n`);
1559
+ return report.ok ? 0 : (exit || 1);
1560
+ }
1561
+ const run = runUnit ?? io.runUnitForList ?? (async (selector, receipt) => main(["--to", stage, "--unit", selector, "--commit", commit, ...receipt], { ...io, unitListClassA }));
1562
+ const outcomes = new Map();
1563
+ const receiptEvidence = new Map();
1564
+ const runId = randomUUID();
1565
+ const bad = new Set(); // failed or blocked selectors, for the dependency check of later units
1566
+ for (const [i, row] of ordered.entries()) {
1567
+ const blocker = (bySelector.get(row.selector)?.deps ?? []).find((d) => bad.has(d));
1568
+ if (blocker) {
1569
+ bad.add(row.selector);
1570
+ o.err(`${tag} unit list ${i + 1}/${ordered.length}: ${row.selector} blocked: its dependency ${blocker} did not pass; not run`);
1571
+ continue;
1572
+ }
1573
+ o.out(`${tag} unit list ${i + 1}/${ordered.length}: ${row.selector} (${row.reason}${row.via ? ` via ${row.via}` : ""}) on commit ${commit.slice(0, 12)}`);
1574
+ const receipt = receiptDir === undefined ? [] : ["--receipt-out", path.join(receiptDir, `gate-${row.selector.replace(/^npm:@rightkit\//, "npm-").replace(/^cargo:/, "")}.json`)];
1575
+ let code = await run(row.selector, receipt, unitListClassA);
1576
+ if (receiptDir !== undefined) {
1577
+ const file = receipt[1];
1578
+ try {
1579
+ const bytes = (o.readFile ?? fs.readFileSync)(file);
1580
+ receiptEvidence.set(row.selector, { status: "written", file: path.basename(file), sha256: createHash("sha256").update(bytes).digest("hex") });
1581
+ } catch (error) {
1582
+ receiptEvidence.set(row.selector, { status: "missing", file: path.basename(file) });
1583
+ if (code === 0) { o.err(`${tag} ${row.selector}: successful run did not produce a readable receipt (${error.message})`); code = 1; }
1584
+ }
1585
+ }
1586
+ outcomes.set(row.selector, { ran: true, code });
1587
+ if (code !== 0) bad.add(row.selector);
1588
+ }
1589
+ const results = classifyUnitResults({ selected: ordered, inventory: inventory ?? { units: rows }, outcomes });
1590
+ const report = unitListReport({ commit, stage, base, selected: ordered, results, unmatched });
1591
+ report.runId = runId;
1592
+ for (const row of report.units) row.receipt = receiptDir === undefined ? { status: "not-requested" } : (receiptEvidence.get(row.selector) ?? { status: "not-run" });
1593
+ 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)` : ""}`);
1594
+ 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)}`);
1595
+ if (receiptDir !== undefined) o.writeFile(path.join(receiptDir, "units-report.json"), `${JSON.stringify(report, null, 2)}\n`);
1596
+ if (report.ok) return 0;
1597
+ return results.find((r) => r.status === "failed")?.code || 1;
1598
+ }
1599
+
1408
1600
  /**
1409
1601
  * 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
1602
  * 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
1603
+ * `--changed [--base <ref>]` (the changed units plus their dependents, planned from the commit's fixed inventory: the routine
1604
+ * route, no handwritten list), `--units-file` (an explicit list, parsed into the same shared run) or
1605
+ * `--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
1606
  * 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
1607
  * all-units flag and its id are removed from `args`). An unresolvable commit is runStages' own refusal, so it goes on.
1415
1608
  */
@@ -1424,27 +1617,59 @@ export function sampleAppOf({ o, root, git, commit }) {
1424
1617
  return apps.find((dir) => typeof dir === "string" && dir && !dir.includes("..") && (rel === dir || rel.startsWith(`${dir}/`))) ?? null;
1425
1618
  }
1426
1619
 
1427
- export async function rightkitDoorRule(o, args, root, git, io, { unitsFileFlag, allUnitsFlag, unitList }) {
1620
+ export async function rightkitDoorRule(o, args, root, git, io, { unitsFileFlag, allUnitsFlag, unitList, changedFlag = false }) {
1428
1621
  const tag = "rightkit-gate:";
1429
1622
  const option = (name) => { const i = args.indexOf(name); return i < 0 ? undefined : args[i + 1]; };
1430
1623
  let pinned;
1431
1624
  try { pinned = (await import("../snapshot.mjs")).resolveCommit(root, option("--commit") ?? "HEAD"); } catch { return {}; }
1432
1625
  const inRightKit = rightkitIdentityAt(git, pinned.commit);
1433
1626
  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`);
1627
+ if (!unitsFileFlag && !allUnitsFlag && !changedFlag) return {};
1628
+ const flag = unitsFileFlag ? "--units-file" : changedFlag ? "--changed" : "--all-units-exception";
1629
+ 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
1630
  return { exit: 1 };
1437
1631
  }
1438
- if (unitsFileFlag) {
1632
+ if (unitsFileFlag || changedFlag) {
1439
1633
  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")) { o.err(`${tag} a unit list run takes only --to, --units-file and optional --commit (a receipt is written per unit run: run the unit alone with --receipt-out)`); return { exit: 2 }; }
1442
- for (const [i, selector] of unitList.entries()) {
1443
- o.out(`${tag} unit list ${i + 1}/${unitList.length}: ${selector} on commit ${pinned.commit.slice(0, 12)}`);
1444
- const code = await main(["--to", stage, "--unit", selector, "--commit", pinned.commit], io);
1445
- 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 }; }
1634
+ const ownFlag = unitsFileFlag ? "--units-file" : "--changed";
1635
+ const allowed = unitsFileFlag ? ["--to", "--commit", "--receipt-dir"] : ["--to", "--commit", "--receipt-dir", "--base", "--changed"];
1636
+ const given = args.filter((a, i) => a.startsWith("--") && !(unitsFileFlag && args[i - 1] === ownFlag) && a !== ownFlag);
1637
+ 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 }; }
1638
+ const receiptDir = option("--receipt-dir");
1639
+ if (receiptDir !== undefined && (receiptDir.startsWith("--") || !path.isAbsolute(receiptDir))) { o.err(`${tag} --receipt-dir needs an absolute directory`); return { exit: 2 }; }
1640
+ // A complete inventory is required for both selection and dependency blocking.
1641
+ let inventory = null;
1642
+ try { inventory = inventoryAtCommit({ git, commit: pinned.commit }); }
1643
+ catch (e) {
1644
+ o.err(`${tag} BLOCKED: cannot plan ${ownFlag} on ${pinned.commit.slice(0, 12)}: ${e.message}; nothing ran`); return { exit: 2 };
1645
+ }
1646
+ if (unitsFileFlag) {
1647
+ const unknown = unitList.filter((selector) => !inventory.units.some((u) => u.selector === selector));
1648
+ if (unknown.length) { o.err(`${tag} BLOCKED: units missing from inventory: ${unknown.join(", ")}; nothing ran`); return { exit: 2 }; }
1649
+ const selected = unitList.map((selector) => ({ selector, reason: "listed" }));
1650
+ return { exit: await runSharedUnitList({ o, io, stage, commit: pinned.commit, selected, inventory, receiptDir }) };
1651
+ }
1652
+ // --changed (rightkit#1505): no handwritten list for routine work. Changed paths against the base select their
1653
+ // units plus every transitive dependent (affected-units.mjs); the plan is printed before anything runs.
1654
+ const base = option("--base") ?? "origin/main";
1655
+ let selection;
1656
+ try {
1657
+ const mergeBase = git("merge-base", base, pinned.commit);
1658
+ if (failed(mergeBase)) throw new Error(`cannot resolve merge base: ${why(mergeBase)}`);
1659
+ const oldInventory = inventoryAtCommit({ git, commit: text(mergeBase).trim() });
1660
+ const changedPaths = changedPathsAt({ git, base, commit: pinned.commit });
1661
+ selection = selectAffectedAcrossInventories({ changedPaths, oldInventory, inventory });
1662
+ if (selection.unmatched.length) throw new Error(`unclassified changed inputs: ${selection.unmatched.join(", ")}; classify their ownership before running`);
1663
+ }
1664
+ catch (e) { o.err(`${tag} BLOCKED: cannot plan --changed on ${pinned.commit.slice(0, 12)}: ${e.message}; nothing ran`); return { exit: 2 }; }
1665
+ 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 ? ", ..." : ""})` : ""}`);
1666
+ for (const s of selection.selected) o.out(`${tag} planned ${s.selector} (${s.reason}${s.via ? ` via ${s.via}` : ""})`);
1667
+ if (!selection.selected.length) {
1668
+ 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`); }
1669
+ o.out(`${tag} unit report: 0 passed, 0 failed, 0 blocked, 0 not-run of 0 on ${pinned.commit.slice(0, 12)}`);
1670
+ return { exit: 0 };
1446
1671
  }
1447
- return { exit: 0 };
1672
+ return { exit: await runSharedUnitList({ o, io, stage, commit: pinned.commit, selected: selection.selected, inventory, receiptDir, base, unmatched: selection.unmatched }) };
1448
1673
  }
1449
1674
  if (allUnitsFlag) {
1450
1675
  const id = option("--all-units-exception");
@@ -1468,7 +1693,7 @@ export async function rightkitDoorRule(o, args, root, git, io, { unitsFileFlag,
1468
1693
  o.out(`${tag} RightKit sample app ${sample}: built as an app, scoped to ${sample} (ci/sample-apps.json)`);
1469
1694
  return {};
1470
1695
  }
1471
- 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`);
1696
+ 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`);
1472
1697
  return { exit: 1 };
1473
1698
  }
1474
1699
 
@@ -2507,6 +2732,7 @@ async function runUnitSnapshot(o, args, root, git, io, option) {
2507
2732
  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); };
2508
2733
  const executor = (o.resolveExecutor ?? gateResolveExecutor)({ env: o.env, platform: o.platform, exists: o.exists, which, readFile: o.readFile }); applyExecutorEnv(o, executor);
2509
2734
  if (executor.kind === "refuse") { o.err(`${tag} BLOCKED: ${executor.problem}`); return 1; }
2735
+ if (option("--ci-proof-out") && executor.kind !== "broker") { o.err(`${tag} BLOCKED: --ci-proof-out requires the managed snapshot broker`); return 1; }
2510
2736
  { const decided = routePlan(o, { to: option("--to"), stages: [], devTest: true, executor, capabilities: await brokerCapabilityStateWithHandshake(o, { to: option("--to"), executor }) });
2511
2737
  if (decided.refusal?.code === "RK_BROKER_CAPABILITY_MISSING") { o.err(`${tag} BLOCKED: ${decided.refusal.code}: ${decided.refusal.message}; nothing ran`); return 1; } }
2512
2738
  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,17 +2751,22 @@ async function runUnitSnapshot(o, args, root, git, io, option) {
2525
2751
  o.out(`${tag} snapshot ${synced.path} is commit ${synced.commit} tree ${synced.tree} (written=${synced.written} removed=${synced.removed} unchanged=${synced.unchanged})`);
2526
2752
  if (synced.identity) o.out(`${tag} source identity ${synced.identity.file}: ${synced.identity.written ? "written" : synced.identity.kept ? "kept" : `not written (${synced.identity.reason})`}`);
2527
2753
  const ds = { own, path: synced.path, commit: synced.commit, tree: synced.tree, root: snapshotsAt, ledger: { entries: [] } };
2754
+ if (io[UNIT_LIST_UNION]) return await runUnionSnapshot({ o, io, root, git, ds, union: io[UNIT_LIST_UNION], unitListClassA: io.unitListClassA });
2528
2755
  // A unit's test or pack that reaches Cargo must never write `target/` into the snapshot (npm units included): see bindUnitCargo.
2529
2756
  // A check starts no unit command: its own Class A path binds read-only Cargo calls. Resolving every unit's compile output
2530
2757
  // here would run unrelated metadata before the scoped check even begins.
2531
2758
  // A crate's consumer rows (ci/gate.config.json rust.<crate>.consumerRows, local-publish.mjs) build their own Cargo workspaces under ci/consumers/: they
2532
2759
  // 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).
2760
+ let privateUnit;
2761
+ try { privateUnit = privateUnitManifest({ selector, content: o.readFile(path.join(ds.path, manifest)) }); }
2762
+ catch (e) { o.err(`${tag} BLOCKED: ${e.message}; nothing ran`); return 1; }
2763
+ if (privateUnit.private && !["check", "compile"].includes(option("--to"))) { o.err(`${tag} BLOCKED: ${selector} is private and cannot be packaged, qualified or published`); return 1; }
2533
2764
  let consumerScope = [];
2534
2765
  if (match[2] && !toolRun) {
2535
2766
  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))))]; }
2536
2767
  catch { consumerScope = []; }
2537
2768
  }
2538
- 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)] } : {}) });
2769
+ 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)] } : {}) });
2539
2770
  if (bound.refusal) { o.err(`${tag} BLOCKED: RK_SNAPSHOT_OUTPUT_UNPINNED: ${bound.refusal}; nothing ran`); return 1; }
2540
2771
  if (bound.note) o.out(`${tag} ${bound.note}`);
2541
2772
  const envExtra = bound.env;
@@ -2551,7 +2782,46 @@ async function runUnitSnapshot(o, args, root, git, io, option) {
2551
2782
  for (const p of calls.slice(0, 10)) o.err(`${tag} RK_CHECK_ERROR: [unit:${stage}] a cargo call the unit stage made did not complete: ${typeof p === "string" ? p : JSON.stringify(p)}`);
2552
2783
  return calls.length === 0;
2553
2784
  } };
2554
- const runCheck = (tier) => (o.runCheck ?? (() => main(["check", "--commit", ds.commit, "--full-a", "--snapshot", ds.path, "--rule-tier", tier, "--scope", path.posix.dirname(manifest)], { ...io, cwd: root, buildOwnership: own })))(tier);
2785
+ // A unit-list run (--units-file) shares one Class A: scoped to every listed unit's directory, run by the first unit, remembered for the rest.
2786
+ const unitDir = path.posix.dirname(manifest);
2787
+ const shared = io.unitListClassA?.dirs?.includes(unitDir) ? io.unitListClassA : null;
2788
+ const runCheck = async (tier) => {
2789
+ const memoKey = `${ds.commit}:${tier}`;
2790
+ // One Class A verdict per commit and tier for the whole list, pass or fail: the scope is every listed unit's
2791
+ // directory, so re-running it per unit after a failure would repeat the same red scans once per unit.
2792
+ 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; }
2793
+ const scopes = shared ? shared.dirs : [unitDir];
2794
+ 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);
2795
+ if (shared) shared.memo.set(memoKey, code);
2796
+ return code;
2797
+ };
2798
+ if (privateUnit.private) {
2799
+ if (!localBuildGrantedAt(source)) { o.err(`${tag} BLOCKED: ${selector} requires the committed local-build grant`); return 1; }
2800
+ if (option("--to") === "compile") {
2801
+ try {
2802
+ const { knownRedEntry } = await import("../unit-gate.mjs");
2803
+ const red = knownRedEntry({ unit: privateUnit, root: ds.path, platform: o.platform });
2804
+ if (red) { o.err(`${tag} BLOCKED: ${selector} is known red (${red.host}: ${red.reason}); nothing compiled`); return 1; }
2805
+ } catch (e) { o.err(`${tag} BLOCKED: ${e.message}; nothing compiled`); return 1; }
2806
+ }
2807
+ const report = { schema: "rightkit.unit-gate-report/1", unit: privateUnit, commit: ds.commit, tree: ds.tree, executor: executor.kind, stages: {} };
2808
+ const save = () => { if (reportOut) o.writeFile(path.resolve(o.cwd, reportOut), `${JSON.stringify(report, null, 2)}\n`); };
2809
+ for (const stage of option("--to") === "compile" ? ["check", "compile"] : ["check"]) {
2810
+ let code = 1;
2811
+ if (await openSnapshotStage({ o, ds, root, stage, tag })) {
2812
+ try {
2813
+ code = stage === "check" ? await runCheck("compile") : await main(["--all", "--commit", ds.commit, "--snapshot", ds.path, "--scope", unitDir], {
2814
+ ...io, cwd: root, readStdin: () => "", buildOwnership: own, classAEarlier: true, snapshotLedger: ds.ledger?.entries ?? [],
2815
+ onCompileLedger: (entries) => { ds.compileAdmitted = entries; }, [PRIVATE_SCOPED_COMPILE]: { selector, unitDir },
2816
+ });
2817
+ } catch (e) { o.err(`${tag} ${selector} ${stage}: ${e.message}`); code = 1; }
2818
+ if (!(await closeSnapshotStage({ o, ds, root, stage, step: `unit:${stage}`, tag })).ok) code = 1;
2819
+ }
2820
+ report.stages[stage] = { ok: code === 0, code }; save();
2821
+ if (code !== 0) return code;
2822
+ }
2823
+ return 0;
2824
+ }
2555
2825
  if (toolRun) {
2556
2826
  const { runUnitTool } = await import("../tool-build.mjs");
2557
2827
  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 ?? {},
@@ -2561,7 +2831,7 @@ async function runUnitSnapshot(o, args, root, git, io, option) {
2561
2831
  ...(reportOut ? { writeReport: (report) => o.writeFile(path.resolve(o.cwd, reportOut), `${JSON.stringify(o.brokerException ? { ...report, brokerException: o.brokerException } : report, null, 2)}\n`) } : {}),
2562
2832
  });
2563
2833
  }
2564
- 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,
2834
+ 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,
2565
2835
  resolve: (sel, r) => resolveUnit(sel, r, { granted: () => localBuildGrantedAt(source) }),
2566
2836
  ...(o.loadUnitOwner ? { loadOwner: o.loadUnitOwner } : {}),
2567
2837
  ...(o.unitGateDeps ?? {}), // test seam: fetchReceipt, stageCommands, verifyReceipts, selfGit
@@ -2575,6 +2845,50 @@ async function runUnitSnapshot(o, args, root, git, io, option) {
2575
2845
  }
2576
2846
  }
2577
2847
 
2848
+ /** One owner, one snapshot and one shared Class A before a unit-list compile. */
2849
+ async function runUnionSnapshot({ o, io, root, git, ds, union, unitListClassA }) {
2850
+ const tag = "rightkit-gate:";
2851
+ const { localBuildGrantedAt, consumerRows } = await import("../local-publish.mjs");
2852
+ const { knownRedEntry } = await import("../unit-gate.mjs");
2853
+ const source = { checkout: root, commit: ds.commit, tree: ds.tree };
2854
+ if (!localBuildGrantedAt(source)) { o.err(`${tag} BLOCKED: unit list requires the committed local-build grant`); return 1; }
2855
+ let config;
2856
+ try {
2857
+ config = JSON.parse(o.readFile(path.join(ds.path, "ci/gate.config.json")));
2858
+ union.consumerDirs = [];
2859
+ for (const row of union.selected) {
2860
+ const file = row.selector.startsWith("cargo:") ? `${row.dir}/Cargo.toml` : `${row.dir}/package.json`;
2861
+ if (failed(git("cat-file", "-e", `${ds.commit}:${file}`))) throw new Error(`${file} is absent from the selected commit`);
2862
+ const unit = privateUnitManifest({ selector: row.selector, content: o.readFile(path.join(ds.path, file)) });
2863
+ const red = knownRedEntry({ unit, root: ds.path, platform: o.platform });
2864
+ if (red) throw new Error(`${row.selector} is known red (${red.host}: ${red.reason})`);
2865
+ if (unit.kind === "cargo") for (const consumer of consumerRows(unit.name, config.rust?.[unit.name] ?? {})) {
2866
+ 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`);
2867
+ const dir = path.posix.dirname(consumer.manifestPath);
2868
+ union.consumerDirs.push(dir); unitListClassA.dirs.push(dir);
2869
+ }
2870
+ }
2871
+ unitListClassA.dirs = [...new Set(unitListClassA.dirs)];
2872
+ } catch (error) { o.err(`${tag} BLOCKED: cannot prepare unit-list scope: ${error.message}`); return 1; }
2873
+ if (!await openSnapshotStage({ o, ds, root, stage: "check", tag })) return 1;
2874
+ let check = 1;
2875
+ 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"); }
2876
+ catch (error) { o.err(`${tag} unit-list check: ${error.message}`); }
2877
+ if (!(await closeSnapshotStage({ o, ds, root, stage: "check", tag })).ok || check !== 0) return check || 1;
2878
+ if (!await openSnapshotStage({ o, ds, root, stage: "compile", tag })) return 1;
2879
+ let code = 1;
2880
+ try {
2881
+ code = await main(["--all", "--commit", ds.commit, "--snapshot", ds.path, ...unitListClassA.dirs.flatMap((dir) => ["--scope", dir])], {
2882
+ ...io, cwd: root, readStdin: () => "", buildOwnership: ds.own, classAEarlier: true, snapshotLedger: ds.ledger?.entries ?? [],
2883
+ onCompileLedger: (entries) => { ds.compileAdmitted = entries; }, [UNIT_LIST_UNION]: union,
2884
+ verifyUnionSnapshot: async () => { await verifyDoorSnapshot(o, ds, root, { ledger: ds.ledger?.entries ?? [] }); return true; },
2885
+ });
2886
+ } catch (error) { o.err(`${tag} unit-list compile: ${error.message}`); }
2887
+ const closed = await closeSnapshotStage({ o, ds, root, stage: "compile", tag });
2888
+ union.verified = closed.ok && union.completed === true && union.sharedClean === true;
2889
+ return closed.ok ? code : 1;
2890
+ }
2891
+
2578
2892
  /**
2579
2893
  * Whether the door takes the snapshot route on this host: every host but hosted CI, whose runner checkout is the commit. Linux
2580
2894
  * compiles it directly; Mac and Dell compile it through the RustRight snapshot carrier. There is no other route and no flag or
@@ -3201,8 +3515,8 @@ export function doorPath(o, gateFile = o.gateFile ?? fileURLToPath(import.meta.u
3201
3515
  * lookup of a usable rustfmt, which the deferred Rust gate needs).
3202
3516
  */
3203
3517
  /** 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. */
3204
- const STAGE_VALUE_FLAGS = Object.freeze(["--to", "--platform", "--tier", "--commit", "--receipt-in", "--receipt-out", "--unit", "--units-file", "--all-units-exception"]);
3205
- const STAGE_BOOLEAN_FLAGS = Object.freeze(["--route"]);
3518
+ 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"]);
3519
+ const STAGE_BOOLEAN_FLAGS = Object.freeze(["--route", "--changed"]);
3206
3520
 
3207
3521
  /**
3208
3522
  * 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
@@ -3235,6 +3549,39 @@ export async function main(argv, io = {}) {
3235
3549
  gateFile: fileURLToPath(import.meta.url), ...io,
3236
3550
  };
3237
3551
  const args = [...argv];
3552
+ if (args.includes("--ci-proof-out")) {
3553
+ try {
3554
+ const problem = stageArgsProblem(args);
3555
+ if (problem) throw new Error(problem);
3556
+ const value = (flag) => { const i = args.indexOf(flag); return i < 0 ? null : args[i + 1]; };
3557
+ 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");
3558
+ 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");
3559
+ const paths = o.platform === "win32" ? path.win32 : path.posix;
3560
+ const scratch = o.platform === "win32" ? "D:\\scratch" : "/Volumes/D/scratch";
3561
+ const file = value("--ci-proof-out");
3562
+ if (!file || !paths.isAbsolute(file)) throw new Error("--ci-proof-out needs an absolute path inside D scratch");
3563
+ const scratchReal = fs.realpathSync.native(scratch);
3564
+ const parentReal = fs.realpathSync.native(paths.dirname(file));
3565
+ const relative = paths.relative(scratchReal, parentReal);
3566
+ if (relative === ".." || relative.startsWith(`..${paths.sep}`) || paths.isAbsolute(relative)) throw new Error("--ci-proof-out parent is outside D scratch");
3567
+ try { fs.lstatSync(file); throw new Error("--ci-proof-out already exists"); }
3568
+ catch (error) { if (error.code !== "ENOENT") throw error; }
3569
+ } catch (error) { o.err(`rightkit-gate: ${error.message}`); return 2; }
3570
+ }
3571
+ const widthFlags = args.reduce((found, arg, i) => arg === "--cargo-jobs" ? [...found, i] : found, []);
3572
+ if (widthFlags.length) {
3573
+ try {
3574
+ if (widthFlags.length !== 1 || io[CARGO_WIDTH] !== undefined) throw new Error("--cargo-jobs may be given once");
3575
+ const index = widthFlags[0];
3576
+ if (args.includes("--") && index > args.indexOf("--")) throw new Error("--cargo-jobs must precede --");
3577
+ const width = parseCargoWidth(args[index + 1]);
3578
+ const routeProblem = cargoWidthRouteProblem(args);
3579
+ if (routeProblem) throw new Error(routeProblem);
3580
+ args.splice(index, 2);
3581
+ io = { ...io, [CARGO_WIDTH]: width };
3582
+ o[CARGO_WIDTH] = width;
3583
+ } catch (error) { o.err(`rightkit-gate: ${error.message}`); return 2; }
3584
+ }
3238
3585
  // 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
3239
3586
  // rebuilt from broker receipts. Machine-readable output is never stamped: the --route JSON, a list or baseline, --json, the version, and the one
3240
3587
  // `verdict deterministic` marker line other tools read.
@@ -3365,7 +3712,13 @@ export async function main(argv, io = {}) {
3365
3712
  const withoutScope = args.slice(1).filter((a, i, list) => a !== "--scope" && list[i - 1] !== "--scope");
3366
3713
  const appArgs = stripSnapshot(withoutScope.filter((a) => a !== "--full-a"));
3367
3714
  if (fullAdmission && !appArgs.includes("--rule-tier")) appArgs.push("--rule-tier", requestedTier);
3368
- 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 } : {}) });
3715
+ // GC-A24: a passing app-rule verdict of a snapshot is reused for the same commit tree, rule code, tier and arguments (ruleVerdictCache).
3716
+ const ruleCache = snapshotDir && snapshotCommit && !args.includes("--worktree") && !o.appCheck ? ruleVerdictCache({ checkout: snapshotCheckout, spawn: o.spawn }) : null;
3717
+ const appKey = ruleCache ? ruleCache.key({ rule: "app-check", tree: snapshotCommit.tree, args: appArgs, gate: gatePackageIdentity(o.gatePackage) }) : null;
3718
+ const appCheck = appKey && ruleCache.passed(appKey)
3719
+ ? (o.out(`check: ${snapshotCommit.commit.slice(0, 12)} app rules: cached pass (tree ${snapshotCommit.tree.slice(0, 12)})`), 0)
3720
+ : 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 } : {}) });
3721
+ if (appKey && appCheck === 0) ruleCache.pass(appKey);
3369
3722
  if (args.includes("--list") || args.includes("--print-baseline") || args.includes("--only") || o.classA === false) {
3370
3723
  // 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.
3371
3724
  // A green partial view exits PARTIAL_EXIT (3), never 0, so a caller that admits only exit 0 rejects it by status alone.
@@ -3406,15 +3759,22 @@ export async function main(argv, io = {}) {
3406
3759
  // The commit's own preflight reads the commit from the checkout's object database; its exports probe imports from the snapshot,
3407
3760
  // whose dependencies class A installed, and reports beside (never over) the commit-bound report publication reads.
3408
3761
  const launch = o.spawnInherit ?? ((cmd, a, opts) => spawnInherit(cmd, a, { ...opts, stdio: "inherit" }));
3409
- const r = launch(process.execPath, [path.join(snapshotDir, "scripts", "preflight.mjs"), "--repo", root, "--commit", snapshotCommit.commit], { cwd: root, env: o.env });
3410
- selfRules = r.status === 0 ? 0 : 1;
3762
+ // GC-A24: RightKit's own preflight and exports probe execute the commit's code with its installed dependencies; a pass is reused
3763
+ // for the same commit tree, installed-dependency bytes, node and platform (and scope), and only a pass.
3411
3764
  const effects = path.join(snapshotDir, "scripts", "ci", "exports-import-effects.mjs");
3412
- if (selfRules === 0 && o.exists(effects) && scopeForward.length === 0) {
3765
+ let selfKey = null;
3766
+ 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; } }
3767
+ const selfCached = Boolean(selfKey && ruleCache.passed(selfKey));
3768
+ if (selfCached) o.out(`preflight: ${snapshotCommit.commit.slice(0, 12)} cached pass (tree ${snapshotCommit.tree.slice(0, 12)}, same installed dependencies)`);
3769
+ const r = selfCached ? { status: 0 } : launch(process.execPath, [path.join(snapshotDir, "scripts", "preflight.mjs"), "--repo", root, "--commit", snapshotCommit.commit], { cwd: root, env: o.env });
3770
+ selfRules = r.status === 0 ? 0 : 1;
3771
+ if (!selfCached && selfRules === 0 && o.exists(effects) && scopeForward.length === 0) {
3413
3772
  const common = o.spawn("git", ["rev-parse", "--path-format=absolute", "--git-common-dir"], { cwd: root });
3414
3773
  const report = path.join(failed(common) ? path.join(root, ".git") : text(common).trim(), "rightkit-gate", "import-effects", `snapshot-${snapshotCommit.commit}.json`);
3415
3774
  const e = launch(process.execPath, [effects, "--root", snapshotDir, "--no-export", "--report", report], { cwd: snapshotDir, env: o.env });
3416
3775
  if (e.status !== 0) selfRules = 1;
3417
3776
  }
3777
+ if (selfKey && !selfCached && selfRules === 0) ruleCache.pass(selfKey);
3418
3778
  } 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) {
3419
3779
  const launch = o.spawnInherit ?? ((cmd, a, opts) => spawnInherit(cmd, a, { ...opts, stdio: "inherit" }));
3420
3780
  const selector = args.includes("--worktree") ? ["--worktree"] : ["--commit", option("--commit") ?? "HEAD"];
@@ -3504,7 +3864,7 @@ export async function main(argv, io = {}) {
3504
3864
  // Full Class A needs a snapshot or the committed hosted checkout. The content pass (`check --commit <sha> --scope <dir>`: publication
3505
3865
  // admission, GC-A03) reads the commit the same way it always did (the warm snapshot, or the runner checkout proven to be that commit
3506
3866
  // in place) and only narrows which executing workspace scans run, so it is the one other form --scope accepts; never the live tree.
3507
- const scopeForm = fullA ? Boolean(snapshotA || hostedCommitA) : classAOnly && !args.includes("--worktree");
3867
+ const scopeForm = fullA ? Boolean(snapshotA || hostedCommitA) : (classAOnly && !args.includes("--worktree")) || Boolean(snapshotB && (o[PRIVATE_SCOPED_COMPILE] || o[UNIT_LIST_UNION]) && o.classAEarlier && o.buildOwnership);
3508
3868
  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; }
3509
3869
  }
3510
3870
  if (args.includes("--base") && (!option("--base") || option("--base").startsWith("--"))) { o.err("rightkit-gate: --base needs a ref"); return 2; }
@@ -3549,18 +3909,19 @@ export async function main(argv, io = {}) {
3549
3909
  // RightKit names its unit on every run (rightkitDoorRule): `--unit <selector>`, `--units-file <json written for this run>` or
3550
3910
  // `--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).
3551
3911
  const gateFlag = (name) => args.includes(name) && (separator < 0 || args.indexOf(name) < separator);
3552
- const unitsFileFlag = gateFlag("--units-file"); const allUnitsFlag = gateFlag("--all-units-exception");
3912
+ const unitsFileFlag = gateFlag("--units-file"); const allUnitsFlag = gateFlag("--all-units-exception"); const changedFlag = gateFlag("--changed");
3553
3913
  let unitList = null;
3554
- if (unitsFileFlag || allUnitsFlag) {
3555
- const flag = unitsFileFlag ? "--units-file" : "--all-units-exception";
3914
+ if (unitsFileFlag || allUnitsFlag || changedFlag) {
3915
+ const flag = unitsFileFlag ? "--units-file" : changedFlag ? "--changed" : "--all-units-exception";
3556
3916
  if (option("--to") === undefined) { o.err(`rightkit-gate: ${flag} applies to a --to stage\n${USAGE}`); return 2; }
3557
- 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; }
3558
- if (!option(flag) || option(flag).startsWith("--")) { o.err(`rightkit-gate: ${flag} needs a value\n${USAGE}`); return 2; }
3917
+ 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; }
3918
+ if (!changedFlag && (!option(flag) || option(flag).startsWith("--"))) { o.err(`rightkit-gate: ${flag} needs a value\n${USAGE}`); return 2; }
3559
3919
  if (unitsFileFlag) {
3560
3920
  try { unitList = readUnitList((f) => o.readFile(path.resolve(o.cwd, f)), option("--units-file")); }
3561
3921
  catch (e) { o.err(`rightkit-gate: ${e.message}`); return 2; }
3562
3922
  }
3563
3923
  }
3924
+ 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; }
3564
3925
  // `--no-broker <exception-id>`: the one documented exception to the mandatory broker on Mac and Dell (broker-exception.mjs). The record is
3565
3926
  // read from the selected commit, never the working tree; every refusal is typed and nothing runs. The run then takes the same stages
3566
3927
  // with the direct executor, and prints and records the exception.
@@ -3604,7 +3965,7 @@ export async function main(argv, io = {}) {
3604
3965
  const gateArgs = separator < 0 ? args : args.slice(0, separator);
3605
3966
  if (gateArgs.includes("--route")) {
3606
3967
  const routeTo = option("--to");
3607
- const clash = ["--unit", "--units-file", "--all-units-exception", "--receipt-in", "--receipt-out"].filter((f) => gateArgs.includes(f));
3968
+ const clash = ["--unit", "--units-file", "--all-units-exception", "--changed", "--receipt-in", "--receipt-out"].filter((f) => gateArgs.includes(f));
3608
3969
  if (routeTo === undefined) { o.err(`rightkit-gate: --route needs --to ${ROUTE_PROBE_STAGES.join("|")}\n${USAGE}`); return 2; }
3609
3970
  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; }
3610
3971
  if (clash.length) { o.err(`rightkit-gate: --route runs nothing and takes no ${clash.join(" or ")}`); return 2; }
@@ -3612,9 +3973,9 @@ export async function main(argv, io = {}) {
3612
3973
  }
3613
3974
  if (option("--to") !== undefined && unitFlag) {
3614
3975
  const selector = option("--unit");
3615
- 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);
3976
+ 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);
3616
3977
  if (!validArgs || !selector) {
3617
- o.err("rightkit-gate: unit stages take only --to, --unit and optional --receipt-out and --commit"); return 2;
3978
+ o.err("rightkit-gate: unit stages take only --to, --unit and optional --receipt-out, --commit and --ci-proof-out"); return 2;
3618
3979
  }
3619
3980
  // 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).
3620
3981
  if (!o.doorSnapshot && snapshotRouteSelected(o)) return await runUnitSnapshot(o, args, root, git, io, option);
@@ -3646,8 +4007,9 @@ export async function main(argv, io = {}) {
3646
4007
  if (unitFlag) { o.err("rightkit-gate: --unit requires --to"); return 2; }
3647
4008
  if (option("--to") !== undefined) {
3648
4009
  // A door run that names no unit: RightKit refuses it unless Adrian's exception or a unit list names what runs (rightkitDoorRule).
3649
- const door = await rightkitDoorRule(o, args, root, git, io, { unitsFileFlag, allUnitsFlag, unitList });
4010
+ const door = await rightkitDoorRule(o, args, root, git, io, { unitsFileFlag, allUnitsFlag, unitList, changedFlag });
3650
4011
  if (door.exit !== undefined) return door.exit;
4012
+ if (o[CARGO_WIDTH] !== undefined) { o.err("rightkit-gate: BLOCKED: --cargo-jobs requires the controlled unit-list route"); return 2; }
3651
4013
  return await runStages(o, args, root, git, io);
3652
4014
  }
3653
4015
  if (sub === "stage") return stageForPublisher(o, args, root, git);
@@ -3690,6 +4052,16 @@ export async function main(argv, io = {}) {
3690
4052
  const executor = (o.resolveExecutor ?? gateResolveExecutor)({ env: o.env, platform: o.platform, exists: o.exists, which, readFile: o.readFile }); applyExecutorEnv(o, executor);
3691
4053
  // A broker-managed host whose broker is unreachable refuses the moment a Cargo manifest is in the snapshot (below): a repository
3692
4054
  // 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.
4055
+ if (o[CARGO_WIDTH] !== undefined && !classAOnly) {
4056
+ try {
4057
+ if (executor.kind !== "broker") throw new Error("--cargo-jobs requires a broker reporting its compile-token pool");
4058
+ const client = executor.client ?? "rustright";
4059
+ const result = spawnBrokerClient(o.spawn, client, ["list"], { env: brokerEnvOf(o, executor), encoding: "utf8", timeout: 20_000, windowsHide: true }, { platform: o.platform, readFile: o.readFile });
4060
+ if (failed(result)) throw new Error("cannot read broker compile-token pool");
4061
+ const size = validateCargoWidthPool(o[CARGO_WIDTH], JSON.parse(text(result)));
4062
+ o.out(`rightkit-gate: Cargo width ${o[CARGO_WIDTH]} (broker token pool ${size})`);
4063
+ } catch (error) { o.err(`rightkit-gate: BLOCKED: ${error.message}`); return 1; }
4064
+ }
3693
4065
  const cargoCommand = executor.cargo ?? ["cargo"];
3694
4066
  // The declared Linux broker route's cargo is `[<absolute validated client>, "cargo"]`, which the scan planner (planScans: `["rustright","cargo"]` or
3695
4067
  // `["cargo"]`) refuses, and a PATH `rustright` is never the client. So the scans are PLANNED with the logical `["rustright","cargo"]` and every spawn the
@@ -3721,7 +4093,9 @@ export async function main(argv, io = {}) {
3721
4093
  let cargoShimDir = null;
3722
4094
  const cleanup = () => {
3723
4095
  if (cargoShimDir) fs.rmSync(cargoShimDir, { recursive: true, force: true });
3724
- if (snapshotGitConfig) { fs.rmSync(snapshotGitConfig, { force: true }); try { fs.rmdirSync(path.dirname(snapshotGitConfig)); } catch { /* not empty: leave it, the next exact sync prunes it */ } }
4096
+ // GC-A24: the config-only origin file stays (snapshotProblem admits exactly it, and the sync keeps exactly it), so an unchanged
4097
+ // snapshot is not rewritten on every run; a snapshot of a checkout whose origin changed gets it pruned by the next sync.
4098
+ void snapshotGitConfig;
3725
4099
  };
3726
4100
  const signals = [];
3727
4101
  try {
@@ -3778,6 +4152,8 @@ export async function main(argv, io = {}) {
3778
4152
  // consumer rows of the crates they exercise (CI treats them the same), never as units.
3779
4153
  let fixtures = [];
3780
4154
  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 */ }
4155
+ // Selected publisher consumer workspaces must participate in discovery, scoped Class A and target binding.
4156
+ 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(/\/$/, "")}/`)));
3781
4157
  // A snapshot has nothing untracked; the working tree (--plan, check --worktree) names its untracked manifests as skipped.
3782
4158
  const untracked = () => {
3783
4159
  if (snapshot) return [];
@@ -4039,6 +4415,7 @@ export async function main(argv, io = {}) {
4039
4415
  fullPlan = planScans({
4040
4416
  // Class A of a commit or tree reads only that snapshot: every scan, cargo's included, runs in the snapshot, never in the live
4041
4417
  // checkout (which may hold other bytes). Compiles (class B) use the live checkout, whose tree the dirty check pinned to HEAD.
4418
+ cargoJobs: classAOnly ? null : (o[CARGO_WIDTH] ?? null),
4042
4419
  changed, contentRoot: repo, liveRoot: (classAOnly && snapshot) || snapshotB ? repo : root, trustedRoot: snapshotA ?? snapshotB ?? root, includeTests: true, rustScope, cargoCommand: planCargoCommand, targetDirs, cargoShim: Boolean(cargoShim),
4043
4420
  tier: fullA ? "release" : (option("--rule-tier") ?? "compile"), cargoLiveRoot,
4044
4421
  // The quiet tests (port, pipe, desktop and wall-clock bound) are proven by the CI shards, one crate per runner, unless
@@ -4051,7 +4428,7 @@ export async function main(argv, io = {}) {
4051
4428
  rustUnits: rust.units, npmUnits: npm, npmRoots, cargoDir: ".", rustLocks, crateFeatures, crateDependents, externalInputs,
4052
4429
  // B1 (rightkit#1458): compile scans of one Cargo workspace run as one cargo invocation per configuration; ci/shards.json `solo` crates never join one.
4053
4430
  // 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.
4054
- classBBatching: o.env.RK_GATE_CLASS_B_BATCH !== "0", shardSolo: shardSoloOf(o, repo),
4431
+ classBBatching: !o[PRIVATE_SCOPED_COMPILE] && o.env.RK_GATE_CLASS_B_BATCH !== "0", shardSolo: shardSoloOf(o, repo),
4055
4432
  // The broker (or, on a direct host, the gate itself) admits compiles; no separate grant file decides it here.
4056
4433
  localCompile: true,
4057
4434
  exists: o.exists, readFile: o.readFile, platform: o.platform,
@@ -4065,10 +4442,24 @@ export async function main(argv, io = {}) {
4065
4442
  if (closure) {
4066
4443
  let kept;
4067
4444
  try {
4445
+ 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");
4068
4446
  kept = closureTools.scopeScans(fullPlan.scans, closure, { rustUnits: rust.units, npmUnits: npm });
4069
4447
  plan = closureTools.scopedPlan(fullPlan, kept.scans, closure);
4448
+ if (o[PRIVATE_SCOPED_COMPILE]) {
4449
+ const { selector, unitDir } = o[PRIVATE_SCOPED_COMPILE];
4450
+ const npmUnit = npm.find((u) => u.dir === unitDir);
4451
+ const rustUnit = rust.units.find((u) => u.dir === unitDir);
4452
+ const owner = selector.startsWith("npm:") ? npmUnit?.name : rustUnit?.name;
4453
+ const names = selector.startsWith("npm:") ? [`test:npm:${owner}`] : [`check:${owner}`, `check-features:${owner}`, `clippy:${owner}`];
4454
+ 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`);
4455
+ }
4070
4456
  } catch (error) { o.err(`${tag} BLOCKED: ${error.message}`); return 1; }
4071
- plan.notes = plan.notes.filter((n) => !n.includes("every Rust unit is in scope"));
4457
+ plan.notes = plan.notes.filter((n) => !n.includes("every Rust unit is in scope") && !n.startsWith("class B batching:"));
4458
+ const batchCandidates = plan.scans.filter((scan) => scan.class === "B" && scan.batchable);
4459
+ const batchCounts = new Map();
4460
+ for (const scan of batchCandidates) batchCounts.set(scan.batchable.key, (batchCounts.get(scan.batchable.key) ?? 0) + 1);
4461
+ const sharedGroups = [...batchCounts.values()].filter((count) => count > 1);
4462
+ 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`);
4072
4463
  const classA = plan.scans.filter((s) => s.class === "A");
4073
4464
  // What actually executes: tests, executing rows and every Cargo scan (metadata, package list, deny, audit run cargo, through the broker
4074
4465
  // 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.
@@ -4077,10 +4468,87 @@ export async function main(argv, io = {}) {
4077
4468
  const cargoExcluded = kept.dropped.filter((s) => closureTools.isCargoScan(s)).length;
4078
4469
  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}`);
4079
4470
  }
4471
+ if (o[CARGO_WIDTH] !== undefined && !classAOnly) {
4472
+ const uncontrolled = plan.scans.find((scan) => scan.class === "B" && cargoWidthScanProblem(scan, planCargoCommand, o[CARGO_WIDTH]));
4473
+ if (uncontrolled) { o.err(`${tag} BLOCKED: --cargo-jobs cannot control Class B scan ${uncontrolled.id}`); return 1; }
4474
+ }
4475
+ let unionScheduler = null;
4476
+ const unionContext = o[UNIT_LIST_UNION];
4477
+ if (unionContext && snapshotB) {
4478
+ try {
4479
+ const { publisherRequirementsForUnits, planUnitListCompile, publisherUnionScheduler, runPublisherSecretRequirement, proveWorkspaceCwd } = await import("../unit-list-compile.mjs");
4480
+ const { publisherRequirementScan } = await import("../deterministic-scans.mjs");
4481
+ const requirements = await publisherRequirementsForUnits({ selected: unionContext.selected, snapshot: repo, rustUnits: rust.units, npmUnits: npm, platform: o.platform, env: o.env });
4482
+ unionContext.expected = new Map(requirements.map((entry) => [entry.selector, entry.requirements.length]));
4483
+ 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");
4484
+ const external = []; const scoped = []; const owner = new Map(); const verdicts = new Map(); const initialFailures = new Set();
4485
+ const { directReadSpawn } = await import("../snapshot-metadata.mjs");
4486
+ const pathKey = o.platform === "win32" ? (Object.keys(o.env).find((k) => k.toUpperCase() === "PATH") ?? "Path") : "PATH";
4487
+ const direct = directCargoPath({ env: { ...o.env, PATH: o.env[pathKey] }, exists: o.exists, platform: o.platform, gateWrappers: true });
4488
+ 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 });
4489
+ for (const entry of requirements) {
4490
+ const rows = []; verdicts.set(entry.selector, entry.verdict);
4491
+ for (const requirement of entry.requirements) {
4492
+ owner.set(requirement.id, entry.selector);
4493
+ if (requirement.internal === "scanCrateForSecrets") {
4494
+ const evidence = await runPublisherSecretRequirement({ requirement, snapshot: repo, commit: snapshotBCommit.commit, tree: snapshotBCommit.tree, verifySnapshot: o.verifyUnionSnapshot });
4495
+ unionContext.internal.push({ selector: entry.selector, id: requirement.id, coverageKey: requirement.coverageKey, status: evidence.status, evidenceHash: evidence.evidenceHash, ...(evidence.findings.length ? { findings: evidence.findings } : {}) });
4496
+ if (evidence.status !== "pass") { initialFailures.add(entry.selector); o.err(`${tag} ${entry.selector}: publisher secret scan failed (${evidence.findings.join(", ")})`); }
4497
+ } else if (requirement.executable === "cargo" && requirement.argv[0] === "fmt") {
4498
+ if (!await o.verifyUnionSnapshot()) throw new Error("snapshot changed before publisher fmt");
4499
+ const result = directSpawn(planCargoCommand[0], [...planCargoCommand.slice(1), ...requirement.argv], { cwd: path.join(repo, requirement.cwd), env: requirement.env });
4500
+ if (!await o.verifyUnionSnapshot()) throw new Error("snapshot changed after publisher fmt");
4501
+ const status = failed(result) ? "fail" : "pass";
4502
+ const evidence = { id: requirement.id, coverageKey: requirement.coverageKey, commit: snapshotBCommit.commit, tree: snapshotBCommit.tree, status };
4503
+ unionContext.internal.push({ selector: entry.selector, ...evidence, evidenceHash: createHash("sha256").update(JSON.stringify(evidence)).digest("hex") });
4504
+ if (status !== "pass") { initialFailures.add(entry.selector); o.err(`${tag} ${entry.selector}: publisher fmt failed: ${why(result)}`); }
4505
+ } else { external.push(requirement); rows.push(requirement); }
4506
+ }
4507
+ if (!rows.length) throw new Error(`${entry.selector}: no executable publisher compile requirements`);
4508
+ scoped.push({ selector: entry.selector, requirements: rows });
4509
+ }
4510
+ const normalizedCwds = new Map(); const cwdProofs = [];
4511
+ const toolchains = new Map();
4512
+ const toolchainOf = (dir) => {
4513
+ if (!toolchains.has(dir)) {
4514
+ const result = o.spawn("rustup", ["show", "active-toolchain"], { cwd: dir, env: { ...o.env, [pathKey]: direct.path } });
4515
+ 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] });
4516
+ }
4517
+ return toolchains.get(dir);
4518
+ };
4519
+ for (const requirement of external) if (requirement.executable === "cargo" && requirement.phase === "compile" && ["check", "clippy"].includes(requirement.argv[0])) {
4520
+ const proof = proveWorkspaceCwd({ requirement, snapshot: repo, checkout: root, toolchainOf, exists: o.exists });
4521
+ if (proof.normalized) normalizedCwds.set(requirement.id, proof.cwd);
4522
+ cwdProofs.push({ id: requirement.id, cwd: proof.cwd, normalized: proof.normalized, reason: proof.reason });
4523
+ }
4524
+ unionContext.cwdProofs = cwdProofs;
4525
+ const jobs = planUnitListCompile(scoped, { normalizedCwds });
4526
+ const config = JSON.parse(o.readFile(path.join(repo, "ci/gate.config.json")));
4527
+ const adapt = (requirement) => {
4528
+ const sel = owner.get(requirement.id) ?? jobs.find((job) => job.members.some((member) => member.coverageKey === requirement.coverageKey))?.members[0]?.selector;
4529
+ const unit = sel?.replace(/^cargo:/, "");
4530
+ const quiet = sel?.startsWith("cargo:") ? config.rust?.[unit]?.quietTests === true : false;
4531
+ return publisherRequirementScan(requirement, { platform: o.platform, cargoCommand: planCargoCommand, cargoLiveRoot, targetDirs, quiet, allowIgnored: verdicts.get(sel)?.allowIgnored === true, cargoJobs: o[CARGO_WIDTH] ?? null });
4532
+ };
4533
+ for (const requirement of external) plan.scans.push(adapt(requirement));
4534
+ const dependencies = Object.fromEntries(unionContext.selected.map((unit) => [unit.selector, (unit.deps ?? []).filter((dep) => unionContext.selected.some((u) => u.selector === dep))]));
4535
+ unionScheduler = publisherUnionScheduler({ jobs, dependencies, initialFailures, requirements: external, adapt, signal: ac.signal, onCoverage: (coverage) => { unionContext.coverage = coverage; }, verify: async ({ row, member, attempts, requirement }) => {
4536
+ const verdict = verdicts.get(member.selector);
4537
+ 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 };
4538
+ unionContext.commands.push({ selector: member.selector, id: member.id, ...proof });
4539
+ 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 };
4540
+ if (executor.kind === "broker" && requirement.executable === "cargo" && !/^[0-9a-f]{64}$/.test(row.snapshotEvidence?.receiptSha256 ?? "")) return { ok: false };
4541
+ return { ok: true, evidenceHash: createHash("sha256").update(JSON.stringify(proof)).digest("hex") };
4542
+ } });
4543
+ unionContext.owner = owner;
4544
+ } catch (error) { o.err(`${tag} BLOCKED: cannot prepare canonical unit-list compile: ${error.message}`); return 1; }
4545
+ }
4080
4546
  // 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
4081
4547
  // receipt and refuses to qualify without a declared run route (rightkit#1332, #1333). Never dropped silently.
4082
4548
  o.onQualifyOwed?.((plan.qualifyOwed ?? []).filter((x) => x.kind !== "e2e-crate" || plan.scans.some((s) => s.id === x.id)));
4083
- const jobs = Math.max(1, Number(o.env.RK_GATE_JOBS ?? 4) || 4);
4549
+ // 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).
4550
+ const defaultJobs = typeof os.availableParallelism === "function" ? os.availableParallelism() : os.cpus().length;
4551
+ const jobs = Math.max(1, Number(o.env.RK_GATE_JOBS ?? defaultJobs) || defaultJobs);
4084
4552
  const testJobs = Math.max(1, Number(o.env.RK_GATE_TEST_JOBS ?? jobs) || jobs);
4085
4553
  // 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.
4086
4554
  const brokerHost = executor.kind === "broker";
@@ -4120,8 +4588,18 @@ export async function main(argv, io = {}) {
4120
4588
  }
4121
4589
  // The result cache keys on the gated commit's object ids; the stdin check above made HEAD the pushed commit.
4122
4590
  let cache = null;
4591
+ const nodeCheckRejects = new Map();
4592
+ let nodeCheckDiagnosticId = null; let nodeCheckDiagnosticState = "not-seen";
4593
+ const countNodeCheckRejection = (reason, scanId) => {
4594
+ 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;
4595
+ nodeCheckRejects.set(reason, (nodeCheckRejects.get(reason) ?? 0) + 1);
4596
+ if (scanId === nodeCheckDiagnosticId) nodeCheckDiagnosticState = `rejected:${reason}`;
4597
+ };
4123
4598
  // rightkit#1463: the input key each scan was looked up under, for the coverage report (gate-coverage.mjs).
4124
4599
  const scanKeys = new Map();
4600
+ // Why a scan got no cache key (a key builder that threw, or a cache that could not open): reported, never hidden (GC-A24).
4601
+ const keyErrors = new Map(); let cacheDisabled = null;
4602
+ const keyError = (scan, error) => keyErrors.set(scan.id, String(error?.message ?? error).slice(0, 300));
4125
4603
  // Full class A on the working tree (the door, and broker admission of the live checkout) caches on the LIVE bytes: every
4126
4604
  // tracked and untracked (not ignored) file is hashed raw, so the door's run and a repeat admission of the same bytes hit the
4127
4605
  // cache, and any edit misses it.
@@ -4217,15 +4695,23 @@ export async function main(argv, io = {}) {
4217
4695
  // 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
4218
4696
  // reused: each call walks every installed dependency file, and the run made three of these walks before its first scan.
4219
4697
  const environment = envAtStart ?? classAEnvironmentDigest({ root: liveBase, gatePackage: o.gatePackage, files, spawn: o.spawn, includeCaches: false });
4220
- const digest = buildCacheDigest({ objectId, headTree: digestOf(files), rustUnits: rust.units, npmUnits: npm, cargoDir: ".", rustLocks, crateFeatures, listFiles, readBlob });
4698
+ const digest = buildCacheDigest({ objectId, headTree: digestOf(files), rustUnits: rust.units, npmUnits: npm, cargoDir: ".", rustLocks, crateFeatures, listFiles, readBlob, onKeyError: keyError });
4221
4699
  // 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
4222
4700
  // missed every row whenever one file joined or left the plan. build-helpers is never reused: it reads the host's trace list,
4223
4701
  // which is outside every key (and takes seconds).
4224
4702
  // 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
4225
4703
  // (the sibling packages its check project maps; scopeScans narrows it per scope) changes the verdict on the same tree.
4226
4704
  const rowShape = (scan) => (scan.tscWorkspace ? `:tscws=${createHash("sha256").update(canonicalJson([...scan.tscWorkspace].sort())).digest("hex")}` : "");
4227
- 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; } };
4228
- } catch { cache = null; }
4705
+ nodeCheckDiagnosticId = plan.scans.filter((scan) => scan.class === "A" && scan.id.startsWith("node-check:")).map((scan) => scan.id).sort()[0];
4706
+ const nodeCheckModule = null; // GC-A24: node-check rows use the generic file key (file, ancestor package.json, node identity)
4707
+ 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;
4708
+ cache = { ...store, narrowNodeCheck: false, digest: (scan, context) => {
4709
+ if (/^build-helpers(:|$)/.test(scan.id)) return null;
4710
+ // This narrow key applies only to the helper's proven plain snapshot node --check.
4711
+ // Uncertain rows miss rather than falling back to a less specific key.
4712
+ 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;
4713
+ } };
4714
+ } catch (error) { cache = null; cacheDisabled = `class A result cache disabled: ${error?.message ?? error}`; o.err(`${tag} note: ${cacheDisabled}`); }
4229
4715
  }
4230
4716
  if (!classAOnly) {
4231
4717
  try {
@@ -4250,12 +4736,15 @@ export async function main(argv, io = {}) {
4250
4736
  if (failed(r)) throw new Error(`git show failed: ${why(r)}`);
4251
4737
  return text(r);
4252
4738
  };
4253
- // The gate's identity is part of every class B key: a changed check or key logic never reuses an older verdict.
4254
- const rowDigest = buildCacheDigest({ objectId, headTree: treeId, rustUnits: rust.units, npmUnits: npm, cargoDir: ".", rustLocks, crateFeatures, listFiles, readBlob });
4255
- const gateIdentity = gateCodeIdentity();
4256
- cache = { ...store, digest: (scan) => { const key = rowDigest(scan); const full = key === null ? null : `${key}:${gateIdentity}`; scanKeys.set(scan.id, full); return full; } };
4739
+ // The class B key identity (key schema and carrier code, classBKeyIdentity) is part of every class B key.
4740
+ const rowDigest = buildCacheDigest({ objectId, headTree: treeId, rustUnits: rust.units, npmUnits: npm, cargoDir: ".", rustLocks, crateFeatures, listFiles, readBlob, onKeyError: keyError });
4741
+ const gateIdentity = classBKeyIdentity();
4742
+ 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; } };
4743
+ } else {
4744
+ cacheDisabled = `class B result cache disabled: ${!headSha ? "no commit" : !treeId ? "no tree id" : `git common dir unreadable (${why(common)})`}`;
4745
+ o.err(`${tag} note: ${cacheDisabled}`);
4257
4746
  }
4258
- } catch { cache = null; }
4747
+ } catch (error) { cache = null; cacheDisabled = `class B result cache disabled: ${error?.message ?? error}`; o.err(`${tag} note: ${cacheDisabled}`); }
4259
4748
  }
4260
4749
  // The scan-tool policy (RA-18 / L9-03): the analyzers class A accepts (shellcheck, actionlint, cargo-deny, cargo-audit) run only from an enrolled
4261
4750
  // executable. It comes from this host's enrolment record under the managed data root, else (RightKit's own checkout only) from the RUNNING
@@ -4281,7 +4770,7 @@ export async function main(argv, io = {}) {
4281
4770
  const scanResult = await (o.runScans ?? runScans)(plan, {
4282
4771
  // 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.
4283
4772
  ...(snapshot ? { trackedFiles: files } : {}),
4284
- 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 } : {}),
4773
+ 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 } : {}),
4285
4774
  ...(census ? { spawn: census.wrapSpawn(defaultSpawnAsync) } : {}),
4286
4775
  // 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
4287
4776
  // executor's validated client, never a PATH lookup (withDeclaredClient).
@@ -4299,7 +4788,7 @@ export async function main(argv, io = {}) {
4299
4788
  ...(!scanSpawn ? { cargoReadTargetRoot: gateTmpRoot({ env: o.env, platform: o.platform, exists: o.exists }) } : {}),
4300
4789
  // 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
4301
4790
  // wrapper's identity) is in every scan's cache key, so no result cached without the wrapper or with another map is reused.
4302
- ...(cargoShim ? { env: cargoShim.scanEnv, ...(cargoShim.sentinel ? { cargoSentinel: cargoShim.sentinel } : {}), cargoLedger: { dir: cargoShim.ledgerDir } } : {}),
4791
+ ...(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 } } : {}),
4303
4792
  // The broker snapshot compile's seam (item 7 rows 7.20 to 7.24): the commit, snapshot, ownership, enrolled pins and receipt reader.
4304
4793
  ...(snapshotBroker ? { snapshotBroker } : {}),
4305
4794
  // `check` (and the broker's compile admission, which runs it on a captured copy of the tree without node_modules) judges the
@@ -4319,8 +4808,20 @@ export async function main(argv, io = {}) {
4319
4808
  return path.join(base, "rightkit-gate-scan-logs", `${path.basename(root)}-${stamp}-${process.pid}`);
4320
4809
  } catch { return null; }
4321
4810
  })(),
4811
+ ...(unionScheduler ? { scheduleClassB: unionScheduler } : {}),
4322
4812
  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)}` : ""}`),
4323
4813
  });
4814
+ if (nodeCheckRejects.size) o.out(`${tag} node-check cache misses: ${[...nodeCheckRejects].sort(([a], [b]) => a.localeCompare(b)).map(([reason, count]) => `${reason}=${count}`).join(", ")}`);
4815
+ if (snapFullA && o.env.RIGHTKIT_PREPARATION_DIAGNOSTIC_DIR && nodeCheckDiagnosticId) o.out(`${tag} node-check diagnostic row: ${nodeCheckDiagnosticState}`);
4816
+ if (unionContext) {
4817
+ const scanById = new Map(plan.scans.map((scan) => [scan.id, scan]));
4818
+ unionContext.rows = scanResult.scans.filter((row) => row.class === "B").map((row) => {
4819
+ const scan = scanById.get(row.id);
4820
+ const command = scan?.tool ? [scan.tool, ...(scan.args ?? [])].join(" ") : null;
4821
+ 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 }) };
4822
+ });
4823
+ }
4824
+ if (unionContext) unionContext.sharedClean = unionContext.rows.filter((row) => row.sharedOrigin).every((row) => row.status === "pass");
4324
4825
  directTiming.cargoEnd = Date.now();
4325
4826
  const freshness = census ? census.finish() : null;
4326
4827
  directTiming.diagnostics = Date.now() - directTiming.cargoEnd;
@@ -4337,7 +4838,7 @@ export async function main(argv, io = {}) {
4337
4838
  for (const note of scanResult.notes) o.out(`${tag} ${note}`);
4338
4839
  // 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.
4339
4840
  try {
4340
- 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() });
4841
+ 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() });
4341
4842
  const base = gateRunsRoot({ env: o.env, platform: o.platform });
4342
4843
  const file = (o.writeCoverage ?? writeCoverageReport)({ dir: path.join(base, "rightkit-gate-coverage"), name: `${path.basename(root)}-${new Date().toISOString().replace(/[:.]/g, "-")}-${process.pid}`, report });
4343
4844
  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)}`);
@@ -4443,6 +4944,7 @@ export async function main(argv, io = {}) {
4443
4944
  o.out(`${tag} direct receipt ${JSON.stringify(directReceipt)}`);
4444
4945
  }
4445
4946
  }
4947
+ if (unionContext) unionContext.completed = true;
4446
4948
  if (failures.length) {
4447
4949
  o.err(`${tag} BLOCKED (${failures.length})`);
4448
4950
  for (const f of failures) o.err(` - ${f}`);
@@ -4478,6 +4980,10 @@ export async function main(argv, io = {}) {
4478
4980
  const tracked = new Set(snapFullA || hostedFullA ? live.files : text(trackedList).split("\0").filter(Boolean).map(posix));
4479
4981
  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}` : ""}`);
4480
4982
  }
4983
+ if (snapshotA && snapshotCommitId && o.env.RIGHTKIT_PREPARATION_DIAGNOSTIC_DIR) {
4984
+ 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 }); }
4985
+ catch { /* Optional diagnostics never change the gate verdict. */ }
4986
+ }
4481
4987
  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}`);
4482
4988
  return 0;
4483
4989
  }