@rightkit/release 0.6.56 → 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 +7 -5
  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
@@ -6,6 +6,10 @@ import path from 'node:path';
6
6
  import crypto from 'node:crypto';
7
7
  import { fileURLToPath } from 'node:url';
8
8
  import { installIdentity } from './dependency-identity.mjs';
9
+ import { answerKey, fileMarks, recallAnswer, rememberAnswer } from './resident-answers.mjs';
10
+ import { resolveOnPath } from './tool-version-memo.mjs';
11
+
12
+ const PER_RUN_BOOKKEEPING = /^(?:RK_GATE_|RIGHTKIT_BUILD_OWNERSHIP$|RUSTRIGHT_GATE_RUN$|RUSTRIGHT_QUIET_LEASE$|RIGHTKIT_CARRIED_CARGO_MAP$|RUSTRIGHT_ATTEST_NONCE$|RUSTRIGHT_RECEIPT_NONCE$|RUSTRIGHT_REQUEST_ID_FILE$|RUSTRIGHT_SNAPSHOT_REQUEST$|RK_DIRECT_RECEIPT$)/;
9
13
 
10
14
  const hash = (bytes) => crypto.createHash('sha256').update(bytes).digest('hex');
11
15
  const inside = (p, dir) => p === dir || p.startsWith(dir + path.sep);
@@ -102,9 +106,50 @@ export async function capturePostClassADiagnostics({ checkout, snapshot, commit,
102
106
  } catch { /* diagnostics never change the gate result */ }
103
107
  }
104
108
 
109
+ /**
110
+ * NN12, Windows: the program `pnpm` starts, named by its bytes, or null when it cannot be named exactly (then preparation runs, as before).
111
+ * Found as the gate starts it (deterministic-scans.mjs resolveInvocation: PATH and PATHEXT, never the current directory). Recognised:
112
+ * - a cmd shim whose one `%*` line runs `"%~dp0\<path>"`: the path as written when it has an extension, else what cmd runs for it, the
113
+ * first of `<path>.exe` / `<path>.com` beside it (pnpm 11+'s global install: `pnpm.CMD` runs `...\node_modules\pnpm\pnpm`, which cmd
114
+ * completes to the native `pnpm.exe`). A `.js`/`.cjs`/`.mjs` target counts with the node that runs it (this process's).
115
+ * - a `pnpm.exe` / `pnpm.com` found directly.
116
+ * Anything else (corepack, a version manager, a shim with several commands or a variable) is not named. Every file is hashed in full.
117
+ * Exported for its test; `platform`, `exists`, `readFile` and `execPath` are injectable.
118
+ */
119
+ export function windowsPnpmIdentity(env, { exists = (f) => { try { return fs.statSync(f).isFile(); } catch { return false; } }, readFile = (f) => fs.readFileSync(f), execPath = process.execPath, pathsOnly = false } = {}) {
120
+ const w = path.win32;
121
+ const pathKey = Object.keys(env ?? {}).find((k) => k.toLowerCase() === 'path');
122
+ const exts = String(env?.PATHEXT || '.COM;.EXE;.BAT;.CMD').split(';').filter(Boolean).map((e) => e.toLowerCase());
123
+ let found = null;
124
+ for (const dir of String(env?.[pathKey] ?? '').split(';').filter(Boolean)) {
125
+ if (!w.isAbsolute(dir)) continue;
126
+ for (const ext of exts) { const f = w.join(dir, `pnpm${ext}`); if (exists(f)) { found = f; break; } }
127
+ if (found) break;
128
+ }
129
+ if (!found) return null;
130
+ // pathsOnly: the caller takes the files' marks itself (large programs by size and time), so no file is hashed here; the
131
+ // caller's readFile may then return only a prefix of a large file, which still carries the MZ signature this check needs.
132
+ const named = pathsOnly ? (f) => [f, ''] : (f) => [f, hash(readFile(f))];
133
+ if (/\.(exe|com)$/i.test(found)) return [named(found)];
134
+ if (!/\.(cmd|bat)$/i.test(found)) return null;
135
+ const text = readFile(found).toString('utf8');
136
+ const runs = text.split(/\r?\n/).filter((l) => l.includes('%*'));
137
+ if (runs.length !== 1) return null;
138
+ const m = /^\s*@?"%~dp0\\?([^"%]+)"\s+%\*\s*$/.exec(runs[0]);
139
+ if (!m) return null;
140
+ const target = w.resolve(w.dirname(found), m[1]);
141
+ if (/\.(m?js|cjs)$/i.test(target)) return exists(target) ? [named(found), named(target), named(execPath)] : null;
142
+ if (w.extname(target)) return null;
143
+ for (const ext of ['.exe', '.com']) {
144
+ if (!exists(target + ext)) continue;
145
+ const bytes = readFile(target + ext);
146
+ return bytes.subarray(0, 2).toString('latin1') === 'MZ' ? [named(found), pathsOnly ? [target + ext, ''] : [target + ext, hash(bytes)]] : null;
147
+ }
148
+ return null;
149
+ }
150
+
105
151
  function pnpmIdentity(env) {
106
- // Do not infer Windows cmd/corepack dispatch or arbitrary shell programs.
107
- if (process.platform === 'win32') return null;
152
+ if (process.platform === 'win32') return windowsPnpmIdentity(env);
108
153
  for (const dir of String(env.PATH ?? '').split(path.delimiter)) {
109
154
  if (!dir || !path.isAbsolute(dir)) continue;
110
155
  const p = path.join(dir, 'pnpm');
@@ -140,12 +185,132 @@ export function canonicalConfigFingerprint(effective, files) {
140
185
  return hash(JSON.stringify({ effective: canonical(effective), files }));
141
186
  }
142
187
 
143
- function pnpmConfigIdentity({ dir, env, spawn }) {
188
+ // NN07 (Dell 2026-11-19, S2_check2 ledger): one gate run asked pnpm the same three config questions three times over (9 starts, one process).
189
+ // pnpm's answers depend on the directory and the environment it is started with, so one run asks each question once per (dir, env) and keeps the
190
+ // answer in memory only (never written, never logged). The two config files are still read and hashed on every call, so an edit of either one
191
+ // changes the fingerprint; a failed question is not remembered.
192
+ const PNPM_CONFIG_ANSWERS = new Map();
193
+ export const forgetPnpmConfigAnswers = () => PNPM_CONFIG_ANSWERS.clear();
194
+ /**
195
+ * The files a pnpm answer given in `dir` with `env` depends on, beyond the question, the directory and the environment (which are in the answer's
196
+ * key). `program` is the pnpm PATH resolves, or null when it cannot be named beyond doubt (then nothing is ever kept).
197
+ * - The program and what it starts. On Windows the launcher alone says nothing (a `pnpm.cmd` has the same bytes across pnpm versions), so the
198
+ * launcher, the script or executable it names and the node that runs it are all listed (windowsPnpmIdentity, the same proof the Class A key
199
+ * uses), with the `package.json` of the pnpm package it belongs to. Elsewhere the resolved program, its real path and that `package.json`.
200
+ * - Every `.npmrc`, `pnpm-workspace.yaml` and `package.json` from `dir` up to the root of the drive (project and workspace settings, the
201
+ * `packageManager` pin), the home `.npmrc`, pnpm's own rc files, node's built-in npmrc, corepack's last-known-good record, and the config
202
+ * files the environment names.
203
+ * A file that does not exist is a dependency too: one that appears later changes the answer.
204
+ */
205
+ export function pnpmConfigDependencies({ dir, env, platform = process.platform, execPath = process.execPath }) {
206
+ const e = env ?? {};
207
+ const files = [];
208
+ let program = null;
209
+ const packageJsonAbove = (file) => { let at = path.dirname(file); for (let i = 0; i < 4; i += 1) { files.push(path.join(at, 'package.json')); if (path.dirname(at) === at) break; at = path.dirname(at); } };
210
+ if (platform === 'win32') {
211
+ // Paths only: the marks are taken by the caller (large programs by size and time), so nothing big is read here — a large
212
+ // file gives its first two bytes, which carry the MZ signature windowsPnpmIdentity checks (an empty read named nothing).
213
+ const small = (f) => { try { if (fs.statSync(f).size <= (1 << 20)) return fs.readFileSync(f); const fd = fs.openSync(f, 'r'); try { const b = Buffer.alloc(2); fs.readSync(fd, b, 0, 2, 0); return b; } finally { fs.closeSync(fd); } } catch { return Buffer.alloc(0); } };
214
+ let identity = null;
215
+ try { identity = windowsPnpmIdentity(e, { execPath, readFile: small, pathsOnly: true }); } catch { identity = null; }
216
+ if (Array.isArray(identity) && identity.length) {
217
+ program = identity[0][0];
218
+ for (const [f] of identity) files.push(f);
219
+ if (identity[1]) packageJsonAbove(identity[1][0]);
220
+ }
221
+ } else {
222
+ const found = resolveOnPath('pnpm', { env: e, platform });
223
+ if (found) {
224
+ program = found; files.push(found);
225
+ let real = found; try { real = fs.realpathSync(found); } catch { real = found; }
226
+ if (real !== found) files.push(real);
227
+ packageJsonAbove(real); files.push(execPath);
228
+ }
229
+ }
230
+ for (let at = path.resolve(String(dir)); ; at = path.dirname(at)) {
231
+ for (const name of ['.npmrc', 'pnpm-workspace.yaml', 'package.json']) files.push(path.join(at, name));
232
+ if (path.dirname(at) === at) break;
233
+ }
234
+ const home = platform === 'win32' ? (e.USERPROFILE ?? e.HOME) : e.HOME;
235
+ if (home) files.push(path.join(home, '.npmrc'), path.join(home, '.config', 'pnpm', 'rc'), path.join(home, 'Library', 'Preferences', 'pnpm', 'rc'));
236
+ if (e.LOCALAPPDATA) files.push(path.join(e.LOCALAPPDATA, 'pnpm', 'config', 'rc'));
237
+ if (e.XDG_CONFIG_HOME) files.push(path.join(e.XDG_CONFIG_HOME, 'pnpm', 'rc'));
238
+ files.push(path.join(path.dirname(execPath), 'etc', 'npmrc'), path.join(path.dirname(execPath), 'node_modules', 'npm', 'npmrc'));
239
+ const corepackHome = e.COREPACK_HOME ?? (platform === 'win32' ? (e.LOCALAPPDATA ? path.join(e.LOCALAPPDATA, 'node', 'corepack') : null) : (home ? path.join(home, '.cache', 'node', 'corepack') : null));
240
+ if (corepackHome) files.push(path.join(corepackHome, 'lastKnownGood.json'));
241
+ for (const [name, value] of Object.entries(e)) if (/^npm_config_(userconfig|globalconfig)$/i.test(name) && typeof value === 'string' && path.isAbsolute(value)) files.push(value);
242
+ return { program, files: [...new Set(files)] };
243
+ }
244
+
245
+ /**
246
+ * `pnpm --version` as pnpm answers it in `cwd` with `env` (NN25, NN07; Dell 2026-11-19, every warm check: five such starts, two of them the same
247
+ * bounded probe). `run()` asks pnpm and returns the version line or null; it may throw, and nothing is kept then. With `remember` the open gate
248
+ * process keeps the answer under the directory and the environment less the gate's per-run bookkeeping, and gives it back only while the files
249
+ * that decide which pnpm runs there still have the marks they had before pnpm was asked (pnpmConfigDependencies).
250
+ */
251
+ /**
252
+ * The inputs that can make `pnpm --version` answered in `dir` differ from the PATH pnpm's own version: the nearest `packageManager`
253
+ * pin up the tree (what pnpm/corepack would switch to) and an explicit `manage-package-manager-versions` setting. Two directories
254
+ * whose switch inputs, program and environment all agree ask the same question, so their answer is shared (NN07: the bounded
255
+ * probe for the Class A environment and the one for the pin check started the same helper twice in one run). Read fresh on every
256
+ * call, so a pin or setting that appears is a new question at once; the stored marks still guard everything else.
257
+ */
258
+ export function pnpmVersionSwitchInputs({ dir }) {
259
+ let pin = '', manageVersions = '';
260
+ for (let at = path.resolve(String(dir)); ; at = path.dirname(at)) {
261
+ if (!pin) {
262
+ try {
263
+ const pm = JSON.parse(fs.readFileSync(path.join(at, 'package.json'), 'utf8'))?.packageManager;
264
+ if (typeof pm === 'string' && pm) { const m = /^pnpm@(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)(?:\+.*)?$/.exec(pm.trim()); pin = m ? m[1] : `other:${pm}`; }
265
+ } catch { /* no readable package.json at this level */ }
266
+ }
267
+ if (!manageVersions) {
268
+ for (const name of ['pnpm-workspace.yaml', '.npmrc']) {
269
+ try { const m = /manage-package-manager-versions["']?\s*[:=]\s*["']?([A-Za-z0-9._-]+)/.exec(fs.readFileSync(path.join(at, name), 'utf8')); if (m) { manageVersions = m[1]; break; } } catch { /* absent */ }
270
+ }
271
+ }
272
+ if (path.dirname(at) === at) break;
273
+ }
274
+ return { pin, manageVersions };
275
+ }
276
+
277
+ export function pnpmVersionAnswer({ cwd, env, remember = false, run, ask }) {
278
+ const dependencies = remember ? pnpmConfigDependencies({ dir: cwd, env }) : null;
279
+ const lastingEnv = dependencies?.program ? Object.entries(env ?? {}).filter(([name]) => !PER_RUN_BOOKKEEPING.test(String(name).toUpperCase())).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)) : null;
280
+ const key = dependencies?.program ? answerKey(['rightkit.pnpm-version-answer/3', dependencies.program, lastingEnv, pnpmVersionSwitchInputs({ dir: cwd })]) : null;
281
+ const kept = key ? recallAnswer(key, { env, ...(ask ? { ask } : {}) }) : null;
282
+ if (kept) return kept;
283
+ const marks = key ? fileMarks(dependencies.files) : null;
284
+ const version = run();
285
+ if (key && typeof version === 'string' && /^\d+\.\d+\.\d+/.test(version)) rememberAnswer(key, version, marks, { env, ...(ask ? { ask } : {}) });
286
+ return version;
287
+ }
288
+
289
+ export function pnpmConfigIdentity({ dir, env, spawn, remember = false }) {
144
290
  const fail = (code) => { const e = new Error(code); e.reuseCode = code; throw e; };
291
+ // The files pnpm's answers depend on, as they are now. They are part of this run's own memory key too: a project `.npmrc` or a workspace
292
+ // setting edited between two calls of one run (install, then match) asks pnpm again, as it did before answers were kept at all.
293
+ const dependencies = pnpmConfigDependencies({ dir, env });
294
+ const marksNow = fileMarks(dependencies.files);
295
+ const scope = hash(JSON.stringify([path.resolve(String(dir)), Object.entries(env ?? {}).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)), marksNow]));
296
+ // NN25 (Dell 2026-11-19, every warm check: `pnpm config list --json`, `get userconfig`, `get globalconfig`): with `remember` (the real spawn
297
+ // only; an injected spawn sees every call) the open gate process keeps each answer for the runs after this one (resident-answers.mjs). It is
298
+ // keyed by the question, the directory and the environment less the gate's per-run bookkeeping (the reuse record's own rule, below), and is
299
+ // given back only while every file it depends on still has the mark it had before pnpm was asked. No pnpm program named: nothing is kept.
300
+ const lastingEnv = remember ? Object.entries(env ?? {}).filter(([name]) => !PER_RUN_BOOKKEEPING.test(String(name).toUpperCase())).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)) : null;
301
+ const lastingKey = (args) => (remember && dependencies.program ? answerKey(['rightkit.pnpm-config-answer/2', path.resolve(String(dir)), lastingEnv, args]) : null);
145
302
  const ask = (args) => {
303
+ const key = `${scope}\u0000${args.join(' ')}`;
304
+ if (PNPM_CONFIG_ANSWERS.has(key)) return PNPM_CONFIG_ANSWERS.get(key);
305
+ const lasting = lastingKey(args);
306
+ const kept = lasting ? recallAnswer(lasting, { env }) : null;
307
+ if (kept !== null) { PNPM_CONFIG_ANSWERS.set(key, kept); return kept; }
146
308
  const r = spawn('pnpm', ['config', ...args], { cwd: dir, env, maxBuffer: 1 << 24 });
147
309
  if (r?.status !== 0 || r?.error || r?.signal) fail(args[0] === 'list' ? 'config-list-failed' : 'config-path-query-failed');
148
- return String(r.stdout ?? '').trim();
310
+ const answer = String(r.stdout ?? '').trim();
311
+ PNPM_CONFIG_ANSWERS.set(key, answer);
312
+ if (lasting && (answer || args[0] !== 'list')) rememberAnswer(lasting, answer, marksNow, { env });
313
+ return answer;
149
314
  };
150
315
  const effective = ask(['list', '--json']);
151
316
  if (!effective) fail('config-list-empty');
@@ -153,7 +318,9 @@ function pnpmConfigIdentity({ dir, env, spawn }) {
153
318
  try { parsed = JSON.parse(effective); } catch { fail('config-json-invalid'); }
154
319
  const user = ask(['get', 'userconfig']);
155
320
  const global = ask(['get', 'globalconfig']);
156
- const userPath = user && user !== 'undefined' && user !== 'null' ? user : (env.HOME ? path.join(env.HOME, '.npmrc') : null);
321
+ // pnpm's default userconfig is ~/.npmrc, home being USERPROFILE on Windows (os.homedir): the Dell gate runs with no HOME (NN12, 2026-11-18: config-path-unknown).
322
+ const home = process.platform === 'win32' ? (env.USERPROFILE ?? env.HOME) : env.HOME;
323
+ const userPath = user && user !== 'undefined' && user !== 'null' ? user : (home ? path.join(home, '.npmrc') : null);
157
324
  if (!userPath || !path.isAbsolute(userPath) || !global || global === 'undefined' || global === 'null' || !path.isAbsolute(global)) fail('config-path-unknown');
158
325
  const file = (p) => {
159
326
  try { return [p, fs.realpathSync(p), hash(fs.readFileSync(p))]; }
@@ -163,20 +330,25 @@ function pnpmConfigIdentity({ dir, env, spawn }) {
163
330
  }
164
331
 
165
332
  export function preparationInputComponents({ source, toolchain, config, store, env }) {
166
- // The per-run ownership handle is a gate lock token, not pnpm input. Keep
167
- // every other non-scheduling variable, including the ownership file path.
168
- const excluded = new Set(['RK_GATE_JOBS', 'RK_GATE_CLASS_B_JOBS', 'RIGHTKIT_BUILD_OWNERSHIP']);
169
- const environment = Object.entries(env).filter(([name]) => !excluded.has(name)).sort(([a], [b]) => a.localeCompare(b));
333
+ // The whole environment is keyed, less only the gate's own per-run bookkeeping, which no install reads: RK_GATE_* (the gate's and the contract
334
+ // test's switches, ledger path, run id and step: "RK_GATE_* never enters a cache key", gate-acceptance.mjs doRun) and the per-run identities the
335
+ // row cache already excludes as measured per-run (deterministic-scans.mjs BUILD_ENV_EXCLUDED: ownership handle, nonces, request files). NN12,
336
+ // Dell 2026-11-18: every gate launch carries its own RK_GATE_SPAWN_LEDGER and contract step, so no run's key ever matched the last one. Everything
337
+ // else stays keyed, so a variable an install hook might read can never be left out (astra62 review 2: an allowlist modelled pnpm, it did not prove it).
338
+ // Why RK_GATE_* as a whole is safe to leave out (astra62 review 3): the install runs with --ignore-scripts and --ignore-pnpmfile
339
+ // (snapshot-check.mjs installSnapshotDependencies), so no code of the repository or its packages runs during it, and pnpm reads its own
340
+ // npm_config_/pnpm_ variables, never the gate's namespace.
341
+ const environment = Object.entries(env ?? {}).filter(([name]) => !PER_RUN_BOOKKEEPING.test(String(name).toUpperCase())).sort(([a], [b]) => a.localeCompare(b));
170
342
  return Object.fromEntries(Object.entries({ source, toolchain, config, store, environment }).map(([name, value]) => [name, hash(JSON.stringify(value))]));
171
343
  }
172
344
 
173
- export function snapshotDependencyReuse({ checkout, snapshot, tree, root, dirs, filters, storeDir, version, env, spawn, diagnostic = {} }) {
345
+ export function snapshotDependencyReuse({ checkout, snapshot, tree, root, dirs, filters, storeDir, version, env, spawn, diagnostic = {}, remember = false }) {
174
346
  let stage = 'pnpm-identity';
175
347
  try {
176
348
  const executable = pnpmIdentity(env);
177
349
  if (!executable) { diagnostic.setup = 'pnpm-unresolved'; return null; }
178
350
  stage = 'git-common';
179
- const git = spawn('git', ['rev-parse', '--git-common-dir'], { cwd: checkout, env });
351
+ const git = spawn('git', ['rev-parse', '--path-format=absolute', '--git-common-dir'], { cwd: checkout, env });
180
352
  if (git?.status !== 0) { diagnostic.setup = 'git-common-failed'; return null; }
181
353
  const common = String(git.stdout ?? '').trim();
182
354
  if (!common) { diagnostic.setup = 'git-common-empty'; return null; }
@@ -184,7 +356,7 @@ export function snapshotDependencyReuse({ checkout, snapshot, tree, root, dirs,
184
356
  const recordPath = path.join(cacheDir, `${hash(`${fs.realpathSync(snapshot)}\0${root}`)}.json`);
185
357
  // Hash values in memory; only the final digest is persisted, never env.
186
358
  stage = 'config';
187
- const config = pnpmConfigIdentity({ dir: path.resolve(snapshot, root), env, spawn });
359
+ const config = pnpmConfigIdentity({ dir: path.resolve(snapshot, root), env, spawn, remember });
188
360
  stage = 'input-identity';
189
361
  const components = preparationInputComponents({ source: { checkout: fs.realpathSync(checkout), snapshot: fs.realpathSync(snapshot), tree, root, dirs: [...dirs].sort(), filters }, toolchain: { pnpm: executable, version, node: [fs.realpathSync(process.execPath), hash(fs.readFileSync(process.execPath)), process.version], platform: [process.platform, process.arch], gate: packageIdentity() }, config, store: fs.realpathSync(storeDir), env });
190
362
  const inputs = hash(JSON.stringify(components));
@@ -196,7 +368,7 @@ export function snapshotDependencyReuse({ checkout, snapshot, tree, root, dirs,
196
368
  matches() {
197
369
  let phase = 'config';
198
370
  try {
199
- if (pnpmConfigIdentity({ dir: path.resolve(snapshot, root), env, spawn }) !== config) { diagnostic.match = 'config-changed'; return false; }
371
+ if (pnpmConfigIdentity({ dir: path.resolve(snapshot, root), env, spawn, remember }) !== config) { diagnostic.match = 'config-changed'; return false; }
200
372
  phase = 'record';
201
373
  const record = JSON.parse(fs.readFileSync(recordPath, 'utf8'));
202
374
  if (record.schema !== 5 || !record.components || typeof record.components !== 'object' || typeof record.dependencies !== 'string') { diagnostic.match = 'record-invalid'; return false; }
@@ -212,7 +384,7 @@ export function snapshotDependencyReuse({ checkout, snapshot, tree, root, dirs,
212
384
  save() {
213
385
  let phase = 'config';
214
386
  try {
215
- if (pnpmConfigIdentity({ dir: path.resolve(snapshot, root), env, spawn }) !== config) { diagnostic.save = 'config-changed'; return; }
387
+ if (pnpmConfigIdentity({ dir: path.resolve(snapshot, root), env, spawn, remember }) !== config) { diagnostic.save = 'config-changed'; return; }
216
388
  phase = 'digest';
217
389
  digestChecks++;
218
390
  const { digest, capture } = dependencyProof(snapshot, dirs, diagnosticDir);
package/snapshot-git.mjs CHANGED
@@ -176,14 +176,30 @@ export function sealedRun(checkout, args, options = {}) {
176
176
  // arguments and the output encoding; at most TREE_LISTING_MEMO_MAX listings are kept.
177
177
  const memoKey = immutableListingKey(info, args, options);
178
178
  if (memoKey !== null && treeListingMemo.has(memoKey)) return { ...treeListingMemo.get(memoKey) };
179
+ // NN22: and across gate processes, from the listing store (setTreeListingStore). Keyed like the memo, never on the working directory: a sealed
180
+ // call runs in a fresh private directory each time, so a key holding it never matched (astra62 review, 2026-11-18).
181
+ const kept = memoKey !== null && listingStore ? listingStore.get(memoKey) : null;
182
+ if (kept) {
183
+ const stdout = options.binary === true ? kept : kept.toString("utf8"); const stderr = options.binary === true ? Buffer.alloc(0) : "";
184
+ const stored = { pid: 0, status: 0, signal: null, stdout, stderr, output: [null, stdout, stderr] };
185
+ if (treeListingMemo.size >= TREE_LISTING_MEMO_MAX) treeListingMemo.delete(treeListingMemo.keys().next().value);
186
+ treeListingMemo.set(memoKey, stored); listingStats.stored += 1;
187
+ return { ...stored };
188
+ }
179
189
  const result = withSealedGit({ ...info, snapshot: options.snapshot }, (git) => git.run(args, options));
180
190
  if (memoKey !== null && result && result.status === 0 && !result.error) {
181
191
  if (treeListingMemo.size >= TREE_LISTING_MEMO_MAX) treeListingMemo.delete(treeListingMemo.keys().next().value);
182
192
  treeListingMemo.set(memoKey, result);
193
+ if (listingStore) listingStore.put(memoKey, Buffer.isBuffer(result.stdout) ? result.stdout : Buffer.from(String(result.stdout ?? ""), "utf8"));
183
194
  }
184
195
  return result;
185
196
  }
186
197
 
198
+ let listingStore = null;
199
+ const listingStats = { stored: 0 };
200
+ /** Keep sealed whole-tree listings of a full object id between gate processes in `store` ({ get(key), put(key, bytes) }: probe-memo.mjs contentStore); null turns it off. Returns the counters. */
201
+ export function setTreeListingStore(store) { listingStore = store && typeof store.get === "function" && typeof store.put === "function" ? store : null; listingStats.stored = 0; return listingStats; }
202
+
187
203
  const TREE_LISTING_MEMO_MAX = 4;
188
204
  const treeListingMemo = new Map();
189
205
  /** The memo key of an `ls-tree -r ... --full-tree <full object id>` call, or null for anything else (never cached). */
@@ -192,5 +208,5 @@ function immutableListingKey(info, args, options) {
192
208
  const target = args[args.length - 1];
193
209
  if (!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(String(target))) return null;
194
210
  if (args.slice(1, -1).some((a) => !/^-/.test(String(a)))) return null;
195
- return JSON.stringify([info.commonDir, info.objectFormat, args, options.encoding ?? null, options.maxBuffer ?? null]);
211
+ return JSON.stringify([info.commonDir, info.objectFormat, args, options.encoding ?? null, options.maxBuffer ?? null, options.binary === true]);
196
212
  }
@@ -18,6 +18,8 @@
18
18
  // the database directory audit reads are absolute, exist (a file; a directory) and lie outside the live checkout.
19
19
  import fs from "node:fs";
20
20
  import path from "node:path";
21
+ import { createHash } from "node:crypto";
22
+ import { createRequire } from "node:module";
21
23
  import { CARGO_REFUSAL_STATUS } from "./cargo-ledger.mjs";
22
24
  import { GATE_COMMIT_ENV } from "./gate-seam.mjs";
23
25
 
@@ -26,6 +28,146 @@ export const CARRIED_METADATA_REFUSED = "RK_SNAPSHOT_CARRIED_REFUSED";
26
28
  const real = (p) => { try { return fs.realpathSync.native(p); } catch { return path.resolve(p); } };
27
29
  const within = (child, parent) => { const rel = path.relative(parent, child); return rel === "" || !(rel === ".." || rel.startsWith(`..${path.sep}`) || path.isAbsolute(rel)); };
28
30
 
31
+ /** Project Cargo's discovery answer onto snapshot-relative paths so another verified snapshot can use it. */
32
+ export function cargoWorkspaceFacts({ root, stdout, realpath = fs.realpathSync }) {
33
+ const metadata = JSON.parse(stdout);
34
+ if (typeof metadata?.workspace_root !== "string" || !Array.isArray(metadata.packages)) throw new Error("cargo metadata lacks workspace_root or packages");
35
+ const resolve = (p) => { try { return realpath(p); } catch { return path.resolve(p); } };
36
+ const rootPath = resolve(root);
37
+ const relative = (absolute) => {
38
+ if (!path.isAbsolute(absolute)) throw new Error(`cargo metadata path ${absolute} is not absolute`);
39
+ const resolved = resolve(absolute);
40
+ if (!within(resolved, rootPath)) throw new Error(`cargo metadata path ${absolute} is outside the repository`);
41
+ return path.relative(rootPath, resolved).replaceAll(path.sep, "/") || ".";
42
+ };
43
+ const cargoDir = relative(metadata.workspace_root);
44
+ const members = metadata.packages.map((pkg) => {
45
+ if (typeof pkg?.name !== "string" || !pkg.name || typeof pkg.manifest_path !== "string") throw new Error("cargo metadata package lacks name or manifest_path");
46
+ const dir = relative(path.dirname(pkg.manifest_path));
47
+ const kinds = (t) => Array.isArray(t.kind) ? t.kind : [];
48
+ const unconditional = (t) => !(t["required-features"] ?? t.required_features ?? []).length;
49
+ const targets = pkg.targets ?? [];
50
+ const bins = targets.filter((t) => kinds(t).includes("bin") && unconditional(t)).map((t) => t.name).sort();
51
+ const testLinksBins = targets.some((t) => kinds(t).includes("test") && t.test !== false && unconditional(t));
52
+ return { name: pkg.name, dir, manifest: path.posix.join(dir, "Cargo.toml"), publish: !(Array.isArray(pkg.publish) && pkg.publish.length === 0), bins, testLinksBins };
53
+ }).sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
54
+ return { cargoDir, members };
55
+ }
56
+
57
+ const load = createRequire(import.meta.url);
58
+
59
+ /**
60
+ * Bind discovery to what Cargo can read under the snapshot. An exact local member or dependency has a finite
61
+ * read set. A member glob or path escaping the snapshot needs Cargo to discover its inputs, so leave it unproven.
62
+ */
63
+ export function cargoWorkspaceTopology({ root, dir, cargoHome, fsApi = fs, parse = (source) => load("smol-toml").parse(source) }) {
64
+ try {
65
+ const base = fsApi.realpathSync(root);
66
+ const workspace = path.resolve(base, dir);
67
+ if (!within(workspace, base) || !path.isAbsolute(cargoHome ?? "")) return null;
68
+ const files = new Map();
69
+ const targetDirs = new Map();
70
+ const snapshotName = (absolute) => path.relative(base, absolute).replaceAll(path.sep, "/") || ".";
71
+ const stat = (absolute) => {
72
+ let entry;
73
+ try { entry = fsApi.lstatSync(absolute); } catch (error) { if (error.code === "ENOENT" || error.code === "ENOTDIR") return null; throw error; }
74
+ if (entry.isSymbolicLink() || path.relative(absolute, fsApi.realpathSync(absolute))) throw new Error("linked Cargo discovery input");
75
+ return entry;
76
+ };
77
+ const read = (absolute) => {
78
+ const key = within(absolute, base) ? snapshotName(absolute) : absolute;
79
+ const entry = stat(absolute);
80
+ if (entry && !entry.isFile()) throw new Error("Cargo discovery input is not a regular file");
81
+ const bytes = entry ? fsApi.readFileSync(absolute) : null;
82
+ files.set(key, bytes ? createHash("sha256").update(bytes).digest("hex") : null);
83
+ return bytes;
84
+ };
85
+ const local = (at, value) => {
86
+ if (typeof value !== "string" || !value || /[:\\\0]/.test(value) || path.isAbsolute(value)) throw new Error("nonportable Cargo path");
87
+ const resolved = path.resolve(at, value);
88
+ if (!within(resolved, base)) throw new Error("Cargo path escapes snapshot");
89
+ return resolved;
90
+ };
91
+ const inspectConfig = (configDir) => {
92
+ for (const name of ["config", "config.toml"]) {
93
+ const bytes = read(path.join(configDir, name));
94
+ if (!bytes) continue;
95
+ const config = parse(String(bytes));
96
+ if (config.paths !== undefined || config.patch !== undefined || config.include !== undefined) throw new Error("Cargo config extends the discovery read set");
97
+ }
98
+ };
99
+ for (let at = workspace; ; at = path.dirname(at)) {
100
+ inspectConfig(path.join(at, ".cargo"));
101
+ read(path.join(at, "rust-toolchain"));
102
+ read(path.join(at, "rust-toolchain.toml"));
103
+ if (within(at, base)) read(path.join(at, "Cargo.lock"));
104
+ else if (read(path.join(at, "Cargo.toml"))) return null;
105
+ if (path.dirname(at) === at) break;
106
+ }
107
+ inspectConfig(cargoHome);
108
+ const target = (absolute) => {
109
+ const entry = stat(absolute);
110
+ targetDirs.set(snapshotName(absolute), entry ? (entry.isDirectory() ? "dir" : entry.isFile() ? "file" : "other") : null);
111
+ return entry;
112
+ };
113
+ const manifests = new Set();
114
+ const includeAncestors = (start) => {
115
+ for (let at = start; within(at, base); at = path.dirname(at)) {
116
+ manifests.add(path.join(at, "Cargo.toml"));
117
+ if (at === base) break;
118
+ }
119
+ };
120
+ includeAncestors(workspace);
121
+ for (const absolute of manifests) {
122
+ const bytes = read(absolute);
123
+ if (!bytes) {
124
+ if (absolute === path.join(workspace, "Cargo.toml")) return null;
125
+ continue;
126
+ }
127
+ const at = path.dirname(absolute);
128
+ const doc = parse(String(bytes));
129
+ const follow = (parent, value) => {
130
+ const member = local(parent, value);
131
+ if (!stat(path.join(member, "Cargo.toml"))?.isFile()) throw new Error("Cargo dependency or member manifest is missing");
132
+ includeAncestors(member);
133
+ };
134
+ for (const name of ["members", "exclude", "default-members"]) {
135
+ const entries = doc.workspace?.[name] ?? [];
136
+ if (!Array.isArray(entries) || entries.some((item) => typeof item !== "string" || /[*?\[\]{}]/.test(item))) return null;
137
+ if (name !== "exclude") for (const member of entries) follow(at, member);
138
+ else for (const member of entries) local(at, member);
139
+ }
140
+ const dependencyTables = [doc.workspace?.dependencies, doc.replace, ...Object.values(doc.patch ?? {})];
141
+ for (const holder of [doc, ...Object.values(doc.target ?? {})]) {
142
+ for (const name of ["dependencies", "build-dependencies", "dev-dependencies", "build_dependencies", "dev_dependencies"]) dependencyTables.push(holder[name]);
143
+ }
144
+ for (const dependencies of dependencyTables) for (const spec of Object.values(dependencies ?? {})) {
145
+ if (spec?.path !== undefined) follow(at, spec.path);
146
+ }
147
+ if (!doc.package) continue;
148
+ if (doc.package.workspace !== undefined) follow(at, doc.package.workspace);
149
+ if (typeof doc.package.build === "string") target(local(at, doc.package.build));
150
+ for (const name of ["lib", "bin", "test", "bench", "example"]) {
151
+ for (const declared of [].concat(doc[name] ?? [])) if (declared.path !== undefined) target(local(at, declared.path));
152
+ }
153
+ for (const name of ["build.rs", "src/lib.rs", "src/main.rs"]) target(path.join(at, name));
154
+ for (const name of ["src/bin", "tests", "benches", "examples"]) {
155
+ const location = path.join(at, name);
156
+ if (!target(location)?.isDirectory()) continue;
157
+ for (const entry of fsApi.readdirSync(location, { withFileTypes: true })) {
158
+ const candidate = path.join(location, entry.name);
159
+ if (entry.name.endsWith(".rs")) target(candidate);
160
+ else if (entry.isDirectory() || entry.isSymbolicLink()) target(path.join(candidate, "main.rs"));
161
+ }
162
+ }
163
+ }
164
+ const sorted = (entries) => [...entries].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
165
+ return createHash("sha256").update(JSON.stringify([sorted(files), sorted(targetDirs)])).digest("hex");
166
+ } catch {
167
+ return null;
168
+ }
169
+ }
170
+
29
171
  /** The flags of `rest` as a Map (flag to value, or true); null when one repeats, is unknown (`--flag=value` included) or lacks its value. */
30
172
  function flagsOf(rest, spec) {
31
173
  const found = new Map();
@@ -99,8 +241,8 @@ export function carriedScanRefusal(words, { checkout = null } = {}) {
99
241
  else own.push(w);
100
242
  }
101
243
  const f = flagsOf(own, { "--locked": "flag", "--prefix": "value", "-e": "value", "-f": "value", "--all-features": "flag", "--no-default-features": "flag", "--features": "value", "-F": "value" });
102
- const shapeOk = f !== null && f.has("--locked") && f.get("--prefix") === "none" && ["normal,build", "normal,build,dev"].includes(f.get("-e") ?? "") && f.get("-f") === "{p}\t{f}" && packages >= 1 && targets <= 1;
103
- return shapeOk ? null : "`tree` is admitted as `tree --locked --prefix none -e normal,build[,dev] -f '{p}<tab>{f}' [--all-features] [--no-default-features] [--features <list>] [--target <triple>] -p <crate>...` only (the feature-equivalence partition)";
244
+ const shapeOk = f !== null && f.has("--locked") && f.get("--prefix") === "none" && ["normal,build", "normal,build,dev"].includes(f.get("-e") ?? "") && f.get("-f") === "{p}\t{f}" && packages >= 1;
245
+ return shapeOk ? null : "`tree` is admitted as `tree --locked --prefix none -e normal,build[,dev] -f '{p}<tab>{f}' [--all-features] [--no-default-features] [--features <list>] [--target <triple>]... -p <crate>...` only (the feature-equivalence partition)";
104
246
  }
105
247
  return `\`cargo ${words.join(" ")}\` is not one of the carried read-only shapes (metadata, fetch --locked, deny, audit --db --no-fetch, fmt --check, package -p <unit> --list --locked, tree)`;
106
248
  }
@@ -123,7 +265,13 @@ export const carriedReadOnlyScan = (words, options) => carriedScanRefusal(words,
123
265
  * second run can only repeat the first. Only a successful call that streams to no file is kept (a failure is never replayed), keyed on the snapshot
124
266
  * directory it ran in and its exact words; every other call (fetch, deny, audit, package, fmt) always runs.
125
267
  */
126
- export function directReadSpawn({ spawn, cargoCommand, snapshotRoot, directPath, pathKey = "PATH", tmpRoot, env, err = () => {}, memo = null, isAsync = false }) {
268
+ /**
269
+ * `served({ cwd, args })`: optional; asks the resident gate for a `cargo metadata` answer it holds for this snapshot while the snapshot is unchanged
270
+ * (gate-serve.mjs snapshotCargoMetadata). Returns `{ status, stdout, stderr }` when the resident gate answered, else null, and the call runs here as
271
+ * before. NN10: each warm run asked Cargo for every workspace's metadata again (6 `cargo metadata` starts per warm run of the witness fixture,
272
+ * 2026-11-17) although the resident gate keeps those answers.
273
+ */
274
+ export function directReadSpawn({ spawn, cargoCommand, snapshotRoot, directPath, pathKey = "PATH", tmpRoot, env, err = () => {}, memo = null, isAsync = false, served = null }) {
127
275
  const prefix = cargoCommand.slice(1);
128
276
  const refused = (code, message) => { err(`rightkit-gate: ${code}: ${message}`); return { status: CARGO_REFUSAL_STATUS, signal: null, error: null, stdout: "", stderr: `rightkit-gate: ${code}: ${message}\n` }; };
129
277
  return (cmd, args, opts = {}) => {
@@ -138,6 +286,10 @@ export function directReadSpawn({ spawn, cargoCommand, snapshotRoot, directPath,
138
286
  const memoKey = memo && words[0] === "metadata" && opts.stdoutFile === undefined ? `${real(opts.cwd)}\0${words.join(" ")}` : null;
139
287
  if (memoKey !== null && memo.has(memoKey)) { const hit = { ...memo.get(memoKey) }; return isAsync ? Promise.resolve(hit) : hit; }
140
288
  const remember = (result) => { if (memoKey !== null && result && !result.error && result.status === 0 && typeof result.stdout === "string") memo.set(memoKey, { status: 0, signal: null, error: null, stdout: result.stdout, stderr: result.stderr ?? "" }); return result; };
289
+ if (typeof served === "function" && words[0] === "metadata" && opts.stdoutFile === undefined) {
290
+ let answer = null; try { answer = served({ cwd: opts.cwd, args: words }); } catch { answer = null; }
291
+ if (answer && answer.status === 0 && typeof answer.stdout === "string") { const r = remember({ status: 0, signal: null, error: null, stdout: answer.stdout, stderr: answer.stderr ?? "" }); return isAsync ? Promise.resolve(r) : r; }
292
+ }
141
293
  let scratch;
142
294
  try { fs.mkdirSync(tmpRoot, { recursive: true }); scratch = fs.mkdtempSync(path.join(tmpRoot, "rk-class-a-cargo-")); }
143
295
  catch (e) { return refused("RK_CLASS_A_SCRATCH", `cannot create a scratch target under ${tmpRoot}: ${e.message}`); }