@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.
@@ -0,0 +1,230 @@
1
+ // A best-effort cache of successful snapshot dependency preparations. A miss
2
+ // always takes the normal offline install path. Records are same-user local
3
+ // state, like the gate's result cache; they are not signed attestations.
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+ import crypto from 'node:crypto';
7
+ import { fileURLToPath } from 'node:url';
8
+ import { installIdentity } from './dependency-identity.mjs';
9
+
10
+ const hash = (bytes) => crypto.createHash('sha256').update(bytes).digest('hex');
11
+ const inside = (p, dir) => p === dir || p.startsWith(dir + path.sep);
12
+ const CONFIG_CODES = new Set(['config-list-failed', 'config-path-query-failed', 'config-list-empty', 'config-json-invalid', 'config-path-unknown', 'config-file-unreadable']);
13
+ const safeError = (error, fallback) => CONFIG_CODES.has(error?.reuseCode) ? error.reuseCode : fallback;
14
+
15
+ // Hash all files, symlink targets, directory names and modes, including pnpm
16
+ // state and tool caches. Follow linked targets once; never trust stat/mtime.
17
+ export function dependencyDigest(snapshot, dirs, { manifest = null } = {}) {
18
+ const h = crypto.createHash('sha256'), seen = new Set(), pending = [];
19
+ let count = 0;
20
+ const root = fs.realpathSync(snapshot);
21
+ const note = (kind, p, mode = null, value = null) => {
22
+ if (!manifest) return;
23
+ if (manifest.length >= 800000) { manifest.truncated = true; return; }
24
+ manifest.push({ kind, pathHash: hash(p), ...(mode === null ? {} : { mode }), ...(value === null ? {} : { valueHash: value }) });
25
+ };
26
+ const walk = (p) => {
27
+ if (++count > 400000) throw new Error('dependency fingerprint exceeds limit');
28
+ const st = fs.lstatSync(p);
29
+ h.update(`${p}\0${st.mode}\0`);
30
+ if (st.isSymbolicLink()) {
31
+ const target = fs.readlinkSync(p);
32
+ h.update(`link\0${target}\0`); if (manifest) note('link', p, st.mode, hash(target));
33
+ try { pending.push(fs.realpathSync(p)); } catch (e) { if (e.code !== 'ENOENT') throw e; h.update('dangling\0'); note('dangling', p); }
34
+ } else if (st.isDirectory()) {
35
+ h.update('dir\0'); note('dir', p, st.mode);
36
+ for (const name of fs.readdirSync(p).sort()) walk(path.join(p, name));
37
+ } else if (st.isFile()) { const digest = hash(fs.readFileSync(p)); h.update(`file\0${digest}\0`); note('file', p, st.mode, digest); }
38
+ else throw new Error('unsupported dependency entry');
39
+ };
40
+ for (const dir of [...dirs].sort()) {
41
+ h.update(`root\0${dir}\0`); note('root', dir);
42
+ try { walk(path.join(snapshot, dir)); } catch (e) { if (e.code !== 'ENOENT' && e.code !== 'ENOTDIR') throw e; h.update('absent\0'); note('absent', dir); }
43
+ }
44
+ while (pending.length) {
45
+ const p = pending.shift();
46
+ if (seen.has(p)) continue;
47
+ seen.add(p);
48
+ if (p === path.parse(p).root || inside(root, p)) throw new Error('dependency link resolves to snapshot ancestor');
49
+ h.update('target\0'); note('target', p); walk(p);
50
+ }
51
+ return h.digest('hex');
52
+ }
53
+
54
+ // Opt-in diagnostics only. Never used as proof; records contain no paths,
55
+ // file contents, link targets or environment values. The directory must
56
+ // already exist inside the host's scratch tree.
57
+ export function captureDependencyManifest(snapshot, dirs) {
58
+ const entries = [];
59
+ const digest = dependencyDigest(snapshot, dirs, { manifest: entries });
60
+ return { digest, entries, complete: !entries.truncated };
61
+ }
62
+
63
+ // GC-A24 (Adrian, 2026-11-05): the proof is pnpm's own install record (installIdentity), not every installed byte; the inputs above
64
+ // (tree, pnpm, node, platform, config, store, environment) already bind what the offline frozen install produces. The byte manifest
65
+ // stays an opt-in diagnostic only.
66
+ function dependencyProof(snapshot, dirs, diagnosticsEnabled) {
67
+ let capture = null;
68
+ if (diagnosticsEnabled) { try { capture = captureDependencyManifest(snapshot, dirs); } catch { capture = null; } }
69
+ return { digest: installIdentity(snapshot, dirs), capture };
70
+ }
71
+
72
+ function writeDiagnostic(dir, phase, root, inputs, components, capture) {
73
+ if (!dir || !path.isAbsolute(dir) || !capture.complete) return;
74
+ let temp;
75
+ try {
76
+ const scratch = fs.realpathSync(process.platform === 'win32' ? 'D:\\scratch' : '/Volumes/D/scratch');
77
+ const target = fs.realpathSync(dir);
78
+ if (!inside(target, scratch) || !fs.statSync(target).isDirectory()) return;
79
+ const file = path.join(target, `dependency-${phase}-${process.pid}-${crypto.randomBytes(8).toString('hex')}.json`);
80
+ temp = `${file}.tmp`;
81
+ fs.writeFileSync(temp, JSON.stringify({ schema: 'rightkit.dependency-manifest/1', phase, rootHash: hash(root), inputs, components, ...capture }), { flag: 'wx' });
82
+ fs.renameSync(temp, file);
83
+ } catch { if (temp) { try { fs.unlinkSync(temp); } catch {} } /* diagnostics never change a proof */ }
84
+ }
85
+
86
+ // Read-only post-Class-A capture. This never reads or updates the reuse record.
87
+ export async function capturePostClassADiagnostics({ checkout, snapshot, commit, roots, diagnosticDir }) {
88
+ if (!diagnosticDir || !Array.isArray(roots)) return;
89
+ try {
90
+ const { treeEntries, dependencyDirs } = await import('./snapshot.mjs');
91
+ const entries = treeEntries(checkout, commit);
92
+ const fold = (s) => process.platform === 'darwin' || process.platform === 'win32' ? s.toLowerCase() : s;
93
+ const dirOf = (p) => p.includes('/') ? p.slice(0, p.lastIndexOf('/')) : '';
94
+ const lockRoots = entries.filter((e) => e.path === 'pnpm-lock.yaml' || e.path.endsWith('/pnpm-lock.yaml')).map((e) => fold(dirOf(e.path))).filter((p) => !p.split('/').includes('node_modules'));
95
+ const nearestLock = (member) => lockRoots.filter((r) => !r || member === r || member.startsWith(`${r}/`)).sort((a, b) => b.length - a.length)[0];
96
+ const generated = [...dependencyDirs(entries, 'linux')];
97
+ for (const root of roots) {
98
+ const owner = fold(path.relative(snapshot, path.resolve(snapshot, root)).split(path.sep).join('/'));
99
+ const dirs = generated.filter((d) => nearestLock(fold(dirOf(d))) === owner);
100
+ writeDiagnostic(diagnosticDir, 'after-a', root, null, null, captureDependencyManifest(snapshot, dirs));
101
+ }
102
+ } catch { /* diagnostics never change the gate result */ }
103
+ }
104
+
105
+ function pnpmIdentity(env) {
106
+ // Do not infer Windows cmd/corepack dispatch or arbitrary shell programs.
107
+ if (process.platform === 'win32') return null;
108
+ for (const dir of String(env.PATH ?? '').split(path.delimiter)) {
109
+ if (!dir || !path.isAbsolute(dir)) continue;
110
+ const p = path.join(dir, 'pnpm');
111
+ let data, real;
112
+ try { real = fs.realpathSync(p); fs.accessSync(real, fs.constants.X_OK); data = fs.readFileSync(real); } catch { continue; }
113
+ const components = [[real, hash(data)]];
114
+ if (data.subarray(0, 2).toString() === '#!') {
115
+ // Recognize only the provisioned pnpm shim's fixed exec target. All
116
+ // other launchers fall back to install, including version managers.
117
+ const text = data.toString('utf8');
118
+ const matches = [...text.matchAll(/^exec "\$basedir\/([^"\n]+)"\s+"\$@"\s*$/gm)];
119
+ if (matches.length !== 1) return null;
120
+ const target = fs.realpathSync(path.resolve(path.dirname(real), matches[0][1]));
121
+ const bytes = fs.readFileSync(target);
122
+ if (bytes.subarray(0, 2).toString() === '#!') return null;
123
+ components.push([target, hash(bytes)]);
124
+ }
125
+ return components;
126
+ }
127
+ return null;
128
+ }
129
+
130
+ function packageIdentity() {
131
+ const root = path.dirname(fileURLToPath(import.meta.url)), rows = [];
132
+ const walk = (dir) => { for (const name of fs.readdirSync(dir).sort()) { if (name === 'node_modules' || name.startsWith('.')) continue; const p = path.join(dir, name), st = fs.lstatSync(p); if (st.isDirectory()) walk(p); else if (st.isFile()) rows.push([path.relative(root, p), st.mode, hash(fs.readFileSync(p))]); else throw new Error('unsupported gate entry'); } };
133
+ walk(root); return hash(JSON.stringify(rows));
134
+ }
135
+
136
+ // Read config in memory only: neither config values nor credentials are stored
137
+ // or logged. Unknown config locations or unreadable files disable reuse.
138
+ export function canonicalConfigFingerprint(effective, files) {
139
+ const canonical = (v) => Array.isArray(v) ? v.map(canonical) : v && typeof v === 'object' ? Object.fromEntries(Object.keys(v).sort().map((key) => [key, canonical(v[key])])) : v;
140
+ return hash(JSON.stringify({ effective: canonical(effective), files }));
141
+ }
142
+
143
+ function pnpmConfigIdentity({ dir, env, spawn }) {
144
+ const fail = (code) => { const e = new Error(code); e.reuseCode = code; throw e; };
145
+ const ask = (args) => {
146
+ const r = spawn('pnpm', ['config', ...args], { cwd: dir, env, maxBuffer: 1 << 24 });
147
+ 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();
149
+ };
150
+ const effective = ask(['list', '--json']);
151
+ if (!effective) fail('config-list-empty');
152
+ let parsed;
153
+ try { parsed = JSON.parse(effective); } catch { fail('config-json-invalid'); }
154
+ const user = ask(['get', 'userconfig']);
155
+ const global = ask(['get', 'globalconfig']);
156
+ const userPath = user && user !== 'undefined' && user !== 'null' ? user : (env.HOME ? path.join(env.HOME, '.npmrc') : null);
157
+ if (!userPath || !path.isAbsolute(userPath) || !global || global === 'undefined' || global === 'null' || !path.isAbsolute(global)) fail('config-path-unknown');
158
+ const file = (p) => {
159
+ try { return [p, fs.realpathSync(p), hash(fs.readFileSync(p))]; }
160
+ catch (e) { if (e.code === 'ENOENT') return [p, 'absent']; fail('config-file-unreadable'); }
161
+ };
162
+ return canonicalConfigFingerprint(parsed, [file(userPath), file(global)]);
163
+ }
164
+
165
+ 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_TEST_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));
170
+ return Object.fromEntries(Object.entries({ source, toolchain, config, store, environment }).map(([name, value]) => [name, hash(JSON.stringify(value))]));
171
+ }
172
+
173
+ export function snapshotDependencyReuse({ checkout, snapshot, tree, root, dirs, filters, storeDir, version, env, spawn, diagnostic = {} }) {
174
+ let stage = 'pnpm-identity';
175
+ try {
176
+ const executable = pnpmIdentity(env);
177
+ if (!executable) { diagnostic.setup = 'pnpm-unresolved'; return null; }
178
+ stage = 'git-common';
179
+ const git = spawn('git', ['rev-parse', '--git-common-dir'], { cwd: checkout, env });
180
+ if (git?.status !== 0) { diagnostic.setup = 'git-common-failed'; return null; }
181
+ const common = String(git.stdout ?? '').trim();
182
+ if (!common) { diagnostic.setup = 'git-common-empty'; return null; }
183
+ const cacheDir = path.join(path.resolve(checkout, common), 'rightkit-gate-dependency-preparation');
184
+ const recordPath = path.join(cacheDir, `${hash(`${fs.realpathSync(snapshot)}\0${root}`)}.json`);
185
+ // Hash values in memory; only the final digest is persisted, never env.
186
+ stage = 'config';
187
+ const config = pnpmConfigIdentity({ dir: path.resolve(snapshot, root), env, spawn });
188
+ stage = 'input-identity';
189
+ 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
+ const inputs = hash(JSON.stringify(components));
191
+ const diagnosticDir = env.RIGHTKIT_PREPARATION_DIAGNOSTIC_DIR;
192
+ let digestChecks = 0;
193
+ diagnostic.setup = 'ready';
194
+ return {
195
+ get digestChecks() { return digestChecks; },
196
+ matches() {
197
+ let phase = 'config';
198
+ try {
199
+ if (pnpmConfigIdentity({ dir: path.resolve(snapshot, root), env, spawn }) !== config) { diagnostic.match = 'config-changed'; return false; }
200
+ phase = 'record';
201
+ const record = JSON.parse(fs.readFileSync(recordPath, 'utf8'));
202
+ if (record.schema !== 5 || !record.components || typeof record.components !== 'object' || typeof record.dependencies !== 'string') { diagnostic.match = 'record-invalid'; return false; }
203
+ const changed = Object.keys(components).filter((key) => record.components[key] !== components[key]);
204
+ if (changed.length || record.inputs !== inputs) { diagnostic.match = 'record-mismatch'; diagnostic.components = changed.length ? changed.join(',') : 'aggregate'; if (diagnosticDir) { try { writeDiagnostic(diagnosticDir, 'lookup', root, inputs, components, captureDependencyManifest(snapshot, dirs)); } catch {} } return false; }
205
+ phase = 'digest'; digestChecks++;
206
+ const { digest, capture } = dependencyProof(snapshot, dirs, diagnosticDir);
207
+ const ok = record.dependencies === digest;
208
+ if (capture) writeDiagnostic(diagnosticDir, 'lookup', root, inputs, components, capture);
209
+ diagnostic.match = ok ? 'hit' : 'dependency-mismatch'; return ok;
210
+ } catch (e) { diagnostic.match = safeError(e, phase === 'record' && e.code === 'ENOENT' ? 'record-missing' : `${phase}-error`); return false; }
211
+ },
212
+ save() {
213
+ let phase = 'config';
214
+ try {
215
+ if (pnpmConfigIdentity({ dir: path.resolve(snapshot, root), env, spawn }) !== config) { diagnostic.save = 'config-changed'; return; }
216
+ phase = 'digest';
217
+ digestChecks++;
218
+ const { digest, capture } = dependencyProof(snapshot, dirs, diagnosticDir);
219
+ const record = JSON.stringify({ schema: 5, inputs, components, dependencies: digest });
220
+ phase = 'write';
221
+ fs.mkdirSync(cacheDir, { recursive: true });
222
+ const temp = `${recordPath}.${process.pid}.${crypto.randomBytes(8).toString('hex')}.tmp`;
223
+ fs.writeFileSync(temp, record, { flag: 'wx' }); fs.renameSync(temp, recordPath);
224
+ if (capture) writeDiagnostic(diagnosticDir, 'save', root, inputs, components, capture);
225
+ diagnostic.save = 'saved';
226
+ } catch (e) { diagnostic.save = safeError(e, `${phase}-error`); }
227
+ },
228
+ };
229
+ } catch (e) { diagnostic.setup = safeError(e, `${stage}-error`); return null; }
230
+ }
@@ -144,7 +144,7 @@ export function directReadSpawn({ spawn, cargoCommand, snapshotRoot, directPath,
144
144
  const cargo = cmd === cargoCommand[0] && prefix.every((w, i) => args[i] === w);
145
145
  if (!cargo || typeof opts.cwd !== "string" || !within(real(opts.cwd), real(snapshotRoot))) return spawn(cmd, args, opts);
146
146
  const words = args.slice(prefix.length);
147
- const shape = carriedScanRefusal(words);
147
+ const shape = words.length === 1 && words[0] === "--version" ? null : carriedScanRefusal(words);
148
148
  if (shape !== null) return refused(CARRIED_METADATA_REFUSED, `\`cargo ${words.join(" ")}\` would run inside the managed snapshot ${snapshotRoot} and is not one of the read-only shapes Class A runs directly (GC-A11): ${shape}`);
149
149
  const memoKey = memo && words[0] === "metadata" && opts.stdoutFile === undefined ? `${real(opts.cwd)}\0${words.join(" ")}` : null;
150
150
  if (memoKey !== null && memo.has(memoKey)) { const hit = { ...memo.get(memoKey) }; return isAsync ? Promise.resolve(hit) : hit; }
@@ -23,7 +23,7 @@ import path from "node:path";
23
23
  import { REQUEST_OVER_CAP_CODE, requestOverCap } from "./broker-wire.mjs";
24
24
  import { ownerFileOf, writeCarrierOwner } from "./carrier-census.mjs";
25
25
  import { BROKER_COMPILE_COMMANDS, CARGO_COMMAND_ALIASES, cargoCommandIndex, cargoSubcommandOf, expandCargoAliases, isCompileCommand, isPackageObservation } from "./cargo-shapes.mjs";
26
- import { canonicalJson, CAUSE_EVIDENCE_SCHEMA, CAUSE_UNEXPLAINED, CAUSE_UNKNOWN, ProvenanceError, verifyBr19Evidence, verifyCauseEvidence, verifyProvenance, verifyReceiptCoverage, verifyResultEvidence } from "./provenance-verify.mjs";
26
+ import { canonicalJson, CAUSE_EVIDENCE_SCHEMA, CAUSE_UNEXPLAINED, CAUSE_UNKNOWN, ProvenanceError, verifyBr19Evidence, verifyCauseEvidence, verifyFailureClass, verifyPostChecks, verifyProvenance, verifyReceiptCoverage, verifyResultEvidence } from "./provenance-verify.mjs";
27
27
 
28
28
  export const SNAPSHOT_REQUEST_SCHEMA = "rustright.snapshot-request/1";
29
29
  // One spelling per variable, the current one (rustright-cli shims.rs reads RUSTRIGHT_* first, then the legacy RIGHTKIT_* spelling, which task
@@ -560,14 +560,18 @@ export function verifyNestedChildren(evidence, receipt, { snapshotPath, checkout
560
560
  * - timingsMs, exit, diagnosticsPath, brokerVersion and executor present with their types; the retired `verdict` and `refreshed` are refused (GB-30: Class A and its verdict reuse are the gate's).
561
561
  * `checkout` and `outputRoots` are required: without them nothing can be said about where the outputs went, so it refuses.
562
562
  */
563
- export function verifySnapshotReceipt(receipt, { pins, jobId, carrier, argv, workspace, observedEnv = {}, adapter = null, adapterEnv = {}, checkout, outputRoots, platform = process.platform, canonicalPath = (p) => fs.realpathSync.native(p), digestInputs = declaredInputDigestsOf, readInputs = readDeclaredInputs, inputPolicy = null }) {
563
+ export function verifySnapshotReceipt(receipt, { pins, jobId, carrier, argv, workspace, observedEnv = {}, adapter = null, adapterEnv = {}, checkout, outputRoots, platform = process.platform, canonicalPath = (p) => fs.realpathSync.native(p), digestInputs = declaredInputDigestsOf, readInputs = readDeclaredInputs, inputPolicy = null, allowFailedCompile = false }) {
564
564
  const requestDigest = requestDigestOf(snapshotRequestCore({ argv, workspace, observedEnv, carrier, adapter, adapterEnv }));
565
565
  const payload = verifyProvenance(receipt, pins, { jobId, nonce: carrier.nonce, requestDigest });
566
566
  // The signed outcome, not the client's exit code: a passing row needs the broker to have signed SUCCEEDED with exit 0 and no
567
567
  // signal (service.rs provenance_payload `result`). An authentic FAILED, or a payload without a result, is not a success.
568
568
  const result = payload.result;
569
569
  if (!result || typeof result !== "object") fail("result", "the signed payload carries no result: the broker did not sign this request's outcome");
570
- if (result.status !== "SUCCEEDED" || result.exitCode !== 0 || (result.signal !== undefined && result.signal !== null)) {
570
+ const success = result.status === "SUCCEEDED" && result.exitCode === 0 && (result.signal === undefined || result.signal === null);
571
+ // Opt in only to an authenticated, non-signal Cargo compile failure. This is evidence of failure,
572
+ // not proof that its cause is a compiler diagnostic or that retry is appropriate.
573
+ const failedCompile = allowFailedCompile === true && adapter === null && isCompileClass(argv) && result.status === "FAILED" && result.failureClass === "compile" && Number.isSafeInteger(result.exitCode) && result.exitCode > 0 && result.exitCode <= 255 && (result.signal === undefined || result.signal === null);
574
+ if (!success && !failedCompile) {
571
575
  // Any terminal status but SUCCEEDED fails the call, whatever the broker says about why (a tracked write is refused at exit with a
572
576
  // `snapshot exit bind: ...` message; the field that carries it is pending RustRight's confirmation, so the usual spellings are read).
573
577
  // The signed result of a broker verdict after a clean run (FAILED with exit 0: RR_UNEXPLAINED_COLD, ...) carries no reason; the receipt's own
@@ -688,7 +692,7 @@ export function verifySnapshotReceipt(receipt, { pins, jobId, carrier, argv, wor
688
692
  ];
689
693
  for (const [name, ok] of typed) if (!ok) fail("evidence", `receipt ${name} is missing or has the wrong type`);
690
694
  for (const name of ["verdict", "refreshed"]) if (Object.hasOwn(receipt, name)) fail("evidence", `receipt carries the retired field ${name}`);
691
- if (receipt.exit !== 0 || receipt.signal !== null) fail("evidence", `receipt exit ${receipt.exit} and signal ${receipt.signal} are not a success (exit 0, no signal)`);
695
+ if (receipt.exit !== result.exitCode || receipt.signal !== null) fail("evidence", `receipt exit ${receipt.exit} and signal ${receipt.signal} do not match the signed result (exit ${result.exitCode}, no signal)`);
692
696
  // RustRight signs the result fields under payload.resultEvidence (service.rs provenance_payload; attestation.rs RESULT_EVIDENCE_FIELDS), never at
693
697
  // the payload's top level. Every receipt copy must equal its signed counterpart, and a receipt with no signed resultEvidence is refused: the
694
698
  // exit, signal, timings and diagnostics path it shows would otherwise be this receipt's own say-so.
@@ -707,9 +711,12 @@ export function verifySnapshotReceipt(receipt, { pins, jobId, carrier, argv, wor
707
711
  // against RustRight's receipt vector case for case) must also accept: no signed-only or receipt-only field anywhere, the signed result evidence with exactly
708
712
  // its four fields and six phases, and the BR19 shape (profile, stage, resources, environment; a value or a typed UNKNOWN, never absent).
709
713
  verifyReceiptCoverage(receipt, payload);
714
+ verifyFailureClass(receipt, payload);
715
+ const postChecks = verifyPostChecks(receipt, payload, { snapshotAttested: true });
716
+ if (success && Object.hasOwn(result, "failureClass") && result.failureClass !== null) fail("result", "a successful result has a non-null failureClass");
710
717
  verifyResultEvidence(receipt, payload);
711
718
  verifyBr19Evidence(receipt, payload);
712
- return { payload, evidence, attribution, toolchain, nestedChildren, requestDigest, causeEvidence };
719
+ return { payload, evidence, attribution, toolchain, nestedChildren, requestDigest, causeEvidence, signedResult: { status: result.status, exitCode: result.exitCode, signal: result.signal ?? null, ...(Object.hasOwn(result, "failureClass") ? { failureClass: result.failureClass } : {}), postChecks } };
713
720
  }
714
721
 
715
722
  export { CAUSE_EVIDENCE_SCHEMA, CAUSE_UNEXPLAINED, CAUSE_UNKNOWN, ProvenanceError };
package/snapshot.mjs CHANGED
@@ -236,20 +236,38 @@ export function resolveCommit(checkout, rev = "HEAD") {
236
236
  * object database and ignore rules; writes only objects (into the checkout's object database) and a temporary index kept outside the
237
237
  * checkout's `.git`, always removed.
238
238
  */
239
- export function snapshotTree({ checkout, dir, baseTree, repo = repositoryOf(checkout) }) {
239
+ export function snapshotTree({ checkout, dir, baseTree, repo = repositoryOf(checkout), indexStore = treeIndexStoreOf(dir) }) {
240
240
  // The sealed runner (snapshot-git.mjs): a private git directory T holds the index and receives every object written; the
241
241
  // checkout's git directory is not written at all (row 5.13), and its configuration, attributes, hooks and filters cannot reach the id.
242
- return withSealedGit({ commonDir: repo.commonDir, objectFormat: repo.objectFormat, snapshot: dir }, (git) => {
242
+ const once = (stored) => withSealedGit({ commonDir: repo.commonDir, objectFormat: repo.objectFormat, snapshot: dir }, (git) => {
243
+ const index = path.join(git.T, "index");
243
244
  try {
244
- git.ok(["read-tree", baseTree]);
245
+ if (stored) fs.copyFileSync(stored, index); else git.ok(["read-tree", baseTree]);
245
246
  git.ok(["add", "-A"]);
246
247
  const id = git.ok(["write-tree"]).trim();
247
248
  if (!/^[0-9a-f]{40}([0-9a-f]{24})?$/.test(id)) throw new SnapshotError("error", `git write-tree printed ${JSON.stringify(id)}`);
249
+ if (indexStore) {
250
+ try { const next = `${indexStore}.${process.pid}.tmp`; fs.copyFileSync(index, next); fs.renameSync(next, indexStore); } catch { /* a cache: the next run starts fresh */ }
251
+ }
248
252
  return id;
249
253
  } catch (e) {
250
254
  throw e instanceof SnapshotError ? e : new SnapshotError("error", e.message);
251
255
  }
252
256
  });
257
+ if (indexStore && fs.existsSync(indexStore)) {
258
+ try { return once(indexStore); } catch { try { fs.rmSync(indexStore, { force: true }); } catch { /* best effort */ } }
259
+ }
260
+ return once(null);
261
+ }
262
+
263
+ /** Where a gate snapshot's tree index is kept (`<snapshot>.tree-index` beside it), or null for any other directory (a checkout). */
264
+ export function treeIndexStoreOf(dir) {
265
+ try {
266
+ const resolved = path.resolve(dir);
267
+ if (!/^[0-9a-f]{16}$/.test(path.basename(resolved))) return null;
268
+ const root = snapshotRoot();
269
+ return path.resolve(path.dirname(resolved)) === path.resolve(root) ? `${resolved}.tree-index` : null;
270
+ } catch { return null; }
253
271
  }
254
272
 
255
273
  /**
@@ -258,7 +276,7 @@ export function snapshotTree({ checkout, dir, baseTree, repo = repositoryOf(chec
258
276
  * input even though the seeded tree id cannot see it. Never follows a link (only real directories are entered); names compare
259
277
  * case-insensitively where the host filesystem does (Mac, Windows; colliding names were refused before this runs).
260
278
  */
261
- function pruneToTree(dir, entries, platform = process.platform, keepRoot = new Set()) {
279
+ function pruneToTree(dir, entries, platform = process.platform, keepRoot = new Set(), keepDirs = new Set()) {
262
280
  const fold = platform === "darwin" || platform === "win32" ? (n) => n.toLowerCase() : (n) => n;
263
281
  const files = new Set(entries.map((e) => fold(e.path)));
264
282
  const dirs = new Set();
@@ -268,7 +286,9 @@ function pruneToTree(dir, entries, platform = process.platform, keepRoot = new S
268
286
  for (const e of fs.readdirSync(d, { withFileTypes: true })) {
269
287
  const r = rel ? `${rel}/${e.name}` : e.name;
270
288
  const p = path.join(d, e.name);
271
- if (e.isDirectory()) { if (dirs.has(fold(r))) walk(p, r); else { fs.rmSync(p, { recursive: true, force: true }); removed++; } }
289
+ // keepDirs: the commit's own generated pnpm dependency directories (dependencyDirs), real directories only, kept whole for the
290
+ // dependency step, which reuses them only when every installed byte matches its last completed install and otherwise removes them.
291
+ if (e.isDirectory()) { if (keepDirs.has(fold(r))) continue; if (dirs.has(fold(r))) walk(p, r); else { fs.rmSync(p, { recursive: true, force: true }); removed++; } }
272
292
  else if (!files.has(fold(r)) && !(rel === "" && keepRoot.has(fold(r)))) { fs.unlinkSync(p); removed++; }
273
293
  }
274
294
  };
@@ -928,7 +948,22 @@ export function syncSnapshot({ checkout, rev = "HEAD", root = snapshotRoot(), ma
928
948
  const s = lstat(identityPath);
929
949
  return !!s?.isFile() && s.nlink === 1n && (process.platform === "win32" || (Number(s.mode) & 0o111) === 0) && fs.readFileSync(identityPath).equals(identityBytes);
930
950
  })();
931
- removed += pruneToTree(dir, entries, process.platform, keepIdentity ? new Set([foldFor(process.platform)(SOURCE_IDENTITY_FILE)]) : new Set());
951
+ // GC-A24: a `.git` that holds exactly the gate's config-only origin file (gateGitConfigBody of the checkout's origin, the one
952
+ // allowance snapshotProblem admits) is kept, so class A does not create and remove it on every run; any other `.git` is pruned.
953
+ const keepGit = (() => {
954
+ try {
955
+ if (entries.some((e) => e.path === ".git" || e.path.startsWith(".git/"))) return false;
956
+ const g = path.join(dir, ".git"); const st = lstat(g);
957
+ if (!st?.isDirectory() || st.isSymbolicLink()) return false;
958
+ const names = fs.readdirSync(g); if (names.length !== 1 || names[0] !== "config") return false;
959
+ const c = lstat(path.join(g, "config")); if (!c?.isFile() || c.nlink !== 1n) return false;
960
+ const origin = originUrlOf(repo.checkout);
961
+ return Boolean(origin) && fs.readFileSync(path.join(g, "config"), "utf8") === gateGitConfigBody(origin);
962
+ } catch { return false; }
963
+ })();
964
+ const keepDeps = dependencyDirs(entries, process.platform);
965
+ if (keepGit) keepDeps.add(foldFor(process.platform)(".git"));
966
+ removed += pruneToTree(dir, entries, process.platform, keepIdentity ? new Set([foldFor(process.platform)(SOURCE_IDENTITY_FILE)]) : new Set(), keepDeps);
932
967
  if (identityBytes) {
933
968
  // Written only when the commit's own ignore rules ignore the name (they are in the snapshot now): an unignored file would change the
934
969
  // tree id the broker computes too, so the gate would break every build of that repository. Then nothing is written and the reason is reported.
package/stage-sidecar.mjs CHANGED
@@ -40,7 +40,21 @@ import { spawnSync as nodeSpawnSync } from "./background-process.mjs";
40
40
  import { resolveCommand } from "./development.mjs";
41
41
  import { carriedCargoMapOf } from "./carried-cargo.mjs";
42
42
  import { BUILD_LAUNCH_REFUSED, buildLaunch } from "./build-launch.mjs";
43
- import { directHost, managedHost, runCargoSync } from "./managed-cargo.mjs";
43
+ import { directCargoPath, directHost, managedHost, nonCompilingCargoEnv, runCargoSync } from "./managed-cargo.mjs";
44
+ import { snapshotCargoMetadata } from "./gate-serve.mjs";
45
+ import { snapshotRoot } from "./snapshot.mjs";
46
+
47
+ /**
48
+ * `cargo metadata` for the sidecar (GC-A11: non-compiling, never through the broker). Inside a gate snapshot the resident gate answers it, cached
49
+ * while the snapshot is unchanged; elsewhere, or when the resident gate is unavailable, the real cargo runs directly.
50
+ */
51
+ function sidecarCargoMetadata(cwd, args, env) {
52
+ const cargoEnv = nonCompilingCargoEnv(env);
53
+ const pathKey = process.platform === "win32" ? (Object.keys(cargoEnv).find((k) => k.toUpperCase() === "PATH") ?? "Path") : "PATH";
54
+ const cargo = directCargoPath({ env: { ...cargoEnv, PATH: cargoEnv[pathKey] }, platform: process.platform }).cargo;
55
+ let root = null; try { root = snapshotRoot({ env }); } catch { root = null; }
56
+ return snapshotCargoMetadata({ cwd, args, cargo, env: cargoEnv, snapshotRootDir: root ?? "/nonexistent" });
57
+ }
44
58
  import { APPROVAL_MACHO_STRIP_LINKEDIT_V1, APPROVAL_RAW_SHA256, approvalDigest } from "./macho-approval-hash.mjs";
45
59
  import {
46
60
  bundledFileName, planMediaSidecar, sourceOfferText, stagedFileName, validateMediaSidecarConfig, verifyStagedSidecars, writeMediaSidecarNotices,
@@ -782,7 +796,9 @@ function resolveCatalogFile(spec, ctx, kind) {
782
796
  if (spec.via === "absolute") return requireSnapshotSource(ctx, spec.file, `the ${label} catalog`);
783
797
  if (spec.via === "path") return requireSnapshotSource(ctx, path.resolve(ctx.appRoot, spec.file), `the ${label} catalog`);
784
798
  if (spec.via === "crate") {
785
- const meta = ctx.run("rustright", ["cargo", "metadata", "--frozen", "--format-version", "1"], { cwd: ctx.appRoot, env: ctx.env });
799
+ // Non-compiling cargo runs directly, never through the broker (GC-A11): from inside a gate snapshot the broker refuses a root request
800
+ // ("a root request cannot run inside a managed snapshot"), which made every crate-located catalog unreadable in a gate compile.
801
+ const meta = sidecarCargoMetadata(ctx.appRoot, ["metadata", "--frozen", "--format-version", "1"], ctx.env ?? process.env);
786
802
  let packages;
787
803
  try { packages = JSON.parse(meta.stdout).packages; } catch { /* refused below */ }
788
804
  if (meta?.status !== 0 || !Array.isArray(packages)) fail("STAGE_SIDECAR_CATALOG_UNREADABLE", `the ${label} catalog crate ${spec.crate} cannot be located: the workspace metadata query failed`, { crate: spec.crate });
@@ -926,7 +942,7 @@ function requireSnapshotSource(ctx, file, label) {
926
942
  * A path outside the snapshot (an absolute CARGO_TARGET_DIR, a target-dir set in the user's Cargo home) stands as reported.
927
943
  */
928
944
  function snapshotTargetDirectory(ctx, env, manifest) {
929
- const resolved = ctx.run("rustright", ["cargo", "metadata", "--offline", "--format-version", "1", "--no-deps", ...(manifest ? ["--manifest-path", manifest] : [])], { cwd: ctx.appRoot, env });
945
+ const resolved = sidecarCargoMetadata(ctx.appRoot, ["metadata", "--offline", "--format-version", "1", "--no-deps", ...(manifest ? ["--manifest-path", manifest] : [])], env);
930
946
  let dir;
931
947
  try { dir = JSON.parse(resolved?.stdout).target_directory; } catch { /* reported below */ }
932
948
  if (resolved?.error || resolved?.status !== 0 || typeof dir !== "string" || !path.isAbsolute(dir)) return { error: resolved?.error?.message ?? `exit ${resolved?.status}` };
@@ -1109,7 +1125,7 @@ function stageCargoBuild(entry, ctx, triple) {
1109
1125
  source = candidates.find((file) => fs.existsSync(file));
1110
1126
  if (!source) fail("STAGE_SIDECAR_BINARY_NOT_FOUND", `the build did not produce ${entry.bin} (looked in ${candidates.join(", ")})`, { bin: entry.bin, candidates });
1111
1127
  } else if (!source || !fs.existsSync(source)) {
1112
- const meta = run("rustright", ["cargo", "metadata", "--format-version", "1", "--no-deps", ...(manifestFile ? ["--manifest-path", manifestFile] : [])], { cwd: appRoot, env: buildEnv });
1128
+ const meta = sidecarCargoMetadata(appRoot, ["metadata", "--format-version", "1", "--no-deps", ...(manifestFile ? ["--manifest-path", manifestFile] : [])], buildEnv);
1113
1129
  let targetDir;
1114
1130
  try { targetDir = JSON.parse(meta.stdout).target_directory; } catch { /* refused below */ }
1115
1131
  if (meta?.status !== 0 || typeof targetDir !== "string" || !path.isAbsolute(targetDir)) targetDir = undefined;
@@ -0,0 +1,37 @@
1
+ #!/usr/bin/env node
2
+ // Line-stamping relay for the gate's inherited-output children (GATE-CONTRACT GC-A21, rightkit#1463/#1514): `node stamp-relay.mjs <cmd> [args...]`
3
+ // runs <cmd> with piped output and writes every complete line to its own stdout/stderr prefixed with the UTC time, the same form the gate's
4
+ // own lines carry. The gate keeps launching synchronously (spawnSync, stdio inherit) and only puts this relay in front, so a child's live output
5
+ // still streams. A partial last line is stamped and ended at exit. The relay passes stdin through, forwards SIGINT, SIGTERM and SIGHUP to the
6
+ // child, and ends the way the child ended: the same exit code, or the same signal re-raised on itself.
7
+ import { spawn } from "node:child_process";
8
+ import { pathToFileURL } from "node:url";
9
+
10
+ export function lineStamper(write, now = () => new Date().toISOString()) {
11
+ let pending = "";
12
+ return {
13
+ push(chunk) {
14
+ pending += chunk;
15
+ let at;
16
+ while ((at = pending.indexOf("\n")) >= 0) { write(`${now()} ${pending.slice(0, at + 1)}`); pending = pending.slice(at + 1); }
17
+ },
18
+ end() { if (pending) { write(`${now()} ${pending}\n`); pending = ""; } },
19
+ };
20
+ }
21
+
22
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
23
+ const [cmd, ...args] = process.argv.slice(2);
24
+ if (!cmd) { process.stderr.write("usage: stamp-relay.mjs <cmd> [args...]\n"); process.exit(64); }
25
+ const child = spawn(cmd, args, { stdio: ["inherit", "pipe", "pipe"], windowsHide: true });
26
+ const out = lineStamper((s) => process.stdout.write(s));
27
+ const err = lineStamper((s) => process.stderr.write(s));
28
+ child.stdout.setEncoding("utf8").on("data", (c) => out.push(c));
29
+ child.stderr.setEncoding("utf8").on("data", (c) => err.push(c));
30
+ for (const sig of ["SIGINT", "SIGTERM", "SIGHUP"]) process.on(sig, () => { try { child.kill(sig); } catch { /* already gone */ } });
31
+ child.on("error", (e) => { process.stderr.write(`${new Date().toISOString()} stamp-relay: ${cmd} could not be started (${e.code ?? e.message})\n`); process.exit(127); });
32
+ child.on("close", (code, signal) => {
33
+ out.end(); err.end();
34
+ if (signal) { process.removeAllListeners(signal); process.kill(process.pid, signal); return; }
35
+ process.exitCode = code ?? 1;
36
+ });
37
+ }
package/unit-gate.mjs CHANGED
@@ -13,6 +13,7 @@ import { RIGHTKIT_REPOSITORY, buildDirectOrigin, directStageEvidence, verifyDire
13
13
  import { exclusionsFor } from "./pack-digest.mjs";
14
14
  import { ATTEST_STAGE_NONCE_ENV, qualificationNonce } from "./provenance-verify.mjs";
15
15
  import { verifyQualificationReceipts } from "./qualification-verify.mjs";
16
+ import { ciCompileIdentity, ciCompileStageNonce, makeCiCompileProof, verifyCiCompileProof } from "./ci-compile-admission.mjs";
16
17
  import { assignJobs, describeCommand, directRowsNotRun, expectedStageCommands } from "./stage-commands.mjs";
17
18
  import { carriedCargoMapOf } from "./carried-cargo.mjs";
18
19
  import { UNSCOPED, readLedger } from "./cargo-ledger.mjs";
@@ -341,11 +342,16 @@ export function knownRedEntry({ unit, root, platform, toRelease = false, readTex
341
342
  * ({ start(stage), end(stage) } returning true or false) is the door's ledger verify around each stage (7.08); `envExtra` carries the
342
343
  * Cargo output pin. Without `source` every behavior is the checkout route's, unchanged.
343
344
  */
344
- export async function runUnitGate({ selector, to, root, commonDir, commit, tree, executor, env, platform, check, source = null, stageGuard = null, envExtra = {}, loadOwner = () => import("./local-publish.mjs"), out = console.log, err = console.error, releaser = null, loadPipeline = loadInGatePipeline, resolve = resolveUnit, writeReport, fetchReceipt = readBrokerReceipt, stageCommands = defaultStageCommands, readKnownRed, verifyReceipts = verifyQualificationReceipts, selfGit = null }) {
345
+ export async function runUnitGate({ selector, to, root, commonDir, commit, tree, executor, env, platform, check, source = null, stageGuard = null, envExtra = {}, loadOwner = () => import("./local-publish.mjs"), out = console.log, err = console.error, releaser = null, loadPipeline = loadInGatePipeline, resolve = resolveUnit, writeReport, fetchReceipt = readBrokerReceipt, stageCommands = defaultStageCommands, readKnownRed, verifyReceipts = verifyQualificationReceipts, selfGit = null, ciProofOut = null }) {
345
346
  const stages = stagesTo(to);
346
347
  if (!stages) { err(`rightkit-gate: invalid unit stage ${to}`); return 2; }
347
348
  let unit;
348
349
  try { unit = resolve(selector, root); } catch (error) { err(`rightkit-gate: BLOCKED: ${error.message}`); return 1; }
350
+ const ciProof = ciProofOut !== null;
351
+ if (ciProof && (typeof ciProofOut !== "string" || !ciProofOut || selector !== "cargo:rightkit-decimal" || to !== "compile" || executor?.kind !== "broker" || !source || !stageGuard)) {
352
+ err("rightkit-gate: BLOCKED: CI compile proof requires the managed snapshot broker route for cargo:rightkit-decimal through compile");
353
+ return 1;
354
+ }
349
355
  // Before any compile (so --to compile|package|qualify|release; --to check compiles nothing): a unit recorded red is refused, not built.
350
356
  if (stages.includes("compile")) {
351
357
  try {
@@ -369,7 +375,7 @@ export async function runUnitGate({ selector, to, root, commonDir, commit, tree,
369
375
  // is sent the stage nonce, a carried Cargo call a nonce derived from it, both bound to this commit, tree, unit and stage, so each job's
370
376
  // signed receipt can be verified hosted for exactly that and nothing else. `--to qualify` is the sanctioned no-upload route to that
371
377
  // evidence: it writes the qualification and verifies it locally exactly as the hosted admission will, and stops there.
372
- const attested = stages.includes("qualify") && executor?.kind === "broker";
378
+ const attested = (stages.includes("qualify") || ciProof) && executor?.kind === "broker";
373
379
  // GB-29: a direct Linux origin has no broker to attest its stages; it records its own direct-origin evidence (direct-origin.mjs), verified locally as the hosted side will.
374
380
  const directLinux = stages.includes("qualify") && executor?.kind === "direct" && platform === "linux";
375
381
  const directStages = {};
@@ -381,7 +387,7 @@ export async function runUnitGate({ selector, to, root, commonDir, commit, tree,
381
387
  };
382
388
  const stageEnv = async (stage, action) => {
383
389
  const run = startRun({ commonDir, commit, tree, stage });
384
- const nonce = attested && ATTESTED_STAGES.includes(stage) ? { [ATTEST_STAGE_NONCE_ENV]: qualificationNonce({ commit, tree, unit: `${unit.kind}:${unit.name}`, stage }) } : {};
390
+ const nonce = attested && ATTESTED_STAGES.includes(stage) ? { [ATTEST_STAGE_NONCE_ENV]: (ciProof ? ciCompileStageNonce(ciCompileIdentity({ commit, tree })) : qualificationNonce({ commit, tree, unit: `${unit.kind}:${unit.name}`, stage })) } : {};
385
391
  try { return await action({ ...env, ...envExtra, ...nonce, ...run.env }); } finally { endRun(run); }
386
392
  };
387
393
  // The hosted admission's own verification of the qualification's receipts, run here against the commit before anything is dispatched
@@ -474,7 +480,17 @@ export async function runUnitGate({ selector, to, root, commonDir, commit, tree,
474
480
  const qualification = directQualification();
475
481
  out(`rightkit-gate: [qualify] ${unit.kind}:${unit.name} direct-origin qualification ${qualification} verified locally; nothing was dispatched`);
476
482
  }
477
- if (attested && !stages.includes("release")) {
483
+ if (ciProof) {
484
+ currentStage = "compile";
485
+ if (state && owner) { await owner.closeLocalUnit(state); state = null; }
486
+ const proof = JSON.stringify(makeCiCompileProof({ commit, tree, receipts: receipts.compile }));
487
+ verifyCiCompileProof(proof, { sha: commit, scope: "rust:rightkit-decimal", git: gitAt });
488
+ const fd = fs.openSync(ciProofOut, "wx", 0o600);
489
+ try { fs.writeFileSync(fd, `${proof}\n`); fs.closeSync(fd); }
490
+ catch (error) { try { fs.closeSync(fd); } catch {} try { fs.unlinkSync(ciProofOut); } catch {} throw error; }
491
+ out(`rightkit-gate: [compile] CI proof ${ciProofOut} verified locally`);
492
+ }
493
+ if (attested && !ciProof && !stages.includes("release")) {
478
494
  // --to qualify on a broker host: the qualification is written beside the artifact and verified as the hosted run will, and no upload exists.
479
495
  currentStage = "qualify";
480
496
  const qualification = writeQualification({ report, artifact, unit, commit, tree, runtime, executor });
@@ -486,5 +502,9 @@ export async function runUnitGate({ selector, to, root, commonDir, commit, tree,
486
502
  if (currentStage) { report.stages[currentStage] = { ok: false }; save(); }
487
503
  err(`rightkit-gate: unit ${selector} stopped: ${error.message}`);
488
504
  return 1;
489
- } finally { if (state && owner) await owner.closeLocalUnit(state); }
505
+ } finally {
506
+ const started = performance.now();
507
+ try { if (state && owner) await owner.closeLocalUnit(state); }
508
+ finally { process[Symbol.for("rightkit.releaseTiming")] = { generatorCloseMs: performance.now() - started, generatorEndEpochMs: performance.timeOrigin + performance.now() }; }
509
+ }
490
510
  }