@rightkit/release 0.6.51 → 0.6.54
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/README.md +1 -1
- package/adapter-env.mjs +16 -105
- package/admission-host.mjs +14 -1
- package/bin/darwin/rightkit-swap +0 -0
- package/bin/rightkit-gate.mjs +609 -404
- package/broker-admission.mjs +122 -2
- package/build-launch.mjs +52 -58
- package/build-release.mjs +2 -2
- package/cargo-ledger.mjs +24 -5
- package/cargo-target-shim.mjs +54 -23
- package/cargo-target.mjs +2 -2
- package/carried-adapter-run.mjs +7 -8
- package/carried-cargo-run.mjs +1 -1
- package/ci-compile-admission.mjs +1 -1
- package/clippy-route.mjs +65 -18
- package/compile-inputs.mjs +91 -15
- package/cross-targets.mjs +5 -3
- package/deps-cargo-lock.mjs +1 -1
- package/deterministic-scans.mjs +789 -259
- package/development.mjs +33 -7
- package/direct-receipt.mjs +3 -5
- package/feature-coverage.mjs +45 -9
- package/feature-partition.mjs +204 -0
- package/feature-sets.mjs +113 -0
- package/gate-acceptance.mjs +187 -115
- package/gate-seam.mjs +352 -0
- package/gate-serve.mjs +34 -2
- package/gate-stages.mjs +6 -2
- package/ghsa-audit.mjs +19 -4
- package/heavy-command.mjs +5 -4
- package/install-tauri-authenticode.mjs +73 -4
- package/ios-dev.mjs +3 -3
- package/ios-package-recipe.mjs +6 -6
- package/linux-setup.mjs +3 -2
- package/local-publish.mjs +113 -17
- package/lock-identity.mjs +24 -100
- package/managed-cargo.mjs +3 -3
- package/managed-root-guard.mjs +2 -2
- package/managed-roots.mjs +3 -3
- package/native-adapters.mjs +41 -244
- package/native-helpers.mjs +1 -1
- package/pack-digest.mjs +1 -1
- package/package-recipe-targets.mjs +3 -3
- package/package.json +2 -2
- package/publication-gate.mjs +29 -6
- package/publish-cargo.mjs +4 -5
- package/publish-local-cargo.mjs +77 -1
- package/qualification-verify.mjs +76 -49
- package/receipt-signature.mjs +104 -0
- package/release-switch-registry.json +4 -0
- package/release-switch-scan.mjs +13 -10
- package/rightkit-versions.json +126 -113
- package/scan-digest.mjs +43 -14
- package/seam-broker.mjs +168 -0
- package/snapshot-check.mjs +4 -1
- package/snapshot-dependency-reuse.mjs +1 -1
- package/snapshot-metadata.mjs +24 -35
- package/snapshot.mjs +328 -49
- package/stage-commands.mjs +59 -5
- package/stage-ledger.mjs +2 -2
- package/{carried-cargo.mjs → stage-seam.mjs} +118 -70
- package/stage-sidecar.mjs +3 -3
- package/tauri-bundle-marker.mjs +5 -2
- package/tauri-locked.mjs +1 -1
- package/tool-build.mjs +8 -6
- package/unit-gate.mjs +40 -10
- package/web-build.mjs +6 -0
- package/broker-handshake.mjs +0 -160
- package/broker-wire.mjs +0 -278
- package/build-ownership.mjs +0 -1578
- package/cargo-shapes.mjs +0 -332
- package/cargo-width.mjs +0 -49
- package/carrier-census.mjs +0 -124
- package/clippy-equivalence.mjs +0 -202
- package/freshness-census.mjs +0 -405
- package/handle-revocation.mjs +0 -100
- package/handle-revocation.rust-vector.json +0 -1
- package/handle-revocation.vectors.json +0 -53
- package/legion-freeze-consumer.mjs +0 -241
- package/linux-qualifier.mjs +0 -83
- package/native-tool-planning.mjs +0 -94
- package/owner-process-proof.mjs +0 -14
- package/ownership-mark.mjs +0 -191
- package/ownership-recover.mjs +0 -78
- package/pnpm-adapter-grammar.mjs +0 -226
- package/provenance-verify.mjs +0 -413
- package/snapshot-broker.mjs +0 -808
- package/snapshot-request.mjs +0 -722
- package/unit-list-compile.mjs +0 -356
package/deterministic-scans.mjs
CHANGED
|
@@ -18,17 +18,17 @@
|
|
|
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";
|
|
22
21
|
import fs from "node:fs";
|
|
22
|
+
import { recordLockChild } from "./snapshot.mjs";
|
|
23
23
|
import os from "node:os";
|
|
24
24
|
import path from "node:path";
|
|
25
25
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
26
26
|
import { spawn as spawnChild, spawnSync } from "./background-process.mjs";
|
|
27
|
-
import { spawnUnderOwnership } from "./build-ownership.mjs";
|
|
28
27
|
import { checkAdvisoryExceptions } from "./advisory-exceptions.mjs";
|
|
29
28
|
import { crateRunsOn, crossCompileEnv, oneOutput, scopedCrossTargets } from "./cross-targets.mjs";
|
|
30
29
|
import { declaredFeatureNames, effectiveCrateFeatures, featureCoverageProblems } from "./feature-coverage.mjs";
|
|
31
|
-
import { CLIPPY_UNIVERSAL_FEATURE_FLAGS, canonicalJson, clippyBatchPlan, clippySelectionOf, digestScanSet, requiredScanIds, rustCratePlan, rustScanId } from "./scan-digest.mjs";
|
|
30
|
+
import { CLIPPY_UNIVERSAL_FEATURE_FLAGS, canonicalJson, clippyBatchPlan, clippySelectionOf, digestScanSet, requiredScanIds, rustCoverageSets, rustCratePlan, rustScanId } from "./scan-digest.mjs";
|
|
31
|
+
import { unlintedFeatures } from "./feature-sets.mjs";
|
|
32
32
|
import { reach } from "./lock-graph.mjs";
|
|
33
33
|
import { cargoManifestState } from "./cargo-manifest-text.mjs";
|
|
34
34
|
import { GRADLE_BUILD_FILE, gradleLockProblems, gradleOwnerOf } from "./gradle-lock.mjs";
|
|
@@ -38,14 +38,20 @@ import { LAUNCH_GUARD_IMPORT } from "./class-a-launch-guard.mjs";
|
|
|
38
38
|
import { advisoryCacheRoot, ensureAdvisoryDb, prepareDenyOverlay, readAdvisoryPin } from "./advisory-db.mjs";
|
|
39
39
|
import { ghsaFindings } from "./ghsa-audit.mjs";
|
|
40
40
|
import { OutdatedUnavailableError, resolveOutdatedBin } from "./outdated-command.mjs";
|
|
41
|
-
import {
|
|
42
|
-
import {
|
|
43
|
-
import {
|
|
44
|
-
import {
|
|
45
|
-
import {
|
|
46
|
-
import { removeCarrier } from "./carrier-census.mjs";
|
|
41
|
+
import { SCAN_TOKEN_ENV, readLedger, scanTokenOf, unclaimedLedgers } from "./cargo-ledger.mjs";
|
|
42
|
+
import { ADMISSION_POLL_MS, CARRIED_CANCEL_GRACE_MS, QUEUED_CEILING_FACTOR, createRunClock, createStatusPoller, watchBrokerAdmission } from "./broker-admission.mjs";
|
|
43
|
+
import { CANCEL_WAIT_ENV, operationDeadlineEnv } from "./broker-admission.mjs";
|
|
44
|
+
import { meetPartitions, partitionByFeatures, partitionCacheKey, splitNote, stripSelectors, treeArgs, workspaceManifestDigest } from "./feature-partition.mjs";
|
|
45
|
+
import { CLASS_A_ENV, NOT_EXECUTED_EXIT, judgeSeamOutcome, normalizeWorkspace, seamEnv, seamSettled, verdictForRun } from "./gate-seam.mjs";
|
|
47
46
|
|
|
48
47
|
export const SCAN_RESULT_SCHEMA = "rightkit.deterministic-scans/1";
|
|
48
|
+
// The seam's run state for the door's lock release (reset plan section 3): a seam row whose client the gate killed, that timed out or was cancelled may have
|
|
49
|
+
// left a broker job queued or finalizing after the row ended, so the door releases the snapshot lock only when `unsettled` is 0; otherwise the lock stays and
|
|
50
|
+
// the next run reclaims it on the broker's stale-owner proof. One gate process runs one batch, so module state is the run's state.
|
|
51
|
+
// The door's evidence for releasing its snapshot lock: `open` counts the seam runs (runScans with a seam, a stage's carrier) that began and have not yet counted their
|
|
52
|
+
// rows; `unsettled` the rows and stage calls counted without a settled outcome. The lock is released only when both are 0: a run that throws before it counts leaves
|
|
53
|
+
// `open` raised, so no count is ever taken as proof by its absence (fresh review of badf93c, D5).
|
|
54
|
+
export const seamRunState = { rows: 0, unsettled: 0, open: 0 };
|
|
49
55
|
/**
|
|
50
56
|
* The checker that produced a scan result: `<name>@<version>#<digest>` where the digest covers this module and scan-digest.mjs,
|
|
51
57
|
* so a changed checker at the same version is a different identity. null when it cannot be computed; prior class A evidence
|
|
@@ -165,7 +171,15 @@ const BUILD_ENV_PREFIXES = ["CARGO_", "RUST", "SCCACHE_", "RK_", "RIGHTKIT_", "R
|
|
|
165
171
|
// Per-run identities never key a result (they change on every run, so the cache could never hit; measured 2026-11-02: HR Class A wrote
|
|
166
172
|
// 3,809 entries and hit none across identical runs): the run's ownership handle, the attest nonce, the request-id file, the carried call's
|
|
167
173
|
// snapshot request and cargo map, the direct receipt path.
|
|
168
|
-
|
|
174
|
+
// The broker's control socket path (RUSTRIGHT_BUILD_BROKER_SOCKET) says where the client connects, never what a row proves; a launch wrapper that names it
|
|
175
|
+
// explicitly made 171 rows miss with no input change (rightkit#1552, Mac 2026-11-09, inheritedEnv [RUSTRIGHT_BUILD_BROKER_SOCKET] only).
|
|
176
|
+
// A network proxy (NPM_CONFIG_HTTPS_PROXY, NPM_CONFIG_NOPROXY, ...) changes how a download is routed, never what a scan proves, and a
|
|
177
|
+
// cloud host sets it per session (measured 2026-11-06: the cloud's NPM_CONFIG_HTTPS_PROXY moved between two runs and 1,115 rows missed).
|
|
178
|
+
const BUILD_ENV_EXCLUDED = /^(RK_GATE_|RUSTRIGHT_QUIET_LEASE$|RIGHTKIT_BUILD_OWNERSHIP$|RIGHTKIT_CARRIED_CARGO_MAP$|RUSTRIGHT_ATTEST_NONCE$|RUSTRIGHT_REQUEST_ID_FILE$|RUSTRIGHT_SNAPSHOT_REQUEST$|RK_DIRECT_RECEIPT$|RUSTRIGHT_BUILD_BROKER_SOCKET$|RIGHTKIT_CROSS_CC_DIR$|.*PROXY)/;
|
|
179
|
+
// PNPM_HOME (where pnpm keeps its own binaries; the calling app profile picks it) is not an input of any scan and is to leave this key once every row's stored index carries
|
|
180
|
+
// its environment shape (a row that only hits never refreshed its index; excluding it first made 74 rows that had no shape miss; Mac 2026-11-07).
|
|
181
|
+
// RIGHTKIT_CROSS_CC_DIR is where the zig wrappers live, not what they are: a cross clippy row keys on its own CC_/CXX_/AR_ variables
|
|
182
|
+
// (scan env), and no Class A row uses it (measured 2026-11-06: setting it on the cloud host made 1,121 Class A rows miss).
|
|
169
183
|
// Per-run parts of a value are normalised: the runtime cargo wrapper's fresh parent (`rk-gate-shim-XXXXXX`) and its folder name
|
|
170
184
|
// (`rk-cargo-shim-<identity>`), whose identity hashes the run's broker section and so differs on every run (measured 2026-11-03: two identical
|
|
171
185
|
// Class A runs of rightkit-asr shared no key, only CARGO differed). The wrapper's CODE keys the result through the gate identity instead
|
|
@@ -176,10 +190,40 @@ export const buildEnvName = (name) => {
|
|
|
176
190
|
if (BUILD_ENV_EXCLUDED.test(upper)) return false;
|
|
177
191
|
return BUILD_ENV_NAMES.has(upper) || BUILD_ENV_PREFIXES.some((prefix) => upper.startsWith(prefix));
|
|
178
192
|
};
|
|
193
|
+
// rightkit#1540 (reset plan section 3): a row's INHERITED environment is keyed on the variables its tool reads, nothing else. A cargo row does not read PNPM_HOME or
|
|
194
|
+
// NPM_CONFIG_CACHE, no row's verdict depends on where the broker's socket or the managed agent-bin lives (RK_/RIGHTKIT_/RUSTRIGHT_ are the gate's and the broker's
|
|
195
|
+
// transport and switches), and a shell that differs only in those made 103 of 119 rows miss with no input change (batch 051b). The row's OWN environment (what the
|
|
196
|
+
// planner set on it) is keyed in full elsewhere (keyEnv(s.env)); this filter is for what the child inherits from the gate's process.
|
|
197
|
+
const CARGO_ENV_NAMES = new Set([...BUILD_ENV_NAMES].filter((n) => !/^(NODE_OPTIONS|NODE_ENV)$/.test(n)));
|
|
198
|
+
const CARGO_ENV_PREFIXES = ["CARGO_", "RUST", "SCCACHE_", "CMAKE_", "CFLAGS_", "CXXFLAGS_", "OPENSSL_", "ORT_", "ONNX", "TAURI_", "WEBVIEW2_", "WINDOWS_SDK", "MSVC"];
|
|
199
|
+
const NODE_ENV_NAMES = new Set(["CI", "GITHUB_ACTIONS", "NODE_OPTIONS", "NODE_ENV", "SOURCE_DATE_EPOCH"]);
|
|
200
|
+
const NODE_ENV_PREFIXES = ["NPM_CONFIG_", "PNPM_"];
|
|
201
|
+
// Locations, not inputs: where pnpm keeps its binaries and where npm caches downloads change no verdict (Mac 2026-11-07 and 2026-11-08).
|
|
202
|
+
const NODE_ENV_LOCATIONS = /^(PNPM_HOME|NPM_CONFIG_CACHE|NPM_CONFIG_STORE_DIR|NPM_CONFIG_PREFIX|NPM_CONFIG_USERCONFIG|NPM_CONFIG_GLOBALCONFIG)$/;
|
|
203
|
+
const CARGO_TOOLS = new Set(["rustright", "cargo", "rustc", "rustfmt", "clippy", "rustdoc", "cargo-deny", "cargo-audit", "swift"]);
|
|
204
|
+
const NODE_TOOLS = new Set(["node", "pnpm", "npm", "npx", "tsc", "vitest", "biome", "oxlint", "eslint"]);
|
|
205
|
+
/** Whether `name` is an inherited-environment input of a row run by `tool` (null: the union, as before). */
|
|
206
|
+
export const buildEnvNameFor = (tool) => (name) => {
|
|
207
|
+
if (tool === null || tool === undefined) return buildEnvName(name);
|
|
208
|
+
const upper = String(name).toUpperCase();
|
|
209
|
+
if (BUILD_ENV_EXCLUDED.test(upper)) return false;
|
|
210
|
+
const cargo = CARGO_ENV_NAMES.has(upper) || CARGO_ENV_PREFIXES.some((p) => upper.startsWith(p));
|
|
211
|
+
if (CARGO_TOOLS.has(tool)) return cargo;
|
|
212
|
+
// A node tool can compile native code from a script (a test that builds a Tauri app), so its rows read the cargo family too, less the node locations.
|
|
213
|
+
if (NODE_TOOLS.has(tool)) return !NODE_ENV_LOCATIONS.test(upper) && (cargo || NODE_ENV_NAMES.has(upper) || NODE_ENV_PREFIXES.some((p) => upper.startsWith(p)));
|
|
214
|
+
return upper === "CI" || upper === "GITHUB_ACTIONS";
|
|
215
|
+
};
|
|
179
216
|
|
|
180
217
|
/** sha256 of the build-relevant part (buildEnvName) of the environment a scan's child receives. Pass the merged `{ ...deps.env, ...scan.env }`. */
|
|
181
|
-
|
|
182
|
-
|
|
218
|
+
/** The build-relevant variables of `env` as {NAME: sha256 of the normalised value}: miss evidence names which ones moved, never their values. */
|
|
219
|
+
export function inheritedEnvShape(env = {}, tool = null) {
|
|
220
|
+
const relevant = buildEnvNameFor(tool);
|
|
221
|
+
return Object.fromEntries(Object.entries(env).filter(([name, value]) => value !== undefined && value !== null && relevant(name)).map(([name, value]) => [String(name).toUpperCase(), sha256(normalizeRunTemp(value)).slice(0, 16)]).sort((x, y) => (x[0] < y[0] ? -1 : 1)));
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
export function inheritedEnvDigest(env = {}, tool = null) {
|
|
225
|
+
const relevant = buildEnvNameFor(tool);
|
|
226
|
+
const rows = Object.entries(env).filter(([name, value]) => value !== undefined && value !== null && relevant(name)).map(([name, value]) => [String(name).toUpperCase(), normalizeRunTemp(value)]);
|
|
183
227
|
rows.sort((x, y) => (x[0] < y[0] ? -1 : x[0] > y[0] ? 1 : 0));
|
|
184
228
|
return sha256(canonicalJson(rows));
|
|
185
229
|
}
|
|
@@ -253,8 +297,48 @@ export function fmtCheckArgs(unit = null) { return unit ? ["fmt", "-p", unit, "-
|
|
|
253
297
|
/** `cargo metadata` that validates manifests and the lock without resolving anything new. */
|
|
254
298
|
export function metadataArgs({ noDeps = true } = {}) { return ["metadata", ...(noDeps ? ["--no-deps"] : []), "--format-version", "1", "--locked"]; }
|
|
255
299
|
|
|
256
|
-
|
|
257
|
-
|
|
300
|
+
// NN27 (GATE-CONTRACT GC-A27): never two compiler passes over one crate, target and feature set. A publisher check is proved by a passing plan
|
|
301
|
+
// row (clippy or check) over the same crate, features, target and all-targets selection with the same compiler-relevant environment: clippy runs
|
|
302
|
+
// the same compile and only adds lints. Output and failure flags (--message-format, --locked, --keep-going, -j, lint arguments after `--`) do not
|
|
303
|
+
// change what compiled. Tests and docs never reuse: their environment or target selection differs. (Moved from unit-list-compile.mjs, retired with
|
|
304
|
+
// the grouped publisher scheduler, reset plan step 5; planUnitListScans in local-publish.mjs is the one caller.)
|
|
305
|
+
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"];
|
|
306
|
+
/** `as`: "check" (what a check or clippy proves) or "clippy" (a clippy with its lint arguments, provable only by the same clippy). */
|
|
307
|
+
export function compileProofKey(scan, as = "check") {
|
|
308
|
+
if (!scan || !Array.isArray(scan.args)) return null;
|
|
309
|
+
const argv = scan.args[0] === "cargo" ? scan.args.slice(1) : scan.args;
|
|
310
|
+
const sub = argv[0];
|
|
311
|
+
if (sub !== "check" && sub !== "clippy") return null;
|
|
312
|
+
if (as === "clippy" && sub !== "clippy") return null;
|
|
313
|
+
const sep = argv.indexOf("--");
|
|
314
|
+
const lints = as === "clippy" ? (sep < 0 ? [] : argv.slice(sep + 1)) : null;
|
|
315
|
+
const packages = []; const features = []; let noDefault = false; let allFeatures = false; let target = null; let allTargets = false;
|
|
316
|
+
for (let i = 1; i < argv.length; i += 1) {
|
|
317
|
+
const a = argv[i];
|
|
318
|
+
if (a === "--") break;
|
|
319
|
+
if (a === "-p" || a === "--package") packages.push(argv[++i]);
|
|
320
|
+
else if (a === "--features" || a === "-F") features.push(...String(argv[++i] ?? "").split(/[ ,]+/).filter(Boolean));
|
|
321
|
+
else if (a.startsWith("--features=")) features.push(...a.slice(11).split(/[ ,]+/).filter(Boolean));
|
|
322
|
+
else if (a === "--no-default-features") noDefault = true;
|
|
323
|
+
else if (a === "--all-features") allFeatures = true;
|
|
324
|
+
else if (a === "--target") target = argv[++i];
|
|
325
|
+
else if (a === "--all-targets") allTargets = true;
|
|
326
|
+
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; }
|
|
327
|
+
else return null; // anything else could change what compiles: no proof either way
|
|
328
|
+
}
|
|
329
|
+
if (packages.length !== 1 || !packages[0]) return null;
|
|
330
|
+
const env = Object.fromEntries(COMPILE_ENV.map((k) => [k, scan.env?.[k] ?? null]));
|
|
331
|
+
return JSON.stringify({ as, ...(lints ? { lints } : {}), cwd: scan.cwd ?? ".", package: packages[0], features: [...new Set(features)].sort(), noDefault, allFeatures, target, allTargets, env });
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/**
|
|
335
|
+
* Translate one authenticated publisher requirement into a normal Class B scan. `batch` (a unit-list run, reset plan step 5) marks the scan `batchable`
|
|
336
|
+
* exactly as planScans marks its own compile rows, so runScans' one class B grouping (classBBatching, the feature partition, the store rule, the
|
|
337
|
+
* serial reuse) groups publisher rows with each other: a check, clippy or doc of one crate, or a Rust test whose executables run outside the
|
|
338
|
+
* broker, with no `--features` of its own. A publisher row never shares a group with a plan row (`publisher` is part of the key), and a group is
|
|
339
|
+
* only of rows with the same verdict rules (`allowIgnored`, `quiet`).
|
|
340
|
+
*/
|
|
341
|
+
export function publisherRequirementScan(requirement, { platform = process.platform, nativeArch = process.arch, cargoCommand = ["cargo"], cargoLiveRoot = null, targetDirs = null, quiet = false, allowIgnored = false, batch = false } = {}) {
|
|
258
342
|
const { id, workspace, cwd, executable, argv, env, phase, coverageKey } = requirement ?? {};
|
|
259
343
|
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
344
|
const plainDir = (value) => typeof value === "string" && /^(?:\.|[A-Za-z0-9_@+.-]+(?:\/[A-Za-z0-9_@+.-]+)*)$/.test(value) && !value.split("/").includes("..");
|
|
@@ -269,16 +353,180 @@ export function publisherRequirementScan(requirement, { platform = process.platf
|
|
|
269
353
|
runOutside = { args: runArgs };
|
|
270
354
|
}
|
|
271
355
|
if (executable === "cargo") {
|
|
272
|
-
if (cargoJobs !== null) args = cargoWidthArgs(args, cargoJobs);
|
|
273
356
|
args = oneOutput(isRustTest && cargoLiveRoot ? args : everyFailure(args), { platform, arch: nativeArch });
|
|
274
357
|
}
|
|
275
358
|
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
359
|
// Do not render the inherited publisher environment into logs or receipts.
|
|
277
360
|
scan.command = commandText({ ...scan, env: {} });
|
|
361
|
+
if (batch && executable === "cargo") {
|
|
362
|
+
const offset = scan.args[0] === "cargo" ? 1 : 0;
|
|
363
|
+
const sub = scan.args[offset];
|
|
364
|
+
const at = scan.args.indexOf("-p");
|
|
365
|
+
const crate = at >= 0 ? scan.args[at + 1] : null;
|
|
366
|
+
const eligible = phase === "compile" ? ["check", "clippy", "doc"].includes(sub) : isRustTest && Boolean(runOutside);
|
|
367
|
+
if (eligible && at > offset && typeof crate === "string" && !crate.startsWith("-") && scan.args.indexOf("-p", at + 1) < 0) {
|
|
368
|
+
const rest = [...scan.args.slice(0, at), ...scan.args.slice(at + 2)];
|
|
369
|
+
if (!rest.some((w) => /^(?:--features(?:=.*)?|-F.*)$/.test(w))) {
|
|
370
|
+
const key = sha256(canonicalJson({ publisher: true, phase, tool: scan.tool, workspace: scan.executionWorkspace ?? null, cwd: scan.cwd, root: scan.root, env: scan.env, rest, at, allowIgnored: scan.allowIgnored === true, quiet: scan.quiet === true })).slice(0, 16);
|
|
371
|
+
// The row's own --target stays in its key (so a group is one target) and is named for the feature partition, as planScans names it for its rows.
|
|
372
|
+
const ti = rest.indexOf("--target"); const target = ti >= 0 && typeof rest[ti + 1] === "string" ? rest[ti + 1] : null;
|
|
373
|
+
scan.batchable = { key, at, crate, unit: crate, ...(target ? { target } : {}) };
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
}
|
|
278
377
|
return scan;
|
|
279
378
|
}
|
|
280
379
|
|
|
380
|
+
// ---- A unit-list run's publisher requirements (reset plan step 5; replaces unit-list-compile.mjs, the grouped publisher scheduler) ----------------------------
|
|
381
|
+
// A unit-list run plans ONE scan set: planScans over the closure of every listed unit, plus one Class B scan per publisher requirement the plan's own rows
|
|
382
|
+
// do not already prove (planUnitListScans). runScans runs that set with its own class B grouping, under the run's one snapshot lock and one shared Class A.
|
|
383
|
+
// judgeUnitList then answers, per requirement and per unit, from the rows runScans returned.
|
|
384
|
+
|
|
385
|
+
/** A requirement as compileRequirements builds it: every field present and `coverageKey` the digest of its body (an altered requirement refuses planning). */
|
|
386
|
+
export function assertCanonicalRequirements(entries) {
|
|
387
|
+
if (!Array.isArray(entries) || !entries.length) throw new Error("unit list needs compile requirements");
|
|
388
|
+
const ids = new Set();
|
|
389
|
+
for (const entry of entries) {
|
|
390
|
+
if (typeof entry?.selector !== "string" || !Array.isArray(entry.requirements) || !entry.requirements.length) throw new Error("each unit needs a nonempty canonical compile plan");
|
|
391
|
+
for (const r of entry.requirements) {
|
|
392
|
+
const body = { workspace: r.workspace, cwd: r.cwd, executable: r.executable, ...(r.internal === undefined ? {} : { internal: r.internal }), argv: r.argv, env: r.env, phase: r.phase };
|
|
393
|
+
if (typeof r.id !== "string" || ids.has(r.id) || typeof r.workspace !== "string" || !r.workspace || typeof r.cwd !== "string" || !r.cwd || (typeof r.executable !== "string" && !(r.executable === null && r.internal === "scanCrateForSecrets")) || !Array.isArray(r.argv) || !r.argv.every((x) => typeof x === "string") || !r.env || typeof r.env !== "object" || Array.isArray(r.env) || !["test", "compile", "check"].includes(r.phase) || sha256(JSON.stringify(body)) !== r.coverageKey) throw new Error(`invalid or duplicate canonical requirement ${r.id ?? "<missing>"}`);
|
|
394
|
+
ids.add(r.id);
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
/** The units a unit-list run does not compile: those that failed an internal requirement (secret scan, format), and every selected unit that depends on one, transitively. */
|
|
400
|
+
export function blockedUnitsOf({ dependencies = {}, initialFailures = new Set() } = {}) {
|
|
401
|
+
const blocked = new Set(initialFailures);
|
|
402
|
+
for (let changed = true; changed;) { changed = false; for (const [selector, deps] of Object.entries(dependencies)) if (!blocked.has(selector) && deps.some((dep) => blocked.has(dep))) { blocked.add(selector); changed = true; } }
|
|
403
|
+
return blocked;
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
/**
|
|
407
|
+
* The publisher scans of a unit-list run, to be appended to the plan's scans. `entries` are the units' external requirements (`[{ selector, requirements }]`),
|
|
408
|
+
* `planned` the plan's own scans, `adapt` publisherRequirementScan with the run's options (batch on). Keeps every requirement of the retired scheduler:
|
|
409
|
+
* - each requirement is authenticated first (assertCanonicalRequirements);
|
|
410
|
+
* - identical requirements of several units (same coverageKey) are ONE scan, every member id mapped to it (`scanOf`);
|
|
411
|
+
* - a requirement that moved to its workspace root (`normalizedCwds`, proveWorkspaceCwd) is planned at that root, so runScans groups it with the others;
|
|
412
|
+
* - NN27: a check or clippy requirement a plan row proves (compileProofKey) gets no scan; `providerOf` names the plan row whose pass stands for it, and
|
|
413
|
+
* that row is returned in `provers` so the run marks it (`provesPublisher`: its pass is stored with, and returns, the broker receipt the publisher verdict needs);
|
|
414
|
+
* - a unit in `blocked` has no scan: its requirements are reported blocked by judgeUnitList.
|
|
415
|
+
*/
|
|
416
|
+
export function planUnitListScans({ entries, planned = [], normalizedCwds = new Map(), adapt, blocked = new Set() }) {
|
|
417
|
+
assertCanonicalRequirements(entries);
|
|
418
|
+
if (typeof adapt !== "function") throw new TypeError("planUnitListScans needs the publisher scan adapter");
|
|
419
|
+
const proofs = new Map();
|
|
420
|
+
for (const scan of planned) {
|
|
421
|
+
if (scan?.class !== SCAN_CLASS.B || scan.deferred || scan.publisherPhase) continue;
|
|
422
|
+
for (const as of ["check", "clippy"]) { const key = compileProofKey(scan, as); if (key !== null && !proofs.has(key)) proofs.set(key, scan.id); }
|
|
423
|
+
}
|
|
424
|
+
const scans = []; const scanOf = new Map(); const providerOf = new Map(); const provers = new Set(); const byCoverage = new Map();
|
|
425
|
+
for (const entry of entries) for (const r of entry.requirements) {
|
|
426
|
+
if (blocked.has(entry.selector)) continue;
|
|
427
|
+
const seen = byCoverage.get(r.coverageKey);
|
|
428
|
+
if (seen) { if (seen.scan) scanOf.set(r.id, seen.scan); else { providerOf.set(r.id, seen.provider); } continue; }
|
|
429
|
+
const scan = adapt({ ...r, cwd: normalizedCwds.get(r.id) ?? r.cwd });
|
|
430
|
+
const argv = scan.args[0] === "cargo" ? scan.args.slice(1) : scan.args;
|
|
431
|
+
const key = r.executable === "cargo" && r.phase === "compile" ? compileProofKey(scan, argv[0] === "clippy" ? "clippy" : "check") : null;
|
|
432
|
+
const provider = key === null ? undefined : proofs.get(key);
|
|
433
|
+
if (provider) { providerOf.set(r.id, provider); provers.add(provider); byCoverage.set(r.coverageKey, { provider }); continue; }
|
|
434
|
+
scans.push(scan); scanOf.set(r.id, scan.id); byCoverage.set(r.coverageKey, { scan: scan.id });
|
|
435
|
+
}
|
|
436
|
+
return { scans, scanOf, providerOf, provers: [...provers] };
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
/**
|
|
440
|
+
* The verdict of each external requirement of a unit-list run, from the rows runScans returned. `rowOf(scanId)` is that run's row; `verify` is the publisher's
|
|
441
|
+
* own judgement of one row (`{ row, member, attempts, requirement }` -> `{ ok, evidenceHash }`: the receipt, the test verdict, skip and truncation rules).
|
|
442
|
+
* Returns `[{ selector, id, coverageKey, status: "passed"|"failed"|"blocked", evidenceHash? }]`, one per requirement. A row that is not a pass, or that does not
|
|
443
|
+
* verify, is failed. A unit whose dependency has any failed or blocked row is blocked as a whole (its passed rows are reported blocked, never passed), so no
|
|
444
|
+
* verdict depends on the order the rows ran in; a unit with a failed row of its own stays failed.
|
|
445
|
+
*/
|
|
446
|
+
export async function judgeUnitList({ entries, dependencies = {}, blocked = new Set(), scanOf, providerOf, rowOf, verify }) {
|
|
447
|
+
const results = [];
|
|
448
|
+
for (const entry of entries) for (const r of entry.requirements) {
|
|
449
|
+
const member = { selector: entry.selector, id: r.id, coverageKey: r.coverageKey };
|
|
450
|
+
if (blocked.has(entry.selector)) { results.push({ ...member, status: "blocked" }); continue; }
|
|
451
|
+
const providerId = scanOf.has(r.id) ? null : providerOf.get(r.id) ?? null;
|
|
452
|
+
const row = rowOf(scanOf.get(r.id) ?? providerId);
|
|
453
|
+
// The receipt of a unit says which row answered each requirement: its own scan, or the plan row that proves it (NN27).
|
|
454
|
+
Object.assign(member, providerId ? { providedBy: providerId } : scanOf.has(r.id) ? { scan: scanOf.get(r.id) } : {});
|
|
455
|
+
let status = "failed"; let evidenceHash;
|
|
456
|
+
try {
|
|
457
|
+
const attempts = row ? [{ id: row.id, status: row.status, ...(row.code ? { code: row.code } : {}), command: row.command, ...(providerId ? { provedBy: providerId } : {}), ...(row.snapshotEvidence ? { snapshotEvidence: row.snapshotEvidence } : {}) }] : [];
|
|
458
|
+
const checked = await verify({ row, member, attempts, requirement: r });
|
|
459
|
+
if (row?.status === "pass" && checked?.ok === true && typeof checked.evidenceHash === "string" && /^[0-9a-f]{64}$/.test(checked.evidenceHash)) { status = "passed"; evidenceHash = checked.evidenceHash; }
|
|
460
|
+
} catch { /* An exception cannot attest a pass. */ }
|
|
461
|
+
results.push({ ...member, status, ...(evidenceHash ? { evidenceHash } : {}) });
|
|
462
|
+
}
|
|
463
|
+
const own = new Set(results.filter((r) => r.status === "failed").map((r) => r.selector));
|
|
464
|
+
const bad = new Set(results.filter((r) => r.status !== "passed").map((r) => r.selector));
|
|
465
|
+
const present = new Set(entries.map((e) => e.selector));
|
|
466
|
+
for (let changed = true; changed;) { changed = false; for (const [selector, deps] of Object.entries(dependencies)) if (!bad.has(selector) && present.has(selector) && deps.some((dep) => bad.has(dep))) { bad.add(selector); changed = true; } }
|
|
467
|
+
for (const r of results) if (bad.has(r.selector) && !own.has(r.selector) && r.status === "passed") { r.status = "blocked"; delete r.evidenceHash; }
|
|
468
|
+
return results;
|
|
469
|
+
}
|
|
470
|
+
|
|
281
471
|
/** Deduplicate concurrent identical probes; transient outcomes are never retained. */
|
|
472
|
+
// The command text a cache key binds. Cargo's build width (`--jobs N`, from --cargo-jobs) changes how many processes compile, never what compiles or
|
|
473
|
+
// a verdict, so it is not part of the key: a row passed at one width is the same row at another (Mac 2026-11-07, run 17 --cargo-jobs 6: all 295
|
|
474
|
+
// stored passes missed as 'nothing changed: the cache failed').
|
|
475
|
+
/** Whether a stored row's command is this scan's command: the same text once Cargo's build width is dropped (67515ffb dropped it from the key but
|
|
476
|
+
* the lookup still compared the raw text, so a different --jobs missed every stored pass). */
|
|
477
|
+
export function sameCommand(stored, s) { return keyCommand({ command: stored, runOutside: s.runOutside }) === keyCommand(s); }
|
|
478
|
+
/**
|
|
479
|
+
* Whether a stored pass is this row's (store rule, GC-A18; rightkit#1537, rightkit#1538): the row's own id and command, written by the
|
|
480
|
+
* invocation that ran it (never a member row projected from a group, which carries `batchedWith`/`batchCommand`), with the evidence the
|
|
481
|
+
* row's kind needs to be judged as the fresh row was: a test row its counts (testResultsProblem), a publisher row on a broker its receipt
|
|
482
|
+
* digest, a test group every member's own run (memberRuns) with that member's counts. `hit` is the cache entry ({ key, at, row }).
|
|
483
|
+
*/
|
|
484
|
+
export function usableStoredPass(hit, s, { cacheKey, viaSeam = false } = {}) {
|
|
485
|
+
const row = hit?.row;
|
|
486
|
+
if (!hit || hit.key !== cacheKey || row?.status !== "pass" || row.id !== s.id || !sameCommand(row.command, s)) return false;
|
|
487
|
+
if (row.batchedWith || row.batchCommand) return false;
|
|
488
|
+
if ((s.kind === "test" || s.runOutside) && testResultsProblem(row.results) !== null) return false;
|
|
489
|
+
// `provesPublisher`: a plan row that stands for a publisher requirement (planUnitListScans, NN27) is judged on a broker host like the publisher row: its pass carries the receipt.
|
|
490
|
+
if ((s.coverageKey || s.provesPublisher) && viaSeam && !/^[0-9a-f]{64}$/.test(row.snapshotEvidence?.receiptSha256 ?? "")) return false;
|
|
491
|
+
if (Array.isArray(s.testGroup)) {
|
|
492
|
+
if (!row.memberRuns || typeof row.memberRuns !== "object") return false;
|
|
493
|
+
for (const m of s.testGroup) { const v = row.memberRuns[m.id]; if (!v || v.status !== "pass" || testResultsProblem(v.results) !== null) return false; }
|
|
494
|
+
}
|
|
495
|
+
return true;
|
|
496
|
+
}
|
|
497
|
+
/** The row a pass stores: everything a later hit needs to be judged as the fresh row was (results, the test run's skip and truncation evidence, each member's own run). */
|
|
498
|
+
export function storedPassRow(s, row) {
|
|
499
|
+
// The accepted executables of a run are run-time objects for a serial row's reuse (rightkit#1539) and are never cache content. What is stored is the digest-bound
|
|
500
|
+
// proof (executableProof: the bound output directories and each executable's path, package, target and sha256): a later serial row whose plain row is a cache hit
|
|
501
|
+
// re-checks every file against it (provenExecutables) and reuses them only when every one is still there with the same digest; otherwise it compiles once, alone.
|
|
502
|
+
const memberRuns = row.memberRuns ? Object.fromEntries(Object.entries(row.memberRuns).map(([id, v]) => { const { acceptedBinaries: _bins, ...rest } = v ?? {}; void _bins; return [id, rest]; })) : null;
|
|
503
|
+
return { id: s.id, class: s.class, command: s.command, tool: s.tool ?? null, toolVersion: row.toolVersion, status: "pass", ...(row.executableProof ? { executableProof: row.executableProof } : {}), ...(s.coverageKey || s.provesPublisher ? { snapshotEvidence: row.snapshotEvidence ?? null } : {}), ...(row.testRun || s.coverageKey ? { testRun: row.testRun ?? null } : {}), ...(row.results ? { results: row.results } : {}), ...(memberRuns ? { memberRuns } : {}) };
|
|
504
|
+
}
|
|
505
|
+
/** The digest-bound proof of a run's accepted test executables (plain data, cacheable): `{ boundDirs, binaries: [{ executable, package, target, version, manifestDir, sha256 }] }`. */
|
|
506
|
+
export function executableProofOf(accepted, boundDirs) {
|
|
507
|
+
return { boundDirs: [...(boundDirs ?? [])].map(String), binaries: (accepted ?? []).map((b) => ({ executable: b.executable, package: b.package ?? null, target: b.target ?? null, version: b.version ?? null, manifestDir: b.manifestDir ?? null, sha256: b.sha256 })) };
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
/**
|
|
511
|
+
* A stored executable proof checked again against the files as they are now: `{ accepted }` when every listed executable is still a regular file inside its bound
|
|
512
|
+
* output directory (and generation target) with the stored sha256, else `{ accepted: null, why }`. An empty list proves an empty list.
|
|
513
|
+
*/
|
|
514
|
+
export function provenExecutables(proof, { generationRoots = null, platform = process.platform, ops = TEST_RUN_OPS } = {}) {
|
|
515
|
+
if (!proof || !Array.isArray(proof.binaries) || !Array.isArray(proof.boundDirs)) return { accepted: null, why: "no stored executable proof" };
|
|
516
|
+
if (!proof.binaries.length) return { accepted: [] };
|
|
517
|
+
if (proof.binaries.some((b) => typeof b?.executable !== "string" || !/^[0-9a-f]{64}$/.test(String(b?.sha256 ?? "")))) return { accepted: null, why: "the stored proof is malformed" };
|
|
518
|
+
const contained = containTestExecutables(proof.binaries.map((b) => ({ ...b })), { boundDirs: proof.boundDirs, generationRoots, platform, ops });
|
|
519
|
+
if (contained.problems.length) return { accepted: null, why: contained.problems.slice(0, 3).join("; ") };
|
|
520
|
+
if (contained.accepted.length !== proof.binaries.length) return { accepted: null, why: "not every stored executable is still there" };
|
|
521
|
+
for (let i = 0; i < proof.binaries.length; i += 1) if (contained.accepted[i].sha256 !== proof.binaries[i].sha256) return { accepted: null, why: `${proof.binaries[i].executable} changed since its plain row passed` };
|
|
522
|
+
return { accepted: contained.accepted };
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
export function keyCommand(s) {
|
|
526
|
+
const base = String(s.command ?? "").replace(/(^|\s)--jobs\s+\d+(?=\s|$)/g, "");
|
|
527
|
+
return s.runOutside ? `${base} ;; run ${canonicalJson(s.runOutside)}` : base;
|
|
528
|
+
}
|
|
529
|
+
|
|
282
530
|
export function singleFlightProbe(probe) {
|
|
283
531
|
const pending = new Map(); const completed = new Map();
|
|
284
532
|
return async (key, ...args) => {
|
|
@@ -476,21 +724,77 @@ export const CACHEABLE_INTERNAL = new Set(["ghsa-audit", "advisory-exceptions",
|
|
|
476
724
|
export const FAILURE_UNCACHEABLE_INTERNAL = new Set(["ghsa-audit", "advisory-exceptions"]);
|
|
477
725
|
/** NN41: the key namespace of a cached failure, so a failure never shares a key with a pass of the same scan. */
|
|
478
726
|
// /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
|
-
|
|
727
|
+
// /3 (2026-11-06): a missing system library (pkg-config, system-deps) is the host, not the inputs; failures stored under /2 may be one.
|
|
728
|
+
/** planScans file digests by file identity (path, inode, size, mtime) for this process: one run plans its stages over the same snapshot. */
|
|
729
|
+
const PLAN_DIGEST_MEMO = new Map();
|
|
730
|
+
export const FAILURE_KEY_SCHEMA = "deterministic-failure/3";
|
|
480
731
|
/** NN23: the version of the internal (file-only) rules; bump when any internal rule's verdict for the same inputs changes. */
|
|
481
732
|
export const INTERNAL_RULES_SCHEMA = "rightkit.internal-rules/1";
|
|
482
733
|
/** 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
734
|
* version, the environment variables that differ. Bounded lists; evidence for Adrian's approval of a miss. */
|
|
735
|
+
/** A key's raw inputs as {path-like entry: value} (the files list entries become `files.N/<path>`), with the key suffix as "(key suffix)". */
|
|
736
|
+
export function flatKeyInputs(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(`${String(at).replace(/\.\d+$/, "")}/${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; }
|
|
737
|
+
const isBlobId = (v) => typeof v === "string" && /^[0-9a-f]{40}([0-9a-f]{24})?$/.test(v);
|
|
738
|
+
/**
|
|
739
|
+
* Carry-over (Adrian 2026-11-07: a key change must not rerun or ask for approval what did not change). A stored pass keyed under an earlier key FORM is
|
|
740
|
+
* the same result under the new key when the row's real inputs provably did not change: the same tool and scan environment; inherited variables
|
|
741
|
+
* that differ only in names the key no longer includes (buildEnvName false now); and every input entry that differs going from a file's content id
|
|
742
|
+
* (the old form) to a value derived from that file (the new form, e.g. a package.json's "type") while the file's content id NOW is still the old
|
|
743
|
+
* one. Anything else (an edited file, an entry added or removed, a schema suffix change, a tool or environment change) is not carried.
|
|
744
|
+
*/
|
|
745
|
+
export function carryOverProof(before, after, { entryNow }) {
|
|
746
|
+
const no = (why) => ({ ok: false, why });
|
|
747
|
+
if (!before || !after) return no("no stored key parts");
|
|
748
|
+
if (before.toolVersion !== after.toolVersion) return no("tool changed");
|
|
749
|
+
// The scan's own environment is compared on the names that can change a result (buildEnvName): a publisher row once keyed the calling session's whole environment.
|
|
750
|
+
const relevant = (env) => Object.fromEntries(Object.entries(env ?? {}).filter(([k]) => buildEnvName(k)));
|
|
751
|
+
if (canonicalJson(relevant(before.env)) !== canonicalJson(relevant(after.env))) return no("scan environment changed");
|
|
752
|
+
if (before.inherited !== after.inherited) {
|
|
753
|
+
if (!before.inheritedShape || !after.inheritedShape) return no("inherited environment changed (no shape to compare)");
|
|
754
|
+
const names = [...new Set([...Object.keys(before.inheritedShape), ...Object.keys(after.inheritedShape)])].filter((k) => before.inheritedShape[k] !== after.inheritedShape[k]);
|
|
755
|
+
const kept = names.filter((k) => buildEnvName(k));
|
|
756
|
+
if (kept.length) return no(`inherited environment changed: ${kept.slice(0, 5).join(", ")}`);
|
|
757
|
+
}
|
|
758
|
+
const a = flatKeyInputs(before.inputs ?? ""); const b = flatKeyInputs(after.inputs ?? "");
|
|
759
|
+
const changed = [...new Set([...a.keys(), ...b.keys()])].filter((k) => a.get(k) !== b.get(k));
|
|
760
|
+
const carried = []; const edited = []; const file0 = (k) => k.slice(k.indexOf("/") + 1);
|
|
761
|
+
for (const k of changed) {
|
|
762
|
+
if (!a.has(k) || !b.has(k)) return no(`input entry ${k} added or removed`);
|
|
763
|
+
if (k === "(key suffix)" || k === "inputs") return no(`${k} changed`);
|
|
764
|
+
const was = a.get(k); const now = b.get(k);
|
|
765
|
+
// A file edit (one content id becoming another): the row's own file changed. It is never carried, but it is recorded so the caller can tell a
|
|
766
|
+
// row whose only other differences are proven form changes (it must rerun, as any edited row does, with no approval) from an unexplained miss.
|
|
767
|
+
if (isBlobId(was) && isBlobId(now)) { edited.push(file0(k)); continue; }
|
|
768
|
+
if (!isBlobId(was) || isBlobId(now)) return no(`${k}: not a content id becoming a derived value`);
|
|
769
|
+
const file = k.slice(k.indexOf("/") + 1);
|
|
770
|
+
let id = null; try { id = entryNow(file); } catch { id = null; }
|
|
771
|
+
if (id !== was) return no(`${k}: the file changed since the stored pass`);
|
|
772
|
+
carried.push(file);
|
|
773
|
+
}
|
|
774
|
+
// ok: the stored pass IS this row's pass (nothing real changed). edited: the row's own files changed and everything else is a proven form change,
|
|
775
|
+
// so it reruns like any edited row (contentOnly), with no approval.
|
|
776
|
+
return edited.length ? { ok: false, why: "own files edited", edited, carried } : { ok: true, carried };
|
|
777
|
+
}
|
|
778
|
+
|
|
484
779
|
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; };
|
|
780
|
+
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(`${String(at).replace(/\.\d+$/, "")}/${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
781
|
const a = flat(before?.inputs ?? ""); const b = flat(after?.inputs ?? "");
|
|
487
782
|
const inputs = [...new Set([...a.keys(), ...b.keys()])].filter((k) => a.get(k) !== b.get(k)).sort();
|
|
488
|
-
|
|
783
|
+
// Only names that can change a result count (buildEnvName); a publisher row's stored environment is the old whole-session one.
|
|
784
|
+
const envKeys = [...new Set([...Object.keys(before?.env ?? {}), ...Object.keys(after?.env ?? {})])].filter((k) => buildEnvName(k) && (before?.env ?? {})[k] !== (after?.env ?? {})[k]).sort();
|
|
785
|
+
// A real file edit changes one content id into another (git blob ids: 40 or 64 hex). Anything else (a key entry whose form changed) is not a file change.
|
|
786
|
+
const blob = (v) => typeof v === "string" && /^[0-9a-f]{40}([0-9a-f]{24})?$/.test(v);
|
|
787
|
+
// A file entry is keyed by its path, never its position in the list (one added file shifted every later position and read as thousands of key-form
|
|
788
|
+
// changes: secret-scan, Mac 2026-11-07). An added or removed file is the row's own change, like an edited one.
|
|
789
|
+
// The advisory rows (cargo-audit, cargo-deny, ghsa-audit, advisory-exceptions, pnpm audit) key on the UTC day by design (the advisory databases move
|
|
790
|
+
// daily): a new day is their own declared input changing, like a file edit, never an unexplained miss (Mac 2026-11-07: 9 rows stopped a run at 00:02Z).
|
|
791
|
+
const day = (k) => k === "day" && /^\d{4}-\d{2}-\d{2}$/.test(String(a.get(k))) && /^\d{4}-\d{2}-\d{2}$/.test(String(b.get(k)));
|
|
792
|
+
const contentOnly = inputs.length > 0 && inputs.every((k) => day(k) || ((blob(a.get(k)) || !a.has(k)) && (blob(b.get(k)) || !b.has(k)) && (a.has(k) || b.has(k))));
|
|
489
793
|
return {
|
|
490
|
-
inputs: inputs.slice(0, 12), inputsChanged: inputs.length,
|
|
794
|
+
inputs: inputs.slice(0, 12), inputsChanged: inputs.length, contentOnly,
|
|
491
795
|
...(before?.toolVersion !== after?.toolVersion ? { tool: { from: before?.toolVersion ?? null, to: after?.toolVersion ?? null } } : {}),
|
|
492
796
|
...(envKeys.length ? { env: envKeys.slice(0, 12) } : {}),
|
|
493
|
-
...(before?.inherited !== after?.inherited ? { inheritedEnv: true } : {}),
|
|
797
|
+
...(before?.inherited !== after?.inherited ? { inheritedEnv: before?.inheritedShape && after?.inheritedShape ? [...new Set([...Object.keys(before.inheritedShape), ...Object.keys(after.inheritedShape)])].filter((k) => before.inheritedShape[k] !== after.inheritedShape[k]).sort().slice(0, 20) : true } : {}),
|
|
494
798
|
};
|
|
495
799
|
}
|
|
496
800
|
/** 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. */
|
|
@@ -499,7 +803,7 @@ export const isFailureCacheableCompileId = (id) => /^(?:check|check-features|che
|
|
|
499
803
|
export function isDeterministicCompileDiagnostics(text) {
|
|
500
804
|
const t = String(text ?? "");
|
|
501
805
|
const diagnostics = /(?:^|\n)\s*error(?:\[[A-Za-z]\d+\])?: /.test(t) || /could not compile|aborting due to/.test(t);
|
|
502
|
-
const environmental = /failed to (?:download|fetch|get|update|load source|create|write|open|remove)|network|spurious|timed out|No space left|Too many open files|Permission denied|Resource temporarily|Text file busy|internal compiler error|panicked at|signal: |SIGKILL|SIGSEGV|Killed/i.test(t);
|
|
806
|
+
const environmental = /failed to (?:download|fetch|get|update|load source|create|write|open|remove)|network|spurious|timed out|No space left|Too many open files|Permission denied|Resource temporarily|Text file busy|internal compiler error|panicked at|pkg-config|PKG_CONFIG|system library|was not found in the pkg-config search path|Package [^\n]* was not found|linker `[^`]*` not found|unable to find library|cannot find -l|signal: |SIGKILL|SIGSEGV|Killed/i.test(t);
|
|
503
807
|
return diagnostics && !environmental;
|
|
504
808
|
}
|
|
505
809
|
export const isLiveScan = (id) => LIVE_SCAN_IDS.some((p) => id === p || String(id).startsWith(`${p}:`));
|
|
@@ -965,7 +1269,7 @@ export function planScans({
|
|
|
965
1269
|
changed = [], contentRoot, liveRoot = contentRoot, trustedRoot = null, exists = fs.existsSync, readFile = (f) => fs.readFileSync(f, "utf8"),
|
|
966
1270
|
platform = process.platform, includeTests = true, localCompile = true,
|
|
967
1271
|
// The host's CPU architecture for its own Rust target (oneOutput, cross-targets.mjs).
|
|
968
|
-
nativeArch = process.arch,
|
|
1272
|
+
nativeArch = process.arch,
|
|
969
1273
|
// Where the quiet test scans (ci/gate.config.json `quietTests`) run: "local" plans them for the quiet lane; "ci" leaves them to the
|
|
970
1274
|
// CI shards (one crate per runner, where the port, pipe, desktop and wall-clock conflicts that force the serial lane do not exist)
|
|
971
1275
|
// and records a note naming them (Adrian 2026-10-22: compile locally on the warm cache, qualify the conflicting tests on VMs).
|
|
@@ -1079,12 +1383,21 @@ export function planScans({
|
|
|
1079
1383
|
files.push(f);
|
|
1080
1384
|
}
|
|
1081
1385
|
// Content digest of the input the scans cover: every accepted changed file's bytes plus every refused name.
|
|
1082
|
-
|
|
1386
|
+
// NN07: a run plans twice (check stage, compile stage) over the same snapshot; a file whose identity (path, inode, size, mtime) is unchanged is
|
|
1387
|
+
// not read and hashed again in this process (measured 2026-11-07: 1.0 s of file reads per plan of RightKit's 13,894 files).
|
|
1388
|
+
const bytesDigest = (f) => {
|
|
1389
|
+
const abs = path.join(contentRoot, f);
|
|
1390
|
+
let id = null; try { const st = fs.statSync(abs, { bigint: true }); id = `${abs}\0${st.ino}\0${st.size}\0${st.mtimeNs}`; } catch { /* read decides */ }
|
|
1391
|
+
if (id && PLAN_DIGEST_MEMO.has(id)) return PLAN_DIGEST_MEMO.get(id);
|
|
1392
|
+
let d; try { d = sha256(readBytes(abs)); } catch { return "unreadable"; }
|
|
1393
|
+
if (id) PLAN_DIGEST_MEMO.set(id, d);
|
|
1394
|
+
return d;
|
|
1395
|
+
};
|
|
1083
1396
|
const inputDigest = sha256(canonicalJson({ files: [...files].sort().map((f) => [f, bytesDigest(f)]), refused: refusals.map((r) => r.raw).sort() }));
|
|
1084
1397
|
const under = (prefix) => files.filter((f) => f.startsWith(prefix));
|
|
1085
1398
|
if (!["compile", "release"].includes(tier)) throw new Error(`planScans: tier must be compile or release, not ${JSON.stringify(tier)}`);
|
|
1086
1399
|
let scans = []; const notes = []; const qualifyOwed = [];
|
|
1087
|
-
if (cargoLiveRoot) notes.push(`broker host: class A cargo
|
|
1400
|
+
if (cargoLiveRoot) notes.push(`broker host: class A cargo reads run in the snapshot with the host's real cargo, never through the broker (GC-A11); class B compiles go to the broker as seam requests from the snapshot (reset plan section 3) when the seam is wired, else as carried requests started from the primary checkout ${cargoLiveRoot} (uncommitted edits there never reach a scan)`);
|
|
1088
1401
|
// A snapshot compile's scans carry its target map (item 7): the map is part of every scan's cache key, so no result cached by a
|
|
1089
1402
|
// live-checkout run (or a compile with another map) is taken for one that writes to these directories.
|
|
1090
1403
|
const snapshotTargets = targetDirs ? { RK_SNAPSHOT_TARGETS: canonicalJson(targetDirs) } : {};
|
|
@@ -1115,12 +1428,12 @@ export function planScans({
|
|
|
1115
1428
|
const refusedScan = (error) => ({ tool: "node", args: ["-e", `console.error(${JSON.stringify(String(error.message))}); process.exit(1)`] });
|
|
1116
1429
|
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] } } : {}) }; };
|
|
1117
1430
|
// Class B (compiles): started from the primary checkout on a broker host, the snapshot carrier names the source.
|
|
1118
|
-
const cargoIn = (ws, ...args) => ({ ...cargoBase(ws,
|
|
1431
|
+
const cargoIn = (ws, ...args) => ({ ...cargoBase(ws, args), ...(cargoLiveRoot ? { root: "cargoLive" } : {}) });
|
|
1119
1432
|
// 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
|
|
1120
1433
|
// --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
|
|
1121
1434
|
// --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
|
|
1122
1435
|
// out of: its test scan stays the one-step `test ... --locked --no-fail-fast`, compile and run together, with no runOutside.
|
|
1123
|
-
const cargoTestIn = (ws, ...args) => ({ ...cargoBase(ws, [...
|
|
1436
|
+
const cargoTestIn = (ws, ...args) => ({ ...cargoBase(ws, [...args, "--message-format=json"], { raw: true }), root: "cargoLive" });
|
|
1124
1437
|
// Class A (reads Cargo inputs, compiles nothing): always the content root, the snapshot or the commit's own tree. These still execute
|
|
1125
1438
|
// cargo (through the broker on a broker host), so a unit-scoped check follows the Rust closure for them (app-closure.mjs scopeScans reads
|
|
1126
1439
|
// the ids `cargo-metadata|cargo-deny|cargo-audit[:<label>]` and `cargo-package-list:<unit>` and the scan's `cwd`; rename one there too).
|
|
@@ -1469,10 +1782,15 @@ export function planScans({
|
|
|
1469
1782
|
// --all-features), none when a lint set already uses --all-features. Some crates' features cannot
|
|
1470
1783
|
// all be on together (rightkit-db sqlcipher vs sqlcipher-system; qa-driver wv2 generations).
|
|
1471
1784
|
const own = featuresOf(name);
|
|
1472
|
-
const
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
1785
|
+
const crate = crateOf(name);
|
|
1786
|
+
const { lintSets, baseSets, crossSets, defaultCheck, checkSets, none } = rustCratePlan(own, platform, crate);
|
|
1787
|
+
// Every feature the crate declares must be enabled by one of the sets of ANY host (the feature-coverage scan below, rightkit#1231): a host-scoped set
|
|
1788
|
+
// is linted on the host whose plan has it. `unlintedFeatures` names the features the gate never lints, each with its reason.
|
|
1789
|
+
const unlinted = unlintedFeatures(own, crate);
|
|
1790
|
+
coverageCrates.push({ name, manifest: inDir(rustDir(name), "Cargo.toml"), sets: rustCoverageSets(own, crate), ...(Object.keys(unlinted).length ? { unlinted } : {}) });
|
|
1791
|
+
// Every set the crate declares is scoped to other hosts (ci/gate.config.json featureSets hosts): no compile row here, as for a crate scoped by `platforms`.
|
|
1792
|
+
if (none) { notes.push(`${crate}: every declared feature set is scoped to other hosts (ci/gate.config.json featureSets hosts); its compile scans are not planned on ${platform}`); continue; }
|
|
1793
|
+
const ws = wsOf(name);
|
|
1476
1794
|
// `cargo clippy --all-targets` type-checks exactly what `cargo check --all-targets` does: the default
|
|
1477
1795
|
// check runs only when no clippy set covers default features.
|
|
1478
1796
|
if (defaultCheck) add({ id: rustScanId.check(name), class: B, batchUnit: name, ...cargoIn(ws, ...checkArgs(crate, { locked: true })) });
|
|
@@ -1482,10 +1800,11 @@ export function planScans({
|
|
|
1482
1800
|
// The other two OS targets, every lint set, -D warnings, on every host (cross-targets.mjs; Adrian 2026-11-02/03, no skip). The zig C
|
|
1483
1801
|
// toolchain must be provisioned (crossCcDir); without it the scan fails naming the fix, never skipped. On a broker host the broker must
|
|
1484
1802
|
// admit the cross target and its CC_/CXX_/AR_ variables; a refusal there fails the scan.
|
|
1803
|
+
// A host-scoped feature set is a native-host set and has no cross-target row (feature-sets.mjs): `crossSets` holds the unscoped ones, each keeping its index among the declared sets.
|
|
1485
1804
|
for (const target of scopedCrossTargets(own, platform)) {
|
|
1486
1805
|
const crossEnv = crossCompileEnv(target);
|
|
1487
|
-
|
|
1488
|
-
const id = `${rustScanId.clippy(name, baseSets.length,
|
|
1806
|
+
crossSets.forEach((set) => {
|
|
1807
|
+
const id = `${rustScanId.clippy(name, baseSets.length, baseSets.indexOf(set))}@${target}`;
|
|
1489
1808
|
if (!crossEnv) { add({ id, class: B, tool: "node", args: ["-e", `console.error("RK_CROSS_CC_UNPROVISIONED: the zig C toolchain for ${target} is not provisioned; run node scripts/ci/provision-zig.mjs <managed data root>/zig (or set RIGHTKIT_CROSS_CC_DIR)"); process.exit(1)`] }); return; }
|
|
1490
1809
|
const scan = cargoIn(ws, ...clippyArgs(crate, { features: set, locked: true, target }));
|
|
1491
1810
|
add({ id, class: B, batchUnit: name, ...scan, env: { ...(scan.env ?? {}), ...crossEnv } });
|
|
@@ -1501,7 +1820,7 @@ export function planScans({
|
|
|
1501
1820
|
}
|
|
1502
1821
|
// Class A, file-only (rightkit#1231): no feature of a crate's Cargo.toml may be left out of every planned feature set, so feature-gated code is never
|
|
1503
1822
|
// unchecked. Crates without Cargo features need no row.
|
|
1504
|
-
const featureful = coverageCrates.filter((c) => { const t = manifestTextOf(c.name); return typeof t === "string" && declaredFeatureNames(t).length > 0; });
|
|
1823
|
+
const featureful = coverageCrates.filter((c) => { const t = manifestTextOf(c.name); return typeof t === "string" && (declaredFeatureNames(t).length > 0 || c.unlinted !== undefined); });
|
|
1505
1824
|
if (featureful.length) add({ id: "feature-coverage", class: A, internal: "feature-coverage", crates: featureful });
|
|
1506
1825
|
if (clippyBatching && clippyEntries.length) {
|
|
1507
1826
|
// One Clippy scan per batch (row 8.6): the independent batches first, the sidecar-bound ones after them (row 8.8; the compile lane
|
|
@@ -1629,7 +1948,8 @@ export function planScans({
|
|
|
1629
1948
|
for (const name of crateNames) {
|
|
1630
1949
|
if (outOfScope(name)) continue;
|
|
1631
1950
|
const own = featuresOf(name);
|
|
1632
|
-
const sets = rustCratePlan(own).baseSets;
|
|
1951
|
+
const sets = rustCratePlan(own, platform, crateOf(name)).baseSets;
|
|
1952
|
+
if (!sets.length) continue; // every declared set is scoped to other hosts (hosts): no test row on this host
|
|
1633
1953
|
const quiet = own.quietTests === true ? { quiet: true } : {};
|
|
1634
1954
|
if (own.quietTests === true && quietTests === "ci") {
|
|
1635
1955
|
deferredToCi.push(...sets.map((set, i) => rustScanId.testRust(name, sets.length, i)), ...(own.alsoSerial ? sets.map((set, i) => rustScanId.testRustSerial(name, sets.length, i)) : []));
|
|
@@ -1642,7 +1962,7 @@ export function planScans({
|
|
|
1642
1962
|
// 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
1963
|
// 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
1964
|
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")) });
|
|
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")) });
|
|
1965
|
+
if (own.alsoSerial) add({ id: rustScanId.testRustSerial(name, sets.length, i), class: B, ...quiet, ...(e2e ? { e2e: true, ...(cargoLiveRoot ? { reuseExecutables: rustScanId.testRust(name, sets.length, i) } : {}) } : {}), ...(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"] }, reuseExecutables: rustScanId.testRust(name, sets.length, i) } : cargoIn(wsOf(name), "test", "-p", crateOf(name), ...set, "--locked", "--no-fail-fast", "--", "--test-threads=1")) });
|
|
1646
1966
|
});
|
|
1647
1967
|
}
|
|
1648
1968
|
for (const name of pkgNames) {
|
|
@@ -1754,14 +2074,31 @@ export function planScans({
|
|
|
1754
2074
|
else if (shardSolo.includes(unit) || shardSolo.includes(crateOf(unit))) why = "ci/shards.json solo";
|
|
1755
2075
|
else if (clippySeparate instanceof Map && clippySeparate.has(unit)) why = String(clippySeparate.get(unit));
|
|
1756
2076
|
else if (sidecarBoundCrate({ dir: path.join(contentRoot, rustDir(unit)), exists, readFile }).bound) why = "sidecar-bound";
|
|
1757
|
-
|
|
1758
|
-
|
|
2077
|
+
// NN42 (LOCKED 2026-11-06): one check/clippy per stage names every --target. The target is not part of the group key: rows that differ only
|
|
2078
|
+
// in their `--target <triple>` and that triple's own variables (CC_/CXX_/AR_/PKG_CONFIG_/RC_<triple>) share a key, and runScans runs crates
|
|
2079
|
+
// with the same set of targets as ONE invocation naming all of them, so Cargo overlaps the triples' graphs under one build lock.
|
|
2080
|
+
const ti = rest.indexOf("--target");
|
|
2081
|
+
const target = ti >= 0 && typeof rest[ti + 1] === "string" ? rest[ti + 1] : null;
|
|
2082
|
+
const tripleKey = target ? target.replace(/-/g, "_") : null;
|
|
2083
|
+
const keyRest = target ? [...rest.slice(0, ti), "--target", "*", ...rest.slice(ti + 2)] : rest;
|
|
2084
|
+
const keyEnv = target ? Object.fromEntries(Object.entries(x.env ?? {}).filter(([k]) => !(k.endsWith(`_${tripleKey}`) || k.toUpperCase().endsWith(`_${tripleKey.toUpperCase()}`)))) : x.env;
|
|
2085
|
+
if (why) {
|
|
2086
|
+
batchNotes.set(why, (batchNotes.get(why) ?? 0) + 1);
|
|
2087
|
+
// A row that cannot join other crates (its own features, solo, separate, sidecar-bound) still names every target with its own crate's
|
|
2088
|
+
// other target rows: the key keeps the crate, so only this crate's rows that differ by --target share an invocation (Mac 2026-11-07:
|
|
2089
|
+
// rightkit-tauri-shell's feature sets ran one target at a time, 1.8 rows/min).
|
|
2090
|
+
if (!target || at < 0 || typeof crate !== "string") return plain;
|
|
2091
|
+
const ownKey = sha256(canonicalJson({ tool: x.tool, cwd: x.cwd ?? ".", root: x.root, env: keyEnv, rest: keyRest, at, crate, only: "targets" })).slice(0, 16);
|
|
2092
|
+
groupCount.set(ownKey, (groupCount.get(ownKey) ?? 0) + 1);
|
|
2093
|
+
return { ...plain, batchable: { key: ownKey, at, crate, unit, target } };
|
|
2094
|
+
}
|
|
2095
|
+
const key = sha256(canonicalJson({ tool: x.tool, cwd: x.cwd ?? ".", root: x.root, env: keyEnv, rest: keyRest, at })).slice(0, 16);
|
|
1759
2096
|
groupCount.set(key, (groupCount.get(key) ?? 0) + 1);
|
|
1760
|
-
return { ...plain, batchable: { key, at, crate, unit } };
|
|
2097
|
+
return { ...plain, batchable: { key, at, crate, unit, ...(target ? { target } : {}) } };
|
|
1761
2098
|
});
|
|
1762
2099
|
if (groupCount.size) {
|
|
1763
2100
|
const grouped = [...groupCount.values()].filter((n) => n > 1);
|
|
1764
|
-
notes.push(`class B batching: ${scans.filter((x) => x.batchable).length} compile scan(s) in ${groupCount.size} configuration group(s); each group of one Cargo workspace and target runs as one cargo invocation (${grouped.reduce((a, n) => a + n, 0)} scan(s) in ${grouped.length} shared group(s)), a failed group is
|
|
2101
|
+
notes.push(`class B batching: ${scans.filter((x) => x.batchable).length} compile scan(s) in ${groupCount.size} configuration group(s); each group of one Cargo workspace and target runs as one cargo invocation (${grouped.reduce((a, n) => a + n, 0)} scan(s) in ${grouped.length} shared group(s)), a failed group is attributed per crate from cargo's JSON messages, every row keeps its own id and command; before a group runs, each member's own feature resolution is compared with the group's (cargo tree, feature-partition.mjs; GATE-CONTRACT GC-A18) and a member the group would compile with other features runs apart`);
|
|
1765
2102
|
for (const [why, n] of batchNotes) notes.push(`class B batching: ${n} compile scan(s) stay their own invocation: ${why}`);
|
|
1766
2103
|
}
|
|
1767
2104
|
const ids = scans.map((s) => s.id);
|
|
@@ -1916,10 +2253,12 @@ export function defaultSpawnAsync(command, args, options = {}) {
|
|
|
1916
2253
|
let child;
|
|
1917
2254
|
try {
|
|
1918
2255
|
// stdin is closed: no scan reads it, and an open pipe nobody writes can block a tool that probes it (Windows).
|
|
1919
|
-
// A detached child (POSIX
|
|
1920
|
-
child =
|
|
2256
|
+
// A detached child (POSIX) has its own process group, which the abort kill signals.
|
|
2257
|
+
child = spawnChild(inv.file, inv.args, { windowsHide: true, windowsVerbatimArguments: inv.verbatim, stdio: ["ignore", "pipe", "pipe"], ...(signal && process.platform !== "win32" ? { detached: true } : {}), ...rest, shell: false, stdio: ["ignore", "pipe", "pipe"] });
|
|
1921
2258
|
} catch (e) { resolve({ status: null, stdout: "", stderr: "", error: e }); return; }
|
|
1922
2259
|
if (onSpawn && child.pid) onSpawn(child.pid);
|
|
2260
|
+
// A detached group is recorded beside the held snapshot lock until it exits, so a crashed gate's leftover group keeps the lock (snapshot.mjs recordLockChild).
|
|
2261
|
+
if (child.pid && process.platform !== "win32" && signal) { try { recordLockChild(child); } catch (e) { resolve({ status: null, stdout: "", stderr: "", error: e }); return; } }
|
|
1923
2262
|
const onAbort = () => killProcessTree(child);
|
|
1924
2263
|
signal?.addEventListener("abort", onAbort, { once: true });
|
|
1925
2264
|
child.stdout.setEncoding("utf8"); child.stderr.setEncoding("utf8");
|
|
@@ -2070,7 +2409,7 @@ export function summarizeCargoJson(text) {
|
|
|
2070
2409
|
|
|
2071
2410
|
/**
|
|
2072
2411
|
* The per-crate verdicts of a failed grouped doc invocation, from its JSON summary: `[{ unit, fail, detail }]` in member order, or null when the messages
|
|
2073
|
-
* cannot attribute (no records, or no member reported an artifact, so "no artifact" would prove nothing):
|
|
2412
|
+
* cannot attribute (no records, or no member reported an artifact, so "no artifact" would prove nothing): every member then carries the group's failure; nothing is bisected.
|
|
2074
2413
|
*/
|
|
2075
2414
|
export function docVerdicts(summary, units, crates) {
|
|
2076
2415
|
if (!summary || !(summary.records > 0) || !Array.isArray(units) || units.length !== crates.length) return null;
|
|
@@ -2123,6 +2462,22 @@ const insideDir = (real, dirReal, platform) => {
|
|
|
2123
2462
|
return rel !== "" && !mod.isAbsolute(rel) && rel.split(/[\\/]/)[0] !== "..";
|
|
2124
2463
|
};
|
|
2125
2464
|
|
|
2465
|
+
/** The leaf directory names of a managed generation target (`<root>/<12 hex>/g/<NNN>/<leaf>`). */
|
|
2466
|
+
const GENERATION_LEAVES = Object.freeze(["target", "t"]);
|
|
2467
|
+
const isGenerationLeaf = (segment) => GENERATION_LEAVES.includes(segment);
|
|
2468
|
+
/**
|
|
2469
|
+
* Whether `dir` is a managed generation target or a directory inside one, under one of the broker's managed `ws` roots (`<data root>/build-control/ws`): the shape the broker
|
|
2470
|
+
* pins an app's outputs to (the 12-hex key is rustright-state's workspace key, which the gate never computes; the generation number, 3 or more digits, is the broker's).
|
|
2471
|
+
*/
|
|
2472
|
+
export function isInsideGenerationTarget(dir, outputRoots, platform = process.platform) {
|
|
2473
|
+
const mod = platform === "win32" ? path.win32 : path;
|
|
2474
|
+
for (const root of outputRoots) {
|
|
2475
|
+
const rel = mod.relative(platform === "win32" ? mod.resolve(root).toLowerCase() : mod.resolve(root), platform === "win32" ? mod.resolve(dir).toLowerCase() : mod.resolve(dir));
|
|
2476
|
+
const segments = rel.split(/[\\/]/);
|
|
2477
|
+
if (segments.length >= 4 && segments[0] !== ".." && !mod.isAbsolute(rel) && /^[0-9a-f]{12}$/.test(segments[0]) && segments[1] === "g" && /^[0-9]{3,}$/.test(segments[2]) && isGenerationLeaf(segments[3])) return true;
|
|
2478
|
+
}
|
|
2479
|
+
return false;
|
|
2480
|
+
}
|
|
2126
2481
|
/**
|
|
2127
2482
|
* Every test executable must be a regular file whose real path is inside the verified output directory (`boundDirs`: the receipt's
|
|
2128
2483
|
* outputDir on a broker host, the scan's bound target directory otherwise); with `generationRoots` its lexical directory must also be a
|
|
@@ -2274,15 +2629,15 @@ export function scanTimeoutMs(scan, options = {}) {
|
|
|
2274
2629
|
}
|
|
2275
2630
|
|
|
2276
2631
|
/**
|
|
2277
|
-
* A scan the broker carries (rightkit#1367 step 2): on a broker host (`brokerHost`; a
|
|
2278
|
-
* (only
|
|
2279
|
-
*
|
|
2280
|
-
* run clock, the
|
|
2632
|
+
* A scan the broker carries (rightkit#1367 step 2): on a broker host (`brokerHost`; a seam run implies one) a cargo or rustright scan, a Swift package build
|
|
2633
|
+
* (only on a seam run: a Swift scan with no seam is a local process), and an npm or node suite that declares a broker call (`brokerCall`: its compiles are
|
|
2634
|
+
* seam calls). The broker queues and orders these; the gate neither counts them nor puts a clock on their queue time. This is the ONE test: the scheduler, the
|
|
2635
|
+
* run clock, the seam route (`viaSeam`) and the Swift seam route (`swiftBrokered`) all derive from it.
|
|
2281
2636
|
*/
|
|
2282
|
-
export function isBrokerCarriedScan(scan, { brokerHost = false,
|
|
2283
|
-
if (brokerHost !== true && !
|
|
2637
|
+
export function isBrokerCarriedScan(scan, { brokerHost = false, seam = false } = {}) {
|
|
2638
|
+
if (brokerHost !== true && !seam) return false;
|
|
2284
2639
|
if (scan?.tool === "rustright" || scan?.tool === "cargo") return true;
|
|
2285
|
-
if (scan?.tool === "swift") return Boolean(
|
|
2640
|
+
if (scan?.tool === "swift") return Boolean(seam);
|
|
2286
2641
|
return Boolean(scan?.brokerCall);
|
|
2287
2642
|
}
|
|
2288
2643
|
|
|
@@ -2367,7 +2722,11 @@ const FAILURE_LINE = /(^|[\s\[])(FAILED|panicked at|error(\[E\d+\])?:|error\[|^f
|
|
|
2367
2722
|
export function failureDetail(r) {
|
|
2368
2723
|
const lines = (text) => String(text ?? "").split(/\r?\n/).map((l) => l.trimEnd()).filter((l) => l.trim());
|
|
2369
2724
|
const out = lines(r?.stdout); const err = lines(r?.stderr);
|
|
2370
|
-
|
|
2725
|
+
// Compiler errors lead: a warning's quoted tool output (rustc's "warning: linker stderr: cc: error: ...") also matches, and listed first it hid
|
|
2726
|
+
// the real errors (Mac 2026-11-07: four rows read as a broker sandbox failure; the errors were unresolved imports and a cmake archiver).
|
|
2727
|
+
const hits = [...out, ...err].filter((l) => FAILURE_LINE.test(l));
|
|
2728
|
+
const quoted = (l) => /^\s*(warning:|\|)/.test(l) || /warning: linker std(err|out)/.test(l);
|
|
2729
|
+
const named = [...hits.filter((l) => !quoted(l)), ...hits.filter(quoted)].slice(0, 12);
|
|
2371
2730
|
const ends = [...out.slice(-4), ...err.slice(-4)];
|
|
2372
2731
|
// `cargo audit` / `cargo deny` without the cargo-audit / cargo-deny binary: cargo's own "no such command" text told a reader to
|
|
2373
2732
|
// search crates.io; the scan's tool is required and missing, which is what actionlint's row already says (E2E L9-02).
|
|
@@ -2626,7 +2985,7 @@ const INTERNAL = {
|
|
|
2626
2985
|
return [`${s.dir === "." ? "swift package" : s.dir}: the Swift type-check did not complete (exit ${r?.status ?? "none"}) and printed no Swift diagnostic: ${failureDetail(r)}`];
|
|
2627
2986
|
},
|
|
2628
2987
|
// Every Cargo feature of a planned crate is enabled by one of its planned feature sets (feature-coverage.mjs, rightkit#1231).
|
|
2629
|
-
"feature-coverage": (s, ctx) => s.crates.flatMap((c) => featureCoverageProblems({ name: c.name, manifestText: ctx.read(c.manifest), sets: c.sets })),
|
|
2988
|
+
"feature-coverage": (s, ctx) => s.crates.flatMap((c) => featureCoverageProblems({ name: c.name, manifestText: ctx.read(c.manifest), sets: c.sets, unlinted: c.unlinted })),
|
|
2630
2989
|
// File-only SwiftPM lockfile check (swift-lock.mjs): runs no SwiftPM, reads Package.swift / project.pbxproj and Package.resolved as committed.
|
|
2631
2990
|
"swift-lock": (s, ctx) => {
|
|
2632
2991
|
const exists = (f) => ctx.deps.exists(path.join(ctx.contentRoot, f));
|
|
@@ -2711,13 +3070,6 @@ const INTERNAL = {
|
|
|
2711
3070
|
/** A span for a message: whole seconds under a minute, minutes from then on. */
|
|
2712
3071
|
export const spanText = (ms) => (ms < 60_000 ? `${Math.max(0, Math.round(ms / 1000))} s` : `${Math.round(ms / 60_000)} min`);
|
|
2713
3072
|
export const scanOperationDeadlineMs = (limitMs) => Math.max(Math.floor(limitMs / 2), limitMs - 20_000);
|
|
2714
|
-
/**
|
|
2715
|
-
* What a carried Swift scan gives carryBrokerAdapterAsync: an UNWATCHED one passes its own limit as the client's operation deadline (the env, and `deadlineMs`, which also bounds the
|
|
2716
|
-
* retry wait); a watched one passes neither (the stopwatch and the ceiling bound it, and the client's deadline is absolute from its start).
|
|
2717
|
-
*/
|
|
2718
|
-
export function carriedCallBudget({ env, limitMs, watched }) {
|
|
2719
|
-
return watched ? { env: {} } : { env: scanOperationEnv(env, limitMs), deadlineMs: scanOperationDeadlineMs(limitMs) };
|
|
2720
|
-
}
|
|
2721
3073
|
export function scanOperationEnv(env, limitMs) {
|
|
2722
3074
|
const deadline = operationDeadlineEnv({ env, deadlineMs: scanOperationDeadlineMs(limitMs) });
|
|
2723
3075
|
if (Object.keys(deadline).length === 0) return {};
|
|
@@ -2774,6 +3126,7 @@ export async function runScans(plan, options = {}) {
|
|
|
2774
3126
|
...options,
|
|
2775
3127
|
};
|
|
2776
3128
|
const classes = options.classes ?? [SCAN_CLASS.A, SCAN_CLASS.B];
|
|
3129
|
+
if (deps.gateSeam) seamRunState.open += 1; // lowered only after this run counted its seam rows (below)
|
|
2777
3130
|
const exclude = options.exclude ?? (() => false);
|
|
2778
3131
|
// An AbortSignal: once aborted, no further scan starts, running children are killed (process tree) and every unfinished scan is "not-run" with code CANCELLED.
|
|
2779
3132
|
const signal = options.signal; const sig = signal ? { signal } : {};
|
|
@@ -2787,27 +3140,27 @@ export async function runScans(plan, options = {}) {
|
|
|
2787
3140
|
// `trackedFiles` (the gate's list of the commit's own files): where the content root is not a git toplevel (a snapshot), the secret scan judges
|
|
2788
3141
|
// exactly these and never what a stage wrote there (rightkit#1393).
|
|
2789
3142
|
const ctx = { deps, contentRoot, liveRoot, cargoLiveRoot, tmpRoot, read: (f) => deps.readFile(path.join(contentRoot, f)), trackedFiles: Array.isArray(options.trackedFiles) ? options.trackedFiles : null };
|
|
2790
|
-
// GATE-CONTRACT GC-A11 (Adrian, 2026-11-02): Class A never runs in the broker. Class A cargo reads are never
|
|
2791
|
-
//
|
|
2792
|
-
|
|
2793
|
-
|
|
2794
|
-
const
|
|
2795
|
-
|
|
2796
|
-
|
|
2797
|
-
const brokerLive = options.brokerLive ?? (brokerHost && typeof deps.snapshotBroker?.client === "string" ? createBrokerLive({ client: deps.snapshotBroker.client, env: deps.env, spawn: defaultSpawnAsync, platform: deps.platform }) : null);
|
|
3143
|
+
// GATE-CONTRACT GC-A11 (Adrian, 2026-11-02): Class A never runs in the broker. Class A cargo reads are never sent to it, in any stage; the gate runs them directly
|
|
3144
|
+
// (snapshot-metadata.mjs directReadSpawn), and cargo-deny / cargo-audit are its own enrolled tools.
|
|
3145
|
+
// A broker host: the gate says so (options.brokerHost, from its executor) and a seam run implies it. One predicate (isBrokerCarriedScan) names the scans the broker carries.
|
|
3146
|
+
const brokerHost = options.brokerHost === true || Boolean(deps.gateSeam);
|
|
3147
|
+
const carriedCtx = { brokerHost, seam: Boolean(deps.gateSeam) };
|
|
3148
|
+
// The broker's live state of a request (queued or running), through an ASYNCHRONOUS client call: the gate's own reader (options.brokerLive), or none.
|
|
3149
|
+
const brokerLive = options.brokerLive ?? null;
|
|
2798
3150
|
// 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.
|
|
2799
3151
|
const pollMs = options.brokerPollMs ?? ADMISSION_POLL_MS;
|
|
2800
3152
|
const statusPoller = brokerLive ? createStatusPoller({ live: brokerLive, intervalMs: pollMs }) : null;
|
|
2801
3153
|
const toolVersions = {}; const toolIdentities = {}; const advisoryDbs = new Map();
|
|
2802
3154
|
const results = [];
|
|
2803
|
-
// Failed grouped invocations
|
|
2804
|
-
// member row (`batchFailure`), so a combined failure stays visible
|
|
3155
|
+
// Failed grouped invocations attributed per crate from their JSON diagnostics (runGroup below): retained as run notes and on each
|
|
3156
|
+
// member row (`batchFailure`), so a combined failure stays visible next to each crate's own verdict.
|
|
2805
3157
|
const batchFailureNotes = [];
|
|
2806
3158
|
// The gate-owned cargo ledger of a wrapped snapshot compile (options.cargoLedger = { dir }): every call the wrapper decided, filed
|
|
2807
|
-
// under its scan's token.
|
|
3159
|
+
// under its scan's token.
|
|
2808
3160
|
const cargoLedger = options.cargoLedger?.dir ? options.cargoLedger : null;
|
|
2809
|
-
const claimedTokens = new Set();
|
|
3161
|
+
const claimedTokens = new Set();
|
|
2810
3162
|
// options.cache ={ read(key), write(key, row), digest(scan) => string | null } (null: not cacheable, which is how the live class A checks opt out).
|
|
3163
|
+
const probeScans = new WeakSet(); // scans looked up for runGroup's per-crate cache (answered like a lookup, never run)
|
|
2811
3164
|
const cache = options.cache && typeof options.cache.read === "function" && typeof options.cache.write === "function" && typeof options.cache.digest === "function" ? options.cache : null;
|
|
2812
3165
|
const cacheHits = [];
|
|
2813
3166
|
// The GitHub advisory scan's same-UTC-day answers live beside the pinned RustSec checkout; a run with no cache (the door's live-scans refresh) asks again.
|
|
@@ -2926,6 +3279,29 @@ export async function runScans(plan, options = {}) {
|
|
|
2926
3279
|
// Class A may run concurrently. Class B runs one scan per component at a time, `classBJobs` components at once (below).
|
|
2927
3280
|
const aScans = ordered.filter((s) => s.class === SCAN_CLASS.A);
|
|
2928
3281
|
const bScans = ordered.filter((s) => s.class === SCAN_CLASS.B);
|
|
3282
|
+
const partitionNotes = new Set(); // GC-A18: why a crate compiled apart from its configuration group (feature-partition.mjs)
|
|
3283
|
+
// The seam (reset plan section 3; gate-seam.mjs): one Class A verdict per workspace at this commit, written only once every planned Class A row of
|
|
3284
|
+
// this run passed; a class-B-only run (classAEarlier) reads the root verdict its class A run wrote under the same deterministic name and derives a
|
|
3285
|
+
// nested workspace's from it. `deps.gateSeam` = { commit, tree, repoKey, snapshot, verdictDir, outputRoots }.
|
|
3286
|
+
// Settled rows by id, for a row that depends on another's result in this process (rightkit#1539: the serial test row runs the plain row's executables). A waiter
|
|
3287
|
+
// that is not answered within its time gets null and goes its own way; nothing blocks forever.
|
|
3288
|
+
const plannedIds = new Set(bScans.map((x) => x.id)); // the class B rows of this run: a serial row waits only for a plain row that is in it
|
|
3289
|
+
const settledRows = new Map(); const rowWaiters = new Map();
|
|
3290
|
+
const settle = (id, row) => { settledRows.set(id, row); const waiters = rowWaiters.get(id); if (waiters) { rowWaiters.delete(id); for (const w of waiters) w(row); } };
|
|
3291
|
+
const waitForRow = (id, ms) => (settledRows.has(id) ? Promise.resolve(settledRows.get(id)) : new Promise((resolve) => {
|
|
3292
|
+
const done = (row) => { clearTimeout(timer); resolve(row); };
|
|
3293
|
+
const timer = setTimeout(() => { const waiters = rowWaiters.get(id); if (waiters) rowWaiters.set(id, waiters.filter((w) => w !== done)); resolve(null); }, Math.max(1, ms));
|
|
3294
|
+
if (!rowWaiters.has(id)) rowWaiters.set(id, []);
|
|
3295
|
+
rowWaiters.get(id).push(done);
|
|
3296
|
+
}));
|
|
3297
|
+
const verdictFiles = new Map();
|
|
3298
|
+
const ensureVerdict = (cwd) => {
|
|
3299
|
+
const ws = normalizeWorkspace(cwd ?? ".");
|
|
3300
|
+
// One function decides (gate-seam.mjs verdictForRun): a run that ran class A writes the verdict of its own scope from its own rows; a class-B-only run reads
|
|
3301
|
+
// the verdict of its scope, or a full one, and never another scope's (fresh review 2026-11-09, E1; the scope is in the file name and the verdict).
|
|
3302
|
+
if (!verdictFiles.has(ws)) verdictFiles.set(ws, (async () => verdictForRun({ seam: deps.gateSeam, workspace: ws, classARows: classes.includes(SCAN_CLASS.A) ? results.filter((r) => r.class === SCAN_CLASS.A).map((r) => ({ id: r.id, status: r.status })) : null }))());
|
|
3303
|
+
return verdictFiles.get(ws);
|
|
3304
|
+
};
|
|
2929
3305
|
// Class A scans are independent content checks (and short broker calls: metadata, package list, deny, audit): they run
|
|
2930
3306
|
// `classAJobs` at a time (default: `jobs`); the rows keep plan order. Class B starts only once every class A row is in.
|
|
2931
3307
|
const aJobs = Math.max(1, Number(options.classAJobs ?? jobs) || jobs);
|
|
@@ -2985,33 +3361,142 @@ export async function runScans(plan, options = {}) {
|
|
|
2985
3361
|
// 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
|
|
2986
3362
|
// 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
|
|
2987
3363
|
// 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
|
|
2988
|
-
// ledger token, signed broker receipt and run limit. A cargo failure (code EXIT: a compile diagnostic) is
|
|
2989
|
-
//
|
|
2990
|
-
//
|
|
2991
|
-
//
|
|
2992
|
-
//
|
|
2993
|
-
// proof that every member passes alone; the plan notes say the equivalence run has not been done.
|
|
3364
|
+
// ledger token, signed broker receipt and run limit. A cargo failure (code EXIT: a compile diagnostic) is attributed per crate from the invocation's own
|
|
3365
|
+
// `--message-format=json` diagnostics (docVerdicts: a crate with an error message fails, a crate with no artifact while another member has one fails, the rest pass);
|
|
3366
|
+
// nothing is bisected (store rule, GC-A18). Any other failure (a refused or unverified receipt, a timeout, a missing tool) is the group's and is not retried:
|
|
3367
|
+
// running it N times would repeat it N times. Feature unification: one invocation unifies features across its crates, so before a group runs the planner
|
|
3368
|
+
// resolves each member alone and in the group with `cargo tree` (feature-partition.mjs) and keeps in one invocation only the members the group resolves as they resolve alone.
|
|
2994
3369
|
const groupOf = new Map();
|
|
2995
3370
|
if (options.classBBatching === true) {
|
|
2996
3371
|
const byKey = new Map();
|
|
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); } });
|
|
2998
|
-
for (const
|
|
3372
|
+
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) || s.publisherRustTest === true)))) { if (!byKey.has(s.batchable.key)) byKey.set(s.batchable.key, []); byKey.get(s.batchable.key).push(i); } });
|
|
3373
|
+
for (const all of byKey.values()) {
|
|
3374
|
+
// NN42: within one key, crates with the same set of targets form one invocation (crates x targets is exactly its members).
|
|
3375
|
+
const targetsOf = new Map();
|
|
3376
|
+
for (const i of all) { const c = bScans[i].batchable.crate; if (!targetsOf.has(c)) targetsOf.set(c, new Set()); targetsOf.get(c).add(bScans[i].batchable.target ?? ""); }
|
|
3377
|
+
const parts = new Map();
|
|
3378
|
+
// One target per invocation (2026-11-10, HeardRight on the Dell): Cargo resolves features for host dependencies and target dependencies, never per triple, so a
|
|
3379
|
+
// call naming two targets gives each the union of both targets' features (the macOS-only sqlcipher-system reached the Linux target, whose C code then wanted
|
|
3380
|
+
// OpenSSL headers). Rows are grouped across crates for the SAME target; a crate's rows for different targets are never one invocation.
|
|
3381
|
+
void targetsOf;
|
|
3382
|
+
for (const i of all) { const sig = bScans[i].batchable.target ?? ""; if (!parts.has(sig)) parts.set(sig, []); parts.get(sig).push(i); }
|
|
3383
|
+
for (const members of parts.values()) if (members.length > 1) { const group = { members, promise: null }; for (const i of members) groupOf.set(i, group); }
|
|
3384
|
+
}
|
|
2999
3385
|
}
|
|
3000
3386
|
const batchScanOf = (idx) => {
|
|
3001
3387
|
const lead = bScans[idx[0]];
|
|
3002
3388
|
const { batchable: _batchable, ...plain } = lead; void _batchable;
|
|
3003
|
-
|
|
3004
|
-
|
|
3005
|
-
const
|
|
3006
|
-
const
|
|
3389
|
+
// A group that holds a plan row standing for a publisher requirement stores and returns the receipt its members' publisher verdicts need (NN27, planUnitListScans).
|
|
3390
|
+
if (idx.some((i) => bScans[i].provesPublisher === true)) plain.provesPublisher = true;
|
|
3391
|
+
const crates = [...new Set(idx.map((i) => bScans[i].batchable.crate))];
|
|
3392
|
+
const targets = [...new Set(idx.map((i) => bScans[i].batchable.target).filter(Boolean))];
|
|
3393
|
+
let args = [...lead.args.slice(0, lead.batchable.at), ...crates.flatMap((c) => ["-p", c]), ...lead.args.slice(lead.batchable.at + 2)];
|
|
3394
|
+
// Benchmark-only merged feature rows: drop the lead's own feature flags and name every member's features as <crate>/<feature>.
|
|
3395
|
+
if (idx.some((i) => Array.isArray(bScans[i].batchable.features))) {
|
|
3396
|
+
const all = [...new Set(idx.flatMap((i) => bScans[i].batchable.features ?? []))];
|
|
3397
|
+
const stop = args.indexOf("--") < 0 ? args.length : args.indexOf("--");
|
|
3398
|
+
const out = []; for (let i = 0; i < args.length; i += 1) { const w = args[i]; if (i < stop && (w === "--features" || w === "-F")) { i += 1; continue; } if (i < stop && /^(?:--features=|-F.)/.test(w)) continue; out.push(w); }
|
|
3399
|
+
const cut = out.indexOf("--"); args = all.length ? (cut < 0 ? [...out, "--features", all.join(",")] : [...out.slice(0, cut), "--features", all.join(","), ...out.slice(cut)]) : out;
|
|
3400
|
+
}
|
|
3401
|
+
if (targets.length > 1) { const t = args.indexOf("--target"); if (t >= 0) args = [...args.slice(0, t), ...targets.flatMap((x) => ["--target", x]), ...args.slice(t + 2)]; }
|
|
3402
|
+
if (targets.length > 1) plain.env = Object.assign({}, ...idx.map((i) => bScans[i].env ?? {}));
|
|
3403
|
+
const units = [...new Set(idx.map((i) => bScans[i].batchable.unit))].map((u) => targets.length > 1 ? u : u);
|
|
3404
|
+
const memberKey = idx.map((i) => `${bScans[i].batchable.unit}@${bScans[i].batchable.target ?? ""}`);
|
|
3405
|
+
// A publisher row (a unit-list run) is named by its cargo subcommand, a plan row by its id.
|
|
3406
|
+
const sub = lead.publisherPhase ? lead.args[lead.args[0] === "cargo" ? 1 : 0] : null;
|
|
3407
|
+
const stage = sub ? (sub === "clippy" ? "clippy" : sub === "doc" ? "doc" : sub === "test" ? "test" : "check") : /^clippy/.test(lead.id) ? "clippy" : /^doc:/.test(lead.id) ? "doc" : /^test:rust/.test(lead.id) ? "test" : "check";
|
|
3408
|
+
const jsonMessages = args.some((a) => /^--message-format=json/.test(a)); // a publisher row already asks for cargo's JSON messages (json-render-diagnostics)
|
|
3409
|
+
const id = `${stage}:batch:${sha256(`${lead.batchable.key}\0${memberKey.join("\0")}`).slice(0, 8)}`;
|
|
3007
3410
|
// A doc group asks for cargo's JSON messages (NN40): each crate's verdict is read from them (docVerdicts), never found by bisection.
|
|
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) } }; }
|
|
3411
|
+
if (stage === "doc") { const jargs = jsonMessages ? args : [...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
3412
|
// NN17/NN39: a test group compiles once (one broker command naming every crate) and each member's own test executables then run in
|
|
3010
3413
|
// parallel outside the broker; each member keeps its own verdict (runOne `testGroup`, memberRuns).
|
|
3011
3414
|
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) } };
|
|
3415
|
+
// NN40 for check and clippy too (Mac 2026-11-07: one crate's Linux error failed a 186-crate batch whole): the group asks for cargo's JSON messages,
|
|
3416
|
+
// so each crate's verdict is read from them (docVerdicts: its own errors, or no artifact because a dependency failed), never one verdict for all.
|
|
3417
|
+
if (jsonMessages) return { ...plain, id, args, captureJson: true, command: commandText({ ...plain, env: {}, args }), batch: { units, members: idx.map((i) => bScans[i].id) } };
|
|
3418
|
+
if (!args.some((a) => /^--message-format/.test(a))) {
|
|
3419
|
+
const cut = args.indexOf("--"); const jargs = cut < 0 ? [...args, "--message-format=json"] : [...args.slice(0, cut), "--message-format=json", ...args.slice(cut)];
|
|
3420
|
+
return { ...plain, id, args: jargs, captureJson: true, command: commandText({ ...plain, env: {}, args: jargs }), batch: { units, members: idx.map((i) => bScans[i].id) } };
|
|
3421
|
+
}
|
|
3012
3422
|
return { ...plain, id, args, command: commandText({ ...plain, env: {}, args }), batch: { units, members: idx.map((i) => bScans[i].id) } };
|
|
3013
3423
|
};
|
|
3014
|
-
|
|
3424
|
+
// Per-crate cache (Mac 2026-11-07: a batch's pass was stored only under the batch's own key, its exact set of crates, so any change in how
|
|
3425
|
+
// crates were grouped reran every one of them). Before a group runs, each member is looked up on its own key; a member that hits is its own
|
|
3426
|
+
// cached row, only the members that miss run (as a smaller group, or alone). A member that passes inside a group is NOT stored under its own key:
|
|
3427
|
+
// the group compiled with the features, targets and dependencies Cargo unified across it, which is not what the member compiles alone
|
|
3428
|
+
// (2026-11-07: 296 conflicting pairs across 28 crates; a member's projected pass hid its own error). The group's row is stored under the
|
|
3429
|
+
// group's own key by its own scanRow; a member hits alone only after it ran alone (store rule, Adrian 2026-11-08). In a cache lookup the members are reported one by one, each with its own cause.
|
|
3430
|
+
const runGroup = async (idx, extraEnv, budget, probed = false) => {
|
|
3431
|
+
if (probed || !cache || idx.length < 2 || signal?.aborted) return runParts(idx, extraEnv, budget);
|
|
3432
|
+
const started = Date.now();
|
|
3433
|
+
const looked = await Promise.all(idx.map(async (i) => { const copy = { ...bScans[i] }; probeScans.add(copy); try { return [i, await scanRow(copy, extraEnv)]; } catch (error) { return [i, { ...failedRow(i, error) }]; } }));
|
|
3434
|
+
const missing = [];
|
|
3435
|
+
for (const [i, r] of looked) {
|
|
3436
|
+
if (r.cached === true) { slots[i] = { ...r, id: bScans[i].id, command: bScans[i].command }; done += 1; try { onResult(slots[i], { done, total, seconds: Math.round((Date.now() - started) / 1000) }); } catch { /* reporting never fails a scan */ } }
|
|
3437
|
+
else if (options.cacheLookupOnly) slots[i] = { ...r, id: bScans[i].id, command: bScans[i].command };
|
|
3438
|
+
else missing.push(i);
|
|
3439
|
+
}
|
|
3440
|
+
if (options.cacheLookupOnly || !missing.length) return;
|
|
3441
|
+
await runParts(missing, extraEnv, budget);
|
|
3442
|
+
};
|
|
3443
|
+
// GC-A18 (rightkit#1538): a group runs as ONE invocation only for the members whose own feature resolution the group preserves (featurePartition,
|
|
3444
|
+
// cargo's own answer through `cargo tree`); the others run as smaller groups or alone, each named in the notes with the package that split it.
|
|
3445
|
+
const runParts = async (idx, extraEnv, budget) => {
|
|
3446
|
+
if (idx.length === 1) { slots[idx[0]] = await runOne(bScans[idx[0]], extraEnv).catch((error) => failedRow(idx[0], error)); return; }
|
|
3447
|
+
let parts;
|
|
3448
|
+
try { parts = await featurePartition(idx); }
|
|
3449
|
+
catch (error) { for (const i of idx) slots[i] = { ...failedRow(i, error), code: "FEATURE_PARTITION", detail: `the feature-equivalence partition of its group did not run: ${String(error?.message ?? error)}` }; return; }
|
|
3450
|
+
if (parts.length === 1) { await runGroupBody(parts[0], extraEnv, budget); return; }
|
|
3451
|
+
await Promise.all(parts.map((part) => (part.length === 1
|
|
3452
|
+
? runOne(bScans[part[0]], extraEnv).then((r) => { slots[part[0]] = r; }).catch((error) => { slots[part[0]] = failedRow(part[0], error); })
|
|
3453
|
+
: runGroupBody(part, extraEnv, { remaining: Math.min(2 * part.length - 1, 31) }))));
|
|
3454
|
+
};
|
|
3455
|
+
// The partition of a configuration group's members (feature-partition.mjs), as index lists in plan order. A group naming several targets
|
|
3456
|
+
// (NN42) keeps as one invocation only the members equivalent on every target; the others run alone.
|
|
3457
|
+
const partitionMemo = new Map();
|
|
3458
|
+
const FEATURE_PARTITION_MS = 5 * 60_000;
|
|
3459
|
+
const featurePartition = async (idx) => {
|
|
3460
|
+
const lead = bScans[idx[0]];
|
|
3461
|
+
const prefix = lead.args[0] === "cargo" ? ["cargo"] : [];
|
|
3462
|
+
const { rest } = stripSelectors(lead.args.slice(prefix.length));
|
|
3463
|
+
const crates = [...new Set(idx.map((i) => bScans[i].batchable.crate))];
|
|
3464
|
+
if (crates.length < 2) return [idx];
|
|
3465
|
+
const targets = [...new Set(idx.map((i) => bScans[i].batchable.target ?? null))];
|
|
3466
|
+
const parts = await partitionCrates({ tool: lead.tool, prefix, rest, crates, targets, cwd: lead.cwd ?? ".", env: lead.env ?? {} });
|
|
3467
|
+
return parts.map((p) => idx.filter((i) => p.crates.includes(bScans[i].batchable.crate))).filter((part) => part.length);
|
|
3468
|
+
};
|
|
3469
|
+
const partitionCrates = async ({ tool, prefix, rest, crates, targets, cwd, env }) => {
|
|
3470
|
+
const dir = path.join(contentRoot, cwd);
|
|
3471
|
+
const inputs = workspaceManifestDigest(dir);
|
|
3472
|
+
const tree = async (packages, target) => {
|
|
3473
|
+
const args = treeArgs({ rest, packages, target });
|
|
3474
|
+
const token = cargoLedger ? scanTokenOf(`feature-partition:${cwd}`) : null; if (token) claimedTokens.add(token);
|
|
3475
|
+
const { CARGO_TARGET_DIR: _targetDir, ...rowEnv } = env; void _targetDir;
|
|
3476
|
+
// Compiles nothing and must leave the tree as it is: its output directory is a scratch one outside every root (the direct read spawn gives it another).
|
|
3477
|
+
const scratch = cargoReadTargetDir({ tmpRoot: options.cargoReadTargetRoot ?? tmpRoot, roots: [contentRoot, liveRoot, cargoLiveRoot] });
|
|
3478
|
+
let r;
|
|
3479
|
+
try { r = await deps.spawn(tool, [...prefix, ...args], { cwd: dir, env: { ...deps.env, ...rowEnv, CARGO_TARGET_DIR: scratch, ...(token ? { [SCAN_TOKEN_ENV]: token } : {}) }, timeout: FEATURE_PARTITION_MS, ...sig }); }
|
|
3480
|
+
finally { try { fs.rmSync(scratch, { recursive: true, force: true }); } catch { /* a scratch directory under the gate's tmp root */ } }
|
|
3481
|
+
if (!r || r.error || r.status !== 0) throw new Error(`cargo tree for ${packages.join(", ")}${target ? ` (--target ${target})` : ""} in ${cwd} failed: ${r?.error?.message ?? (tail(r) || `exit ${r?.status}`)}`);
|
|
3482
|
+
return r.stdout ?? "";
|
|
3483
|
+
};
|
|
3484
|
+
// The cargo that resolves is part of what it resolves (fresh review 2026-11-09, E6): its version joins the key, with the module's own code (partitionCacheKey).
|
|
3485
|
+
let toolVersion = null;
|
|
3486
|
+
try { toolVersion = (await probe(tool, path.join(cargoLiveRoot ?? contentRoot, cwd)))?.version ?? null; } catch { toolVersion = null; }
|
|
3487
|
+
const one = async (target) => {
|
|
3488
|
+
const key = partitionCacheKey({ rest, crates, target, cwd, inputs, toolVersion });
|
|
3489
|
+
const stored = cache?.read(key);
|
|
3490
|
+
if (stored && stored.key === key && Array.isArray(stored.row?.partition)) return stored.row.partition;
|
|
3491
|
+
if (!partitionMemo.has(key)) partitionMemo.set(key, partitionByFeatures({ crates, tree: (packages) => tree(packages, target) }).then((parts) => { cache?.write(key, { id: "feature-partition", status: "pass", crates: [...crates].sort(), target, partition: parts }); return parts; }));
|
|
3492
|
+
return partitionMemo.get(key);
|
|
3493
|
+
};
|
|
3494
|
+
// Several targets (NN42): the common refinement of the per-target partitions, so no boundary any target drew is crossed (rightkit#1538, second review).
|
|
3495
|
+
const result = meetPartitions(await Promise.all(targets.map(one)));
|
|
3496
|
+
for (const p of result) if (p.split) partitionNotes.add(`class B batching: ${splitNote(p.split)}`);
|
|
3497
|
+
return result;
|
|
3498
|
+
};
|
|
3499
|
+
const runGroupBody = async (idx, extraEnv, budget = { remaining: Math.min(2 * idx.length - 1, 31) }) => {
|
|
3015
3500
|
if (budget.remaining <= 0 || signal?.aborted) {
|
|
3016
3501
|
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" };
|
|
3017
3502
|
return;
|
|
@@ -3025,42 +3510,37 @@ export async function runScans(plan, options = {}) {
|
|
|
3025
3510
|
if (row.memberRuns && !signal?.aborted) {
|
|
3026
3511
|
idx.forEach((i) => {
|
|
3027
3512
|
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;
|
|
3513
|
+
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, ...(row.seam ? { seam: true, seamSettled: row.seamSettled === true } : {}), status: v.status, ...(v.code ? { code: v.code } : {}), ...(v.detail ? { detail: v.detail } : {}), ...(v.results ? { results: v.results } : {}), ...(v.testRun ? { testRun: v.testRun } : {}), ...(v.acceptedBinaries ? { acceptedBinaries: v.acceptedBinaries } : {}), ...(v.executableProof ? { executableProof: v.executableProof } : {}), ...(row.snapshotEvidence ? { snapshotEvidence: row.snapshotEvidence } : {}), ...(row.cached ? { cached: true } : {}) };
|
|
3514
|
+
slots[i] = own; done += 1; settle(m.id, own);
|
|
3030
3515
|
try { onResult(own, { done, total, seconds: Math.round((Date.now() - started) / 1000) }); } catch { /* reporting never fails a scan */ }
|
|
3031
3516
|
});
|
|
3032
3517
|
return;
|
|
3033
3518
|
}
|
|
3034
|
-
// A failure reused from the result cache (NN41) was authenticated or diagnosed when it was written, so it attributes the same way.
|
|
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"));
|
|
3036
3519
|
// 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
|
|
3037
|
-
// another member has one fails, the rest pass. Without usable messages (none, or no artifact for any member)
|
|
3038
|
-
|
|
3520
|
+
// another member has one fails, the rest pass. Without usable messages (none, or no artifact for any member) every member carries the group's failure (below); nothing is bisected
|
|
3521
|
+
// (Adrian 2026-11-08, store rule: a row is stored only for the invocation that ran it; blame comes from Cargo's messages, not from reruns).
|
|
3522
|
+
const verdicts = row.status === "fail" && bs.captureJson && row.jsonSummary?.records > 0 && !signal?.aborted ? docVerdicts(row.jsonSummary, idx.map((i) => bScans[i].batchable.unit), idx.map((i) => bScans[i].batchable.crate)) : null;
|
|
3039
3523
|
if (verdicts && !signal?.aborted) {
|
|
3040
3524
|
batchFailureNotes.push(`class B batching: grouped doc invocation ${bs.id} (${idx.length} crates: ${bs.batch.units.join(", ")}) failed (EXIT) and was attributed per crate from its --message-format=json output, not bisected; failing: ${verdicts.filter((v) => v.fail).map((v) => v.unit).join(", ") || "none named"}`);
|
|
3041
3525
|
idx.forEach((i, k) => {
|
|
3042
3526
|
const m = bScans[i]; const v = verdicts[k];
|
|
3043
|
-
const own = { id: m.id, class: m.class, command: m.command, batchCommand: row.command, tool: m.tool ?? null, toolVersion: row.toolVersion ?? null, status: v.fail ? "fail" : "pass", ...(v.fail ? { code: "EXIT", detail: `${row.id} (${idx.length} crates: ${bs.batch.units.join(", ")}): ${v.detail}` } : {}), ...(row.cached ? { cached: true } : {}), timing: row.timing ?? null, batchedWith: { id: row.id, units: bs.batch.units }, batchFailure: { id: bs.id, units: bs.batch.units, command: row.command, ...(row.authenticatedFailure ? { authenticatedFailure: row.authenticatedFailure } : {}), ...(row.snapshotEvidence ? { snapshotEvidence: row.snapshotEvidence } : {}), detail: "the grouped doc invocation failed; this row's verdict is its own, read from the invocation's JSON messages" }, ...(row.identities ? { identities: row.identities } : {}) };
|
|
3044
|
-
slots[i] = own; done += 1;
|
|
3527
|
+
const own = { id: m.id, class: m.class, command: m.command, batchCommand: row.command, tool: m.tool ?? null, toolVersion: row.toolVersion ?? null, ...(row.seam ? { seam: true, seamSettled: row.seamSettled === true } : {}), status: v.fail ? "fail" : "pass", ...(v.fail ? { code: "EXIT", detail: `${row.id} (${idx.length} crates: ${bs.batch.units.join(", ")}): ${v.detail}` } : {}), ...(row.cached ? { cached: true } : {}), timing: row.timing ?? null, batchedWith: { id: row.id, units: bs.batch.units }, batchFailure: { id: bs.id, units: bs.batch.units, command: row.command, ...(row.authenticatedFailure ? { authenticatedFailure: row.authenticatedFailure } : {}), ...(row.snapshotEvidence ? { snapshotEvidence: row.snapshotEvidence } : {}), detail: "the grouped doc invocation failed; this row's verdict is its own, read from the invocation's JSON messages" }, ...(row.identities ? { identities: row.identities } : {}) };
|
|
3528
|
+
slots[i] = own; done += 1; settle(m.id, own);
|
|
3045
3529
|
try { onResult(own, { done, total, seconds: Math.round((Date.now() - started) / 1000) }); } catch { /* reporting never fails a scan */ }
|
|
3046
3530
|
});
|
|
3047
|
-
|
|
3048
|
-
|
|
3049
|
-
|
|
3050
|
-
|
|
3051
|
-
|
|
3052
|
-
|
|
3053
|
-
|
|
3054
|
-
const half = Math.ceil(idx.length / 2);
|
|
3055
|
-
await runGroup(idx.slice(0, half), extraEnv, budget);
|
|
3056
|
-
await runGroup(idx.slice(half), extraEnv, budget);
|
|
3057
|
-
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 }] };
|
|
3531
|
+
// NN42: cargo's messages name the crate, not the target. A crate that failed in an invocation naming several targets runs each of its
|
|
3532
|
+
// targets alone, so the verdict names the target that fails and the others pass on their own.
|
|
3533
|
+
const multi = new Set(idx.map((i) => bScans[i].batchable.target).filter(Boolean)).size > 1;
|
|
3534
|
+
if (multi && !signal?.aborted) {
|
|
3535
|
+
const redo = idx.filter((i) => slots[i]?.status === "fail");
|
|
3536
|
+
await Promise.all(redo.map(async (i) => { const alone = await runOne(bScans[i], extraEnv).catch((error) => failedRow(i, error)); slots[i] = { ...alone, batchFailure: { id: bs.id, units: bs.batch.units, command: row.command, detail: "the multi-target invocation failed for this crate; this target ran alone" } }; }));
|
|
3537
|
+
}
|
|
3058
3538
|
return;
|
|
3059
3539
|
}
|
|
3060
3540
|
for (const i of idx) {
|
|
3061
3541
|
const m = bScans[i];
|
|
3062
|
-
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 } : {}) };
|
|
3063
|
-
slots[i] = own; done += 1;
|
|
3542
|
+
const own = { id: m.id, class: m.class, command: m.command, batchCommand: row.command, tool: m.tool ?? null, toolVersion: row.toolVersion ?? null, ...(row.seam ? { seam: true, seamSettled: row.seamSettled === true } : {}), 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 } : {}), ...(options.cacheLookupOnly ? { lookupMiss: row.lookupMiss === true, uncacheable: row.uncacheable === true, ...(row.cacheMiss ? { cacheMiss: row.cacheMiss } : {}) } : {}) };
|
|
3543
|
+
slots[i] = own; done += 1; settle(m.id, own);
|
|
3064
3544
|
try { onResult(own, { done, total, seconds: Math.round((Date.now() - started) / 1000) }); } catch { /* reporting never fails a scan */ }
|
|
3065
3545
|
}
|
|
3066
3546
|
};
|
|
@@ -3083,48 +3563,11 @@ export async function runScans(plan, options = {}) {
|
|
|
3083
3563
|
// A scan that throws becomes a failed row: with several components in flight, a rejection must not abandon the others.
|
|
3084
3564
|
const job = runB(i, extraEnv)
|
|
3085
3565
|
.catch((error) => failedRow(i, error))
|
|
3086
|
-
.then((row) => { slots[i] = row; }).finally(() => { busy.delete(key); running.delete(job); });
|
|
3566
|
+
.then((row) => { slots[i] = row; settle(bScans[i].id, row); }).finally(() => { busy.delete(key); running.delete(job); });
|
|
3087
3567
|
running.add(job);
|
|
3088
3568
|
}
|
|
3089
3569
|
};
|
|
3090
|
-
if (
|
|
3091
|
-
// A caller-supplied dependency scheduler uses this initialized executor: every job still passes Class A,
|
|
3092
|
-
// tool, carrier, ledger, receipt, timeout and quiet-lease checks in the same scan path.
|
|
3093
|
-
const issued = new WeakSet();
|
|
3094
|
-
const remember = (row) => { issued.add(row); return row; };
|
|
3095
|
-
const executeRaw = async (scan) => {
|
|
3096
|
-
if (!scan.quiet) return runOne(scan);
|
|
3097
|
-
if (classAFailed || classBBlocked || signal?.aborted) return runOne(scan);
|
|
3098
|
-
let lease = null;
|
|
3099
|
-
if (quietLane) { try { lease = (await quietLane.acquire({ ttlMs: QUIET_LEASE_MAX_MS })) ?? null; } catch { lease = null; } }
|
|
3100
|
-
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" };
|
|
3101
|
-
try { return await runOne({ ...scan, timeoutMs: Math.min(scanTimeoutMs(scan, options), QUIET_SCAN_MAX_MS) }, lease?.env ?? null); }
|
|
3102
|
-
finally { if (lease && typeof quietLane.release === "function") { try { await quietLane.release(lease.id); } catch { /* lease expires */ } } }
|
|
3103
|
-
};
|
|
3104
|
-
const execute = async (scan) => remember(Object.freeze(await executeRaw(scan)));
|
|
3105
|
-
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); };
|
|
3106
|
-
// The caller supplies only members ready on its current frontier. Reuse the existing
|
|
3107
|
-
// signed batch/bisection path without admitting other members of their planned group.
|
|
3108
|
-
const executeGroup = async (scans) => {
|
|
3109
|
-
if (!Array.isArray(scans) || scans.length < 2) throw new Error("scheduleClassB: a batch needs at least two scans");
|
|
3110
|
-
const indices = scans.map((scan) => bScans.indexOf(scan));
|
|
3111
|
-
const group = groupOf.get(indices[0]);
|
|
3112
|
-
if (!group || new Set(indices).size !== indices.length || indices.some((i) => i < 0 || groupOf.get(i) !== group)) throw new Error("scheduleClassB: incompatible batch members");
|
|
3113
|
-
await runGroup(indices, null);
|
|
3114
|
-
return indices.map((i) => remember(Object.freeze(slots[i] ?? failedRow(i, "batch produced no row"))));
|
|
3115
|
-
};
|
|
3116
|
-
const project = (row, scan) => {
|
|
3117
|
-
if (!issued.has(row) || !bScans.includes(scan)) throw new Error("scheduleClassB: invalid projection");
|
|
3118
|
-
return remember(Object.freeze({ ...row, id: scan.id, command: scan.command }));
|
|
3119
|
-
};
|
|
3120
|
-
const notRun = (scan, detail) => {
|
|
3121
|
-
if (!bScans.includes(scan)) throw new Error("scheduleClassB: unknown scan");
|
|
3122
|
-
return remember(Object.freeze({ id: scan.id, class: scan.class, command: scan.command, status: "not-run", detail: String(detail) }));
|
|
3123
|
-
};
|
|
3124
|
-
const rows = await options.scheduleClassB({ scans: bScans, execute, executeGroup, canGroup, project, notRun });
|
|
3125
|
-
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");
|
|
3126
|
-
rows.forEach((row, i) => { slots[i] = row; });
|
|
3127
|
-
} else if (brokerHost) {
|
|
3570
|
+
if (brokerHost) {
|
|
3128
3571
|
await scheduleBrokerHostClassB({
|
|
3129
3572
|
scans: bScans, lanes, localJobs: bJobs, carried: (scan) => isBrokerScheduledScan(scan, carriedCtx), pipeline: options.classBPipeline ?? 1,
|
|
3130
3573
|
run: async (i) => { try { slots[i] = await runB(i); } catch (error) { slots[i] = failedRow(i, error); } },
|
|
@@ -3134,7 +3577,7 @@ export async function runScans(plan, options = {}) {
|
|
|
3134
3577
|
await drain(lanes.doc);
|
|
3135
3578
|
await drain(lanes.tests);
|
|
3136
3579
|
}
|
|
3137
|
-
if (
|
|
3580
|
+
if (lanes.quiet.length) {
|
|
3138
3581
|
// One lease per quiet suite, as in class A above.
|
|
3139
3582
|
for (const i of lanes.quiet) {
|
|
3140
3583
|
if (classAFailed || classBBlocked || signal?.aborted) {
|
|
@@ -3186,7 +3629,10 @@ export async function runScans(plan, options = {}) {
|
|
|
3186
3629
|
const owned = { cargoReadTarget: null };
|
|
3187
3630
|
try {
|
|
3188
3631
|
const row = await scanRowIn(s, extraEnv, owned, timing);
|
|
3189
|
-
|
|
3632
|
+
const out = { ...row, timing: { ...timing, elapsedMs: performance.now() - started } };
|
|
3633
|
+
// A lookup or probe answer (lookupMiss present) says nothing ran: it settles nothing. A cache hit found by a probe is a real answer and does.
|
|
3634
|
+
if (out.lookupMiss === undefined) settle(s.id, out);
|
|
3635
|
+
return out;
|
|
3190
3636
|
} finally { if (owned.cargoReadTarget) fs.rmSync(owned.cargoReadTarget, { recursive: true, force: true }); }
|
|
3191
3637
|
}
|
|
3192
3638
|
async function scanRowIn(s, extraEnv, owned, timing) {
|
|
@@ -3256,11 +3702,8 @@ export async function runScans(plan, options = {}) {
|
|
|
3256
3702
|
}
|
|
3257
3703
|
const p = await probe(s.tool, probeAt);
|
|
3258
3704
|
row.toolVersion = p.ok ? p.version : null;
|
|
3259
|
-
// The broker runs the cargo-deny / cargo-audit a carried scan names: that identity is the broker's tool registration, not the gate's to bind.
|
|
3260
|
-
// `options.cargoReadsCarried === true` (the gate, when its executor is the broker and cargo reads go through carried requests, as in the check stage that has no snapshotBroker) makes them carried exactly as snapshotBroker does; it waives nothing else (actionlint and shellcheck stay locally enrolled).
|
|
3261
|
-
const brokerCarried = cargoReadsAreCarried && s.class === SCAN_CLASS.A && (s.tool === "rustright" || s.tool === "cargo");
|
|
3262
3705
|
const advisoryTool = s.advisoryDb === "deny" ? "cargo-deny" : s.advisoryDb === "audit" ? "cargo-audit" : null;
|
|
3263
|
-
const trusts = advisoryTool
|
|
3706
|
+
const trusts = advisoryTool ? [advisoryTool] : [];
|
|
3264
3707
|
const identities = []; if (p.identity) identities.push(p.identity);
|
|
3265
3708
|
let missingDep = null; let depVersionProblem = null; let depTrust = null; const depVersions = [];
|
|
3266
3709
|
for (const dep of [...(s.requires ?? []), ...trusts]) {
|
|
@@ -3270,8 +3713,7 @@ export async function runScans(plan, options = {}) {
|
|
|
3270
3713
|
depVersions.push(d.identity ? `${d.version}@${d.identity.sha256}` : d.version);
|
|
3271
3714
|
if (d.identity) identities.push(d.identity);
|
|
3272
3715
|
}
|
|
3273
|
-
if (
|
|
3274
|
-
else if (identities.length) row.identities = identities.map((i) => ({ tool: i.tool, path: i.path, sha256: i.sha256, version: i.version, source: i.source }));
|
|
3716
|
+
if (identities.length) row.identities = identities.map((i) => ({ tool: i.tool, path: i.path, sha256: i.sha256, version: i.version, source: i.source }));
|
|
3275
3717
|
if (!p.ok) { status = "fail"; code = p.code ?? "TOOL_MISSING"; detail = p.code && p.code !== "TOOL_MISSING" ? `${p.code}: ${p.why}` : `required tool ${s.tool} is missing or not runnable (${p.why}); a required scan is never skipped`; }
|
|
3276
3718
|
else if (p.pinProblem) { status = "fail"; code = "TOOL_VERSION"; detail = `TOOL_VERSION: ${p.pinProblem} (at ${p.command})`; }
|
|
3277
3719
|
else if (depTrust) { status = "fail"; code = depTrust.code; detail = `${depTrust.code}: ${s.tool} needs ${depTrust.dep}: ${depTrust.why}`; }
|
|
@@ -3284,10 +3726,12 @@ export async function runScans(plan, options = {}) {
|
|
|
3284
3726
|
// crate's closure, its lock entries, the toolchain files, the tool version and the build environment; a miss runs the compile and
|
|
3285
3727
|
// verifies the broker's signed evidence as before, and only a verified pass is written.
|
|
3286
3728
|
const carriedScan = isBrokerCarriedScan(s, carriedCtx);
|
|
3287
|
-
|
|
3288
|
-
|
|
3729
|
+
// The seam (plan section 3): a class B cargo row on a broker host is one spawn of `rustright cargo` in the snapshot with the two seam variables.
|
|
3730
|
+
// Adapters (the Swift package build) take the same seam: `rustright run rightkit-swift -- <argv>` in the snapshot with the two variables (plan section 3).
|
|
3731
|
+
const viaSeam = Boolean(deps.gateSeam) && s.class === SCAN_CLASS.B && s.root === "cargoLive" && (s.tool === "rustright" || s.tool === "cargo" || (s.tool === "swift" && carriedScan));
|
|
3732
|
+
if (viaSeam) row.seam = true;
|
|
3289
3733
|
// NN02: a publisher row (coverageKey) is cached too, with the signed broker receipt and test-run evidence its publisher verify needs.
|
|
3290
|
-
if (cache
|
|
3734
|
+
if (cache) {
|
|
3291
3735
|
const cacheStarted = performance.now();
|
|
3292
3736
|
try {
|
|
3293
3737
|
// A plain node --check row has no guard, carrier, advisory or
|
|
@@ -3302,18 +3746,21 @@ export async function runScans(plan, options = {}) {
|
|
|
3302
3746
|
// child environment (with its one explicit ownership exception).
|
|
3303
3747
|
// NN29: a publisher row carries the gate's whole environment, per-run identities included (build ownership handle, carrier map, run markers):
|
|
3304
3748
|
// its key drops them, or every run would miss.
|
|
3305
|
-
|
|
3306
|
-
|
|
3749
|
+
// Only build-relevant names key a publisher row (buildEnvName: compiler, cargo, toolchain, RK_/RIGHTKIT_ switches ...): the rest of the gate's environment (the
|
|
3750
|
+
// calling session's ids, sockets, PATH order, locale) is not an input of the compile (Mac 2026-11-07: a restarted session changed CLAUDE_* and 73 passes missed).
|
|
3751
|
+
const keyEnv = (env) => (s.coverageKey ? Object.fromEntries(Object.entries(env ?? {}).filter(([k]) => buildEnvName(k) && !/^(?:RIGHTKIT_BUILD_OWNERSHIP|RK_GATE_|RIGHTKIT_CARRIED_|RIGHTKIT_CARGO_SCAN|RIGHTKIT_RUN_|RUSTRIGHT_OWNERSHIP|TMPDIR$|PWD$|OLDPWD$|SHLVL$|_$)/.test(k))) : env);
|
|
3752
|
+
// rightkit#1540: the inherited environment is keyed per tool (buildEnvNameFor); the row's own env is keyed in full below (`env: keyEnv(s.env)`), so it is not repeated here.
|
|
3753
|
+
const inherited = cache.narrowNodeCheck && /^node-check:/.test(s.id) ? sha256('node-check-child-env-in-digest/1') : inheritedEnvDigest(keyEnv(deps.env), s.tool ?? null);
|
|
3307
3754
|
if (digest) {
|
|
3308
|
-
cacheKey = scanCacheKey({ id: s.id, command:
|
|
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 } };
|
|
3755
|
+
cacheKey = scanCacheKey({ id: s.id, command: keyCommand(s), toolVersion, env: keyEnv(s.env ?? {}), inheritedEnv: inherited, digest });
|
|
3756
|
+
keyParts = { inputs: sha256(String(digest)), env: sha256(canonicalJson({ toolVersion, env: keyEnv(s.env ?? {}), inherited })), raw: { inputs: String(digest), toolVersion, env: keyEnv(s.env ?? {}), inherited, inheritedShape: inheritedEnvShape(keyEnv(deps.env), s.tool ?? null) } };
|
|
3310
3757
|
// NN41: a deterministic compile failure is keyed like the pass plus the tool version (the client's, its identity digest), the installed broker runtime
|
|
3311
3758
|
// identity (options.failureIdentity: version, clientDigest, brokerDigest) and the failure namespace; the digest already binds the unit closure, lock entries and toolchain files.
|
|
3312
3759
|
// No identity from the caller means no failure is ever stored or reused.
|
|
3313
|
-
if (typeof options.failureIdentity === "string" && options.failureIdentity !== "" && isFailureCacheableCompileId(s.id) && !s.runOutside && s.kind !== "test" && !s.publisherRustTest && (s.tool === "rustright" || s.tool === "cargo")) failKey = scanCacheKey({ id: s.id, command: `${s.command} ;; ${FAILURE_KEY_SCHEMA}`, toolVersion: `${toolVersion} ;; broker-runtime ${options.failureIdentity}`, env: s.env ?? {}, inheritedEnv: inherited, digest });
|
|
3760
|
+
if (typeof options.failureIdentity === "string" && options.failureIdentity !== "" && isFailureCacheableCompileId(s.id) && !s.runOutside && s.kind !== "test" && !s.publisherRustTest && (s.tool === "rustright" || s.tool === "cargo")) failKey = scanCacheKey({ id: s.id, command: `${keyCommand({ command: s.command })} ;; ${FAILURE_KEY_SCHEMA}`, toolVersion: `${toolVersion} ;; broker-runtime ${options.failureIdentity}`, env: s.env ?? {}, inheritedEnv: inherited, digest });
|
|
3314
3761
|
}
|
|
3315
3762
|
} catch (error) { cacheKey = null; row.cacheKeyError = String(error?.message ?? error).slice(0, 300); }
|
|
3316
|
-
|
|
3763
|
+
let hit = cacheKey ? cache.read(cacheKey) : null;
|
|
3317
3764
|
// 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
3765
|
// (its inputs digest and environment digest); a later miss is "unchanged" (inputs and environment the same: the cache failed),
|
|
3319
3766
|
// "changed" (an input or the environment moved: a legitimate rerun) or "new" (no stored pass: a new row, or a cold run).
|
|
@@ -3324,26 +3771,98 @@ export async function runScans(plan, options = {}) {
|
|
|
3324
3771
|
const idx = cache.read(rowIndexKey)?.row ?? null;
|
|
3325
3772
|
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
3773
|
row.rowIndex = { key: rowIndexKey, inputs: inputsDigest, env: envDigest, raw: keyParts.raw };
|
|
3774
|
+
// A hit refreshes a row index that lacks the environment shape (stored before the shape existed), so a later key change can carry this row over.
|
|
3775
|
+
if (hit && hit.key === cacheKey && hit.row?.status === "pass" && !options.cacheLookupOnly && !probeScans.has(s) && !idx?.raw?.inheritedShape) {
|
|
3776
|
+
try { cache.write(rowIndexKey, { id: s.id, inputs: inputsDigest, env: envDigest, raw: keyParts.raw, at: new Date().toISOString() }); } catch { /* the hit stands */ }
|
|
3777
|
+
}
|
|
3778
|
+
// Carry-over (carryOverProof): a pass stored under an earlier key form, whose real inputs provably did not change, is this row's pass.
|
|
3779
|
+
if (!(hit && hit.key === cacheKey && hit.row?.status === "pass") && idx?.raw && row.cacheMiss.kind === "changed") {
|
|
3780
|
+
// entryNow (a path's content id now) exists on the class A cache; a class B row has none and its inputs digest is one string, so only an
|
|
3781
|
+
// environment-only difference can carry over there (no changed entry is ever looked up).
|
|
3782
|
+
const proof = carryOverProof(idx.raw, keyParts.raw, { entryNow: typeof cache.entryNow === "function" ? cache.entryNow : () => null });
|
|
3783
|
+
if (!proof.ok && proof.edited?.length && row.cacheMiss.why) row.cacheMiss.why = { ...row.cacheMiss.why, contentOnly: true, formChangesProven: proof.carried };
|
|
3784
|
+
if (proof.ok) {
|
|
3785
|
+
const oldKey = scanCacheKey({ id: s.id, command: keyCommand(s), toolVersion: idx.raw.toolVersion, env: idx.raw.env ?? {}, inheritedEnv: idx.raw.inherited, digest: idx.raw.inputs });
|
|
3786
|
+
const old = cache.read(oldKey);
|
|
3787
|
+
if (usableStoredPass(old, s, { cacheKey: oldKey, viaSeam })) {
|
|
3788
|
+
hit = { ...old, key: cacheKey };
|
|
3789
|
+
row.carriedOver = { from: oldKey.slice(0, 16), files: proof.carried };
|
|
3790
|
+
if (!options.cacheLookupOnly) { try { cache.write(cacheKey, old.row); cache.write(rowIndexKey, { id: s.id, inputs: inputsDigest, env: envDigest, raw: keyParts.raw, at: new Date().toISOString() }); } catch { /* the pass stands; the next run carries it again */ } }
|
|
3791
|
+
}
|
|
3792
|
+
}
|
|
3793
|
+
}
|
|
3327
3794
|
}
|
|
3328
3795
|
timing.cacheLookupMs = performance.now() - cacheStarted;
|
|
3329
3796
|
// A cached test pass counts only with the counts it recorded: without them its coverage is unknown, so it runs again.
|
|
3330
3797
|
// ...and only if it passed at least one test: a cached all-skipped "pass" (written before D17) runs again (rightkit#1236).
|
|
3331
3798
|
// 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.
|
|
3332
|
-
|
|
3333
|
-
|
|
3334
|
-
if (hit
|
|
3799
|
+
// One predicate for every stored pass (usableStoredPass; rightkit#1538): the row's own id and command, written by the invocation that ran it, with
|
|
3800
|
+
// the evidence its kind needs; a test group's hit carries each member's own run, so the members are judged exactly as on the run that stored it.
|
|
3801
|
+
if (usableStoredPass(hit, s, { cacheKey, viaSeam })) {
|
|
3335
3802
|
cacheHits.push(s.id);
|
|
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 } : {}) };
|
|
3803
|
+
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 } : s.provesPublisher ? { snapshotEvidence: hit.row.snapshotEvidence ?? null, ...(hit.row.testRun ? { testRun: hit.row.testRun } : {}) } : hit.row.testRun ? { testRun: hit.row.testRun } : {}), ...(hit.row.memberRuns ? { memberRuns: hit.row.memberRuns } : {}), ...(hit.row.executableProof ? { executableProof: hit.row.executableProof } : {}), ...(row.seam ? { seamSettled: true } : {}) };
|
|
3337
3804
|
}
|
|
3338
3805
|
// NN41: the same inputs, toolchain and broker runtime already failed this compile deterministically: report that failure, marked cached, without running it.
|
|
3339
3806
|
const failHit = failKey ? cache.read(failKey) : null;
|
|
3340
|
-
if (failHit && failHit.key === failKey && failHit.row?.status === "fail" && failHit.row.id === s.id && failHit.row.command
|
|
3807
|
+
if (failHit && failHit.key === failKey && failHit.row?.status === "fail" && failHit.row.id === s.id && sameCommand(failHit.row.command, s) && failHit.row.failureIdentity === options.failureIdentity && failHit.row.code === "EXIT" && typeof failHit.row.detail === "string" && failHit.row.detail !== "") {
|
|
3341
3808
|
cacheHits.push(s.id);
|
|
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 } : {}) };
|
|
3809
|
+
return { ...row, ...(row.seam ? { seamSettled: true } : {}), 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 } : {}) };
|
|
3343
3810
|
}
|
|
3344
3811
|
}
|
|
3345
3812
|
// 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
|
-
|
|
3813
|
+
// A probe (runGroup's per-crate lookup) answers like a lookup.
|
|
3814
|
+
if (options.cacheLookupOnly || probeScans.has(s)) return { ...row, status: "not-run", lookupMiss: Boolean(cacheKey), uncacheable: !cacheKey, detail: cacheKey ? "would miss the cache" : "has no cache key", ...(row.seam ? { seamSettled: true } : {}) }; // nothing was submitted
|
|
3815
|
+
// rightkit#1539: a serial test row owns no compile while its plain row is in this run. It waits for the plain row of the same crate and configuration
|
|
3816
|
+
// (grouped or alone) and runs that row's accepted executables with --test-threads=1 under its own id, results and key; the plain row's compile verdict
|
|
3817
|
+
// is never stored under this key (store rule). One compile per crate and configuration, whatever happens:
|
|
3818
|
+
// plain compiled and passed -> its executables run here (none listed: a pass with zero tests, as the plain row's)
|
|
3819
|
+
// plain was a cache hit -> its stored executable proof is checked again (provenExecutables): every executable still there with the same sha256 runs
|
|
3820
|
+
// here and nothing compiles; only an absent or changed executable (or no proof) makes this row compile once, alone
|
|
3821
|
+
// plain failed / did not run -> this row fails or does not run on that dependency; it never compiles a second time
|
|
3822
|
+
// plain not settled in time -> this row fails (TEST_DEPENDENCY_TIMEOUT); the plain compile may still be in flight, so no compile here
|
|
3823
|
+
// The schedulers start rows in plan order and the plain row is planned first (planScans), so the wait never holds the slot the plain row needs.
|
|
3824
|
+
if (s.reuseExecutables && (s.runOutside || s.e2e) && plannedIds.has(s.reuseExecutables)) {
|
|
3825
|
+
const reuseLimit = scanTimeoutMs(s, options);
|
|
3826
|
+
let base = await waitForRow(s.reuseExecutables, Math.min(reuseLimit, QUIET_SCAN_MAX_MS));
|
|
3827
|
+
// None of the outcomes below submits anything for this row: a seam row is settled by construction (the plain row's own job is counted on the plain row).
|
|
3828
|
+
if (row.seam) row.seamSettled = true;
|
|
3829
|
+
if (!base) return { ...row, status: "fail", code: "TEST_DEPENDENCY_TIMEOUT", detail: `${s.id}: its plain row ${s.reuseExecutables} did not finish within this row's limit; this row reuses that row's executables and never compiles them a second time` };
|
|
3830
|
+
if (base.status === "not-run") return { ...row, status: "not-run", detail: `${s.id}: its plain row ${s.reuseExecutables} did not run (${String(base.detail ?? "not run").slice(0, 300)})` };
|
|
3831
|
+
if (base.status !== "pass") return { ...row, status: "fail", code: "TEST_DEPENDENCY_FAILED", detail: `${s.id}: its plain row ${s.reuseExecutables} failed (${base.code ?? "fail"}); the serial run of the same executables proves nothing more` };
|
|
3832
|
+
// A cache hit of the plain row compiled nothing in this run; its stored proof stands in for the executables when every file still matches it (Adrian's
|
|
3833
|
+
// compile-once agreement, rightkit#1539). A stale or absent proof is recorded and this row compiles once, alone, below.
|
|
3834
|
+
if (base.cached === true && !Array.isArray(base.acceptedBinaries) && s.runOutside) {
|
|
3835
|
+
const proven = provenExecutables(base.executableProof, { generationRoots: viaSeam ? (deps.gateSeam.outputRoots ?? null) : null, platform: deps.platform ?? process.platform, ops: { ...TEST_RUN_OPS, ...(options.testRunOps ?? {}) } });
|
|
3836
|
+
if (proven.accepted) { base = { ...base, acceptedBinaries: proven.accepted }; row.reusedCachedProof = true; }
|
|
3837
|
+
else row.reuseFallback = `${s.reuseExecutables} was a cache hit and its stored executables cannot be reused (${proven.why}); this row compiles once on its own`;
|
|
3838
|
+
}
|
|
3839
|
+
// An end-to-end crate's serial row is the same `--no-run` compile as its plain row and runs no test (they run in qualify): the plain row's pass, compiled in this run or
|
|
3840
|
+
// a cache hit of the same inputs, is this compile's pass, so nothing is repeated (Adrian's compile-once, rightkit#1539); it is not stored under this key (store rule).
|
|
3841
|
+
if (s.e2e && !s.runOutside) return { ...row, status: "pass", reusedExecutablesOf: base.id, detail: `${s.id}: its compile is ${base.id}'s, ${base.cached === true ? "a cache hit of the same compile" : "compiled once in this run"} (end-to-end crate: no test runs here)`, ...(base.snapshotEvidence ? { snapshotEvidence: base.snapshotEvidence } : {}), ...(base.seam ? { seam: true, seamSettled: true } : {}) };
|
|
3842
|
+
if (!Array.isArray(base.acceptedBinaries) && base.cached !== true) return { ...row, status: "fail", code: "TEST_DEPENDENCY_NO_EXECUTABLES", detail: `${s.id}: its plain row ${s.reuseExecutables} passed without an executable list to reuse` };
|
|
3843
|
+
if (Array.isArray(base.acceptedBinaries) && !base.acceptedBinaries.length) {
|
|
3844
|
+
row.results = { runner: "libtest", tests: 0, pass: 0, fail: 0, skipped: 0, todo: 0, binaries: 0 }; row.testRun = { executables: [], outputTruncated: false, skipMarkers: 0 }; row.reusedExecutablesOf = base.id;
|
|
3845
|
+
if (base.seam) { row.seam = true; row.seamSettled = true; }
|
|
3846
|
+
return { ...row, status: "pass", detail: `${s.id}: ${base.id} listed no test executable; nothing to run` };
|
|
3847
|
+
}
|
|
3848
|
+
if (Array.isArray(base.acceptedBinaries)) {
|
|
3849
|
+
const ops = { ...TEST_RUN_OPS, ...(options.testRunOps ?? {}) };
|
|
3850
|
+
const ran = await runTestBinaries({ scan: s, binaries: base.acceptedBinaries, spawn: deps.spawn, env: { ...deps.env, ...s.env, ...(extraEnv ?? {}) }, limitMs: reuseLimit, signal, ops, concurrency: 1 });
|
|
3851
|
+
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) };
|
|
3852
|
+
row.reusedExecutablesOf = base.id; if (base.snapshotEvidence) row.snapshotEvidence = base.snapshotEvidence; if (base.seam) { row.seam = true; row.seamSettled = true; }
|
|
3853
|
+
let reuseStatus = ran.status; let reuseCode = ran.code ?? null; let reuseDetail = ran.detail ?? null;
|
|
3854
|
+
if (reuseStatus === "pass" && s.publisherRustTest && row.testRun.outputTruncated) { reuseStatus = "fail"; reuseCode = "TEST_OUTPUT_TRUNCATED"; reuseDetail = `${s.id}: test output was truncated; skip evidence is incomplete`; }
|
|
3855
|
+
if (reuseStatus === "pass" && s.publisherRustTest && !s.allowIgnored && (row.results?.skipped ?? 0) > 0) { reuseStatus = "fail"; reuseCode = "IGNORED_TESTS"; reuseDetail = `${row.results.skipped} ignored Rust test(s) require an approved reason`; }
|
|
3856
|
+
if (reuseStatus === "fail" && options.scanLogDir && ran.outputs?.length) {
|
|
3857
|
+
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} (executables of ${base.id}, --test-threads=1)\n${ran.outputs.map((o) => `=== test executable ${o.label} (exit ${o.exit ?? "none"}${o.signal ? `, signal ${o.signal}` : ""})\n--- stdout\n${o.stdout}\n--- stderr\n${o.stderr}\n`).join("")}`); row.log = file; reuseDetail = `${reuseDetail} (full output: ${file})`; } catch { /* the tail in the row remains */ }
|
|
3858
|
+
}
|
|
3859
|
+
if (reuseStatus === "pass" && cacheKey && cache && !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() });
|
|
3860
|
+
if (reuseStatus === "pass" && cacheKey && cache && !signal?.aborted) cache.write(cacheKey, storedPassRow(s, row));
|
|
3861
|
+
return { ...row, status: reuseStatus, ...(reuseCode ? { code: reuseCode } : {}), ...(reuseDetail ? { detail: reuseDetail } : {}) };
|
|
3862
|
+
}
|
|
3863
|
+
// Only a cache hit of the plain row whose stored executables could not be proven again reaches here: this row compiles once, alone (one compile per crate and configuration).
|
|
3864
|
+
row.reuseFallback ??= `${s.reuseExecutables} was a cache hit (no executables in this run); this row compiles once on its own`;
|
|
3865
|
+
}
|
|
3347
3866
|
// 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
|
|
3348
3867
|
// 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.
|
|
3349
3868
|
const ledgerToken = cargoLedger ? scanTokenOf(s.id) : null;
|
|
@@ -3355,7 +3874,7 @@ export async function runScans(plan, options = {}) {
|
|
|
3355
3874
|
// checkout-pinned output), a wrapped snapshot compile (the wrapper binds every cargo call; the sentinel asserts none escapes), a
|
|
3356
3875
|
// carried read (the broker owns the output and a carried child gets no CARGO_TARGET_DIR) and the broker client itself.
|
|
3357
3876
|
let readTargetEnv = {};
|
|
3358
|
-
if (s.class === SCAN_CLASS.A && s.tool === "cargo" && !
|
|
3877
|
+
if (s.class === SCAN_CLASS.A && s.tool === "cargo" && !cargoLedger && !options.cargoSentinel && !Object.hasOwn(s.env ?? {}, "CARGO_TARGET_DIR")) {
|
|
3359
3878
|
try { owned.cargoReadTarget = cargoReadTargetDir({ tmpRoot: options.cargoReadTargetRoot ?? tmpRoot, roots: [contentRoot, liveRoot, cargoLiveRoot] }); }
|
|
3360
3879
|
catch (e) { return { ...row, status: "fail", code: "CARGO_READ_TARGET", detail: `${s.id}: ${e.message}` }; }
|
|
3361
3880
|
readTargetEnv = { CARGO_TARGET_DIR: owned.cargoReadTarget };
|
|
@@ -3421,7 +3940,7 @@ export async function runScans(plan, options = {}) {
|
|
|
3421
3940
|
// The scan's run limit is a stopwatch. A scan the broker carries (class B, not a quiet suite under its lease) is watched: the stopwatch does not tick while
|
|
3422
3941
|
// every request of the scan is QUEUED at the broker (broker-admission.mjs), so queue time is neither charged to the scan nor bounded by a gate allowance.
|
|
3423
3942
|
// Without a live reader (no client to ask) the stopwatch simply runs, and every unwatched carried scan gives its client the scan's own limit as the operation deadline
|
|
3424
|
-
// (RUSTRIGHT_OPERATION_DEADLINE_MS
|
|
3943
|
+
// (RUSTRIGHT_OPERATION_DEADLINE_MS, scanOperationEnv), so the client cancels by id before the gate stops it.
|
|
3425
3944
|
const watched = carriedScan && s.class === SCAN_CLASS.B && s.quiet !== true && brokerLive !== null;
|
|
3426
3945
|
let admission = null; let graceTimer = null; let genRefDir = null; let clockExpired = false;
|
|
3427
3946
|
// A carried scan is cancelled by id first and its process tree stopped only after a grace; any other scan is stopped at once.
|
|
@@ -3437,70 +3956,56 @@ export async function runScans(plan, options = {}) {
|
|
|
3437
3956
|
// Every class A row that executes repository code (tests, lint/typecheck with repository config, generators) runs under the
|
|
3438
3957
|
// launch guard: class A runs before any compile, so none of them may start one (joint plan step 4; inventory gap 3).
|
|
3439
3958
|
const guardEnv = s.class === SCAN_CLASS.A && (s.kind === "test" || s.executes === true) ? launchGuardEnv({ ...deps.env, ...s.env, ...(extraEnv ?? {}) }) : {};
|
|
3440
|
-
// The broker snapshot carrier (joint plan step 4d): this one cargo request names the commit, the snapshot, the ownership
|
|
3441
|
-
// handle and its own argv and working directory, under a fresh nonce; the ownership records the submit first.
|
|
3442
3959
|
const finalArgs = args.map((a) => (a === "{contentRoot}" ? contentRoot : a));
|
|
3443
3960
|
// SwiftPM writes its `.build/` inside the package by default: that must never land in the commit snapshot or the checkout, so the
|
|
3444
3961
|
// build directory is the gate's own, keyed by the repository and the scan so it stays warm.
|
|
3445
|
-
// GB-67: on a broker host the scan is the
|
|
3962
|
+
// GB-67: on a broker host the scan is the seam's `rightkit-swift` adapter job and the broker owns SwiftPM's scratch (it appends the one managed path and the
|
|
3446
3963
|
// product location is `build --show-bin-path`): the gate sends no scratch or build path, and never adds one. Only a host with no broker (Linux direct) keeps its own.
|
|
3447
|
-
const
|
|
3964
|
+
const swiftSeam = viaSeam && s.tool === "swift";
|
|
3965
|
+
// The broker owns SwiftPM's scratch for the seam job (`rustright run rightkit-swift`): the `rightkit-swift` adapter checks it
|
|
3966
|
+
// (rustright check_swift_state_flags refuses --scratch-path/--build-path; check_swift_package requires the one relative --package-path). GB-67, 833f62ae0.
|
|
3967
|
+
const swiftBrokered = s.tool === "swift" && swiftSeam;
|
|
3448
3968
|
// The adapter takes exactly one relative --package-path (adapter.rs check_swift_package); the scan runs in its package directory, so that is `.`.
|
|
3449
3969
|
if (swiftBrokered && finalArgs[0] === "build" && !finalArgs.some((a) => a === "--package-path" || a.startsWith("--package-path="))) finalArgs.splice(1, 0, "--package-path", ".");
|
|
3450
3970
|
if (s.tool === "swift" && finalArgs[0] === "build" && !swiftBrokered && !finalArgs.some((a) => a === "--scratch-path" || a === "--build-path" || a.startsWith("--scratch-path=") || a.startsWith("--build-path="))) {
|
|
3451
3971
|
try { finalArgs.push("--scratch-path", swiftScratchPath({ tmpRoot, roots: [contentRoot, liveRoot, cargoLiveRoot], id: s.id })); }
|
|
3452
3972
|
catch (e) { stopClock(); advisory?.cleanup?.(); return { ...row, status: "fail", code: "SWIFT_SCRATCH", detail: `${s.id}: ${e.message}` }; }
|
|
3453
3973
|
}
|
|
3454
|
-
let carrier = null;
|
|
3455
|
-
if (viaSnapshotBroker) {
|
|
3456
|
-
const sb = deps.snapshotBroker;
|
|
3457
|
-
const cwd = path.join(rootDir(s.root), s.cwd ?? "");
|
|
3458
|
-
const refDir = fs.mkdtempSync(path.join(os.tmpdir(), "rk-snapreq-"));
|
|
3459
|
-
try {
|
|
3460
|
-
const cargoArgv = s.tool === "rustright" ? finalArgs.slice(1) : finalArgs;
|
|
3461
|
-
const made = writeSnapshotRequest({ controlRoot: sb.controlRoot, commit: sb.commit, snapshot: sb.snapshot, declaredInputs: sb.declaredInputs ?? [], handle: sb.handle, primaryCwd: fs.realpathSync.native(cwd), argv: cargoArgv, requestIdFile: path.join(refDir, "request.json") });
|
|
3462
|
-
carrier = { made, refDir, cargoArgv };
|
|
3463
|
-
} catch (e) { fs.rmSync(refDir, { recursive: true, force: true }); stopClock(); advisory?.cleanup?.(); return { ...row, status: "fail", code: "SNAPSHOT_REQUEST", detail: `the snapshot request for ${s.id} could not be written: ${e.message}` }; }
|
|
3464
|
-
}
|
|
3465
|
-
// From here to the end of its verification the carrier and the request reference are this request's: every exit (cancel,
|
|
3466
|
-
// timeout, a thrown spawn, a refused receipt) removes them.
|
|
3467
3974
|
// A wrapped snapshot compile with several Cargo workspaces (options.cargoSentinel, item 7): a scan whose own env binds no
|
|
3468
3975
|
// CARGO_TARGET_DIR gets an empty directory of its own as one. Every cargo reached through the wrapper is bound elsewhere; only
|
|
3469
3976
|
// a cargo that bypassed it (an absolute path, `rustup run`, a reset PATH) can write here, and the scan then fails below.
|
|
3977
|
+
// A seam row never names a target directory: the broker pins the job's target (BUILD.md "Queue/tests/adapters": "Broker pins target"),
|
|
3978
|
+
// and a caller-supplied CARGO_TARGET_DIR or CARGO_BUILD_TARGET_DIR that differs is refused at admission ("conflicting CARGO_BUILD_TARGET_DIR",
|
|
3979
|
+
// every class B row of the first HR run on the reset broker, 2026-11-09). No sentinel is made for it and both variables are stripped below.
|
|
3470
3980
|
let sentinel = null;
|
|
3471
|
-
|
|
3472
|
-
if (options.cargoSentinel && !viaSnapshotBroker && !Object.hasOwn(s.env ?? {}, "CARGO_TARGET_DIR")) {
|
|
3981
|
+
if (!viaSeam && options.cargoSentinel && !Object.hasOwn(s.env ?? {}, "CARGO_TARGET_DIR")) {
|
|
3473
3982
|
sentinel = path.join(options.cargoSentinel, sha256(s.id).slice(0, 16));
|
|
3474
3983
|
fs.rmSync(sentinel, { recursive: true, force: true });
|
|
3475
3984
|
fs.mkdirSync(sentinel, { recursive: true });
|
|
3476
3985
|
}
|
|
3477
3986
|
const sentinelEnv = sentinel ? { CARGO_TARGET_DIR: sentinel, CARGO_BUILD_TARGET_DIR: sentinel } : {};
|
|
3987
|
+
// The composed spawn environment of a seam row, with no target directory of the caller's (the broker pins it; see above).
|
|
3988
|
+
const seamSpawnEnv = (composed) => { if (!viaSeam) return composed; const out = { ...composed }; for (const key of Object.keys(out)) if (/^(CARGO_TARGET_DIR|CARGO_BUILD_TARGET_DIR)$/i.test(key)) delete out[key]; return out; };
|
|
3478
3989
|
// A Rust test scan's JSON listing (every compiler-artifact record) streams whole to a file of its own: the kept tail of a spawn would lose the early artifact records of a noisy compile.
|
|
3479
3990
|
let listingDir = null; let listingFile = null; let listingText = ""; let listingCut = false;
|
|
3480
3991
|
let testOutputs = null;
|
|
3481
3992
|
if (s.runOutside || s.captureJson) { listingDir =fs.mkdtempSync(path.join(tmpRoot, "rk-testlist-")); listingFile = path.join(listingDir, "listing.jsonl"); }
|
|
3482
3993
|
try {
|
|
3483
|
-
// The
|
|
3484
|
-
|
|
3485
|
-
|
|
3486
|
-
|
|
3487
|
-
|
|
3488
|
-
|
|
3489
|
-
|
|
3490
|
-
|
|
3491
|
-
|
|
3492
|
-
}
|
|
3994
|
+
// The seam's two variables, last so nothing overrides them; the Class A verdict is written (or read) before the first class B spawn of its workspace.
|
|
3995
|
+
let seamVars = {};
|
|
3996
|
+
// An npm or node suite that reaches the broker (`brokerCall`) on a seam run makes its cargo calls through the runtime wrapper, which sends them through the seam when
|
|
3997
|
+
// these two variables are present (cargo-target-shim.mjs). Each call names the verdict of its own directory,
|
|
3998
|
+
// derived from this one (seam-broker.mjs runSeamCall); its outcome is filed in this scan's ledger and counted below.
|
|
3999
|
+
const seamSuite = !viaSeam && Boolean(deps.gateSeam) && s.class === SCAN_CLASS.B && Boolean(s.brokerCall);
|
|
4000
|
+
if (viaSeam || seamSuite) {
|
|
4001
|
+
try { seamVars = seamEnv({ commit: deps.gateSeam.commit, classA: await ensureVerdict(viaSeam ? (s.cwd ?? ".") : ".") }); }
|
|
4002
|
+
catch (e) { stopClock(); advisory?.cleanup?.(); return { ...row, status: "fail", code: "CLASS_A_VERDICT", detail: `${s.id}: ${e.message}` }; }
|
|
3493
4003
|
}
|
|
3494
|
-
if (
|
|
3495
|
-
//
|
|
3496
|
-
|
|
3497
|
-
|
|
3498
|
-
|
|
3499
|
-
if (watched) { admission = watchBrokerAdmission({ clock: runClock, refFiles: () => swiftRefs, live: brokerLive, poller: statusPoller }); admission.start(); }
|
|
3500
|
-
try {
|
|
3501
|
-
const carried = await carryBrokerAdapterAsync({ adapter: "rightkit-swift", words: finalArgs, cwd: path.join(rootDir(s.root), s.cwd ?? ""), env: { ...deps.env, ...s.env, ...(extraEnv ?? {}), ...swiftBudget.env }, ...(swiftBudget.deadlineMs !== undefined ? { deadlineMs: swiftBudget.deadlineMs } : {}), section: brokerSection(deps.snapshotBroker), record: (entry) => { if (typeof entry.requestRef === "string" && !swiftRefs.includes(entry.requestRef)) swiftRefs.push(entry.requestRef); if (cargoLedger && ledgerToken) appendLedger(cargoLedger.dir, ledgerToken, entry); }, err: () => {}, stdio: "capture", signal: scanSignal, spawn: deps.adapterSpawn ?? defaultSpawnAsync });
|
|
3502
|
-
r = { status: carried.status, stdout: carried.stdout, stderr: carried.stderr };
|
|
3503
|
-
} catch (e) { r = { error: e }; } finally { stopClock(); advisory?.cleanup?.(); }
|
|
4004
|
+
if (swiftSeam) {
|
|
4005
|
+
// The adapter through the seam: one `rustright run rightkit-swift -- <argv>` in the snapshot; the result line and receipt are judged below exactly as a cargo row's.
|
|
4006
|
+
const client = toolCommand("rustright");
|
|
4007
|
+
try { r = await deps.spawn(client, ["run", "rightkit-swift", "--", ...finalArgs], { cwd: path.join(deps.gateSeam.snapshot, s.cwd ?? ""), env: seamSpawnEnv({ ...deps.env, ...s.env, ...(extraEnv ?? {}), ...seamVars }), signal: scanSignal, timeout: limitMs }); }
|
|
4008
|
+
catch (e) { r = { error: e }; } finally { stopClock(); advisory?.cleanup?.(); }
|
|
3504
4009
|
} else {
|
|
3505
4010
|
// The executables this scan runs are the ones resolved and verified above: read their bytes again now, immediately before the launch
|
|
3506
4011
|
// (a replaced binary is TOOL_REPLACED), and hand the scan only those paths: actionlint its shellcheck, cargo its cargo-deny / cargo-audit.
|
|
@@ -3521,18 +4026,17 @@ export async function runScans(plan, options = {}) {
|
|
|
3521
4026
|
const wrapperBin = (cargoLedger || options.cargoSentinel) && typeof scanCargo === "string" && typeof scanPath === "string" ? (deps.platform === "win32" ? path.win32 : path.posix).dirname(scanCargo) : null;
|
|
3522
4027
|
const wrapperFirst = wrapperBin !== null && scanPath.split(pathSep)[0] === wrapperBin;
|
|
3523
4028
|
const trustEnv = trustedDirs.length ? { [pathKey]: (wrapperFirst ? [wrapperBin, ...trustedDirs, scanPath.slice(wrapperBin.length + 1)] : [...trustedDirs, scanPath]).filter(Boolean).join(pathSep) } : {};
|
|
3524
|
-
// A watched scan names where its client writes the request id (RUSTRIGHT_REQUEST_ID_FILE) so the gate can ask the broker for it:
|
|
3525
|
-
// a scan that reaches the broker through `rustright cargo`, or the reference files its
|
|
4029
|
+
// A watched scan names where its client writes the request id (RUSTRIGHT_REQUEST_ID_FILE) so the gate can ask the broker for it: a file of its own for
|
|
4030
|
+
// a scan that reaches the broker through `rustright cargo`, or the reference files its seam calls record in the cargo ledger (an npm suite with a broker call).
|
|
3526
4031
|
let refEnv = {};
|
|
3527
4032
|
if (watched) {
|
|
3528
4033
|
let refFiles;
|
|
3529
|
-
if (
|
|
3530
|
-
else if (s.tool === "rustright" || s.tool === "cargo") { genRefDir = fs.mkdtempSync(path.join(os.tmpdir(), "rk-scanreq-")); const file = path.join(genRefDir, "request.json"); refEnv = { RUSTRIGHT_REQUEST_ID_FILE: file }; refFiles = () => [file]; }
|
|
4034
|
+
if (s.tool === "rustright" || s.tool === "cargo") { genRefDir = fs.mkdtempSync(path.join(os.tmpdir(), "rk-scanreq-")); const file = path.join(genRefDir, "request.json"); refEnv = { RUSTRIGHT_REQUEST_ID_FILE: file }; refFiles = () => [file]; }
|
|
3531
4035
|
else refFiles = () => { try { return ledgerToken && cargoLedger ? readLedger(cargoLedger.dir, ledgerToken).entries.filter((e) => e.status === "pending" && typeof e.requestRef === "string").map((e) => e.requestRef) : []; } catch { return []; } };
|
|
3532
4036
|
admission = watchBrokerAdmission({ clock: runClock, refFiles, live: brokerLive, poller: statusPoller });
|
|
3533
4037
|
admission.start();
|
|
3534
4038
|
}
|
|
3535
|
-
try { r = await deps.spawn(p.command, spawnArgs, { cwd: path.join(rootDir(s.root), s.cwd ?? ""), env: { ...deps.env, ...sentinelEnv, ...readTargetEnv, ...s.env, ...(extraEnv ?? {}), ...guardEnv, ...ledgerEnv, ...
|
|
4039
|
+
try { r = await deps.spawn(p.command, spawnArgs, { cwd: viaSeam ? path.join(deps.gateSeam.snapshot, s.cwd ?? "") : path.join(rootDir(s.root), s.cwd ?? ""), env: seamSpawnEnv({ ...deps.env, ...sentinelEnv, ...readTargetEnv, ...s.env, ...(extraEnv ?? {}), ...guardEnv, ...ledgerEnv, ...refEnv, ...(carriedScan && !watched ? scanOperationEnv({ ...deps.env, ...s.env }, limitMs) : {}), ...trustEnv, ...seamVars }), signal: scanSignal, ...(listingFile ? { stdoutFile: listingFile } : {}), ...(watched ? {} : { timeout: limitMs }) }); } finally { stopClock(); advisory?.cleanup?.(); }
|
|
3536
4040
|
if ((s.runOutside || s.captureJson) && r && !r.error) {
|
|
3537
4041
|
// The whole listing: the file the spawn streamed, else (a spawn that does not know stdoutFile) its stdout. What a reader sees of a failed compile is the rendered errors.
|
|
3538
4042
|
let fromFile = false;
|
|
@@ -3565,8 +4069,12 @@ export async function runScans(plan, options = {}) {
|
|
|
3565
4069
|
let problems;
|
|
3566
4070
|
try {
|
|
3567
4071
|
const ledger = readLedger(cargoLedger.dir, ledgerToken);
|
|
3568
|
-
problems = [...ledger.problems
|
|
3569
|
-
|
|
4072
|
+
problems = [...ledger.problems];
|
|
4073
|
+
// The seam calls this scan's own process made (a suite's cargo through the wrapper): the row is a seam row for the door's lock, settled only when every such
|
|
4074
|
+
// call is, and no record is unreadable (its owner is unknown).
|
|
4075
|
+
const seamCalls = ledger.entries.filter((e) => e.mode === "seam");
|
|
4076
|
+
if (!viaSeam && (seamCalls.length || (deps.gateSeam && ledger.malformed))) { row.seam = true; row.seamSettled = ledger.malformed === 0 && seamCalls.every((e) => e.settled === true); }
|
|
4077
|
+
} catch (e) { problems = [`the cargo ledger cannot be read (${e.message})`]; if (deps.gateSeam && !viaSeam) { row.seam = true; row.seamSettled = false; } }
|
|
3570
4078
|
if (problems.length) {
|
|
3571
4079
|
ledgerProblem = true;
|
|
3572
4080
|
const text = `${s.id}: the gate's cargo ledger records ${problems.length} cargo call(s) that did not complete as a verified success: ${problems.slice(0, 5).join("; ")}`;
|
|
@@ -3580,37 +4088,24 @@ export async function runScans(plan, options = {}) {
|
|
|
3580
4088
|
}
|
|
3581
4089
|
// The broker's signed account of that request: the receipt verifies against this host's pins and its snapshotEvidence names
|
|
3582
4090
|
// this commit, this snapshot unchanged from START to exit, this ownership and the output directory. Anything less fails the row.
|
|
3583
|
-
|
|
3584
|
-
|
|
3585
|
-
|
|
3586
|
-
|
|
3587
|
-
|
|
3588
|
-
|
|
3589
|
-
|
|
3590
|
-
|
|
3591
|
-
}
|
|
3592
|
-
|
|
3593
|
-
|
|
3594
|
-
|
|
3595
|
-
|
|
3596
|
-
|
|
3597
|
-
|
|
3598
|
-
|
|
3599
|
-
if (original?.code !== "result" || status !== "fail" || code !== "EXIT" || signal?.aborted || !Number.isSafeInteger(r?.status) || r.status <= 0) throw original;
|
|
3600
|
-
verified = verifySnapshotReceipt(receipt, { ...receiptOptions, allowFailedCompile: true });
|
|
3601
|
-
if (verified.signedResult?.status !== "FAILED" || verified.signedResult.failureClass !== "compile" || verified.signedResult.exitCode !== r.status || verified.signedResult.signal !== null) throw original;
|
|
3602
|
-
code = "BROKER_COMPILE_FAILURE";
|
|
3603
|
-
// Bisection needs the fully verified, signed post-run verdict as well as the matching client exit.
|
|
3604
|
-
row.authenticatedFailure = { status: verified.signedResult.status, failureClass: verified.signedResult.failureClass, exitCode: verified.signedResult.exitCode, postChecks: verified.signedResult.postChecks, retryable: verified.signedResult.postChecks?.verified === true };
|
|
3605
|
-
}
|
|
3606
|
-
const { evidence } = verified;
|
|
3607
|
-
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 } : {}) };
|
|
3608
|
-
} catch (e) {
|
|
3609
|
-
status = "fail"; code = "SNAPSHOT_EVIDENCE"; detail = `${s.id}: the broker's snapshot evidence did not verify (${e.code ?? "error"}: ${e.message})`;
|
|
3610
|
-
}
|
|
4091
|
+
// The seam's verdict for the row (gate-seam.mjs judgeSeamOutcome): exactly one rustright-result line, a durable receipt whose postconditions hold for this
|
|
4092
|
+
// commit and tree, read before the exit code; a refusal keeps its code, a killed child with no line fails, an executed failure keeps its exit.
|
|
4093
|
+
if (viaSeam && !signal?.aborted) {
|
|
4094
|
+
// What this row sent, for the receipt's own request fields: the cargo argv after `cargo` (or the adapter's argv), the directory it ran in, the adapter if any.
|
|
4095
|
+
const sentArgv = swiftSeam ? finalArgs : (finalArgs[0] === "cargo" ? finalArgs.slice(1) : finalArgs);
|
|
4096
|
+
const judged = judgeSeamOutcome({ child: r, stderr: r?.stderr ?? "", commit: deps.gateSeam.commit, tree: deps.gateSeam.tree, classA: seamVars[CLASS_A_ENV] ?? null, expect: { argv: sentArgv, cwd: path.join(deps.gateSeam.snapshot, s.cwd ?? ""), adapter: swiftSeam ? "rightkit-swift" : null } });
|
|
4097
|
+
// The receipt's test executable list is always recorded, a null one with the broker's reason, so every listing is judged against it (GC-A08: an executable runs only when
|
|
4098
|
+
// it is on the compile receipt's signed list; a seam receipt with no list runs nothing).
|
|
4099
|
+
if (judged.evidence) row.snapshotEvidence = { receiptSha256: judged.evidence.receiptSha256, receiptPath: judged.evidence.receiptPath, requestId: judged.evidence.requestId, outputDir: judged.evidence.outputDir, targetTriple: judged.evidence.targetTriple ?? null, cargoDir: s.cwd ?? ".", seam: true, testExecutables: judged.evidence.testExecutables ?? null, testExecutablesReason: judged.evidence.testExecutablesReason ?? null, receiptStatus: judged.evidence.receiptStatus ?? null };
|
|
4100
|
+
// Settled, for the door's lock release (seamRunState): positive evidence only. A parsed result line AND either a durable receipt read (the job reached its
|
|
4101
|
+
// terminal state) or an explicit before-execution refusal (a code, or exit 125 with nothing admitted). A missing or malformed line, a missing receipt, a killed
|
|
4102
|
+
// client or a spawn error leaves the row unsettled, and the lock stays (astra, 2026-11-09).
|
|
4103
|
+
// A code with a requestId is a client failure AFTER admission (cli.rs transport_failure_after_admission_retains_correlation: RK_CLIENT_ERROR, exit 125, no receipt): the job's
|
|
4104
|
+
// state is unknown, so it is NOT settled. Only a refusal before admission (no requestId) or a durable receipt settles the row (astra, 2026-11-09).
|
|
4105
|
+
row.seamSettled = seamSettled(judged);
|
|
4106
|
+
if (judged.status === "fail") { status = "fail"; code = judged.code; detail = `${s.id}: ${judged.detail}`; }
|
|
3611
4107
|
}
|
|
3612
4108
|
} finally {
|
|
3613
|
-
if (carrier) { removeCarrier(carrier.made.file); fs.rmSync(carrier.refDir, { recursive: true, force: true }); }
|
|
3614
4109
|
if (tscProject) fs.rmSync(tscProject.dir, { recursive: true, force: true });
|
|
3615
4110
|
if (listingDir) fs.rmSync(listingDir, { recursive: true, force: true });
|
|
3616
4111
|
}
|
|
@@ -3621,17 +4116,31 @@ export async function runScans(plan, options = {}) {
|
|
|
3621
4116
|
if (s.runOutside && status === "pass" && r && !r.error) {
|
|
3622
4117
|
const fail = (c, d) => { status = "fail"; code = c; detail = d; };
|
|
3623
4118
|
const listing = parseTestListing(listingText);
|
|
3624
|
-
const platform = deps.
|
|
4119
|
+
const platform = deps.platform ?? process.platform;
|
|
3625
4120
|
if (listingCut) fail("TEST_LISTING", `${s.id}: the compile listing was cut at the kept output tail, so the test executables cannot be enumerated`);
|
|
3626
4121
|
else if (listing.buildFinished !== true) fail("TEST_LISTING", `${s.id}: the compile exited 0 but its listing has no successful build-finished record (${listing.buildFinished === false ? "a build-finished record said failure" : "none found"})`);
|
|
3627
4122
|
else if (listing.binaries.length === 0) {
|
|
3628
4123
|
// End-to-end tests only (Adrian, 2026-11-03): a crate whose test build lists no test executable has no test to run; the row passes
|
|
3629
|
-
// with zero libtest counts, the same as a test build that runs none (testResultsProblem).
|
|
3630
|
-
|
|
3631
|
-
|
|
4124
|
+
// with zero libtest counts, the same as a test build that runs none (testResultsProblem). Only after the same receipt judgments as a listing with
|
|
4125
|
+
// executables (GC-A08): the broker's list must be present (a missing or null list, with its reason, is unsigned) and must itself be empty, or cargo's
|
|
4126
|
+
// listing lost what the compile produced (fresh reviews of badf93c).
|
|
4127
|
+
const signedOn = viaSeam && row.snapshotEvidence && Object.hasOwn(row.snapshotEvidence, "testExecutables");
|
|
4128
|
+
const signedList = signedOn ? row.snapshotEvidence.testExecutables : null;
|
|
4129
|
+
const zeroPlatform = deps.platform ?? process.platform;
|
|
4130
|
+
const unsigned = signedOn ? signedTestExecutableProblems([], signedList, row.snapshotEvidence.testExecutablesReason, zeroPlatform) : [];
|
|
4131
|
+
if (viaSeam && !signedOn) fail("TEST_EXECUTABLE_UNSIGNED", `${s.id}: the broker's receipt lists no test executables`);
|
|
4132
|
+
else if (unsigned.length) fail("TEST_EXECUTABLE_UNSIGNED", `${s.id}: ${unsigned.slice(0, 3).join("; ")}; the row fails and nothing was run`);
|
|
4133
|
+
else if (Array.isArray(signedList) && signedList.length) fail("TEST_EXECUTABLE_MISSING", `${s.id}: the broker's receipt lists ${signedList.length} test executable(s) and cargo's listing yielded none; the row fails and nothing was run`);
|
|
4134
|
+
else {
|
|
4135
|
+
row.results = { runner: "libtest", tests: 0, pass: 0, fail: 0, skipped: 0, todo: 0, binaries: 0 };
|
|
4136
|
+
row.acceptedBinaries = []; row.executableProof = executableProofOf([], []); // its serial row has nothing to run either, and never compiles again for it
|
|
4137
|
+
// A test group with no executable at all: every member has its own empty run, so the member projection carries it to the member's serial row.
|
|
4138
|
+
if (Array.isArray(s.testGroup)) row.memberRuns = Object.fromEntries(s.testGroup.map((m) => [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`, acceptedBinaries: [], executableProof: executableProofOf([], []) }]));
|
|
4139
|
+
detail = `${s.id}: no test executable (${listing.artifacts} artifact record(s)); end-to-end tests only, nothing to run`;
|
|
4140
|
+
}
|
|
3632
4141
|
} else {
|
|
3633
4142
|
let boundDirs; let generationRoots = null;
|
|
3634
|
-
if (
|
|
4143
|
+
if (viaSeam) { boundDirs = row.snapshotEvidence?.outputDir ? [row.snapshotEvidence.outputDir] : []; generationRoots = deps.gateSeam.outputRoots ?? null; }
|
|
3635
4144
|
else {
|
|
3636
4145
|
const scanDir = path.join(rootDir(s.root), s.cwd ?? "");
|
|
3637
4146
|
const target = s.env?.CARGO_TARGET_DIR ?? deps.env?.CARGO_TARGET_DIR ?? "target";
|
|
@@ -3639,12 +4148,19 @@ export async function runScans(plan, options = {}) {
|
|
|
3639
4148
|
}
|
|
3640
4149
|
const ops = { ...TEST_RUN_OPS, ...(options.testRunOps ?? {}) };
|
|
3641
4150
|
const contained = containTestExecutables(listing.binaries, { boundDirs, generationRoots, platform, ops });
|
|
4151
|
+
row.acceptedBinaries = contained.accepted; // for a serial row of the same crate that reuses them (rightkit#1539); never stored in the cache (storedPassRow)
|
|
4152
|
+
row.executableProof = executableProofOf(contained.accepted, boundDirs); // the digest-bound proof a later serial row re-checks when this row is a cache hit
|
|
3642
4153
|
// ADR-001 C2 (rightkit#1454): a broker that signs the compile's test executables (receipt.testExecutables, rustright) binds each one;
|
|
3643
|
-
// an executable whose path or sha256 is not in that signed list never runs.
|
|
3644
|
-
const signedProblems =
|
|
3645
|
-
|
|
4154
|
+
// an executable whose path or sha256 is not in that signed list never runs. A receipt with no list runs nothing (TEST_EXECUTABLE_UNSIGNED below); a null list carries the broker's reason.
|
|
4155
|
+
const signedProblems = viaSeam && row.snapshotEvidence && Object.hasOwn(row.snapshotEvidence, "testExecutables") ? signedTestExecutableProblems(contained.accepted, row.snapshotEvidence.testExecutables, row.snapshotEvidence.testExecutablesReason, platform) : [];
|
|
4156
|
+
// The seam's receipt is the broker's list of what the compile produced: an executable it lists that cargo's stdout did not yield (a cut listing, a parse gap)
|
|
4157
|
+
// would otherwise never run and nothing would say so (fresh review 2026-11-09, E5). Every listed executable must be among the ones about to run.
|
|
4158
|
+
const receiptMissing = viaSeam && Array.isArray(row.snapshotEvidence?.testExecutables) ? row.snapshotEvidence.testExecutables.map((e) => (typeof e?.path === "string" ? e.path : typeof e?.executable === "string" ? e.executable : null)).filter(Boolean).filter((p) => { let real = p; try { real = fs.realpathSync.native(p); } catch { /* compared as given */ } return !contained.accepted.some((b) => b.real === real || b.executable === p); }) : [];
|
|
4159
|
+
// GC-A08: on every broker route a test compile's executables run only from the receipt's list; a receipt with no list field runs nothing (not only for publishers).
|
|
4160
|
+
if (viaSeam && !Object.hasOwn(row.snapshotEvidence ?? {}, "testExecutables")) fail("TEST_EXECUTABLE_UNSIGNED", `${s.id}: the broker's receipt lists no test executables`);
|
|
3646
4161
|
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`);
|
|
3647
4162
|
else if (signedProblems.length) fail("TEST_EXECUTABLE_UNSIGNED", `${s.id}: ${signedProblems.slice(0, 5).join("; ")}; the row fails and nothing was run`);
|
|
4163
|
+
else if (receiptMissing.length) fail("TEST_EXECUTABLE_MISSING", `${s.id}: the broker's receipt lists ${receiptMissing.length} test executable(s) cargo's listing did not yield (${receiptMissing.slice(0, 3).join(", ")}); the row fails and nothing was run`);
|
|
3648
4164
|
else if (Array.isArray(s.testGroup)) {
|
|
3649
4165
|
// 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
4166
|
const byCrate = new Map();
|
|
@@ -3653,9 +4169,9 @@ export async function runScans(plan, options = {}) {
|
|
|
3653
4169
|
const worker = async () => {
|
|
3654
4170
|
while (next < list.length) {
|
|
3655
4171
|
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
|
|
4172
|
+
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`, acceptedBinaries: [], executableProof: executableProofOf([], []) }; continue; }
|
|
3657
4173
|
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) } };
|
|
4174
|
+
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) }, acceptedBinaries: bins, executableProof: executableProofOf(bins, boundDirs) };
|
|
3659
4175
|
}
|
|
3660
4176
|
};
|
|
3661
4177
|
await Promise.all(Array.from({ length: Math.max(1, Math.min(testRunConcurrency(), list.length)) }, worker));
|
|
@@ -3700,13 +4216,16 @@ export async function runScans(plan, options = {}) {
|
|
|
3700
4216
|
const problem = status === "pass" && row.results ? testResultsProblem(row.results) : null;
|
|
3701
4217
|
if (problem) { status = "fail"; code = problem.code; detail = problem.detail; }
|
|
3702
4218
|
}
|
|
4219
|
+
// NN41: on a seam row code EXIT means the judge read this job's own durable receipt, its postconditions held and the executed command itself failed
|
|
4220
|
+
// (gate-seam.mjs judgeSeamOutcome), so the failure is the broker's authenticated one and is cached like a pass, keyed with the broker's runtime identity. Only a receipt
|
|
4221
|
+
// whose status is FAILED: a TIMED_OUT or CANCELLED job keeps its observed exit (it may be cargo's own) but its failure is the stop, never the source.
|
|
3703
4222
|
// 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
|
|
3704
4223
|
// 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).
|
|
3705
|
-
if (status === "fail" && failKey && !signal?.aborted && !ledgerProblem && typeof detail === "string" && detail !== "" && (
|
|
4224
|
+
if (status === "fail" && failKey && !signal?.aborted && !ledgerProblem && typeof detail === "string" && detail !== "" && (code === "EXIT" && (!carriedScan || (viaSeam && row.snapshotEvidence?.receiptStatus === "FAILED"))) && isDeterministicCompileDiagnostics(`${r?.stdout ?? ""}\n${r?.stderr ?? ""}`)) {
|
|
3706
4225
|
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 } : {}) });
|
|
3707
4226
|
}
|
|
3708
4227
|
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,
|
|
4228
|
+
if (status === "pass" && cacheKey && !signal?.aborted) cache.write(cacheKey, storedPassRow(s, row));
|
|
3710
4229
|
}
|
|
3711
4230
|
}
|
|
3712
4231
|
} catch (e) { status = "fail"; code = "SCAN_ERROR"; detail = e.message; }
|
|
@@ -3729,12 +4248,23 @@ export async function runScans(plan, options = {}) {
|
|
|
3729
4248
|
results.push({ id: "cargo-ledger", class: SCAN_CLASS.B, command: "cargo ledger", tool: null, toolVersion: null, status: "fail", code: "RK_CARGO_LEDGER", detail: `cargo calls were filed under ${unclaimed.length} scan token(s) no scan owns (${unclaimed.slice(0, 3).join(", ")}), so they cannot be tied to a scan (${SCAN_TOKEN_ENV} was cleared, or the call came from outside every scan): ${calls.slice(0, 5).join("; ") || "unreadable"}` });
|
|
3730
4249
|
}
|
|
3731
4250
|
}
|
|
4251
|
+
// A class-A-only run on a seam host writes the root verdict its class B run (classAEarlier) will name; nothing is written when any row failed, and a
|
|
4252
|
+
// green class A whose verdict could not be written is not a passing run (the compile that follows would have no verdict to name).
|
|
4253
|
+
const seamNotes = []; let verdictFailure = null;
|
|
4254
|
+
if (deps.gateSeam && classes.includes(SCAN_CLASS.A) && !classes.includes(SCAN_CLASS.B) && !classAFailed && !signal?.aborted) {
|
|
4255
|
+
// The verdict of this run's scope (full, or the --scope dirs it covered); a green class A that cannot write it has failed.
|
|
4256
|
+
try { seamNotes.push(`class A verdict written: ${await ensureVerdict(".")}`); } catch (e) { verdictFailure = `CLASS_A_VERDICT: class A passed but its verdict was not written: ${e.message}`; seamNotes.push(verdictFailure); }
|
|
4257
|
+
}
|
|
3732
4258
|
const cancelled = signal?.aborted === true;
|
|
4259
|
+
// Positive evidence only: a seam row is settled when it carries seamSettled (a parsed result with a durable receipt or an explicit refusal, a cache hit, a lookup); every other seam row, whatever its code, keeps the lock.
|
|
4260
|
+
for (const r of results) if (r.seam === true) { seamRunState.rows += 1; if (r.seamSettled !== true || (cancelled && r.status !== "pass")) seamRunState.unsettled += 1; }
|
|
4261
|
+
if (deps.gateSeam) seamRunState.open -= 1;
|
|
4262
|
+
const allPassed = !cancelled && verdictFailure === null && results.every((r) => r.status === "pass");
|
|
3733
4263
|
return {
|
|
3734
|
-
schema: SCAN_RESULT_SCHEMA, ok:
|
|
4264
|
+
schema: SCAN_RESULT_SCHEMA, ok: allPassed, complete: allPassed, classes, checker, ...(cancelled ? { cancelled: true } : {}), ...(verdictFailure ? { verdictFailure } : {}),
|
|
3735
4265
|
inputDigest: plan.inputDigest ?? null,
|
|
3736
4266
|
deferred: results.filter((r) => r.status === "deferred").map((r) => r.id),
|
|
3737
|
-
scans: results, toolVersions, toolIdentities, cacheHits: [...cacheHits].sort(), notes: [...(plan.notes ?? []), ...batchFailureNotes, ...(cargoLedger ? [UNOBSERVED_NESTED_CARGO_NOTE] : [])],
|
|
4267
|
+
scans: results, toolVersions, toolIdentities, cacheHits: [...cacheHits].sort(), notes: [...(plan.notes ?? []), ...batchFailureNotes, ...partitionNotes, ...seamNotes, ...(cargoLedger ? [UNOBSERVED_NESTED_CARGO_NOTE] : [])],
|
|
3738
4268
|
scanSetDigest: digestScanSet(results),
|
|
3739
4269
|
classDigests: { A: digestScanSet(results.filter((r) => r.class === "A")), B: digestScanSet(results.filter((r) => r.class === "B")) },
|
|
3740
4270
|
};
|