@rightkit/release 0.6.56 → 0.6.61
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 +4 -0
- package/acceptance-admission.mjs +104 -0
- package/acceptance-launch.mjs +234 -0
- package/acceptance-lines.mjs +1254 -0
- package/acceptance-result.mjs +77 -0
- package/acceptance-rows.mjs +47 -0
- package/admission-files.mjs +2 -0
- package/affected-units.mjs +17 -0
- package/app-check.mjs +6 -2
- package/app-closure.mjs +3 -1
- package/bin/rightkit-gate.mjs +546 -121
- package/broker-admission.mjs +45 -2
- package/broker-pins.mjs +11 -1
- package/broker-toolchain.mjs +113 -0
- package/cargo-profile-contract.mjs +7 -2
- package/class-a-cache-history.mjs +135 -0
- package/cli/right-release.mjs +0 -0
- package/code-closure.mjs +24 -0
- package/config-inspect.mjs +6 -0
- package/consumer-contracts.mjs +3 -1
- package/contract-nn.json +166 -0
- package/deterministic-scans.mjs +835 -112
- package/feature-coverage.mjs +109 -82
- package/feature-partition.mjs +76 -0
- package/forbidden-literals.mjs +78 -0
- package/gate/calls.mjs +121 -0
- package/gate/compile.mjs +190 -0
- package/gate/crate-results.mjs +127 -0
- package/gate/run-calls.mjs +241 -0
- package/gate/tests.mjs +234 -0
- package/gate-coverage.mjs +12 -3
- package/gate-release-admission.mjs +200 -0
- package/gate-seam.mjs +100 -4
- package/gate-serve.mjs +178 -32
- package/gate-stages.mjs +59 -0
- package/legacy-contract-receipt.mjs +809 -0
- package/local-publish.mjs +7 -5
- package/local-runtime.mjs +2 -2
- package/nsis-payload.mjs +4 -3
- package/ownership-applicability.mjs +5 -0
- package/ownership-class-rules.mjs +19 -8
- package/ownership-mandatory-set.json +15 -21
- package/ownership-mandatory-set.mjs +19 -4
- package/package.json +14 -8
- package/probe-memo.mjs +252 -0
- package/publication-artifacts.mjs +56 -2
- package/publish-local-npm.mjs +3 -0
- package/publish-update.mjs +2 -2
- package/receipt-signature.mjs +40 -0
- package/release.mjs +47 -29
- package/resident-answers.mjs +66 -0
- package/rightkit-ownership.json +20 -11
- package/rightkit-versions.json +349 -183
- package/runtime-bundle-stage.mjs +146 -0
- package/scan-digest.mjs +28 -4
- package/seam-broker.mjs +8 -1
- package/shell-contract.mjs +23 -2
- package/snapshot-changes.mjs +106 -0
- package/snapshot-check.mjs +17 -13
- package/snapshot-dependency-reuse.mjs +186 -14
- package/snapshot-git.mjs +17 -1
- package/snapshot-metadata.mjs +155 -3
- package/snapshot.mjs +90 -12
- package/spawn-ledger.mjs +21 -2
- package/stage-sidecar.mjs +231 -19
- package/suite-trust-roots.mjs +2 -2
- package/test-env.mjs +26 -0
- package/tool-version-memo.mjs +46 -0
- package/win-package-recipe.mjs +11 -0
- package/bin/darwin/rightkit-swap +0 -0
- package/gate-acceptance.mjs +0 -3362
package/bin/rightkit-gate.mjs
CHANGED
|
@@ -73,6 +73,8 @@
|
|
|
73
73
|
// SIGINT/SIGTERM stop scheduling, kill every running scan's process tree and exit non-zero listing the scans not run.
|
|
74
74
|
import fs from "node:fs";
|
|
75
75
|
import { createHash, randomUUID } from "node:crypto";
|
|
76
|
+
import { openClassAHistory, openClassBHistory } from "../class-a-cache-history.mjs";
|
|
77
|
+
import { writeFileAtomic } from "../atomic-write.mjs";
|
|
76
78
|
import { envNamed, gateRunsRoot, resolveManagedRoots } from "../managed-roots.mjs";
|
|
77
79
|
import { resolveBrokerClient, spawnBrokerClient } from "../broker-client.mjs";
|
|
78
80
|
import os from "node:os";
|
|
@@ -81,20 +83,33 @@ import { hostTarget } from "../cross-targets.mjs";
|
|
|
81
83
|
import { FOREIGN_PRE_COMMIT, retireHooksIn } from "../hook-retirement.mjs";
|
|
82
84
|
import { fileURLToPath } from "node:url";
|
|
83
85
|
import { installIdentity, installStateBytes } from "../dependency-identity.mjs";
|
|
86
|
+
import { pnpmVersionAnswer } from "../snapshot-dependency-reuse.mjs";
|
|
84
87
|
import { BIOME_CONFIG_FILES, CHECKER_IDENTITY, OXLINT_CONFIG_FILES, ESLINT_CONFIG_FILES, LOCAL_CLASS_B_JOBS, WORKSPACE_RUST_FILE, ancestorConfigChanged, ancestorDirsOf, canonicalJson, defaultSpawn, defaultSpawnAsync, judgeUnitList, blockedUnitsOf, digestScanSet, fileScanCache, findRustfmt, metadataArgs, planScans, planUnitListScans, publisherRequirementScan, runScans, sidecarBoundCrate, scanToolPolicyFromPipeline, scanDeferrals, scanFailures, seamRunState } from "../deterministic-scans.mjs";
|
|
85
88
|
import { changedLockNames, parseLock, reach } from "../lock-graph.mjs";
|
|
86
89
|
import { resolveExecutor } from "../gate-executor.mjs";
|
|
87
90
|
// The gate's own executor: an outer gate's cargo wrapper on PATH is never this gate's cargo (gate-executor.mjs `gateWrappers`).
|
|
88
91
|
const gateResolveExecutor = (args) => resolveExecutor({ ...args, gateWrappers: true });
|
|
92
|
+
/**
|
|
93
|
+
* NN09, NN25: which cargo and rustc the broker compiles with, read in this process from the broker's own host configuration
|
|
94
|
+
* (broker-toolchain.mjs) instead of asking through the client (`rustright cargo --version`, `rustright rustc -V`). null for an injected
|
|
95
|
+
* spawn (a test sees every start it expects), for a host that does not compile through the RustRight client, and on any doubt; the caller then
|
|
96
|
+
* asks as before.
|
|
97
|
+
*/
|
|
98
|
+
function brokerToolchainOf(o, executor) {
|
|
99
|
+
if (o.spawn !== defaultSpawn || executor?.kind !== "broker" || !Array.isArray(executor.cargo) || executor.cargo.length < 2) return null;
|
|
100
|
+
let answer = null;
|
|
101
|
+
try { const launcher = resolveOnPath(executor.cargo[0], { env: o.env, platform: o.platform }); answer = launcher ? brokerToolchain({ launcher }) : null; } catch { answer = null; }
|
|
102
|
+
return answer?.ok ? answer : null;
|
|
103
|
+
}
|
|
89
104
|
import { ALL_UNITS_ERRORS, ALL_UNITS_EXCEPTIONS_FILE, BROKER_EXCEPTIONS_FILE, BROKER_EXCEPTION_ERRORS, CARGO_WORKSPACE_LIST_FILE, CARGO_WORKSPACE_LIST_KEY, RIGHTKIT_IDENTITY_FILE, authorizeAllUnits, authorizeNoBroker, checkCargoWorkspaceList, describeAllUnitsException, describeBrokerException, isRightKitIdentity, unitsOfSelector } from "../broker-exception.mjs";
|
|
90
105
|
import { SIGNING_REFUSAL_CODES, suiteSigningRefusals } from "../suite-signing-policy.mjs";
|
|
91
106
|
import { gitListRustFiles } from "../signing-files.mjs";
|
|
92
107
|
import { nativeHelpersFromConfig } from "../native-helpers.mjs";
|
|
93
|
-
import { buildCoverageReport, seconds, writeCoverageReport } from "../gate-coverage.mjs";
|
|
108
|
+
import { buildCoverageReport, limitedEvidenceOf, seconds, writeCoverageReport } from "../gate-coverage.mjs";
|
|
94
109
|
import { renderViews, renderViewsOf } from "../render-views.mjs";
|
|
95
110
|
import { LINUX_BROKER_ROUTE, NO_BROKER_ENV, directCargoPath, directPlatform, managedRuntimeClient, realCargoOf, runCargoSync } from "../managed-cargo.mjs";
|
|
96
111
|
import { createBrokerLive } from "../broker-admission.mjs";
|
|
97
|
-
import { bindingOf, compileOutputsRecord, compileReuseProblem, endRun, readReceipt, RECEIPT_SCHEMA, receiptKey, sameBinding, sameSource, sealedFor, stagesTo, startRun, STAGES, STAGE_SOURCES, writeReceipt } from "../gate-stages.mjs";
|
|
112
|
+
import { bindingOf, builtBinsOfRun, compileOutputsRecord, compileReuseProblem, endRun, readReceipt, RECEIPT_SCHEMA, receiptKey, sameBinding, sameSource, sealedFor, stagesTo, startRun, STAGES, STAGE_SOURCES, writeReceipt } from "../gate-stages.mjs";
|
|
98
113
|
import { spawnSync as spawnInherit } from "../background-process.mjs";
|
|
99
114
|
// GC-A21: a run that stamps its own lines also stamps its inherited-output children's lines, through stamp-relay.mjs in front of the child
|
|
100
115
|
// (the launch stays synchronous and the output still streams). Set by main() when the run stamps; off for machine-readable runs.
|
|
@@ -106,15 +121,21 @@ const inheritLaunch = (cmd, a, opts) => (stampChildLines
|
|
|
106
121
|
import { readDiskPolicy, scratchRoots } from "../disk-policy.mjs";
|
|
107
122
|
import { buildDirectReceipt, directVerdict, resolveTargetDirectory, verifyDirectReceipt, writeDirectDiagnostics } from "../direct-receipt.mjs";
|
|
108
123
|
import { platformDirOf } from "../platform-dir.mjs";
|
|
109
|
-
import { buildInventory, classifyUnitResults, dependencyFirstOrder, selectAffectedAcrossInventories, unitListReport } from "../affected-units.mjs";
|
|
124
|
+
import { buildInventory, classifyUnitResults, dependencyFirstOrder, selectAffectedAcrossInventories, classifyUnitRows, unitListReport } from "../affected-units.mjs";
|
|
110
125
|
import { createRequire } from "node:module";
|
|
111
|
-
import { BUILD_CONTROL_PROTOCOL, HANDSHAKE_PROBE_ID, RUNTIME_MANIFEST_FILE, parseRuntimeIdentity } from "../seam-broker.mjs";
|
|
126
|
+
import { BUILD_CONTROL_PROTOCOL, HANDSHAKE_PROBE_ID, RUNTIME_MANIFEST_FILE, brokerControlTarget, parseRuntimeIdentity } from "../seam-broker.mjs";
|
|
112
127
|
import { snapshotReclaimJudge } from "../seam-broker.mjs";
|
|
113
128
|
import net from "node:net";
|
|
114
129
|
import { installSpawnLedger } from "../spawn-ledger.mjs";
|
|
130
|
+
import { rememberedVersion, resolveOnPath } from "../tool-version-memo.mjs";
|
|
131
|
+
import { brokerToolchain } from "../broker-toolchain.mjs";
|
|
132
|
+
import { SNAPSHOT_PROOF_COUNTS, snapshotProofLine } from "../snapshot.mjs";
|
|
133
|
+
import { contentStore, installProbeMemo } from "../probe-memo.mjs";
|
|
134
|
+
import { discoveryRun, sealedRepoInfo, setTreeListingStore } from "../snapshot-git.mjs";
|
|
115
135
|
import { processIdentity, snapshotLockBody, verdictFileName } from "../gate-seam.mjs";
|
|
116
136
|
|
|
117
137
|
const PRIVATE_SCOPED_COMPILE = Symbol("private scoped compile");
|
|
138
|
+
const CLASS_A_HISTORY = Symbol("Class A cache history");
|
|
118
139
|
const UNIT_LIST_UNION = Symbol("unit list union");
|
|
119
140
|
// Class B row input digests per tree (see rowDigest in the compile stage); counted so the run summary shows the time keying took.
|
|
120
141
|
const ROW_DIGEST_MEMO = new Map();
|
|
@@ -484,7 +505,7 @@ export function installedDependencyDigest({ root, files, includeCaches = true })
|
|
|
484
505
|
* (node_modules/.modules.yaml) and the installed dependency bytes (installedDependencyDigest). The broker binds an admission ticket to it and recomputes it when the compile starts
|
|
485
506
|
* (`rightkit-gate env-digest`), so a dependency or tool change while a compile waits invalidates the ticket.
|
|
486
507
|
*/
|
|
487
|
-
export function classAEnvironmentDigest({ root, files, spawn = defaultSpawn, includeCaches = true, gatePackage = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..") }) {
|
|
508
|
+
export function classAEnvironmentDigest({ root, files, spawn = defaultSpawn, includeCaches = true, gatePackage = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."), onRowEnvironment }) {
|
|
488
509
|
// Only a file that does not exist is "absent"; any other read failure throws: an input whose bytes cannot be read is never
|
|
489
510
|
// identified by a placeholder that would match the same failure later.
|
|
490
511
|
// `optional`: only an install-state file may legitimately not exist; a gate file found by the walk must be readable.
|
|
@@ -499,14 +520,21 @@ export function classAEnvironmentDigest({ root, files, spawn = defaultSpawn, inc
|
|
|
499
520
|
const gateFiles = [`class-a-key-schema:${CLASS_A_KEY_SCHEMA}`, ...walkGate(gatePkg).sort().map((f) => path.relative(gatePkg, f)).filter((rel) => !releaseOnly(rel)).map((rel) => `${rel}:${fileDigest(path.join(gatePkg, rel))}`)];
|
|
500
521
|
// Bounded: a pnpm that switches itself to the repository's packageManager version on first use, or waits on the network,
|
|
501
522
|
// must fail the probe (and its process tree) within PNPM_PROBE_TIMEOUT_MS, never hang an admission.
|
|
502
|
-
|
|
523
|
+
// NN25, NN07: asked once and then kept by the open gate process while the files that decide which pnpm runs here are unchanged
|
|
524
|
+
// (snapshot-dependency-reuse.mjs pnpmVersionAnswer); only the real spawn remembers, a failed or timed-out probe is never kept.
|
|
525
|
+
const pnpmVersion = pnpmVersionAnswer({ cwd: root, env: process.env, remember: spawn === defaultSpawn, run: () => {
|
|
503
526
|
const r = spawn("pnpm", ["--version"], { cwd: root, boundedMs: PNPM_PROBE_TIMEOUT_MS });
|
|
504
527
|
if (r?.timedOut) throw new Error(`cannot identify pnpm for the class A environment (pnpm --version timed out after ${PNPM_PROBE_TIMEOUT_MS} ms; run it once in ${root} so pnpm can switch to the packageManager version)`);
|
|
505
528
|
if (failed(r) || !text(r).trim()) throw new Error(`cannot identify pnpm for the class A environment (${r?.error ? `could not run pnpm: ${r.error.code ?? r.error.message}` : why(r)})`);
|
|
506
529
|
return text(r).trim();
|
|
507
|
-
})
|
|
508
|
-
const installState =
|
|
509
|
-
|
|
530
|
+
} });
|
|
531
|
+
const installState =files.filter((f) => /(^|\/)package\.json$/.test(f)).map((f) => path.join(path.dirname(path.join(root, f)), "node_modules", ".modules.yaml")).map((m) => { let d; try { d = createHash("sha256").update(installStateBytes(".modules.yaml", fs.readFileSync(m))).digest("hex"); } catch (error) { d = fileDigest(m, { optional: true }); } return `${path.relative(root, m)}:${d}`; });
|
|
532
|
+
const installed = installedDependencyDigest({ root, files, includeCaches });
|
|
533
|
+
const bind = (gateInputs) => createHash("sha256").update([`node ${process.version}`, `pnpm ${pnpmVersion}`, `platform ${process.platform}-${process.arch}`, ...gateInputs, ...installState, `installed ${installed}`].join("\n")).digest("hex");
|
|
534
|
+
// The verdict binds all gate data. Only cargo-deny rows using the packaged
|
|
535
|
+
// policy read deny-default.toml. Their per-row digest binds its exact bytes.
|
|
536
|
+
if (onRowEnvironment) onRowEnvironment(bind(gateFiles.filter((entry) => !entry.startsWith("deny-default.toml:"))));
|
|
537
|
+
return bind(gateFiles);
|
|
510
538
|
}
|
|
511
539
|
|
|
512
540
|
/** The pnpm a package.json pins (`packageManager: "pnpm@12.16.1+sha512.."` -> `12.16.1`), or null for no pnpm pin. */
|
|
@@ -540,8 +568,9 @@ export function pnpmPinProblem({ root, files, spawn = defaultSpawn, readFile = (
|
|
|
540
568
|
if (pin) pins.set(f, pin);
|
|
541
569
|
}
|
|
542
570
|
if (!pins.size) return null;
|
|
543
|
-
|
|
544
|
-
|
|
571
|
+
// Kept by the open gate process like the Class A environment's probe (pnpmVersionAnswer); a probe that fails is asked again next time.
|
|
572
|
+
let r = null; // the probe's own result when it ran (the refusals below name its error); null when the kept answer was used
|
|
573
|
+
const onPath = pnpmVersionAnswer({ cwd: neutralCwd, env: process.env, remember: spawn === defaultSpawn, run: () => { r = spawn("pnpm", ["--version"], { cwd: neutralCwd, boundedMs: PNPM_PROBE_TIMEOUT_MS }); return failed(r) ? "" : text(r).trim(); } }) ?? "";
|
|
545
574
|
const fix = (pin) => `install the pinned pnpm as the pnpm on PATH (for example \`pnpm self-update ${pin}\`), or make the repository's own pin resolvable (corepack enable, network access to the pnpm release), and run again`;
|
|
546
575
|
const bad = [...pins].filter(([, pin]) => pin !== onPath);
|
|
547
576
|
if (!bad.length) return null;
|
|
@@ -842,6 +871,86 @@ export function lockScope({ changed, cargoDir = ".", unitNames, showBase, readLo
|
|
|
842
871
|
// The build inputs that change how every crate compiles, relative to the Cargo workspace root, plus the gate's own config.
|
|
843
872
|
const SHARED_RUST_INPUTS = ["Cargo.lock", "Cargo.toml", "rust-toolchain", "rust-toolchain.toml", ".cargo", "deny.toml", "clippy.toml", ".clippy.toml", "rustfmt.toml", ".rustfmt.toml", "vendor"];
|
|
844
873
|
const GATE_CONFIG = "ci/gate.config.json";
|
|
874
|
+
/**
|
|
875
|
+
* The Cargo.toml files a workspace at `dir` reads (NN04: one edited manifest reruns only its workspace): every one under `dir`, and every one reached
|
|
876
|
+
* through a `path = "..."` or `path = '...'` dependency of those (dependencies, [dependencies.x] tables, [patch], [workspace.dependencies]),
|
|
877
|
+
* transitively. `all`: the commit's file list; `readBlob(path)`: a file's text.
|
|
878
|
+
* Whenever it cannot be sure it found every manifest the workspace reads, it answers EVERY Cargo.toml of the commit (GC-A19's key), never fewer:
|
|
879
|
+
* a manifest it cannot read, a `path =` it cannot parse (a multi-line or escaped string), a workspace member outside `dir` (`members` naming
|
|
880
|
+
* `..`), or a Cargo configuration of `dir` or an ancestor that overrides paths (`paths =` in .cargo/config[.toml]) (astra62 review, 2026-11-18).
|
|
881
|
+
*/
|
|
882
|
+
// smol-toml loads on first parse (as in cargo-contract.mjs), so a CI job whose closure only imports this module needs no install; when it cannot
|
|
883
|
+
// load, every reader here answers "cannot tell" (null, or every manifest), never fewer checks or manifests.
|
|
884
|
+
let manifestTomlParse;
|
|
885
|
+
const parseManifestToml = (text) => (manifestTomlParse ??= createRequire(import.meta.url)("smol-toml").parse)(text);
|
|
886
|
+
export function cargoManifestsOfWorkspace({ dir, all, readBlob }) {
|
|
887
|
+
const isManifest = (f) => /(^|\/)Cargo\.toml$/.test(f);
|
|
888
|
+
const present = new Set(all.filter(isManifest));
|
|
889
|
+
const every = [...present].sort();
|
|
890
|
+
const isTable = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
|
|
891
|
+
// Decoded TOML (smol-toml), so every spelling of a key means what Cargo reads (astra62 review 3: a Unicode-escaped "path" key). Null: unreadable or unparsable.
|
|
892
|
+
const docOf = (f) => { try { const t = readBlob(f); return typeof t === "string" ? parseManifestToml(t) : null; } catch { return null; } };
|
|
893
|
+
const inRepo = (p) => { const n = path.posix.normalize(p); return n.startsWith("..") ? null : n === "." ? "" : n; };
|
|
894
|
+
const join = (base, rel) => inRepo(path.posix.join(base === "." ? "" : base, rel));
|
|
895
|
+
// A Cargo configuration of the workspace or an ancestor that overrides or patches paths: every manifest.
|
|
896
|
+
const dirs = dir === "." ? ["."] : dir.split("/").map((_, i, parts) => parts.slice(0, i + 1).join("/")).concat(".");
|
|
897
|
+
for (const d of dirs) for (const name of [".cargo/config.toml", ".cargo/config"]) {
|
|
898
|
+
const p = d === "." ? name : `${d}/${name}`;
|
|
899
|
+
if (!all.includes(p)) continue;
|
|
900
|
+
const doc = docOf(p);
|
|
901
|
+
if (doc === null || doc.paths !== undefined || doc.patch !== undefined) return every;
|
|
902
|
+
}
|
|
903
|
+
const out = new Set([...present].filter((f) => dir === "." || f.startsWith(`${dir}/`))); const queue = [...out];
|
|
904
|
+
const add = (m) => { if (m !== null && present.has(m) && !out.has(m)) { out.add(m); queue.push(m); } };
|
|
905
|
+
// The workspace root a member inherits from: `package.workspace`, else the nearest ancestor manifest with a [workspace] table.
|
|
906
|
+
const rootOf = (m, doc) => {
|
|
907
|
+
const base = path.posix.dirname(m);
|
|
908
|
+
if (isTable(doc.workspace)) return m;
|
|
909
|
+
if (isTable(doc.package) && doc.package.workspace !== undefined) return typeof doc.package.workspace === "string" ? join(base, `${doc.package.workspace}/Cargo.toml`) : undefined;
|
|
910
|
+
for (let d = base; d !== "." && d !== ""; d = path.posix.dirname(d)) {
|
|
911
|
+
const up = path.posix.dirname(d) === "." ? "Cargo.toml" : `${path.posix.dirname(d)}/Cargo.toml`;
|
|
912
|
+
if (!present.has(up)) continue;
|
|
913
|
+
const parent = docOf(up); if (parent === null) return undefined;
|
|
914
|
+
if (isTable(parent.workspace)) return up;
|
|
915
|
+
}
|
|
916
|
+
return null;
|
|
917
|
+
};
|
|
918
|
+
while (queue.length) {
|
|
919
|
+
const m = queue.pop(); const doc = docOf(m);
|
|
920
|
+
if (doc === null) return every;
|
|
921
|
+
const base = path.posix.dirname(m);
|
|
922
|
+
// dev_dependencies and build_dependencies are the spellings Cargo accepted before edition 2024 (astra62 review 4).
|
|
923
|
+
const tables = [doc.dependencies, doc["dev-dependencies"], doc["build-dependencies"], doc.dev_dependencies, doc.build_dependencies, doc.replace,
|
|
924
|
+
...(isTable(doc.target) ? Object.values(doc.target).flatMap((t) => (isTable(t) ? [t.dependencies, t["dev-dependencies"], t["build-dependencies"], t.dev_dependencies, t.build_dependencies] : [null])) : []),
|
|
925
|
+
...(isTable(doc.workspace) ? [doc.workspace.dependencies] : []),
|
|
926
|
+
...(isTable(doc.patch) ? Object.values(doc.patch) : doc.patch === undefined ? [] : [null])];
|
|
927
|
+
let inherits = false;
|
|
928
|
+
for (const t of tables) {
|
|
929
|
+
if (t === undefined) continue;
|
|
930
|
+
if (!isTable(t)) return every;
|
|
931
|
+
for (const spec of Object.values(t)) {
|
|
932
|
+
if (!isTable(spec)) continue;
|
|
933
|
+
// A backslash is a separator to Cargo on Windows and a file-name character elsewhere: cannot tell which manifest, so every one.
|
|
934
|
+
if (spec.path !== undefined) { if (typeof spec.path !== "string" || spec.path.includes("\\")) return every; add(join(base, `${spec.path}/Cargo.toml`)); }
|
|
935
|
+
if (spec.workspace === true) inherits = true;
|
|
936
|
+
}
|
|
937
|
+
}
|
|
938
|
+
// Any `workspace = true` anywhere outside the [workspace] table (a dependency, a package field, `[lints] workspace = true`, whatever Cargo adds next)
|
|
939
|
+
// reads the workspace root's manifest: follow it to the root, wherever it is, for this manifest and every path dependency reached (astra62 review 4:
|
|
940
|
+
// a dependency's inherited lints come from its own workspace's root).
|
|
941
|
+
const inheritsAnywhere = (v, depth = 0) => isTable(v) && depth < 8 && (v.workspace === true || Object.entries(v).some(([k, x]) => !(depth === 0 && k === "workspace") && inheritsAnywhere(x, depth + 1)));
|
|
942
|
+
if (inherits || inheritsAnywhere(doc)) {
|
|
943
|
+
const root = rootOf(m, doc);
|
|
944
|
+
if (root === undefined || root === null) return every;
|
|
945
|
+
add(root);
|
|
946
|
+
}
|
|
947
|
+
// A member named outside the workspace directory: every manifest (members may be globs; only those inside are found by the directory rule).
|
|
948
|
+
// Only the keyed workspace's own root: another workspace reached through a path dependency contributes its manifest, not its members.
|
|
949
|
+
if (m === (dir === "." ? "Cargo.toml" : `${dir}/Cargo.toml`) && isTable(doc.workspace) && Array.isArray(doc.workspace.members) && doc.workspace.members.some((x) => typeof x !== "string" || join(base, x) === null || (dir !== "." && !`${join(base, x)}/`.startsWith(`${dir}/`)))) return every;
|
|
950
|
+
}
|
|
951
|
+
return [...out].sort();
|
|
952
|
+
}
|
|
953
|
+
|
|
845
954
|
// What cargo, clippy, rustfmt and cargo-deny also read from EVERY ancestor directory of the workspace (the repository root and each
|
|
846
955
|
// directory between it and the workspace: they search upward), relative to that directory.
|
|
847
956
|
const ANCESTOR_RUST_INPUTS = [".cargo", "rust-toolchain", "rust-toolchain.toml", "clippy.toml", ".clippy.toml", "rustfmt.toml", ".rustfmt.toml", "deny.toml"];
|
|
@@ -904,7 +1013,9 @@ const within = (dir, p) => dir === "." || p === dir || p.startsWith(`${dir}/`);
|
|
|
904
1013
|
// current directory, a bare ".." segment, or the manifest directory's parent. Its tests may read anything in the repository.
|
|
905
1014
|
// A comparison with ".." (`name != ".."`), a method whose name only ends in current_dir (`get_current_dir()`), `.ancestors()` of a runtime path and
|
|
906
1015
|
// comment text do not leave the crate; they keyed whole crates' tests on the whole tree (rightkit-fs, rightkit-child-process; NN20, 2026-11-06).
|
|
907
|
-
|
|
1016
|
+
// A literal made only of parent steps ("..", "../", "../..", "../../") is such a walk, however many steps; one handed to a string test
|
|
1017
|
+
// (`starts_with("../")`, `contains("..")`) or compared with == or != is not.
|
|
1018
|
+
const TEST_LEAVES_CRATE = /CARGO_WORKSPACE_DIR|workspace_root|(?<![A-Za-z0-9_])current_dir\s*\(|(?<![=!]=\s{0,4})(?<!\b(?:starts_with|ends_with|contains|strip_prefix|strip_suffix)\s{0,2}\(\s{0,4})"\.\.(?:[\\/]{1,2}\.\.)*(?:[\\/]{1,2})?"|CARGO_MANIFEST_DIR[^;\n]{0,120}\.(?:parent|ancestors)\s*\(/;
|
|
908
1019
|
|
|
909
1020
|
export function externalInputs({ dir, files, readBlob, exists, includeRuntimePaths = true }) {
|
|
910
1021
|
const paths = new Set(); let unresolved = null; let leavesCrate = null;
|
|
@@ -920,6 +1031,11 @@ export function externalInputs({ dir, files, readBlob, exists, includeRuntimePat
|
|
|
920
1031
|
const resolved = path.posix.normalize(path.posix.join(base, raw)).replace(/\/+$/, "");
|
|
921
1032
|
if (resolved === ".." || resolved.startsWith("../")) { escapes += 1; continue; }
|
|
922
1033
|
if (within(dir, resolved) || paths.has(resolved)) continue;
|
|
1034
|
+
// A literal that resolves to a directory the crate itself is inside ("../", "../.." from the crate or one of its files) names no file. It is string
|
|
1035
|
+
// handling (`clean.starts_with("../")`) or the start of a path completed elsewhere. Taken as an input it is the tree id of the whole repository, or of
|
|
1036
|
+
// crates/, so every commit changed the key: six RustRight crates reran 38 rows per commit for this (Mac and Dell, 2026-11-17). Compile rows read
|
|
1037
|
+
// files only through include macros, #[path] and build scripts, all followed above. A TEST that walks up this way is caught by TEST_LEAVES_CRATE.
|
|
1038
|
+
if (resolved === "." || dir.startsWith(`${resolved}/`)) continue;
|
|
923
1039
|
if (exists(resolved)) { paths.add(resolved); if (resolved.endsWith(".rs")) enqueue(resolved, { external: true }); }
|
|
924
1040
|
}
|
|
925
1041
|
if (escapes === bases.length) stop(`${from}: ${JSON.stringify(rel)} leaves the repository`);
|
|
@@ -1014,7 +1130,7 @@ const plainRelative = (p) => typeof p === "string" && p !== "" && !path.posix.is
|
|
|
1014
1130
|
* package, whatever its spec, transitively, by package name) and the root npm inputs; (the scripts/ci self-test scan no longer exists: Adrian, 2026-11-03, end-to-end tests only). Every other class B scan (generated-docs, swift-build) uses the whole tree.
|
|
1015
1131
|
* - Class A: pnpm-lockfile and advisory-exceptions are never cached (live answers). cargo-deny, cargo-audit and pnpm-audit are cached by
|
|
1016
1132
|
* their inputs and the identity of the advisory data they read (rightkit#1464, ADR-001 C5; advisoryKey below): a Cargo workspace's lock
|
|
1017
|
-
* blob,
|
|
1133
|
+
* blob, the workspace's manifest closure, configuration, and the pinned RustSec commit (cargo-deny and cargo-audit
|
|
1018
1134
|
* read exactly that commit); a pnpm root's lock, manifests and npm configuration. cargo-deny also reads the crate index (yanked
|
|
1019
1135
|
* versions) and pnpm audit asks the registry, neither of which a commit pins, so those keys carry the UTC day: a rerun the same day is a
|
|
1020
1136
|
* hit, the next day is a run. A changed pin, lock, manifest or configuration is a different key; rustfmt,
|
|
@@ -1036,7 +1152,7 @@ function shardSoloOf(o, repo) {
|
|
|
1036
1152
|
} catch { return []; }
|
|
1037
1153
|
}
|
|
1038
1154
|
|
|
1039
|
-
export function buildCacheDigest({ objectId, headTree, rustUnits = [], npmUnits = [], cargoDir = ".", rustLock = null, rustLocks = null, crateFeatures = {}, listFiles = null, readBlob = null, today = () => new Date().toISOString().slice(0, 10), onKeyError = null }) {
|
|
1155
|
+
export function buildCacheDigest({ objectId, headTree, rustUnits = [], npmUnits = [], cargoDir = ".", rustLock = null, rustLocks = null, crateFeatures = {}, listFiles = null, readBlob = null, today = () => new Date().toISOString().slice(0, 10), onKeyError = null, shellcheckRoot = null, shellcheckEnv = process.env, onUncacheable = null }) {
|
|
1040
1156
|
const memo = new Map(); const reachMemos = new Map(); const externalMemo = new Map();
|
|
1041
1157
|
const idOf = (p) => { if (!memo.has(p)) memo.set(p, p === "." ? headTree : objectId(p)); return memo.get(p); };
|
|
1042
1158
|
// npm: a package's test, tsc and eslint scans read the package, every workspace package it depends on (package.json
|
|
@@ -1110,6 +1226,7 @@ export function buildCacheDigest({ objectId, headTree, rustUnits = [], npmUnits
|
|
|
1110
1226
|
// The key of an advisory scan (rightkit#1464), or null when an input cannot be identified (the scan then runs). Every input that decides the
|
|
1111
1227
|
// verdict and is not in the scan's id, command or environment is here; the advisory database's commit (cargo) is in the scan's own environment
|
|
1112
1228
|
// (RK_ADVISORY_DB_COMMIT) and its pin object, the gate's code and advisory-db.json are in the environment digest the caller appends.
|
|
1229
|
+
let defaultDenyId;
|
|
1113
1230
|
const advisoryKey = (scan) => {
|
|
1114
1231
|
if (typeof listFiles !== "function") return null;
|
|
1115
1232
|
const dir = typeof scan.cwd === "string" && scan.cwd !== "" ? scan.cwd : ".";
|
|
@@ -1137,10 +1254,105 @@ export function buildCacheDigest({ objectId, headTree, rustUnits = [], npmUnits
|
|
|
1137
1254
|
if (idOf(lock) === null || idOf(lock) === undefined) return null;
|
|
1138
1255
|
const ancestors = ancestorDirsOf(dir);
|
|
1139
1256
|
const config = [dir, ...ancestors].flatMap((d) => [".cargo", "deny.toml", "audit.toml", "rust-toolchain", "rust-toolchain.toml"].map((f) => inWs(d, f)));
|
|
1140
|
-
|
|
1141
|
-
|
|
1257
|
+
// NN04: the manifests this workspace reads, not every Cargo.toml of the commit: those under its directory and those its path dependencies reach,
|
|
1258
|
+
// followed to a fixed point (a crate outside the workspace that it depends on still counts). A manifest edit in another workspace kept rerunning
|
|
1259
|
+
// every workspace's deny and audit rows (witness fixture, 2026-11-17: an edit in rk reran app/engine, app/src-tauri, rightkit-a, rightkit-b).
|
|
1260
|
+
const manifests = cargoManifestsOfWorkspace({ dir, all, readBlob });
|
|
1261
|
+
const kind = scan.id.startsWith("cargo-deny") ? "cargo-deny" : "cargo-audit";
|
|
1262
|
+
const inputs = idsOf([lock, ...manifests, ...config]);
|
|
1263
|
+
if (kind === "cargo-deny") {
|
|
1264
|
+
const policy = inWs(dir, "deny.toml");
|
|
1265
|
+
if (!all.includes(policy)) {
|
|
1266
|
+
if (idOf(policy) != null) throw new Error(policy + ": expected a policy file");
|
|
1267
|
+
defaultDenyId ??= createHash("sha256").update(fs.readFileSync(new URL("../deny-default.toml", import.meta.url))).digest("hex");
|
|
1268
|
+
inputs.push(["@rightkit/release/deny-default.toml", defaultDenyId]);
|
|
1269
|
+
} else {
|
|
1270
|
+
const contents = readBlob?.(policy);
|
|
1271
|
+
if (typeof contents !== "string") throw new Error(policy + ": cannot read the workspace policy");
|
|
1272
|
+
inputs.push(["workspace deny policy bytes", createHash("sha256").update(contents).digest("hex")]);
|
|
1273
|
+
}
|
|
1274
|
+
}
|
|
1275
|
+
return canonicalJson({ kind, id: scan.id, day: today(), pin: scan.advisoryPin ?? null, inputs });
|
|
1276
|
+
};
|
|
1277
|
+
const boundShellcheckFiles = (scan) => {
|
|
1278
|
+
const [format, sources, ...entries] = scan.args ?? [];
|
|
1279
|
+
if (scan.root !== "content" || scan.cwd || format !== "--format=gcc" || sources !== "--external-sources" || !entries.length)
|
|
1280
|
+
throw new Error("unsupported ShellCheck command");
|
|
1281
|
+
const env = Object.fromEntries(Object.entries({ ...shellcheckEnv, ...scan.env }).map(([k, v]) => [k.toUpperCase(), v]));
|
|
1282
|
+
if (String(env.SHELLCHECK_OPTS ?? "").trim()) throw new Error("SHELLCHECK_OPTS can add inputs outside the planned command");
|
|
1283
|
+
const root = fs.realpathSync.native(shellcheckRoot);
|
|
1284
|
+
const tracked = new Set(listFiles("."));
|
|
1285
|
+
const inputs = new Set();
|
|
1286
|
+
const present = (file) => {
|
|
1287
|
+
try { fs.lstatSync(file); return true; }
|
|
1288
|
+
catch (error) { if (error.code === "ENOENT" || error.code === "ENOTDIR") return false; throw error; }
|
|
1289
|
+
};
|
|
1290
|
+
const readInput = (relative) => {
|
|
1291
|
+
if (!plainRelative(relative) || relative.startsWith("-") || !tracked.has(relative) || idOf(relative) == null)
|
|
1292
|
+
throw new Error(relative + ": ShellCheck input is outside the tracked file set");
|
|
1293
|
+
const file = path.join(root, relative);
|
|
1294
|
+
if (!fs.lstatSync(file).isFile() || path.relative(file, fs.realpathSync.native(file)))
|
|
1295
|
+
throw new Error(relative + ": ShellCheck input is a link or special file");
|
|
1296
|
+
const content = readBlob(relative);
|
|
1297
|
+
if (typeof content !== "string") throw new Error(relative + ": unreadable ShellCheck input");
|
|
1298
|
+
inputs.add(relative);
|
|
1299
|
+
return content.split(/\r\n|[\r\n]/).map((line) => line.trim());
|
|
1300
|
+
};
|
|
1301
|
+
const safeDirective = /^(?:(?:disable|enable|shell|extended-analysis|external-sources)=[\w,-]+[ \t]*)+$/;
|
|
1302
|
+
const checkedRc = new Set();
|
|
1303
|
+
let checkedHostRc = false;
|
|
1304
|
+
const checkHostRc = () => {
|
|
1305
|
+
if (checkedHostRc) return;
|
|
1306
|
+
const candidates = [];
|
|
1307
|
+
for (let dir = root; path.dirname(dir) !== dir;) {
|
|
1308
|
+
dir = path.dirname(dir);
|
|
1309
|
+
candidates.push(path.join(dir, ".shellcheckrc"), path.join(dir, "shellcheckrc"));
|
|
1310
|
+
}
|
|
1311
|
+
for (const home of new Set([env.HOME, env.USERPROFILE, os.homedir()].filter(Boolean))) {
|
|
1312
|
+
candidates.push(path.resolve(root, home, ".shellcheckrc"), path.resolve(root, home, ".config", "shellcheckrc"));
|
|
1313
|
+
if (process.platform === "win32") candidates.push(path.resolve(root, home, "AppData", "Roaming", "shellcheckrc"));
|
|
1314
|
+
}
|
|
1315
|
+
if (env.APPDATA) candidates.push(path.resolve(root, env.APPDATA, "shellcheckrc"));
|
|
1316
|
+
if (env.XDG_CONFIG_HOME) candidates.push(path.resolve(root, env.XDG_CONFIG_HOME, "shellcheckrc"));
|
|
1317
|
+
const external = candidates.find(present);
|
|
1318
|
+
if (external) throw new Error(external + ": ShellCheck configuration comes from outside tracked content");
|
|
1319
|
+
checkedHostRc = true;
|
|
1320
|
+
};
|
|
1321
|
+
for (const entry of entries) {
|
|
1322
|
+
if (!plainRelative(entry)) throw new Error("unsupported ShellCheck entry path");
|
|
1323
|
+
const candidates = ancestorDirsOf(path.posix.dirname(entry)).reverse().flatMap((d) => [inWs(d, ".shellcheckrc"), inWs(d, "shellcheckrc")]);
|
|
1324
|
+
const rc = candidates.find((f) => tracked.has(f) || present(path.join(root, f)));
|
|
1325
|
+
if (!rc) checkHostRc();
|
|
1326
|
+
else if (!checkedRc.has(rc)) {
|
|
1327
|
+
for (const [i, line] of readInput(rc).entries()) {
|
|
1328
|
+
if (line && !line.startsWith("#") && !safeDirective.test(line)) throw new Error(rc + ":" + (i + 1) + ": unsupported ShellCheck configuration");
|
|
1329
|
+
}
|
|
1330
|
+
checkedRc.add(rc);
|
|
1331
|
+
}
|
|
1332
|
+
}
|
|
1333
|
+
// Prove only complete, simple lines. Compound commands, substitutions and other
|
|
1334
|
+
// source-resolution mechanisms are left to the real tool and receive no reusable key.
|
|
1335
|
+
const safeWord = String.raw`(?:[-\w./:@%+,]+|'[^']*'|"[^"\\$\x60]*")`;
|
|
1336
|
+
const safeLine = new RegExp(String.raw`^(?:(?:set|printf|echo|cd|exit|return|true|false|:)(?:[ \t]+${safeWord})*|[a-zA-Z_]\w*=${safeWord})$`);
|
|
1337
|
+
const literalSource = /^(?:source|\.)[ \t]+(?:"([\w./@+-]+)"|'([\w./@+-]+)'|([\w./@+-]+))$/;
|
|
1338
|
+
const queue = [...entries]; const visited = new Set(queue);
|
|
1339
|
+
for (const file of queue) {
|
|
1340
|
+
for (const [i, line] of readInput(file).entries()) {
|
|
1341
|
+
const annotation = /^#[ \t\u00a0]*shellcheck(?:[ \t\u00a0]+(.*))?$/.exec(line);
|
|
1342
|
+
if (!line || (line.startsWith("#") && !line.endsWith("\\") && (!annotation || safeDirective.test(annotation[1] ?? ""))) || safeLine.test(line)) continue;
|
|
1343
|
+
const source = literalSource.exec(line);
|
|
1344
|
+
const literal = source?.[1] ?? source?.[2] ?? source?.[3];
|
|
1345
|
+
if (literal === "/dev/null") continue;
|
|
1346
|
+
const relative = literal && path.posix.normalize(literal);
|
|
1347
|
+
if (!plainRelative(relative) || literal.startsWith("-") || literal.split("/").includes("..") || !tracked.has(relative))
|
|
1348
|
+
throw new Error(file + ":" + (i + 1) + ": ShellCheck read set is unproven" + (literal ? " for source " + literal : ""));
|
|
1349
|
+
if (!visited.has(relative)) { visited.add(relative); queue.push(relative); }
|
|
1350
|
+
}
|
|
1351
|
+
}
|
|
1352
|
+
return [...inputs];
|
|
1142
1353
|
};
|
|
1143
1354
|
const fileList = (scan) => {
|
|
1355
|
+
if (scan.id === "shellcheck" && shellcheckRoot) return boundShellcheckFiles(scan);
|
|
1144
1356
|
if (Array.isArray(scan.files) && scan.files.length) return scan.files;
|
|
1145
1357
|
const args = Array.isArray(scan.args) ? scan.args : [];
|
|
1146
1358
|
if (/^rustfmt:/.test(scan.id)) {
|
|
@@ -1187,7 +1399,11 @@ export function buildCacheDigest({ objectId, headTree, rustUnits = [], npmUnits
|
|
|
1187
1399
|
if (liveScan(scan.id) && !ADVISORY_SCAN.test(scan.id)) return null;
|
|
1188
1400
|
try {
|
|
1189
1401
|
if (ADVISORY_SCAN.test(scan.id)) return advisoryKey(scan);
|
|
1190
|
-
|
|
1402
|
+
let files;
|
|
1403
|
+
if (scan.id === "shellcheck" && shellcheckRoot) {
|
|
1404
|
+
try { files = fileList(scan); }
|
|
1405
|
+
catch (error) { onUncacheable?.(scan, error.message); return null; }
|
|
1406
|
+
} else files = fileList(scan);
|
|
1191
1407
|
// node --check reads a package.json above the file only for its "type" (module or commonjs): a version bump there is not an input (NN20; every
|
|
1192
1408
|
// release reran 423 node-check rows). Any other read of the manifest, or an unreadable one, keys on its whole content as before.
|
|
1193
1409
|
const nodeType = (p) => { if (!/^node-check:/.test(scan.id) || !/(^|\/)package\.json$/.test(p) || typeof readBlob !== "function") return null; try { const v = JSON.parse(String(readBlob(p))); return `type:${v?.type ?? "commonjs"}`; } catch { return null; } };
|
|
@@ -1452,7 +1668,7 @@ async function installHook(o, root) {
|
|
|
1452
1668
|
* apps/coderight-tauri), else the repository root. Every right-release stage runs there, the sealed set is read from there, and the
|
|
1453
1669
|
* receipt is keyed to it (receiptKey). Returns { appRoot, appDir } with appDir relative to the repository root, "." at the root.
|
|
1454
1670
|
*/
|
|
1455
|
-
export function appRootOf({ root, cwd, exists = fs.existsSync, configDirs = null, platform = process.platform }) {
|
|
1671
|
+
export function appRootOf({ root, cwd, exists = fs.existsSync, configDirs = null, platform = process.platform, soleNestedApp = false }) {
|
|
1456
1672
|
// rightkit#1553: on Windows a path names the same directory in any letter case (git reports D:/Claude/heardright, a runner may start in
|
|
1457
1673
|
// D:\claude\heardright\tauri-app-next). path.win32.relative compares case-blind and keeps the cwd's spelling of each segment; posix stays exact.
|
|
1458
1674
|
// A sibling sharing a prefix (D:\a\bc against root D:\a\b) is outside: relative() answers "..\bc", never a prefix match.
|
|
@@ -1475,6 +1691,14 @@ export function appRootOf({ root, cwd, exists = fs.existsSync, configDirs = null
|
|
|
1475
1691
|
const segments = rel.split(p.sep).filter(Boolean);
|
|
1476
1692
|
for (let n = segments.length; n > 0; n--) { const found = configDirAt(segments.slice(0, n).join("/")); if (found) { appDir = found; break; } }
|
|
1477
1693
|
}
|
|
1694
|
+
// Dev/test/render hand ONE app to right-release. Run from the root of a repository whose selected commit holds no root
|
|
1695
|
+
// config and exactly one nested app, that app is unambiguous (the witness fixture's app/; "--to test" from its root
|
|
1696
|
+
// refused "no right-release.config at <commit>"). Several nested apps stay ambiguous and the root answer stands, so the
|
|
1697
|
+
// stage refuses naming the missing config instead of guessing. Other stages never take this: their scope stays the cwd's.
|
|
1698
|
+
if (soleNestedApp && committed && inside && rel === "" && appDir === "." && !committed.has(fold("."))) {
|
|
1699
|
+
const dirs = [...committed.values()];
|
|
1700
|
+
if (dirs.length === 1) appDir = dirs[0];
|
|
1701
|
+
}
|
|
1478
1702
|
return { appRoot: appDir === "." ? rootAbs : p.join(rootAbs, ...appDir.split("/")), appDir };
|
|
1479
1703
|
}
|
|
1480
1704
|
|
|
@@ -1615,7 +1839,7 @@ export function changedPathsAt({ git, base, commit }) {
|
|
|
1615
1839
|
* (with `--receipt-dir`) plus one aggregate report. Returns the exit the door run ends with: 0 only when every
|
|
1616
1840
|
* selected unit passed, else the first failing unit's code (1 when only blocked units failed the run).
|
|
1617
1841
|
*/
|
|
1618
|
-
export async function runSharedUnitList({ o, io, stage, commit, selected, inventory, receiptDir = undefined, base = null, unmatched = [], runUnit = null }) {
|
|
1842
|
+
export async function runSharedUnitList({ o, io, stage, commit, selected, inventory, receiptDir = undefined, base = null, unmatched = [], runUnit = null, root = null }) {
|
|
1619
1843
|
const tag = "rightkit-gate:";
|
|
1620
1844
|
const bySelector = new Map((inventory?.units ?? []).map((u) => [u.selector, u]));
|
|
1621
1845
|
const rows = selected.map((s) => ({ dir: unitDirOfSelector(s.selector), reason: "listed", ...bySelector.get(s.selector), ...s }));
|
|
@@ -1655,12 +1879,9 @@ export async function runSharedUnitList({ o, io, stage, commit, selected, invent
|
|
|
1655
1879
|
const internal = union.internal.filter((r) => r.selector === unit.selector);
|
|
1656
1880
|
const expected = union.expected?.get(unit.selector);
|
|
1657
1881
|
const all = [...internal, ...evidence];
|
|
1658
|
-
const failed = !expected || all.length !== expected || all.some((r) => r.status === "failed" || r.status === "fail");
|
|
1659
|
-
const blocked = !failed && all.some((r) => r.status === "blocked" || r.status === "not-run");
|
|
1660
1882
|
// A unit passes only on a run that exited 0: a scheduler or stage exception never leaves earlier evidence standing as a pass (cloud 2026-11-06:
|
|
1661
|
-
// a lookup's coverage was reported as 132 passed after "scheduleClassB: invalid projection").
|
|
1662
|
-
|
|
1663
|
-
return { selector: unit.selector, status, ...(status === "failed" ? { code: exit || 1 } : {}) };
|
|
1883
|
+
// a lookup's coverage was reported as 132 passed after "scheduleClassB: invalid projection"). The word and its reason: affected-units.mjs.
|
|
1884
|
+
return { selector: unit.selector, ...classifyUnitRows({ rows: all, expected, exit, verified: union.verified }) };
|
|
1664
1885
|
});
|
|
1665
1886
|
const report = unitListReport({ commit, stage, base, selected: ordered, results, unmatched }); report.runId = union.runId;
|
|
1666
1887
|
for (const row of report.units) {
|
|
@@ -1671,17 +1892,31 @@ export async function runSharedUnitList({ o, io, stage, commit, selected, invent
|
|
|
1671
1892
|
const data = `${JSON.stringify(evidence, null, 2)}\n`; o.writeFile(path.join(receiptDir, name), data);
|
|
1672
1893
|
row.receipt = { status: "written", file: name, sha256: createHash("sha256").update(data).digest("hex") };
|
|
1673
1894
|
}
|
|
1674
|
-
o.out(`${tag} unit ${row.selector}: ${row.status}`);
|
|
1895
|
+
o.out(`${tag} unit ${row.selector}: ${row.status}${row.ownRows === "all-passed" ? " (its own rows all passed; the run did not)" : ""}`);
|
|
1675
1896
|
}
|
|
1676
|
-
|
|
1897
|
+
const onlyRunCount = report.units.filter((u) => u.ownRows === "all-passed").length;
|
|
1898
|
+
o.out(`${tag} unit report: ${report.counts.passed} passed, ${report.counts.failed} failed, ${report.counts.blocked} blocked, ${report.counts["not-run"]} not-run of ${ordered.length} on ${commit.slice(0, 12)}${onlyRunCount ? `; ${onlyRunCount} of the failed had every row of their own passed and ${report.counts.failed - onlyRunCount} had a failure of their own` : ""}`);
|
|
1677
1899
|
if (receiptDir !== undefined) o.writeFile(path.join(receiptDir, "units-report.json"), `${JSON.stringify(report, null, 2)}\n`);
|
|
1678
1900
|
return report.ok ? 0 : (exit || 1);
|
|
1679
1901
|
}
|
|
1680
|
-
|
|
1902
|
+
// NN13 (Dell 2026-11-19, `--to check --units-file` of two units: two `snapshot lock held` lines). Each unit of the list is a door run of its own
|
|
1903
|
+
// and each took the repository's snapshot lock again. The list is one run: it takes the lock once, here, every unit's door joins it
|
|
1904
|
+
// (io.unitListLock, read in runUnitSnapshot where a unit run would take its own), and it is released once, after the last unit, on the same
|
|
1905
|
+
// proof as a door's.
|
|
1906
|
+
let listLock = null;
|
|
1907
|
+
if (!runUnit && !io.runUnitForList && !io.unitListLock && root && o.env.GITHUB_ACTIONS !== "true") {
|
|
1908
|
+
const snap = await import("../snapshot.mjs");
|
|
1909
|
+
const snapshotsAt = o.snapshotRoot ?? snap.snapshotRoot({ platform: o.platform, env: o.env });
|
|
1910
|
+
const taken = takeRunLock({ o, checkout: root, snapshotsAt, commit, snap, tag });
|
|
1911
|
+
if (taken.exit !== undefined) return taken.exit;
|
|
1912
|
+
listLock = { ...taken, started: false };
|
|
1913
|
+
}
|
|
1914
|
+
const run = runUnit ?? io.runUnitForList ?? (async (selector, receipt) => main(["--to", stage, "--unit", selector, "--commit", commit, ...receipt], { ...io, unitListClassA, ...(listLock ? { unitListLock: listLock } : {}) }));
|
|
1681
1915
|
const outcomes = new Map();
|
|
1682
1916
|
const receiptEvidence = new Map();
|
|
1683
1917
|
const runId = randomUUID();
|
|
1684
1918
|
const bad = new Set(); // failed or blocked selectors, for the dependency check of later units
|
|
1919
|
+
try {
|
|
1685
1920
|
for (const [i, row] of ordered.entries()) {
|
|
1686
1921
|
const blocker = (bySelector.get(row.selector)?.deps ?? []).find((d) => bad.has(d));
|
|
1687
1922
|
if (blocker) {
|
|
@@ -1705,6 +1940,7 @@ export async function runSharedUnitList({ o, io, stage, commit, selected, invent
|
|
|
1705
1940
|
outcomes.set(row.selector, { ran: true, code });
|
|
1706
1941
|
if (code !== 0) bad.add(row.selector);
|
|
1707
1942
|
}
|
|
1943
|
+
} finally { if (listLock) releaseSeamLock({ o, release: listLock.release, seamBody: listLock.started ? listLock.body : null, tag }); }
|
|
1708
1944
|
const results = classifyUnitResults({ selected: ordered, inventory: inventory ?? { units: rows }, outcomes });
|
|
1709
1945
|
const report = unitListReport({ commit, stage, base, selected: ordered, results, unmatched });
|
|
1710
1946
|
report.runId = runId;
|
|
@@ -1766,7 +2002,7 @@ export async function rightkitDoorRule(o, args, root, git, io, { unitsFileFlag,
|
|
|
1766
2002
|
const unknown = unitList.filter((selector) => !inventory.units.some((u) => u.selector === selector));
|
|
1767
2003
|
if (unknown.length) { o.err(`${tag} BLOCKED: units missing from inventory: ${unknown.join(", ")}; nothing ran`); return { exit: 2 }; }
|
|
1768
2004
|
const selected = unitList.map((selector) => ({ selector, reason: "listed" }));
|
|
1769
|
-
return { exit: await runSharedUnitList({ o, io, stage, commit: pinned.commit, selected, inventory, receiptDir }) };
|
|
2005
|
+
return { exit: await runSharedUnitList({ o, io, stage, commit: pinned.commit, selected, inventory, receiptDir, root }) };
|
|
1770
2006
|
}
|
|
1771
2007
|
// --changed (rightkit#1505): no handwritten list for routine work. Changed paths against the base select their
|
|
1772
2008
|
// units plus every transitive dependent (affected-units.mjs); the plan is printed before anything runs.
|
|
@@ -1788,7 +2024,7 @@ export async function rightkitDoorRule(o, args, root, git, io, { unitsFileFlag,
|
|
|
1788
2024
|
o.out(`${tag} unit report: 0 passed, 0 failed, 0 blocked, 0 not-run of 0 on ${pinned.commit.slice(0, 12)}`);
|
|
1789
2025
|
return { exit: 0 };
|
|
1790
2026
|
}
|
|
1791
|
-
return { exit: await runSharedUnitList({ o, io, stage, commit: pinned.commit, selected: selection.selected, inventory, receiptDir, base, unmatched: selection.unmatched }) };
|
|
2027
|
+
return { exit: await runSharedUnitList({ o, io, stage, commit: pinned.commit, selected: selection.selected, inventory, receiptDir, base, unmatched: selection.unmatched, root }) };
|
|
1792
2028
|
}
|
|
1793
2029
|
if (allUnitsFlag) {
|
|
1794
2030
|
const id = option("--all-units-exception");
|
|
@@ -1855,7 +2091,7 @@ async function runStages(o, args, root, git, io) {
|
|
|
1855
2091
|
const scopeCommit = o.doorSnapshot ? o.doorSnapshot.commit : selected ? selected.commit : text(git("rev-parse", "HEAD")).trim();
|
|
1856
2092
|
const inventory = committedConfigDirs({ git, commit: scopeCommit });
|
|
1857
2093
|
if (inventory.refusal) { o.err(`${tag} cannot read the app configuration of the selected commit: ${inventory.refusal}`); return 2; }
|
|
1858
|
-
const { appRoot, appDir } = appRootOf({ root, cwd: o.cwd, configDirs: inventory.dirs });
|
|
2094
|
+
const { appRoot, appDir } = appRootOf({ root, cwd: o.cwd, configDirs: inventory.dirs, soleNestedApp: devTest });
|
|
1859
2095
|
// `--route`: which route this stage takes here and whether it refuses, answered without running anything (rightkit#1297).
|
|
1860
2096
|
if (o.routeProbe) return await runRouteProbe(o, args, root, git, { to, platform, stages: devTest ? [] : stages, devTest, appDir });
|
|
1861
2097
|
// Commit-only build (GATE-CONTRACT §1): on every host (not hosted CI, whose runner checkout is the commit) the door selects a commit
|
|
@@ -1896,7 +2132,7 @@ async function runStages(o, args, root, git, io) {
|
|
|
1896
2132
|
let synced;
|
|
1897
2133
|
try { synced = (o.syncSnapshot ?? snap.syncSnapshot)({ checkout: root, rev: selected.commit, root: snapshotsAt, lock: { held: taken.view } }); }
|
|
1898
2134
|
catch (e) { o.err(`${tag} ${e.code === "error" ? "RK_CHECK_ERROR" : "BLOCKED"}: snapshot ${e.message}; nothing ran`); return e.code === "error" ? 2 : 1; }
|
|
1899
|
-
o.out(`${tag} snapshot ${synced.path} is commit ${synced.commit} tree ${synced.tree} (written=${synced.written} removed=${synced.removed} unchanged=${synced.unchanged})`);
|
|
2135
|
+
o.out(`${tag} snapshot ${synced.path} is commit ${synced.commit} tree ${synced.tree} (written=${synced.written} removed=${synced.removed} unchanged=${synced.unchanged})${synced.removedPaths?.length ? ` removed: ${synced.removedPaths.join(", ")}` : ""}`);
|
|
1900
2136
|
if (synced.identity) o.out(`${tag} source identity ${synced.identity.file}: ${synced.identity.written ? "written" : synced.identity.kept ? "kept" : `not written (${synced.identity.reason})`}`);
|
|
1901
2137
|
started = true;
|
|
1902
2138
|
return await runStages({ ...o, snapshotLock: taken.view, doorSnapshot: { lock: taken.view, path: synced.path, commit: synced.commit, tree: synced.tree, root: snapshotsAt, ledger: { entries: [] } } }, args, root, git, { ...io, snapshotLock: taken.view });
|
|
@@ -1922,7 +2158,14 @@ async function runStages(o, args, root, git, io) {
|
|
|
1922
2158
|
const which = (cmd) => { const r = o.spawn(o.platform === "win32" ? "where" : "which", [cmd]); return failed(r) ? [] : text(r).split(/\r?\n/).map((l) => l.trim()).filter(Boolean); };
|
|
1923
2159
|
const executor = (o.resolveExecutor ?? gateResolveExecutor)({ env: o.env, platform: o.platform, exists: o.exists, which, readFile: o.readFile }); applyExecutorEnv(o, executor);
|
|
1924
2160
|
if (executor.kind === "refuse") { o.err(`${tag} BLOCKED: ${executor.problem}`); return 1; }
|
|
1925
|
-
|
|
2161
|
+
// NN01/NN25: a tool's version is remembered across runs while its program file is unchanged (tool-version-memo.mjs); a shim is asked each time.
|
|
2162
|
+
const versionStore = (() => { try { return path.join(gateRunsRoot({ env: o.env, platform: o.platform }), "tool-versions.json"); } catch { return null; } })();
|
|
2163
|
+
const versionAsked = (cmd, a) => rememberedVersion(cmd, a, { env: o.env, platform: o.platform, storeFile: o.spawn === defaultSpawn ? versionStore : null, run: (c, args) => { const r = o.spawn(c, args, { cwd: root }); return failed(r) ? null : text(r).trim().split(/\r?\n/)[0]; } });
|
|
2164
|
+
// pnpm is a launcher, which tool-version-memo.mjs never remembers by its own file. Its version here is kept by the open gate process while
|
|
2165
|
+
// the files that decide which pnpm runs in this directory are unchanged (pnpmVersionAnswer; NN25: `pnpm --version` on every warm run).
|
|
2166
|
+
const version = (cmd, a) => (cmd === "pnpm" && a.length === 1 && a[0] === "--version"
|
|
2167
|
+
? pnpmVersionAnswer({ cwd: root, env: o.env, remember: o.spawn === defaultSpawn, run: () => versionAsked(cmd, a) })
|
|
2168
|
+
: versionAsked(cmd, a));
|
|
1926
2169
|
const listed = git("ls-tree", "-r", "--name-only", "-z", commit);
|
|
1927
2170
|
const lockFiles = {};
|
|
1928
2171
|
for (const f of failed(listed) ? [] : text(listed).split("\0").filter((x) => /(^|\/)(Cargo\.lock|pnpm-lock\.yaml)$/.test(x))) {
|
|
@@ -1930,7 +2173,7 @@ async function runStages(o, args, root, git, io) {
|
|
|
1930
2173
|
}
|
|
1931
2174
|
const binding = bindingOf({
|
|
1932
2175
|
tree, lockFiles, gateFile: fileURLToPath(import.meta.url), gateJudge: gateCodeIdentity(), executor: o.brokerException ? `${executor.kind}:exception:${o.brokerException.exceptionId}` : executor.kind,
|
|
1933
|
-
toolchain: { classA: { "cargo-deny": version("cargo-deny", ["--version"]), "cargo-audit": version("cargo-audit", ["--version"]), actionlint: version("actionlint", ["-version"]), shellcheck: version("shellcheck", ["--version"]) }, node: process.version, rustc: version(executor.kind === "broker" && executor.cargo.length > 1 ? executor.cargo[0] : "rustc", executor.kind === "broker" && executor.cargo.length > 1 ? ["rustc", "-V"] : ["-V"]), pnpm: version("pnpm", ["--version"]) },
|
|
2176
|
+
toolchain: { classA: { "cargo-deny": version("cargo-deny", ["--version"]), "cargo-audit": version("cargo-audit", ["--version"]), actionlint: version("actionlint", ["-version"]), shellcheck: version("shellcheck", ["--version"]) }, node: process.version, rustc: brokerToolchainOf(o, executor)?.rustc.version ?? version(executor.kind === "broker" && executor.cargo.length > 1 ? executor.cargo[0] : "rustc", executor.kind === "broker" && executor.cargo.length > 1 ? ["rustc", "-V"] : ["-V"]), pnpm: version("pnpm", ["--version"]) },
|
|
1934
2177
|
});
|
|
1935
2178
|
// Release writes to R2. The write credential lives only in the trusted publisher: a GitHub Actions job in the protected
|
|
1936
2179
|
// publication environment, which sets RIGHTKIT_PUBLISHER=github-environment. Hosts and agents never hold it, so the door refuses the
|
|
@@ -2114,12 +2357,14 @@ async function runStages(o, args, root, git, io) {
|
|
|
2114
2357
|
if (ds.carriedOutputs?.size) ok = await admissionDryRun("after the sidecars were staged, before the app compiles");
|
|
2115
2358
|
else o.out(`${tag} [compile] release admission dry-run skipped here: no broker receipt names the app's Cargo target yet; the package stage's build runs the same admission rows at its start`);
|
|
2116
2359
|
}
|
|
2117
|
-
let compiledDirs = []; let compiledBins = null; let qualifyOwed = [];
|
|
2360
|
+
let compiledDirs = []; let compiledBins = null; let qualifyOwed = []; let limitedEvidence = [];
|
|
2118
2361
|
const reportOutputs = (dirs, bins = null) => { compiledDirs = [...dirs]; compiledBins = bins; };
|
|
2119
|
-
if (ok) ok = (await (o.runCompile ?? (() => main(ds ? ["--all", "--commit", commit, "--snapshot", ds.path] : ["--all"], { ...io, cwd: root, readStdin: () => "", ...(ds ? { snapshotLock: ds.lock, classAEarlier: true, seamScope: appDir === "." ? null : [appDir], snapshotLedger: ds.ledger?.entries ?? [], onCompileLedger: (entries) => { ds.compileAdmitted = entries; }, onDirectReceipt: (r) => { directReceipt = r; }, onCompileOutputs: reportOutputs, onQualifyOwed: (list) => { qualifyOwed = list; } } : {}) })))({ reportOutputs })) === 0;
|
|
2362
|
+
if (ok) ok = (await (o.runCompile ?? (() => main(ds ? ["--all", "--commit", commit, "--snapshot", ds.path] : ["--all"], { ...io, cwd: root, readStdin: () => "", ...(ds ? { snapshotLock: ds.lock, classAEarlier: true, seamScope: appDir === "." ? null : [appDir], snapshotLedger: ds.ledger?.entries ?? [], onCompileLedger: (entries) => { ds.compileAdmitted = entries; }, onDirectReceipt: (r) => { directReceipt = r; }, onCompileOutputs: reportOutputs, onQualifyOwed: (list) => { qualifyOwed = list; }, onLimitedEvidence: (list) => { limitedEvidence = list; } } : {}) })))({ reportOutputs })) === 0;
|
|
2120
2363
|
if (directReceipt) extra = { ...extra, direct: directReceipt };
|
|
2121
2364
|
// What the plan left to the qualify stage is recorded with the compile, so qualification can prove it is not lost (rightkit#1332, #1333).
|
|
2122
2365
|
if (qualifyOwed.length) extra = { ...extra, qualifyOwed };
|
|
2366
|
+
// Cross-target rows type-check against stand-ins and never link: listed as limited evidence so no qualification can cite them (GC-A14, NN38).
|
|
2367
|
+
if (limitedEvidence.length) extra = { ...extra, limitedEvidence };
|
|
2123
2368
|
// What this compile produced, recorded with its result so a later run can prove the outputs are still there (GB-13).
|
|
2124
2369
|
if (ok) extra = { ...extra, outputs: compileOutputsRecord({ dirs: compiledDirs, env: o.env, builtBins: compiledBins }) };
|
|
2125
2370
|
// The cross-check with `.rightkit/compile-inputs.json`: a declared input that covers ledger entries must carry the digest of those
|
|
@@ -3062,7 +3307,9 @@ async function runUnitSnapshot(o, args, root, git, io, option) {
|
|
|
3062
3307
|
const snapshotsAt = o.snapshotRoot ?? snap.snapshotRoot({ platform: o.platform, env: o.env });
|
|
3063
3308
|
{ const mismatch = await declaredSnapshotRootRefusal(o, executor, snapshotsAt); if (mismatch) { o.err(`${tag} BLOCKED: ${mismatch.code}: ${mismatch.message}; nothing ran`); return 1; } }
|
|
3064
3309
|
// The same one exclusion as the door (takeRunLock): on a broker host the unit's stage calls are seam requests, which the broker admits only under the snapshot lock.
|
|
3065
|
-
|
|
3310
|
+
// A unit of a unit list joins the list's one lock (runSharedUnitList, NN13): the lock is not re-entrant, so a second take by this same
|
|
3311
|
+
// process would be refused as busy. Every other unit run takes its own.
|
|
3312
|
+
const taken = io.unitListLock ?? takeRunLock({ o, checkout: root, snapshotsAt, commit, snap, tag });
|
|
3066
3313
|
if (taken.exit !== undefined) return taken.exit;
|
|
3067
3314
|
let started = false;
|
|
3068
3315
|
try {
|
|
@@ -3070,7 +3317,7 @@ async function runUnitSnapshot(o, args, root, git, io, option) {
|
|
|
3070
3317
|
try { synced = (o.syncSnapshot ?? snap.syncSnapshot)({ checkout: root, rev: commit, root: snapshotsAt, lock: { held: taken.view } }); }
|
|
3071
3318
|
catch (e) { o.err(`${tag} ${e.code === "error" ? "RK_CHECK_ERROR" : "BLOCKED"}: snapshot ${e.message}; nothing ran`); return e.code === "error" ? 2 : 1; }
|
|
3072
3319
|
started = true;
|
|
3073
|
-
o.out(`${tag} snapshot ${synced.path} is commit ${synced.commit} tree ${synced.tree} (written=${synced.written} removed=${synced.removed} unchanged=${synced.unchanged})`);
|
|
3320
|
+
o.out(`${tag} snapshot ${synced.path} is commit ${synced.commit} tree ${synced.tree} (written=${synced.written} removed=${synced.removed} unchanged=${synced.unchanged})${synced.removedPaths?.length ? ` removed: ${synced.removedPaths.join(", ")}` : ""}`);
|
|
3074
3321
|
if (synced.identity) o.out(`${tag} source identity ${synced.identity.file}: ${synced.identity.written ? "written" : synced.identity.kept ? "kept" : `not written (${synced.identity.reason})`}`);
|
|
3075
3322
|
const ds = { lock: taken.view, path: synced.path, commit: synced.commit, tree: synced.tree, root: snapshotsAt, ledger: { entries: [] } };
|
|
3076
3323
|
if (io[UNIT_LIST_UNION]) return await runUnionSnapshot({ o, io, root, git, ds, union: io[UNIT_LIST_UNION], unitListClassA: io.unitListClassA });
|
|
@@ -3165,7 +3412,9 @@ async function runUnitSnapshot(o, args, root, git, io, option) {
|
|
|
3165
3412
|
});
|
|
3166
3413
|
} finally { bound.cleanup(); }
|
|
3167
3414
|
} finally {
|
|
3168
|
-
|
|
3415
|
+
// The list releases its own lock after its last unit, on the same proof; a unit only tells it that work began under the lock.
|
|
3416
|
+
if (io.unitListLock) { if (started) io.unitListLock.started = true; }
|
|
3417
|
+
else releaseSeamLock({ o, release: taken.release, seamBody: started ? taken.body : null, tag });
|
|
3169
3418
|
}
|
|
3170
3419
|
}
|
|
3171
3420
|
|
|
@@ -3729,6 +3978,13 @@ async function runDevTest(o, args, root, git, io, to, appRoot, appDir) {
|
|
|
3729
3978
|
const tree = ds ? ds.tree : text(git("rev-parse", "HEAD^{tree}")).trim();
|
|
3730
3979
|
const common = text(git("rev-parse", "--git-common-dir")).trim();
|
|
3731
3980
|
if (!/^[0-9a-f]{40}$/.test(commit) || !common) { o.err(`${tag} cannot read HEAD and the git directory`); return 2; }
|
|
3981
|
+
// `--to dev|test|render` hand an app to right-release, which reads the app's right-release.config. A repository with none (RustRight) had its
|
|
3982
|
+
// test stage fail in 0.3 s inside right-release with ERR_MODULE_NOT_FOUND after a full class A (Mac, 2026-11-17). Said here, before any work.
|
|
3983
|
+
{ const at = (f) => (appDir === "." ? f : `${appDir}/${f}`);
|
|
3984
|
+
if (!["right-release.config.json", "right-release.config.mjs"].some((f) => !failed(git("cat-file", "-e", `${commit}:${at(f)}`)))) {
|
|
3985
|
+
o.err(`${tag} --to ${to} runs an app's own ${to} through right-release, and ${appDir === "." ? "this repository" : appDir} has no right-release.config.json or .mjs at ${commit.slice(0, 12)}; nothing ran. A Cargo workspace's own tests run in --to compile (its test:rust rows).`);
|
|
3986
|
+
return 2;
|
|
3987
|
+
} }
|
|
3732
3988
|
// Hosted CI's runner checkout is the commit; anywhere else the snapshot is, and the checkout may hold anything.
|
|
3733
3989
|
if (!ds) {
|
|
3734
3990
|
const dirty = git("status", "--porcelain", "--untracked-files=no");
|
|
@@ -3868,6 +4124,32 @@ export function stageArgsProblem(args) {
|
|
|
3868
4124
|
return null;
|
|
3869
4125
|
}
|
|
3870
4126
|
|
|
4127
|
+
/**
|
|
4128
|
+
* GC-A15 at the check stage: one line for every Cargo profile table other than `[profile.release]` in the app roots a commit tracks (the
|
|
4129
|
+
* directory of each `right-release.config`), found by the release tool's own scan of the commit's snapshot. `tracked` is the commit's file
|
|
4130
|
+
* list, `snapshotDir` its snapshot, `label` the name printed for an app at the repository root. RightKit's own repository gives none: it is
|
|
4131
|
+
* judged per unit. No lines means the rule holds. Exported for its test.
|
|
4132
|
+
*/
|
|
4133
|
+
export async function cargoProfileRuleLines({ tracked, snapshotDir, label }) {
|
|
4134
|
+
let rightkitRepo = false;
|
|
4135
|
+
if (tracked.includes(RIGHTKIT_IDENTITY_FILE)) { try { rightkitRepo = isRightKitIdentity(fs.readFileSync(path.join(snapshotDir, ...RIGHTKIT_IDENTITY_FILE.split("/")), "utf8")); } catch { rightkitRepo = false; } }
|
|
4136
|
+
if (rightkitRepo) return [];
|
|
4137
|
+
const appRoots = [...new Set(tracked.filter((f) => /(^|\/)right-release\.config\.(json|mjs)$/.test(f)).map((f) => path.posix.dirname(f)))].sort();
|
|
4138
|
+
const { scanCargoProfileContract, formatCargoProfileFindings } = await import("../cargo-profile-contract.mjs");
|
|
4139
|
+
return appRoots.flatMap((dir) => formatCargoProfileFindings(scanCargoProfileContract(path.join(snapshotDir, ...(dir === "." ? [] : dir.split("/"))), { sources: false }).filter((f) => f.rule === "profile-extra" && /^\[profile\.[^\]]+\] is not allowed/.test(f.message)), dir === "." ? label : dir));
|
|
4140
|
+
}
|
|
4141
|
+
|
|
4142
|
+
/**
|
|
4143
|
+
* The Cargo home a run's Cargo reads (`CARGO_HOME`, else `.cargo` under the user's home), named by where it really is: the workspace proof
|
|
4144
|
+
* (snapshot-metadata.mjs cargoWorkspaceTopology) refuses any discovery input reached through a link, and an agent profile's `.cargo` is a
|
|
4145
|
+
* link to the user's Cargo home. A Cargo home that does not exist keeps its spelled path (the proof reads it as absent). Exported for its test.
|
|
4146
|
+
*/
|
|
4147
|
+
export function cargoHomeOf(env, { realpath = fs.realpathSync, homedir = os.homedir } = {}) {
|
|
4148
|
+
let home = env.CARGO_HOME || path.join(env.USERPROFILE || env.HOME || homedir(), ".cargo");
|
|
4149
|
+
try { home = realpath(home); } catch { /* absent: as spelled */ }
|
|
4150
|
+
return home;
|
|
4151
|
+
}
|
|
4152
|
+
|
|
3871
4153
|
export async function main(argv, io = {}) {
|
|
3872
4154
|
const o = {
|
|
3873
4155
|
spawn: defaultSpawn, exists: fs.existsSync, readFile: (f) => fs.readFileSync(f, "utf8"), writeFile: fs.writeFileSync, mkdir: fs.mkdirSync, chmod: fs.chmodSync, readdir: fs.readdirSync,
|
|
@@ -3976,7 +4258,7 @@ export async function main(argv, io = {}) {
|
|
|
3976
4258
|
let synced;
|
|
3977
4259
|
try { synced = (o.syncSnapshot ?? snap.syncSnapshot)({ checkout, rev: selected.commit, root: snapshotsAt, lock: { held: view } }); }
|
|
3978
4260
|
catch (e) { o.err(`rightkit-gate: ${e.code === "error" ? sc.CHECK_ERROR : "BLOCKED"}: snapshot ${e.message}; nothing ran`); return e.code === "error" ? 2 : 1; }
|
|
3979
|
-
o.out(`rightkit-gate: snapshot ${synced.path} is commit ${synced.commit} tree ${synced.tree} (written=${synced.written} removed=${synced.removed} unchanged=${synced.unchanged})`);
|
|
4261
|
+
o.out(`rightkit-gate: snapshot ${synced.path} is commit ${synced.commit} tree ${synced.tree} (written=${synced.written} removed=${synced.removed} unchanged=${synced.unchanged})${synced.removedPaths?.length ? ` removed: ${synced.removedPaths.join(", ")}` : ""}`);
|
|
3980
4262
|
if (synced.identity) o.out(`rightkit-gate: source identity ${synced.identity.file}: ${synced.identity.written ? "written" : synced.identity.kept ? "kept" : `not written (${synced.identity.reason})`}`);
|
|
3981
4263
|
const next = [...argv]; const ci = next.indexOf("--commit");
|
|
3982
4264
|
if (ci >= 0) next.splice(ci, 2, "--commit", synced.commit); else next.push("--commit", synced.commit);
|
|
@@ -4041,11 +4323,36 @@ export async function main(argv, io = {}) {
|
|
|
4041
4323
|
const appArgs = stripSnapshot(withoutScope.filter((a) => a !== "--full-a"));
|
|
4042
4324
|
if (fullAdmission && !appArgs.includes("--rule-tier")) appArgs.push("--rule-tier", requestedTier);
|
|
4043
4325
|
// GC-A24: a passing app-rule verdict of a snapshot is reused for the same commit tree, rule code, tier and arguments (ruleVerdictCache).
|
|
4326
|
+
let history;
|
|
4327
|
+
if (fullAdmission && snapshotDir && !o.runScans && o.classA !== false) {
|
|
4328
|
+
try {
|
|
4329
|
+
// NN25: no git starts after the resident proof. The snapshot sync already resolved this checkout's repository
|
|
4330
|
+
// (snapshot.mjs repositoryOf -> snapshot-git.mjs sealedRepoInfo, cached per canonical path in this process), so the
|
|
4331
|
+
// common dir is read from that cache, never asked again. An injected spawn (tests) is asked as before.
|
|
4332
|
+
const commonDir = o.spawn === defaultSpawn ? sealedRepoInfo(snapshotCheckout).commonDir : (() => { const common = o.spawn("git", ["rev-parse", "--path-format=absolute", "--git-common-dir"], { cwd: snapshotCheckout }); if (failed(common) || !text(common).trim()) throw new Error("cannot identify Class A cache location"); return text(common).trim(); })();
|
|
4333
|
+
const storeDir = o.env.RK_GATE_CACHE_DIR || path.join(commonDir, "rightkit-gate-cache");
|
|
4334
|
+
history = openClassAHistory({ historyRoot: path.join(gateRunsRoot({ env: o.env, platform: o.platform }), "rightkit-class-a-history"), storeDir });
|
|
4335
|
+
} catch (error) { o.err(`rightkit-gate: BLOCKED: ${error.message}`); return 1; }
|
|
4336
|
+
}
|
|
4044
4337
|
const ruleCache = snapshotDir && snapshotCommit && !args.includes("--worktree") && !o.appCheck ? ruleVerdictCache({ checkout: snapshotCheckout, spawn: o.spawn }) : null;
|
|
4045
4338
|
const appKey = ruleCache ? ruleCache.key({ rule: "app-check", tree: snapshotCommit.tree, args: appArgs, gate: gatePackageIdentity(o.gatePackage) }) : null;
|
|
4046
|
-
const
|
|
4339
|
+
const appCached = Boolean(appKey && ruleCache.passed(appKey));
|
|
4340
|
+
let appCheck = appCached
|
|
4047
4341
|
? (o.out(`check: ${snapshotCommit.commit.slice(0, 12)} app rules: cached pass (tree ${snapshotCommit.tree.slice(0, 12)})`), 0)
|
|
4048
4342
|
: await (o.appCheck ?? (await import("../app-check.mjs")).main)(appArgs, { out: o.out, err: o.err, label: "check", cwd: o.cwd, ...(snapshotDir && !args.includes("--worktree") ? { snapshot: snapshotDir } : {}) });
|
|
4343
|
+
// GC-A15 ("An app carries no Cargo profile table but [profile.release]"; Adrian 2026-11-03: "hard block"). The rule lived only in the release
|
|
4344
|
+
// tool (release.mjs cargo-profile-contract), so a commit that adds [profile.dev] to an app passed check and compile (contract test N15, failed
|
|
4345
|
+
// on sealed 0.6.58 and on the Dell copy 2026-11-19). It is judged here with the app rules, by the release tool's own scan (same workspace
|
|
4346
|
+
// roots, same exemptions), for every app root the commit tracks (a right-release.config), and its verdict is cached with theirs per tree.
|
|
4347
|
+
// RightKit itself is judged per unit (rightkitDoorRule) and is not an app repository: its e2e-app keeps a [profile.dev] for its own harness.
|
|
4348
|
+
if (!appCached && appCheck === 0 && fullAdmission && snapshotDir && snapshotCommit && !o.appCheck) {
|
|
4349
|
+
try {
|
|
4350
|
+
const listed = o.spawn("git", ["ls-tree", "-r", "--name-only", "-z", snapshotCommit.commit], { cwd: snapshotCheckout });
|
|
4351
|
+
if (failed(listed)) throw new Error(`cannot list commit ${snapshotCommit.commit}`);
|
|
4352
|
+
const lines = await cargoProfileRuleLines({ tracked: text(listed).split("\0").filter(Boolean), snapshotDir, label: path.basename(snapshotCheckout) });
|
|
4353
|
+
if (lines.length) { for (const line of lines) o.err(`check: ${line}`); appCheck = 1; }
|
|
4354
|
+
} catch (error) { o.err(`rightkit-gate: BLOCKED: the Cargo profile rule (GC-A15) could not be judged: ${error.message}`); return 1; }
|
|
4355
|
+
}
|
|
4049
4356
|
if (appKey && appCheck === 0) ruleCache.pass(appKey);
|
|
4050
4357
|
if (args.includes("--list") || args.includes("--print-baseline") || args.includes("--only") || o.classA === false) {
|
|
4051
4358
|
// A view of the app rules, never a class A verdict: say so, so no caller can take its exit 0 for a full check.
|
|
@@ -4062,12 +4369,13 @@ export async function main(argv, io = {}) {
|
|
|
4062
4369
|
const checkCwd = repoArg ? path.resolve(o.cwd, repoArg) : o.cwd;
|
|
4063
4370
|
// The app rules' tier is the stage's (rightkit#1296); class A's deterministic scans are the same at either tier.
|
|
4064
4371
|
const ruleTier = requestedTier;
|
|
4065
|
-
const classA = await main(["--class-a", "--rule-tier", ruleTier, ...(args.includes("--full-a") ? ["--full-a"] : []), ...(args.includes("--worktree") ? ["--worktree"] : ["--commit", snapshotCommit?.commit ?? option("--commit") ?? "HEAD"]), ...(snapshotDir ? ["--snapshot", snapshotDir] : []), ...scopeForward], { ...io, cwd: checkCwd });
|
|
4372
|
+
const classA = await main(["--class-a", "--rule-tier", ruleTier, ...(args.includes("--full-a") ? ["--full-a"] : []), ...(args.includes("--worktree") ? ["--worktree"] : ["--commit", snapshotCommit?.commit ?? option("--commit") ?? "HEAD"]), ...(snapshotDir ? ["--snapshot", snapshotDir] : []), ...scopeForward], { ...io, cwd: checkCwd, [CLASS_A_HISTORY]: history });
|
|
4066
4373
|
// RightKit checking itself: its own rules (line endings, consumer recipes, npm surface, version copies and the version feed, dispatcher
|
|
4067
4374
|
// pins, consumer locks, generated docs, temp paths: scripts/preflight.mjs) and its exports' import safety are class A for the RightKit repository.
|
|
4068
4375
|
let selfRules = 0;
|
|
4069
|
-
|
|
4070
|
-
|
|
4376
|
+
// NN25: in snapshot mode the checkout's canonical top was resolved before the proof (snapshotCheckout); asking git again
|
|
4377
|
+
// here would start a git process after the resident proof for an answer this process already holds.
|
|
4378
|
+
const root = snapshotCheckout ?? (() => { const top = o.spawn("git", ["rev-parse", "--show-toplevel"], { cwd: checkCwd }); return failed(top) ? null : path.resolve(text(top).trim()); })();
|
|
4071
4379
|
const self = o.selfPath ?? fileURLToPath(import.meta.url);
|
|
4072
4380
|
// RightKit's own scripts are the checked repository's code: they run only after the app rules and every class A scan passed,
|
|
4073
4381
|
// never after a failure, so a red tree executes nothing of its own.
|
|
@@ -4422,6 +4730,11 @@ export async function main(argv, io = {}) {
|
|
|
4422
4730
|
// On a broker host, the spawn every Class A Cargo scan of the snapshot runs through: a Cargo call inside the snapshot is a carried read-only
|
|
4423
4731
|
// request of one of the exact admitted shapes (snapshot-metadata.mjs), anything else passes through (node, git, the client's probe).
|
|
4424
4732
|
let scanSpawn = null;
|
|
4733
|
+
// Freeze the snapshot's Class A forecast before its metadata rows start.
|
|
4734
|
+
const guardCargoDiscovery = fullA && Boolean(snapshotA) && !o.runScans;
|
|
4735
|
+
const cargoMetadata = guardCargoDiscovery ? await import("../snapshot-metadata.mjs") : null;
|
|
4736
|
+
let authenticateCargoWorkspace = null;
|
|
4737
|
+
let classACargoPath = null;
|
|
4425
4738
|
if (snapshot && snapshotB) {
|
|
4426
4739
|
// Direct host: no broker grant to satisfy, so no config-only .git; the snapshot is scanned and compiled in place.
|
|
4427
4740
|
repo = snapshotB;
|
|
@@ -4489,30 +4802,61 @@ export async function main(argv, io = {}) {
|
|
|
4489
4802
|
const { directReadSpawn } = await import("../snapshot-metadata.mjs");
|
|
4490
4803
|
const pathKey = o.platform === "win32" ? (Object.keys(o.env).find((k) => k.toUpperCase() === "PATH") ?? "Path") : "PATH";
|
|
4491
4804
|
const direct = directCargoPath({ env: { ...o.env, PATH: o.env[pathKey] }, exists: o.exists, platform: o.platform, gateWrappers: true });
|
|
4805
|
+
classACargoPath = direct.cargo;
|
|
4492
4806
|
const readOpts = { cargoCommand: planCargoCommand, snapshotRoot: repo, directPath: direct.path, pathKey, tmpRoot: gateTmpRoot({ env: o.env, platform: o.platform, exists: o.exists }), env: o.env, err: o.err };
|
|
4493
4807
|
// One memo for the run (rightkit#1460): the unit discovery's `metadata --no-deps --locked` and the Class A `cargo-metadata` scan of the same
|
|
4494
4808
|
// workspace are the same call on the same verified snapshot, so the scan reuses the discovery's result instead of running Cargo again.
|
|
4495
4809
|
const readMemo = new Map();
|
|
4496
|
-
|
|
4497
|
-
|
|
4810
|
+
// NN10: a metadata read is answered by the resident gate when it holds one for this unchanged snapshot (only for the real spawn: a test's
|
|
4811
|
+
// injected spawn sees every call). Asked with the direct cargo by its path and the same environment minus the per-call scratch target, so
|
|
4812
|
+
// the resident gate's key is the same from run to run.
|
|
4813
|
+
const served = !guardCargoDiscovery && o.spawn === defaultSpawn && direct.cargo ? await (async () => {
|
|
4814
|
+
const { snapshotCargoMetadata } = await import("../gate-serve.mjs");
|
|
4815
|
+
const { snapshotRoot: snapshotRootOf } = await import("../snapshot.mjs");
|
|
4816
|
+
let rootDir = null; try { rootDir = snapshotRootOf({ env: o.env }); } catch { rootDir = null; }
|
|
4817
|
+
if (!rootDir) return null;
|
|
4818
|
+
const servedEnv = { ...o.env, [pathKey]: direct.path };
|
|
4819
|
+
return ({ cwd, args }) => { const r = snapshotCargoMetadata({ cwd, args, cargo: direct.cargo, env: servedEnv, snapshotRootDir: rootDir, run: () => ({ status: null }) }); return r.served ? r : null; };
|
|
4820
|
+
})() : null;
|
|
4821
|
+
snapshotSpawn = directReadSpawn({ spawn: withDeclaredClient((c, a, opts) => o.spawn(c, a, opts)), ...readOpts, memo: readMemo, served });
|
|
4822
|
+
scanSpawn = directReadSpawn({ spawn: withDeclaredClient(defaultSpawnAsync), ...readOpts, memo: readMemo, isAsync: true, served });
|
|
4498
4823
|
}
|
|
4499
4824
|
npm = discoverNpmUnits({ root: repo, tracked, readFile: readSnap, exists: o.exists });
|
|
4500
4825
|
npmRoots = discoverPnpmRoots({ root: repo, tracked, exists: o.exists });
|
|
4501
4826
|
let metadata = null;
|
|
4502
|
-
if (scopeDirs.length) {
|
|
4827
|
+
if (scopeDirs.length || (guardCargoDiscovery && manifests.length)) {
|
|
4503
4828
|
closureTools = await import("../app-closure.mjs");
|
|
4829
|
+
const committed = new Set(files);
|
|
4504
4830
|
const readCommitted = (file) => {
|
|
4505
|
-
if (!
|
|
4831
|
+
if (!committed.has(file)) throw new Error(`${file} is absent from the committed tree`);
|
|
4506
4832
|
return readSnap(path.join(repo, file));
|
|
4507
4833
|
};
|
|
4508
4834
|
const sourceMetadata = closureTools.cargoMetadataFromManifests({ manifests: manifests.filter((m) => !fixtures.some((d) => m.startsWith(`${d.replace(/\/$/, "")}/`))), readFile: readCommitted });
|
|
4509
|
-
|
|
4510
|
-
|
|
4511
|
-
|
|
4512
|
-
|
|
4513
|
-
|
|
4514
|
-
|
|
4515
|
-
|
|
4835
|
+
if (scopeDirs.length) {
|
|
4836
|
+
const inventory = discoverRustWorkspaces({ root: repo, tracked, fixtures, readFile: readSnap, metadata: sourceMetadata });
|
|
4837
|
+
closure = closureTools.closureOf({ scopeDirs, npmUnits: npm, rustUnits: inventory.units, readFile: readCommitted });
|
|
4838
|
+
const selectedWorkspaces = new Set(inventory.units.filter((u) => closure.rust.has(u.name)).map((u) => u.cargoDir));
|
|
4839
|
+
metadata = (dir) => {
|
|
4840
|
+
const source = sourceMetadata(dir);
|
|
4841
|
+
return !guardCargoDiscovery && selectedWorkspaces.has(source.cargoDir) ? workspaceMetadata({ root: repo, spawn: snapshotSpawn, cargoCommand: planCargoCommand, dir, realpath: fs.realpathSync }) : source;
|
|
4842
|
+
};
|
|
4843
|
+
} else {
|
|
4844
|
+
metadata = sourceMetadata;
|
|
4845
|
+
}
|
|
4846
|
+
if (guardCargoDiscovery) {
|
|
4847
|
+
// Cargo authenticates the workspace, committed members and publishability after admission.
|
|
4848
|
+
const shape = (facts) => canonicalJson(facts.members.filter((m) => committed.has(m.manifest))
|
|
4849
|
+
.map(({ name, dir, manifest, publish }) => ({ name, dir, manifest, publish }))
|
|
4850
|
+
.sort((a, b) => a.manifest < b.manifest ? -1 : a.manifest > b.manifest ? 1 : 0));
|
|
4851
|
+
authenticateCargoWorkspace = (scan, result, stored) => {
|
|
4852
|
+
const dir = scan.cwd ?? ".";
|
|
4853
|
+
const observed = result && !result.truncated ? cargoMetadata.cargoWorkspaceFacts({ root: repo, stdout: result.stdout }) : stored;
|
|
4854
|
+
if (observed?.cargoDir !== dir || !Array.isArray(observed.members) || shape(observed) !== shape(sourceMetadata(dir))) {
|
|
4855
|
+
throw new Error("RK_CARGO_DISCOVERY: " + scan.id + " has no matching authentic Cargo workspace & member inventory");
|
|
4856
|
+
}
|
|
4857
|
+
return observed;
|
|
4858
|
+
};
|
|
4859
|
+
}
|
|
4516
4860
|
}
|
|
4517
4861
|
rust = discoverRustWorkspaces({ root: repo, spawn: snapshotSpawn, cargoCommand: planCargoCommand, tracked, untracked, fixtures, readFile: readSnap, ...(metadata ? { metadata } : {}) });
|
|
4518
4862
|
if (closure) {
|
|
@@ -4775,6 +5119,18 @@ export async function main(argv, io = {}) {
|
|
|
4775
5119
|
const cargoExcluded = kept.dropped.filter((s) => closureTools.isCargoScan(s)).length;
|
|
4776
5120
|
o.out(`${tag} scope ${closure.dirs.join(", ")}: dependency directories ${closure.dependencyDirs.join(", ")}; ${closure.npm.size} npm & ${closure.rust.size} Rust unit(s); Class A ${executing} executing scan(s) (${cargoRun} Cargo), ${classA.length - executing} repository file-only scan(s); ${kept.dropped.length} unrelated executing scan(s) excluded (${cargoExcluded} Cargo); ${plan.scans.length - classA.length} closure Class B scan(s) do not run in this check; install roots ${installRoots.join(", ") || "none"}; scope digest ${plan.scopeDigest}`);
|
|
4777
5121
|
}
|
|
5122
|
+
const cargoMetadataTopologies = new Map();
|
|
5123
|
+
if (authenticateCargoWorkspace) {
|
|
5124
|
+
// Dell 2026-11-19 (NN01, NN03, NN04, NN10, NN21, NN24): an agent profile's `.cargo` is a link to the user's Cargo home, the proof below
|
|
5125
|
+
// refuses any linked discovery input, so all six fixture workspaces came back unproven and their metadata rows ran real Cargo on every
|
|
5126
|
+
// run. The Cargo home is named by where it really is; a link that moves names another directory and changes the proof.
|
|
5127
|
+
const cargoHome = cargoHomeOf(o.env);
|
|
5128
|
+
for (const row of plan.scans.filter((scan) => scan.class === "A" && /^cargo-metadata(:|$)/.test(scan.id))) {
|
|
5129
|
+
const proof = classACargoPath && cargoMetadata.cargoWorkspaceTopology({ root: repo, dir: row.cwd ?? ".", cargoHome });
|
|
5130
|
+
if (proof) cargoMetadataTopologies.set(row.id, proof);
|
|
5131
|
+
else row.cargoWorkspaceUncacheable = true;
|
|
5132
|
+
}
|
|
5133
|
+
}
|
|
4778
5134
|
const unionContext = o[UNIT_LIST_UNION];
|
|
4779
5135
|
if (unionContext && snapshotB) {
|
|
4780
5136
|
try {
|
|
@@ -4884,7 +5240,13 @@ export async function main(argv, io = {}) {
|
|
|
4884
5240
|
// (`["rustright", ...]`) asks through that one. No client to ask (a shim-only executor with none resolved): no reader, and the scan's limit simply runs.
|
|
4885
5241
|
const executorClient = path.basename(String(cargoCommand[0] ?? "")).replace(/\.(exe|cmd|bat)$/i, "") === "rustright" ? (brokerClientOf(o, executor) ?? cargoCommand[0]) : null;
|
|
4886
5242
|
const brokerClient = !brokerHost ? null : declaredClient ? "rustright" : managedRuntimeClient(o.env, o.platform, o.exists) ?? executorClient;
|
|
4887
|
-
|
|
5243
|
+
// NN07: job states are read over the broker's own endpoint from this process when the endpoint and the runtime identity beside the client
|
|
5244
|
+
// can be established (the same target the snapshot-status query uses); otherwise through the client, as before.
|
|
5245
|
+
const brokerWire = (() => {
|
|
5246
|
+
if (!brokerClient || o.spawn !== defaultSpawn) return null;
|
|
5247
|
+
try { const target = brokerControlTarget({ ...o, env: { ...o.env, ...(executor.env ?? {}) } }, { client: brokerClient }); return target.ok ? { endpoint: target.endpoint, protocol: BUILD_CONTROL_PROTOCOL, runtime: target.identity } : null; } catch { return null; }
|
|
5248
|
+
})();
|
|
5249
|
+
const brokerLive = brokerClient ? createBrokerLive({ client: brokerClient, env: { ...o.env, ...(executor.env ?? {}) }, spawn: withDeclaredClient(defaultSpawnAsync), platform: o.platform, wire: brokerWire }) : null;
|
|
4888
5250
|
|
|
4889
5251
|
if (planOnly) {
|
|
4890
5252
|
o.out(`${tag} plan: ${plan.scans.length} scan(s) for ${changed.length} changed file(s) vs ${base.slice(0, 12)} (reads the working tree; nothing runs)`);
|
|
@@ -4913,6 +5275,8 @@ export async function main(argv, io = {}) {
|
|
|
4913
5275
|
}
|
|
4914
5276
|
// The result cache keys on the gated commit's object ids; the stdin check above made HEAD the pushed commit.
|
|
4915
5277
|
let cache = null;
|
|
5278
|
+
let classAHistory = null;
|
|
5279
|
+
let classBHistory = null;
|
|
4916
5280
|
const nodeCheckRejects = new Map();
|
|
4917
5281
|
let nodeCheckDiagnosticId = null; let nodeCheckDiagnosticState = "not-seen";
|
|
4918
5282
|
const countNodeCheckRejection = (reason, scanId) => {
|
|
@@ -4925,6 +5289,8 @@ export async function main(argv, io = {}) {
|
|
|
4925
5289
|
// Why a scan got no cache key (a key builder that threw, or a cache that could not open): reported, never hidden (GC-A24).
|
|
4926
5290
|
const keyErrors = new Map(); let cacheDisabled = null;
|
|
4927
5291
|
const keyError = (scan, error) => keyErrors.set(scan.id, String(error?.message ?? error).slice(0, 300));
|
|
5292
|
+
const uncacheableReasons = new Map();
|
|
5293
|
+
const uncacheable = (scan, reason) => uncacheableReasons.set(scan.id, reason);
|
|
4928
5294
|
// Full class A on the working tree (the door, and broker admission of the live checkout) caches on the LIVE bytes: every
|
|
4929
5295
|
// tracked and untracked (not ignored) file is hashed raw, so the door's run and a repeat admission of the same bytes hit the
|
|
4930
5296
|
// cache, and any edit misses it.
|
|
@@ -4992,7 +5358,7 @@ export async function main(argv, io = {}) {
|
|
|
4992
5358
|
// changes while class A runs voids the verdict.
|
|
4993
5359
|
// envStartWithCaches records, for audit, the tool caches as the run found them (what its checks could read); the pass line
|
|
4994
5360
|
// carries it next to the env the verdict binds.
|
|
4995
|
-
let envAtStart = null; let envStartWithCaches = null; let cachesAtStart = null;
|
|
5361
|
+
let envAtStart = null; let envStartWithCaches = null; let cachesAtStart = null; let rowEnvironment = null;
|
|
4996
5362
|
if (boundFullA) {
|
|
4997
5363
|
const orphans = orphanedPnpmStores({ root: liveBase, files: live.files });
|
|
4998
5364
|
if (orphans.length) { o.err(`${tag} BLOCKED: orphaned nested pnpm store(s) ${orphans.join(", ")}: left by a standalone install in a workspace member; they can hold stale dependencies and make concurrent vitest runs clear their shared module cache under each other. Move them aside (or reinstall) and run again.`); return 1; }
|
|
@@ -5001,7 +5367,11 @@ export async function main(argv, io = {}) {
|
|
|
5001
5367
|
try { const f = JSON.parse(o.readFile(path.join(liveBase, GATE_CONFIG))).fixtures; if (Array.isArray(f)) pinFixtures = f.filter((d) => typeof d === "string"); } catch { /* no config: no fixtures */ }
|
|
5002
5368
|
const pinProblem = pnpmPinProblem({ root: liveBase, files: live.files, spawn: o.spawn, readFile: o.readFile, fixtures: pinFixtures, platform: o.platform });
|
|
5003
5369
|
if (pinProblem) { o.err(`${tag} BLOCKED: ${pinProblem.message}; no class A row ran`); return 1; }
|
|
5004
|
-
try {
|
|
5370
|
+
try {
|
|
5371
|
+
envAtStart = classAEnvironmentDigest({ root: liveBase, gatePackage: o.gatePackage, files: live.files, spawn: o.spawn, includeCaches: false, onRowEnvironment: (value) => { rowEnvironment = value; } });
|
|
5372
|
+
envStartWithCaches = envAtStart;
|
|
5373
|
+
cachesAtStart = toolCacheManifest({ root: liveBase, files: live.files });
|
|
5374
|
+
}
|
|
5005
5375
|
catch (error) { o.err(`${tag} BLOCKED: ${error.message}`); return 1; }
|
|
5006
5376
|
}
|
|
5007
5377
|
if (boundFullA) {
|
|
@@ -5011,7 +5381,10 @@ export async function main(argv, io = {}) {
|
|
|
5011
5381
|
const { files, ids, digestOf } = live;
|
|
5012
5382
|
const under = (dir) => (dir === "." || dir === "" ? files : files.filter((f) => f === dir || f.startsWith(`${dir}/`)));
|
|
5013
5383
|
const objectId = (p) => (ids.has(p) ? ids.get(p) : under(p).length ? digestOf(under(p)) : null);
|
|
5014
|
-
const
|
|
5384
|
+
const storeDir = o.env.RK_GATE_CACHE_DIR ? path.resolve(o.env.RK_GATE_CACHE_DIR) : path.join(path.resolve(root, text(common).trim()), "rightkit-gate-cache");
|
|
5385
|
+
// Nov-18 cache rule applies to every bound full-A form (snapshot, hosted, live), not only guarded snapshot discovery.
|
|
5386
|
+
classAHistory = o[CLASS_A_HISTORY] ?? openClassAHistory({ historyRoot: path.join(gateRunsRoot({ env: o.env, platform: o.platform }), "rightkit-class-a-history"), storeDir });
|
|
5387
|
+
const store = fileScanCache(storeDir);
|
|
5015
5388
|
const listFiles = (dir) => under(dir);
|
|
5016
5389
|
const readBlob = (p) => fs.readFileSync(path.join(liveBase, p), "utf8");
|
|
5017
5390
|
// The verdict also depends on what is not in the tree: the gate's own code and advisory data, the node and pnpm that run
|
|
@@ -5019,8 +5392,8 @@ export async function main(argv, io = {}) {
|
|
|
5019
5392
|
// Tool caches (vitest, tsc build info, ...) are left out: the scans write them themselves, so keying on them made every rerun miss.
|
|
5020
5393
|
// A6: the digest bound at the start of this run is this very computation (same root, gate package, files and tool-cache setting), so it is
|
|
5021
5394
|
// reused: each call walks every installed dependency file, and the run made three of these walks before its first scan.
|
|
5022
|
-
const environment =
|
|
5023
|
-
const digest = buildCacheDigest({ objectId, headTree: digestOf(files), rustUnits: rust.units, npmUnits: npm, cargoDir: ".", rustLocks, crateFeatures, listFiles, readBlob, onKeyError: keyError });
|
|
5395
|
+
const environment = rowEnvironment;
|
|
5396
|
+
const digest = buildCacheDigest({ objectId, headTree: digestOf(files), rustUnits: rust.units, npmUnits: npm, cargoDir: ".", rustLocks, crateFeatures, listFiles, readBlob, onKeyError: keyError, shellcheckRoot: liveBase, shellcheckEnv: o.env, onUncacheable: uncacheable });
|
|
5024
5397
|
// A row's key is its own inputs plus the environment; the run's scope and scan set are not inputs of one row, and keying on them
|
|
5025
5398
|
// missed every row whenever one file joined or left the plan. build-helpers is never reused: it reads the host's trace list,
|
|
5026
5399
|
// which is outside every key (and takes seconds).
|
|
@@ -5031,15 +5404,24 @@ export async function main(argv, io = {}) {
|
|
|
5031
5404
|
const nodeCheckModule = null; // GC-A24: node-check rows use the generic file key (file, ancestor package.json, node identity)
|
|
5032
5405
|
const nodeCheckDigest = nodeCheckModule ? nodeCheckModule.createNodeCheckCacheDigest({ snapshot: liveBase, tree: digestOf(files), files, gateIdentity: gateCodeIdentity(), gatePackage: o.gatePackage, nodePath: process.execPath, onReject: countNodeCheckRejection, ...(o.env.RIGHTKIT_PREPARATION_DIAGNOSTIC_DIR && nodeCheckDiagnosticId ? { onDiagnostic: (record) => { nodeCheckDiagnosticState = "eligible"; nodeCheckModule.writeNodeCheckDiagnostic(o.env.RIGHTKIT_PREPARATION_DIAGNOSTIC_DIR, record); }, diagnosticScanId: nodeCheckDiagnosticId } : {}) }) : null;
|
|
5033
5406
|
// entryNow: a path's content id in this run's tree, for carryOverProof (a pass stored under an earlier key form is carried when its files are unchanged).
|
|
5034
|
-
cache = { ...store, narrowNodeCheck: false, entryNow: (p) => objectId(p), digest: (scan, context) => {
|
|
5035
|
-
if (/^build-helpers(:|$)/.test(scan.id)) return null;
|
|
5407
|
+
cache = { ...store, narrowNodeCheck: false, uncacheableReason: (scan) => uncacheableReasons.get(scan.id), entryNow: (p) => objectId(p), digest: (scan, context) => {
|
|
5408
|
+
if (/^build-helpers(:|$)/.test(scan.id) || scan.cargoWorkspaceUncacheable) return null;
|
|
5036
5409
|
// This narrow key applies only to the helper's proven plain snapshot node --check.
|
|
5037
5410
|
// Uncertain rows miss rather than falling back to a less specific key.
|
|
5038
|
-
const key = digest(scan);
|
|
5411
|
+
const key = digest(scan);
|
|
5412
|
+
const topology = cargoMetadataTopologies.get(scan.id);
|
|
5413
|
+
const full = key === null ? null : key + ":" + (classAEnvironmentBound(scan) ? environment : CLASS_A_KEY_SCHEMA) + rowShape(scan) + (topology ? ":metadata=" + topology : "");
|
|
5414
|
+
scanKeys.set(scan.id, full);
|
|
5415
|
+
return full;
|
|
5039
5416
|
} };
|
|
5040
|
-
} catch (error) {
|
|
5417
|
+
} catch (error) {
|
|
5418
|
+
cacheDisabled = `class A cache preparation failed: ${error?.message ?? error}`;
|
|
5419
|
+
o.err(`${tag} BLOCKED: ${cacheDisabled}`);
|
|
5420
|
+
return 1;
|
|
5421
|
+
}
|
|
5041
5422
|
}
|
|
5042
5423
|
if (!classAOnly) {
|
|
5424
|
+
const needsForecast = !o.runScans;
|
|
5043
5425
|
try {
|
|
5044
5426
|
const headSha = snapshotBCommit?.commit ?? text(git("rev-parse", "HEAD")).trim();
|
|
5045
5427
|
const treeId = text(git("rev-parse", `${headSha}^{tree}`)).trim();
|
|
@@ -5051,7 +5433,11 @@ export async function main(argv, io = {}) {
|
|
|
5051
5433
|
const line = text(r).split(/\r?\n/).find(Boolean);
|
|
5052
5434
|
return line ? (line.split("\t")[0].split(/\s+/)[2] ?? null) : null;
|
|
5053
5435
|
};
|
|
5054
|
-
const
|
|
5436
|
+
const storeDir = o.env.RK_GATE_CACHE_DIR ? path.resolve(o.env.RK_GATE_CACHE_DIR) : path.join(path.resolve(root, text(common).trim()), "rightkit-gate-cache");
|
|
5437
|
+
if (needsForecast) classBHistory = openClassBHistory({ historyRoot: path.join(gateRunsRoot({ env: o.env, platform: o.platform }), "rightkit-class-a-history"), storeDir });
|
|
5438
|
+
// Mixed A+B in one invocation needs its Class A history too; boundFullA opened it above when that block ran.
|
|
5439
|
+
if (needsForecast && !classAHistory && !(snapshotB && o.classAEarlier === true)) classAHistory = o[CLASS_A_HISTORY] ?? openClassAHistory({ historyRoot: path.join(gateRunsRoot({ env: o.env, platform: o.platform }), "rightkit-class-a-history"), storeDir });
|
|
5440
|
+
const store = fileScanCache(storeDir);
|
|
5055
5441
|
const listFiles = (dir) => {
|
|
5056
5442
|
const r = git("ls-tree", "-r", "--name-only", "-z", headSha, "--", dir);
|
|
5057
5443
|
if (failed(r)) throw new Error(`git ls-tree failed: ${why(r)}`);
|
|
@@ -5078,9 +5464,14 @@ export async function main(argv, io = {}) {
|
|
|
5078
5464
|
cache = { ...store, digest: (scan) => { const key = rowDigest(scan); const full = key === null ? null : `${key}:${gateIdentity}`; scanKeys.set(scan.id, full); for (const member of scan.batch?.members ?? []) scanKeys.set(member, full); return full; } };
|
|
5079
5465
|
} else {
|
|
5080
5466
|
cacheDisabled = `class B result cache disabled: ${!headSha ? "no commit" : !treeId ? "no tree id" : `git common dir unreadable (${why(common)})`}`;
|
|
5081
|
-
o.err(`${tag} note: ${cacheDisabled}`);
|
|
5467
|
+
if (!needsForecast) o.err(`${tag} note: ${cacheDisabled}`);
|
|
5082
5468
|
}
|
|
5083
|
-
} catch (error) {
|
|
5469
|
+
} catch (error) {
|
|
5470
|
+
cache = null;
|
|
5471
|
+
cacheDisabled = `class B cache preparation failed: ${error?.message ?? error}`;
|
|
5472
|
+
if (!needsForecast) o.err(`${tag} note: ${cacheDisabled}`);
|
|
5473
|
+
}
|
|
5474
|
+
if (needsForecast && (!classBHistory || !cache)) { o.err(`${tag} RK_CACHE_DIVERGENCE: ${cacheDisabled}`); return 1; }
|
|
5084
5475
|
}
|
|
5085
5476
|
// The scan-tool policy (RA-18 / L9-03): the analyzers class A accepts (shellcheck, actionlint, cargo-deny, cargo-audit) run only from an enrolled
|
|
5086
5477
|
// executable. It comes from this host's enrolment record under the managed data root, else (RightKit's own checkout only) from the RUNNING
|
|
@@ -5116,10 +5507,15 @@ export async function main(argv, io = {}) {
|
|
|
5116
5507
|
} catch (error) { o.err(`${tag} BLOCKED: RK_SEAM: ${error.message}; nothing ran`); return 1; }
|
|
5117
5508
|
}
|
|
5118
5509
|
directTiming.cargoStart = Date.now();
|
|
5510
|
+
const stageClasses = classAOnly ? ["A"] : classAEarlier ? ["B"] : ["A", "B"];
|
|
5119
5511
|
const scanOptions = {
|
|
5512
|
+
...(authenticateCargoWorkspace ? { cargoWorkspaceFactsFor: authenticateCargoWorkspace } : {}),
|
|
5513
|
+
...(classACargoPath ? { classAToolPaths: { cargo: classACargoPath } } : {}),
|
|
5514
|
+
// NN09: the broker's compiler is read from its host configuration in this process; no `rustright cargo --version` starts (broker-toolchain.mjs).
|
|
5515
|
+
...(() => { const bt = brokerToolchainOf(o, executor); return bt ? { brokerToolchain: bt } : {}; })(),
|
|
5120
5516
|
// The commit's own files (rightkit#1393): a snapshot is not a git toplevel, so the secret scan needs this list to judge tracked files only and never what a stage wrote there.
|
|
5121
5517
|
...(snapshot ? { trackedFiles: files } : {}),
|
|
5122
|
-
classes:
|
|
5518
|
+
classes: stageClasses, ...(classAEarlier ? { classAEarlier: true } : {}), jobs, classBJobs, classBBatching: !o[PRIVATE_SCOPED_COMPILE], groupTests: true, classBPipeline: 2, ...(brokerHost ? { brokerHost: true } : {}), ...(brokerLive ? { brokerLive } : {}), signal: ac.signal, ...(cache ? { cache } : {}),
|
|
5123
5519
|
// NN41: the installed broker runtime's identity keys every cached compile failure; null (a direct host, an unreadable manifest) means no failure is cached.
|
|
5124
5520
|
...(brokerHost && cache ? (() => { const identity = brokerRuntimeIdentityText({ clients: [brokerClient, executor?.client, cargoCommand[0]], env: { ...o.env, ...(executor.env ?? {}) }, platform: o.platform }); return identity ? { failureIdentity: identity } : {}; })() : {}),
|
|
5125
5521
|
// The declared Linux broker route: the scans are planned with the logical `rustright`, which this spawn (and scanSpawn's pass-through below) starts as the
|
|
@@ -5159,43 +5555,53 @@ export async function main(argv, io = {}) {
|
|
|
5159
5555
|
})(),
|
|
5160
5556
|
onResult: (row, p) => o.out(`${tag} [${p.done}/${p.total}] ${(row.cached ? (row.status === "pass" ? "cached" : "cached-fail") : row.status).padEnd(11)} ${row.id} (${p.seconds}s)${row.batchedWith ? ` [batch of ${row.batchedWith.units.length}]` : ""}${row.status === "fail" ? ` :: ${String(row.detail ?? "").slice(0, 300)}` : row.advice ? ` :: ${String(row.advice).slice(0, 300)}` : ""}`),
|
|
5161
5557
|
};
|
|
5162
|
-
// Adrian 2026-11-
|
|
5163
|
-
//
|
|
5164
|
-
//
|
|
5165
|
-
//
|
|
5558
|
+
// Adrian 2026-11-18 cache rule supersedes the 2026-11-08 explained-runs path:
|
|
5559
|
+
// every cached class in this invocation needs its independent forecast history.
|
|
5560
|
+
// Without it there is no approved prior outcome to forecast from, so fail closed
|
|
5561
|
+
// before any scan dispatch instead of running unexpected misses.
|
|
5562
|
+
const historyByClass = { A: classAHistory, B: classBHistory };
|
|
5166
5563
|
if (!o.runScans && cache) {
|
|
5167
|
-
const
|
|
5168
|
-
|
|
5169
|
-
// Adrian 2026-11-06: "when we change something, we know exactly which rows are going to be called. Anything other than that needs approval."
|
|
5170
|
-
// A row that misses ONLY because files in its own key changed (new content ids, no tool, toolchain, broker or environment change) is one this
|
|
5171
|
-
// change must call: it runs, listed. Every other miss (nothing changed, no stored result, a tool or environment change) is reported as unexpected, with its cause.
|
|
5172
|
-
const expected = (r) => r.cacheMiss?.kind === "changed" && (r.cacheMiss.why?.inputsChanged ?? 0) > 0 && r.cacheMiss.why.contentOnly === true && !r.cacheMiss.why.tool && !r.cacheMiss.why.env && !r.cacheMiss.why.inheritedEnv;
|
|
5173
|
-
const called = allMisses.filter(expected);
|
|
5174
|
-
if (called.length) o.out(`${tag} cache lookup: ${called.length} row(s) rerun because their own files changed: ${called.slice(0, 12).map((r) => `${r.id} (${(r.cacheMiss.why.inputs ?? []).slice(0, 2).map((k) => k.replace(/^[^/]*\//, "")).join(", ")})`).join("; ")}${called.length > 12 ? "; ..." : ""}`);
|
|
5175
|
-
const misses = allMisses.filter((r) => !expected(r));
|
|
5176
|
-
if (misses.length) {
|
|
5177
|
-
const prior = new Map(lookup.scans.map((r) => [r.id, r]));
|
|
5178
|
-
const kindOf = (r) => r.cacheMiss?.kind ?? "new";
|
|
5179
|
-
const entries = misses.map((r) => ({ id: r.id, cause: kindOf(r) === "unchanged" ? "nothing changed: the cache failed" : kindOf(r) === "new" ? "no stored result (a new row, or the cache is empty)" : "inputs or environment changed", ...(r.cacheMiss?.why ? { evidence: r.cacheMiss.why } : {}), ...(r.cacheMiss?.last ? { lastPass: r.cacheMiss.last } : {}), ...(r.cacheMiss?.now ? { now: r.cacheMiss.now } : {}) })).sort((a, b) => a.id.localeCompare(b.id));
|
|
5180
|
-
const byCause = entries.reduce((m, e) => ((m[e.cause] = (m[e.cause] ?? 0) + 1), m), {});
|
|
5181
|
-
const changedInputs = {}; for (const e of entries) for (const k of e.evidence?.inputs ?? []) changedInputs[k] = (changedInputs[k] ?? 0) + 1;
|
|
5182
|
-
const tools = [...new Set(entries.filter((e) => e.evidence?.tool).map((e) => `${e.evidence.tool.from} -> ${e.evidence.tool.to}`))];
|
|
5183
|
-
const envs = [...new Set(entries.flatMap((e) => e.evidence?.env ?? []))];
|
|
5184
|
-
const commitOfRun = snapshotBCommit?.commit ?? snapshotCommitId?.commit ?? null;
|
|
5185
|
-
const body = { schema: "rightkit.gate-miss-report/1", commit: commitOfRun, planned: lookup.scans.length, hit: lookup.scans.filter((r) => r.cached).length, uncacheable: lookup.scans.filter((r) => r.uncacheable).length, misses: entries.length, byCause, topChangedInputs: Object.entries(changedInputs).sort((a, b) => b[1] - a[1]).slice(0, 20), tools, env: envs, rows: entries };
|
|
5186
|
-
// The digest names WHAT would run and WHY (commit, row ids, causes), never evidence noise, so the same misses on a rerun match the same approval.
|
|
5187
|
-
const digest = createHash("sha256").update(JSON.stringify({ schema: body.schema, commit: body.commit, rows: entries.map((e) => [e.id, e.cause]) })).digest("hex");
|
|
5188
|
-
const reportFile = path.join(gateRunsRoot({ env: o.env, platform: o.platform }), "rightkit-gate-misses", `${path.basename(root)}-${new Date().toISOString().replace(/[:.]/g, "-")}-${digest.slice(0, 12)}.json`);
|
|
5189
|
-
try { fs.mkdirSync(path.dirname(reportFile), { recursive: true }); fs.writeFileSync(reportFile, `${JSON.stringify({ ...body, digest }, null, 2)}\n`); } catch { /* the summary below still names everything */ }
|
|
5190
|
-
o.out(`${tag} cache lookup: ${body.planned} planned, ${body.hit} hit, ${body.misses} unexpected miss(es) (${Object.entries(byCause).map(([c, n]) => `${n} ${c}`).join("; ")}), ${body.uncacheable} uncacheable by design; report ${reportFile} (digest ${digest})`);
|
|
5191
|
-
if (body.topChangedInputs.length) o.out(`${tag} cache lookup: most-changed inputs ${body.topChangedInputs.slice(0, 8).map(([k, n]) => `${k} (${n})`).join(", ")}`);
|
|
5192
|
-
if (tools.length) o.out(`${tag} cache lookup: tool changes ${tools.slice(0, 5).join("; ")}`);
|
|
5193
|
-
if (envs.length) o.out(`${tag} cache lookup: environment changes ${envs.slice(0, 10).join(", ")}`);
|
|
5194
|
-
o.err(`${tag} RK_CACHE_MISS: ${body.misses} row(s) miss the cache without a change to their own files; they run now. Each miss is explained in the report; a miss where nothing changed is a cache bug: file it with the report`);
|
|
5195
|
-
void prior;
|
|
5196
|
-
} else o.out(`${tag} cache lookup: ${lookup.scans.length} planned, ${lookup.scans.filter((r) => r.cached).length} hit, ${called.length} rerun for changed files, 0 unexpected; ${lookup.scans.filter((r) => r.uncacheable).length} uncacheable by design`);
|
|
5564
|
+
const missingHistory = stageClasses.filter((cls) => !historyByClass[cls]);
|
|
5565
|
+
if (missingHistory.length) { o.err(`${tag} RK_CACHE_DIVERGENCE: cache forecast history unavailable for class ${missingHistory.join(", ")}; restore its verified history or select a new store for a declared cold run`); return 1; }
|
|
5197
5566
|
}
|
|
5198
|
-
|
|
5567
|
+
let scanResult;
|
|
5568
|
+
const decisionFiles = {};
|
|
5569
|
+
const activeHistories = stageClasses.filter((cls) => historyByClass[cls]);
|
|
5570
|
+
if (activeHistories.length) {
|
|
5571
|
+
try {
|
|
5572
|
+
for (const cls of activeHistories) {
|
|
5573
|
+
const history = historyByClass[cls];
|
|
5574
|
+
const stage = cls === "B" ? "class-b" : "class-a";
|
|
5575
|
+
const decisionFile = path.join(gateRunsRoot({ env: o.env, platform: o.platform }), `rightkit-${stage}-decisions`, randomUUID() + ".json");
|
|
5576
|
+
decisionFiles[cls] = decisionFile;
|
|
5577
|
+
const evidence = { stage, host: os.hostname(), commit: snapshotBCommit?.commit ?? snapshotCommitId?.commit ?? hostedCommitA?.commit ?? null, tree: snapshotBCommit?.tree ?? liveSnapshot, baseline: history.file };
|
|
5578
|
+
const forecasts = {};
|
|
5579
|
+
scanOptions[`class${cls}CacheForecast`] = (rows, { phase } = {}) => {
|
|
5580
|
+
const forecast = history.forecast(rows);
|
|
5581
|
+
if (phase) forecasts[phase] = forecast;
|
|
5582
|
+
writeFileAtomic(decisionFile, JSON.stringify({ ...evidence, phase: "forecast", forecast, ...(phase ? { forecasts } : {}) }), { mode: 0o600 });
|
|
5583
|
+
return forecast;
|
|
5584
|
+
};
|
|
5585
|
+
}
|
|
5586
|
+
scanResult = await runScans(plan, scanOptions);
|
|
5587
|
+
let blocked = false;
|
|
5588
|
+
for (const cls of activeHistories) {
|
|
5589
|
+
const history = historyByClass[cls];
|
|
5590
|
+
const stage = cls === "B" ? "class-b" : "class-a";
|
|
5591
|
+
const decisionFile = decisionFiles[cls];
|
|
5592
|
+
const decision = scanResult[`class${cls}CacheDecision`];
|
|
5593
|
+
if (!decision) throw new Error(`Class ${cls} scanner returned no forecast decision`);
|
|
5594
|
+
const evidence = { stage, host: os.hostname(), commit: snapshotBCommit?.commit ?? snapshotCommitId?.commit ?? hostedCommitA?.commit ?? null, tree: snapshotBCommit?.tree ?? liveSnapshot, baseline: history.file };
|
|
5595
|
+
writeFileAtomic(decisionFile, JSON.stringify({ ...evidence, ...decision, phase: "observed" }), { mode: 0o600 });
|
|
5596
|
+
if (decision.mismatches.length) {
|
|
5597
|
+
blocked = true;
|
|
5598
|
+
for (const row of decision.mismatches) o.err(`${tag} RK_CACHE_DIVERGENCE ${JSON.stringify(row)}`);
|
|
5599
|
+
o.err(`${tag} BLOCKED: ${decision.dispatchedRows.length} row dispatches. Evidence: ${decisionFile}`);
|
|
5600
|
+
} else o.out(`${tag} Class ${cls} cache decision: ${decisionFile}`);
|
|
5601
|
+
}
|
|
5602
|
+
if (blocked) return 1;
|
|
5603
|
+
} catch (error) { o.err(`${tag} RK_CACHE_DIVERGENCE: ${error.message}`); return 1; }
|
|
5604
|
+
} else scanResult = await (o.runScans ?? runScans)(plan, scanOptions);
|
|
5199
5605
|
if (nodeCheckRejects.size) o.out(`${tag} node-check cache misses: ${[...nodeCheckRejects].sort(([a], [b]) => a.localeCompare(b)).map(([reason, count]) => `${reason}=${count}`).join(", ")}`);
|
|
5200
5606
|
if (snapFullA && o.env.RIGHTKIT_PREPARATION_DIAGNOSTIC_DIR && nodeCheckDiagnosticId) o.out(`${tag} node-check diagnostic row: ${nodeCheckDiagnosticState}`);
|
|
5201
5607
|
if (unionContext) {
|
|
@@ -5230,6 +5636,7 @@ export async function main(argv, io = {}) {
|
|
|
5230
5636
|
// rightkit#1463: the per-scan coverage report (hit / ran / skipped, with the cache key and the reason), written beside the scan logs; a cache that never hits shows here.
|
|
5231
5637
|
try {
|
|
5232
5638
|
const report = buildCoverageReport({ plan, scanResult, keys: scanKeys, keyErrors, cacheDisabled, classes: classAOnly ? ["A"] : classAEarlier ? ["B"] : ["A", "B"], commit: snapshotBCommit?.commit ?? snapshotCommitId?.commit ?? hostedCommitA?.commit ?? null, startedAt: new Date(directTiming.cargoStart).toISOString(), endedAt: new Date(directTiming.cargoEnd).toISOString() });
|
|
5639
|
+
o.onLimitedEvidence?.(limitedEvidenceOf(report));
|
|
5233
5640
|
const base = gateRunsRoot({ env: o.env, platform: o.platform });
|
|
5234
5641
|
const file = (o.writeCoverage ?? writeCoverageReport)({ dir: path.join(base, "rightkit-gate-coverage"), name: `${path.basename(root)}-${new Date().toISOString().replace(/[:.]/g, "-")}-${process.pid}`, report });
|
|
5235
5642
|
const otherPass = (report.scans ?? []).filter((s) => s.coverage === "skipped" && /is not part of this pass/.test(String(s.reason ?? ""))).length;
|
|
@@ -5238,6 +5645,15 @@ export async function main(argv, io = {}) {
|
|
|
5238
5645
|
// What a full class A verdict binds, green or red: the bytes it judged, unchanged from start to end, and the environment it judged
|
|
5239
5646
|
// in (gate, tools, installed dependencies, tool caches), unchanged too. A verdict whose binding moved covers nothing: a green one is
|
|
5240
5647
|
// refused and a red one names no reusable deterministic cause (rightkit#1257). Returns { env, notes } or { prefix, problem, exit }.
|
|
5648
|
+
const recordedHistories = new Set();
|
|
5649
|
+
const recordHistory = () => {
|
|
5650
|
+
for (const cls of activeHistories) {
|
|
5651
|
+
if (recordedHistories.has(cls)) continue;
|
|
5652
|
+
try { historyByClass[cls].record(scanResult[`class${cls}CacheDecision`]); recordedHistories.add(cls); }
|
|
5653
|
+
catch (error) { o.err(`${tag} BLOCKED: cannot record verified Class ${cls} cache outcomes: ${error.message}`); return false; }
|
|
5654
|
+
}
|
|
5655
|
+
return true;
|
|
5656
|
+
};
|
|
5241
5657
|
const judgedBinding = async () => {
|
|
5242
5658
|
if (hostedFullA) {
|
|
5243
5659
|
try { await verifyCommittedCheckout({ git, root, ...hostedCommitA, when: "after class A" }); }
|
|
@@ -5254,7 +5670,7 @@ export async function main(argv, io = {}) {
|
|
|
5254
5670
|
}
|
|
5255
5671
|
if (!live) return { env: null, notes: [] };
|
|
5256
5672
|
let envDigest; let envNoCaches;
|
|
5257
|
-
try { envDigest = classAEnvironmentDigest({ root: liveBase, gatePackage: o.gatePackage, files: live.files, spawn: o.spawn }); envNoCaches =
|
|
5673
|
+
try { envDigest = classAEnvironmentDigest({ root: liveBase, gatePackage: o.gatePackage, files: live.files, spawn: o.spawn }); envNoCaches = envDigest; }
|
|
5258
5674
|
catch (error) { return { prefix: "BLOCKED", exit: 1, problem: error.message }; }
|
|
5259
5675
|
const notes = [];
|
|
5260
5676
|
if (cachesAtStart !== null) {
|
|
@@ -5286,23 +5702,17 @@ export async function main(argv, io = {}) {
|
|
|
5286
5702
|
// rebuilds or proves fresh for this commit. A unit only checked, linted, documented, deferred to CI or without such a target counts for nothing.
|
|
5287
5703
|
const unitByName = new Map(rust.units.map((u) => [u.name, u]));
|
|
5288
5704
|
const known = new Set(unitByName.keys());
|
|
5289
|
-
|
|
5290
|
-
//
|
|
5291
|
-
//
|
|
5292
|
-
const
|
|
5293
|
-
|
|
5294
|
-
|
|
5295
|
-
|
|
5296
|
-
|
|
5297
|
-
|
|
5298
|
-
|
|
5299
|
-
|
|
5300
|
-
if (r.status !== "pass" || r.cached === true || !/^test:rust(?:-serial)?:/.test(String(r.id))) continue;
|
|
5301
|
-
const unit = unitByName.get(rustUnitOfScanId(r.id, known));
|
|
5302
|
-
// Every compile is release for the host target (GC-A15, cross-targets.mjs oneOutput): the test executables are under <triple>/release.
|
|
5303
|
-
if (snapshotBroker) addBins(r.snapshotEvidence?.outputDir, unit, r.snapshotEvidence?.targetTriple ? `${r.snapshotEvidence.targetTriple}/release` : null);
|
|
5304
|
-
else addBins(targetDirs?.[unit?.cargoDir ?? "."], unit, `${hostTarget()}/release`);
|
|
5305
|
-
}
|
|
5705
|
+
// Where Cargo put them: `<dir>/<triple>/release` (every compile is release for the host target, GC-A15, cross-targets.mjs oneOutput); on a broker
|
|
5706
|
+
// host the signed receipt names the directory and the triple, and a row with no triple vouches for nothing: a guessed path could vouch for a stale
|
|
5707
|
+
// binary. A row answered from the cache vouches for its programs only while they are still the bytes it linked (gate-stages.mjs builtBinsOfRun).
|
|
5708
|
+
const builtBins = builtBinsOfRun({
|
|
5709
|
+
rows: scanResult.scans,
|
|
5710
|
+
unitOf: (r) => unitByName.get(rustUnitOfScanId(r.id, known)),
|
|
5711
|
+
placeOf: (r) => { const unit = unitByName.get(rustUnitOfScanId(r.id, known)); return snapshotBroker ? { dir: r.snapshotEvidence?.outputDir, profile: r.snapshotEvidence?.targetTriple ? `${r.snapshotEvidence.targetTriple}/release` : null } : { dir: targetDirs?.[unit?.cargoDir ?? "."], profile: `${hostTarget()}/release` }; },
|
|
5712
|
+
keyOf: (r) => { const full = scanKeys.get(r.id); return typeof full === "string" && full ? createHash("sha256").update(`built-bins/1\n${full}`).digest("hex") : null; },
|
|
5713
|
+
store: cache,
|
|
5714
|
+
note: (text) => o.out(`${tag} built programs: ${text}`),
|
|
5715
|
+
});
|
|
5306
5716
|
const outputWorkspaces = (snapshotBroker ? scanResult.scans.map((r) => r.snapshotEvidence?.outputDir) : Object.values(targetDirs ?? {})).filter(Boolean).map((dir) => [dir]);
|
|
5307
5717
|
o.onCompileOutputs?.(outputWorkspaces.map(([dir]) => dir), builtBins);
|
|
5308
5718
|
o.out(`${tag} class B keying: ${ROW_DIGEST_STATS.misses} row digest(s) computed in ${(ROW_DIGEST_STATS.ms / 1000).toFixed(1)} s, ${ROW_DIGEST_STATS.hits} reused`);
|
|
@@ -5336,6 +5746,7 @@ export async function main(argv, io = {}) {
|
|
|
5336
5746
|
o.onDirectReceipt?.(directReceipt);
|
|
5337
5747
|
o.out(`${tag} direct receipt ${JSON.stringify(directReceipt)}`);
|
|
5338
5748
|
}
|
|
5749
|
+
if (classBHistory && !recordHistory()) return 1;
|
|
5339
5750
|
}
|
|
5340
5751
|
if (unionContext) unionContext.completed = true;
|
|
5341
5752
|
if (failures.length) {
|
|
@@ -5351,6 +5762,7 @@ export async function main(argv, io = {}) {
|
|
|
5351
5762
|
if (binding.exit === 2) return 2;
|
|
5352
5763
|
} else {
|
|
5353
5764
|
for (const n of binding.notes) o.out(`${tag} ${n}`);
|
|
5765
|
+
if (!recordHistory()) return 1;
|
|
5354
5766
|
const marker = (await import("../snapshot-check.mjs")).deterministicMarker(scanResult, plan.scopeDigest ? createHash("sha256").update(`${binding.env}:${plan.scopeDigest}:${plan.scanSetDigest}`).digest("hex") : binding.env);
|
|
5355
5767
|
if (marker) o.out(marker);
|
|
5356
5768
|
}
|
|
@@ -5377,6 +5789,7 @@ export async function main(argv, io = {}) {
|
|
|
5377
5789
|
try { await (await import("../snapshot-dependency-reuse.mjs")).capturePostClassADiagnostics({ checkout: root, snapshot: snapshotA, commit: snapshotCommitId.commit, roots: installRoots, diagnosticDir: o.env.RIGHTKIT_PREPARATION_DIAGNOSTIC_DIR }); }
|
|
5378
5790
|
catch { /* Optional diagnostics never change the gate verdict. */ }
|
|
5379
5791
|
}
|
|
5792
|
+
if (!recordHistory()) return 1;
|
|
5380
5793
|
o.out(`${tag} class A ${plan.scopeDigest ? "scoped" : "full"} pass: ${scanResult.scans.length} deterministic check(s), the ones that execute repository code included, over ${changed.length} file(s) of ${base}`);
|
|
5381
5794
|
return 0;
|
|
5382
5795
|
}
|
|
@@ -5385,9 +5798,11 @@ export async function main(argv, io = {}) {
|
|
|
5385
5798
|
// full class A pass, and it says so (reviewer, 2026-10-27). The full gate runs them before any compile.
|
|
5386
5799
|
const notRun = plan.scans.filter((s) => s.class === "A" && s.executes === true).map((s) => s.id);
|
|
5387
5800
|
if (notRun.length) o.out(`${tag} class A partial: ${notRun.length} check(s) that execute repository code (tests, typecheck, lint, generated docs) run in the full gate, not in check: ${notRun.slice(0, 8).join(", ")}${notRun.length > 8 ? ", …" : ""}`);
|
|
5801
|
+
if (!recordHistory()) return 1;
|
|
5388
5802
|
o.out(`${tag} class A content pass: ${scanResult.scans.length} deterministic scan(s) over ${changed.length} file(s) of ${base}`);
|
|
5389
5803
|
return 0;
|
|
5390
5804
|
}
|
|
5805
|
+
if (!recordHistory()) return 1;
|
|
5391
5806
|
o.out(`${tag} pass (${changed.length} changed file(s) vs ${base}); ${deferrals.length} scan(s) deferred, not passed${scanResult.cacheHits.length ? `; ${scanResult.cacheHits.length} reused from the result cache` : ""}`);
|
|
5392
5807
|
return 0;
|
|
5393
5808
|
} finally {
|
|
@@ -5416,6 +5831,16 @@ export const callingGatePath = () => fs.realpathSync(fileURLToPath(import.meta.u
|
|
|
5416
5831
|
if (invokedDirectly) {
|
|
5417
5832
|
// GC-A27 NN07-NN12: with RK_GATE_SPAWN_LEDGER set, every child process of this run is recorded (spawn-ledger.mjs). Off otherwise.
|
|
5418
5833
|
installSpawnLedger();
|
|
5834
|
+
// NN07: a fixed question about the checkout (git top level, object format, whether an id names a commit, where a tool is) is asked once per process.
|
|
5835
|
+
// NN22: whole-tree listings of a full commit id are kept between gate processes (probe-memo.mjs treeListStore).
|
|
5836
|
+
{
|
|
5837
|
+
const treeLists = (() => { try { return path.join(gateRunsRoot({ env: process.env, platform: process.platform }), "tree-lists"); } catch { return null; } })();
|
|
5838
|
+
installProbeMemo({ storeDir: treeLists });
|
|
5839
|
+
// NN22: the sealed listing (snapshot.mjs treeEntries) runs in a fresh private directory, so it is kept by object database, not by working directory.
|
|
5840
|
+
setTreeListingStore(treeLists ? contentStore(path.join(treeLists, "sealed")) : null);
|
|
5841
|
+
}
|
|
5842
|
+
// NN11/NN28: how this run proved the snapshot, once, at the end (snapshot.mjs SNAPSHOT_PROOF_COUNTS).
|
|
5843
|
+
process.once("exit", () => { const c = SNAPSHOT_PROOF_COUNTS; if (c.treeHashes + c.verifyWalks + c.residentProofs > 0) { try { process.stdout.write(`${stampChildLines ? `${new Date().toISOString()} ` : ""}rightkit-gate: ${snapshotProofLine(c.changeSource ?? "none")}\n`); } catch { /* stdout closed */ } } });
|
|
5419
5844
|
// Every child this run starts that can reach rustright (scans, unit stages, right-release dev/test, their builds) inherits it.
|
|
5420
5845
|
process.env.RUSTRIGHT_CALLING_GATE = callingGatePath();
|
|
5421
5846
|
delete process.env.RIGHTKIT_CALLING_GATE; // one spelling, never both
|