@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.
- package/affected-units.mjs +190 -0
- package/bin/rightkit-gate.mjs +629 -132
- package/build-ownership.mjs +206 -41
- package/cargo-width.mjs +49 -0
- package/ci-compile-admission.mjs +57 -0
- package/committed-cargo-workspace.mjs +58 -0
- package/cross-targets.mjs +18 -2
- package/dependency-identity.mjs +98 -0
- package/deterministic-scans.mjs +256 -57
- package/gate-acceptance.mjs +1443 -0
- package/gate-coverage.mjs +17 -6
- package/gate-serve.mjs +239 -0
- package/handle-revocation.mjs +100 -0
- package/handle-revocation.rust-vector.json +1 -0
- package/handle-revocation.vectors.json +53 -0
- package/local-publish.mjs +109 -34
- package/managed-cargo.mjs +11 -0
- package/node-check-cache.mjs +95 -0
- package/owner-process-proof.mjs +14 -0
- package/ownership-mark.mjs +10 -1
- package/ownership-recover.mjs +78 -0
- package/package.json +2 -1
- package/performance-diagnostic.mjs +19 -0
- package/provenance-verify.mjs +35 -0
- package/publication-gate.mjs +62 -29
- package/publish-cargo.mjs +19 -4
- package/qualification-verify.mjs +12 -2
- package/rightkit-drift.mjs +4 -3
- package/rightkit-versions.json +1 -1
- package/snapshot-broker.mjs +1 -1
- package/snapshot-check.mjs +91 -12
- package/snapshot-dependency-reuse.mjs +230 -0
- package/snapshot-metadata.mjs +1 -1
- package/snapshot-request.mjs +12 -5
- package/snapshot.mjs +41 -6
- package/stage-sidecar.mjs +20 -4
- package/stamp-relay.mjs +37 -0
- package/unit-gate.mjs +25 -5
- package/unit-list-compile.mjs +277 -0
package/build-ownership.mjs
CHANGED
|
@@ -67,7 +67,9 @@ import { spawn as spawnDetachedDefault, spawnSync } from "./background-process.m
|
|
|
67
67
|
import { managedRuntimeClient } from "./managed-cargo.mjs";
|
|
68
68
|
import { resolveManagedRoots } from "./managed-roots.mjs";
|
|
69
69
|
import { requireManagedRoot } from "./managed-root-guard.mjs";
|
|
70
|
-
import {
|
|
70
|
+
import { readEnrolledPins } from "./broker-pins.mjs";
|
|
71
|
+
import { isRevocationEnvelope, readRevocation, revocationFile, verifyRevocation } from "./handle-revocation.mjs";
|
|
72
|
+
import { OWNERSHIP_ENV, OWNERSHIP_FILE_ENV, OwnershipBusy, holds, markBrokerSubmit, markBrokerUnsent, isMarkLockText, markCarriedSend, markLockFile, withMarkLock } from "./ownership-mark.mjs";
|
|
71
73
|
|
|
72
74
|
// The mark itself lives in a leaf module (ownership-mark.mjs): snapshot-broker.mjs records carried sends through it, and importing this
|
|
73
75
|
// file from there would close a cycle (this file -> managed-cargo -> cargo-target-shim -> snapshot-broker).
|
|
@@ -615,6 +617,20 @@ export function processProbe({ platform = process.platform, spawn = spawnSync, s
|
|
|
615
617
|
for (const p of members) if (!Number.isFinite(p.startedMs)) throw new Error(`cannot read the start time of pid ${p.pid}`);
|
|
616
618
|
return { members, byPid: new Map(rows.map((row) => [row.pid, row])), own };
|
|
617
619
|
},
|
|
620
|
+
/** One fresh process table for every recorded group in this release; never retained across releases. */
|
|
621
|
+
groupSnapshots(groups) {
|
|
622
|
+
for (const group of groups) if (!Number.isInteger(group) || group <= 1) throw new Error(`no usable process group (${group})`);
|
|
623
|
+
const { rows, own } = psList();
|
|
624
|
+
const byPid = new Map(rows.map((row) => [row.pid, row]));
|
|
625
|
+
const snapshots = new Map([...new Set(groups)].map((group) => [group, { members: [], byPid, own }]));
|
|
626
|
+
for (const p of rows) {
|
|
627
|
+
const snapshot = snapshots.get(p.group);
|
|
628
|
+
if (!snapshot || own.has(p.pid)) continue;
|
|
629
|
+
if (!Number.isFinite(p.startedMs)) throw new Error(`cannot read the start time of pid ${p.pid}`);
|
|
630
|
+
snapshot.members.push(p);
|
|
631
|
+
}
|
|
632
|
+
return snapshots;
|
|
633
|
+
},
|
|
618
634
|
/**
|
|
619
635
|
* Pids of processes whose environment carries `<OWNERSHIP_ENV>=<handle>` (this gate's own chain left out). Linux reads
|
|
620
636
|
* /proc/<pid>/environ (an unreadable entry of this user's throws: unknown); macOS reads `ps eww`, which shows the environment
|
|
@@ -648,7 +664,7 @@ export function processProbe({ platform = process.platform, spawn = spawnSync, s
|
|
|
648
664
|
* with this gate's anchor. `{ owner, anchorMs, recorded }` as there. Returns `[{ pid, why }]` (held), or throws: a listing
|
|
649
665
|
* that did not finish cleanly is unknown, and the caller stays busy.
|
|
650
666
|
*/
|
|
651
|
-
hiddenHolders({ owner, anchorMs, recorded = [] } = {}) {
|
|
667
|
+
hiddenHolders({ owner, anchorMs, recorded = [], timing = null } = {}) {
|
|
652
668
|
if (platform !== "darwin") return null;
|
|
653
669
|
// Without this process's own user id nothing could be told from another user's (which is skipped): unknown, never "none".
|
|
654
670
|
if (!Number.isInteger(uid)) throw new Error("this process's user id is unknown");
|
|
@@ -680,7 +696,10 @@ export function processProbe({ platform = process.platform, spawn = spawnSync, s
|
|
|
680
696
|
// `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
697
|
// launchd does not manage (a reparented orphan) or one that is gone; anything else is unknown (rc null: it could not run).
|
|
682
698
|
const blame = (pid) => {
|
|
683
|
-
const
|
|
699
|
+
const started = performance.now();
|
|
700
|
+
let r;
|
|
701
|
+
try { r = spawn("launchctl", ["blame", String(pid)], { encoding: "utf8", env: { ...process.env, LC_ALL: "C", LANG: "C" }, timeout: 5000, maxBuffer: 1 << 16 }); }
|
|
702
|
+
finally { if (timing) { timing.blameCount = (timing.blameCount ?? 0) + 1; timing.blameMs = (timing.blameMs ?? 0) + performance.now() - started; } }
|
|
684
703
|
if (r.error) return { rc: null, line: String(r.error.message ?? r.error) };
|
|
685
704
|
const text = `${String(r.stdout ?? "")}${String(r.stderr ?? "")}`.split(/\r?\n/).find((l) => l.trim() !== "") ?? "";
|
|
686
705
|
return { rc: r.status, line: text.trim() };
|
|
@@ -1033,7 +1052,8 @@ function coveredMember(m, owner, { byPid, own }) {
|
|
|
1033
1052
|
* Whether the work `owner` covers, other than the process `self` (the live gate at release, null at reclaim), is proven gone.
|
|
1034
1053
|
* Returns the proofs, or throws a reason that is busy.
|
|
1035
1054
|
*/
|
|
1036
|
-
function coveredWorkGone(owner, { probe, lease, file, selfPid = null, waitMs = 0 }) {
|
|
1055
|
+
function coveredWorkGone(owner, { probe, lease, file, selfPid = null, waitMs = 0, timing = null, revoked = null, processOnly = false, broker = null }) {
|
|
1056
|
+
const measure = (name, fn) => { const start = performance.now(); try { return fn(); } finally { if (timing) timing[name] = (timing[name] ?? 0) + performance.now() - start; } };
|
|
1037
1057
|
const proofs = [];
|
|
1038
1058
|
let rebooted = false;
|
|
1039
1059
|
// A reboot is only a question for a dead owner; a live gate releasing its own record has not outlived one.
|
|
@@ -1073,7 +1093,7 @@ function coveredWorkGone(owner, { probe, lease, file, selfPid = null, waitMs = 0
|
|
|
1073
1093
|
}
|
|
1074
1094
|
} else if (!rebooted && c.kind === "group") {
|
|
1075
1095
|
let snap;
|
|
1076
|
-
try { snap = probe.groupSnapshot(c.group); } catch (e) { throw new Error(`process group ${c.group} cannot be listed (${e.message})`); }
|
|
1096
|
+
try { snap = measure("groupMs", () => probe.groupSnapshot(c.group)); } catch (e) { throw new Error(`process group ${c.group} cannot be listed (${e.message})`); }
|
|
1077
1097
|
const children = snap.members.filter((m) => m.pid !== selfPid && coveredMember(m, owner, snap)).map((m) => m.pid);
|
|
1078
1098
|
if (children.length) throw new Error(`process group ${c.group} still has ${children.length} member(s) started under this ownership: ${children.join(", ")}`);
|
|
1079
1099
|
proofs.push(`process group ${c.group} has no member started under this ownership`);
|
|
@@ -1084,23 +1104,49 @@ function coveredWorkGone(owner, { probe, lease, file, selfPid = null, waitMs = 0
|
|
|
1084
1104
|
const intents = entries.filter((n) => n.startsWith("intent-"));
|
|
1085
1105
|
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
1106
|
const groups = entries.filter((n) => /^group-\d+\.json$/.test(n));
|
|
1107
|
+
if (timing) timing.detachedGroups = groups.length;
|
|
1087
1108
|
const recorded = [];
|
|
1109
|
+
const groupRecords = [];
|
|
1088
1110
|
for (const name of groups) {
|
|
1089
|
-
let entry;
|
|
1090
|
-
try {
|
|
1111
|
+
let entry, bytes, writtenMs;
|
|
1112
|
+
try {
|
|
1113
|
+
const entryFile = path.join(registry, name);
|
|
1114
|
+
bytes = fs.readFileSync(entryFile, "utf8");
|
|
1115
|
+
entry = JSON.parse(bytes);
|
|
1116
|
+
writtenMs = fs.statSync(entryFile).mtimeMs;
|
|
1117
|
+
} catch { throw new Error(`the detached-child entry ${name} cannot be read`); }
|
|
1091
1118
|
if (!Number.isInteger(entry?.group) || !Number.isFinite(entry?.startedMs)) throw new Error(`the detached-child entry ${name} cannot be read`);
|
|
1092
1119
|
recorded.push({ group: entry.group, command: entry.command });
|
|
1120
|
+
groupRecords.push({ name, entry, bytes, writtenMs });
|
|
1121
|
+
}
|
|
1122
|
+
let snapshots = null;
|
|
1123
|
+
if (groups.length && typeof probe.groupSnapshots === "function") {
|
|
1124
|
+
try { snapshots = measure("detachedGroupsMs", () => probe.groupSnapshots(groupRecords.map(({ entry }) => entry.group))); }
|
|
1125
|
+
catch (e) { throw new Error(`detached process groups cannot be listed (${e.message})`); }
|
|
1126
|
+
if (!(snapshots instanceof Map)) throw new Error("detached process groups cannot be listed (invalid bulk process table)");
|
|
1127
|
+
}
|
|
1128
|
+
for (const { entry, writtenMs } of groupRecords) {
|
|
1093
1129
|
let snapshot;
|
|
1094
|
-
try { snapshot =
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
try { writtenMs = fs.statSync(path.join(registry, name)).mtimeMs; } catch { /* unknown: judged as before */ }
|
|
1130
|
+
try { snapshot = snapshots ? snapshots.get(entry.group) : measure("detachedGroupsMs", () => probe.groupSnapshot(entry.group)); }
|
|
1131
|
+
catch (e) { throw new Error(`detached process group ${entry.group} cannot be listed (${e.message})`); }
|
|
1132
|
+
if (!snapshot || !Array.isArray(snapshot.members)) throw new Error(`detached process group ${entry.group} cannot be listed (missing process table)`);
|
|
1133
|
+
// A later leader is a reused group ID; otherwise any member at or after the recorded lower bound holds the release.
|
|
1099
1134
|
const leader = snapshot.members.find((m) => m.pid === entry.group);
|
|
1100
1135
|
if (leader && Number.isFinite(writtenMs) && leader.startedMs > writtenMs + START_SLACK_MS) continue;
|
|
1101
1136
|
const live = snapshot.members.filter((m) => m.pid !== selfPid && m.startedMs >= entry.startedMs - START_SLACK_MS).map((m) => m.pid);
|
|
1102
1137
|
if (live.length) throw new Error(`detached process group ${entry.group} (${entry.command}) still has ${live.length} member(s): ${live.join(", ")}`);
|
|
1103
1138
|
}
|
|
1139
|
+
// Catch changes during this sample. As with the old per-group checks, this is not an atomic spawn/release fence.
|
|
1140
|
+
let after;
|
|
1141
|
+
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})`); }
|
|
1142
|
+
const relevant = (names) => names.filter((n) => n.startsWith("intent-") || /^group-\d+\.json$/.test(n)).sort();
|
|
1143
|
+
if (JSON.stringify(relevant(entries)) !== JSON.stringify(relevant(after))) throw new Error("the detached-child registry changed during the process sample");
|
|
1144
|
+
for (const { name, bytes, writtenMs } of groupRecords) {
|
|
1145
|
+
try {
|
|
1146
|
+
const entryFile = path.join(registry, name);
|
|
1147
|
+
if (fs.readFileSync(entryFile, "utf8") !== bytes || fs.statSync(entryFile).mtimeMs !== writtenMs) throw new Error("changed");
|
|
1148
|
+
} catch { throw new Error(`the detached-child entry ${name} changed during the process sample`); }
|
|
1149
|
+
}
|
|
1104
1150
|
if (groups.length) proofs.push(`the ${groups.length} detached process group(s) it started are empty`);
|
|
1105
1151
|
// See `unreadable` in processProbe. The baseline is the later of (1) the acquisition of the last owner whose release proved zero
|
|
1106
1152
|
// readers and (2) the snapshot root's birth in this boot, capped at this ownership's own acquisition (a process the gate
|
|
@@ -1115,7 +1161,7 @@ function coveredWorkGone(owner, { probe, lease, file, selfPid = null, waitMs = 0
|
|
|
1115
1161
|
// 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
1162
|
const skipBefore = baselines.length ? Math.max(...baselines) : Date.parse(owner.acquiredAt);
|
|
1117
1163
|
let carriers;
|
|
1118
|
-
try { carriers = probe.tokenHolders(owner.handle, skipBefore); } catch (e) { throw new Error(`processes carrying ${OWNERSHIP_ENV} cannot be listed (${e.message})`); }
|
|
1164
|
+
try { carriers = measure("tokenHoldersMs", () => probe.tokenHolders(owner.handle, skipBefore)); } catch (e) { throw new Error(`processes carrying ${OWNERSHIP_ENV} cannot be listed (${e.message})`); }
|
|
1119
1165
|
if (carriers) {
|
|
1120
1166
|
const others = carriers.filter((pid) => pid !== selfPid);
|
|
1121
1167
|
if (others.length) throw new Error(`process(es) ${others.join(", ")} still carry ${OWNERSHIP_ENV}=${owner.handle}`);
|
|
@@ -1123,7 +1169,7 @@ function coveredWorkGone(owner, { probe, lease, file, selfPid = null, waitMs = 0
|
|
|
1123
1169
|
}
|
|
1124
1170
|
if (owner.snapshot) {
|
|
1125
1171
|
let users;
|
|
1126
|
-
try { users = probe.snapshotUsers(owner.snapshot, skipBefore); } catch (e) { throw new Error(`processes using the snapshot cannot be listed (${e.message})`); }
|
|
1172
|
+
try { users = measure("snapshotUsersMs", () => probe.snapshotUsers(owner.snapshot, skipBefore)); } catch (e) { throw new Error(`processes using the snapshot cannot be listed (${e.message})`); }
|
|
1127
1173
|
if (users) {
|
|
1128
1174
|
const others = users.filter((u) => u.pid !== selfPid);
|
|
1129
1175
|
if (others.length) throw new Error(`process(es) ${others.map((u) => `${u.pid} (${u.how})`).join(", ")} still use the snapshot ${owner.snapshot}`);
|
|
@@ -1136,7 +1182,7 @@ function coveredWorkGone(owner, { probe, lease, file, selfPid = null, waitMs = 0
|
|
|
1136
1182
|
// ownership token, an actual snapshot user, and the broker lease hold a release.
|
|
1137
1183
|
if (typeof probe.hiddenHolders === "function") {
|
|
1138
1184
|
let hidden;
|
|
1139
|
-
try { hidden = probe.hiddenHolders({ owner, anchorMs: skipBefore, recorded }); } catch { hidden = null; }
|
|
1185
|
+
try { hidden = measure("hiddenHoldersMs", () => probe.hiddenHolders({ owner, anchorMs: skipBefore, recorded, timing })); } catch { hidden = null; }
|
|
1140
1186
|
const others = (hidden ?? []).filter((h) => h.pid !== selfPid);
|
|
1141
1187
|
if (others.length) {
|
|
1142
1188
|
const shown = others.slice(0, 8);
|
|
@@ -1146,7 +1192,9 @@ function coveredWorkGone(owner, { probe, lease, file, selfPid = null, waitMs = 0
|
|
|
1146
1192
|
} else if (!rebooted) {
|
|
1147
1193
|
throw new Error(`the record names no containment (${JSON.stringify(c)})`);
|
|
1148
1194
|
}
|
|
1149
|
-
if (
|
|
1195
|
+
if (processOnly) {
|
|
1196
|
+
proofs.push("broker work NOT judged: a process-only proof (rightkit#1511) says nothing about broker leases");
|
|
1197
|
+
} else if (owner.broker?.submitted) {
|
|
1150
1198
|
// Every submission under this handle must be accounted for by NAME, never by the bare handle (GB-21, GB-23, GB-85). The bare handle answers REAPED when at least one
|
|
1151
1199
|
// member completed and none is held (rustright snapshot.rs `status`), so it proves only that no lease is held now: a completed sibling never stands in for an
|
|
1152
1200
|
// unknown submission. Each recorded sub-handle (broker.handles, recorded before its send) is asked by its exact name and must be one of
|
|
@@ -1157,29 +1205,71 @@ function coveredWorkGone(owner, { probe, lease, file, selfPid = null, waitMs = 0
|
|
|
1157
1205
|
const unsent = owner.broker.unsent && typeof owner.broker.unsent === "object" ? owner.broker.unsent : {};
|
|
1158
1206
|
const waitOptions = waitMs > 0 ? { waitMs } : {};
|
|
1159
1207
|
const settled = (sub) => unsent[sub] && typeof unsent[sub].reason === "string";
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1208
|
+
// rightkit#1511: a sub-handle the broker can no longer answer may instead carry the broker's signed revocation of exactly that sub-handle, bound to
|
|
1209
|
+
// this record's bytes (handle-revocation.mjs). It is offered only by a dead owner's reclaim (judgeOwner), never by a release; a bad revocation throws.
|
|
1210
|
+
const revokedOf = new Map();
|
|
1211
|
+
const revocation = (sub) => { if (!revoked) return null; if (!revokedOf.has(sub)) revokedOf.set(sub, revoked(sub)); return revokedOf.get(sub); };
|
|
1212
|
+
// rightkit#1513 (Adrian, 2026-11-05: "It should ideally auto recover"): in a dead owner's reclaim (never a live release), after every process
|
|
1213
|
+
// proof above passed, a sub-handle the broker answers UNKNOWN with no member row was never received when the SAME broker process has run since
|
|
1214
|
+
// before this ownership was acquired: that broker would hold a claim, lease or member row for anything it got, and no process remains to send it.
|
|
1215
|
+
const acquiredMs = Date.parse(owner.acquiredAt);
|
|
1216
|
+
const brokerUpThroughout = selfPid === null && broker && Number.isFinite(broker.startedMs) && Number.isFinite(acquiredMs) && broker.startedMs + 2000 < acquiredMs;
|
|
1217
|
+
const neverReceived = new Set();
|
|
1218
|
+
const everyUnsent = () => handles.length > 0 && handles.every((sub) => settled(sub) || revocation(sub) !== null || brokerUpThroughout);
|
|
1219
|
+
const status = measure("leaseMs", () => lease({ snapshot: owner.snapshot, handle: owner.handle, ...waitOptions }));
|
|
1220
|
+
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
1221
|
if (status.state === "REAPED") proofs.push(`broker lease for ${owner.handle} is REAPED`);
|
|
1164
1222
|
// 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.
|
|
1165
1223
|
if (Array.isArray(status.members)) for (const sub of handles) { const row = status.members.find((m) => m.handle === sub); if (row && row.state !== "REAPED") throw new Error(`the broker lists sub-handle ${sub} as ${row.state} among the members of ${owner.handle}`); }
|
|
1166
|
-
let neverStarted = 0;
|
|
1224
|
+
let neverStarted = 0; let revokedCount = 0;
|
|
1167
1225
|
for (const sub of handles) {
|
|
1168
1226
|
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 });
|
|
1227
|
+
const one = measure("leaseMs", () => lease({ snapshot: owner.snapshot, handle: sub, ...waitOptions }));
|
|
1170
1228
|
const member = Array.isArray(one.members) ? one.members.find((m) => m.handle === sub) : null;
|
|
1171
1229
|
if (one.state === "REAPED") {
|
|
1172
1230
|
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`);
|
|
1173
1231
|
continue;
|
|
1174
1232
|
}
|
|
1175
1233
|
if (settled(sub) && one.state === "UNKNOWN" && Array.isArray(one.members) && one.members.length === 0) { proofs.push(`${sub} never started (${unsent[sub].reason}) and the broker holds nothing under it`); neverStarted += 1; continue; }
|
|
1234
|
+
// The revocation settles only what the broker cannot answer: UNKNOWN, no member row for it here or in the owner's answer. ACTIVE or a listed member always holds.
|
|
1235
|
+
const listed = Array.isArray(status.members) && status.members.some((m) => m.handle === sub);
|
|
1236
|
+
const rev = one.state === "UNKNOWN" && Array.isArray(one.members) && one.members.length === 0 && !listed ? revocation(sub) : null;
|
|
1237
|
+
if (rev) { proofs.push(`${sub} is UNKNOWN to the broker and revoked by its signed revocation ${rev.file} (proof ${rev.payload.proofSha256})`); revokedCount += 1; continue; }
|
|
1238
|
+
if (brokerUpThroughout && one.state === "UNKNOWN" && Array.isArray(one.members) && one.members.length === 0 && !listed) { neverReceived.add(sub); continue; }
|
|
1176
1239
|
throw new Error(`broker work may exist under sub-handle ${sub} and its lease is ${one.state} (${one.why})`);
|
|
1177
1240
|
}
|
|
1178
|
-
if (
|
|
1241
|
+
if (neverReceived.size) proofs.push(`${neverReceived.size} sub-handle(s) never reached the broker: UNKNOWN with no member row to broker pid ${broker.pid}, up since ${new Date(broker.startedMs).toISOString()}, before this ownership (${owner.acquiredAt}), and no process of the run remains (${[...neverReceived].slice(0, 3).join(", ")}${neverReceived.size > 3 ? ", ..." : ""})`);
|
|
1242
|
+
if (handles.length) proofs.push(neverStarted === 0 && revokedCount === 0 && neverReceived.size === 0 ? `broker lease for each of ${handles.length} sub-handle(s) is REAPED` : `every one of ${handles.length} sub-handle(s) is accounted for: ${handles.length - neverStarted - revokedCount - neverReceived.size} REAPED, ${neverStarted} proven never started, ${neverReceived.size} never reached the broker, ${revokedCount} revoked by the broker`);
|
|
1179
1243
|
}
|
|
1180
1244
|
return proofs;
|
|
1181
1245
|
}
|
|
1182
1246
|
|
|
1247
|
+
/**
|
|
1248
|
+
* rightkit#1511 (rustright#228): the process half of a dead owner's reclaim, for RustRight's offline revocation helper to bind before it signs: the owner pid is
|
|
1249
|
+
* gone (or now runs another process) and every process check of a reclaim passes (detached groups, token holders, snapshot users, containment), with NO broker
|
|
1250
|
+
* lease judged and nothing written. Returns `{ schema, ownerFile, dataRoot, ownerSha256, ownerHandle, snapshot, host, proofs, provedAt }`; throws OwnershipBusy
|
|
1251
|
+
* naming what is still live or unknown. It never stands in for a reclaim: the reclaim still runs every check, the broker's included.
|
|
1252
|
+
*/
|
|
1253
|
+
/** Which RightKit code produced a process proof: this package's name and version and the SHA-256 of build-ownership.mjs itself. */
|
|
1254
|
+
function probeIdentity() {
|
|
1255
|
+
const here = new URL(import.meta.url);
|
|
1256
|
+
const pkg = JSON.parse(fs.readFileSync(new URL("./package.json", here), "utf8"));
|
|
1257
|
+
return { package: pkg.name, version: pkg.version, moduleSha256: crypto.createHash("sha256").update(fs.readFileSync(here)).digest("hex") };
|
|
1258
|
+
}
|
|
1259
|
+
export const OWNER_PROCESS_PROOF_SCHEMA = "rightkit.owner-process-proof/1";
|
|
1260
|
+
export function proveOwnerProcessesGone({ file, platform = process.platform, probe = processProbe({ platform }), host = os.hostname(), now = () => new Date() }) {
|
|
1261
|
+
const observed = readText(file);
|
|
1262
|
+
if (observed === null) throw new OwnershipBusy(`build ownership ${file}: no record`);
|
|
1263
|
+
const noLease = () => { throw new Error("a process-only proof asks the broker nothing"); };
|
|
1264
|
+
const { owner, proofs } = judgeOwner(observed, { file, probe, lease: noLease, host, processOnly: true });
|
|
1265
|
+
if (readText(file) !== observed) throw new OwnershipBusy(`build ownership ${file} changed while its processes were judged`);
|
|
1266
|
+
return {
|
|
1267
|
+
schema: OWNER_PROCESS_PROOF_SCHEMA, ownerFile: fs.realpathSync.native(file), dataRoot: fs.realpathSync.native(dataRootOf(file)),
|
|
1268
|
+
ownerSha256: crypto.createHash("sha256").update(Buffer.from(observed, "utf8")).digest("hex"), ownerHandle: owner.handle, snapshot: owner.snapshot ?? null,
|
|
1269
|
+
host, proofs, provedAt: now().toISOString(), probe: probeIdentity(),
|
|
1270
|
+
};
|
|
1271
|
+
}
|
|
1272
|
+
|
|
1183
1273
|
/**
|
|
1184
1274
|
* Whether the claimant a standing `.reclaim` body names is `"dead"` (proven), `"live"` or `"unknown"`. The body is the claimant's own owner record, so the same identity
|
|
1185
1275
|
* rules as the record's judge apply: another host or an unreadable body is unknown; a reboot since the claimant started, a gone pid, or a pid that now runs a process that
|
|
@@ -1200,7 +1290,7 @@ export function judgeClaimant(text, { probe, host }) {
|
|
|
1200
1290
|
* Why the record `observed` may be reclaimed (`{ owner, proofs }`), or an OwnershipBusy throw naming what is still live or
|
|
1201
1291
|
* unknown. Pure apart from the probes.
|
|
1202
1292
|
*/
|
|
1203
|
-
export function judgeOwner(observed, { file, probe, lease, host = os.hostname() }) {
|
|
1293
|
+
export function judgeOwner(observed, { file, probe, lease, host = os.hostname(), pins = null, processOnly = false, broker = null }) {
|
|
1204
1294
|
let owner = null;
|
|
1205
1295
|
try { owner = JSON.parse(observed); } catch { owner = null; }
|
|
1206
1296
|
const busy = (why, detail = {}) => new OwnershipBusy(`build ownership ${file}: ${why}`, { owner, ...detail });
|
|
@@ -1214,8 +1304,19 @@ export function judgeOwner(observed, { file, probe, lease, host = os.hostname()
|
|
|
1214
1304
|
throw busy(`held by pid ${owner.pid} (${owner.stage ?? "stage"} of ${owner.commit ?? "a commit"}) since ${owner.acquiredAt}`);
|
|
1215
1305
|
}
|
|
1216
1306
|
const proofs = [self.alive ? `owner pid ${owner.pid} now runs another process (started ${new Date(self.startedMs).toISOString()}, owner started ${new Date(owner.startedMs).toISOString()})` : `owner pid ${owner.pid} is gone`];
|
|
1217
|
-
|
|
1218
|
-
|
|
1307
|
+
// rightkit#1511: revocations are judged against the exact bytes judged here; the reclaim rereads both under its claim before it removes anything.
|
|
1308
|
+
const revocations = [];
|
|
1309
|
+
const revoked = pins ? (sub) => {
|
|
1310
|
+
const dataRoot = fs.realpathSync.native(dataRootOf(file));
|
|
1311
|
+
const at = revocationFile(dataRoot, owner.handle, sub, owner.snapshot);
|
|
1312
|
+
const bytes = readRevocation(at);
|
|
1313
|
+
if (bytes === null || !isRevocationEnvelope(bytes)) return null;
|
|
1314
|
+
const payload = verifyRevocation(bytes, pins, { ownerFile: fs.realpathSync.native(file), dataRoot, ownerBytes: Buffer.from(observed, "utf8"), owner, sub });
|
|
1315
|
+
revocations.push({ file: at, bytes });
|
|
1316
|
+
return { file: at, payload };
|
|
1317
|
+
} : null;
|
|
1318
|
+
try { proofs.push(...coveredWorkGone(owner, { probe, lease, file, revoked, processOnly, broker })); } catch (e) { throw busy(`owner pid ${owner.pid} is gone but ${e.message}`); }
|
|
1319
|
+
return { owner, proofs, revocations };
|
|
1219
1320
|
}
|
|
1220
1321
|
|
|
1221
1322
|
/**
|
|
@@ -1236,6 +1337,8 @@ export function acquireBuildOwnership({
|
|
|
1236
1337
|
hooks = {},
|
|
1237
1338
|
managedRoot,
|
|
1238
1339
|
device,
|
|
1340
|
+
brokerPins,
|
|
1341
|
+
brokerIdentity,
|
|
1239
1342
|
} = {}) {
|
|
1240
1343
|
// First, before the environment, the record or any write: the managed root exists (decision D4). `managedRoot` and `device` are
|
|
1241
1344
|
// fixtures' seams; a production caller passes neither.
|
|
@@ -1267,7 +1370,7 @@ export function acquireBuildOwnership({
|
|
|
1267
1370
|
if (!live.alive || (Number.isFinite(owner.startedMs) && Number.isFinite(live.startedMs) && !sameStart(live.startedMs, owner.startedMs))) {
|
|
1268
1371
|
throw new OwnershipBusy(`build ownership ${file}: ${OWNERSHIP_ENV}=${inherited} names a record whose owner pid ${owner.pid} is no longer the process that took it; a nested gate joins only a live owner's record`);
|
|
1269
1372
|
}
|
|
1270
|
-
return { handle: inherited, file, joined: true, reclaimed: null, owner, markBrokerSubmit: (callHandle) => markBrokerSubmit(file, inherited, callHandle), markBrokerUnsent: (callHandle, reason) => markBrokerUnsent(file, inherited, callHandle, reason), held: () => holds(file, inherited), release: () => ({ released: false, joined: true }) };
|
|
1373
|
+
return { handle: inherited, file, joined: true, reclaimed: null, owner, markBrokerSubmit: (callHandle, note) => markBrokerSubmit(file, inherited, callHandle, { note }), markBrokerUnsent: (callHandle, reason) => markBrokerUnsent(file, inherited, callHandle, reason), held: () => holds(file, inherited), release: () => ({ released: false, joined: true }) };
|
|
1271
1374
|
}
|
|
1272
1375
|
throw new OwnershipBusy(`build ownership ${file}: ${OWNERSHIP_ENV}=${inherited} is not the current owner; a nested gate never takes ownership of its own`);
|
|
1273
1376
|
}
|
|
@@ -1306,18 +1409,31 @@ export function acquireBuildOwnership({
|
|
|
1306
1409
|
};
|
|
1307
1410
|
const body = JSON.stringify(record);
|
|
1308
1411
|
const release = () => {
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1412
|
+
const timingKey = Symbol.for("rightkit.releaseTiming");
|
|
1413
|
+
const timing = process[timingKey] ?? null;
|
|
1414
|
+
const start = performance.now();
|
|
1415
|
+
if (timing) timing.releaseStartEpochMs = performance.timeOrigin + start;
|
|
1416
|
+
try {
|
|
1417
|
+
if (!holds(file, handle)) return { released: false, why: "no longer the owner" };
|
|
1418
|
+
let proofs;
|
|
1419
|
+
// The record as it is now (a broker submit may have been marked since it was written).
|
|
1420
|
+
try { proofs = coveredWorkGone(JSON.parse(readText(file)), { probe, lease, file, selfPid: process.pid, waitMs: RELEASE_LEASE_WAIT_MS, timing }); }
|
|
1421
|
+
catch (e) { return { released: false, why: `left for the next gate to reclaim: ${e.message}` }; }
|
|
1422
|
+
finally { if (exportEnv && process.env[OWNERSHIP_ENV] === handle) { delete process.env[OWNERSHIP_ENV]; delete process.env[OWNERSHIP_FILE_ENV]; } }
|
|
1423
|
+
// Only a release that proved zero readers leaves the marker; a held one leaves none (and keeps the record).
|
|
1424
|
+
writeCleanMarker(file, record);
|
|
1425
|
+
fs.rmSync(file, { force: true });
|
|
1426
|
+
fs.rmSync(markLockFile(file), { force: true });
|
|
1427
|
+
fs.rmSync(childrenDir(file, handle), { recursive: true, force: true });
|
|
1428
|
+
return { released: true, proofs };
|
|
1429
|
+
} finally {
|
|
1430
|
+
if (timing) {
|
|
1431
|
+
timing.releaseMs = performance.now() - start;
|
|
1432
|
+
timing.releaseEndEpochMs = performance.timeOrigin + performance.now();
|
|
1433
|
+
delete process[timingKey];
|
|
1434
|
+
try { process.stderr.write(`rightkit-release-timing ${JSON.stringify(timing)}\n`); } catch { /* diagnostics must not affect release */ }
|
|
1435
|
+
}
|
|
1436
|
+
}
|
|
1321
1437
|
};
|
|
1322
1438
|
const done = (reclaimed) => {
|
|
1323
1439
|
// Windows: the gate enters its job before it returns, so every child it starts from here on is contained.
|
|
@@ -1338,12 +1454,15 @@ export function acquireBuildOwnership({
|
|
|
1338
1454
|
catch (e) { if (holds(file, handle)) fs.rmSync(file, { force: true }); throw new OwnershipBusy(`build ownership ${file}: the containment could not be recorded (${e.code ?? e.message}: ${e.message})`); }
|
|
1339
1455
|
}
|
|
1340
1456
|
if (exportEnv) { process.env[OWNERSHIP_ENV] = handle; process.env[OWNERSHIP_FILE_ENV] = file; }
|
|
1341
|
-
return { handle, file, joined: false, reclaimed, owner: record, contained: platform === "win32" ? record.containment.contained === true : true, markBrokerSubmit: (callHandle) => markBrokerSubmit(file, handle, callHandle), markBrokerUnsent: (callHandle, reason) => markBrokerUnsent(file, handle, callHandle, reason), held: () => holds(file, handle), release };
|
|
1457
|
+
return { handle, file, joined: false, reclaimed, owner: record, contained: platform === "win32" ? record.containment.contained === true : true, markBrokerSubmit: (callHandle, note) => markBrokerSubmit(file, handle, callHandle, { note }), markBrokerUnsent: (callHandle, reason) => markBrokerUnsent(file, handle, callHandle, reason), held: () => holds(file, handle), release };
|
|
1342
1458
|
};
|
|
1343
1459
|
if (publish(file, body)) return done(null);
|
|
1344
1460
|
const observed = readText(file);
|
|
1345
1461
|
if (observed === null) { if (publish(file, body)) return done(null); throw new OwnershipBusy(`build ownership ${file} was taken by another process`); }
|
|
1346
|
-
|
|
1462
|
+
// GC-A25 is proposed, not operative: RustRight has not frozen the revocation's authoritative path (its f227 completion key fences legacy reuse; a record
|
|
1463
|
+
// only beside this one does not) nor its publication sequence. Until then no production reclaim honours a revocation; only a caller that passes
|
|
1464
|
+
// `brokerPins` explicitly (fixtures) exercises the branch. Enable by defaulting to enrolledPinsFor(file, platform) once GC-A25 is operative.
|
|
1465
|
+
const judged = judgeOwner(observed, { file, probe, lease, pins: brokerPins ?? null, broker: brokerIdentity === undefined ? runningBrokerProcess({ platform }) : brokerIdentity });
|
|
1347
1466
|
hooks.afterJudge?.();
|
|
1348
1467
|
// A reclaim means the previous release was not clean (a crash, or a release that ended held): nothing unreadable is skipped.
|
|
1349
1468
|
record.cleanBefore = null;
|
|
@@ -1361,13 +1480,21 @@ export function acquireBuildOwnership({
|
|
|
1361
1480
|
}
|
|
1362
1481
|
try {
|
|
1363
1482
|
hooks.afterClaim?.(reclaim);
|
|
1483
|
+
// rightkit#1511: the reread, the removal and the new record run under the record's mark lock too, so no submit or unsent mark of the old owner can land
|
|
1484
|
+
// between the reread and the removal (a mark after it finds another handle and refuses). The lock is released by withMarkLock, not removed here.
|
|
1485
|
+
// A mark lock that cannot be read was left by a crash (it is only ever published whole). The owner and every process under it are proven gone and this
|
|
1486
|
+
// reclaim holds the claim, so no marker of this record can exist: that exact debris is removed, compare-by-content, instead of blocking every later gate.
|
|
1487
|
+
const debris = readText(markLockFile(file));
|
|
1488
|
+
if (debris !== null && !isMarkLockText(debris) && readText(markLockFile(file)) === debris) fs.rmSync(markLockFile(file), { force: true });
|
|
1489
|
+
withMarkLock(file, () => {
|
|
1364
1490
|
if (readText(file) !== observed) throw new OwnershipBusy(`build ownership ${file} changed before it could be reclaimed`);
|
|
1491
|
+
for (const r of judged.revocations) { let now = null; try { now = readRevocation(r.file); } catch { now = null; } if (!now || !now.equals(r.bytes)) throw new OwnershipBusy(`build ownership ${file}: the broker revocation ${r.file} changed before the record could be reclaimed`); }
|
|
1365
1492
|
fs.rmSync(file, { force: true });
|
|
1366
|
-
fs.rmSync(markLockFile(file), { force: true });
|
|
1367
1493
|
fs.rmSync(holderFile(file, judged.owner.handle), { force: true });
|
|
1368
1494
|
fs.rmSync(holderScriptFile(holderFile(file, judged.owner.handle)), { force: true });
|
|
1369
1495
|
fs.rmSync(childrenDir(file, judged.owner.handle), { recursive: true, force: true });
|
|
1370
1496
|
if (!publish(file, reclaimBody)) throw new OwnershipBusy(`build ownership ${file} was taken by another process`);
|
|
1497
|
+
});
|
|
1371
1498
|
} finally {
|
|
1372
1499
|
// Token-checked: only this reclaim's own claim is removed (a successor's claim, published after this one was judged dead, stays).
|
|
1373
1500
|
if (readText(reclaim) === reclaimBody) fs.rmSync(reclaim, { force: true });
|
|
@@ -1375,6 +1502,44 @@ export function acquireBuildOwnership({
|
|
|
1375
1502
|
return done({ from: judged.owner.handle, pid: judged.owner.pid, proofs: judged.proofs });
|
|
1376
1503
|
}
|
|
1377
1504
|
|
|
1505
|
+
/**
|
|
1506
|
+
* rightkit#1511: the host's ENROLLED broker pin (`<managed root>/pins/broker-<platform>.json`; the record is `<managed root>/build-ownership/<key>/owner.json`),
|
|
1507
|
+
* or null when none is enrolled or it cannot be read: then no revocation is honoured and the reclaim proofs stand as before. Never the checkout fallback.
|
|
1508
|
+
*/
|
|
1509
|
+
function enrolledPinsFor(file, platform) {
|
|
1510
|
+
try { return readEnrolledPins({ dataRoot: dataRootOf(file), platform }); } catch { return null; }
|
|
1511
|
+
}
|
|
1512
|
+
|
|
1513
|
+
/** The managed data root a record `<root>/build-ownership/<key>/owner.json` lives under. */
|
|
1514
|
+
const dataRootOf = (file) => path.dirname(path.dirname(path.dirname(file)));
|
|
1515
|
+
|
|
1516
|
+
/**
|
|
1517
|
+
* rightkit#1513: the running RustRight broker's pid and start time (epoch ms), from launchd and ps (macOS); null when it cannot be
|
|
1518
|
+
* established. A broker that has run continuously since before an ownership was acquired saw every request of that run.
|
|
1519
|
+
*/
|
|
1520
|
+
export function runningBrokerProcess({ platform = process.platform, run = spawnSync, uid = process.getuid?.() } = {}) {
|
|
1521
|
+
if (platform === "win32") {
|
|
1522
|
+
// The Dell's broker runs as rustright-broker.exe (D:\.rustright\runtime). Exactly one such process, else unknown (fail safe).
|
|
1523
|
+
try {
|
|
1524
|
+
const script = "$p = @(Get-Process -Name rustright-broker -ErrorAction SilentlyContinue); if ($p.Count -eq 1) { \"$($p[0].Id) $($p[0].StartTime.ToUniversalTime().ToString('o'))\" }";
|
|
1525
|
+
const r = run("powershell.exe", ["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(script, "utf16le").toString("base64")], { encoding: "utf8", timeout: 15000, windowsHide: true });
|
|
1526
|
+
const m = /^(\d+) (\S+)\s*$/m.exec(String(r.stdout ?? ""));
|
|
1527
|
+
if (!m) return null;
|
|
1528
|
+
const pid = Number(m[1]); const startedMs = Date.parse(m[2]);
|
|
1529
|
+
return Number.isInteger(pid) && pid > 0 && Number.isFinite(startedMs) ? { pid, startedMs } : null;
|
|
1530
|
+
} catch { return null; }
|
|
1531
|
+
}
|
|
1532
|
+
if (platform !== "darwin") return null;
|
|
1533
|
+
try {
|
|
1534
|
+
const lc = run("launchctl", ["print", `gui/${uid}/dev.rustright.broker`], { encoding: "utf8", timeout: 5000 });
|
|
1535
|
+
const pid = Number(/^\s*pid = (\d+)$/m.exec(String(lc.stdout ?? ""))?.[1]);
|
|
1536
|
+
if (!Number.isInteger(pid) || pid <= 0) return null;
|
|
1537
|
+
const ps = run("ps", ["-o", "lstart=", "-p", String(pid)], { encoding: "utf8", timeout: 5000, env: { ...process.env, LC_ALL: "C", LANG: "C" } });
|
|
1538
|
+
const startedMs = Date.parse(String(ps.stdout ?? "").trim());
|
|
1539
|
+
return Number.isFinite(startedMs) ? { pid, startedMs } : null;
|
|
1540
|
+
} catch { return null; }
|
|
1541
|
+
}
|
|
1542
|
+
|
|
1378
1543
|
/** Replaces the record atomically while it is still `handle`'s. */
|
|
1379
1544
|
function rewriteRecord(file, handle, change) {
|
|
1380
1545
|
const text = readText(file);
|
package/cargo-width.mjs
ADDED
|
@@ -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
|
+
}
|