@rightkit/release 0.6.57 → 0.6.62
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 +552 -124
- 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 +170 -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 +179 -34
- package/gate-stages.mjs +59 -0
- package/legacy-contract-receipt.mjs +809 -0
- package/local-publish.mjs +2 -4
- 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 +89 -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,10 @@
|
|
|
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
|
+
/** One line, once, when the gate set an unusable cache aside and started an empty one in the same place (class-a-cache-history.mjs). */
|
|
78
|
+
const cacheRestartNote = (o) => ({ store, reason, storeAside }) => (o.out ?? console.log)(`rightkit-gate: cache restarted: ${store} could not be used (${reason}); ${storeAside ? `the old one is kept at ${storeAside}` : "there was no old store to keep"}; every row is checked once more and stored here`);
|
|
79
|
+
import { writeFileAtomic } from "../atomic-write.mjs";
|
|
76
80
|
import { envNamed, gateRunsRoot, resolveManagedRoots } from "../managed-roots.mjs";
|
|
77
81
|
import { resolveBrokerClient, spawnBrokerClient } from "../broker-client.mjs";
|
|
78
82
|
import os from "node:os";
|
|
@@ -81,20 +85,33 @@ import { hostTarget } from "../cross-targets.mjs";
|
|
|
81
85
|
import { FOREIGN_PRE_COMMIT, retireHooksIn } from "../hook-retirement.mjs";
|
|
82
86
|
import { fileURLToPath } from "node:url";
|
|
83
87
|
import { installIdentity, installStateBytes } from "../dependency-identity.mjs";
|
|
88
|
+
import { pnpmVersionAnswer } from "../snapshot-dependency-reuse.mjs";
|
|
84
89
|
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
90
|
import { changedLockNames, parseLock, reach } from "../lock-graph.mjs";
|
|
86
91
|
import { resolveExecutor } from "../gate-executor.mjs";
|
|
87
92
|
// The gate's own executor: an outer gate's cargo wrapper on PATH is never this gate's cargo (gate-executor.mjs `gateWrappers`).
|
|
88
93
|
const gateResolveExecutor = (args) => resolveExecutor({ ...args, gateWrappers: true });
|
|
94
|
+
/**
|
|
95
|
+
* NN09, NN25: which cargo and rustc the broker compiles with, read in this process from the broker's own host configuration
|
|
96
|
+
* (broker-toolchain.mjs) instead of asking through the client (`rustright cargo --version`, `rustright rustc -V`). null for an injected
|
|
97
|
+
* 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
|
|
98
|
+
* asks as before.
|
|
99
|
+
*/
|
|
100
|
+
function brokerToolchainOf(o, executor) {
|
|
101
|
+
if (o.spawn !== defaultSpawn || executor?.kind !== "broker" || !Array.isArray(executor.cargo) || executor.cargo.length < 2) return null;
|
|
102
|
+
let answer = null;
|
|
103
|
+
try { const launcher = resolveOnPath(executor.cargo[0], { env: o.env, platform: o.platform }); answer = launcher ? brokerToolchain({ launcher }) : null; } catch { answer = null; }
|
|
104
|
+
return answer?.ok ? answer : null;
|
|
105
|
+
}
|
|
89
106
|
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
107
|
import { SIGNING_REFUSAL_CODES, suiteSigningRefusals } from "../suite-signing-policy.mjs";
|
|
91
108
|
import { gitListRustFiles } from "../signing-files.mjs";
|
|
92
109
|
import { nativeHelpersFromConfig } from "../native-helpers.mjs";
|
|
93
|
-
import { buildCoverageReport, seconds, writeCoverageReport } from "../gate-coverage.mjs";
|
|
110
|
+
import { buildCoverageReport, limitedEvidenceOf, seconds, writeCoverageReport } from "../gate-coverage.mjs";
|
|
94
111
|
import { renderViews, renderViewsOf } from "../render-views.mjs";
|
|
95
112
|
import { LINUX_BROKER_ROUTE, NO_BROKER_ENV, directCargoPath, directPlatform, managedRuntimeClient, realCargoOf, runCargoSync } from "../managed-cargo.mjs";
|
|
96
113
|
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";
|
|
114
|
+
import { bindingOf, builtBinsOfRun, compileOutputsRecord, compileReuseProblem, endRun, readReceipt, RECEIPT_SCHEMA, receiptKey, sameBinding, sameSource, sealedFor, stagesTo, startRun, STAGES, STAGE_SOURCES, writeReceipt } from "../gate-stages.mjs";
|
|
98
115
|
import { spawnSync as spawnInherit } from "../background-process.mjs";
|
|
99
116
|
// 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
117
|
// (the launch stays synchronous and the output still streams). Set by main() when the run stamps; off for machine-readable runs.
|
|
@@ -106,15 +123,21 @@ const inheritLaunch = (cmd, a, opts) => (stampChildLines
|
|
|
106
123
|
import { readDiskPolicy, scratchRoots } from "../disk-policy.mjs";
|
|
107
124
|
import { buildDirectReceipt, directVerdict, resolveTargetDirectory, verifyDirectReceipt, writeDirectDiagnostics } from "../direct-receipt.mjs";
|
|
108
125
|
import { platformDirOf } from "../platform-dir.mjs";
|
|
109
|
-
import { buildInventory, classifyUnitResults, dependencyFirstOrder, selectAffectedAcrossInventories, unitListReport } from "../affected-units.mjs";
|
|
126
|
+
import { buildInventory, classifyUnitResults, dependencyFirstOrder, selectAffectedAcrossInventories, classifyUnitRows, unitListReport } from "../affected-units.mjs";
|
|
110
127
|
import { createRequire } from "node:module";
|
|
111
|
-
import { BUILD_CONTROL_PROTOCOL, HANDSHAKE_PROBE_ID, RUNTIME_MANIFEST_FILE, parseRuntimeIdentity } from "../seam-broker.mjs";
|
|
128
|
+
import { BUILD_CONTROL_PROTOCOL, HANDSHAKE_PROBE_ID, RUNTIME_MANIFEST_FILE, brokerControlTarget, parseRuntimeIdentity } from "../seam-broker.mjs";
|
|
112
129
|
import { snapshotReclaimJudge } from "../seam-broker.mjs";
|
|
113
130
|
import net from "node:net";
|
|
114
131
|
import { installSpawnLedger } from "../spawn-ledger.mjs";
|
|
132
|
+
import { rememberedVersion, resolveOnPath } from "../tool-version-memo.mjs";
|
|
133
|
+
import { brokerToolchain } from "../broker-toolchain.mjs";
|
|
134
|
+
import { SNAPSHOT_PROOF_COUNTS, snapshotProofLine } from "../snapshot.mjs";
|
|
135
|
+
import { contentStore, installProbeMemo } from "../probe-memo.mjs";
|
|
136
|
+
import { discoveryRun, sealedRepoInfo, setTreeListingStore } from "../snapshot-git.mjs";
|
|
115
137
|
import { processIdentity, snapshotLockBody, verdictFileName } from "../gate-seam.mjs";
|
|
116
138
|
|
|
117
139
|
const PRIVATE_SCOPED_COMPILE = Symbol("private scoped compile");
|
|
140
|
+
const CLASS_A_HISTORY = Symbol("Class A cache history");
|
|
118
141
|
const UNIT_LIST_UNION = Symbol("unit list union");
|
|
119
142
|
// Class B row input digests per tree (see rowDigest in the compile stage); counted so the run summary shows the time keying took.
|
|
120
143
|
const ROW_DIGEST_MEMO = new Map();
|
|
@@ -484,7 +507,7 @@ export function installedDependencyDigest({ root, files, includeCaches = true })
|
|
|
484
507
|
* (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
508
|
* (`rightkit-gate env-digest`), so a dependency or tool change while a compile waits invalidates the ticket.
|
|
486
509
|
*/
|
|
487
|
-
export function classAEnvironmentDigest({ root, files, spawn = defaultSpawn, includeCaches = true, gatePackage = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..") }) {
|
|
510
|
+
export function classAEnvironmentDigest({ root, files, spawn = defaultSpawn, includeCaches = true, gatePackage = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."), onRowEnvironment }) {
|
|
488
511
|
// Only a file that does not exist is "absent"; any other read failure throws: an input whose bytes cannot be read is never
|
|
489
512
|
// identified by a placeholder that would match the same failure later.
|
|
490
513
|
// `optional`: only an install-state file may legitimately not exist; a gate file found by the walk must be readable.
|
|
@@ -499,14 +522,21 @@ export function classAEnvironmentDigest({ root, files, spawn = defaultSpawn, inc
|
|
|
499
522
|
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
523
|
// Bounded: a pnpm that switches itself to the repository's packageManager version on first use, or waits on the network,
|
|
501
524
|
// must fail the probe (and its process tree) within PNPM_PROBE_TIMEOUT_MS, never hang an admission.
|
|
502
|
-
|
|
525
|
+
// NN25, NN07: asked once and then kept by the open gate process while the files that decide which pnpm runs here are unchanged
|
|
526
|
+
// (snapshot-dependency-reuse.mjs pnpmVersionAnswer); only the real spawn remembers, a failed or timed-out probe is never kept.
|
|
527
|
+
const pnpmVersion = pnpmVersionAnswer({ cwd: root, env: process.env, remember: spawn === defaultSpawn, run: () => {
|
|
503
528
|
const r = spawn("pnpm", ["--version"], { cwd: root, boundedMs: PNPM_PROBE_TIMEOUT_MS });
|
|
504
529
|
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
530
|
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
531
|
return text(r).trim();
|
|
507
|
-
})
|
|
508
|
-
const installState =
|
|
509
|
-
|
|
532
|
+
} });
|
|
533
|
+
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}`; });
|
|
534
|
+
const installed = installedDependencyDigest({ root, files, includeCaches });
|
|
535
|
+
const bind = (gateInputs) => createHash("sha256").update([`node ${process.version}`, `pnpm ${pnpmVersion}`, `platform ${process.platform}-${process.arch}`, ...gateInputs, ...installState, `installed ${installed}`].join("\n")).digest("hex");
|
|
536
|
+
// The verdict binds all gate data. Only cargo-deny rows using the packaged
|
|
537
|
+
// policy read deny-default.toml. Their per-row digest binds its exact bytes.
|
|
538
|
+
if (onRowEnvironment) onRowEnvironment(bind(gateFiles.filter((entry) => !entry.startsWith("deny-default.toml:"))));
|
|
539
|
+
return bind(gateFiles);
|
|
510
540
|
}
|
|
511
541
|
|
|
512
542
|
/** The pnpm a package.json pins (`packageManager: "pnpm@12.16.1+sha512.."` -> `12.16.1`), or null for no pnpm pin. */
|
|
@@ -540,8 +570,9 @@ export function pnpmPinProblem({ root, files, spawn = defaultSpawn, readFile = (
|
|
|
540
570
|
if (pin) pins.set(f, pin);
|
|
541
571
|
}
|
|
542
572
|
if (!pins.size) return null;
|
|
543
|
-
|
|
544
|
-
|
|
573
|
+
// Kept by the open gate process like the Class A environment's probe (pnpmVersionAnswer); a probe that fails is asked again next time.
|
|
574
|
+
let r = null; // the probe's own result when it ran (the refusals below name its error); null when the kept answer was used
|
|
575
|
+
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
576
|
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
577
|
const bad = [...pins].filter(([, pin]) => pin !== onPath);
|
|
547
578
|
if (!bad.length) return null;
|
|
@@ -842,6 +873,86 @@ export function lockScope({ changed, cargoDir = ".", unitNames, showBase, readLo
|
|
|
842
873
|
// The build inputs that change how every crate compiles, relative to the Cargo workspace root, plus the gate's own config.
|
|
843
874
|
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
875
|
const GATE_CONFIG = "ci/gate.config.json";
|
|
876
|
+
/**
|
|
877
|
+
* 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
|
|
878
|
+
* through a `path = "..."` or `path = '...'` dependency of those (dependencies, [dependencies.x] tables, [patch], [workspace.dependencies]),
|
|
879
|
+
* transitively. `all`: the commit's file list; `readBlob(path)`: a file's text.
|
|
880
|
+
* 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:
|
|
881
|
+
* a manifest it cannot read, a `path =` it cannot parse (a multi-line or escaped string), a workspace member outside `dir` (`members` naming
|
|
882
|
+
* `..`), or a Cargo configuration of `dir` or an ancestor that overrides paths (`paths =` in .cargo/config[.toml]) (astra62 review, 2026-11-18).
|
|
883
|
+
*/
|
|
884
|
+
// 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
|
|
885
|
+
// load, every reader here answers "cannot tell" (null, or every manifest), never fewer checks or manifests.
|
|
886
|
+
let manifestTomlParse;
|
|
887
|
+
const parseManifestToml = (text) => (manifestTomlParse ??= createRequire(import.meta.url)("smol-toml").parse)(text);
|
|
888
|
+
export function cargoManifestsOfWorkspace({ dir, all, readBlob }) {
|
|
889
|
+
const isManifest = (f) => /(^|\/)Cargo\.toml$/.test(f);
|
|
890
|
+
const present = new Set(all.filter(isManifest));
|
|
891
|
+
const every = [...present].sort();
|
|
892
|
+
const isTable = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
|
|
893
|
+
// 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.
|
|
894
|
+
const docOf = (f) => { try { const t = readBlob(f); return typeof t === "string" ? parseManifestToml(t) : null; } catch { return null; } };
|
|
895
|
+
const inRepo = (p) => { const n = path.posix.normalize(p); return n.startsWith("..") ? null : n === "." ? "" : n; };
|
|
896
|
+
const join = (base, rel) => inRepo(path.posix.join(base === "." ? "" : base, rel));
|
|
897
|
+
// A Cargo configuration of the workspace or an ancestor that overrides or patches paths: every manifest.
|
|
898
|
+
const dirs = dir === "." ? ["."] : dir.split("/").map((_, i, parts) => parts.slice(0, i + 1).join("/")).concat(".");
|
|
899
|
+
for (const d of dirs) for (const name of [".cargo/config.toml", ".cargo/config"]) {
|
|
900
|
+
const p = d === "." ? name : `${d}/${name}`;
|
|
901
|
+
if (!all.includes(p)) continue;
|
|
902
|
+
const doc = docOf(p);
|
|
903
|
+
if (doc === null || doc.paths !== undefined || doc.patch !== undefined) return every;
|
|
904
|
+
}
|
|
905
|
+
const out = new Set([...present].filter((f) => dir === "." || f.startsWith(`${dir}/`))); const queue = [...out];
|
|
906
|
+
const add = (m) => { if (m !== null && present.has(m) && !out.has(m)) { out.add(m); queue.push(m); } };
|
|
907
|
+
// The workspace root a member inherits from: `package.workspace`, else the nearest ancestor manifest with a [workspace] table.
|
|
908
|
+
const rootOf = (m, doc) => {
|
|
909
|
+
const base = path.posix.dirname(m);
|
|
910
|
+
if (isTable(doc.workspace)) return m;
|
|
911
|
+
if (isTable(doc.package) && doc.package.workspace !== undefined) return typeof doc.package.workspace === "string" ? join(base, `${doc.package.workspace}/Cargo.toml`) : undefined;
|
|
912
|
+
for (let d = base; d !== "." && d !== ""; d = path.posix.dirname(d)) {
|
|
913
|
+
const up = path.posix.dirname(d) === "." ? "Cargo.toml" : `${path.posix.dirname(d)}/Cargo.toml`;
|
|
914
|
+
if (!present.has(up)) continue;
|
|
915
|
+
const parent = docOf(up); if (parent === null) return undefined;
|
|
916
|
+
if (isTable(parent.workspace)) return up;
|
|
917
|
+
}
|
|
918
|
+
return null;
|
|
919
|
+
};
|
|
920
|
+
while (queue.length) {
|
|
921
|
+
const m = queue.pop(); const doc = docOf(m);
|
|
922
|
+
if (doc === null) return every;
|
|
923
|
+
const base = path.posix.dirname(m);
|
|
924
|
+
// dev_dependencies and build_dependencies are the spellings Cargo accepted before edition 2024 (astra62 review 4).
|
|
925
|
+
const tables = [doc.dependencies, doc["dev-dependencies"], doc["build-dependencies"], doc.dev_dependencies, doc.build_dependencies, doc.replace,
|
|
926
|
+
...(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])) : []),
|
|
927
|
+
...(isTable(doc.workspace) ? [doc.workspace.dependencies] : []),
|
|
928
|
+
...(isTable(doc.patch) ? Object.values(doc.patch) : doc.patch === undefined ? [] : [null])];
|
|
929
|
+
let inherits = false;
|
|
930
|
+
for (const t of tables) {
|
|
931
|
+
if (t === undefined) continue;
|
|
932
|
+
if (!isTable(t)) return every;
|
|
933
|
+
for (const spec of Object.values(t)) {
|
|
934
|
+
if (!isTable(spec)) continue;
|
|
935
|
+
// A backslash is a separator to Cargo on Windows and a file-name character elsewhere: cannot tell which manifest, so every one.
|
|
936
|
+
if (spec.path !== undefined) { if (typeof spec.path !== "string" || spec.path.includes("\\")) return every; add(join(base, `${spec.path}/Cargo.toml`)); }
|
|
937
|
+
if (spec.workspace === true) inherits = true;
|
|
938
|
+
}
|
|
939
|
+
}
|
|
940
|
+
// Any `workspace = true` anywhere outside the [workspace] table (a dependency, a package field, `[lints] workspace = true`, whatever Cargo adds next)
|
|
941
|
+
// 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:
|
|
942
|
+
// a dependency's inherited lints come from its own workspace's root).
|
|
943
|
+
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)));
|
|
944
|
+
if (inherits || inheritsAnywhere(doc)) {
|
|
945
|
+
const root = rootOf(m, doc);
|
|
946
|
+
if (root === undefined || root === null) return every;
|
|
947
|
+
add(root);
|
|
948
|
+
}
|
|
949
|
+
// A member named outside the workspace directory: every manifest (members may be globs; only those inside are found by the directory rule).
|
|
950
|
+
// Only the keyed workspace's own root: another workspace reached through a path dependency contributes its manifest, not its members.
|
|
951
|
+
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;
|
|
952
|
+
}
|
|
953
|
+
return [...out].sort();
|
|
954
|
+
}
|
|
955
|
+
|
|
845
956
|
// What cargo, clippy, rustfmt and cargo-deny also read from EVERY ancestor directory of the workspace (the repository root and each
|
|
846
957
|
// directory between it and the workspace: they search upward), relative to that directory.
|
|
847
958
|
const ANCESTOR_RUST_INPUTS = [".cargo", "rust-toolchain", "rust-toolchain.toml", "clippy.toml", ".clippy.toml", "rustfmt.toml", ".rustfmt.toml", "deny.toml"];
|
|
@@ -904,7 +1015,9 @@ const within = (dir, p) => dir === "." || p === dir || p.startsWith(`${dir}/`);
|
|
|
904
1015
|
// current directory, a bare ".." segment, or the manifest directory's parent. Its tests may read anything in the repository.
|
|
905
1016
|
// A comparison with ".." (`name != ".."`), a method whose name only ends in current_dir (`get_current_dir()`), `.ancestors()` of a runtime path and
|
|
906
1017
|
// 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
|
-
|
|
1018
|
+
// A literal made only of parent steps ("..", "../", "../..", "../../") is such a walk, however many steps; one handed to a string test
|
|
1019
|
+
// (`starts_with("../")`, `contains("..")`) or compared with == or != is not.
|
|
1020
|
+
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
1021
|
|
|
909
1022
|
export function externalInputs({ dir, files, readBlob, exists, includeRuntimePaths = true }) {
|
|
910
1023
|
const paths = new Set(); let unresolved = null; let leavesCrate = null;
|
|
@@ -920,6 +1033,11 @@ export function externalInputs({ dir, files, readBlob, exists, includeRuntimePat
|
|
|
920
1033
|
const resolved = path.posix.normalize(path.posix.join(base, raw)).replace(/\/+$/, "");
|
|
921
1034
|
if (resolved === ".." || resolved.startsWith("../")) { escapes += 1; continue; }
|
|
922
1035
|
if (within(dir, resolved) || paths.has(resolved)) continue;
|
|
1036
|
+
// 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
|
|
1037
|
+
// 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
|
|
1038
|
+
// 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
|
|
1039
|
+
// 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.
|
|
1040
|
+
if (resolved === "." || dir.startsWith(`${resolved}/`)) continue;
|
|
923
1041
|
if (exists(resolved)) { paths.add(resolved); if (resolved.endsWith(".rs")) enqueue(resolved, { external: true }); }
|
|
924
1042
|
}
|
|
925
1043
|
if (escapes === bases.length) stop(`${from}: ${JSON.stringify(rel)} leaves the repository`);
|
|
@@ -1014,7 +1132,7 @@ const plainRelative = (p) => typeof p === "string" && p !== "" && !path.posix.is
|
|
|
1014
1132
|
* 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
1133
|
* - Class A: pnpm-lockfile and advisory-exceptions are never cached (live answers). cargo-deny, cargo-audit and pnpm-audit are cached by
|
|
1016
1134
|
* 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,
|
|
1135
|
+
* blob, the workspace's manifest closure, configuration, and the pinned RustSec commit (cargo-deny and cargo-audit
|
|
1018
1136
|
* read exactly that commit); a pnpm root's lock, manifests and npm configuration. cargo-deny also reads the crate index (yanked
|
|
1019
1137
|
* 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
1138
|
* hit, the next day is a run. A changed pin, lock, manifest or configuration is a different key; rustfmt,
|
|
@@ -1036,7 +1154,7 @@ function shardSoloOf(o, repo) {
|
|
|
1036
1154
|
} catch { return []; }
|
|
1037
1155
|
}
|
|
1038
1156
|
|
|
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 }) {
|
|
1157
|
+
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
1158
|
const memo = new Map(); const reachMemos = new Map(); const externalMemo = new Map();
|
|
1041
1159
|
const idOf = (p) => { if (!memo.has(p)) memo.set(p, p === "." ? headTree : objectId(p)); return memo.get(p); };
|
|
1042
1160
|
// npm: a package's test, tsc and eslint scans read the package, every workspace package it depends on (package.json
|
|
@@ -1110,6 +1228,7 @@ export function buildCacheDigest({ objectId, headTree, rustUnits = [], npmUnits
|
|
|
1110
1228
|
// 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
1229
|
// 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
1230
|
// (RK_ADVISORY_DB_COMMIT) and its pin object, the gate's code and advisory-db.json are in the environment digest the caller appends.
|
|
1231
|
+
let defaultDenyId;
|
|
1113
1232
|
const advisoryKey = (scan) => {
|
|
1114
1233
|
if (typeof listFiles !== "function") return null;
|
|
1115
1234
|
const dir = typeof scan.cwd === "string" && scan.cwd !== "" ? scan.cwd : ".";
|
|
@@ -1137,10 +1256,105 @@ export function buildCacheDigest({ objectId, headTree, rustUnits = [], npmUnits
|
|
|
1137
1256
|
if (idOf(lock) === null || idOf(lock) === undefined) return null;
|
|
1138
1257
|
const ancestors = ancestorDirsOf(dir);
|
|
1139
1258
|
const config = [dir, ...ancestors].flatMap((d) => [".cargo", "deny.toml", "audit.toml", "rust-toolchain", "rust-toolchain.toml"].map((f) => inWs(d, f)));
|
|
1140
|
-
|
|
1141
|
-
|
|
1259
|
+
// NN04: the manifests this workspace reads, not every Cargo.toml of the commit: those under its directory and those its path dependencies reach,
|
|
1260
|
+
// followed to a fixed point (a crate outside the workspace that it depends on still counts). A manifest edit in another workspace kept rerunning
|
|
1261
|
+
// 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).
|
|
1262
|
+
const manifests = cargoManifestsOfWorkspace({ dir, all, readBlob });
|
|
1263
|
+
const kind = scan.id.startsWith("cargo-deny") ? "cargo-deny" : "cargo-audit";
|
|
1264
|
+
const inputs = idsOf([lock, ...manifests, ...config]);
|
|
1265
|
+
if (kind === "cargo-deny") {
|
|
1266
|
+
const policy = inWs(dir, "deny.toml");
|
|
1267
|
+
if (!all.includes(policy)) {
|
|
1268
|
+
if (idOf(policy) != null) throw new Error(policy + ": expected a policy file");
|
|
1269
|
+
defaultDenyId ??= createHash("sha256").update(fs.readFileSync(new URL("../deny-default.toml", import.meta.url))).digest("hex");
|
|
1270
|
+
inputs.push(["@rightkit/release/deny-default.toml", defaultDenyId]);
|
|
1271
|
+
} else {
|
|
1272
|
+
const contents = readBlob?.(policy);
|
|
1273
|
+
if (typeof contents !== "string") throw new Error(policy + ": cannot read the workspace policy");
|
|
1274
|
+
inputs.push(["workspace deny policy bytes", createHash("sha256").update(contents).digest("hex")]);
|
|
1275
|
+
}
|
|
1276
|
+
}
|
|
1277
|
+
return canonicalJson({ kind, id: scan.id, day: today(), pin: scan.advisoryPin ?? null, inputs });
|
|
1278
|
+
};
|
|
1279
|
+
const boundShellcheckFiles = (scan) => {
|
|
1280
|
+
const [format, sources, ...entries] = scan.args ?? [];
|
|
1281
|
+
if (scan.root !== "content" || scan.cwd || format !== "--format=gcc" || sources !== "--external-sources" || !entries.length)
|
|
1282
|
+
throw new Error("unsupported ShellCheck command");
|
|
1283
|
+
const env = Object.fromEntries(Object.entries({ ...shellcheckEnv, ...scan.env }).map(([k, v]) => [k.toUpperCase(), v]));
|
|
1284
|
+
if (String(env.SHELLCHECK_OPTS ?? "").trim()) throw new Error("SHELLCHECK_OPTS can add inputs outside the planned command");
|
|
1285
|
+
const root = fs.realpathSync.native(shellcheckRoot);
|
|
1286
|
+
const tracked = new Set(listFiles("."));
|
|
1287
|
+
const inputs = new Set();
|
|
1288
|
+
const present = (file) => {
|
|
1289
|
+
try { fs.lstatSync(file); return true; }
|
|
1290
|
+
catch (error) { if (error.code === "ENOENT" || error.code === "ENOTDIR") return false; throw error; }
|
|
1291
|
+
};
|
|
1292
|
+
const readInput = (relative) => {
|
|
1293
|
+
if (!plainRelative(relative) || relative.startsWith("-") || !tracked.has(relative) || idOf(relative) == null)
|
|
1294
|
+
throw new Error(relative + ": ShellCheck input is outside the tracked file set");
|
|
1295
|
+
const file = path.join(root, relative);
|
|
1296
|
+
if (!fs.lstatSync(file).isFile() || path.relative(file, fs.realpathSync.native(file)))
|
|
1297
|
+
throw new Error(relative + ": ShellCheck input is a link or special file");
|
|
1298
|
+
const content = readBlob(relative);
|
|
1299
|
+
if (typeof content !== "string") throw new Error(relative + ": unreadable ShellCheck input");
|
|
1300
|
+
inputs.add(relative);
|
|
1301
|
+
return content.split(/\r\n|[\r\n]/).map((line) => line.trim());
|
|
1302
|
+
};
|
|
1303
|
+
const safeDirective = /^(?:(?:disable|enable|shell|extended-analysis|external-sources)=[\w,-]+[ \t]*)+$/;
|
|
1304
|
+
const checkedRc = new Set();
|
|
1305
|
+
let checkedHostRc = false;
|
|
1306
|
+
const checkHostRc = () => {
|
|
1307
|
+
if (checkedHostRc) return;
|
|
1308
|
+
const candidates = [];
|
|
1309
|
+
for (let dir = root; path.dirname(dir) !== dir;) {
|
|
1310
|
+
dir = path.dirname(dir);
|
|
1311
|
+
candidates.push(path.join(dir, ".shellcheckrc"), path.join(dir, "shellcheckrc"));
|
|
1312
|
+
}
|
|
1313
|
+
for (const home of new Set([env.HOME, env.USERPROFILE, os.homedir()].filter(Boolean))) {
|
|
1314
|
+
candidates.push(path.resolve(root, home, ".shellcheckrc"), path.resolve(root, home, ".config", "shellcheckrc"));
|
|
1315
|
+
if (process.platform === "win32") candidates.push(path.resolve(root, home, "AppData", "Roaming", "shellcheckrc"));
|
|
1316
|
+
}
|
|
1317
|
+
if (env.APPDATA) candidates.push(path.resolve(root, env.APPDATA, "shellcheckrc"));
|
|
1318
|
+
if (env.XDG_CONFIG_HOME) candidates.push(path.resolve(root, env.XDG_CONFIG_HOME, "shellcheckrc"));
|
|
1319
|
+
const external = candidates.find(present);
|
|
1320
|
+
if (external) throw new Error(external + ": ShellCheck configuration comes from outside tracked content");
|
|
1321
|
+
checkedHostRc = true;
|
|
1322
|
+
};
|
|
1323
|
+
for (const entry of entries) {
|
|
1324
|
+
if (!plainRelative(entry)) throw new Error("unsupported ShellCheck entry path");
|
|
1325
|
+
const candidates = ancestorDirsOf(path.posix.dirname(entry)).reverse().flatMap((d) => [inWs(d, ".shellcheckrc"), inWs(d, "shellcheckrc")]);
|
|
1326
|
+
const rc = candidates.find((f) => tracked.has(f) || present(path.join(root, f)));
|
|
1327
|
+
if (!rc) checkHostRc();
|
|
1328
|
+
else if (!checkedRc.has(rc)) {
|
|
1329
|
+
for (const [i, line] of readInput(rc).entries()) {
|
|
1330
|
+
if (line && !line.startsWith("#") && !safeDirective.test(line)) throw new Error(rc + ":" + (i + 1) + ": unsupported ShellCheck configuration");
|
|
1331
|
+
}
|
|
1332
|
+
checkedRc.add(rc);
|
|
1333
|
+
}
|
|
1334
|
+
}
|
|
1335
|
+
// Prove only complete, simple lines. Compound commands, substitutions and other
|
|
1336
|
+
// source-resolution mechanisms are left to the real tool and receive no reusable key.
|
|
1337
|
+
const safeWord = String.raw`(?:[-\w./:@%+,]+|'[^']*'|"[^"\\$\x60]*")`;
|
|
1338
|
+
const safeLine = new RegExp(String.raw`^(?:(?:set|printf|echo|cd|exit|return|true|false|:)(?:[ \t]+${safeWord})*|[a-zA-Z_]\w*=${safeWord})$`);
|
|
1339
|
+
const literalSource = /^(?:source|\.)[ \t]+(?:"([\w./@+-]+)"|'([\w./@+-]+)'|([\w./@+-]+))$/;
|
|
1340
|
+
const queue = [...entries]; const visited = new Set(queue);
|
|
1341
|
+
for (const file of queue) {
|
|
1342
|
+
for (const [i, line] of readInput(file).entries()) {
|
|
1343
|
+
const annotation = /^#[ \t\u00a0]*shellcheck(?:[ \t\u00a0]+(.*))?$/.exec(line);
|
|
1344
|
+
if (!line || (line.startsWith("#") && !line.endsWith("\\") && (!annotation || safeDirective.test(annotation[1] ?? ""))) || safeLine.test(line)) continue;
|
|
1345
|
+
const source = literalSource.exec(line);
|
|
1346
|
+
const literal = source?.[1] ?? source?.[2] ?? source?.[3];
|
|
1347
|
+
if (literal === "/dev/null") continue;
|
|
1348
|
+
const relative = literal && path.posix.normalize(literal);
|
|
1349
|
+
if (!plainRelative(relative) || literal.startsWith("-") || literal.split("/").includes("..") || !tracked.has(relative))
|
|
1350
|
+
throw new Error(file + ":" + (i + 1) + ": ShellCheck read set is unproven" + (literal ? " for source " + literal : ""));
|
|
1351
|
+
if (!visited.has(relative)) { visited.add(relative); queue.push(relative); }
|
|
1352
|
+
}
|
|
1353
|
+
}
|
|
1354
|
+
return [...inputs];
|
|
1142
1355
|
};
|
|
1143
1356
|
const fileList = (scan) => {
|
|
1357
|
+
if (scan.id === "shellcheck" && shellcheckRoot) return boundShellcheckFiles(scan);
|
|
1144
1358
|
if (Array.isArray(scan.files) && scan.files.length) return scan.files;
|
|
1145
1359
|
const args = Array.isArray(scan.args) ? scan.args : [];
|
|
1146
1360
|
if (/^rustfmt:/.test(scan.id)) {
|
|
@@ -1187,7 +1401,11 @@ export function buildCacheDigest({ objectId, headTree, rustUnits = [], npmUnits
|
|
|
1187
1401
|
if (liveScan(scan.id) && !ADVISORY_SCAN.test(scan.id)) return null;
|
|
1188
1402
|
try {
|
|
1189
1403
|
if (ADVISORY_SCAN.test(scan.id)) return advisoryKey(scan);
|
|
1190
|
-
|
|
1404
|
+
let files;
|
|
1405
|
+
if (scan.id === "shellcheck" && shellcheckRoot) {
|
|
1406
|
+
try { files = fileList(scan); }
|
|
1407
|
+
catch (error) { onUncacheable?.(scan, error.message); return null; }
|
|
1408
|
+
} else files = fileList(scan);
|
|
1191
1409
|
// 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
1410
|
// release reran 423 node-check rows). Any other read of the manifest, or an unreadable one, keys on its whole content as before.
|
|
1193
1411
|
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 +1670,7 @@ async function installHook(o, root) {
|
|
|
1452
1670
|
* apps/coderight-tauri), else the repository root. Every right-release stage runs there, the sealed set is read from there, and the
|
|
1453
1671
|
* receipt is keyed to it (receiptKey). Returns { appRoot, appDir } with appDir relative to the repository root, "." at the root.
|
|
1454
1672
|
*/
|
|
1455
|
-
export function appRootOf({ root, cwd, exists = fs.existsSync, configDirs = null, platform = process.platform }) {
|
|
1673
|
+
export function appRootOf({ root, cwd, exists = fs.existsSync, configDirs = null, platform = process.platform, soleNestedApp = false }) {
|
|
1456
1674
|
// 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
1675
|
// 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
1676
|
// A sibling sharing a prefix (D:\a\bc against root D:\a\b) is outside: relative() answers "..\bc", never a prefix match.
|
|
@@ -1475,6 +1693,14 @@ export function appRootOf({ root, cwd, exists = fs.existsSync, configDirs = null
|
|
|
1475
1693
|
const segments = rel.split(p.sep).filter(Boolean);
|
|
1476
1694
|
for (let n = segments.length; n > 0; n--) { const found = configDirAt(segments.slice(0, n).join("/")); if (found) { appDir = found; break; } }
|
|
1477
1695
|
}
|
|
1696
|
+
// Dev/test/render hand ONE app to right-release. Run from the root of a repository whose selected commit holds no root
|
|
1697
|
+
// config and exactly one nested app, that app is unambiguous (the witness fixture's app/; "--to test" from its root
|
|
1698
|
+
// refused "no right-release.config at <commit>"). Several nested apps stay ambiguous and the root answer stands, so the
|
|
1699
|
+
// stage refuses naming the missing config instead of guessing. Other stages never take this: their scope stays the cwd's.
|
|
1700
|
+
if (soleNestedApp && committed && inside && rel === "" && appDir === "." && !committed.has(fold("."))) {
|
|
1701
|
+
const dirs = [...committed.values()];
|
|
1702
|
+
if (dirs.length === 1) appDir = dirs[0];
|
|
1703
|
+
}
|
|
1478
1704
|
return { appRoot: appDir === "." ? rootAbs : p.join(rootAbs, ...appDir.split("/")), appDir };
|
|
1479
1705
|
}
|
|
1480
1706
|
|
|
@@ -1615,7 +1841,7 @@ export function changedPathsAt({ git, base, commit }) {
|
|
|
1615
1841
|
* (with `--receipt-dir`) plus one aggregate report. Returns the exit the door run ends with: 0 only when every
|
|
1616
1842
|
* selected unit passed, else the first failing unit's code (1 when only blocked units failed the run).
|
|
1617
1843
|
*/
|
|
1618
|
-
export async function runSharedUnitList({ o, io, stage, commit, selected, inventory, receiptDir = undefined, base = null, unmatched = [], runUnit = null }) {
|
|
1844
|
+
export async function runSharedUnitList({ o, io, stage, commit, selected, inventory, receiptDir = undefined, base = null, unmatched = [], runUnit = null, root = null }) {
|
|
1619
1845
|
const tag = "rightkit-gate:";
|
|
1620
1846
|
const bySelector = new Map((inventory?.units ?? []).map((u) => [u.selector, u]));
|
|
1621
1847
|
const rows = selected.map((s) => ({ dir: unitDirOfSelector(s.selector), reason: "listed", ...bySelector.get(s.selector), ...s }));
|
|
@@ -1655,12 +1881,9 @@ export async function runSharedUnitList({ o, io, stage, commit, selected, invent
|
|
|
1655
1881
|
const internal = union.internal.filter((r) => r.selector === unit.selector);
|
|
1656
1882
|
const expected = union.expected?.get(unit.selector);
|
|
1657
1883
|
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
1884
|
// 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 } : {}) };
|
|
1885
|
+
// a lookup's coverage was reported as 132 passed after "scheduleClassB: invalid projection"). The word and its reason: affected-units.mjs.
|
|
1886
|
+
return { selector: unit.selector, ...classifyUnitRows({ rows: all, expected, exit, verified: union.verified }) };
|
|
1664
1887
|
});
|
|
1665
1888
|
const report = unitListReport({ commit, stage, base, selected: ordered, results, unmatched }); report.runId = union.runId;
|
|
1666
1889
|
for (const row of report.units) {
|
|
@@ -1671,17 +1894,31 @@ export async function runSharedUnitList({ o, io, stage, commit, selected, invent
|
|
|
1671
1894
|
const data = `${JSON.stringify(evidence, null, 2)}\n`; o.writeFile(path.join(receiptDir, name), data);
|
|
1672
1895
|
row.receipt = { status: "written", file: name, sha256: createHash("sha256").update(data).digest("hex") };
|
|
1673
1896
|
}
|
|
1674
|
-
o.out(`${tag} unit ${row.selector}: ${row.status}`);
|
|
1897
|
+
o.out(`${tag} unit ${row.selector}: ${row.status}${row.ownRows === "all-passed" ? " (its own rows all passed; the run did not)" : ""}`);
|
|
1675
1898
|
}
|
|
1676
|
-
|
|
1899
|
+
const onlyRunCount = report.units.filter((u) => u.ownRows === "all-passed").length;
|
|
1900
|
+
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
1901
|
if (receiptDir !== undefined) o.writeFile(path.join(receiptDir, "units-report.json"), `${JSON.stringify(report, null, 2)}\n`);
|
|
1678
1902
|
return report.ok ? 0 : (exit || 1);
|
|
1679
1903
|
}
|
|
1680
|
-
|
|
1904
|
+
// 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
|
|
1905
|
+
// 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
|
|
1906
|
+
// (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
|
|
1907
|
+
// proof as a door's.
|
|
1908
|
+
let listLock = null;
|
|
1909
|
+
if (!runUnit && !io.runUnitForList && !io.unitListLock && root && o.env.GITHUB_ACTIONS !== "true") {
|
|
1910
|
+
const snap = await import("../snapshot.mjs");
|
|
1911
|
+
const snapshotsAt = o.snapshotRoot ?? snap.snapshotRoot({ platform: o.platform, env: o.env });
|
|
1912
|
+
const taken = takeRunLock({ o, checkout: root, snapshotsAt, commit, snap, tag });
|
|
1913
|
+
if (taken.exit !== undefined) return taken.exit;
|
|
1914
|
+
listLock = { ...taken, started: false };
|
|
1915
|
+
}
|
|
1916
|
+
const run = runUnit ?? io.runUnitForList ?? (async (selector, receipt) => main(["--to", stage, "--unit", selector, "--commit", commit, ...receipt], { ...io, unitListClassA, ...(listLock ? { unitListLock: listLock } : {}) }));
|
|
1681
1917
|
const outcomes = new Map();
|
|
1682
1918
|
const receiptEvidence = new Map();
|
|
1683
1919
|
const runId = randomUUID();
|
|
1684
1920
|
const bad = new Set(); // failed or blocked selectors, for the dependency check of later units
|
|
1921
|
+
try {
|
|
1685
1922
|
for (const [i, row] of ordered.entries()) {
|
|
1686
1923
|
const blocker = (bySelector.get(row.selector)?.deps ?? []).find((d) => bad.has(d));
|
|
1687
1924
|
if (blocker) {
|
|
@@ -1705,6 +1942,7 @@ export async function runSharedUnitList({ o, io, stage, commit, selected, invent
|
|
|
1705
1942
|
outcomes.set(row.selector, { ran: true, code });
|
|
1706
1943
|
if (code !== 0) bad.add(row.selector);
|
|
1707
1944
|
}
|
|
1945
|
+
} finally { if (listLock) releaseSeamLock({ o, release: listLock.release, seamBody: listLock.started ? listLock.body : null, tag }); }
|
|
1708
1946
|
const results = classifyUnitResults({ selected: ordered, inventory: inventory ?? { units: rows }, outcomes });
|
|
1709
1947
|
const report = unitListReport({ commit, stage, base, selected: ordered, results, unmatched });
|
|
1710
1948
|
report.runId = runId;
|
|
@@ -1766,7 +2004,7 @@ export async function rightkitDoorRule(o, args, root, git, io, { unitsFileFlag,
|
|
|
1766
2004
|
const unknown = unitList.filter((selector) => !inventory.units.some((u) => u.selector === selector));
|
|
1767
2005
|
if (unknown.length) { o.err(`${tag} BLOCKED: units missing from inventory: ${unknown.join(", ")}; nothing ran`); return { exit: 2 }; }
|
|
1768
2006
|
const selected = unitList.map((selector) => ({ selector, reason: "listed" }));
|
|
1769
|
-
return { exit: await runSharedUnitList({ o, io, stage, commit: pinned.commit, selected, inventory, receiptDir }) };
|
|
2007
|
+
return { exit: await runSharedUnitList({ o, io, stage, commit: pinned.commit, selected, inventory, receiptDir, root }) };
|
|
1770
2008
|
}
|
|
1771
2009
|
// --changed (rightkit#1505): no handwritten list for routine work. Changed paths against the base select their
|
|
1772
2010
|
// units plus every transitive dependent (affected-units.mjs); the plan is printed before anything runs.
|
|
@@ -1788,7 +2026,7 @@ export async function rightkitDoorRule(o, args, root, git, io, { unitsFileFlag,
|
|
|
1788
2026
|
o.out(`${tag} unit report: 0 passed, 0 failed, 0 blocked, 0 not-run of 0 on ${pinned.commit.slice(0, 12)}`);
|
|
1789
2027
|
return { exit: 0 };
|
|
1790
2028
|
}
|
|
1791
|
-
return { exit: await runSharedUnitList({ o, io, stage, commit: pinned.commit, selected: selection.selected, inventory, receiptDir, base, unmatched: selection.unmatched }) };
|
|
2029
|
+
return { exit: await runSharedUnitList({ o, io, stage, commit: pinned.commit, selected: selection.selected, inventory, receiptDir, base, unmatched: selection.unmatched, root }) };
|
|
1792
2030
|
}
|
|
1793
2031
|
if (allUnitsFlag) {
|
|
1794
2032
|
const id = option("--all-units-exception");
|
|
@@ -1855,7 +2093,7 @@ async function runStages(o, args, root, git, io) {
|
|
|
1855
2093
|
const scopeCommit = o.doorSnapshot ? o.doorSnapshot.commit : selected ? selected.commit : text(git("rev-parse", "HEAD")).trim();
|
|
1856
2094
|
const inventory = committedConfigDirs({ git, commit: scopeCommit });
|
|
1857
2095
|
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 });
|
|
2096
|
+
const { appRoot, appDir } = appRootOf({ root, cwd: o.cwd, configDirs: inventory.dirs, soleNestedApp: devTest });
|
|
1859
2097
|
// `--route`: which route this stage takes here and whether it refuses, answered without running anything (rightkit#1297).
|
|
1860
2098
|
if (o.routeProbe) return await runRouteProbe(o, args, root, git, { to, platform, stages: devTest ? [] : stages, devTest, appDir });
|
|
1861
2099
|
// 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 +2134,7 @@ async function runStages(o, args, root, git, io) {
|
|
|
1896
2134
|
let synced;
|
|
1897
2135
|
try { synced = (o.syncSnapshot ?? snap.syncSnapshot)({ checkout: root, rev: selected.commit, root: snapshotsAt, lock: { held: taken.view } }); }
|
|
1898
2136
|
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})`);
|
|
2137
|
+
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
2138
|
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
2139
|
started = true;
|
|
1902
2140
|
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 +2160,14 @@ async function runStages(o, args, root, git, io) {
|
|
|
1922
2160
|
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
2161
|
const executor = (o.resolveExecutor ?? gateResolveExecutor)({ env: o.env, platform: o.platform, exists: o.exists, which, readFile: o.readFile }); applyExecutorEnv(o, executor);
|
|
1924
2162
|
if (executor.kind === "refuse") { o.err(`${tag} BLOCKED: ${executor.problem}`); return 1; }
|
|
1925
|
-
|
|
2163
|
+
// 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.
|
|
2164
|
+
const versionStore = (() => { try { return path.join(gateRunsRoot({ env: o.env, platform: o.platform }), "tool-versions.json"); } catch { return null; } })();
|
|
2165
|
+
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]; } });
|
|
2166
|
+
// 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
|
|
2167
|
+
// the files that decide which pnpm runs in this directory are unchanged (pnpmVersionAnswer; NN25: `pnpm --version` on every warm run).
|
|
2168
|
+
const version = (cmd, a) => (cmd === "pnpm" && a.length === 1 && a[0] === "--version"
|
|
2169
|
+
? pnpmVersionAnswer({ cwd: root, env: o.env, remember: o.spawn === defaultSpawn, run: () => versionAsked(cmd, a) })
|
|
2170
|
+
: versionAsked(cmd, a));
|
|
1926
2171
|
const listed = git("ls-tree", "-r", "--name-only", "-z", commit);
|
|
1927
2172
|
const lockFiles = {};
|
|
1928
2173
|
for (const f of failed(listed) ? [] : text(listed).split("\0").filter((x) => /(^|\/)(Cargo\.lock|pnpm-lock\.yaml)$/.test(x))) {
|
|
@@ -1930,7 +2175,7 @@ async function runStages(o, args, root, git, io) {
|
|
|
1930
2175
|
}
|
|
1931
2176
|
const binding = bindingOf({
|
|
1932
2177
|
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"]) },
|
|
2178
|
+
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
2179
|
});
|
|
1935
2180
|
// Release writes to R2. The write credential lives only in the trusted publisher: a GitHub Actions job in the protected
|
|
1936
2181
|
// publication environment, which sets RIGHTKIT_PUBLISHER=github-environment. Hosts and agents never hold it, so the door refuses the
|
|
@@ -2114,12 +2359,14 @@ async function runStages(o, args, root, git, io) {
|
|
|
2114
2359
|
if (ds.carriedOutputs?.size) ok = await admissionDryRun("after the sidecars were staged, before the app compiles");
|
|
2115
2360
|
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
2361
|
}
|
|
2117
|
-
let compiledDirs = []; let compiledBins = null; let qualifyOwed = [];
|
|
2362
|
+
let compiledDirs = []; let compiledBins = null; let qualifyOwed = []; let limitedEvidence = [];
|
|
2118
2363
|
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;
|
|
2364
|
+
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
2365
|
if (directReceipt) extra = { ...extra, direct: directReceipt };
|
|
2121
2366
|
// 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
2367
|
if (qualifyOwed.length) extra = { ...extra, qualifyOwed };
|
|
2368
|
+
// Cross-target rows type-check against stand-ins and never link: listed as limited evidence so no qualification can cite them (GC-A14, NN38).
|
|
2369
|
+
if (limitedEvidence.length) extra = { ...extra, limitedEvidence };
|
|
2123
2370
|
// What this compile produced, recorded with its result so a later run can prove the outputs are still there (GB-13).
|
|
2124
2371
|
if (ok) extra = { ...extra, outputs: compileOutputsRecord({ dirs: compiledDirs, env: o.env, builtBins: compiledBins }) };
|
|
2125
2372
|
// The cross-check with `.rightkit/compile-inputs.json`: a declared input that covers ledger entries must carry the digest of those
|
|
@@ -3062,7 +3309,9 @@ async function runUnitSnapshot(o, args, root, git, io, option) {
|
|
|
3062
3309
|
const snapshotsAt = o.snapshotRoot ?? snap.snapshotRoot({ platform: o.platform, env: o.env });
|
|
3063
3310
|
{ const mismatch = await declaredSnapshotRootRefusal(o, executor, snapshotsAt); if (mismatch) { o.err(`${tag} BLOCKED: ${mismatch.code}: ${mismatch.message}; nothing ran`); return 1; } }
|
|
3064
3311
|
// 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
|
-
|
|
3312
|
+
// 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
|
|
3313
|
+
// process would be refused as busy. Every other unit run takes its own.
|
|
3314
|
+
const taken = io.unitListLock ?? takeRunLock({ o, checkout: root, snapshotsAt, commit, snap, tag });
|
|
3066
3315
|
if (taken.exit !== undefined) return taken.exit;
|
|
3067
3316
|
let started = false;
|
|
3068
3317
|
try {
|
|
@@ -3070,7 +3319,7 @@ async function runUnitSnapshot(o, args, root, git, io, option) {
|
|
|
3070
3319
|
try { synced = (o.syncSnapshot ?? snap.syncSnapshot)({ checkout: root, rev: commit, root: snapshotsAt, lock: { held: taken.view } }); }
|
|
3071
3320
|
catch (e) { o.err(`${tag} ${e.code === "error" ? "RK_CHECK_ERROR" : "BLOCKED"}: snapshot ${e.message}; nothing ran`); return e.code === "error" ? 2 : 1; }
|
|
3072
3321
|
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})`);
|
|
3322
|
+
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
3323
|
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
3324
|
const ds = { lock: taken.view, path: synced.path, commit: synced.commit, tree: synced.tree, root: snapshotsAt, ledger: { entries: [] } };
|
|
3076
3325
|
if (io[UNIT_LIST_UNION]) return await runUnionSnapshot({ o, io, root, git, ds, union: io[UNIT_LIST_UNION], unitListClassA: io.unitListClassA });
|
|
@@ -3165,7 +3414,9 @@ async function runUnitSnapshot(o, args, root, git, io, option) {
|
|
|
3165
3414
|
});
|
|
3166
3415
|
} finally { bound.cleanup(); }
|
|
3167
3416
|
} finally {
|
|
3168
|
-
|
|
3417
|
+
// 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.
|
|
3418
|
+
if (io.unitListLock) { if (started) io.unitListLock.started = true; }
|
|
3419
|
+
else releaseSeamLock({ o, release: taken.release, seamBody: started ? taken.body : null, tag });
|
|
3169
3420
|
}
|
|
3170
3421
|
}
|
|
3171
3422
|
|
|
@@ -3202,12 +3453,12 @@ async function runUnionSnapshot({ o, io, root, git, ds, union, unitListClassA })
|
|
|
3202
3453
|
if (!await openSnapshotStage({ o, ds, root, stage: "compile", tag })) return 1;
|
|
3203
3454
|
let code = 1;
|
|
3204
3455
|
// Crates build together (docs/design/2026-11-10-gate-fresh-design.md; Adrian, 2026-11-04: "RK has to build all it's necessary crates together"): a list of crates on a
|
|
3205
|
-
// broker host is compiled by gate/compile.mjs as a few Cargo calls naming every crate, each crate with its own result.
|
|
3206
|
-
//
|
|
3456
|
+
// broker host is compiled by gate/compile.mjs as a few Cargo calls naming every crate, each crate with its own result. No switch selects the per-crate rows
|
|
3457
|
+
// (the RK_GATE_LEGACY_ROWS switch was removed 2026-11-24, rightkit#1514: compiles are combined, GC-A27 NN09).
|
|
3207
3458
|
let together = null;
|
|
3208
3459
|
try {
|
|
3209
3460
|
const ex = (o.resolveExecutor ?? gateResolveExecutor)({ env: o.env, platform: o.platform, exists: o.exists, which: whichIn(o), readFile: o.readFile });
|
|
3210
|
-
if (
|
|
3461
|
+
if (ex?.kind === "broker" && union.selected.every((row) => row.selector.startsWith("cargo:"))) together = { client: brokerClientOf(o, ex) };
|
|
3211
3462
|
} catch { together = null; }
|
|
3212
3463
|
if (together) {
|
|
3213
3464
|
try {
|
|
@@ -3729,6 +3980,13 @@ async function runDevTest(o, args, root, git, io, to, appRoot, appDir) {
|
|
|
3729
3980
|
const tree = ds ? ds.tree : text(git("rev-parse", "HEAD^{tree}")).trim();
|
|
3730
3981
|
const common = text(git("rev-parse", "--git-common-dir")).trim();
|
|
3731
3982
|
if (!/^[0-9a-f]{40}$/.test(commit) || !common) { o.err(`${tag} cannot read HEAD and the git directory`); return 2; }
|
|
3983
|
+
// `--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
|
|
3984
|
+
// 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.
|
|
3985
|
+
{ const at = (f) => (appDir === "." ? f : `${appDir}/${f}`);
|
|
3986
|
+
if (!["right-release.config.json", "right-release.config.mjs"].some((f) => !failed(git("cat-file", "-e", `${commit}:${at(f)}`)))) {
|
|
3987
|
+
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).`);
|
|
3988
|
+
return 2;
|
|
3989
|
+
} }
|
|
3732
3990
|
// Hosted CI's runner checkout is the commit; anywhere else the snapshot is, and the checkout may hold anything.
|
|
3733
3991
|
if (!ds) {
|
|
3734
3992
|
const dirty = git("status", "--porcelain", "--untracked-files=no");
|
|
@@ -3868,6 +4126,32 @@ export function stageArgsProblem(args) {
|
|
|
3868
4126
|
return null;
|
|
3869
4127
|
}
|
|
3870
4128
|
|
|
4129
|
+
/**
|
|
4130
|
+
* 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
|
|
4131
|
+
* 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
|
|
4132
|
+
* list, `snapshotDir` its snapshot, `label` the name printed for an app at the repository root. RightKit's own repository gives none: it is
|
|
4133
|
+
* judged per unit. No lines means the rule holds. Exported for its test.
|
|
4134
|
+
*/
|
|
4135
|
+
export async function cargoProfileRuleLines({ tracked, snapshotDir, label }) {
|
|
4136
|
+
let rightkitRepo = false;
|
|
4137
|
+
if (tracked.includes(RIGHTKIT_IDENTITY_FILE)) { try { rightkitRepo = isRightKitIdentity(fs.readFileSync(path.join(snapshotDir, ...RIGHTKIT_IDENTITY_FILE.split("/")), "utf8")); } catch { rightkitRepo = false; } }
|
|
4138
|
+
if (rightkitRepo) return [];
|
|
4139
|
+
const appRoots = [...new Set(tracked.filter((f) => /(^|\/)right-release\.config\.(json|mjs)$/.test(f)).map((f) => path.posix.dirname(f)))].sort();
|
|
4140
|
+
const { scanCargoProfileContract, formatCargoProfileFindings } = await import("../cargo-profile-contract.mjs");
|
|
4141
|
+
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));
|
|
4142
|
+
}
|
|
4143
|
+
|
|
4144
|
+
/**
|
|
4145
|
+
* 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
|
|
4146
|
+
* (snapshot-metadata.mjs cargoWorkspaceTopology) refuses any discovery input reached through a link, and an agent profile's `.cargo` is a
|
|
4147
|
+
* 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.
|
|
4148
|
+
*/
|
|
4149
|
+
export function cargoHomeOf(env, { realpath = fs.realpathSync, homedir = os.homedir } = {}) {
|
|
4150
|
+
let home = env.CARGO_HOME || path.join(env.USERPROFILE || env.HOME || homedir(), ".cargo");
|
|
4151
|
+
try { home = realpath(home); } catch { /* absent: as spelled */ }
|
|
4152
|
+
return home;
|
|
4153
|
+
}
|
|
4154
|
+
|
|
3871
4155
|
export async function main(argv, io = {}) {
|
|
3872
4156
|
const o = {
|
|
3873
4157
|
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 +4260,7 @@ export async function main(argv, io = {}) {
|
|
|
3976
4260
|
let synced;
|
|
3977
4261
|
try { synced = (o.syncSnapshot ?? snap.syncSnapshot)({ checkout, rev: selected.commit, root: snapshotsAt, lock: { held: view } }); }
|
|
3978
4262
|
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})`);
|
|
4263
|
+
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
4264
|
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
4265
|
const next = [...argv]; const ci = next.indexOf("--commit");
|
|
3982
4266
|
if (ci >= 0) next.splice(ci, 2, "--commit", synced.commit); else next.push("--commit", synced.commit);
|
|
@@ -4041,11 +4325,37 @@ export async function main(argv, io = {}) {
|
|
|
4041
4325
|
const appArgs = stripSnapshot(withoutScope.filter((a) => a !== "--full-a"));
|
|
4042
4326
|
if (fullAdmission && !appArgs.includes("--rule-tier")) appArgs.push("--rule-tier", requestedTier);
|
|
4043
4327
|
// GC-A24: a passing app-rule verdict of a snapshot is reused for the same commit tree, rule code, tier and arguments (ruleVerdictCache).
|
|
4328
|
+
let history;
|
|
4329
|
+
if (fullAdmission && snapshotDir && !o.runScans && o.classA !== false) {
|
|
4330
|
+
try {
|
|
4331
|
+
// NN25: no git starts after the resident proof. The snapshot sync already resolved this checkout's repository
|
|
4332
|
+
// (snapshot.mjs repositoryOf -> snapshot-git.mjs sealedRepoInfo, cached per canonical path in this process), so the
|
|
4333
|
+
// common dir is read from that cache, never asked again. An injected spawn (tests) is asked as before.
|
|
4334
|
+
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(); })();
|
|
4335
|
+
// The store has one fixed place per repository; no caller moves it (Adrian, 2026-11-24, rightkit#1514).
|
|
4336
|
+
const storeDir = path.join(commonDir, "rightkit-gate-cache");
|
|
4337
|
+
history = openClassAHistory({ historyRoot: path.join(gateRunsRoot({ env: o.env, platform: o.platform }), "rightkit-class-a-history"), storeDir, onRestart: cacheRestartNote(o) });
|
|
4338
|
+
} catch (error) { o.err(`rightkit-gate: BLOCKED: ${error.message}`); return 1; }
|
|
4339
|
+
}
|
|
4044
4340
|
const ruleCache = snapshotDir && snapshotCommit && !args.includes("--worktree") && !o.appCheck ? ruleVerdictCache({ checkout: snapshotCheckout, spawn: o.spawn }) : null;
|
|
4045
4341
|
const appKey = ruleCache ? ruleCache.key({ rule: "app-check", tree: snapshotCommit.tree, args: appArgs, gate: gatePackageIdentity(o.gatePackage) }) : null;
|
|
4046
|
-
const
|
|
4342
|
+
const appCached = Boolean(appKey && ruleCache.passed(appKey));
|
|
4343
|
+
let appCheck = appCached
|
|
4047
4344
|
? (o.out(`check: ${snapshotCommit.commit.slice(0, 12)} app rules: cached pass (tree ${snapshotCommit.tree.slice(0, 12)})`), 0)
|
|
4048
4345
|
: 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 } : {}) });
|
|
4346
|
+
// 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
|
|
4347
|
+
// tool (release.mjs cargo-profile-contract), so a commit that adds [profile.dev] to an app passed check and compile (contract test N15, failed
|
|
4348
|
+
// 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
|
|
4349
|
+
// roots, same exemptions), for every app root the commit tracks (a right-release.config), and its verdict is cached with theirs per tree.
|
|
4350
|
+
// RightKit itself is judged per unit (rightkitDoorRule) and is not an app repository: its e2e-app keeps a [profile.dev] for its own harness.
|
|
4351
|
+
if (!appCached && appCheck === 0 && fullAdmission && snapshotDir && snapshotCommit && !o.appCheck) {
|
|
4352
|
+
try {
|
|
4353
|
+
const listed = o.spawn("git", ["ls-tree", "-r", "--name-only", "-z", snapshotCommit.commit], { cwd: snapshotCheckout });
|
|
4354
|
+
if (failed(listed)) throw new Error(`cannot list commit ${snapshotCommit.commit}`);
|
|
4355
|
+
const lines = await cargoProfileRuleLines({ tracked: text(listed).split("\0").filter(Boolean), snapshotDir, label: path.basename(snapshotCheckout) });
|
|
4356
|
+
if (lines.length) { for (const line of lines) o.err(`check: ${line}`); appCheck = 1; }
|
|
4357
|
+
} catch (error) { o.err(`rightkit-gate: BLOCKED: the Cargo profile rule (GC-A15) could not be judged: ${error.message}`); return 1; }
|
|
4358
|
+
}
|
|
4049
4359
|
if (appKey && appCheck === 0) ruleCache.pass(appKey);
|
|
4050
4360
|
if (args.includes("--list") || args.includes("--print-baseline") || args.includes("--only") || o.classA === false) {
|
|
4051
4361
|
// 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 +4372,13 @@ export async function main(argv, io = {}) {
|
|
|
4062
4372
|
const checkCwd = repoArg ? path.resolve(o.cwd, repoArg) : o.cwd;
|
|
4063
4373
|
// The app rules' tier is the stage's (rightkit#1296); class A's deterministic scans are the same at either tier.
|
|
4064
4374
|
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 });
|
|
4375
|
+
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
4376
|
// RightKit checking itself: its own rules (line endings, consumer recipes, npm surface, version copies and the version feed, dispatcher
|
|
4067
4377
|
// pins, consumer locks, generated docs, temp paths: scripts/preflight.mjs) and its exports' import safety are class A for the RightKit repository.
|
|
4068
4378
|
let selfRules = 0;
|
|
4069
|
-
|
|
4070
|
-
|
|
4379
|
+
// NN25: in snapshot mode the checkout's canonical top was resolved before the proof (snapshotCheckout); asking git again
|
|
4380
|
+
// here would start a git process after the resident proof for an answer this process already holds.
|
|
4381
|
+
const root = snapshotCheckout ?? (() => { const top = o.spawn("git", ["rev-parse", "--show-toplevel"], { cwd: checkCwd }); return failed(top) ? null : path.resolve(text(top).trim()); })();
|
|
4071
4382
|
const self = o.selfPath ?? fileURLToPath(import.meta.url);
|
|
4072
4383
|
// RightKit's own scripts are the checked repository's code: they run only after the app rules and every class A scan passed,
|
|
4073
4384
|
// never after a failure, so a red tree executes nothing of its own.
|
|
@@ -4422,6 +4733,11 @@ export async function main(argv, io = {}) {
|
|
|
4422
4733
|
// 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
4734
|
// request of one of the exact admitted shapes (snapshot-metadata.mjs), anything else passes through (node, git, the client's probe).
|
|
4424
4735
|
let scanSpawn = null;
|
|
4736
|
+
// Freeze the snapshot's Class A forecast before its metadata rows start.
|
|
4737
|
+
const guardCargoDiscovery = fullA && Boolean(snapshotA) && !o.runScans;
|
|
4738
|
+
const cargoMetadata = guardCargoDiscovery ? await import("../snapshot-metadata.mjs") : null;
|
|
4739
|
+
let authenticateCargoWorkspace = null;
|
|
4740
|
+
let classACargoPath = null;
|
|
4425
4741
|
if (snapshot && snapshotB) {
|
|
4426
4742
|
// Direct host: no broker grant to satisfy, so no config-only .git; the snapshot is scanned and compiled in place.
|
|
4427
4743
|
repo = snapshotB;
|
|
@@ -4489,30 +4805,61 @@ export async function main(argv, io = {}) {
|
|
|
4489
4805
|
const { directReadSpawn } = await import("../snapshot-metadata.mjs");
|
|
4490
4806
|
const pathKey = o.platform === "win32" ? (Object.keys(o.env).find((k) => k.toUpperCase() === "PATH") ?? "Path") : "PATH";
|
|
4491
4807
|
const direct = directCargoPath({ env: { ...o.env, PATH: o.env[pathKey] }, exists: o.exists, platform: o.platform, gateWrappers: true });
|
|
4808
|
+
classACargoPath = direct.cargo;
|
|
4492
4809
|
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
4810
|
// 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
4811
|
// workspace are the same call on the same verified snapshot, so the scan reuses the discovery's result instead of running Cargo again.
|
|
4495
4812
|
const readMemo = new Map();
|
|
4496
|
-
|
|
4497
|
-
|
|
4813
|
+
// 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
|
|
4814
|
+
// injected spawn sees every call). Asked with the direct cargo by its path and the same environment minus the per-call scratch target, so
|
|
4815
|
+
// the resident gate's key is the same from run to run.
|
|
4816
|
+
const served = !guardCargoDiscovery && o.spawn === defaultSpawn && direct.cargo ? await (async () => {
|
|
4817
|
+
const { snapshotCargoMetadata } = await import("../gate-serve.mjs");
|
|
4818
|
+
const { snapshotRoot: snapshotRootOf } = await import("../snapshot.mjs");
|
|
4819
|
+
let rootDir = null; try { rootDir = snapshotRootOf({ env: o.env }); } catch { rootDir = null; }
|
|
4820
|
+
if (!rootDir) return null;
|
|
4821
|
+
const servedEnv = { ...o.env, [pathKey]: direct.path };
|
|
4822
|
+
return ({ cwd, args }) => { const r = snapshotCargoMetadata({ cwd, args, cargo: direct.cargo, env: servedEnv, snapshotRootDir: rootDir, run: () => ({ status: null }) }); return r.served ? r : null; };
|
|
4823
|
+
})() : null;
|
|
4824
|
+
snapshotSpawn = directReadSpawn({ spawn: withDeclaredClient((c, a, opts) => o.spawn(c, a, opts)), ...readOpts, memo: readMemo, served });
|
|
4825
|
+
scanSpawn = directReadSpawn({ spawn: withDeclaredClient(defaultSpawnAsync), ...readOpts, memo: readMemo, isAsync: true, served });
|
|
4498
4826
|
}
|
|
4499
4827
|
npm = discoverNpmUnits({ root: repo, tracked, readFile: readSnap, exists: o.exists });
|
|
4500
4828
|
npmRoots = discoverPnpmRoots({ root: repo, tracked, exists: o.exists });
|
|
4501
4829
|
let metadata = null;
|
|
4502
|
-
if (scopeDirs.length) {
|
|
4830
|
+
if (scopeDirs.length || (guardCargoDiscovery && manifests.length)) {
|
|
4503
4831
|
closureTools = await import("../app-closure.mjs");
|
|
4832
|
+
const committed = new Set(files);
|
|
4504
4833
|
const readCommitted = (file) => {
|
|
4505
|
-
if (!
|
|
4834
|
+
if (!committed.has(file)) throw new Error(`${file} is absent from the committed tree`);
|
|
4506
4835
|
return readSnap(path.join(repo, file));
|
|
4507
4836
|
};
|
|
4508
4837
|
const sourceMetadata = closureTools.cargoMetadataFromManifests({ manifests: manifests.filter((m) => !fixtures.some((d) => m.startsWith(`${d.replace(/\/$/, "")}/`))), readFile: readCommitted });
|
|
4509
|
-
|
|
4510
|
-
|
|
4511
|
-
|
|
4512
|
-
|
|
4513
|
-
|
|
4514
|
-
|
|
4515
|
-
|
|
4838
|
+
if (scopeDirs.length) {
|
|
4839
|
+
const inventory = discoverRustWorkspaces({ root: repo, tracked, fixtures, readFile: readSnap, metadata: sourceMetadata });
|
|
4840
|
+
closure = closureTools.closureOf({ scopeDirs, npmUnits: npm, rustUnits: inventory.units, readFile: readCommitted });
|
|
4841
|
+
const selectedWorkspaces = new Set(inventory.units.filter((u) => closure.rust.has(u.name)).map((u) => u.cargoDir));
|
|
4842
|
+
metadata = (dir) => {
|
|
4843
|
+
const source = sourceMetadata(dir);
|
|
4844
|
+
return !guardCargoDiscovery && selectedWorkspaces.has(source.cargoDir) ? workspaceMetadata({ root: repo, spawn: snapshotSpawn, cargoCommand: planCargoCommand, dir, realpath: fs.realpathSync }) : source;
|
|
4845
|
+
};
|
|
4846
|
+
} else {
|
|
4847
|
+
metadata = sourceMetadata;
|
|
4848
|
+
}
|
|
4849
|
+
if (guardCargoDiscovery) {
|
|
4850
|
+
// Cargo authenticates the workspace, committed members and publishability after admission.
|
|
4851
|
+
const shape = (facts) => canonicalJson(facts.members.filter((m) => committed.has(m.manifest))
|
|
4852
|
+
.map(({ name, dir, manifest, publish }) => ({ name, dir, manifest, publish }))
|
|
4853
|
+
.sort((a, b) => a.manifest < b.manifest ? -1 : a.manifest > b.manifest ? 1 : 0));
|
|
4854
|
+
authenticateCargoWorkspace = (scan, result, stored) => {
|
|
4855
|
+
const dir = scan.cwd ?? ".";
|
|
4856
|
+
const observed = result && !result.truncated ? cargoMetadata.cargoWorkspaceFacts({ root: repo, stdout: result.stdout }) : stored;
|
|
4857
|
+
if (observed?.cargoDir !== dir || !Array.isArray(observed.members) || shape(observed) !== shape(sourceMetadata(dir))) {
|
|
4858
|
+
throw new Error("RK_CARGO_DISCOVERY: " + scan.id + " has no matching authentic Cargo workspace & member inventory");
|
|
4859
|
+
}
|
|
4860
|
+
return observed;
|
|
4861
|
+
};
|
|
4862
|
+
}
|
|
4516
4863
|
}
|
|
4517
4864
|
rust = discoverRustWorkspaces({ root: repo, spawn: snapshotSpawn, cargoCommand: planCargoCommand, tracked, untracked, fixtures, readFile: readSnap, ...(metadata ? { metadata } : {}) });
|
|
4518
4865
|
if (closure) {
|
|
@@ -4775,6 +5122,18 @@ export async function main(argv, io = {}) {
|
|
|
4775
5122
|
const cargoExcluded = kept.dropped.filter((s) => closureTools.isCargoScan(s)).length;
|
|
4776
5123
|
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
5124
|
}
|
|
5125
|
+
const cargoMetadataTopologies = new Map();
|
|
5126
|
+
if (authenticateCargoWorkspace) {
|
|
5127
|
+
// 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
|
|
5128
|
+
// refuses any linked discovery input, so all six fixture workspaces came back unproven and their metadata rows ran real Cargo on every
|
|
5129
|
+
// run. The Cargo home is named by where it really is; a link that moves names another directory and changes the proof.
|
|
5130
|
+
const cargoHome = cargoHomeOf(o.env);
|
|
5131
|
+
for (const row of plan.scans.filter((scan) => scan.class === "A" && /^cargo-metadata(:|$)/.test(scan.id))) {
|
|
5132
|
+
const proof = classACargoPath && cargoMetadata.cargoWorkspaceTopology({ root: repo, dir: row.cwd ?? ".", cargoHome });
|
|
5133
|
+
if (proof) cargoMetadataTopologies.set(row.id, proof);
|
|
5134
|
+
else row.cargoWorkspaceUncacheable = true;
|
|
5135
|
+
}
|
|
5136
|
+
}
|
|
4778
5137
|
const unionContext = o[UNIT_LIST_UNION];
|
|
4779
5138
|
if (unionContext && snapshotB) {
|
|
4780
5139
|
try {
|
|
@@ -4884,7 +5243,13 @@ export async function main(argv, io = {}) {
|
|
|
4884
5243
|
// (`["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
5244
|
const executorClient = path.basename(String(cargoCommand[0] ?? "")).replace(/\.(exe|cmd|bat)$/i, "") === "rustright" ? (brokerClientOf(o, executor) ?? cargoCommand[0]) : null;
|
|
4886
5245
|
const brokerClient = !brokerHost ? null : declaredClient ? "rustright" : managedRuntimeClient(o.env, o.platform, o.exists) ?? executorClient;
|
|
4887
|
-
|
|
5246
|
+
// NN07: job states are read over the broker's own endpoint from this process when the endpoint and the runtime identity beside the client
|
|
5247
|
+
// can be established (the same target the snapshot-status query uses); otherwise through the client, as before.
|
|
5248
|
+
const brokerWire = (() => {
|
|
5249
|
+
if (!brokerClient || o.spawn !== defaultSpawn) return null;
|
|
5250
|
+
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; }
|
|
5251
|
+
})();
|
|
5252
|
+
const brokerLive = brokerClient ? createBrokerLive({ client: brokerClient, env: { ...o.env, ...(executor.env ?? {}) }, spawn: withDeclaredClient(defaultSpawnAsync), platform: o.platform, wire: brokerWire }) : null;
|
|
4888
5253
|
|
|
4889
5254
|
if (planOnly) {
|
|
4890
5255
|
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 +5278,8 @@ export async function main(argv, io = {}) {
|
|
|
4913
5278
|
}
|
|
4914
5279
|
// The result cache keys on the gated commit's object ids; the stdin check above made HEAD the pushed commit.
|
|
4915
5280
|
let cache = null;
|
|
5281
|
+
let classAHistory = null;
|
|
5282
|
+
let classBHistory = null;
|
|
4916
5283
|
const nodeCheckRejects = new Map();
|
|
4917
5284
|
let nodeCheckDiagnosticId = null; let nodeCheckDiagnosticState = "not-seen";
|
|
4918
5285
|
const countNodeCheckRejection = (reason, scanId) => {
|
|
@@ -4925,6 +5292,8 @@ export async function main(argv, io = {}) {
|
|
|
4925
5292
|
// 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
5293
|
const keyErrors = new Map(); let cacheDisabled = null;
|
|
4927
5294
|
const keyError = (scan, error) => keyErrors.set(scan.id, String(error?.message ?? error).slice(0, 300));
|
|
5295
|
+
const uncacheableReasons = new Map();
|
|
5296
|
+
const uncacheable = (scan, reason) => uncacheableReasons.set(scan.id, reason);
|
|
4928
5297
|
// Full class A on the working tree (the door, and broker admission of the live checkout) caches on the LIVE bytes: every
|
|
4929
5298
|
// 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
5299
|
// cache, and any edit misses it.
|
|
@@ -4992,7 +5361,7 @@ export async function main(argv, io = {}) {
|
|
|
4992
5361
|
// changes while class A runs voids the verdict.
|
|
4993
5362
|
// envStartWithCaches records, for audit, the tool caches as the run found them (what its checks could read); the pass line
|
|
4994
5363
|
// carries it next to the env the verdict binds.
|
|
4995
|
-
let envAtStart = null; let envStartWithCaches = null; let cachesAtStart = null;
|
|
5364
|
+
let envAtStart = null; let envStartWithCaches = null; let cachesAtStart = null; let rowEnvironment = null;
|
|
4996
5365
|
if (boundFullA) {
|
|
4997
5366
|
const orphans = orphanedPnpmStores({ root: liveBase, files: live.files });
|
|
4998
5367
|
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 +5370,11 @@ export async function main(argv, io = {}) {
|
|
|
5001
5370
|
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
5371
|
const pinProblem = pnpmPinProblem({ root: liveBase, files: live.files, spawn: o.spawn, readFile: o.readFile, fixtures: pinFixtures, platform: o.platform });
|
|
5003
5372
|
if (pinProblem) { o.err(`${tag} BLOCKED: ${pinProblem.message}; no class A row ran`); return 1; }
|
|
5004
|
-
try {
|
|
5373
|
+
try {
|
|
5374
|
+
envAtStart = classAEnvironmentDigest({ root: liveBase, gatePackage: o.gatePackage, files: live.files, spawn: o.spawn, includeCaches: false, onRowEnvironment: (value) => { rowEnvironment = value; } });
|
|
5375
|
+
envStartWithCaches = envAtStart;
|
|
5376
|
+
cachesAtStart = toolCacheManifest({ root: liveBase, files: live.files });
|
|
5377
|
+
}
|
|
5005
5378
|
catch (error) { o.err(`${tag} BLOCKED: ${error.message}`); return 1; }
|
|
5006
5379
|
}
|
|
5007
5380
|
if (boundFullA) {
|
|
@@ -5011,7 +5384,10 @@ export async function main(argv, io = {}) {
|
|
|
5011
5384
|
const { files, ids, digestOf } = live;
|
|
5012
5385
|
const under = (dir) => (dir === "." || dir === "" ? files : files.filter((f) => f === dir || f.startsWith(`${dir}/`)));
|
|
5013
5386
|
const objectId = (p) => (ids.has(p) ? ids.get(p) : under(p).length ? digestOf(under(p)) : null);
|
|
5014
|
-
const
|
|
5387
|
+
const storeDir = path.join(path.resolve(root, text(common).trim()), "rightkit-gate-cache");
|
|
5388
|
+
// Nov-18 cache rule applies to every bound full-A form (snapshot, hosted, live), not only guarded snapshot discovery.
|
|
5389
|
+
classAHistory = o[CLASS_A_HISTORY] ?? openClassAHistory({ historyRoot: path.join(gateRunsRoot({ env: o.env, platform: o.platform }), "rightkit-class-a-history"), storeDir, onRestart: cacheRestartNote(o) });
|
|
5390
|
+
const store = fileScanCache(storeDir);
|
|
5015
5391
|
const listFiles = (dir) => under(dir);
|
|
5016
5392
|
const readBlob = (p) => fs.readFileSync(path.join(liveBase, p), "utf8");
|
|
5017
5393
|
// 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 +5395,8 @@ export async function main(argv, io = {}) {
|
|
|
5019
5395
|
// Tool caches (vitest, tsc build info, ...) are left out: the scans write them themselves, so keying on them made every rerun miss.
|
|
5020
5396
|
// 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
5397
|
// 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 });
|
|
5398
|
+
const environment = rowEnvironment;
|
|
5399
|
+
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
5400
|
// 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
5401
|
// missed every row whenever one file joined or left the plan. build-helpers is never reused: it reads the host's trace list,
|
|
5026
5402
|
// which is outside every key (and takes seconds).
|
|
@@ -5031,15 +5407,24 @@ export async function main(argv, io = {}) {
|
|
|
5031
5407
|
const nodeCheckModule = null; // GC-A24: node-check rows use the generic file key (file, ancestor package.json, node identity)
|
|
5032
5408
|
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
5409
|
// 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;
|
|
5410
|
+
cache = { ...store, narrowNodeCheck: false, uncacheableReason: (scan) => uncacheableReasons.get(scan.id), entryNow: (p) => objectId(p), digest: (scan, context) => {
|
|
5411
|
+
if (/^build-helpers(:|$)/.test(scan.id) || scan.cargoWorkspaceUncacheable) return null;
|
|
5036
5412
|
// This narrow key applies only to the helper's proven plain snapshot node --check.
|
|
5037
5413
|
// Uncertain rows miss rather than falling back to a less specific key.
|
|
5038
|
-
const key = digest(scan);
|
|
5414
|
+
const key = digest(scan);
|
|
5415
|
+
const topology = cargoMetadataTopologies.get(scan.id);
|
|
5416
|
+
const full = key === null ? null : key + ":" + (classAEnvironmentBound(scan) ? environment : CLASS_A_KEY_SCHEMA) + rowShape(scan) + (topology ? ":metadata=" + topology : "");
|
|
5417
|
+
scanKeys.set(scan.id, full);
|
|
5418
|
+
return full;
|
|
5039
5419
|
} };
|
|
5040
|
-
} catch (error) {
|
|
5420
|
+
} catch (error) {
|
|
5421
|
+
cacheDisabled = `class A cache preparation failed: ${error?.message ?? error}`;
|
|
5422
|
+
o.err(`${tag} BLOCKED: ${cacheDisabled}`);
|
|
5423
|
+
return 1;
|
|
5424
|
+
}
|
|
5041
5425
|
}
|
|
5042
5426
|
if (!classAOnly) {
|
|
5427
|
+
const needsForecast = !o.runScans;
|
|
5043
5428
|
try {
|
|
5044
5429
|
const headSha = snapshotBCommit?.commit ?? text(git("rev-parse", "HEAD")).trim();
|
|
5045
5430
|
const treeId = text(git("rev-parse", `${headSha}^{tree}`)).trim();
|
|
@@ -5051,7 +5436,11 @@ export async function main(argv, io = {}) {
|
|
|
5051
5436
|
const line = text(r).split(/\r?\n/).find(Boolean);
|
|
5052
5437
|
return line ? (line.split("\t")[0].split(/\s+/)[2] ?? null) : null;
|
|
5053
5438
|
};
|
|
5054
|
-
const
|
|
5439
|
+
const storeDir = path.join(path.resolve(root, text(common).trim()), "rightkit-gate-cache");
|
|
5440
|
+
if (needsForecast) classBHistory = openClassBHistory({ historyRoot: path.join(gateRunsRoot({ env: o.env, platform: o.platform }), "rightkit-class-a-history"), storeDir, onRestart: cacheRestartNote(o) });
|
|
5441
|
+
// Mixed A+B in one invocation needs its Class A history too; boundFullA opened it above when that block ran.
|
|
5442
|
+
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, onRestart: cacheRestartNote(o) });
|
|
5443
|
+
const store = fileScanCache(storeDir);
|
|
5055
5444
|
const listFiles = (dir) => {
|
|
5056
5445
|
const r = git("ls-tree", "-r", "--name-only", "-z", headSha, "--", dir);
|
|
5057
5446
|
if (failed(r)) throw new Error(`git ls-tree failed: ${why(r)}`);
|
|
@@ -5078,9 +5467,14 @@ export async function main(argv, io = {}) {
|
|
|
5078
5467
|
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
5468
|
} else {
|
|
5080
5469
|
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}`);
|
|
5470
|
+
if (!needsForecast) o.err(`${tag} note: ${cacheDisabled}`);
|
|
5082
5471
|
}
|
|
5083
|
-
} catch (error) {
|
|
5472
|
+
} catch (error) {
|
|
5473
|
+
cache = null;
|
|
5474
|
+
cacheDisabled = `class B cache preparation failed: ${error?.message ?? error}`;
|
|
5475
|
+
if (!needsForecast) o.err(`${tag} note: ${cacheDisabled}`);
|
|
5476
|
+
}
|
|
5477
|
+
if (needsForecast && (!classBHistory || !cache)) { o.err(`${tag} RK_CACHE_DIVERGENCE: ${cacheDisabled}`); return 1; }
|
|
5084
5478
|
}
|
|
5085
5479
|
// 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
5480
|
// 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 +5510,15 @@ export async function main(argv, io = {}) {
|
|
|
5116
5510
|
} catch (error) { o.err(`${tag} BLOCKED: RK_SEAM: ${error.message}; nothing ran`); return 1; }
|
|
5117
5511
|
}
|
|
5118
5512
|
directTiming.cargoStart = Date.now();
|
|
5513
|
+
const stageClasses = classAOnly ? ["A"] : classAEarlier ? ["B"] : ["A", "B"];
|
|
5119
5514
|
const scanOptions = {
|
|
5515
|
+
...(authenticateCargoWorkspace ? { cargoWorkspaceFactsFor: authenticateCargoWorkspace } : {}),
|
|
5516
|
+
...(classACargoPath ? { classAToolPaths: { cargo: classACargoPath } } : {}),
|
|
5517
|
+
// NN09: the broker's compiler is read from its host configuration in this process; no `rustright cargo --version` starts (broker-toolchain.mjs).
|
|
5518
|
+
...(() => { const bt = brokerToolchainOf(o, executor); return bt ? { brokerToolchain: bt } : {}; })(),
|
|
5120
5519
|
// 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
5520
|
...(snapshot ? { trackedFiles: files } : {}),
|
|
5122
|
-
classes:
|
|
5521
|
+
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
5522
|
// 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
5523
|
...(brokerHost && cache ? (() => { const identity = brokerRuntimeIdentityText({ clients: [brokerClient, executor?.client, cargoCommand[0]], env: { ...o.env, ...(executor.env ?? {}) }, platform: o.platform }); return identity ? { failureIdentity: identity } : {}; })() : {}),
|
|
5125
5524
|
// 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 +5558,53 @@ export async function main(argv, io = {}) {
|
|
|
5159
5558
|
})(),
|
|
5160
5559
|
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
5560
|
};
|
|
5162
|
-
// Adrian 2026-11-
|
|
5163
|
-
//
|
|
5164
|
-
//
|
|
5165
|
-
//
|
|
5561
|
+
// Adrian 2026-11-18 cache rule supersedes the 2026-11-08 explained-runs path:
|
|
5562
|
+
// every cached class in this invocation needs its independent forecast history.
|
|
5563
|
+
// Without it there is no approved prior outcome to forecast from, so fail closed
|
|
5564
|
+
// before any scan dispatch instead of running unexpected misses.
|
|
5565
|
+
const historyByClass = { A: classAHistory, B: classBHistory };
|
|
5166
5566
|
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`);
|
|
5567
|
+
const missingHistory = stageClasses.filter((cls) => !historyByClass[cls]);
|
|
5568
|
+
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
5569
|
}
|
|
5198
|
-
|
|
5570
|
+
let scanResult;
|
|
5571
|
+
const decisionFiles = {};
|
|
5572
|
+
const activeHistories = stageClasses.filter((cls) => historyByClass[cls]);
|
|
5573
|
+
if (activeHistories.length) {
|
|
5574
|
+
try {
|
|
5575
|
+
for (const cls of activeHistories) {
|
|
5576
|
+
const history = historyByClass[cls];
|
|
5577
|
+
const stage = cls === "B" ? "class-b" : "class-a";
|
|
5578
|
+
const decisionFile = path.join(gateRunsRoot({ env: o.env, platform: o.platform }), `rightkit-${stage}-decisions`, randomUUID() + ".json");
|
|
5579
|
+
decisionFiles[cls] = decisionFile;
|
|
5580
|
+
const evidence = { stage, host: os.hostname(), commit: snapshotBCommit?.commit ?? snapshotCommitId?.commit ?? hostedCommitA?.commit ?? null, tree: snapshotBCommit?.tree ?? liveSnapshot, baseline: history.file };
|
|
5581
|
+
const forecasts = {};
|
|
5582
|
+
scanOptions[`class${cls}CacheForecast`] = (rows, { phase } = {}) => {
|
|
5583
|
+
const forecast = history.forecast(rows);
|
|
5584
|
+
if (phase) forecasts[phase] = forecast;
|
|
5585
|
+
writeFileAtomic(decisionFile, JSON.stringify({ ...evidence, phase: "forecast", forecast, ...(phase ? { forecasts } : {}) }), { mode: 0o600 });
|
|
5586
|
+
return forecast;
|
|
5587
|
+
};
|
|
5588
|
+
}
|
|
5589
|
+
scanResult = await runScans(plan, scanOptions);
|
|
5590
|
+
let blocked = false;
|
|
5591
|
+
for (const cls of activeHistories) {
|
|
5592
|
+
const history = historyByClass[cls];
|
|
5593
|
+
const stage = cls === "B" ? "class-b" : "class-a";
|
|
5594
|
+
const decisionFile = decisionFiles[cls];
|
|
5595
|
+
const decision = scanResult[`class${cls}CacheDecision`];
|
|
5596
|
+
if (!decision) throw new Error(`Class ${cls} scanner returned no forecast decision`);
|
|
5597
|
+
const evidence = { stage, host: os.hostname(), commit: snapshotBCommit?.commit ?? snapshotCommitId?.commit ?? hostedCommitA?.commit ?? null, tree: snapshotBCommit?.tree ?? liveSnapshot, baseline: history.file };
|
|
5598
|
+
writeFileAtomic(decisionFile, JSON.stringify({ ...evidence, ...decision, phase: "observed" }), { mode: 0o600 });
|
|
5599
|
+
if (decision.mismatches.length) {
|
|
5600
|
+
blocked = true;
|
|
5601
|
+
for (const row of decision.mismatches) o.err(`${tag} RK_CACHE_DIVERGENCE ${JSON.stringify(row)}`);
|
|
5602
|
+
o.err(`${tag} BLOCKED: ${decision.dispatchedRows.length} row dispatches. Evidence: ${decisionFile}`);
|
|
5603
|
+
} else o.out(`${tag} Class ${cls} cache decision: ${decisionFile}`);
|
|
5604
|
+
}
|
|
5605
|
+
if (blocked) return 1;
|
|
5606
|
+
} catch (error) { o.err(`${tag} RK_CACHE_DIVERGENCE: ${error.message}`); return 1; }
|
|
5607
|
+
} else scanResult = await (o.runScans ?? runScans)(plan, scanOptions);
|
|
5199
5608
|
if (nodeCheckRejects.size) o.out(`${tag} node-check cache misses: ${[...nodeCheckRejects].sort(([a], [b]) => a.localeCompare(b)).map(([reason, count]) => `${reason}=${count}`).join(", ")}`);
|
|
5200
5609
|
if (snapFullA && o.env.RIGHTKIT_PREPARATION_DIAGNOSTIC_DIR && nodeCheckDiagnosticId) o.out(`${tag} node-check diagnostic row: ${nodeCheckDiagnosticState}`);
|
|
5201
5610
|
if (unionContext) {
|
|
@@ -5230,6 +5639,7 @@ export async function main(argv, io = {}) {
|
|
|
5230
5639
|
// 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
5640
|
try {
|
|
5232
5641
|
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() });
|
|
5642
|
+
o.onLimitedEvidence?.(limitedEvidenceOf(report));
|
|
5233
5643
|
const base = gateRunsRoot({ env: o.env, platform: o.platform });
|
|
5234
5644
|
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
5645
|
const otherPass = (report.scans ?? []).filter((s) => s.coverage === "skipped" && /is not part of this pass/.test(String(s.reason ?? ""))).length;
|
|
@@ -5238,6 +5648,15 @@ export async function main(argv, io = {}) {
|
|
|
5238
5648
|
// 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
5649
|
// in (gate, tools, installed dependencies, tool caches), unchanged too. A verdict whose binding moved covers nothing: a green one is
|
|
5240
5650
|
// refused and a red one names no reusable deterministic cause (rightkit#1257). Returns { env, notes } or { prefix, problem, exit }.
|
|
5651
|
+
const recordedHistories = new Set();
|
|
5652
|
+
const recordHistory = () => {
|
|
5653
|
+
for (const cls of activeHistories) {
|
|
5654
|
+
if (recordedHistories.has(cls)) continue;
|
|
5655
|
+
try { historyByClass[cls].record(scanResult[`class${cls}CacheDecision`]); recordedHistories.add(cls); }
|
|
5656
|
+
catch (error) { o.err(`${tag} BLOCKED: cannot record verified Class ${cls} cache outcomes: ${error.message}`); return false; }
|
|
5657
|
+
}
|
|
5658
|
+
return true;
|
|
5659
|
+
};
|
|
5241
5660
|
const judgedBinding = async () => {
|
|
5242
5661
|
if (hostedFullA) {
|
|
5243
5662
|
try { await verifyCommittedCheckout({ git, root, ...hostedCommitA, when: "after class A" }); }
|
|
@@ -5254,7 +5673,7 @@ export async function main(argv, io = {}) {
|
|
|
5254
5673
|
}
|
|
5255
5674
|
if (!live) return { env: null, notes: [] };
|
|
5256
5675
|
let envDigest; let envNoCaches;
|
|
5257
|
-
try { envDigest = classAEnvironmentDigest({ root: liveBase, gatePackage: o.gatePackage, files: live.files, spawn: o.spawn }); envNoCaches =
|
|
5676
|
+
try { envDigest = classAEnvironmentDigest({ root: liveBase, gatePackage: o.gatePackage, files: live.files, spawn: o.spawn }); envNoCaches = envDigest; }
|
|
5258
5677
|
catch (error) { return { prefix: "BLOCKED", exit: 1, problem: error.message }; }
|
|
5259
5678
|
const notes = [];
|
|
5260
5679
|
if (cachesAtStart !== null) {
|
|
@@ -5286,23 +5705,17 @@ export async function main(argv, io = {}) {
|
|
|
5286
5705
|
// 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
5706
|
const unitByName = new Map(rust.units.map((u) => [u.name, u]));
|
|
5288
5707
|
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
|
-
}
|
|
5708
|
+
// Where Cargo put them: `<dir>/<triple>/release` (every compile is release for the host target, GC-A15, cross-targets.mjs oneOutput); on a broker
|
|
5709
|
+
// 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
|
|
5710
|
+
// binary. A row answered from the cache vouches for its programs only while they are still the bytes it linked (gate-stages.mjs builtBinsOfRun).
|
|
5711
|
+
const builtBins = builtBinsOfRun({
|
|
5712
|
+
rows: scanResult.scans,
|
|
5713
|
+
unitOf: (r) => unitByName.get(rustUnitOfScanId(r.id, known)),
|
|
5714
|
+
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` }; },
|
|
5715
|
+
keyOf: (r) => { const full = scanKeys.get(r.id); return typeof full === "string" && full ? createHash("sha256").update(`built-bins/1\n${full}`).digest("hex") : null; },
|
|
5716
|
+
store: cache,
|
|
5717
|
+
note: (text) => o.out(`${tag} built programs: ${text}`),
|
|
5718
|
+
});
|
|
5306
5719
|
const outputWorkspaces = (snapshotBroker ? scanResult.scans.map((r) => r.snapshotEvidence?.outputDir) : Object.values(targetDirs ?? {})).filter(Boolean).map((dir) => [dir]);
|
|
5307
5720
|
o.onCompileOutputs?.(outputWorkspaces.map(([dir]) => dir), builtBins);
|
|
5308
5721
|
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 +5749,7 @@ export async function main(argv, io = {}) {
|
|
|
5336
5749
|
o.onDirectReceipt?.(directReceipt);
|
|
5337
5750
|
o.out(`${tag} direct receipt ${JSON.stringify(directReceipt)}`);
|
|
5338
5751
|
}
|
|
5752
|
+
if (classBHistory && !recordHistory()) return 1;
|
|
5339
5753
|
}
|
|
5340
5754
|
if (unionContext) unionContext.completed = true;
|
|
5341
5755
|
if (failures.length) {
|
|
@@ -5351,6 +5765,7 @@ export async function main(argv, io = {}) {
|
|
|
5351
5765
|
if (binding.exit === 2) return 2;
|
|
5352
5766
|
} else {
|
|
5353
5767
|
for (const n of binding.notes) o.out(`${tag} ${n}`);
|
|
5768
|
+
if (!recordHistory()) return 1;
|
|
5354
5769
|
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
5770
|
if (marker) o.out(marker);
|
|
5356
5771
|
}
|
|
@@ -5377,6 +5792,7 @@ export async function main(argv, io = {}) {
|
|
|
5377
5792
|
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
5793
|
catch { /* Optional diagnostics never change the gate verdict. */ }
|
|
5379
5794
|
}
|
|
5795
|
+
if (!recordHistory()) return 1;
|
|
5380
5796
|
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
5797
|
return 0;
|
|
5382
5798
|
}
|
|
@@ -5385,9 +5801,11 @@ export async function main(argv, io = {}) {
|
|
|
5385
5801
|
// full class A pass, and it says so (reviewer, 2026-10-27). The full gate runs them before any compile.
|
|
5386
5802
|
const notRun = plan.scans.filter((s) => s.class === "A" && s.executes === true).map((s) => s.id);
|
|
5387
5803
|
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 ? ", …" : ""}`);
|
|
5804
|
+
if (!recordHistory()) return 1;
|
|
5388
5805
|
o.out(`${tag} class A content pass: ${scanResult.scans.length} deterministic scan(s) over ${changed.length} file(s) of ${base}`);
|
|
5389
5806
|
return 0;
|
|
5390
5807
|
}
|
|
5808
|
+
if (!recordHistory()) return 1;
|
|
5391
5809
|
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
5810
|
return 0;
|
|
5393
5811
|
} finally {
|
|
@@ -5416,6 +5834,16 @@ export const callingGatePath = () => fs.realpathSync(fileURLToPath(import.meta.u
|
|
|
5416
5834
|
if (invokedDirectly) {
|
|
5417
5835
|
// GC-A27 NN07-NN12: with RK_GATE_SPAWN_LEDGER set, every child process of this run is recorded (spawn-ledger.mjs). Off otherwise.
|
|
5418
5836
|
installSpawnLedger();
|
|
5837
|
+
// 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.
|
|
5838
|
+
// NN22: whole-tree listings of a full commit id are kept between gate processes (probe-memo.mjs treeListStore).
|
|
5839
|
+
{
|
|
5840
|
+
const treeLists = (() => { try { return path.join(gateRunsRoot({ env: process.env, platform: process.platform }), "tree-lists"); } catch { return null; } })();
|
|
5841
|
+
installProbeMemo({ storeDir: treeLists });
|
|
5842
|
+
// NN22: the sealed listing (snapshot.mjs treeEntries) runs in a fresh private directory, so it is kept by object database, not by working directory.
|
|
5843
|
+
setTreeListingStore(treeLists ? contentStore(path.join(treeLists, "sealed")) : null);
|
|
5844
|
+
}
|
|
5845
|
+
// NN11/NN28: how this run proved the snapshot, once, at the end (snapshot.mjs SNAPSHOT_PROOF_COUNTS).
|
|
5846
|
+
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
5847
|
// Every child this run starts that can reach rustright (scans, unit stages, right-release dev/test, their builds) inherits it.
|
|
5420
5848
|
process.env.RUSTRIGHT_CALLING_GATE = callingGatePath();
|
|
5421
5849
|
delete process.env.RIGHTKIT_CALLING_GATE; // one spelling, never both
|