@rightkit/release 0.6.45 → 0.6.47

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4,6 +4,8 @@
4
4
  // passing host run receipts from that same SHA: macOS and Windows, or macOS only for Swift.
5
5
  // Format: docs/RIGHTKIT-SHARED-PACKAGES.md, "Publication gate" -> "Evidence file format".
6
6
  import crypto from "node:crypto";
7
+ import { crossTargetsFor } from "./cross-targets.mjs";
8
+ import { committedCargoWorkspace } from "./committed-cargo-workspace.mjs";
7
9
  import fs from "node:fs";
8
10
  import os from "node:os";
9
11
  import path from "node:path";
@@ -71,7 +73,7 @@ const BATCH_COMMAND = Object.freeze({
71
73
 
72
74
  /** Problems with a batch receipt for the crate `evidence.name` (empty when it proves fmt, secret scan and clippy).
73
75
  * `tree` is the current HEAD tree when known; `undefined` skips only that comparison. */
74
- export function batchReceiptProblems(batch, evidence, tree) {
76
+ export function batchReceiptProblems(batch, evidence, tree, expectedWorkspace) {
75
77
  if (!batch || typeof batch !== "object" || Array.isArray(batch)) return ["batch receipt must be an object"];
76
78
  const problems = [];
77
79
  if (!text(batch.id)) problems.push("batch.id");
@@ -79,6 +81,11 @@ export function batchReceiptProblems(batch, evidence, tree) {
79
81
  if (!SHA.test(String(batch.tree ?? ""))) problems.push("batch.tree (must be a 40-hex git tree)");
80
82
  else if (tree !== undefined && batch.tree !== tree) problems.push(`batch.tree (must equal the HEAD tree ${tree})`);
81
83
  if (!(Array.isArray(batch.crates) && batch.crates.includes(evidence.name))) problems.push("batch.crates (must name this crate)");
84
+ const workspace = batch.workspaces?.[evidence.name];
85
+ const validWorkspace = typeof workspace === "string" && (workspace === "." || (/^(?!\/)(?!.*(?:^|\/)\.\.(?:\/|$))[^\\]+$/.test(workspace) && !workspace.endsWith("/")));
86
+ if (!validWorkspace) problems.push("batch.workspaces (must identify this crate's workspace)");
87
+ if (!text(expectedWorkspace)) problems.push("expected workspace is required for batch evidence");
88
+ else if (workspace !== expectedWorkspace) problems.push("batch workspace differs from authenticated workspace");
82
89
  const checks = Array.isArray(batch.checks) ? batch.checks : [];
83
90
  for (const name of BATCH_CHECKS) {
84
91
  const rows = checks.filter((row) => row?.name === name);
@@ -88,31 +95,32 @@ export function batchReceiptProblems(batch, evidence, tree) {
88
95
  if (row.commit !== evidence.commit || row.tree !== batch.tree) problems.push(`batch check ${name} not bound to the batch commit and tree`);
89
96
  if (!(text(row.command) && BATCH_COMMAND[name].test(row.command))) problems.push(`batch check ${name} command`);
90
97
  }
91
- // fmt is workspace-wide; clippy and the secret scan name the crates they covered.
92
- if (name !== "fmt" && !rows.some((row) => Array.isArray(row.crates) && row.crates.includes(evidence.name))) problems.push(`batch check ${name} does not cover this crate`);
98
+ if (!rows.some((row) => Array.isArray(row.crates) && row.crates.includes(evidence.name)
99
+ && (name === "secret-scan" || (validWorkspace && row.workspace === workspace)))) problems.push(`batch check ${name} does not cover this crate and workspace`);
93
100
  }
94
101
  return problems;
95
102
  }
96
103
 
97
- /**
98
- * Feature sets of this crate that a batch receipt did NOT lint (0.4.1 review A2). Batch mode lints each crate's tested
99
- * feature sets in shared `-p a -p b` runs, so a receipt from before every set was linted (0.4.0: first set only)
100
- * still satisfies `batchReceiptProblems`, which accepts any ONE clippy row covering the crate. Replay therefore
101
- * needs one passing row per feature set: bound to the evidence commit and the batch tree, naming the crate (`-p <crate>`
102
- * and `crates`), and ending `--no-deps --all-targets <features> -- -D warnings`. `featureSets` is the crate's
103
- * `ci/gate.config.json` list (`[[]]` when unset). Returns the missing sets as argument arrays.
104
- */
105
- export function batchClippyMissingFeatureSets(batch, evidence, featureSets) {
104
+ /** Missing native and cross-target configurations, each bound to the authenticated workspace. */
105
+ export function batchClippyMissingConfigurations(batch, evidence, featureSets, targets, expectedWorkspace) {
106
+ const sets = (Array.isArray(featureSets) && featureSets.length ? featureSets : [[]]);
107
+ if (!text(expectedWorkspace) || !Array.isArray(targets) || sets.some((set) => !Array.isArray(set) || set.some((arg) => !text(arg)))) throw new Error("invalid batch clippy requirements");
106
108
  const rows = (Array.isArray(batch?.checks) ? batch.checks : []).filter((row) => row?.name === "clippy" && row.ok === true
107
- && row.commit === evidence.commit && row.tree === batch.tree && Array.isArray(row.crates) && row.crates.includes(evidence.name) && text(row.command));
108
- const sets = (Array.isArray(featureSets) && featureSets.length ? featureSets : [[]]).map((set) => (Array.isArray(set) ? set : []));
109
- return sets.filter((features) => {
110
- const tail = ` --no-deps --all-targets${features.length ? ` ${features.join(" ")}` : ""} -- -D warnings`;
111
- return !rows.some((row) => {
112
- const words = row.command.split(" ");
113
- return row.command.endsWith(tail) && words.some((word, index) => word === "-p" && words[index + 1] === evidence.name);
114
- });
115
- });
109
+ && row.commit === evidence.commit && row.tree === batch.tree && row.workspace === expectedWorkspace
110
+ && Array.isArray(row.crates) && row.crates.includes(evidence.name) && row.crates.length > 0
111
+ && new Set(row.crates).size === row.crates.length
112
+ && row.crates.every((crate) => typeof crate === "string" && /^[A-Za-z0-9_-]+$/.test(crate) && batch.workspaces?.[crate] === expectedWorkspace));
113
+ const missing = [];
114
+ for (const features of sets) for (const target of [null, ...targets]) {
115
+ const command = (crates) => ["cargo", "clippy", ...crates.flatMap((crate) => ["-p", crate]), "--message-format=json-render-diagnostics", "--no-deps", "--all-targets", ...(target ? ["--target", target] : []), ...features, "--", "-D", "warnings"].join(" ");
116
+ if (!rows.some((row) => row.command === command(row.crates))) missing.push({ features, target });
117
+ }
118
+ return missing;
119
+ }
120
+
121
+ // Historical helper keeps its feature-array result while requiring independent workspace identity.
122
+ export function batchClippyMissingFeatureSets(batch, evidence, featureSets, expectedWorkspace) {
123
+ return batchClippyMissingConfigurations(batch, evidence, featureSets, [], expectedWorkspace).map((entry) => entry.features);
116
124
  }
117
125
 
118
126
  /**
@@ -122,7 +130,7 @@ export function batchClippyMissingFeatureSets(batch, evidence, featureSets) {
122
130
  * `secretScan` (a valid batch receipt covering the crate). Every run on the proving host (darwin, or win32 under a win32-only policy) at the evidence commit must prove a
123
131
  * step for it to count. Call after the gate accepted the evidence (the gate binds commit, tree and artifact).
124
132
  */
125
- export function provenGateSteps(evidence) {
133
+ export function provenGateSteps(evidence, expectedWorkspace, gateConfig) {
126
134
  const none = { tests: false, clippy: false, fmt: false, secretScan: false };
127
135
  if (!evidence || !SHA.test(String(evidence.commit ?? "")) || !text(evidence.name)) return none;
128
136
  // The proving host is the one a recorded win32-only policy names; every other evidence is proved on darwin.
@@ -132,7 +140,13 @@ export function provenGateSteps(evidence) {
132
140
  const name = escapeRegExp(evidence.name);
133
141
  const stepProves = (run, pattern, needTests) => (Array.isArray(run.steps) ? run.steps : []).some((step) => step?.ok === true
134
142
  && pattern.test(String(step.command ?? "")) && (!needTests || (step.executed > 0 && step.failed === 0)));
135
- const batchOk = (run) => run.batch !== undefined && batchReceiptProblems(run.batch, evidence, undefined).length === 0;
143
+ const batchOk = (run) => {
144
+ if (!gateConfig || run.batch === undefined || batchReceiptProblems(run.batch, evidence, undefined, expectedWorkspace).length) return false;
145
+ try {
146
+ const entry = gateConfig?.rust?.[evidence.name] ?? {};
147
+ return batchClippyMissingConfigurations(run.batch, evidence, entry.featureSets ?? [[]], crossTargetsFor(entry, run.host.os), expectedWorkspace).length === 0;
148
+ } catch { return false; }
149
+ };
136
150
  return {
137
151
  tests: runs.every((run) => stepProves(run, new RegExp(`^cargo test -p ${name}( |$)`), true)),
138
152
  clippy: runs.every((run) => batchOk(run) || stepProves(run, new RegExp(`^cargo clippy -p ${name} .*-- -D warnings$`), false)),
@@ -143,7 +157,7 @@ export function provenGateSteps(evidence) {
143
157
 
144
158
  // Names of the fields of one host run that do not qualify (empty when the run qualifies). Every run binds to
145
159
  // the same unit, commit and artifact: commit, host arch, feature set and artifactSha256 equal to the evidence.
146
- function invalidRunFields(run, evidence, tree) {
160
+ function invalidRunFields(run, evidence, tree, expectedWorkspace) {
147
161
  const bad = [];
148
162
  if (run.commit !== evidence.commit) bad.push(`commit (must equal ${evidence.commit})`);
149
163
  if (!text(run.host?.arch)) bad.push("host.arch");
@@ -155,13 +169,14 @@ function invalidRunFields(run, evidence, tree) {
155
169
  if (!(Number.isInteger(run.passed) && run.passed > 0)) bad.push("passed (must be > 0)");
156
170
  if (run.failed !== 0) bad.push("failed (must be 0)");
157
171
  if (run.jobs !== undefined && !(Number.isInteger(run.jobs) && run.jobs >= 1 && run.jobs <= MAX_CARGO_JOBS)) bad.push(`jobs (must be an integer from 1 to ${MAX_CARGO_JOBS})`);
158
- if (run.batch !== undefined) bad.push(...batchReceiptProblems(run.batch, evidence, tree ?? null).map((problem) => `batch: ${problem}`));
172
+ if (run.batch !== undefined) bad.push(...batchReceiptProblems(run.batch, evidence, tree ?? null, expectedWorkspace).map((problem) => `batch: ${problem}`));
159
173
  return bad;
160
174
  }
161
175
 
162
- function gateResult(missing, evidence) {
176
+ function gateResult(missing, evidence, workspace) {
163
177
  const result = { ok: missing.length === 0, missing };
164
178
  Object.defineProperty(result, "evidence", { value: evidence });
179
+ Object.defineProperty(result, "workspace", { value: workspace });
165
180
  return Object.freeze(result);
166
181
  }
167
182
 
@@ -207,7 +222,7 @@ export function validatePublicationEvidence({ expected = {}, evidence, artifactB
207
222
  if (!matching.length) { missing.push(`no ${label} host run receipt`); continue; }
208
223
  // Every run on the host must qualify: a failing run is not masked by a passing run beside it.
209
224
  matching.forEach((run, index) => {
210
- const fields = invalidRunFields(run, evidence, tree);
225
+ const fields = invalidRunFields(run, evidence, tree, expected.workspace);
211
226
  if (fields.length) missing.push(`${label} run receipt ${index} invalid: ${fields.join(", ")}`);
212
227
  });
213
228
  }
@@ -232,16 +247,34 @@ export function checkPublicationGate({ kind, name, version, packagePath, evidenc
232
247
  const runs = Array.isArray(evidence?.runs) ? evidence.runs : [];
233
248
  const tree = runs.some((run) => run?.batch !== undefined) ? git(["rev-parse", "HEAD^{tree}"], packagePath) : undefined;
234
249
  if (tree === null) missing.push(`cannot read the HEAD tree for ${packagePath}`);
250
+ let workspace;
251
+ if (runs.some((run) => run?.batch !== undefined) && SHA.test(String(head ?? ""))) {
252
+ try {
253
+ const root = git(["rev-parse", "--show-toplevel"], packagePath);
254
+ if (!root) throw new Error("cannot resolve repository root");
255
+ const unitDir = path.relative(root, packagePath).split(path.sep).join("/");
256
+ const read = (file) => {
257
+ const entry = git(["ls-tree", "--name-only", head, "--", file], root);
258
+ if (entry === null) throw new Error(`cannot inspect committed ${file}`);
259
+ if (entry === "") return null;
260
+ if (entry !== file) throw new Error(`ambiguous committed ${file}`);
261
+ const contents = git(["show", `${head}:${file}`], root);
262
+ if (contents === null) throw new Error(`cannot read committed ${file}`);
263
+ return contents;
264
+ };
265
+ workspace = committedCargoWorkspace({ unitDir, read });
266
+ } catch (error) { missing.push(`cannot authenticate Cargo workspace: ${error.message}`); }
267
+ }
235
268
  // Local publication retains its recorded single-host grant. CI callers own their policy separately.
236
269
  const singleHost = (kind === "npm" || kind === "cargo") ? singleHostOfPolicy(evidence) : null;
237
- const result = validatePublicationEvidence({ expected: { kind, name, version, commit: head, tree,
270
+ const result = validatePublicationEvidence({ expected: { kind, name, version, commit: head, tree, workspace,
238
271
  ...(directLinux ? { directLinux: true } : singleHost ? { requiredHosts: [singleHost] } : {}) }, evidence, artifactBytes });
239
272
  for (const problem of result.missing) {
240
273
  if (problem === `evidence commit ${evidence?.commit} != expected commit ${head}`) {
241
274
  missing.push(`evidence commit ${evidence.commit} != current HEAD ${head} (${describeCommitMismatch(evidence.commit, head, packagePath, git)})`);
242
275
  } else missing.push(problem);
243
276
  }
244
- return gateResult(missing, evidence);
277
+ return gateResult(missing, evidence, workspace);
245
278
  }
246
279
 
247
280
  // Enforce: throws on missing evidence unless dryRun (then reports and continues).
package/publish-cargo.mjs CHANGED
@@ -3,7 +3,8 @@ import fs from "node:fs";
3
3
  import path from "node:path";
4
4
  import { createHash } from "node:crypto";
5
5
  import { fileURLToPath } from "node:url";
6
- import { enforcePublicationGate, defaultEvidencePath, provenGateSteps, singleHostOfPolicy, batchClippyMissingFeatureSets } from "./publication-gate.mjs";
6
+ import { crossTargetsFor } from "./cross-targets.mjs";
7
+ import { enforcePublicationGate, defaultEvidencePath, provenGateSteps, singleHostOfPolicy, batchClippyMissingConfigurations } from "./publication-gate.mjs";
7
8
  import { runCargoSync } from "./managed-cargo.mjs";
8
9
  import { assertPublishCapability, refuseHostUpload } from "./host-upload-refusal.mjs";
9
10
  import { spawnSync } from "./background-process.mjs";
@@ -394,7 +395,20 @@ export async function runCargoPublish(options, execute = (_command, args, settin
394
395
  // and artifact digest must match. Windows evidence keeps its actual win32 host policy on the Mac.
395
396
  const reuseEvidence = options.fromEvidence === true;
396
397
  if (reuseEvidence && (options.dryRun || options.allowDirty || !options.evidence)) throw new Error("--from-evidence requires a real publish, clean source and explicit evidence");
397
- const proven = (reuseEvidence || options.trustEvidenceSteps === true) && !options.dryRun ? provenGateSteps(gate.evidence) : {};
398
+ let batchConfig;
399
+ if ((reuseEvidence || options.trustEvidenceSteps === true) && !options.dryRun && gate.evidence?.runs?.some((run) => run?.batch)) {
400
+ const status = (deps.workspaceStatus ?? ((root) => spawnSync("git", ["status", "--porcelain", "--", "ci/gate.config.json"], { cwd: root, encoding: "utf8", windowsHide: true })))(options.workspaceRoot);
401
+ if (status.error || status.status !== 0 || String(status.stdout ?? "").trim()) throw new Error("batch evidence reuse requires clean ci/gate.config.json");
402
+ try { batchConfig = JSON.parse(fs.readFileSync(path.join(options.workspaceRoot, "ci", "gate.config.json"), "utf8")); }
403
+ catch { throw new Error("batch evidence reuse cannot read ci/gate.config.json"); }
404
+ const proofHost = singleHostOfPolicy(gate.evidence) ?? "darwin";
405
+ for (const run of gate.evidence.runs.filter((item) => item?.host?.os === proofHost && item.batch)) {
406
+ const entry = batchConfig?.rust?.[options.crate] ?? {};
407
+ const missing = batchClippyMissingConfigurations(run.batch, gate.evidence, entry.featureSets ?? [[]], crossTargetsFor(entry, run.host.os), gate.workspace);
408
+ if (missing.length) throw new Error(`batch clippy missing configured feature/target coverage: ${missing.map(({ features, target }) => `${features.join(" ") || "default"} @ ${target ?? "native"}`).join("; ")}`);
409
+ }
410
+ }
411
+ const proven = (reuseEvidence || options.trustEvidenceSteps === true) && !options.dryRun ? provenGateSteps(gate.evidence, gate.workspace, batchConfig) : {};
398
412
  if (reuseEvidence && (proven.tests !== true || proven.clippy !== true)) throw new Error("--from-evidence requires gate-proven tests and clippy for this crate and commit");
399
413
  if (reuseEvidence) {
400
414
  const status = (deps.workspaceStatus ?? ((workspaceRoot) => spawnSync("git", ["status", "--porcelain", "--", `crates/${options.crate}/Cargo.toml`, `crates/${options.crate}/Cargo.lock`, "ci/gate.config.json", "ci/asset-gated.json"], { cwd: workspaceRoot, encoding: "utf8", windowsHide: true })))(options.workspaceRoot);
@@ -425,8 +439,9 @@ export async function runCargoPublish(options, execute = (_command, args, settin
425
439
  }
426
440
  // A batch run's clippy lives in its batch receipt, which `expected` leaves out: demand one row per feature set (0.4.1 review A2).
427
441
  if (run.batch) {
428
- const missing = batchClippyMissingFeatureSets(run.batch, gate.evidence, config?.rust?.[options.crate]?.featureSets ?? [[]]);
429
- if (missing.length) throw new Error(`--from-evidence missing batch clippy for feature set${missing.length === 1 ? "" : "s"}: ${missing.map((features) => features.join(" ") || "default").join("; ")}`);
442
+ const entry = config?.rust?.[options.crate] ?? {};
443
+ const missing = batchClippyMissingConfigurations(run.batch, gate.evidence, entry.featureSets ?? [[]], crossTargetsFor(entry, run.host.os), gate.workspace);
444
+ if (missing.length) throw new Error(`--from-evidence missing batch clippy feature/target coverage: ${missing.map(({ features, target }) => `${features.join(" ") || "default"} @ ${target ?? "native"}`).join("; ")}`);
430
445
  }
431
446
  }
432
447
  }
@@ -40,6 +40,16 @@ export function enrolledPins(sha, git) {
40
40
  export function verifyQualificationReceipts(text, { sha, git }) {
41
41
  let q;
42
42
  try { q = JSON.parse(text); } catch { refuse("the qualification input is not JSON"); }
43
+ return verifyReceiptStages(q, { sha, git, stages: ATTESTED_STAGES, nonceOf: ({ commit, tree, unit, stage }) => qualificationNonce({ commit, tree, unit, stage }) });
44
+ }
45
+
46
+ // CI supplies its independently bound nonce; publication always uses the fixed wrapper above.
47
+ export function verifyCiCompileReceipts(q, { sha, git, stageNonce }) {
48
+ requireThat(typeof stageNonce === "string" && SHA256_HEX.test(stageNonce), "the CI compile nonce is invalid");
49
+ return verifyReceiptStages(q, { sha, git, stages: ["compile"], nonceOf: () => stageNonce });
50
+ }
51
+
52
+ function verifyReceiptStages(q, { sha, git, stages, nonceOf }) {
43
53
  const tree = String(git("rev-parse", `${sha}^{tree}`)).trim();
44
54
  requireThat(/^[0-9a-f]{40}$/.test(tree), `cannot read the tree of ${sha.slice(0, 12)}`);
45
55
  requireThat(q?.tree === tree, `the qualification receipt is for tree ${String(q?.tree).slice(0, 12)}, the dispatched commit's tree is ${tree.slice(0, 12)}`);
@@ -64,11 +74,11 @@ export function verifyQualificationReceipts(text, { sha, git }) {
64
74
  let primaryRoot = null, snapshotPath = null, handle = null;
65
75
  const seen = new Set();
66
76
  const verified = {};
67
- for (const stage of ATTESTED_STAGES) {
77
+ for (const stage of stages) {
68
78
  const list = q.stages?.[stage]?.receipts;
69
79
  requireThat(Array.isArray(list) && list.length >= 1, `the qualification receipt's ${stage} stage carries no signed broker receipts; an unauthenticated qualification admits nothing`);
70
80
  requireThat(list.length <= MAX_VERIFIED_RECEIPTS, `the qualification receipt's ${stage} stage carries ${list.length} receipts (at most ${MAX_VERIFIED_RECEIPTS})`);
71
- const stageNonce = qualificationNonce({ commit: sha, tree, unit, stage });
81
+ const stageNonce = nonceOf({ commit: sha, tree, unit, stage });
72
82
  // The nonces a receipt may carry, before its row is known: every carried call (a Cargo call, and a pnpm adapter job, rightkit#1301 B8) the
73
83
  // nonce derived for the directory of each of the stage's rows it could be and the argv it signed. The row it is assigned to (below) must
74
84
  // then be the one that fits.
@@ -3,6 +3,7 @@
3
3
  // published versions, and (with --apply) move them forward and refresh the lockfiles.
4
4
  // Self-contained (node: built-ins only) so the SessionStart hook can carry a byte copy of it.
5
5
  // node rightkit-drift.mjs [--apply [--all]] [app-root] (--all also adopts breaking bumps)
6
+ import { nonCompilingCargoEnv } from "./managed-cargo.mjs";
6
7
  import { spawnSync } from "./background-process.mjs";
7
8
  import { existsSync, readFileSync, writeFileSync, realpathSync } from "node:fs";
8
9
  import path from "node:path";
@@ -83,9 +84,9 @@ export function launchOf(command, args, { platform = process.platform, spawn = s
83
84
  return { command: target, args, shell: false };
84
85
  }
85
86
 
86
- function run(command, args, cwd, { spawn = spawnSync, platform = process.platform, readFile } = {}) {
87
+ function run(command, args, cwd, { spawn = spawnSync, platform = process.platform, readFile, env } = {}) {
87
88
  const launch = launchOf(command, args, { platform, spawn, readFile });
88
- const result = spawn(launch.command, launch.args, { cwd, stdio: "inherit", windowsHide: true, shell: launch.shell });
89
+ const result = spawn(launch.command, launch.args, { cwd, stdio: "inherit", windowsHide: true, shell: launch.shell, ...(env ? { env } : {}) });
89
90
  if (result.status !== 0) throw new Error(`${command} ${args.join(" ")} failed in ${cwd} (exit ${result.status ?? result.error?.message})`);
90
91
  }
91
92
 
@@ -113,7 +114,7 @@ export function applyRightkitAdoption(appRoot, versions = loadRightkitVersions()
113
114
  for (const file of byFile.keys()) {
114
115
  const dir = path.join(appRoot, path.dirname(file));
115
116
  if (file.endsWith("package.json")) run("pnpm", ["install", "--lockfile-only", "--ignore-scripts"], dir, runOptions);
116
- else run("rustright", ["cargo", "metadata", "--format-version", "1", "--manifest-path", path.join(appRoot, file)], dir, runOptions);
117
+ else run("cargo", ["metadata", "--format-version", "1", "--manifest-path", path.join(appRoot, file)], dir, { ...runOptions, env: nonCompilingCargoEnv(runOptions?.env ?? process.env) });
117
118
  }
118
119
  }
119
120
  return drift;
@@ -50,7 +50,7 @@
50
50
  "@rightkit/qa": "0.7.0",
51
51
  "@rightkit/qa-chrome": "0.1.12",
52
52
  "@rightkit/react-shell": "0.7.3",
53
- "@rightkit/release": "0.6.45",
53
+ "@rightkit/release": "0.6.47",
54
54
  "@rightkit/settings-ui": "0.7.1",
55
55
  "@rightkit/social-ui": "0.1.0",
56
56
  "@rightkit/system-ui": "0.1.0",
@@ -123,7 +123,7 @@ export function createSnapshotBroker({ env = process.env, platform = process.pla
123
123
  return {
124
124
  carrierSweep,
125
125
  controlRoot: roots.controlRoot, commit: { sha: commit.sha, tree: commit.tree }, snapshot: { path: snapshot.path, expectedTree: snapshot.expectedTree },
126
- declaredInputs: readDeclaredInputs(snapshot.path), handle: ownership.handle, markBrokerSubmit: (callHandle) => ownership.markBrokerSubmit(callHandle), markBrokerUnsent: typeof ownership.markBrokerUnsent === "function" ? (callHandle, reason) => ownership.markBrokerUnsent(callHandle, reason) : undefined,
126
+ declaredInputs: readDeclaredInputs(snapshot.path), handle: ownership.handle, markBrokerSubmit: (callHandle, note) => ownership.markBrokerSubmit(callHandle, note), markBrokerUnsent: typeof ownership.markBrokerUnsent === "function" ? (callHandle, reason) => ownership.markBrokerUnsent(callHandle, reason) : undefined,
127
127
  pins: { host: pins.host, keyId: pins.keyId, publicKey: pins.publicKey, brokerDigest: pins.brokerDigest }, pinsSource: pins.source,
128
128
  checkout: fs.realpathSync.native(checkout), outputRoots: brokerOutputRoots({ dataRoot: managedData }), platform, client,
129
129
  receiptOf: async (requestId) => receiptSync({ client, requestId, env, spawn, platform }),
@@ -20,10 +20,14 @@
20
20
  import crypto from "node:crypto";
21
21
  import fs from "node:fs";
22
22
  import path from "node:path";
23
+ import { serveRequest } from "./gate-serve.mjs";
23
24
  import { LIVE_SCAN_IDS, defaultSpawn, isLiveScan, isRegistryScan, launchGuardEnv, planScans, runScans } from "./deterministic-scans.mjs";
24
25
  import { compileLaunch } from "./class-a-launch-guard.mjs";
25
26
  import { SnapshotError, dependencyDirs, isInside, snapshotProblem, snapshotTree, treeEntries } from "./snapshot.mjs";
26
27
  import { discoveryRun, sealedRun } from "./snapshot-git.mjs";
28
+ import { snapshotDependencyReuse } from "./snapshot-dependency-reuse.mjs";
29
+ import { gateRunsRoot } from "./managed-roots.mjs";
30
+ import { writePerformanceDiagnostic } from "./performance-diagnostic.mjs";
27
31
 
28
32
  export const CHECK_ERROR = "RK_CHECK_ERROR";
29
33
  export const LIVE_SCANS_SCHEMA = "rightkit.live-scans/1";
@@ -39,6 +43,37 @@ export class CheckError extends Error {
39
43
  const text = (r) => String(r?.stdout ?? "");
40
44
  const failed = (r) => !r || Boolean(r.error) || r.status !== 0;
41
45
  const tail = (r) => `${r?.stderr ?? ""}\n${r?.stdout ?? ""}`.trim().split(/\r?\n/).slice(-6).join(" | ").slice(-600);
46
+ // Store only bounded structured diagnostics, never arbitrary pnpm output or environment values.
47
+ const PREPARATION_CODE_LIMIT = 1000;
48
+ export function preparationStreamEvidence(value) {
49
+ const bytes = Buffer.from(String(value ?? ""), "utf8");
50
+ const codes = []; let line = 1; let capped = false;
51
+ for (const part of bytes.toString("utf8").split(/\r\n|\n|\r/)) {
52
+ for (const match of part.matchAll(/\bERR_PNPM_[A-Z0-9_]+\b/g)) {
53
+ if (match[0].length <= 96 && codes.length < PREPARATION_CODE_LIMIT) codes.push({ code: match[0], line });
54
+ else capped = true;
55
+ }
56
+ line += 1;
57
+ }
58
+ return { sha256: crypto.createHash("sha256").update(bytes).digest("hex"), bytes: bytes.length, codes, codesTruncated: capped };
59
+ }
60
+ function preparationFailure(r, env) {
61
+ const stdout = preparationStreamEvidence(r?.stdout); const stderr = preparationStreamEvidence(r?.stderr);
62
+ const incomplete = Boolean(r?.error) || r?.truncated === true;
63
+ const diagnostic = { schema: "rightkit.preparation-diagnostic/1", captureComplete: !incomplete, captureTruncated: r?.truncated === true, stdout, stderr };
64
+ let file = null;
65
+ try {
66
+ const base = path.join(gateRunsRoot({ env }), "rightkit-gate-preparation");
67
+ fs.mkdirSync(base, { recursive: true, mode: 0o700 });
68
+ const dir = fs.mkdtempSync(path.join(base, "failure-"));
69
+ file = path.join(dir, "diagnostic.json");
70
+ fs.writeFileSync(file, `${JSON.stringify(diagnostic, null, 2)}\n`, { mode: 0o600 });
71
+ } catch { file = null; }
72
+ const codes = [...new Set([...stderr.codes, ...stdout.codes].map((item) => item.code))];
73
+ return { codes, detail: `structured diagnostics ${incomplete ? "incomplete" : "complete"}${stdout.codesTruncated || stderr.codesTruncated ? " (codes bounded)" : ""}${file ? `; file ${file}` : "; file unavailable"}` };
74
+ }
75
+ const safeTarballName = (name) => typeof name === "string" && /^[A-Za-z0-9][A-Za-z0-9._+-]{0,199}$/.test(name) ? name : null;
76
+
42
77
  // A path is outside only as `..`, `..<sep>…` or absolute: a sibling named `..x` is inside (snapshot.mjs isInside; review item5-r2 #4).
43
78
  const inside = (child, parent) => isInside(child, parent, path);
44
79
 
@@ -86,17 +121,34 @@ export function commitOf(checkout, rev, spawn = defaultSpawn) { // eslint-disabl
86
121
  * are admitted and the ledger must still match exactly. Then the result is `{ tree, ledger: [{ path, type, size, sha256, execBit }] }`.
87
122
  */
88
123
  export function verifySnapshotDir({ checkout, dir, commit, tree, when, ledger, admitNew }) {
124
+ const diagnosticDir = process.env.RIGHTKIT_PREPARATION_DIAGNOSTIC_DIR;
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
+ const phase = labels.get(when) ?? 'other';
127
+ const rows = [];
128
+ const timed = diagnosticDir ? (label, fn) => { const start = performance.now(); try { return fn(); } finally { try { rows.push({ label: `${phase}-${label}`, ms: performance.now() - start, count: 1 }); } catch {} } } : (_label, fn) => fn();
129
+ // GC-A24: a plain verify asks the resident gate (gate-serve.mjs) whether this snapshot was proven this tree with no change since; a
130
+ // full verify takes the change generation first and records the proof after it passes. Any doubt means the full verify below.
131
+ const plain = ledger === undefined && admitNew !== true;
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; }
136
+ if (Number.isInteger(c?.generation)) generation = c.generation;
137
+ }
138
+ try {
89
139
  const ledgerMode = ledger !== undefined || admitNew === true;
90
140
  let inspected;
91
- try { inspected = snapshotProblem({ dir, entries: treeEntries(checkout, commit), checkout, commit, ledger, admitNew }); }
141
+ try { const entries = timed('tree-entries', () => treeEntries(checkout, commit)); inspected = timed('walk', () => snapshotProblem({ dir, entries, checkout, commit, ledger, admitNew })); }
92
142
  catch (e) { throw new CheckError(`cannot list snapshot ${dir} ${when}: ${e.message}`); }
93
143
  const extra = ledgerMode ? inspected.problem : inspected;
94
144
  if (extra) throw new CheckError(`snapshot ${dir} is not exactly commit ${commit}${ledgerMode ? " plus its stage-output ledger" : ""} ${when}: ${extra}`);
95
145
  let actual;
96
- try { actual = snapshotTree({ checkout, dir, baseTree: tree }); }
146
+ try { actual = timed('tree-hash', () => snapshotTree({ checkout, dir, baseTree: tree })); }
97
147
  catch (e) { throw new CheckError(`cannot compute the tree of snapshot ${dir} ${when}: ${e.message}`); }
98
148
  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 });
99
150
  return ledgerMode ? { tree: actual, ledger: inspected.admitted } : actual;
151
+ } finally { if (diagnosticDir) writePerformanceDiagnostic(diagnosticDir, 'snapshot-verify', rows); }
100
152
  }
101
153
 
102
154
  /** Every file of the commit with its blob id, from the checkout's object database: what the snapshot holds. */
@@ -293,6 +345,23 @@ export function installSnapshotDependencies({ checkout, snapshot, commit, tree,
293
345
  const version = versionOf(dir);
294
346
  if (!version) throw new CheckError("pnpm is not runnable on this host; the snapshot's dependencies cannot be installed");
295
347
  if (pin && version !== pin) throw new CheckError(`pnpm ${version} is on PATH, but root ${root} of the commit pins pnpm@${pin} (packageManager); install the pinned pnpm`);
348
+ const ownedDirs = generated.filter((d) => nearestLock(fold(dirOf(d))) === owner);
349
+ const reuseStarted = performance.now();
350
+ const reuseDiagnostic = {};
351
+ const reuse = snapshotDependencyReuse({ checkout, snapshot: base, tree, root, dirs: ownedDirs, filters, storeDir, version, env, spawn, diagnostic: reuseDiagnostic });
352
+ if (reuse?.matches()) {
353
+ const skipped = probe ? probe({ dir, root, names: allowedBuilds(dir), spawn, env }) : [];
354
+ if (reuse.matches()) {
355
+ verifySnapshotDir({ checkout, dir: base, commit, tree, when: "after reused dependency probes", ...(ledger !== undefined ? { ledger } : {}) });
356
+ const lockfileSha256 = crypto.createHash("sha256").update(fs.readFileSync(path.join(dir, "pnpm-lock.yaml"))).digest("hex");
357
+ records.push({ root, storeDir, storeSource: source, pnpm: version, pinned: pin, lockfileSha256, ms: 0, allowedBuildsNotRun: skipped, reused: true, reuseCheckMs: Math.round(performance.now() - reuseStarted), dependencyDigestChecks: reuse.digestChecks, reuseDiagnostic });
358
+ continue;
359
+ }
360
+ }
361
+ const reuseCheckMs = Math.round(performance.now() - reuseStarted);
362
+ // GC-A24: dependency directories kept by the snapshot sync that do not match their last completed install are removed before the
363
+ // install, so a non-reused install starts from nothing, exactly as when the sync removed them.
364
+ for (const d of ownedDirs) fs.rmSync(path.join(base, ...d.split("/")), { recursive: true, force: true });
296
365
  const started = now();
297
366
  // The virtual store is pinned inside the snapshot and the global virtual store off, whatever the host's pnpm config says: the
298
367
  // install writes nowhere but the snapshot (links to the existing store's content are the only reads outside it).
@@ -309,15 +378,22 @@ export function installSnapshotDependencies({ checkout, snapshot, commit, tree,
309
378
  // and the code and its URL may be a few lines apart (Dell, 2026-11-02: the specific message never fired; only progress lines showed).
310
379
  const joined = out.replace(/(https?:\/\/)\s+/g, "$1");
311
380
  const miss = /ERR_PNPM_NO_OFFLINE_TARBALL[\s\S]{0,600}?(https?:\/\/\S+?\/-\/(\S+?)\.tgz)/.exec(joined);
312
- const message = miss
313
- ? `root ${root}: ${miss[2]} is missing from the store ${storeDir} (offline install, no network fallback); install the checkout's dependencies so the store holds it, then run the check again`
314
- : `root ${root}: offline dependency install failed (store ${storeDir}): ${tail(r) || r?.error?.message || `exit ${r?.status}`}`;
315
- try { cleanup(); } catch (error) { throw new CheckError(`${message}; dependency cleanup failed: ${error.message}`); }
316
- throw new CheckError(`${message}; invalidated generated dependency output for owning lockroot ${root}`);
381
+ const diagnostic = preparationFailure(r, env);
382
+ const missingName = safeTarballName(miss?.[2]);
383
+ const message = miss && missingName
384
+ ? `root ${root}: ${missingName} is missing from the store ${storeDir} (offline install, no network fallback); install the checkout's dependencies so the store holds it, then run the check again`
385
+ : `root ${root}: offline dependency install failed (store ${storeDir}): ${diagnostic.codes.join(", ") || `exit ${Number.isInteger(r?.status) ? r.status : "unknown"}`}`;
386
+ const detail = `${message}; ${diagnostic.detail}`;
387
+ try { cleanup(); } catch (error) { throw new CheckError(`${detail}; dependency cleanup failed: ${error.message}`); }
388
+ throw new CheckError(`${detail}; invalidated generated dependency output for owning lockroot ${root}`);
317
389
  }
318
390
  const lockfileSha256 = crypto.createHash("sha256").update(fs.readFileSync(path.join(dir, "pnpm-lock.yaml"))).digest("hex");
319
391
  const skipped = probe ? probe({ dir, root, names: allowedBuilds(dir), spawn, env }) : [];
320
- records.push({ root, storeDir, storeSource: source, pnpm: version, pinned: pin, lockfileSha256, ms, allowedBuildsNotRun: skipped });
392
+ verifySnapshotDir({ checkout, dir: base, commit, tree, when: "after dependency installation and probes", ...(ledger !== undefined ? { ledger } : {}) });
393
+ const reuseSaveStarted = performance.now();
394
+ reuse?.save();
395
+ const reuseSaveMs = Math.round(performance.now() - reuseSaveStarted);
396
+ records.push({ root, storeDir, storeSource: source, pnpm: version, pinned: pin, lockfileSha256, ms, allowedBuildsNotRun: skipped, reuseCheckMs, reuseSaveMs, dependencyDigestChecks: reuse?.digestChecks ?? 0, reuseDiagnostic });
321
397
  }
322
398
  return records;
323
399
  }
@@ -364,9 +440,12 @@ export function verifySnapshotStore({ checkout, snapshot, commit, tree, ledger,
364
440
  if (failed(r)) {
365
441
  const joined = `${r?.stdout ?? ""}\n${r?.stderr ?? ""}`.replace(/(https?:\/\/)\s+/g, "$1");
366
442
  const miss = /ERR_PNPM_NO_OFFLINE_TARBALL[\s\S]{0,600}?(https?:\/\/\S+?\/-\/(\S+?)\.tgz)/.exec(joined);
367
- throw new CheckError(miss
368
- ? `root ${root}: ${miss[2]} is missing from the store ${storeDir} (offline, no network fallback); install the checkout's dependencies so the store holds it, then run the check again`
369
- : `root ${root}: the offline store check failed (store ${storeDir}): ${tail(r) || r?.error?.message || `exit ${r?.status}`}`);
443
+ const diagnostic = preparationFailure(r, env);
444
+ const missingName = safeTarballName(miss?.[2]);
445
+ const message = miss && missingName
446
+ ? `root ${root}: ${missingName} is missing from the store ${storeDir} (offline, no network fallback); install the checkout's dependencies so the store holds it, then run the check again`
447
+ : `root ${root}: the offline store check failed (store ${storeDir}): ${diagnostic.codes.join(", ") || `exit ${Number.isInteger(r?.status) ? r.status : "unknown"}`}`;
448
+ throw new CheckError(`${message}; ${diagnostic.detail}`);
370
449
  }
371
450
  records.push({ root, storeDir, storeSource: source, pnpm: version, pinned: pin, lockfileSha256: crypto.createHash("sha256").update(fs.readFileSync(path.join(dir, "pnpm-lock.yaml"))).digest("hex"), ms });
372
451
  }
@@ -383,7 +462,7 @@ export function describeStoreCheck(record) {
383
462
  /** One line per installed root, for the check's output and evidence. */
384
463
  export function describeInstall(record) {
385
464
  if (record.skipped) return `snapshot dependencies root=${record.root} not installed: ${record.skipped}`;
386
- return `snapshot dependencies root=${record.root} pnpm=${record.pnpm}${record.pinned ? ` (pinned ${record.pinned})` : ""} store=${record.storeDir} (from ${record.storeSource}) lockfile=sha256:${record.lockfileSha256} ms=${record.ms}${record.allowedBuildsNotRun.length ? ` build-scripts-not-run=${record.allowedBuildsNotRun.map((b) => (b.probe === "none" ? `${b.name}@${b.version}(deferred, not proven here: ${b.result})` : `${b.name}@${b.version}(usable: ${b.probe} -> ${b.result})`)).join(",")}` : ""}`;
465
+ return `snapshot dependencies root=${record.root} pnpm=${record.pnpm}${record.pinned ? ` (pinned ${record.pinned})` : ""} store=${record.storeDir} (from ${record.storeSource}) lockfile=sha256:${record.lockfileSha256} ms=${record.ms}${record.reuseCheckMs !== undefined ? ` reuse-check-ms=${record.reuseCheckMs}${record.reuseSaveMs !== undefined ? ` reuse-save-ms=${record.reuseSaveMs}` : ""} dependency-digest-checks=${record.dependencyDigestChecks}${record.reuseDiagnostic ? ` reuse-setup=${record.reuseDiagnostic.setup ?? 'unknown'}${record.reuseDiagnostic.match ? ` reuse-match=${record.reuseDiagnostic.match}` : ""}${record.reuseDiagnostic.components ? ` reuse-components=${record.reuseDiagnostic.components}` : ""}${record.reuseDiagnostic.save ? ` reuse-save=${record.reuseDiagnostic.save}` : ""}` : ""}` : ""}${record.reused ? " preparation=reused (installed bytes verified; store availability not re-proved)" : ""}${record.allowedBuildsNotRun.length ? ` build-scripts-not-run=${record.allowedBuildsNotRun.map((b) => (b.probe === "none" ? `${b.name}@${b.version}(deferred, not proven here: ${b.result})` : `${b.name}@${b.version}(usable: ${b.probe} -> ${b.result})`)).join(",")}` : ""}`;
387
466
  }
388
467
 
389
468
  /** The deterministic-red marker for a failed run, or null when any failure is not one a re-run of the same inputs reproduces. */