@rightkit/release 0.6.52 → 0.6.54

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/README.md +1 -1
  2. package/adapter-env.mjs +16 -105
  3. package/admission-host.mjs +14 -1
  4. package/bin/darwin/rightkit-swap +0 -0
  5. package/bin/rightkit-gate.mjs +585 -404
  6. package/broker-admission.mjs +122 -2
  7. package/build-launch.mjs +52 -58
  8. package/build-release.mjs +2 -2
  9. package/cargo-ledger.mjs +24 -5
  10. package/cargo-target-shim.mjs +54 -23
  11. package/cargo-target.mjs +2 -2
  12. package/carried-adapter-run.mjs +7 -8
  13. package/carried-cargo-run.mjs +1 -1
  14. package/ci-compile-admission.mjs +1 -1
  15. package/clippy-route.mjs +65 -18
  16. package/compile-inputs.mjs +91 -15
  17. package/cross-targets.mjs +5 -3
  18. package/deps-cargo-lock.mjs +1 -1
  19. package/deterministic-scans.mjs +789 -259
  20. package/development.mjs +33 -7
  21. package/direct-receipt.mjs +3 -5
  22. package/feature-coverage.mjs +45 -9
  23. package/feature-partition.mjs +204 -0
  24. package/feature-sets.mjs +113 -0
  25. package/gate-acceptance.mjs +187 -115
  26. package/gate-seam.mjs +352 -0
  27. package/gate-serve.mjs +34 -2
  28. package/gate-stages.mjs +6 -2
  29. package/ghsa-audit.mjs +19 -4
  30. package/heavy-command.mjs +5 -4
  31. package/install-tauri-authenticode.mjs +73 -4
  32. package/ios-dev.mjs +3 -3
  33. package/ios-package-recipe.mjs +6 -6
  34. package/linux-setup.mjs +3 -2
  35. package/local-publish.mjs +113 -17
  36. package/lock-identity.mjs +24 -100
  37. package/managed-cargo.mjs +3 -3
  38. package/managed-root-guard.mjs +2 -2
  39. package/managed-roots.mjs +3 -3
  40. package/native-adapters.mjs +41 -244
  41. package/native-helpers.mjs +1 -1
  42. package/pack-digest.mjs +1 -1
  43. package/package-recipe-targets.mjs +3 -3
  44. package/package.json +2 -2
  45. package/publication-gate.mjs +29 -6
  46. package/publish-cargo.mjs +4 -5
  47. package/publish-local-cargo.mjs +77 -1
  48. package/qualification-verify.mjs +76 -49
  49. package/receipt-signature.mjs +104 -0
  50. package/release-switch-registry.json +4 -0
  51. package/release-switch-scan.mjs +13 -10
  52. package/rightkit-versions.json +126 -113
  53. package/scan-digest.mjs +43 -14
  54. package/seam-broker.mjs +168 -0
  55. package/snapshot-check.mjs +4 -1
  56. package/snapshot-dependency-reuse.mjs +1 -1
  57. package/snapshot-metadata.mjs +24 -35
  58. package/snapshot.mjs +328 -49
  59. package/stage-commands.mjs +59 -5
  60. package/stage-ledger.mjs +2 -2
  61. package/{carried-cargo.mjs → stage-seam.mjs} +118 -70
  62. package/stage-sidecar.mjs +3 -3
  63. package/tauri-bundle-marker.mjs +5 -2
  64. package/tauri-locked.mjs +1 -1
  65. package/tool-build.mjs +8 -6
  66. package/unit-gate.mjs +40 -10
  67. package/broker-handshake.mjs +0 -160
  68. package/broker-wire.mjs +0 -278
  69. package/build-ownership.mjs +0 -1578
  70. package/cargo-shapes.mjs +0 -332
  71. package/cargo-width.mjs +0 -49
  72. package/carrier-census.mjs +0 -124
  73. package/clippy-equivalence.mjs +0 -202
  74. package/freshness-census.mjs +0 -405
  75. package/handle-revocation.mjs +0 -100
  76. package/handle-revocation.rust-vector.json +0 -1
  77. package/handle-revocation.vectors.json +0 -53
  78. package/legion-freeze-consumer.mjs +0 -241
  79. package/linux-qualifier.mjs +0 -83
  80. package/native-tool-planning.mjs +0 -94
  81. package/owner-process-proof.mjs +0 -14
  82. package/ownership-mark.mjs +0 -191
  83. package/ownership-recover.mjs +0 -78
  84. package/pnpm-adapter-grammar.mjs +0 -226
  85. package/provenance-verify.mjs +0 -413
  86. package/snapshot-broker.mjs +0 -808
  87. package/snapshot-request.mjs +0 -722
  88. package/unit-list-compile.mjs +0 -356
@@ -81,7 +81,7 @@ 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
83
  import { installIdentity, installStateBytes } from "../dependency-identity.mjs";
84
- import { BIOME_CONFIG_FILES, CHECKER_IDENTITY, OXLINT_CONFIG_FILES, 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
+ import { BIOME_CONFIG_FILES, CHECKER_IDENTITY, OXLINT_CONFIG_FILES, ESLINT_CONFIG_FILES, LOCAL_CLASS_B_JOBS, WORKSPACE_RUST_FILE, ancestorConfigChanged, ancestorDirsOf, canonicalJson, defaultSpawn, defaultSpawnAsync, judgeUnitList, blockedUnitsOf, digestScanSet, fileScanCache, findRustfmt, metadataArgs, planScans, planUnitListScans, publisherRequirementScan, runScans, sidecarBoundCrate, scanToolPolicyFromPipeline, scanDeferrals, scanFailures, seamRunState } from "../deterministic-scans.mjs";
85
85
  import { changedLockNames, parseLock, reach } from "../lock-graph.mjs";
86
86
  import { resolveExecutor } from "../gate-executor.mjs";
87
87
  // The gate's own executor: an outer gate's cargo wrapper on PATH is never this gate's cargo (gate-executor.mjs `gateWrappers`).
@@ -92,7 +92,7 @@ import { gitListRustFiles } from "../signing-files.mjs";
92
92
  import { nativeHelpersFromConfig } from "../native-helpers.mjs";
93
93
  import { buildCoverageReport, seconds, writeCoverageReport } from "../gate-coverage.mjs";
94
94
  import { renderViews, renderViewsOf } from "../render-views.mjs";
95
- import { LINUX_BROKER_ROUTE, NO_BROKER_ENV, directCargoPath, directPlatform, linuxBrokerDeclared, managedRuntimeClient, realCargoOf, runCargoSync } from "../managed-cargo.mjs";
95
+ import { LINUX_BROKER_ROUTE, NO_BROKER_ENV, directCargoPath, directPlatform, managedRuntimeClient, realCargoOf, runCargoSync } from "../managed-cargo.mjs";
96
96
  import { createBrokerLive } from "../broker-admission.mjs";
97
97
  import { bindingOf, compileOutputsRecord, compileReuseProblem, endRun, readReceipt, RECEIPT_SCHEMA, receiptKey, sameBinding, sameSource, sealedFor, stagesTo, startRun, STAGES, STAGE_SOURCES, writeReceipt } from "../gate-stages.mjs";
98
98
  import { spawnSync as spawnInherit } from "../background-process.mjs";
@@ -105,19 +105,20 @@ const inheritLaunch = (cmd, a, opts) => (stampChildLines
105
105
  : spawnInherit(cmd, a, { ...opts, stdio: "inherit" }));
106
106
  import { readDiskPolicy, scratchRoots } from "../disk-policy.mjs";
107
107
  import { buildDirectReceipt, directVerdict, resolveTargetDirectory, verifyDirectReceipt, writeDirectDiagnostics } from "../direct-receipt.mjs";
108
- import { createFreshnessCensus } from "../freshness-census.mjs";
109
108
  import { platformDirOf } from "../platform-dir.mjs";
110
109
  import { buildInventory, classifyUnitResults, dependencyFirstOrder, selectAffectedAcrossInventories, unitListReport } from "../affected-units.mjs";
111
110
  import { createRequire } from "node:module";
112
- import { nativeToolRefusal, nativeToolUses } from "../native-tool-planning.mjs";
113
- import { BUILD_CONTROL_PROTOCOL, HANDSHAKE_PROBE_ID, RUNTIME_MANIFEST_FILE, mergeCapabilityViews, parseRuntimeIdentity, queryBrokerHandshake } from "../broker-handshake.mjs";
111
+ import { BUILD_CONTROL_PROTOCOL, HANDSHAKE_PROBE_ID, RUNTIME_MANIFEST_FILE, parseRuntimeIdentity } from "../seam-broker.mjs";
112
+ import { snapshotReclaimJudge } from "../seam-broker.mjs";
114
113
  import net from "node:net";
115
114
  import { installSpawnLedger } from "../spawn-ledger.mjs";
116
- import { cargoWidthRouteProblem, cargoWidthScanProblem, cargoWidthUnitsProblem, parseCargoWidth, validateCargoWidthPool } from "../cargo-width.mjs";
115
+ import { processIdentity, snapshotLockBody, verdictFileName } from "../gate-seam.mjs";
117
116
 
118
117
  const PRIVATE_SCOPED_COMPILE = Symbol("private scoped compile");
119
118
  const UNIT_LIST_UNION = Symbol("unit list union");
120
- const CARGO_WIDTH = Symbol("Cargo width");
119
+ // Class B row input digests per tree (see rowDigest in the compile stage); counted so the run summary shows the time keying took.
120
+ const ROW_DIGEST_MEMO = new Map();
121
+ const ROW_DIGEST_STATS = { hits: 0, misses: 0, ms: 0 };
121
122
  const ZERO = /^0+$/;
122
123
  const SAFE_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
123
124
  const posix = (p) => String(p).replaceAll("\\", "/");
@@ -136,7 +137,10 @@ export const MOBILE_PLATFORMS = Object.freeze(new Set(["ios", "android"]));
136
137
  // and the code of the runtime cargo wrapper and broker carrier, which decides what a carried compile ran and how its receipt is verified.
137
138
  // 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
138
139
  // an edit elsewhere in the gate must not discard every compile result (rightkit#1506: Pulse, RK, RustRight and Legion kept 0 class B hits).
139
- const CLASS_B_KEY_SCHEMA = "rightkit.class-b-key/2";
140
+ // /3 (0.6.54, rightkit#1538): every class B pass stored under /2 is left behind. Until 0.6.53 a grouped invocation stored a pass under each member's
141
+ // own key (a projected pass that never proved the member's own command) and a test group's pass was stored without its members' own runs; a
142
+ // /2 entry cannot be told from one that ran alone by its key, so none is read. The warm target directory is untouched: a rerun is a warm compile.
143
+ const CLASS_B_KEY_SCHEMA = "rightkit.class-b-key/3";
140
144
  // GC-A24: passing rule-engine verdicts (app rules, RightKit's preflight) of a snapshot, under the checkout's git common directory.
141
145
  const RULE_VERDICT_SCHEMA = "rightkit.rule-verdict/1";
142
146
  function ruleVerdictCache({ checkout, spawn }) {
@@ -168,31 +172,26 @@ function gatePackageIdentity(gatePackage = path.resolve(path.dirname(fileURLToPa
168
172
  const CLASS_A_KEY_SCHEMA = "rightkit.class-a-key/3";
169
173
  /** Whether a class A row's verdict depends on the installed dependencies (GC-A24): it executes repository code, or its tool is pnpm. */
170
174
  function classAEnvironmentBound(scan) { return scan.executes === true || scan.tool === "pnpm"; }
171
- let classBKeyIdentityMemo = null;
172
- /** Adrian's approval of one cache-miss report for ONE run: RK_GATE_MISS_APPROVAL names a JSON file {digest, by: "adrian", reason}. Attested, not
173
- * authenticated (an agent could write it) until Adrian picks a trust root; every run prints it. */
174
- function missApproval(o, digest, commit) {
175
- const file = o.env?.RK_GATE_MISS_APPROVAL;
176
- if (!file) return { ok: false, why: "no approval given" };
177
- let e; try { e = JSON.parse(fs.readFileSync(file, "utf8")); } catch (error) { return { ok: false, why: `${file} unreadable (${error.message})` }; }
178
- if (e?.by !== "adrian") return { ok: false, why: `${file} is not by adrian` };
179
- if (e?.digest !== digest) return { ok: false, why: `${file} approves report ${String(e?.digest).slice(0, 12)}, this run's report is ${digest.slice(0, 12)}` };
180
- if (typeof e?.reason !== "string" || !e.reason.trim()) return { ok: false, why: `${file} gives no reason` };
181
- // Single use (Adrian 2026-11-06: "why would it be recorded for 2 hours if it's for a single run?"): the run it permits consumes it.
182
- const used = path.join(gateRunsRoot({ env: o.env, platform: o.platform }), "rightkit-gate-misses", "consumed", `${digest}.json`);
183
- try { fs.mkdirSync(path.dirname(used), { recursive: true }); fs.writeFileSync(used, JSON.stringify({ digest, commit, file, reason: e.reason, at: new Date().toISOString() }), { flag: "wx" }); }
184
- catch (error) { return { ok: false, why: error?.code === "EEXIST" ? `report ${digest.slice(0, 12)} was already approved for one run and that run has used it` : `the approval could not be recorded as used (${error.message})` }; }
185
- return { ok: true, note: `cache-miss approval ${file} (attested, not authenticated): by adrian for this one run of report ${digest.slice(0, 12)} on ${String(commit).slice(0, 12)}: ${e.reason}` };
186
- }
187
-
188
- function classBKeyIdentity() {
189
- if (classBKeyIdentityMemo === null) {
175
+ /**
176
+ * The code that decides what a class B pass means, in the key: on a seam run (a broker host compiling a snapshot) the seam's judge, its control helpers, the runtime cargo
177
+ * wrapper and the ledger a suite's seam calls are filed in; on a direct host the wrapper, the snapshot metadata reads and the ledger. Each route keys only its own judging code
178
+ * (fresh review of badf93c, D7). Any edit to a listed module is a deliberate cold start of that route (step 5 of the reset plan edited cargo-target-shim.mjs: one cold start of
179
+ * both routes' result caches; the warm target directory is untouched).
180
+ */
181
+ const CLASS_B_JUDGE_FILES = Object.freeze({
182
+ seam: ["gate-seam.mjs", "seam-broker.mjs", "cargo-target-shim.mjs", "cargo-ledger.mjs"],
183
+ direct: ["cargo-target-shim.mjs", "snapshot-metadata.mjs", "cargo-ledger.mjs", "gate-seam.mjs"],
184
+ });
185
+ const classBKeyIdentityMemo2 = new Map();
186
+ function classBKeyIdentity(route = "direct") {
187
+ if (!classBKeyIdentityMemo2.has(route)) {
190
188
  const h = createHash("sha256");
191
189
  h.update(CLASS_B_KEY_SCHEMA);
192
- 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))); }
193
- classBKeyIdentityMemo = h.digest("hex").slice(0, 24);
190
+ h.update(`\0route:${route}\0`);
191
+ for (const f of CLASS_B_JUDGE_FILES[route]) { h.update(`\0${f}\0`); h.update(fs.readFileSync(new URL(`../${f}`, import.meta.url))); }
192
+ classBKeyIdentityMemo2.set(route, h.digest("hex").slice(0, 24));
194
193
  }
195
- return classBKeyIdentityMemo;
194
+ return classBKeyIdentityMemo2.get(route);
196
195
  }
197
196
  let gateCodeIdentityMemo = null;
198
197
  function gateCodeIdentity() {
@@ -201,8 +200,8 @@ function gateCodeIdentity() {
201
200
  h.update(CHECKER_IDENTITY ?? `unidentified-${process.pid}-${Date.now()}`);
202
201
  h.update("\0");
203
202
  h.update(fs.readFileSync(fileURLToPath(import.meta.url)));
204
- // The runtime cargo wrapper and the broker carrier it runs: their code decides what a carried compile did.
205
- 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))); }
203
+ // The runtime cargo wrapper and the seam it sends through: their code decides what a broker compile did.
204
+ for (const f of ["cargo-target-shim.mjs", "seam-broker.mjs", "gate-seam.mjs", "snapshot-metadata.mjs", "cargo-ledger.mjs", "gate-stages.mjs"]) { h.update(`\0${f}\0`); h.update(fs.readFileSync(new URL(`../${f}`, import.meta.url))); }
206
205
  gateCodeIdentityMemo = h.digest("hex").slice(0, 24);
207
206
  }
208
207
  return gateCodeIdentityMemo;
@@ -1189,7 +1188,10 @@ export function buildCacheDigest({ objectId, headTree, rustUnits = [], npmUnits
1189
1188
  try {
1190
1189
  if (ADVISORY_SCAN.test(scan.id)) return advisoryKey(scan);
1191
1190
  const files = fileList(scan);
1192
- if (files) return canonicalJson({ kind: "files", id: scan.id, files: [...new Set(files)].sort().map((p) => [p, idOf(p)]) });
1191
+ // node --check reads a package.json above the file only for its "type" (module or commonjs): a version bump there is not an input (NN20; every
1192
+ // release reran 423 node-check rows). Any other read of the manifest, or an unreadable one, keys on its whole content as before.
1193
+ const nodeType = (p) => { if (!/^node-check:/.test(scan.id) || !/(^|\/)package\.json$/.test(p) || typeof readBlob !== "function") return null; try { const v = JSON.parse(String(readBlob(p))); return `type:${v?.type ?? "commonjs"}`; } catch { return null; } };
1194
+ if (files) return canonicalJson({ kind: "files", id: scan.id, files: [...new Set(files)].sort().map((p) => [p, nodeType(p) ?? idOf(p)]) });
1193
1195
  if (/^cargo-package-list:/.test(scan.id)) {
1194
1196
  const unit = scan.id.slice("cargo-package-list:".length);
1195
1197
  const head = byName.get(unit);
@@ -1450,18 +1452,30 @@ async function installHook(o, root) {
1450
1452
  * apps/coderight-tauri), else the repository root. Every right-release stage runs there, the sealed set is read from there, and the
1451
1453
  * receipt is keyed to it (receiptKey). Returns { appRoot, appDir } with appDir relative to the repository root, "." at the root.
1452
1454
  */
1453
- export function appRootOf({ root, cwd, exists = fs.existsSync, configDirs = null }) {
1454
- const inside = cwd && (cwd === root || cwd.startsWith(root + path.sep));
1455
+ export function appRootOf({ root, cwd, exists = fs.existsSync, configDirs = null, platform = process.platform }) {
1456
+ // rightkit#1553: on Windows a path names the same directory in any letter case (git reports D:/Claude/heardright, a runner may start in
1457
+ // D:\claude\heardright\tauri-app-next). path.win32.relative compares case-blind and keeps the cwd's spelling of each segment; posix stays exact.
1458
+ // A sibling sharing a prefix (D:\a\bc against root D:\a\b) is outside: relative() answers "..\bc", never a prefix match.
1459
+ const p = platform === "win32" ? path.win32 : path.posix;
1460
+ const fold = platform === "win32" ? (s) => s.toLowerCase() : (s) => s;
1461
+ const rootAbs = p.resolve(root);
1462
+ const rel = cwd ? p.relative(rootAbs, p.resolve(cwd)) : null;
1463
+ const inside = rel !== null && (rel === "" || (rel !== ".." && !rel.startsWith(`..${p.sep}`) && !p.isAbsolute(rel)));
1455
1464
  // With `configDirs` (the directories whose committed tree holds a release config: `committedConfigDirs`) the scope is the SELECTED COMMIT's, read from
1456
- // its tree alone; the checkout's files are never asked, so a newer, dirty or edited checkout cannot move an older commit's app. Without it (callers that
1457
- // hold no commit) the live checkout answers, as before. Either way the directory the gate was run from is the explicit identity.
1458
- const hasConfig = configDirs
1459
- ? (d) => configDirs.has(path.relative(root, d).split(path.sep).join("/") || ".")
1460
- : (d) => ["right-release.config.json", "right-release.config.mjs"].some((f) => exists(path.join(d, f)));
1465
+ // its tree alone, and the answer is that tree's own spelling of the directory; the checkout's files are never asked, so a newer, dirty or edited checkout
1466
+ // cannot move an older commit's app. Without it (callers that hold no commit) the live checkout answers, as before. Either way the directory the gate was
1467
+ // run from is the explicit identity.
1468
+ const committed = configDirs ? new Map([...configDirs].map((d) => [fold(d), d])) : null;
1469
+ const configDirAt = (relPosix) => committed
1470
+ ? (committed.get(fold(relPosix)) ?? null)
1471
+ : (["right-release.config.json", "right-release.config.mjs"].some((f) => exists(p.join(rootAbs, ...relPosix.split("/"), f))) ? relPosix : null);
1461
1472
  // The nearest directory at or above cwd (below the root) that carries a release config is the app; a deeper cwd (apps/foo/src) is apps/foo.
1462
- let appRoot = root;
1463
- if (inside) for (let d = path.resolve(cwd); d.startsWith(root) && d !== root; d = path.dirname(d)) { if (hasConfig(d)) { appRoot = d; break; } }
1464
- return { appRoot, appDir: path.relative(root, appRoot).split(path.sep).join("/") || "." };
1473
+ let appDir = ".";
1474
+ if (inside && rel !== "") {
1475
+ const segments = rel.split(p.sep).filter(Boolean);
1476
+ for (let n = segments.length; n > 0; n--) { const found = configDirAt(segments.slice(0, n).join("/")); if (found) { appDir = found; break; } }
1477
+ }
1478
+ return { appRoot: appDir === "." ? rootAbs : p.join(rootAbs, ...appDir.split("/")), appDir };
1465
1479
  }
1466
1480
 
1467
1481
  /**
@@ -1603,10 +1617,6 @@ export function changedPathsAt({ git, base, commit }) {
1603
1617
  */
1604
1618
  export async function runSharedUnitList({ o, io, stage, commit, selected, inventory, receiptDir = undefined, base = null, unmatched = [], runUnit = null }) {
1605
1619
  const tag = "rightkit-gate:";
1606
- if (io[CARGO_WIDTH] !== undefined) {
1607
- const problem = cargoWidthUnitsProblem(selected);
1608
- if (problem) { o.err(`${tag} BLOCKED: ${problem}`); return 2; }
1609
- }
1610
1620
  const bySelector = new Map((inventory?.units ?? []).map((u) => [u.selector, u]));
1611
1621
  const rows = selected.map((s) => ({ dir: unitDirOfSelector(s.selector), reason: "listed", ...bySelector.get(s.selector), ...s }));
1612
1622
  const order = inventory ? dependencyFirstOrder(inventory, new Set(rows.map((r) => r.selector))) : rows.map((r) => r.selector);
@@ -1618,6 +1628,28 @@ export async function runSharedUnitList({ o, io, stage, commit, selected, invent
1618
1628
  if (stage === "compile" && !runUnit && !io.runUnitForList && ordered.length) {
1619
1629
  const union = { selected: ordered, inventory, rows: null, coverage: null, internal: [], commands: [], commit, runId: randomUUID() };
1620
1630
  const exit = await main(["--to", "compile", "--unit", ordered[0].selector, "--commit", commit], { ...io, unitListClassA, [UNIT_LIST_UNION]: union });
1631
+ if (union.fresh) {
1632
+ // Each crate has its own result (gate/compile.mjs): passed, failed, or not built because something it depends on failed. A unit's status is its crate's.
1633
+ const { unitResult } = await import("../gate/compile.mjs");
1634
+ const statusOf = (unit) => { const r = union.fresh.byCrate[unit.selector.slice("cargo:".length)]?.result; return r === "passed" && union.verified ? "passed" : r === "not-built" ? "blocked" : "failed"; };
1635
+ const results = ordered.map((unit) => { const status = statusOf(unit); return { selector: unit.selector, status, ...(status === "failed" ? { code: 1 } : {}) }; });
1636
+ const report = unitListReport({ commit, stage, base, selected: ordered, results, unmatched }); report.runId = union.runId; report.counts2 = union.fresh.counts;
1637
+ for (const row of report.units) {
1638
+ if (receiptDir === undefined) row.receipt = { status: "not-requested" };
1639
+ else {
1640
+ const crate = row.selector.slice("cargo:".length);
1641
+ const name = `gate-${crate}.json`;
1642
+ const data = `${JSON.stringify(unitResult({ selector: row.selector, commit, tree: union.fresh.tree, platform: union.fresh.platform, crate, run: union.fresh }), null, 2)}
1643
+ `; o.writeFile(path.join(receiptDir, name), data);
1644
+ row.receipt = { status: "written", file: name, sha256: createHash("sha256").update(data).digest("hex") };
1645
+ }
1646
+ o.out(`${tag} unit ${row.selector}: ${row.status}`);
1647
+ }
1648
+ 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)}`);
1649
+ if (receiptDir !== undefined) o.writeFile(path.join(receiptDir, "units-report.json"), `${JSON.stringify(report, null, 2)}
1650
+ `);
1651
+ return report.ok ? 0 : (exit || 1);
1652
+ }
1621
1653
  const results = ordered.map((unit) => {
1622
1654
  const evidence = union.coverage?.filter((r) => r.selector === unit.selector) ?? [];
1623
1655
  const internal = union.internal.filter((r) => r.selector === unit.selector);
@@ -1625,12 +1657,14 @@ export async function runSharedUnitList({ o, io, stage, commit, selected, invent
1625
1657
  const all = [...internal, ...evidence];
1626
1658
  const failed = !expected || all.length !== expected || all.some((r) => r.status === "failed" || r.status === "fail");
1627
1659
  const blocked = !failed && all.some((r) => r.status === "blocked" || r.status === "not-run");
1628
- const status = failed ? "failed" : blocked ? "blocked" : union.verified && all.every((r) => r.status === "passed" || r.status === "pass") ? "passed" : "failed";
1660
+ // A unit passes only on a run that exited 0: a scheduler or stage exception never leaves earlier evidence standing as a pass (cloud 2026-11-06:
1661
+ // a lookup's coverage was reported as 132 passed after "scheduleClassB: invalid projection").
1662
+ const status = failed ? "failed" : blocked ? "blocked" : exit === 0 && union.verified && all.every((r) => r.status === "passed" || r.status === "pass") ? "passed" : "failed";
1629
1663
  return { selector: unit.selector, status, ...(status === "failed" ? { code: exit || 1 } : {}) };
1630
1664
  });
1631
1665
  const report = unitListReport({ commit, stage, base, selected: ordered, results, unmatched }); report.runId = union.runId;
1632
1666
  for (const row of report.units) {
1633
- 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) };
1667
+ 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), publisher: { scanSetDigest: union.publisher?.scanSetDigest ?? null, scanIds: union.publisher?.scanIds ?? [] } };
1634
1668
  if (receiptDir === undefined) row.receipt = { status: "not-requested" };
1635
1669
  else {
1636
1670
  const name = `gate-${row.selector.replace(/^npm:@rightkit\//, "npm-").replace(/^cargo:/, "")}.json`;
@@ -1786,7 +1820,7 @@ async function runStages(o, args, root, git, io) {
1786
1820
  const option = (name) => { const i = args.indexOf(name); return i < 0 ? undefined : args[i + 1]; };
1787
1821
  const tag = "rightkit-gate:";
1788
1822
  const to = option("--to");
1789
- // dev and test are door stages like the rest: the same commit-only route (select a commit, sync its snapshot under ownership, class A
1823
+ // dev and test are door stages like the rest: the same commit-only route (select a commit, sync its snapshot under the snapshot lock, class A
1790
1824
  // of the snapshot), then right-release dev|test with the snapshot's app root as its cwd. They have no stage list of their own.
1791
1825
  // render (rightkit#1288) is a door stage of the same family: class A of the snapshot, then the app's declared view-render target built through the carrier and run headless.
1792
1826
  const devTest = to === "dev" || to === "test" || to === "render";
@@ -1825,18 +1859,18 @@ async function runStages(o, args, root, git, io) {
1825
1859
  // `--route`: which route this stage takes here and whether it refuses, answered without running anything (rightkit#1297).
1826
1860
  if (o.routeProbe) return await runRouteProbe(o, args, root, git, { to, platform, stages: devTest ? [] : stages, devTest, appDir });
1827
1861
  // Commit-only build (GATE-CONTRACT §1): on every host (not hosted CI, whose runner checkout is the commit) the door selects a commit
1828
- // (--commit <rev>, default HEAD), takes the repository's build ownership, syncs the commit's gate-owned snapshot once, and every stage
1862
+ // (--commit <rev>, default HEAD), takes the repository's snapshot lock, syncs the commit's gate-owned snapshot once, and every stage
1829
1863
  // below reads that snapshot; the checkout may hold anything and is never a build source. Every non-hosted host takes this route: Mac
1830
1864
  // and Dell compile it through the RustRight snapshot carrier (`deps.snapshotBroker`, wired by `productionEntryDeps`; item 7 rows 7.20
1831
1865
  // to 7.24, rightkit#1301), right-release's own children included. Once it is selected any failure refuses; there is no retry on the
1832
1866
  // checkout, and no flag or environment variable selects another route.
1833
- // The route and every refusal the door can meet before it takes ownership are `routePlan`'s, the one function the `--route` probe
1867
+ // The route and every refusal the door can meet before it takes the lock are `routePlan`'s, the one function the `--route` probe
1834
1868
  // also answers from (rightkit#1297 L1): the probe and the real run cannot drift, and the door-route parity test compares the two.
1835
1869
  if (!o.doorSnapshot) {
1836
1870
  const whichRoute = (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); };
1837
1871
  const routeExecutor = (o.resolveExecutor ?? gateResolveExecutor)({ env: o.env, platform: o.platform, exists: o.exists, which: whichRoute, readFile: o.readFile });
1838
1872
  let decided;
1839
- try { decided = routePlan(o, { to, stages: devTest ? [] : stages, devTest, executor: routeExecutor, stagePlatform: platform, capabilities: await brokerCapabilityStateWithHandshake(o, { to, executor: routeExecutor }), appConfig: selected && to !== "check" ? routeAppConfig({ git, commit: selected.commit, appDir, platform: devTestPlatform(args) }) : null }); }
1873
+ try { decided = routePlan(o, { to, stages: devTest ? [] : stages, devTest, executor: routeExecutor, stagePlatform: platform, appConfig: selected && to !== "check" ? routeAppConfig({ git, commit: selected.commit, appDir, platform: devTestPlatform(args) }) : null }); }
1840
1874
  catch (e) { o.err(`${tag} ${e.message}`); return 2; }
1841
1875
  if (decided.refusal) { o.err(`${tag} BLOCKED: ${decided.refusal.code}: ${decided.refusal.message}; nothing ran${decided.route === "snapshot" ? " and the checkout is never built" : ""}`); return 1; }
1842
1876
  const notPublisher = decided.route === "snapshot" ? releaseRouteRefusal(o, { stages, platform }) : null;
@@ -1850,23 +1884,28 @@ async function runStages(o, args, root, git, io) {
1850
1884
  }
1851
1885
  if (!o.doorSnapshot && !hosted) {
1852
1886
  const snap = await import("../snapshot.mjs");
1853
- const { acquireBuildOwnership, ownershipFile } = await import("../build-ownership.mjs");
1854
1887
  const snapshotsAt = o.snapshotRoot ?? snap.snapshotRoot({ platform: o.platform, env: o.env });
1855
- let own;
1856
- try { own = (o.acquireOwnership ?? acquireBuildOwnership)({ file: ownershipFile({ platform: o.platform, beside: o.snapshotRoot, repository: snap.repositoryOf(root).key }), stage: `door:${to}`, snapshot: path.join(snapshotsAt, snap.repositoryOf(root).key), commit: selected.commit, platform: o.platform, env: o.env }); }
1857
- catch (e) { if (e.code !== "busy" && e.code !== "refused") throw e; o.err(`${tag} BLOCKED: ${e.message}; nothing ran${e.code === "refused" ? ", nothing created" : ""}`); return 1; }
1858
- o.out(`${tag} build ownership ${own.joined ? "joined" : "held"} ${own.handle}${own.reclaimed ? ` (reclaimed from ${own.reclaimed.from}: ${own.reclaimed.proofs.join("; ")})` : ""}`);
1888
+ // The run's one exclusion, the snapshot lock (reset plan section 3): taken before the sync, held through the whole door run, every job and every test, and released in the finally
1889
+ // below only on the gate's own proof that no job of this run can still be live in the broker. The lock body is { pid, identity, commit, token } on a broker host, which the
1890
+ // broker reads at submission and before spawn; a dead holder's lock is reclaimed only on the broker's SNAPSHOT_STATUS IDLE proof (gate-seam.mjs). A host with no broker takes the legacy lock.
1891
+ const taken = takeRunLock({ o, checkout: root, snapshotsAt, commit: selected.commit, snap, tag });
1892
+ if (taken.exit !== undefined) return taken.exit;
1893
+ let started = false;
1859
1894
  try {
1860
1895
  // One sync per door run: a second one would prune what class A installed into the snapshot.
1861
1896
  let synced;
1862
- try { synced = (o.syncSnapshot ?? snap.syncSnapshot)({ checkout: root, rev: selected.commit, root: snapshotsAt }); }
1897
+ try { synced = (o.syncSnapshot ?? snap.syncSnapshot)({ checkout: root, rev: selected.commit, root: snapshotsAt, lock: { held: taken.view } }); }
1863
1898
  catch (e) { o.err(`${tag} ${e.code === "error" ? "RK_CHECK_ERROR" : "BLOCKED"}: snapshot ${e.message}; nothing ran`); return e.code === "error" ? 2 : 1; }
1864
1899
  o.out(`${tag} snapshot ${synced.path} is commit ${synced.commit} tree ${synced.tree} (written=${synced.written} removed=${synced.removed} unchanged=${synced.unchanged})`);
1865
1900
  if (synced.identity) o.out(`${tag} source identity ${synced.identity.file}: ${synced.identity.written ? "written" : synced.identity.kept ? "kept" : `not written (${synced.identity.reason})`}`);
1866
- return await runStages({ ...o, buildOwnership: own, doorSnapshot: { own, path: synced.path, commit: synced.commit, tree: synced.tree, root: snapshotsAt, ledger: { entries: [] } } }, args, root, git, { ...io, buildOwnership: own });
1901
+ started = true;
1902
+ return await runStages({ ...o, snapshotLock: taken.view, doorSnapshot: { lock: taken.view, path: synced.path, commit: synced.commit, tree: synced.tree, root: snapshotsAt, ledger: { entries: [] } } }, args, root, git, { ...io, snapshotLock: taken.view });
1867
1903
  } finally {
1868
- const r = own.release();
1869
- if (r?.released === false && !own.joined) o.err(`${tag} build ownership ${own.handle} kept: ${r.why}`);
1904
+ // The lock, held through the batch, is released only here, after every job and test of the door run ended, and only when the gate can prove by itself
1905
+ // that no job of this run can still be live in the broker: every seam row ended with a result (none killed by the gate, timed out, cancelled or left without a
1906
+ // result line; deterministic-scans.mjs seamRunState). The broker's SNAPSHOT_STATUS is stale-owner proof and is not asked for a live holder (astra, 2026-11-09).
1907
+ // Otherwise the lock stays, and the next run reclaims it through that stale-owner proof once this process is gone and the jobs ended (fresh review E2).
1908
+ releaseSeamLock({ o, release: taken.release, seamBody: started ? taken.body : null, tag });
1870
1909
  }
1871
1910
  }
1872
1911
  if (devTest) return await runDevTest(o, args, root, git, io, to, appRoot, appDir);
@@ -1890,7 +1929,7 @@ async function runStages(o, args, root, git, io) {
1890
1929
  const shown = git("show", `${commit}:${f}`); if (!failed(shown)) lockFiles[f] = text(shown);
1891
1930
  }
1892
1931
  const binding = bindingOf({
1893
- tree, lockFiles, gateFile: fileURLToPath(import.meta.url), executor: o.brokerException ? `${executor.kind}:exception:${o.brokerException.exceptionId}` : executor.kind,
1932
+ tree, lockFiles, gateFile: fileURLToPath(import.meta.url), gateJudge: gateCodeIdentity(), executor: o.brokerException ? `${executor.kind}:exception:${o.brokerException.exceptionId}` : executor.kind,
1894
1933
  toolchain: { classA: { "cargo-deny": version("cargo-deny", ["--version"]), "cargo-audit": version("cargo-audit", ["--version"]), actionlint: version("actionlint", ["-version"]), shellcheck: version("shellcheck", ["--version"]) }, node: process.version, rustc: version(executor.kind === "broker" && executor.cargo.length > 1 ? executor.cargo[0] : "rustc", executor.kind === "broker" && executor.cargo.length > 1 ? ["rustc", "-V"] : ["-V"]), pnpm: version("pnpm", ["--version"]) },
1895
1934
  });
1896
1935
  // Release writes to R2. The write credential lives only in the trusted publisher: a GitHub Actions job in the protected
@@ -1934,15 +1973,16 @@ async function runStages(o, args, root, git, io) {
1934
1973
  // (source-split.mjs). Anywhere else it runs in the app root of the checkout, which hosted CI's runner holds at the commit.
1935
1974
  const sourceOf = ds ? sourceSplitOf({ root, ds, appDir }) : null;
1936
1975
  const rightRelease = async (stage, cliArgs, extraEnv = {}) => {
1937
- // A broker host's child reaches the broker only through this stage's carrier (carried-cargo.mjs): its Cargo calls, and its pnpm, node and QA
1976
+ // A broker host's child reaches the broker only through this stage's carrier (stage-seam.mjs): its Cargo calls, and its pnpm, node and QA
1938
1977
  // steps as adapter jobs with the third-party children's compiles nested under them. Every call is in the gate-owned ledger and is verified
1939
1978
  // again after the child ends.
1940
- const carrier = await carrierForChildren({ o, ds, root, git, executor, stage, tag });
1979
+ const carrier = await carrierForChildren({ o, ds, root, git, executor, stage, tag, appDir });
1941
1980
  if (carrier.refusal) { o.err(`${tag} BLOCKED: ${carrier.refusal}; nothing ran`); return false; }
1942
1981
  const run = startRun({ commonDir, commit, tree, stage, ...(sourceOf ? { source: sourceOf } : {}) });
1943
1982
  let childOk = false;
1944
1983
  try {
1945
1984
  o.out(`${tag} [${stage}] right-release ${cliArgs.join(" ")}${sourceOf ? ` (from the snapshot ${ds.path})` : ""}`);
1985
+ // The seam's two variables come with the carrier (seamStageEnvOf), as for every other stage with children.
1946
1986
  const r = (o.spawnInherit ?? inheritLaunch)(process.execPath, [cli, ...cliArgs], { cwd: sourceOf ? snapshotAppRootOf(ds.path, appDir) : appRoot, env: carriedEnv(carrier, { ...o.env, ...run.env }, extraEnv) });
1947
1987
  childOk = r.status === 0;
1948
1988
  } finally { endRun(run); }
@@ -2028,11 +2068,11 @@ async function runStages(o, args, root, git, io) {
2028
2068
  return 1;
2029
2069
  }
2030
2070
  // The start of every stage: the snapshot is exactly tree + dependencies + the ledger of the stages before it (7.08, decision 2 Q1).
2031
- if (ds && !(await openSnapshotStage({ o, ds, root, stage, tag }))) { receipt.stages[stage] = { ok: false, at: new Date().toISOString(), snapshot: { path: ds.path, tree: ds.tree, intactAfter: false }, ownership: ds.own.handle }; save(); o.err(`${tag} --to ${to} stopped before ${stage}: the snapshot is not the commit's bytes plus the ledger; nothing ran`); return 2; }
2032
- let ok = false; const at = new Date().toISOString(); const stageStartedMs = Date.now(); let extra = {}; let directReceipt = null;
2071
+ if (ds && !(await openSnapshotStage({ o, ds, root, stage, tag }))) { receipt.stages[stage] = { ok: false, at: new Date().toISOString(), snapshot: { path: ds.path, tree: ds.tree, intactAfter: false }, snapshotLock: ds.lock.token }; save(); o.err(`${tag} --to ${to} stopped before ${stage}: the snapshot is not the commit's bytes plus the ledger; nothing ran`); return 2; }
2072
+ let ok = false; const at = new Date().toISOString(); const stageStartedMs = Date.now(); let extra = {}; let directReceipt = null; let packageSigned = new Map();
2033
2073
  if (stage === "check") {
2034
2074
  { const problem = await pinFloor(false); if (problem) { o.err(`${tag} BLOCKED: ${problem.message}; no class A row ran and nothing compiled`); return 1; } }
2035
- ok = (await (o.runCheck ?? (() => main(["check", "--commit", ds ? commit : "HEAD", "--full-a", ...(ds ? ["--snapshot", ds.path] : []), ...appScope, "--rule-tier", earlyTier], { ...io, cwd: root, ...(ds ? { buildOwnership: ds.own } : {}) })))(earlyTier)) === 0;
2075
+ ok = (await (o.runCheck ?? (() => main(["check", "--commit", ds ? commit : "HEAD", "--full-a", ...(ds ? ["--snapshot", ds.path] : []), ...appScope, "--rule-tier", earlyTier], { ...io, cwd: root, ...(ds ? { snapshotLock: ds.lock } : {}) })))(earlyTier)) === 0;
2036
2076
  extra = { ruleTier: earlyTier };
2037
2077
  }
2038
2078
  else if (stage === "compile") {
@@ -2044,13 +2084,22 @@ async function runStages(o, args, root, git, io) {
2044
2084
  // rightkit#1462 (ADR-001 section 7): a run that goes on to package runs the release admission, read-only, before anything compiles: the same rows `right-release build`
2045
2085
  // runs at its start (files: config and inputs; host: tools, credentials, signing hosts; network: pin freshness against the registries), asked through its own
2046
2086
  // `--dry-run`, which prints the rows and exits non-zero on a finding before any lock, cache, install or child build exists. A refusal then costs seconds, not a class B.
2047
- if (stages.includes("package") && !mobile && PLATFORMS.includes(platform)) {
2048
- o.out(`${tag} [compile] release admission dry-run for ${platform} before any compile (right-release build --platform ${platform} --dry-run)`);
2049
- if (!await rightRelease(stage, ["build", "--platform", platform, "--dry-run"])) { o.err(`${tag} BLOCKED: [compile] the release admission (pin freshness, host tools, credentials, signing hosts) refused ${platform}; nothing compiled`); ok = false; }
2050
- }
2087
+ // On a broker host the admission's recipe expansion binds the app's Cargo target from a signed receipt (stage-seam.mjs carriedOutputDir; the snapshot holds no
2088
+ // target and Cargo cannot be asked for one there). Before the first carried call of the door run no receipt exists, so the dry-run refused every package run with
2089
+ // RK_SPLIT_TARGET_UNRESOLVED (HeardRight on the Dell, 2026-11-10: "the Cargo target directory <snapshot>/tauri-app-next/target is inside the snapshot"). There it runs
2090
+ // right after the sidecars are staged, whose receipts name the target; an app with no carried call before its compile skips the early dry-run, and the package
2091
+ // stage's own `right-release build` runs the same admission rows at its start.
2092
+ const wantsAdmission = stages.includes("package") && !mobile && PLATFORMS.includes(platform);
2093
+ const admissionDryRun = async (when) => {
2094
+ o.out(`${tag} [compile] release admission dry-run for ${platform} ${when} (right-release build --platform ${platform} --dry-run)`);
2095
+ if (!await rightRelease(stage, ["build", "--platform", platform, "--dry-run"])) { o.err(`${tag} BLOCKED: [compile] the release admission (pin freshness, host tools, credentials, signing hosts) refused ${platform}; nothing compiled`); return false; }
2096
+ return true;
2097
+ };
2098
+ const admissionAfterStaging = wantsAdmission && executor.kind === "broker" && Boolean(ds);
2099
+ if (wantsAdmission && !admissionAfterStaging) ok = await admissionDryRun("before any compile");
2051
2100
  // On the snapshot route the sidecars are staged from the snapshot's own config and sources through right-release's source split
2052
2101
  // (the staged files and receipt land beside the sources the compile reads; the caches and build trees stay the checkout's), before
2053
- // `main --all` compiles. A broker host's stage-sidecar child reaches Cargo through the stage's carrier (carried-cargo.mjs).
2102
+ // `main --all` compiles. A broker host's stage-sidecar child reaches Cargo through the stage's carrier (stage-seam.mjs).
2054
2103
  // right-release runs in appRoot (nested apps), so the repository-relative config is handed over absolute (Astra, second pass).
2055
2104
  // On the snapshot route sidecars are staged ONCE per door run by the ledger bookkeeping (attribution diff, immutable staged entries).
2056
2105
  // rightkit#1331: the declared compile inputs that are the app's web build output are produced in the snapshot before ANY compile reads them,
@@ -2061,9 +2110,13 @@ async function runStages(o, args, root, git, io) {
2061
2110
  if (ok && ds) ok = await stageWindowsIdentityOnce({ o, ds, root, git, appDir, cli, commonDir, commit, tree, stage, executor });
2062
2111
  if (ok && ds) ok = await stageSidecarsOnce({ o, ds, root, git, configs: sidecarConfigs, appDir, cli, commonDir, commit, tree, stage, executor });
2063
2112
  else for (const config of ok ? sidecarConfigs : []) if (!await rightRelease(stage, ["stage-sidecar", "--config", path.join(root, config)])) { ok = false; break; }
2113
+ if (ok && admissionAfterStaging) {
2114
+ if (ds.carriedOutputs?.size) ok = await admissionDryRun("after the sidecars were staged, before the app compiles");
2115
+ else o.out(`${tag} [compile] release admission dry-run skipped here: no broker receipt names the app's Cargo target yet; the package stage's build runs the same admission rows at its start`);
2116
+ }
2064
2117
  let compiledDirs = []; let compiledBins = null; let qualifyOwed = [];
2065
2118
  const reportOutputs = (dirs, bins = null) => { compiledDirs = [...dirs]; compiledBins = bins; };
2066
- if (ok) ok = (await (o.runCompile ?? (() => main(ds ? ["--all", "--commit", commit, "--snapshot", ds.path] : ["--all"], { ...io, cwd: root, readStdin: () => "", ...(ds ? { buildOwnership: ds.own, classAEarlier: true, snapshotLedger: ds.ledger?.entries ?? [], onCompileLedger: (entries) => { ds.compileAdmitted = entries; }, onDirectReceipt: (r) => { directReceipt = r; }, onCompileOutputs: reportOutputs, onQualifyOwed: (list) => { qualifyOwed = list; } } : {}) })))({ reportOutputs })) === 0;
2119
+ if (ok) ok = (await (o.runCompile ?? (() => main(ds ? ["--all", "--commit", commit, "--snapshot", ds.path] : ["--all"], { ...io, cwd: root, readStdin: () => "", ...(ds ? { snapshotLock: ds.lock, classAEarlier: true, seamScope: appDir === "." ? null : [appDir], snapshotLedger: ds.ledger?.entries ?? [], onCompileLedger: (entries) => { ds.compileAdmitted = entries; }, onDirectReceipt: (r) => { directReceipt = r; }, onCompileOutputs: reportOutputs, onQualifyOwed: (list) => { qualifyOwed = list; } } : {}) })))({ reportOutputs })) === 0;
2067
2120
  if (directReceipt) extra = { ...extra, direct: directReceipt };
2068
2121
  // What the plan left to the qualify stage is recorded with the compile, so qualification can prove it is not lost (rightkit#1332, #1333).
2069
2122
  if (qualifyOwed.length) extra = { ...extra, qualifyOwed };
@@ -2097,7 +2150,7 @@ async function runStages(o, args, root, git, io) {
2097
2150
  // Row 7.04c (R-T1, 7.09): the snapshot holds no Cargo target. On a direct host the checkout's output directory is resolved here, in the primary
2098
2151
  // checkout, and handed to right-release absolute: it binds every manifest's target for this stage, and the sealed manifest must record it back
2099
2152
  // (the door never trusts the child's value alone). One workspace is pinned as a whole; several are refused, naming them. A broker host's target
2100
- // is the carrier's (rows 7.20 to 7.24): the carried calls' signed receipts name it (carried-cargo.mjs), and no CARGO_TARGET_DIR is passed.
2153
+ // is the carrier's (rows 7.20 to 7.24): the carried calls' signed receipts name it (stage-seam.mjs), and no CARGO_TARGET_DIR is passed.
2101
2154
  let packagePin = { dir: null };
2102
2155
  if (ok && ds && executor.kind !== "broker") {
2103
2156
  packagePin = await cargoOutputPinForScope({ o, git, root, commit, executor, snapshot: ds.path, ...(appDir === "." ? {} : { scopeDirs: [appDir] }) });
@@ -2118,6 +2171,20 @@ async function runStages(o, args, root, git, io) {
2118
2171
  const sealed = ok ? (o.sealedFor ?? sealedFor)({ root: releaseRoot, commit, platform }) : null;
2119
2172
  if (ok && !sealed) { o.err(`${tag} [package] the build reported success but sealed nothing for ${commit.slice(0, 8)} on ${platform}`); ok = false; }
2120
2173
  if (sealed) extra = { platform, sealed: sealed.id, manifestSha256: sealed.digest };
2174
+ // The Windows package build Authenticode-signs the staged sidecar executables in place before the installer embeds them (sign-windows.mjs; HeardRight on
2175
+ // the Dell, 2026-11-10: the stage closed with "a staged sidecar output ... changed after it was staged" for the two files it had just signed). Such a
2176
+ // change is admitted as on the dev route (rightkit#1555): from exactly the staged bytes to exactly the signed bytes the build's externalBin receipt
2177
+ // names, and the gate itself verifies the signature on the bytes now on disk.
2178
+ // Read whether or not the build went on to seal: a build that failed after signing (updater signature, hardening, seal) otherwise closed the stage with
2179
+ // the two signed sidecars reported as changed staged entries, on top of its real error.
2180
+ if (ds && platform === "win") {
2181
+ try {
2182
+ const stateBase = path.join(releaseRoot, ".right-release", "state");
2183
+ const ids = sealed ? [sealed.id] : fs.readdirSync(stateBase).filter((id) => id.endsWith(`-${commit.slice(0, 8)}`)).sort();
2184
+ for (const id of ids) for (const [k, v] of packageSignedInPlace({ ds, receipt: path.join(stateBase, id, "windows", "external-bin.json") })) packageSigned.set(k, v);
2185
+ await assertSignedInPlaceSigned(o, ds.path, packageSigned);
2186
+ } catch (e) { if (ok) o.err(`${tag} RK_CHECK_ERROR: [package] ${e.message}`); ok = false; packageSigned = new Map(); }
2187
+ }
2121
2188
  // The cross-check: the Cargo targets the sealed manifest records are the directory this door resolved itself. A different one voids the stage.
2122
2189
  try { packageMulti?.cleanup?.(); } catch { /* the wrapper's map is the gate's own temp directory */ }
2123
2190
  if (ok && sealed && ds && (packagePin.dir || packagePin.dirs?.length > 1)) {
@@ -2128,7 +2195,7 @@ async function runStages(o, args, root, git, io) {
2128
2195
  if (drift.length) {
2129
2196
  for (const problem of drift.slice(0, 10)) o.err(`${tag} ${SPLIT_TARGET_DRIFT_CODE}: [package] ${problem}`);
2130
2197
  const closedDrift = await closeSnapshotStage({ o, ds, root, stage, step: stage, tag });
2131
- receipt.stages[stage] = { ok: false, at, voided: SPLIT_TARGET_DRIFT_CODE, ...extra, snapshot: { path: ds.path, tree: ds.tree, intactAfter: closedDrift.ok }, ownership: ds.own.handle };
2198
+ receipt.stages[stage] = { ok: false, at, voided: SPLIT_TARGET_DRIFT_CODE, ...extra, snapshot: { path: ds.path, tree: ds.tree, intactAfter: closedDrift.ok }, snapshotLock: ds.lock.token };
2132
2199
  save();
2133
2200
  o.err(`${tag} --to ${to} stopped at ${stage}: ${SPLIT_TARGET_DRIFT_CODE}; the sealed set is void and nothing after it ran`);
2134
2201
  return 2;
@@ -2152,7 +2219,7 @@ async function runStages(o, args, root, git, io) {
2152
2219
  if (drift.length) {
2153
2220
  for (const problem of drift.slice(0, 10)) o.err(`${tag} ${SPLIT_TARGET_DRIFT_CODE}: [package] ${problem}`);
2154
2221
  const closedDrift = await closeSnapshotStage({ o, ds, root, stage, step: stage, tag });
2155
- receipt.stages[stage] = { ok: false, at, voided: SPLIT_TARGET_DRIFT_CODE, ...extra, snapshot: { path: ds.path, tree: ds.tree, intactAfter: closedDrift.ok }, ownership: ds.own.handle };
2222
+ receipt.stages[stage] = { ok: false, at, voided: SPLIT_TARGET_DRIFT_CODE, ...extra, snapshot: { path: ds.path, tree: ds.tree, intactAfter: closedDrift.ok }, snapshotLock: ds.lock.token };
2156
2223
  save();
2157
2224
  o.err(`${tag} --to ${to} stopped at ${stage}: ${SPLIT_TARGET_DRIFT_CODE}; the sealed set is void and nothing after it ran`);
2158
2225
  return 2;
@@ -2169,7 +2236,7 @@ async function runStages(o, args, root, git, io) {
2169
2236
  // store); the release tier is owed first, as for desktop qualification.
2170
2237
  const releaseTier = receipt.stages.check?.ok && receipt.stages.check.ruleTier === "release"
2171
2238
  ? (o.out(`${tag} [release] the release tier already passed at check for this exact input; not run again`), 0)
2172
- : await (o.runReleaseCheck ?? (() => main(["check", "--commit", ds ? commit : "HEAD", "--full-a", ...(ds ? ["--snapshot", ds.path] : []), ...appScope, "--rule-tier", "release"], { ...io, cwd: root, ...(ds ? { buildOwnership: ds.own } : {}) })))();
2239
+ : await (o.runReleaseCheck ?? (() => main(["check", "--commit", ds ? commit : "HEAD", "--full-a", ...(ds ? ["--snapshot", ds.path] : []), ...appScope, "--rule-tier", "release"], { ...io, cwd: root, ...(ds ? { snapshotLock: ds.lock } : {}) })))();
2173
2240
  if (releaseTier !== 0) { o.err(`${tag} [release] the release tier (every rule and scan) is red for ${commit.slice(0, 12)}; nothing was uploaded`); ok = false; }
2174
2241
  else ok = await rightRelease(stage, ["upload", "--platform", platform, "--release", sealed.sealed, "--apply"]);
2175
2242
  extra = { sealed: sealed.sealed, manifestSha256: sealed.manifestSha256, track: platform === "ios" ? "testflight" : "play-internal", ruleTier: "release" };
@@ -2177,7 +2244,7 @@ async function runStages(o, args, root, git, io) {
2177
2244
  // Qualification owes the release tier: every rule and scan, the ones held out of compile admission included (app-check.mjs TIERS).
2178
2245
  const releaseTier = receipt.stages.check?.ok && receipt.stages.check.ruleTier === "release"
2179
2246
  ? (o.out(`${tag} [qualify] the release tier already passed at check for this exact input; not run again`), 0)
2180
- : await (o.runReleaseCheck ?? (() => main(["check", "--commit", ds ? commit : "HEAD", "--full-a", ...(ds ? ["--snapshot", ds.path] : []), ...appScope, "--rule-tier", "release"], { ...io, cwd: root, ...(ds ? { buildOwnership: ds.own } : {}) })))();
2247
+ : await (o.runReleaseCheck ?? (() => main(["check", "--commit", ds ? commit : "HEAD", "--full-a", ...(ds ? ["--snapshot", ds.path] : []), ...appScope, "--rule-tier", "release"], { ...io, cwd: root, ...(ds ? { snapshotLock: ds.lock } : {}) })))();
2181
2248
  if (releaseTier !== 0) { o.err(`${tag} [qualify] the release tier (every rule and scan) is red for ${commit.slice(0, 12)}; nothing was qualified`); ok = false; }
2182
2249
  else {
2183
2250
  // rightkit#1332, #1333: what compile left to qualification (end-to-end crates, declared Swift packages) must have a declared run route here.
@@ -2197,9 +2264,9 @@ async function runStages(o, args, root, git, io) {
2197
2264
  // The stage covers the commit only if the snapshot is still its tree plus the ledger and the host is still this door's (E6, 7.08):
2198
2265
  // what the stage's children wrote may remain only as ledger entries, recorded by this gate's own walk and kept in the receipt (never
2199
2266
  // in the snapshot); a staged entry changed since staging voids the stage.
2200
- const closed = await closeSnapshotStage({ o, ds, root, stage, step: stage, tag });
2267
+ const closed = await closeSnapshotStage({ o, ds, root, stage, step: stage, tag, signedInPlace: packageSigned });
2201
2268
  const { receiptLedger } = await import("../stage-ledger.mjs");
2202
- extra = { ...extra, snapshot: { path: ds.path, tree: ds.tree, intactAfter: closed.ok, ledger: receiptLedger(closed.entries) }, ownership: ds.own.handle };
2269
+ extra = { ...extra, snapshot: { path: ds.path, tree: ds.tree, intactAfter: closed.ok, ledger: receiptLedger(closed.entries) }, snapshotLock: ds.lock.token };
2203
2270
  if (!closed.ok) { receipt.stages[stage] = { ok: false, at, ...extra }; save(); o.err(`${tag} --to ${to} stopped at ${stage}: the result covers no known bytes`); return 2; }
2204
2271
  }
2205
2272
  receipt.stages[stage] = { ok, at, ...extra };
@@ -2291,10 +2358,10 @@ async function verifyDoorSnapshot(o, ds, root, { ledger, admitNew = false }) {
2291
2358
 
2292
2359
  /**
2293
2360
  * The start of a stage: the snapshot is exactly tree + dependencies + the ledger of the stages before it, no entry new, changed or
2294
- * missing, and the host's ownership is still held (7.08, decision 2 Q1). An ignored file planted before the stage is a new entry here.
2361
+ * missing, and the run's snapshot lock is still held (7.08, decision 2 Q1). An ignored file planted before the stage is a new entry here.
2295
2362
  */
2296
2363
  export async function openSnapshotStage({ o, ds, root, stage, tag = "rightkit-gate:" }) {
2297
- if (!ds.own.held()) { o.err(`${tag} RK_CHECK_ERROR: [${stage}] the build ownership ${ds.own.handle} is no longer held`); return false; }
2364
+ if (!ds.lock.held()) { o.err(`${tag} RK_CHECK_ERROR: [${stage}] the snapshot lock ${ds.lock.token} is no longer held`); return false; }
2298
2365
  const { diffEntries, sameEntries } = await import("../stage-ledger.mjs");
2299
2366
  let walked;
2300
2367
  try { walked = await walkDoorSnapshot(o, ds, root); } catch (e) { o.err(`${tag} RK_CHECK_ERROR: [${stage}] ${e.message}`); return false; }
@@ -2309,13 +2376,79 @@ export async function openSnapshotStage({ o, ds, root, stage, tag = "rightkit-ga
2309
2376
  return true;
2310
2377
  }
2311
2378
 
2379
+ /**
2380
+ * rightkit#1555: whether a staged ledger entry `was` may now be `now` because the Authenticode step signed it in place: the signer's report names
2381
+ * the path, its digest before signing is the staged digest, and its digest after signing is the digest on disk now. Anything else is still a
2382
+ * change of an immutable staged entry.
2383
+ */
2384
+ export function signedInPlaceAdmits(was, now, reported) {
2385
+ return Boolean(was && now && reported && typeof was.sha256 === "string" && reported.sha256Before === was.sha256 && reported.sha256After === now.sha256);
2386
+ }
2387
+
2388
+ /**
2389
+ * rightkit#1555: the gate itself checks every file the report admits: a valid, timestamped Authenticode signature whose leaf is the product's
2390
+ * one signer (suite-signing-policy SIGN_SUBJECT), on the bytes now on disk. A report a child forged for unsigned or foreign-signed bytes is
2391
+ * refused here, whoever wrote it. `o.verifyWindows` is the test seam; the default is sign-windows.mjs verifyWindowsFiles (signtool verify /pa).
2392
+ */
2393
+ export async function assertSignedInPlaceSigned(o, snapshotDir, signedInPlace) {
2394
+ if (!signedInPlace.size) return;
2395
+ const { SIGN_SUBJECT } = await import("../suite-signing-policy.mjs");
2396
+ const verify = o.verifyWindows ?? (await import("../sign-windows.mjs")).verifyWindowsFiles;
2397
+ const files = [...signedInPlace.keys()].map((rel) => path.join(snapshotDir, ...rel.split("/")));
2398
+ const records = verify(files);
2399
+ for (const file of files) {
2400
+ const record = (records ?? []).find((r) => path.resolve(r?.file ?? "") === path.resolve(file));
2401
+ if (!record || record.subject !== SIGN_SUBJECT || record.authenticode !== "Valid") {
2402
+ throw new Error(`${file} is reported signed in place but is not validly Authenticode-signed by ${SIGN_SUBJECT} (${JSON.stringify(record?.subject ?? null)} / ${JSON.stringify(record?.authenticode ?? null)})`);
2403
+ }
2404
+ }
2405
+ }
2406
+
2407
+ /**
2408
+ * The staged executables a Windows package build signed in place, as `Map(snapshot-relative posix path -> { sha256Before, sha256After })`: a staged ledger
2409
+ * entry whose bytes now differ, for which the build's externalBin receipt (external-bin.mjs, `rightkit-external-bin-v1`) names that exact pair of digests.
2410
+ * An absent receipt admits nothing.
2411
+ */
2412
+ export function packageSignedInPlace({ ds, receipt, readFile = (f) => fs.readFileSync(f), exists = fs.existsSync }) {
2413
+ const out = new Map();
2414
+ if (!exists(receipt)) return out;
2415
+ const doc = JSON.parse(String(readFile(receipt)));
2416
+ if (doc?.contract !== "rightkit-external-bin-v1" || !Array.isArray(doc.files)) throw new Error(`${receipt} is not a rightkit-external-bin-v1 receipt`);
2417
+ for (const e of ds.ledger?.entries ?? []) {
2418
+ if (e.kind !== "staged" || !/\.(exe|dll)$/i.test(e.path)) continue;
2419
+ const file = path.join(ds.path, ...e.path.split("/"));
2420
+ if (!exists(file)) continue;
2421
+ const now = createHash("sha256").update(readFile(file)).digest("hex");
2422
+ if (now === e.sha256) continue;
2423
+ if (doc.files.some((f) => f?.preSignSha256 === e.sha256 && f?.signedSha256 === now)) out.set(e.path, { sha256Before: e.sha256, sha256After: now });
2424
+ }
2425
+ return out;
2426
+ }
2427
+
2428
+ /** The signer's report as `Map(snapshot-relative posix path -> { sha256Before, sha256After })`; a path outside the snapshot or a malformed report is refused. */
2429
+ export function readSignedInPlaceReport(file, snapshotDir, { readFile = (f) => fs.readFileSync(f, "utf8"), exists = fs.existsSync } = {}) {
2430
+ const out = new Map();
2431
+ if (!exists(file)) return out;
2432
+ const report = JSON.parse(readFile(file));
2433
+ if (report?.schema !== "rightkit.signed-in-place/1" || !Array.isArray(report.files)) throw new Error(`${file} is not a rightkit.signed-in-place/1 report`);
2434
+ for (const f of report.files) {
2435
+ const rel = typeof f?.path === "string" ? path.relative(snapshotDir, path.resolve(f.path)) : "";
2436
+ if (!rel || rel.startsWith("..") || path.isAbsolute(rel)) throw new Error(`${file} names ${f?.path}, which is not inside the snapshot ${snapshotDir}`);
2437
+ if (!/^[0-9a-f]{64}$/.test(f.sha256Before ?? "") || !/^[0-9a-f]{64}$/.test(f.sha256After ?? "")) throw new Error(`${file}: ${rel} lacks its before/after sha256`);
2438
+ // Authenticode signs executables and libraries; a report naming anything else is not the signer's.
2439
+ if (!/\.(exe|dll)$/i.test(rel)) throw new Error(`${file} names ${rel}, which is not an executable or library the signer signs`);
2440
+ out.set(rel.split(path.sep).join("/"), { sha256Before: f.sha256Before, sha256After: f.sha256After });
2441
+ }
2442
+ return out;
2443
+ }
2444
+
2312
2445
  /**
2313
2446
  * The end of a stage: what its children wrote may remain only as ledger entries. A staged entry is immutable for the rest of the run
2314
2447
  * (the bytes the compile read are the bytes sealed); a generated entry may be rewritten or removed and is re-recorded here. Returns
2315
2448
  * `{ ok, entries }` and replaces the door's ledger with the entries just recorded.
2316
2449
  */
2317
- export async function closeSnapshotStage({ o, ds, root, stage, step = "stage", tag = "rightkit-gate:" }) {
2318
- if (!ds.own.held()) { o.err(`${tag} RK_CHECK_ERROR: [${stage}] the build ownership ${ds.own.handle} is no longer held`); return { ok: false, entries: ds.ledger?.entries ?? [] }; }
2450
+ export async function closeSnapshotStage({ o, ds, root, stage, step = "stage", tag = "rightkit-gate:", signedInPlace = new Map() }) {
2451
+ if (!ds.lock.held()) { o.err(`${tag} RK_CHECK_ERROR: [${stage}] the snapshot lock ${ds.lock.token} is no longer held`); return { ok: false, entries: ds.ledger?.entries ?? [] }; }
2319
2452
  const { entryKey } = await import("../stage-ledger.mjs");
2320
2453
  let walked;
2321
2454
  try { walked = await walkDoorSnapshot(o, ds, root); } catch (e) { o.err(`${tag} RK_CHECK_ERROR: [${stage}] ${e.message}`); return { ok: false, entries: ds.ledger?.entries ?? [] }; }
@@ -2327,10 +2460,12 @@ export async function closeSnapshotStage({ o, ds, root, stage, step = "stage", t
2327
2460
  // of the same config, every file it names present with that digest; the files it names become this stage's staged entries.
2328
2461
  const restaged = stage === "package" ? await restagedSidecars({ o, ds, prior, now }) : { paths: new Set(), receipts: new Set(), producers: new Set(), problems: [] };
2329
2462
  problems.push(...restaged.problems);
2330
- for (const [p, e] of prior) if (e.kind === "staged" && !restaged.paths.has(p) && !restaged.receipts.has(p) && !(restaged.producers.has(e.producer?.step) && !now.has(p)) && (!now.has(p) || entryKey(now.get(p)) !== entryKey(e))) problems.push(`${p} is a staged sidecar output and ${now.has(p) ? "changed" : "was removed"} after it was staged (a staged entry is immutable for the door run)`);
2463
+ // rightkit#1555: a staged entry the Authenticode step re-signed in place is admitted only from exactly its staged bytes to exactly the signed bytes it reported.
2464
+ const signedOk = (p, e) => signedInPlaceAdmits(e, now.get(p), signedInPlace.get(p));
2465
+ for (const [p, e] of prior) if (e.kind === "staged" && !restaged.paths.has(p) && !restaged.receipts.has(p) && !signedOk(p, e) && !(restaged.producers.has(e.producer?.step) && !now.has(p)) && (!now.has(p) || entryKey(now.get(p)) !== entryKey(e))) problems.push(`${p} is a staged sidecar output and ${now.has(p) ? "changed" : "was removed"} after it was staged (a staged entry is immutable for the door run)`);
2331
2466
  // Evidence (Pulse Windows dev, 2026-11-06): for each staged entry that changed, its sha256 then and now; for a receipt, the fields that differ.
2332
2467
  for (const [p, e] of prior) {
2333
- if (e.kind !== "staged" || !now.has(p) || entryKey(now.get(p)) === entryKey(e) || restaged.paths.has(p) || restaged.receipts.has(p)) continue;
2468
+ if (e.kind !== "staged" || !now.has(p) || entryKey(now.get(p)) === entryKey(e) || restaged.paths.has(p) || restaged.receipts.has(p) || signedOk(p, e)) continue;
2334
2469
  o.err(`${tag} staged-change evidence: ${p}: sha256 ${String(e.sha256).slice(0, 16)} at staging (${e.size} bytes) -> ${String(now.get(p).sha256).slice(0, 16)} now (${now.get(p).size} bytes)`);
2335
2470
  const before = ds.stagedReceipts?.get(p);
2336
2471
  if (before) {
@@ -2447,8 +2582,8 @@ export async function stageSidecarsOnce({ o, ds, root, git = null, configs, appD
2447
2582
  const { TAURI_CONFIG: inherited, ...cleanEnv } = o.env; void inherited; // never set or pass one (refused at the door's start)
2448
2583
  for (const config of configs) {
2449
2584
  const before = ds.ledger?.entries ?? [];
2450
- // The stage-sidecar child's Cargo calls (its builds and metadata queries) are carried on a broker host (carried-cargo.mjs).
2451
- const carrier = await carrierForChildren({ o, ds, root, git, executor, stage, tag, producer: true });
2585
+ // The stage-sidecar child's Cargo calls (its builds and metadata queries) are carried on a broker host (stage-seam.mjs).
2586
+ const carrier = await carrierForChildren({ o, ds, root, git, executor, stage, tag, appDir });
2452
2587
  if (carrier.refusal) { o.err(`${tag} BLOCKED: ${carrier.refusal}; nothing was staged`); return false; }
2453
2588
  const run = startRun({ commonDir, commit, tree, stage, source });
2454
2589
  let r;
@@ -2552,7 +2687,7 @@ function copyDeclared(declared, from, to) {
2552
2687
  export async function stageWebBuildOnce({ o, ds, root, git = null, appDir, cli, commonDir, commit, tree, stage, executor = null, tag = "rightkit-gate:" }) {
2553
2688
  if (ds.webBuilt) return true;
2554
2689
  ds.webBuilt = true;
2555
- const { readDeclaredInputs, SnapshotRequestError } = await import("../snapshot-request.mjs");
2690
+ const { readDeclaredInputs, SnapshotRequestError } = await import("../compile-inputs.mjs");
2556
2691
  let declared;
2557
2692
  try { declared = readDeclaredInputs(ds.path).map((x) => x.split(/[\\/]/).join("/")); }
2558
2693
  catch (e) { if (e instanceof SnapshotRequestError) return true; throw e; } // a malformed declaration refuses in the compile, which names it
@@ -2624,7 +2759,7 @@ export async function stageWebBuildOnce({ o, ds, root, git = null, appDir, cli,
2624
2759
  export async function stageWindowsIdentityOnce({ o, ds, root, git = null, appDir, cli, commonDir, commit, tree, stage, executor = null, tag = "rightkit-gate:" }) {
2625
2760
  if (ds.identityBuilt) return true;
2626
2761
  ds.identityBuilt = true;
2627
- const { readDeclaredInputs, SnapshotRequestError } = await import("../snapshot-request.mjs");
2762
+ const { readDeclaredInputs, SnapshotRequestError } = await import("../compile-inputs.mjs");
2628
2763
  let declared;
2629
2764
  try { declared = readDeclaredInputs(ds.path).map((x) => x.split(/[\\/]/).join("/")); }
2630
2765
  catch (e) { if (e instanceof SnapshotRequestError) return true; throw e; }
@@ -2642,7 +2777,7 @@ export async function stageWindowsIdentityOnce({ o, ds, root, git = null, appDir
2642
2777
  const producer = path.join(path.dirname(cli), "..", "windows-identity.mjs");
2643
2778
  for (const config of configs) {
2644
2779
  const before = ds.ledger?.entries ?? [];
2645
- const carrier = await carrierForChildren({ o, ds, root, git, executor, stage, tag, producer: true });
2780
+ const carrier = await carrierForChildren({ o, ds, root, git, executor, stage, tag, appDir });
2646
2781
  if (carrier.refusal) { o.err(`${tag} BLOCKED: ${carrier.refusal}; the Windows identity package did not build`); return false; }
2647
2782
  const run = startRun({ commonDir, commit, tree, stage, source });
2648
2783
  let r;
@@ -2725,6 +2860,69 @@ async function cargoOutputPinForScope(options) {
2725
2860
  }
2726
2861
 
2727
2862
  /** Bind only committed closure workspaces to checkout outputs; runtime Cargo outside that map refuses. */
2863
+ /**
2864
+ * The lock arguments of a snapshot run (reset plan section 3), for every route that syncs or reads a snapshot: `{ lock, body }` for `takeSnapshotLock`, or `{ refusal }`. On a
2865
+ * broker host the body is { pid, identity, commit, token } and the lock is held through every job and test; a dead holder's lock is reclaimed only on the broker's SNAPSHOT_STATUS
2866
+ * IDLE proof. A host with no broker (Linux direct) takes the legacy lock, held the same way and reclaimed when its holder is proven gone: a seam lock there would demand a
2867
+ * broker proof that cannot exist and wedge the snapshot after the first crash.
2868
+ */
2869
+ // The judge's client is the RustRight client by absolute path, resolved as every other seam call resolves it (brokerClientOf: the declared Linux route's client,
2870
+ // else `which rustright`): the Mac and Dell executor shape carries no `client` field, so reading `ex.client` gave the judge null and it never asked the broker
2871
+ // (HR retries of 2026-11-09, rightkit#1548). Exported for the test that drives it with the real executor shape.
2872
+ export function seamLockFor({ o, root, snapshotsAt, commit, snap, tag }) {
2873
+ if (!/^[0-9a-f]{40}$/.test(String(commit))) return { lock: {}, body: null };
2874
+ const identity = processIdentity(process.pid, { platform: o.platform, spawnSync: (c, a, opts) => o.spawn(c, a, opts) });
2875
+ // On a broker host the seam is the only class B path: without an identity the lock the broker reads cannot be written, so nothing runs (no silent legacy lock).
2876
+ let executorKind = null; let client = null;
2877
+ try { const ex = (o.resolveExecutor ?? gateResolveExecutor)({ env: o.env, platform: o.platform, exists: o.exists, which: whichIn(o), readFile: o.readFile }); executorKind = ex?.kind ?? null; client = brokerClientOf(o, ex) ?? null; } catch { executorKind = null; client = null; }
2878
+ if (!identity && executorKind === "broker") return { refusal: `${tag} BLOCKED: RK_SEAM_IDENTITY: this process's birth identity could not be read (ps), so the snapshot lock the broker requires cannot be written; nothing ran` };
2879
+ if (executorKind !== "broker") {
2880
+ if (!identity) o.err(`${tag} note: this process's birth identity could not be read; the snapshot lock is the legacy one (no broker on this host)`);
2881
+ return { lock: {}, body: null };
2882
+ }
2883
+ // A dead holder's lock is reclaimed only on the broker's SNAPSHOT_STATUS proof that the snapshot is IDLE for exactly that owner (gate-seam.mjs); no broker, no proof.
2884
+ // Everything the judge needs is resolved here and bound into it (snapshotReclaimJudge): nothing is read from an outer scope when the sync calls it (astra, 2026-11-09, twice).
2885
+ const snapshotPath = path.join(snapshotsAt, snap.repositoryOf(root).key);
2886
+ const judge = snapshotReclaimJudge({ o, client, snapshotPath });
2887
+ const body = snapshotLockBody({ identity, commit });
2888
+ return { lock: { body, judge }, body };
2889
+ }
2890
+
2891
+ /**
2892
+ * Releases a run's snapshot lock (`release`, from takeSnapshotLock) only on positive evidence. A broker-host lock (`seamBody`) is kept while any seam row or stage carrier of
2893
+ * the run is unsettled or uncounted, for the broker's stale-owner proof; a legacy lock, and a lock of a run that started no work (`seamBody` null), is released at once.
2894
+ */
2895
+ function releaseSeamLock({ o, release, seamBody, tag }) {
2896
+ try {
2897
+ if (!release) return;
2898
+ // Positive evidence (fresh review of badf93c, D5): every seam run and stage carrier that began has counted its rows (open 0), and none was unsettled.
2899
+ if (!seamBody || (seamRunState.unsettled === 0 && seamRunState.open === 0)) release();
2900
+ else o.err(`${tag} note: the snapshot lock ${release.lockFile ?? ""} is kept: ${seamRunState.unsettled} seam row(s) of this run ended without a settled result and ${seamRunState.open} seam run(s) or stage(s) ended before counting theirs (killed, timed out, cancelled or failed), so a broker job may still be finishing; the lock is reclaimed on the broker's proof`);
2901
+ } catch { /* a lock is removed by its holder only; a failed removal leaves it for the stale-holder rule */ }
2902
+ }
2903
+
2904
+ /**
2905
+ * The one exclusion of a snapshot run: takes the snapshot lock of `checkout`'s repository before anything is synced or read, and says so in the log
2906
+ * (`snapshot lock held <token>`, with `(reclaimed from <owner>: <proof>)` when a dead holder's lock was reclaimed). `{ release, body, view }`: `release` frees it
2907
+ * (releaseSeamLock), `view` is what every nested gate is handed to join it, `body` is the seam body (null for the legacy lock). A refusal prints under the route's own
2908
+ * prefix and returns `{ exit }`: `door` (BLOCKED, exit 1) or `check` (RK_CHECK_ERROR, exit 2). Nothing is created when the lock cannot be taken.
2909
+ */
2910
+ function takeRunLock({ o, checkout, snapshotsAt, commit, snap, tag, route = "door" }) {
2911
+ const refuse = (message, created) => { o.err(route === "check" ? `${tag} RK_CHECK_ERROR: ${message}; nothing ran${created === false ? ", nothing created" : ""}` : `${tag} BLOCKED: ${message}; nothing ran${created === false ? ", nothing created" : ""}`); return { exit: route === "check" ? 2 : 1 }; };
2912
+ const taken = seamLockFor({ o, root: checkout, snapshotsAt, commit, snap, tag });
2913
+ if (taken.refusal) { o.err(taken.refusal); return { exit: route === "check" ? 2 : 1 }; }
2914
+ let release;
2915
+ try { release = (o.takeSnapshotLock ?? snap.takeSnapshotLock)({ checkout, root: snapshotsAt, lock: taken.lock }); }
2916
+ catch (e) {
2917
+ if (e.code === "busy") return refuse(e.message);
2918
+ if (e.code === "refused") return refuse(e.message, false);
2919
+ if (e.code === "error") { o.err(`${tag} RK_CHECK_ERROR: snapshot lock ${e.message}; nothing ran`); return { exit: 2 }; }
2920
+ throw e;
2921
+ }
2922
+ o.out(`${tag} snapshot lock held ${release.token}${release.reclaimed ? ` (reclaimed from ${release.reclaimed.from}: ${release.reclaimed.proof})` : ""}`);
2923
+ return { release, body: taken.body, view: snap.lockView(release) };
2924
+ }
2925
+
2728
2926
  async function bindUnitCargo({ o, git, root, ds, executor, which, scopeDirs, extraWorkspaces = [], onlyWorkspaces = null }) {
2729
2927
  let selection;
2730
2928
  try { selection = await committedCargoManifests({ o, git, root, commit: ds.commit, scopeDirs, extraWorkspaces }); }
@@ -2783,12 +2981,10 @@ async function bindUnitCargo({ o, git, root, ds, executor, which, scopeDirs, ext
2783
2981
  const shimModule = await import("../cargo-target-shim.mjs");
2784
2982
  let broker = null; let realCargo = null;
2785
2983
  if (executor.kind === "broker") {
2786
- if (!o.snapshotBroker) return { refusal: "a broker host reaches Cargo from a unit stage only through the snapshot carrier (deps.snapshotBroker), which this gate was started without" };
2787
2984
  let sb;
2788
- try { sb = await carrierBroker({ o, root, ds, executor, which }); } catch (error) { return { refusal: `the snapshot carrier cannot be built (${error.code ?? "error"}: ${error.message})` }; }
2789
- // Installing the carrier map sends nothing: the ownership records each carried request's sub-handle just before it is sent (snapshot-broker.mjs).
2790
- const { brokerSection } = await import("../snapshot-broker.mjs");
2791
- broker = { checkoutDirs: Object.fromEntries(workspaces.map((w) => [w, path.join(checkoutReal, ...(w === "." ? [] : w.split("/")))])), section: (o.brokerSection ?? brokerSection)(sb) };
2985
+ try { sb = await seamBrokerFor({ o, root, ds, executor, which }); } catch (error) { return { refusal: `the broker client of the seam cannot be resolved (${error.code ?? "error"}: ${error.message})` }; }
2986
+ // Installing the wrapper's map sends nothing: every compile a unit stage's tests reach is a seam call, filed in the scan's ledger (cargo-target-shim.mjs).
2987
+ broker = { checkoutDirs: Object.fromEntries(workspaces.map((w) => [w, path.join(checkoutReal, ...(w === "." ? [] : w.split("/")))])), section: sb };
2792
2988
  // The unit stages' non-compiling cargo (the `cargo fmt --check` step, metadata) runs directly with the broker's real cargo, as class A
2793
2989
  // does (GC-A11). Without it the wrapper sent `cargo fmt -p <crate> --check` to the broker, which refuses non-compiling requests: every
2794
2990
  // unit compile on the Mac and Dell stopped there (rightkit-document-workspace on the Dell, 2026-11-03, exit 125).
@@ -2802,19 +2998,34 @@ async function bindUnitCargo({ o, git, root, ds, executor, which, scopeDirs, ext
2802
2998
  catch (error) { if (dir) fs.rmSync(dir, { recursive: true, force: true }); return { refusal: `the runtime cargo wrapper cannot be installed (${error.message})` }; }
2803
2999
  const scan = shimModule.shimScanEnv(o.env, installed);
2804
3000
  const delta = Object.fromEntries(Object.entries(scan).filter(([k, v]) => o.env[k] !== v));
2805
- const { CARRIED_CARGO_MAP_ENV } = await import("../carried-cargo.mjs");
3001
+ const { CARRIED_CARGO_MAP_ENV } = await import("../stage-seam.mjs");
3002
+ const { readLedgerDir } = await import("../cargo-ledger.mjs");
3003
+ // On a broker host the unit stages' compiles are seam calls filed in this wrapper's ledger: the run's snapshot lock waits for them like a door stage's (seamRunState),
3004
+ // raised here and lowered in cleanup once every call is counted; a run that ends without cleanup keeps the lock.
3005
+ const seamCounted = installed.mode === "broker";
3006
+ if (seamCounted) seamRunState.open += 1;
3007
+ let counted = false;
2806
3008
  return {
2807
3009
  targetDirs, // { [cargoDir]: the checkout's target directory } on a direct host (null per workspace on a broker host, whose carried receipt names the output directory)
2808
3010
  env: { ...delta, ...(installed.mode === "broker" ? { [CARRIED_CARGO_MAP_ENV]: installed.mapFile } : {}) }, note: `runtime cargo wrapper ${installed.shim} (${installed.mode}): each cargo call a unit stage reaches binds its workspace's checkout target directory or is refused`,
2809
3011
  // Every call the wrapper decided is in the gate-owned ledger: a refused or unverified call fails the stage even when the test ignored cargo's exit (7.10, decision C).
2810
- check: async () => { const { readLedger, UNSCOPED } = await import("../cargo-ledger.mjs"); return readLedger(installed.ledgerDir, UNSCOPED).problems ?? []; },
2811
- cleanup: () => { fs.rmSync(installed.dir ?? dir, { recursive: true, force: true }); },
3012
+ // Every file of the ledger (a call that carried a scan token files under it).
3013
+ check: async () => readLedgerDir(installed.ledgerDir).problems ?? [],
3014
+ cleanup: () => {
3015
+ if (seamCounted && !counted) {
3016
+ counted = true;
3017
+ try { const { entries, malformed } = readLedgerDir(installed.ledgerDir); seamRunState.unsettled += entries.filter((e) => e.mode === "seam" && e.settled !== true).length + malformed; }
3018
+ catch { seamRunState.unsettled += 1; /* the calls' outcomes are unknown: keep the lock */ }
3019
+ seamRunState.open -= 1;
3020
+ }
3021
+ fs.rmSync(installed.dir ?? dir, { recursive: true, force: true });
3022
+ },
2812
3023
  };
2813
3024
  }
2814
3025
 
2815
3026
  /**
2816
3027
  * `--to <stage> --unit <selector> [--commit <rev>]` on the snapshot route (row 7.06a): select a commit (HEAD by default), take the
2817
- * repository's build ownership, sync its snapshot, run class A of the snapshot (`check --commit <sha> --full-a --snapshot <dir>`), and build
3028
+ * repository's snapshot lock, sync its snapshot, run class A of the snapshot (`check --commit <sha> --full-a --snapshot <dir>`), and build
2818
3029
  * the unit from the snapshot (`--workspace <snapshot>`). Commit and tree come from the selection; no HEAD or status is read. The unit
2819
3030
  * manifest and the local-build grant are read from the selected commit, so one present only in the checkout is refused. Each stage is
2820
3031
  * bracketed by the ledger verify (7.08); Cargo's output is pinned to the checkout's target directory (7.09); `--to release` keeps its
@@ -2827,14 +3038,13 @@ async function runUnitSnapshot(o, args, root, git, io, option) {
2827
3038
  const match = /^(?:npm:@rightkit\/([a-z0-9-]+)|cargo:(rightkit-[a-z0-9-]+))$/.exec(selector);
2828
3039
  const manifest = match && (match[1] ? `packages/${match[1]}/package.json` : `crates/${match[2]}/Cargo.toml`);
2829
3040
  if (!manifest) { o.err(`${tag} BLOCKED: unit needs npm:@rightkit/<name> or cargo:rightkit-<name>`); return 1; }
2830
- // `--to tool` (tool-build.mjs) builds and enrols one named tool binary; its unit and host are decided here, before ownership, a snapshot or any process.
3041
+ // `--to tool` (tool-build.mjs) builds and enrols one named tool binary; its unit and host are decided here, before the lock, a snapshot or any process.
2831
3042
  const toolRun = option("--to") === "tool";
2832
3043
  if (toolRun) {
2833
3044
  const { toolPlan } = await import("../tool-build.mjs");
2834
3045
  try { toolPlan({ selector, platform: o.platform }); } catch (e) { o.err(`${tag} BLOCKED: ${e.message}; nothing ran`); return 1; }
2835
3046
  }
2836
3047
  const snap = await import("../snapshot.mjs");
2837
- const { acquireBuildOwnership, ownershipFile } = await import("../build-ownership.mjs");
2838
3048
  let selected;
2839
3049
  try { selected = snap.resolveCommit(root, option("--commit") ?? "HEAD"); }
2840
3050
  catch (e) { o.err(`${tag} cannot resolve ${option("--commit") ?? "HEAD"} to a commit: ${e.message}`); return 2; }
@@ -2845,24 +3055,24 @@ async function runUnitSnapshot(o, args, root, git, io, option) {
2845
3055
  const executor = (o.resolveExecutor ?? gateResolveExecutor)({ env: o.env, platform: o.platform, exists: o.exists, which, readFile: o.readFile }); applyExecutorEnv(o, executor);
2846
3056
  if (executor.kind === "refuse") { o.err(`${tag} BLOCKED: ${executor.problem}`); return 1; }
2847
3057
  if (option("--ci-proof-out") && executor.kind !== "broker") { o.err(`${tag} BLOCKED: --ci-proof-out requires the managed snapshot broker`); return 1; }
2848
- { const decided = routePlan(o, { to: option("--to"), stages: [], devTest: true, executor, capabilities: await brokerCapabilityStateWithHandshake(o, { to: option("--to"), executor }) });
3058
+ { const decided = routePlan(o, { to: option("--to"), stages: [], devTest: true, executor });
2849
3059
  if (decided.refusal?.code === "RK_BROKER_CAPABILITY_MISSING") { o.err(`${tag} BLOCKED: ${decided.refusal.code}: ${decided.refusal.message}; nothing ran`); return 1; } }
2850
- 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; }
2851
3060
  const common = git("rev-parse", "--git-common-dir");
2852
3061
  if (failed(common) || !text(common).trim()) { o.err(`${tag} cannot read the git directory`); return 2; }
2853
3062
  const snapshotsAt = o.snapshotRoot ?? snap.snapshotRoot({ platform: o.platform, env: o.env });
2854
3063
  { const mismatch = await declaredSnapshotRootRefusal(o, executor, snapshotsAt); if (mismatch) { o.err(`${tag} BLOCKED: ${mismatch.code}: ${mismatch.message}; nothing ran`); return 1; } }
2855
- let own;
2856
- try { own = (o.acquireOwnership ?? acquireBuildOwnership)({ file: ownershipFile({ platform: o.platform, beside: o.snapshotRoot, repository: snap.repositoryOf(root).key }), stage: `door:unit:${option("--to")}`, snapshot: path.join(snapshotsAt, snap.repositoryOf(root).key), commit, platform: o.platform, env: o.env }); }
2857
- catch (e) { if (e.code !== "busy" && e.code !== "refused") throw e; o.err(`${tag} BLOCKED: ${e.message}; nothing ran${e.code === "refused" ? ", nothing created" : ""}`); return 1; }
2858
- o.out(`${tag} build ownership ${own.joined ? "joined" : "held"} ${own.handle}${own.reclaimed ? ` (reclaimed from ${own.reclaimed.from}: ${own.reclaimed.proofs.join("; ")})` : ""}`);
3064
+ // The same one exclusion as the door (takeRunLock): on a broker host the unit's stage calls are seam requests, which the broker admits only under the snapshot lock.
3065
+ const taken = takeRunLock({ o, checkout: root, snapshotsAt, commit, snap, tag });
3066
+ if (taken.exit !== undefined) return taken.exit;
3067
+ let started = false;
2859
3068
  try {
2860
3069
  let synced;
2861
- try { synced = (o.syncSnapshot ?? snap.syncSnapshot)({ checkout: root, rev: commit, root: snapshotsAt }); }
3070
+ try { synced = (o.syncSnapshot ?? snap.syncSnapshot)({ checkout: root, rev: commit, root: snapshotsAt, lock: { held: taken.view } }); }
2862
3071
  catch (e) { o.err(`${tag} ${e.code === "error" ? "RK_CHECK_ERROR" : "BLOCKED"}: snapshot ${e.message}; nothing ran`); return e.code === "error" ? 2 : 1; }
3072
+ started = true;
2863
3073
  o.out(`${tag} snapshot ${synced.path} is commit ${synced.commit} tree ${synced.tree} (written=${synced.written} removed=${synced.removed} unchanged=${synced.unchanged})`);
2864
3074
  if (synced.identity) o.out(`${tag} source identity ${synced.identity.file}: ${synced.identity.written ? "written" : synced.identity.kept ? "kept" : `not written (${synced.identity.reason})`}`);
2865
- const ds = { own, path: synced.path, commit: synced.commit, tree: synced.tree, root: snapshotsAt, ledger: { entries: [] } };
3075
+ const ds = { lock: taken.view, path: synced.path, commit: synced.commit, tree: synced.tree, root: snapshotsAt, ledger: { entries: [] } };
2866
3076
  if (io[UNIT_LIST_UNION]) return await runUnionSnapshot({ o, io, root, git, ds, union: io[UNIT_LIST_UNION], unitListClassA: io.unitListClassA });
2867
3077
  // A unit's test or pack that reaches Cargo must never write `target/` into the snapshot (npm units included): see bindUnitCargo.
2868
3078
  // A check starts no unit command: its own Class A path binds read-only Cargo calls. Resolving every unit's compile output
@@ -2897,13 +3107,16 @@ async function runUnitSnapshot(o, args, root, git, io, option) {
2897
3107
  // 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.
2898
3108
  const unitDir = path.posix.dirname(manifest);
2899
3109
  const shared = io.unitListClassA?.dirs?.includes(unitDir) ? io.unitListClassA : null;
3110
+ // The unit's stage children (its tests, pack and adapters, through the runtime cargo wrapper and the stage seam) name the root verdict of the scope its own class A
3111
+ // writes (runCheck below: the unit's directory, or every listed unit's for a unit list); each call derives its own directory's verdict from it (seam-broker.mjs verdictForCwd).
3112
+ const unitEnvExtra = { ...envExtra, ...(executor.kind === "broker" ? { RUSTRIGHT_GATE_COMMIT: ds.commit, RUSTRIGHT_CLASS_A: path.join(path.dirname(path.dirname(path.resolve(ds.path))), "class-a-verdicts", verdictFileName({ commit: ds.commit, scope: shared ? shared.dirs : [unitDir], workspace: "." })) } : {}) };
2900
3113
  const runCheck = async (tier) => {
2901
3114
  const memoKey = `${ds.commit}:${tier}`;
2902
3115
  // One Class A verdict per commit and tier for the whole list, pass or fail: the scope is every listed unit's
2903
3116
  // directory, so re-running it per unit after a failure would repeat the same red scans once per unit.
2904
3117
  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; }
2905
3118
  const scopes = shared ? shared.dirs : [unitDir];
2906
- 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);
3119
+ 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, snapshotLock: ds.lock })))(tier);
2907
3120
  if (shared) shared.memo.set(memoKey, code);
2908
3121
  return code;
2909
3122
  };
@@ -2923,7 +3136,7 @@ async function runUnitSnapshot(o, args, root, git, io, option) {
2923
3136
  if (await openSnapshotStage({ o, ds, root, stage, tag })) {
2924
3137
  try {
2925
3138
  code = stage === "check" ? await runCheck("compile") : await main(["--all", "--commit", ds.commit, "--snapshot", ds.path, "--scope", unitDir], {
2926
- ...io, cwd: root, readStdin: () => "", buildOwnership: own, classAEarlier: true, snapshotLedger: ds.ledger?.entries ?? [],
3139
+ ...io, cwd: root, readStdin: () => "", snapshotLock: ds.lock, classAEarlier: true, snapshotLedger: ds.ledger?.entries ?? [],
2927
3140
  onCompileLedger: (entries) => { ds.compileAdmitted = entries; }, [PRIVATE_SCOPED_COMPILE]: { selector, unitDir },
2928
3141
  });
2929
3142
  } catch (e) { o.err(`${tag} ${selector} ${stage}: ${e.message}`); code = 1; }
@@ -2936,14 +3149,14 @@ async function runUnitSnapshot(o, args, root, git, io, option) {
2936
3149
  }
2937
3150
  if (toolRun) {
2938
3151
  const { runUnitTool } = await import("../tool-build.mjs");
2939
- 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 ?? {},
3152
+ 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: unitEnvExtra, targetDirs: bound.targetDirs ?? {},
2940
3153
  resolve: (sel, r) => resolveUnit(sel, r, { granted: () => localBuildGrantedAt(source) }),
2941
3154
  ...(o.toolBuildDeps ?? {}), // test seam: run, enroll, dataRoot, readKnownRed
2942
3155
  stageGuard, check: runCheck, out: o.out, err: o.err,
2943
3156
  ...(reportOut ? { writeReport: (report) => o.writeFile(path.resolve(o.cwd, reportOut), `${JSON.stringify(o.brokerException ? { ...report, brokerException: o.brokerException } : report, null, 2)}\n`) } : {}),
2944
3157
  });
2945
3158
  }
2946
- 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,
3159
+ 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: unitEnvExtra, ciProofOut: option("--ci-proof-out") ?? null,
2947
3160
  resolve: (sel, r) => resolveUnit(sel, r, { granted: () => localBuildGrantedAt(source) }),
2948
3161
  ...(o.loadUnitOwner ? { loadOwner: o.loadUnitOwner } : {}),
2949
3162
  ...(o.unitGateDeps ?? {}), // test seam: fetchReceipt, stageCommands, verifyReceipts, selfGit
@@ -2952,8 +3165,7 @@ async function runUnitSnapshot(o, args, root, git, io, option) {
2952
3165
  });
2953
3166
  } finally { bound.cleanup(); }
2954
3167
  } finally {
2955
- const r = own.release();
2956
- if (r?.released === false && !own.joined) o.err(`${tag} build ownership ${own.handle} kept: ${r.why}`);
3168
+ releaseSeamLock({ o, release: taken.release, seamBody: started ? taken.body : null, tag });
2957
3169
  }
2958
3170
  }
2959
3171
 
@@ -2984,14 +3196,38 @@ async function runUnionSnapshot({ o, io, root, git, ds, union, unitListClassA })
2984
3196
  } catch (error) { o.err(`${tag} BLOCKED: cannot prepare unit-list scope: ${error.message}`); return 1; }
2985
3197
  if (!await openSnapshotStage({ o, ds, root, stage: "check", tag })) return 1;
2986
3198
  let check = 1;
2987
- 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"); }
3199
+ 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, snapshotLock: ds.lock, [UNIT_LIST_UNION]: union, ...((ds.ledger?.entries ?? []).length === 0 ? { snapshotProvedBefore: ds.path } : {}) })))("compile"); }
2988
3200
  catch (error) { o.err(`${tag} unit-list check: ${error.message}`); }
2989
3201
  if (!(await closeSnapshotStage({ o, ds, root, stage: "check", tag })).ok || check !== 0) return check || 1;
2990
3202
  if (!await openSnapshotStage({ o, ds, root, stage: "compile", tag })) return 1;
2991
3203
  let code = 1;
3204
+ // Crates build together (docs/design/2026-11-10-gate-fresh-design.md; Adrian, 2026-11-04: "RK has to build all it's necessary crates together"): a list of crates on a
3205
+ // broker host is compiled by gate/compile.mjs as a few Cargo calls naming every crate, each crate with its own result. RK_GATE_LEGACY_ROWS=1 keeps the per-crate rows
3206
+ // until the proof runs pass on both hosts; the legacy branch and that switch are then deleted together.
3207
+ let together = null;
3208
+ try {
3209
+ const ex = (o.resolveExecutor ?? gateResolveExecutor)({ env: o.env, platform: o.platform, exists: o.exists, which: whichIn(o), readFile: o.readFile });
3210
+ if (o.env.RK_GATE_LEGACY_ROWS !== "1" && ex?.kind === "broker" && union.selected.every((row) => row.selector.startsWith("cargo:"))) together = { client: brokerClientOf(o, ex) };
3211
+ } catch { together = null; }
3212
+ if (together) {
3213
+ try {
3214
+ const { compileTogether } = await import("../gate/compile.mjs");
3215
+ const verdictFile = path.join(path.dirname(path.dirname(path.resolve(ds.path))), "class-a-verdicts", verdictFileName({ commit: ds.commit, scope: unitListClassA.dirs, workspace: "." }));
3216
+ const run = await compileTogether({
3217
+ snapshot: path.resolve(ds.path), commit: ds.commit, crates: union.selected.map((row) => row.selector.slice("cargo:".length)), rustConfig: config.rust ?? {},
3218
+ platform: o.platform, client: together.client ?? "rustright", env: o.env, verdictFile, storeDir: `${path.resolve(ds.path)}.calls`,
3219
+ out: (line) => o.out(`${tag} ${line}`), onUnsettled: () => { seamRunState.unsettled += 1; },
3220
+ });
3221
+ union.fresh = { ...run, tree: ds.tree, platform: o.platform };
3222
+ code = run.code;
3223
+ } catch (error) { o.err(`${tag} unit-list compile (together): ${error.stack ?? error.message}`); code = 1; }
3224
+ const closedTogether = await closeSnapshotStage({ o, ds, root, stage: "compile", tag });
3225
+ union.verified = closedTogether.ok;
3226
+ return closedTogether.ok ? code : 1;
3227
+ }
2992
3228
  try {
2993
3229
  code = await main(["--all", "--commit", ds.commit, "--snapshot", ds.path, ...unitListClassA.dirs.flatMap((dir) => ["--scope", dir])], {
2994
- ...io, cwd: root, readStdin: () => "", buildOwnership: ds.own, classAEarlier: true, snapshotLedger: ds.ledger?.entries ?? [],
3230
+ ...io, cwd: root, readStdin: () => "", snapshotLock: ds.lock, classAEarlier: true, snapshotLedger: ds.ledger?.entries ?? [],
2995
3231
  onCompileLedger: (entries) => { ds.compileAdmitted = entries; }, [UNIT_LIST_UNION]: union,
2996
3232
  verifyUnionSnapshot: async () => { await verifyDoorSnapshot(o, ds, root, { ledger: ds.ledger?.entries ?? [] }); return true; },
2997
3233
  });
@@ -3024,21 +3260,18 @@ function sourceSplitOf({ root, ds, appDir }) {
3024
3260
 
3025
3261
  /**
3026
3262
  * Why the snapshot route cannot start on this host, or null. The route is the executor's: `direct` hosts (Linux always, any host
3027
- * with no broker) take it as they are. A broker host compiles the snapshot only through the RustRight snapshot carrier, which the
3028
- * gate reaches through `deps.snapshotBroker` (production wires it on Mac and Dell: `productionEntryDeps`); a gate started without
3029
- * it is refused (RK_SNAPSHOT_CARRIER_NOT_WIRED: tests only, never production), and a broker that cannot be reached is refused too
3030
- * (RK_SNAPSHOT_BROKER_UNAVAILABLE). Neither ever falls back to compiling the checkout.
3263
+ * with no broker) take it as they are. A broker host compiles the snapshot only through the seam (rustright cargo|run with the two seam variables, reset plan
3264
+ * section 3), and a broker that cannot be reached is refused (RK_SNAPSHOT_BROKER_UNAVAILABLE). Neither ever falls back to compiling the checkout.
3031
3265
  */
3032
3266
  export function snapshotRouteRefusal(o) {
3033
3267
  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); };
3034
3268
  const executor = (o.resolveExecutor ?? gateResolveExecutor)({ env: o.env, platform: o.platform, exists: o.exists, which, readFile: o.readFile });
3035
3269
  if (executor.kind === "refuse") return { code: "RK_SNAPSHOT_BROKER_UNAVAILABLE", message: executor.problem };
3036
- if (executor.kind === "broker" && !o.snapshotBroker) return { code: "RK_SNAPSHOT_CARRIER_NOT_WIRED", message: `a ${o.platform} host compiles a commit snapshot only through the RustRight snapshot carrier (item 7 rows 7.20 to 7.24), and this gate was started without it` };
3037
3270
  return null;
3038
3271
  }
3039
3272
 
3040
3273
  /** The refusal codes a route probe can answer with: the codes the stages themselves print (`BLOCKED: <code>: ...`). */
3041
- export const ROUTE_REFUSAL_CODES = Object.freeze(["RK_TAURI_CONFIG_OVERRIDE", "RK_STAGE_HOST_MISMATCH", "RK_SNAPSHOT_BROKER_UNAVAILABLE", "RK_SNAPSHOT_CARRIER_NOT_WIRED", "RK_BROKER_CAPABILITY_MISSING", "RK_BROKER_UNAVAILABLE",
3274
+ export const ROUTE_REFUSAL_CODES = Object.freeze(["RK_TAURI_CONFIG_OVERRIDE", "RK_STAGE_HOST_MISMATCH", "RK_SNAPSHOT_BROKER_UNAVAILABLE", "RK_BROKER_CAPABILITY_MISSING", "RK_BROKER_UNAVAILABLE",
3042
3275
  // One signing identity per product (rightkit#1303): the Mac and the Dell refuse an unsigned, ad hoc or re-identified test or dev build.
3043
3276
  ...SIGNING_REFUSAL_CODES,
3044
3277
  // The Mac's shared native helper list (targets.mac.macPackage.nativeHelpers) must validate before a Mac test, dev or package stage runs (rightkit#1308).
@@ -3047,66 +3280,6 @@ export const ROUTE_REFUSAL_CODES = Object.freeze(["RK_TAURI_CONFIG_OVERRIDE", "R
3047
3280
  export const ROUTE_PROBE_STAGES = Object.freeze(["check", "compile", "package", "qualify", "dev", "test", "render"]);
3048
3281
  export const ROUTE_SCHEMA = "rightkit-gate.route/1";
3049
3282
 
3050
- /**
3051
- * The capabilities a broker must advertise for the carried stages (rightkit#1301 B2). RustRight reports them in `rustright doctor --json`
3052
- * as `.broker.capabilities` (the HANDSHAKE's `capabilities`: `journal-v1`, `snapshot-readonly-v1`, `snapshot-adapter-v1`, ...; constants
3053
- * in rustright-protocol response.rs). The two required strings ship with RustRight's upcoming change: today's broker (78eda7e) reports no
3054
- * `.broker.capabilities`, so this release refuses every stage that builds until that broker is installed. `snapshot-adapter-v1`
3055
- * (rustright#190, rightkit#1301 B10) is the broker's acceptance of a snapshot-bound adapter job (pnpm, node, QA) inside a gate snapshot,
3056
- * under which a Tauri CLI's compiles run nested: without it every pnpm step of a snapshot stage (an app's dev and package steps, an npm
3057
- * unit's compile and package) is refused by the broker, so the gate refuses first. `stage-grant-v1` is no longer required: the gate mints
3058
- * no stage grant (one model: every compile of a snapshot stage is a carried request or nested under one).
3059
- */
3060
- export const REQUIRED_BROKER_CAPABILITIES = Object.freeze(["snapshot-readonly-v1", "snapshot-adapter-v1"]);
3061
-
3062
- /**
3063
- * The broker's capabilities, asked without a build through `rustright doctor --json`: `{ ok: true, capabilities }` or `{ ok: false, problem }`.
3064
- * A missing client, a client that cannot run, a hung (20 s), unparsable or field-less answer is `ok: false`, which the route refuses (fail
3065
- * closed). A doctor that reports an unhealthy host still prints its JSON: the field decides, not the exit status.
3066
- */
3067
- export function queryBrokerCapabilities(o, { executor = null } = {}) {
3068
- const client = brokerClientOf(o, executor);
3069
- if (!client) return { ok: false, problem: "the RustRight client is not on PATH" };
3070
- const r = spawnBrokerClient(o.spawn, client, ["doctor", "--json"], { env: brokerEnvOf(o, executor), encoding: "utf8", timeout: 20_000, windowsHide: true }, { platform: o.platform ?? process.platform, readFile: o.readFile });
3071
- if (r?.error || r?.status === null || r?.status === undefined) return { ok: false, problem: `\`rustright doctor --json\` did not finish: ${why(r)}` };
3072
- let doc;
3073
- try { doc = JSON.parse(text(r)); } catch { return { ok: false, problem: `\`rustright doctor --json\` printed no JSON${r.status ? ` (exit ${r.status})` : ""}` }; }
3074
- const caps = doc?.broker?.capabilities;
3075
- if (!Array.isArray(caps) || !caps.every((c) => typeof c === "string")) return { ok: false, problem: "`rustright doctor --json` reports no `.broker.capabilities` (a broker that predates snapshot-readonly-v1 and snapshot-adapter-v1)" };
3076
- // The list is the broker's HANDSHAKE.capabilities only when the client received that handshake: an unreachable broker (doctor reports an empty list for it) advertises nothing, which is a
3077
- // different statement from a broker that advertises few capabilities, so it is a problem naming why, never a list. Each name is advertised once.
3078
- if (doc.broker.reachable !== true) return { ok: false, problem: `the broker is not reachable, so its HANDSHAKE.capabilities were not received (\`rustright doctor --json\` .broker.reachable is ${JSON.stringify(doc.broker.reachable ?? null)}${typeof doc.broker.error === "string" && doc.broker.error ? `: ${doc.broker.error}` : ""})` };
3079
- if (new Set(caps).size !== caps.length) return { ok: false, problem: "`rustright doctor --json` lists a capability twice: the broker's HANDSHAKE.capabilities are not read from an answer that repeats itself" };
3080
- return { ok: true, capabilities: caps };
3081
- }
3082
-
3083
- /**
3084
- * What a route decision needs of the broker: `null` when nothing is asked (not a broker executor, hosted CI, `--to check`, or a gate
3085
- * whose broker is an injected fixture without a declared capability query), else the answer. The production carrier asks the real
3086
- * client; a test's injected broker declares its own through `o.brokerCapabilities`.
3087
- */
3088
- export function brokerCapabilityState(o, { to, executor }) {
3089
- if (executor?.kind !== "broker" || to === "check" || o.env.GITHUB_ACTIONS === "true") return null;
3090
- if (typeof o.brokerCapabilities === "function") return o.brokerCapabilities(o);
3091
- return typeof o.snapshotBroker?.create === "function" ? queryBrokerCapabilities(o, { executor }) : null;
3092
- }
3093
-
3094
- /**
3095
- * GB-51 / GB-62: the capability state a route plans from, with the broker's HANDSHAKE received by the gate itself (broker-handshake.mjs) beside `rustright doctor --json`: both are asked, they must agree,
3096
- * and a plan sees only names advertised by what answered. Not asked (null) exactly when `brokerCapabilityState` asks nothing; an injected fixture broker that declares its own capabilities
3097
- * (`o.brokerCapabilities`) keeps them unless it also declares a handshake (`o.brokerHandshake`, a function returning a parsed handshake or `{ ok: false, problem }`).
3098
- */
3099
- export async function brokerCapabilityStateWithHandshake(o, { to, executor }) {
3100
- const doctor = brokerCapabilityState(o, { to, executor });
3101
- if (doctor === null) return null;
3102
- const injected = typeof o.brokerHandshake === "function";
3103
- if (!injected && typeof o.brokerCapabilities === "function") return doctor;
3104
- let handshake;
3105
- try {
3106
- handshake = injected ? await o.brokerHandshake(o) : await queryBrokerHandshake({ ...o, env: brokerEnvOf(o, executor) }, { client: brokerClientOf(o, executor) });
3107
- } catch (error) { handshake = { ok: false, problem: `the broker's HANDSHAKE could not be read (${error?.message ?? error})` }; }
3108
- return mergeCapabilityViews({ doctor, handshake });
3109
- }
3110
3283
 
3111
3284
  /**
3112
3285
  * The refusal of `--to release` on a host that is not the trusted publisher, or null: a release uploads sealed bytes and runs only in the release workflow's
@@ -3132,7 +3305,7 @@ export function releaseRouteRefusal(o, { stages, platform }) {
3132
3305
  * `executor` is a resolved executor. Returns { route, refusal } with
3133
3306
  * refusal null or { code, stage, message }. Reads no checkout, takes no ownership, syncs no snapshot and spawns nothing itself.
3134
3307
  */
3135
- export function routePlan(o, { to, stages, devTest, executor, capabilities = null, appConfig = null, stagePlatform = null }) {
3308
+ export function routePlan(o, { to, stages, devTest, executor, appConfig = null, stagePlatform = null }) {
3136
3309
  const refuse = (code, stage, message) => ({ code, stage, message });
3137
3310
  const hosted = o.env.GITHUB_ACTIONS === "true";
3138
3311
  const snapshot = !hosted && snapshotRouteSelected(o);
@@ -3148,18 +3321,8 @@ export function routePlan(o, { to, stages, devTest, executor, capabilities = nul
3148
3321
  }
3149
3322
  const refused = to === "check" ? null : snapshotRouteRefusal(o);
3150
3323
  if (refused) return { route, refusal: refuse(refused.code, to, refused.message) };
3151
- // The broker must accept what the carried stages ask of it (rightkit#1301 B2): a missing or failing capability query refuses.
3152
- if (capabilities && executor?.kind === "broker" && to !== "check") {
3153
- const missing = capabilities.ok ? REQUIRED_BROKER_CAPABILITIES.filter((c) => !capabilities.capabilities.includes(c)) : REQUIRED_BROKER_CAPABILITIES;
3154
- if (!capabilities.ok || missing.length) return { route, refusal: refuse("RK_BROKER_CAPABILITY_MISSING", to, `the broker ${capabilities.ok ? `does not advertise ${missing.join(", ")}` : `cannot be asked for its capabilities (${capabilities.problem})`} (\`rustright doctor --json\` \`.broker.capabilities\`); this release builds only against a broker that accepts snapshot-bound read-only Cargo and snapshot-bound adapter jobs (rightkit#1301, rustright#188, rustright#190)`) };
3155
- }
3156
- }
3157
- // GB-51: a declared native build tool with no carried adapter (xcodegen, xcodebuild, Gradle, CMake) refuses here, at planning, naming the missing
3158
- // capability, instead of after the earlier stages built (the door's launch-time refusal remains the backstop).
3159
- if (snapshot && executor?.kind === "broker" && appConfig?.config && to !== "check") {
3160
- const refusalText = nativeToolRefusal(nativeToolUses({ config: appConfig.config, to, devPlatform: appConfig.nativePlatform ?? appConfig.devPlatform ?? null, platform: appConfig.nativePlatform ?? null }), { capabilities, readFile: appConfig.readFile ?? null, listFiles: appConfig.listFiles ?? null });
3161
- if (refusalText) return { route, refusal: refuse("RK_BROKER_CAPABILITY_MISSING", to, refusalText) };
3162
3324
  }
3325
+ // No capability query (reset plan section 3): a native tool whose adapter the broker does not register is refused by the broker before it spawns anything (RK_ADAPTER_UNKNOWN).
3163
3326
  // One signing identity per product, every build (rightkit#1303): on the Mac and the Dell a test or dev build that would run unsigned, ad hoc or under
3164
3327
  // another identifier is refused here, from the commit's own config, so `--route` and a real run decide alike. Linux and hosted CI are exempt.
3165
3328
  if (snapshot && appConfig?.config && (to === "test" || to === "dev")) {
@@ -3226,8 +3389,7 @@ async function runRouteProbe(o, args, root, git, { to, platform, stages, devTest
3226
3389
  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); };
3227
3390
  const executor = (o.resolveExecutor ?? gateResolveExecutor)({ env: o.env, platform: o.platform, exists: o.exists, which, readFile: o.readFile });
3228
3391
  let plan;
3229
- const capabilities = await brokerCapabilityStateWithHandshake(o, { to, executor });
3230
- try { plan = routePlan(o, { to, stages, devTest, executor, stagePlatform: platform, capabilities, appConfig: to !== "check" ? routeAppConfig({ git, commit: selected.commit, appDir, platform: devTestPlatform(args) }) : null }); }
3392
+ try { plan = routePlan(o, { to, stages, devTest, executor, stagePlatform: platform, appConfig: to !== "check" ? routeAppConfig({ git, commit: selected.commit, appDir, platform: devTestPlatform(args) }) : null }); }
3231
3393
  catch (e) { o.err(`${tag} ${e.message}`); return 2; }
3232
3394
  // The declared Linux broker's snapshot root: the probe reports the refusal a real run would meet (read-only: one status probe of the broker).
3233
3395
  if (!plan.refusal && plan.route === "snapshot") {
@@ -3240,13 +3402,13 @@ async function runRouteProbe(o, args, root, git, { to, platform, stages, devTest
3240
3402
  const version = JSON.parse(fs.readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
3241
3403
  o.out(JSON.stringify({
3242
3404
  schema: ROUTE_SCHEMA, gate: version, to, platform: platform ?? null, host: o.platform, app: appDir, commit: selected.commit,
3243
- executor: executor.kind, carrier: o.snapshotBroker ? (o.snapshotBroker.kind ?? "injected") : null, route: plan.route,
3244
- brokerCapabilities: capabilities?.ok ? capabilities.capabilities : null, stages: devTest ? ["check", to] : stages, refusal: plan.refusal, checkoutClean: failed(dirty) ? null : !text(dirty).trim(),
3405
+ executor: executor.kind, route: plan.route,
3406
+ stages: devTest ? ["check", to] : stages, refusal: plan.refusal, checkoutClean: failed(dirty) ? null : !text(dirty).trim(),
3245
3407
  }));
3246
3408
  return 0;
3247
3409
  }
3248
3410
 
3249
- // ---- the carrier of a snapshot stage's right-release children (carried-cargo.mjs; rightkit#1301) --------------------------------------
3411
+ // ---- the carrier of a snapshot stage's right-release children (stage-seam.mjs; rightkit#1301) --------------------------------------
3250
3412
 
3251
3413
  /**
3252
3414
  * The environment of a carried stage's child: the base, the stage's carrier and the caller's extras, without an output directory.
@@ -3267,8 +3429,8 @@ export function carriedEnv(carrier, base, extra = {}) {
3267
3429
 
3268
3430
  // ---- the declared Linux broker's snapshot root --------------------------------------------------------------------------------------------------
3269
3431
  // The broker admits a snapshot only under `<its data root>/snapshots`. On Linux the gate's snapshot root is `~/.config/rightkit/gate.json` `snapshotRoot`, else
3270
- // `~/.local/state/rightkit/snapshots` (snapshot.mjs snapshotRoot); a host whose broker keeps its data elsewhere would sync thousands of files, take build ownership and submit,
3271
- // only to be refused at admission with the ownership left unknown. So the declared route compares the two BEFORE ownership or a sync, and refuses typed.
3432
+ // `~/.local/state/rightkit/snapshots` (snapshot.mjs snapshotRoot); a host whose broker keeps its data elsewhere would sync thousands of files, take the snapshot lock and submit,
3433
+ // only to be refused at admission. So the declared route compares the two BEFORE the lock or a sync, and refuses typed.
3272
3434
  export const LINUX_SNAPSHOT_ROOT_MISMATCH = "RK_LINUX_BROKER_SNAPSHOT_ROOT_MISMATCH";
3273
3435
  const ANSWERING_ROOTS_TIMEOUT_MS = 10_000;
3274
3436
 
@@ -3363,7 +3525,7 @@ export async function declaredSnapshotRootRefusal(o, executor, snapshotsAt) {
3363
3525
  const real = (p) => { try { return fs.realpathSync.native(p); } catch { return path.resolve(p); } };
3364
3526
  const expected = path.join(dataRoot, "snapshots");
3365
3527
  if (real(expected) === real(snapshotsAt)) return null;
3366
- return { code: LINUX_SNAPSHOT_ROOT_MISMATCH, message: `the gate's snapshot root is ${snapshotsAt}, but the declared Linux broker admits snapshots only under ${expected} (${basis}); set "snapshotRoot": ${JSON.stringify(expected)} in ~/.config/rightkit/gate.json (the gate host configuration), then run again. Nothing was synced and no build ownership was taken` };
3528
+ return { code: LINUX_SNAPSHOT_ROOT_MISMATCH, message: `the gate's snapshot root is ${snapshotsAt}, but the declared Linux broker admits snapshots only under ${expected} (${basis}); set "snapshotRoot": ${JSON.stringify(expected)} in ~/.config/rightkit/gate.json (the gate host configuration), then run again. Nothing was synced and no snapshot lock was taken` };
3367
3529
  }
3368
3530
 
3369
3531
  /** The RustRight client this executor drives: the declared Linux route's validated client, else the absolute `rustright` on PATH (Mac, Dell). */
@@ -3373,21 +3535,25 @@ const brokerEnvOf = (o, executor) => (executor?.route === LINUX_BROKER_ROUTE &&
3373
3535
  const whichIn = (o) => (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); };
3374
3536
 
3375
3537
  /**
3376
- * The gate's snapshot broker for this door run: `o.snapshotBroker` is the production carrier statement (`{ kind, create }`, which
3377
- * builds the broker once: the host's enrolled pins, the declared inputs read from the snapshot, the build ownership and the RustRight
3378
- * client) or, in a test, a ready broker object. Built once per door run.
3538
+ * The broker of one door run for the seam (reset plan section 3), as plain data the stage map and the runtime cargo wrapper carry: the RustRight client by absolute path (the
3539
+ * win32 `.cmd` shim resolved once, so no child resolves or spawns a .cmd: broker-client.mjs), the commit, the snapshot, the primary checkout, the broker's managed `ws` output roots
3540
+ * (the generation targets a test executable must lie in) and the platform. The gate knows nothing else of the broker; the client builds whatever framing it speaks.
3379
3541
  */
3380
- async function carrierBroker({ o, root, ds, executor = null, which = whichIn(o) }) {
3381
- if (ds.carrierBroker) return ds.carrierBroker;
3382
- const carrier = o.snapshotBroker;
3383
- let sb = carrier;
3384
- if (typeof carrier?.create === "function") {
3385
- const client = executor?.route === LINUX_BROKER_ROUTE && executor.kind === "broker" ? executor.client : which("rustright").find((c) => path.isAbsolute(c));
3386
- const { brokerLeaseState } = await import("../build-ownership.mjs");
3387
- sb = carrier.create({ lease: brokerLeaseState, env: brokerEnvOf(o, executor), platform: o.platform, checkout: root, commit: { sha: ds.commit, tree: ds.tree }, snapshot: { path: ds.path, expectedTree: ds.tree }, ownership: ds.own, client, gateFile: callingGatePath(), spawn: o.spawn });
3388
- }
3389
- ds.carrierBroker = sb;
3390
- return sb;
3542
+ function seamBrokerOf({ o, root, executor = null, commit, snapshot, which = whichIn(o) }) {
3543
+ const found = executor?.route === LINUX_BROKER_ROUTE && executor.kind === "broker" ? executor.client : which("rustright").find((c) => path.isAbsolute(c));
3544
+ if (typeof found !== "string" || !(o.platform === "win32" ? path.win32 : path).isAbsolute(found)) throw Object.assign(new Error("a broker snapshot compile needs the RustRight client (`rustright`) by absolute path"), { code: "RK_SNAPSHOT_BROKER" });
3545
+ let client;
3546
+ try { client = resolveBrokerClient(found, { platform: o.platform }).file; } catch (e) { throw Object.assign(new Error(e.message), { code: e.code ?? "RK_BROKER_CLIENT_UNRESOLVED" }); }
3547
+ return {
3548
+ client, commit: { sha: commit.sha, tree: commit.tree }, snapshot: { path: snapshot.path, expectedTree: snapshot.expectedTree }, checkout: fs.realpathSync.native(root),
3549
+ outputRoots: [path.join(resolveManagedRoots({ env: o.env, platform: o.platform }).buildControl, "ws")], platform: o.platform,
3550
+ };
3551
+ }
3552
+ /** The seam broker of the door run's snapshot, built once per run. */
3553
+ async function seamBrokerFor({ o, root, ds, executor = null, which = whichIn(o) }) {
3554
+ if (ds.seamBroker) return ds.seamBroker;
3555
+ ds.seamBroker = seamBrokerOf({ o, root, executor, commit: { sha: ds.commit, tree: ds.tree }, snapshot: { path: ds.path, expectedTree: ds.tree }, which });
3556
+ return ds.seamBroker;
3391
3557
  }
3392
3558
 
3393
3559
  /** The commit's Cargo workspaces in the snapshot, each with its counterpart in the primary checkout: `{ [cargoDir]: checkout path }`, from the files alone. */
@@ -3414,48 +3580,52 @@ async function snapshotCargoWorkspaces({ git, ds, root }) {
3414
3580
  * child's environment; `finish` runs after the child ended, fails on any call that was refused, unverified or unfinished and on any
3415
3581
  * receipt the gate cannot verify again itself, and removes the carrier. A direct executor, or no snapshot, has nothing to carry.
3416
3582
  */
3417
- async function carrierForChildren({ o, ds, root, git, executor, stage, tag = "rightkit-gate:", producer = false }) {
3583
+ /**
3584
+ * The seam's two variables for a door stage's children (reset plan section 3): the commit and the root verdict the door's class A wrote for its scope (`[appDir]`, or
3585
+ * full for an app at the repository root). Every child of every stage with a carrier gets them (rightRelease, the sidecar and Windows identity producers, dev and test),
3586
+ * so its pnpm, node, QA and cargo calls go through the seam, each naming its own directory's verdict (seam-broker.mjs verdictForCwd). Empty off a broker snapshot.
3587
+ */
3588
+ function seamStageEnvOf({ ds, executor, appDir = "." }) {
3589
+ if (!ds || executor?.kind !== "broker" || !/^[0-9a-f]{40}$/.test(String(ds.commit))) return {};
3590
+ return { RUSTRIGHT_GATE_COMMIT: ds.commit, RUSTRIGHT_CLASS_A: path.join(path.dirname(path.dirname(path.resolve(ds.path))), "class-a-verdicts", verdictFileName({ commit: ds.commit, scope: appDir === "." ? null : [appDir], workspace: "." })) };
3591
+ }
3592
+
3593
+ async function carrierForChildren({ o, ds, root, git, executor, stage, tag = "rightkit-gate:", appDir = "." }) {
3418
3594
  const none = { env: {}, carried: false, refusal: null, async finish() { return true; }, cleanup() {} };
3419
3595
  if (!ds || executor?.kind !== "broker") return none;
3420
3596
  let base = null;
3421
3597
  try {
3422
3598
  if (!git) throw new Error("the gate's git reader is missing");
3423
- const carried = await import("../carried-cargo.mjs");
3424
- const { brokerSection } = await import("../snapshot-broker.mjs");
3425
- const sb = await carrierBroker({ o, root, ds, executor });
3426
- // Only a PRODUCER carrier (the gate's own web-build, windows-identity and stage-sidecar steps, which write declared inputs by design) takes the gate's digest of the
3427
- // declared inputs at stage open (absent included); the end-of-stage ledger re-verify then accepts any receipt state for an input that digest says the step changed.
3428
- // Every other carrier passes none: each receipt, adapter receipts included, must equal the stage-end digest of every declared input (strict), so a child that swaps
3429
- // an input around an admission and restores it is refused. A malformed declaration or an unreadable input is the refusal below, as before.
3430
- let openInputDigests = null;
3431
- if (producer) {
3432
- const { readDeclaredInputs: readInputsOf, declaredInputDigestsOf: digestInputsOf } = await import("../snapshot-request.mjs");
3433
- openInputDigests = digestInputsOf(ds.path, readInputsOf(ds.path), { allowAbsent: true });
3434
- }
3435
- // Installing the carrier map sends nothing, so it records nothing: the child's own uncarried probes (`rustc -vV`, `--version`) never
3436
- // reach the broker under a snapshot, and each carried request records its sub-handle just before it is sent (snapshot-broker.mjs).
3599
+ const { installStageCarrier } = await import("../stage-seam.mjs");
3600
+ const sb = await seamBrokerFor({ o, root, ds, executor });
3601
+ // Installing the stage map sends nothing, so it records nothing: each seam call a child makes is filed in the stage ledger as pending before it is sent (stage-seam.mjs).
3437
3602
  const checkoutDirs = await snapshotCargoWorkspaces({ git, ds, root });
3438
3603
  base = fs.mkdtempSync(path.join(os.tmpdir(), "rk-carrier-"));
3439
- // The carrier is the map and the ledger on every platform: no PATH wrapper and no stage grant. The child's pnpm, node and QA steps are carried
3440
- // adapter jobs and its Cargo calls carried requests; whatever the Tauri CLI compiles runs nested under the adapter job that started it, and the
3441
- // broker's signed list of those children is what the gate verifies and reads the bundle root from (carried-cargo.mjs).
3442
- const installed = (o.installCarrier ?? carried.installCarrier)({ base, snapshotRoot: ds.path, checkoutDirs, section: (o.brokerSection ?? brokerSection)(sb), known: Object.fromEntries(ds.carriedOutputs ?? []), platform: o.platform, env: o.env });
3443
- o.out(`${tag} [${stage}] carrier (${installed.mode}): ${Object.keys(checkoutDirs).length} workspace(s); each right-release cargo call and each pnpm, node or QA step is one carried request with its own signed receipt, and a compile a step's child makes is nested under it`);
3604
+ // The stage's carrier is the map and the ledger on every platform: no PATH wrapper and no stage grant. The child's pnpm, node and QA steps are seam adapter calls and its
3605
+ // Cargo calls seam calls; whatever the Tauri CLI compiles runs under the adapter job that started it, and the receipt's output directory is where the gate reads the bundle root (stage-seam.mjs).
3606
+ const installed = (o.installCarrier ?? installStageCarrier)({ base, snapshotRoot: ds.path, checkoutDirs, section: sb, known: Object.fromEntries(ds.carriedOutputs ?? []), platform: o.platform, env: o.env });
3607
+ o.out(`${tag} [${stage}] carrier (${installed.mode}): ${Object.keys(checkoutDirs).length} workspace(s); each right-release cargo call and each pnpm, node or QA step is one seam call filed in the stage ledger, with the broker's receipt read for it`);
3444
3608
  let finished = false;
3445
3609
  const cleanup = () => { try { installed.cleanup?.(); } catch { /* removed below */ } fs.rmSync(base, { recursive: true, force: true }); };
3610
+ // The stage's children may make seam calls from here on: the door's lock waits until this stage's finish has counted them (seamRunState.open; a stage that never
3611
+ // reaches its finish leaves it raised and the lock kept).
3612
+ seamRunState.open += 1;
3446
3613
  return {
3447
- env: installed.env, carried: true, refusal: null, cleanup,
3614
+ env: { ...installed.env, ...seamStageEnvOf({ ds, executor, appDir }) }, carried: true, refusal: null, cleanup,
3448
3615
  async finish({ stage: at = stage } = {}) {
3449
3616
  if (finished) return true;
3450
3617
  finished = true;
3451
- let problems;
3618
+ let problems; let counted = false;
3452
3619
  try {
3453
- problems = await installed.problems(sb, openInputDigests ? { openInputDigests } : {});
3620
+ problems = await installed.problems();
3621
+ // A child's seam call with no settled outcome may have left a broker job running: the door then keeps its snapshot lock (reset plan section 3).
3622
+ seamRunState.unsettled += installed.seamUnsettled?.() ?? 0;
3623
+ seamRunState.open -= 1; counted = true;
3454
3624
  // The output directories the stage's verified receipts name: the package stage's sealed manifest must record only these.
3455
3625
  for (const dir of installed.outputDirs?.() ?? []) ((ds.carriedByStage ??= {})[at] ??= new Set()).add(dir);
3456
3626
  // And by workspace, for the next stage's children: a receipt already names the output directory, so none asks Cargo for it.
3457
3627
  for (const [root, dir] of installed.outputsByWorkspace?.() ?? []) (ds.carriedOutputs ??= new Map()).set(root, dir);
3458
- } catch (error) { problems = [`the cargo ledger cannot be read (${error.message})`]; } finally { cleanup(); }
3628
+ } catch (error) { problems = [`the cargo ledger cannot be read (${error.message})`]; seamRunState.unsettled += 1; /* the children's seam outcomes are unknown: keep the lock */ if (!counted) seamRunState.open -= 1; } finally { cleanup(); }
3459
3629
  for (const p of problems.slice(0, 10)) o.err(`${tag} RK_CHECK_ERROR: [${at}] a broker call the right-release child made did not complete: ${typeof p === "string" ? p : JSON.stringify(p)}`);
3460
3630
  return problems.length === 0;
3461
3631
  },
@@ -3539,7 +3709,7 @@ export async function runRenderStage({ o, ds, root, appDir, commit, tree, env, p
3539
3709
  /**
3540
3710
  * rightkit-gate --to dev|test [--commit <rev>] [-- <right-release dev|test arguments>]: the local compiles, on a commit like every other
3541
3711
  * stage (docs/GATE-CONTRACT.md "Commit-only build": `--to dev` and `--to test` build a commit; `--worktree` never admits a build). The
3542
- * door has selected the commit and synced its snapshot under ownership (runStages); this runs full class A of that snapshot
3712
+ * door has selected the commit and synced its snapshot under the snapshot lock (runStages); this runs full class A of that snapshot
3543
3713
  * (`check --commit <sha> --full-a --snapshot <dir>`, never `--worktree`), then right-release dev|test with the snapshot's app root as
3544
3714
  * its cwd under a live door run, which carries the source split. Hosted CI, whose runner checkout is the commit, keeps its own
3545
3715
  * clean checkout. The snapshot is verified before right-release starts and after it ends (E6): a result that covers no known bytes
@@ -3569,7 +3739,7 @@ async function runDevTest(o, args, root, git, io, to, appRoot, appDir) {
3569
3739
  if (executor.kind === "refuse") { o.err(`${tag} BLOCKED: ${executor.problem}`); return 1; }
3570
3740
  o.out(`${tag} --to ${to} for ${commit.slice(0, 12)}${appDir === "." ? "" : ` (app ${appDir})`}: check (class A) -> right-release ${to}; executor ${executor.kind}${ds ? `; snapshot ${ds.path}` : ""}`);
3571
3741
  // Full class A of the commit before right-release compiles anything: of the snapshot, the checks that execute repository code included.
3572
- const checked = await (o.runCheck ?? (() => main(["check", "--commit", ds ? commit : "HEAD", "--full-a", ...(ds ? ["--snapshot", ds.path] : []), ...(appDir === "." ? [] : ["--scope", appDir])], { ...io, cwd: root, ...(ds ? { buildOwnership: ds.own } : {}) })))();
3742
+ const checked = await (o.runCheck ?? (() => main(["check", "--commit", ds ? commit : "HEAD", "--full-a", ...(ds ? ["--snapshot", ds.path] : []), ...(appDir === "." ? [] : ["--scope", appDir])], { ...io, cwd: root, ...(ds ? { snapshotLock: ds.lock } : {}) })))();
3573
3743
  if (checked !== 0) { o.err(`${tag} --to ${to} stopped at check: nothing compiled`); return 1; }
3574
3744
  // The snapshot is exactly tree + dependencies + the ledger before right-release starts; what it wrote may remain only as ledger
3575
3745
  // entries (a generated `gen/schemas`, a dist), recorded by this gate's own walk (stage-ledger.mjs, decision 2 Q1).
@@ -3614,7 +3784,7 @@ async function runDevTest(o, args, root, git, io, to, appRoot, appDir) {
3614
3784
  if (!staged) { o.err(`${tag} --to ${to} stopped: the declared sidecars could not be staged; nothing compiled`); return 1; }
3615
3785
  }
3616
3786
  // right-release dev and test, and the Tauri CLI and every other child they start, reach Cargo only through the stage's carrier on a broker host.
3617
- const carrier = await carrierForChildren({ o, ds, root, git, executor, stage: to, tag });
3787
+ const carrier = await carrierForChildren({ o, ds, root, git, executor, stage: to, tag, appDir });
3618
3788
  if (carrier.refusal) { o.err(`${tag} BLOCKED: ${carrier.refusal}; nothing compiled`); return 1; }
3619
3789
  const run = startRun({ commonDir, commit, tree, stage: to, ...(source ? { source } : {}) });
3620
3790
  try {
@@ -3632,9 +3802,16 @@ async function runDevTest(o, args, root, git, io, to, appRoot, appDir) {
3632
3802
  if (ds && !(await closeSnapshotStage({ o, ds, root, stage: to, step: to, tag })).ok) { o.err(`${tag} --to ${to} stopped: the result covers no known bytes`); return 2; }
3633
3803
  return rendered === 0 && carriedRendered ? 0 : 1;
3634
3804
  }
3635
- const r = (o.spawnInherit ?? inheritLaunch)(process.execPath, [cli, to, ...passthrough], { cwd: source ? snapshotAppRootOf(ds.path, appDir) : appRoot, env: childEnv });
3805
+ // rightkit#1555: beside (never inside) the snapshot, a fixed name per snapshot, so no run-specific value reaches a key.
3806
+ // Only the Windows dev install signs staged copies in place (install-tauri-authenticode.mjs); no other route names or reads a report.
3807
+ const signedReport = ds && to === "dev" && o.platform === "win32" ? `${ds.path}.signed-in-place.json` : null;
3808
+ if (signedReport) { try { fs.rmSync(signedReport, { force: true }); } catch { /* a stale report is refused below by its digests */ } }
3809
+ const r = (o.spawnInherit ?? inheritLaunch)(process.execPath, [cli, to, ...passthrough], { cwd: source ? snapshotAppRootOf(ds.path, appDir) : appRoot, env: signedReport ? { ...childEnv, RIGHTKIT_SIGNED_IN_PLACE_REPORT: signedReport } : childEnv });
3636
3810
  const carriedOk = await carrier.finish({ stage: to });
3637
- if (ds && !(await closeSnapshotStage({ o, ds, root, stage: to, step: to, tag })).ok) { o.err(`${tag} --to ${to} stopped: the result covers no known bytes`); return 2; }
3811
+ let signedInPlace = new Map();
3812
+ // Only a right-release dev that succeeded wrote its report last; a failed one is read as no report (every staged change then refuses).
3813
+ if (signedReport && r.status === 0) { try { signedInPlace = readSignedInPlaceReport(signedReport, ds.path); await assertSignedInPlaceSigned(o, ds.path, signedInPlace); } catch (e) { o.err(`${tag} RK_CHECK_ERROR: [${to}] ${e.message}`); return 2; } }
3814
+ if (ds && !(await closeSnapshotStage({ o, ds, root, stage: to, step: to, tag, signedInPlace })).ok) { o.err(`${tag} --to ${to} stopped: the result covers no known bytes`); return 2; }
3638
3815
  return r.status === 0 && carriedOk ? 0 : 1;
3639
3816
  } finally { endRun(run); carrier.cleanup(); try { pinMulti?.cleanup?.(); } catch { /* the wrapper map is the gate's own temp directory */ } }
3640
3817
  }
@@ -3705,7 +3882,7 @@ export async function main(argv, io = {}) {
3705
3882
  const problem = stageArgsProblem(args);
3706
3883
  if (problem) throw new Error(problem);
3707
3884
  const value = (flag) => { const i = args.indexOf(flag); return i < 0 ? null : args[i + 1]; };
3708
- 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");
3885
+ 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") throw new Error("--ci-proof-out requires the single cargo:rightkit-decimal snapshot compile route");
3709
3886
  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");
3710
3887
  const paths = o.platform === "win32" ? path.win32 : path.posix;
3711
3888
  const scratch = o.platform === "win32" ? "D:\\scratch" : "/Volumes/D/scratch";
@@ -3719,20 +3896,8 @@ export async function main(argv, io = {}) {
3719
3896
  catch (error) { if (error.code !== "ENOENT") throw error; }
3720
3897
  } catch (error) { o.err(`rightkit-gate: ${error.message}`); return 2; }
3721
3898
  }
3722
- const widthFlags = args.reduce((found, arg, i) => arg === "--cargo-jobs" ? [...found, i] : found, []);
3723
- if (widthFlags.length) {
3724
- try {
3725
- if (widthFlags.length !== 1 || io[CARGO_WIDTH] !== undefined) throw new Error("--cargo-jobs may be given once");
3726
- const index = widthFlags[0];
3727
- if (args.includes("--") && index > args.indexOf("--")) throw new Error("--cargo-jobs must precede --");
3728
- const width = parseCargoWidth(args[index + 1]);
3729
- const routeProblem = cargoWidthRouteProblem(args);
3730
- if (routeProblem) throw new Error(routeProblem);
3731
- args.splice(index, 2);
3732
- io = { ...io, [CARGO_WIDTH]: width };
3733
- o[CARGO_WIDTH] = width;
3734
- } catch (error) { o.err(`rightkit-gate: ${error.message}`); return 2; }
3735
- }
3899
+ // `--cargo-jobs` is retired (reset plan step 5): the broker decides how many cargo processes run, and a result key never carries a width (the stored command is compared with `--jobs` dropped).
3900
+ if (args.includes("--cargo-jobs")) { o.err("rightkit-gate: --cargo-jobs is retired: the broker decides how many cargo processes run and no result key carries a width; run again without it"); return 2; }
3736
3901
  // 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
3737
3902
  // rebuilt from broker receipts. Machine-readable output is never stamped: the --route JSON, a list or baseline, --json, the version, and the one
3738
3903
  // `verdict deterministic` marker line other tools read.
@@ -3767,7 +3932,12 @@ export async function main(argv, io = {}) {
3767
3932
  // `--verify --env <digest>` also requires the installed dependency environment to still be the digest `env-digest --snapshot` recorded.
3768
3933
  if (args[0] === "snapshot") {
3769
3934
  const sc = await import("../snapshot-check.mjs");
3770
- return (await import("../snapshot.mjs")).snapshotCommand(o, args.slice(1), { environmentDigest: ({ checkout, dir, commit }) => classAEnvironmentDigest({ root: dir, gatePackage: o.gatePackage, files: sc.commitFiles(checkout, commit, o.spawn).files, spawn: o.spawn }) });
3935
+ const snapMod = await import("../snapshot.mjs");
3936
+ return snapMod.snapshotCommand(o, args.slice(1), {
3937
+ environmentDigest: ({ checkout, dir, commit }) => classAEnvironmentDigest({ root: dir, gatePackage: o.gatePackage, files: sc.commitFiles(checkout, commit, o.spawn).files, spawn: o.spawn }),
3938
+ // The sync takes the snapshot lock like every route: the seam body and broker proof on a broker host, the legacy lock elsewhere.
3939
+ lockFor: ({ checkout, commit, root: snapshotsAt }) => seamLockFor({ o, root: checkout, snapshotsAt, commit, snap: snapMod, tag: "rightkit-gate:" }),
3940
+ });
3771
3941
  }
3772
3942
  // `live-scans`: re-run only the live remote scans (pnpm-audit) of a checked tree, answering the broker's verdict-reuse refresh
3773
3943
  // (../snapshot-check.mjs; GATE-CONTRACT §1, E18; rightkit#1257).
@@ -3779,7 +3949,7 @@ export async function main(argv, io = {}) {
3779
3949
  // commit, never a diff. Nothing compiles. The RustRight broker runs exactly this before it admits any compile. `--list`,
3780
3950
  // `--print-baseline` and `--only` stay app-check-only views.
3781
3951
  // `check --commit <sha>` without `--snapshot` reads the gate's one warm snapshot of that commit, selected the way
3782
- // every `--to` stage selects it: per-repository build ownership first, then one sync of the commit into the gate-owned source directory, then the
3952
+ // every `--to` stage selects it: the snapshot lock first, then one sync of the commit into the gate-owned source directory, then the
3783
3953
  // check of that snapshot below. There is no export and no copy of the source (docs/GATE-CONTRACT.md, 2026-10-29); the checkout's own files are
3784
3954
  // never read, so an uncommitted edit in it is ignored. Hosted CI has no warm snapshot: its runner checkout is the commit, scanned in place.
3785
3955
  // `check --commit <sha> --full-a` takes the same route (GB-48, GATE 34/36/44, E17): the selected commit's snapshot, never a conversion to
@@ -3789,50 +3959,50 @@ export async function main(argv, io = {}) {
3789
3959
  if (commitCheck) {
3790
3960
  const sc = await import("../snapshot-check.mjs");
3791
3961
  const snap = await import("../snapshot.mjs");
3792
- const { acquireBuildOwnership, ownershipFile } = await import("../build-ownership.mjs");
3793
3962
  const at = option("--repo") ? path.resolve(o.cwd, option("--repo")) : o.cwd;
3794
3963
  const top0 = o.spawn("git", ["rev-parse", "--show-toplevel"], { cwd: at });
3795
3964
  if (failed(top0) || !text(top0).trim()) { o.err("rightkit-gate: not inside a git repository"); return 2; }
3796
- let own = o.buildOwnership ?? null; let ownHere = false;
3965
+ // The snapshot lock this check runs under: the one a calling gate holds (joined, never taken twice), else its own, taken before the sync and held through the check.
3966
+ let view = o.snapshotLock ?? null; let taken = null; let started = false;
3797
3967
  try {
3798
3968
  const checkout = fs.realpathSync.native(path.resolve(text(top0).trim()));
3799
3969
  const selected = sc.commitOf(checkout, option("--commit") ?? "HEAD", o.spawn);
3800
3970
  const snapshotsAt = o.snapshotRoot ?? snap.snapshotRoot({ platform: o.platform, env: o.env });
3801
- if (!own) {
3802
- try { own = (o.acquireOwnership ?? acquireBuildOwnership)({ file: ownershipFile({ platform: o.platform, beside: o.snapshotRoot, repository: snap.repositoryOf(checkout).key }), stage: "check", snapshot: path.join(snapshotsAt, snap.repositoryOf(checkout).key), commit: selected.commit, platform: o.platform, env: o.env }); ownHere = true; }
3803
- catch (e) { if (e.code !== "busy" && e.code !== "refused") throw e; o.err(`rightkit-gate: RK_CHECK_ERROR: ${e.message}; nothing ran${e.code === "refused" ? ", nothing created" : ""}`); return 2; }
3804
- o.out(`rightkit-gate: build ownership ${own.joined ? "joined" : "held"} ${own.handle}${own.reclaimed ? ` (reclaimed from ${own.reclaimed.from}: ${own.reclaimed.proofs.join("; ")})` : ""}`);
3971
+ if (!view) {
3972
+ taken = takeRunLock({ o, checkout, snapshotsAt, commit: selected.commit, snap, tag: "rightkit-gate:", route: "check" });
3973
+ if (taken.exit !== undefined) return taken.exit;
3974
+ view = taken.view;
3805
3975
  }
3806
3976
  let synced;
3807
- try { synced = (o.syncSnapshot ?? snap.syncSnapshot)({ checkout, rev: selected.commit, root: snapshotsAt }); }
3977
+ try { synced = (o.syncSnapshot ?? snap.syncSnapshot)({ checkout, rev: selected.commit, root: snapshotsAt, lock: { held: view } }); }
3808
3978
  catch (e) { o.err(`rightkit-gate: ${e.code === "error" ? sc.CHECK_ERROR : "BLOCKED"}: snapshot ${e.message}; nothing ran`); return e.code === "error" ? 2 : 1; }
3809
3979
  o.out(`rightkit-gate: snapshot ${synced.path} is commit ${synced.commit} tree ${synced.tree} (written=${synced.written} removed=${synced.removed} unchanged=${synced.unchanged})`);
3810
3980
  if (synced.identity) o.out(`rightkit-gate: source identity ${synced.identity.file}: ${synced.identity.written ? "written" : synced.identity.kept ? "kept" : `not written (${synced.identity.reason})`}`);
3811
3981
  const next = [...argv]; const ci = next.indexOf("--commit");
3812
3982
  if (ci >= 0) next.splice(ci, 2, "--commit", synced.commit); else next.push("--commit", synced.commit);
3813
3983
  next.push("--snapshot", synced.path);
3814
- return await main(next, { ...io, buildOwnership: own });
3984
+ started = true;
3985
+ return await main(next, { ...io, snapshotLock: view });
3815
3986
  } catch (e) { if (e instanceof sc.CheckError) { o.err(`rightkit-gate: ${sc.CHECK_ERROR}: ${e.message}`); return 2; } throw e; }
3816
- finally { if (ownHere) { const r = own.release(); if (r?.released === false && !own.joined) o.err(`rightkit-gate: build ownership ${own.handle} kept: ${r.why}`); } }
3987
+ finally { if (taken) releaseSeamLock({ o, release: taken.release, seamBody: started ? taken.body : null, tag: "rightkit-gate:" }); }
3817
3988
  }
3818
- if ((sub === "check" || (!sub && args.includes("--all"))) && args.includes("--snapshot") && !o.buildOwnership) {
3819
- // Per-repository build ownership (../build-ownership.mjs; GATE-CONTRACT §1): held from before the first snapshot read through the
3820
- // end of the check, so no other request can sync the snapshot while class A runs in it. A nested gate whose
3821
- // RIGHTKIT_BUILD_OWNERSHIP names the current owner joins it. Busy (or liveness unknown) runs nothing.
3822
- const { acquireBuildOwnership, ownershipFile } = await import("../build-ownership.mjs");
3989
+ if ((sub === "check" || (!sub && args.includes("--all"))) && args.includes("--snapshot") && !o.snapshotLock) {
3990
+ // The snapshot lock (reset plan section 3), the run's one exclusion: held from before the first snapshot read through the end of the check or compile, so no other
3991
+ // request can sync the snapshot while it reads it. A nested gate is handed the held lock (`snapshotLock`) and joins it instead of taking a second one. Busy (or a
3992
+ // holder not proven gone) runs nothing.
3823
3993
  const snap = await import("../snapshot.mjs");
3824
- let key;
3825
- try { key = snap.repositoryOf(option("--repo") ? path.resolve(o.cwd, option("--repo")) : o.cwd).key; }
3826
- catch (e) { o.err(`rightkit-gate: RK_CHECK_ERROR: the repository whose build ownership this check takes cannot be identified: ${e.message}; nothing ran`); return 2; }
3827
- // The record is keyed by the repository --repo/cwd names while --snapshot names a separate directory: they must be one repository.
3994
+ const checkoutHere = option("--repo") ? path.resolve(o.cwd, option("--repo")) : o.cwd;
3995
+ let key; let checkout;
3996
+ try { const repo = snap.repositoryOf(checkoutHere); key = repo.key; checkout = repo.checkout; }
3997
+ catch (e) { o.err(`rightkit-gate: RK_CHECK_ERROR: the repository whose snapshot lock this check takes cannot be identified: ${e.message}; nothing ran`); return 2; }
3998
+ // The lock is keyed by the repository --repo/cwd names while --snapshot names a separate directory: they must be one repository.
3828
3999
  const snapshotRootHere = o.snapshotRoot ?? snap.snapshotRoot({ platform: o.platform, env: o.env });
3829
4000
  if (path.basename(option("--snapshot") ?? "") !== key || path.resolve(o.cwd, path.dirname(option("--snapshot"))) !== path.resolve(o.cwd, snapshotRootHere)) { o.err(`rightkit-gate: RK_CHECK_ERROR: --snapshot ${option("--snapshot")} is not the snapshot of repository ${key} (its directory name must be the repository key, inside the snapshot root ${snapshotRootHere}); nothing ran`); return 2; }
3830
- let own;
3831
- try { own = (o.acquireOwnership ?? acquireBuildOwnership)({ file: ownershipFile({ platform: o.platform, beside: o.snapshotRoot, repository: key }), stage: sub ?? "compile", snapshot: option("--snapshot") ?? null, commit: option("--commit") ?? null, platform: o.platform, env: o.env }); }
3832
- catch (e) { if (e.code !== "busy" && e.code !== "refused") throw e; o.err(`rightkit-gate: RK_CHECK_ERROR: ${e.message}; nothing ran${e.code === "refused" ? ", nothing created" : ""}`); return 2; }
3833
- o.out(`rightkit-gate: build ownership ${own.joined ? "joined" : "held"} ${own.handle}${own.reclaimed ? ` (reclaimed from ${own.reclaimed.from}: ${own.reclaimed.proofs.join("; ")})` : ""}`);
3834
- try { return await main(argv, { ...io, buildOwnership: own }); }
3835
- finally { const r = own.release(); if (r?.released === false && !own.joined) o.err(`rightkit-gate: build ownership ${own.handle} kept: ${r.why}`); }
4001
+ let commit = null; try { commit = snap.resolveCommit(checkout, option("--commit") ?? "HEAD").commit; } catch { commit = null; }
4002
+ const taken = takeRunLock({ o, checkout, snapshotsAt: snapshotRootHere, commit, snap, tag: "rightkit-gate:", route: "check" });
4003
+ if (taken.exit !== undefined) return taken.exit;
4004
+ try { return await main(argv, { ...io, snapshotLock: taken.view }); }
4005
+ finally { releaseSeamLock({ o, release: taken.release, seamBody: taken.body, tag: "rightkit-gate:" }); }
3836
4006
  }
3837
4007
  if (sub === "check") {
3838
4008
  // `--snapshot <dir>`: full class A of the gate-owned snapshot of a selected commit (../snapshot-check.mjs). The checkout is only
@@ -3848,8 +4018,13 @@ export async function main(argv, io = {}) {
3848
4018
  snapshotCheckout = fs.realpathSync.native(path.resolve(text(top0).trim()));
3849
4019
  snapshotDir = sc.snapshotOption(args, { checkout: snapshotCheckout });
3850
4020
  snapshotCommit = sc.commitOf(snapshotCheckout, option("--commit"), o.spawn);
3851
- sc.verifySnapshotDir({ checkout: snapshotCheckout, dir: snapshotDir, ...snapshotCommit, when: "before the check" });
3852
- o.out(`rightkit-gate: snapshot ${snapshotDir} is commit ${snapshotCommit.commit} tree ${snapshotCommit.tree} (verified before the check)`);
4021
+ // NN07 (no repeated work): the door's stage opener has just proved this snapshot against the commit with an empty ledger (nothing staged
4022
+ // before the check), which is this same proof; the check does not walk the tree a second time.
4023
+ if (o.snapshotProvedBefore === snapshotDir) o.out(`rightkit-gate: snapshot ${snapshotDir} is commit ${snapshotCommit.commit} tree ${snapshotCommit.tree} (proved by the door before the check)`);
4024
+ else {
4025
+ sc.verifySnapshotDir({ checkout: snapshotCheckout, dir: snapshotDir, ...snapshotCommit, when: "before the check" });
4026
+ o.out(`rightkit-gate: snapshot ${snapshotDir} is commit ${snapshotCommit.commit} tree ${snapshotCommit.tree} (verified before the check)`);
4027
+ }
3853
4028
  } catch (e) { o.err(`rightkit-gate: ${sc.CHECK_ERROR}: ${e.message}`); return 2; }
3854
4029
  }
3855
4030
  if (args.filter((arg) => arg === "--rule-tier").length > 1 || (args.includes("--rule-tier") && option("--rule-tier") === undefined)) {
@@ -3959,24 +4134,12 @@ export async function main(argv, io = {}) {
3959
4134
  }
3960
4135
  }
3961
4136
  }
3962
- // A RustRight broker's check names the tree it captured for the compile: the declared inputs there (ignored files the
3963
- // commit does not hold) are judged too, as the bytes the compile will read.
3964
- let inputs = 0;
3965
- const captured = o.env.RIGHTKIT_COMPILE_INPUTS;
3966
- if (captured) {
3967
- const { judgeCompileInputs } = await import("../compile-inputs.mjs");
3968
- const judged = judgeCompileInputs(path.resolve(captured));
3969
- for (const i of judged.inputs) o.out(`rightkit-gate: compile input ${i.path}: ${i.files} file(s), sha256 ${i.sha256}`);
3970
- for (const f of judged.findings) o.err(`rightkit-gate: compile input FAIL ${f}`);
3971
- if (!judged.inputs.length && !judged.findings.length) o.out("rightkit-gate: no declared compile inputs in the captured tree");
3972
- inputs = judged.findings.length ? 1 : 0;
3973
- }
3974
4137
  if (snapshotDir) {
3975
4138
  try { sc.verifySnapshotDir({ checkout: snapshotCheckout, dir: snapshotDir, ...snapshotCommit, when: "after the check" }); }
3976
4139
  catch (e) { o.err(`rightkit-gate: ${sc.CHECK_ERROR}: ${e.message}; the result covers no known bytes`); return 2; }
3977
4140
  o.out(`rightkit-gate: snapshot ${snapshotDir} is still tree ${snapshotCommit.tree} after the check`);
3978
4141
  }
3979
- return Math.max(appCheck, classA, selfRules, inputs);
4142
+ return Math.max(appCheck, classA, selfRules);
3980
4143
  }
3981
4144
  const classAOnly = args.includes("--class-a");
3982
4145
  // --full-a: every class A check, the ones that execute the repository's code (tests, typecheck, lint, generated docs) included,
@@ -4017,7 +4180,7 @@ export async function main(argv, io = {}) {
4017
4180
  // Full Class A needs a snapshot or the committed hosted checkout. The content pass (`check --commit <sha> --scope <dir>`: publication
4018
4181
  // admission, GC-A03) reads the commit the same way it always did (the warm snapshot, or the runner checkout proven to be that commit
4019
4182
  // in place) and only narrows which executing workspace scans run, so it is the one other form --scope accepts; never the live tree.
4020
- const scopeForm = fullA ? Boolean(snapshotA || hostedCommitA) : (classAOnly && !args.includes("--worktree")) || Boolean(snapshotB && (o[PRIVATE_SCOPED_COMPILE] || o[UNIT_LIST_UNION]) && o.classAEarlier && o.buildOwnership);
4183
+ const scopeForm = fullA ? Boolean(snapshotA || hostedCommitA) : (classAOnly && !args.includes("--worktree")) || Boolean(snapshotB && (o[PRIVATE_SCOPED_COMPILE] || o[UNIT_LIST_UNION]) && o.classAEarlier && o.snapshotLock);
4021
4184
  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; }
4022
4185
  }
4023
4186
  if (args.includes("--base") && (!option("--base") || option("--base").startsWith("--"))) { o.err("rightkit-gate: --base needs a ref"); return 2; }
@@ -4162,7 +4325,6 @@ export async function main(argv, io = {}) {
4162
4325
  // A door run that names no unit: RightKit refuses it unless Adrian's exception or a unit list names what runs (rightkitDoorRule).
4163
4326
  const door = await rightkitDoorRule(o, args, root, git, io, { unitsFileFlag, allUnitsFlag, unitList, changedFlag });
4164
4327
  if (door.exit !== undefined) return door.exit;
4165
- if (o[CARGO_WIDTH] !== undefined) { o.err("rightkit-gate: BLOCKED: --cargo-jobs requires the controlled unit-list route"); return 2; }
4166
4328
  return await runStages(o, args, root, git, io);
4167
4329
  }
4168
4330
  if (sub === "stage") return stageForPublisher(o, args, root, git);
@@ -4205,16 +4367,6 @@ export async function main(argv, io = {}) {
4205
4367
  const executor = (o.resolveExecutor ?? gateResolveExecutor)({ env: o.env, platform: o.platform, exists: o.exists, which, readFile: o.readFile }); applyExecutorEnv(o, executor);
4206
4368
  // A broker-managed host whose broker is unreachable refuses the moment a Cargo manifest is in the snapshot (below): a repository
4207
4369
  // 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.
4208
- if (o[CARGO_WIDTH] !== undefined && !classAOnly) {
4209
- try {
4210
- if (executor.kind !== "broker") throw new Error("--cargo-jobs requires a broker reporting its compile-token pool");
4211
- const client = executor.client ?? "rustright";
4212
- const result = spawnBrokerClient(o.spawn, client, ["list"], { env: brokerEnvOf(o, executor), encoding: "utf8", timeout: 20_000, windowsHide: true }, { platform: o.platform, readFile: o.readFile });
4213
- if (failed(result)) throw new Error("cannot read broker compile-token pool");
4214
- const size = validateCargoWidthPool(o[CARGO_WIDTH], JSON.parse(text(result)));
4215
- o.out(`rightkit-gate: Cargo width ${o[CARGO_WIDTH]} (broker token pool ${size})`);
4216
- } catch (error) { o.err(`rightkit-gate: BLOCKED: ${error.message}`); return 1; }
4217
- }
4218
4370
  const cargoCommand = executor.cargo ?? ["cargo"];
4219
4371
  // The declared Linux broker route's cargo is `[<absolute validated client>, "cargo"]`, which the scan planner (planScans: `["rustright","cargo"]` or
4220
4372
  // `["cargo"]`) refuses, and a PATH `rustright` is never the client. So the scans are PLANNED with the logical `["rustright","cargo"]` and every spawn the
@@ -4322,15 +4474,13 @@ export async function main(argv, io = {}) {
4322
4474
  return failed(r) ? [] : text(r).split("\0").filter(Boolean).map(posix);
4323
4475
  };
4324
4476
  if (executor.kind === "broker" && snapshot && (snapshotA || snapshotB) && manifests.length) {
4325
- const { createSnapshotBroker } = await import("../snapshot-broker.mjs");
4326
4477
  const snapshotCheck = await import("../snapshot-check.mjs");
4327
4478
  const snapshotCommitOf = () => snapshotCheck.commitOf(fs.realpathSync.native(root), String(snapshot), o.spawn);
4328
- // The broker is built before anything is read: a missing enrollment, ownership or client refuses here, naming its code (as the compile does).
4479
+ // The seam's broker (the client, the commit, the snapshot) is built before anything is read: a missing client refuses here, naming its code (as the compile does).
4329
4480
  try {
4330
- if (o.snapshotBroker && typeof o.snapshotBroker.create !== "function") discoveryBroker = o.snapshotBroker; // a fixture broker (tests)
4331
- else {
4481
+ {
4332
4482
  const sc = snapshotCommitOf();
4333
- discoveryBroker = createSnapshotBroker({ env: o.env, platform: o.platform, checkout: root, commit: { sha: sc.commit, tree: sc.tree }, snapshot: { path: repo, expectedTree: sc.tree }, ownership: o.buildOwnership, client: executor.route === LINUX_BROKER_ROUTE ? executor.client : which("rustright").find((c) => path.isAbsolute(c)), gateFile: callingGatePath(), spawn: o.spawn });
4483
+ discoveryBroker = seamBrokerOf({ o, root, executor, commit: { sha: sc.commit, tree: sc.tree }, snapshot: { path: repo, expectedTree: sc.tree }, which });
4334
4484
  }
4335
4485
  } catch (error) { o.err(`${tag} BLOCKED: ${error.code ?? "RK_SNAPSHOT_BROKER"}: ${error.message}; nothing compiled`); return 1; }
4336
4486
  // GATE-CONTRACT GC-A11 (Adrian, 2026-11-02): Class A never runs in the broker. The snapshot's discovery metadata and every Class A Cargo
@@ -4433,12 +4583,10 @@ export async function main(argv, io = {}) {
4433
4583
  const shimModule = await import("../cargo-target-shim.mjs");
4434
4584
  let broker = null;
4435
4585
  if (wrapBroker) {
4436
- // Broker mode (the Mac, decision C): every cargo a test reaches is its own carried request. The gate's own snapshot-to-checkout
4437
- // map is the only source of a request's primaryCwd; each carried request records its sub-handle in the ownership just before it is sent.
4586
+ // Broker mode (the Mac and the Dell): every compile a test reaches is a seam call from its own workspace directory in the snapshot.
4438
4587
  const checkoutRoot = fs.realpathSync.native(root);
4439
4588
  const checkoutDirs = Object.fromEntries(rust.workspaces.map((ws) => [ws.cargoDir, path.join(checkoutRoot, ...(ws.cargoDir === "." ? [] : ws.cargoDir.split("/")))]));
4440
- const { brokerSection } = await import("../snapshot-broker.mjs");
4441
- broker = { checkoutDirs, section: brokerSection(wrapBroker) };
4589
+ broker = { checkoutDirs, section: wrapBroker };
4442
4590
  }
4443
4591
  // Its own base directory: the wrapper's directory is named by its identity, and a unit stage's outer wrapper over the same
4444
4592
  // workspaces has the same identity, so a shared base would let this run's cleanup delete the wrapper the next stage runs under.
@@ -4460,32 +4608,31 @@ export async function main(argv, io = {}) {
4460
4608
  // With a ledger the verify returns an object ({ tree, ledger }), without one the tree id: only the refusal (a throw) matters here.
4461
4609
  sc.verifySnapshotDir({ checkout, dir: snapshotB, ...snapshotBCommit, when: "before the compile", ...(o.snapshotLedger ? { ledger: o.snapshotLedger } : {}) });
4462
4610
  directTiming.bindEnd = Date.now();
4463
- // A direct host digests the declared compile inputs in place (the snapshot's own .rightkit/compile-inputs.json, never the
4464
- // checkout's); a malformed manifest refuses before anything compiles. The broker digests them for a broker host.
4465
- if (executor.kind === "direct") {
4611
+ // The declared compile inputs are judged in the snapshot itself (its own declaration file, never the checkout's), on every host: the broker captures none (the seam carries
4612
+ // none, reset plan section 4), so the gate is the only judge of the bytes the compile reads that the commit does not hold. A malformed declaration, a link, a file that does not
4613
+ // parse or a secret in one refuses before anything compiles (these were the checks of the broker-captured tree, RIGHTKIT_COMPILE_INPUTS, retired with it); a declared path the
4614
+ // snapshot does not hold is a note, as on a direct host before, and the compile that reads it fails by itself.
4615
+ {
4466
4616
  const inputsModule = await import("../compile-inputs.mjs");
4467
4617
  const judged = inputsModule.judgeCompileInputs(snapshotB);
4468
- // Only a malformed manifest refuses here (the broker's request does the same); a declared path the snapshot does not hold, or a
4469
- // finding in one, is recorded with the diagnostics and left to the check stage that judges the captured inputs.
4470
- const malformed = judged.findings.filter((f) => f.startsWith(`${inputsModule.COMPILE_INPUTS_FILE}:`));
4471
- if (malformed.length) throw Object.assign(new Error(`the snapshot's declared compile inputs are malformed: ${malformed.join("; ")}`), { code: "RK_COMPILE_INPUTS" });
4472
- directDeclared = judged.inputs;
4473
- directDeclaredNotes = judged.findings.map((f) => `declared compile input: ${f}`);
4618
+ const refused = judged.malformed ? [judged.malformed] : judged.findings.filter((f) => !judged.missing.includes(f));
4619
+ if (refused.length) throw Object.assign(new Error(`the snapshot's declared compile inputs are refused: ${refused.join("; ")}`), { code: "RK_COMPILE_INPUTS" });
4620
+ for (const f of judged.missing) o.out(`${tag} declared compile input: ${f}`);
4621
+ if (executor.kind === "direct") {
4622
+ directDeclared = judged.inputs;
4623
+ directDeclaredNotes = judged.missing.map((f) => `declared compile input: ${f}`);
4624
+ }
4474
4625
  }
4475
4626
  o.out(`${tag} snapshot ${snapshotB} is commit ${snapshotBCommit.commit} tree ${snapshotBCommit.tree} (verified before the compile)`);
4476
4627
  for (const r of sc.installSnapshotDependencies({ checkout, snapshot: snapshotB, ...snapshotBCommit, ...(o.snapshotLedger !== undefined ? { ledger: o.snapshotLedger } : {}), roots: installRoots, ...(closure ? { packageDirs: npm.filter((u) => closure.npm.has(u.name)).map((u) => u.dir) } : {}), env: o.env, spawn: o.spawn })) o.out(`${tag} ${sc.describeInstall(r)}`);
4477
4628
  } catch (error) { o.err(`${tag} ${error.code === "RK_CHECK_ERROR" ? "RK_CHECK_ERROR" : "BLOCKED"}: ${error.message}`); return error.code === "RK_CHECK_ERROR" ? 2 : 1; }
4478
- // A broker host (item 7 rows 7.20 to 7.24): the compile goes through the RustRight snapshot carrier. The broker pins the output
4479
- // directory (its managed generation target), so no checkout target is resolved here; the gate's broker is built once, with the
4480
- // host's enrolled pins, the declared inputs read from the snapshot and the build ownership; a missing piece refuses before
4481
- // anything compiles (an app repository with no enrollment included), never a compile around the broker.
4629
+ // A broker host: the compile goes through the seam (reset plan section 3). The broker pins the output directory (its managed generation target), so no checkout target
4630
+ // is resolved here; the seam's broker (client, commit, snapshot) is built once; a missing client refuses before anything compiles, never a compile around the broker.
4482
4631
  if (executor.kind === "broker" && manifests.length) {
4483
4632
  try {
4484
- const { createSnapshotBroker } = await import("../snapshot-broker.mjs");
4485
- const client = executor.route === LINUX_BROKER_ROUTE ? executor.client : which("rustright").find((c) => path.isAbsolute(c));
4486
- snapshotBroker = discoveryBroker ?? createSnapshotBroker({ env: o.env, platform: o.platform, checkout: root, commit: { sha: snapshotBCommit.commit, tree: snapshotBCommit.tree }, snapshot: { path: snapshotB, expectedTree: snapshotBCommit.tree }, ownership: o.buildOwnership, client, gateFile: callingGatePath(), spawn: o.spawn });
4633
+ snapshotBroker = discoveryBroker ?? seamBrokerOf({ o, root, executor, commit: { sha: snapshotBCommit.commit, tree: snapshotBCommit.tree }, snapshot: { path: snapshotB, expectedTree: snapshotBCommit.tree }, which });
4487
4634
  } catch (error) { o.err(`${tag} BLOCKED: ${error.code ?? "RK_SNAPSHOT_BROKER"}: ${error.message}; nothing compiled`); return 1; }
4488
- o.out(`${tag} broker snapshot compile: pins ${snapshotBroker.pins.keyId.slice(0, 12)} from ${snapshotBroker.pinsSource}, ${snapshotBroker.declaredInputs.length} declared input(s) read from the snapshot, ownership ${snapshotBroker.handle}`);
4635
+ o.out(`${tag} broker snapshot compile: the seam, client ${snapshotBroker.client}, snapshot ${snapshotB}`);
4489
4636
  }
4490
4637
  { const rc = await bindCargoWrapper(snapshotB, snapshotBroker); if (rc) return rc; }
4491
4638
  }
@@ -4576,7 +4723,6 @@ export async function main(argv, io = {}) {
4576
4723
  fullPlan = planScans({
4577
4724
  // Class A of a commit or tree reads only that snapshot: every scan, cargo's included, runs in the snapshot, never in the live
4578
4725
  // checkout (which may hold other bytes). Compiles (class B) use the live checkout, whose tree the dirty check pinned to HEAD.
4579
- cargoJobs: classAOnly ? null : (o[CARGO_WIDTH] ?? null),
4580
4726
  changed, contentRoot: repo, liveRoot: (classAOnly && snapshot) || snapshotB ? repo : root, trustedRoot: snapshotA ?? snapshotB ?? root, includeTests: true, rustScope, cargoCommand: planCargoCommand, targetDirs, cargoShim: Boolean(cargoShim),
4581
4727
  tier: fullA ? "release" : (option("--rule-tier") ?? "compile"), cargoLiveRoot,
4582
4728
  // The quiet tests (port, pipe, desktop and wall-clock bound) are proven by the CI shards, one crate per runner, unless
@@ -4588,8 +4734,8 @@ export async function main(argv, io = {}) {
4588
4734
  e2eCrateDirs, swiftPackages,
4589
4735
  rustUnits: rust.units, npmUnits: npm, npmRoots, cargoDir: ".", rustLocks, crateFeatures, crateDependents, externalInputs,
4590
4736
  // B1 (rightkit#1458): compile scans of one Cargo workspace run as one cargo invocation per configuration; ci/shards.json `solo` crates never join one.
4591
- // 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.
4592
- classBBatching: !o[PRIVATE_SCOPED_COMPILE] && o.env.RK_GATE_CLASS_B_BATCH !== "0", shardSolo: shardSoloOf(o, repo),
4737
+ // Batching is always on (the RK_GATE_CLASS_B_BATCH switch is gone, 2026-11-08): 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.
4738
+ classBBatching: !o[PRIVATE_SCOPED_COMPILE], shardSolo: shardSoloOf(o, repo),
4593
4739
  // The broker (or, on a direct host, the gate itself) admits compiles; no separate grant file decides it here.
4594
4740
  localCompile: true,
4595
4741
  exists: o.exists, readFile: o.readFile, platform: o.platform,
@@ -4629,19 +4775,12 @@ export async function main(argv, io = {}) {
4629
4775
  const cargoExcluded = kept.dropped.filter((s) => closureTools.isCargoScan(s)).length;
4630
4776
  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}`);
4631
4777
  }
4632
- if (o[CARGO_WIDTH] !== undefined && !classAOnly) {
4633
- const uncontrolled = plan.scans.find((scan) => scan.class === "B" && cargoWidthScanProblem(scan, planCargoCommand, o[CARGO_WIDTH]));
4634
- if (uncontrolled) { o.err(`${tag} BLOCKED: --cargo-jobs cannot control Class B scan ${uncontrolled.id}`); return 1; }
4635
- }
4636
- let unionScheduler = null;
4637
4778
  const unionContext = o[UNIT_LIST_UNION];
4638
4779
  if (unionContext && snapshotB) {
4639
4780
  try {
4640
- const { publisherRequirementsForUnits, planUnitListCompile, publisherUnionScheduler, runPublisherSecretRequirement, proveWorkspaceCwd } = await import("../unit-list-compile.mjs");
4641
- const { publisherRequirementScan } = await import("../deterministic-scans.mjs");
4642
- const requirements = await publisherRequirementsForUnits({ selected: unionContext.selected, snapshot: repo, rustUnits: rust.units, npmUnits: npm, platform: o.platform, env: o.env });
4781
+ const { publisherRequirementsForUnits, runPublisherSecretRequirement, proveWorkspaceCwd } = await import("../local-publish.mjs");
4782
+ const requirements = publisherRequirementsForUnits({ selected: unionContext.selected, snapshot: repo, rustUnits: rust.units, npmUnits: npm, platform: o.platform, env: o.env });
4643
4783
  unionContext.expected = new Map(requirements.map((entry) => [entry.selector, entry.requirements.length]));
4644
- 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");
4645
4784
  const external = []; const scoped = []; const owner = new Map(); const verdicts = new Map(); const initialFailures = new Set();
4646
4785
  const { directReadSpawn } = await import("../snapshot-metadata.mjs");
4647
4786
  const pathKey = o.platform === "win32" ? (Object.keys(o.env).find((k) => k.toUpperCase() === "PATH") ?? "Path") : "PATH";
@@ -4670,37 +4809,63 @@ export async function main(argv, io = {}) {
4670
4809
  }
4671
4810
  const normalizedCwds = new Map(); const cwdProofs = [];
4672
4811
  const toolchains = new Map();
4812
+ // A direct cargo that is a toolchain's own binary (…/toolchains/<name>/bin/cargo), not the rustup proxy, runs that toolchain in every directory:
4813
+ // no directory override can change it, so the proof needs no rustup (Dell 2026-11-07: `rustup show active-toolchain` hung, no answer in 30 s).
4814
+ const fixedToolchain = /[\\/]toolchains[\\/]([^\\/]+)[\\/]bin[\\/]cargo(?:\.exe)?$/i.exec(String(direct.cargo ?? ""))?.[1] ?? null;
4673
4815
  const toolchainOf = (dir) => {
4816
+ if (fixedToolchain) return { toolchain: fixedToolchain };
4674
4817
  if (!toolchains.has(dir)) {
4675
- const result = o.spawn("rustup", ["show", "active-toolchain"], { cwd: dir, env: { ...o.env, [pathKey]: direct.path } });
4818
+ // rustup on the direct PATH, else the real one in CARGO_HOME/bin: on a broker host the only rustup on PATH may be the broker's managed shim,
4819
+ // which the direct PATH drops (Dell 2026-11-07: every proof read "effective toolchain unavailable (spawn-error)" and no publisher row could group).
4820
+ const sep = o.platform === "win32" ? ";" : ":"; const exe = o.platform === "win32" ? "rustup.exe" : "rustup";
4821
+ const onPath = String(direct.path ?? "").split(sep).filter(Boolean).some((d) => o.exists(path.join(d, exe)));
4822
+ const home = o.env.CARGO_HOME || path.join(o.env.USERPROFILE || o.env.HOME || "", ".cargo");
4823
+ const rustupCmd = onPath ? "rustup" : (o.exists(path.join(home, "bin", exe)) ? path.join(home, "bin", exe) : "rustup");
4824
+ const result = o.spawn(rustupCmd, ["show", "active-toolchain"], { cwd: dir, env: { ...o.env, [pathKey]: direct.path }, timeout: 20000 });
4676
4825
  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] });
4677
4826
  }
4678
4827
  return toolchains.get(dir);
4679
4828
  };
4680
- for (const requirement of external) if (requirement.executable === "cargo" && requirement.phase === "compile" && ["check", "clippy"].includes(requirement.argv[0])) {
4829
+ for (const requirement of external) if (requirement.executable === "cargo" && ((requirement.phase === "compile" && ["check", "clippy", "doc"].includes(requirement.argv[0])) || (requirement.phase === "test" && requirement.argv[0] === "test"))) {
4681
4830
  const proof = proveWorkspaceCwd({ requirement, snapshot: repo, checkout: root, toolchainOf, exists: o.exists });
4682
4831
  if (proof.normalized) normalizedCwds.set(requirement.id, proof.cwd);
4683
4832
  cwdProofs.push({ id: requirement.id, cwd: proof.cwd, normalized: proof.normalized, reason: proof.reason });
4684
4833
  }
4685
4834
  unionContext.cwdProofs = cwdProofs;
4686
- const jobs = planUnitListCompile(scoped, { normalizedCwds });
4835
+ // Why a publisher row could not move to its workspace root (and so cannot join a group) is evidence, printed with the plan (Dell 2026-11-07: 0 grouped jobs).
4836
+ { const by = new Map(); for (const proof of cwdProofs) { const k = proof.normalized ? "moved" : proof.reason; by.set(k, (by.get(k) ?? 0) + 1); }
4837
+ o.out(`${tag} note: publisher working-directory proofs: ${[...by].map(([k, n]) => `${n} ${k}`).join("; ") || "none"}`); }
4838
+ // ONE scan set (reset plan step 5): the plan's own rows over the closure of every listed unit, plus one Class B scan per publisher requirement those rows do not
4839
+ // already prove (NN27); runScans runs it with its own class B grouping (classBBatching, the feature partition, the store rule, the serial reuse), under this run's
4840
+ // one snapshot lock and one shared Class A. Rows are judged per requirement and per unit after the run (judgeUnitList).
4687
4841
  const config = JSON.parse(o.readFile(path.join(repo, "ci/gate.config.json")));
4842
+ const dependencies = Object.fromEntries(unionContext.selected.map((unit) => [unit.selector, (unit.deps ?? []).filter((dep) => unionContext.selected.some((u) => u.selector === dep))]));
4843
+ const blocked = blockedUnitsOf({ dependencies, initialFailures });
4844
+ const solo = shardSoloOf(o, repo);
4845
+ const dirOf = new Map(unionContext.selected.map((unit) => [unit.selector, unit.dir]));
4688
4846
  const adapt = (requirement) => {
4689
- const sel = owner.get(requirement.id) ?? jobs.find((job) => job.members.some((member) => member.coverageKey === requirement.coverageKey))?.members[0]?.selector;
4847
+ const sel = owner.get(requirement.id);
4690
4848
  const unit = sel?.replace(/^cargo:/, "");
4691
4849
  const quiet = sel?.startsWith("cargo:") ? config.rust?.[unit]?.quietTests === true : false;
4692
- return publisherRequirementScan(requirement, { platform: o.platform, cargoCommand: planCargoCommand, cargoLiveRoot, targetDirs, quiet, allowIgnored: verdicts.get(sel)?.allowIgnored === true, cargoJobs: o[CARGO_WIDTH] ?? null });
4850
+ // A crate that ci/shards.json lists solo, or that is sidecar-bound, never joins another crate's invocation (planScans' own rule for its rows).
4851
+ const alone = sel?.startsWith("cargo:") && (solo.includes(unit) || sidecarBoundCrate({ dir: path.join(repo, dirOf.get(sel) ?? `crates/${unit}`), exists: o.exists, readFile: o.readFile }).bound);
4852
+ return publisherRequirementScan(requirement, { platform: o.platform, cargoCommand: planCargoCommand, cargoLiveRoot, targetDirs, quiet, allowIgnored: verdicts.get(sel)?.allowIgnored === true, batch: !alone });
4693
4853
  };
4694
- for (const requirement of external) plan.scans.push(adapt(requirement));
4695
- const dependencies = Object.fromEntries(unionContext.selected.map((unit) => [unit.selector, (unit.deps ?? []).filter((dep) => unionContext.selected.some((u) => u.selector === dep))]));
4696
- unionScheduler = publisherUnionScheduler({ reuseProofs: o.env.RK_GATE_PUBLISHER_REUSE !== "0", concurrency: Math.max(1, Number(o.env.RK_GATE_PUBLISHER_JOBS ?? 1) || 1), jobs, dependencies, initialFailures, requirements: external, adapt, signal: ac.signal, onCoverage: (coverage) => { unionContext.coverage = coverage; }, verify: async ({ row, member, attempts, requirement }) => {
4854
+ const planned = planUnitListScans({ entries: scoped, planned: plan.scans, normalizedCwds, adapt, blocked });
4855
+ const provers = new Set(planned.provers);
4856
+ for (const [i, scan] of plan.scans.entries()) if (provers.has(scan.id)) plan.scans[i] = { ...scan, provesPublisher: true };
4857
+ for (const scan of planned.scans) plan.scans.push(scan);
4858
+ const publisherDigest = digestScanSet(planned.scans);
4859
+ { const keys = new Set(planned.scans.filter((x) => x.batchable).map((x) => x.batchable.key));
4860
+ o.out(`${tag} note: unit-list publisher scans: ${planned.scans.length} scan(s) for ${scoped.reduce((n, e) => n + e.requirements.length, 0)} external requirement(s) of ${scoped.length} unit(s); ${planned.scans.filter((x) => x.batchable).length} batchable in ${keys.size} configuration group(s) (runScans groups them); ${planned.providerOf.size} proved by a plan row (NN27); ${blocked.size} unit(s) blocked before any compile; publisher scan-set digest ${publisherDigest}`); }
4861
+ unionContext.publisher = { scoped, dependencies, blocked, scanOf: planned.scanOf, providerOf: planned.providerOf, scanIds: planned.scans.map((x) => x.id), scanSetDigest: publisherDigest, verify: async ({ row, member, attempts, requirement }) => {
4697
4862
  const verdict = verdicts.get(member.selector);
4698
4863
  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 };
4699
4864
  unionContext.commands.push({ selector: member.selector, id: member.id, ...proof });
4700
4865
  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 };
4701
4866
  if (executor.kind === "broker" && requirement.executable === "cargo" && !/^[0-9a-f]{64}$/.test(row.snapshotEvidence?.receiptSha256 ?? "")) return { ok: false };
4702
4867
  return { ok: true, evidenceHash: createHash("sha256").update(JSON.stringify(proof)).digest("hex") };
4703
- } });
4868
+ } };
4704
4869
  unionContext.owner = owner;
4705
4870
  } catch (error) { o.err(`${tag} BLOCKED: cannot prepare canonical unit-list compile: ${error.message}`); return 1; }
4706
4871
  }
@@ -4710,7 +4875,6 @@ export async function main(argv, io = {}) {
4710
4875
  // 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).
4711
4876
  const defaultJobs = typeof os.availableParallelism === "function" ? os.availableParallelism() : os.cpus().length;
4712
4877
  const jobs = Math.max(1, Number(o.env.RK_GATE_JOBS ?? defaultJobs) || defaultJobs);
4713
- const testJobs = Math.max(1, Number(o.env.RK_GATE_TEST_JOBS ?? jobs) || jobs);
4714
4878
  // 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.
4715
4879
  const brokerHost = executor.kind === "broker";
4716
4880
  const classBJobs = brokerHost ? LOCAL_CLASS_B_JOBS : Math.max(1, Number(o.env.RK_GATE_CLASS_B_JOBS ?? 3) || 3);
@@ -4866,7 +5030,8 @@ export async function main(argv, io = {}) {
4866
5030
  nodeCheckDiagnosticId = plan.scans.filter((scan) => scan.class === "A" && scan.id.startsWith("node-check:")).map((scan) => scan.id).sort()[0];
4867
5031
  const nodeCheckModule = null; // GC-A24: node-check rows use the generic file key (file, ancestor package.json, node identity)
4868
5032
  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;
4869
- cache = { ...store, narrowNodeCheck: false, digest: (scan, context) => {
5033
+ // entryNow: a path's content id in this run's tree, for carryOverProof (a pass stored under an earlier key form is carried when its files are unchanged).
5034
+ cache = { ...store, narrowNodeCheck: false, entryNow: (p) => objectId(p), digest: (scan, context) => {
4870
5035
  if (/^build-helpers(:|$)/.test(scan.id)) return null;
4871
5036
  // This narrow key applies only to the helper's proven plain snapshot node --check.
4872
5037
  // Uncertain rows miss rather than falling back to a less specific key.
@@ -4898,8 +5063,18 @@ export async function main(argv, io = {}) {
4898
5063
  return text(r);
4899
5064
  };
4900
5065
  // The class B key identity (key schema and carrier code, classBKeyIdentity) is part of every class B key.
4901
- const rowDigest = buildCacheDigest({ objectId, headTree: treeId, rustUnits: rust.units, npmUnits: npm, cargoDir: ".", rustLocks, crateFeatures, listFiles, readBlob, onKeyError: keyError });
4902
- const gateIdentity = classBKeyIdentity();
5066
+ const rawRowDigest = buildCacheDigest({ objectId, headTree: treeId, rustUnits: rust.units, npmUnits: npm, cargoDir: ".", rustLocks, crateFeatures, listFiles, readBlob, onKeyError: keyError });
5067
+ // A row's input digest reads only the selected commit's tree (git ls-tree/show at headSha), so one answer per tree and row serves the lookup pass and
5068
+ // every per-crate probe of the run (Mac 2026-11-07, brosef: the broker sat idle ~22 s after each grouped job while the next groups' members were
5069
+ // re-keyed one at a time on the gate's thread; 103 s of a 422 s run). Keyed by the tree and the row's whole scan identity; a null answer is not kept.
5070
+ const rowDigest = (scan) => {
5071
+ const k = `${treeId}\0${canonicalJson({ id: scan.id, args: scan.args ?? null, env: scan.env ?? null, cwd: scan.cwd ?? null, root: scan.root ?? null, kind: scan.kind ?? null, coverageKey: scan.coverageKey ?? null, runOutside: scan.runOutside ?? null, batch: scan.batch ?? null, command: scan.command ?? null })}`;
5072
+ if (ROW_DIGEST_MEMO.has(k)) { ROW_DIGEST_STATS.hits += 1; return ROW_DIGEST_MEMO.get(k); }
5073
+ const t0 = performance.now(); const d = rawRowDigest(scan); ROW_DIGEST_STATS.ms += performance.now() - t0; ROW_DIGEST_STATS.misses += 1;
5074
+ if (d !== null && d !== undefined) ROW_DIGEST_MEMO.set(k, d);
5075
+ return d;
5076
+ };
5077
+ const gateIdentity = classBKeyIdentity(snapshotB && brokerHost ? "seam" : "direct");
4903
5078
  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; } };
4904
5079
  } else {
4905
5080
  cacheDisabled = `class B result cache disabled: ${!headSha ? "no commit" : !treeId ? "no tree id" : `git common dir unreadable (${why(common)})`}`;
@@ -4919,25 +5094,38 @@ export async function main(argv, io = {}) {
4919
5094
  } catch (error) { o.err(`${tag} BLOCKED: ${error.code ?? "RK_SCAN_TOOLS"}: ${error.message}; no scan ran`); return 1; }
4920
5095
  const enrolledTools = Object.keys(scanTools?.policy ?? {});
4921
5096
  if (enrolledTools.length) o.out(`${tag} scan-tool policy: ${enrolledTools.map((name) => `${name} (${scanTools.sources?.[name] ?? "enrolled"})`).join(", ")}`);
4922
- // The direct compile's freshness census (row 7.19): the fingerprint units before the scans, and the fingerprint log of each cargo
4923
- // process that compiles (CARGO_LOG on that process only, read from its own standard error). A broker host's census is the broker's.
4924
5097
  // The door's compile stage runs only after its check stage passed full class A of this same snapshot, once, before the compile and under the
4925
5098
  // cargo wrapper (rightkit#1328): this pass runs class B alone. Set by the door (io option), never by a command-line flag.
4926
5099
  const classAEarlier = Boolean(snapshotB && o.classAEarlier === true);
4927
5100
  if (classAEarlier) o.out(`${tag} class A is not repeated: it ran once before the compile, under the cargo wrapper, on this snapshot`);
4928
- const census = snapshotB && !snapshotBroker ? createFreshnessCensus({ targetDirs }) : null;
5101
+ // The seam (reset plan section 3; gate-seam.mjs): on a broker host compiling a snapshot, every class B cargo row is one `rustright cargo` spawn in the snapshot
5102
+ // with RUSTRIGHT_GATE_COMMIT and RUSTRIGHT_CLASS_A; the Class A verdict lives under the data root, beside the snapshots. The legacy carrier is not taken.
5103
+ // The same seam is wired for the door's full class A run on the snapshot (snapshotA): that run writes the root verdict the compile (classAEarlier) reads.
5104
+ let gateSeam = null;
5105
+ const seamSnapshot = snapshotB && snapshotBCommit ? { path: snapshotB, id: snapshotBCommit, what: "class B runs as rustright cargo in" } : snapFullA && snapshotA && snapshotCommitId ? { path: snapshotA, id: snapshotCommitId, what: "class A writes the verdict for" } : null;
5106
+ if (seamSnapshot && brokerHost) {
5107
+ try {
5108
+ const snapshotPath = path.resolve(seamSnapshot.path);
5109
+ const state = JSON.parse(o.readFile(`${snapshotPath}.state.json`));
5110
+ if (state?.schema !== "rightkit.snapshot-state/1" || state.commit !== seamSnapshot.id.commit || state.tree !== seamSnapshot.id.tree || typeof state.repoKey !== "string") throw new Error(`${snapshotPath}.state.json does not describe commit ${seamSnapshot.id.commit} tree ${seamSnapshot.id.tree}`);
5111
+ // scope: what this run's class A covered, or what its class B was scoped to (--scope dirs; null = full). A door compile that is not itself scoped names the scope
5112
+ // the door's own check ran with (`seamScope`: [appDir] for an app below the repository root), so it reads that verdict (fresh review of badf93c, D2). The verdict is bound to it (gate-seam.mjs verdictForRun):
5113
+ // a class A scoped to a unit writes that unit's verdict, a class B scoped to it reads that one or a full one, never another unit's (fresh review 2026-11-09, E1).
5114
+ gateSeam = { commit: seamSnapshot.id.commit, tree: seamSnapshot.id.tree, repoKey: state.repoKey, snapshot: snapshotPath, verdictDir: path.join(path.dirname(path.dirname(snapshotPath)), "class-a-verdicts"), outputRoots: null /* a seam executable is bound by its receipt: inside the receipt outputDir and on its signed list with its sha256; no gate-derived root that could disagree with the broker */, scope: scopeDirs.length ? scopeDirs : (classAEarlier && Array.isArray(o.seamScope) && o.seamScope.length ? o.seamScope : null) };
5115
+ o.out(`${tag} seam: ${seamSnapshot.what} ${snapshotPath}, commit ${seamSnapshot.id.commit.slice(0, 12)}; Class A verdicts under ${gateSeam.verdictDir}`);
5116
+ } catch (error) { o.err(`${tag} BLOCKED: RK_SEAM: ${error.message}; nothing ran`); return 1; }
5117
+ }
4929
5118
  directTiming.cargoStart = Date.now();
4930
- census?.start();
4931
5119
  const scanOptions = {
4932
5120
  // 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.
4933
5121
  ...(snapshot ? { trackedFiles: files } : {}),
4934
- 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", groupTests: o.env.RK_GATE_GROUP_TESTS !== "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 } : {}),
5122
+ classes: classAOnly ? ["A"] : classAEarlier ? ["B"] : ["A", "B"], ...(classAEarlier ? { classAEarlier: true } : {}), jobs, classBJobs, classBBatching: !o[PRIVATE_SCOPED_COMPILE], groupTests: true, classBPipeline: 2, ...(brokerHost ? { brokerHost: true } : {}), ...(brokerLive ? { brokerLive } : {}), signal: ac.signal, ...(cache ? { cache } : {}),
4935
5123
  // NN41: the installed broker runtime's identity keys every cached compile failure; null (a direct host, an unreadable manifest) means no failure is cached.
4936
5124
  ...(brokerHost && cache ? (() => { const identity = brokerRuntimeIdentityText({ clients: [brokerClient, executor?.client, cargoCommand[0]], env: { ...o.env, ...(executor.env ?? {}) }, platform: o.platform }); return identity ? { failureIdentity: identity } : {}; })() : {}),
4937
- ...(census ? { spawn: census.wrapSpawn(defaultSpawnAsync) } : {}),
4938
5125
  // 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
4939
5126
  // executor's validated client, never a PATH lookup (withDeclaredClient).
4940
- ...(declaredClient && !scanSpawn ? { spawn: withDeclaredClient(census ? census.wrapSpawn(defaultSpawnAsync) : defaultSpawnAsync) } : {}),
5127
+ ...(declaredClient && !scanSpawn ? { spawn: withDeclaredClient(defaultSpawnAsync) } : {}),
5128
+ ...(gateSeam ? { gateSeam } : {}),
4941
5129
  toolPolicy: scanTools?.policy ?? {},
4942
5130
  // The class A cargo reads (deny, audit, metadata, fetch) are carried requests the broker executes (scanSpawn): cargo-deny and cargo-audit are then the
4943
5131
  // broker's registered tools, in the check stage too (which has no snapshotBroker). Only when the reads really go to the broker.
@@ -4952,8 +5140,6 @@ export async function main(argv, io = {}) {
4952
5140
  // 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
4953
5141
  // wrapper's identity) is in every scan's cache key, so no result cached without the wrapper or with another map is reused.
4954
5142
  ...(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 } } : {}),
4955
- // The broker snapshot compile's seam (item 7 rows 7.20 to 7.24): the commit, snapshot, ownership, enrolled pins and receipt reader.
4956
- ...(snapshotBroker ? { snapshotBroker } : {}),
4957
5143
  // `check` (and the broker's compile admission, which runs it on a captured copy of the tree without node_modules) judges the
4958
5144
  // content: it never executes the repository's own code. The class A checks that do (tests, typecheck, lint, generated docs:
4959
5145
  // `executes`) run in the full gate (--all, the push hook, the door's compile stage), after the content checks and before any compile.
@@ -4971,19 +5157,19 @@ export async function main(argv, io = {}) {
4971
5157
  return path.join(base, "rightkit-gate-scan-logs", `${path.basename(root)}-${stamp}-${process.pid}`);
4972
5158
  } catch { return null; }
4973
5159
  })(),
4974
- ...(unionScheduler ? { scheduleClassB: unionScheduler } : {}),
4975
5160
  onResult: (row, p) => o.out(`${tag} [${p.done}/${p.total}] ${(row.cached ? (row.status === "pass" ? "cached" : "cached-fail") : row.status).padEnd(11)} ${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)}` : ""}`),
4976
5161
  };
4977
5162
  // Adrian 2026-11-06: "every time should be warm". Before anything runs, every planned row is looked up in the cache. If any would miss, the
4978
5163
  // run stops with a miss report (each row, its cause and the evidence: changed inputs, tool or environment, no stored result, or nothing
4979
- // changed at all). Only Adrian's approval naming that report's digest lets those rows run (RK_GATE_MISS_APPROVAL=<file>).
5164
+ // changed at all). Every miss is explained in the report and the rows run; a miss where nothing changed is a cache bug to file with the
5165
+ // report, never a reason to stop the run or to ask Adrian (2026-11-08: explained invalidation replaces approval).
4980
5166
  if (!o.runScans && cache) {
4981
5167
  const lookup = await runScans(plan, { ...scanOptions, cacheLookupOnly: true, onResult: () => {} });
4982
5168
  const allMisses = lookup.scans.filter((r) => r.lookupMiss);
4983
5169
  // Adrian 2026-11-06: "when we change something, we know exactly which rows are going to be called. Anything other than that needs approval."
4984
5170
  // A row that misses ONLY because files in its own key changed (new content ids, no tool, toolchain, broker or environment change) is one this
4985
- // change must call: it runs, listed. Every other miss (nothing changed, no stored result, a tool or environment change) needs approval.
4986
- const expected = (r) => r.cacheMiss?.kind === "changed" && (r.cacheMiss.why?.inputsChanged ?? 0) > 0 && !r.cacheMiss.why.tool && !r.cacheMiss.why.env && !r.cacheMiss.why.inheritedEnv;
5171
+ // change must call: it runs, listed. Every other miss (nothing changed, no stored result, a tool or environment change) is reported as unexpected, with its cause.
5172
+ const expected = (r) => r.cacheMiss?.kind === "changed" && (r.cacheMiss.why?.inputsChanged ?? 0) > 0 && r.cacheMiss.why.contentOnly === true && !r.cacheMiss.why.tool && !r.cacheMiss.why.env && !r.cacheMiss.why.inheritedEnv;
4987
5173
  const called = allMisses.filter(expected);
4988
5174
  if (called.length) o.out(`${tag} cache lookup: ${called.length} row(s) rerun because their own files changed: ${called.slice(0, 12).map((r) => `${r.id} (${(r.cacheMiss.why.inputs ?? []).slice(0, 2).map((k) => k.replace(/^[^/]*\//, "")).join(", ")})`).join("; ")}${called.length > 12 ? "; ..." : ""}`);
4989
5175
  const misses = allMisses.filter((r) => !expected(r));
@@ -4997,20 +5183,16 @@ export async function main(argv, io = {}) {
4997
5183
  const envs = [...new Set(entries.flatMap((e) => e.evidence?.env ?? []))];
4998
5184
  const commitOfRun = snapshotBCommit?.commit ?? snapshotCommitId?.commit ?? null;
4999
5185
  const body = { schema: "rightkit.gate-miss-report/1", commit: commitOfRun, planned: lookup.scans.length, hit: lookup.scans.filter((r) => r.cached).length, uncacheable: lookup.scans.filter((r) => r.uncacheable).length, misses: entries.length, byCause, topChangedInputs: Object.entries(changedInputs).sort((a, b) => b[1] - a[1]).slice(0, 20), tools, env: envs, rows: entries };
5000
- const digest = createHash("sha256").update(JSON.stringify(body)).digest("hex");
5186
+ // The digest names WHAT would run and WHY (commit, row ids, causes), never evidence noise, so the same misses on a rerun match the same approval.
5187
+ const digest = createHash("sha256").update(JSON.stringify({ schema: body.schema, commit: body.commit, rows: entries.map((e) => [e.id, e.cause]) })).digest("hex");
5001
5188
  const reportFile = path.join(gateRunsRoot({ env: o.env, platform: o.platform }), "rightkit-gate-misses", `${path.basename(root)}-${new Date().toISOString().replace(/[:.]/g, "-")}-${digest.slice(0, 12)}.json`);
5002
5189
  try { fs.mkdirSync(path.dirname(reportFile), { recursive: true }); fs.writeFileSync(reportFile, `${JSON.stringify({ ...body, digest }, null, 2)}\n`); } catch { /* the summary below still names everything */ }
5003
- const approval = missApproval(o, digest, commitOfRun);
5004
5190
  o.out(`${tag} cache lookup: ${body.planned} planned, ${body.hit} hit, ${body.misses} unexpected miss(es) (${Object.entries(byCause).map(([c, n]) => `${n} ${c}`).join("; ")}), ${body.uncacheable} uncacheable by design; report ${reportFile} (digest ${digest})`);
5005
5191
  if (body.topChangedInputs.length) o.out(`${tag} cache lookup: most-changed inputs ${body.topChangedInputs.slice(0, 8).map(([k, n]) => `${k} (${n})`).join(", ")}`);
5006
5192
  if (tools.length) o.out(`${tag} cache lookup: tool changes ${tools.slice(0, 5).join("; ")}`);
5007
5193
  if (envs.length) o.out(`${tag} cache lookup: environment changes ${envs.slice(0, 10).join(", ")}`);
5008
- if (!approval.ok) {
5009
- o.err(`${tag} BLOCKED: RK_CACHE_MISS: ${body.misses} row(s) would miss the cache without a change to their own files; nothing ran. Bring the report to Adrian; his approval names its digest and covers one run (RK_GATE_MISS_APPROVAL=<file>: {digest: "${digest}", by: "adrian", reason})${approval.why ? ` (${approval.why})` : ""}`);
5010
- void prior;
5011
- return 1;
5012
- }
5013
- o.out(`${tag} ${approval.note}`);
5194
+ o.err(`${tag} RK_CACHE_MISS: ${body.misses} row(s) miss the cache without a change to their own files; they run now. Each miss is explained in the report; a miss where nothing changed is a cache bug: file it with the report`);
5195
+ void prior;
5014
5196
  } else o.out(`${tag} cache lookup: ${lookup.scans.length} planned, ${lookup.scans.filter((r) => r.cached).length} hit, ${called.length} rerun for changed files, 0 unexpected; ${lookup.scans.filter((r) => r.uncacheable).length} uncacheable by design`);
5015
5197
  }
5016
5198
  const scanResult = await (o.runScans ?? runScans)(plan, scanOptions);
@@ -5024,9 +5206,15 @@ export async function main(argv, io = {}) {
5024
5206
  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 }) };
5025
5207
  });
5026
5208
  }
5209
+ // The publisher requirements of a unit-list run, judged from the rows runScans returned (a cache lookup's rows never reach here: this is the real run).
5210
+ if (unionContext?.publisher) {
5211
+ const rowById = new Map(scanResult.scans.map((row) => [row.id, row]));
5212
+ const { scoped, dependencies, blocked, scanOf, providerOf, verify } = unionContext.publisher;
5213
+ unionContext.coverage = await judgeUnitList({ entries: scoped, dependencies, blocked, scanOf, providerOf, rowOf: (id) => rowById.get(id), verify });
5214
+ }
5027
5215
  if (unionContext) unionContext.sharedClean = unionContext.rows.filter((row) => row.sharedOrigin).every((row) => row.status === "pass");
5028
5216
  directTiming.cargoEnd = Date.now();
5029
- const freshness = census ? census.finish() : null;
5217
+ const freshness = null; // no census (reset plan section 4)
5030
5218
  directTiming.diagnostics = Date.now() - directTiming.cargoEnd;
5031
5219
  if (ac.signal.aborted) {
5032
5220
  const notRun = scanResult.scans.filter((r) => r.status !== "pass" && r.status !== "fail").map((r) => r.id);
@@ -5117,11 +5305,12 @@ export async function main(argv, io = {}) {
5117
5305
  }
5118
5306
  const outputWorkspaces = (snapshotBroker ? scanResult.scans.map((r) => r.snapshotEvidence?.outputDir) : Object.values(targetDirs ?? {})).filter(Boolean).map((dir) => [dir]);
5119
5307
  o.onCompileOutputs?.(outputWorkspaces.map(([dir]) => dir), builtBins);
5308
+ o.out(`${tag} class B keying: ${ROW_DIGEST_STATS.misses} row digest(s) computed in ${(ROW_DIGEST_STATS.ms / 1000).toFixed(1)} s, ${ROW_DIGEST_STATS.hits} reused`);
5120
5309
  if (snapshotBroker) o.out(`${tag} broker compile: ${new Set(scanResult.scans.map((r) => r.snapshotEvidence?.requestId).filter(Boolean)).size} carried request(s) with verified signed receipts (${scanResult.scans.filter((r) => r.snapshotEvidence).length} scan row(s)); no direct receipt on a broker host`);
5121
5310
  else {
5122
5311
  // The direct host's own receipt (GATE-CONTRACT "Broker interface", row 7.18): the contract's returned-evidence names minus the
5123
5312
  // broker-only ones (admission, queue, reusedFrom): the run, the commit, the snapshot's tree at start and exit, the declared
5124
- // inputs digested in place, the verdict, the freshness census (7.19), the timings, the exit status, the structured
5313
+ // inputs digested in place, the verdict, the timings, the exit status, the structured
5125
5314
  // diagnostics, the resolved output directory (7.09, with its inputs) and `refreshed` (nothing is reused on a direct host).
5126
5315
  // The gate refuses its own receipt unless it verifies, so a consumer never meets a receipt with a name missing.
5127
5316
  const requestId = randomUUID();
@@ -5135,7 +5324,7 @@ export async function main(argv, io = {}) {
5135
5324
  const diagnosticsPath = writeDirectDiagnostics({ dir: diagnosticsDir, requestId, commit: { sha: snapshotBCommit.commit, tree: snapshotBCommit.tree }, exit: exitCode, scans: scanResult.scans, failures, deferrals, notes: [...scanResult.notes, ...directDeclaredNotes], freshness });
5136
5325
  directReceipt = buildDirectReceipt({
5137
5326
  requestId, issuedAt: new Date().toISOString(), commit: { sha: snapshotBCommit.commit, tree: snapshotBCommit.tree },
5138
- snapshotPath: snapshotB, treeAtStart: snapshotBCommit.tree, treeAtExit: snapshotBCommit.tree, ownershipHandle: o.buildOwnership?.handle ?? null,
5327
+ snapshotPath: snapshotB, treeAtStart: snapshotBCommit.tree, treeAtExit: snapshotBCommit.tree, ownershipHandle: o.snapshotLock?.token ?? null,
5139
5328
  declaredInputDigests: directDeclared, verdict: directVerdict({ scans: scanResult.scans, failures, deferrals }), freshness,
5140
5329
  timingsMs: { bind: directTiming.bindEnd - directTiming.bindStart, cargo: directTiming.cargoEnd - directTiming.cargoStart, afterExitBind: directTiming.afterEnd - directTiming.afterStart, diagnostics: directTiming.diagnostics + (Date.now() - wrote) },
5141
5330
  exit: exitCode, diagnosticsPath, outputDirs: targetDirs ?? {}, outputResolution,
@@ -5211,18 +5400,11 @@ export async function main(argv, io = {}) {
5211
5400
  const SNAPSHOT_ABSOLUTE_ENV = ["CARGO_HOME", "RUSTUP_HOME", "SCCACHE_DIR", "TMPDIR", "TMP", "TEMP"];
5212
5401
 
5213
5402
  /**
5214
- * What the production entry (`node rightkit-gate.mjs ...`) hands `main` as its injected dependencies, and what `--route` reports: the
5215
- * snapshot carrier on Mac and Dell (rightkit#1301: right-release's own Cargo calls, the Tauri CLI's and cargo-about's are carried, so
5216
- * every stage compiles the commit's snapshot through the broker); nothing on Linux, which compiles direct with no broker. Tests inject
5217
- * their own carrier through `main`; the contract test (door-route.test.mjs) runs the real entry. `platform` is the host whose deps are
5218
- * asked for (the real entry passes none).
5403
+ * What the production entry (`node rightkit-gate.mjs ...`) hands `main` as its injected dependencies, and what `--route` reports: nothing. The seam (reset plan section 3) needs
5404
+ * no injected carrier: a broker host compiles through the RustRight client with the two seam variables, a direct host compiles directly. Tests inject their own through `main`.
5219
5405
  */
5220
- export async function productionEntryDeps({ platform = process.platform, env = process.env } = {}) {
5221
- // A direct Linux host carries nothing. A Linux host that DECLARED the broker route (managed-cargo.mjs linuxBrokerDeclared) gets the same carrier as the
5222
- // Mac and the Dell, valid declaration or not: an invalid one is refused by the executor (kind "refuse"), never left to compile direct without a carrier.
5223
- if (directPlatform(platform) && !linuxBrokerDeclared(env, platform)) return {};
5224
- const { PRODUCTION_SNAPSHOT_CARRIER } = await import("../snapshot-broker.mjs");
5225
- return { snapshotBroker: PRODUCTION_SNAPSHOT_CARRIER };
5406
+ export async function productionEntryDeps() {
5407
+ return {};
5226
5408
  }
5227
5409
 
5228
5410
  const invokedDirectly = (() => {
@@ -5237,7 +5419,6 @@ if (invokedDirectly) {
5237
5419
  // Every child this run starts that can reach rustright (scans, unit stages, right-release dev/test, their builds) inherits it.
5238
5420
  process.env.RUSTRIGHT_CALLING_GATE = callingGatePath();
5239
5421
  delete process.env.RIGHTKIT_CALLING_GATE; // one spelling, never both
5240
- // Production carries the snapshot carrier on Mac and Dell (rightkit#1301): every child that reaches Cargo is carried, so every stage
5241
- // compiles the commit's snapshot. Linux takes the snapshot route direct, with no carrier. Tests inject theirs.
5422
+ // Mac and Dell compile the commit's snapshot through the seam, Linux takes the snapshot route direct. Tests inject their own dependencies.
5242
5423
  productionEntryDeps().then((deps) => main(process.argv.slice(2), deps)).then((code) => process.exit(code), (e) => { console.error(`rightkit-gate: ${e?.stack ?? e}`); process.exit(2); });
5243
5424
  }