@rightkit/release 0.6.45 → 0.6.46

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.
@@ -615,6 +615,20 @@ export function processProbe({ platform = process.platform, spawn = spawnSync, s
615
615
  for (const p of members) if (!Number.isFinite(p.startedMs)) throw new Error(`cannot read the start time of pid ${p.pid}`);
616
616
  return { members, byPid: new Map(rows.map((row) => [row.pid, row])), own };
617
617
  },
618
+ /** One fresh process table for every recorded group in this release; never retained across releases. */
619
+ groupSnapshots(groups) {
620
+ for (const group of groups) if (!Number.isInteger(group) || group <= 1) throw new Error(`no usable process group (${group})`);
621
+ const { rows, own } = psList();
622
+ const byPid = new Map(rows.map((row) => [row.pid, row]));
623
+ const snapshots = new Map([...new Set(groups)].map((group) => [group, { members: [], byPid, own }]));
624
+ for (const p of rows) {
625
+ const snapshot = snapshots.get(p.group);
626
+ if (!snapshot || own.has(p.pid)) continue;
627
+ if (!Number.isFinite(p.startedMs)) throw new Error(`cannot read the start time of pid ${p.pid}`);
628
+ snapshot.members.push(p);
629
+ }
630
+ return snapshots;
631
+ },
618
632
  /**
619
633
  * Pids of processes whose environment carries `<OWNERSHIP_ENV>=<handle>` (this gate's own chain left out). Linux reads
620
634
  * /proc/<pid>/environ (an unreadable entry of this user's throws: unknown); macOS reads `ps eww`, which shows the environment
@@ -648,7 +662,7 @@ export function processProbe({ platform = process.platform, spawn = spawnSync, s
648
662
  * with this gate's anchor. `{ owner, anchorMs, recorded }` as there. Returns `[{ pid, why }]` (held), or throws: a listing
649
663
  * that did not finish cleanly is unknown, and the caller stays busy.
650
664
  */
651
- hiddenHolders({ owner, anchorMs, recorded = [] } = {}) {
665
+ hiddenHolders({ owner, anchorMs, recorded = [], timing = null } = {}) {
652
666
  if (platform !== "darwin") return null;
653
667
  // Without this process's own user id nothing could be told from another user's (which is skipped): unknown, never "none".
654
668
  if (!Number.isInteger(uid)) throw new Error("this process's user id is unknown");
@@ -680,7 +694,10 @@ export function processProbe({ platform = process.platform, spawn = spawnSync, s
680
694
  // `launchctl blame <pid>` (LC_ALL=C, 5 s): exit 0 and a reason is a launchd job; exit 3 and the "not managed" line is a process
681
695
  // launchd does not manage (a reparented orphan) or one that is gone; anything else is unknown (rc null: it could not run).
682
696
  const blame = (pid) => {
683
- const r = spawn("launchctl", ["blame", String(pid)], { encoding: "utf8", env: { ...process.env, LC_ALL: "C", LANG: "C" }, timeout: 5000, maxBuffer: 1 << 16 });
697
+ const started = performance.now();
698
+ let r;
699
+ try { r = spawn("launchctl", ["blame", String(pid)], { encoding: "utf8", env: { ...process.env, LC_ALL: "C", LANG: "C" }, timeout: 5000, maxBuffer: 1 << 16 }); }
700
+ finally { if (timing) { timing.blameCount = (timing.blameCount ?? 0) + 1; timing.blameMs = (timing.blameMs ?? 0) + performance.now() - started; } }
684
701
  if (r.error) return { rc: null, line: String(r.error.message ?? r.error) };
685
702
  const text = `${String(r.stdout ?? "")}${String(r.stderr ?? "")}`.split(/\r?\n/).find((l) => l.trim() !== "") ?? "";
686
703
  return { rc: r.status, line: text.trim() };
@@ -1033,7 +1050,8 @@ function coveredMember(m, owner, { byPid, own }) {
1033
1050
  * Whether the work `owner` covers, other than the process `self` (the live gate at release, null at reclaim), is proven gone.
1034
1051
  * Returns the proofs, or throws a reason that is busy.
1035
1052
  */
1036
- function coveredWorkGone(owner, { probe, lease, file, selfPid = null, waitMs = 0 }) {
1053
+ function coveredWorkGone(owner, { probe, lease, file, selfPid = null, waitMs = 0, timing = null }) {
1054
+ const measure = (name, fn) => { const start = performance.now(); try { return fn(); } finally { if (timing) timing[name] = (timing[name] ?? 0) + performance.now() - start; } };
1037
1055
  const proofs = [];
1038
1056
  let rebooted = false;
1039
1057
  // A reboot is only a question for a dead owner; a live gate releasing its own record has not outlived one.
@@ -1073,7 +1091,7 @@ function coveredWorkGone(owner, { probe, lease, file, selfPid = null, waitMs = 0
1073
1091
  }
1074
1092
  } else if (!rebooted && c.kind === "group") {
1075
1093
  let snap;
1076
- try { snap = probe.groupSnapshot(c.group); } catch (e) { throw new Error(`process group ${c.group} cannot be listed (${e.message})`); }
1094
+ try { snap = measure("groupMs", () => probe.groupSnapshot(c.group)); } catch (e) { throw new Error(`process group ${c.group} cannot be listed (${e.message})`); }
1077
1095
  const children = snap.members.filter((m) => m.pid !== selfPid && coveredMember(m, owner, snap)).map((m) => m.pid);
1078
1096
  if (children.length) throw new Error(`process group ${c.group} still has ${children.length} member(s) started under this ownership: ${children.join(", ")}`);
1079
1097
  proofs.push(`process group ${c.group} has no member started under this ownership`);
@@ -1084,23 +1102,49 @@ function coveredWorkGone(owner, { probe, lease, file, selfPid = null, waitMs = 0
1084
1102
  const intents = entries.filter((n) => n.startsWith("intent-"));
1085
1103
  if (intents.length) throw new Error(`a detached spawn was in flight when its gate stopped (${intents[0]}), so its process group is unknown`);
1086
1104
  const groups = entries.filter((n) => /^group-\d+\.json$/.test(n));
1105
+ if (timing) timing.detachedGroups = groups.length;
1087
1106
  const recorded = [];
1107
+ const groupRecords = [];
1088
1108
  for (const name of groups) {
1089
- let entry;
1090
- try { entry = JSON.parse(fs.readFileSync(path.join(registry, name), "utf8")); } catch { throw new Error(`the detached-child entry ${name} cannot be read`); }
1109
+ let entry, bytes, writtenMs;
1110
+ try {
1111
+ const entryFile = path.join(registry, name);
1112
+ bytes = fs.readFileSync(entryFile, "utf8");
1113
+ entry = JSON.parse(bytes);
1114
+ writtenMs = fs.statSync(entryFile).mtimeMs;
1115
+ } catch { throw new Error(`the detached-child entry ${name} cannot be read`); }
1091
1116
  if (!Number.isInteger(entry?.group) || !Number.isFinite(entry?.startedMs)) throw new Error(`the detached-child entry ${name} cannot be read`);
1092
1117
  recorded.push({ group: entry.group, command: entry.command });
1118
+ groupRecords.push({ name, entry, bytes, writtenMs });
1119
+ }
1120
+ let snapshots = null;
1121
+ if (groups.length && typeof probe.groupSnapshots === "function") {
1122
+ try { snapshots = measure("detachedGroupsMs", () => probe.groupSnapshots(groupRecords.map(({ entry }) => entry.group))); }
1123
+ catch (e) { throw new Error(`detached process groups cannot be listed (${e.message})`); }
1124
+ if (!(snapshots instanceof Map)) throw new Error("detached process groups cannot be listed (invalid bulk process table)");
1125
+ }
1126
+ for (const { entry, writtenMs } of groupRecords) {
1093
1127
  let snapshot;
1094
- try { snapshot = probe.groupSnapshot(entry.group); } catch (e) { throw new Error(`detached process group ${entry.group} cannot be listed (${e.message})`); }
1095
- // The entry is written after the spawn returns, so the group's own leader (pid == group) started before the file's mtime. A
1096
- // leader that started later is a new process that took the id: the kernel reuses a group id only once that group is empty.
1097
- let writtenMs = NaN;
1098
- try { writtenMs = fs.statSync(path.join(registry, name)).mtimeMs; } catch { /* unknown: judged as before */ }
1128
+ try { snapshot = snapshots ? snapshots.get(entry.group) : measure("detachedGroupsMs", () => probe.groupSnapshot(entry.group)); }
1129
+ catch (e) { throw new Error(`detached process group ${entry.group} cannot be listed (${e.message})`); }
1130
+ if (!snapshot || !Array.isArray(snapshot.members)) throw new Error(`detached process group ${entry.group} cannot be listed (missing process table)`);
1131
+ // A later leader is a reused group ID; otherwise any member at or after the recorded lower bound holds the release.
1099
1132
  const leader = snapshot.members.find((m) => m.pid === entry.group);
1100
1133
  if (leader && Number.isFinite(writtenMs) && leader.startedMs > writtenMs + START_SLACK_MS) continue;
1101
1134
  const live = snapshot.members.filter((m) => m.pid !== selfPid && m.startedMs >= entry.startedMs - START_SLACK_MS).map((m) => m.pid);
1102
1135
  if (live.length) throw new Error(`detached process group ${entry.group} (${entry.command}) still has ${live.length} member(s): ${live.join(", ")}`);
1103
1136
  }
1137
+ // Catch changes during this sample. As with the old per-group checks, this is not an atomic spawn/release fence.
1138
+ let after;
1139
+ try { after = fs.readdirSync(registry); } catch (e) { if (e.code === "ENOENT" && !groups.length) after = []; else throw new Error(`the detached-child record ${registry} cannot be re-read (${e.message})`); }
1140
+ const relevant = (names) => names.filter((n) => n.startsWith("intent-") || /^group-\d+\.json$/.test(n)).sort();
1141
+ if (JSON.stringify(relevant(entries)) !== JSON.stringify(relevant(after))) throw new Error("the detached-child registry changed during the process sample");
1142
+ for (const { name, bytes, writtenMs } of groupRecords) {
1143
+ try {
1144
+ const entryFile = path.join(registry, name);
1145
+ if (fs.readFileSync(entryFile, "utf8") !== bytes || fs.statSync(entryFile).mtimeMs !== writtenMs) throw new Error("changed");
1146
+ } catch { throw new Error(`the detached-child entry ${name} changed during the process sample`); }
1147
+ }
1104
1148
  if (groups.length) proofs.push(`the ${groups.length} detached process group(s) it started are empty`);
1105
1149
  // See `unreadable` in processProbe. The baseline is the later of (1) the acquisition of the last owner whose release proved zero
1106
1150
  // readers and (2) the snapshot root's birth in this boot, capped at this ownership's own acquisition (a process the gate
@@ -1115,7 +1159,7 @@ function coveredWorkGone(owner, { probe, lease, file, selfPid = null, waitMs = 0
1115
1159
  // on a free host after a release that proved zero readers, or by a reclaim that proved the previous work gone). Never "no anchor".
1116
1160
  const skipBefore = baselines.length ? Math.max(...baselines) : Date.parse(owner.acquiredAt);
1117
1161
  let carriers;
1118
- try { carriers = probe.tokenHolders(owner.handle, skipBefore); } catch (e) { throw new Error(`processes carrying ${OWNERSHIP_ENV} cannot be listed (${e.message})`); }
1162
+ try { carriers = measure("tokenHoldersMs", () => probe.tokenHolders(owner.handle, skipBefore)); } catch (e) { throw new Error(`processes carrying ${OWNERSHIP_ENV} cannot be listed (${e.message})`); }
1119
1163
  if (carriers) {
1120
1164
  const others = carriers.filter((pid) => pid !== selfPid);
1121
1165
  if (others.length) throw new Error(`process(es) ${others.join(", ")} still carry ${OWNERSHIP_ENV}=${owner.handle}`);
@@ -1123,7 +1167,7 @@ function coveredWorkGone(owner, { probe, lease, file, selfPid = null, waitMs = 0
1123
1167
  }
1124
1168
  if (owner.snapshot) {
1125
1169
  let users;
1126
- try { users = probe.snapshotUsers(owner.snapshot, skipBefore); } catch (e) { throw new Error(`processes using the snapshot cannot be listed (${e.message})`); }
1170
+ try { users = measure("snapshotUsersMs", () => probe.snapshotUsers(owner.snapshot, skipBefore)); } catch (e) { throw new Error(`processes using the snapshot cannot be listed (${e.message})`); }
1127
1171
  if (users) {
1128
1172
  const others = users.filter((u) => u.pid !== selfPid);
1129
1173
  if (others.length) throw new Error(`process(es) ${others.map((u) => `${u.pid} (${u.how})`).join(", ")} still use the snapshot ${owner.snapshot}`);
@@ -1136,7 +1180,7 @@ function coveredWorkGone(owner, { probe, lease, file, selfPid = null, waitMs = 0
1136
1180
  // ownership token, an actual snapshot user, and the broker lease hold a release.
1137
1181
  if (typeof probe.hiddenHolders === "function") {
1138
1182
  let hidden;
1139
- try { hidden = probe.hiddenHolders({ owner, anchorMs: skipBefore, recorded }); } catch { hidden = null; }
1183
+ try { hidden = measure("hiddenHoldersMs", () => probe.hiddenHolders({ owner, anchorMs: skipBefore, recorded, timing })); } catch { hidden = null; }
1140
1184
  const others = (hidden ?? []).filter((h) => h.pid !== selfPid);
1141
1185
  if (others.length) {
1142
1186
  const shown = others.slice(0, 8);
@@ -1158,7 +1202,7 @@ function coveredWorkGone(owner, { probe, lease, file, selfPid = null, waitMs = 0
1158
1202
  const waitOptions = waitMs > 0 ? { waitMs } : {};
1159
1203
  const settled = (sub) => unsent[sub] && typeof unsent[sub].reason === "string";
1160
1204
  const everyUnsent = handles.length > 0 && handles.every(settled);
1161
- const status = lease({ snapshot: owner.snapshot, handle: owner.handle, ...waitOptions });
1205
+ const status = measure("leaseMs", () => lease({ snapshot: owner.snapshot, handle: owner.handle, ...waitOptions }));
1162
1206
  if (status.state === "ACTIVE" || (status.state !== "REAPED" && !everyUnsent)) throw new Error(`broker work may exist under this handle and its lease is ${status.state} (${status.why})`);
1163
1207
  if (status.state === "REAPED") proofs.push(`broker lease for ${owner.handle} is REAPED`);
1164
1208
  // GB-23: the answer's own member rows account for each recorded sub-handle too: a recorded one that the broker lists and does not list REAPED keeps ownership, whatever the aggregate said.
@@ -1166,7 +1210,7 @@ function coveredWorkGone(owner, { probe, lease, file, selfPid = null, waitMs = 0
1166
1210
  let neverStarted = 0;
1167
1211
  for (const sub of handles) {
1168
1212
  if (typeof sub !== "string" || !sub.startsWith(`${owner.handle}#`) || sub.length <= owner.handle.length + 1) throw new Error(`the record lists ${JSON.stringify(sub)}, which is not a sub-handle of ${owner.handle}`);
1169
- const one = lease({ snapshot: owner.snapshot, handle: sub, ...waitOptions });
1213
+ const one = measure("leaseMs", () => lease({ snapshot: owner.snapshot, handle: sub, ...waitOptions }));
1170
1214
  const member = Array.isArray(one.members) ? one.members.find((m) => m.handle === sub) : null;
1171
1215
  if (one.state === "REAPED") {
1172
1216
  if (Array.isArray(one.members) && !(member && member.state === "REAPED")) throw new Error(`the broker answers REAPED for ${sub} but lists no completed submission under that name`);
@@ -1306,18 +1350,31 @@ export function acquireBuildOwnership({
1306
1350
  };
1307
1351
  const body = JSON.stringify(record);
1308
1352
  const release = () => {
1309
- if (!holds(file, handle)) return { released: false, why: "no longer the owner" };
1310
- let proofs;
1311
- // The record as it is now (a broker submit may have been marked since it was written).
1312
- try { proofs = coveredWorkGone(JSON.parse(readText(file)), { probe, lease, file, selfPid: process.pid, waitMs: RELEASE_LEASE_WAIT_MS }); }
1313
- catch (e) { return { released: false, why: `left for the next gate to reclaim: ${e.message}` }; }
1314
- finally { if (exportEnv && process.env[OWNERSHIP_ENV] === handle) { delete process.env[OWNERSHIP_ENV]; delete process.env[OWNERSHIP_FILE_ENV]; } }
1315
- // Only a release that proved zero readers leaves the marker; a held one leaves none (and keeps the record).
1316
- writeCleanMarker(file, record);
1317
- fs.rmSync(file, { force: true });
1318
- fs.rmSync(markLockFile(file), { force: true });
1319
- fs.rmSync(childrenDir(file, handle), { recursive: true, force: true });
1320
- return { released: true, proofs };
1353
+ const timingKey = Symbol.for("rightkit.releaseTiming");
1354
+ const timing = process[timingKey] ?? null;
1355
+ const start = performance.now();
1356
+ if (timing) timing.releaseStartEpochMs = performance.timeOrigin + start;
1357
+ try {
1358
+ if (!holds(file, handle)) return { released: false, why: "no longer the owner" };
1359
+ let proofs;
1360
+ // The record as it is now (a broker submit may have been marked since it was written).
1361
+ try { proofs = coveredWorkGone(JSON.parse(readText(file)), { probe, lease, file, selfPid: process.pid, waitMs: RELEASE_LEASE_WAIT_MS, timing }); }
1362
+ catch (e) { return { released: false, why: `left for the next gate to reclaim: ${e.message}` }; }
1363
+ finally { if (exportEnv && process.env[OWNERSHIP_ENV] === handle) { delete process.env[OWNERSHIP_ENV]; delete process.env[OWNERSHIP_FILE_ENV]; } }
1364
+ // Only a release that proved zero readers leaves the marker; a held one leaves none (and keeps the record).
1365
+ writeCleanMarker(file, record);
1366
+ fs.rmSync(file, { force: true });
1367
+ fs.rmSync(markLockFile(file), { force: true });
1368
+ fs.rmSync(childrenDir(file, handle), { recursive: true, force: true });
1369
+ return { released: true, proofs };
1370
+ } finally {
1371
+ if (timing) {
1372
+ timing.releaseMs = performance.now() - start;
1373
+ timing.releaseEndEpochMs = performance.timeOrigin + performance.now();
1374
+ delete process[timingKey];
1375
+ try { process.stderr.write(`rightkit-release-timing ${JSON.stringify(timing)}\n`); } catch { /* diagnostics must not affect release */ }
1376
+ }
1377
+ }
1321
1378
  };
1322
1379
  const done = (reclaimed) => {
1323
1380
  // Windows: the gate enters its job before it returns, so every child it starts from here on is contained.
@@ -0,0 +1,49 @@
1
+ // Cargo argv width is explicit so broker admission, cache keys and signed receipts see the same request.
2
+ const COMPILE = new Set(["build", "check", "clippy", "doc", "rustdoc", "test", "bench"]);
3
+
4
+ export function parseCargoWidth(value) {
5
+ if (typeof value !== "string" || !/^[1-9][0-9]*$/.test(value)) throw new Error("--cargo-jobs needs a positive decimal integer");
6
+ const width = Number(value);
7
+ if (!Number.isSafeInteger(width) || width > 0xffffffff) throw new Error("--cargo-jobs is out of range");
8
+ return width;
9
+ }
10
+
11
+ export function cargoWidthArgs(argv, width) {
12
+ if (!Array.isArray(argv) || !argv.every((x) => typeof x === "string") || !COMPILE.has(argv[0])) throw new Error("--cargo-jobs cannot control this Cargo command");
13
+ if (!Number.isSafeInteger(width) || width < 1 || width > 0xffffffff) throw new Error("invalid Cargo width");
14
+ const end = argv.indexOf("--");
15
+ if (argv.slice(1, end < 0 ? undefined : end).some((arg) => arg === "--jobs" || arg.startsWith("--jobs=") || arg === "-j" || arg.startsWith("-j"))) throw new Error("--cargo-jobs conflicts with an existing Cargo jobs flag");
16
+ return [argv[0], "--jobs", String(width), ...argv.slice(1)];
17
+ }
18
+
19
+ export function validateCargoWidthPool(width, status) {
20
+ const size = status?.type === "LIST" && status?.broker?.phase === "READY" ? status.broker.tokens?.size : null;
21
+ if (!Number.isSafeInteger(size) || size < 1) throw new Error("broker does not report a ready compile-token pool");
22
+ if (width > size) throw new Error(`--cargo-jobs ${width} exceeds broker token pool ${size}`);
23
+ return size;
24
+ }
25
+
26
+ /** Width is supported only on the shared Cargo unit-list door, never on command or app routes. */
27
+ export function cargoWidthRouteProblem(args) {
28
+ if (!Array.isArray(args) || !args[0]?.startsWith("--") || args.includes("--")) return "--cargo-jobs needs a controlled unit-list compile";
29
+ const at = args.indexOf("--to");
30
+ if (at < 0 || args[at + 1] !== "compile" || !(args.includes("--units-file") || args.includes("--changed")) || ["--route", "--unit", "--all", "--all-units-exception", "--no-broker"].some((flag) => args.includes(flag))) return "--cargo-jobs needs a controlled unit-list compile";
31
+ return null;
32
+ }
33
+
34
+ export function cargoWidthUnitsProblem(selected) {
35
+ if (!Array.isArray(selected) || selected.some((unit) => typeof unit?.selector !== "string" || !/^cargo:rightkit-[a-z0-9-]+$/.test(unit.selector))) return "--cargo-jobs supports Cargo-only unit lists; nested npm, native and custom adapters are uncontrolled";
36
+ return null;
37
+ }
38
+
39
+ export function cargoWidthScanProblem(scan, cargoCommand, width) {
40
+ const prefix = cargoCommand.slice(1);
41
+ if (scan?.tool !== cargoCommand[0] || !Array.isArray(scan.args) || prefix.some((word, i) => scan.args[i] !== word)) return 'uncontrolled Class B command';
42
+ const args = scan.args.slice(prefix.length);
43
+ if (!COMPILE.has(args[0])) return 'uncontrolled Cargo subcommand';
44
+ const end = args.indexOf('--');
45
+ const own = args.slice(1, end < 0 ? undefined : end);
46
+ const flags = own.flatMap((word, i) => word === '--jobs' || word.startsWith('--jobs=') || word === '-j' || word.startsWith('-j') ? [i] : []);
47
+ if (flags.length !== 1 || own[flags[0]] !== '--jobs' || own[flags[0] + 1] !== String(width)) return 'uncontrolled Cargo width';
48
+ return null;
49
+ }
@@ -0,0 +1,57 @@
1
+ // Compile-only CI admission for one named Rust fixture. This is not a publication qualification.
2
+ // Local Class A is enforced by the gate; hosted CI independently repeats Class A.
3
+ import { createHash } from "node:crypto";
4
+ import { canonicalJson } from "./provenance-verify.mjs";
5
+ import { verifyCiCompileReceipts } from "./qualification-verify.mjs";
6
+
7
+ export const CI_SCOPE = "rust:rightkit-decimal";
8
+ const REPOSITORY = "bogusyogi/rightkit";
9
+ const WORKFLOW = ".github/workflows/ci.yml";
10
+ const SCHEMA = "rightkit.ci-compile-proof/1";
11
+ const GIT_ID = /^[a-f0-9]{40}$/;
12
+ const record = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
13
+ const exactKeys = (value, keys) => record(value) && Object.keys(value).length === keys.length && keys.every((key) => Object.hasOwn(value, key));
14
+ const sha256 = (value) => createHash("sha256").update(value).digest("hex");
15
+ const refuse = (message) => { throw new Error(`CI compile admission refused: ${message}`); };
16
+
17
+ export function ciCompileIdentity({ commit, tree, scope = CI_SCOPE }) {
18
+ if (typeof commit !== "string" || !GIT_ID.test(commit) || typeof tree !== "string" || !GIT_ID.test(tree) || scope !== CI_SCOPE) refuse("invalid commit, tree or scope");
19
+ return { repository: REPOSITORY, workflow: WORKFLOW, commit, tree, scope };
20
+ }
21
+
22
+ function canonicalIdentity(identity) {
23
+ if (!exactKeys(identity, ["repository", "workflow", "commit", "tree", "scope"])) refuse("invalid identity fields");
24
+ const expected = ciCompileIdentity(identity);
25
+ if (identity.repository !== expected.repository || identity.workflow !== expected.workflow) refuse("invalid repository or workflow");
26
+ return expected;
27
+ }
28
+
29
+ export function ciCompileScopeDigest(identity) {
30
+ return sha256(canonicalJson(canonicalIdentity(identity)));
31
+ }
32
+
33
+ export function ciCompileStageNonce(identity) {
34
+ return sha256(`rightkit-ci-compile-v1\n${canonicalJson(canonicalIdentity(identity))}`);
35
+ }
36
+
37
+ export function makeCiCompileProof({ commit, tree, receipts }) {
38
+ const identity = ciCompileIdentity({ commit, tree });
39
+ if (!Array.isArray(receipts) || receipts.length === 0 || !receipts.every((receipt) => exactKeys(receipt, ["id", "provenance"]) && typeof receipt.id === "string" && receipt.id.length > 0 && record(receipt.provenance))) refuse("invalid compile receipts");
40
+ return { schema: SCHEMA, ...identity, unit: { kind: "cargo", name: "rightkit-decimal" }, stages: { compile: { receipts } } };
41
+ }
42
+
43
+ export function verifyCiCompileProof(text, { sha, scope, git }) {
44
+ if (typeof sha !== "string" || !GIT_ID.test(sha) || scope !== CI_SCOPE || typeof git !== "function") refuse("invalid expected commit, scope or git reader");
45
+ let proof;
46
+ try { proof = JSON.parse(text); } catch { refuse("proof is not JSON"); }
47
+ let tree;
48
+ try { tree = String(git("rev-parse", `${sha}^{tree}`)).trim(); } catch { refuse("cannot read expected commit tree"); }
49
+ const identity = ciCompileIdentity({ commit: sha, tree, scope });
50
+ if (!exactKeys(proof, ["schema", "repository", "workflow", "commit", "tree", "scope", "unit", "stages"]) || proof.schema !== SCHEMA || Object.keys(identity).some((key) => proof[key] !== identity[key])) refuse("proof identity does not match expected commit, tree and scope");
51
+ if (!exactKeys(proof.unit, ["kind", "name"]) || proof.unit.kind !== "cargo" || proof.unit.name !== "rightkit-decimal") refuse("proof unit does not match scope");
52
+ if (!exactKeys(proof.stages, ["compile"]) || !exactKeys(proof.stages.compile, ["receipts"])) refuse("invalid compile stage");
53
+ const receipts = proof.stages.compile.receipts;
54
+ if (!Array.isArray(receipts) || !receipts.every((receipt) => exactKeys(receipt, ["id", "provenance"]) && typeof receipt.id === "string" && receipt.id.length > 0 && record(receipt.provenance))) refuse("invalid compile receipts");
55
+ const verified = verifyCiCompileReceipts(proof, { sha, git, stageNonce: ciCompileStageNonce(identity) });
56
+ return { commit: identity.commit, tree: identity.tree, scope: identity.scope, scopeSha256: ciCompileScopeDigest(identity), provenance: verified.compile };
57
+ }
@@ -0,0 +1,58 @@
1
+ // Resolve only manifest-explicit Cargo membership from authenticated commit bytes.
2
+ // Unsupported implicit/path-dependency membership fails closed.
3
+ import path from "node:path";
4
+ import { createRequire } from "node:module";
5
+ const parse = (text) => createRequire(import.meta.url)("smol-toml").parse(text);
6
+
7
+ export function committedCargoWorkspace({ unitDir, read }) {
8
+ if (!/^crates\/[A-Za-z0-9_-]+$/.test(unitDir)) throw new Error("unsupported crate path");
9
+ const get = (file) => {
10
+ const value = read(file);
11
+ if (value === null) return null;
12
+ if (value === undefined) throw new Error(`unavailable committed manifest ${file}`);
13
+ return parse(String(value));
14
+ };
15
+ const unit = get(`${unitDir}/Cargo.toml`);
16
+ if (!unit?.package) throw new Error(`missing package manifest ${unitDir}`);
17
+ if (get("crates/Cargo.toml") !== null) throw new Error("nested crates workspace requires explicit resolution");
18
+ const explicit = unit.package.workspace;
19
+ if (explicit !== undefined) {
20
+ if (typeof explicit !== "string") throw new Error("invalid package.workspace");
21
+ const resolved = path.posix.normalize(path.posix.join(unitDir, explicit));
22
+ if (resolved !== "." && resolved !== unitDir) throw new Error("unsupported package.workspace location");
23
+ const owner = resolved === "." ? get("Cargo.toml") : unit;
24
+ if (!owner?.workspace) throw new Error("package.workspace is not a workspace");
25
+ if (resolved === unitDir) return unitDir;
26
+ }
27
+ if (unit.workspace) return unitDir;
28
+ const root = get("Cargo.toml");
29
+ if (!root?.workspace) throw new Error("workspace membership cannot be established");
30
+ const matches = (patterns) => {
31
+ if (patterns === undefined) return false;
32
+ if (!Array.isArray(patterns) || patterns.some((p) => typeof p !== "string")) throw new Error("invalid workspace members or exclude");
33
+ return patterns.some((p) => {
34
+ if (!/^[A-Za-z0-9_.*\/-]+$/.test(p) || p.includes("**") || p.split("/").includes("..")) throw new Error("unsupported workspace glob");
35
+ const regex = new RegExp(`^${p.split("*").map((s) => s.replace(/[.]/g, "\\.")).join("[^/]*")}/?$`);
36
+ return regex.test(unitDir);
37
+ });
38
+ };
39
+ if (matches(root.workspace.exclude)) throw new Error("excluded crate has no explicit workspace");
40
+ if (!matches(root.workspace.members)) throw new Error("implicit workspace membership cannot be established");
41
+ return ".";
42
+ }
43
+
44
+ const sourceReads = new WeakMap();
45
+ // Candidate source reader authenticates blobs and signals absence with this precise error.
46
+ export function candidateWorkspace(source, unitDir) {
47
+ if (typeof source?.readData !== "function") throw new Error("authenticated source reader missing");
48
+ let cache = sourceReads.get(source);
49
+ if (!cache) { cache = new Map(); sourceReads.set(source, cache); }
50
+ return committedCargoWorkspace({ unitDir, read: (name) => {
51
+ if (cache.has(name)) return cache.get(name);
52
+ let value;
53
+ try { value = source.readData(name).toString("utf8"); }
54
+ catch (error) { if (error.message === `candidate missing ${name}`) value = null; else throw error; }
55
+ cache.set(name, value);
56
+ return value;
57
+ } });
58
+ }
@@ -0,0 +1,98 @@
1
+ // The identity of installed pnpm dependencies (GC-A24, rightkit#1506; Adrian, 2026-11-05: "if that's the best shape, do it").
2
+ //
3
+ // The gate installs `--offline --frozen-lockfile` from pnpm's content-addressed store, which checks every package against the
4
+ // lockfile's integrity hash, so the installed bytes are a function of the lockfile, the store and pnpm. Their identity is therefore
5
+ // pnpm's own record of the install, not a walk over every installed byte (the former walk read ~44k files per root and duplicated
6
+ // pnpm's integrity check). Per node_modules root this binds:
7
+ // - .modules.yaml and .pnpm-workspace-state-v1.json, with the install timestamps pnpm writes on every install removed;
8
+ // - .pnpm/lock.yaml, the lockfile pnpm recorded for the virtual store it built;
9
+ // - every top-level entry (including one level of @scope): its name, kind and link target;
10
+ // - any link that resolves outside the repository and outside every walked root (a `link:`/`file:` package pnpm did not take from
11
+ // the store), hashed whole, because no lockfile integrity covers those bytes.
12
+ // A root that does not exist is bound as absent.
13
+ import crypto from "node:crypto";
14
+ import fs from "node:fs";
15
+ import path from "node:path";
16
+
17
+ const sha = (bytes) => crypto.createHash("sha256").update(bytes).digest("hex");
18
+ const inside = (p, dir) => p === dir || p.startsWith(dir + path.sep);
19
+
20
+ /**
21
+ * The bytes of a pnpm install-state file as identities bind them: pnpm stamps the time of every install into `.modules.yaml`
22
+ * (`prunedAt`) and `.pnpm-workspace-state-v1.json` (`lastValidatedTimestamp`, `validation.recordedAtNs`, the lockfile's
23
+ * `mtimeNs`/`ctimeNs`). Only those fields are dropped (measured 2026-11-05: they were the only bytes of 867 entries in 104 roots
24
+ * that differed between two identical installs). Any other file is returned unchanged.
25
+ */
26
+ export function installStateBytes(name, bytes) {
27
+ if (name === ".modules.yaml") return Buffer.from(String(bytes).replace(/^\s*"?prunedAt"?\s*:.*$/m, ""));
28
+ if (name === ".pnpm-workspace-state-v1.json") {
29
+ try {
30
+ const state = JSON.parse(String(bytes)); delete state.lastValidatedTimestamp;
31
+ if (state.validation && typeof state.validation === "object") {
32
+ delete state.validation.recordedAtNs;
33
+ for (const entry of Object.values(state.validation.files ?? {})) if (entry && typeof entry === "object") { delete entry.mtimeNs; delete entry.ctimeNs; }
34
+ }
35
+ return Buffer.from(JSON.stringify(state));
36
+ } catch { return bytes; }
37
+ }
38
+ return bytes;
39
+ }
40
+
41
+ const STATE_FILES = [".modules.yaml", ".pnpm-workspace-state-v1.json", path.join(".pnpm", "lock.yaml")];
42
+
43
+ /** Whole-content hash of a directory or file outside the store (a linked local package). Bounded; never follows links inside it. */
44
+ function hashOutside(target, budget) {
45
+ const h = crypto.createHash("sha256");
46
+ const walk = (p) => {
47
+ if (++budget.count > budget.max) throw new Error(`linked package ${target} exceeds ${budget.max} entries`);
48
+ const st = fs.lstatSync(p);
49
+ if (st.isSymbolicLink()) { h.update(`link\0${path.relative(target, p)}\0${fs.readlinkSync(p)}\0`); return; }
50
+ if (st.isDirectory()) { h.update(`dir\0${path.relative(target, p)}\0`); for (const n of fs.readdirSync(p).sort()) { if (n === "node_modules" || n === ".git") continue; walk(path.join(p, n)); } return; }
51
+ if (st.isFile()) { h.update(`file\0${path.relative(target, p)}\0${st.mode & 0o111 ? "x" : "-"}\0${sha(fs.readFileSync(p))}\0`); return; }
52
+ };
53
+ walk(target);
54
+ return h.digest("hex");
55
+ }
56
+
57
+ /**
58
+ * The identity of the installed dependencies under `dirs` (node_modules directories, absolute or relative to `root`).
59
+ * `repoRoot` (default `root`) bounds what counts as "inside the repository" for linked packages.
60
+ */
61
+ export function installIdentity(root, dirs, { repoRoot = root, maxLinkedEntries = 200000 } = {}) {
62
+ const h = crypto.createHash("sha256");
63
+ const realRepo = fs.realpathSync(repoRoot);
64
+ const walked = [];
65
+ for (const d of [...dirs].sort()) { try { walked.push(fs.realpathSync(path.resolve(root, d))); } catch { /* absent: bound below */ } }
66
+ const outside = new Set();
67
+ const budget = { count: 0, max: maxLinkedEntries };
68
+ const rel = (p) => (inside(p, realRepo) ? path.relative(realRepo, p).split(path.sep).join("/") : p);
69
+ for (const d of [...dirs].sort()) {
70
+ const dir = path.resolve(root, d);
71
+ h.update(`root\0${rel(dir)}\0`);
72
+ let st; try { st = fs.lstatSync(dir); } catch (error) { if (error?.code === "ENOENT" || error?.code === "ENOTDIR") { h.update("absent\0"); continue; } throw error; }
73
+ if (!st.isDirectory()) { h.update(`not-a-directory\0${st.mode}\0`); continue; }
74
+ for (const f of STATE_FILES) {
75
+ let bytes; try { bytes = fs.readFileSync(path.join(dir, f)); } catch (error) { if (error?.code === "ENOENT") { h.update(`${f}\0absent\0`); continue; } throw error; }
76
+ h.update(`${f}\0${sha(installStateBytes(path.basename(f), bytes))}\0`);
77
+ }
78
+ const entry = (p, name) => {
79
+ const est = fs.lstatSync(p);
80
+ if (est.isSymbolicLink()) {
81
+ const target = fs.readlinkSync(p);
82
+ h.update(`link\0${name}\0${target}\0`);
83
+ let real = null; try { real = fs.realpathSync(p); } catch (error) { if (error?.code !== "ENOENT") throw error; h.update("dangling\0"); }
84
+ if (real && !inside(real, realRepo) && !walked.some((w) => inside(real, w))) outside.add(real);
85
+ return;
86
+ }
87
+ h.update(`${est.isDirectory() ? "dir" : est.isFile() ? "file" : "other"}\0${name}\0`);
88
+ };
89
+ for (const name of fs.readdirSync(dir).sort()) {
90
+ if (name === ".pnpm" || name === ".bin" || name.startsWith(".")) continue;
91
+ const p = path.join(dir, name);
92
+ if (name.startsWith("@") && fs.lstatSync(p).isDirectory()) { for (const sub of fs.readdirSync(p).sort()) entry(path.join(p, sub), `${name}/${sub}`); }
93
+ else entry(p, name);
94
+ }
95
+ }
96
+ for (const real of [...outside].sort()) h.update(`outside\0${real}\0${hashOutside(real, budget)}\0`);
97
+ return h.digest("hex");
98
+ }