@rightkit/release 0.6.50 → 0.6.52
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/bin/rightkit-gate.mjs +137 -18
- package/build-ownership.mjs +26 -5
- package/deterministic-scans.mjs +90 -15
- package/install-app.mjs +3 -0
- package/package.json +1 -1
- package/rightkit-versions.json +1 -1
- package/unit-list-compile.mjs +87 -8
- package/web-build.mjs +6 -0
package/bin/rightkit-gate.mjs
CHANGED
|
@@ -164,10 +164,27 @@ function gatePackageIdentity(gatePackage = path.resolve(path.dirname(fileURLToPa
|
|
|
164
164
|
return gatePackageMemo.get(gatePackage);
|
|
165
165
|
}
|
|
166
166
|
// GC-A24: the class A key schema a standalone-tool row carries in place of the environment digest; bumped when what a class A key covers changes.
|
|
167
|
-
|
|
167
|
+
// Bump when any class A rule's verdict for the same inputs changes (NN23): the class A key names the rules' version, never every gate file's bytes.
|
|
168
|
+
const CLASS_A_KEY_SCHEMA = "rightkit.class-a-key/3";
|
|
168
169
|
/** Whether a class A row's verdict depends on the installed dependencies (GC-A24): it executes repository code, or its tool is pnpm. */
|
|
169
170
|
function classAEnvironmentBound(scan) { return scan.executes === true || scan.tool === "pnpm"; }
|
|
170
171
|
let classBKeyIdentityMemo = null;
|
|
172
|
+
/** Adrian's approval of one cache-miss report for ONE run: RK_GATE_MISS_APPROVAL names a JSON file {digest, by: "adrian", reason}. Attested, not
|
|
173
|
+
* authenticated (an agent could write it) until Adrian picks a trust root; every run prints it. */
|
|
174
|
+
function missApproval(o, digest, commit) {
|
|
175
|
+
const file = o.env?.RK_GATE_MISS_APPROVAL;
|
|
176
|
+
if (!file) return { ok: false, why: "no approval given" };
|
|
177
|
+
let e; try { e = JSON.parse(fs.readFileSync(file, "utf8")); } catch (error) { return { ok: false, why: `${file} unreadable (${error.message})` }; }
|
|
178
|
+
if (e?.by !== "adrian") return { ok: false, why: `${file} is not by adrian` };
|
|
179
|
+
if (e?.digest !== digest) return { ok: false, why: `${file} approves report ${String(e?.digest).slice(0, 12)}, this run's report is ${digest.slice(0, 12)}` };
|
|
180
|
+
if (typeof e?.reason !== "string" || !e.reason.trim()) return { ok: false, why: `${file} gives no reason` };
|
|
181
|
+
// Single use (Adrian 2026-11-06: "why would it be recorded for 2 hours if it's for a single run?"): the run it permits consumes it.
|
|
182
|
+
const used = path.join(gateRunsRoot({ env: o.env, platform: o.platform }), "rightkit-gate-misses", "consumed", `${digest}.json`);
|
|
183
|
+
try { fs.mkdirSync(path.dirname(used), { recursive: true }); fs.writeFileSync(used, JSON.stringify({ digest, commit, file, reason: e.reason, at: new Date().toISOString() }), { flag: "wx" }); }
|
|
184
|
+
catch (error) { return { ok: false, why: error?.code === "EEXIST" ? `report ${digest.slice(0, 12)} was already approved for one run and that run has used it` : `the approval could not be recorded as used (${error.message})` }; }
|
|
185
|
+
return { ok: true, note: `cache-miss approval ${file} (attested, not authenticated): by adrian for this one run of report ${digest.slice(0, 12)} on ${String(commit).slice(0, 12)}: ${e.reason}` };
|
|
186
|
+
}
|
|
187
|
+
|
|
171
188
|
function classBKeyIdentity() {
|
|
172
189
|
if (classBKeyIdentityMemo === null) {
|
|
173
190
|
const h = createHash("sha256");
|
|
@@ -476,7 +493,11 @@ export function classAEnvironmentDigest({ root, files, spawn = defaultSpawn, inc
|
|
|
476
493
|
// `gatePackage` defaults to this very package; only a test that must not be disturbed by other writers of the live package injects another.
|
|
477
494
|
const gatePkg = gatePackage;
|
|
478
495
|
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)]));
|
|
479
|
-
|
|
496
|
+
// NN23 (approved by Adrian 2026-11-06 with its one cold run): the gate's CODE enters the key as CLASS_A_KEY_SCHEMA, bumped by hand when a
|
|
497
|
+
// class A rule's verdict changes, not as the bytes of every file (any release re-keyed every row). Data the scans read (advisory database,
|
|
498
|
+
// rule tables, configs) still enters by content; release-only files (changelog, docs, version manifests, the package's own tests) do not.
|
|
499
|
+
const releaseOnly = (rel) => /\.(?:mjs|cjs|js|ts)$/.test(rel) || /\.md$/i.test(rel) || /(^|\/)(?:package\.json|rightkit-versions\.json)$/.test(rel) || /\.test\.(?:mjs|js)$/.test(rel);
|
|
500
|
+
const gateFiles = [`class-a-key-schema:${CLASS_A_KEY_SCHEMA}`, ...walkGate(gatePkg).sort().map((f) => path.relative(gatePkg, f)).filter((rel) => !releaseOnly(rel)).map((rel) => `${rel}:${fileDigest(path.join(gatePkg, rel))}`)];
|
|
480
501
|
// Bounded: a pnpm that switches itself to the repository's packageManager version on first use, or waits on the network,
|
|
481
502
|
// must fail the probe (and its process tree) within PNPM_PROBE_TIMEOUT_MS, never hang an admission.
|
|
482
503
|
const pnpmVersion = (() => {
|
|
@@ -838,6 +859,8 @@ export function rustUnitOfScanId(id, known = null) {
|
|
|
838
859
|
let rest;
|
|
839
860
|
if (["clippy", "check", "check-features", "check-dependent", "doc"].includes(parts[0])) rest = parts.slice(1);
|
|
840
861
|
else if (parts[0] === "test" && (parts[1] === "rust" || parts[1] === "rust-serial")) rest = parts.slice(2);
|
|
862
|
+
// A publisher row (`publisher:cargo:<crate>:<n>`) reads the same crate closure as that crate's own rows (NN02: an unchanged crate reruns none of them).
|
|
863
|
+
else if (parts[0] === "publisher" && parts[1] === "cargo" && /^\d+$/.test(parts[parts.length - 1] ?? "")) rest = parts.slice(2, -1);
|
|
841
864
|
else return null;
|
|
842
865
|
if (!(known instanceof Set)) return rest[0] ?? null;
|
|
843
866
|
for (let take = rest.length; take >= 1; take -= 1) { const name = rest.slice(0, take).join(":"); if (known.has(name)) return name; }
|
|
@@ -880,7 +903,9 @@ const within = (dir, p) => dir === "." || p === dir || p.startsWith(`${dir}/`);
|
|
|
880
903
|
*/
|
|
881
904
|
// A source (a test, usually) that navigates out of its crate at run time without naming the path: the workspace root, the
|
|
882
905
|
// current directory, a bare ".." segment, or the manifest directory's parent. Its tests may read anything in the repository.
|
|
883
|
-
|
|
906
|
+
// A comparison with ".." (`name != ".."`), a method whose name only ends in current_dir (`get_current_dir()`), `.ancestors()` of a runtime path and
|
|
907
|
+
// comment text do not leave the crate; they keyed whole crates' tests on the whole tree (rightkit-fs, rightkit-child-process; NN20, 2026-11-06).
|
|
908
|
+
const TEST_LEAVES_CRATE = /CARGO_WORKSPACE_DIR|workspace_root|(?<![A-Za-z0-9_])current_dir\s*\(|(?<![=!]=\s{0,4})"\.\.\/?"|CARGO_MANIFEST_DIR[^;\n]{0,120}\.(?:parent|ancestors)\s*\(/;
|
|
884
909
|
|
|
885
910
|
export function externalInputs({ dir, files, readBlob, exists, includeRuntimePaths = true }) {
|
|
886
911
|
const paths = new Set(); let unresolved = null; let leavesCrate = null;
|
|
@@ -935,7 +960,13 @@ export function externalInputs({ dir, files, readBlob, exists, includeRuntimePat
|
|
|
935
960
|
for (const m of text.matchAll(RERUN_LITERAL)) consider(file, [dir], m[1].trim());
|
|
936
961
|
if (BUILD_LEAVES_CRATE.test(text)) stop(`${file}: a build script that reads files and navigates out of its crate`);
|
|
937
962
|
}
|
|
938
|
-
|
|
963
|
+
// Only TEST code can make a test read files outside the crate: an integration test or bench file, or the #[cfg(test)] part of a source file.
|
|
964
|
+
// Library code that resolves a caller's relative path (std::env::current_dir) does not (rightkit-fs; it keyed every dependent's tests on the whole tree, NN20).
|
|
965
|
+
if (includeRuntimePaths && !build && !external && leavesCrate === null) {
|
|
966
|
+
const at = text.indexOf("#[cfg(test)]");
|
|
967
|
+
const testText = /(^|\/)(?:tests|benches)\//.test(file) ? text : at >= 0 ? text.slice(at) : "";
|
|
968
|
+
if (testText && TEST_LEAVES_CRATE.test(testText.replace(/\/\/[^\n]*/g, ""))) leavesCrate = file;
|
|
969
|
+
}
|
|
939
970
|
};
|
|
940
971
|
for (const file of files) if (file.endsWith(".rs")) enqueue(file, { build: path.posix.basename(file) === "build.rs" && path.posix.dirname(file) === dir });
|
|
941
972
|
// Fixed point: an out-of-crate .rs file that is reached is itself a source, so its own references are followed, and theirs.
|
|
@@ -1135,6 +1166,8 @@ export function buildCacheDigest({ objectId, headTree, rustUnits = [], npmUnits
|
|
|
1135
1166
|
}
|
|
1136
1167
|
if (/^node-check:/.test(scan.id)) { const f = scan.id.slice("node-check:".length); return [f, ...ancestorDirsOf(path.posix.dirname(f)).map((d) => inWs(d, "package.json"))]; }
|
|
1137
1168
|
if (scan.internal === "secret-scan" && Array.isArray(scan.dirs) && typeof listFiles === "function") return [...new Set(scan.dirs.flatMap((d) => listFiles(d)))];
|
|
1169
|
+
// The lock checks read the lock and manifest files of the one directory their id names (NN20: on the whole tree, any commit reran them).
|
|
1170
|
+
{ const m = /^(?:gradle-lock|python-lock):(.+)$/.exec(scan.id); if (m && typeof listFiles === "function") return listFiles(m[1]); }
|
|
1138
1171
|
if (scan.id === "shellcheck") return [...args.filter((x) => /\.(sh|bash)$/.test(x)), ".shellcheckrc"];
|
|
1139
1172
|
if (scan.id === "actionlint") return [...args.filter((x) => /\.ya?ml$/.test(x)), ".github/actionlint.yaml"];
|
|
1140
1173
|
return null;
|
|
@@ -1177,15 +1210,27 @@ export function buildCacheDigest({ objectId, headTree, rustUnits = [], npmUnits
|
|
|
1177
1210
|
// every member it names: each member's own compile key, in member order, plus the batch's own id and command (its member list, target and
|
|
1178
1211
|
// environment). Any member that falls back to the whole tree makes the batch fall back too. A changed member changes the key, so the
|
|
1179
1212
|
// batch runs again as a whole (cargo is incremental); no member's result is ever taken from another invocation's.
|
|
1180
|
-
if (/^(?:clippy|check|doc):batch:/.test(String(scan.id)) && Array.isArray(scan.batch?.units) && scan.batch.units.length && scan.batch.units.every((n) => known.has(n))) {
|
|
1213
|
+
if (/^(?:clippy|check|doc|test):batch:/.test(String(scan.id)) && Array.isArray(scan.batch?.units) && scan.batch.units.length && scan.batch.units.every((n) => known.has(n))) {
|
|
1181
1214
|
const keys = scan.batch.units.map((n) => rustUnitKey(n, scan));
|
|
1182
1215
|
return keys.includes(undefined) ? whole() : canonicalJson({ kind: "rust-batch", id: scan.id, units: scan.batch.units.map((n, i) => [n, keys[i]]) });
|
|
1183
1216
|
}
|
|
1217
|
+
// A grouped publisher invocation (publisher-batch:*) is keyed on every crate it names (`-p`), each crate's own key, like a class B batch: on the
|
|
1218
|
+
// whole tree it missed on every commit, whatever the commit touched (NN20).
|
|
1219
|
+
if (/^publisher-batch:/.test(String(scan.id)) && Array.isArray(scan.args)) {
|
|
1220
|
+
const names = scan.args.flatMap((a, i) => (a === "-p" && typeof scan.args[i + 1] === "string" ? [scan.args[i + 1]] : []));
|
|
1221
|
+
if (names.length && names.every((n) => known.has(n))) {
|
|
1222
|
+
const keys = names.map((n) => rustUnitKey(n, scan));
|
|
1223
|
+
if (!keys.includes(undefined)) return canonicalJson({ kind: "rust-batch", id: scan.id, units: names.map((n, i) => [n, keys[i]]) });
|
|
1224
|
+
}
|
|
1225
|
+
}
|
|
1184
1226
|
const unit = rustUnitOfScanId(scan.id, known);
|
|
1227
|
+
const debug = process.env.RK_GATE_KEY_DEBUG && new RegExp(process.env.RK_GATE_KEY_DEBUG).test(scan.id);
|
|
1185
1228
|
if (!unit) {
|
|
1229
|
+
if (debug) process.stderr.write(`key-debug ${scan.id}: no Rust unit (known ${known.size})\n`);
|
|
1186
1230
|
return npmScanKey(scan) ?? whole();
|
|
1187
1231
|
}
|
|
1188
1232
|
const keyed = rustUnitKey(unit, scan);
|
|
1233
|
+
if (debug) process.stderr.write(`key-debug ${scan.id}: unit ${unit}, publisherPhase ${scan.publisherPhase}, ${keyed === undefined ? "falls back to the whole tree" : "crate key"}\n`);
|
|
1189
1234
|
return keyed === undefined ? whole() : keyed;
|
|
1190
1235
|
} catch (error) { onKeyError?.(scan, error); return null; }
|
|
1191
1236
|
};
|
|
@@ -1194,7 +1239,7 @@ export function buildCacheDigest({ objectId, headTree, rustUnits = [], npmUnits
|
|
|
1194
1239
|
// crate share one computation (B7: per-job prep, one git read of the manifest and one closure walk per scan before).
|
|
1195
1240
|
// (unitKeyMemo is declared before the returned key function; declared here it was never initialised and every Rust key threw.)
|
|
1196
1241
|
function rustUnitKey(unit, scan) {
|
|
1197
|
-
const memoKey = `${unit}\0${/^test:rust(?:-serial)
|
|
1242
|
+
const memoKey = `${unit}\0${/^test:(?:rust(?:-serial)?|batch):/.test(scan.id) || scan.publisherPhase === "test" ? "test" : "compile"}`;
|
|
1198
1243
|
if (unitKeyMemo.has(memoKey)) return unitKeyMemo.get(memoKey);
|
|
1199
1244
|
const keyed = rustUnitKeyOf(unit, scan);
|
|
1200
1245
|
unitKeyMemo.set(memoKey, keyed);
|
|
@@ -1204,7 +1249,7 @@ export function buildCacheDigest({ objectId, headTree, rustUnits = [], npmUnits
|
|
|
1204
1249
|
const head = byName.get(unit);
|
|
1205
1250
|
const ws = wsOf(head); const lock = lockFor(ws);
|
|
1206
1251
|
if (!lock || typeof listFiles !== "function" || typeof readBlob !== "function") return undefined;
|
|
1207
|
-
const testScan = /^test:rust(?:-serial)
|
|
1252
|
+
const testScan = /^test:(?:rust(?:-serial)?|batch):/.test(scan.id) || scan.publisherPhase === "test";
|
|
1208
1253
|
const ownConfig = crateFeatures?.[unit] ?? crateFeatures?.[crateOf(head)] ?? null;
|
|
1209
1254
|
let testInputs = []; let declaredInputs = false;
|
|
1210
1255
|
if (testScan) {
|
|
@@ -1213,7 +1258,7 @@ export function buildCacheDigest({ objectId, headTree, rustUnits = [], npmUnits
|
|
|
1213
1258
|
if (!Array.isArray(declared) || declared.length === 0 || !declared.every(plainRelative)) return undefined;
|
|
1214
1259
|
testInputs = [...new Set(declared)].sort(); declaredInputs = true;
|
|
1215
1260
|
}
|
|
1216
|
-
} else if (!COMPILE_SCAN_PREFIXES.has(String(scan.id).split(":")[0])) return undefined;
|
|
1261
|
+
} else if (!COMPILE_SCAN_PREFIXES.has(String(scan.id).split(":")[0]) && scan.publisherPhase !== "compile") return undefined;
|
|
1217
1262
|
if (!reachMemos.has(ws)) reachMemos.set(ws, new Map());
|
|
1218
1263
|
const reached = [...reach(lock, crateOf(head), reachMemos.get(ws))];
|
|
1219
1264
|
// A crate that is its own workspace (one workspace and lock per crate) holds its sibling crates in its lock as path packages: the
|
|
@@ -1223,7 +1268,8 @@ export function buildCacheDigest({ objectId, headTree, rustUnits = [], npmUnits
|
|
|
1223
1268
|
for (const member of closure) {
|
|
1224
1269
|
const found = externalOf(member);
|
|
1225
1270
|
if (found.unresolved) return undefined;
|
|
1226
|
-
|
|
1271
|
+
// A dependency's own tests never run here: only the tested crate's test code decides whether its tests leave the crate.
|
|
1272
|
+
if (testScan && !declaredInputs && found.leavesCrate && member === head) return undefined;
|
|
1227
1273
|
for (const p of found.paths) extra.add(p);
|
|
1228
1274
|
}
|
|
1229
1275
|
// The shared inputs, projected to what this crate consumes.
|
|
@@ -2282,6 +2328,25 @@ export async function closeSnapshotStage({ o, ds, root, stage, step = "stage", t
|
|
|
2282
2328
|
const restaged = stage === "package" ? await restagedSidecars({ o, ds, prior, now }) : { paths: new Set(), receipts: new Set(), producers: new Set(), problems: [] };
|
|
2283
2329
|
problems.push(...restaged.problems);
|
|
2284
2330
|
for (const [p, e] of prior) if (e.kind === "staged" && !restaged.paths.has(p) && !restaged.receipts.has(p) && !(restaged.producers.has(e.producer?.step) && !now.has(p)) && (!now.has(p) || entryKey(now.get(p)) !== entryKey(e))) problems.push(`${p} is a staged sidecar output and ${now.has(p) ? "changed" : "was removed"} after it was staged (a staged entry is immutable for the door run)`);
|
|
2331
|
+
// Evidence (Pulse Windows dev, 2026-11-06): for each staged entry that changed, its sha256 then and now; for a receipt, the fields that differ.
|
|
2332
|
+
for (const [p, e] of prior) {
|
|
2333
|
+
if (e.kind !== "staged" || !now.has(p) || entryKey(now.get(p)) === entryKey(e) || restaged.paths.has(p) || restaged.receipts.has(p)) continue;
|
|
2334
|
+
o.err(`${tag} staged-change evidence: ${p}: sha256 ${String(e.sha256).slice(0, 16)} at staging (${e.size} bytes) -> ${String(now.get(p).sha256).slice(0, 16)} now (${now.get(p).size} bytes)`);
|
|
2335
|
+
const before = ds.stagedReceipts?.get(p);
|
|
2336
|
+
if (before) {
|
|
2337
|
+
try {
|
|
2338
|
+
const a = JSON.parse(before); const b = JSON.parse(fs.readFileSync(path.join(ds.path, p), "utf8"));
|
|
2339
|
+
for (const k of new Set([...Object.keys(a), ...Object.keys(b)])) if (k !== "files" && JSON.stringify(a[k]) !== JSON.stringify(b[k])) o.err(`${tag} staged-change evidence: ${p}: ${k}: ${JSON.stringify(a[k]).slice(0, 200)} -> ${JSON.stringify(b[k]).slice(0, 200)}`);
|
|
2340
|
+
const byName = (list) => new Map((Array.isArray(list) ? list : []).map((f) => [f.name ?? f.dest, f]));
|
|
2341
|
+
const fa = byName(a.files); const fb = byName(b.files);
|
|
2342
|
+
for (const n of new Set([...fa.keys(), ...fb.keys()])) {
|
|
2343
|
+
const x = fa.get(n) ?? {}; const y = fb.get(n) ?? {};
|
|
2344
|
+
const diff = [...new Set([...Object.keys(x), ...Object.keys(y)])].filter((k) => !["changed", "cached"].includes(k) && JSON.stringify(x[k]) !== JSON.stringify(y[k]));
|
|
2345
|
+
if (diff.length) o.err(`${tag} staged-change evidence: ${p}: files[${n}]: ${diff.map((k) => `${k} ${JSON.stringify(x[k]).slice(0, 80)} -> ${JSON.stringify(y[k]).slice(0, 80)}`).join("; ")}`);
|
|
2346
|
+
}
|
|
2347
|
+
} catch (error) { o.err(`${tag} staged-change evidence: ${p}: the receipts could not be compared (${error.message})`); }
|
|
2348
|
+
}
|
|
2349
|
+
}
|
|
2285
2350
|
if (problems.length) { for (const p of problems.slice(0, 10)) o.err(`${tag} RK_CHECK_ERROR: [${stage}] ${p}`); return { ok: false, entries: ds.ledger?.entries ?? [] }; }
|
|
2286
2351
|
// The compile's own verify (snapshot-check.mjs, 5.09d) returned the entries it admitted: they must be the entries this walk found.
|
|
2287
2352
|
if (Array.isArray(ds.compileAdmitted) && stage === "compile") {
|
|
@@ -2410,6 +2475,8 @@ export async function stageSidecarsOnce({ o, ds, root, git = null, configs, appD
|
|
|
2410
2475
|
const priorPaths = new Set(before.map((e) => e.path));
|
|
2411
2476
|
const priorByPath = new Map(before.map((e) => [e.path, e]));
|
|
2412
2477
|
ds.ledger = { entries: walked.entries.map((e) => (priorPaths.has(e.path) && priorByPath.get(e.path).sha256 === e.sha256 ? priorByPath.get(e.path) : { ...e, kind: "staged", producer: { stage: "sidecar", step: config } })) };
|
|
2478
|
+
// Evidence for a later "changed after it was staged": the receipt exactly as this staging wrote it.
|
|
2479
|
+
if (receiptAbs) { try { (ds.stagedReceipts ??= new Map()).set(receiptAbs, fs.readFileSync(path.join(ds.path, receiptAbs), "utf8")); } catch { /* the close names the change without the field diff */ } }
|
|
2413
2480
|
}
|
|
2414
2481
|
return true;
|
|
2415
2482
|
}
|
|
@@ -2490,7 +2557,9 @@ export async function stageWebBuildOnce({ o, ds, root, git = null, appDir, cli,
|
|
|
2490
2557
|
try { declared = readDeclaredInputs(ds.path).map((x) => x.split(/[\\/]/).join("/")); }
|
|
2491
2558
|
catch (e) { if (e instanceof SnapshotRequestError) return true; throw e; } // a malformed declaration refuses in the compile, which names it
|
|
2492
2559
|
const absent = () => declared.filter((rel) => !(o.exists ?? fs.existsSync)(path.join(ds.path, ...rel.split("/"))));
|
|
2493
|
-
|
|
2560
|
+
// Children of this run (the app's own `right-release web-build` step) reuse these outputs instead of rebuilding them (web-build.mjs).
|
|
2561
|
+
const markBuilt = () => { if (declared.length && o.env) o.env.RK_GATE_WEB_BUILT = snapshotAppRootOf(ds.path, appDir); };
|
|
2562
|
+
if (!absent().length) { markBuilt(); return true; }
|
|
2494
2563
|
const configs = git ? committedWebBuildConfigs({ o, git, commit, appDir, base: ds.path }) : [];
|
|
2495
2564
|
if (!configs.length) { o.out(`${tag} [${stage}] declared compile input(s) ${absent().join(", ")} are absent from the snapshot and no release config under ${appDir} declares web.build; the compile will report them missing`); return true; }
|
|
2496
2565
|
const { declaredOutputProblems } = await import("../stage-ledger.mjs");
|
|
@@ -2538,6 +2607,7 @@ export async function stageWebBuildOnce({ o, ds, root, git = null, appDir, cli,
|
|
|
2538
2607
|
} catch (e) { o.out(`${tag} [${stage}] web-build ${config}: the dist cache was not written (${e.message}); the next run builds again`); }
|
|
2539
2608
|
}
|
|
2540
2609
|
}
|
|
2610
|
+
if (!absent().length) markBuilt();
|
|
2541
2611
|
return true;
|
|
2542
2612
|
}
|
|
2543
2613
|
|
|
@@ -4167,7 +4237,15 @@ export async function main(argv, io = {}) {
|
|
|
4167
4237
|
// first, in the tier asked for (compile by default), and plans nothing while they are red. --plan and --class-a (which runs them in
|
|
4168
4238
|
// `check`) are untouched.
|
|
4169
4239
|
if (snapshot && !classAOnly) {
|
|
4170
|
-
|
|
4240
|
+
// NN07/NN02: the same app-rule verdict for the same tree, rules, tier and arguments is reused (ruleVerdictCache, as `check` does): a warm run reran it every time.
|
|
4241
|
+
const appArgv = ["--repo", root, "--commit", snapshot, "--rule-tier", option("--rule-tier") ?? "compile"];
|
|
4242
|
+
const appTree = o.appCheck ? null : git("rev-parse", `${snapshot}^{tree}`);
|
|
4243
|
+
const appCache = appTree && !failed(appTree) ? ruleVerdictCache({ checkout: root, spawn: o.spawn }) : null;
|
|
4244
|
+
const appRulesKey = appCache ? appCache.key({ rule: "app-check-entry", tree: text(appTree).trim(), args: appArgv.slice(2), gate: gatePackageIdentity(o.gatePackage) }) : null;
|
|
4245
|
+
const appRules = appRulesKey && appCache.passed(appRulesKey)
|
|
4246
|
+
? (o.out(`check: ${String(snapshot).slice(0, 12)} app rules (${option("--rule-tier") ?? "compile"} tier): cached pass (tree ${text(appTree).trim().slice(0, 12)})`), 0)
|
|
4247
|
+
: await (o.appCheck ?? (await import("../app-check.mjs")).main)(appArgv, { out: o.out, err: o.err, label: "check", cwd: o.cwd });
|
|
4248
|
+
if (appRulesKey && appRules === 0) appCache.pass(appRulesKey);
|
|
4171
4249
|
if (appRules !== 0) { const id = git("rev-parse", String(snapshot)); o.err(`${tag} BLOCKED: the app rules are red for ${(failed(id) ? String(snapshot) : text(id).trim()).slice(0, 12)}; no scan was planned or run`); return appRules; }
|
|
4172
4250
|
}
|
|
4173
4251
|
|
|
@@ -4615,7 +4693,7 @@ export async function main(argv, io = {}) {
|
|
|
4615
4693
|
};
|
|
4616
4694
|
for (const requirement of external) plan.scans.push(adapt(requirement));
|
|
4617
4695
|
const dependencies = Object.fromEntries(unionContext.selected.map((unit) => [unit.selector, (unit.deps ?? []).filter((dep) => unionContext.selected.some((u) => u.selector === dep))]));
|
|
4618
|
-
unionScheduler = publisherUnionScheduler({ jobs, dependencies, initialFailures, requirements: external, adapt, signal: ac.signal, onCoverage: (coverage) => { unionContext.coverage = coverage; }, verify: async ({ row, member, attempts, requirement }) => {
|
|
4696
|
+
unionScheduler = publisherUnionScheduler({ reuseProofs: o.env.RK_GATE_PUBLISHER_REUSE !== "0", concurrency: Math.max(1, Number(o.env.RK_GATE_PUBLISHER_JOBS ?? 1) || 1), jobs, dependencies, initialFailures, requirements: external, adapt, signal: ac.signal, onCoverage: (coverage) => { unionContext.coverage = coverage; }, verify: async ({ row, member, attempts, requirement }) => {
|
|
4619
4697
|
const verdict = verdicts.get(member.selector);
|
|
4620
4698
|
const proof = { commit: snapshotBCommit.commit, tree: snapshotBCommit.tree, requirement: member.coverageKey, command: row?.command ?? null, attempts, snapshotEvidence: row?.snapshotEvidence ?? null, testRun: row?.testRun ?? null, results: row?.results ?? null };
|
|
4621
4699
|
unionContext.commands.push({ selector: member.selector, id: member.id, ...proof });
|
|
@@ -4769,7 +4847,7 @@ export async function main(argv, io = {}) {
|
|
|
4769
4847
|
const { files, ids, digestOf } = live;
|
|
4770
4848
|
const under = (dir) => (dir === "." || dir === "" ? files : files.filter((f) => f === dir || f.startsWith(`${dir}/`)));
|
|
4771
4849
|
const objectId = (p) => (ids.has(p) ? ids.get(p) : under(p).length ? digestOf(under(p)) : null);
|
|
4772
|
-
const store = fileScanCache(path.join(path.resolve(root, text(common).trim()), "rightkit-gate-cache"));
|
|
4850
|
+
const store = fileScanCache(o.env.RK_GATE_CACHE_DIR ? path.resolve(o.env.RK_GATE_CACHE_DIR) : path.join(path.resolve(root, text(common).trim()), "rightkit-gate-cache"));
|
|
4773
4851
|
const listFiles = (dir) => under(dir);
|
|
4774
4852
|
const readBlob = (p) => fs.readFileSync(path.join(liveBase, p), "utf8");
|
|
4775
4853
|
// The verdict also depends on what is not in the tree: the gate's own code and advisory data, the node and pnpm that run
|
|
@@ -4808,7 +4886,7 @@ export async function main(argv, io = {}) {
|
|
|
4808
4886
|
const line = text(r).split(/\r?\n/).find(Boolean);
|
|
4809
4887
|
return line ? (line.split("\t")[0].split(/\s+/)[2] ?? null) : null;
|
|
4810
4888
|
};
|
|
4811
|
-
const store = fileScanCache(path.join(path.resolve(root, text(common).trim()), "rightkit-gate-cache"));
|
|
4889
|
+
const store = fileScanCache(o.env.RK_GATE_CACHE_DIR ? path.resolve(o.env.RK_GATE_CACHE_DIR) : path.join(path.resolve(root, text(common).trim()), "rightkit-gate-cache"));
|
|
4812
4890
|
const listFiles = (dir) => {
|
|
4813
4891
|
const r = git("ls-tree", "-r", "--name-only", "-z", headSha, "--", dir);
|
|
4814
4892
|
if (failed(r)) throw new Error(`git ls-tree failed: ${why(r)}`);
|
|
@@ -4850,10 +4928,10 @@ export async function main(argv, io = {}) {
|
|
|
4850
4928
|
const census = snapshotB && !snapshotBroker ? createFreshnessCensus({ targetDirs }) : null;
|
|
4851
4929
|
directTiming.cargoStart = Date.now();
|
|
4852
4930
|
census?.start();
|
|
4853
|
-
const
|
|
4931
|
+
const scanOptions = {
|
|
4854
4932
|
// The commit's own files (rightkit#1393): a snapshot is not a git toplevel, so the secret scan needs this list to judge tracked files only and never what a stage wrote there.
|
|
4855
4933
|
...(snapshot ? { trackedFiles: files } : {}),
|
|
4856
|
-
classes: classAOnly ? ["A"] : classAEarlier ? ["B"] : ["A", "B"], ...(classAEarlier ? { classAEarlier: true } : {}), jobs, testJobs, classBJobs, classBBatching: !o[PRIVATE_SCOPED_COMPILE] && o.env.RK_GATE_CLASS_B_BATCH !== "0", classBPipeline: Math.max(1, Number(o.env.RK_GATE_CLASS_B_PIPELINE ?? 2) || 2), ...(brokerHost ? { brokerHost: true } : {}), ...(brokerLive ? { brokerLive } : {}), signal: ac.signal, ...(cache ? { cache } : {}),
|
|
4934
|
+
classes: classAOnly ? ["A"] : classAEarlier ? ["B"] : ["A", "B"], ...(classAEarlier ? { classAEarlier: true } : {}), jobs, testJobs, classBJobs, classBBatching: !o[PRIVATE_SCOPED_COMPILE] && o.env.RK_GATE_CLASS_B_BATCH !== "0", groupTests: o.env.RK_GATE_GROUP_TESTS !== "0", classBPipeline: Math.max(1, Number(o.env.RK_GATE_CLASS_B_PIPELINE ?? 2) || 2), ...(brokerHost ? { brokerHost: true } : {}), ...(brokerLive ? { brokerLive } : {}), signal: ac.signal, ...(cache ? { cache } : {}),
|
|
4857
4935
|
// NN41: the installed broker runtime's identity keys every cached compile failure; null (a direct host, an unreadable manifest) means no failure is cached.
|
|
4858
4936
|
...(brokerHost && cache ? (() => { const identity = brokerRuntimeIdentityText({ clients: [brokerClient, executor?.client, cargoCommand[0]], env: { ...o.env, ...(executor.env ?? {}) }, platform: o.platform }); return identity ? { failureIdentity: identity } : {}; })() : {}),
|
|
4859
4937
|
...(census ? { spawn: census.wrapSpawn(defaultSpawnAsync) } : {}),
|
|
@@ -4895,7 +4973,47 @@ export async function main(argv, io = {}) {
|
|
|
4895
4973
|
})(),
|
|
4896
4974
|
...(unionScheduler ? { scheduleClassB: unionScheduler } : {}),
|
|
4897
4975
|
onResult: (row, p) => o.out(`${tag} [${p.done}/${p.total}] ${(row.cached ? (row.status === "pass" ? "cached" : "cached-fail") : row.status).padEnd(11)} ${row.id} (${p.seconds}s)${row.batchedWith ? ` [batch of ${row.batchedWith.units.length}]` : ""}${row.status === "fail" ? ` :: ${String(row.detail ?? "").slice(0, 300)}` : row.advice ? ` :: ${String(row.advice).slice(0, 300)}` : ""}`),
|
|
4898
|
-
}
|
|
4976
|
+
};
|
|
4977
|
+
// Adrian 2026-11-06: "every time should be warm". Before anything runs, every planned row is looked up in the cache. If any would miss, the
|
|
4978
|
+
// run stops with a miss report (each row, its cause and the evidence: changed inputs, tool or environment, no stored result, or nothing
|
|
4979
|
+
// changed at all). Only Adrian's approval naming that report's digest lets those rows run (RK_GATE_MISS_APPROVAL=<file>).
|
|
4980
|
+
if (!o.runScans && cache) {
|
|
4981
|
+
const lookup = await runScans(plan, { ...scanOptions, cacheLookupOnly: true, onResult: () => {} });
|
|
4982
|
+
const allMisses = lookup.scans.filter((r) => r.lookupMiss);
|
|
4983
|
+
// Adrian 2026-11-06: "when we change something, we know exactly which rows are going to be called. Anything other than that needs approval."
|
|
4984
|
+
// A row that misses ONLY because files in its own key changed (new content ids, no tool, toolchain, broker or environment change) is one this
|
|
4985
|
+
// change must call: it runs, listed. Every other miss (nothing changed, no stored result, a tool or environment change) needs approval.
|
|
4986
|
+
const expected = (r) => r.cacheMiss?.kind === "changed" && (r.cacheMiss.why?.inputsChanged ?? 0) > 0 && !r.cacheMiss.why.tool && !r.cacheMiss.why.env && !r.cacheMiss.why.inheritedEnv;
|
|
4987
|
+
const called = allMisses.filter(expected);
|
|
4988
|
+
if (called.length) o.out(`${tag} cache lookup: ${called.length} row(s) rerun because their own files changed: ${called.slice(0, 12).map((r) => `${r.id} (${(r.cacheMiss.why.inputs ?? []).slice(0, 2).map((k) => k.replace(/^[^/]*\//, "")).join(", ")})`).join("; ")}${called.length > 12 ? "; ..." : ""}`);
|
|
4989
|
+
const misses = allMisses.filter((r) => !expected(r));
|
|
4990
|
+
if (misses.length) {
|
|
4991
|
+
const prior = new Map(lookup.scans.map((r) => [r.id, r]));
|
|
4992
|
+
const kindOf = (r) => r.cacheMiss?.kind ?? "new";
|
|
4993
|
+
const entries = misses.map((r) => ({ id: r.id, cause: kindOf(r) === "unchanged" ? "nothing changed: the cache failed" : kindOf(r) === "new" ? "no stored result (a new row, or the cache is empty)" : "inputs or environment changed", ...(r.cacheMiss?.why ? { evidence: r.cacheMiss.why } : {}), ...(r.cacheMiss?.last ? { lastPass: r.cacheMiss.last } : {}), ...(r.cacheMiss?.now ? { now: r.cacheMiss.now } : {}) })).sort((a, b) => a.id.localeCompare(b.id));
|
|
4994
|
+
const byCause = entries.reduce((m, e) => ((m[e.cause] = (m[e.cause] ?? 0) + 1), m), {});
|
|
4995
|
+
const changedInputs = {}; for (const e of entries) for (const k of e.evidence?.inputs ?? []) changedInputs[k] = (changedInputs[k] ?? 0) + 1;
|
|
4996
|
+
const tools = [...new Set(entries.filter((e) => e.evidence?.tool).map((e) => `${e.evidence.tool.from} -> ${e.evidence.tool.to}`))];
|
|
4997
|
+
const envs = [...new Set(entries.flatMap((e) => e.evidence?.env ?? []))];
|
|
4998
|
+
const commitOfRun = snapshotBCommit?.commit ?? snapshotCommitId?.commit ?? null;
|
|
4999
|
+
const body = { schema: "rightkit.gate-miss-report/1", commit: commitOfRun, planned: lookup.scans.length, hit: lookup.scans.filter((r) => r.cached).length, uncacheable: lookup.scans.filter((r) => r.uncacheable).length, misses: entries.length, byCause, topChangedInputs: Object.entries(changedInputs).sort((a, b) => b[1] - a[1]).slice(0, 20), tools, env: envs, rows: entries };
|
|
5000
|
+
const digest = createHash("sha256").update(JSON.stringify(body)).digest("hex");
|
|
5001
|
+
const reportFile = path.join(gateRunsRoot({ env: o.env, platform: o.platform }), "rightkit-gate-misses", `${path.basename(root)}-${new Date().toISOString().replace(/[:.]/g, "-")}-${digest.slice(0, 12)}.json`);
|
|
5002
|
+
try { fs.mkdirSync(path.dirname(reportFile), { recursive: true }); fs.writeFileSync(reportFile, `${JSON.stringify({ ...body, digest }, null, 2)}\n`); } catch { /* the summary below still names everything */ }
|
|
5003
|
+
const approval = missApproval(o, digest, commitOfRun);
|
|
5004
|
+
o.out(`${tag} cache lookup: ${body.planned} planned, ${body.hit} hit, ${body.misses} unexpected miss(es) (${Object.entries(byCause).map(([c, n]) => `${n} ${c}`).join("; ")}), ${body.uncacheable} uncacheable by design; report ${reportFile} (digest ${digest})`);
|
|
5005
|
+
if (body.topChangedInputs.length) o.out(`${tag} cache lookup: most-changed inputs ${body.topChangedInputs.slice(0, 8).map(([k, n]) => `${k} (${n})`).join(", ")}`);
|
|
5006
|
+
if (tools.length) o.out(`${tag} cache lookup: tool changes ${tools.slice(0, 5).join("; ")}`);
|
|
5007
|
+
if (envs.length) o.out(`${tag} cache lookup: environment changes ${envs.slice(0, 10).join(", ")}`);
|
|
5008
|
+
if (!approval.ok) {
|
|
5009
|
+
o.err(`${tag} BLOCKED: RK_CACHE_MISS: ${body.misses} row(s) would miss the cache without a change to their own files; nothing ran. Bring the report to Adrian; his approval names its digest and covers one run (RK_GATE_MISS_APPROVAL=<file>: {digest: "${digest}", by: "adrian", reason})${approval.why ? ` (${approval.why})` : ""}`);
|
|
5010
|
+
void prior;
|
|
5011
|
+
return 1;
|
|
5012
|
+
}
|
|
5013
|
+
o.out(`${tag} ${approval.note}`);
|
|
5014
|
+
} else o.out(`${tag} cache lookup: ${lookup.scans.length} planned, ${lookup.scans.filter((r) => r.cached).length} hit, ${called.length} rerun for changed files, 0 unexpected; ${lookup.scans.filter((r) => r.uncacheable).length} uncacheable by design`);
|
|
5015
|
+
}
|
|
5016
|
+
const scanResult = await (o.runScans ?? runScans)(plan, scanOptions);
|
|
4899
5017
|
if (nodeCheckRejects.size) o.out(`${tag} node-check cache misses: ${[...nodeCheckRejects].sort(([a], [b]) => a.localeCompare(b)).map(([reason, count]) => `${reason}=${count}`).join(", ")}`);
|
|
4900
5018
|
if (snapFullA && o.env.RIGHTKIT_PREPARATION_DIAGNOSTIC_DIR && nodeCheckDiagnosticId) o.out(`${tag} node-check diagnostic row: ${nodeCheckDiagnosticState}`);
|
|
4901
5019
|
if (unionContext) {
|
|
@@ -4926,7 +5044,8 @@ export async function main(argv, io = {}) {
|
|
|
4926
5044
|
const report = buildCoverageReport({ plan, scanResult, keys: scanKeys, keyErrors, cacheDisabled, classes: classAOnly ? ["A"] : classAEarlier ? ["B"] : ["A", "B"], commit: snapshotBCommit?.commit ?? snapshotCommitId?.commit ?? hostedCommitA?.commit ?? null, startedAt: new Date(directTiming.cargoStart).toISOString(), endedAt: new Date(directTiming.cargoEnd).toISOString() });
|
|
4927
5045
|
const base = gateRunsRoot({ env: o.env, platform: o.platform });
|
|
4928
5046
|
const file = (o.writeCoverage ?? writeCoverageReport)({ dir: path.join(base, "rightkit-gate-coverage"), name: `${path.basename(root)}-${new Date().toISOString().replace(/[:.]/g, "-")}-${process.pid}`, report });
|
|
4929
|
-
|
|
5047
|
+
const otherPass = (report.scans ?? []).filter((s) => s.coverage === "skipped" && /is not part of this pass/.test(String(s.reason ?? ""))).length;
|
|
5048
|
+
o.out(`${tag} coverage report ${file}: ${report.totals.planned - otherPass} scan(s) in this pass (class ${classAOnly ? "A" : classAEarlier ? "B" : "A+B"}), ${report.totals.hit} hit, ${report.totals.ran} ran, ${report.totals.skipped - otherPass} skipped; ${otherPass} belong to the other pass; scans took ${seconds(directTiming.cargoEnd - directTiming.cargoStart)}`);
|
|
4930
5049
|
} catch (error) { o.out(`${tag} note: the coverage report could not be written (${error.message})`); }
|
|
4931
5050
|
// What a full class A verdict binds, green or red: the bytes it judged, unchanged from start to end, and the environment it judged
|
|
4932
5051
|
// in (gate, tools, installed dependencies, tool caches), unchanged too. A verdict whose binding moved covers nothing: a green one is
|
package/build-ownership.mjs
CHANGED
|
@@ -1086,10 +1086,12 @@ function coveredWorkGone(owner, { probe, lease, file, selfPid = null, waitMs = 0
|
|
|
1086
1086
|
if (state.active > allowed) throw new Error(`job ${c.name} still holds ${state.active} process(es)${selfPid === null ? "" : " (this gate is one)"}`);
|
|
1087
1087
|
proofs.push(`job ${c.name} holds ${state.active === 0 ? "no process" : "only this gate"}`);
|
|
1088
1088
|
} else {
|
|
1089
|
+
// Windows destroys a job object only after its last handle closed AND every process in it exited: a job that no longer exists holds no
|
|
1090
|
+
// process, whatever its holder managed to record (a holder torn down with its session never writes "drained"; Dell compile-6, 2026-11-06).
|
|
1089
1091
|
const holder = readHolder(holderFile(file, owner.handle));
|
|
1090
1092
|
if (holder?.state === "drained") proofs.push(`job ${c.name} drained (holder pid ${holder.holder} at ${holder.at})`);
|
|
1091
1093
|
else if (holder?.state === "failed") proofs.push(`the gate never ran inside job ${c.name} (holder failed: ${holder.why})`);
|
|
1092
|
-
else
|
|
1094
|
+
else proofs.push(`job ${c.name} no longer exists, so no process remains in it (holder recorded ${holder?.state ?? "nothing"})`);
|
|
1093
1095
|
}
|
|
1094
1096
|
} else if (!rebooted && c.kind === "group") {
|
|
1095
1097
|
let snap;
|
|
@@ -1214,8 +1216,10 @@ function coveredWorkGone(owner, { probe, lease, file, selfPid = null, waitMs = 0
|
|
|
1214
1216
|
// before this ownership was acquired: that broker would hold a claim, lease or member row for anything it got, and no process remains to send it.
|
|
1215
1217
|
const acquiredMs = Date.parse(owner.acquiredAt);
|
|
1216
1218
|
const brokerUpThroughout = selfPid === null && broker && Number.isFinite(broker.startedMs) && Number.isFinite(acquiredMs) && broker.startedMs + 2000 < acquiredMs;
|
|
1219
|
+
// The broker holding no work at all (brokerIdle) proves the same for a broker that restarted after this ownership was acquired.
|
|
1220
|
+
const brokerHoldsNothing = selfPid === null && Boolean(broker?.idle);
|
|
1217
1221
|
const neverReceived = new Set();
|
|
1218
|
-
const everyUnsent = () => handles.length > 0 && handles.every((sub) => settled(sub) || revocation(sub) !== null || brokerUpThroughout);
|
|
1222
|
+
const everyUnsent = () => handles.length > 0 && handles.every((sub) => settled(sub) || revocation(sub) !== null || brokerUpThroughout || brokerHoldsNothing);
|
|
1219
1223
|
const status = measure("leaseMs", () => lease({ snapshot: owner.snapshot, handle: owner.handle, ...waitOptions }));
|
|
1220
1224
|
if (status.state === "ACTIVE" || (status.state !== "REAPED" && !everyUnsent())) throw new Error(`broker work may exist under this handle and its lease is ${status.state} (${status.why})`);
|
|
1221
1225
|
if (status.state === "REAPED") proofs.push(`broker lease for ${owner.handle} is REAPED`);
|
|
@@ -1235,10 +1239,10 @@ function coveredWorkGone(owner, { probe, lease, file, selfPid = null, waitMs = 0
|
|
|
1235
1239
|
const listed = Array.isArray(status.members) && status.members.some((m) => m.handle === sub);
|
|
1236
1240
|
const rev = one.state === "UNKNOWN" && Array.isArray(one.members) && one.members.length === 0 && !listed ? revocation(sub) : null;
|
|
1237
1241
|
if (rev) { proofs.push(`${sub} is UNKNOWN to the broker and revoked by its signed revocation ${rev.file} (proof ${rev.payload.proofSha256})`); revokedCount += 1; continue; }
|
|
1238
|
-
if (brokerUpThroughout && one.state === "UNKNOWN" && Array.isArray(one.members) && one.members.length === 0 && !listed) { neverReceived.add(sub); continue; }
|
|
1242
|
+
if ((brokerUpThroughout || brokerHoldsNothing) && one.state === "UNKNOWN" && Array.isArray(one.members) && one.members.length === 0 && !listed) { neverReceived.add(sub); continue; }
|
|
1239
1243
|
throw new Error(`broker work may exist under sub-handle ${sub} and its lease is ${one.state} (${one.why})`);
|
|
1240
1244
|
}
|
|
1241
|
-
if (neverReceived.size) proofs.push(`${neverReceived.size} sub-handle(s)
|
|
1245
|
+
if (neverReceived.size) proofs.push(`${neverReceived.size} sub-handle(s) hold no broker work: UNKNOWN with no member row, ${brokerUpThroughout ? `to broker pid ${broker.pid}, up since ${new Date(broker.startedMs).toISOString()}, before this ownership (${owner.acquiredAt})` : `and the broker holds no work at all (READY, recovery complete, nothing in flight, no owner)`}, and no process of the run remains (${[...neverReceived].slice(0, 3).join(", ")}${neverReceived.size > 3 ? ", ..." : ""})`);
|
|
1242
1246
|
if (handles.length) proofs.push(neverStarted === 0 && revokedCount === 0 && neverReceived.size === 0 ? `broker lease for each of ${handles.length} sub-handle(s) is REAPED` : `every one of ${handles.length} sub-handle(s) is accounted for: ${handles.length - neverStarted - revokedCount - neverReceived.size} REAPED, ${neverStarted} proven never started, ${neverReceived.size} never reached the broker, ${revokedCount} revoked by the broker`);
|
|
1243
1247
|
}
|
|
1244
1248
|
return proofs;
|
|
@@ -1462,7 +1466,7 @@ export function acquireBuildOwnership({
|
|
|
1462
1466
|
// GC-A25 is proposed, not operative: RustRight has not frozen the revocation's authoritative path (its f227 completion key fences legacy reuse; a record
|
|
1463
1467
|
// only beside this one does not) nor its publication sequence. Until then no production reclaim honours a revocation; only a caller that passes
|
|
1464
1468
|
// `brokerPins` explicitly (fixtures) exercises the branch. Enable by defaulting to enrolledPinsFor(file, platform) once GC-A25 is operative.
|
|
1465
|
-
const judged = judgeOwner(observed, { file, probe, lease, pins: brokerPins ?? null, broker: brokerIdentity === undefined ? runningBrokerProcess({ platform }) : brokerIdentity });
|
|
1469
|
+
const judged = judgeOwner(observed, { file, probe, lease, pins: brokerPins ?? null, broker: brokerIdentity === undefined ? { ...(runningBrokerProcess({ platform }) ?? {}), idle: brokerIdle({ platform }) } : brokerIdentity });
|
|
1466
1470
|
hooks.afterJudge?.();
|
|
1467
1471
|
// A reclaim means the previous release was not clean (a crash, or a release that ended held): nothing unreadable is skipped.
|
|
1468
1472
|
record.cleanBefore = null;
|
|
@@ -1517,6 +1521,23 @@ const dataRootOf = (file) => path.dirname(path.dirname(path.dirname(file)));
|
|
|
1517
1521
|
* rightkit#1513: the running RustRight broker's pid and start time (epoch ms), from launchd and ps (macOS); null when it cannot be
|
|
1518
1522
|
* established. A broker that has run continuously since before an ownership was acquired saw every request of that run.
|
|
1519
1523
|
*/
|
|
1524
|
+
/**
|
|
1525
|
+
* rightkit#1513 (Adrian: "It should ideally auto recover"): the broker's own answer that it holds no work at all: phase READY, its restart
|
|
1526
|
+
* recovery complete, nothing in flight, no build owner and no quiet lease (`rustright list`). With that answer a sub-handle the broker calls
|
|
1527
|
+
* UNKNOWN with no member row has no work anywhere, even when the broker restarted after the ownership was acquired. Any other answer is null.
|
|
1528
|
+
*/
|
|
1529
|
+
export function brokerIdle({ env = process.env, platform = process.platform, spawn = spawnSync, client = managedRuntimeClient(env, platform) } = {}) {
|
|
1530
|
+
if (!client) return null;
|
|
1531
|
+
try {
|
|
1532
|
+
const r = run(spawn, client, ["list"], env);
|
|
1533
|
+
if (r.error || r.status !== 0) return null;
|
|
1534
|
+
const d = JSON.parse(String(r.stdout ?? "").trim());
|
|
1535
|
+
const b = d?.broker;
|
|
1536
|
+
const idle = b?.phase === "READY" && b?.recovery?.complete === true && b?.quietLease === null && Array.isArray(d?.inFlight) && d.inFlight.length === 0 && Array.isArray(d?.owners) && d.owners.length === 0;
|
|
1537
|
+
return idle ? { phase: b.phase, recovered: b.recovery?.recovered ?? null } : null;
|
|
1538
|
+
} catch { return null; }
|
|
1539
|
+
}
|
|
1540
|
+
|
|
1520
1541
|
export function runningBrokerProcess({ platform = process.platform, run = spawnSync, uid = process.getuid?.() } = {}) {
|
|
1521
1542
|
if (platform === "win32") {
|
|
1522
1543
|
// The Dell's broker runs as rustright-broker.exe (D:\.rustright\runtime). Exactly one such process, else unknown (fail safe).
|
package/deterministic-scans.mjs
CHANGED
|
@@ -475,7 +475,24 @@ export const CACHEABLE_INTERNAL = new Set(["ghsa-audit", "advisory-exceptions",
|
|
|
475
475
|
/** NN41: internal rules whose failure is never reused: their answer depends on the UTC day or a remote service, not only on their inputs. */
|
|
476
476
|
export const FAILURE_UNCACHEABLE_INTERNAL = new Set(["ghsa-audit", "advisory-exceptions"]);
|
|
477
477
|
/** NN41: the key namespace of a cached failure, so a failure never shares a key with a pass of the same scan. */
|
|
478
|
-
|
|
478
|
+
// /2: a broker-authenticated compile failure is stored only when its output shows compiler diagnostics and no tool or environment failure (a build-script tool panic is environmental; Dell pulse-hub, 2026-11-06).
|
|
479
|
+
export const FAILURE_KEY_SCHEMA = "deterministic-failure/2";
|
|
480
|
+
/** NN23: the version of the internal (file-only) rules; bump when any internal rule's verdict for the same inputs changes. */
|
|
481
|
+
export const INTERNAL_RULES_SCHEMA = "rightkit.internal-rules/1";
|
|
482
|
+
/** Why a row's cache key moved, from the stored pass's key parts to this run's: the input entries that differ (paths and the like), the tool
|
|
483
|
+
* version, the environment variables that differ. Bounded lists; evidence for Adrian's approval of a miss. */
|
|
484
|
+
export function explainKeyChange(before, after) {
|
|
485
|
+
const flat = (text) => { const out = new Map(); const walk = (v, at) => { if (v && typeof v === "object") { if (Array.isArray(v) && v.length === 2 && typeof v[0] === "string" && typeof v[1] !== "object") { out.set(`${at}/${v[0]}`, String(v[1])); return; } for (const [k, x] of Object.entries(v)) walk(x, at ? `${at}.${k}` : k); } else out.set(at, String(v)); }; const s = String(text); const m = /^([\[{][\s\S]*[\]}]):([^:]+)$/.exec(s); try { walk(JSON.parse(m ? m[1] : s), ""); if (m) out.set("(key suffix)", m[2]); } catch { out.set("inputs", s); } return out; };
|
|
486
|
+
const a = flat(before?.inputs ?? ""); const b = flat(after?.inputs ?? "");
|
|
487
|
+
const inputs = [...new Set([...a.keys(), ...b.keys()])].filter((k) => a.get(k) !== b.get(k)).sort();
|
|
488
|
+
const envKeys = [...new Set([...Object.keys(before?.env ?? {}), ...Object.keys(after?.env ?? {})])].filter((k) => (before?.env ?? {})[k] !== (after?.env ?? {})[k]).sort();
|
|
489
|
+
return {
|
|
490
|
+
inputs: inputs.slice(0, 12), inputsChanged: inputs.length,
|
|
491
|
+
...(before?.toolVersion !== after?.toolVersion ? { tool: { from: before?.toolVersion ?? null, to: after?.toolVersion ?? null } } : {}),
|
|
492
|
+
...(envKeys.length ? { env: envKeys.slice(0, 12) } : {}),
|
|
493
|
+
...(before?.inherited !== after?.inherited ? { inheritedEnv: true } : {}),
|
|
494
|
+
};
|
|
495
|
+
}
|
|
479
496
|
/** NN41: the compile scans whose failure can be deterministic: check, clippy and doc rows (single or batched, native or cross). Test runs are never among them. */
|
|
480
497
|
export const isFailureCacheableCompileId = (id) => /^(?:check|check-features|check-dependent|clippy|doc)(?::|$)/.test(String(id));
|
|
481
498
|
/** NN41: a plain (non-broker) compile exit whose output carries compiler error diagnostics and no sign of the environment failing (network, disk, signal, internal compiler error). */
|
|
@@ -1622,7 +1639,9 @@ export function planScans({
|
|
|
1622
1639
|
const e2e = e2eCrateDirs instanceof Set && e2eCrateDirs.has(rustDir(name));
|
|
1623
1640
|
if (e2e) { qualifyOwed.push({ id: rustScanId.testRust(name, sets.length, 0), kind: "e2e-crate", dir: rustDir(name), crate: crateOf(name), reason: "end-to-end crate: its tests drive a built app and never run as class B unit tests (P7)" }); notes.push(`${crateOf(name)} is an end-to-end crate: its test scan compiles with --no-run here; its tests run in the qualify stage against the built app (qa.journeys), never as class B unit tests`); }
|
|
1624
1641
|
sets.forEach((set, i) => {
|
|
1625
|
-
|
|
1642
|
+
// NN17/NN39: the plain test rows of one workspace and configuration are batchable: one grouped `cargo test` compile on a broker host (runScans runTestGroup).
|
|
1643
|
+
// A quiet suite keeps its own lease and runs alone; an end-to-end crate only compiles (--no-run); the serial re-run (alsoSerial, below) keeps its own run.
|
|
1644
|
+
add({ id: rustScanId.testRust(name, sets.length, i), class: B, ...quiet, ...(!e2e && cargoLiveRoot && quiet.quiet !== true ? { batchUnit: name } : {}), ...(e2e ? { e2e: true } : {}), ...(e2e ? cargoIn(wsOf(name), "test", "-p", crateOf(name), ...set, "--locked", "--no-run") : cargoLiveRoot ? { ...cargoTestIn(wsOf(name), "test", "-p", crateOf(name), ...set, "--locked"), runOutside: { args: [] } } : cargoIn(wsOf(name), "test", "-p", crateOf(name), ...set, "--locked", "--no-fail-fast")) });
|
|
1626
1645
|
if (own.alsoSerial) add({ id: rustScanId.testRustSerial(name, sets.length, i), class: B, ...quiet, ...(e2e ? { e2e: true } : {}), ...(e2e ? cargoIn(wsOf(name), "test", "-p", crateOf(name), ...set, "--locked", "--no-run") : cargoLiveRoot ? { ...cargoTestIn(wsOf(name), "test", "-p", crateOf(name), ...set, "--locked"), runOutside: { args: ["--test-threads=1"] } } : cargoIn(wsOf(name), "test", "-p", crateOf(name), ...set, "--locked", "--no-fail-fast", "--", "--test-threads=1")) });
|
|
1627
1646
|
});
|
|
1628
1647
|
}
|
|
@@ -2975,7 +2994,7 @@ export async function runScans(plan, options = {}) {
|
|
|
2975
2994
|
const groupOf = new Map();
|
|
2976
2995
|
if (options.classBBatching === true) {
|
|
2977
2996
|
const byKey = new Map();
|
|
2978
|
-
bScans.forEach((s, i) => { if (s.batchable && !s.deferred && (laneOf(s) === "compile" || laneOf(s) === "doc")) { if (!byKey.has(s.batchable.key)) byKey.set(s.batchable.key, []); byKey.get(s.batchable.key).push(i); } });
|
|
2997
|
+
bScans.forEach((s, i) => { if (s.batchable && !s.deferred && (laneOf(s) === "compile" || laneOf(s) === "doc" || (options.groupTests !== false && laneOf(s) === "tests" && s.runOutside && /^test:rust/.test(s.id)))) { if (!byKey.has(s.batchable.key)) byKey.set(s.batchable.key, []); byKey.get(s.batchable.key).push(i); } });
|
|
2979
2998
|
for (const members of byKey.values()) if (members.length > 1) { const group = { members, promise: null }; for (const i of members) groupOf.set(i, group); }
|
|
2980
2999
|
}
|
|
2981
3000
|
const batchScanOf = (idx) => {
|
|
@@ -2983,10 +3002,13 @@ export async function runScans(plan, options = {}) {
|
|
|
2983
3002
|
const { batchable: _batchable, ...plain } = lead; void _batchable;
|
|
2984
3003
|
const args = [...lead.args.slice(0, lead.batchable.at), ...idx.flatMap((i) => ["-p", bScans[i].batchable.crate]), ...lead.args.slice(lead.batchable.at + 2)];
|
|
2985
3004
|
const units = idx.map((i) => bScans[i].batchable.unit);
|
|
2986
|
-
const stage = /^clippy/.test(lead.id) ? "clippy" : /^doc:/.test(lead.id) ? "doc" : "check";
|
|
3005
|
+
const stage = /^clippy/.test(lead.id) ? "clippy" : /^doc:/.test(lead.id) ? "doc" : /^test:rust/.test(lead.id) ? "test" : "check";
|
|
2987
3006
|
const id = `${stage}:batch:${sha256(`${lead.batchable.key}\0${units.join("\0")}`).slice(0, 8)}`;
|
|
2988
3007
|
// A doc group asks for cargo's JSON messages (NN40): each crate's verdict is read from them (docVerdicts), never found by bisection.
|
|
2989
3008
|
if (stage === "doc") { const jargs = [...args, "--message-format=json"]; return { ...plain, id, args: jargs, captureJson: true, command: commandText({ ...plain, env: {}, args: jargs }), batch: { units, members: idx.map((i) => bScans[i].id) } }; }
|
|
3009
|
+
// NN17/NN39: a test group compiles once (one broker command naming every crate) and each member's own test executables then run in
|
|
3010
|
+
// parallel outside the broker; each member keeps its own verdict (runOne `testGroup`, memberRuns).
|
|
3011
|
+
if (stage === "test") return { ...plain, id, args, testGroup: idx.map((i) => ({ id: bScans[i].id, crate: bScans[i].batchable.crate })), command: commandText({ ...plain, env: {}, args }), batch: { units, members: idx.map((i) => bScans[i].id) } };
|
|
2990
3012
|
return { ...plain, id, args, command: commandText({ ...plain, env: {}, args }), batch: { units, members: idx.map((i) => bScans[i].id) } };
|
|
2991
3013
|
};
|
|
2992
3014
|
const runGroup = async (idx, extraEnv, budget = { remaining: Math.min(2 * idx.length - 1, 31) }) => {
|
|
@@ -3000,6 +3022,15 @@ export async function runScans(plan, options = {}) {
|
|
|
3000
3022
|
const bs = batchScanOf(idx);
|
|
3001
3023
|
let row;
|
|
3002
3024
|
try { row = await scanRow(bs, extraEnv); } catch (error) { row = { id: bs.id, status: "fail", code: "SCAN_ERROR", detail: String(error?.message ?? error) }; }
|
|
3025
|
+
if (row.memberRuns && !signal?.aborted) {
|
|
3026
|
+
idx.forEach((i) => {
|
|
3027
|
+
const m = bScans[i]; const v = row.memberRuns[m.id] ?? { status: "fail", code: "TEST_GROUP", detail: `${m.id}: the test group ${row.id} produced no run for this member` };
|
|
3028
|
+
const own = { id: m.id, class: m.class, command: m.command, batchCommand: row.command, batchedWith: { id: row.id, units: bs.batch.units }, tool: m.tool ?? null, toolVersion: row.toolVersion ?? null, status: v.status, ...(v.code ? { code: v.code } : {}), ...(v.detail ? { detail: v.detail } : {}), ...(v.results ? { results: v.results } : {}), ...(v.testRun ? { testRun: v.testRun } : {}), ...(row.snapshotEvidence ? { snapshotEvidence: row.snapshotEvidence } : {}) };
|
|
3029
|
+
slots[i] = own; done += 1;
|
|
3030
|
+
try { onResult(own, { done, total, seconds: Math.round((Date.now() - started) / 1000) }); } catch { /* reporting never fails a scan */ }
|
|
3031
|
+
});
|
|
3032
|
+
return;
|
|
3033
|
+
}
|
|
3003
3034
|
// A failure reused from the result cache (NN41) was authenticated or diagnosed when it was written, so it attributes the same way.
|
|
3004
3035
|
const attributable = (row.code === "EXIT" && !row.snapshotEvidence) || (row.code === "BROKER_COMPILE_FAILURE" && row.authenticatedFailure?.retryable === true && row.authenticatedFailure?.failureClass === "compile" && row.snapshotEvidence?.receiptSha256) || (row.failureCached === true && (row.code === "EXIT" || row.code === "BROKER_COMPILE_FAILURE"));
|
|
3005
3036
|
// NN40: a failed doc invocation is attributed from its own JSON messages: a crate with an error message fails, a crate with no artifact while
|
|
@@ -3176,18 +3207,21 @@ export async function runScans(plan, options = {}) {
|
|
|
3176
3207
|
try {
|
|
3177
3208
|
// GC-A24: a deterministic internal rule (its verdict a function of the files it reads and the rule code) is reused by its input key,
|
|
3178
3209
|
// with the rule code's identity (CHECKER_IDENTITY) as its tool version. Network and advice rules are never reused this way.
|
|
3179
|
-
let internalKey = null; let internalFailKey = null;
|
|
3210
|
+
let internalKey = null; let internalFailKey = null; let internalIndex = null;
|
|
3180
3211
|
if (s.internal && cache && CACHEABLE_INTERNAL.has(s.internal) && typeof CHECKER_IDENTITY === "string") {
|
|
3181
3212
|
try {
|
|
3182
3213
|
const digest = cache.digest(s, {});
|
|
3183
3214
|
if (digest) {
|
|
3184
|
-
|
|
3215
|
+
// NN23: keyed on the internal rules' schema (bumped by hand when a rule's verdict changes), not on the checker's source bytes.
|
|
3216
|
+
internalKey = scanCacheKey({ id: s.id, command: s.command ?? `internal:${s.internal}`, toolVersion: INTERNAL_RULES_SCHEMA, env: {}, inheritedEnv: inheritedEnvDigest({}), digest });
|
|
3217
|
+
internalIndex = { key: sha256(`rk-row-index/1\0${s.id}`), inputs: sha256(String(digest)), env: INTERNAL_RULES_SCHEMA, raw: { inputs: String(digest), toolVersion: INTERNAL_RULES_SCHEMA, env: {}, inherited: null } };
|
|
3185
3218
|
// NN41: a file-only rule's violation list is a function of the same inputs, so it is keyed like its pass plus the rule code (CHECKER_IDENTITY);
|
|
3186
3219
|
// a rule whose answer depends on the day or a remote service (FAILURE_UNCACHEABLE_INTERNAL) never has its failure reused.
|
|
3187
|
-
if (!FAILURE_UNCACHEABLE_INTERNAL.has(s.internal)) internalFailKey = scanCacheKey({ id: s.id, command: `${s.command ?? `internal:${s.internal}`} ;; ${FAILURE_KEY_SCHEMA}`, toolVersion:
|
|
3220
|
+
if (!FAILURE_UNCACHEABLE_INTERNAL.has(s.internal)) internalFailKey = scanCacheKey({ id: s.id, command: `${s.command ?? `internal:${s.internal}`} ;; ${FAILURE_KEY_SCHEMA}`, toolVersion: INTERNAL_RULES_SCHEMA, env: {}, inheritedEnv: inheritedEnvDigest({}), digest });
|
|
3188
3221
|
}
|
|
3189
3222
|
} catch (error) { internalKey = null; internalFailKey = null; row.cacheKeyError = String(error?.message ?? error).slice(0, 300); }
|
|
3190
3223
|
const hit = internalKey ? cache.read(internalKey) : null;
|
|
3224
|
+
if (internalIndex) { const idx = cache.read(internalIndex.key)?.row ?? null; row.cacheMiss = { kind: !idx ? "new" : idx.inputs === internalIndex.inputs && idx.env === internalIndex.env ? "unchanged" : "changed", ...(idx ? { last: idx.at ?? null } : {}), ...(idx?.raw ? { why: explainKeyChange(idx.raw, internalIndex.raw) } : {}), now: { inputs: internalIndex.raw.inputs.slice(0, 4000) } }; }
|
|
3191
3225
|
if (hit && hit.key === internalKey && hit.row?.status === "pass" && hit.row.id === s.id) {
|
|
3192
3226
|
cacheHits.push(s.id);
|
|
3193
3227
|
return { ...row, status: "pass", cached: true, detail: `cached ${String(hit.at ?? "").slice(0, 10) || "earlier"}` };
|
|
@@ -3199,12 +3233,14 @@ export async function runScans(plan, options = {}) {
|
|
|
3199
3233
|
return { ...row, status: "fail", cached: true, failureCached: true, detail: failHit.row.detail };
|
|
3200
3234
|
}
|
|
3201
3235
|
}
|
|
3236
|
+
if (options.cacheLookupOnly && s.internal) return { ...row, status: "not-run", lookupMiss: Boolean(internalKey), detail: internalKey ? "would miss the cache" : "has no cache key" };
|
|
3202
3237
|
if (s.internal) {
|
|
3203
3238
|
const out = await INTERNAL[s.internal](s, ctx);
|
|
3204
3239
|
if (out && out.missing) { status = "fail"; code = "TOOL_MISSING"; detail = out.missing; }
|
|
3205
3240
|
else if (out && !Array.isArray(out) && out.code) { status = "fail"; code = out.code; detail = out.detail; }
|
|
3206
3241
|
else if (out && !Array.isArray(out) && typeof out.advice === "string") { advice = out.advice; }
|
|
3207
3242
|
else if (out.length) { status = "fail"; detail = out.join("; "); }
|
|
3243
|
+
if (status === "pass" && internalKey && !advice && !signal?.aborted && internalIndex) cache.write(internalIndex.key, { id: s.id, inputs: internalIndex.inputs, env: internalIndex.env, raw: internalIndex.raw, at: new Date().toISOString() });
|
|
3208
3244
|
if (status === "pass" && internalKey && !advice && !signal?.aborted) cache.write(internalKey, { id: s.id, class: s.class, command: s.command ?? `internal:${s.internal}`, tool: null, toolVersion: CHECKER_IDENTITY, status: "pass" });
|
|
3209
3245
|
// NN41: only a violation list (the rule ran and named what is wrong) is a deterministic failure; a missing tool or a coded refusal is the environment's.
|
|
3210
3246
|
else if (status === "fail" && !code && internalFailKey && Array.isArray(out) && out.length && !signal?.aborted) cache.write(internalFailKey, { id: s.id, class: s.class, command: s.command ?? `internal:${s.internal}`, tool: null, toolVersion: CHECKER_IDENTITY, status: "fail", detail });
|
|
@@ -3242,7 +3278,7 @@ export async function runScans(plan, options = {}) {
|
|
|
3242
3278
|
else if (missingDep) { status = "fail"; code = "TOOL_MISSING"; detail = `${s.tool} needs ${missingDep}, which is missing or not runnable; without it the scan would pass unchecked, so it fails`; }
|
|
3243
3279
|
else if (depVersionProblem) { status = "fail"; code = "TOOL_VERSION"; detail = `TOOL_VERSION: ${s.tool} runs ${depVersionProblem}`; }
|
|
3244
3280
|
else {
|
|
3245
|
-
let cacheKey = null; let failKey = null; let ledgerProblem = false;
|
|
3281
|
+
let cacheKey = null; let failKey = null; let ledgerProblem = false; let keyParts = null;
|
|
3246
3282
|
// GATE-CONTRACT GC-T14: every unchanged scan result is reused by its full input key, a broker-carried compile included (measured
|
|
3247
3283
|
// 2026-11-02: HR class B re-ran 92 broker jobs, most with no dirty unit, because carried compiles were never cached). The key covers the
|
|
3248
3284
|
// crate's closure, its lock entries, the toolchain files, the tool version and the build environment; a miss runs the compile and
|
|
@@ -3250,7 +3286,8 @@ export async function runScans(plan, options = {}) {
|
|
|
3250
3286
|
const carriedScan = isBrokerCarriedScan(s, carriedCtx);
|
|
3251
3287
|
const viaSnapshotBroker = carriedScan && Boolean(deps.snapshotBroker) && s.root === "cargoLive" && (s.tool === "rustright" || s.tool === "cargo");
|
|
3252
3288
|
const carriedRead = cargoReadsAreCarried && s.class === SCAN_CLASS.A && (s.tool === "rustright" || s.tool === "cargo");
|
|
3253
|
-
|
|
3289
|
+
// NN02: a publisher row (coverageKey) is cached too, with the signed broker receipt and test-run evidence its publisher verify needs.
|
|
3290
|
+
if (cache && !carriedRead) {
|
|
3254
3291
|
const cacheStarted = performance.now();
|
|
3255
3292
|
try {
|
|
3256
3293
|
// A plain node --check row has no guard, carrier, advisory or
|
|
@@ -3263,9 +3300,13 @@ export async function runScans(plan, options = {}) {
|
|
|
3263
3300
|
const toolVersion = [p.identity ? `${p.version}@${p.identity.sha256}` : p.version, ...depVersions].join(" + ");
|
|
3264
3301
|
// The narrow node-check digest already binds the complete actual
|
|
3265
3302
|
// child environment (with its one explicit ownership exception).
|
|
3266
|
-
|
|
3303
|
+
// NN29: a publisher row carries the gate's whole environment, per-run identities included (build ownership handle, carrier map, run markers):
|
|
3304
|
+
// its key drops them, or every run would miss.
|
|
3305
|
+
const keyEnv = (env) => (s.coverageKey ? Object.fromEntries(Object.entries(env ?? {}).filter(([k]) => !/^(?:RIGHTKIT_BUILD_OWNERSHIP|RK_GATE_|RIGHTKIT_CARRIED_|RIGHTKIT_CARGO_SCAN|RIGHTKIT_RUN_|RUSTRIGHT_OWNERSHIP|TMPDIR$|PWD$|OLDPWD$|SHLVL$|_$)/.test(k))) : env);
|
|
3306
|
+
const inherited = cache.narrowNodeCheck && /^node-check:/.test(s.id) ? sha256('node-check-child-env-in-digest/1') : inheritedEnvDigest(keyEnv({ ...deps.env, ...s.env }));
|
|
3267
3307
|
if (digest) {
|
|
3268
|
-
cacheKey = scanCacheKey({ id: s.id, command: s.runOutside ? `${s.command} ;; run ${canonicalJson(s.runOutside)}` : s.command, toolVersion, env: s.env ?? {}, inheritedEnv: inherited, digest });
|
|
3308
|
+
cacheKey = scanCacheKey({ id: s.id, command: s.runOutside ? `${s.command} ;; run ${canonicalJson(s.runOutside)}` : s.command, toolVersion, env: keyEnv(s.env ?? {}), inheritedEnv: inherited, digest });
|
|
3309
|
+
keyParts = { inputs: sha256(String(digest)), env: sha256(canonicalJson({ toolVersion, env: keyEnv(s.env ?? {}), inherited })), raw: { inputs: String(digest), toolVersion, env: keyEnv(s.env ?? {}), inherited } };
|
|
3269
3310
|
// NN41: a deterministic compile failure is keyed like the pass plus the tool version (the client's, its identity digest), the installed broker runtime
|
|
3270
3311
|
// identity (options.failureIdentity: version, clientDigest, brokerDigest) and the failure namespace; the digest already binds the unit closure, lock entries and toolchain files.
|
|
3271
3312
|
// No identity from the caller means no failure is ever stored or reused.
|
|
@@ -3273,14 +3314,26 @@ export async function runScans(plan, options = {}) {
|
|
|
3273
3314
|
}
|
|
3274
3315
|
} catch (error) { cacheKey = null; row.cacheKeyError = String(error?.message ?? error).slice(0, 300); }
|
|
3275
3316
|
const hit = cacheKey ? cache.read(cacheKey) : null;
|
|
3317
|
+
// Adrian 2026-11-06: a rerun that misses the cache fails unless the miss is explained. Each stored pass leaves a per-row index
|
|
3318
|
+
// (its inputs digest and environment digest); a later miss is "unchanged" (inputs and environment the same: the cache failed),
|
|
3319
|
+
// "changed" (an input or the environment moved: a legitimate rerun) or "new" (no stored pass: a new row, or a cold run).
|
|
3320
|
+
if (cacheKey && keyParts) {
|
|
3321
|
+
const rowIndexKey = sha256(`rk-row-index/1\0${s.id}`);
|
|
3322
|
+
const inputsDigest = keyParts.inputs;
|
|
3323
|
+
const envDigest = keyParts.env;
|
|
3324
|
+
const idx = cache.read(rowIndexKey)?.row ?? null;
|
|
3325
|
+
row.cacheMiss = { kind: !idx ? "new" : idx.inputs === inputsDigest && idx.env === envDigest ? "unchanged" : "changed", ...(idx ? { last: idx.at ?? null } : {}), ...(idx?.raw ? { why: explainKeyChange(idx.raw, keyParts.raw) } : {}), now: { inputs: keyParts.raw.inputs.slice(0, 4000), toolVersion: keyParts.raw.toolVersion, inherited: keyParts.raw.inherited } };
|
|
3326
|
+
row.rowIndex = { key: rowIndexKey, inputs: inputsDigest, env: envDigest, raw: keyParts.raw };
|
|
3327
|
+
}
|
|
3276
3328
|
timing.cacheLookupMs = performance.now() - cacheStarted;
|
|
3277
3329
|
// A cached test pass counts only with the counts it recorded: without them its coverage is unknown, so it runs again.
|
|
3278
3330
|
// ...and only if it passed at least one test: a cached all-skipped "pass" (written before D17) runs again (rightkit#1236).
|
|
3279
3331
|
// A Rust test scan (runOutside) is judged the same way: the executables are unknown until the compile, so its key is the source digest and the cached row must carry the summed libtest counts.
|
|
3280
3332
|
const testEvidence = (s.kind !== "test" && !s.runOutside) || testResultsProblem(hit?.row?.results) === null;
|
|
3281
|
-
|
|
3333
|
+
const publisherEvidence = !s.coverageKey || !viaSnapshotBroker || /^[0-9a-f]{64}$/.test(hit?.row?.snapshotEvidence?.receiptSha256 ?? "");
|
|
3334
|
+
if (hit && hit.key === cacheKey && hit.row?.status === "pass" && hit.row.id === s.id && hit.row.command === s.command && testEvidence && publisherEvidence) {
|
|
3282
3335
|
cacheHits.push(s.id);
|
|
3283
|
-
return { ...row, status: "pass", cached: true, detail: `cached ${String(hit.at ?? "").slice(0, 10) || "earlier"}`, ...(s.kind === "test" ? { results: hit.row.results } : {}) };
|
|
3336
|
+
return { ...row, status: "pass", cached: true, detail: `cached ${String(hit.at ?? "").slice(0, 10) || "earlier"}`, ...(s.kind === "test" || s.runOutside || s.coverageKey ? { results: hit.row.results } : {}), ...(s.coverageKey ? { snapshotEvidence: hit.row.snapshotEvidence ?? null, testRun: hit.row.testRun ?? null } : {}) };
|
|
3284
3337
|
}
|
|
3285
3338
|
// NN41: the same inputs, toolchain and broker runtime already failed this compile deterministically: report that failure, marked cached, without running it.
|
|
3286
3339
|
const failHit = failKey ? cache.read(failKey) : null;
|
|
@@ -3289,6 +3342,8 @@ export async function runScans(plan, options = {}) {
|
|
|
3289
3342
|
return { ...row, status: "fail", code: failHit.row.code, cached: true, failureCached: true, detail: `cached failure ${String(failHit.at ?? "").slice(0, 10) || "earlier"} (same inputs, toolchain and broker runtime): ${failHit.row.detail}`, ...(failHit.row.authenticatedFailure ? { authenticatedFailure: failHit.row.authenticatedFailure } : {}), ...(failHit.row.jsonSummary ? { jsonSummary: failHit.row.jsonSummary } : {}) };
|
|
3290
3343
|
}
|
|
3291
3344
|
}
|
|
3345
|
+
// Adrian 2026-11-06: the cache is looked up for every planned row BEFORE anything runs (options.cacheLookupOnly): a miss is reported with its cause, never run.
|
|
3346
|
+
if (options.cacheLookupOnly) return { ...row, status: "not-run", lookupMiss: Boolean(cacheKey), uncacheable: !cacheKey, detail: cacheKey ? "would miss the cache" : "has no cache key" };
|
|
3292
3347
|
// Every cargo call the wrapper decides during this scan is filed under this token in the gate's ledger: the scan's own call AND the
|
|
3293
3348
|
// calls the scan itself makes before it (the cargo-deny row's prefetch and its full metadata), so none is filed "unscoped" and fails the run.
|
|
3294
3349
|
const ledgerToken = cargoLedger ? scanTokenOf(s.id) : null;
|
|
@@ -3590,6 +3645,25 @@ export async function runScans(plan, options = {}) {
|
|
|
3590
3645
|
if (s.publisherRustTest && viaSnapshotBroker && !Object.hasOwn(row.snapshotEvidence ?? {}, "testExecutables")) fail("TEST_EXECUTABLE_UNSIGNED", `${s.id}: the broker did not sign a test executable list`);
|
|
3591
3646
|
else if (contained.problems.length) fail("TEST_EXECUTABLE_OUTSIDE_OUTPUT", `${s.id}: ${contained.problems.slice(0, 5).join("; ")}; the row fails and nothing was run`);
|
|
3592
3647
|
else if (signedProblems.length) fail("TEST_EXECUTABLE_UNSIGNED", `${s.id}: ${signedProblems.slice(0, 5).join("; ")}; the row fails and nothing was run`);
|
|
3648
|
+
else if (Array.isArray(s.testGroup)) {
|
|
3649
|
+
// NN17/NN39: the group's members run their own executables in parallel (a pool the size of the test concurrency), each with its own verdict.
|
|
3650
|
+
const byCrate = new Map();
|
|
3651
|
+
for (const b of contained.accepted) { if (!byCrate.has(b.package)) byCrate.set(b.package, []); byCrate.get(b.package).push(b); }
|
|
3652
|
+
const memberRuns = {}; const list = s.testGroup; let next = 0;
|
|
3653
|
+
const worker = async () => {
|
|
3654
|
+
while (next < list.length) {
|
|
3655
|
+
const m = list[next++]; const bins = byCrate.get(m.crate) ?? [];
|
|
3656
|
+
if (!bins.length) { memberRuns[m.id] = { status: "pass", results: { runner: "libtest", tests: 0, pass: 0, fail: 0, skipped: 0, todo: 0, binaries: 0 }, detail: `${m.id}: no test executable; end-to-end tests only, nothing to run` }; continue; }
|
|
3657
|
+
const ran = await runTestBinaries({ scan: { ...s, id: m.id }, binaries: bins, spawn: deps.spawn, env: { ...deps.env, ...s.env, ...(extraEnv ?? {}) }, limitMs, signal, ops, concurrency: 1 });
|
|
3658
|
+
memberRuns[m.id] = { status: ran.status, ...(ran.code ? { code: ran.code } : {}), ...(ran.detail ? { detail: ran.detail } : {}), results: ran.results, testRun: { executables: ran.executables, outputTruncated: ran.executables.some((e) => e.outputTruncated), skipMarkers: ran.executables.reduce((n, e) => n + (e.skipMarkers ?? 0), 0) } };
|
|
3659
|
+
}
|
|
3660
|
+
};
|
|
3661
|
+
await Promise.all(Array.from({ length: Math.max(1, Math.min(testRunConcurrency(), list.length)) }, worker));
|
|
3662
|
+
row.memberRuns = memberRuns;
|
|
3663
|
+
const bad = list.filter((m) => memberRuns[m.id]?.status !== "pass");
|
|
3664
|
+
if (bad.length) { status = "fail"; code = "TEST_GROUP_MEMBER_FAILED"; detail = `${bad.length} of ${list.length} member(s) failed their tests: ${bad.slice(0, 8).map((m) => m.id).join(", ")}`; }
|
|
3665
|
+
else row.results = { runner: "libtest", tests: list.reduce((n, m) => n + (memberRuns[m.id].results?.tests ?? 0), 0), pass: list.reduce((n, m) => n + (memberRuns[m.id].results?.pass ?? 0), 0), fail: 0, skipped: list.reduce((n, m) => n + (memberRuns[m.id].results?.skipped ?? 0), 0), todo: 0 };
|
|
3666
|
+
}
|
|
3593
3667
|
else {
|
|
3594
3668
|
const budget = s.quiet === true ? Math.max(1, Math.min(limitMs, QUIET_SCAN_MAX_MS - (Date.now() - scanStartedAt))) : limitMs;
|
|
3595
3669
|
const ran = await runTestBinaries({ scan: s, binaries: contained.accepted, spawn: deps.spawn, env: { ...deps.env, ...s.env, ...(extraEnv ?? {}) }, limitMs: budget, signal, ops, ...(s.publisherRustTest && s.runOutside.args.includes("--test-threads=1") ? { concurrency: 1 } : {}) });
|
|
@@ -3628,10 +3702,11 @@ export async function runScans(plan, options = {}) {
|
|
|
3628
3702
|
}
|
|
3629
3703
|
// NN41: store a deterministic compile failure only: the broker's authenticated compile failure, or a plain exit of a compile with compiler error diagnostics and no sign of
|
|
3630
3704
|
// the environment failing. Never a timeout, abort, SCAN_ERROR, refusal, unverified receipt, ledger problem, test run or infrastructure error (those return or carry another code).
|
|
3631
|
-
if (status === "fail" && failKey && !signal?.aborted && !ledgerProblem && typeof detail === "string" && detail !== "" && ((code === "BROKER_COMPILE_FAILURE" && row.authenticatedFailure?.failureClass === "compile") || (code === "EXIT" && !carriedScan && !carrier && isDeterministicCompileDiagnostics(`${r?.stdout ?? ""}\n${r?.stderr ?? ""}`))
|
|
3705
|
+
if (status === "fail" && failKey && !signal?.aborted && !ledgerProblem && typeof detail === "string" && detail !== "" && ((code === "BROKER_COMPILE_FAILURE" && row.authenticatedFailure?.failureClass === "compile") || (code === "EXIT" && !carriedScan && !carrier)) && isDeterministicCompileDiagnostics(`${r?.stdout ?? ""}\n${r?.stderr ?? ""}`)) {
|
|
3632
3706
|
cache.write(failKey, { id: s.id, class: s.class, command: s.command, tool: s.tool ?? null, toolVersion: row.toolVersion, status: "fail", code, detail: detail.slice(0, 6000), failureIdentity: options.failureIdentity, ...(row.authenticatedFailure ? { authenticatedFailure: row.authenticatedFailure } : {}), ...(row.jsonSummary ? { jsonSummary: row.jsonSummary } : {}) });
|
|
3633
3707
|
}
|
|
3634
|
-
if (status === "pass" && cacheKey && !signal?.aborted) cache.write(
|
|
3708
|
+
if (status === "pass" && cacheKey && !signal?.aborted && row.rowIndex) cache.write(row.rowIndex.key, { id: s.id, inputs: row.rowIndex.inputs, env: row.rowIndex.env, raw: row.rowIndex.raw, at: new Date().toISOString() });
|
|
3709
|
+
if (status === "pass" && cacheKey && !signal?.aborted) cache.write(cacheKey, { id: s.id, class: s.class, command: s.command, tool: s.tool ?? null, toolVersion: row.toolVersion, status: "pass", ...(s.coverageKey ? { snapshotEvidence: row.snapshotEvidence ?? null, testRun: row.testRun ?? null } : {}), ...(row.results ? { results: row.results } : {}) });
|
|
3635
3710
|
}
|
|
3636
3711
|
}
|
|
3637
3712
|
} catch (e) { status = "fail"; code = "SCAN_ERROR"; detail = e.message; }
|
package/install-app.mjs
CHANGED
|
@@ -187,6 +187,9 @@ export function trashName(appName, now = new Date()) {
|
|
|
187
187
|
export function launchEnvironment(base = process.env, { home = os.userInfo().homedir } = {}) {
|
|
188
188
|
const environment = { ...base, HOME: home };
|
|
189
189
|
delete environment.CLAUDE_CONFIG_DIR;
|
|
190
|
+
// The installed app is the user's, not the build's: a door run's own variables (build ownership, broker socket, carrier map, run
|
|
191
|
+
// markers) must not follow it, or every later door run finds the running app holding that run's ownership (Pulse Mac dev, 2026-11-06).
|
|
192
|
+
for (const key of Object.keys(environment)) if (/^(RIGHTKIT_(BUILD_|CARGO_|CARRIED_|MANAGED_AGENT_)|RK_GATE_)/.test(key)) delete environment[key];
|
|
190
193
|
return environment;
|
|
191
194
|
}
|
|
192
195
|
|
package/package.json
CHANGED
package/rightkit-versions.json
CHANGED
|
@@ -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.
|
|
53
|
+
"@rightkit/release": "0.6.52",
|
|
54
54
|
"@rightkit/settings-ui": "0.7.1",
|
|
55
55
|
"@rightkit/social-ui": "0.1.0",
|
|
56
56
|
"@rightkit/system-ui": "0.1.0",
|
package/unit-list-compile.mjs
CHANGED
|
@@ -8,6 +8,39 @@ import { scanCrateForSecrets } from "./publish-cargo.mjs";
|
|
|
8
8
|
const digest = (value) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
|
|
9
9
|
const bodyOf = ({ workspace, cwd, executable, internal, argv, env, phase }) => ({ workspace, cwd, executable, ...(internal === undefined ? {} : { internal }), argv, env, phase });
|
|
10
10
|
|
|
11
|
+
// NN27 (GATE-CONTRACT GC-A27): never two compiler passes over one crate, target and feature set. A publisher `cargo check` is proved by a
|
|
12
|
+
// passing plan row (clippy or check) over the same crate, features, target and all-targets selection with the same compiler-relevant
|
|
13
|
+
// environment: clippy runs the same compile and only adds lints. Output and failure flags (--message-format, --locked, --keep-going,
|
|
14
|
+
// -j, lint arguments after `--`) do not change what compiled. Tests and docs never reuse: their environment or target selection differs.
|
|
15
|
+
const COMPILE_ENV = ["CC", "CXX", "AR", "LD", "RUSTC", "RUSTFLAGS", "RUSTC_WRAPPER", "RUSTC_WORKSPACE_WRAPPER", "CARGO_TARGET_DIR", "CARGO_BUILD_TARGET", "MACOSX_DEPLOYMENT_TARGET", "CARGO_ENCODED_RUSTFLAGS"];
|
|
16
|
+
/** `as`: "check" (what a check or clippy proves) or "clippy" (a clippy with its lint arguments, provable only by the same clippy). */
|
|
17
|
+
export function compileProofKey(scan, as = "check") {
|
|
18
|
+
if (!scan || !Array.isArray(scan.args)) return null;
|
|
19
|
+
const argv = scan.args[0] === "cargo" ? scan.args.slice(1) : scan.args;
|
|
20
|
+
const sub = argv[0];
|
|
21
|
+
if (sub !== "check" && sub !== "clippy") return null;
|
|
22
|
+
if (as === "clippy" && sub !== "clippy") return null;
|
|
23
|
+
const sep = argv.indexOf("--");
|
|
24
|
+
const lints = as === "clippy" ? (sep < 0 ? [] : argv.slice(sep + 1)) : null;
|
|
25
|
+
const packages = []; const features = []; let noDefault = false; let allFeatures = false; let target = null; let allTargets = false;
|
|
26
|
+
for (let i = 1; i < argv.length; i += 1) {
|
|
27
|
+
const a = argv[i];
|
|
28
|
+
if (a === "--") break;
|
|
29
|
+
if (a === "-p" || a === "--package") packages.push(argv[++i]);
|
|
30
|
+
else if (a === "--features" || a === "-F") features.push(...String(argv[++i] ?? "").split(/[ ,]+/).filter(Boolean));
|
|
31
|
+
else if (a.startsWith("--features=")) features.push(...a.slice(11).split(/[ ,]+/).filter(Boolean));
|
|
32
|
+
else if (a === "--no-default-features") noDefault = true;
|
|
33
|
+
else if (a === "--all-features") allFeatures = true;
|
|
34
|
+
else if (a === "--target") target = argv[++i];
|
|
35
|
+
else if (a === "--all-targets") allTargets = true;
|
|
36
|
+
else if (a === "--locked" || a === "--keep-going" || a === "--no-deps" || a.startsWith("--message-format") || a === "--profile" || a.startsWith("--profile=") || a === "-j" || a === "--jobs" || a.startsWith("-j") || a.startsWith("--jobs=")) { if (a === "--profile" || a === "-j" || a === "--jobs") i += 1; }
|
|
37
|
+
else return null; // anything else could change what compiles: no proof either way
|
|
38
|
+
}
|
|
39
|
+
if (packages.length !== 1 || !packages[0]) return null;
|
|
40
|
+
const env = Object.fromEntries(COMPILE_ENV.map((k) => [k, scan.env?.[k] ?? null]));
|
|
41
|
+
return JSON.stringify({ as, ...(lints ? { lints } : {}), cwd: scan.cwd ?? ".", package: packages[0], features: [...new Set(features)].sort(), noDefault, allFeatures, target, allTargets, env });
|
|
42
|
+
}
|
|
43
|
+
|
|
11
44
|
/** One in-memory plan; env is execution-only and must never be written to a report. */
|
|
12
45
|
export function planUnitListCompile(requirementsByUnit, { normalizedCwds = new Map() } = {}) {
|
|
13
46
|
if (!Array.isArray(requirementsByUnit) || !requirementsByUnit.length) throw new Error("unit list needs compile requirements");
|
|
@@ -101,7 +134,7 @@ export async function runPublisherSecretRequirement({ requirement, snapshot, com
|
|
|
101
134
|
* `run` uses the real scoped snapshot scan runner; `verify` must validate its receipt and command binding.
|
|
102
135
|
* Neither execution environment nor raw receipt is placed in the returned report.
|
|
103
136
|
*/
|
|
104
|
-
export async function executeUnitListCompile({ jobs, dependencies = {}, initialFailures = new Set(), run, verify }) {
|
|
137
|
+
export async function executeUnitListCompile({ jobs, dependencies = {}, initialFailures = new Set(), run, verify, concurrency = 1 }) {
|
|
105
138
|
if (!Array.isArray(jobs) || typeof run !== "function" || typeof verify !== "function") throw new Error("snapshot scan runner and receipt verifier are required");
|
|
106
139
|
const pending = jobs.map((job) => ({ ...job, members: job.members.map((member) => ({ ...member })) }));
|
|
107
140
|
const all = pending.flatMap((job) => job.members);
|
|
@@ -150,7 +183,9 @@ export async function executeUnitListCompile({ jobs, dependencies = {}, initialF
|
|
|
150
183
|
// themselves runnable. If such waits form a cycle, execute the ready subset to make progress.
|
|
151
184
|
let admitted = frontier.filter(({ job, ready }) => ready.length === job.members.length);
|
|
152
185
|
if (!admitted.length && frontier.length && !progress) admitted = [frontier[0]];
|
|
153
|
-
|
|
186
|
+
// NN17/NN39: the admitted jobs are independent (one ready requirement per unit, its earlier ones done), so they run `concurrency` at a time;
|
|
187
|
+
// 1 is the serial order this loop had. Every result is still verified per member before anything later is admitted.
|
|
188
|
+
const runAdmitted = async ({ job, ready }) => {
|
|
154
189
|
let invocation = { ...job, members: ready };
|
|
155
190
|
if (job.batchAt !== undefined) {
|
|
156
191
|
const names = [...new Set(ready.map((m) => m.package))];
|
|
@@ -170,14 +205,16 @@ export async function executeUnitListCompile({ jobs, dependencies = {}, initialF
|
|
|
170
205
|
record(member, status, proof); job.members.splice(job.members.indexOf(member), 1);
|
|
171
206
|
}
|
|
172
207
|
progress = true;
|
|
173
|
-
}
|
|
208
|
+
};
|
|
209
|
+
const queue = [...admitted];
|
|
210
|
+
await Promise.all(Array.from({ length: Math.max(1, Math.min(Number(concurrency) || 1, queue.length)) }, async () => { while (queue.length) await runAdmitted(queue.shift()); }));
|
|
174
211
|
if (!progress) throw new Error("unit requirements have an unresolved or cyclic dependency");
|
|
175
212
|
}
|
|
176
213
|
return results;
|
|
177
214
|
}
|
|
178
215
|
|
|
179
216
|
/** Bridge the authenticated publisher jobs to runScans' initialized Class B scheduler. */
|
|
180
|
-
export function publisherUnionScheduler({ jobs, dependencies = {}, initialFailures = new Set(), requirements, adapt, verify, signal = null, onCoverage = () => {} }) {
|
|
217
|
+
export function publisherUnionScheduler({ reuseProofs = true, concurrency = 1, jobs, dependencies = {}, initialFailures = new Set(), requirements, adapt, verify, signal = null, onCoverage = () => {} }) {
|
|
181
218
|
if (!Array.isArray(requirements) || requirements.some((r) => r.internal) || typeof adapt !== "function" || typeof verify !== "function") throw new Error("publisher scheduler needs external requirements, adapter and verifier; internal scans must already be verified");
|
|
182
219
|
const byId = new Map(requirements.map((r) => [r.id, r]));
|
|
183
220
|
if (byId.size !== requirements.length) throw new Error("duplicate publisher requirement IDs");
|
|
@@ -197,8 +234,33 @@ export function publisherUnionScheduler({ jobs, dependencies = {}, initialFailur
|
|
|
197
234
|
for (const [n, j] of indices.entries()) slots[j] = rows[n];
|
|
198
235
|
}
|
|
199
236
|
}
|
|
200
|
-
|
|
237
|
+
// Passing plan rows that prove a compile (NN27), with the evidence a publisher verify needs on a broker host.
|
|
238
|
+
const proofs = new Map();
|
|
239
|
+
for (let i = 0; i < scans.length; i += 1) {
|
|
240
|
+
if (byId.has(scans[i].id) || slots[i]?.status !== "pass") continue;
|
|
241
|
+
if (scans[i].root === "cargoLive" && !/^[0-9a-f]{64}$/.test(slots[i].snapshotEvidence?.receiptSha256 ?? "")) continue;
|
|
242
|
+
for (const as of ["check", "clippy"]) { const key = compileProofKey(scans[i], as); if (key !== null && !proofs.has(key)) proofs.set(key, { id: scans[i].id, row: slots[i] }); }
|
|
243
|
+
}
|
|
244
|
+
// A quiet suite needs the broker drained for its quiet lease: a job with a quiet member runs alone (exclusive), the others share.
|
|
245
|
+
let shared = 0; let exclusive = false; const waiters = [];
|
|
246
|
+
const wake = () => { const ready = waiters.splice(0); for (const w of ready) w(); };
|
|
247
|
+
const acquire = async (alone) => {
|
|
248
|
+
for (;;) {
|
|
249
|
+
if (alone ? (!exclusive && shared === 0) : !exclusive) { if (alone) exclusive = true; else shared += 1; return; }
|
|
250
|
+
await new Promise((resolve) => waiters.push(resolve));
|
|
251
|
+
}
|
|
252
|
+
};
|
|
253
|
+
const release = (alone) => { if (alone) exclusive = false; else shared -= 1; wake(); };
|
|
254
|
+
const result = await executeUnitListCompile({ concurrency, jobs, dependencies, initialFailures,
|
|
201
255
|
run: async (job) => {
|
|
256
|
+
const alone = job.members.some((member) => scans[byScan.get(member.id)]?.quiet === true);
|
|
257
|
+
await acquire(alone);
|
|
258
|
+
try { return await runJob(job); } finally { release(alone); }
|
|
259
|
+
},
|
|
260
|
+
verify: async ({ job, result: row, member }) => verify({ job, row, member, attempts: attempts.get(member.id) ?? [], requirement: byId.get(member.id) }),
|
|
261
|
+
});
|
|
262
|
+
async function runJob(job) {
|
|
263
|
+
{
|
|
202
264
|
const byMember = new Map();
|
|
203
265
|
const budget = { remaining: Math.min(2 * job.members.length - 1, 31) };
|
|
204
266
|
const runMembers = async (members) => {
|
|
@@ -206,6 +268,24 @@ export function publisherUnionScheduler({ jobs, dependencies = {}, initialFailur
|
|
|
206
268
|
for (const member of members) { const history = attempts.get(member.id) ?? []; history.push({ status: "not-run", code: signal?.aborted ? "CANCELLED" : "BATCH_BUDGET" }); attempts.set(member.id, history); }
|
|
207
269
|
return;
|
|
208
270
|
}
|
|
271
|
+
// NN27: a member whose compile a passing plan row already proved reuses that row; only the rest compile.
|
|
272
|
+
const proved = [];
|
|
273
|
+
const rest = members.filter((member) => {
|
|
274
|
+
const own = { ...scans[byScan.get(member.id)], cwd: job.cwd }; // the job's cwd is the workspace when proveWorkspaceCwd moved it
|
|
275
|
+
const ownArgv = own.args?.[0] === "cargo" ? own.args.slice(1) : own.args ?? [];
|
|
276
|
+
const key = compileProofKey(own, ownArgv[0] === "clippy" ? "clippy" : "check");
|
|
277
|
+
const proof = key === null || !reuseProofs ? undefined : proofs.get(key);
|
|
278
|
+
if (!proof) return true;
|
|
279
|
+
proved.push([member, proof]); return false;
|
|
280
|
+
});
|
|
281
|
+
for (const [member, proof] of proved) {
|
|
282
|
+
const row = { ...proof.row, provedBy: proof.id };
|
|
283
|
+
const history = attempts.get(member.id) ?? [];
|
|
284
|
+
history.push({ id: proof.id, status: row.status, command: row.command, provedBy: proof.id, ...(row.snapshotEvidence ? { snapshotEvidence: row.snapshotEvidence } : {}) });
|
|
285
|
+
attempts.set(member.id, history); executed.set(member.id, row); byMember.set(member.id, row);
|
|
286
|
+
}
|
|
287
|
+
if (!rest.length) return;
|
|
288
|
+
members = rest;
|
|
209
289
|
budget.remaining -= 1;
|
|
210
290
|
const representative = byId.get(members[0].id);
|
|
211
291
|
if (!representative) throw new Error("unknown publisher requirement");
|
|
@@ -234,9 +314,8 @@ export function publisherUnionScheduler({ jobs, dependencies = {}, initialFailur
|
|
|
234
314
|
};
|
|
235
315
|
await runMembers(job.members);
|
|
236
316
|
return { byMember };
|
|
237
|
-
}
|
|
238
|
-
|
|
239
|
-
});
|
|
317
|
+
}
|
|
318
|
+
}
|
|
240
319
|
onCoverage(result);
|
|
241
320
|
for (const item of result) {
|
|
242
321
|
const index = byScan.get(item.id); const scan = scans[index]; const row = executed.get(item.id);
|
package/web-build.mjs
CHANGED
|
@@ -17,6 +17,7 @@
|
|
|
17
17
|
// runs only under a live door run. The exported runner checks it again, so no in-process caller spawns a step around it.
|
|
18
18
|
import path from "node:path";
|
|
19
19
|
import { pathToFileURL } from "node:url";
|
|
20
|
+
import fs from "node:fs";
|
|
20
21
|
import { spawnSync } from "./background-process.mjs";
|
|
21
22
|
import { existsSync, readFileSync } from "node:fs";
|
|
22
23
|
import { CommandSpecError, loadAppConfig, resolveInvocation, validateStep } from "./command-spec.mjs";
|
|
@@ -115,6 +116,11 @@ export async function main(argv = process.argv.slice(2), { env = process.env, re
|
|
|
115
116
|
const appRoot = path.dirname(path.resolve(opts.config));
|
|
116
117
|
const refusal = webBuildDoorRefusal({ appRoot, env, spawnSyncFn, requireDoor });
|
|
117
118
|
if (refusal) throw doorError(refusal);
|
|
119
|
+
// The door already produced this app's declared web outputs for this run (rightkit-gate stageWebBuildOnce: built, restored from its dist
|
|
120
|
+
// cache, or present in the snapshot): running vite again would rewrite them, and a Tauri crate that embeds them rebuilds and changes after its
|
|
121
|
+
// sidecar was staged (Pulse Windows dev, 2026-11-06). The door's own marker names the app root; anything else builds as before.
|
|
122
|
+
const real = (p) => { try { return fs.realpathSync(p); } catch { return path.resolve(p); } };
|
|
123
|
+
if (env.RK_GATE_WEB_BUILT && real(env.RK_GATE_WEB_BUILT) === real(appRoot)) { log(`right-release web-build: skipped; the door already produced the declared web outputs of ${appRoot} for this run`); return 0; }
|
|
118
124
|
const { config } = await loadConfig(opts.config);
|
|
119
125
|
return runWebBuild(planWebBuild(config), { appRoot, env, dryRun: opts.dryRun, spawnSyncFn, requireDoor, log });
|
|
120
126
|
}
|