@rightkit/release 0.6.57 → 0.6.61

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/README.md +4 -0
  2. package/acceptance-admission.mjs +104 -0
  3. package/acceptance-launch.mjs +234 -0
  4. package/acceptance-lines.mjs +1254 -0
  5. package/acceptance-result.mjs +77 -0
  6. package/acceptance-rows.mjs +47 -0
  7. package/admission-files.mjs +2 -0
  8. package/affected-units.mjs +17 -0
  9. package/app-check.mjs +6 -2
  10. package/app-closure.mjs +3 -1
  11. package/bin/rightkit-gate.mjs +546 -121
  12. package/broker-admission.mjs +45 -2
  13. package/broker-pins.mjs +11 -1
  14. package/broker-toolchain.mjs +113 -0
  15. package/cargo-profile-contract.mjs +7 -2
  16. package/class-a-cache-history.mjs +135 -0
  17. package/cli/right-release.mjs +0 -0
  18. package/code-closure.mjs +24 -0
  19. package/config-inspect.mjs +6 -0
  20. package/consumer-contracts.mjs +3 -1
  21. package/contract-nn.json +166 -0
  22. package/deterministic-scans.mjs +835 -112
  23. package/feature-coverage.mjs +109 -82
  24. package/feature-partition.mjs +76 -0
  25. package/forbidden-literals.mjs +78 -0
  26. package/gate/calls.mjs +121 -0
  27. package/gate/compile.mjs +190 -0
  28. package/gate/crate-results.mjs +127 -0
  29. package/gate/run-calls.mjs +241 -0
  30. package/gate/tests.mjs +234 -0
  31. package/gate-coverage.mjs +12 -3
  32. package/gate-release-admission.mjs +200 -0
  33. package/gate-seam.mjs +100 -4
  34. package/gate-serve.mjs +178 -32
  35. package/gate-stages.mjs +59 -0
  36. package/legacy-contract-receipt.mjs +809 -0
  37. package/local-publish.mjs +2 -4
  38. package/local-runtime.mjs +2 -2
  39. package/nsis-payload.mjs +4 -3
  40. package/ownership-applicability.mjs +5 -0
  41. package/ownership-class-rules.mjs +19 -8
  42. package/ownership-mandatory-set.json +15 -21
  43. package/ownership-mandatory-set.mjs +19 -4
  44. package/package.json +14 -8
  45. package/probe-memo.mjs +252 -0
  46. package/publication-artifacts.mjs +56 -2
  47. package/publish-local-npm.mjs +3 -0
  48. package/publish-update.mjs +2 -2
  49. package/receipt-signature.mjs +40 -0
  50. package/release.mjs +47 -29
  51. package/resident-answers.mjs +66 -0
  52. package/rightkit-ownership.json +20 -11
  53. package/rightkit-versions.json +349 -183
  54. package/runtime-bundle-stage.mjs +146 -0
  55. package/scan-digest.mjs +28 -4
  56. package/seam-broker.mjs +8 -1
  57. package/shell-contract.mjs +23 -2
  58. package/snapshot-changes.mjs +106 -0
  59. package/snapshot-check.mjs +17 -13
  60. package/snapshot-dependency-reuse.mjs +186 -14
  61. package/snapshot-git.mjs +17 -1
  62. package/snapshot-metadata.mjs +155 -3
  63. package/snapshot.mjs +90 -12
  64. package/spawn-ledger.mjs +21 -2
  65. package/stage-sidecar.mjs +231 -19
  66. package/suite-trust-roots.mjs +2 -2
  67. package/test-env.mjs +26 -0
  68. package/tool-version-memo.mjs +46 -0
  69. package/win-package-recipe.mjs +11 -0
  70. package/bin/darwin/rightkit-swap +0 -0
  71. package/gate-acceptance.mjs +0 -3362
@@ -0,0 +1,146 @@
1
+ // Internal planner for a receipt-backed mixed runtime bundle. It performs no writes.
2
+ import { createHash } from "node:crypto";
3
+ import fs from "node:fs";
4
+ import path from "node:path";
5
+
6
+ const HASH = /^[0-9a-f]{64}$/;
7
+ export const runtimeBundleRelative = (value) => typeof value === "string" && value.length > 0 &&
8
+ !/[\\\x00-\x1f<>:"|?*]/.test(value) && !path.posix.isAbsolute(value) &&
9
+ value.split("/").every((part) => part && part !== "." && part !== ".." &&
10
+ !/[. ]$/.test(part) && !/^(?:con|conin\$|conout\$|prn|aux|nul|com[1-9¹²³]|lpt[1-9¹²³])(?:\.|$)/i.test(part));
11
+ const fail = (message) => { throw new Error(`runtime bundle: ${message}`); };
12
+
13
+ // Check every existing path component before any staging writer runs. Missing
14
+ // components are allowed; links, reparse points and special files are not.
15
+ export function checkRuntimeBundlePath(root, dir, io = fs) {
16
+ if (!path.isAbsolute(root) || !runtimeBundleRelative(dir)) fail("invalid root or directory");
17
+ let current = path.parse(root).root;
18
+ const parts = path.relative(current, path.resolve(root, ...dir.split("/"))).split(path.sep);
19
+ for (const part of parts) {
20
+ current = path.join(current, part);
21
+ let stat;
22
+ try { stat = io.lstatSync(current); } catch (error) {
23
+ if (error.code === "ENOENT") continue;
24
+ throw error;
25
+ }
26
+ if (stat.isSymbolicLink() || !stat.isDirectory()) fail(`unsafe directory ${current}`);
27
+ }
28
+ const bundle = path.resolve(root, ...dir.split("/"));
29
+ if (!bundle.startsWith(`${path.resolve(root)}${path.sep}`)) fail("directory escapes root");
30
+ let parent = path.resolve(root);
31
+ for (const part of dir.split("/")) {
32
+ if (io.existsSync(parent)) {
33
+ const names = io.readdirSync(parent);
34
+ const child = path.join(parent, part);
35
+ if (io.existsSync(child) && !names.includes(part)) fail(`directory spelling differs: ${part}`);
36
+ if (!names.includes(part) && names.some((name) => name.toLowerCase() === part.toLowerCase())) fail(`directory spelling differs: ${part}`);
37
+ }
38
+ parent = path.join(parent, part);
39
+ }
40
+ const walk = (folder) => {
41
+ const entries = io.readdirSync(folder, { withFileTypes: true });
42
+ const names = new Set();
43
+ for (const item of entries) {
44
+ const folded = item.name.toLowerCase();
45
+ if (names.has(folded) || (folder === bundle && folded === "manifest.json" && item.name !== "manifest.json")) fail(`case-colliding entry: ${item.name}`);
46
+ names.add(folded);
47
+ if (!runtimeBundleRelative(item.name)) fail(`unsafe path component: ${item.name}`);
48
+ const full = path.join(folder, item.name);
49
+ const stat = io.lstatSync(full);
50
+ if (stat.isSymbolicLink()) fail(`symbolic link ${full}`);
51
+ if (stat.isDirectory()) walk(full);
52
+ else if (!stat.isFile()) fail(`non-regular file ${full}`);
53
+ }
54
+ };
55
+ if (io.existsSync(bundle)) walk(bundle);
56
+ }
57
+
58
+ /** Reject aliases and links in any existing component of a planned output. */
59
+ export function checkRuntimeBundleOutput(root, output, io = fs) {
60
+ if (!path.isAbsolute(root) || !runtimeBundleRelative(output)) fail("invalid planned output");
61
+ const base = path.resolve(root);
62
+ const resolved = path.resolve(base, ...output.split("/"));
63
+ if (!resolved.startsWith(`${base}${path.sep}`)) fail("planned output escapes root");
64
+ let parent = base;
65
+ const parts = output.split("/");
66
+ for (let index = 0; index < parts.length; index += 1) {
67
+ const part = parts[index];
68
+ if (!io.existsSync(parent)) break;
69
+ const names = io.readdirSync(parent);
70
+ const child = path.join(parent, part);
71
+ if ((io.existsSync(child) && !names.includes(part)) || (!names.includes(part) && names.some((name) => name.toLowerCase() === part.toLowerCase()))) fail(`output spelling differs: ${output}`);
72
+ if (!names.includes(part)) break;
73
+ const stat = io.lstatSync(child);
74
+ if (stat.isSymbolicLink() || (index < parts.length - 1 && !stat.isDirectory()) || (index === parts.length - 1 && !stat.isDirectory() && !stat.isFile())) fail(`unsafe output: ${output}`);
75
+ parent = child;
76
+ }
77
+ }
78
+
79
+ /** Build strict rightkit-onnx schema 1 from outputs already verified by staging.
80
+ * `catalogRow` is the actual selected, validated catalog row, not a caller-supplied substitute.
81
+ * `rows` are earlier stage receipt rows; nested notices carry their own digest.
82
+ */
83
+ export function planRuntimeBundle({ root, dir, target, identity, catalogRow, rows, io = fs }) {
84
+ checkRuntimeBundlePath(root, dir, io);
85
+ if (!identity || ![identity.version, identity.variant, identity.catalogRow].every((v) => typeof v === "string" && v.trim() === v && v)) fail("invalid ONNX identity");
86
+ if (!target || !["macos", "windows", "linux"].includes(target.os) || !["aarch64", "x86_64", "universal"].includes(target.arch)) fail("invalid target");
87
+ const row = catalogRow;
88
+ const servingArch = row?.arch === target.arch || (target.os === "macos" && target.arch !== "universal" && row?.arch === "universal");
89
+ if (!row || row.library !== "onnxruntime" || row.id !== identity.catalogRow || row.version !== identity.version || row.os !== target.os || !servingArch || !["approved", "pinned"].includes(row.status)) fail("ONNX identity does not match selected catalog row");
90
+ if (row.variant !== undefined && row.variant !== identity.variant) fail("ONNX variant does not match catalog");
91
+ const directml = Array.isArray(row.companions) && row.companions.some((id) => typeof id === "string" && /^directml-/.test(id));
92
+ if (directml && identity.variant !== "directml") fail("ONNX variant conflicts with DirectML companion");
93
+ if (identity.variant === "directml" && !directml) fail("ONNX catalog row has no DirectML companion");
94
+ if (!Array.isArray(rows)) fail("missing stage rows");
95
+ const base = `${dir}/`;
96
+ const candidates = [];
97
+ for (const item of rows) {
98
+ if (item.path?.startsWith(base)) candidates.push(item);
99
+ for (const notice of item.notices ?? []) if (notice.path?.startsWith(base)) candidates.push(notice);
100
+ }
101
+ const onnx = rows.filter((item) => (item.kind === "onnxruntime" || (item.kind === "native-library" && item.library === "onnxruntime")) && item.path?.startsWith(base) && !item.companionOf);
102
+ if (onnx.length !== 1 || onnx[0].catalogRow !== row.id || onnx[0].version !== row.version) fail("expected exactly one matching staged ONNX row in bundle");
103
+ const canonicalOnnx = { windows: "onnxruntime.dll", macos: "libonnxruntime.dylib", linux: "libonnxruntime.so" }[target.os];
104
+ if (onnx[0].path !== `${base}${canonicalOnnx}`) fail("ONNX file does not have the runtime loader's canonical name");
105
+ if (directml) {
106
+ const companions = row.companions.filter((id) => typeof id === "string" && /^directml-/.test(id));
107
+ if (companions.length !== 1 || rows.filter((item) => ((item.kind === "native-library" && item.library === "directml") || (item.kind === "onnxruntime" && item.companionOf === row.id)) && item.catalogRow === companions[0] && item.path === `${base}DirectML.dll`).length !== 1) fail("selected DirectML companion was not staged in bundle");
108
+ }
109
+ const listed = new Map();
110
+ for (const item of candidates) {
111
+ const name = item.path.slice(base.length);
112
+ if (!runtimeBundleRelative(name) || name.toLowerCase() === "manifest.json" || !HASH.test(item.sha256 ?? "")) fail("invalid staged file row");
113
+ const key = name.toLowerCase();
114
+ const previous = listed.get(key);
115
+ if (previous) {
116
+ if (previous.path !== name || previous.sha256 !== item.sha256) fail(`conflicting staged file ${name}`);
117
+ continue;
118
+ }
119
+ const full = path.resolve(root, ...item.path.split("/"));
120
+ const bundleRoot = path.resolve(root, ...dir.split("/"));
121
+ if (!full.startsWith(`${bundleRoot}${path.sep}`)) fail(`file escapes bundle: ${name}`);
122
+ let parent = bundleRoot;
123
+ for (const part of name.split("/")) {
124
+ if (!io.readdirSync(parent).includes(part)) fail(`file spelling differs: ${name}`);
125
+ parent = path.join(parent, part);
126
+ }
127
+ const stat = io.lstatSync(full);
128
+ if (!stat.isFile() || stat.isSymbolicLink()) fail(`not a regular file: ${name}`);
129
+ const bytes = io.readFileSync(full);
130
+ if (createHash("sha256").update(bytes).digest("hex") !== item.sha256 || (item.sizeBytes !== undefined && item.sizeBytes !== bytes.length)) fail(`staged file changed: ${name}`);
131
+ listed.set(key, { path: name, sha256: item.sha256, bytes: bytes.length });
132
+ }
133
+ if (!listed.size) fail("empty bundle");
134
+ const bundle = path.resolve(root, ...dir.split("/"));
135
+ const walk = (folder, prefix = "") => {
136
+ for (const item of io.readdirSync(folder, { withFileTypes: true })) {
137
+ const name = prefix ? `${prefix}/${item.name}` : item.name;
138
+ if (item.isDirectory()) walk(path.join(folder, item.name), name);
139
+ else if (name !== "manifest.json" && listed.get(name.toLowerCase())?.path !== name) fail(`unlisted file: ${name}`);
140
+ }
141
+ };
142
+ walk(bundle);
143
+ const files = [...listed.values()].sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
144
+ const arch = { x86_64: "x64", aarch64: "arm64", universal: "universal" }[target.arch];
145
+ return { schema: 1, platform: `${target.os}-${arch}`, onnxruntime: { version: identity.version, variant: identity.variant, catalogRow: identity.catalogRow }, files };
146
+ }
package/scan-digest.mjs CHANGED
@@ -52,12 +52,35 @@ export const rustScanId = Object.freeze({
52
52
  * (feature-sets.mjs) is absent from every list; `none` is true when the crate declares sets and none of them is planned on this host.
53
53
  * `platform` may be left out only for a crate with no host-scoped set. Pure.
54
54
  */
55
- export function rustCratePlan(own = {}, platform = undefined, crate = "<crate>") {
55
+ /**
56
+ * NN27: whether a planned `check` feature set compiles a configuration a clippy set of the same crate already compiles. Only the default
57
+ * `--all-features` check is judged (a set the crate's config names in checkFeatureSets is kept as written): it is redundant when some lint set turns
58
+ * on every feature the crate declares (no features at all, or all of them named). `declared`: the crate's declared feature names, or null when its
59
+ * manifest cannot be read (then nothing is dropped).
60
+ */
61
+ export function allFeaturesCheckIsRedundant({ set, declared, lintSets, explicit = false }) {
62
+ if (explicit || !Array.isArray(declared) || !(set.length === 1 && set[0] === "--all-features")) return false;
63
+ const enabledBy = (l) => {
64
+ if (l.includes("--all-features")) return null;
65
+ const on = new Set();
66
+ for (let i = 0; i < l.length; i += 1) {
67
+ const v = l[i] === "--features" || l[i] === "-F" ? l[i + 1] : l[i].startsWith("--features=") ? l[i].slice(11) : null;
68
+ if (v) for (const f of v.split(/[\s,]+/).filter(Boolean)) on.add(f);
69
+ }
70
+ return on;
71
+ };
72
+ return lintSets.some((l) => { const on = enabledBy(l); return on !== null && declared.every((f) => on.has(f)); });
73
+ }
74
+
75
+ // `declaredFeatures`: the crate's declared Cargo feature names when the caller can read its manifest (the planner and requiredScanIds both pass them,
76
+ // so the rows planned and the rows required agree); without them no check set is dropped.
77
+ export function rustCratePlan(own = {}, platform = undefined, crate = "<crate>", declaredFeatures = null) {
56
78
  const configured = Array.isArray(own?.featureSets) && own.featureSets.length > 0;
57
79
  const declaredSets = configured ? hostFeatureSets(own, platform, "featureSets", crate) : [[]];
58
80
  const crossSets = configured ? crossFeatureSets(own, platform, "featureSets", crate) : declaredSets;
59
81
  const checkList = Array.isArray(own?.checkFeatureSets) ? hostFeatureSets(own, platform, "checkFeatureSets", crate) : null;
60
- return planFrom(own, { configured, declaredSets, crossSets, checkList, crate });
82
+ const plan = planFrom(own, { configured, declaredSets, crossSets, checkList, crate });
83
+ return { ...plan, checkSets: plan.checkSets.filter((set) => !allFeaturesCheckIsRedundant({ set, declared: declaredFeatures, lintSets: plan.lintSets, explicit: checkList !== null })) };
61
84
  }
62
85
 
63
86
  /**
@@ -153,7 +176,8 @@ export const REQUIRED_SCAN_PREFIXES = Object.freeze(["rustfmt:"]);
153
176
  * `crateFeatures` is ci/gate.config.json `rust`. `includeTests` adds the per-feature-set test scans. Extra scans in a record are
154
177
  * allowed; a missing one is not. planScans builds its ids from the same helpers, and a test holds the two in agreement.
155
178
  */
156
- export function requiredScanIds({ units, crateFeatures = {}, platform = undefined, exists, includeTests = false, perCrateWorkspaces = undefined, clippyBatching = false, shardSolo = [], clippySeparate = new Map(), sidecarBound = new Set() }) {
179
+ // `declaredFeaturesOf(name)`: the crate's declared Cargo feature names (rustCratePlan), so the required rows match the planned ones.
180
+ export function requiredScanIds({ units, crateFeatures = {}, platform = undefined, exists, declaredFeaturesOf = () => null, includeTests = false, perCrateWorkspaces = undefined, clippyBatching = false, shardSolo = [], clippySeparate = new Map(), sidecarBound = new Set() }) {
157
181
  if (!Array.isArray(units) || units.length === 0 || !units.every((n) => typeof n === "string" && n)) throw new TypeError("requiredScanIds: units must be a non-empty array of names");
158
182
  if (typeof exists !== "function") throw new TypeError("requiredScanIds: exists(repoPath) is required");
159
183
  // One Cargo workspace and lock per crate (rightkit#1285): every unit has its own crates/<name>/Cargo.lock, so the per-workspace scans
@@ -168,7 +192,7 @@ export function requiredScanIds({ units, crateFeatures = {}, platform = undefine
168
192
  for (const name of units) {
169
193
  const own = crateFeatures?.[name] ?? {};
170
194
  // `platform`: the host that produced the record; a crate with host-scoped feature sets (feature-sets.mjs) owes that host's sets only.
171
- const { lintSets, baseSets, defaultCheck, checkSets, none } = rustCratePlan(own, platform, name);
195
+ const { lintSets, baseSets, defaultCheck, checkSets, none } = rustCratePlan(own, platform, name, declaredFeaturesOf(name));
172
196
  if (perCrate) {
173
197
  for (const id of ["cargo-metadata", "cargo-deny", "cargo-audit"]) ids.add(`${id}:${name}`);
174
198
  if (exists(`crates/${name}/.rightkit/advisory-exceptions.json`)) ids.add(`advisory-exceptions:${name}`);
package/seam-broker.mjs CHANGED
@@ -4,7 +4,7 @@ import fs from "node:fs";
4
4
  import path from "node:path";
5
5
  import { resolveBrokerClient } from "./broker-client.mjs";
6
6
  import { discoverBrokerSocket } from "./managed-roots.mjs";
7
- import { CLASS_A_ENV, CLASS_A_VERDICT_SCHEMA, GATE_COMMIT_ENV, classAVerdict, judgeSeamOutcome, seamSettled, snapshotStatusAllowsReclaim, snapshotStatusMessage, snapshotStatusSync, writeClassAVerdict } from "./gate-seam.mjs";
7
+ import { CLASS_A_ENV, CLASS_A_VERDICT_SCHEMA, GATE_COMMIT_ENV, classAVerdict, judgeSeamOutcome, seamSettled, snapshotStatusAllowsReclaim, snapshotStatusMessage, snapshotStatusSync, writeClassAVerdict, contractJobTag, recordContractJob, RECEIPT_NONCE_ENV } from "./gate-seam.mjs";
8
8
  import { spawnSync as nodeSpawnSync } from "node:child_process";
9
9
 
10
10
  /** `rustright_protocol::BUILD_CONTROL_PROTOCOL`: carried in every request envelope, the seam's SNAPSHOT_STATUS query included. */
@@ -54,6 +54,12 @@ function runSeamCall(argv, { cwd, env, stdio = "pipe", client = "rustright", spa
54
54
  try { classA = verdictForCwd(env, cwd, { fsApi }); }
55
55
  catch (error) { const message = `the Class A verdict for ${cwd} cannot be named (${error.message}); nothing was submitted`; return { result: { status: 125, signal: null, stdout: "", stderr: `rightkit-gate: RK_SEAM_VERDICT: ${message}\n`, error: null, refusal: { code: "RK_SEAM_VERDICT", message } }, ledger: { status: "refused", settled: true, code: "RK_SEAM_VERDICT", message } }; }
56
56
  env = { ...env, [CLASS_A_ENV]: classA };
57
+ // A contract-test run tags this job (gate-seam.mjs contractJobTag). An inherited nonce is never reused: each job gets its own or none.
58
+ let tag = null;
59
+ try { tag = contractJobTag(env); }
60
+ catch (error) { const message = `${error.message}; nothing was submitted`; return { result: { status: 125, signal: null, stdout: "", stderr: `rightkit-gate: RK_CONTRACT_RUN: ${message}\n`, error: null, refusal: { code: "RK_CONTRACT_RUN", message } }, ledger: { status: "refused", settled: true, code: "RK_CONTRACT_RUN", message } }; }
61
+ delete env[RECEIPT_NONCE_ENV];
62
+ if (tag) env[RECEIPT_NONCE_ENV] = tag.nonce;
57
63
  const r = spawnSync(client, argv, { cwd, env, stdio: stdio === "inherit" ? ["ignore", "inherit", "pipe"] : "pipe", encoding: "utf8", maxBuffer });
58
64
  if (r.error) return { result: { status: 1, signal: null, stdout: "", stderr: String(r.error.message ?? r.error), error: r.error, refusal: { code: "SPAWN_ERROR", message: String(r.error.message ?? r.error) } }, ledger: { status: "unsettled", settled: false, code: "SPAWN_ERROR" } };
59
65
  const judged = judgeSeamOutcome({ child: r, stderr: r.stderr ?? "", commit: env[GATE_COMMIT_ENV], tree: null, classA, expect });
@@ -62,6 +68,7 @@ function runSeamCall(argv, { cwd, env, stdio = "pipe", client = "rustright", spa
62
68
  const settled = seamSettled(judged);
63
69
  const status = pass ? (r.status ?? 0) : (Number.isInteger(r.status) && r.status !== 0 ? r.status : (preAdmissionRefusal ? 125 : 1));
64
70
  const evidence = judged.evidence ? { outputDir: judged.evidence.outputDir, targetTriple: judged.evidence.targetTriple, requestId: judged.evidence.requestId, receipt: judged.evidence.receiptPath, receiptSha256: judged.evidence.receiptSha256 } : {};
71
+ if (tag) { try { recordContractJob(tag, { argv, cwd, requestId: evidence.requestId ?? judged.result?.requestId ?? null, receipt: evidence.receipt ?? null, receiptSha256: evidence.receiptSha256 ?? null, status }, { fsApi }); } catch { /* the contract test finds the job missing from its list and fails the run */ } }
65
72
  return {
66
73
  result: { status, signal: r.signal ?? null, stdout: r.stdout ?? "", stderr: r.stderr ?? "", error: null, ...evidence, ...(pass ? {} : { refusal: { code: judged.code, message: judged.detail } }) },
67
74
  ledger: { status: pass ? "verified" : !settled ? "unsettled" : preAdmissionRefusal ? "refused" : "failed", settled, ...(pass ? {} : { code: judged.code, message: String(judged.detail ?? "").slice(0, 2000) }), ...evidence },
@@ -820,10 +820,31 @@ const qaWindowLabel = perApp(({ app, root }) => {
820
820
  else if (c === ")" || c === "]") depth = Math.max(0, depth - 1);
821
821
  else if (depth === 0 && (c === ";" || c === "{")) { end = k; break; }
822
822
  }
823
+ // Read this constructor's own balanced receiver chain. A previous cfg
824
+ // block can make the surrounding statement end before the constructor.
825
+ let label;
826
+ let chainedWindow = false;
827
+ let cursor = m.index + m[0].length;
828
+ for (;;) {
829
+ const method = /^\s*\.\s*([A-Za-z_]\w*)\s*\(/.exec(f.skel.slice(cursor));
830
+ if (!method) break;
831
+ const open = cursor + method[0].length - 1;
832
+ const close = matchClose(f.skel, open);
833
+ if (close < 0) break;
834
+ if (method[1] === "window") {
835
+ chainedWindow = true;
836
+ const [arg] = callArgs(f.skel, open);
837
+ const literal = arg && /^\s*"([^"]*)"\s*$/.exec(f.code.slice(arg[0], arg[1]));
838
+ label = literal?.[1];
839
+ }
840
+ cursor = close + 1;
841
+ }
842
+ // Retain existing named-binding lookup while its full Rust scope analysis
843
+ // remains outside this direct receiver repair.
823
844
  const statement = f.code.slice(start, end);
824
- let label = /\.\s*window\s*\(\s*"([^"]*)"\s*\)/.exec(f.code.slice(m.index, end))?.[1];
825
845
  const bound = /^\s*let\s+(?:mut\s+)?([A-Za-z_]\w*)\b/.exec(statement)?.[1];
826
- if (label === undefined && bound && fn) label = new RegExp(`\\b${bound}\\s*\\.\\s*window\\s*\\(\\s*"([^"]*)"\\s*\\)`).exec(f.code.slice(m.index, fn.bodyEnd))?.[1];
846
+ if (!chainedWindow && bound) label = /\.\s*window\s*\(\s*"([^"]*)"\s*\)/.exec(f.code.slice(m.index, end))?.[1];
847
+ if (!chainedWindow && label === undefined && bound && fn) label = new RegExp(`\\b${bound}\\s*\\.\\s*window\\s*\\(\\s*"([^"]*)"\\s*\\)`).exec(f.code.slice(m.index, fn.bodyEnd))?.[1];
827
848
  const mismatch = label === undefined ? shellLabel !== "main" : label !== shellLabel;
828
849
  if (!mismatch) continue;
829
850
  const bind = label === undefined ? 'no .window(..), so it binds "main"' : `.window("${label}")`;
@@ -0,0 +1,106 @@
1
+ // Which paths of a snapshot changed since its tree was last proven, and what that leaves to prove (GATE-CONTRACT NN11).
2
+ //
3
+ // NN11: a run hashes the snapshot's tree at most once. Until 2026-11-19 every proof that was not answered "nothing changed" hashed the whole
4
+ // tree again (`git add -A`, `git write-tree`): a first run of the witness fixture hashed it 6 times for a check and 9 times for a compile,
5
+ // because each stage writes its outputs into the snapshot (installed dependencies, build outputs) and every event there dropped the proof.
6
+ //
7
+ // The open gate process (gate-serve.mjs) sees every change by name. So it keeps, per snapshot, the paths that changed since the tree was
8
+ // proven; a later proof walks the snapshot as before (the walk refuses anything that is not the commit or an admitted output) and then checks
9
+ // only the commit's files that those changes could have touched, each against the commit's own blob id. A stage that wrote only outputs touched
10
+ // none of them. The tree id is a function of the commit's files alone once the walk has passed, so it is still the proven one.
11
+ //
12
+ // What is kept is deliberately coarse in the safe direction:
13
+ // - `changed`: paths whose content or metadata changed (the watcher's "change"). A commit file is checked when it IS such a path.
14
+ // - `renamed`: paths that appeared, disappeared or were renamed (the watcher's "rename"). A directory renamed into place brings its whole
15
+ // content without one event per file, so a commit file is checked when it is such a path OR lies under one.
16
+ // - past MAX_PATHS the two sets collapse to their first two path components, kept as `renamed` (everything under them is checked); past
17
+ // MAX_PREFIXES, or after an event without a name, nothing is known and the caller hashes the tree.
18
+ // When the files to check are ALL of the commit's files, that is a whole-tree hash by another name: the caller hashes the tree and counts it.
19
+ import { createHash } from "node:crypto";
20
+ import fs from "node:fs";
21
+ import path from "node:path";
22
+
23
+ export const MAX_PATHS = 5000;
24
+ export const MAX_PREFIXES = 2000;
25
+ const LINK_MODE = "120000";
26
+
27
+ const slash = (p) => String(p ?? "").split(/[\\/]+/).filter(Boolean).join("/");
28
+ const prefixOf = (rel) => rel.split("/").slice(0, 2).join("/");
29
+
30
+ /** The record the open process keeps for one snapshot since its tree was proven. `touch(type, rel)`: one watcher event, `rel` relative to the snapshot. */
31
+ export function createChangeLedger({ maxPaths = MAX_PATHS, maxPrefixes = MAX_PREFIXES } = {}) {
32
+ let changed = new Set(); let renamed = new Set(); let collapsed = false; let unknown = false;
33
+ const collapse = () => {
34
+ const next = new Set();
35
+ for (const p of [...changed, ...renamed]) next.add(prefixOf(p));
36
+ changed = new Set(); renamed = next; collapsed = true;
37
+ if (renamed.size > maxPrefixes) { unknown = true; renamed = new Set(); }
38
+ };
39
+ return {
40
+ touch(type, rel) {
41
+ if (unknown) return;
42
+ const p = slash(rel);
43
+ // The snapshot directory itself: a "change" is its own listing or metadata (each entry that changed reports under its own name); a
44
+ // "rename" is the directory replaced, and then nothing under it is known.
45
+ if (!p) { if (type !== "change") { unknown = true; changed = new Set(); renamed = new Set(); } return; }
46
+ if (collapsed) { renamed.add(prefixOf(p)); if (renamed.size > maxPrefixes) { unknown = true; renamed = new Set(); } return; }
47
+ (type === "change" ? changed : renamed).add(p);
48
+ if (changed.size + renamed.size > maxPaths) collapse();
49
+ },
50
+ /** `{ changed: [...], renamed: [...] }`, or null when it is not known what changed. */
51
+ list() { return unknown ? null : { changed: [...changed].sort(), renamed: [...renamed].sort() }; },
52
+ get unknown() { return unknown; },
53
+ };
54
+ }
55
+
56
+ /** The git blob id of `bytes` under `objectFormat` ("sha1" or "sha256"). */
57
+ export function blobOid(bytes, objectFormat = "sha1") {
58
+ return createHash(objectFormat === "sha256" ? "sha256" : "sha1").update(`blob ${bytes.length}\0`).update(bytes).digest("hex");
59
+ }
60
+
61
+ /**
62
+ * The commit's entries (`[{ path, mode, oid }]`) that the changes could have touched. On a file system that folds case (Windows, macOS) paths
63
+ * are compared without case: the watcher names a path as it was written, the commit as it was committed.
64
+ */
65
+ export function entriesToRecheck(entries, changes, { platform = process.platform } = {}) {
66
+ const fold = platform === "win32" || platform === "darwin" ? (s) => s.toLowerCase() : (s) => s;
67
+ const exact = new Set((changes?.changed ?? []).map((p) => fold(slash(p))));
68
+ const roots = (changes?.renamed ?? []).map((p) => fold(slash(p)));
69
+ const rootSet = new Set(roots);
70
+ const under = (p) => { if (rootSet.has(p)) return true; let at = p.lastIndexOf("/"); while (at > 0) { if (rootSet.has(p.slice(0, at))) return true; at = p.lastIndexOf("/", at - 1); } return false; };
71
+ return entries.filter((e) => { const p = fold(e.path); return exact.has(p) || under(p); });
72
+ }
73
+
74
+ /**
75
+ * Whether the tree proven before still stands after `changes`: `{ ok: true, checked }` when every commit file the changes could have touched
76
+ * still has the commit's bytes, else `{ ok: false, why }` and the caller hashes the tree (which then says exactly what differs). Never ok when
77
+ * nothing is known (`changes` null), when every file of the commit would have to be checked, or when a touched entry is a link (the tree hash
78
+ * judges how a link is held on this platform).
79
+ */
80
+ export function treeStandsAfterChanges({ dir, entries, changes, objectFormat = null, platform = process.platform, read = (f) => fs.readFileSync(f), lstat = (f) => fs.lstatSync(f) }) {
81
+ if (!changes || !Array.isArray(changes.changed) || !Array.isArray(changes.renamed)) return { ok: false, why: "what changed is not known" };
82
+ if (!Array.isArray(entries) || entries.length === 0) return { ok: false, why: "the commit has no files to compare" };
83
+ const named = new Set(entriesToRecheck(entries, changes, { platform }));
84
+ // Every commit file is looked at (not read): one that is missing, or that has a second name (a hard link: pnpm links a `file:` package's
85
+ // files into node_modules, and a write through that other name is reported under it, never under the commit's path; review 2026-11-19),
86
+ // is compared whatever the change record says.
87
+ const stats = new Map();
88
+ for (const e of entries) {
89
+ let st = null; try { st = lstat(path.join(dir, ...e.path.split("/"))); } catch { st = null; }
90
+ stats.set(e, st);
91
+ if (!st || st.nlink > 1) named.add(e);
92
+ }
93
+ const touched = entries.filter((e) => named.has(e));
94
+ if (touched.length === entries.length) return { ok: false, why: "every file of the commit may have changed: that is a whole-tree hash" };
95
+ for (const e of touched) {
96
+ if (e.mode === LINK_MODE) return { ok: false, why: `${e.path} is a link` };
97
+ const file = path.join(dir, ...e.path.split("/"));
98
+ const st = stats.get(e);
99
+ if (!st) { try { lstat(file); } catch (error) { return { ok: false, why: `${e.path}: ${error?.code ?? "cannot be read"}` }; } return { ok: false, why: `${e.path}: cannot be read` }; }
100
+ if (!st.isFile() || st.isSymbolicLink?.()) return { ok: false, why: `${e.path} is not a regular file` };
101
+ let bytes; try { bytes = read(file); } catch (error) { return { ok: false, why: `${e.path}: ${error?.code ?? "cannot be read"}` }; }
102
+ // The id says which hash made it: 40 hex is SHA-1, 64 is SHA-256. No question to git is needed.
103
+ if (blobOid(bytes, objectFormat ?? (String(e.oid).length === 64 ? "sha256" : "sha1")) !== e.oid) return { ok: false, why: `${e.path} is not the commit's bytes` };
104
+ }
105
+ return { ok: true, checked: touched.length };
106
+ }
@@ -23,9 +23,9 @@ import path from "node:path";
23
23
  import { serveRequest } from "./gate-serve.mjs";
24
24
  import { LIVE_SCAN_IDS, defaultSpawn, isLiveScan, isRegistryScan, launchGuardEnv, planScans, runScans } from "./deterministic-scans.mjs";
25
25
  import { compileLaunch } from "./class-a-launch-guard.mjs";
26
- import { SnapshotError, dependencyDirs, isInside, snapshotProblem, snapshotTree, treeEntries } from "./snapshot.mjs";
26
+ import { SnapshotError, dependencyDirs, isInside, noteChangeSource, snapshotProblem, snapshotTree, treeEntries, treeProvenByChanges, SNAPSHOT_PROOF_COUNTS } from "./snapshot.mjs";
27
27
  import { discoveryRun, sealedRun } from "./snapshot-git.mjs";
28
- import { snapshotDependencyReuse } from "./snapshot-dependency-reuse.mjs";
28
+ import { pnpmVersionAnswer, snapshotDependencyReuse } from "./snapshot-dependency-reuse.mjs";
29
29
  import { gateRunsRoot } from "./managed-roots.mjs";
30
30
  import { writePerformanceDiagnostic } from "./performance-diagnostic.mjs";
31
31
 
@@ -120,7 +120,7 @@ export function commitOf(checkout, rev, spawn = defaultSpawn) { // eslint-disabl
120
120
  * (the entries an earlier verify returned) and/or `admitNew` (the END of a stage only), the stage's own ignored, untracked outputs
121
121
  * are admitted and the ledger must still match exactly. Then the result is `{ tree, ledger: [{ path, type, size, sha256, execBit }] }`.
122
122
  */
123
- export function verifySnapshotDir({ checkout, dir, commit, tree, when, ledger, admitNew }) {
123
+ export function verifySnapshotDir({ checkout, dir, commit, tree, when, ledger, admitNew, resident = serveRequest }) {
124
124
  const diagnosticDir = process.env.RIGHTKIT_PREPARATION_DIAGNOSTIC_DIR;
125
125
  const labels = new Map([["before the check", "before-check"], ["after the check", "after-check"], ["before class A", "before-class-a"], ["after class A", "after-class-a"], ["before dependency installation", "before-dependencies"], ["after dependency installation and probes", "after-dependencies"], ["after reused dependency probes", "after-reuse"], ["after failed dependency installation cleanup", "failed-dependencies"], ["before the offline store check", "before-store"], ["after the offline store check", "after-store"], ["for env-digest", "env-digest"]]);
126
126
  const phase = labels.get(when) ?? 'other';
@@ -130,23 +130,27 @@ export function verifySnapshotDir({ checkout, dir, commit, tree, when, ledger, a
130
130
  // full verify takes the change generation first and records the proof after it passes. Any doubt means the full verify below.
131
131
  const plain = ledger === undefined && admitNew !== true;
132
132
  let generation = null;
133
- if (plain) {
134
- const c = serveRequest({ op: "check", dir, tree }, { root: path.dirname(path.resolve(dir)) });
135
- if (c?.clean === true) { rows.push({ label: `${phase}-resident-proof`, ms: 0, count: 1 }); if (diagnosticDir) writePerformanceDiagnostic(diagnosticDir, 'snapshot-verify', rows); return tree; }
133
+ // Asked in every case (NN11): with a ledger the answer is never "nothing changed", but it still says what changed since the tree was proven.
134
+ const c = noteChangeSource(resident({ op: "check", dir, tree }, { root: path.dirname(path.resolve(dir)) }));
135
+ {
136
+ if (plain && c?.clean === true) { SNAPSHOT_PROOF_COUNTS.residentProofs += 1; rows.push({ label: `${phase}-resident-proof`, ms: 0, count: 1 }); if (diagnosticDir) writePerformanceDiagnostic(diagnosticDir, 'snapshot-verify', rows); return tree; }
136
137
  if (Number.isInteger(c?.generation)) generation = c.generation;
137
138
  }
138
139
  try {
139
140
  const ledgerMode = ledger !== undefined || admitNew === true;
140
- let inspected;
141
- try { const entries = timed('tree-entries', () => treeEntries(checkout, commit)); inspected = timed('walk', () => snapshotProblem({ dir, entries, checkout, commit, ledger, admitNew })); }
141
+ let inspected; let entries;
142
+ try { entries = timed('tree-entries', () => treeEntries(checkout, commit)); SNAPSHOT_PROOF_COUNTS.verifyWalks += 1; inspected = timed('walk', () => snapshotProblem({ dir, entries, checkout, commit, ledger, admitNew })); }
142
143
  catch (e) { throw new CheckError(`cannot list snapshot ${dir} ${when}: ${e.message}`); }
143
144
  const extra = ledgerMode ? inspected.problem : inspected;
144
145
  if (extra) throw new CheckError(`snapshot ${dir} is not exactly commit ${commit}${ledgerMode ? " plus its stage-output ledger" : ""} ${when}: ${extra}`);
145
146
  let actual;
146
- try { actual = timed('tree-hash', () => snapshotTree({ checkout, dir, baseTree: tree })); }
147
+ // NN11: the walk passed. When the open gate process knows what changed since this tree was proven, only the commit's files those changes
148
+ // could have touched are compared with the commit's blobs (snapshot.mjs treeProvenByChanges); otherwise the tree is hashed.
149
+ try { actual = c?.base && timed('changed-files', () => treeProvenByChanges({ reply: c, dir, tree, entries })) ? tree : timed('tree-hash', () => snapshotTree({ checkout, dir, baseTree: tree })); }
147
150
  catch (e) { throw new CheckError(`cannot compute the tree of snapshot ${dir} ${when}: ${e.message}`); }
148
151
  if (actual !== tree) throw new CheckError(`snapshot ${dir} is tree ${actual} ${when}, not tree ${tree} of commit ${commit}`);
149
- if (plain && generation !== null) serveRequest({ op: "record", dir, tree, generation });
152
+ // A plain verify found exactly the commit: "record". With a ledger the commit's files are this tree beside admitted outputs: "tree-record".
153
+ if (generation !== null) resident({ op: plain ? "record" : "tree-record", dir, tree, generation });
150
154
  return ledgerMode ? { tree: actual, ledger: inspected.admitted } : actual;
151
155
  } finally { if (diagnosticDir) writePerformanceDiagnostic(diagnosticDir, 'snapshot-verify', rows); }
152
156
  }
@@ -326,7 +330,7 @@ export function installSnapshotDependencies({ checkout, snapshot, commit, tree,
326
330
  verifySnapshotDir({ checkout, dir: base, commit, tree, when: "after failed dependency installation cleanup", ...(ledger !== undefined ? { ledger } : {}) });
327
331
  };
328
332
  };
329
- const versionOf = (cwd) => { const r = spawn("pnpm", ["--version"], { cwd, env: { ...env, COREPACK_ENABLE_AUTO_PIN: "0" } }); return failed(r) ? null : text(r).trim().split(/\r?\n/).pop(); };
333
+ const versionOf = (cwd) => { const probeEnv = { ...env, COREPACK_ENABLE_AUTO_PIN: "0" }; return pnpmVersionAnswer({ cwd, env: probeEnv, remember: spawn === defaultSpawn, run: () => { const r = spawn("pnpm", ["--version"], { cwd, env: probeEnv }); return failed(r) ? null : text(r).trim().split(/\r?\n/).pop(); } }); };
330
334
  for (const root of roots) {
331
335
  const dir = path.resolve(base, root);
332
336
  if (!inside(dir, base)) throw new CheckError(`root ${root}: dependency install is outside the snapshot`);
@@ -348,7 +352,7 @@ export function installSnapshotDependencies({ checkout, snapshot, commit, tree,
348
352
  const ownedDirs = generated.filter((d) => nearestLock(fold(dirOf(d))) === owner);
349
353
  const reuseStarted = performance.now();
350
354
  const reuseDiagnostic = {};
351
- const reuse = snapshotDependencyReuse({ checkout, snapshot: base, tree, root, dirs: ownedDirs, filters, storeDir, version, env, spawn, diagnostic: reuseDiagnostic });
355
+ const reuse = snapshotDependencyReuse({ checkout, snapshot: base, tree, root, dirs: ownedDirs, filters, storeDir, version, env, spawn, diagnostic: reuseDiagnostic, remember: spawn === defaultSpawn });
352
356
  if (reuse?.matches()) {
353
357
  const skipped = probe ? probe({ dir, root, names: allowedBuilds(dir), spawn, env }) : [];
354
358
  if (reuse.matches()) {
@@ -417,7 +421,7 @@ export function verifySnapshotStore({ checkout, snapshot, commit, tree, ledger,
417
421
  } catch (error) { throw new CheckError(`the snapshot store check needs a real snapshot directory: ${snapshot}: ${error.message}`); }
418
422
  if (inside(base, checkout) || inside(checkout, base)) throw new CheckError(`snapshot ${base} and checkout ${checkout} overlap`);
419
423
  verifySnapshotDir({ checkout, dir: base, commit, tree, when: "before the offline store check", ...(ledger !== undefined ? { ledger } : {}) });
420
- const versionOf = (cwd) => { const r = spawn("pnpm", ["--version"], { cwd, env: { ...env, COREPACK_ENABLE_AUTO_PIN: "0" } }); return failed(r) ? null : text(r).trim().split(/\r?\n/).pop(); };
424
+ const versionOf = (cwd) => { const probeEnv = { ...env, COREPACK_ENABLE_AUTO_PIN: "0" }; return pnpmVersionAnswer({ cwd, env: probeEnv, remember: spawn === defaultSpawn, run: () => { const r = spawn("pnpm", ["--version"], { cwd, env: probeEnv }); return failed(r) ? null : text(r).trim().split(/\r?\n/).pop(); } }); };
421
425
  for (const root of roots) {
422
426
  const dir = path.resolve(base, root);
423
427
  if (!inside(dir, base)) throw new CheckError(`root ${root}: the store check is outside the snapshot`);