@rightkit/release 0.6.42 → 0.6.44

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.
@@ -392,6 +392,16 @@ export function checkCrateAdvisoryExceptions({ root = process.cwd(), now = new D
392
392
  }
393
393
  for (const p of checkAdvisoryExceptions({ root: here, now, allowPending, exceptionsFile: CRATE_EXCEPTIONS_FILE, readFile: f => readFile(path.join(here, f)) })) problems.push(`${dir}: ${p}`);
394
394
  }
395
+ // RightKit is one Cargo workspace with one Cargo.lock (GATE-CONTRACT GC-T24): the repository root holds the ledger, deny.toml and
396
+ // .cargo/audit.toml for every crate that is a member of it.
397
+ if (exists(path.join(root, 'Cargo.toml')) && exists(path.join(root, LOCK_FILE))) {
398
+ const ignores = [DENY_FILE, AUDIT_FILE].some(f => { try { return IGNORE_LIST_RE.test(readFile(path.join(root, f))); } catch { return false; } });
399
+ if (!exists(path.join(root, CRATE_EXCEPTIONS_FILE))) {
400
+ if (ignores) problems.push(`.: ${DENY_FILE} or ${AUDIT_FILE} ignores an advisory but ${CRATE_EXCEPTIONS_FILE} does not exist`);
401
+ } else {
402
+ for (const p of checkAdvisoryExceptions({ root, now, allowPending, exceptionsFile: CRATE_EXCEPTIONS_FILE, readFile: f => readFile(path.join(root, f)) })) problems.push(`.: ${p}`);
403
+ }
404
+ }
395
405
  return problems;
396
406
  }
397
407
 
@@ -1552,6 +1552,7 @@ async function runStages(o, args, root, git, io) {
1552
1552
  try { synced = (o.syncSnapshot ?? snap.syncSnapshot)({ checkout: root, rev: selected.commit, root: snapshotsAt }); }
1553
1553
  catch (e) { o.err(`${tag} ${e.code === "error" ? "RK_CHECK_ERROR" : "BLOCKED"}: snapshot ${e.message}; nothing ran`); return e.code === "error" ? 2 : 1; }
1554
1554
  o.out(`${tag} snapshot ${synced.path} is commit ${synced.commit} tree ${synced.tree} (written=${synced.written} removed=${synced.removed} unchanged=${synced.unchanged})`);
1555
+ if (synced.identity) o.out(`${tag} source identity ${synced.identity.file}: ${synced.identity.written ? "written" : synced.identity.kept ? "kept" : `not written (${synced.identity.reason})`}`);
1555
1556
  return await runStages({ ...o, buildOwnership: own, doorSnapshot: { own, path: synced.path, commit: synced.commit, tree: synced.tree, root: snapshotsAt, ledger: { entries: [] } } }, args, root, git, { ...io, buildOwnership: own });
1556
1557
  } finally {
1557
1558
  const r = own.release();
@@ -2522,6 +2523,7 @@ async function runUnitSnapshot(o, args, root, git, io, option) {
2522
2523
  try { synced = (o.syncSnapshot ?? snap.syncSnapshot)({ checkout: root, rev: commit, root: snapshotsAt }); }
2523
2524
  catch (e) { o.err(`${tag} ${e.code === "error" ? "RK_CHECK_ERROR" : "BLOCKED"}: snapshot ${e.message}; nothing ran`); return e.code === "error" ? 2 : 1; }
2524
2525
  o.out(`${tag} snapshot ${synced.path} is commit ${synced.commit} tree ${synced.tree} (written=${synced.written} removed=${synced.removed} unchanged=${synced.unchanged})`);
2526
+ if (synced.identity) o.out(`${tag} source identity ${synced.identity.file}: ${synced.identity.written ? "written" : synced.identity.kept ? "kept" : `not written (${synced.identity.reason})`}`);
2525
2527
  const ds = { own, path: synced.path, commit: synced.commit, tree: synced.tree, root: snapshotsAt, ledger: { entries: [] } };
2526
2528
  // A unit's test or pack that reaches Cargo must never write `target/` into the snapshot (npm units included): see bindUnitCargo.
2527
2529
  // A check starts no unit command: its own Class A path binds read-only Cargo calls. Resolving every unit's compile output
@@ -3305,6 +3307,7 @@ export async function main(argv, io = {}) {
3305
3307
  try { synced = (o.syncSnapshot ?? snap.syncSnapshot)({ checkout, rev: selected.commit, root: snapshotsAt }); }
3306
3308
  catch (e) { o.err(`rightkit-gate: ${e.code === "error" ? sc.CHECK_ERROR : "BLOCKED"}: snapshot ${e.message}; nothing ran`); return e.code === "error" ? 2 : 1; }
3307
3309
  o.out(`rightkit-gate: snapshot ${synced.path} is commit ${synced.commit} tree ${synced.tree} (written=${synced.written} removed=${synced.removed} unchanged=${synced.unchanged})`);
3310
+ if (synced.identity) o.out(`rightkit-gate: source identity ${synced.identity.file}: ${synced.identity.written ? "written" : synced.identity.kept ? "kept" : `not written (${synced.identity.reason})`}`);
3308
3311
  const next = [...argv]; const ci = next.indexOf("--commit");
3309
3312
  if (ci >= 0) next.splice(ci, 2, "--commit", synced.commit); else next.push("--commit", synced.commit);
3310
3313
  next.push("--snapshot", synced.path);
@@ -2416,16 +2416,36 @@ const INTERNAL = {
2416
2416
  "dependency-freshness": async (s, ctx) => {
2417
2417
  let bin;
2418
2418
  try { bin = resolveOutdatedBin(); } catch (e) { return { advice: `dependency freshness not measured: ${e instanceof OutdatedUnavailableError ? e.message : `right-update could not be located (${e.message})`}` }; }
2419
+ // The answer is a property of the repository's lock files and of the registry at this hour, not of the unit being gated: a run per unit of one
2420
+ // commit asks the registry again for the same locks (88 s per crate on 2026-11-04, 6795 s over 77 crate runs). One answer per lock set and UTC hour.
2421
+ let cachePath = null;
2422
+ try {
2423
+ const names = [".rightkit/update.json", "Cargo.lock", "pnpm-lock.yaml", "package.json"];
2424
+ const h = crypto.createHash("sha256");
2425
+ for (const n of names) { h.update(`${n}\0`); try { h.update(fs.readFileSync(path.join(ctx.contentRoot, n))); } catch { h.update("absent"); } }
2426
+ const dir = path.join(ctx.tmpRoot ?? os.tmpdir(), "rightkit-freshness-cache");
2427
+ cachePath = path.join(dir, `${h.digest("hex").slice(0, 32)}-${new Date().toISOString().slice(0, 13)}.json`);
2428
+ const hit = JSON.parse(fs.readFileSync(cachePath, "utf8"));
2429
+ if (typeof hit?.advice === "string") return { advice: hit.advice };
2430
+ } catch { /* no cached answer: measure */ }
2431
+ const remember = (result) => {
2432
+ // A measurement that timed out is cached too: it is the 120 s case (41 of 81 crate runs on 2026-11-04), and asking again for every unit of the same
2433
+ // lock set within the hour is the cost this cache removes. The advice text says "not measured", so nobody reads it as a pass.
2434
+ if (cachePath && typeof result?.advice === "string") {
2435
+ try { fs.mkdirSync(path.dirname(cachePath), { recursive: true }); fs.writeFileSync(cachePath, JSON.stringify({ advice: result.advice })); } catch { /* the cache is an optimisation only */ }
2436
+ }
2437
+ return result;
2438
+ };
2419
2439
  let r;
2420
2440
  try { r = await ctx.deps.spawn(process.execPath, [bin, "check", "--json", "--repo", ctx.contentRoot], { cwd: ctx.contentRoot, encoding: "utf8", env: { ...ctx.deps.env, ...PNPM_NO_HOOKS_ENV }, timeout: 120_000, maxBuffer: 1 << 26 }); }
2421
- catch (e) { return { advice: `dependency freshness not measured: right-update check did not run (${e.message})` }; }
2441
+ catch (e) { return remember({ advice: `dependency freshness not measured: right-update check did not run (${e.message})` }); }
2422
2442
  let report = null;
2423
2443
  try { report = JSON.parse(String(r?.stdout ?? "")); } catch { report = null; }
2424
- if (!report || !Array.isArray(report.entries)) return { advice: `dependency freshness not measured: right-update check printed no report${r?.status ? ` (exit ${r.status})` : ""}` };
2444
+ if (!report || !Array.isArray(report.entries)) return remember({ advice: `dependency freshness not measured: right-update check printed no report${r?.status ? ` (exit ${r.status})` : ""}` });
2425
2445
  const behind = report.entries.filter((e) => e.status === "outdated");
2426
2446
  const unjudged = report.entries.filter((e) => e.status === "unknown" || e.error).length;
2427
2447
  const named = behind.slice(0, 5).map((e) => `${e.name} ${e.pinned ?? "?"} -> ${e.latest ?? "?"}`).join(", ");
2428
- return { advice: `${behind.length} behind latest${named ? ` (${named}${behind.length > 5 ? ", ..." : ""})` : ""}${unjudged ? `; ${unjudged} not judged` : ""}` };
2448
+ return remember({ advice: `${behind.length} behind latest${named ? ` (${named}${behind.length > 5 ? ", ..." : ""})` : ""}${unjudged ? `; ${unjudged} not judged` : ""}` });
2429
2449
  },
2430
2450
  // The Swift type-check (rightkit#1289): Mac host only, Class A, before any compile stage. SwiftPM compiles each target with `-Xswiftc -typecheck`: swiftc type-checks every
2431
2451
  // source against the real SDK and the target's dependencies and writes no object file, so a labelled-argument order error fails here in seconds instead of at the
package/managed-cargo.mjs CHANGED
@@ -272,8 +272,14 @@ export function brokerClientRoute({ env = process.env, platform = process.platfo
272
272
  return { client, env: socket ? { ...env, RUSTRIGHT_BUILD_BROKER_SOCKET: socket } : env, mapUnavailable: platform === 'darwin' };
273
273
  }
274
274
 
275
+ /** Cargo commands that compile nothing: Class A, run direct with the pinned toolchain and never carried by the broker (GC-A11, BROKER-CONTRACT interface item 14). */
276
+ const NON_COMPILING_CARGO = new Set(['metadata', 'fetch', 'tree', 'locate-project', 'pkgid', 'verify-project', 'read-manifest']);
277
+
275
278
  export function runCargoSync(args, options = {}, { platform = process.platform, exists = existsSync, spawn = spawnSync, fsOps } = {}) {
276
279
  const env = options.env ?? process.env;
280
+ // The broker refuses every carried request that compiles nothing (RK_CHECK_ERROR), so right-release's `cargo metadata` of the compile and
281
+ // package stages runs here, directly, exactly as the gate runs its Class A cargo calls.
282
+ if (NON_COMPILING_CARGO.has(args[0])) return spawn("cargo", args, { ...options, env: directCargoEnv(env, platform, exists) });
277
283
  const seam = carriedSeam(args, options, { platform, spawn });
278
284
  if (seam) return seam;
279
285
  // A gate run outside the broker by Adrian's recorded exception: the real toolchain, shims off PATH, on every platform (NO_BROKER_ENV).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rightkit/release",
3
- "version": "0.6.42",
3
+ "version": "0.6.44",
4
4
  "description": "Portable release CLI/SDK with fail-closed public GitHub Releases and private R2 + RightApps distribution.",
5
5
  "license": "MIT OR Apache-2.0",
6
6
  "type": "module",
@@ -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.42",
53
+ "@rightkit/release": "0.6.44",
54
54
  "@rightkit/settings-ui": "0.7.1",
55
55
  "@rightkit/social-ui": "0.1.0",
56
56
  "@rightkit/system-ui": "0.1.0",
@@ -529,7 +529,7 @@
529
529
  "rightkit-app-host": "0.1.0",
530
530
  "rightkit-app-lock": "0.1.0",
531
531
  "rightkit-app-manager": "0.1.2",
532
- "rightkit-app-settings": "0.3.3",
532
+ "rightkit-app-settings": "0.3.4",
533
533
  "rightkit-app-update": "0.1.0",
534
534
  "rightkit-apple-ops": "0.1.2",
535
535
  "rightkit-approvals": "0.1.0",
@@ -569,7 +569,7 @@
569
569
  "rightkit-contracts": "0.1.10",
570
570
  "rightkit-contrast": "0.1.0",
571
571
  "rightkit-crash": "0.3.8",
572
- "rightkit-credentials": "0.4.6",
572
+ "rightkit-credentials": "0.5.0",
573
573
  "rightkit-crypto": "0.1.2",
574
574
  "rightkit-daemon": "0.5.3",
575
575
  "rightkit-db": "0.5.5",
@@ -605,7 +605,7 @@
605
605
  "rightkit-evidence-governance": "0.1.1",
606
606
  "rightkit-evidence-report": "0.1.1",
607
607
  "rightkit-feed": "0.1.0",
608
- "rightkit-ffmpeg": "0.2.16",
608
+ "rightkit-ffmpeg": "0.3.0",
609
609
  "rightkit-file-watch": "0.4.4",
610
610
  "rightkit-fs": "0.4.12",
611
611
  "rightkit-fsindex": "0.6.2",
@@ -659,7 +659,7 @@
659
659
  "rightkit-privileged-helper": "0.1.1",
660
660
  "rightkit-prompt-recipes": "0.1.0",
661
661
  "rightkit-pty": "0.1.0",
662
- "rightkit-qa": "0.10.3",
662
+ "rightkit-qa": "0.10.4",
663
663
  "rightkit-qa-driver": "0.7.1",
664
664
  "rightkit-record": "0.4.0",
665
665
  "rightkit-reframe": "0.1.1",
@@ -88,7 +88,7 @@ export function commitOf(checkout, rev, spawn = defaultSpawn) { // eslint-disabl
88
88
  export function verifySnapshotDir({ checkout, dir, commit, tree, when, ledger, admitNew }) {
89
89
  const ledgerMode = ledger !== undefined || admitNew === true;
90
90
  let inspected;
91
- try { inspected = snapshotProblem({ dir, entries: treeEntries(checkout, commit), checkout, ledger, admitNew }); }
91
+ try { inspected = snapshotProblem({ dir, entries: treeEntries(checkout, commit), checkout, commit, ledger, admitNew }); }
92
92
  catch (e) { throw new CheckError(`cannot list snapshot ${dir} ${when}: ${e.message}`); }
93
93
  const extra = ledgerMode ? inspected.problem : inspected;
94
94
  if (extra) throw new CheckError(`snapshot ${dir} is not exactly commit ${commit}${ledgerMode ? " plus its stage-output ledger" : ""} ${when}: ${extra}`);
@@ -0,0 +1,48 @@
1
+ // The source-identity file of a gate snapshot (docs/GATE-CONTRACT.md GC-A23; rightkit#1504, rustright#176).
2
+ //
3
+ // A gate snapshot has no `.git`, so a build script that wants the commit it is built from (Pulse's membrane-runtime and this repository's
4
+ // rightkit-context-runtime read it) finds nothing and reports "unknown". The gate therefore writes `.rightkit-source-identity.json`
5
+ // into the snapshot root for the commit it syncs:
6
+ // { "schema": "rightkit.source-identity.v1", "commit": "<40 hex>", "trees": { "": "<root tree id>", "<dir>": "<tree id>", ... } }
7
+ // with one `trees` entry for the root and one for every directory of the commit that holds a Cargo.toml, Package.swift or
8
+ // package.json, each the git tree id `git rev-parse <commit>:<dir>` prints, read from the checkout's object database through the sealed
9
+ // runner. The bytes are a pure function of the commit (keys sorted, fixed spacing, one trailing newline), so every sync of one commit
10
+ // writes the same file and a verify can recompute it.
11
+ //
12
+ // It is a generated file, never a commit byte: snapshot.mjs admits it as its fourth named allowance (beside the pnpm dependency
13
+ // directories and the config-only `.git/config`) only when ALL hold: it sits at the snapshot root; the commit does not track a file
14
+ // of that name; it is a regular file with one hard link; its bytes equal sourceIdentityBytes() for the snapshot's commit; and the
15
+ // commit's own ignore rules ignore it (so the seeded tree id, which the broker computes the same way, still equals `<sha>^{tree}`).
16
+ // Any other byte, a link, a second name or a missing ignore rule is an extra path and fails the snapshot as before.
17
+ import { sealedRun } from "./snapshot-git.mjs";
18
+
19
+ export const SOURCE_IDENTITY_FILE = ".rightkit-source-identity.json";
20
+ export const SOURCE_IDENTITY_SCHEMA = "rightkit.source-identity.v1";
21
+ const MARKERS = new Set(["Cargo.toml", "Package.swift", "package.json"]);
22
+ const CHUNK = 200;
23
+
24
+ /** The directories of the commit (posix, "" for the root) that hold a Cargo.toml, Package.swift or package.json, sorted. */
25
+ export function identityDirectories(entries) {
26
+ const dirs = new Set([""]);
27
+ for (const e of entries) {
28
+ const i = e.path.lastIndexOf("/");
29
+ if (MARKERS.has(i < 0 ? e.path : e.path.slice(i + 1))) dirs.add(i < 0 ? "" : e.path.slice(0, i));
30
+ }
31
+ return [...dirs].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
32
+ }
33
+
34
+ /** The exact bytes (a Buffer) of the identity file for `commit`: `entries` are the commit's `treeEntries`, `run` is injectable (tests). */
35
+ export function sourceIdentityBytes({ checkout, commit, entries, run = sealedRun }) {
36
+ if (!/^[0-9a-f]{40}$/.test(String(commit))) throw new Error(`the source identity needs a 40-hex SHA-1 commit id, not ${JSON.stringify(commit)}`);
37
+ const dirs = identityDirectories(entries);
38
+ const trees = {};
39
+ for (let i = 0; i < dirs.length; i += CHUNK) {
40
+ const chunk = dirs.slice(i, i + CHUNK);
41
+ const r = run(checkout, ["rev-parse", ...chunk.map((d) => (d === "" ? `${commit}^{tree}` : `${commit}:${d}`))]);
42
+ if (r.error || r.status !== 0) throw new Error(`git rev-parse of the commit's trees failed: ${r.error ? r.error.message : String(r.stderr ?? "").trim() || `exit ${r.status}`}`);
43
+ const ids = String(r.stdout ?? "").split("\n").filter(Boolean);
44
+ if (ids.length !== chunk.length || !ids.every((id) => /^[0-9a-f]{40}$/.test(id))) throw new Error(`git rev-parse answered ${ids.length} tree ids for ${chunk.length} directories`);
45
+ chunk.forEach((d, k) => { trees[d] = ids[k]; });
46
+ }
47
+ return Buffer.from(`${JSON.stringify({ schema: SOURCE_IDENTITY_SCHEMA, commit, trees }, null, 2)}\n`, "utf8");
48
+ }
package/snapshot.mjs CHANGED
@@ -39,6 +39,7 @@ import { readDiskPolicy, scratchRoots } from "./disk-policy.mjs";
39
39
  import { resolveManagedRoots } from "./managed-roots.mjs";
40
40
  import { HostConfigError, hostConfigFile, readSnapshotRootConfig } from "./snapshot-root-config.mjs";
41
41
  import { discoveryGit, discoveryRun, sealedRepoInfo, sealedRun, withSealedGit } from "./snapshot-git.mjs";
42
+ import { SOURCE_IDENTITY_FILE, sourceIdentityBytes } from "./snapshot-identity.mjs";
42
43
  import { acquireBuildOwnership, migrateBirthlessRoot, OwnershipBusy, ownershipFile, recordRootBirth } from "./build-ownership.mjs";
43
44
  // The error class and the managed-root guard live in managed-root-guard.mjs, which build-ownership.mjs imports too (decision D4 rule 1).
44
45
  import { SnapshotError, requireManagedRoot } from "./managed-root-guard.mjs";
@@ -257,7 +258,7 @@ export function snapshotTree({ checkout, dir, baseTree, repo = repositoryOf(chec
257
258
  * input even though the seeded tree id cannot see it. Never follows a link (only real directories are entered); names compare
258
259
  * case-insensitively where the host filesystem does (Mac, Windows; colliding names were refused before this runs).
259
260
  */
260
- function pruneToTree(dir, entries, platform = process.platform) {
261
+ function pruneToTree(dir, entries, platform = process.platform, keepRoot = new Set()) {
261
262
  const fold = platform === "darwin" || platform === "win32" ? (n) => n.toLowerCase() : (n) => n;
262
263
  const files = new Set(entries.map((e) => fold(e.path)));
263
264
  const dirs = new Set();
@@ -268,7 +269,7 @@ function pruneToTree(dir, entries, platform = process.platform) {
268
269
  const r = rel ? `${rel}/${e.name}` : e.name;
269
270
  const p = path.join(d, e.name);
270
271
  if (e.isDirectory()) { if (dirs.has(fold(r))) walk(p, r); else { fs.rmSync(p, { recursive: true, force: true }); removed++; } }
271
- else if (!files.has(fold(r))) { fs.unlinkSync(p); removed++; }
272
+ else if (!files.has(fold(r)) && !(rel === "" && keepRoot.has(fold(r)))) { fs.unlinkSync(p); removed++; }
272
273
  }
273
274
  };
274
275
  walk(dir, "");
@@ -324,6 +325,11 @@ function refuseCaseCollisions(entries, commit, platform = process.platform) {
324
325
  * byte-equal to what the gate writes for THIS checkout's origin (gateGitConfigBody over `git config --get remote.origin.url`).
325
326
  * Any other URL (`ext::sh -c id` was the r2#5 probe), any other section, any other byte is an extra. A checkout with no origin
326
327
  * gets no `.git` at all.
328
+ * 3. the generated source-identity file `.rightkit-source-identity.json` at the snapshot root (snapshot-identity.mjs, GATE-CONTRACT
329
+ * GC-A23; rightkit#1504): admitted only when the caller names the snapshot's `commit`, the commit tracks no file of that name, it
330
+ * is a regular, non-executable file with one hard link, its bytes equal sourceIdentityBytes() for that commit exactly, and the
331
+ * commit's own ignore rules ignore it (so the seeded tree id, the broker's included, still equals `<sha>^{tree}`). Without
332
+ * `commit`, with other bytes, or unignored, it is an extra like any other file.
327
333
  * Nothing else is an extra the gate may leave, and the dependency bytes of allowance 1 are bound by the environment digest
328
334
  * (`rightkit-gate env-digest --snapshot`, which `verifySnapshot` takes as `environment`), so a changed or planted byte under a
329
335
  * `node_modules` is refused at the end verify even though this walk lets the directory be.
@@ -413,7 +419,7 @@ function sha256File(file) {
413
419
  return h.digest("hex");
414
420
  }
415
421
 
416
- function inspectSnapshot({ dir, entries, checkout, platform = process.platform, originUrl, ledger, admitNew = false }) {
422
+ function inspectSnapshot({ dir, entries, checkout, commit, platform = process.platform, originUrl, ledger, admitNew = false }) {
417
423
  const problem = (message) => ({ problem: message, admitted: [] });
418
424
  const ledgerMode = ledger !== undefined || admitNew === true;
419
425
  const fold = foldFor(platform);
@@ -454,6 +460,22 @@ function inspectSnapshot({ dir, entries, checkout, platform = process.platform,
454
460
  if (!s?.isFile() || fs.readFileSync(config, "utf8") !== gateGitConfigBody(origin)) return `${rel}/config is not in the commit's tree (it is not byte-equal to the gate's config-only file for this checkout's origin)`;
455
461
  return null;
456
462
  };
463
+ // Allowance 3: the generated source-identity file (see the allowances above). Judged here, never as a ledger candidate, so the ledger
464
+ // and the tree id stay exactly what they were.
465
+ const identityName = fold(SOURCE_IDENTITY_FILE);
466
+ const identityProblem = (r, p) => {
467
+ if (!commit) return `${r} is not in the commit's tree (the source-identity file is admitted only when the snapshot's commit is named)`;
468
+ const s = lstat(p);
469
+ if (!s?.isFile()) return `${r} is not in the commit's tree (it is not a regular file)`;
470
+ if (s.nlink > 1n) return `${r} is not in the commit's tree and has ${s.nlink} hard links (the gate's source-identity file has one)`;
471
+ if (platform !== "win32" && (Number(s.mode) & 0o111) !== 0) return `${r} is not in the commit's tree and is executable (the gate writes the source-identity file without an exec bit)`;
472
+ let want;
473
+ try { want = sourceIdentityBytes({ checkout, commit, entries }); }
474
+ catch (e) { return `${r} is not in the commit's tree and the source identity of commit ${commit} cannot be recomputed to judge it: ${e.message}`; }
475
+ if (!fs.readFileSync(p).equals(want)) return `${r} is not in the commit's tree and is not the gate's source identity for commit ${commit} (its bytes differ from the deterministic file)`;
476
+ if (!neutralIgnored(dir, [r]).has(r)) return `${r} is the gate's source identity but the commit's own ignore rules do not ignore it, so it would change the tree id (add /${SOURCE_IDENTITY_FILE} to the commit's .gitignore)`;
477
+ return null;
478
+ };
457
479
  const fileProblem = (r, p, entry) => {
458
480
  const s = lstat(p);
459
481
  if (!s) return `${r} vanished while it was checked`;
@@ -519,7 +541,7 @@ function inspectSnapshot({ dir, entries, checkout, platform = process.platform,
519
541
  else if (dirs.has(key)) found = walk(p, r, false);
520
542
  else if (key === ".git") found = gitConfigProblem(r, p);
521
543
  else found = ledgerMode ? candidateDir(p, r) : `${r} is not in the commit's tree (a directory the commit does not have)`;
522
- } else if (!inDeps) found = !byKey.has(key) ? (ledgerMode ? candidate(p, r) : `${r} is not in the commit's tree`) : fileProblem(r, p, byKey.get(key));
544
+ } else if (!inDeps) found = !byKey.has(key) ? (rel === "" && key === identityName ? identityProblem(r, p) : ledgerMode ? candidate(p, r) : `${r} is not in the commit's tree`) : fileProblem(r, p, byKey.get(key));
523
545
  if (found) return found;
524
546
  }
525
547
  return null;
@@ -889,17 +911,55 @@ export function syncSnapshot({ checkout, rev = "HEAD", root = snapshotRoot(), ma
889
911
  try { fs.rmdirSync(stagingRoot); } catch { /* another sync's staging, or not empty */ }
890
912
  }
891
913
 
892
- // 4. Everything the commit does not hold is removed: the snapshot is exactly the commit (§1).
914
+ // 4. Everything the commit does not hold is removed: the snapshot is exactly the commit (§1). The one exception is the gate's own
915
+ // source-identity file when it already holds this commit's exact bytes (kept, so its mtime and Cargo's fingerprints stay warm).
893
916
  assertLockHeld();
894
- removed += pruneToTree(dir, entries);
917
+ let identityBytes = null;
918
+ const identity = { file: SOURCE_IDENTITY_FILE, written: false, kept: false, reason: null };
919
+ if (repo.objectFormat !== "sha1") identity.reason = `the repository's object format is ${repo.objectFormat}, and the source identity records SHA-1 ids`;
920
+ else if (wanted.has(SOURCE_IDENTITY_FILE)) identity.reason = `the commit itself tracks ${SOURCE_IDENTITY_FILE}`;
921
+ else {
922
+ try { identityBytes = sourceIdentityBytes({ checkout: repo.checkout, commit, entries }); }
923
+ catch (e) { throw new SnapshotError("error", `the source identity of commit ${commit} cannot be computed: ${e.message}`); }
924
+ }
925
+ const identityPath = path.join(dir, SOURCE_IDENTITY_FILE);
926
+ const keepIdentity = (() => {
927
+ if (!identityBytes) return false;
928
+ const s = lstat(identityPath);
929
+ return !!s?.isFile() && s.nlink === 1n && (process.platform === "win32" || (Number(s.mode) & 0o111) === 0) && fs.readFileSync(identityPath).equals(identityBytes);
930
+ })();
931
+ removed += pruneToTree(dir, entries, process.platform, keepIdentity ? new Set([foldFor(process.platform)(SOURCE_IDENTITY_FILE)]) : new Set());
932
+ if (identityBytes) {
933
+ // 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
+ // 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.
935
+ if (!neutralIgnored(dir, [SOURCE_IDENTITY_FILE]).has(SOURCE_IDENTITY_FILE)) {
936
+ identity.reason = `the commit's own ignore rules do not ignore /${SOURCE_IDENTITY_FILE}; add it to the commit's .gitignore and no source identity is written to this snapshot until then`;
937
+ if (keepIdentity) fs.unlinkSync(identityPath); // a copy kept from an earlier sync would now be an unignored extra
938
+ } else if (keepIdentity) identity.kept = true;
939
+ else {
940
+ assertLockHeld();
941
+ const stagingRoot2 = `${dir}.staging`;
942
+ const tmp = path.join(stagingRoot2, `identity-${crypto.randomUUID()}`);
943
+ fs.mkdirSync(stagingRoot2, { recursive: true, mode: 0o700 });
944
+ try {
945
+ fs.writeFileSync(tmp, identityBytes, { mode: 0o644, flag: "wx" });
946
+ if (process.platform !== "win32") fs.chmodSync(tmp, 0o644);
947
+ fs.renameSync(tmp, identityPath);
948
+ identity.written = true;
949
+ } finally {
950
+ fs.rmSync(tmp, { force: true });
951
+ try { fs.rmdirSync(stagingRoot2); } catch { /* another sync's staging, or not empty */ }
952
+ }
953
+ }
954
+ }
895
955
 
896
956
  assertLockHeld();
897
- const extra = snapshotProblem({ dir, entries, checkout: repo.checkout });
957
+ const extra = snapshotProblem({ dir, entries, checkout: repo.checkout, commit });
898
958
  if (extra) throw new SnapshotError("mismatch", `snapshot ${dir} is not exactly commit ${commit} after sync: ${extra}`);
899
959
  const actual = snapshotTree({ checkout: repo.checkout, dir, baseTree: tree, repo });
900
960
  if (actual !== tree) throw new SnapshotError("mismatch", `snapshot ${dir} is tree ${actual} after sync, not tree ${tree} of commit ${commit}`);
901
961
  writeState(stateFile, { schema: STATE_SCHEMA, repo: repo.checkout, repoKey: repo.key, commit, tree, paths: [...wanted.keys()], stat: nextStat, syncedAt: new Date(now()).toISOString() });
902
- return { schema: SNAPSHOT_SCHEMA, path: dir, repoKey: repo.key, commit, tree, written, removed, modesFixed, unchanged, linksRemoved, hardLinksReplaced, casesFixed, ms: now() - started };
962
+ return { schema: SNAPSHOT_SCHEMA, path: dir, repoKey: repo.key, commit, tree, written, removed, modesFixed, unchanged, linksRemoved, hardLinksReplaced, casesFixed, identity, ms: now() - started };
903
963
  } finally {
904
964
  release();
905
965
  }
@@ -930,7 +990,7 @@ export function verifySnapshot({ checkout, rev = "HEAD", root = snapshotRoot(),
930
990
  if (path.resolve(path.dirname(at)) === path.resolve(root)) requirePrivateRoot(root, lstat(root));
931
991
  if (!lstat(at)?.isDirectory()) throw new SnapshotError("mismatch", `no snapshot directory at ${at}`);
932
992
  // The seeded tree id cannot see an ignored file or follow a link, so the directory itself is walked first (E6, §1 exact snapshot).
933
- const inspected = snapshotProblem({ dir: at, entries: treeEntries(repo.checkout, commit), checkout: repo.checkout, ledger, admitNew });
993
+ const inspected = snapshotProblem({ dir: at, entries: treeEntries(repo.checkout, commit), checkout: repo.checkout, commit, ledger, admitNew });
934
994
  const extra = ledger !== undefined || admitNew ? inspected.problem : inspected;
935
995
  if (extra) throw new SnapshotError("mismatch", `the snapshot at ${at} is not exactly commit ${commit}${ledger !== undefined || admitNew ? " plus its stage-output ledger" : ""}: ${extra}`);
936
996
  const actual = snapshotTree({ checkout: repo.checkout, dir: at, baseTree: tree, repo });
package/stage-ledger.mjs CHANGED
@@ -15,6 +15,7 @@ import fs from "node:fs";
15
15
  import os from "node:os";
16
16
  import path from "node:path";
17
17
  import { spawnSync } from "./background-process.mjs";
18
+ import { SOURCE_IDENTITY_FILE } from "./snapshot-identity.mjs";
18
19
 
19
20
  export const LEDGER_RESERVED_SEGMENTS = Object.freeze(["target", ".right-release", ".git", "node_modules"]);
20
21
  export const NULL_DEVICE = process.platform === "win32" ? "NUL" : "/dev/null";
@@ -99,6 +100,10 @@ export function walkSnapshot({ dir, tracked, dependencyRoots = new Set(), run =
99
100
  const bad = reserved(r);
100
101
  if (bad) { problems.push(`${r} is under the reserved path segment ${JSON.stringify(bad)} (a stage output is never written there)`); continue; }
101
102
  if (st.nlink > 1) { problems.push(`${r} has ${st.nlink} hard links (a stage output has exactly one)`); continue; }
103
+ // The gate's own generated source-identity file (snapshot-identity.mjs, GC-A23) is neither a stage output nor a ledger entry. Its bytes,
104
+ // type, mode, link count and ignore status are judged against the commit by snapshot.mjs (inspectSnapshot), which every stage-open
105
+ // and stage-close verify runs right after this walk; this walk only keeps it out of the ledger.
106
+ if (rel === "" && key === f(SOURCE_IDENTITY_FILE)) continue;
102
107
  candidates.push({ rel: r, abs: p, size: st.size, execBit: platform !== "win32" && (st.mode & 0o111) !== 0 });
103
108
  }
104
109
  return any;