@rightkit/release 0.6.46 → 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/gate-serve.mjs CHANGED
@@ -42,6 +42,9 @@ export async function serve({ root, idleMs = Number(process.env.RK_GATE_SERVE_ID
42
42
  const watchedRoot = fs.realpathSync(root);
43
43
  const generation = new Map(); // snapshot key -> change count
44
44
  const proven = new Map(); // snapshot key -> { tree, generation }
45
+ // GC-A11 non-compiling cargo answers (cargo metadata), keyed on the request and the snapshot's change count: an unchanged snapshot is answered
46
+ // from memory, any change to it (or a restart) runs cargo again. Bounded: oldest dropped past 64 entries.
47
+ const cargoAnswers = new Map(); // request digest -> { key, generation, status, stdout, stderr }
45
48
  let watcher = null; let healthy = false; let cookieSeq = 0;
46
49
  const cookies = new Map(); // cookie name -> resolve
47
50
  // Only entries inside a snapshot directory (`<16 hex>/...`) are snapshot content; `<key>.tree-index`, `<key>.state.json` and the like
@@ -88,6 +91,7 @@ export async function serve({ root, idleMs = Number(process.env.RK_GATE_SERVE_ID
88
91
  if (key === null) return { ok: false, why: "not a snapshot directory name" };
89
92
  if (!(await cookieSync())) return { ok: false, why: "watcher not current" };
90
93
  if (req.op === "begin") return { ok: true, generation: generation.get(key) ?? 0 };
94
+ if (req.op === "cargo-metadata") return cargoMetadataOp(req, key, real);
91
95
  if (req.op === "record") {
92
96
  if (typeof req.tree !== "string" || !Number.isInteger(req.generation)) return { ok: false, why: "bad record" };
93
97
  if ((generation.get(key) ?? 0) !== req.generation) return { ok: false, why: "changed during the proof" };
@@ -102,7 +106,37 @@ export async function serve({ root, idleMs = Number(process.env.RK_GATE_SERVE_ID
102
106
  }
103
107
  return { ok: false, why: "unknown op" };
104
108
  };
109
+ async function cargoMetadataOp(req, key, snapshotDir) {
110
+ const args = Array.isArray(req.args) ? req.args.map(String) : null;
111
+ if (!args || args[0] !== "metadata") return { ok: false, why: "only cargo metadata is served" };
112
+ if (typeof req.cargo !== "string" || !path.isAbsolute(req.cargo) || typeof req.cwd !== "string") return { ok: false, why: "bad cargo request" };
113
+ let cwd; try { cwd = fs.realpathSync(req.cwd); } catch { return { ok: false, why: "no such cwd" }; }
114
+ if (cwd !== snapshotDir && !cwd.startsWith(`${snapshotDir}${path.sep}`)) return { ok: false, why: "cwd outside the snapshot" };
115
+ const env = req.env && typeof req.env === "object" ? Object.fromEntries(Object.entries(req.env).map(([k, v]) => [k, String(v)])) : {};
116
+ let cargoId; try { const st = fs.statSync(req.cargo); cargoId = `${st.size}:${st.mtimeMs}:${st.ino}`; } catch { return { ok: false, why: "no such cargo" }; }
117
+ const digest = crypto.createHash("sha256").update(JSON.stringify({ key, cwd, args, cargo: req.cargo, cargoId, env: Object.entries(env).sort() })).digest("hex");
118
+ const hit = cargoAnswers.get(digest);
119
+ const now = generation.get(key) ?? 0;
120
+ if (hit && hit.generation === now) return { ok: true, cached: true, status: hit.status, stdout: hit.stdout, stderr: hit.stderr };
121
+ const before = now;
122
+ const result = await new Promise((resolve) => {
123
+ let child; try { child = spawn(req.cargo, args, { cwd, env, stdio: ["ignore", "pipe", "pipe"], windowsHide: true }); } catch (error) { resolve({ status: -1, stdout: "", stderr: String(error?.message ?? error) }); return; }
124
+ const out = []; const err = [];
125
+ child.stdout.on("data", (d) => out.push(d)); child.stderr.on("data", (d) => err.push(d));
126
+ child.on("error", (error) => resolve({ status: -1, stdout: "", stderr: String(error?.message ?? error) }));
127
+ child.on("close", (status) => resolve({ status: status ?? -1, stdout: Buffer.concat(out).toString("utf8"), stderr: Buffer.concat(err).toString("utf8") }));
128
+ });
129
+ // Cached only when cargo succeeded and nothing in the snapshot changed while it ran (the cookie makes every earlier event visible first).
130
+ if (result.status === 0 && (await cookieSync()) && (generation.get(key) ?? 0) === before) {
131
+ cargoAnswers.set(digest, { key, generation: before, ...result });
132
+ while (cargoAnswers.size > 64) cargoAnswers.delete(cargoAnswers.keys().next().value);
133
+ }
134
+ return { ok: true, cached: false, ...result };
135
+ }
105
136
  const sock = socketPath();
137
+ // One server per host: a second one started in the same instant must not steal the socket from a live first one (seen 2026-11-05).
138
+ const live = await new Promise((resolve) => { const c = net.connect(sock); c.on("connect", () => { c.destroy(); resolve(true); }); c.on("error", () => resolve(false)); });
139
+ if (live) { log("another server already answers on the socket; exiting"); process.exit(0); }
106
140
  if (process.platform !== "win32") { fs.mkdirSync(path.dirname(sock), { recursive: true }); try { fs.unlinkSync(sock); } catch { /* none */ } }
107
141
  const server = net.createServer((conn) => {
108
142
  let buf = "";
@@ -119,7 +153,12 @@ export async function serve({ root, idleMs = Number(process.env.RK_GATE_SERVE_ID
119
153
  });
120
154
  await new Promise((resolve, reject) => { server.once("error", reject); server.listen(sock, resolve); });
121
155
  log(`serving ${watchedRoot} on ${sock} (pid ${process.pid}, identity ${IDENTITY})`);
122
- const idle = setInterval(() => { if (Date.now() - lastRequest > idleMs) { log("idle; exiting"); process.exit(0); } }, 10_000);
156
+ // Exit when idle, or as soon as the socket is no longer this server's (another server replaced it): no orphan lingers.
157
+ let sockIno = null; try { sockIno = fs.statSync(sock).ino; } catch { sockIno = null; }
158
+ const idle = setInterval(() => {
159
+ if (Date.now() - lastRequest > idleMs) { log("idle; exiting"); process.exit(0); }
160
+ if (process.platform !== "win32") { let ino = null; try { ino = fs.statSync(sock).ino; } catch { ino = null; } if (ino !== sockIno) { log("socket replaced; exiting"); process.exit(0); } }
161
+ }, 10_000);
123
162
  idle.unref?.();
124
163
  return server;
125
164
  }
@@ -141,9 +180,10 @@ async function ask(req, timeoutMs) {
141
180
  /** One synchronous request to the resident server; null when it is disabled, unreachable or did not answer. Starts it when absent. */
142
181
  export function serveRequest(req, { env = process.env, root = null, timeoutMs = 3000 } = {}) {
143
182
  if (env.RK_GATE_SERVE === "0") return null;
144
- const r = spawnSync(process.execPath, [SELF, "ask", JSON.stringify(req), String(timeoutMs)], { encoding: "utf8", timeout: timeoutMs + 2000, env: { ...env } });
183
+ const r = spawnSync(process.execPath, [SELF, "ask", JSON.stringify(req), String(timeoutMs)], { encoding: "utf8", timeout: timeoutMs + 2000, maxBuffer: 1 << 28, env: { ...env } });
145
184
  let res = null; try { res = JSON.parse(String(r.stdout ?? "").trim().split("\n").pop()); } catch { res = null; }
146
- if ((!res || res.unreachable) && root) startServer({ root, env });
185
+ // Start a server only when none is listening; a bad reply or a timeout from a live one never starts a second.
186
+ if (res?.unreachable && root) startServer({ root, env });
147
187
  return res && res.ok ? res : null;
148
188
  }
149
189
 
@@ -162,6 +202,27 @@ function startServer({ root, env }) {
162
202
  } catch { /* the next run tries again; this one verifies in full */ }
163
203
  }
164
204
 
205
+ /**
206
+ * GC-A11 `cargo metadata` for a directory inside a gate snapshot, answered by the resident gate (cached per snapshot while it is unchanged), else
207
+ * run directly with `cargo` (an absolute path) and `env`. Returns `{ status, stdout, stderr, served, cached }`. Never through the broker.
208
+ */
209
+ export function snapshotCargoMetadata({ cwd, args, cargo, env, snapshotRootDir, run = spawnSync }) {
210
+ let snapshotDir = null;
211
+ try {
212
+ const realRoot = fs.realpathSync(snapshotRootDir); const realCwd = fs.realpathSync(cwd);
213
+ const rel = path.relative(realRoot, realCwd);
214
+ const first = rel.split(path.sep)[0];
215
+ if (rel && !rel.startsWith("..") && !path.isAbsolute(rel) && /^[0-9a-f]{16}$/.test(first)) snapshotDir = path.join(realRoot, first);
216
+ } catch { snapshotDir = null; }
217
+ if (snapshotDir && cargo) {
218
+ const keep = Object.fromEntries(Object.entries(env ?? {}).filter(([k]) => /^(PATH|Path|HOME|USERPROFILE|SYSTEMROOT|SystemRoot|TMPDIR|TEMP|TMP|CARGO.*|RUSTUP.*|RUSTC.*|RUSTFLAGS|RUSTDOCFLAGS)$/.test(k)));
219
+ const res = serveRequest({ op: "cargo-metadata", dir: snapshotDir, cwd, args, cargo, env: keep }, { env, root: snapshotRootDir, timeoutMs: 120_000 });
220
+ if (res && Number.isInteger(res.status)) return { status: res.status, stdout: res.stdout ?? "", stderr: res.stderr ?? "", served: true, cached: res.cached === true };
221
+ }
222
+ const r = run(cargo ?? "cargo", args, { cwd, env, encoding: "utf8", maxBuffer: 1 << 28 });
223
+ return { status: r.status, stdout: String(r.stdout ?? ""), stderr: String(r.stderr ?? ""), served: false, cached: false };
224
+ }
225
+
165
226
  // ---- entry --------------------------------------------------------------------------------------------------------------------------------
166
227
 
167
228
  if (process.argv[1] && fs.realpathSync(process.argv[1]) === fs.realpathSync(SELF)) {
@@ -170,7 +231,8 @@ if (process.argv[1] && fs.realpathSync(process.argv[1]) === fs.realpathSync(SELF
170
231
  serve({ root: a, log: (m) => console.log(`${new Date().toISOString()} gate-serve: ${m}`) }).catch((error) => { console.log(`${new Date().toISOString()} gate-serve: cannot serve: ${error?.message ?? error}`); process.exit(1); });
171
232
  } else if (cmd === "ask") {
172
233
  let req = null; try { req = JSON.parse(a); } catch { req = null; }
173
- ask(req ?? {}, Number(b) || 3000).then((res) => { process.stdout.write(`${JSON.stringify(res)}\n`); process.exit(0); });
234
+ // Exit only after the reply is flushed: process.exit right after a large write to a pipe truncates it (a cargo metadata answer is megabytes).
235
+ ask(req ?? {}, Number(b) || 3000).then((res) => { process.stdout.write(`${JSON.stringify(res)}\n`, () => process.exit(0)); });
174
236
  } else if (cmd === "status") {
175
237
  ask({ op: "status" }, 3000).then((res) => { console.log(JSON.stringify(res, null, 2)); process.exit(res.ok ? 0 : 1); });
176
238
  } else { console.error("usage: gate-serve.mjs serve <snapshot-root> | status"); process.exit(2); }
@@ -0,0 +1,100 @@
1
+ // GB-21/23/57 additive branch (rustright#228, rightkit#1511): a broker-signed revocation of ONE exact sub-handle whose lease the broker can no longer
2
+ // answer (UNKNOWN, no member row). It settles that sub-handle for a dead owner's reclaim only. It never stands in for REAPED or UNSENT, never
3
+ // overrides an ACTIVE lease or a listed member, and never releases a live owner: every other reclaim proof (owner pid, sibling sub-handles,
4
+ // detached groups, token holders, snapshot users) still runs unchanged.
5
+ //
6
+ // Trust: the host's ENROLLED broker pin only (broker-pins.mjs readEnrolledPins), never the revocation, the record, an environment variable or a
7
+ // checkout. The signature scheme is the broker's provenance scheme (ES256, P-256, canonical JSON) under its own domain string, so a receipt can
8
+ // never be replayed as a revocation, or the reverse.
9
+ //
10
+ // Location: exactly `<data root>/snapshot-leases/completed/<name>` (no suffix), where name is the lowercase SHA-256 of the canonical JSON array
11
+ // [snapshot, ownership]: the broker's own f227 completion key for that sub-handle, so the revocation also fences legacy exact-handle reuse (Terra,
12
+ // 2026-11-05). One file, read, authenticated and reread there; no sidecar. A file there with another schema (a legacy completion) is not a revocation
13
+ // and is ignored here; a link or a non-file refuses.
14
+ import { createHash, createPublicKey, verify } from "node:crypto";
15
+ import fs from "node:fs";
16
+ import path from "node:path";
17
+ import { canonicalJson } from "./provenance-verify.mjs";
18
+
19
+ export const REVOCATION_SCHEMA = "rustright.snapshot-revocation.v1";
20
+ export const REVOCATION_DOMAIN = "rustright-snapshot-revocation-v1";
21
+ export const REVOCATION_DIR = path.join("snapshot-leases", "completed");
22
+ /** The signed payload's fields, exactly (Terra's proposal, 2026-11-05; not frozen until the shared golden fixture agrees). */
23
+ export const REVOCATION_FIELDS = Object.freeze(["dataRoot", "host", "keyId", "ownerFile", "ownerSha256", "ownership", "proofSha256", "runtime", "schema", "snapshot"]);
24
+ const SHA = /^[0-9a-f]{64}$/;
25
+
26
+ export class RevocationError extends Error {
27
+ constructor(code, message) { super(message); this.name = "RevocationError"; this.code = code; }
28
+ }
29
+ const refuse = (code, message) => { throw new RevocationError(code, message); };
30
+ const sha256Hex = (data) => createHash("sha256").update(data).digest("hex");
31
+ const isRecord = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
32
+ const ID = /^[A-Za-z0-9._-]+$/;
33
+
34
+ /** The exact bytes the broker signs for a revocation payload. */
35
+ export const revocationSignedBytes = (payload) => Buffer.from(`${REVOCATION_DOMAIN}\n${canonicalJson(payload)}`, "utf8");
36
+
37
+ /** The f227 completion name of one sub-handle of one snapshot: lowercase SHA-256 of canonical JSON `[snapshot, ownership]`. */
38
+ export const revocationName = (snapshot, ownership) => sha256Hex(Buffer.from(canonicalJson([snapshot, ownership]), "utf8"));
39
+
40
+ /** The one path a revocation of `sub` (`<ownerHandle>#<id>`) of `snapshot` may live at under the managed data root `dataRoot`. */
41
+ export function revocationFile(dataRoot, ownerHandle, sub, snapshot) {
42
+ if (typeof ownerHandle !== "string" || !ID.test(ownerHandle)) refuse("handle", `${JSON.stringify(ownerHandle)} is not an owner handle`);
43
+ if (typeof sub !== "string" || !sub.startsWith(`${ownerHandle}#`) || !ID.test(sub.slice(ownerHandle.length + 1))) refuse("handle", `${JSON.stringify(sub)} is not a sub-handle of ${ownerHandle}`);
44
+ if (typeof snapshot !== "string" || !path.isAbsolute(snapshot)) refuse("root", "the owner record names no absolute snapshot");
45
+ if (typeof dataRoot !== "string" || !path.isAbsolute(dataRoot)) refuse("root", "the managed data root is not absolute");
46
+ return path.join(dataRoot, REVOCATION_DIR, revocationName(snapshot, sub));
47
+ }
48
+
49
+ /** The revocation's bytes, or null when none exists. A link, a directory or an unreadable entry is a refusal, never null. */
50
+ export function readRevocation(file) {
51
+ let meta;
52
+ try { meta = fs.lstatSync(file); } catch (e) { if (e.code === "ENOENT") return null; return refuse("read", `${file} cannot be read (${e.code ?? e.message})`); }
53
+ if (!meta.isFile()) refuse("read", `${file} is not a plain file`);
54
+ return fs.readFileSync(file);
55
+ }
56
+
57
+ /** Whether `bytes` claim to be a snapshot revocation at all (its envelope schema); anything else at the completion key is the broker's own record. */
58
+ export function isRevocationEnvelope(bytes) {
59
+ try { return JSON.parse(Buffer.isBuffer(bytes) ? bytes.toString("utf8") : String(bytes))?.schema === REVOCATION_SCHEMA; } catch { return false; }
60
+ }
61
+
62
+ const publicKeyOf = (hex) => {
63
+ const bytes = Buffer.from(hex, "hex");
64
+ if (bytes.length !== 65 || bytes[0] !== 0x04) refuse("pin", "the pinned public key is not an uncompressed SEC1 P-256 point");
65
+ return createPublicKey({ key: { kty: "EC", crv: "P-256", x: bytes.subarray(1, 33).toString("base64url"), y: bytes.subarray(33, 65).toString("base64url") }, format: "jwk" });
66
+ };
67
+
68
+ /**
69
+ * Verifies `bytes` as the broker's revocation of exactly `sub` for exactly this owner record. Returns the signed payload; throws RevocationError
70
+ * (stable `code`) on any mismatch.
71
+ * pins: the host's enrolled `{ host, keyId, publicKey, brokerDigest }`
72
+ * expected: { ownerFile, dataRoot (both canonical, realpath), ownerBytes (the record bytes the reclaim judged), owner (parsed), sub }
73
+ */
74
+ export function verifyRevocation(bytes, pins, { ownerFile, dataRoot, ownerBytes, owner, sub }) {
75
+ let envelope = null;
76
+ try { envelope = JSON.parse(Buffer.isBuffer(bytes) ? bytes.toString("utf8") : String(bytes)); } catch { envelope = null; }
77
+ if (!isRecord(envelope) || envelope.schema !== REVOCATION_SCHEMA) refuse("schema", "not a handle revocation");
78
+ const { payload, signature } = envelope;
79
+ if (!isRecord(payload) || !isRecord(signature)) refuse("malformed", "payload or signature is missing");
80
+ if (signature.alg !== "ES256") refuse("alg", "signature algorithm must be ES256");
81
+ if (!isRecord(pins) || typeof pins.publicKey !== "string" || sha256Hex(Buffer.from(pins.publicKey, "hex")) !== pins.keyId) refuse("pin", "the pinned key id does not match the pinned public key");
82
+ if (signature.keyId !== pins.keyId || payload.keyId !== pins.keyId) refuse("key", "not signed by the pinned broker key");
83
+ if (typeof signature.value !== "string" || !/^[0-9a-fA-F]{128}$/.test(signature.value)) refuse("signature", "signature is not 64 bytes r||s in hex");
84
+ let good = false;
85
+ try { good = verify("sha256", revocationSignedBytes(payload), { key: publicKeyOf(pins.publicKey), dsaEncoding: "ieee-p1363" }, Buffer.from(signature.value, "hex")); } catch (e) { if (e instanceof RevocationError) throw e; }
86
+ if (!good) refuse("signature", "signature does not verify");
87
+ // Everything below is signed: exactly these fields, bound to this host's broker runtime, this exact record's bytes, its snapshot and this exact sub-handle.
88
+ const fields = Object.keys(payload).sort();
89
+ if (JSON.stringify(fields) !== JSON.stringify(REVOCATION_FIELDS)) refuse("malformed", `the payload carries ${fields.join(", ")}, not exactly ${REVOCATION_FIELDS.join(", ")}`);
90
+ if (payload.schema !== REVOCATION_SCHEMA) refuse("schema", "the signed payload is not a snapshot revocation");
91
+ if (payload.host !== pins.host) refuse("host", "signed for another host");
92
+ if (!isRecord(payload.runtime) || JSON.stringify(Object.keys(payload.runtime)) !== '["brokerDigest"]' || payload.runtime.brokerDigest !== pins.brokerDigest) refuse("runtime", "signed by another broker runtime");
93
+ if (payload.dataRoot !== dataRoot) refuse("root", "revokes a sub-handle under another managed data root");
94
+ if (payload.ownerFile !== ownerFile) refuse("root", "revokes a sub-handle of another ownership record");
95
+ if (payload.snapshot !== owner.snapshot) refuse("root", "revokes a sub-handle of another snapshot");
96
+ if (payload.ownership !== sub) refuse("handle", `revokes ${payload.ownership}, not ${sub}`);
97
+ if (payload.ownerSha256 !== sha256Hex(ownerBytes)) refuse("owner", "signed over other owner record bytes (the record changed, or it is another record)");
98
+ if (typeof payload.proofSha256 !== "string" || !SHA.test(payload.proofSha256)) refuse("proof", "proofSha256 is not a lowercase SHA-256");
99
+ return payload;
100
+ }
@@ -0,0 +1 @@
1
+ {"envelope":{"payload":{"dataRoot":"/Volumes/D/.rightkit-managed","host":"fixture-host","keyId":"698bea63dc44a344663ff1429aea10842df27b6b991ef25866b2c6c02cdcc5be","ownerFile":"/Volumes/D/.rightkit-managed/build-ownership/770a65dcafd91981/owner.json","ownerSha256":"be6603d17ef691daaece03448790d3927c98d606a6576d105fbe6bfcc467a5a5","ownership":"26e12157-e275-4bfd-95a2-f1ff48f56e50#bf51a9c8-2f5d-4b80-9fa4-72a0be202da8","proofSha256":"dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd","runtime":{"brokerDigest":"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"},"schema":"rustright.snapshot-revocation.v1","snapshot":"/Volumes/D/.rightkit-managed/snapshots/770a65dcafd91981"},"schema":"rustright.snapshot-revocation.v1","signature":{"alg":"ES256","keyId":"698bea63dc44a344663ff1429aea10842df27b6b991ef25866b2c6c02cdcc5be","value":"3f5fcdd39de47815032dcb4ba074b50a8e91d58cec8e0b89a234fc5a4e9fddf8a6769c4be9099afe62b87cf9e73464a0f3c532fcfab6cb23714f05d800ac8a9a"}},"pins":{"brokerDigest":"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb","host":"fixture-host","keyId":"698bea63dc44a344663ff1429aea10842df27b6b991ef25866b2c6c02cdcc5be","publicKey":"046b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c2964fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"}}
@@ -0,0 +1,53 @@
1
+ {
2
+ "schema": "rightkit.revocation-vectors/1",
3
+ "note": "rightkit#1511 / rustright#228 shared golden fixture. TEST KEY ONLY: never enrolled, never a broker key. Status: proposal, not frozen.",
4
+ "domain": "rustright-snapshot-revocation-v1",
5
+ "pins": {
6
+ "host": "fixture-host",
7
+ "keyId": "588caca3ea3415184feb9075c98ec15d92b0ed9aae918b27eff229f77cada0cc",
8
+ "publicKey": "04c51817454bc646c6b036d7c1ff156f4e2e2938173bbf5b00da7387f44f95e3f7f21c0fff3995ccd03c3c1985dcc12b483e85b37e3793e6da4e3529245f02b86a",
9
+ "brokerDigest": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
10
+ },
11
+ "ownerBytes": "{\"schema\":\"rightkit.build-ownership/1\",\"handle\":\"26e12157-e275-4bfd-95a2-f1ff48f56e50\",\"host\":\"fixture-host\",\"pid\":4242,\"snapshot\":\"/Volumes/D/.rightkit-managed/snapshots/770a65dcafd91981\"}",
12
+ "payload": {
13
+ "schema": "rustright.snapshot-revocation.v1",
14
+ "keyId": "588caca3ea3415184feb9075c98ec15d92b0ed9aae918b27eff229f77cada0cc",
15
+ "host": "fixture-host",
16
+ "runtime": {
17
+ "brokerDigest": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
18
+ },
19
+ "snapshot": "/Volumes/D/.rightkit-managed/snapshots/770a65dcafd91981",
20
+ "ownership": "26e12157-e275-4bfd-95a2-f1ff48f56e50#bf51a9c8-2f5d-4b80-9fa4-72a0be202da8",
21
+ "dataRoot": "/Volumes/D/.rightkit-managed",
22
+ "ownerFile": "/Volumes/D/.rightkit-managed/build-ownership/770a65dcafd91981/owner.json",
23
+ "ownerSha256": "be6603d17ef691daaece03448790d3927c98d606a6576d105fbe6bfcc467a5a5",
24
+ "proofSha256": "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd"
25
+ },
26
+ "signedBytesUtf8": "rustright-snapshot-revocation-v1\n{\"dataRoot\":\"/Volumes/D/.rightkit-managed\",\"host\":\"fixture-host\",\"keyId\":\"588caca3ea3415184feb9075c98ec15d92b0ed9aae918b27eff229f77cada0cc\",\"ownerFile\":\"/Volumes/D/.rightkit-managed/build-ownership/770a65dcafd91981/owner.json\",\"ownerSha256\":\"be6603d17ef691daaece03448790d3927c98d606a6576d105fbe6bfcc467a5a5\",\"ownership\":\"26e12157-e275-4bfd-95a2-f1ff48f56e50#bf51a9c8-2f5d-4b80-9fa4-72a0be202da8\",\"proofSha256\":\"dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd\",\"runtime\":{\"brokerDigest\":\"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"},\"schema\":\"rustright.snapshot-revocation.v1\",\"snapshot\":\"/Volumes/D/.rightkit-managed/snapshots/770a65dcafd91981\"}",
27
+ "signedBytesSha256": "61fd2ace1fa136a1e5dc77fb9c23fa0eca8d9079cc2288a21d7553c39d692623",
28
+ "fileNameInput": "[\"/Volumes/D/.rightkit-managed/snapshots/770a65dcafd91981\",\"26e12157-e275-4bfd-95a2-f1ff48f56e50#bf51a9c8-2f5d-4b80-9fa4-72a0be202da8\"]",
29
+ "fileName": "bf1857c7d0d283fdacc8d62dc941ef413ad234c1dbed42dcc55825e9e4d93cb4",
30
+ "expectedPath": "/Volumes/D/.rightkit-managed/snapshot-leases/completed/bf1857c7d0d283fdacc8d62dc941ef413ad234c1dbed42dcc55825e9e4d93cb4",
31
+ "envelope": {
32
+ "schema": "rustright.snapshot-revocation.v1",
33
+ "payload": {
34
+ "schema": "rustright.snapshot-revocation.v1",
35
+ "keyId": "588caca3ea3415184feb9075c98ec15d92b0ed9aae918b27eff229f77cada0cc",
36
+ "host": "fixture-host",
37
+ "runtime": {
38
+ "brokerDigest": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
39
+ },
40
+ "snapshot": "/Volumes/D/.rightkit-managed/snapshots/770a65dcafd91981",
41
+ "ownership": "26e12157-e275-4bfd-95a2-f1ff48f56e50#bf51a9c8-2f5d-4b80-9fa4-72a0be202da8",
42
+ "dataRoot": "/Volumes/D/.rightkit-managed",
43
+ "ownerFile": "/Volumes/D/.rightkit-managed/build-ownership/770a65dcafd91981/owner.json",
44
+ "ownerSha256": "be6603d17ef691daaece03448790d3927c98d606a6576d105fbe6bfcc467a5a5",
45
+ "proofSha256": "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd"
46
+ },
47
+ "signature": {
48
+ "alg": "ES256",
49
+ "keyId": "588caca3ea3415184feb9075c98ec15d92b0ed9aae918b27eff229f77cada0cc",
50
+ "value": "dbd7e96246ce60b3393cd544bb3d1368bbdfe0b99083cf6fd235458ff4df6de21cad283712ec51769c0486c8af164cca72d20eb61a8377c5b40db28475c1face"
51
+ }
52
+ }
53
+ }
package/local-publish.mjs CHANGED
@@ -479,7 +479,7 @@ export function localTestPlan({ kind, unit, dir, config, manifest, batch = false
479
479
  }
480
480
 
481
481
  /** Publisher compile-stage obligations. Caller supplies authenticated source policy and execution environment. */
482
- export function compileRequirements({ kind, unit, dir, config, manifest, platform = "darwin", workspace, env, assetGated = {}, allowIgnored = false, allowIgnoredUnits = [], jobs }) {
482
+ export function compileRequirements({ kind, unit, dir, config, manifest, platform = "darwin", workspace, env, assetGated = {}, allowIgnored = false, allowIgnoredUnits = [], jobs, formatProven = false }) {
483
483
  if (kind !== "cargo" && kind !== "npm") throw new Error(`unsupported compile requirement kind ${kind}`);
484
484
  if (kind === "cargo" && (typeof workspace !== "string" || !workspace)) throw new Error("authenticated Cargo workspace is required");
485
485
  if (!env || typeof env !== "object" || Array.isArray(env)) throw new Error("publisher execution environment is required");
@@ -490,7 +490,9 @@ export function compileRequirements({ kind, unit, dir, config, manifest, platfor
490
490
  const configReason = kind === "cargo" && typeof config?.rust?.[unit]?.allowIgnored === "string" ? config.rust[unit].allowIgnored.trim() : "";
491
491
  const ignoredAllowed = Boolean(allowIgnored || allowIgnoredUnits.includes(unit) || configReason);
492
492
  const steps = [...plan.steps];
493
- if (kind === "cargo") steps.unshift({ command: "cargo", args: qualifyFmtArgs(unit), test: false });
493
+ // A gate run that already passed class A's rustfmt rows over every Rust file of this same snapshot passes formatProven: the crate's own
494
+ // `cargo fmt -p <crate> --check` would repeat that check, one crate at a time (a 140-crate unit list spent minutes on it, 2026-11-05).
495
+ if (kind === "cargo" && !formatProven) steps.unshift({ command: "cargo", args: qualifyFmtArgs(unit), test: false });
494
496
  const requirements = [];
495
497
  const add = (requirement) => requirements.push({ id: `publisher:${kind}:${unit}:${requirements.length}`, ...requirement, coverageKey: sha256(JSON.stringify(requirement)) });
496
498
  if (kind === "cargo") add({ workspace, cwd: dir, executable: null, internal: "scanCrateForSecrets", argv: [dir], env: {}, phase: "check" });
package/managed-cargo.mjs CHANGED
@@ -202,6 +202,17 @@ export function directCargoPath({ env = process.env, exists = existsSync, readHe
202
202
  return { path: kept.join(win ? ";" : ":"), dropped, cargo };
203
203
  }
204
204
 
205
+ /**
206
+ * GC-A11 (Adrian, 2026-11-02: "Class a never in the broker. Any cargo things that are cheap and non compiling are in class a, can run outside the
207
+ * broker"): the environment for a NON-COMPILING cargo call (metadata, locate-project, tree, package --no-verify) on any host: PATH with the broker's
208
+ * own toolchain first and every RustRight shim dropped, so `cargo` is the real binary. The broker refuses such a request from inside a snapshot.
209
+ */
210
+ export function nonCompilingCargoEnv(env = process.env, platform = process.platform) {
211
+ const pathKey = platform === "win32" ? (Object.keys(env).find((k) => k.toUpperCase() === "PATH") ?? "Path") : "PATH";
212
+ const direct = directCargoPath({ env: { ...env, PATH: env[pathKey] }, platform, gateWrappers: true });
213
+ return { ...env, [pathKey]: direct.path };
214
+ }
215
+
205
216
  /** `env` for a direct host: PATH without RustRight shim directories. Unchanged on Mac, Windows and a declared Linux broker route. */
206
217
  export function directCargoEnv(env = process.env, platform = process.platform, exists = existsSync) {
207
218
  if (!directHost(platform, env)) return env; // Mac, Windows, and a Linux host that declared a broker route (no direct cargo there)
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env node
2
+ // rightkit#1511: prints the process-only proof of one dead owner record as JSON (build-ownership.mjs proveOwnerProcessesGone). Writes nothing.
3
+ // usage: node owner-process-proof.mjs <managed root>/build-ownership/<key>/owner.json
4
+ // exit 0 with the proof on stdout; exit 2 with the reason on stderr when a process is still live or unknown; exit 64 on bad usage.
5
+ import { proveOwnerProcessesGone } from "./build-ownership.mjs";
6
+
7
+ const file = process.argv[2];
8
+ if (!file || process.argv.length !== 3) { process.stderr.write("usage: owner-process-proof.mjs <owner.json>\n"); process.exit(64); }
9
+ try {
10
+ process.stdout.write(`${JSON.stringify(proveOwnerProcessesGone({ file }), null, 2)}\n`);
11
+ } catch (e) {
12
+ process.stderr.write(`${e.message}\n`);
13
+ process.exit(2);
14
+ }
@@ -29,6 +29,9 @@ export function holds(file, handle) {
29
29
  * while it is still this handle's, under a short lock beside the record (carried calls of parallel children, in other
30
30
  * processes, mark the same record).
31
31
  */
32
+ /** The row id a caller names, else this process's command line (no environment), cut to 240 characters. */
33
+ const carryNote = (note) => (typeof note === "string" && note ? note : process.argv.slice(1).join(" ")).slice(0, 240);
34
+
32
35
  export function markBrokerSubmit(file, handle, callHandle, options = {}) {
33
36
  if (typeof callHandle !== "string" || callHandle.length <= handle.length + 1 || !callHandle.startsWith(`${handle}#`) || !/^[A-Za-z0-9._-]+$/.test(callHandle.slice(handle.length + 1))) {
34
37
  throw new OwnershipBusy(`build ownership ${file}: a broker submit is recorded only for a carried request's sub-handle of ${handle} (<handle>#<id>), not ${JSON.stringify(callHandle ?? null)}`);
@@ -39,7 +42,10 @@ export function markBrokerSubmit(file, handle, callHandle, options = {}) {
39
42
  if (owner?.handle !== handle) throw new OwnershipBusy(`build ownership ${file} is no longer held by ${handle}; no broker request may be submitted`);
40
43
  const seen = Array.isArray(owner.broker?.handles) ? owner.broker.handles : [];
41
44
  if (owner.broker?.submitted && seen.includes(callHandle)) return owner;
42
- const next = { ...owner, broker: { ...(owner.broker ?? {}), submitted: true, at: owner.broker?.at ?? new Date().toISOString(), handles: [...seen, callHandle] } };
45
+ // rightkit#1510: which process and which row or command carried each sub-handle, so a sub-handle left UNKNOWN can be traced to its
46
+ // request. Diagnostic only: no reclaim proof reads it, and handle order never maps concurrent rows.
47
+ const sent = { ...(owner.broker?.sent ?? {}), [callHandle]: { at: new Date().toISOString(), pid: process.pid, note: carryNote(options.note) } };
48
+ const next = { ...owner, broker: { ...(owner.broker ?? {}), submitted: true, at: owner.broker?.at ?? new Date().toISOString(), handles: [...seen, callHandle], sent } };
43
49
  const tmp = `${file}.${crypto.randomUUID()}.tmp`;
44
50
  fs.writeFileSync(tmp, JSON.stringify(next), { flag: "wx", mode: 0o600 });
45
51
  try { fs.renameSync(tmp, file); } finally { fs.rmSync(tmp, { force: true }); }
@@ -102,6 +108,9 @@ export function judgeLockHolder(rec, { identity, host = os.hostname() }) {
102
108
  }
103
109
 
104
110
  /** Creates `target` holding `record` atomically and exclusively: the content is complete the moment the name exists (write a temp file, hard-link it). */
111
+ /** Whether `text` is a well-formed mark lock. A lock is published only fully written (createExclusive links a complete file), so an unreadable one is crash debris. */
112
+ export const isMarkLockText = (text) => parseLock(text ?? "") !== null;
113
+
105
114
  function createExclusive(target, record) {
106
115
  const tmp = `${target}.${record.nonce}.tmp`;
107
116
  fs.writeFileSync(tmp, JSON.stringify(record), { flag: "wx", mode: 0o600 });
@@ -0,0 +1,78 @@
1
+ #!/usr/bin/env node
2
+ // Recovery for a build-ownership record left by a gate that died or was stopped (rightkit#1513; Adrian, 2026-11-05: "have proper recovery
3
+ // tools for the fucking gate. This recovery avoidance is wrong"; "It should ideally auto recover").
4
+ // The gate's own reclaim recovers automatically (build-ownership.mjs coveredWorkGone): a sub-handle the broker answers UNKNOWN with no member
5
+ // row was never received when the same broker process has run since before the ownership was acquired and no process of the run remains.
6
+ // This tool explains a held record (processes, broker leases, every sub-handle) and, with --apply, runs that reclaim now and releases.
7
+ //
8
+ // node ownership-recover.mjs <owner.json> [--apply] [--wait-ms N]
9
+ // Dry run by default: prints the evidence and the plan, changes nothing. Exit 0 recovered (or nothing to do / plan clean), 2 refused, 64 usage.
10
+ import { spawnSync } from "node:child_process";
11
+ import fs from "node:fs";
12
+ import { fileURLToPath } from "node:url";
13
+ import { acquireBuildOwnership, brokerLeaseState, proveOwnerProcessesGone, runningBrokerProcess } from "./build-ownership.mjs";
14
+
15
+ const SETTLE_MS = 2000;
16
+
17
+ export async function recover({ file, apply = false, waitMs = 600_000, log = console.log, lease = brokerLeaseState, broker = () => runningBrokerProcess(), sleep = (ms) => new Promise((r) => setTimeout(r, ms)) }) {
18
+ const text = (() => { try { return fs.readFileSync(file, "utf8"); } catch (e) { if (e.code === "ENOENT") return null; throw e; } })();
19
+ if (text === null) { log(`recover: ${file}: no record; nothing to recover`); return 0; }
20
+ const owner = JSON.parse(text);
21
+ log(`recover: ${file}: held by ${owner.handle} (pid ${owner.pid}, ${owner.stage ?? "stage"} of ${owner.commit ?? "a commit"}) since ${owner.acquiredAt}`);
22
+
23
+ // 1. Processes: the owner and everything of its run are gone (the reclaim's own process proof, no broker judged).
24
+ let proof;
25
+ try { proof = proveOwnerProcessesGone({ file }); } catch (e) { log(`recover: REFUSED: ${e.message}`); return 2; }
26
+ for (const p of proof.proofs) log(` process: ${p}`);
27
+
28
+ // 2. Broker: every submission settled. Wait for ACTIVE work of the dead run to finish (a stopped gate leaves its last broker jobs running).
29
+ const subs = [...new Set(Array.isArray(owner.broker?.handles) ? owner.broker.handles : [])];
30
+ const unsent = owner.broker?.unsent ?? {};
31
+ const deadline = Date.now() + waitMs;
32
+ let ownerLease;
33
+ for (;;) {
34
+ ownerLease = lease({ snapshot: owner.snapshot, handle: owner.handle });
35
+ if (ownerLease.state !== "ACTIVE") break;
36
+ if (Date.now() > deadline) { log(`recover: REFUSED: broker work under ${owner.handle} is still ACTIVE after ${Math.round(waitMs / 1000)} s`); return 2; }
37
+ log(` broker: ${owner.handle} ACTIVE; waiting`); await sleep(5000);
38
+ }
39
+ log(` broker: owner lease ${ownerLease.state} (${(ownerLease.members ?? []).length} member row(s))`);
40
+ if (!subs.length || !owner.broker?.submitted) log(" broker: no carried request was recorded");
41
+
42
+ const brk = broker();
43
+ const acquiredMs = Date.parse(owner.acquiredAt);
44
+ const brokerSawAll = Boolean(brk && Number.isFinite(acquiredMs) && brk.startedMs + SETTLE_MS < acquiredMs);
45
+ log(` broker process: ${brk ? `pid ${brk.pid} up since ${new Date(brk.startedMs).toISOString()}` : "not established"}; ${brokerSawAll ? "continuously up since before this ownership" : "NOT shown up since before this ownership"}`);
46
+
47
+ const toMark = []; const refused = []; let reaped = 0;
48
+ for (const sub of subs) {
49
+ if (unsent[sub]) continue;
50
+ const one = lease({ snapshot: owner.snapshot, handle: sub });
51
+ const listed = (ownerLease.members ?? []).find((m) => m.handle === sub);
52
+ if (one.state === "REAPED") { reaped += 1; continue; }
53
+ if (one.state === "ACTIVE" || (listed && listed.state !== "REAPED")) { refused.push(`${sub}: ${one.state}${listed ? ` (listed ${listed.state})` : ""}`); continue; }
54
+ if (one.state === "UNKNOWN" && Array.isArray(one.members) && one.members.length === 0 && !listed && brokerSawAll) { toMark.push(sub); continue; }
55
+ refused.push(`${sub}: ${one.state} (${one.why ?? ""})${brokerSawAll ? "" : "; the broker was not up throughout, so UNKNOWN proves nothing"}`);
56
+ }
57
+ log(` sub-handles: ${subs.length} recorded, ${reaped} REAPED, ${Object.keys(unsent).length} already marked unsent, ${toMark.length} never received, ${refused.length} unresolved`);
58
+ if (refused.length) { for (const r of refused.slice(0, 10)) log(` unresolved: ${r}`); log("recover: REFUSED: some broker work cannot be accounted for"); return 2; }
59
+
60
+ // The reclaim itself settles a never-received sub-handle (build-ownership.mjs coveredWorkGone, rightkit#1513): the next gate run recovers this
61
+ // record automatically; --apply runs that same reclaim now and releases.
62
+ if (!apply) { log(`recover: recoverable: ${reaped} REAPED, ${toMark.length} never reached the broker. The next gate run reclaims it automatically; --apply reclaims now.`); return 0; }
63
+ let own;
64
+ try { own = acquireBuildOwnership({ file, stage: "ownership-recover", snapshot: owner.snapshot, commit: owner.commit, exportEnv: false }); }
65
+ catch (e) { log(`recover: REFUSED by the reclaim: ${e.message}`); return 2; }
66
+ for (const p of own.reclaimed?.proofs ?? []) log(` reclaim: ${p.slice(0, 200)}`);
67
+ const rel = own.release();
68
+ log(`recover: recovered ${owner.handle}; released ${rel?.released === true ? "cleanly" : JSON.stringify(rel).slice(0, 200)}`);
69
+ return 0;
70
+ }
71
+
72
+ if (process.argv[1] && fs.realpathSync(process.argv[1]) === fs.realpathSync(fileURLToPath(import.meta.url))) {
73
+ const args = process.argv.slice(2);
74
+ const file = args.find((a) => !a.startsWith("--"));
75
+ const waitAt = args.indexOf("--wait-ms");
76
+ if (!file) { console.error("usage: ownership-recover.mjs <owner.json> [--apply] [--wait-ms N]"); process.exit(64); }
77
+ recover({ file, apply: args.includes("--apply"), waitMs: waitAt >= 0 ? Number(args[waitAt + 1]) : undefined }).then((code) => process.exit(code), (e) => { console.error(`recover: ${e.stack ?? e}`); process.exit(2); });
78
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rightkit/release",
3
- "version": "0.6.46",
3
+ "version": "0.6.47",
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",
@@ -100,7 +100,7 @@
100
100
  "smol-toml": "1.9.1"
101
101
  },
102
102
  "scripts": {
103
- "test": "node --test affected-units.test.mjs batch-workspace.test.mjs unit-list-compile.test.mjs snapshot-dependency-reuse.test.mjs publisher-requirement-scan.test.mjs node-check-cache.test.mjs preparation-diagnostics.test.mjs gate-coverage-timing.test.mjs failure-class.test.mjs cargo-width.test.mjs ci-compile-admission.test.mjs",
103
+ "test": "node --test affected-units.test.mjs batch-workspace.test.mjs unit-list-compile.test.mjs snapshot-dependency-reuse.test.mjs publisher-requirement-scan.test.mjs node-check-cache.test.mjs preparation-diagnostics.test.mjs gate-coverage-timing.test.mjs failure-class.test.mjs cargo-width.test.mjs ci-compile-admission.test.mjs ownership-mark-note.test.mjs handle-revocation.test.mjs test-run-output.test.mjs ownership-auto-recover.test.mjs gate-acceptance.test.mjs stamp-relay.test.mjs",
104
104
  "test:registry-parity": "node registry-parity.mjs --allow-unpublished",
105
105
  "test:signer:windows": "node sign-release-manifest.integration.mjs",
106
106
  "verify:standalone": "node standalone-clone-verify.mjs"
@@ -3,6 +3,7 @@
3
3
  // published versions, and (with --apply) move them forward and refresh the lockfiles.
4
4
  // Self-contained (node: built-ins only) so the SessionStart hook can carry a byte copy of it.
5
5
  // node rightkit-drift.mjs [--apply [--all]] [app-root] (--all also adopts breaking bumps)
6
+ import { nonCompilingCargoEnv } from "./managed-cargo.mjs";
6
7
  import { spawnSync } from "./background-process.mjs";
7
8
  import { existsSync, readFileSync, writeFileSync, realpathSync } from "node:fs";
8
9
  import path from "node:path";
@@ -83,9 +84,9 @@ export function launchOf(command, args, { platform = process.platform, spawn = s
83
84
  return { command: target, args, shell: false };
84
85
  }
85
86
 
86
- function run(command, args, cwd, { spawn = spawnSync, platform = process.platform, readFile } = {}) {
87
+ function run(command, args, cwd, { spawn = spawnSync, platform = process.platform, readFile, env } = {}) {
87
88
  const launch = launchOf(command, args, { platform, spawn, readFile });
88
- const result = spawn(launch.command, launch.args, { cwd, stdio: "inherit", windowsHide: true, shell: launch.shell });
89
+ const result = spawn(launch.command, launch.args, { cwd, stdio: "inherit", windowsHide: true, shell: launch.shell, ...(env ? { env } : {}) });
89
90
  if (result.status !== 0) throw new Error(`${command} ${args.join(" ")} failed in ${cwd} (exit ${result.status ?? result.error?.message})`);
90
91
  }
91
92
 
@@ -113,7 +114,7 @@ export function applyRightkitAdoption(appRoot, versions = loadRightkitVersions()
113
114
  for (const file of byFile.keys()) {
114
115
  const dir = path.join(appRoot, path.dirname(file));
115
116
  if (file.endsWith("package.json")) run("pnpm", ["install", "--lockfile-only", "--ignore-scripts"], dir, runOptions);
116
- else run("rustright", ["cargo", "metadata", "--format-version", "1", "--manifest-path", path.join(appRoot, file)], dir, runOptions);
117
+ else run("cargo", ["metadata", "--format-version", "1", "--manifest-path", path.join(appRoot, file)], dir, { ...runOptions, env: nonCompilingCargoEnv(runOptions?.env ?? process.env) });
117
118
  }
118
119
  }
119
120
  return drift;
@@ -50,7 +50,7 @@
50
50
  "@rightkit/qa": "0.7.0",
51
51
  "@rightkit/qa-chrome": "0.1.12",
52
52
  "@rightkit/react-shell": "0.7.3",
53
- "@rightkit/release": "0.6.46",
53
+ "@rightkit/release": "0.6.47",
54
54
  "@rightkit/settings-ui": "0.7.1",
55
55
  "@rightkit/social-ui": "0.1.0",
56
56
  "@rightkit/system-ui": "0.1.0",
@@ -123,7 +123,7 @@ export function createSnapshotBroker({ env = process.env, platform = process.pla
123
123
  return {
124
124
  carrierSweep,
125
125
  controlRoot: roots.controlRoot, commit: { sha: commit.sha, tree: commit.tree }, snapshot: { path: snapshot.path, expectedTree: snapshot.expectedTree },
126
- declaredInputs: readDeclaredInputs(snapshot.path), handle: ownership.handle, markBrokerSubmit: (callHandle) => ownership.markBrokerSubmit(callHandle), markBrokerUnsent: typeof ownership.markBrokerUnsent === "function" ? (callHandle, reason) => ownership.markBrokerUnsent(callHandle, reason) : undefined,
126
+ declaredInputs: readDeclaredInputs(snapshot.path), handle: ownership.handle, markBrokerSubmit: (callHandle, note) => ownership.markBrokerSubmit(callHandle, note), markBrokerUnsent: typeof ownership.markBrokerUnsent === "function" ? (callHandle, reason) => ownership.markBrokerUnsent(callHandle, reason) : undefined,
127
127
  pins: { host: pins.host, keyId: pins.keyId, publicKey: pins.publicKey, brokerDigest: pins.brokerDigest }, pinsSource: pins.source,
128
128
  checkout: fs.realpathSync.native(checkout), outputRoots: brokerOutputRoots({ dataRoot: managedData }), platform, client,
129
129
  receiptOf: async (requestId) => receiptSync({ client, requestId, env, spawn, platform }),
package/stage-sidecar.mjs CHANGED
@@ -40,7 +40,21 @@ import { spawnSync as nodeSpawnSync } from "./background-process.mjs";
40
40
  import { resolveCommand } from "./development.mjs";
41
41
  import { carriedCargoMapOf } from "./carried-cargo.mjs";
42
42
  import { BUILD_LAUNCH_REFUSED, buildLaunch } from "./build-launch.mjs";
43
- import { directHost, managedHost, runCargoSync } from "./managed-cargo.mjs";
43
+ import { directCargoPath, directHost, managedHost, nonCompilingCargoEnv, runCargoSync } from "./managed-cargo.mjs";
44
+ import { snapshotCargoMetadata } from "./gate-serve.mjs";
45
+ import { snapshotRoot } from "./snapshot.mjs";
46
+
47
+ /**
48
+ * `cargo metadata` for the sidecar (GC-A11: non-compiling, never through the broker). Inside a gate snapshot the resident gate answers it, cached
49
+ * while the snapshot is unchanged; elsewhere, or when the resident gate is unavailable, the real cargo runs directly.
50
+ */
51
+ function sidecarCargoMetadata(cwd, args, env) {
52
+ const cargoEnv = nonCompilingCargoEnv(env);
53
+ const pathKey = process.platform === "win32" ? (Object.keys(cargoEnv).find((k) => k.toUpperCase() === "PATH") ?? "Path") : "PATH";
54
+ const cargo = directCargoPath({ env: { ...cargoEnv, PATH: cargoEnv[pathKey] }, platform: process.platform }).cargo;
55
+ let root = null; try { root = snapshotRoot({ env }); } catch { root = null; }
56
+ return snapshotCargoMetadata({ cwd, args, cargo, env: cargoEnv, snapshotRootDir: root ?? "/nonexistent" });
57
+ }
44
58
  import { APPROVAL_MACHO_STRIP_LINKEDIT_V1, APPROVAL_RAW_SHA256, approvalDigest } from "./macho-approval-hash.mjs";
45
59
  import {
46
60
  bundledFileName, planMediaSidecar, sourceOfferText, stagedFileName, validateMediaSidecarConfig, verifyStagedSidecars, writeMediaSidecarNotices,
@@ -782,7 +796,9 @@ function resolveCatalogFile(spec, ctx, kind) {
782
796
  if (spec.via === "absolute") return requireSnapshotSource(ctx, spec.file, `the ${label} catalog`);
783
797
  if (spec.via === "path") return requireSnapshotSource(ctx, path.resolve(ctx.appRoot, spec.file), `the ${label} catalog`);
784
798
  if (spec.via === "crate") {
785
- const meta = ctx.run("rustright", ["cargo", "metadata", "--frozen", "--format-version", "1"], { cwd: ctx.appRoot, env: ctx.env });
799
+ // Non-compiling cargo runs directly, never through the broker (GC-A11): from inside a gate snapshot the broker refuses a root request
800
+ // ("a root request cannot run inside a managed snapshot"), which made every crate-located catalog unreadable in a gate compile.
801
+ const meta = sidecarCargoMetadata(ctx.appRoot, ["metadata", "--frozen", "--format-version", "1"], ctx.env ?? process.env);
786
802
  let packages;
787
803
  try { packages = JSON.parse(meta.stdout).packages; } catch { /* refused below */ }
788
804
  if (meta?.status !== 0 || !Array.isArray(packages)) fail("STAGE_SIDECAR_CATALOG_UNREADABLE", `the ${label} catalog crate ${spec.crate} cannot be located: the workspace metadata query failed`, { crate: spec.crate });
@@ -926,7 +942,7 @@ function requireSnapshotSource(ctx, file, label) {
926
942
  * A path outside the snapshot (an absolute CARGO_TARGET_DIR, a target-dir set in the user's Cargo home) stands as reported.
927
943
  */
928
944
  function snapshotTargetDirectory(ctx, env, manifest) {
929
- const resolved = ctx.run("rustright", ["cargo", "metadata", "--offline", "--format-version", "1", "--no-deps", ...(manifest ? ["--manifest-path", manifest] : [])], { cwd: ctx.appRoot, env });
945
+ const resolved = sidecarCargoMetadata(ctx.appRoot, ["metadata", "--offline", "--format-version", "1", "--no-deps", ...(manifest ? ["--manifest-path", manifest] : [])], env);
930
946
  let dir;
931
947
  try { dir = JSON.parse(resolved?.stdout).target_directory; } catch { /* reported below */ }
932
948
  if (resolved?.error || resolved?.status !== 0 || typeof dir !== "string" || !path.isAbsolute(dir)) return { error: resolved?.error?.message ?? `exit ${resolved?.status}` };
@@ -1109,7 +1125,7 @@ function stageCargoBuild(entry, ctx, triple) {
1109
1125
  source = candidates.find((file) => fs.existsSync(file));
1110
1126
  if (!source) fail("STAGE_SIDECAR_BINARY_NOT_FOUND", `the build did not produce ${entry.bin} (looked in ${candidates.join(", ")})`, { bin: entry.bin, candidates });
1111
1127
  } else if (!source || !fs.existsSync(source)) {
1112
- const meta = run("rustright", ["cargo", "metadata", "--format-version", "1", "--no-deps", ...(manifestFile ? ["--manifest-path", manifestFile] : [])], { cwd: appRoot, env: buildEnv });
1128
+ const meta = sidecarCargoMetadata(appRoot, ["metadata", "--format-version", "1", "--no-deps", ...(manifestFile ? ["--manifest-path", manifestFile] : [])], buildEnv);
1113
1129
  let targetDir;
1114
1130
  try { targetDir = JSON.parse(meta.stdout).target_directory; } catch { /* refused below */ }
1115
1131
  if (meta?.status !== 0 || typeof targetDir !== "string" || !path.isAbsolute(targetDir)) targetDir = undefined;