@rightkit/release 0.6.45 → 0.6.46
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/affected-units.mjs +190 -0
- package/bin/rightkit-gate.mjs +613 -125
- package/build-ownership.mjs +85 -28
- package/cargo-width.mjs +49 -0
- package/ci-compile-admission.mjs +57 -0
- package/committed-cargo-workspace.mjs +58 -0
- package/dependency-identity.mjs +98 -0
- package/deterministic-scans.mjs +235 -44
- package/gate-coverage.mjs +17 -6
- package/gate-serve.mjs +177 -0
- package/local-publish.mjs +107 -34
- package/node-check-cache.mjs +95 -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-versions.json +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/unit-gate.mjs +25 -5
- package/unit-list-compile.mjs +276 -0
package/gate-serve.mjs
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
// The resident gate (GC-A24, rightkit#1506): a gate-owned, per-host process outside the broker that watches the snapshot root and
|
|
2
|
+
// remembers which snapshot directories were proven exactly a tree, so a repeat proof of an unchanged snapshot needs no walk.
|
|
3
|
+
//
|
|
4
|
+
// Measured before it was built (Mac, 2026-11-05): node with the gate's modules starts in 34-50 ms, so residency buys nothing at
|
|
5
|
+
// startup; what it buys is proof. A warm RK check spent ~3.3 s of 10.8 s in six snapshot verifies of an unchanged directory.
|
|
6
|
+
//
|
|
7
|
+
// Correctness:
|
|
8
|
+
// - A proof is recorded only with the change generation taken BEFORE the walk began: any event for that snapshot between "begin" and
|
|
9
|
+
// "record" leaves it unproven.
|
|
10
|
+
// - Every answer is preceded by a cookie sync (as watchman does): the server writes a cookie file in the watched root and waits for its
|
|
11
|
+
// own event, so every change made before the request has been delivered and counted before the server answers.
|
|
12
|
+
// - A watcher error, a dropped or unknown event, an unreachable server, a timeout, or a server running other gate code all mean "not
|
|
13
|
+
// proven", and the caller does the full verify. The server never says "clean" on a guess.
|
|
14
|
+
// - Only plain verifies (no stage-output ledger) use it.
|
|
15
|
+
//
|
|
16
|
+
// Lifecycle: started detached by the first client that finds no server (RK_GATE_SERVE=0 disables it); one server per host and data root;
|
|
17
|
+
// exits after RK_GATE_SERVE_IDLE_MS (default 30 min) without a request, or when a client runs different gate code. No system service is
|
|
18
|
+
// installed. Commands: `node gate-serve.mjs serve`, `node gate-serve.mjs status`, and the internal client ops below.
|
|
19
|
+
import crypto from "node:crypto";
|
|
20
|
+
import fs from "node:fs";
|
|
21
|
+
import net from "node:net";
|
|
22
|
+
import os from "node:os";
|
|
23
|
+
import path from "node:path";
|
|
24
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
25
|
+
import { fileURLToPath } from "node:url";
|
|
26
|
+
import { resolveManagedRoots } from "./managed-roots.mjs";
|
|
27
|
+
|
|
28
|
+
const SELF = fileURLToPath(import.meta.url);
|
|
29
|
+
const SCHEMA = "rightkit.gate-serve/1";
|
|
30
|
+
const COOKIE_PREFIX = "0000000000000000.gate-serve-cookie-";
|
|
31
|
+
const IDENTITY = (() => { try { return crypto.createHash("sha256").update(fs.readFileSync(SELF)).digest("hex").slice(0, 16); } catch { return "unknown"; } })();
|
|
32
|
+
|
|
33
|
+
function dataRoot(env = process.env) { return resolveManagedRoots({ env, platform: process.platform }).dataRoot; }
|
|
34
|
+
export function socketPath(env = process.env) {
|
|
35
|
+
if (process.platform === "win32") return `\\\\.\\pipe\\rightkit-gate-serve-${(os.userInfo().username || "user").replace(/[^A-Za-z0-9_-]/g, "_")}`;
|
|
36
|
+
return path.join(dataRoot(env), "gate-serve", "serve.sock");
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// ---- server ---------------------------------------------------------------------------------------------------------------------------
|
|
40
|
+
|
|
41
|
+
export async function serve({ root, idleMs = Number(process.env.RK_GATE_SERVE_IDLE_MS ?? 30 * 60 * 1000), log = () => {} } = {}) {
|
|
42
|
+
const watchedRoot = fs.realpathSync(root);
|
|
43
|
+
const generation = new Map(); // snapshot key -> change count
|
|
44
|
+
const proven = new Map(); // snapshot key -> { tree, generation }
|
|
45
|
+
let watcher = null; let healthy = false; let cookieSeq = 0;
|
|
46
|
+
const cookies = new Map(); // cookie name -> resolve
|
|
47
|
+
// Only entries inside a snapshot directory (`<16 hex>/...`) are snapshot content; `<key>.tree-index`, `<key>.state.json` and the like
|
|
48
|
+
// beside it are the gate's own metadata, and the cookie is `0000000000000000.gate-serve-cookie-*` (a name the snapshot root accepts).
|
|
49
|
+
const keyOf = (rel) => { const base = String(rel ?? "").split(/[\\/]/)[0]; return /^[0-9a-f]{16}$/.test(base) ? base : null; };
|
|
50
|
+
const bumpAll = () => { for (const k of new Set([...generation.keys(), ...proven.keys()])) generation.set(k, (generation.get(k) ?? 0) + 1); proven.clear(); };
|
|
51
|
+
const startWatch = () => {
|
|
52
|
+
try {
|
|
53
|
+
watcher = fs.watch(watchedRoot, { recursive: true, persistent: true }, (_event, filename) => {
|
|
54
|
+
if (filename == null) { bumpAll(); return; } // an event without a name: anything may have changed
|
|
55
|
+
const name = String(filename);
|
|
56
|
+
const base = name.split(/[\\/]/)[0];
|
|
57
|
+
if (base.startsWith(COOKIE_PREFIX)) { const r = cookies.get(base); if (r) { cookies.delete(base); r(); } return; }
|
|
58
|
+
const key = keyOf(name);
|
|
59
|
+
// The watched root's own entry (its listing changed) carries no content: the entry that changed reports under its own name.
|
|
60
|
+
if (key === null) { if (/^[0-9a-f]{16}\./.test(base) || name === path.basename(watchedRoot)) return; bumpAll(); return; } // gate metadata beside a snapshot; anything else: drop every proof
|
|
61
|
+
generation.set(key, (generation.get(key) ?? 0) + 1);
|
|
62
|
+
proven.delete(key);
|
|
63
|
+
});
|
|
64
|
+
watcher.on("error", (error) => { log(`watcher error: ${error?.message ?? error}; every proof dropped, restarting the watch`); healthy = false; bumpAll(); try { watcher.close(); } catch { /* closed */ } setTimeout(startWatch, 200); });
|
|
65
|
+
healthy = true;
|
|
66
|
+
} catch (error) { healthy = false; log(`cannot watch ${watchedRoot}: ${error?.message ?? error}`); setTimeout(startWatch, 1000); }
|
|
67
|
+
};
|
|
68
|
+
startWatch();
|
|
69
|
+
// Every change made before this call has been delivered once the cookie's own event arrives (events of one watch are ordered).
|
|
70
|
+
const cookieSync = (timeoutMs = 2000) => new Promise((resolve) => {
|
|
71
|
+
if (!healthy) { resolve(false); return; }
|
|
72
|
+
const name = `${COOKIE_PREFIX}${process.pid}-${++cookieSeq}`;
|
|
73
|
+
const file = path.join(watchedRoot, name);
|
|
74
|
+
const timer = setTimeout(() => { cookies.delete(name); try { fs.rmSync(file, { force: true }); } catch { /* gone */ } resolve(false); }, timeoutMs);
|
|
75
|
+
cookies.set(name, () => { clearTimeout(timer); try { fs.rmSync(file, { force: true }); } catch { /* gone */ } resolve(true); });
|
|
76
|
+
try { fs.writeFileSync(file, String(Date.now())); } catch { clearTimeout(timer); cookies.delete(name); resolve(false); }
|
|
77
|
+
});
|
|
78
|
+
let lastRequest = Date.now();
|
|
79
|
+
const handle = async (req) => {
|
|
80
|
+
lastRequest = Date.now();
|
|
81
|
+
if (req?.schema !== SCHEMA) return { ok: false, why: "schema" };
|
|
82
|
+
if (req.identity !== IDENTITY) { setTimeout(() => process.exit(0), 50); return { ok: false, why: "gate code changed; the server exits" }; }
|
|
83
|
+
if (req.op === "status") return { ok: true, healthy, root: watchedRoot, proven: [...proven].map(([k, v]) => ({ key: k, tree: v.tree })), pid: process.pid, identity: IDENTITY };
|
|
84
|
+
const dir = typeof req.dir === "string" ? req.dir : "";
|
|
85
|
+
let real; try { real = fs.realpathSync(dir); } catch { return { ok: false, why: "no such directory" }; }
|
|
86
|
+
if (path.dirname(real) !== watchedRoot) return { ok: false, why: "not a snapshot of the watched root" };
|
|
87
|
+
const key = keyOf(path.basename(real));
|
|
88
|
+
if (key === null) return { ok: false, why: "not a snapshot directory name" };
|
|
89
|
+
if (!(await cookieSync())) return { ok: false, why: "watcher not current" };
|
|
90
|
+
if (req.op === "begin") return { ok: true, generation: generation.get(key) ?? 0 };
|
|
91
|
+
if (req.op === "record") {
|
|
92
|
+
if (typeof req.tree !== "string" || !Number.isInteger(req.generation)) return { ok: false, why: "bad record" };
|
|
93
|
+
if ((generation.get(key) ?? 0) !== req.generation) return { ok: false, why: "changed during the proof" };
|
|
94
|
+
proven.set(key, { tree: req.tree, generation: req.generation });
|
|
95
|
+
return { ok: true };
|
|
96
|
+
}
|
|
97
|
+
if (req.op === "check") {
|
|
98
|
+
const p = proven.get(key);
|
|
99
|
+
const now = generation.get(key) ?? 0;
|
|
100
|
+
const clean = Boolean(p && p.tree === req.tree && p.generation === now);
|
|
101
|
+
return { ok: true, clean, generation: now };
|
|
102
|
+
}
|
|
103
|
+
return { ok: false, why: "unknown op" };
|
|
104
|
+
};
|
|
105
|
+
const sock = socketPath();
|
|
106
|
+
if (process.platform !== "win32") { fs.mkdirSync(path.dirname(sock), { recursive: true }); try { fs.unlinkSync(sock); } catch { /* none */ } }
|
|
107
|
+
const server = net.createServer((conn) => {
|
|
108
|
+
let buf = "";
|
|
109
|
+
conn.on("data", async (d) => {
|
|
110
|
+
buf += d;
|
|
111
|
+
const nl = buf.indexOf("\n");
|
|
112
|
+
if (nl < 0) return;
|
|
113
|
+
let req = null; try { req = JSON.parse(buf.slice(0, nl)); } catch { req = null; }
|
|
114
|
+
buf = "";
|
|
115
|
+
let res; try { res = await handle(req); } catch (error) { res = { ok: false, why: String(error?.message ?? error) }; }
|
|
116
|
+
conn.end(`${JSON.stringify(res)}\n`);
|
|
117
|
+
});
|
|
118
|
+
conn.on("error", () => {});
|
|
119
|
+
});
|
|
120
|
+
await new Promise((resolve, reject) => { server.once("error", reject); server.listen(sock, resolve); });
|
|
121
|
+
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);
|
|
123
|
+
idle.unref?.();
|
|
124
|
+
return server;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// ---- client (synchronous: verifySnapshotDir is synchronous) ------------------------------------------------------------------------------
|
|
128
|
+
|
|
129
|
+
async function ask(req, timeoutMs) {
|
|
130
|
+
return new Promise((resolve) => {
|
|
131
|
+
const conn = net.connect(socketPath());
|
|
132
|
+
let out = "";
|
|
133
|
+
const timer = setTimeout(() => { conn.destroy(); resolve({ ok: false, why: "timeout" }); }, timeoutMs);
|
|
134
|
+
conn.on("connect", () => conn.write(`${JSON.stringify({ schema: SCHEMA, identity: IDENTITY, ...req })}\n`));
|
|
135
|
+
conn.on("data", (d) => { out += d; });
|
|
136
|
+
conn.on("end", () => { clearTimeout(timer); try { resolve(JSON.parse(out)); } catch { resolve({ ok: false, why: "bad reply" }); } });
|
|
137
|
+
conn.on("error", (error) => { clearTimeout(timer); resolve({ ok: false, why: error?.code ?? "error", unreachable: true }); });
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** One synchronous request to the resident server; null when it is disabled, unreachable or did not answer. Starts it when absent. */
|
|
142
|
+
export function serveRequest(req, { env = process.env, root = null, timeoutMs = 3000 } = {}) {
|
|
143
|
+
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 } });
|
|
145
|
+
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 });
|
|
147
|
+
return res && res.ok ? res : null;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function startServer({ root, env }) {
|
|
151
|
+
try {
|
|
152
|
+
const logDir = path.join(dataRoot(env), "gate-serve");
|
|
153
|
+
fs.mkdirSync(logDir, { recursive: true });
|
|
154
|
+
const out = fs.openSync(path.join(logDir, "serve.log"), "a");
|
|
155
|
+
// A minimal environment: the server outlives the run that started it, so it must carry none of that run's tokens (the build
|
|
156
|
+
// ownership guard rightly refuses a run while any process still holds an earlier run's RIGHTKIT_BUILD_OWNERSHIP).
|
|
157
|
+
const keep = ["PATH", "HOME", "USERPROFILE", "SYSTEMROOT", "SystemRoot", "TEMP", "TMP", "TMPDIR", "LOCALAPPDATA", "APPDATA", "RIGHTKIT_MANAGED_ROOT", "RK_GATE_SERVE_IDLE_MS"];
|
|
158
|
+
const childEnv = Object.fromEntries(keep.filter((k) => env[k] !== undefined).map((k) => [k, env[k]]));
|
|
159
|
+
const child = spawn(process.execPath, [SELF, "serve", root], { detached: true, stdio: ["ignore", out, out], env: childEnv, cwd: path.dirname(SELF), windowsHide: true });
|
|
160
|
+
child.unref();
|
|
161
|
+
fs.closeSync(out);
|
|
162
|
+
} catch { /* the next run tries again; this one verifies in full */ }
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
// ---- entry --------------------------------------------------------------------------------------------------------------------------------
|
|
166
|
+
|
|
167
|
+
if (process.argv[1] && fs.realpathSync(process.argv[1]) === fs.realpathSync(SELF)) {
|
|
168
|
+
const [cmd, a, b] = process.argv.slice(2);
|
|
169
|
+
if (cmd === "serve") {
|
|
170
|
+
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
|
+
} else if (cmd === "ask") {
|
|
172
|
+
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); });
|
|
174
|
+
} else if (cmd === "status") {
|
|
175
|
+
ask({ op: "status" }, 3000).then((res) => { console.log(JSON.stringify(res, null, 2)); process.exit(res.ok ? 0 : 1); });
|
|
176
|
+
} else { console.error("usage: gate-serve.mjs serve <snapshot-root> | status"); process.exit(2); }
|
|
177
|
+
}
|
package/local-publish.mjs
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
import { committedCargoWorkspace } from "./committed-cargo-workspace.mjs";
|
|
2
3
|
// `right-release publish npm|cargo ... --local`: publish ONE @rightkit npm package or crate from the Mac (npm and
|
|
3
4
|
// crates) or from Windows (crates only) under Adrian's local-build grant (2026-10-14, committed
|
|
4
5
|
// .rightkit-local-build.json). It does not weaken the publication gate: it runs the unit's own CI tests
|
|
@@ -423,14 +424,21 @@ export const GATE_CONFIG_FILES = Object.freeze(["ci/gate.config.json", "ci/asset
|
|
|
423
424
|
|
|
424
425
|
export { CROSS_TARGETS, ZIG_TARGETS, CROSS_CC_ENV, crossTargetsFor, crossCompileEnv } from "./cross-targets.mjs";
|
|
425
426
|
|
|
426
|
-
/**
|
|
427
|
+
/** Build a selected npm package and its workspace dependency closure, in dependency order. */
|
|
428
|
+
export function npmBuildClosureArgs(unit) {
|
|
429
|
+
if (typeof unit !== "string" || unit.length > 214 || !/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/.test(unit) || unit.includes("...")) throw new Error("invalid npm package name for workspace build");
|
|
430
|
+
// Adapter registration accepts --if-present after run, not as a leading option.
|
|
431
|
+
return ["-r", "--workspace-concurrency=1", "--filter", `${unit}...`, "run", "--if-present", "build"];
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
/** Local compile and test commands for one unit, aligned with CI's selected-unit coverage. */
|
|
427
435
|
export function localTestPlan({ kind, unit, dir, config, manifest, batch = false, platform = "darwin" }) {
|
|
428
436
|
if (kind === "npm") {
|
|
429
437
|
// End-to-end tests only (Adrian, 2026-11-03): an npm unit with no test script has no test step, as a crate with no test qualifies on its other steps.
|
|
430
438
|
return {
|
|
431
439
|
id: `npm:${dir}`, featureLabels: ["default"],
|
|
432
440
|
steps: [
|
|
433
|
-
{ command: "pnpm", args:
|
|
441
|
+
{ command: "pnpm", args: npmBuildClosureArgs(unit), test: false },
|
|
434
442
|
...(manifest?.scripts?.test ? [{ command: "pnpm", args: ["--dir", dir, "run", "test"], test: true }] : []),
|
|
435
443
|
],
|
|
436
444
|
};
|
|
@@ -470,33 +478,75 @@ export function localTestPlan({ kind, unit, dir, config, manifest, batch = false
|
|
|
470
478
|
return { id: `rust:${unit}`, featureLabels: featureSets.map((features) => features.join(" ") || "default"), consumerRows: consumers, steps };
|
|
471
479
|
}
|
|
472
480
|
|
|
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 }) {
|
|
483
|
+
if (kind !== "cargo" && kind !== "npm") throw new Error(`unsupported compile requirement kind ${kind}`);
|
|
484
|
+
if (kind === "cargo" && (typeof workspace !== "string" || !workspace)) throw new Error("authenticated Cargo workspace is required");
|
|
485
|
+
if (!env || typeof env !== "object" || Array.isArray(env)) throw new Error("publisher execution environment is required");
|
|
486
|
+
if (!Array.isArray(allowIgnoredUnits)) throw new Error("allowIgnoredUnits must be an array");
|
|
487
|
+
const plan = localTestPlan({ kind, unit, dir, config, manifest, batch: false, platform });
|
|
488
|
+
const gated = Object.hasOwn(assetGated[kind === "npm" ? "npm" : "crates"] ?? {}, unit);
|
|
489
|
+
const executionEnv = testEnv({ env }, gated);
|
|
490
|
+
const configReason = kind === "cargo" && typeof config?.rust?.[unit]?.allowIgnored === "string" ? config.rust[unit].allowIgnored.trim() : "";
|
|
491
|
+
const ignoredAllowed = Boolean(allowIgnored || allowIgnoredUnits.includes(unit) || configReason);
|
|
492
|
+
const steps = [...plan.steps];
|
|
493
|
+
if (kind === "cargo") steps.unshift({ command: "cargo", args: qualifyFmtArgs(unit), test: false });
|
|
494
|
+
const requirements = [];
|
|
495
|
+
const add = (requirement) => requirements.push({ id: `publisher:${kind}:${unit}:${requirements.length}`, ...requirement, coverageKey: sha256(JSON.stringify(requirement)) });
|
|
496
|
+
if (kind === "cargo") add({ workspace, cwd: dir, executable: null, internal: "scanCrateForSecrets", argv: [dir], env: {}, phase: "check" });
|
|
497
|
+
for (const step of steps) {
|
|
498
|
+
const consumer = step.command === "cargo" && step.args.includes("--manifest-path");
|
|
499
|
+
const cwd = consumer || kind === "npm" ? "." : dir;
|
|
500
|
+
const manifestIndex = step.args.indexOf("--manifest-path");
|
|
501
|
+
const requirementWorkspace = consumer ? path.posix.dirname(step.args[manifestIndex + 1]) : kind === "cargo" ? workspace : ".";
|
|
502
|
+
const argv = step.command === "cargo" ? oneOutput(withCargoJobs(step.args, jobs), { platform }) : [...step.args];
|
|
503
|
+
add({ workspace: requirementWorkspace, cwd, executable: step.command, argv, env: { ...executionEnv, ...(step.env ?? {}) }, phase: step.test ? "test" : "compile" });
|
|
504
|
+
}
|
|
505
|
+
return {
|
|
506
|
+
unit, requirements, consumerWorkspaces: [...new Set((plan.consumerRows ?? []).map((row) => path.posix.dirname(row.manifestPath)))],
|
|
507
|
+
verdict: { source: "judgeUnit", allowNoTests: true, allowIgnored: ignoredAllowed, allowIgnoredReason: configReason || null, allowMissingAssets: gated, requireZeroFailed: true, rejectTruncatedTestOutput: true, brokerCompiledTestsRunOutsideBroker: true },
|
|
508
|
+
sourceObligations: { cleanUnitAndGateConfig: true, cleanTrackedConsumerManifestsAndLocks: true },
|
|
509
|
+
};
|
|
510
|
+
}
|
|
511
|
+
|
|
473
512
|
/**
|
|
474
513
|
* The clippy invocations that replace each crate's own `cargo clippy -p <crate> --no-deps --all-targets
|
|
475
|
-
* <
|
|
476
|
-
*
|
|
477
|
-
*
|
|
478
|
-
*
|
|
514
|
+
* <features> -- -D warnings`: same flags and lint level, so the same lints on the same code. RightKit is one Cargo
|
|
515
|
+
* workspace (GC-T24, rightkit#1505 superseding #1285's one workspace per crate), so crates whose invocation would
|
|
516
|
+
* differ only in `-p <crate>` share ONE invocation naming every crate, run at the workspace root. Grouping is exact:
|
|
517
|
+
* same feature set, same target (or none), same asset-gated environment. A feature set that names crate-specific
|
|
518
|
+
* features (`--features`/`-F <names>`) never groups: one invocation would apply those names to every crate in it, so
|
|
519
|
+
* such a crate keeps its own invocation, exactly as deterministic-scans.mjs `batchable` refuses the same sets.
|
|
520
|
+
* Feature unification inside one invocation is the GC-I11 caveat the scan batching already carries; the members of
|
|
521
|
+
* a group share the invocation's verdict through the batch receipt, and each crate's tested/check/doc steps still
|
|
522
|
+
* run per crate in its own publish flow.
|
|
479
523
|
*/
|
|
480
|
-
export function batchClippyInvocations(layer, { featuresOf = () => [], featureSetsOf = (unit) => [featuresOf(unit)], assetGatedOf = () => false, crossTargetsOf = () => [] } = {}) {
|
|
524
|
+
export function batchClippyInvocations(layer, { featuresOf = () => [], featureSetsOf = (unit) => [featuresOf(unit)], assetGatedOf = () => false, crossTargetsOf = () => [], workspaceOf = () => "." } = {}) {
|
|
481
525
|
const invocations = [];
|
|
526
|
+
const groups = new Map(); // group key -> invocation being built (its index in `invocations` stays at first sight)
|
|
527
|
+
const namesFeatures = (features) => features.some((f) => f === "--features" || f === "-F" || f.startsWith("--features=") || /^-F.+/.test(f));
|
|
528
|
+
const add = (unit, features, target) => {
|
|
529
|
+
const env = target ? crossCompileEnv(target) : null;
|
|
530
|
+
if (target && !env) throw new Error(`RK_CROSS_CC_UNPROVISIONED: the zig C toolchain for ${target} is not provisioned; run node scripts/ci/provision-zig.mjs <managed data root>/zig (or set RIGHTKIT_CROSS_CC_DIR)`);
|
|
531
|
+
const assetGated = assetGatedOf(unit);
|
|
532
|
+
const workspace = workspaceOf(unit);
|
|
533
|
+
const tail = ["--message-format=json-render-diagnostics", "--no-deps", "--all-targets", ...(target ? ["--target", target] : []), ...features, "--", "-D", "warnings"];
|
|
534
|
+
if (namesFeatures(features)) { invocations.push({ crates: [unit], workspace, assetGated, ...(env ? { env } : {}), args: ["clippy", "-p", unit, ...tail] }); return; }
|
|
535
|
+
const key = JSON.stringify([workspace, features, target, assetGated, env]);
|
|
536
|
+
const existing = groups.get(key);
|
|
537
|
+
if (existing) { existing.crates.push(unit); existing.args.splice(1 + 2 * (existing.crates.length - 1), 0, "-p", unit); return; }
|
|
538
|
+
const invocation = { crates: [unit], workspace, assetGated, ...(env ? { env } : {}), args: ["clippy", "-p", unit, ...tail] };
|
|
539
|
+
groups.set(key, invocation);
|
|
540
|
+
invocations.push(invocation);
|
|
541
|
+
};
|
|
482
542
|
for (const unit of layer) {
|
|
483
543
|
// Every tested feature set of a crate is linted, in order; identical sets of one crate collapse to one run.
|
|
484
544
|
const sets = featureSetsOf(unit) ?? [[]];
|
|
485
545
|
const unique = sets.filter((set, index) => sets.findIndex((other) => JSON.stringify(other ?? []) === JSON.stringify(set ?? [])) === index);
|
|
486
546
|
for (const set of unique) {
|
|
487
547
|
const features = set ?? [];
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
args: ["clippy", "-p", unit, "--message-format=json-render-diagnostics", "--no-deps", "--all-targets", ...features, "--", "-D", "warnings"],
|
|
491
|
-
});
|
|
492
|
-
for (const target of crossTargetsOf(unit)) {
|
|
493
|
-
const env = crossCompileEnv(target);
|
|
494
|
-
if (!env) throw new Error(`RK_CROSS_CC_UNPROVISIONED: the zig C toolchain for ${target} is not provisioned; run node scripts/ci/provision-zig.mjs <managed data root>/zig (or set RIGHTKIT_CROSS_CC_DIR)`);
|
|
495
|
-
invocations.push({
|
|
496
|
-
crates: [unit], assetGated: assetGatedOf(unit), ...(env ? { env } : {}),
|
|
497
|
-
args: ["clippy", "-p", unit, "--message-format=json-render-diagnostics", "--no-deps", "--all-targets", "--target", target, ...features, "--", "-D", "warnings"],
|
|
498
|
-
});
|
|
499
|
-
}
|
|
548
|
+
add(unit, features, null);
|
|
549
|
+
for (const target of crossTargetsOf(unit)) add(unit, features, target);
|
|
500
550
|
}
|
|
501
551
|
}
|
|
502
552
|
return invocations;
|
|
@@ -735,7 +785,6 @@ async function* publishUnitStages(parsed, deps, batch) {
|
|
|
735
785
|
if (feed.stagedNpm?.[unit] !== version && feed.registry?.npm?.[unit] !== version) refuse(`${unit}@${version}: stage the version in ${feedPath} and commit it before qualification`);
|
|
736
786
|
}
|
|
737
787
|
}
|
|
738
|
-
if (await (deps.registryHas ?? defaultRegistryHas)({ kind, name: unit, version })) refuse(`${unit}@${version} is already on the ${kind === "npm" ? "npm" : "crates.io"} registry; bump the version`);
|
|
739
788
|
log(`[right-release] local publish ${kind}:${unit}@${version} at ${head.slice(0, 12)} (local-build grant, ${LOCAL_HOST_POLICIES[platform]} policy)`);
|
|
740
789
|
|
|
741
790
|
// 2. The unit's own tests, exactly as the CI gate defines them.
|
|
@@ -805,6 +854,10 @@ async function* publishUnitStages(parsed, deps, batch) {
|
|
|
805
854
|
const packageEnv = yield { stage: "compile", kind, name: unit, version, commit: head, brokerRequests: brokerRequests.splice(0) };
|
|
806
855
|
if (packageEnv) Object.assign(env, testEnv({ env: packageEnv }, isAssetGated));
|
|
807
856
|
|
|
857
|
+
// Availability is a publication/qualification precondition, not a compile precondition.
|
|
858
|
+
// A gate that stops at compile never advances past the yield above and never needs a new version.
|
|
859
|
+
if (await (deps.registryHas ?? defaultRegistryHas)({ kind, name: unit, version })) refuse(`${unit}@${version} is already on the ${kind === "npm" ? "npm" : "crates.io"} registry; bump the version`);
|
|
860
|
+
|
|
808
861
|
// 3. Pack the artifact and hash it.
|
|
809
862
|
// An npm pack is a broker job whose --pack-destination the adapter accepts only as an empty child of the host's scratch root, so the
|
|
810
863
|
// tarball goes there (the workspace rule for run output) rather than in the OS temp directory; the package itself is packed from the
|
|
@@ -994,22 +1047,43 @@ async function runLocalPublishBatch(parsed, deps) {
|
|
|
994
1047
|
if (published.length) refuse(`already on the crates.io registry: ${published.join(", ")}; bump the version or remove them from the batch`);
|
|
995
1048
|
log(`[right-release] local publish cargo batch: ${crates.length} crate(s) in ${layers.length} layer(s) at ${head.slice(0, 12)}, concurrency ${concurrency} (local-build grant, ${LOCAL_HOST_POLICIES[platform]} policy)`);
|
|
996
1049
|
|
|
997
|
-
//
|
|
1050
|
+
// Resolve membership independently from selected commit blobs, never from the receipt or live files.
|
|
998
1051
|
const env = testEnv(deps, false);
|
|
1052
|
+
const workspaces = {};
|
|
1053
|
+
const manifests = new Map();
|
|
1054
|
+
const readCommittedManifest = (file) => {
|
|
1055
|
+
if (manifests.has(file)) return manifests.get(file);
|
|
1056
|
+
const entry = git(["ls-tree", "--name-only", head, "--", file], workspaceRoot);
|
|
1057
|
+
if (entry === null) refuse(`cannot inspect committed ${file}`);
|
|
1058
|
+
if (entry !== "" && entry !== file) refuse(`ambiguous committed ${file}`);
|
|
1059
|
+
const contents = entry === "" ? null : git(["show", `${head}:${file}`], workspaceRoot);
|
|
1060
|
+
if (entry !== "" && contents === null) refuse(`cannot read committed ${file}`);
|
|
1061
|
+
manifests.set(file, contents);
|
|
1062
|
+
return contents;
|
|
1063
|
+
};
|
|
1064
|
+
for (const unit of crates) {
|
|
1065
|
+
try { workspaces[unit] = committedCargoWorkspace({ unitDir: `crates/${unit}`, read: readCommittedManifest }); }
|
|
1066
|
+
catch (error) { refuse(`cannot resolve committed Cargo workspace for ${unit}: ${error.message}`); }
|
|
1067
|
+
}
|
|
1068
|
+
const workspacePaths = [...new Set(Object.values(workspaces))].flatMap((workspace) => [path.posix.join(workspace, "Cargo.toml"), path.posix.join(workspace, "Cargo.lock")]);
|
|
1069
|
+
const workspaceDirty = git(["status", "--porcelain", "--", ...workspacePaths], workspaceRoot);
|
|
1070
|
+
if (workspaceDirty === null || workspaceDirty !== "") refuse(`Cargo workspace manifests or locks are not clean: ${workspaceDirty ?? "cannot read git status"}`);
|
|
1071
|
+
|
|
1072
|
+
// Each row records the workspace and exact units covered by that invocation.
|
|
999
1073
|
const stamp = { commit: head, tree };
|
|
1000
1074
|
const checks = []; const commands = [];
|
|
1001
|
-
|
|
1002
|
-
const batchCheck = async (name, command, args, crateNames, runEnv = env, cwds = [workspaceRoot]) => {
|
|
1075
|
+
const batchCheck = async (name, command, args, crateNames, runEnv = env, workspace = ".") => {
|
|
1003
1076
|
const text = `${command} ${args.join(" ")}`;
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
}
|
|
1009
|
-
checks.push({ name, command: text, ok: true, ...stamp, ...(crateNames ? { crates: crateNames } : {}) });
|
|
1077
|
+
const cwd = path.resolve(workspaceRoot, workspace);
|
|
1078
|
+
log(`[right-release] batch ${name}: ${text} (in ${workspace})`);
|
|
1079
|
+
const result = await run(command, command === "cargo" ? oneOutput(args, { platform }) : args, { cwd, env: runEnv });
|
|
1080
|
+
if (result.error || result.status !== 0) refuse(`batch ${name} failed (${result.error?.message ?? `exit ${result.status}`}): ${text} (in ${workspace})\n${tail(`${result.stdout ?? ""}\n${result.stderr ?? ""}`)}`);
|
|
1081
|
+
checks.push({ name, command: text, ok: true, ...stamp, crates: crateNames, workspace });
|
|
1010
1082
|
commands.push(text);
|
|
1011
1083
|
};
|
|
1012
|
-
|
|
1084
|
+
for (const workspace of new Set(Object.values(workspaces))) {
|
|
1085
|
+
await batchCheck("fmt", "cargo", ["fmt", "--all", "--check"], crates.filter((unit) => workspaces[unit] === workspace), env, workspace);
|
|
1086
|
+
}
|
|
1013
1087
|
log("[right-release] batch secret-scan: crate directories of the batch");
|
|
1014
1088
|
const scan = deps.scanSecrets ?? scanCrateForSecrets;
|
|
1015
1089
|
const violations = crates.flatMap((unit) => scan(path.join(workspaceRoot, "crates", unit)).map((file) => `${unit}: ${file}`));
|
|
@@ -1019,12 +1093,11 @@ async function runLocalPublishBatch(parsed, deps) {
|
|
|
1019
1093
|
commands.push(scanText);
|
|
1020
1094
|
const featureSetsOf = (unit) => gateConfig?.rust?.[unit]?.featureSets ?? [[]];
|
|
1021
1095
|
for (const layer of layers) {
|
|
1022
|
-
for (const invocation of batchClippyInvocations(layer, { featureSetsOf, assetGatedOf: isAssetGated, crossTargetsOf: (unit) => crossTargetsFor(gateConfig?.rust?.[unit], platform) })) {
|
|
1023
|
-
|
|
1024
|
-
await batchCheck("clippy", "cargo", invocation.args, invocation.crates, { ...testEnv(deps, invocation.assetGated), ...(invocation.env ?? {}) }, invocation.crates.map((unit) => path.join(workspaceRoot, "crates", unit)));
|
|
1096
|
+
for (const invocation of batchClippyInvocations(layer, { featureSetsOf, assetGatedOf: isAssetGated, crossTargetsOf: (unit) => crossTargetsFor(gateConfig?.rust?.[unit], platform), workspaceOf: (unit) => workspaces[unit] })) {
|
|
1097
|
+
await batchCheck("clippy", "cargo", invocation.args, invocation.crates, { ...testEnv(deps, invocation.assetGated), ...(invocation.env ?? {}) }, invocation.workspace);
|
|
1025
1098
|
}
|
|
1026
1099
|
}
|
|
1027
|
-
const receipt = { id: `batch-${head.slice(0, 12)}-${sha256(JSON.stringify(layers)).slice(0, 8)}`, ...stamp, crates, checks };
|
|
1100
|
+
const receipt = { id: `batch-${head.slice(0, 12)}-${sha256(JSON.stringify(layers)).slice(0, 8)}`, ...stamp, crates, workspaces, checks };
|
|
1028
1101
|
|
|
1029
1102
|
// 4. Publish layer by layer. A crate's publish returns only after its registry readback proved the exact
|
|
1030
1103
|
// checksum visible in the index, so layer N+1 starts only once every layer-N dependency is visible.
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
// Narrow reuse identity for plain Node syntax checks. Admission still binds the
|
|
2
|
+
// complete raw Class A environment; the host's runtime libraries remain under
|
|
3
|
+
// the same trusted-host assumption as other locally executed tools.
|
|
4
|
+
import fs from 'node:fs';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import crypto from 'node:crypto';
|
|
7
|
+
import { fileURLToPath } from 'node:url';
|
|
8
|
+
|
|
9
|
+
const hash = (data) => crypto.createHash('sha256').update(data).digest('hex');
|
|
10
|
+
|
|
11
|
+
// Pure data transformation: no values are persisted, only the resulting hash.
|
|
12
|
+
export function nodeCheckFingerprint(input) {
|
|
13
|
+
return hash(JSON.stringify(input));
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function writeNodeCheckDiagnostic(dir, record) {
|
|
17
|
+
let temp;
|
|
18
|
+
try {
|
|
19
|
+
const hex = (s) => typeof s === 'string' && /^[0-9a-f]{64}$/.test(s);
|
|
20
|
+
const scalar = ['key', 'tree', 'source', 'gate', 'gatePackage', 'helper', 'node', 'executable', 'runtime', 'cwd', 'scan', 'normalizedEnvironment', 'overriddenEnvironment'];
|
|
21
|
+
const names = ['schema', ...scalar, 'ancestors', 'environment'];
|
|
22
|
+
if (!record || Object.keys(record).length !== names.length || Object.keys(record).some((k) => !names.includes(k)) || record.schema !== 'rightkit.node-check-components/1' || !scalar.every((k) => hex(record[k]))) return;
|
|
23
|
+
const pairs = (rows, nullable) => Array.isArray(rows) && rows.length <= 4096 && rows.every((r) => Array.isArray(r) && r.length === 2 && hex(r[0]) && (hex(r[1]) || (nullable && r[1] === null)));
|
|
24
|
+
if (!pairs(record.ancestors, true) || !pairs(record.environment, false) || !path.isAbsolute(dir)) return;
|
|
25
|
+
const scratch = fs.realpathSync(process.platform === 'win32' ? 'D:\\scratch' : '/Volumes/D/scratch');
|
|
26
|
+
const target = fs.realpathSync(dir);
|
|
27
|
+
if (!(target === scratch || target.startsWith(scratch + path.sep)) || !fs.statSync(target).isDirectory()) return;
|
|
28
|
+
const file = path.join(target, `node-check-${process.pid}-${crypto.randomBytes(8).toString('hex')}.json`);
|
|
29
|
+
temp = `${file}.tmp`;
|
|
30
|
+
fs.writeFileSync(temp, JSON.stringify(record), { flag: 'wx' });
|
|
31
|
+
fs.renameSync(temp, file);
|
|
32
|
+
} catch { if (temp) { try { fs.unlinkSync(temp); } catch {} } }
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function createNodeCheckCacheDigest({ snapshot, tree, files, gateIdentity, gatePackage = path.dirname(fileURLToPath(import.meta.url)), nodePath, onReject = () => {}, onDiagnostic = null, diagnosticScanId = null }) {
|
|
36
|
+
const reject = (reason, id) => { try { onReject(reason, id); } catch {} return null; };
|
|
37
|
+
let captured = false;
|
|
38
|
+
try {
|
|
39
|
+
const root = fs.realpathSync(snapshot);
|
|
40
|
+
const executable = fs.realpathSync(nodePath);
|
|
41
|
+
const nodeHash = hash(fs.readFileSync(executable));
|
|
42
|
+
const helperHash = hash(fs.readFileSync(fileURLToPath(import.meta.url)));
|
|
43
|
+
const walkGate = (dir) => fs.readdirSync(dir, { withFileTypes: true }).flatMap((e) => (e.name === 'node_modules' || e.name.startsWith('.') ? [] : e.isDirectory() ? walkGate(path.join(dir, e.name)) : [path.join(dir, e.name)]));
|
|
44
|
+
const gateFiles = walkGate(gatePackage).sort().map((f) => [path.relative(gatePackage, f), hash(fs.readFileSync(f))]);
|
|
45
|
+
const gatePackageHash = nodeCheckFingerprint(gateFiles);
|
|
46
|
+
const committed = new Set(files);
|
|
47
|
+
const ancestors = [];
|
|
48
|
+
for (let dir = path.dirname(root);;) {
|
|
49
|
+
const file = path.join(dir, 'package.json');
|
|
50
|
+
try { ancestors.push([file, hash(fs.readFileSync(file))]); }
|
|
51
|
+
catch (e) { if (e.code !== 'ENOENT' && e.code !== 'ENOTDIR') throw e; ancestors.push([file, null]); }
|
|
52
|
+
const parent = path.dirname(dir); if (parent === dir) break; dir = parent;
|
|
53
|
+
}
|
|
54
|
+
return (scan, { childEnv, cwd, command, shimProof = null }) => {
|
|
55
|
+
try {
|
|
56
|
+
const file = typeof scan.id === 'string' && scan.id.startsWith('node-check:') ? scan.id.slice(11) : null;
|
|
57
|
+
if (!file || !committed.has(file) || scan.class !== 'A' || scan.tool !== 'node' || scan.root !== 'content' || scan.cwd || scan.executes || scan.internal || scan.runOutside || scan.deferred || scan.requires?.length || Object.keys(scan.env ?? {}).some((name) => name !== 'RK_SNAPSHOT_TARGETS') || !Array.isArray(scan.args) || scan.args.length !== 2 || scan.args[0] !== '--check' || scan.args[1] !== file) return reject('row-shape', scan.id);
|
|
58
|
+
if (fs.realpathSync(cwd) !== root || fs.realpathSync(command) !== executable) return reject('runtime-path', scan.id);
|
|
59
|
+
const target = path.resolve(root, file);
|
|
60
|
+
if (!target.startsWith(root + path.sep) || fs.realpathSync(target) !== target || !fs.lstatSync(target).isFile()) return reject('source-path', scan.id);
|
|
61
|
+
// These two handles identify the surrounding run, not a Node syntax
|
|
62
|
+
// check; options and preloads remain forbidden below.
|
|
63
|
+
const rows = Object.entries(childEnv).filter(([k, v]) => v !== undefined && v !== null && k !== 'RIGHTKIT_BUILD_OWNERSHIP' && k !== 'CODEX_TOOL_CALL_ID').sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
|
|
64
|
+
// Options, preloads, and dynamic-loader overrides can read unbounded
|
|
65
|
+
// external files, so no cache key is issued when any are present.
|
|
66
|
+
const active = (pattern) => rows.some(([k, v]) => pattern.test(k) && String(v) !== '');
|
|
67
|
+
if (active(/^NODE_OPTIONS$/i)) return reject('node-options', scan.id);
|
|
68
|
+
// This host integration variable configures the computer-use REPL,
|
|
69
|
+
// not Node's CLI. Its value still participates in the fingerprint.
|
|
70
|
+
if (rows.some(([k, v]) => /^NODE_/i.test(k) && k !== 'NODE_REPL_TRUSTED_BROWSER_CLIENT_SHA256S' && String(v) !== '')) return reject('node-environment', scan.id);
|
|
71
|
+
if (active(/^(LD_|DYLD_)/i)) return reject('loader-environment', scan.id);
|
|
72
|
+
if (active(/^(OPENSSL_CONF(?:_INCLUDE)?|OPENSSL_MODULES|SSL_CERT_(?:FILE|DIR)|ICU_DATA)$/i)) return reject('runtime-config-environment', scan.id);
|
|
73
|
+
let environment = rows;
|
|
74
|
+
let overridden = [];
|
|
75
|
+
if (shimProof) {
|
|
76
|
+
const { shim, bin, sentinel, originalEnv } = shimProof;
|
|
77
|
+
if (!originalEnv || typeof originalEnv !== 'object' || !path.isAbsolute(shim) || !path.isAbsolute(bin) || path.dirname(shim) !== bin || !sentinel || sentinel !== path.join(path.dirname(bin), 'unbound')) return reject('shim-proof', scan.id);
|
|
78
|
+
const pathKey = Object.keys(originalEnv).find((k) => k.toUpperCase() === 'PATH') ?? 'PATH';
|
|
79
|
+
const originalPath = originalEnv[pathKey] ?? '';
|
|
80
|
+
const expectedSentinel = path.join(sentinel, hash(scan.id).slice(0, 16));
|
|
81
|
+
if (childEnv.CARGO !== shim || childEnv[pathKey] !== `${bin}${path.delimiter}${originalPath}` || childEnv.CARGO_TARGET_DIR !== expectedSentinel || childEnv.CARGO_BUILD_TARGET_DIR !== expectedSentinel) return reject('shim-proof', scan.id);
|
|
82
|
+
environment = rows.map(([k, v]) => k === 'CARGO' ? [k, { generated: 'cargo-wrapper' }] : k === pathKey ? [k, { generated: 'wrapper-path', original: originalPath }] : (k === 'CARGO_TARGET_DIR' || k === 'CARGO_BUILD_TARGET_DIR') ? [k, { generated: 'scan-sentinel' }] : [k, v]);
|
|
83
|
+
overridden = ['CARGO', 'CARGO_TARGET_DIR', 'CARGO_BUILD_TARGET_DIR'].map((k) => [k, Object.hasOwn(originalEnv, k), originalEnv[k] ?? null]);
|
|
84
|
+
}
|
|
85
|
+
const source = hash(fs.readFileSync(target));
|
|
86
|
+
const key = nodeCheckFingerprint({ schema: 'rightkit.node-check-cache/2', tree, root, file, source, gateIdentity, gatePackageHash, helperHash, executable, nodeHash, nodeVersion: process.version, platform: process.platform, arch: process.arch, ancestors, argv: scan.args, id: scan.id, cwd: root, environment, overridden });
|
|
87
|
+
if (!captured && typeof onDiagnostic === 'function' && scan.id === diagnosticScanId) {
|
|
88
|
+
captured = true;
|
|
89
|
+
try { onDiagnostic({ schema: 'rightkit.node-check-components/1', key, tree: hash(String(tree)), source, gate: hash(String(gateIdentity)), gatePackage: gatePackageHash, helper: helperHash, node: nodeHash, executable: hash(executable), runtime: nodeCheckFingerprint([process.version, process.platform, process.arch]), cwd: hash(root), scan: nodeCheckFingerprint([scan.id, scan.args]), normalizedEnvironment: nodeCheckFingerprint([environment, overridden]), overriddenEnvironment: nodeCheckFingerprint(overridden), ancestors: ancestors.map(([name, value]) => [hash(name), value === null ? null : hash(value)]), environment: rows.map(([name, value]) => [hash(name), hash(String(value))]) }); } catch {}
|
|
90
|
+
}
|
|
91
|
+
return key;
|
|
92
|
+
} catch { return reject('row-error', scan?.id); }
|
|
93
|
+
};
|
|
94
|
+
} catch { return (scan) => reject('setup-error', scan?.id); }
|
|
95
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rightkit/release",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.46",
|
|
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,6 +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
104
|
"test:registry-parity": "node registry-parity.mjs --allow-unpublished",
|
|
104
105
|
"test:signer:windows": "node sign-release-manifest.integration.mjs",
|
|
105
106
|
"verify:standalone": "node standalone-clone-verify.mjs"
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
// Optional bounded measurements; never part of a gate verdict or cache key.
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import crypto from 'node:crypto';
|
|
5
|
+
|
|
6
|
+
export function writePerformanceDiagnostic(dir, category, rows) {
|
|
7
|
+
let temp;
|
|
8
|
+
try {
|
|
9
|
+
if (!dir || !path.isAbsolute(dir) || !['preflight', 'snapshot-verify'].includes(category) || !Array.isArray(rows) || rows.length > 256) return;
|
|
10
|
+
if (!rows.every((r) => r && /^[a-z0-9-]{1,80}$/.test(r.label) && Number.isFinite(r.ms) && r.ms >= 0 && Number.isInteger(r.count) && r.count >= 0)) return;
|
|
11
|
+
const scratch = fs.realpathSync(process.platform === 'win32' ? 'D:\\scratch' : '/Volumes/D/scratch');
|
|
12
|
+
const target = fs.realpathSync(dir);
|
|
13
|
+
if (!(target === scratch || target.startsWith(scratch + path.sep)) || !fs.statSync(target).isDirectory()) return;
|
|
14
|
+
const file = path.join(target, `timing-${category}-${process.pid}-${crypto.randomBytes(8).toString('hex')}.json`);
|
|
15
|
+
temp = `${file}.tmp`;
|
|
16
|
+
fs.writeFileSync(temp, JSON.stringify({ schema: 'rightkit.performance-diagnostic/1', category, rows: rows.map(({ label, ms, count }) => ({ label, ms, count })) }), { flag: 'wx' });
|
|
17
|
+
fs.renameSync(temp, file);
|
|
18
|
+
} catch { if (temp) { try { fs.unlinkSync(temp); } catch {} } }
|
|
19
|
+
}
|
package/provenance-verify.mjs
CHANGED
|
@@ -144,6 +144,11 @@ export function verifyReceiptCoverage(receipt, payload) {
|
|
|
144
144
|
covered(receipt, payload, "stageEvidence", STAGE_EVIDENCE_FIELDS, "stage evidence");
|
|
145
145
|
covered(receipt, payload, "resultEvidence", RESULT_EVIDENCE_FIELDS, "result evidence");
|
|
146
146
|
covered(receipt, payload, "br19Evidence", BR19_EVIDENCE_FIELDS, "BR19 evidence");
|
|
147
|
+
const receiptClass = Object.hasOwn(receipt, "failureClass");
|
|
148
|
+
const signedClass = isRecord(payload.result) && Object.hasOwn(payload.result, "failureClass");
|
|
149
|
+
if (receiptClass !== signedClass || (receiptClass && !equalValue(receipt.failureClass, payload.result.failureClass))) refuse("evidence", "receipt failureClass differs from the signed result");
|
|
150
|
+
// RustRight treats a missing postChecks and null as equivalent for older receipts.
|
|
151
|
+
if (!equalValue(receipt.postChecks ?? null, payload.result?.postChecks ?? null)) refuse("evidence", "receipt postChecks differs from the signed result");
|
|
147
152
|
for (const name of RETIRED_RESULT_FIELDS) {
|
|
148
153
|
if (receipt[name] !== undefined || (isRecord(payload.resultEvidence) && payload.resultEvidence[name] !== undefined)) refuse("evidence", `receipt ${name} is a retired verdict-reuse field`);
|
|
149
154
|
}
|
|
@@ -199,11 +204,41 @@ export function verifyBr19Evidence(receipt, payload) {
|
|
|
199
204
|
if (!(typeof environment.digest === "string" && /^[0-9a-f]{64}$/.test(environment.digest) && names("forwarded") && names("dropped"))) bad("environment needs a 64-hex digest and forwarded and dropped name lists");
|
|
200
205
|
}
|
|
201
206
|
|
|
207
|
+
export const FAILURE_CLASSES = Object.freeze(["admission", "compile", "test", "tool", "cancelled", "timeout", "broker"]);
|
|
208
|
+
/** Validate an optional signed failure class; verifyReceiptCoverage binds the receipt copy. */
|
|
209
|
+
export function verifyFailureClass(receipt, payload) {
|
|
210
|
+
const signed = isRecord(payload.result) && Object.hasOwn(payload.result, "failureClass");
|
|
211
|
+
const copy = Object.hasOwn(receipt, "failureClass");
|
|
212
|
+
if (signed !== copy || (signed && !equalValue(receipt.failureClass, payload.result.failureClass))) refuse("evidence", "receipt failureClass differs from the signed result");
|
|
213
|
+
if (signed && payload.result.failureClass !== null && !FAILURE_CLASSES.includes(payload.result.failureClass)) refuse("evidence", "signed failureClass is neither null nor a recognized class");
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
const POST_CHECK_FIELDS = Object.freeze(["schema", "ran", "failed", "inputClosure", "inputBoundary", "verified"]);
|
|
217
|
+
/** Validate signed post-run checks. Snapshot callers additionally require applicable, signed boundary evidence. */
|
|
218
|
+
export function verifyPostChecks(receipt, payload, { snapshotAttested = false } = {}) {
|
|
219
|
+
const checks = payload.result?.postChecks ?? null;
|
|
220
|
+
if (!equalValue(receipt.postChecks ?? null, checks)) refuse("evidence", "receipt postChecks differs from the signed result");
|
|
221
|
+
if (checks === null) return null;
|
|
222
|
+
const bad = () => refuse("evidence", "the signed result's postChecks is malformed");
|
|
223
|
+
if (!isRecord(checks) || Object.keys(checks).length !== POST_CHECK_FIELDS.length || POST_CHECK_FIELDS.some((key) => !Object.hasOwn(checks, key))) bad();
|
|
224
|
+
if (checks.schema !== "rustright.post-checks.v1" || typeof checks.ran !== "boolean" || typeof checks.verified !== "boolean" || !Array.isArray(checks.failed) || !checks.failed.every((name) => ["freshness", "projection", "toolchainIdentity"].includes(name))) bad();
|
|
225
|
+
if (!["verified", "inputs-mutated", "unverified", "not-applicable"].includes(checks.inputClosure) || !["intact", "violated", "unverified", "unrequested", "not-applicable"].includes(checks.inputBoundary)) bad();
|
|
226
|
+
const boundary = payload.inputBoundary?.status;
|
|
227
|
+
if (typeof boundary === "string" && boundary !== checks.inputBoundary) refuse("evidence", "postChecks.inputBoundary differs from the signed inputBoundary");
|
|
228
|
+
if (snapshotAttested && (checks.inputClosure === "not-applicable" || checks.inputBoundary === "not-applicable" || typeof boundary !== "string" || boundary !== checks.inputBoundary)) refuse("evidence", "snapshot postChecks lacks applicable signed input boundary or closure evidence");
|
|
229
|
+
const verified = checks.ran && checks.failed.length === 0 && ["verified", "not-applicable"].includes(checks.inputClosure) && ["intact", "unrequested", "not-applicable"].includes(checks.inputBoundary);
|
|
230
|
+
if (checks.verified !== verified) refuse("evidence", "the signed postChecks.verified does not follow from its checks");
|
|
231
|
+
if (payload.result?.failureClass === "compile" && !(checks.ran && checks.failed.length === 0)) refuse("evidence", "a signed compile failure whose post-run checks did not all run and pass");
|
|
232
|
+
return checks;
|
|
233
|
+
}
|
|
234
|
+
|
|
202
235
|
/** `verify_receipt_strict`: `verifyReceiptLenient`, then the signed result evidence and the BR19 shape. A gate applies it to every compile receipt, never the lenient form alone. */
|
|
203
236
|
export function verifyReceiptStrict(receipt, pins, expected) {
|
|
204
237
|
const payload = verifyReceiptLenient(receipt, pins, expected);
|
|
205
238
|
verifyResultEvidence(receipt, payload);
|
|
206
239
|
verifyBr19Evidence(receipt, payload);
|
|
240
|
+
verifyFailureClass(receipt, payload);
|
|
241
|
+
verifyPostChecks(receipt, payload);
|
|
207
242
|
return payload;
|
|
208
243
|
}
|
|
209
244
|
|