@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/deterministic-scans.mjs
CHANGED
|
@@ -18,6 +18,7 @@
|
|
|
18
18
|
// result is a plain object (per-scan status, tool versions, scanSetDigest) usable as receipt content
|
|
19
19
|
// (packages/release/pipeline-receipts.mjs); it carries no authority by itself.
|
|
20
20
|
import crypto from "node:crypto";
|
|
21
|
+
import { cargoWidthArgs } from "./cargo-width.mjs";
|
|
21
22
|
import fs from "node:fs";
|
|
22
23
|
import os from "node:os";
|
|
23
24
|
import path from "node:path";
|
|
@@ -252,6 +253,44 @@ export function fmtCheckArgs(unit = null) { return unit ? ["fmt", "-p", unit, "-
|
|
|
252
253
|
/** `cargo metadata` that validates manifests and the lock without resolving anything new. */
|
|
253
254
|
export function metadataArgs({ noDeps = true } = {}) { return ["metadata", ...(noDeps ? ["--no-deps"] : []), "--format-version", "1", "--locked"]; }
|
|
254
255
|
|
|
256
|
+
/** Translate one authenticated publisher requirement into a normal Class B scan. */
|
|
257
|
+
export function publisherRequirementScan(requirement, { platform = process.platform, nativeArch = process.arch, cargoCommand = ["cargo"], cargoLiveRoot = null, targetDirs = null, quiet = false, allowIgnored = false, cargoJobs = null } = {}) {
|
|
258
|
+
const { id, workspace, cwd, executable, argv, env, phase, coverageKey } = requirement ?? {};
|
|
259
|
+
if (typeof id !== "string" || !id || typeof coverageKey !== "string" || !coverageKey || !Array.isArray(argv) || !argv.every((arg) => typeof arg === "string") || !env || typeof env !== "object" || Array.isArray(env) || !["compile", "test"].includes(phase)) throw new TypeError("invalid publisher requirement");
|
|
260
|
+
const plainDir = (value) => typeof value === "string" && /^(?:\.|[A-Za-z0-9_@+.-]+(?:\/[A-Za-z0-9_@+.-]+)*)$/.test(value) && !value.split("/").includes("..");
|
|
261
|
+
if (!plainDir(workspace) || !plainDir(cwd) || !["cargo", "pnpm"].includes(executable) || !Array.isArray(cargoCommand) || !cargoCommand.length || !cargoCommand.every((part) => typeof part === "string" && part)) throw new TypeError("invalid publisher requirement command or workspace");
|
|
262
|
+
const isRustTest = executable === "cargo" && phase === "test" && argv[0] === "test";
|
|
263
|
+
let args = [...argv]; let runOutside;
|
|
264
|
+
if (isRustTest && cargoLiveRoot) {
|
|
265
|
+
const separator = args.indexOf("--");
|
|
266
|
+
const runArgs = separator < 0 ? [] : args.slice(separator + 1);
|
|
267
|
+
args = (separator < 0 ? args : args.slice(0, separator)).filter((arg) => arg !== "--no-fail-fast" && !arg.startsWith("--message-format="));
|
|
268
|
+
args.push("--message-format=json");
|
|
269
|
+
runOutside = { args: runArgs };
|
|
270
|
+
}
|
|
271
|
+
if (executable === "cargo") {
|
|
272
|
+
if (cargoJobs !== null) args = cargoWidthArgs(args, cargoJobs);
|
|
273
|
+
args = oneOutput(isRustTest && cargoLiveRoot ? args : everyFailure(args), { platform, arch: nativeArch });
|
|
274
|
+
}
|
|
275
|
+
const scan = { id, coverageKey, ...(executable === "cargo" ? { executionWorkspace: workspace } : {}), publisherPhase: phase, class: SCAN_CLASS.B, root: executable === "cargo" && cargoLiveRoot ? "cargoLive" : "live", cwd, tool: executable === "cargo" ? cargoCommand[0] : executable, args: executable === "cargo" ? [...cargoCommand.slice(1), ...args] : args, env: { ...env, ...(targetDirs?.[workspace] ? { CARGO_TARGET_DIR: targetDirs[workspace] } : {}) }, ...(quiet && phase === "test" ? { quiet: true } : {}), ...(runOutside ? { runOutside } : {}), ...(isRustTest ? { publisherRustTest: true, allowIgnored } : {}), ...(executable === "pnpm" && phase === "test" ? { kind: "test" } : {}) };
|
|
276
|
+
// Do not render the inherited publisher environment into logs or receipts.
|
|
277
|
+
scan.command = commandText({ ...scan, env: {} });
|
|
278
|
+
return scan;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/** Deduplicate concurrent identical probes; transient outcomes are never retained. */
|
|
282
|
+
export function singleFlightProbe(probe) {
|
|
283
|
+
const pending = new Map(); const completed = new Map();
|
|
284
|
+
return async (key, ...args) => {
|
|
285
|
+
if (completed.has(key)) return completed.get(key);
|
|
286
|
+
if (pending.has(key)) return pending.get(key);
|
|
287
|
+
const job = Promise.resolve().then(() => probe(...args));
|
|
288
|
+
pending.set(key, job);
|
|
289
|
+
try { const outcome = await job; if (!outcome?.transient) completed.set(key, outcome); return outcome; }
|
|
290
|
+
finally { pending.delete(key); }
|
|
291
|
+
};
|
|
292
|
+
}
|
|
293
|
+
|
|
255
294
|
// ---- Clippy batching (GATE-CONTRACT §1 "Clippy route & batching"; item 8 rows 8.6, 8.8, 8.15) -----------------------------------------
|
|
256
295
|
|
|
257
296
|
// The batch planner itself (clippyBatchPlan, clippySelectionOf, CLIPPY_UNIVERSAL_FEATURE_FLAGS) lives in scan-digest.mjs, beside the scan
|
|
@@ -430,6 +469,8 @@ export const PINNED_SCAN_TOOLS = Object.freeze({ shellcheck: "0.11.0", oxlint: "
|
|
|
430
469
|
* service. A verdict that includes them is reusable only after they are re-run (`rightkit-gate live-scans`; GATE-CONTRACT §1, E18),
|
|
431
470
|
* and a red caused by one is never deterministic. Ids are `<prefix>` or `<prefix>:<root>`; rustright's REMOTE_SCANS mirrors this list. */
|
|
432
471
|
export const LIVE_SCAN_IDS = Object.freeze(["pnpm-audit", "ghsa-audit"]);
|
|
472
|
+
/** Internal rules whose verdict is a function of the files they read and the rule code only (GC-A24): reused by input key. */
|
|
473
|
+
export const CACHEABLE_INTERNAL = new Set(["secret-scan", "json-parse", "toml-parse", "yaml-parse", "license", "changelog-version", "ownership-catalog", "swift-lock", "gradle-lock", "python-lock"]);
|
|
433
474
|
export const isLiveScan = (id) => LIVE_SCAN_IDS.some((p) => id === p || String(id).startsWith(`${p}:`));
|
|
434
475
|
/** Scans whose FAILURE may come from the registry rather than their inputs: `pnpm-lockfile` (`install --frozen-lockfile --lockfile-only`)
|
|
435
476
|
* re-verifies lockfile entries against the registry when pnpm's cache is cold, so an outage fails it. Their pass is deterministic, but a
|
|
@@ -438,6 +479,30 @@ export const REGISTRY_SCAN_IDS = Object.freeze(["pnpm-lockfile"]);
|
|
|
438
479
|
export const isRegistryScan = (id) => REGISTRY_SCAN_IDS.some((p) => id === p || String(id).startsWith(`${p}:`));
|
|
439
480
|
/** Files per rustfmt scan: 120 paths of ~100 bytes stay under Windows' 32 KB command line with the tool and flags. */
|
|
440
481
|
export const RUSTFMT_BATCH = 120;
|
|
482
|
+
/** FNV-1a of a path: the stable bucket hash of rustfmtBuckets. */
|
|
483
|
+
function pathBucketHash(text) {
|
|
484
|
+
let h = 0x811c9dc5;
|
|
485
|
+
for (let i = 0; i < text.length; i++) { h ^= text.charCodeAt(i); h = Math.imul(h, 0x01000193) >>> 0; }
|
|
486
|
+
return h;
|
|
487
|
+
}
|
|
488
|
+
/** Most bytes of file arguments one rustfmt bucket passes: Windows refuses a command line past 32,767 characters. */
|
|
489
|
+
export const RUSTFMT_BUCKET_BYTES = 24000;
|
|
490
|
+
/**
|
|
491
|
+
* Splits `files` into rustfmt buckets: bucket = path hash mod a power-of-two count, the smallest with at most 100 files per bucket on
|
|
492
|
+
* average whose every bucket's arguments fit RUSTFMT_BUCKET_BYTES. Empty buckets are dropped; each bucket is sorted. A file's bucket
|
|
493
|
+
* depends only on its path and the count, which changes only when the file count crosses a power of two.
|
|
494
|
+
*/
|
|
495
|
+
export function rustfmtBuckets(files) {
|
|
496
|
+
const sorted = [...files].sort();
|
|
497
|
+
let count = 1;
|
|
498
|
+
while (count * 100 < sorted.length) count *= 2;
|
|
499
|
+
for (;;) {
|
|
500
|
+
const buckets = Array.from({ length: count }, () => []);
|
|
501
|
+
for (const f of sorted) buckets[pathBucketHash(f) % count].push(f);
|
|
502
|
+
if (buckets.every((b) => b.reduce((n, f) => n + f.length + 3, 0) <= RUSTFMT_BUCKET_BYTES)) return buckets.filter((b) => b.length);
|
|
503
|
+
count *= 2;
|
|
504
|
+
}
|
|
505
|
+
}
|
|
441
506
|
|
|
442
507
|
/** True when this module is the checked repository's own in-tree copy (packages/release of `contentRoot`), where its scripts/ live. */
|
|
443
508
|
export function inTreeGate(contentRoot, exists = fs.existsSync) {
|
|
@@ -869,7 +934,7 @@ export function planScans({
|
|
|
869
934
|
changed = [], contentRoot, liveRoot = contentRoot, trustedRoot = null, exists = fs.existsSync, readFile = (f) => fs.readFileSync(f, "utf8"),
|
|
870
935
|
platform = process.platform, includeTests = true, localCompile = true,
|
|
871
936
|
// The host's CPU architecture for its own Rust target (oneOutput, cross-targets.mjs).
|
|
872
|
-
nativeArch = process.arch,
|
|
937
|
+
nativeArch = process.arch, cargoJobs = null,
|
|
873
938
|
// Where the quiet test scans (ci/gate.config.json `quietTests`) run: "local" plans them for the quiet lane; "ci" leaves them to the
|
|
874
939
|
// CI shards (one crate per runner, where the port, pipe, desktop and wall-clock conflicts that force the serial lane do not exist)
|
|
875
940
|
// and records a note naming them (Adrian 2026-10-22: compile locally on the warm cache, qualify the conflicting tests on VMs).
|
|
@@ -954,6 +1019,11 @@ export function planScans({
|
|
|
954
1019
|
// crate and configuration, so required ids (GC-A14's three targets, scan-receipt) and GC-T14 keys are untouched; only the run is shared.
|
|
955
1020
|
// `shardSolo` and `clippySeparate` keep a crate out of every group, as they do for clippyBatching. Off unless the caller (rightkit-gate) asks.
|
|
956
1021
|
classBBatching = false,
|
|
1022
|
+
// Dependency-freshness advice (rightkit#1475): planned only when the caller asks for advice in this run. It is a live
|
|
1023
|
+
// registry answer that can never fail a run, and its uncached cost (a 120 s timeout in 41 of 81 crate runs,
|
|
1024
|
+
// 2026-11-04) must not sit on the blocking path to a compile; update reporting (@rightkit/outdated) owns asking.
|
|
1025
|
+
// A caller that wants the row passes true and gets exactly the historical scan, timeouts recorded as not measured.
|
|
1026
|
+
freshnessAdvice = false,
|
|
957
1027
|
} = {}) {
|
|
958
1028
|
if (!contentRoot) throw new TypeError("planScans: contentRoot is required");
|
|
959
1029
|
if (!Array.isArray(cargoCommand) || cargoCommand.length === 0 || !["rustright", "cargo"].includes(cargoCommand[0]) || cargoCommand.slice(1).some((a) => a !== "cargo")) {
|
|
@@ -1014,12 +1084,12 @@ export function planScans({
|
|
|
1014
1084
|
const refusedScan = (error) => ({ tool: "node", args: ["-e", `console.error(${JSON.stringify(String(error.message))}); process.exit(1)`] });
|
|
1015
1085
|
const cargoBase = (ws, args, { raw = false } = {}) => { let argv; try { argv = oneOutput(raw ? args : everyFailure(args), { platform, arch: nativeArch }); } catch (error) { return { ...refusedScan(error), ...(ws !== "." ? { cwd: ws } : {}) }; } return { tool: cargoCommand[0], args: [...cargoCommand.slice(1), ...argv], ...(ws !== "." ? { cwd: ws } : {}), ...(targetDirs?.[ws] ? { env: { CARGO_TARGET_DIR: targetDirs[ws] } } : {}) }; };
|
|
1016
1086
|
// Class B (compiles): started from the primary checkout on a broker host, the snapshot carrier names the source.
|
|
1017
|
-
const cargoIn = (ws, ...args) => ({ ...cargoBase(ws, args), ...(cargoLiveRoot ? { root: "cargoLive" } : {}) });
|
|
1087
|
+
const cargoIn = (ws, ...args) => ({ ...cargoBase(ws, cargoJobs === null ? args : cargoWidthArgs(args, cargoJobs)), ...(cargoLiveRoot ? { root: "cargoLive" } : {}) });
|
|
1018
1088
|
// A Rust test scan on a BROKER host (cargoLiveRoot set; GATE-CONTRACT GC-A08): the broker compiles with the plain test command plus --locked and
|
|
1019
1089
|
// --message-format=json (the broker adds --no-run itself and never executes a test), and the gate runs the listed executables outside it. --no-fail-fast and
|
|
1020
1090
|
// --test-threads=1 are RUN arguments (runOutside.args), never part of the compile. A direct host (no broker, cargoLiveRoot unset) has nothing to keep tests
|
|
1021
1091
|
// out of: its test scan stays the one-step `test ... --locked --no-fail-fast`, compile and run together, with no runOutside.
|
|
1022
|
-
const cargoTestIn = (ws, ...args) => ({ ...cargoBase(ws, [...args, "--message-format=json"], { raw: true }), root: "cargoLive" });
|
|
1092
|
+
const cargoTestIn = (ws, ...args) => ({ ...cargoBase(ws, [...(cargoJobs === null ? args : cargoWidthArgs(args, cargoJobs)), "--message-format=json"], { raw: true }), root: "cargoLive" });
|
|
1023
1093
|
// Class A (reads Cargo inputs, compiles nothing): always the content root, the snapshot or the commit's own tree. These still execute
|
|
1024
1094
|
// cargo (through the broker on a broker host), so a unit-scoped check follows the Rust closure for them (app-closure.mjs scopeScans reads
|
|
1025
1095
|
// the ids `cargo-metadata|cargo-deny|cargo-audit[:<label>]` and `cargo-package-list:<unit>` and the scan's `cwd`; rename one there too).
|
|
@@ -1173,13 +1243,13 @@ export function planScans({
|
|
|
1173
1243
|
}
|
|
1174
1244
|
byEdition.set(found.edition, [...(byEdition.get(found.edition) ?? []), f]);
|
|
1175
1245
|
}
|
|
1176
|
-
//
|
|
1177
|
-
// HeardRight on the Dell, 2026-10-27), so a
|
|
1246
|
+
// rustfmt runs per edition in buckets: Windows refuses a command line past ~32 KB (spawn ENAMETOOLONG on a large repository,
|
|
1247
|
+
// HeardRight on the Dell, 2026-10-27), so a bucket's arguments stay under RUSTFMT_BUCKET_BYTES. A file's bucket is a hash of its path over a
|
|
1248
|
+
// power-of-two bucket count (GC-A24, rightkit#1506): an edited or added file changes only its own bucket's key, where the former
|
|
1249
|
+
// sorted slices shifted every later batch. The first bucket keeps the plain id.
|
|
1178
1250
|
for (const [edition, group] of [...byEdition].sort((a, b) => (a[0] < b[0] ? -1 : 1))) {
|
|
1179
|
-
const
|
|
1180
|
-
|
|
1181
|
-
const batch = sorted.slice(i, i + RUSTFMT_BATCH);
|
|
1182
|
-
add({ id: `rustfmt:${edition}${i ? `:${i / RUSTFMT_BATCH + 1}` : ""}`, class: A, tool: "rustfmt", args: ["--check", "--edition", edition, ...batch], root: "content" });
|
|
1251
|
+
for (const [i, bucket] of rustfmtBuckets(group).entries()) {
|
|
1252
|
+
add({ id: `rustfmt:${edition}${i ? `:${i + 1}` : ""}`, class: A, tool: "rustfmt", args: ["--check", "--edition", edition, ...bucket], root: "content" });
|
|
1183
1253
|
}
|
|
1184
1254
|
}
|
|
1185
1255
|
for (const f of files.filter((f) => /\.(mjs|cjs|js)$/.test(f) && !f.includes("node_modules") && !declaredFixture(f)).sort()) {
|
|
@@ -1255,8 +1325,9 @@ export function planScans({
|
|
|
1255
1325
|
// Exceptions expire by date, not by change: checked on every run, whatever changed.
|
|
1256
1326
|
if (exists(path.join(contentRoot, "ci/advisory-exceptions.json"))) add({ id: "advisory-exceptions", class: A, internal: "advisory-exceptions" });
|
|
1257
1327
|
// Dependency freshness (rightkit#1475): `right-update check --json` once per repository that commits `.rightkit/update.json`. Advice only: it never
|
|
1258
|
-
// fails a run (latest is a live registry answer), and the row carries "N behind latest".
|
|
1259
|
-
|
|
1328
|
+
// fails a run (latest is a live registry answer), and the row carries "N behind latest". Planned only on request
|
|
1329
|
+
// (`freshnessAdvice`): optional advice never blocks a compile (reconciled scope, rightkit#1505).
|
|
1330
|
+
if (freshnessAdvice && exists(path.join(contentRoot, ".rightkit/update.json"))) add({ id: "dependency-freshness", class: A, internal: "dependency-freshness", advise: true });
|
|
1260
1331
|
// An app's advisory exceptions follow the same policy as RightKit's own: a Cargo workspace whose deny.toml or .cargo/audit.toml
|
|
1261
1332
|
// ignores an advisory needs its ledger, <workspace>/.rightkit/advisory-exceptions.json, with owner, evidence, an unexpired
|
|
1262
1333
|
// reviewBy, the exact affected versions and dependents in that workspace's Cargo.lock, and a person's approval; deny.toml and
|
|
@@ -2054,7 +2125,9 @@ export async function runTestBinaries({ scan, binaries, spawn, env, limitMs, sig
|
|
|
2054
2125
|
if (r?.error?.code === "ETIMEDOUT" || r?.timedOut === true) { stopped = "TIMEOUT"; executables.push({ label, sha256: b.sha256, status: "fail" }); failures.push(`${label}: killed with its process tree at the run limit`); return; }
|
|
2055
2126
|
const summary = parseLibtestSummary(`${r?.stdout ?? ""}\n${r?.stderr ?? ""}`);
|
|
2056
2127
|
if (summary) { total.tests += summary.passed + summary.failed + summary.ignored; total.pass += summary.passed; total.fail += summary.failed; total.skipped += summary.ignored; }
|
|
2057
|
-
const
|
|
2128
|
+
const output = `${r?.stdout ?? ""}\n${r?.stderr ?? ""}`.replace(/\u001b\[[0-9;?]*[ -/]*[@-~]/g, "");
|
|
2129
|
+
const skipMarkers = output.split(/\r\n|\n|\r/).filter((line) => /(?:^|[\s\]:])SKIP(?=[\s:]|$)/.test(line)).length;
|
|
2130
|
+
const entry = { label, sha256: b.sha256, outputTruncated: r?.truncated === true, skipMarkers, status: "pass", ...(summary ? { passed: summary.passed, failed: summary.failed, ignored: summary.ignored } : {}) };
|
|
2058
2131
|
if (!r || r.error) { entry.status = "fail"; failures.push(`${label}: ${r?.error?.message ?? "no result"}`); }
|
|
2059
2132
|
else if (r.status !== 0) { entry.status = "fail"; failures.push(`${label}: ${failureDetail(r) || `exit ${r.status}`}`); }
|
|
2060
2133
|
else if (summary && (!summary.ok || summary.failed > 0)) { entry.status = "fail"; failures.push(`${label}: exited 0 but its summary reports ${summary.failed} failed test(s)`); }
|
|
@@ -2157,6 +2230,7 @@ function scanDirectory(scan) {
|
|
|
2157
2230
|
*/
|
|
2158
2231
|
export function classBChainKey(scan, carried) {
|
|
2159
2232
|
const dir = scanDirectory(scan);
|
|
2233
|
+
if (carried && typeof scan?.executionWorkspace === "string") return scan.executionWorkspace;
|
|
2160
2234
|
return carried ? (dir ?? ".") : `local:${dir ?? scan?.id ?? "."}`;
|
|
2161
2235
|
}
|
|
2162
2236
|
|
|
@@ -2190,7 +2264,8 @@ export async function scheduleBrokerHostClassB({ scans, lanes, carried, localJob
|
|
|
2190
2264
|
try { await run(i); } finally { free(); }
|
|
2191
2265
|
continue;
|
|
2192
2266
|
}
|
|
2193
|
-
|
|
2267
|
+
const scanDepth = scans[i].executionWorkspace ? 1 : depth;
|
|
2268
|
+
while (flight.size >= scanDepth) await Promise.race(flight);
|
|
2194
2269
|
const job = run(i).finally(() => flight.delete(job));
|
|
2195
2270
|
flight.add(job);
|
|
2196
2271
|
}
|
|
@@ -2199,6 +2274,7 @@ export async function scheduleBrokerHostClassB({ scans, lanes, carried, localJob
|
|
|
2199
2274
|
}
|
|
2200
2275
|
|
|
2201
2276
|
export function laneOf(scan) {
|
|
2277
|
+
if (scan.publisherPhase === "compile") return "compile";
|
|
2202
2278
|
if (/^(clippy|check|check-features|check-dependent):/.test(scan.id)) return "compile";
|
|
2203
2279
|
if (/^doc:/.test(scan.id)) return "doc";
|
|
2204
2280
|
return scan.quiet === true ? "quiet" : "tests";
|
|
@@ -2641,8 +2717,11 @@ export async function runScans(plan, options = {}) {
|
|
|
2641
2717
|
// One reader for the whole run: every watched scan registers with it (first read after 1 s, then every 5 s, two reads in flight at most), instead of a client spawn per scan.
|
|
2642
2718
|
const pollMs = options.brokerPollMs ?? ADMISSION_POLL_MS;
|
|
2643
2719
|
const statusPoller = brokerLive ? createStatusPoller({ live: brokerLive, intervalMs: pollMs }) : null;
|
|
2644
|
-
const toolVersions = {}; const toolIdentities = {}; const
|
|
2720
|
+
const toolVersions = {}; const toolIdentities = {}; const advisoryDbs = new Map();
|
|
2645
2721
|
const results = [];
|
|
2722
|
+
// Failed grouped invocations that were bisected for attribution (runGroup below): retained as run notes and on each
|
|
2723
|
+
// member row (`batchFailure`), so a combined failure stays visible even when every diagnostic split then passes.
|
|
2724
|
+
const batchFailureNotes = [];
|
|
2646
2725
|
// The gate-owned cargo ledger of a wrapped snapshot compile (options.cargoLedger = { dir }): every call the wrapper decided, filed
|
|
2647
2726
|
// under its scan's token. `ledgerSeen` is the run's one-use record of carriers and request ids across every scan.
|
|
2648
2727
|
const cargoLedger = options.cargoLedger?.dir ? options.cargoLedger : null;
|
|
@@ -2674,8 +2753,7 @@ export async function runScans(plan, options = {}) {
|
|
|
2674
2753
|
const classBBlocked = !inCallA && !priorClassAValid && options.classAEarlier !== true;
|
|
2675
2754
|
|
|
2676
2755
|
const toolCommand = (tool) => (tool === "node" ? deps.execPath : tool === "rustfmt" ? deps.findRustfmt({ env: deps.env, exists: deps.exists, readdir: deps.readdir, platform: deps.platform, spawn: deps.lookupSpawn }) : tool);
|
|
2677
|
-
|
|
2678
|
-
if (probed.has(tool)) return probed.get(tool);
|
|
2756
|
+
const probeFlight = singleFlightProbe(async (tool, scanDir = null) => {
|
|
2679
2757
|
let outcome;
|
|
2680
2758
|
// A trusted analyzer is resolved ONCE, from its enrolment (never PATH), and its bytes verified before this probe runs it.
|
|
2681
2759
|
const trust = TRUSTED_SCAN_TOOLS.includes(tool) ? resolveTrustedScanTool(tool, { policy: options.toolPolicy, platform: deps.platform, ops: options.toolOps }) : null;
|
|
@@ -2715,9 +2793,15 @@ export async function runScans(plan, options = {}) {
|
|
|
2715
2793
|
}
|
|
2716
2794
|
}
|
|
2717
2795
|
toolVersions[tool] = outcome.ok ? outcome.version : null;
|
|
2718
|
-
if (!outcome.transient) probed.set(tool, outcome);
|
|
2719
2796
|
return outcome;
|
|
2720
|
-
}
|
|
2797
|
+
});
|
|
2798
|
+
const probe = (tool, scanDir = null) => {
|
|
2799
|
+
const trust = TRUSTED_SCAN_TOOLS.includes(tool) ? resolveTrustedScanTool(tool, { policy: options.toolPolicy, platform: deps.platform, ops: options.toolOps }) : null;
|
|
2800
|
+
const command = trust ? (trust.ok ? trust.identity.path : null) : toolCommand(tool);
|
|
2801
|
+
const cwd = (tool === "rustright" || (tool === "cargo" && cargoLiveRoot)) && scanDir ? scanDir : (deps.probeDir ?? probeDir());
|
|
2802
|
+
const key = sha256(canonicalJson({ tool, command, cwd, args: PROBES[tool] ?? ["--version"], env: deps.env }));
|
|
2803
|
+
return probeFlight(key, tool, scanDir);
|
|
2804
|
+
};
|
|
2721
2805
|
|
|
2722
2806
|
const jobs = Math.max(1, Number(options.jobs ?? 1) || 1);
|
|
2723
2807
|
const testJobs = Math.max(1, Number(options.testJobs ?? jobs) || jobs);
|
|
@@ -2736,6 +2820,7 @@ export async function runScans(plan, options = {}) {
|
|
|
2736
2820
|
async function runOneBody(s, extraEnv = null) {
|
|
2737
2821
|
if (signal?.aborted) return { id: s.id, class: s.class, command: s.command, tool: s.tool ?? null, toolVersion: null, status: "not-run", code: "CANCELLED", detail: "cancelled before it started" };
|
|
2738
2822
|
const started = Date.now();
|
|
2823
|
+
const scanStarted = performance.now();
|
|
2739
2824
|
let row = await scanRow(s, extraEnv);
|
|
2740
2825
|
// rightkit#1459: a class A scan that timed out is run once more before it fails Class A (a hung tool, e.g. actionlint on 2026-11-02, ran
|
|
2741
2826
|
// 27 min and failed a run whose rerun passed in 1 s). Class B and carried scans are not retried: a compile that times out is a real failure.
|
|
@@ -2743,8 +2828,9 @@ export async function runScans(plan, options = {}) {
|
|
|
2743
2828
|
if (row.status === "fail" && row.code === "TIMEOUT" && s.class === SCAN_CLASS.A && s.kind !== "test" && !signal?.aborted) {
|
|
2744
2829
|
const first = row;
|
|
2745
2830
|
row = await scanRow(s, extraEnv);
|
|
2746
|
-
row = { ...row, retried: { code: first.code, detail: first.detail } };
|
|
2831
|
+
row = { ...row, retried: { code: first.code, detail: first.detail, timing: first.timing ?? null } };
|
|
2747
2832
|
}
|
|
2833
|
+
row = { ...row, scanElapsedMs: performance.now() - scanStarted };
|
|
2748
2834
|
done += 1;
|
|
2749
2835
|
try { onResult(row, { done, total, seconds: Math.round((Date.now() - started) / 1000) }); } catch { /* reporting never fails a scan */ }
|
|
2750
2836
|
return row;
|
|
@@ -2811,9 +2897,10 @@ export async function runScans(plan, options = {}) {
|
|
|
2811
2897
|
// are one group; a group of two or more runs as ONE cargo invocation naming every member (`-p a -p b ...`) and the invocation's verdict becomes each
|
|
2812
2898
|
// member's row, under the member's own id and command (so required scan ids and the scan-set digest are what the plan said). The invocation is a scan
|
|
2813
2899
|
// of its own for everything else: it takes its own cache entry (the gate keys it on every member's inputs, `check:batch:` / `clippy:batch:`), cargo
|
|
2814
|
-
// ledger token, signed broker receipt and run limit. A cargo failure (code EXIT: a compile diagnostic) is bisected
|
|
2900
|
+
// ledger token, signed broker receipt and run limit. A cargo failure (code EXIT: a compile diagnostic) is bisected for attribution: each
|
|
2815
2901
|
// half runs again as a smaller invocation, down to one crate, which runs as its own per-crate scan, so a failure always names the crate that fails and
|
|
2816
|
-
// the crates that pass still pass
|
|
2902
|
+
// the crates that pass still pass; the grouped failure itself is retained on every member row (`batchFailure`) and in the run notes, so a combined
|
|
2903
|
+
// failure stays visible even when the splits pass. Any other failure (a refused or unverified receipt, a timeout, a missing tool) is the group's and is not retried:
|
|
2817
2904
|
// running it N times would repeat it N times. Equivalence caveat (GC-I11): one invocation unifies features across its crates, so a pass here is not
|
|
2818
2905
|
// proof that every member passes alone; the plan notes say the equivalence run has not been done.
|
|
2819
2906
|
const groupOf = new Map();
|
|
@@ -2828,23 +2915,34 @@ export async function runScans(plan, options = {}) {
|
|
|
2828
2915
|
const args = [...lead.args.slice(0, lead.batchable.at), ...idx.flatMap((i) => ["-p", bScans[i].batchable.crate]), ...lead.args.slice(lead.batchable.at + 2)];
|
|
2829
2916
|
const units = idx.map((i) => bScans[i].batchable.unit);
|
|
2830
2917
|
const id = `${/^clippy/.test(lead.id) ? "clippy" : "check"}:batch:${sha256(`${lead.batchable.key}\0${units.join("\0")}`).slice(0, 8)}`;
|
|
2831
|
-
return { ...plain, id, args, command: commandText({ ...plain, args }), batch: { units, members: idx.map((i) => bScans[i].id) } };
|
|
2918
|
+
return { ...plain, id, args, command: commandText({ ...plain, env: {}, args }), batch: { units, members: idx.map((i) => bScans[i].id) } };
|
|
2832
2919
|
};
|
|
2833
|
-
const runGroup = async (idx, extraEnv) => {
|
|
2920
|
+
const runGroup = async (idx, extraEnv, budget = { remaining: Math.min(2 * idx.length - 1, 31) }) => {
|
|
2921
|
+
if (budget.remaining <= 0 || signal?.aborted) {
|
|
2922
|
+
for (const i of idx) slots[i] = { ...failedRow(i, "batch attribution was not run"), code: signal?.aborted ? "CANCELLED" : "BATCH_BUDGET", detail: signal?.aborted ? "batch attribution was cancelled" : "batch attribution budget exhausted" };
|
|
2923
|
+
return;
|
|
2924
|
+
}
|
|
2925
|
+
budget.remaining -= 1;
|
|
2834
2926
|
if (idx.length === 1) { const i = idx[0]; slots[i] = await runOne(bScans[i], extraEnv).catch((error) => failedRow(i, error)); return; }
|
|
2835
2927
|
const started = Date.now();
|
|
2836
2928
|
const bs = batchScanOf(idx);
|
|
2837
2929
|
let row;
|
|
2838
2930
|
try { row = await scanRow(bs, extraEnv); } catch (error) { row = { id: bs.id, status: "fail", code: "SCAN_ERROR", detail: String(error?.message ?? error) }; }
|
|
2839
|
-
|
|
2931
|
+
const attributable = (row.code === "EXIT" && !row.snapshotEvidence) || (row.code === "BROKER_COMPILE_FAILURE" && row.authenticatedFailure?.retryable === true && row.authenticatedFailure?.failureClass === "compile" && row.snapshotEvidence?.receiptSha256);
|
|
2932
|
+
if (row.status === "fail" && attributable && !signal?.aborted) {
|
|
2933
|
+
// Bisect for attribution, but keep the grouped failure itself as evidence (rightkit#1458, reconciled scope
|
|
2934
|
+
// 2026-11-04): the splits below prove each member's own required scan; they do not erase that the combined
|
|
2935
|
+
// invocation failed (feature unification across the group is one way that happens, GC-I11).
|
|
2936
|
+
batchFailureNotes.push(`class B batching: grouped invocation ${bs.id} (${idx.length} crates: ${bs.batch.units.join(", ")}) failed (EXIT) and was bisected to attribute it; member rows carry it as batchFailure`);
|
|
2840
2937
|
const half = Math.ceil(idx.length / 2);
|
|
2841
|
-
await runGroup(idx.slice(0, half), extraEnv);
|
|
2842
|
-
await runGroup(idx.slice(half), extraEnv);
|
|
2938
|
+
await runGroup(idx.slice(0, half), extraEnv, budget);
|
|
2939
|
+
await runGroup(idx.slice(half), extraEnv, budget);
|
|
2940
|
+
for (const i of idx) if (slots[i]) slots[i] = { ...slots[i], individualStatus: slots[i].individualStatus ?? slots[i].status, individualCode: slots[i].individualCode ?? slots[i].code ?? null, status: "fail", code: "BATCH_REQUIREMENT_FAILED", batchFailure: { id: bs.id, units: bs.batch.units, command: row.command, ...(row.authenticatedFailure ? { authenticatedFailure: row.authenticatedFailure } : {}), ...(row.snapshotEvidence ? { snapshotEvidence: row.snapshotEvidence } : {}), ...(row.detail ? { detail: row.detail } : {}) }, batchAttempts: [...(slots[i].batchAttempts ?? []), { id: bs.id, status: row.status, command: row.command, ...(row.authenticatedFailure ? { authenticatedFailure: row.authenticatedFailure } : {}), ...(row.snapshotEvidence ? { snapshotEvidence: row.snapshotEvidence } : {}), timing: row.timing ?? null }] };
|
|
2843
2941
|
return;
|
|
2844
2942
|
}
|
|
2845
2943
|
for (const i of idx) {
|
|
2846
2944
|
const m = bScans[i];
|
|
2847
|
-
const own = { id: m.id, class: m.class, command: m.command, tool: m.tool ?? null, toolVersion: row.toolVersion ?? null, status: row.status, ...(row.code ? { code: row.code } : {}), ...(row.detail ? { detail: row.status === "fail" ? `${row.id} (${idx.length} crates: ${bs.batch.units.join(", ")}): ${row.detail}` : row.detail } : {}), ...(row.cached ? { cached: true } : {}), batchedWith: { id: row.id, units: bs.batch.units }, ...(row.snapshotEvidence ? { snapshotEvidence: row.snapshotEvidence } : {}), ...(row.identities ? { identities: row.identities } : {}), ...(row.log ? { log: row.log } : {}) };
|
|
2945
|
+
const own = { id: m.id, class: m.class, command: m.command, batchCommand: row.command, tool: m.tool ?? null, toolVersion: row.toolVersion ?? null, status: row.status, ...(row.code ? { code: row.code } : {}), ...(row.detail ? { detail: row.status === "fail" ? `${row.id} (${idx.length} crates: ${bs.batch.units.join(", ")}): ${row.detail}` : row.detail } : {}), ...(row.cached ? { cached: true } : {}), timing: row.timing ?? null, batchedWith: { id: row.id, units: bs.batch.units }, ...(row.authenticatedFailure ? { authenticatedFailure: row.authenticatedFailure } : {}), ...(row.snapshotEvidence ? { snapshotEvidence: row.snapshotEvidence } : {}), ...(row.identities ? { identities: row.identities } : {}), ...(row.log ? { log: row.log } : {}) };
|
|
2848
2946
|
slots[i] = own; done += 1;
|
|
2849
2947
|
try { onResult(own, { done, total, seconds: Math.round((Date.now() - started) / 1000) }); } catch { /* reporting never fails a scan */ }
|
|
2850
2948
|
}
|
|
@@ -2860,7 +2958,7 @@ export async function runScans(plan, options = {}) {
|
|
|
2860
2958
|
};
|
|
2861
2959
|
const drain = async (queue, extraEnv = null) => {
|
|
2862
2960
|
const busy = new Set(); const running = new Set();
|
|
2863
|
-
const keyOf = (i) => bScans[i].cwd ?? ".";
|
|
2961
|
+
const keyOf = (i) => bScans[i].executionWorkspace ?? bScans[i].cwd ?? ".";
|
|
2864
2962
|
while (queue.length || running.size) {
|
|
2865
2963
|
const at = running.size < bJobs ? queue.findIndex((i) => !busy.has(keyOf(i))) : -1;
|
|
2866
2964
|
if (at === -1) { await Promise.race(running); continue; }
|
|
@@ -2872,7 +2970,44 @@ export async function runScans(plan, options = {}) {
|
|
|
2872
2970
|
running.add(job);
|
|
2873
2971
|
}
|
|
2874
2972
|
};
|
|
2875
|
-
if (
|
|
2973
|
+
if (typeof options.scheduleClassB === "function") {
|
|
2974
|
+
// A caller-supplied dependency scheduler uses this initialized executor: every job still passes Class A,
|
|
2975
|
+
// tool, carrier, ledger, receipt, timeout and quiet-lease checks in the same scan path.
|
|
2976
|
+
const issued = new WeakSet();
|
|
2977
|
+
const remember = (row) => { issued.add(row); return row; };
|
|
2978
|
+
const executeRaw = async (scan) => {
|
|
2979
|
+
if (!scan.quiet) return runOne(scan);
|
|
2980
|
+
if (classAFailed || classBBlocked || signal?.aborted) return runOne(scan);
|
|
2981
|
+
let lease = null;
|
|
2982
|
+
if (quietLane) { try { lease = (await quietLane.acquire({ ttlMs: QUIET_LEASE_MAX_MS })) ?? null; } catch { lease = null; } }
|
|
2983
|
+
if (!lease && options.requireQuietLease) return { id: scan.id, class: scan.class, command: scan.command, status: "fail", code: "QUIET_LEASE_UNAVAILABLE", detail: "the broker quiet lease could not be held" };
|
|
2984
|
+
try { return await runOne({ ...scan, timeoutMs: Math.min(scanTimeoutMs(scan, options), QUIET_SCAN_MAX_MS) }, lease?.env ?? null); }
|
|
2985
|
+
finally { if (lease && typeof quietLane.release === "function") { try { await quietLane.release(lease.id); } catch { /* lease expires */ } } }
|
|
2986
|
+
};
|
|
2987
|
+
const execute = async (scan) => remember(Object.freeze(await executeRaw(scan)));
|
|
2988
|
+
const canGroup = (a, b) => { const i = bScans.indexOf(a); const j = bScans.indexOf(b); return i >= 0 && j >= 0 && Boolean(groupOf.get(i)) && groupOf.get(i) === groupOf.get(j); };
|
|
2989
|
+
// The caller supplies only members ready on its current frontier. Reuse the existing
|
|
2990
|
+
// signed batch/bisection path without admitting other members of their planned group.
|
|
2991
|
+
const executeGroup = async (scans) => {
|
|
2992
|
+
if (!Array.isArray(scans) || scans.length < 2) throw new Error("scheduleClassB: a batch needs at least two scans");
|
|
2993
|
+
const indices = scans.map((scan) => bScans.indexOf(scan));
|
|
2994
|
+
const group = groupOf.get(indices[0]);
|
|
2995
|
+
if (!group || new Set(indices).size !== indices.length || indices.some((i) => i < 0 || groupOf.get(i) !== group)) throw new Error("scheduleClassB: incompatible batch members");
|
|
2996
|
+
await runGroup(indices, null);
|
|
2997
|
+
return indices.map((i) => remember(Object.freeze(slots[i] ?? failedRow(i, "batch produced no row"))));
|
|
2998
|
+
};
|
|
2999
|
+
const project = (row, scan) => {
|
|
3000
|
+
if (!issued.has(row) || !bScans.includes(scan)) throw new Error("scheduleClassB: invalid projection");
|
|
3001
|
+
return remember(Object.freeze({ ...row, id: scan.id, command: scan.command }));
|
|
3002
|
+
};
|
|
3003
|
+
const notRun = (scan, detail) => {
|
|
3004
|
+
if (!bScans.includes(scan)) throw new Error("scheduleClassB: unknown scan");
|
|
3005
|
+
return remember(Object.freeze({ id: scan.id, class: scan.class, command: scan.command, status: "not-run", detail: String(detail) }));
|
|
3006
|
+
};
|
|
3007
|
+
const rows = await options.scheduleClassB({ scans: bScans, execute, executeGroup, canGroup, project, notRun });
|
|
3008
|
+
if (!Array.isArray(rows) || rows.length !== bScans.length || rows.some((row, i) => !row || !issued.has(row) || row.id !== bScans[i].id || typeof row.status !== "string")) throw new Error("scheduleClassB must return executor-issued results in plan order");
|
|
3009
|
+
rows.forEach((row, i) => { slots[i] = row; });
|
|
3010
|
+
} else if (brokerHost) {
|
|
2876
3011
|
await scheduleBrokerHostClassB({
|
|
2877
3012
|
scans: bScans, lanes, localJobs: bJobs, carried: (scan) => isBrokerScheduledScan(scan, carriedCtx), pipeline: options.classBPipeline ?? 1,
|
|
2878
3013
|
run: async (i) => { try { slots[i] = await runB(i); } catch (error) { slots[i] = failedRow(i, error); } },
|
|
@@ -2882,7 +3017,7 @@ export async function runScans(plan, options = {}) {
|
|
|
2882
3017
|
await drain(lanes.doc);
|
|
2883
3018
|
await drain(lanes.tests);
|
|
2884
3019
|
}
|
|
2885
|
-
if (lanes.quiet.length) {
|
|
3020
|
+
if (typeof options.scheduleClassB !== "function" && lanes.quiet.length) {
|
|
2886
3021
|
// One lease per quiet suite, as in class A above.
|
|
2887
3022
|
for (const i of lanes.quiet) {
|
|
2888
3023
|
if (classAFailed || classBBlocked || signal?.aborted) {
|
|
@@ -2928,11 +3063,16 @@ export async function runScans(plan, options = {}) {
|
|
|
2928
3063
|
|
|
2929
3064
|
// `extraEnv` (the quiet lease id) reaches the child but never the cache key: a lease changes nothing a scan proves.
|
|
2930
3065
|
async function scanRow(s, extraEnv = null) {
|
|
2931
|
-
//
|
|
3066
|
+
// One invocation owns one timing, including cache lookup, probes, execution and verification.
|
|
3067
|
+
const started = performance.now();
|
|
3068
|
+
const timing = { invocationId: crypto.randomUUID(), elapsedMs: null, cacheLookupMs: null, executionMs: null };
|
|
2932
3069
|
const owned = { cargoReadTarget: null };
|
|
2933
|
-
try {
|
|
3070
|
+
try {
|
|
3071
|
+
const row = await scanRowIn(s, extraEnv, owned, timing);
|
|
3072
|
+
return { ...row, timing: { ...timing, elapsedMs: performance.now() - started } };
|
|
3073
|
+
} finally { if (owned.cargoReadTarget) fs.rmSync(owned.cargoReadTarget, { recursive: true, force: true }); }
|
|
2934
3074
|
}
|
|
2935
|
-
async function scanRowIn(s, extraEnv, owned) {
|
|
3075
|
+
async function scanRowIn(s, extraEnv, owned, timing) {
|
|
2936
3076
|
const row = { id: s.id, class: s.class, command: s.command, tool: s.tool ?? null, toolVersion: null, status: "fail" };
|
|
2937
3077
|
const scanStartedAt = Date.now();
|
|
2938
3078
|
if (s.class === SCAN_CLASS.B && classBBlocked) {
|
|
@@ -2948,18 +3088,33 @@ export async function runScans(plan, options = {}) {
|
|
|
2948
3088
|
return { ...row, status: "deferred", detail: s.deferred };
|
|
2949
3089
|
}
|
|
2950
3090
|
try {
|
|
3091
|
+
// 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,
|
|
3092
|
+
// with the rule code's identity (CHECKER_IDENTITY) as its tool version. Network and advice rules are never reused this way.
|
|
3093
|
+
let internalKey = null;
|
|
3094
|
+
if (s.internal && cache && CACHEABLE_INTERNAL.has(s.internal) && typeof CHECKER_IDENTITY === "string") {
|
|
3095
|
+
try {
|
|
3096
|
+
const digest = cache.digest(s, {});
|
|
3097
|
+
if (digest) internalKey = scanCacheKey({ id: s.id, command: s.command ?? `internal:${s.internal}`, toolVersion: CHECKER_IDENTITY, env: {}, inheritedEnv: inheritedEnvDigest({}), digest });
|
|
3098
|
+
} catch (error) { internalKey = null; row.cacheKeyError = String(error?.message ?? error).slice(0, 300); }
|
|
3099
|
+
const hit = internalKey ? cache.read(internalKey) : null;
|
|
3100
|
+
if (hit && hit.key === internalKey && hit.row?.status === "pass" && hit.row.id === s.id) {
|
|
3101
|
+
cacheHits.push(s.id);
|
|
3102
|
+
return { ...row, status: "pass", cached: true, detail: `cached ${String(hit.at ?? "").slice(0, 10) || "earlier"}` };
|
|
3103
|
+
}
|
|
3104
|
+
}
|
|
2951
3105
|
if (s.internal) {
|
|
2952
3106
|
const out = await INTERNAL[s.internal](s, ctx);
|
|
2953
3107
|
if (out && out.missing) { status = "fail"; code = "TOOL_MISSING"; detail = out.missing; }
|
|
2954
3108
|
else if (out && !Array.isArray(out) && out.code) { status = "fail"; code = out.code; detail = out.detail; }
|
|
2955
3109
|
else if (out && !Array.isArray(out) && typeof out.advice === "string") { advice = out.advice; }
|
|
2956
3110
|
else if (out.length) { status = "fail"; detail = out.join("; "); }
|
|
3111
|
+
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" });
|
|
2957
3112
|
} else {
|
|
2958
3113
|
const scanDir = path.join(rootDir(s.root), s.cwd ?? "");
|
|
2959
3114
|
// The RustRight client's version probe starts in a Cargo workspace of the primary checkout; a class A cargo scan's own directory is
|
|
2960
3115
|
// in the snapshot, so its probe uses the checkout's counterpart (reading no file of it), or the checkout when it has none.
|
|
2961
3116
|
let probeAt = scanDir;
|
|
2962
|
-
if (cargoLiveRoot && s.root !== "cargoLive" && (s.tool === "rustright" || s.tool === "cargo")) {
|
|
3117
|
+
if (s.class !== SCAN_CLASS.A && cargoLiveRoot && s.root !== "cargoLive" && (s.tool === "rustright" || s.tool === "cargo")) {
|
|
2963
3118
|
const counterpart = path.join(cargoLiveRoot, s.cwd ?? "");
|
|
2964
3119
|
let isDir = false; try { isDir = fs.statSync(counterpart).isDirectory(); } catch { isDir = false; }
|
|
2965
3120
|
probeAt = isDir ? counterpart : cargoLiveRoot;
|
|
@@ -2996,14 +3151,24 @@ export async function runScans(plan, options = {}) {
|
|
|
2996
3151
|
const carriedScan = isBrokerCarriedScan(s, carriedCtx);
|
|
2997
3152
|
const viaSnapshotBroker = carriedScan && Boolean(deps.snapshotBroker) && s.root === "cargoLive" && (s.tool === "rustright" || s.tool === "cargo");
|
|
2998
3153
|
const carriedRead = cargoReadsAreCarried && s.class === SCAN_CLASS.A && (s.tool === "rustright" || s.tool === "cargo");
|
|
2999
|
-
if (cache && !carriedRead) {
|
|
3154
|
+
if (cache && !carriedRead && !s.coverageKey) {
|
|
3155
|
+
const cacheStarted = performance.now();
|
|
3000
3156
|
try {
|
|
3001
|
-
|
|
3157
|
+
// A plain node --check row has no guard, carrier, advisory or
|
|
3158
|
+
// trusted-tool environment additions. Include its actual ledger
|
|
3159
|
+
// token and sentinel (when present) in the narrow key.
|
|
3160
|
+
const nodeSentinel = options.cargoSentinel && !Object.hasOwn(s.env ?? {}, "CARGO_TARGET_DIR") ? path.join(options.cargoSentinel, sha256(s.id).slice(0, 16)) : null;
|
|
3161
|
+
const nodeEnv = { ...deps.env, ...(nodeSentinel ? { CARGO_TARGET_DIR: nodeSentinel, CARGO_BUILD_TARGET_DIR: nodeSentinel } : {}), ...s.env, ...(extraEnv ?? {}), ...(cargoLedger ? { [SCAN_TOKEN_ENV]: scanTokenOf(s.id) } : {}) };
|
|
3162
|
+
const digest = cache.digest(s, { childEnv: nodeEnv, cwd: scanDir, command: p.command, shimProof: options.nodeCheckShimContext ?? null });
|
|
3002
3163
|
// The analyzers a scan runs through (actionlint's shellcheck) judge it too, so their versions key it as well.
|
|
3003
3164
|
const toolVersion = [p.identity ? `${p.version}@${p.identity.sha256}` : p.version, ...depVersions].join(" + ");
|
|
3004
|
-
|
|
3005
|
-
|
|
3165
|
+
// The narrow node-check digest already binds the complete actual
|
|
3166
|
+
// child environment (with its one explicit ownership exception).
|
|
3167
|
+
const inherited = cache.narrowNodeCheck && /^node-check:/.test(s.id) ? sha256('node-check-child-env-in-digest/1') : inheritedEnvDigest({ ...deps.env, ...s.env });
|
|
3168
|
+
if (digest) cacheKey = scanCacheKey({ id: s.id, command: s.runOutside ? `${s.command} ;; run ${canonicalJson(s.runOutside)}` : s.command, toolVersion, env: s.env ?? {}, inheritedEnv: inherited, digest });
|
|
3169
|
+
} catch (error) { cacheKey = null; row.cacheKeyError = String(error?.message ?? error).slice(0, 300); }
|
|
3006
3170
|
const hit = cacheKey ? cache.read(cacheKey) : null;
|
|
3171
|
+
timing.cacheLookupMs = performance.now() - cacheStarted;
|
|
3007
3172
|
// A cached test pass counts only with the counts it recorded: without them its coverage is unknown, so it runs again.
|
|
3008
3173
|
// ...and only if it passed at least one test: a cached all-skipped "pass" (written before D17) runs again (rightkit#1236).
|
|
3009
3174
|
// 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.
|
|
@@ -3257,8 +3422,19 @@ export async function runScans(plan, options = {}) {
|
|
|
3257
3422
|
try {
|
|
3258
3423
|
const ref = readRequestRef(path.join(carrier.refDir, "request.json"));
|
|
3259
3424
|
const receipt = await deps.snapshotBroker.receiptOf(ref.requestId);
|
|
3260
|
-
const
|
|
3261
|
-
|
|
3425
|
+
const receiptOptions = { pins: deps.snapshotBroker.pins, jobId: ref.requestId, carrier: carrier.made.carrier, argv: carrier.cargoArgv, workspace: ref.workspace, observedEnv: observedEnvOf({ ...deps.env, ...s.env, ...(extraEnv ?? {}) }, deps.platform ?? process.platform), checkout: deps.snapshotBroker.checkout, outputRoots: deps.snapshotBroker.outputRoots, platform: deps.snapshotBroker.platform ?? deps.platform ?? process.platform };
|
|
3426
|
+
let verified;
|
|
3427
|
+
try { verified = verifySnapshotReceipt(receipt, receiptOptions); }
|
|
3428
|
+
catch (original) {
|
|
3429
|
+
if (original?.code !== "result" || status !== "fail" || code !== "EXIT" || signal?.aborted || !Number.isSafeInteger(r?.status) || r.status <= 0) throw original;
|
|
3430
|
+
verified = verifySnapshotReceipt(receipt, { ...receiptOptions, allowFailedCompile: true });
|
|
3431
|
+
if (verified.signedResult?.status !== "FAILED" || verified.signedResult.failureClass !== "compile" || verified.signedResult.exitCode !== r.status || verified.signedResult.signal !== null) throw original;
|
|
3432
|
+
code = "BROKER_COMPILE_FAILURE";
|
|
3433
|
+
// Bisection needs the fully verified, signed post-run verdict as well as the matching client exit.
|
|
3434
|
+
row.authenticatedFailure = { status: verified.signedResult.status, failureClass: verified.signedResult.failureClass, exitCode: verified.signedResult.exitCode, postChecks: verified.signedResult.postChecks, retryable: verified.signedResult.postChecks?.verified === true };
|
|
3435
|
+
}
|
|
3436
|
+
const { evidence } = verified;
|
|
3437
|
+
row.snapshotEvidence = { receiptSha256: sha256(canonicalJson(receipt)), requestId: ref.requestId, outputDir: evidence.outputDir, cargoDir: s.cwd ?? ".", targetTriple: typeof receipt?.targetTriple === "string" && /^[A-Za-z0-9_.]+(?:-[A-Za-z0-9_.]+){1,4}$/.test(receipt.targetTriple) ? receipt.targetTriple : null, treeAtStart: evidence.snapshot.treeAtStart, treeAtExit: evidence.snapshot.treeAtExit, ...(receipt && Object.hasOwn(receipt, "testExecutables") ? { testExecutables: receipt.testExecutables, testExecutablesReason: receipt.testExecutablesReason ?? null } : {}) };
|
|
3262
3438
|
} catch (e) {
|
|
3263
3439
|
status = "fail"; code = "SNAPSHOT_EVIDENCE"; detail = `${s.id}: the broker's snapshot evidence did not verify (${e.code ?? "error"}: ${e.message})`;
|
|
3264
3440
|
}
|
|
@@ -3296,16 +3472,31 @@ export async function runScans(plan, options = {}) {
|
|
|
3296
3472
|
// ADR-001 C2 (rightkit#1454): a broker that signs the compile's test executables (receipt.testExecutables, rustright) binds each one;
|
|
3297
3473
|
// an executable whose path or sha256 is not in that signed list never runs. An older broker that signs no list leaves containment only.
|
|
3298
3474
|
const signedProblems = viaSnapshotBroker && row.snapshotEvidence && Object.hasOwn(row.snapshotEvidence, "testExecutables") ? signedTestExecutableProblems(contained.accepted, row.snapshotEvidence.testExecutables, row.snapshotEvidence.testExecutablesReason, platform) : [];
|
|
3299
|
-
if (
|
|
3475
|
+
if (s.publisherRustTest && viaSnapshotBroker && !Object.hasOwn(row.snapshotEvidence ?? {}, "testExecutables")) fail("TEST_EXECUTABLE_UNSIGNED", `${s.id}: the broker did not sign a test executable list`);
|
|
3476
|
+
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`);
|
|
3300
3477
|
else if (signedProblems.length) fail("TEST_EXECUTABLE_UNSIGNED", `${s.id}: ${signedProblems.slice(0, 5).join("; ")}; the row fails and nothing was run`);
|
|
3301
3478
|
else {
|
|
3302
3479
|
const budget = s.quiet === true ? Math.max(1, Math.min(limitMs, QUIET_SCAN_MAX_MS - (Date.now() - scanStartedAt))) : limitMs;
|
|
3303
|
-
const ran = await runTestBinaries({ scan: s, binaries: contained.accepted, spawn: deps.spawn, env: { ...deps.env, ...s.env, ...(extraEnv ?? {}) }, limitMs: budget, signal, ops });
|
|
3304
|
-
row.results = ran.results; row.testRun = { executables: ran.executables };
|
|
3480
|
+
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 } : {}) });
|
|
3481
|
+
row.results = ran.results; row.testRun = { executables: ran.executables, outputTruncated: ran.executables.some((e) => e.outputTruncated), skipMarkers: ran.executables.reduce((n, e) => n + (e.skipMarkers ?? 0), 0) };
|
|
3482
|
+
if (s.publisherRustTest && row.testRun.outputTruncated) fail("TEST_OUTPUT_TRUNCATED", `${s.id}: test output was truncated; skip evidence is incomplete`);
|
|
3305
3483
|
if (ran.status !== "pass") { status = ran.status; code = ran.code; detail = ran.detail; }
|
|
3306
3484
|
}
|
|
3307
3485
|
}
|
|
3308
3486
|
}
|
|
3487
|
+
if (s.coverageKey && s.publisherPhase === "test" && !s.runOutside) {
|
|
3488
|
+
const output = `${r?.stdout ?? ""}\n${r?.stderr ?? ""}`.replace(/\u001b\[[0-9;?]*[ -/]*[@-~]/g, "");
|
|
3489
|
+
row.testRun = { outputTruncated: r?.truncated === true, skipMarkers: output.split(/\r\n|\n|\r/).filter((line) => /(?:^|[\s\]:])SKIP(?=[\s:]|$)/.test(line)).length };
|
|
3490
|
+
if (status === "pass" && row.testRun.outputTruncated) { status = "fail"; code = "TEST_OUTPUT_TRUNCATED"; detail = `${s.id}: test output was truncated; skip evidence is incomplete`; }
|
|
3491
|
+
}
|
|
3492
|
+
if (s.publisherRustTest && status === "pass") {
|
|
3493
|
+
if (!s.runOutside) {
|
|
3494
|
+
const counts = parseLibtestSummary(`${r?.stdout ?? ""}\n${r?.stderr ?? ""}`);
|
|
3495
|
+
if (counts && counts.results > 0) row.results = { runner: "libtest", tests: counts.passed + counts.failed + counts.ignored, pass: counts.passed, fail: counts.failed, skipped: counts.ignored, todo: 0 };
|
|
3496
|
+
else { status = "fail"; code = "NO_TEST_SUMMARY"; detail = "the Rust test command printed no recognisable libtest summary"; }
|
|
3497
|
+
}
|
|
3498
|
+
if (status === "pass" && !s.allowIgnored && (row.results?.skipped ?? 0) > 0) { status = "fail"; code = "IGNORED_TESTS"; detail = `${row.results.skipped} ignored Rust test(s) require an approved reason`; }
|
|
3499
|
+
}
|
|
3309
3500
|
if (status === "fail" && options.scanLogDir && r) {
|
|
3310
3501
|
try { fs.mkdirSync(options.scanLogDir, { recursive: true }); const file = path.join(options.scanLogDir, `${s.id.replace(/[^A-Za-z0-9._-]+/g, "_")}.log`); fs.writeFileSync(file, `$ ${s.command ?? s.id}\nexit ${r.status}\n--- stdout\n${r.stdout ?? ""}\n--- stderr\n${r.stderr ?? ""}\n`); row.log = file; detail = `${detail} (full output: ${file})`; } catch { /* the tail in the row remains */ }
|
|
3311
3502
|
}
|
|
@@ -3347,7 +3538,7 @@ export async function runScans(plan, options = {}) {
|
|
|
3347
3538
|
schema: SCAN_RESULT_SCHEMA, ok: !cancelled && results.every((r) => r.status === "pass"), complete: !cancelled && results.every((r) => r.status === "pass"), classes, checker, ...(cancelled ? { cancelled: true } : {}),
|
|
3348
3539
|
inputDigest: plan.inputDigest ?? null,
|
|
3349
3540
|
deferred: results.filter((r) => r.status === "deferred").map((r) => r.id),
|
|
3350
|
-
scans: results, toolVersions, toolIdentities, cacheHits: [...cacheHits].sort(), notes: [...(plan.notes ?? []), ...(cargoLedger ? [UNOBSERVED_NESTED_CARGO_NOTE] : [])],
|
|
3541
|
+
scans: results, toolVersions, toolIdentities, cacheHits: [...cacheHits].sort(), notes: [...(plan.notes ?? []), ...batchFailureNotes, ...(cargoLedger ? [UNOBSERVED_NESTED_CARGO_NOTE] : [])],
|
|
3351
3542
|
scanSetDigest: digestScanSet(results),
|
|
3352
3543
|
classDigests: { A: digestScanSet(results.filter((r) => r.class === "A")), B: digestScanSet(results.filter((r) => r.class === "B")) },
|
|
3353
3544
|
};
|
package/gate-coverage.mjs
CHANGED
|
@@ -6,24 +6,35 @@ import path from "node:path";
|
|
|
6
6
|
|
|
7
7
|
export const COVERAGE_SCHEMA = "rightkit.gate-coverage/1";
|
|
8
8
|
|
|
9
|
+
const duration = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : null;
|
|
10
|
+
function timingOf(value) {
|
|
11
|
+
if (!value || typeof value !== "object" || typeof value.invocationId !== "string" || !value.invocationId) return null;
|
|
12
|
+
return { invocationId: value.invocationId, elapsedMs: duration(value.elapsedMs), cacheLookupMs: duration(value.cacheLookupMs), executionMs: duration(value.executionMs) };
|
|
13
|
+
}
|
|
14
|
+
function telemetryOf(row) {
|
|
15
|
+
const attempts = Array.isArray(row?.batchAttempts) ? row.batchAttempts.filter((entry) => entry && typeof entry.id === "string" && typeof entry.status === "string").map((entry) => ({ id: entry.id, status: entry.status, timing: timingOf(entry.timing) })) : [];
|
|
16
|
+
return { timing: timingOf(row?.timing), scanElapsedMs: duration(row?.scanElapsedMs), retryTiming: timingOf(row?.retried?.timing), batchAttempts: attempts };
|
|
17
|
+
}
|
|
18
|
+
|
|
9
19
|
/**
|
|
10
20
|
* The report for `plan` (the planned scans, `plan.scans`) and `scanResult` (runScans' rows). `keys` is a Map of scan id -> the input key the cache
|
|
11
21
|
* looked the scan up under (null or absent: the scan is never cached or no key could be formed). `classes` are the classes this pass runs.
|
|
12
22
|
*/
|
|
13
|
-
export function buildCoverageReport({ plan, scanResult, keys = new Map(), classes = ["A", "B"], commit = null, startedAt = null, endedAt = null }) {
|
|
23
|
+
export function buildCoverageReport({ plan, scanResult, keys = new Map(), keyErrors = new Map(), cacheDisabled = null, classes = ["A", "B"], commit = null, startedAt = null, endedAt = null }) {
|
|
14
24
|
const rows = new Map((scanResult?.scans ?? []).map((row) => [row.id, row]));
|
|
15
25
|
const scans = (plan?.scans ?? []).map((scan) => {
|
|
16
26
|
const row = rows.get(scan.id);
|
|
17
27
|
const key = keys.get(scan.id) ?? null;
|
|
28
|
+
const telemetry = telemetryOf(row);
|
|
18
29
|
if (row) {
|
|
19
|
-
if (row.cached === true) return { id: scan.id, class: scan.class, coverage: "hit", status: row.status, key, reason: row.detail ?? "answered from the result cache" };
|
|
20
|
-
if (row.status === "pass" || row.status === "fail") return { id: scan.id, class: scan.class, coverage: "ran", status: row.status, key, reason: key === null ? "no cache key (this scan is never cached, or no key could be formed)" : "no cached result for this key", ...(row.code ? { code: row.code } : {}) };
|
|
21
|
-
return { id: scan.id, class: scan.class, coverage: "skipped", status: row.status, key, reason: row.detail ?? row.status };
|
|
30
|
+
if (row.cached === true) return { id: scan.id, class: scan.class, ...telemetry, coverage: "hit", status: row.status, key, reason: row.detail ?? "answered from the result cache" };
|
|
31
|
+
if (row.status === "pass" || row.status === "fail") return { id: scan.id, class: scan.class, ...telemetry, coverage: "ran", status: row.status, key, reason: key === null ? ((keyErrors.get(scan.id) ?? row.cacheKeyError) ? `no cache key: ${keyErrors.get(scan.id) ?? row.cacheKeyError}` : cacheDisabled ?? "no cache key (this scan is never cached, or no key could be formed)") : "no cached result for this key", ...(row.code ? { code: row.code } : {}) };
|
|
32
|
+
return { id: scan.id, class: scan.class, ...telemetry, coverage: "skipped", status: row.status, key, reason: row.detail ?? row.status };
|
|
22
33
|
}
|
|
23
|
-
return { id: scan.id, class: scan.class, coverage: "skipped", status: "not-in-pass", key, reason: classes.includes(scan.class) ? "planned but no result was returned" : `class ${scan.class} is not part of this pass (classes ${classes.join("+")})` };
|
|
34
|
+
return { id: scan.id, class: scan.class, ...telemetry, coverage: "skipped", status: "not-in-pass", key, reason: classes.includes(scan.class) ? "planned but no result was returned" : `class ${scan.class} is not part of this pass (classes ${classes.join("+")})` };
|
|
24
35
|
});
|
|
25
36
|
const count = (what) => scans.filter((s) => s.coverage === what).length;
|
|
26
|
-
return { schema: COVERAGE_SCHEMA, commit, startedAt, endedAt, totals: { planned: scans.length, hit: count("hit"), ran: count("ran"), skipped: count("skipped") }, scans };
|
|
37
|
+
return { schema: COVERAGE_SCHEMA, commit, startedAt, endedAt, ...(cacheDisabled ? { cacheDisabled } : {}), totals: { planned: scans.length, hit: count("hit"), ran: count("ran"), skipped: count("skipped") }, scans };
|
|
27
38
|
}
|
|
28
39
|
|
|
29
40
|
/** Writes the report as `<dir>/<name>.json` (the directory is created); returns the path. */
|