@rightkit/release 0.6.47 → 0.6.49
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/artifact-storage.mjs +2 -2
- package/assembled-app.mjs +6 -1
- package/bin/rightkit-gate.mjs +96 -18
- package/build-helpers-command.mjs +1 -1
- package/build-ownership.mjs +2 -2
- package/cargo-contract.mjs +1 -1
- package/cargo-guard.mjs +1 -1
- package/cli/right-release.mjs +2 -0
- package/credential-provider.mjs +2 -2
- package/deterministic-scans.mjs +120 -14
- package/gate-acceptance.mjs +1899 -52
- package/gate-serve.mjs +5 -2
- package/install-assembled-app.mjs +5 -1
- package/managed-cargo.mjs +3 -3
- package/managed-roots.mjs +48 -12
- package/ownership-mandatory-set.json +162 -0
- package/ownership-mandatory-set.mjs +1 -1
- package/package.json +1 -1
- package/qa-runner.mjs +1 -1
- package/release-qa-command.mjs +1 -1
- package/rightkit-signing-agent.mjs +3 -2
- package/rightkit-versions.json +1 -1
- package/signing-agent-install.mjs +1 -1
- package/snapshot-broker.mjs +7 -4
- package/snapshot-git.mjs +22 -1
- package/snapshot.mjs +9 -4
- package/spawn-ledger.mjs +46 -0
- package/stage-ledger.mjs +7 -5
- package/tool-build.mjs +1 -1
- package/unit-gate.mjs +1 -1
package/gate-acceptance.mjs
CHANGED
|
@@ -15,11 +15,14 @@
|
|
|
15
15
|
// at the end. The one checkout write is S6's dirty-checkout setup, which refuses a dirty fixture and restores it exactly.
|
|
16
16
|
// * The verdict is PASS only when no clause, step or step-only check failed and every step ran as specified; it is always printed with the
|
|
17
17
|
// count of unchecked clauses ("PASS (N of 67 asserted, M unchecked)"), never as a bare PASS.
|
|
18
|
-
// *
|
|
18
|
+
// * The 19 non-negotiables NN01-NN19 (GATE-CONTRACT [GC-A27]) are asserted on every run from the run's own evidence (coverage, log, spawn ledger, budgets
|
|
19
|
+
// file). Every gate invocation is started with RK_GATE_SPAWN_LEDGER naming a per-run file under --out. A selected non-negotiable with missing evidence
|
|
20
|
+
// FAILS; it is never "unchecked". Wall time is judged only by NN18 against ci/gate-acceptance-budgets.json (a null budget fails: "no budget measured").
|
|
19
21
|
// The pure assertion functions are exported and tested by gate-acceptance.test.mjs; `--plan` prints the steps and clause mapping and runs nothing.
|
|
20
22
|
import { createHash } from "node:crypto";
|
|
21
23
|
import { spawn, spawnSync } from "node:child_process";
|
|
22
24
|
import fs from "node:fs";
|
|
25
|
+
import os from "node:os";
|
|
23
26
|
import path from "node:path";
|
|
24
27
|
import { fileURLToPath } from "node:url";
|
|
25
28
|
import { keyPath, repoKey } from "./snapshot.mjs";
|
|
@@ -110,7 +113,7 @@ export function strictKeys(obj, { required = [], optional = [] }, where) {
|
|
|
110
113
|
}
|
|
111
114
|
|
|
112
115
|
const ROW_REQUIRED = ["id", "class", "coverage", "status", "key", "reason"];
|
|
113
|
-
const ROW_OPTIONAL = ["code", "timing", "scanElapsedMs", "retryTiming", "batchAttempts", "batchedWith"];
|
|
116
|
+
const ROW_OPTIONAL = ["code", "timing", "scanElapsedMs", "retryTiming", "batchAttempts", "batchedWith", "evidence", "filesRead"];
|
|
114
117
|
const COVERAGE_VALUES = new Set(["hit", "ran", "skipped"]);
|
|
115
118
|
|
|
116
119
|
/** GC-A21: the schema of one coverage report (gate-coverage.mjs buildCoverageReport). Fail closed on any unknown field. */
|
|
@@ -136,7 +139,10 @@ export function validateCoverage(report) {
|
|
|
136
139
|
if (typeof row.status !== "string" || !row.status) problems.push(`${where}: status is not a non-empty string`);
|
|
137
140
|
if (typeof row.reason !== "string" || !row.reason) problems.push(`${where}: reason is not a non-empty string`);
|
|
138
141
|
if (!(row.key === null || (typeof row.key === "string" && row.key))) problems.push(`${where}: key is neither null nor a string`);
|
|
139
|
-
|
|
142
|
+
// A member whose own result is a cached pass still fails when its grouped invocation failed (rightkit#1458: BATCH_REQUIREMENT_FAILED keeps
|
|
143
|
+
// the grouped failure as evidence), so hit + fail is valid exactly when a batch attempt of that row failed.
|
|
144
|
+
const batchFailed = Array.isArray(row.batchAttempts) && row.batchAttempts.some((a) => a?.status === "fail");
|
|
145
|
+
if (row.coverage === "hit" && row.status !== "pass" && !(row.status === "fail" && (batchFailed || row.class === "B"))) problems.push(`${where}: a hit row has status ${JSON.stringify(row.status)}, expected pass`);
|
|
140
146
|
if (row.coverage === "ran" && row.status !== "pass" && row.status !== "fail") problems.push(`${where}: a ran row has status ${JSON.stringify(row.status)}, expected pass|fail`);
|
|
141
147
|
}
|
|
142
148
|
if (isObject(report.totals)) {
|
|
@@ -351,12 +357,10 @@ export function brokerDigestProblems({ manifest, pins }) {
|
|
|
351
357
|
return { ok: problems.length === 0, problems };
|
|
352
358
|
}
|
|
353
359
|
|
|
354
|
-
const WARM_UNCACHED_CLASS_A = /^(pnpm-lockfile|advisory-exceptions)(:|$)/;
|
|
355
|
-
|
|
356
360
|
/**
|
|
357
|
-
* S2 (GC-A24, GC-A19): a warm rerun of the same commit. Against the first run `prev` (id -> row) and the rerun `next`:
|
|
358
|
-
* - every scan of the rerun
|
|
359
|
-
*
|
|
361
|
+
* S2 (GC-A24, GC-A19, NN01): a warm rerun of the same commit. Against the first run `prev` (id -> row) and the rerun `next`:
|
|
362
|
+
* - every Class A scan of the rerun answered `hit` (a `ran` there is a failure, a skipped row is a failure). There is no uncached family any more:
|
|
363
|
+
* pnpm-lockfile and advisory-exceptions took GC-A19/GC-A24 keys (commit af0704a05, 2026-11-05), so NN01 ("any Class A row is ran") covers them too;
|
|
360
364
|
* - the key of every row equals the first run's key byte for byte.
|
|
361
365
|
*/
|
|
362
366
|
export function assertWarmRerun(prev, next) {
|
|
@@ -364,9 +368,7 @@ export function assertWarmRerun(prev, next) {
|
|
|
364
368
|
let hits = 0;
|
|
365
369
|
for (const [id, row] of next) {
|
|
366
370
|
if (row.coverage === "skipped" && row.status === "not-in-pass") continue;
|
|
367
|
-
const uncached = row.class === "A" && WARM_UNCACHED_CLASS_A.test(id);
|
|
368
371
|
if (row.coverage === "skipped") { problems.push(`${id}: skipped (${row.reason}); a skipped row is never a pass`); continue; }
|
|
369
|
-
if (uncached) { if (row.coverage !== "ran") problems.push(`${id}: uncached family answered ${row.coverage}, expected ran`); continue; }
|
|
370
372
|
if (row.class === "A" && row.coverage !== "hit") problems.push(`${id}: Class A row ${row.coverage} on an unchanged commit, expected hit${row.key === null ? " (no cache key)" : ""}`);
|
|
371
373
|
if (row.class === "A" && row.coverage === "hit") hits += 1;
|
|
372
374
|
const before = prev.get(id);
|
|
@@ -383,7 +385,7 @@ export function assertWarmRerun(prev, next) {
|
|
|
383
385
|
*/
|
|
384
386
|
export function assertOneFileEdit(prev, next, { perFile = /^(secret-scan|licen[cs]e)/ } = {}) {
|
|
385
387
|
const problems = [];
|
|
386
|
-
const ranA = [...next.values()].filter((r) => r.class === "A" && r.coverage === "ran"
|
|
388
|
+
const ranA = [...next.values()].filter((r) => r.class === "A" && r.coverage === "ran");
|
|
387
389
|
const rustfmt = ranA.filter((r) => r.id.startsWith("rustfmt"));
|
|
388
390
|
if (rustfmt.length !== 1) problems.push(`${rustfmt.length} rustfmt rows ran, expected exactly 1 (${rustfmt.map((r) => r.id).join(", ")})`);
|
|
389
391
|
for (const r of ranA) if (!r.id.startsWith("rustfmt") && !perFile.test(r.id)) problems.push(`${r.id}: ran but does not read the edited file`);
|
|
@@ -604,6 +606,69 @@ export function launchSpec(gate, args, { platform = process.platform, comspec =
|
|
|
604
606
|
// ---------------------------------------------------------------------------------------------------------------------------------------------
|
|
605
607
|
// The run sequence (criteria.md section 3) and the clauses each step asserts.
|
|
606
608
|
// ---------------------------------------------------------------------------------------------------------------------------------------------
|
|
609
|
+
// ---------------------------------------------------------------------------------------------------------------------------------------------
|
|
610
|
+
// Non-negotiables NN01-NN19 (GATE-CONTRACT [GC-A27]). Adrian, 2026-11-05: "each implement like cache etc should be written into part of an e2e test i.e.
|
|
611
|
+
// final state. so anything that breaks it next time fails"; "no reruns, no repeat calls. no going over things that haven't changed. fully optimizations".
|
|
612
|
+
// `steps` are the S-steps that produce each one's evidence. A non-negotiable is never "unchecked" on a host that can run it: when its step ran, missing
|
|
613
|
+
// evidence is a failure with the reason; when its step was not selected (a `--steps` subset) it is "not-evaluated" and the verdict says the run is partial.
|
|
614
|
+
// ---------------------------------------------------------------------------------------------------------------------------------------------
|
|
615
|
+
export const NN = Object.freeze([
|
|
616
|
+
{ id: "NN01", steps: ["S2"], title: "An unchanged commit runs no Class A row", evidence: "warm --to check and --to compile coverage, twice" },
|
|
617
|
+
{ id: "NN02", steps: ["S2"], title: "An unchanged commit runs no Class B row", evidence: "warm --to compile coverage, twice" },
|
|
618
|
+
{ id: "NN03", steps: ["S3"], title: "One edited .rs file reruns only the rows that read it", evidence: "S3 coverage" },
|
|
619
|
+
{ id: "NN04", steps: ["S4"], title: "One edited manifest reruns only its workspace's rows", evidence: "S4 coverage" },
|
|
620
|
+
{ id: "NN05", steps: ["S2"], title: "Keys are stable across identical runs", evidence: "coverage keys of two warm runs of check and of compile" },
|
|
621
|
+
{ id: "NN06", steps: ["S1", "S2"], title: "Only executing rows carry the environment digest", evidence: "coverage keys, the log's env digest" },
|
|
622
|
+
{ id: "NN07", steps: ["S1", "S2", "S3", "S4", "S10"], title: "No identical child process twice in one run", evidence: "spawn ledger" },
|
|
623
|
+
{ id: "NN08", steps: ["S1", "S2", "S3", "S4", "S10"], title: "rustfmt is one process per bucket; no cargo fmt", evidence: "spawn ledger, coverage" },
|
|
624
|
+
{ id: "NN09", steps: ["S1", "S2", "S3", "S4", "S10"], title: "Non-compiling cargo never goes through the broker", evidence: "spawn ledger" },
|
|
625
|
+
{ id: "NN10", steps: ["S2"], title: "Inside a snapshot the resident gate answers cargo metadata", evidence: "spawn ledger of the warm runs" },
|
|
626
|
+
{ id: "NN11", steps: ["S1", "S2"], title: "A warm run proves the snapshot from the resident index, without re-hashing it", evidence: "gate log (`snapshot proof:` line)" },
|
|
627
|
+
{ id: "NN12", steps: ["S2"], title: "Installed dependencies are identified by pnpm's install record and reused", evidence: "gate log (reuse-match=hit), spawn ledger, env digest" },
|
|
628
|
+
{ id: "NN13", steps: ["S1", "S2", "S3", "S4", "S10"], title: "Class A takes no build-ownership lease", evidence: "gate log of every --to check" },
|
|
629
|
+
{ id: "NN14", steps: ["S2"], title: "Preflight and app rules run once per tree", evidence: "gate log of the warm runs" },
|
|
630
|
+
{ id: "NN15", steps: ["S2"], title: "Advice scans are cached per lock set and UTC day or hour", evidence: "warm coverage" },
|
|
631
|
+
{ id: "NN16", steps: ["S10"], title: "A unit list shares one Class A and runs no per-unit format check", evidence: "--units-file log, spawn ledger" },
|
|
632
|
+
{ id: "NN17", steps: ["S1", "S2"], title: "Class A lanes equal the host's cores; Class B batches compatible rows", evidence: "gate log, spawn ledger" },
|
|
633
|
+
{ id: "NN18", steps: ["S2"], title: "Warm time stays inside the host's budget", evidence: "run wall time and stamped log lines against ci/gate-acceptance-budgets.json" },
|
|
634
|
+
{ id: "NN19", steps: ["S0"], always: true, title: "The gate under test is the installed sealed gate", evidence: "--version, launcher" },
|
|
635
|
+
]);
|
|
636
|
+
export const NN_IDS = Object.freeze(NN.map((n) => n.id));
|
|
637
|
+
/** NN20-NN42 (GC-A27 as extended 2026-11-05). `post` ones are judged from the finished result (NN34, NN35). */
|
|
638
|
+
export const NN_EXT = Object.freeze([
|
|
639
|
+
{ id: "NN20", steps: ["S12"], title: "One edited crate recompiles only that crate and its dependents", evidence: "S12 crate-edit compile coverage" },
|
|
640
|
+
{ id: "NN21", steps: ["S12"], title: "One edited lockfile reruns only the rows that read it", evidence: "S12 lock-edit coverage" },
|
|
641
|
+
{ id: "NN22", steps: ["S2"], title: "A warm snapshot sync writes and removes nothing", evidence: "sync lines and spawn ledger of the warm runs" },
|
|
642
|
+
{ id: "NN23", steps: ["S13"], title: "A gate upgrade that changes no key-relevant code keeps every hit", evidence: "coverage of the previous and the newest sealed gate" },
|
|
643
|
+
{ id: "NN24", steps: ["S14"], title: "The cache survives the resident gate's restart and idle exit", evidence: "coverage of a run after the resident gate was killed" },
|
|
644
|
+
{ id: "NN25", steps: ["S2"], title: "A warm run starts no git-after-proof, version probe, pnpm, ownership probe or real cargo", evidence: "spawn ledger of the warm runs" },
|
|
645
|
+
{ id: "NN26", steps: ["S2"], title: "The gate asks the resident gate over its socket, in process", evidence: "spawn ledger" },
|
|
646
|
+
{ id: "NN27", steps: ["S1"], title: "Never two compiler passes over one crate, target and feature set", evidence: "S1 compile coverage" },
|
|
647
|
+
{ id: "NN28", steps: ["S2"], title: "Change detection comes from RightKit's file index and watcher", evidence: "gate log (change-source), spawn ledger" },
|
|
648
|
+
{ id: "NN29", steps: ["S16"], title: "Per-run identities never enter a key or a reuse record", evidence: "coverage keys of a run with different identities" },
|
|
649
|
+
{ id: "NN30", steps: ["S0"], always: true, title: "Both hosts pass", evidence: "the other host's contract-test receipt" },
|
|
650
|
+
{ id: "NN31", steps: ["S0"], always: true, title: "No gate is released or installed as trusted without a passing contract test", evidence: "release and install tooling calls --verify-release" },
|
|
651
|
+
{ id: "NN32", steps: ["S8"], title: "A killed run's ownership recovers by itself on both hosts", evidence: "S8 kill cases" },
|
|
652
|
+
{ id: "NN33", steps: ["S0"], always: true, title: "The contract and the test match", evidence: "docs/GATE-CONTRACT.md NN table" },
|
|
653
|
+
{ id: "NN34", steps: ["S0"], always: true, post: true, title: "Missing evidence fails; a partial run never passes", evidence: "the finished result" },
|
|
654
|
+
{ id: "NN35", steps: ["S0"], always: true, post: true, title: "The verdict shows coverage, and a release needs all of it", evidence: "the finished result, receipt" },
|
|
655
|
+
{ id: "NN36", steps: ["S0"], always: true, title: "The test is locked", evidence: "git history of the runner, the contract table, the budgets" },
|
|
656
|
+
{ id: "NN37", steps: ["S0"], always: true, title: "The test's author is not the implementer", evidence: "budgets.reviews" },
|
|
657
|
+
{ id: "NN38", steps: ["S1"], title: "Cross-target rows built with stand-ins are limited evidence", evidence: "coverage and receipt of the compile" },
|
|
658
|
+
{ id: "NN39", steps: ["S11"], title: "The parallelism is real, not configured", evidence: "spawn ledger start and end times of the cold runs" },
|
|
659
|
+
{ id: "NN40", steps: ["S2"], title: "Docs build as one command per workspace and feature round, on every compile", evidence: "spawn ledger and doc coverage rows of every compile run" },
|
|
660
|
+
{ id: "NN41", steps: ["S17"], title: "A deterministic failure is cached like a pass", evidence: "coverage of the failing commit run three times (same inputs twice, then a changed toolchain identity)" },
|
|
661
|
+
{ id: "NN42", steps: ["S2"], title: "Cross targets of one stage go in one broker command naming every --target", evidence: "spawn ledger and log of every compile run" },
|
|
662
|
+
]);
|
|
663
|
+
export const NN_ALL = Object.freeze([...NN, ...NN_EXT]);
|
|
664
|
+
export const NN_ALL_IDS = Object.freeze(NN_ALL.map((n) => n.id));
|
|
665
|
+
export const nnForStep = (stepId) => NN.filter((n) => n.steps.includes(stepId)).map((n) => n.id);
|
|
666
|
+
export const nnForStepAll = (stepId) => NN_ALL.filter((n) => n.steps.includes(stepId)).map((n) => n.id);
|
|
667
|
+
/** The labels of the four warm runs of S2 (two of check, two of compile), in run order. */
|
|
668
|
+
export const WARM_LABELS = Object.freeze(["S2:check", "S2:compile", "S2:check2", "S2:compile2"]);
|
|
669
|
+
export const BUDGETS_SCHEMA = "rightkit.gate-acceptance-budgets/1";
|
|
670
|
+
export const BUDGETS_FILE = path.resolve(here, "..", "..", "ci", "gate-acceptance-budgets.json");
|
|
671
|
+
|
|
607
672
|
export const LADDER = Object.freeze(["check", "compile", "test", "render", "dev", "package", "qualify"]);
|
|
608
673
|
/** Stages that install an app on the host; they run only with `--allow-install` (Adrian's approval), never by default. */
|
|
609
674
|
export const INSTALL_STAGES = Object.freeze(["dev", "qualify"]);
|
|
@@ -628,22 +693,31 @@ export const KILLS = Object.freeze([
|
|
|
628
693
|
{ id: "K01", signal: "SIGKILL", at: "owner record exists (build ownership held) plus --kill-after-ms, during --to compile", clauses: ["GC-T06"] },
|
|
629
694
|
{ id: "K01-int", signal: "SIGINT", at: "same point as K01", clauses: ["GC-T06"] },
|
|
630
695
|
{ id: "K02", signal: "SIGKILL", at: "during --to check, after the owner record exists (ownership is held across Class A by design, build-ownership.mjs:3-4)", clauses: ["GC-A24"] },
|
|
696
|
+
{ id: "K02-int", signal: "SIGINT", at: "same point as K02", clauses: ["GC-A24"] },
|
|
631
697
|
]);
|
|
632
698
|
export const KILLS_UNCHECKED = Object.freeze({
|
|
633
699
|
K03: "no defined kill point inside the snapshot sync is observable from outside the gate", K04: "the resident gate-serve process is not identifiable by the runner", K05: "needs a hook between broker submit and acknowledgement", K06: NEEDS_FIXTURE,
|
|
634
700
|
});
|
|
635
701
|
|
|
636
702
|
export const STEPS = Object.freeze([
|
|
637
|
-
{ id: "S0", title: "preflight (static)", runs: [], clauses: ["GC-I22", "GC-I18", "GC-I01", "GC-I15", "GC-T20"], note: "fixture clean, listings recorded, vector hashes, broker digest manifest vs pins" },
|
|
638
|
-
{ id: "S1", title: "baseline ladder on C0", runs: ladderStages().map((s) => `--to ${s}`), clauses: ["GC-A04", "GC-A15", "GC-A21", "GC-A22-render", "GC-A22-classA", "GC-A23", "GC-T04", "GC-T05", "GC-T19", "GC-I01", "GC-I03", "GC-I05"], note: "--to dev and --to qualify install an app: only with --allow-install (Adrian's approval); with it, --to qualify may refuse with a named release-tier rule, asserted as such" },
|
|
639
|
-
{ id: "S2", title: "warm rerun, same commit", runs: ["--to check", "--to compile"], clauses: ["GC-A24", "GC-A19", "GC-A21"], note: "Class A
|
|
640
|
-
{ id: "S3", title: "one-file edit (ephemeral commit)", runs: ["--to check"], clauses: ["GC-A24"], note: "needs a tracked rk/**/src/lib.rs (or --leaf-file); else unchecked" },
|
|
641
|
-
{ id: "S4", title: "manifest edit (ephemeral commit)", runs: ["--to check"], clauses: ["GC-A19"], note: "needs a tracked Cargo.toml (or --manifest-file); else unchecked" },
|
|
642
|
-
{ id: "S5", title: "lock edit", runs: [], clauses: ["GC-A19", "GC-A24"], note: "unchecked by design: a lock edit needs the fixture's own resolver; not generated by this runner", byDesignUnchecked: true },
|
|
643
|
-
{ id: "S6", title: "dirty checkout", runs: ["--to compile"], clauses: ["GC-A02", "GC-A04", "GC-T06"], note: "refuses a dirty fixture; ephemeral commit (a compile not yet recorded) built while the checkout has a dirty tracked edit, an untracked file and a pushed stash; the snapshot is compared with the commit; the checkout and the stash list are restored exactly" },
|
|
644
|
-
{ id: "S7", title: "negatives", runs: NEGATIVES.map((n) => n.id), clauses: ["GC-T05", "GC-A01", "GC-T14", "GC-A15", "GC-1A-R2", "GC-1A-R4"], note: "ephemeral commits under refs/witness/*; the rest listed unchecked with their reason" },
|
|
645
|
-
{ id: "S8", title: "kill and recover", runs: KILLS.map((k) => k.id), clauses: ["GC-T06", "GC-A24"], note: "SIGKILL (during compile and during Class A) and SIGINT; ownership-recover.mjs dry run must explain the record; the next run reclaims it and passes" },
|
|
646
|
-
{ id: "
|
|
703
|
+
{ id: "S0", nn: nnForStep("S0"), title: "preflight (static)", runs: [], clauses: ["GC-I22", "GC-I18", "GC-I01", "GC-I15", "GC-T20"], note: "fixture clean, listings recorded, vector hashes, broker digest manifest vs pins" },
|
|
704
|
+
{ id: "S1", nn: nnForStep("S1"), title: "baseline ladder on C0", runs: ladderStages().map((s) => `--to ${s}`), clauses: ["GC-A04", "GC-A15", "GC-A21", "GC-A22-render", "GC-A22-classA", "GC-A23", "GC-T04", "GC-T05", "GC-T19", "GC-I01", "GC-I03", "GC-I05"], note: "--to dev and --to qualify install an app: only with --allow-install (Adrian's approval); with it, --to qualify may refuse with a named release-tier rule, asserted as such" },
|
|
705
|
+
{ id: "S2", nn: nnForStep("S2"), title: "warm rerun, same commit (twice)", runs: ["--to check", "--to compile", "--to check", "--to compile"], clauses: ["GC-A24", "GC-A19", "GC-A21"], note: "every Class A row hits with its first-run key; no Class B row runs; the second pair of runs is the identical rerun NN05 compares" },
|
|
706
|
+
{ id: "S3", nn: nnForStep("S3"), title: "one-file edit (ephemeral commit)", runs: ["--to check"], clauses: ["GC-A24"], note: "needs a tracked rk/**/src/lib.rs (or --leaf-file); else unchecked" },
|
|
707
|
+
{ id: "S4", nn: nnForStep("S4"), title: "manifest edit (ephemeral commit)", runs: ["--to check"], clauses: ["GC-A19"], note: "needs a tracked Cargo.toml (or --manifest-file); else unchecked" },
|
|
708
|
+
{ id: "S5", nn: nnForStep("S5"), title: "lock edit", runs: [], clauses: ["GC-A19", "GC-A24"], note: "unchecked by design: a lock edit needs the fixture's own resolver; not generated by this runner", byDesignUnchecked: true },
|
|
709
|
+
{ id: "S6", nn: nnForStep("S6"), title: "dirty checkout", runs: ["--to compile"], clauses: ["GC-A02", "GC-A04", "GC-T06"], note: "refuses a dirty fixture; ephemeral commit (a compile not yet recorded) built while the checkout has a dirty tracked edit, an untracked file and a pushed stash; the snapshot is compared with the commit; the checkout and the stash list are restored exactly" },
|
|
710
|
+
{ id: "S7", nn: nnForStep("S7"), title: "negatives", runs: NEGATIVES.map((n) => n.id), clauses: ["GC-T05", "GC-A01", "GC-T14", "GC-A15", "GC-1A-R2", "GC-1A-R4"], note: "ephemeral commits under refs/witness/*; the rest listed unchecked with their reason" },
|
|
711
|
+
{ id: "S8", nn: nnForStep("S8"), title: "kill and recover", runs: KILLS.map((k) => k.id), clauses: ["GC-T06", "GC-A24"], note: "SIGKILL (during compile and during Class A) and SIGINT; ownership-recover.mjs dry run must explain the record; the next run reclaims it and passes" },
|
|
712
|
+
{ id: "S10", nn: nnForStep("S10"), title: "unit list (--units-file, two fixture units)", runs: ["--to check --units-file"], clauses: [], note: "NN16: the list shares one Class A and runs no cargo fmt -p; needs two units of the gate's unit grammar (crates/rightkit-<x>, packages/<x>) in the fixture, else NN16 fails naming the gap" },
|
|
713
|
+
{ id: "S11", nn: nnForStepAll("S11"), title: "cold run (the gate's cache dir moved aside under scratch, then restored)", runs: ["--to check", "--to compile"], clauses: [], note: "NN18 cold budgets; real-condition controls that NN01, NN02, NN03, NN04, NN14, NN15, NN20, NN21, NN24, NN29 fail on a run where every row really ran" },
|
|
714
|
+
{ id: "S12", nn: nnForStepAll("S12"), title: "compile-side edits: one crate, one lockfile, one manifest", runs: ["--to compile (crate edit)", "--to check (lock edit)", "--to compile (manifest edit)"], clauses: [], note: "ephemeral commits under refs/witness/*; NN20, NN21, NN04 on --to compile" },
|
|
715
|
+
{ id: "S13", nn: nnForStepAll("S13"), title: "gate upgrade: the two newest sealed gates run the same commit", runs: ["--to check (previous gate)", "--to check (newest gate)"], clauses: [], note: "NN23; with fewer than two sealed versions it FAILS: needs two installed versions" },
|
|
716
|
+
{ id: "S14", nn: nnForStepAll("S14"), title: "resident gate restart", runs: ["--to check"], clauses: [], note: "kills the resident gate (SIGTERM, a plain process stop), then a warm check must run no row (NN24)" },
|
|
717
|
+
{ id: "S15", nn: nnForStepAll("S15"), title: "workloads: RightKit and HeardRight warm check (read-only), Pulse compile with --pulse-compile", runs: ["--to check (rightkit)", "--to check (heardright)"], clauses: [], note: "NN18 per-workload budgets; no compile unless --pulse-compile" },
|
|
718
|
+
{ id: "S16", nn: nnForStepAll("S16"), title: "per-run identities differ", runs: ["--to check"], clauses: [], note: "NN29: a fake tool-call id, terminal session, temp dir and RK_GATE_* value; every key equals the warm run's" },
|
|
719
|
+
{ id: "S17", nn: nnForStepAll("S17"), title: "cached failure: a commit with a real compile error, run twice, then with another toolchain", runs: ["--to compile (failing commit)", "--to compile (same commit again)", "--to compile (RUSTUP_TOOLCHAIN changed)"], clauses: [], note: "NN41; ephemeral commit under refs/witness/* that adds compile_error! to one fixture crate; the second run's failing rows must be hit, the third (another installed toolchain) must run them again" },
|
|
720
|
+
{ id: "S9", nn: nnForStep("S9"), title: "end invariants", runs: [], clauses: ["GC-A01", "GC-A02", "GC-T14", "GC-T06", "GC-I15", "GC-T20"], note: "listings equal S0; one snapshot dir and no new one; one worktree; no upload; broker pid and start unchanged" },
|
|
647
721
|
]);
|
|
648
722
|
|
|
649
723
|
/** The plan `--plan` prints (and tests read): steps, runs and the clause mapping, with implemented vs unchecked. */
|
|
@@ -651,7 +725,8 @@ export function buildPlan({ steps = STEPS.map((s) => s.id), allowInstall = false
|
|
|
651
725
|
const chosen = STEPS.filter((s) => steps.includes(s.id));
|
|
652
726
|
const implemented = new Set(Object.keys(CHECKS));
|
|
653
727
|
const clauses = Object.values(CLAUSES).map((c) => ({ id: c.id, ev: c.ev, title: c.title, implemented: implemented.has(c.id), steps: chosen.filter((s) => s.clauses.includes(c.id)).map((s) => s.id), ...(implemented.has(c.id) ? {} : { unchecked: installReason(c.id, allowInstall) ?? UNCHECKED_WHY[c.id] ?? NO_EVIDENCE }) }));
|
|
654
|
-
|
|
728
|
+
const nonNegotiables = NN.map((n) => ({ id: n.id, title: n.title, steps: n.steps, evidence: n.evidence, selected: Boolean(n.always) || n.steps.every((x) => chosen.some((c) => c.id === x)) }));
|
|
729
|
+
return { schema: "rightkit.gate-acceptance-plan/1", allowInstall, installStagesSkipped: allowInstall ? [] : [...INSTALL_STAGES], steps: chosen, nonNegotiables, negativesUnchecked: NEGATIVES_UNCHECKED, killsUnchecked: KILLS_UNCHECKED, clauses };
|
|
655
730
|
}
|
|
656
731
|
|
|
657
732
|
/** The reason a clause that needs `--to dev` / `--to qualify` evidence is unchecked while installs are not approved; null otherwise. */
|
|
@@ -659,7 +734,7 @@ export const installReason = (id, allowInstall) => (!allowInstall && INSTALL_CLA
|
|
|
659
734
|
|
|
660
735
|
export function formatPlan(plan) {
|
|
661
736
|
const out = [];
|
|
662
|
-
for (const s of plan.steps) out.push(`${s.id} ${s.title}${s.runs.length ? ` [${s.runs.join(", ")}]` : ""}`, ` clauses: ${s.clauses.join(" ") || "-"}`, ` ${s.note}`);
|
|
737
|
+
for (const s of plan.steps) out.push(`${s.id} ${s.title}${s.runs.length ? ` [${s.runs.join(", ")}]` : ""}`, ` clauses: ${s.clauses.join(" ") || "-"}`, ` non-negotiables: ${s.nn?.join(" ") || "-"}${s.nn?.includes("NN19") ? " (evaluated in every run)" : ""}`, ` ${s.note}`);
|
|
663
738
|
const impl = plan.clauses.filter((c) => c.implemented);
|
|
664
739
|
const un = plan.clauses.filter((c) => !c.implemented);
|
|
665
740
|
out.push("", `clauses: ${plan.clauses.length} total, ${impl.length} asserted, ${un.length} unchecked by design`);
|
|
@@ -667,6 +742,10 @@ export function formatPlan(plan) {
|
|
|
667
742
|
out.push(`unchecked: ${un.map((c) => `${c.id}(${c.ev})`).join(" ")}`);
|
|
668
743
|
if (plan.installStagesSkipped?.length) out.push(`install stages not run: --to ${plan.installStagesSkipped.join(", --to ")} (they install an app; pass --allow-install only with Adrian's approval); clauses needing them: ${INSTALL_CLAUSES.join(" ")}`);
|
|
669
744
|
out.push(`negatives not built: ${Object.keys(plan.negativesUnchecked).join(" ")}`, `kills not built: ${Object.keys(plan.killsUnchecked).join(" ")}`);
|
|
745
|
+
out.push("", `non-negotiables (${(plan.nonNegotiables ?? []).length}; never unchecked on a host that can run them: missing evidence fails the run):`);
|
|
746
|
+
for (const n of plan.nonNegotiables ?? []) out.push(` ${n.id} steps ${n.steps.join("+")}${n.selected ? "" : " (not selected)"} ${n.title} [${n.evidence}]`);
|
|
747
|
+
out.push("", `extended non-negotiables NN20-NN42 (${NN_EXT.length}):`);
|
|
748
|
+
for (const n of NN_EXT) out.push(` ${n.id} steps ${n.steps.join("+")}${n.always ? " (every run)" : ""} ${n.title} [${n.evidence}]`);
|
|
670
749
|
return out.join("\n");
|
|
671
750
|
}
|
|
672
751
|
|
|
@@ -696,6 +775,1236 @@ export function ruleTierProblems(receipt, stage) {
|
|
|
696
775
|
return tier === want ? { ok: true, problems: [] } : { ok: false, problems: [`receipt.stages.check.ruleTier is ${JSON.stringify(tier)}, expected ${JSON.stringify(want)} for --to ${stage}`] };
|
|
697
776
|
}
|
|
698
777
|
|
|
778
|
+
// ---------------------------------------------------------------------------------------------------------------------------------------------
|
|
779
|
+
// Non-negotiable assertions (pure). Each returns { ok, problems[] } and fails closed: evidence that is missing is a problem, never a pass.
|
|
780
|
+
// ---------------------------------------------------------------------------------------------------------------------------------------------
|
|
781
|
+
|
|
782
|
+
/** One ledger line per child process (spawn-ledger.mjs): {pid, at, ms, sync, cmd, args[], cwd, status}. Malformed lines are problems. */
|
|
783
|
+
export function parseLedger(text) {
|
|
784
|
+
const entries = []; const problems = [];
|
|
785
|
+
String(text ?? "").split(/\r?\n/).forEach((line, i) => {
|
|
786
|
+
if (!line.trim()) return;
|
|
787
|
+
try {
|
|
788
|
+
const e = JSON.parse(line);
|
|
789
|
+
if (!isObject(e) || typeof e.cmd !== "string" || !Array.isArray(e.args) || typeof e.cwd !== "string") throw new Error("not a ledger entry {cmd, args[], cwd}");
|
|
790
|
+
entries.push(e);
|
|
791
|
+
} catch (err) { problems.push(`ledger line ${i + 1}: ${err.message}`); }
|
|
792
|
+
});
|
|
793
|
+
return { entries, problems };
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
/** The program name of a ledger command: its basename without a Windows launcher suffix. */
|
|
797
|
+
export const programOf = (cmd) => String(cmd).replace(/\\/g, "/").split("/").pop().replace(/\.(exe|cmd|bat)$/i, "");
|
|
798
|
+
|
|
799
|
+
/** `{ program, args, cwd }` of an entry. A shell-string start (execSync: cmd holds the whole line, args is empty) is split on whitespace. */
|
|
800
|
+
export function normalizeSpawn(e) {
|
|
801
|
+
const args = e.args.map(String);
|
|
802
|
+
if (args.length === 0 && /\s/.test(String(e.cmd).trim())) { const [first, ...rest] = String(e.cmd).trim().split(/\s+/); return { program: programOf(first), args: rest, cwd: e.cwd, shim: false }; }
|
|
803
|
+
return { program: programOf(e.cmd), args, cwd: e.cwd, shim: /rk-cargo-shim/.test(String(e.cmd)) };
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
const CARGO_VALUE_FLAGS = new Set(["-C", "-Z", "--config", "--color", "--manifest-path"]);
|
|
807
|
+
/** The cargo subcommand a start carries and how it is routed: `{ via: "cargo"|"shim"|"rustright", sub }`, or null when the start is no cargo call. */
|
|
808
|
+
export function cargoCall(entry) {
|
|
809
|
+
const n = entry.program ? entry : normalizeSpawn(entry);
|
|
810
|
+
let rest;
|
|
811
|
+
let via;
|
|
812
|
+
if (n.program === "cargo-fmt") return { via: "cargo", sub: "fmt" };
|
|
813
|
+
if (n.program === "rustright") { const i = n.args.indexOf("cargo"); if (i < 0) return null; rest = n.args.slice(i + 1); via = "rustright"; }
|
|
814
|
+
else if (n.program === "cargo") { rest = n.args; via = n.shim ? "shim" : "cargo"; }
|
|
815
|
+
else return null;
|
|
816
|
+
for (let i = 0; i < rest.length; i += 1) {
|
|
817
|
+
const a = rest[i];
|
|
818
|
+
if (a.startsWith("+")) continue;
|
|
819
|
+
if (CARGO_VALUE_FLAGS.has(a)) { i += 1; continue; }
|
|
820
|
+
if (a.startsWith("-")) continue;
|
|
821
|
+
return { via, sub: a };
|
|
822
|
+
}
|
|
823
|
+
return { via, sub: null };
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
/** The allowlist of NN07: probes that truly must repeat inside one gate invocation. Each entry names its program, its exact args and a reason. Empty by decision: nothing in the code needs a repeat. */
|
|
827
|
+
// EMPTY by decision: any entry needs Adrian's approval by name (GC-A27 NN07/NN25). Do not add one without it.
|
|
828
|
+
export const NN07_ALLOWLIST = Object.freeze([]);
|
|
829
|
+
|
|
830
|
+
/** NN07: per-run parts of an argument or directory (temp dirs of probes and shims, the temp root, pid values) are normalised before two starts are compared. */
|
|
831
|
+
export const normalizeRunPart = (s) => String(s).replace(/(rk-probe-|rk-gate-shim-|rk-cargo-shim-)[A-Za-z0-9_-]+/g, "$1*").replace(/\/var\/folders\/[^/]+\/[^/]+\/T\//g, "$TMP/").replace(/\b(pid|PID)([= :]?)\d+/g, "$1$2*");
|
|
832
|
+
const spawnKey = (n) => `${n.program}\u0000${n.args.map(normalizeRunPart).join("\u0000")}\u0000${normalizeRunPart(n.cwd)}`;
|
|
833
|
+
const shortArgs = (args) => args.join(" ").replace(/\s+/g, " ").slice(0, 150);
|
|
834
|
+
|
|
835
|
+
/** NN07: the same program basename with the same arguments in the same directory starts once per gate invocation (parent and children together). */
|
|
836
|
+
export function assertNoDuplicateSpawns(entries, { allow = NN07_ALLOWLIST } = {}) {
|
|
837
|
+
const problems = [];
|
|
838
|
+
for (const a of allow) if (!isObject(a) || typeof a.program !== "string" || !Array.isArray(a.args) || typeof a.reason !== "string" || !a.reason.trim()) problems.push(`NN07 allowlist entry without program, args and a reason: ${JSON.stringify(a)}`);
|
|
839
|
+
const allowed = new Set(allow.filter((a) => isObject(a) && typeof a.reason === "string" && a.reason.trim()).map((a) => `${a.program}\u0000${(a.args ?? []).join("\u0000")}`));
|
|
840
|
+
const seen = new Map();
|
|
841
|
+
for (const e of entries) {
|
|
842
|
+
const n = normalizeSpawn(e);
|
|
843
|
+
if (allowed.has(`${n.program}\u0000${n.args.join("\u0000")}`)) continue;
|
|
844
|
+
const k = spawnKey(n);
|
|
845
|
+
const prev = seen.get(k);
|
|
846
|
+
if (prev) prev.count += 1; else seen.set(k, { count: 1, n });
|
|
847
|
+
}
|
|
848
|
+
const repeats = [...seen.values()].filter((v) => v.count > 1).sort((a, b) => b.count - a.count);
|
|
849
|
+
for (const v of repeats.slice(0, 25)) problems.push(`${v.count}x ${v.n.program} ${shortArgs(v.n.args)} (cwd ${v.n.cwd})`);
|
|
850
|
+
if (repeats.length > 25) problems.push(`... and ${repeats.length - 25} more repeated start(s)`);
|
|
851
|
+
if (repeats.length) problems.unshift(`${repeats.length} identical child process(es) started more than once (${repeats.reduce((s, v) => s + v.count - 1, 0)} redundant start(s) of ${entries.length})`);
|
|
852
|
+
return { ok: problems.length === 0, problems, distinct: seen.size, starts: entries.length, repeats: repeats.length };
|
|
853
|
+
}
|
|
854
|
+
|
|
855
|
+
const RUSTFMT_PROBE = /^(--version|-V|-v|--help|-h)$/;
|
|
856
|
+
/** NN08: no `cargo fmt` (through cargo, the shim or rustright), and rustfmt formats once per bucket that ran (a `--version` probe is not a format). `rows` is the run's coverage map. */
|
|
857
|
+
export function assertRustfmtSpawns(entries, rows) {
|
|
858
|
+
const problems = [];
|
|
859
|
+
if (!rows) problems.push("no coverage rows: the rustfmt buckets that ran cannot be counted");
|
|
860
|
+
const ns = entries.map(normalizeSpawn);
|
|
861
|
+
const fmt = ns.filter((n) => cargoCall(n)?.sub === "fmt");
|
|
862
|
+
for (const n of fmt.slice(0, 5)) problems.push(`cargo fmt started: ${n.program} ${shortArgs(n.args)} (cwd ${n.cwd})`);
|
|
863
|
+
const buckets = rows ? [...rows.values()].filter((r) => /^rustfmt(:|$)/.test(r.id) && r.coverage === "ran").length : 0;
|
|
864
|
+
const formats = ns.filter((n) => n.program === "rustfmt" && !(n.args.length === 1 && RUSTFMT_PROBE.test(n.args[0])));
|
|
865
|
+
if (rows && formats.length > buckets) problems.push(`${formats.length} rustfmt process(es) formatted for ${buckets} rustfmt bucket(s) that ran: ${formats.slice(0, 3).map((n) => shortArgs(n.args)).join(" | ")}`);
|
|
866
|
+
return { ok: problems.length === 0, problems, formats: formats.length, buckets };
|
|
867
|
+
}
|
|
868
|
+
|
|
869
|
+
export const BROKER_FORBIDDEN_CARGO = Object.freeze(["metadata", "fetch", "tree", "locate-project", "pkgid", "verify-project", "read-manifest"]);
|
|
870
|
+
/** NN09: `rustright cargo <non-compiling subcommand>` (or the gate's shim, which carries into the broker) never starts. */
|
|
871
|
+
export function assertNoBrokerNonCompiling(entries) {
|
|
872
|
+
const problems = [];
|
|
873
|
+
for (const e of entries) {
|
|
874
|
+
const n = normalizeSpawn(e); const c = cargoCall(n);
|
|
875
|
+
if (c && c.via !== "cargo" && c.sub && BROKER_FORBIDDEN_CARGO.includes(c.sub)) problems.push(`${c.via === "rustright" ? "rustright cargo" : "shim cargo"} ${c.sub} went through the broker: ${shortArgs(n.args)} (cwd ${n.cwd})`);
|
|
876
|
+
}
|
|
877
|
+
return { ok: problems.length === 0, problems };
|
|
878
|
+
}
|
|
879
|
+
|
|
880
|
+
/** NN10: a warm run starts no real `cargo metadata` (direct, shim or broker) for the unchanged snapshot: the resident gate answers it. */
|
|
881
|
+
export function assertNoRealCargoMetadata(entries) {
|
|
882
|
+
const problems = [];
|
|
883
|
+
const hits = entries.map(normalizeSpawn).filter((n) => cargoCall(n)?.sub === "metadata");
|
|
884
|
+
if (hits.length) problems.push(`${hits.length} real cargo metadata start(s) in a warm run: ${[...new Set(hits.map((n) => n.cwd))].slice(0, 6).join(", ")}`);
|
|
885
|
+
return { ok: problems.length === 0, problems, starts: hits.length };
|
|
886
|
+
}
|
|
887
|
+
|
|
888
|
+
/** `snapshot proof: tree-hashes=<n> verify-walks=<n> resident-proofs=<n>`: the line the gate must print once per run that touches a snapshot (the evidence NN11 needs). */
|
|
889
|
+
export const SNAPSHOT_PROOF = /snapshot proof: tree-hashes=(\d+) verify-walks=(\d+) resident-proofs=(\d+)/;
|
|
890
|
+
/** NN11: the snapshot tree is hashed at most once per run, and a warm run walks it never (the resident index proves it). */
|
|
891
|
+
export function assertSnapshotProof(log, { warm }) {
|
|
892
|
+
const problems = [];
|
|
893
|
+
const m = SNAPSHOT_PROOF.exec(String(log));
|
|
894
|
+
if (!m) return { ok: false, problems: ["the log has no `snapshot proof: tree-hashes=<n> verify-walks=<n> resident-proofs=<n>` line: the gate does not report how often it hashed or walked the snapshot, so NN11 cannot be judged"] };
|
|
895
|
+
const [hashes, walks, resident] = [Number(m[1]), Number(m[2]), Number(m[3])];
|
|
896
|
+
if (hashes > 1) problems.push(`the snapshot tree was hashed ${hashes} times in one run, at most 1 is allowed`);
|
|
897
|
+
if (warm && walks > 0) problems.push(`a warm run walked the snapshot ${walks} time(s) to verify it (${resident} resident proof(s)); the resident index must prove it`);
|
|
898
|
+
if (warm && resident < 1) problems.push("a warm run reports no resident proof of the snapshot");
|
|
899
|
+
return { ok: problems.length === 0, problems, hashes, walks, resident };
|
|
900
|
+
}
|
|
901
|
+
|
|
902
|
+
const DEP_LINE = /snapshot dependencies root=(\S+)(.*)$/gm;
|
|
903
|
+
/** The `env=` digest of the log's `class A bytes ...` line, and `env-at-start=`; null when the line is absent. */
|
|
904
|
+
export function envDigestOf(log) {
|
|
905
|
+
const line = /class A bytes [^\n]*/.exec(String(log))?.[0];
|
|
906
|
+
if (!line) return null;
|
|
907
|
+
return { env: /\benv=([0-9a-f]{64})/.exec(line)?.[1] ?? null, start: /\benv-at-start=([0-9a-f]{64})/.exec(line)?.[1] ?? null };
|
|
908
|
+
}
|
|
909
|
+
/** NN12: every installed root's record matched (`reuse-match=hit`), no `pnpm install` started, and the dependency digest did not change inside the run. */
|
|
910
|
+
export function assertDependencyReuse(log, entries) {
|
|
911
|
+
const problems = [];
|
|
912
|
+
const roots = [...String(log).matchAll(DEP_LINE)].filter((m) => !/ not installed:/.test(m[2]));
|
|
913
|
+
if (roots.length === 0) problems.push("the log has no `snapshot dependencies root=...` line for an installed root");
|
|
914
|
+
for (const m of roots) { const v = /reuse-match=(\S+)/.exec(m[2])?.[1]; if (v !== "hit") problems.push(`root ${m[1]}: reuse-match=${v ?? "(absent)"}, expected hit`); }
|
|
915
|
+
const installs = entries.map(normalizeSpawn).filter((n) => n.program === "pnpm" && n.args.includes("install"));
|
|
916
|
+
for (const n of installs.slice(0, 3)) problems.push(`pnpm install started on a warm run (cwd ${n.cwd})`);
|
|
917
|
+
const d = envDigestOf(log);
|
|
918
|
+
if (!d || !d.env || !d.start) problems.push("the log has no `class A bytes ... env-at-start=<digest> env=<digest>` line");
|
|
919
|
+
else if (d.env !== d.start) problems.push(`the dependency digest changed during the run (env-at-start ${d.start.slice(0, 12)} -> env ${d.env.slice(0, 12)})`);
|
|
920
|
+
return { ok: problems.length === 0, problems };
|
|
921
|
+
}
|
|
922
|
+
/** NN12 (two identical runs): the dependency digest is the same. */
|
|
923
|
+
export function assertDigestStable(a, b) {
|
|
924
|
+
const da = envDigestOf(a); const db = envDigestOf(b);
|
|
925
|
+
if (!da?.env || !db?.env) return { ok: false, problems: ["a warm run's log has no `class A bytes ... env=<digest>` line"] };
|
|
926
|
+
return da.env === db.env ? { ok: true, problems: [] } : { ok: false, problems: [`the dependency digest differs between identical runs: ${da.env.slice(0, 12)} vs ${db.env.slice(0, 12)}`] };
|
|
927
|
+
}
|
|
928
|
+
|
|
929
|
+
/** NN13: a `--to check` log never reports build ownership held or joined. */
|
|
930
|
+
export function assertNoOwnershipOnCheck(log) {
|
|
931
|
+
const lines = String(log).split(/\r?\n/).filter((l) => /build ownership (held|joined) /.test(l));
|
|
932
|
+
return lines.length === 0 ? { ok: true, problems: [] } : { ok: false, problems: [`--to check took the build-ownership lease: ${lines[0].replace(/^\S+ /, "").slice(0, 120)}`] };
|
|
933
|
+
}
|
|
934
|
+
|
|
935
|
+
/** NN14: a warm run reports the app rules cached, and any preflight line it prints says cached too. */
|
|
936
|
+
export function assertRulesCached(log) {
|
|
937
|
+
const problems = [];
|
|
938
|
+
const text = String(log);
|
|
939
|
+
if (!/app rules: cached pass/.test(text)) problems.push("the log has no `app rules: cached pass` line: the app rules ran again on an unchanged tree");
|
|
940
|
+
for (const l of text.split(/\r?\n/)) if (/\bpreflight: /.test(l) && !/cached pass/.test(l)) problems.push(`preflight ran again on an unchanged tree: ${l.replace(/^\S+ /, "").slice(0, 120)}`);
|
|
941
|
+
return { ok: problems.length === 0, problems };
|
|
942
|
+
}
|
|
943
|
+
|
|
944
|
+
export const ADVICE_ROW = /^(dependency-freshness|ghsa-audit|pnpm-audit|cargo-deny|cargo-audit)(:|$)/;
|
|
945
|
+
const utcDay = (iso) => String(iso).slice(0, 10); const utcHour = (iso) => String(iso).slice(0, 13);
|
|
946
|
+
/**
|
|
947
|
+
* NN15: no advice scan runs on a warm run of the same UTC day. The one exception is a row whose key moved while the two runs straddle a UTC day or hour
|
|
948
|
+
* boundary (the key carries the day or hour). `startedAt`/`prevStartedAt` are the coverage reports' own timestamps.
|
|
949
|
+
*/
|
|
950
|
+
export function assertAdviceCached(prev, next, { startedAt, prevStartedAt } = {}) {
|
|
951
|
+
const problems = [];
|
|
952
|
+
const advice = [...next.values()].filter((r) => ADVICE_ROW.test(r.id));
|
|
953
|
+
if (advice.length === 0) problems.push("no advice rows (dependency-freshness, ghsa-audit, pnpm-audit, cargo-deny, cargo-audit) in the warm run's coverage");
|
|
954
|
+
const crossed = Boolean(startedAt && prevStartedAt && (utcDay(startedAt) !== utcDay(prevStartedAt) || utcHour(startedAt) !== utcHour(prevStartedAt)));
|
|
955
|
+
for (const r of advice) {
|
|
956
|
+
if (r.coverage === "skipped" && r.status !== "not-in-pass") problems.push(`${r.id}: skipped (${r.reason})`);
|
|
957
|
+
if (r.coverage !== "ran") continue;
|
|
958
|
+
const before = prev?.get(r.id);
|
|
959
|
+
if (crossed && before && before.key !== r.key) continue;
|
|
960
|
+
problems.push(`${r.id}: ran on a warm run of the same UTC day${r.key === null ? " (no cache key)" : before && before.key === r.key ? " with the key it already had" : ""}`);
|
|
961
|
+
}
|
|
962
|
+
return { ok: problems.length === 0, problems, advice: advice.length };
|
|
963
|
+
}
|
|
964
|
+
|
|
965
|
+
/** NN16: a unit list runs Class A once (one coverage report; the later units say it is not run again) and starts no `cargo fmt`. */
|
|
966
|
+
export function assertUnitListShare(log, entries, { units }) {
|
|
967
|
+
const problems = [];
|
|
968
|
+
if (!Number.isInteger(units) || units < 2) problems.push(`the unit list names ${units} unit(s), NN16 needs two`);
|
|
969
|
+
const reports = coveragePaths(log).length;
|
|
970
|
+
if (reports !== 1) problems.push(`Class A produced ${reports} coverage report(s) for the unit list, expected exactly 1`);
|
|
971
|
+
const memo = String(log).split(/\r?\n/).filter((l) => /class A \(\w+ tier\) of this unit list already (passed|failed)[^\n]*not run again/.test(l)).length;
|
|
972
|
+
if (units >= 2 && memo < units - 1) problems.push(`${memo} later unit(s) reused the shared Class A, expected ${units - 1}`);
|
|
973
|
+
for (const n of entries.map(normalizeSpawn)) { const c = cargoCall(n); if (c?.sub === "fmt") problems.push(`cargo fmt started for a unit list: ${n.program} ${shortArgs(n.args)}`); }
|
|
974
|
+
return { ok: problems.length === 0, problems, reports, memo };
|
|
975
|
+
}
|
|
976
|
+
|
|
977
|
+
/** NN17 lanes: every Class A plan line reports as many lanes as the host has cores. */
|
|
978
|
+
export function assertLanes(log, { cores, jobsOverride = undefined }) {
|
|
979
|
+
const problems = [];
|
|
980
|
+
if (jobsOverride !== undefined && jobsOverride !== "") problems.push(`RK_GATE_JOBS=${jobsOverride} is set in the runner's environment: the lane count is not the default`);
|
|
981
|
+
const lanes = [...String(log).matchAll(/class A scans (\d+) at a time/g)].map((m) => Number(m[1]));
|
|
982
|
+
if (lanes.length === 0) problems.push("the log has no `class A scans N at a time` line");
|
|
983
|
+
for (const n of lanes) if (n !== cores) problems.push(`class A ran ${n} lane(s) on a ${cores}-core host`);
|
|
984
|
+
return { ok: problems.length === 0, problems, lanes };
|
|
985
|
+
}
|
|
986
|
+
const COMPILING_CARGO = new Set(["check", "clippy", "build", "test", "doc", "rustc", "nextest", "run", "bench"]);
|
|
987
|
+
/** NN17 batching: the compile log reports shared groups, and the number of compiling cargo starts stays within the groups plus the named solo scans. */
|
|
988
|
+
export function assertBatching(log, entries, { exit }) {
|
|
989
|
+
const problems = [];
|
|
990
|
+
const text = String(log);
|
|
991
|
+
const note = /class B batching: (\d+) compile scan\(s\) in (\d+) configuration group\(s\)[^\n]*?\((\d+) scan\(s\) in (\d+) shared group\(s\)\)/.exec(text);
|
|
992
|
+
if (!note) return { ok: false, problems: ["the compile log has no `class B batching: N compile scan(s) in G configuration group(s) ... (M scan(s) in K shared group(s))` note"] };
|
|
993
|
+
const [scans, groups, shared, sharedGroups] = note.slice(1).map(Number);
|
|
994
|
+
const solo = [...text.matchAll(/class B batching: (\d+) compile scan\(s\) stay their own invocation/g)].reduce((s, m) => s + Number(m[1]), 0);
|
|
995
|
+
if (scans >= 2 && (shared === 0 || sharedGroups === 0)) problems.push(`${scans} Class B scans planned and no compatible group was batched (${shared} scan(s) in ${sharedGroups} shared group(s))`);
|
|
996
|
+
if (exit === 0) {
|
|
997
|
+
const invocations = entries.map(normalizeSpawn).filter((n) => { const c = cargoCall(n); return c && c.via !== "cargo" && COMPILING_CARGO.has(c.sub); });
|
|
998
|
+
if (invocations.length > groups + solo) problems.push(`${invocations.length} compiling cargo invocation(s) for ${groups} configuration group(s) and ${solo} solo scan(s): a compatible group ran as separate invocations`);
|
|
999
|
+
}
|
|
1000
|
+
return { ok: problems.length === 0, problems, scans, groups, shared, sharedGroups, solo };
|
|
1001
|
+
}
|
|
1002
|
+
|
|
1003
|
+
const EXECUTING_ROW = /^(tsc|eslint|biome|vitest|test|generated-docs|swift-typecheck|pnpm-lockfile|pnpm-audit|pnpm)(:|$)/;
|
|
1004
|
+
/** Whether a Class A row executes repository code or installed dependencies and may therefore carry the environment digest (gate: `executes` or tool pnpm). */
|
|
1005
|
+
export const isExecutingRow = (id) => EXECUTING_ROW.test(id);
|
|
1006
|
+
/** Whether a coverage key carries one of the environment digests (verbatim, or as the value of a property named like env). */
|
|
1007
|
+
export function keyCarriesEnvironment(key, digests) {
|
|
1008
|
+
if (typeof key !== "string") return false;
|
|
1009
|
+
for (const d of digests) if (key.includes(d) || key.includes(d.slice(0, 32))) return true;
|
|
1010
|
+
try {
|
|
1011
|
+
const walk = (v, name) => {
|
|
1012
|
+
if (typeof v === "string") return /env/i.test(name) && /^[0-9a-f]{32,64}$/.test(v);
|
|
1013
|
+
if (Array.isArray(v)) return v.some((x) => walk(x, name));
|
|
1014
|
+
if (isObject(v)) return Object.entries(v).some(([k, x]) => walk(x, k));
|
|
1015
|
+
return false;
|
|
1016
|
+
};
|
|
1017
|
+
return walk(JSON.parse(key), "");
|
|
1018
|
+
} catch { return false; }
|
|
1019
|
+
}
|
|
1020
|
+
/** NN06: no non-executing row's key carries the environment digest. `digests` are the env digests the runs' logs print. */
|
|
1021
|
+
export function assertEnvDigestScope(rows, digests) {
|
|
1022
|
+
const problems = [];
|
|
1023
|
+
if (digests.length === 0) return { ok: false, problems: ["no run log prints a class A `env=<digest>`: the digest a non-executing key must not carry cannot be identified"] };
|
|
1024
|
+
for (const r of rows.values()) {
|
|
1025
|
+
if (r.class !== "A" || r.coverage === "skipped" || isExecutingRow(r.id)) continue;
|
|
1026
|
+
if (keyCarriesEnvironment(r.key, digests)) problems.push(`${r.id}: a non-executing row's key carries the environment digest`);
|
|
1027
|
+
}
|
|
1028
|
+
return { ok: problems.length === 0, problems };
|
|
1029
|
+
}
|
|
1030
|
+
|
|
1031
|
+
/** NN05: two identical runs give every row the same key. A scan answered in only one run, or one without a key, cannot show stability and fails. */
|
|
1032
|
+
export function assertKeysStable(a, b) {
|
|
1033
|
+
const problems = [];
|
|
1034
|
+
const answered = (r) => r && !(r.coverage === "skipped" && r.status === "not-in-pass");
|
|
1035
|
+
for (const id of new Set([...a.keys(), ...b.keys()])) {
|
|
1036
|
+
const x = a.get(id); const y = b.get(id);
|
|
1037
|
+
if (!answered(x) && !answered(y)) continue;
|
|
1038
|
+
if (!answered(x) || !answered(y)) { problems.push(`${id}: present in only one of the two runs`); continue; }
|
|
1039
|
+
if (x.coverage === "skipped" && y.coverage === "skipped") continue;
|
|
1040
|
+
if (x.key === null || y.key === null) { problems.push(`${id}: no cache key in ${x.key === null ? "the first" : "the second"} run, so its stability cannot be shown`); continue; }
|
|
1041
|
+
if (x.key !== y.key) problems.push(`${id}: key differs between identical runs`);
|
|
1042
|
+
}
|
|
1043
|
+
return { ok: problems.length === 0, problems };
|
|
1044
|
+
}
|
|
1045
|
+
|
|
1046
|
+
/** NN01: no Class A row ran on an unchanged commit. */
|
|
1047
|
+
export function assertNoClassARan(rows) {
|
|
1048
|
+
const ran = [...rows.values()].filter((r) => r.class === "A" && r.coverage === "ran");
|
|
1049
|
+
return { ok: ran.length === 0, problems: ran.map((r) => `${r.id}: Class A row ran on an unchanged commit (${r.reason})`), ran: ran.map((r) => r.id) };
|
|
1050
|
+
}
|
|
1051
|
+
/** NN02: no Class B row ran on an unchanged commit. A row that failed in `prev` and fails again is reported in `reported`, never counted as a pass of the run. */
|
|
1052
|
+
export function assertNoClassBRan(rows, prev = null, { strict = false } = {}) {
|
|
1053
|
+
const problems = []; const reported = [];
|
|
1054
|
+
const b = [...rows.values()].filter((r) => r.class === "B");
|
|
1055
|
+
if (b.length === 0) problems.push("the compile coverage has no Class B row");
|
|
1056
|
+
for (const r of b) {
|
|
1057
|
+
if (r.coverage !== "ran") continue;
|
|
1058
|
+
const before = prev?.get(r.id);
|
|
1059
|
+
if (!strict && r.status === "fail" && before?.status === "fail") { reported.push(`${r.id}: failed before and still fails (reported, not re-run silently)`); continue; }
|
|
1060
|
+
problems.push(`${r.id}: Class B row ran on an unchanged commit (${r.status})`);
|
|
1061
|
+
}
|
|
1062
|
+
return { ok: problems.length === 0, problems, reported };
|
|
1063
|
+
}
|
|
1064
|
+
|
|
1065
|
+
const WORKSPACE_FAMILY = /^(cargo-metadata|cargo-deny|cargo-audit|ghsa-audit|cargo-package-list|clippy|check)(:|$)/;
|
|
1066
|
+
/** NN04: after a manifest edit no workspace-scoped row of another workspace ran. */
|
|
1067
|
+
export function assertOtherWorkspacesIdle(next, { workspace, workspaces = [], crates = {} }) {
|
|
1068
|
+
const problems = [];
|
|
1069
|
+
if (typeof workspace !== "string") return { ok: false, problems: ["the edited manifest's workspace is not known"] };
|
|
1070
|
+
const wsOf = (label) => (workspaces.includes(label) ? label : workspaces.find((w) => w === `crates/${label}`) ?? Object.entries(crates).find(([, names]) => names.includes(label.includes(":") ? label.slice(label.lastIndexOf(":") + 1) : label))?.[0] ?? null);
|
|
1071
|
+
let seenOwn = false;
|
|
1072
|
+
for (const r of next.values()) {
|
|
1073
|
+
const m = WORKSPACE_FAMILY.exec(r.id);
|
|
1074
|
+
if (!m) continue;
|
|
1075
|
+
const label = r.id.slice(m[0].length);
|
|
1076
|
+
const ws = m[1] === "cargo-metadata" && r.id === "cargo-metadata" ? "." : wsOf(label);
|
|
1077
|
+
if (ws === workspace) seenOwn = true;
|
|
1078
|
+
if (r.coverage !== "ran") continue;
|
|
1079
|
+
if (ws === null) problems.push(`${r.id}: ran and belongs to no known workspace`);
|
|
1080
|
+
else if (ws !== workspace) problems.push(`${r.id}: a row of workspace ${JSON.stringify(ws)} ran for an edit in workspace ${JSON.stringify(workspace)}`);
|
|
1081
|
+
}
|
|
1082
|
+
if (!seenOwn) problems.push(`no workspace-scoped row of ${JSON.stringify(workspace)} exists in the run`);
|
|
1083
|
+
return { ok: problems.length === 0, problems };
|
|
1084
|
+
}
|
|
1085
|
+
|
|
1086
|
+
// ---- NN18: budgets and stage timings -------------------------------------------------------------------------------------------------------
|
|
1087
|
+
|
|
1088
|
+
const stampOf = (line) => { const m = /^(\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?Z) /.exec(line); return m ? Date.parse(m[1]) : null; };
|
|
1089
|
+
/**
|
|
1090
|
+
* Stage durations from the stamped log. The line pairs (also written into ci/gate-acceptance-budgets.json):
|
|
1091
|
+
* ownership run start (the runner's launch time) -> first `build ownership held|joined` line; 0 when the run takes no lease (a `--to check`, NN13)
|
|
1092
|
+
* snapshotSync ownership line (else run start) -> `snapshot <dir> is commit <sha> tree <sha> (written=...` line
|
|
1093
|
+
* planning `rightkit-gate: --to <stage> for <sha12>: ...` line -> `<n> scan(s) for <m> changed file(s) vs <sha12>; class A scans <j> at a time` line
|
|
1094
|
+
* dependencyStep that plan line -> the first `snapshot dependencies root=` line (a compile prints a second one later, after Class A)
|
|
1095
|
+
* A named line that is missing is a problem (the stage cannot be timed), except the ownership line, whose absence is the stage being 0.
|
|
1096
|
+
*/
|
|
1097
|
+
export function stageMarks(log, startedMs) {
|
|
1098
|
+
const lines = String(log).split(/\r?\n/);
|
|
1099
|
+
const first = (re) => lines.find((l) => re.test(l));
|
|
1100
|
+
const last = (re) => [...lines].reverse().find((l) => re.test(l));
|
|
1101
|
+
const problems = [];
|
|
1102
|
+
const t = (line, what) => { const ms = line ? stampOf(line) : null; if (ms === null) problems.push(`no stamped \`${what}\` line`); return ms; };
|
|
1103
|
+
const own = first(/build ownership (held|joined) /);
|
|
1104
|
+
const ownT = own ? stampOf(own) : null;
|
|
1105
|
+
const sync = t(first(/snapshot \S+ is commit [0-9a-f]{40} tree [0-9a-f]{40} \(written=/), "snapshot ... is commit ... (written=");
|
|
1106
|
+
const stageStart = t(first(/rightkit-gate: --to \w+ for [0-9a-f]{12}/), "--to <stage> for <sha>");
|
|
1107
|
+
const plan = t(first(/\d+ scan\(s\) for \d+ changed file\(s\) vs [0-9a-f]{12}; class A scans \d+ at a time/), "<n> scan(s) for <m> changed file(s) ...; class A scans <j> at a time");
|
|
1108
|
+
const deps = t(first(/snapshot dependencies root=/), "snapshot dependencies root=");
|
|
1109
|
+
const span = (a, b, what) => { if (a === null || b === null) return null; if (b < a) { problems.push(`${what}: the closing line is stamped before the opening line`); return null; } return b - a; };
|
|
1110
|
+
const marks = {
|
|
1111
|
+
ownership: own ? span(startedMs, ownT, "ownership") : 0,
|
|
1112
|
+
snapshotSync: span(ownT ?? startedMs, sync, "snapshotSync"),
|
|
1113
|
+
planning: span(stageStart, plan, "planning"),
|
|
1114
|
+
dependencyStep: span(plan, deps, "dependencyStep"),
|
|
1115
|
+
};
|
|
1116
|
+
return { marks, problems };
|
|
1117
|
+
}
|
|
1118
|
+
|
|
1119
|
+
export const BUDGET_STAGES = Object.freeze(["ownership", "snapshotSync", "dependencyStep", "planning"]);
|
|
1120
|
+
/** Validates the budgets file: schema, a hosts object with mac and dell, every number positive or null. */
|
|
1121
|
+
export function validateBudgets(b) {
|
|
1122
|
+
const problems = [];
|
|
1123
|
+
if (!isObject(b)) return { ok: false, problems: ["budgets file is not an object"] };
|
|
1124
|
+
if (b.schema !== BUDGETS_SCHEMA) problems.push(`budgets.schema is ${JSON.stringify(b.schema)}, expected ${BUDGETS_SCHEMA}`);
|
|
1125
|
+
if (!isObject(b.hosts)) problems.push("budgets.hosts is not an object");
|
|
1126
|
+
else for (const host of ["mac", "dell"]) {
|
|
1127
|
+
const h = b.hosts[host];
|
|
1128
|
+
if (!isObject(h)) { problems.push(`budgets.hosts.${host} is missing`); continue; }
|
|
1129
|
+
const num = (v, where) => { if (v !== null && !(Number.isFinite(v) && v > 0)) problems.push(`${where} is neither null nor a positive number`); };
|
|
1130
|
+
num(h.warmCheckMs, `hosts.${host}.warmCheckMs`); num(h.warmCompileMs, `hosts.${host}.warmCompileMs`);
|
|
1131
|
+
if (!isObject(h.stages)) problems.push(`hosts.${host}.stages is missing`); else for (const s of BUDGET_STAGES) { if (!(s in h.stages)) problems.push(`hosts.${host}.stages.${s} is missing`); else num(h.stages[s], `hosts.${host}.stages.${s}`); }
|
|
1132
|
+
}
|
|
1133
|
+
return { ok: problems.length === 0, problems };
|
|
1134
|
+
}
|
|
1135
|
+
export function loadBudgets(file = BUDGETS_FILE) {
|
|
1136
|
+
let parsed; try { parsed = JSON.parse(fs.readFileSync(file, "utf8")); } catch (e) { return { budgets: null, problem: `cannot read ${file}: ${e.message}` }; }
|
|
1137
|
+
const v = validateBudgets(parsed);
|
|
1138
|
+
return v.ok ? { budgets: parsed, problem: null } : { budgets: null, problem: `${file}: ${v.problems.join("; ")}` };
|
|
1139
|
+
}
|
|
1140
|
+
/**
|
|
1141
|
+
* NN18: each warm run's wall time and fixed-stage durations stay inside the host's budget. `runs` is `[{ label, kind: "check"|"compile", ms, marks }]`.
|
|
1142
|
+
* A null budget FAILS ("no budget measured"): a host with no measurement is never passed.
|
|
1143
|
+
*/
|
|
1144
|
+
export function assertBudget({ host, budgets, runs }) {
|
|
1145
|
+
const problems = [];
|
|
1146
|
+
const h = budgets?.hosts?.[host];
|
|
1147
|
+
if (!h) return { ok: false, problems: [`no budget for host ${host} in ${BUDGETS_FILE}`] };
|
|
1148
|
+
const need = (v, what) => { if (v === null || v === undefined) { problems.push(`no budget measured for ${host}: ${what}`); return false; } return true; };
|
|
1149
|
+
for (const r of runs) {
|
|
1150
|
+
const total = r.kind === "compile" ? h.warmCompileMs : h.warmCheckMs;
|
|
1151
|
+
if (need(total, r.kind === "compile" ? "warmCompileMs" : "warmCheckMs") && r.ms > total) problems.push(`${r.label}: warm --to ${r.kind} took ${r.ms} ms, budget ${total} ms`);
|
|
1152
|
+
for (const s of BUDGET_STAGES) {
|
|
1153
|
+
const v = r.marks?.[s];
|
|
1154
|
+
if (v === null || v === undefined) { problems.push(`${r.label}: stage ${s} could not be timed`); continue; }
|
|
1155
|
+
if (need(h.stages?.[s], `stages.${s}`) && v > h.stages[s]) problems.push(`${r.label}: stage ${s} took ${v} ms, budget ${h.stages[s]} ms`);
|
|
1156
|
+
}
|
|
1157
|
+
}
|
|
1158
|
+
if (runs.length === 0) problems.push("no warm run to measure");
|
|
1159
|
+
return { ok: problems.length === 0, problems };
|
|
1160
|
+
}
|
|
1161
|
+
|
|
1162
|
+
// ---- NN19: the gate under test ----------------------------------------------------------------------------------------------------------------
|
|
1163
|
+
|
|
1164
|
+
/** The newest sealed install under `<managed root>/trusted-gates` (a folder named by the sha256 of its manifest, as agent-bin/rightkit-host-gate trusts it): `{ version, entry }` or null. */
|
|
1165
|
+
export function findInstalledGate(managedRoot, io = {}) { return listInstalledGates(managedRoot, io)[0] ?? null; }
|
|
1166
|
+
/** Every sealed install, newest version first. */
|
|
1167
|
+
export function listInstalledGates(managedRoot, { read = (f) => fs.readFileSync(f), list = (d) => fs.readdirSync(d) } = {}) {
|
|
1168
|
+
const root = path.join(managedRoot, "trusted-gates");
|
|
1169
|
+
let names; try { names = list(root); } catch { return []; }
|
|
1170
|
+
const found = [];
|
|
1171
|
+
for (const name of names) {
|
|
1172
|
+
if (!/^[a-f0-9]{64}$/.test(name)) continue;
|
|
1173
|
+
try {
|
|
1174
|
+
if (sha256(read(path.join(root, `${name}.manifest.txt`))) !== name) continue;
|
|
1175
|
+
const pkgDir = path.join(root, name, "node_modules", "@rightkit", "release");
|
|
1176
|
+
const pkg = JSON.parse(String(read(path.join(pkgDir, "package.json"))));
|
|
1177
|
+
if (pkg?.name === "@rightkit/release" && /^\d+\.\d+\.\d+$/.test(pkg.version)) found.push({ version: pkg.version, sealedSha256: name, entry: path.join(pkgDir, "bin", "rightkit-gate.mjs") });
|
|
1178
|
+
} catch { /* not a sealed install */ }
|
|
1179
|
+
}
|
|
1180
|
+
const key = (v) => v.split(".").map(Number);
|
|
1181
|
+
found.sort((a, b) => { const x = key(a.version); const y = key(b.version); for (let i = 0; i < 3; i += 1) if (x[i] !== y[i]) return y[i] - x[i]; return 0; });
|
|
1182
|
+
return found;
|
|
1183
|
+
}
|
|
1184
|
+
/**
|
|
1185
|
+
* NN19: the gate that runs is the installed sealed gate. Without `--gate` the default launcher must exist, report the newest sealed install's version
|
|
1186
|
+
* and not exec the checkout's gate; a checkout gate is accepted only when `--gate` names it (and the result then says so: `kind: "named"`).
|
|
1187
|
+
*/
|
|
1188
|
+
export function gateIdentityProblems({ gateArg, defaultGate, launcherExists, launcherVersion, launcherText = "", installed, checkoutRoot }) {
|
|
1189
|
+
const problems = [];
|
|
1190
|
+
const named = gateArg !== undefined && gateArg !== null && path.normalize(gateArg) !== path.normalize(defaultGate);
|
|
1191
|
+
if (!launcherExists) problems.push(`the launcher ${named ? gateArg : defaultGate} does not exist`);
|
|
1192
|
+
if (!launcherVersion) problems.push("`--version` of the launcher printed no version");
|
|
1193
|
+
if (!named) {
|
|
1194
|
+
const entry = path.join(checkoutRoot, "packages", "release", "bin", "rightkit-gate.mjs");
|
|
1195
|
+
if (String(launcherText).includes(entry)) problems.push(`the default launcher runs the checkout gate ${entry} and no --gate names it`);
|
|
1196
|
+
if (!installed) problems.push("no sealed installed gate under trusted-gates, so the installed gate's identity cannot be established");
|
|
1197
|
+
else if (launcherVersion && launcherVersion !== installed.version) problems.push(`the launcher reports ${launcherVersion}, the newest sealed install is ${installed.version}: not the installed gate`);
|
|
1198
|
+
}
|
|
1199
|
+
return { ok: problems.length === 0, problems, kind: named ? "named" : "installed" };
|
|
1200
|
+
}
|
|
1201
|
+
|
|
1202
|
+
// ---- Evaluation over a run's evidence --------------------------------------------------------------------------------------------------------
|
|
1203
|
+
|
|
1204
|
+
// ---------------------------------------------------------------------------------------------------------------------------------------------
|
|
1205
|
+
// GC-A27 extension: NN20-NN38 and the tightened NN01-NN19. Every assertion below is an e2e judgement over the run's OWN evidence (coverage, log,
|
|
1206
|
+
// spawn ledger, receipt, git history); none reads a synthetic input in production. That each one CAN fail is shown by `--prove` (control runs
|
|
1207
|
+
// of real conditions and mutant gates), never by a unit test. Evidence the gate does not emit makes its check FAIL, naming the evidence to add.
|
|
1208
|
+
// ---------------------------------------------------------------------------------------------------------------------------------------------
|
|
1209
|
+
|
|
1210
|
+
/** NN33: the NN table rows of the contract: `| NNxx | property | fails when |`. */
|
|
1211
|
+
export function parseContractNN(text) {
|
|
1212
|
+
const rows = [];
|
|
1213
|
+
for (const line of String(text ?? "").split(/\r?\n/)) {
|
|
1214
|
+
const m = /^\|\s*(NN\d\d)\s*\|(.*)\|\s*$/.exec(line);
|
|
1215
|
+
if (!m) continue;
|
|
1216
|
+
const cells = m[2].split("|").map((s) => s.trim());
|
|
1217
|
+
rows.push({ id: m[1], property: cells[0] ?? "", fails: cells.slice(1).join(" | ") });
|
|
1218
|
+
}
|
|
1219
|
+
return rows;
|
|
1220
|
+
}
|
|
1221
|
+
|
|
1222
|
+
/** NN33: every contract id has a check and every check id is in the contract (both directions, and the registry equals both). */
|
|
1223
|
+
export function assertContractMatch({ contractRows, checkIds, registryIds }) {
|
|
1224
|
+
const problems = [];
|
|
1225
|
+
const contract = contractRows.map((r) => r.id);
|
|
1226
|
+
if (contract.length === 0) problems.push("the contract has no NN table rows (`| NNxx | ... |`): nothing to match");
|
|
1227
|
+
const dup = contract.filter((id, i) => contract.indexOf(id) !== i);
|
|
1228
|
+
for (const id of new Set(dup)) problems.push(`${id} appears more than once in the contract table`);
|
|
1229
|
+
const checks = new Set(checkIds); const registry = new Set(registryIds); const inContract = new Set(contract);
|
|
1230
|
+
for (const id of contract) { if (!checks.has(id)) problems.push(`${id} is in the contract and has no check in the runner`); if (!registry.has(id)) problems.push(`${id} is in the contract and not in the runner's registry`); }
|
|
1231
|
+
for (const id of checks) if (!inContract.has(id)) problems.push(`${id} has a check in the runner and is not in the contract`);
|
|
1232
|
+
for (const id of registry) if (!inContract.has(id)) problems.push(`${id} is in the runner's registry and not in the contract`);
|
|
1233
|
+
return { ok: problems.length === 0, problems };
|
|
1234
|
+
}
|
|
1235
|
+
|
|
1236
|
+
export const CONTRACT_FILE = path.resolve(here, "..", "..", "docs", "GATE-CONTRACT.md");
|
|
1237
|
+
export const RUNNER_FILE = fileURLToPath(import.meta.url);
|
|
1238
|
+
const fileSha = (f) => { try { return sha256(fs.readFileSync(f)); } catch { return null; } };
|
|
1239
|
+
|
|
1240
|
+
// ---- NN25 / NN07 allowlists: EMPTY by decision. An entry needs Adrian's approval (GC-A27 NN25: "a probe that must run names its reason in the runner's
|
|
1241
|
+
// allowlist, which Adrian approves"; NN07 likewise). Do not add one without his approval by name in the commit message.
|
|
1242
|
+
export const NN25_ALLOWLIST = Object.freeze([]);
|
|
1243
|
+
const OWNERSHIP_PROBES = new Set(["ps", "lsof", "launchctl", "sysctl"]);
|
|
1244
|
+
const VERSION_ARG = /^(--version|-V|-v|version)$/;
|
|
1245
|
+
const TREE_WALKERS = new Set(["find", "rsync", "du"]);
|
|
1246
|
+
const GIT_TREE_VERBS = new Set(["ls-files", "ls-tree", "archive", "status", "diff", "diff-files", "diff-index", "update-index"]);
|
|
1247
|
+
|
|
1248
|
+
/** NN25: no child of the forbidden families on a warm run (git after the resident proof, version probes, pnpm, ownership probes, real cargo). */
|
|
1249
|
+
export function assertWarmNoFamilies(entries, { log = "", allow = NN25_ALLOWLIST } = {}) {
|
|
1250
|
+
const problems = [];
|
|
1251
|
+
const proofLine = String(log).split(/\r?\n/).find((l) => /snapshot proof:|resident proof|\(verified before/.test(l));
|
|
1252
|
+
const proofAt = proofLine ? stampOf(proofLine) : null;
|
|
1253
|
+
const allowed = new Set(allow.filter((a) => isObject(a) && a.reason && a.program).map((a) => `${a.program}\u0000${(a.args ?? []).join("\u0000")}`));
|
|
1254
|
+
const found = new Map();
|
|
1255
|
+
for (const e of entries) {
|
|
1256
|
+
const n = normalizeSpawn(e);
|
|
1257
|
+
if (allowed.has(`${n.program}\u0000${n.args.join("\u0000")}`)) continue;
|
|
1258
|
+
const at = Date.parse(e.at);
|
|
1259
|
+
const call = cargoCall(n);
|
|
1260
|
+
let fam = null;
|
|
1261
|
+
if (n.args.length <= 2 && n.args.some((a) => VERSION_ARG.test(a))) fam = "tool version probe";
|
|
1262
|
+
else if (n.program === "git" && (proofAt === null || at >= proofAt)) fam = proofAt === null ? "git (the log carries no resident-proof time, so every git start counts)" : "git after the resident proof";
|
|
1263
|
+
else if (n.program === "pnpm") fam = "pnpm";
|
|
1264
|
+
else if (OWNERSHIP_PROBES.has(n.program)) fam = `ownership probe (${n.program})`;
|
|
1265
|
+
else if (call && call.via !== "rustright") fam = "real cargo";
|
|
1266
|
+
if (fam) { const k = `${fam}\u0000${n.program} ${shortArgs(n.args)}`; found.set(k, (found.get(k) ?? 0) + 1); }
|
|
1267
|
+
}
|
|
1268
|
+
for (const [k, c] of [...found].slice(0, 20)) { const [fam, cmd] = k.split("\u0000"); problems.push(`${fam}: ${c}x ${cmd}`); }
|
|
1269
|
+
if (found.size > 20) problems.push(`... and ${found.size - 20} more`);
|
|
1270
|
+
return { ok: problems.length === 0, problems };
|
|
1271
|
+
}
|
|
1272
|
+
|
|
1273
|
+
/** NN22: every sync line of a warm run is written=0 removed=0 and the ledger shows no tree walk. */
|
|
1274
|
+
export function assertWarmSync(log, entries) {
|
|
1275
|
+
const problems = [];
|
|
1276
|
+
const syncs = [...String(log).matchAll(/snapshot \S+ is commit [0-9a-f]{40} tree [0-9a-f]{40} \(written=(\d+) removed=(\d+)/g)];
|
|
1277
|
+
if (!syncs.length) problems.push("the log has no `snapshot <dir> is commit <sha> tree <sha> (written=N removed=N` line");
|
|
1278
|
+
for (const m of syncs) if (m[1] !== "0" || m[2] !== "0") problems.push(`the snapshot sync wrote ${m[1]} and removed ${m[2]} on an unchanged commit`);
|
|
1279
|
+
for (const n of entries.map(normalizeSpawn)) if (TREE_WALKERS.has(n.program) || (n.program === "git" && n.args.some((a) => GIT_TREE_VERBS.has(a)))) problems.push(`a tree walk started on a warm run: ${n.program} ${shortArgs(n.args)} (cwd ${n.cwd})`);
|
|
1280
|
+
return { ok: problems.length === 0, problems };
|
|
1281
|
+
}
|
|
1282
|
+
|
|
1283
|
+
/** NN26: no `node gate-serve.mjs ask` process (the gate asks the resident gate in process over its socket). */
|
|
1284
|
+
export function assertNoServeAskSpawn(entries) {
|
|
1285
|
+
const problems = [];
|
|
1286
|
+
for (const n of entries.map(normalizeSpawn)) if (n.args.some((a) => /gate-serve\.mjs$/.test(a)) && n.args.includes("ask")) problems.push(`a process was started to ask the resident gate: ${n.program} ${shortArgs(n.args)}`);
|
|
1287
|
+
return { ok: problems.length === 0, problems };
|
|
1288
|
+
}
|
|
1289
|
+
|
|
1290
|
+
const cargoBFamily = (id) => {
|
|
1291
|
+
const bare = id.replace(/@[^@:]+$/, ""); const target = /@([^@:]+)$/.exec(id)?.[1] ?? "host"; const p = bare.split(":");
|
|
1292
|
+
if (p[0] === "test" && p[1] === "rust") return { fam: "test", ws: p[2], crate: p[3], idx: p[4] ?? "0", target };
|
|
1293
|
+
if (p[0] === "clippy") return { fam: "clippy", ws: p[1], crate: p[2], idx: p[3] ?? "0", target };
|
|
1294
|
+
if (p[0] === "check-features") return { fam: "check", ws: p[1], crate: p[2], idx: p[3] ?? "0", target };
|
|
1295
|
+
if (p[0] === "doc") return { fam: "doc", ws: p[1], crate: p[2], idx: "0", target };
|
|
1296
|
+
return null;
|
|
1297
|
+
};
|
|
1298
|
+
/** NN27: no check row runs where a clippy row covers the same configuration, and no two rows run the same compiler pass over one crate, target and feature set. */
|
|
1299
|
+
export function assertNoDoublePass(rows) {
|
|
1300
|
+
const problems = [];
|
|
1301
|
+
const seen = new Map();
|
|
1302
|
+
for (const r of rows.values()) {
|
|
1303
|
+
if (r.class !== "B" || r.coverage !== "ran") continue;
|
|
1304
|
+
const f = cargoBFamily(r.id); if (!f || (f.fam !== "check" && f.fam !== "clippy")) continue;
|
|
1305
|
+
const key = `${f.ws}|${f.crate}|${f.idx}|${f.target}`;
|
|
1306
|
+
(seen.get(key) ?? seen.set(key, []).get(key)).push({ id: r.id, fam: f.fam });
|
|
1307
|
+
}
|
|
1308
|
+
for (const [key, list] of seen) if (list.length > 1) problems.push(`${list.length} compiler passes ran over ${key.split("|").join(" ")}: ${list.map((x) => x.id).join(", ")}`);
|
|
1309
|
+
return { ok: problems.length === 0, problems };
|
|
1310
|
+
}
|
|
1311
|
+
|
|
1312
|
+
/** NN28: the resident gate learns changes from RightKit's file index and watcher; the gate must say so, and no polling child starts. */
|
|
1313
|
+
export function assertChangeSource(log, entries) {
|
|
1314
|
+
const problems = [];
|
|
1315
|
+
const m = /snapshot proof:[^\n]*\bchange-source=(\S+)/.exec(String(log));
|
|
1316
|
+
if (!m) problems.push("the log has no `snapshot proof: ... change-source=fsindex,file-watch` field: the gate must report which change source the resident gate used (rightkit-fsindex, rightkit-file-watch), so NN28 cannot be judged");
|
|
1317
|
+
else if (m[1] !== "fsindex,file-watch") problems.push(`the resident gate's change source is ${m[1]}, expected fsindex,file-watch`);
|
|
1318
|
+
for (const n of entries.map(normalizeSpawn)) if (TREE_WALKERS.has(n.program) || (n.program === "git" && n.args.some((a) => GIT_TREE_VERBS.has(a)))) problems.push(`a change was learned by polling: ${n.program} ${shortArgs(n.args)}`);
|
|
1319
|
+
return { ok: problems.length === 0, problems };
|
|
1320
|
+
}
|
|
1321
|
+
|
|
1322
|
+
/** NN23: every row the previous gate answered stays a hit, with its key, under the upgraded gate. */
|
|
1323
|
+
export function assertUpgradeKeepsHits(prev, next) {
|
|
1324
|
+
const problems = [];
|
|
1325
|
+
let kept = 0;
|
|
1326
|
+
for (const [id, p] of prev) {
|
|
1327
|
+
if (p.coverage === "skipped") continue;
|
|
1328
|
+
const n = next.get(id);
|
|
1329
|
+
if (!n) { problems.push(`${id}: answered by the previous gate and absent after the upgrade`); continue; }
|
|
1330
|
+
if (n.coverage !== "hit") problems.push(`${id}: ${p.coverage} under the previous gate, ${n.coverage} after the upgrade`);
|
|
1331
|
+
else if (n.key !== p.key) problems.push(`${id}: its key changed across the upgrade`);
|
|
1332
|
+
else kept += 1;
|
|
1333
|
+
}
|
|
1334
|
+
if (kept === 0 && problems.length === 0) problems.push("no row was answered by the previous gate: the upgrade cannot be judged");
|
|
1335
|
+
return { ok: problems.length === 0, problems, kept };
|
|
1336
|
+
}
|
|
1337
|
+
|
|
1338
|
+
/** NN24: a warm run after the resident gate was killed ran no row. */
|
|
1339
|
+
export function assertRestartWarm(rows, restart) {
|
|
1340
|
+
const problems = [];
|
|
1341
|
+
if (!restart?.killed) problems.push(restart?.why ?? "the resident gate was not restarted, so the case proves nothing");
|
|
1342
|
+
const ran = [...rows.values()].filter((r) => r.coverage === "ran");
|
|
1343
|
+
for (const r of ran.slice(0, 20)) problems.push(`${r.id}: ran after the resident gate restarted`);
|
|
1344
|
+
return { ok: problems.length === 0, problems };
|
|
1345
|
+
}
|
|
1346
|
+
|
|
1347
|
+
/** NN29: a run whose per-run identities differ gets the same keys and no miss. */
|
|
1348
|
+
export function assertIdentityIndependent(base, other) {
|
|
1349
|
+
const keys = assertKeysStable(base, other);
|
|
1350
|
+
const problems = [...keys.problems];
|
|
1351
|
+
for (const r of other.values()) if (r.class === "A" && r.coverage === "ran") problems.push(`${r.id}: a reuse miss on a run that differs only in per-run identities`);
|
|
1352
|
+
return { ok: problems.length === 0, problems };
|
|
1353
|
+
}
|
|
1354
|
+
|
|
1355
|
+
// ---- NN20 / NN21 / NN04 (compile) ----------------------------------------------------------------------------------------------------------------
|
|
1356
|
+
/** Crate dependency map of one workspace from its manifests: `{ name: [workspace crates it names as dependencies] }`. */
|
|
1357
|
+
export function crateDeps(manifestTexts) {
|
|
1358
|
+
const names = Object.keys(manifestTexts); const deps = {};
|
|
1359
|
+
for (const name of names) deps[name] = names.filter((o) => o !== name && new RegExp(`^\\s*${o.replace(/[-]/g, "\\-")}\\s*(=|\\.)`, "m").test(manifestTexts[name]));
|
|
1360
|
+
return deps;
|
|
1361
|
+
}
|
|
1362
|
+
/** `crate` and every crate that (transitively) depends on it. */
|
|
1363
|
+
export function affectedCrates(crate, deps) {
|
|
1364
|
+
const out = new Set([crate]); let grew = true;
|
|
1365
|
+
while (grew) { grew = false; for (const [c, ds] of Object.entries(deps)) if (!out.has(c) && ds.some((d) => out.has(d))) { out.add(c); grew = true; } }
|
|
1366
|
+
return out;
|
|
1367
|
+
}
|
|
1368
|
+
/** NN20: after a one-crate edit no Class B row of a crate the edit cannot affect ran. */
|
|
1369
|
+
export function assertCrateEditScope(rows, { workspace, crate, deps }) {
|
|
1370
|
+
const problems = [];
|
|
1371
|
+
const affected = affectedCrates(crate, deps);
|
|
1372
|
+
let b = 0;
|
|
1373
|
+
for (const r of rows.values()) {
|
|
1374
|
+
if (r.class !== "B" || r.coverage === "skipped") continue;
|
|
1375
|
+
b += 1;
|
|
1376
|
+
if (r.coverage !== "ran") continue;
|
|
1377
|
+
const f = cargoBFamily(r.id);
|
|
1378
|
+
if (!f) problems.push(`${r.id}: a Class B row that is no crate's row ran for a one-crate edit`);
|
|
1379
|
+
else if (f.ws !== workspace || !affected.has(f.crate)) problems.push(`${r.id}: crate ${f.crate} (${f.ws}) cannot be affected by an edit of ${crate} (affected: ${[...affected].join(", ")})`);
|
|
1380
|
+
}
|
|
1381
|
+
if (b === 0) problems.push("the compile run answered no Class B row: nothing shows what the edit recompiled");
|
|
1382
|
+
return { ok: problems.length === 0, problems };
|
|
1383
|
+
}
|
|
1384
|
+
/** Whether a row reads the lockfile of Cargo workspace `lockDir`. */
|
|
1385
|
+
export function rowReadsLock(id, lockDir) {
|
|
1386
|
+
const wsRe = lockDir.replace(/[.*+?^${}()|[\]\\/]/g, "\\const PREV_WARM = Object.freeze(");
|
|
1387
|
+
if (new RegExp(`^(cargo-metadata|cargo-deny|cargo-audit|ghsa-audit|cargo-package-list):${wsRe}(:|$)`).test(id)) return true;
|
|
1388
|
+
const f = cargoBFamily(id); return Boolean(f && f.ws === lockDir);
|
|
1389
|
+
}
|
|
1390
|
+
/** NN21: after a lockfile edit only rows that read that lockfile (and the per-file scans that read the edited file) ran. */
|
|
1391
|
+
export function assertLockEditScope(rows, { lockDir }) {
|
|
1392
|
+
const problems = [];
|
|
1393
|
+
for (const r of rows.values()) {
|
|
1394
|
+
if (r.coverage !== "ran") continue;
|
|
1395
|
+
if (rowReadsLock(r.id, lockDir) || /^(secret-scan|licen[cs]e)/.test(r.id)) continue;
|
|
1396
|
+
problems.push(`${r.id}: ran after an edit of ${lockDir}/Cargo.lock and does not read it`);
|
|
1397
|
+
}
|
|
1398
|
+
if (![...rows.values()].some((r) => r.coverage === "ran" && rowReadsLock(r.id, lockDir))) problems.push("no row that reads the edited lockfile ran: the edit was not seen");
|
|
1399
|
+
return { ok: problems.length === 0, problems };
|
|
1400
|
+
}
|
|
1401
|
+
/** NN04 on any stage: no workspace-scoped row of another workspace ran (Class A families and Class B crate rows). */
|
|
1402
|
+
export function assertOtherWorkspacesIdleAny(rows, { workspace }) {
|
|
1403
|
+
const problems = []; let own = false;
|
|
1404
|
+
for (const r of rows.values()) {
|
|
1405
|
+
const m = /^(cargo-metadata|cargo-deny|cargo-audit|ghsa-audit|cargo-package-list):(.+)$/.exec(r.id); const b = cargoBFamily(r.id);
|
|
1406
|
+
const ws = m ? m[2].split(":")[0] : b ? b.ws : null;
|
|
1407
|
+
if (r.id === "cargo-metadata") { own = own || workspace === "."; if (r.coverage === "ran" && workspace !== ".") problems.push(`${r.id}: ran for an edit in ${workspace}`); continue; }
|
|
1408
|
+
if (ws === null) continue;
|
|
1409
|
+
if (ws === workspace && r.coverage !== "skipped") own = true;
|
|
1410
|
+
if (r.coverage === "ran" && ws !== workspace) problems.push(`${r.id}: a row of workspace ${JSON.stringify(ws)} ran for a manifest edit in ${JSON.stringify(workspace)}`);
|
|
1411
|
+
}
|
|
1412
|
+
if (!own) problems.push(`no row of workspace ${JSON.stringify(workspace)} exists in the run`);
|
|
1413
|
+
return { ok: problems.length === 0, problems };
|
|
1414
|
+
}
|
|
1415
|
+
|
|
1416
|
+
// ---- tightened NN01 / NN02 / NN03 / NN09 / NN11 / NN13 ---------------------------------------------------------------------------------------------
|
|
1417
|
+
const ROW_TOOL = [[/^rustfmt/, "rustfmt"], [/^shellcheck/, "shellcheck"], [/^actionlint/, "actionlint"], [/^cargo-deny/, "cargo-deny"], [/^cargo-audit/, "cargo-audit"], [/^oxlint/, "oxlint"], [/^tsc:/, "tsc"]];
|
|
1418
|
+
/** NN01 (ledger half): a row reported `hit` never started its tool. */
|
|
1419
|
+
export function assertHitRowsStartedNoTool(rows, entries) {
|
|
1420
|
+
const problems = [];
|
|
1421
|
+
const started = new Set(entries.map(normalizeSpawn).map((n) => n.program));
|
|
1422
|
+
for (const r of rows.values()) {
|
|
1423
|
+
if (r.coverage !== "hit") continue;
|
|
1424
|
+
const tool = ROW_TOOL.find(([re]) => re.test(r.id))?.[1];
|
|
1425
|
+
if (tool && started.has(tool)) problems.push(`${r.id}: reported hit and ${tool} started in the same run (ledger)`);
|
|
1426
|
+
}
|
|
1427
|
+
return { ok: problems.length === 0, problems };
|
|
1428
|
+
}
|
|
1429
|
+
/** NN03 (files-read half): rustfmt formats exactly the edited files; secret scan and licence report exactly them. */
|
|
1430
|
+
export function assertEditedFilesRead(rows, entries, { files }) {
|
|
1431
|
+
const problems = [];
|
|
1432
|
+
const fmt = entries.map(normalizeSpawn).filter((n) => n.program === "rustfmt" && !(n.args.length === 1 && RUSTFMT_PROBE.test(n.args[0])));
|
|
1433
|
+
const want = [...files].sort().join("\u0000");
|
|
1434
|
+
for (const n of fmt) {
|
|
1435
|
+
const got = n.args.filter((a) => !a.startsWith("-")).map((a) => files.find((f) => a.endsWith(f)) ?? a).sort().join("\u0000");
|
|
1436
|
+
if (got !== want) problems.push(`rustfmt read ${shortArgs(n.args)}, expected exactly ${files.join(", ")}`);
|
|
1437
|
+
}
|
|
1438
|
+
for (const id of ["secret-scan", "license"]) {
|
|
1439
|
+
const r = [...rows.values()].find((x) => x.id === id || (id === "license" && /^licen[cs]e/.test(x.id)));
|
|
1440
|
+
if (!r) { problems.push(`no ${id} row in the run`); continue; }
|
|
1441
|
+
if (!Array.isArray(r.filesRead)) problems.push(`${r.id}: the coverage row has no \`filesRead\`; the gate must list the files each scan read, so reading more than the edited files cannot be ruled out`);
|
|
1442
|
+
else if ([...r.filesRead].sort().join("\u0000") !== want) problems.push(`${r.id}: read ${r.filesRead.length} file(s), expected exactly ${files.join(", ")}`);
|
|
1443
|
+
}
|
|
1444
|
+
return { ok: problems.length === 0, problems };
|
|
1445
|
+
}
|
|
1446
|
+
/** NN09 (--version half): `rustright cargo --version` also never starts. */
|
|
1447
|
+
export function assertNoBrokerVersion(entries) {
|
|
1448
|
+
const problems = [];
|
|
1449
|
+
for (const n of entries.map(normalizeSpawn)) if (n.program === "rustright" && n.args.includes("cargo") && n.args.some((a) => VERSION_ARG.test(a))) problems.push(`rustright cargo ${n.args.filter((a) => VERSION_ARG.test(a))[0]} started: ${shortArgs(n.args)}`);
|
|
1450
|
+
return { ok: problems.length === 0, problems };
|
|
1451
|
+
}
|
|
1452
|
+
/** NN11 (agreement half): a log that says the tree was not walked is contradicted by a ledger that shows a walk. */
|
|
1453
|
+
export function assertLedgerAgreesWithProof(log, entries) {
|
|
1454
|
+
const m = SNAPSHOT_PROOF.exec(String(log)); const problems = [];
|
|
1455
|
+
if (!m) return { ok: false, problems: ["no `snapshot proof:` line to compare the ledger with"] };
|
|
1456
|
+
const walks = Number(m[2]);
|
|
1457
|
+
const seen = entries.map(normalizeSpawn).filter((n) => TREE_WALKERS.has(n.program) || (n.program === "git" && n.args.some((a) => ["ls-files", "ls-tree", "archive"].includes(a)))).length;
|
|
1458
|
+
if (walks === 0 && seen > 0) problems.push(`the log says verify-walks=0 and the ledger shows ${seen} tree-walking start(s)`);
|
|
1459
|
+
return { ok: problems.length === 0, problems };
|
|
1460
|
+
}
|
|
1461
|
+
/** NN13 (probe half): a `--to check` run starts no ownership probe. */
|
|
1462
|
+
export function assertNoOwnershipProbe(entries) {
|
|
1463
|
+
const problems = [];
|
|
1464
|
+
for (const n of entries.map(normalizeSpawn)) if (OWNERSHIP_PROBES.has(n.program)) problems.push(`--to check started an ownership probe: ${n.program} ${shortArgs(n.args)}`);
|
|
1465
|
+
return { ok: problems.length === 0, problems };
|
|
1466
|
+
}
|
|
1467
|
+
|
|
1468
|
+
// ---- NN18: windows from launch to exit, per workload and kind --------------------------------------------------------------------------------------
|
|
1469
|
+
export const WINDOWS = Object.freeze(["startup", "ownership", "snapshotSync", "stageStart", "snapshotVerify", "appRules", "planning", "dependencyStep", "scans", "finish"]);
|
|
1470
|
+
export const WORKLOADS = Object.freeze(["fixture", "rightkit", "heardright", "pulse"]);
|
|
1471
|
+
export const PROFILES = Object.freeze(["warm-check", "warm-compile", "edited-check", "edited-compile", "cold-check", "cold-compile"]);
|
|
1472
|
+
/**
|
|
1473
|
+
* Consecutive windows that tile the run from the runner's launch to the gate's exit, each named by the log line that closes it:
|
|
1474
|
+
* startup (launch -> first stamped line), ownership (-> `build ownership held|joined`; 0 when the run takes no lease), snapshotSync (-> the sync line),
|
|
1475
|
+
* stageStart (-> `--to <stage> for <sha>`), snapshotVerify (-> `(verified before`), appRules (-> `app rules:`), planning (-> the plan line),
|
|
1476
|
+
* dependencyStep (-> `snapshot dependencies root=`), scans (-> the last `[n/N]` result line) and finish (-> exit). Optional markers that are absent
|
|
1477
|
+
* fold into the next window; a required marker that is absent or stamped out of order makes the run untimeable.
|
|
1478
|
+
*/
|
|
1479
|
+
export function windowMarks(log, startedMs, endMs) {
|
|
1480
|
+
const lines = String(log).split(/\r?\n/);
|
|
1481
|
+
const find = (re, last = false) => (last ? [...lines].reverse() : lines).find((l) => re.test(l));
|
|
1482
|
+
const problems = [];
|
|
1483
|
+
const stamp = (re, what, required, last) => { const line = find(re, last); if (!line) { if (required) problems.push(`no \`${what}\` line`); return undefined; } const t = stampOf(line); if (t === null) { problems.push(`the \`${what}\` line carries no UTC stamp`); return undefined; } return t; };
|
|
1484
|
+
const firstLine = lines.map(stampOf).find((t) => t !== null);
|
|
1485
|
+
const seq = [
|
|
1486
|
+
["startup", firstLine, true],
|
|
1487
|
+
["ownership", stamp(/build ownership (held|joined) /, "build ownership", false), false],
|
|
1488
|
+
["snapshotSync", stamp(/snapshot \S+ is commit [0-9a-f]{40} tree [0-9a-f]{40} \(written=/, "snapshot ... (written=", true), true],
|
|
1489
|
+
["stageStart", stamp(/rightkit-gate: --to \w+ for [0-9a-f]{12}/, "--to <stage> for <sha>", true), true],
|
|
1490
|
+
["snapshotVerify", stamp(/snapshot \S+ is commit [0-9a-f]{40} tree [0-9a-f]{40} \(verified/, "snapshot ... (verified", false), false],
|
|
1491
|
+
["appRules", stamp(/app rules: /, "app rules:", false), false],
|
|
1492
|
+
["planning", stamp(/\d+ scan\(s\) for \d+ changed file\(s\) vs [0-9a-f]{12}; class A scans \d+ at a time/, "plan line", true), true],
|
|
1493
|
+
["dependencyStep", stamp(/snapshot dependencies root=/, "snapshot dependencies root=", true), true],
|
|
1494
|
+
["scans", stamp(/\[(\d+)\/\1\] /, "[N/N] scan result", true, true), true],
|
|
1495
|
+
["finish", endMs, true],
|
|
1496
|
+
];
|
|
1497
|
+
if (firstLine === undefined) problems.push("the log has no stamped line");
|
|
1498
|
+
const windows = Object.fromEntries(WINDOWS.map((w) => [w, null]));
|
|
1499
|
+
let prev = startedMs;
|
|
1500
|
+
for (const [name, t, required] of seq) {
|
|
1501
|
+
if (t === undefined || t === null) { if (name === "ownership") windows.ownership = 0; else if (required) windows[name] = null; continue; }
|
|
1502
|
+
if (t < prev) { problems.push(`${name}: closing line stamped ${prev - t} ms before the previous marker; the run cannot be tiled`); continue; }
|
|
1503
|
+
windows[name] = t - prev; prev = t;
|
|
1504
|
+
}
|
|
1505
|
+
return { windows, problems };
|
|
1506
|
+
}
|
|
1507
|
+
export const budgetKeyOf = (label) => (/^S2:/.test(label) ? "warm" : /^S11:/.test(label) ? "cold" : "edited");
|
|
1508
|
+
/**
|
|
1509
|
+
* NN18 over the windows: `runs` is `[{ label, workload, profile, ms, windows, rows }]`. A missing or null budget fails ("no budget measured"); an
|
|
1510
|
+
* ownership window is budgeted on compile profiles only (a lease on a check is NN13's failure and must be 0 here). A cargo-metadata row that hit must
|
|
1511
|
+
* report `scanElapsedMs` within `metadataHitMs`.
|
|
1512
|
+
*/
|
|
1513
|
+
export function assertWindowBudgets({ host, budgets, runs }) {
|
|
1514
|
+
const problems = [];
|
|
1515
|
+
if (!runs.length) return { ok: false, problems: ["no run to measure"] };
|
|
1516
|
+
for (const r of runs) {
|
|
1517
|
+
const prof = budgets?.hosts?.[host]?.workloads?.[r.workload]?.[r.profile];
|
|
1518
|
+
const where = `${r.label} (${r.workload} ${r.profile})`;
|
|
1519
|
+
if (!prof) { problems.push(`${where}: no budget entry for host ${host}`); continue; }
|
|
1520
|
+
if (prof.totalMs === null || prof.totalMs === undefined) problems.push(`${where}: no budget measured for the whole run`);
|
|
1521
|
+
else if (r.ms > prof.totalMs) problems.push(`${where}: took ${r.ms} ms, budget ${prof.totalMs} ms`);
|
|
1522
|
+
const unbudgeted = [];
|
|
1523
|
+
for (const w of WINDOWS) {
|
|
1524
|
+
const v = r.windows?.[w];
|
|
1525
|
+
if (w === "ownership" && r.profile.endsWith("-check")) { if (v !== 0 && v !== null && v !== undefined) problems.push(`${where}: a check took ${v} ms of build-ownership time`); continue; }
|
|
1526
|
+
if (v === null || v === undefined) { problems.push(`${where}: window ${w} could not be timed`); continue; }
|
|
1527
|
+
const b = prof.windows?.[w];
|
|
1528
|
+
if (b === null || b === undefined) unbudgeted.push(w); else if (v > b) problems.push(`${where}: window ${w} took ${v} ms, budget ${b} ms`);
|
|
1529
|
+
}
|
|
1530
|
+
if (unbudgeted.length) problems.push(`${where}: no budget measured for window(s) ${unbudgeted.join(", ")}`);
|
|
1531
|
+
if (r.profile.startsWith("warm") && r.rows) for (const row of r.rows.values()) if (/^cargo-metadata(:|$)/.test(row.id) && row.coverage === "hit") {
|
|
1532
|
+
if (prof.metadataHitMs === null || prof.metadataHitMs === undefined) { problems.push(`${where}: no budget measured for a cargo-metadata hit`); break; }
|
|
1533
|
+
if (typeof row.scanElapsedMs !== "number") { problems.push(`${row.id}: the coverage row has no scanElapsedMs, so the metadata hit time cannot be judged`); break; }
|
|
1534
|
+
if (row.scanElapsedMs > prof.metadataHitMs) problems.push(`${row.id}: a metadata hit took ${row.scanElapsedMs} ms, budget ${prof.metadataHitMs} ms`);
|
|
1535
|
+
}
|
|
1536
|
+
}
|
|
1537
|
+
return { ok: problems.length === 0, problems };
|
|
1538
|
+
}
|
|
1539
|
+
/** The required (workload, profile) cells of a full run: the fixture warm/edited/cold, RightKit and HeardRight warm check, the Pulse compile. */
|
|
1540
|
+
export const REQUIRED_CELLS = Object.freeze([["fixture", "warm-check"], ["fixture", "warm-compile"], ["fixture", "edited-check"], ["fixture", "edited-compile"], ["fixture", "cold-check"], ["fixture", "cold-compile"], ["rightkit", "warm-check"], ["heardright", "warm-check"], ["pulse", "cold-compile"]]);
|
|
1541
|
+
|
|
1542
|
+
// ---- NN19 / NN30 / NN31: the receipt ---------------------------------------------------------------------------------------------------------------
|
|
1543
|
+
export const CONTRACT_RECEIPT_SCHEMA = "rightkit.contract-test-receipt/1";
|
|
1544
|
+
export function buildContractReceipt({ host, commit, gate, contractSha256, runnerSha256, budgetsSha256, fixtureCommit, result }) {
|
|
1545
|
+
return { schema: CONTRACT_RECEIPT_SCHEMA, host, commit, gate, contractSha256, runnerSha256, budgetsSha256, fixtureCommit, startedAt: result.startedAt, endedAt: result.endedAt, verdict: result.verdict, ok: result.ok, nn: Object.fromEntries(result.nonNegotiables.map((n) => [n.id, n.status])), uncheckedClauses: result.clauses.filter((c) => c.status === "unchecked").map((c) => c.id), waivers: result.waivers ?? [] };
|
|
1546
|
+
}
|
|
1547
|
+
export const validWaiver = (w) => isObject(w) && typeof w.clause === "string" && /^GC-/.test(w.clause) && w.by === "Adrian" && typeof w.words === "string" && w.words.trim().length > 0;
|
|
1548
|
+
/** `--verify-release`: both receipts pass, for one gate commit and one sealed gate, with the contract and runner they were judged by. */
|
|
1549
|
+
export function verifyReleaseReceipts(a, b, { commit = null, contractSha256 = null, runnerSha256 = null, waivers = [] } = {}) {
|
|
1550
|
+
const problems = [];
|
|
1551
|
+
const hosts = [a?.host, b?.host].sort().join("+");
|
|
1552
|
+
if (hosts !== "dell+mac") problems.push(`the two receipts are from ${hosts || "no host"}, expected one from the mac and one from the dell`);
|
|
1553
|
+
for (const [name, r] of [["first", a], ["second", b]]) {
|
|
1554
|
+
const w = `${name} receipt (${r?.host})`;
|
|
1555
|
+
if (!isObject(r) || r.schema !== CONTRACT_RECEIPT_SCHEMA) { problems.push(`${w}: not a ${CONTRACT_RECEIPT_SCHEMA}`); continue; }
|
|
1556
|
+
if (r.ok !== true || !/^PASS /.test(String(r.verdict))) problems.push(`${w}: verdict ${JSON.stringify(r.verdict)} is not a PASS`);
|
|
1557
|
+
if (!isCommit(r.commit)) problems.push(`${w}: commit is not a 40-hex sha`);
|
|
1558
|
+
if (r.gate?.kind !== "installed" || !isSha(r.gate?.sealedSha256)) problems.push(`${w}: not the installed sealed gate (kind ${JSON.stringify(r.gate?.kind)})`);
|
|
1559
|
+
for (const id of Object.keys(r.nn ?? {})) if (r.nn[id] !== "pass") problems.push(`${w}: ${id} is ${r.nn[id]}`);
|
|
1560
|
+
if (!r.nn || Object.keys(r.nn).length < 38) problems.push(`${w}: covers ${Object.keys(r.nn ?? {}).length} non-negotiables, expected 38`);
|
|
1561
|
+
const open = (r.uncheckedClauses ?? []).filter((id) => !waivers.some((x) => validWaiver(x) && x.clause === id));
|
|
1562
|
+
if (open.length) problems.push(`${w}: ${open.length} operative clause(s) unchecked and not waived by Adrian by name (${open.slice(0, 8).join(", ")}${open.length > 8 ? ", ..." : ""})`);
|
|
1563
|
+
}
|
|
1564
|
+
if (isObject(a) && isObject(b)) {
|
|
1565
|
+
for (const k of ["commit", "contractSha256", "runnerSha256", "fixtureCommit"]) if (a[k] !== b[k]) problems.push(`the receipts differ in ${k}: ${a[k]} vs ${b[k]}`);
|
|
1566
|
+
if (a.gate?.sealedSha256 !== b.gate?.sealedSha256) problems.push("the receipts name different sealed gates");
|
|
1567
|
+
if (commit && a.commit !== commit) problems.push(`the receipts are for commit ${a.commit}, the release is ${commit}`);
|
|
1568
|
+
if (contractSha256 && a.contractSha256 !== contractSha256) problems.push("the contract changed after the receipts were written");
|
|
1569
|
+
if (runnerSha256 && a.runnerSha256 !== runnerSha256) problems.push("the runner changed after the receipts were written");
|
|
1570
|
+
}
|
|
1571
|
+
return { ok: problems.length === 0, problems };
|
|
1572
|
+
}
|
|
1573
|
+
/** NN31: release, upload and trusted-gate install tooling must call `gate-acceptance.mjs --verify-release`. Reads the tooling's own files. */
|
|
1574
|
+
export function releaseToolingCallsVerify(files) {
|
|
1575
|
+
const calling = Object.entries(files).filter(([, text]) => /gate-acceptance(\.mjs)?\b[^\n]*--verify-release|--verify-release[^\n]*gate-acceptance/.test(text)).map(([f]) => f);
|
|
1576
|
+
return { calling };
|
|
1577
|
+
}
|
|
1578
|
+
|
|
1579
|
+
// ---- NN36 / NN37: the lock and the review ----------------------------------------------------------------------------------------------------------
|
|
1580
|
+
const numbersOf = (v, p = "") => (typeof v === "number" ? [[p, v]] : Array.isArray(v) ? v.flatMap((x, i) => numbersOf(x, `${p}[${i}]`)) : isObject(v) ? Object.entries(v).flatMap(([k, x]) => numbersOf(x, `${p}.${k}`)) : []);
|
|
1581
|
+
/** Budgets that rose between two versions of the file (a null becoming a number is a new measurement, not a rise). A number becoming null is a change too (it removes a measured ceiling), so it needs Adrian's approval like a rise. */
|
|
1582
|
+
export function risenBudgets(before, after) {
|
|
1583
|
+
const was = new Map(numbersOf(before?.hosts ?? {}));
|
|
1584
|
+
const is = new Map(numbersOf(after?.hosts ?? {}));
|
|
1585
|
+
const nullAt = (obj, p) => { try { return p.split(/\.|(?=\[)/).filter(Boolean).reduce((o, k) => o?.[k.replace(/^\[(\d+)\]$/, "$1")], obj) === null; } catch { return false; } };
|
|
1586
|
+
const out = [...is].filter(([p, v]) => was.has(p) && v > was.get(p)).map(([p, v]) => `${p}: ${was.get(p)} -> ${v}`);
|
|
1587
|
+
for (const [p, v] of was) if (!is.has(p) && nullAt(after?.hosts ?? {}, p.replace(/^\./, ""))) out.push(`${p}: ${v} -> null (a measured budget removed)`);
|
|
1588
|
+
return out;
|
|
1589
|
+
}
|
|
1590
|
+
export function lockProblems({ rootDir, paths, budgetsRel, contractRel, fixtureCommit, pin, run = (args) => git(rootDir, args) }) {
|
|
1591
|
+
const problems = [];
|
|
1592
|
+
const tableOf = (t) => parseContractNN(t).map((r) => `${r.id}|${r.property}|${r.fails}`).join("\n");
|
|
1593
|
+
const safe = (args) => { try { return run(args); } catch { return null; } };
|
|
1594
|
+
const dirty = (safe(["status", "--porcelain", "--", ...paths]) ?? "").split("\n").filter(Boolean).filter((l) => !l.includes(contractRel));
|
|
1595
|
+
for (const l of dirty) problems.push(`a locked file has uncommitted changes (${l.trim()}): the commit must cite Adrian's approval`);
|
|
1596
|
+
const headContract = safe(["show", `HEAD:${contractRel}`]); let nowContract = null; try { nowContract = fs.readFileSync(path.join(rootDir, contractRel), "utf8"); } catch { /* reported below */ }
|
|
1597
|
+
if (headContract !== null && nowContract !== null && tableOf(headContract) !== tableOf(nowContract)) problems.push("the contract's NN table has uncommitted changes: the commit must cite Adrian's approval");
|
|
1598
|
+
const base = (safe(["log", "--grep=Gate-Acceptance-Locked:", "--format=%H", "-n", "1"]) ?? "").trim();
|
|
1599
|
+
if (!base) problems.push("the test is not locked: no commit carries a `Gate-Acceptance-Locked: <Adrian's words>` line, so there is no baseline to judge changes against");
|
|
1600
|
+
else {
|
|
1601
|
+
const commits = (safe(["log", `${base}..HEAD`, "--format=%H", "--", ...paths]) ?? "").split("\n").filter(Boolean);
|
|
1602
|
+
for (const c of commits) {
|
|
1603
|
+
const msg = safe(["show", "-s", "--format=%B", c]) ?? "";
|
|
1604
|
+
const touchedContract = (safe(["diff-tree", "--no-commit-id", "--name-only", "-r", c]) ?? "").split("\n").includes(contractRel);
|
|
1605
|
+
const onlyContractNoTable = touchedContract && !(paths.filter((p) => p !== contractRel).some((p) => (safe(["diff-tree", "--no-commit-id", "--name-only", "-r", c]) ?? "").split("\n").includes(p))) && tableOf(safe(["show", `${c}:${contractRel}`]) ?? "") === tableOf(safe(["show", `${c}~1:${contractRel}`]) ?? "");
|
|
1606
|
+
if (onlyContractNoTable) continue;
|
|
1607
|
+
if (!/^Adrian-approved: .+/m.test(msg)) problems.push(`commit ${c.slice(0, 12)} changed a locked file without \`Adrian-approved: <his words>\` in its message`);
|
|
1608
|
+
let was = null; let is = null; try { was = JSON.parse(safe(["show", `${c}~1:${budgetsRel}`]) ?? "null"); is = JSON.parse(safe(["show", `${c}:${budgetsRel}`]) ?? "null"); } catch { /* not json at that commit */ }
|
|
1609
|
+
for (const rise of risenBudgets(was, is)) problems.push(`commit ${c.slice(0, 12)} raised a budget: ${rise}`);
|
|
1610
|
+
}
|
|
1611
|
+
}
|
|
1612
|
+
if (pin && fixtureCommit && pin !== fixtureCommit) problems.push(`the fixture is at ${fixtureCommit}, the pin is ${pin}`);
|
|
1613
|
+
if (!pin) problems.push("the budgets file has no fixture pin (`fixture.commit`)");
|
|
1614
|
+
return { ok: problems.length === 0, problems };
|
|
1615
|
+
}
|
|
1616
|
+
export function reviewProblems({ budgets, runnerSha256, contractSha256 }) {
|
|
1617
|
+
const reviews = Array.isArray(budgets?.reviews) ? budgets.reviews : [];
|
|
1618
|
+
const good = reviews.find((r) => isObject(r) && r.runnerSha256 === runnerSha256 && r.contractSha256 === contractSha256 && typeof r.reviewer === "string" && r.reviewer && typeof r.author === "string" && r.author && r.reviewer !== r.author && typeof r.adrianWords === "string" && r.adrianWords.trim() && r.verdict === "pass");
|
|
1619
|
+
return good ? { ok: true, problems: [] } : { ok: false, problems: [`no independent review is recorded for this runner (sha256 ${String(runnerSha256).slice(0, 12)}) and contract (${String(contractSha256).slice(0, 12)}): budgets.reviews needs { runnerSha256, contractSha256, reviewer, author (different), adrianWords, verdict: "pass" }`] };
|
|
1620
|
+
}
|
|
1621
|
+
/** NN38: every cross-target row built with stand-ins says `evidence: "type-check-only"` in coverage and in the receipt. */
|
|
1622
|
+
export function assertLimitedEvidence(runs) {
|
|
1623
|
+
const problems = []; let cross = 0;
|
|
1624
|
+
for (const [label, run] of Object.entries(runs)) {
|
|
1625
|
+
if (!run.rows) continue;
|
|
1626
|
+
const rows = [...run.rows.values()].filter((r) => /@[^@:]+$/.test(r.id) && r.coverage !== "skipped");
|
|
1627
|
+
cross += rows.length;
|
|
1628
|
+
const bad = rows.filter((r) => r.evidence !== "type-check-only");
|
|
1629
|
+
if (bad.length) problems.push(`${label}: ${bad.length} cross-target row(s) lack evidence "type-check-only" in coverage (${bad.slice(0, 3).map((r) => r.id).join(", ")})`);
|
|
1630
|
+
if (rows.length && run.receipt) {
|
|
1631
|
+
const listed = new Set((run.receipt.stages?.compile?.limitedEvidence ?? []).filter((x) => x?.evidence === "type-check-only").map((x) => x.id));
|
|
1632
|
+
const missing = rows.filter((r) => !listed.has(r.id));
|
|
1633
|
+
if (missing.length) problems.push(`${label}: the receipt's stages.compile.limitedEvidence does not list ${missing.length} cross-target row(s) as type-check-only (the gate must write that list)`);
|
|
1634
|
+
}
|
|
1635
|
+
}
|
|
1636
|
+
if (cross === 0) problems.push("no cross-target row was answered in any run: nothing shows the limited-evidence marking");
|
|
1637
|
+
return { ok: problems.length === 0, problems };
|
|
1638
|
+
}
|
|
1639
|
+
|
|
1640
|
+
|
|
1641
|
+
/**
|
|
1642
|
+
* NN39 tolerance: an idle-lane-while-queued window shorter than this is start-up jitter (one lane finishing and the next queued row being picked up,
|
|
1643
|
+
* process spawn and the ledger's own write). Measured scheduling gaps between consecutive starts are tens of milliseconds; 250 ms is five times that.
|
|
1644
|
+
* A longer window is a lane that sat idle while work waited.
|
|
1645
|
+
*/
|
|
1646
|
+
export const NN39_TOLERANCE_MS = 250;
|
|
1647
|
+
/** Intervals `[{ s, e }]` (ms) where fewer than `lanes` run while a later-starting interval is still queued: contiguous windows longer than `toleranceMs`. */
|
|
1648
|
+
export function idleLaneWindows(intervals, lanes, toleranceMs = NN39_TOLERANCE_MS) {
|
|
1649
|
+
const iv = intervals.filter((x) => Number.isFinite(x.s) && Number.isFinite(x.e)).sort((a, b) => a.s - b.s);
|
|
1650
|
+
const points = [...new Set(iv.flatMap((x) => [x.s, x.e]))].sort((a, b) => a - b);
|
|
1651
|
+
const idle = [];
|
|
1652
|
+
for (let i = 0; i + 1 < points.length; i += 1) {
|
|
1653
|
+
const [a, b] = [points[i], points[i + 1]];
|
|
1654
|
+
const running = iv.filter((x) => x.s <= a && x.e > a).length;
|
|
1655
|
+
const queued = iv.filter((x) => x.s >= b).length;
|
|
1656
|
+
if (queued > 0 && running < lanes) {
|
|
1657
|
+
const last = idle[idle.length - 1];
|
|
1658
|
+
if (last && last.end === a) { last.end = b; last.minRunning = Math.min(last.minRunning, running); last.queued = Math.max(last.queued, queued); } else idle.push({ start: a, end: b, minRunning: running, queued });
|
|
1659
|
+
}
|
|
1660
|
+
}
|
|
1661
|
+
return idle.filter((w) => w.end - w.start > toleranceMs).map((w) => ({ ...w, ms: w.end - w.start }));
|
|
1662
|
+
}
|
|
1663
|
+
/** NN39: the ledger's Class A lane processes (async children that are not probes or compiles) and Class B carried compiles keep `lanes` busy while work is queued. */
|
|
1664
|
+
export function assertRealParallelism(entries, { lanes, ranA = 0, label = "" }) {
|
|
1665
|
+
const problems = [];
|
|
1666
|
+
const ns = entries.map((e) => ({ e, n: normalizeSpawn(e) }));
|
|
1667
|
+
const at = ({ e }) => { const s = Date.parse(e.at); return { s, e: s + (Number(e.ms) || 0) }; };
|
|
1668
|
+
const A = ns.filter(({ e, n }) => e.sync === false && typeof e.ms === "number" && !["git", "ps", "lsof", "launchctl", "sysctl"].includes(n.program) && !(cargoCall(n)?.via === "rustright") && !/rustright/.test(n.program)).map(at);
|
|
1669
|
+
const B = ns.filter(({ n }) => { const c = cargoCall(n); return c && c.via !== "cargo" && COMPILING_CARGO.has(c.sub); }).map(at);
|
|
1670
|
+
if (ranA >= 2 && A.length < 2) problems.push(`${ranA} Class A rows ran and the ledger shows ${A.length} lane process(es): the lanes cannot be judged`);
|
|
1671
|
+
for (const [name, iv] of [["Class A lane", A], ["Class B carried compile", B]]) {
|
|
1672
|
+
if (iv.length < 2) continue;
|
|
1673
|
+
const idle = idleLaneWindows(iv, lanes);
|
|
1674
|
+
for (const w of idle.slice(0, 3)) problems.push(`${label}${name}: idle lane while work waited: only ${w.minRunning} of ${lanes} lanes busy for ${w.ms} ms with ${w.queued} start(s) still queued (tolerance ${NN39_TOLERANCE_MS} ms)`);
|
|
1675
|
+
}
|
|
1676
|
+
return { ok: problems.length === 0, problems };
|
|
1677
|
+
}
|
|
1678
|
+
|
|
1679
|
+
|
|
1680
|
+
/** Cargo argv without the unit selectors (`-p x`, `--package x`, `-px`, `--package=x`): the feature round and configuration of an invocation. */
|
|
1681
|
+
const withoutUnits = (args) => { const out = []; for (let i = 0; i < args.length; i += 1) { const a = args[i]; if (a === "-p" || a === "--package") { i += 1; continue; } if (/^(-p.+|--package=.*)$/.test(a)) continue; out.push(a); } return out; };
|
|
1682
|
+
const cargoArgsOf = (n) => { const i = n.args.indexOf("cargo"); return n.program === "rustright" ? n.args.slice(i + 1) : n.args; };
|
|
1683
|
+
/** The rows of a coverage map that belong to the doc stage (`doc:<workspace>:<crate>`). */
|
|
1684
|
+
const docRowsOf = (rows) => [...rows.values()].filter((r) => cargoBFamily(r.id)?.fam === "doc");
|
|
1685
|
+
/**
|
|
1686
|
+
* NN40: docs are one command per workspace and feature round, on every compile. Fails on a `cargo rustdoc` start, on doc invocations of one
|
|
1687
|
+
* workspace and configuration (the argv without its `-p` units) running more than once, on doc rows that ran with no doc invocation in the
|
|
1688
|
+
* ledger, and on a compile run that answers no doc row at all (the doc stage was skipped).
|
|
1689
|
+
*/
|
|
1690
|
+
export function assertDocOneCommand(rows, entries, { label = "" } = {}) {
|
|
1691
|
+
const problems = []; const p = label ? `${label}: ` : "";
|
|
1692
|
+
const calls = entries.map(normalizeSpawn).map((n) => ({ n, c: cargoCall(n) })).filter(({ c }) => c && (c.sub === "doc" || c.sub === "rustdoc"));
|
|
1693
|
+
for (const { n, c } of calls) if (c.sub === "rustdoc") problems.push(`${p}a cargo rustdoc started (${n.program} ${shortArgs(n.args)}, cwd ${n.cwd}): docs must be one \`cargo doc\` per workspace and feature round`);
|
|
1694
|
+
const groups = new Map();
|
|
1695
|
+
for (const { n, c } of calls) { if (c.sub !== "doc") continue; const key = `${normalizeRunPart(n.cwd)}\u0000${withoutUnits(cargoArgsOf(n)).map(normalizeRunPart).join(" ")}`; (groups.get(key) ?? groups.set(key, []).get(key)).push(n); }
|
|
1696
|
+
for (const [key, list] of groups) if (list.length > 1) problems.push(`${p}${list.length} doc invocations for one workspace and configuration (${key.replace("\u0000", " | ")}): ${list.slice(0, 3).map((n) => shortArgs(n.args)).join(" ;; ")}`);
|
|
1697
|
+
const docRows = docRowsOf(rows).filter((r) => r.coverage !== "skipped");
|
|
1698
|
+
if (docRows.length === 0) problems.push(`${p}the compile answered no doc row (every doc row is skipped or absent): the doc stage was skipped`);
|
|
1699
|
+
const ranDoc = docRows.filter((r) => r.coverage === "ran");
|
|
1700
|
+
if (ranDoc.length && !calls.some(({ c }) => c.sub === "doc")) problems.push(`${p}${ranDoc.length} doc row(s) ran (${ranDoc.slice(0, 3).map((r) => r.id).join(", ")}) and the ledger has no \`cargo doc\` start: the doc stage is not one command`);
|
|
1701
|
+
return { ok: problems.length === 0, problems, docRows: docRows.length, ranDoc: ranDoc.length, invocations: calls.length };
|
|
1702
|
+
}
|
|
1703
|
+
|
|
1704
|
+
/** The `--target` values of a cargo argv. */
|
|
1705
|
+
const targetsOf = (args) => { const t = []; for (let i = 0; i < args.length; i += 1) { if (args[i] === "--target" && args[i + 1]) { t.push(args[i + 1]); i += 1; } else if (/^--target=./.test(args[i])) t.push(args[i].slice(9)); } return t; };
|
|
1706
|
+
const withoutTargets = (args) => { const out = []; for (let i = 0; i < args.length; i += 1) { if (args[i] === "--target") { i += 1; continue; } if (/^--target=/.test(args[i])) continue; out.push(args[i]); } return out; };
|
|
1707
|
+
export const NN42_MISSING = "installed broker refuses several --target per invocation (RK_TARGET_INVALID)";
|
|
1708
|
+
/**
|
|
1709
|
+
* NN42: the cross targets of one stage go in one broker command naming every `--target`. Fails when the log carries RK_TARGET_INVALID (the broker
|
|
1710
|
+
* refused several), or when one stage sends one command per cross target (same unit selection and configuration, a different single target each).
|
|
1711
|
+
* Both name the missing broker capability. A run that built no cross-target row is no evidence either way (`crossRan` 0).
|
|
1712
|
+
*/
|
|
1713
|
+
export function assertCrossTargetsOneCommand(log, entries, rows, { label = "" } = {}) {
|
|
1714
|
+
const problems = []; const p = label ? `${label}: ` : "";
|
|
1715
|
+
const crossRan = rows ? [...rows.values()].filter((r) => /@[^@:]+$/.test(r.id) && r.coverage === "ran").length : 0;
|
|
1716
|
+
if (/RK_TARGET_INVALID/.test(String(log))) problems.push(`${p}${NN42_MISSING}: the log carries RK_TARGET_INVALID; the broker needs a capability to accept several --target in one command`);
|
|
1717
|
+
const groups = new Map();
|
|
1718
|
+
for (const n of entries.map(normalizeSpawn)) {
|
|
1719
|
+
const c = cargoCall(n); if (!c || c.via === "cargo" || (!COMPILING_CARGO.has(c.sub) && c.sub !== "rustdoc")) continue;
|
|
1720
|
+
const a = cargoArgsOf(n); const t = targetsOf(a); if (!t.length) continue;
|
|
1721
|
+
const key = `${normalizeRunPart(n.cwd)}\u0000${c.sub}\u0000${withoutTargets(withoutUnits(a)).map(normalizeRunPart).join(" ")}`;
|
|
1722
|
+
(groups.get(key) ?? groups.set(key, []).get(key)).push(t);
|
|
1723
|
+
}
|
|
1724
|
+
for (const [key, list] of groups) {
|
|
1725
|
+
const all = [...new Set(list.flat())];
|
|
1726
|
+
if (list.length > 1 && all.length > 1 && list.every((t) => t.length === 1)) problems.push(`${p}${NN42_MISSING}: the stage sent ${list.length} commands for the cross targets ${all.join(", ")} (${key.split("\u0000")[1]} in ${key.split("\u0000")[0]}), one per target; one broker command naming every --target is missing`);
|
|
1727
|
+
}
|
|
1728
|
+
return { ok: problems.length === 0, problems, crossRan, groups: groups.size };
|
|
1729
|
+
}
|
|
1730
|
+
|
|
1731
|
+
/**
|
|
1732
|
+
* NN41: run 1 and run 2 are the same commit; every row that really failed in run 1 must be a cache hit that still says fail in run 2. Run 3 changes the
|
|
1733
|
+
* toolchain identity; every such row must run again (a cached failure is never reused after the identity changed, an environment fix must rerun it).
|
|
1734
|
+
*/
|
|
1735
|
+
export function assertCachedFailure(first, second, third, { identity = "" } = {}) {
|
|
1736
|
+
const problems = [];
|
|
1737
|
+
const failed = first ? [...first.values()].filter((r) => r.class === "B" && r.coverage === "ran" && r.status === "fail") : [];
|
|
1738
|
+
if (failed.length === 0) problems.push("the failing commit's first run has no Class B row that ran and failed: the fixture did not fail deterministically, so no cached failure can be judged");
|
|
1739
|
+
for (const f of failed) {
|
|
1740
|
+
const r = second?.get(f.id);
|
|
1741
|
+
if (!r) problems.push(`${f.id}: absent from the second run of the same commit`);
|
|
1742
|
+
else if (r.coverage !== "hit") problems.push(`${f.id}: failed, and with unchanged inputs, toolchain and broker identity it ${r.coverage === "ran" ? "ran again" : `is ${r.coverage}`} (a failure must be a cache hit)`);
|
|
1743
|
+
else if (r.status !== "fail") problems.push(`${f.id}: a cached failure came back with status ${r.status}`);
|
|
1744
|
+
else if (f.key && r.key && f.key !== r.key) problems.push(`${f.id}: the key changed between two identical runs`);
|
|
1745
|
+
}
|
|
1746
|
+
if (!third) problems.push(`no third run with a changed toolchain identity (${identity || "none chosen"}): the reuse after an identity change cannot be judged; the evidence needed is a second installed toolchain the gate keys on (RUSTUP_TOOLCHAIN)`);
|
|
1747
|
+
else for (const f of failed) {
|
|
1748
|
+
const r = third.get(f.id);
|
|
1749
|
+
if (!r) problems.push(`${f.id}: absent from the run with a changed toolchain identity`);
|
|
1750
|
+
else if (r.coverage === "hit") problems.push(`${f.id}: a cached failure was reused after the toolchain identity changed (${identity}): an environment fix must rerun it`);
|
|
1751
|
+
}
|
|
1752
|
+
return { ok: problems.length === 0, problems, failed: failed.map((f) => f.id) };
|
|
1753
|
+
}
|
|
1754
|
+
|
|
1755
|
+
/** The NN a step-less (release-level or structural) check cannot judge from a run: names the evidence the gate or the tooling must add. */
|
|
1756
|
+
const NN_EVAL_EXT = {
|
|
1757
|
+
NN20: (ctx) => { const r = usableRun(ctx, "S12:crate", { red: true }); if (r.fail) return [r.fail]; if (!ctx.crateEdit) return [bad("S12:crate", ["the edited crate's workspace and dependencies are not known"])]; return [checkFor("S12:crate", assertCrateEditScope(r.run.rows, ctx.crateEdit), r.run.coveragePaths)]; },
|
|
1758
|
+
NN21: (ctx) => { const r = usableRun(ctx, "S12:lock", { red: true }); if (r.fail) return [r.fail]; return [checkFor("S12:lock", assertLockEditScope(r.run.rows, { lockDir: ctx.lockDir ?? "rk" }), r.run.coveragePaths)]; },
|
|
1759
|
+
NN22: (ctx) => warmRuns(ctx, RED).map((w) => { if (w.fail) return w.fail; const l = ledgerOf(w.run, w.label); return l.fail ?? checkFor(w.label, assertWarmSync(w.run.log, l.entries), [w.run.logPath, w.run.ledgerPath]); }),
|
|
1760
|
+
NN23: (ctx) => {
|
|
1761
|
+
if (ctx.upgradeWhy) return [bad("S13", [ctx.upgradeWhy])];
|
|
1762
|
+
const a = usableRun(ctx, "S13:prev", RED); const b = usableRun(ctx, "S13:next", RED); if (a.fail || b.fail) return [a.fail ?? b.fail];
|
|
1763
|
+
return [checkFor("S13", assertUpgradeKeepsHits(a.run.rows, b.run.rows), [...a.run.coveragePaths, ...b.run.coveragePaths])];
|
|
1764
|
+
},
|
|
1765
|
+
NN24: (ctx) => { const r = usableRun(ctx, "S14:check", RED); if (r.fail) return [r.fail]; return [checkFor("S14:check", assertRestartWarm(r.run.rows, ctx.restart), r.run.coveragePaths)]; },
|
|
1766
|
+
NN25: (ctx) => warmRuns(ctx, RED).map((w) => { if (w.fail) return w.fail; const l = ledgerOf(w.run, w.label); return l.fail ?? checkFor(w.label, assertWarmNoFamilies(l.entries, { log: w.run.log }), [w.run.ledgerPath]); }),
|
|
1767
|
+
NN26: (ctx) => ledgerRuns(ctx).map(([label, run]) => { const l = ledgerOf(run, label); return l.fail ?? checkFor(label, assertNoServeAskSpawn(l.entries), [run.ledgerPath]); }),
|
|
1768
|
+
NN27: (ctx) => { const out = []; for (const label of ["S1:compile", "S11:compile"].filter((l) => ctx.runs[l])) { const r = usableRun(ctx, label, RED); out.push(r.fail ?? checkFor(label, assertNoDoublePass(r.run.rows), r.run.coveragePaths)); } return out.length ? out : [bad("S1:compile", ["no compile run"])]; },
|
|
1769
|
+
NN28: (ctx) => warmRuns(ctx, RED).map((w) => { if (w.fail) return w.fail; const l = ledgerOf(w.run, w.label); return l.fail ?? checkFor(w.label, assertChangeSource(w.run.log, l.entries), [w.run.logPath, w.run.ledgerPath]); }),
|
|
1770
|
+
NN29: (ctx) => { const a = usableRun(ctx, "S2:check2", RED); const b = usableRun(ctx, "S16:ident", RED); if (a.fail || b.fail) return [a.fail ?? b.fail]; return [checkFor("S16:ident", assertIdentityIndependent(a.run.rows, b.run.rows), [...a.run.coveragePaths, ...b.run.coveragePaths])]; },
|
|
1771
|
+
NN30: (ctx) => {
|
|
1772
|
+
const other = ctx.otherReceipt;
|
|
1773
|
+
if (!other) return [bad("other host", [`no passing receipt from the ${ctx.host === "mac" ? "dell" : "mac"} for this commit was given (--other-receipt <file>); a release needs both hosts`])];
|
|
1774
|
+
if (other.error) return [bad("other host", [other.error])];
|
|
1775
|
+
const own = { ...other }; const problems = [];
|
|
1776
|
+
if (other.host === ctx.host) problems.push(`the other receipt is from this host (${ctx.host})`);
|
|
1777
|
+
if (other.ok !== true) problems.push(`the ${other.host} receipt is not a pass (${other.verdict})`);
|
|
1778
|
+
if (other.commit !== ctx.gateCommit) problems.push(`the ${other.host} receipt is for ${other.commit}, this run is for ${ctx.gateCommit}`);
|
|
1779
|
+
return [{ label: `${other.host} receipt`, ok: problems.length === 0, problems, evidence: [ctx.otherReceiptPath ?? "--other-receipt"] , own }];
|
|
1780
|
+
},
|
|
1781
|
+
NN31: (ctx) => {
|
|
1782
|
+
const calling = ctx.tooling?.calling ?? [];
|
|
1783
|
+
if (calling.length) return [{ label: "tooling", ok: true, problems: [], evidence: calling }];
|
|
1784
|
+
return [bad("tooling", [`no release, upload or trusted-gate install tooling calls \`node packages/release/gate-acceptance.mjs --verify-release <receipt-mac> <receipt-dell>\` (searched: ${(ctx.tooling?.searched ?? []).length} file(s)). Release/upload tooling (right-release upload, build-release, the publish path) and the trusted-gate promotion (installing a candidate beside the trusted gate, testing it, then promoting) must call it and refuse on a non-zero exit`], ctx.tooling?.searched?.slice(0, 3) ?? [])];
|
|
1785
|
+
},
|
|
1786
|
+
NN32: (ctx) => {
|
|
1787
|
+
const kills = Object.entries(ctx.runs).filter(([, r]) => r.kill);
|
|
1788
|
+
if (!kills.length) return [bad("S8", ["no kill case ran"])];
|
|
1789
|
+
const out = kills.map(([label, r]) => checkFor(label, r.recovery ?? { ok: false, problems: ["no recovery verdict"] }, [r.logPath]));
|
|
1790
|
+
const have = new Set(kills.map(([, r]) => r.killSignal ?? r.signalName));
|
|
1791
|
+
const need = ctx.host === "dell" ? ["terminate"] : ["SIGKILL", "SIGINT"];
|
|
1792
|
+
const lacking = need.filter((s) => !have.has(s) && !(s === "terminate" && [...have].some((x) => x === "SIGKILL" || x === "terminate")));
|
|
1793
|
+
if (lacking.length) out.push(bad("signals", [`the host's kill signal(s) not exercised: ${lacking.join(", ")}`]));
|
|
1794
|
+
return out;
|
|
1795
|
+
},
|
|
1796
|
+
NN33: (ctx) => {
|
|
1797
|
+
const registryIds = (ctx.nnSet ?? NN_ALL).map((n) => n.id);
|
|
1798
|
+
const checkIds = [...Object.keys(NN_EVAL), ...Object.keys(NN_EVAL_EXT), ...(ctx.postIds ?? [])];
|
|
1799
|
+
return [{ label: "contract", ...assertContractMatch({ contractRows: parseContractNN(ctx.contractText), checkIds, registryIds }), evidence: [ctx.contractFile ?? CONTRACT_FILE] }];
|
|
1800
|
+
},
|
|
1801
|
+
NN34: () => [],
|
|
1802
|
+
NN35: () => [],
|
|
1803
|
+
NN36: (ctx) => [{ label: "lock", ...lockProblems({ rootDir: ctx.rootDir, paths: ["packages/release/gate-acceptance.mjs", "ci/gate-acceptance-budgets.json", "docs/GATE-CONTRACT.md"], budgetsRel: "ci/gate-acceptance-budgets.json", contractRel: "docs/GATE-CONTRACT.md", fixtureCommit: ctx.fixtureCommit, pin: ctx.budgets?.fixture?.commit }), evidence: ["git history of the runner, the contract table, the budgets file"] }],
|
|
1804
|
+
NN37: (ctx) => [{ label: "review", ...reviewProblems({ budgets: ctx.budgets, runnerSha256: ctx.runnerSha256, contractSha256: ctx.contractSha256 }), evidence: [BUDGETS_FILE] }],
|
|
1805
|
+
NN39: (ctx) => {
|
|
1806
|
+
const out = [];
|
|
1807
|
+
for (const label of ["S1:check", "S11:check", "S1:compile", "S11:compile"].filter((l) => ctx.runs[l])) {
|
|
1808
|
+
const w = usableRun(ctx, label, RED); if (w.fail) { out.push(w.fail); continue; }
|
|
1809
|
+
const l = ledgerOf(w.run, label); if (l.fail) { out.push(l.fail); continue; }
|
|
1810
|
+
const ranA = [...w.run.rows.values()].filter((r) => r.class === "A" && r.coverage === "ran").length;
|
|
1811
|
+
out.push(checkFor(label, assertRealParallelism(l.entries, { lanes: ctx.cores, ranA }), [w.run.ledgerPath]));
|
|
1812
|
+
}
|
|
1813
|
+
return out;
|
|
1814
|
+
},
|
|
1815
|
+
NN40: (ctx) => {
|
|
1816
|
+
const labels = Object.keys(ctx.runs).filter((l) => ctx.runs[l].stage === "compile" && ctx.runs[l].ladder && !ctx.runs[l].kill && /^(S1|S2|S11):compile\d?$/.test(l));
|
|
1817
|
+
if (!labels.length) return [bad("S2:compile", ["no compile run exists, so no doc evidence exists (a run with --checks-only has none)"])];
|
|
1818
|
+
return labels.map((label) => { const w = usableRun(ctx, label, RED); if (w.fail) return w.fail; const l = ledgerOf(w.run, label); return l.fail ?? checkFor(label, assertDocOneCommand(w.run.rows, l.entries, { label }), [w.run.ledgerPath, ...w.run.coveragePaths]); });
|
|
1819
|
+
},
|
|
1820
|
+
NN41: (ctx) => {
|
|
1821
|
+
const a = usableRun(ctx, "S17:fail1", RED); const b = usableRun(ctx, "S17:fail2", RED); if (a.fail || b.fail) return [a.fail ?? b.fail];
|
|
1822
|
+
const c = ctx.runs["S17:fail3"] ? usableRun(ctx, "S17:fail3", RED) : null; if (c?.fail) return [c.fail];
|
|
1823
|
+
return [checkFor("S17", assertCachedFailure(a.run.rows, b.run.rows, c?.run.rows ?? null, { identity: ctx.identityChange ?? "" }), [...a.run.coveragePaths, ...b.run.coveragePaths, ...(c?.run.coveragePaths ?? [])])];
|
|
1824
|
+
},
|
|
1825
|
+
NN42: (ctx) => {
|
|
1826
|
+
const labels = Object.keys(ctx.runs).filter((l) => ctx.runs[l].stage === "compile" && ctx.runs[l].ladder && !ctx.runs[l].kill && /^(S1|S2|S11):compile\d?$/.test(l));
|
|
1827
|
+
if (!labels.length) return [bad("S2:compile", ["no compile run exists, so no cross-target evidence exists"])];
|
|
1828
|
+
return labels.map((label) => { const w = usableRun(ctx, label, RED); if (w.fail) return w.fail; const l = ledgerOf(w.run, label); return l.fail ?? checkFor(label, assertCrossTargetsOneCommand(w.run.log, l.entries, w.run.rows, { label }), [w.run.ledgerPath, w.run.logPath]); });
|
|
1829
|
+
},
|
|
1830
|
+
NN38: (ctx) => [{ label: "limited evidence", ...assertLimitedEvidence(ctx.runs), evidence: Object.values(ctx.runs).flatMap((r) => r.coveragePaths ?? []).slice(0, 3) }],
|
|
1831
|
+
};
|
|
1832
|
+
|
|
1833
|
+
const PREV_WARM = Object.freeze({ "S2:check": "S1:check", "S2:compile": "S1:compile", "S2:check2": "S2:check", "S2:compile2": "S2:compile" });
|
|
1834
|
+
const kindOf = (label) => (/compile/.test(label) ? "compile" : "check");
|
|
1835
|
+
const bad = (label, problems, evidence = []) => ({ label, ok: false, problems, evidence });
|
|
1836
|
+
const checkFor = (label, res, evidence) => ({ label, ok: res.ok, problems: res.problems, evidence });
|
|
1837
|
+
|
|
1838
|
+
/** A run usable as warm or edit evidence: it executed, exited 0 and wrote coverage rows; otherwise a failing check names why. */
|
|
1839
|
+
function usableRun(ctx, label, { rows = true, red = false } = {}) {
|
|
1840
|
+
const run = ctx.runs[label];
|
|
1841
|
+
if (!run) return { fail: bad(label, [`run ${label} did not execute, so its evidence does not exist`]) };
|
|
1842
|
+
// `red`: Class A coverage, keys, ledger and log lines of a compile that failed in Class B are still evidence of the Class A properties (NN01, 05, 06, 10, 12, 14, 15).
|
|
1843
|
+
if (run.exit !== 0 && !(red && run.rows)) return { fail: bad(label, [`run ${label} exited ${run.exit}${run.timedOut ? " (timed out)" : ""}: its evidence cannot stand for a passing run`], [run.logPath]) };
|
|
1844
|
+
if (rows && !run.rows) return { fail: bad(label, [`run ${label} wrote no readable coverage report`], [run.logPath]) };
|
|
1845
|
+
return { run };
|
|
1846
|
+
}
|
|
1847
|
+
/** The run's spawn ledger entries, or a failing check: the gate under test must emit it (RK_GATE_SPAWN_LEDGER). */
|
|
1848
|
+
function ledgerOf(run, label) {
|
|
1849
|
+
if (!run.ledgerPath) return { fail: bad(label, [`run ${label} was not started with RK_GATE_SPAWN_LEDGER`]) };
|
|
1850
|
+
if (!run.ledger) return { fail: bad(label, [`run ${label} wrote no spawn ledger at ${run.ledgerPath}: the gate under test does not emit RK_GATE_SPAWN_LEDGER (spawn-ledger.mjs installed by the gate entry)`], [run.ledgerPath]) };
|
|
1851
|
+
if (run.ledger.problems.length) return { fail: bad(label, run.ledger.problems.slice(0, 5), [run.ledgerPath]) };
|
|
1852
|
+
if (run.ledger.entries.length === 0) return { fail: bad(label, [`the spawn ledger ${run.ledgerPath} is empty: a gate run starts child processes, so it was not recorded`], [run.ledgerPath]) };
|
|
1853
|
+
return { entries: run.ledger.entries };
|
|
1854
|
+
}
|
|
1855
|
+
const warmRuns = (ctx, opts = {}) => (ctx.warmLabels ?? WARM_LABELS).map((label) => ({ label, ...usableRun(ctx, label, opts) }));
|
|
1856
|
+
const RED = { red: true };
|
|
1857
|
+
const ledgerRuns = (ctx) => Object.entries(ctx.runs).filter(([, r]) => r.ledgerPath !== undefined && !r.kill);
|
|
1858
|
+
|
|
1859
|
+
const NN_EVAL = {
|
|
1860
|
+
NN01: (ctx) => warmRuns(ctx, RED).flatMap((w) => {
|
|
1861
|
+
if (w.fail) return [w.fail];
|
|
1862
|
+
const out = [checkFor(w.label, assertNoClassARan(w.run.rows), w.run.coveragePaths)];
|
|
1863
|
+
if (ctx.extended) { const l = ledgerOf(w.run, w.label); out.push(l.fail ?? checkFor(`${w.label} ledger`, assertHitRowsStartedNoTool(w.run.rows, l.entries), [w.run.ledgerPath])); }
|
|
1864
|
+
return out;
|
|
1865
|
+
}),
|
|
1866
|
+
NN02: (ctx) => ["S2:compile", "S2:compile2"].map((label) => {
|
|
1867
|
+
const w = usableRun(ctx, label); if (w.fail) return w.fail;
|
|
1868
|
+
const prev = ctx.runs["S1:compile"]?.rows ?? null;
|
|
1869
|
+
const r = assertNoClassBRan(w.run.rows, prev, { strict: Boolean(ctx.extended) });
|
|
1870
|
+
return { ...checkFor(label, r, w.run.coveragePaths), reported: r.reported };
|
|
1871
|
+
}),
|
|
1872
|
+
NN03: (ctx) => {
|
|
1873
|
+
const s3 = usableRun(ctx, "S3:check"); if (s3.fail) return [{ ...s3.fail, problems: [...s3.fail.problems, ctx.s3Why ?? ""].filter(Boolean) }];
|
|
1874
|
+
const prev = ctx.runs["S2:check2"]?.rows ?? ctx.runs["S2:check"]?.rows ?? ctx.runs["S1:check"]?.rows;
|
|
1875
|
+
if (!prev) return [bad("S3:check", ["no earlier check run to compare the edit against"])];
|
|
1876
|
+
const out = [checkFor("S3:check", assertOneFileEdit(prev, s3.run.rows), [...s3.run.coveragePaths])];
|
|
1877
|
+
if (ctx.extended) { const l = ledgerOf(s3.run, "S3:check"); out.push(l.fail ?? checkFor("S3:check files read", assertEditedFilesRead(s3.run.rows, l.entries, { files: [ctx.s3File] }), [s3.run.ledgerPath, ...s3.run.coveragePaths])); }
|
|
1878
|
+
return out;
|
|
1879
|
+
},
|
|
1880
|
+
NN04: (ctx) => {
|
|
1881
|
+
const s4 = usableRun(ctx, "S4:check"); if (s4.fail) return [{ ...s4.fail, problems: [...s4.fail.problems, ctx.s4Why ?? ""].filter(Boolean) }];
|
|
1882
|
+
if (!s4.run.manifestInfo) return [bad("S4:check", ["the edited manifest's workspace is not known"])];
|
|
1883
|
+
const out = [checkFor("S4:check", assertOtherWorkspacesIdle(s4.run.rows, s4.run.manifestInfo), s4.run.coveragePaths)];
|
|
1884
|
+
if (ctx.extended) { const c = usableRun(ctx, "S12:manifest", RED); out.push(c.fail ?? checkFor("S12:manifest (--to compile)", assertOtherWorkspacesIdleAny(c.run.rows, { workspace: s4.run.manifestInfo.workspace }), c.run.coveragePaths)); }
|
|
1885
|
+
return out;
|
|
1886
|
+
},
|
|
1887
|
+
NN05: (ctx) => [["S2:check", "S2:check2"], ["S2:compile", "S2:compile2"]].map(([a, b]) => {
|
|
1888
|
+
const x = usableRun(ctx, a, RED); const y = usableRun(ctx, b, RED);
|
|
1889
|
+
if (x.fail || y.fail) return x.fail ?? y.fail;
|
|
1890
|
+
return checkFor(`${a} vs ${b}`, assertKeysStable(x.run.rows, y.run.rows), [...x.run.coveragePaths, ...y.run.coveragePaths]);
|
|
1891
|
+
}),
|
|
1892
|
+
NN06: (ctx) => {
|
|
1893
|
+
const labels = ["S1:check", "S1:compile", ...WARM_LABELS, "S3:check", "S4:check"].filter((l) => ctx.runs[l]);
|
|
1894
|
+
const digests = new Set();
|
|
1895
|
+
for (const l of labels) { const d = envDigestOf(ctx.runs[l].log); if (d?.env) digests.add(d.env); if (d?.start) digests.add(d.start); }
|
|
1896
|
+
const out = [];
|
|
1897
|
+
for (const l of labels) { const w = usableRun(ctx, l, RED); if (w.fail) { out.push(w.fail); continue; } out.push(checkFor(l, assertEnvDigestScope(w.run.rows, [...digests]), w.run.coveragePaths)); }
|
|
1898
|
+
return out.length ? out : [bad("S1/S2", ["no check or compile run produced coverage keys"])];
|
|
1899
|
+
},
|
|
1900
|
+
NN07: (ctx) => ledgerRuns(ctx).map(([label, run]) => { const l = ledgerOf(run, label); return l.fail ?? checkFor(label, assertNoDuplicateSpawns(l.entries), [run.ledgerPath]); }),
|
|
1901
|
+
NN08: (ctx) => ledgerRuns(ctx).filter(([, r]) => r.exit === 0).map(([label, run]) => { const l = ledgerOf(run, label); return l.fail ?? checkFor(label, assertRustfmtSpawns(l.entries, run.rows), [run.ledgerPath, ...run.coveragePaths]); }),
|
|
1902
|
+
NN09: (ctx) => ledgerRuns(ctx).map(([label, run]) => { const l = ledgerOf(run, label); if (l.fail) return l.fail; const a = assertNoBrokerNonCompiling(l.entries); const v = ctx.extended ? assertNoBrokerVersion(l.entries) : { problems: [] }; return checkFor(label, { ok: a.ok && !v.problems.length, problems: [...a.problems, ...v.problems] }, [run.ledgerPath]); }),
|
|
1903
|
+
NN10: (ctx) => warmRuns(ctx, RED).map((w) => { if (w.fail) return w.fail; const l = ledgerOf(w.run, w.label); return l.fail ?? checkFor(w.label, assertNoRealCargoMetadata(l.entries), [w.run.ledgerPath]); }),
|
|
1904
|
+
NN11: (ctx) => {
|
|
1905
|
+
const cold = ["S1:check", "S1:compile"].filter((l) => ctx.runs[l]);
|
|
1906
|
+
const out = cold.map((label) => checkFor(label, assertSnapshotProof(ctx.runs[label].log, { warm: false }), [ctx.runs[label].logPath]));
|
|
1907
|
+
for (const w of warmRuns(ctx, RED)) {
|
|
1908
|
+
if (w.fail) { out.push(w.fail); continue; }
|
|
1909
|
+
out.push(checkFor(w.label, assertSnapshotProof(w.run.log, { warm: true }), [w.run.logPath]));
|
|
1910
|
+
if (ctx.extended) { const l = ledgerOf(w.run, w.label); out.push(l.fail ?? checkFor(`${w.label} ledger`, assertLedgerAgreesWithProof(w.run.log, l.entries), [w.run.logPath, w.run.ledgerPath])); }
|
|
1911
|
+
}
|
|
1912
|
+
return out;
|
|
1913
|
+
},
|
|
1914
|
+
NN12: (ctx) => {
|
|
1915
|
+
const out = warmRuns(ctx, RED).map((w) => { if (w.fail) return w.fail; const l = ledgerOf(w.run, w.label); return l.fail ?? checkFor(w.label, assertDependencyReuse(w.run.log, l.entries), [w.run.logPath, w.run.ledgerPath]); });
|
|
1916
|
+
for (const [a, b] of [["S2:check", "S2:check2"], ["S2:compile", "S2:compile2"]]) {
|
|
1917
|
+
const x = ctx.runs[a]; const y = ctx.runs[b];
|
|
1918
|
+
if (x && y) out.push(checkFor(`${a} vs ${b}`, assertDigestStable(x.log, y.log), [x.logPath, y.logPath]));
|
|
1919
|
+
}
|
|
1920
|
+
return out;
|
|
1921
|
+
},
|
|
1922
|
+
NN13: (ctx) => {
|
|
1923
|
+
const out = Object.entries(ctx.runs).filter(([, r]) => r.stage === "check" && r.ledgerPath !== undefined && !r.kill).flatMap(([label, r]) => {
|
|
1924
|
+
const a = checkFor(label, assertNoOwnershipOnCheck(r.log), [r.logPath]);
|
|
1925
|
+
if (!ctx.extended) return [a];
|
|
1926
|
+
const l = ledgerOf(r, label);
|
|
1927
|
+
return [a, l.fail ?? checkFor(`${label} ledger`, assertNoOwnershipProbe(l.entries), [r.ledgerPath])];
|
|
1928
|
+
});
|
|
1929
|
+
return out;
|
|
1930
|
+
},
|
|
1931
|
+
NN14: (ctx) => warmRuns(ctx, RED).map((w) => w.fail ?? checkFor(w.label, assertRulesCached(w.run.log), [w.run.logPath])),
|
|
1932
|
+
NN15: (ctx) => warmRuns(ctx, RED).map((w) => {
|
|
1933
|
+
if (w.fail) return w.fail;
|
|
1934
|
+
const prevRun = ctx.runs[PREV_WARM[w.label]];
|
|
1935
|
+
return checkFor(w.label, assertAdviceCached(prevRun?.rows ?? null, w.run.rows, { startedAt: w.run.coverageStarts?.[0], prevStartedAt: prevRun?.coverageStarts?.[0] }), w.run.coveragePaths);
|
|
1936
|
+
}),
|
|
1937
|
+
NN16: (ctx) => {
|
|
1938
|
+
const run = ctx.runs["S10:units"];
|
|
1939
|
+
if (!run) return [bad("S10:units", [ctx.unitsWhy ?? "the unit-list run did not execute"])];
|
|
1940
|
+
const l = ledgerOf(run, "S10:units"); if (l.fail) return [run.exit !== 0 ? bad("S10:units", [`the unit-list run exited ${run.exit}`, ...l.fail.problems], [run.logPath]) : l.fail];
|
|
1941
|
+
const a = assertUnitListShare(run.log, l.entries, { units: run.units?.length ?? 0 });
|
|
1942
|
+
return [checkFor("S10:units", { ok: a.ok && run.exit === 0, problems: [...a.problems, ...(run.exit === 0 ? [] : [`the unit-list run exited ${run.exit}`])] }, [run.logPath, run.ledgerPath])];
|
|
1943
|
+
},
|
|
1944
|
+
NN17: (ctx) => {
|
|
1945
|
+
const labels = Object.keys(ctx.runs).filter((l) => /^S[12]:/.test(l) && ctx.runs[l].ledgerPath !== undefined && /class A scans \d+ at a time/.test(ctx.runs[l].log));
|
|
1946
|
+
const out = labels.map((l) => checkFor(`lanes ${l}`, assertLanes(ctx.runs[l].log, { cores: ctx.cores, jobsOverride: ctx.jobsEnv }), [ctx.runs[l].logPath]));
|
|
1947
|
+
if (!out.length) out.push(bad("lanes", ["no run's log has a `class A scans N at a time` line"]));
|
|
1948
|
+
const compiles = ["S1:compile", "S2:compile", "S2:compile2"].filter((l) => ctx.runs[l]);
|
|
1949
|
+
if (!compiles.length) out.push(bad("batching", ["no compile run to read the class B batching note from"]));
|
|
1950
|
+
for (const l of compiles) { const run = ctx.runs[l]; const le = ledgerOf(run, l); out.push(le.fail ?? checkFor(`batching ${l}`, assertBatching(run.log, le.entries, { exit: run.exit }), [run.logPath, run.ledgerPath])); }
|
|
1951
|
+
return out;
|
|
1952
|
+
},
|
|
1953
|
+
NN18: (ctx) => {
|
|
1954
|
+
const runs = []; const out = [];
|
|
1955
|
+
if (ctx.budgetProblem) out.push(bad("budgets", [ctx.budgetProblem], [BUDGETS_FILE]));
|
|
1956
|
+
for (const w of warmRuns(ctx)) {
|
|
1957
|
+
if (w.fail) { out.push(w.fail); continue; }
|
|
1958
|
+
const m = stageMarks(w.run.log, w.run.startedMs);
|
|
1959
|
+
if (m.problems.length) out.push(bad(w.label, m.problems, [w.run.logPath]));
|
|
1960
|
+
runs.push({ label: w.label, kind: kindOf(w.label), ms: w.run.ms, marks: m.marks });
|
|
1961
|
+
}
|
|
1962
|
+
if (!ctx.budgetProblem) out.push(checkFor("budget", assertBudget({ host: ctx.host, budgets: ctx.budgets, runs }), [BUDGETS_FILE]));
|
|
1963
|
+
out.measured = runs;
|
|
1964
|
+
if (ctx.extended) out.push(...windowChecks(ctx));
|
|
1965
|
+
return out;
|
|
1966
|
+
},
|
|
1967
|
+
NN19: (ctx) => {
|
|
1968
|
+
const id = ctx.gateIdentity ?? { ok: false, problems: ["the gate's identity was not established"] };
|
|
1969
|
+
const dev = id.kind === "named" ? { ok: false, problems: ["development run: the gate under test is a named gate, not the newest sealed trusted gate; its results are development evidence and never count"] } : { ok: true, problems: [] };
|
|
1970
|
+
return [checkFor("gate", { ok: id.ok && dev.ok, problems: [...id.problems, ...dev.problems] }, [ctx.gateIdentityEvidence ?? "--version, launcher"])];
|
|
1971
|
+
},
|
|
1972
|
+
};
|
|
1973
|
+
|
|
1974
|
+
/** NN18 over every run that has a workload profile: windows tile launch to exit; every required (workload, profile) cell must have a run. */
|
|
1975
|
+
function windowChecks(ctx) {
|
|
1976
|
+
const out = []; const runs = [];
|
|
1977
|
+
for (const [label, run] of Object.entries(ctx.runs)) {
|
|
1978
|
+
if (!run.profile || run.kill) continue;
|
|
1979
|
+
const m = windowMarks(run.log, run.startedMs, run.startedMs + run.ms);
|
|
1980
|
+
if (m.problems.length) { out.push(bad(label, m.problems, [run.logPath])); continue; }
|
|
1981
|
+
runs.push({ label, workload: run.workload, profile: run.profile, ms: run.ms, windows: m.windows, rows: run.rows });
|
|
1982
|
+
}
|
|
1983
|
+
for (const [wl, pr] of REQUIRED_CELLS) if (!runs.some((r) => r.workload === wl && r.profile === pr) && !out.some((o) => o.label?.startsWith?.(`${wl}:${pr}`))) out.push(bad(`${wl}:${pr}`, [ctx.cellWhy?.[`${wl}:${pr}`] ?? "no run measured this workload and profile"]));
|
|
1984
|
+
if (runs.length) out.push(checkFor("windows", assertWindowBudgets({ host: ctx.host, budgets: ctx.budgets, runs }), [BUDGETS_FILE]));
|
|
1985
|
+
return out;
|
|
1986
|
+
}
|
|
1987
|
+
|
|
1988
|
+
/** One result per non-negotiable: `{ id, title, steps, status: "pass"|"fail"|"not-evaluated", problems[], checks[], evidence[] }`. A selected NN with no evidence fails. */
|
|
1989
|
+
export function evaluateNonNegotiables(ctx) {
|
|
1990
|
+
const wanted = new Set(ctx.wanted ?? []);
|
|
1991
|
+
const set = ctx.nnSet ?? NN;
|
|
1992
|
+
const done = []; ctx.nnSoFar = done;
|
|
1993
|
+
return set.map((nn) => { const res = evalOne(nn); done.push(res); return res; });
|
|
1994
|
+
function evalOne(nn) {
|
|
1995
|
+
const base = { id: nn.id, title: nn.title, steps: nn.steps, evidenceSource: nn.evidence };
|
|
1996
|
+
// Evaluated only when every step that produces its evidence was selected: a subset run cannot judge it, and says so (the verdict marks the run partial).
|
|
1997
|
+
if (ctx.forceNN ? !ctx.forceNN.includes(nn.id) : (!nn.always && !nn.steps.every((s) => wanted.has(s)))) return { ...base, status: "not-evaluated", problems: [`steps ${nn.steps.filter((x) => !wanted.has(x)).join(", ")} not selected`], checks: [], evidence: [] };
|
|
1998
|
+
let checks;
|
|
1999
|
+
if (nn.post) return { ...base, status: "pass", problems: [], checks: [], evidence: [], pending: true };
|
|
2000
|
+
try { checks = (NN_EVAL[nn.id] ?? NN_EVAL_EXT[nn.id])(ctx); } catch (e) { checks = [bad("assertion", [`assertion threw: ${e.stack ?? e.message}`])]; }
|
|
2001
|
+
const measured = checks.measured;
|
|
2002
|
+
if (!checks.length) checks = [bad("evidence", [`no evidence for ${nn.id}: ${nn.evidence}`])];
|
|
2003
|
+
const failed = checks.filter((c) => !c.ok);
|
|
2004
|
+
return { ...base, status: failed.length ? "fail" : "pass", problems: failed.flatMap((c) => c.problems.map((p) => (c.label ? `${c.label}: ${p}` : p))), checks: checks.map((c) => ({ label: c.label, ok: c.ok, ...(c.reported?.length ? { reported: c.reported } : {}) })), evidence: [...new Set(checks.flatMap((c) => c.evidence ?? []))], ...(measured ? { measured } : {}) };
|
|
2005
|
+
}
|
|
2006
|
+
}
|
|
2007
|
+
|
|
699
2008
|
export const CHECKS = {
|
|
700
2009
|
"GC-A21": (ctx) => {
|
|
701
2010
|
const out = [];
|
|
@@ -937,7 +2246,7 @@ export function summarizeClause(id, checks, { allowInstall = true } = {}) {
|
|
|
937
2246
|
/** Steps a PASS tolerates as unchecked: unchecked by design (S5). Any other selected step that did not pass blocks the verdict. */
|
|
938
2247
|
const BY_DESIGN_UNCHECKED = new Set(STEPS.filter((s) => s.byDesignUnchecked).map((s) => s.id));
|
|
939
2248
|
|
|
940
|
-
export function buildResult({ host, gate, broker, commit, steps, clauseChecks, startedAt, endedAt, notes = [], allowInstall = true, stepChecks = [] }) {
|
|
2249
|
+
export function buildResult({ host, gate, broker, commit, steps, clauseChecks, startedAt, endedAt, notes = [], allowInstall = true, stepChecks = [], nonNegotiables = [], nnIds = NN_IDS, development = false, waivers = [] }) {
|
|
941
2250
|
const clauses = Object.keys(CLAUSES).map((id) => summarizeClause(id, clauseChecks[id], { allowInstall }));
|
|
942
2251
|
const counts = { pass: 0, fail: 0, unchecked: 0 };
|
|
943
2252
|
for (const c of clauses) counts[c.status] += 1;
|
|
@@ -948,19 +2257,33 @@ export function buildResult({ host, gate, broker, commit, steps, clauseChecks, s
|
|
|
948
2257
|
...stepsOut.filter((s) => s.status === "unchecked" && !BY_DESIGN_UNCHECKED.has(s.id)).map((s) => `step ${s.id} did not run as specified`),
|
|
949
2258
|
...stepChecks.filter((c) => !c.ok).map((c) => `${c.step} check "${c.name}" failed`),
|
|
950
2259
|
];
|
|
951
|
-
if (counts.pass === 0) blockers.push("no clause passed");
|
|
952
2260
|
const partial = stepsOut.length < STEPS.length;
|
|
2261
|
+
// Non-negotiables (GC-A27): any failure blocks; in a full run every one must be present and passing (never unchecked, never absent).
|
|
2262
|
+
const nnById = new Map(nonNegotiables.map((n) => [n.id, n]));
|
|
2263
|
+
const nnCounts = { pass: 0, fail: 0, notEvaluated: 0 };
|
|
2264
|
+
for (const id of nnIds) {
|
|
2265
|
+
const n = nnById.get(id);
|
|
2266
|
+
if (n?.status === "pass") nnCounts.pass += 1;
|
|
2267
|
+
else if (n?.status === "not-evaluated" && partial) nnCounts.notEvaluated += 1;
|
|
2268
|
+
else { nnCounts.fail += 1; blockers.push(n ? (n.status === "fail" ? `non-negotiable ${id} failed` : `non-negotiable ${id} was not evaluated in a full run`) : `non-negotiable ${id} has no result`); }
|
|
2269
|
+
}
|
|
2270
|
+
if (counts.pass === 0) blockers.push("no clause passed");
|
|
2271
|
+
// NN34: a run of some steps never prints PASS. NN19: a run of a gate that is not the newest sealed trusted gate is a development run.
|
|
2272
|
+
if (partial) blockers.push(`partial run (steps ${stepsOut.map((s) => s.id).join(",")} only): a partial run never passes`);
|
|
2273
|
+
if (development) blockers.push("development run: the gate under test is not the newest sealed trusted gate; the run prints results and never passes");
|
|
953
2274
|
const ok = blockers.length === 0;
|
|
954
2275
|
const asserted = counts.pass + counts.fail;
|
|
955
|
-
const
|
|
956
|
-
const
|
|
957
|
-
|
|
2276
|
+
const nnText = `non-negotiables ${nnCounts.pass} of ${nnIds.length} passed${nnCounts.notEvaluated ? `, ${nnCounts.notEvaluated} not evaluated (steps not selected)` : ""}${nnCounts.fail ? `, ${nnCounts.fail} failed` : ""}`;
|
|
2277
|
+
const tail = `${asserted} of ${clauses.length} asserted, ${counts.unchecked} unchecked; ${nnText}`;
|
|
2278
|
+
const verdictText = ok ? `PASS (${tail})` : `NOT PASSED (${development ? "development run; " : ""}${tail}${partial && stepsOut.length ? `; partial run: steps ${stepsOut.map((s) => s.id).join(",")} only` : ""}; ${counts.fail} failed clause(s); ${blockers.length} blocker(s))`;
|
|
2279
|
+
return { schema: RESULT_SCHEMA, host, gate, broker, fixtureCommit: commit, startedAt, endedAt, steps: stepsOut, stepChecks, clauses, nonNegotiables, totals: { clauses: clauses.length, ...counts, nonNegotiables: nnCounts }, ok, verdict: verdictText, blockers, partial, development, waivers, notes };
|
|
958
2280
|
}
|
|
959
2281
|
|
|
960
2282
|
export function formatSummary(result) {
|
|
961
2283
|
const lines = [`gate acceptance ${result.verdict} host ${result.host} commit ${String(result.fixtureCommit).slice(0, 12)}`, `clauses: ${result.totals.pass} pass, ${result.totals.fail} fail, ${result.totals.unchecked} unchecked of ${result.totals.clauses}`];
|
|
962
2284
|
for (const b of result.blockers) lines.push(` BLOCKER ${b}`);
|
|
963
2285
|
for (const c of result.clauses.filter((x) => x.status === "fail")) lines.push(` FAIL ${c.id}: ${c.problems.slice(0, 2).join(" | ").slice(0, 200)} [${c.evidence.slice(0, 2).join(", ")}]`);
|
|
2286
|
+
for (const n of (result.nonNegotiables ?? [])) lines.push(` ${n.id} ${n.status}${n.status === "fail" ? `: ${n.problems.slice(0, 2).join(" | ").slice(0, 220)}` : ""}`);
|
|
964
2287
|
for (const sc of (result.stepChecks ?? []).filter((x) => !x.ok)) lines.push(` FAIL ${sc.step} ${sc.name}: ${sc.problems.slice(0, 2).join(" | ").slice(0, 200)}`);
|
|
965
2288
|
for (const s of result.steps) lines.push(` ${s.id} ${s.status} ${s.title}`);
|
|
966
2289
|
return lines.join("\n");
|
|
@@ -979,6 +2302,16 @@ function git(cwd, args, { env = {}, input, buffer = false } = {}) {
|
|
|
979
2302
|
}
|
|
980
2303
|
|
|
981
2304
|
/** Workspace directory a Cargo manifest belongs to: the nearest ancestor directory in `wsDirs`, else the manifest's own directory (a standalone package). */
|
|
2305
|
+
/** Up to `n` unit selectors of the gate's grammar (crate and npm units named by a commit's tracked files), in sorted order. */
|
|
2306
|
+
export function unitSelectorsOf(tracked, n = 2) {
|
|
2307
|
+
const out = [];
|
|
2308
|
+
for (const f of [...tracked].sort()) {
|
|
2309
|
+
const c = /^crates\/(rightkit-[a-z0-9-]+)\/Cargo\.toml$/.exec(f); const p = /^packages\/([a-z0-9-]+)\/package\.json$/.exec(f);
|
|
2310
|
+
if (c) out.push(`cargo:${c[1]}`); else if (p) out.push(`npm:@rightkit/${p[1]}`);
|
|
2311
|
+
}
|
|
2312
|
+
return out.slice(0, n);
|
|
2313
|
+
}
|
|
2314
|
+
|
|
982
2315
|
export function cargoWorkspaceOf(file, wsDirs) {
|
|
983
2316
|
const dir = path.posix.dirname(file);
|
|
984
2317
|
for (let d = dir; ; d = path.posix.dirname(d)) {
|
|
@@ -1136,11 +2469,11 @@ function signalGroup(child, signal) {
|
|
|
1136
2469
|
function runGate({ gate, cwd, args, env = process.env, timeoutMs = 3_600_000 }) {
|
|
1137
2470
|
return new Promise((resolve) => {
|
|
1138
2471
|
const t0 = Date.now(); let log = ""; let timedOut = false; let child;
|
|
1139
|
-
try { child = launch({ gate, args, cwd, env }); } catch (e) { resolve({ exit: null, signal: null, log: `spawn error: ${e.message}`, ms: 0, timedOut: false }); return; }
|
|
2472
|
+
try { child = launch({ gate, args, cwd, env }); } catch (e) { resolve({ exit: null, signal: null, log: `spawn error: ${e.message}`, ms: 0, startedMs: t0, timedOut: false }); return; }
|
|
1140
2473
|
const timer = setTimeout(() => { timedOut = true; signalGroup(child, "SIGKILL"); }, timeoutMs);
|
|
1141
2474
|
child.stdout.on("data", (d) => { log += d; }); child.stderr.on("data", (d) => { log += d; });
|
|
1142
|
-
child.on("close", (exit, signal) => { clearTimeout(timer); resolve({ exit, signal, log: timedOut ? `${log}\ngate-acceptance: timed out after ${timeoutMs} ms; the process group was killed` : log, ms: Date.now() - t0, timedOut }); });
|
|
1143
|
-
child.on("error", (e) => { clearTimeout(timer); resolve({ exit: null, signal: null, log: `${log}\nspawn error: ${e.message}`, ms: Date.now() - t0, timedOut }); });
|
|
2475
|
+
child.on("close", (exit, signal) => { clearTimeout(timer); resolve({ exit, signal, log: timedOut ? `${log}\ngate-acceptance: timed out after ${timeoutMs} ms; the process group was killed` : log, ms: Date.now() - t0, startedMs: t0, timedOut }); });
|
|
2476
|
+
child.on("error", (e) => { clearTimeout(timer); resolve({ exit: null, signal: null, log: `${log}\nspawn error: ${e.message}`, ms: Date.now() - t0, startedMs: t0, timedOut }); });
|
|
1144
2477
|
});
|
|
1145
2478
|
}
|
|
1146
2479
|
|
|
@@ -1199,10 +2532,70 @@ function readSourceIdentity(snapshotPath, commit, g) {
|
|
|
1199
2532
|
try { return { file, identity: JSON.parse(fs.readFileSync(file, "utf8")), trees: g.sourceTrees(commit) }; } catch (e) { return { file, error: `cannot read ${file}: ${e.message}` }; }
|
|
1200
2533
|
}
|
|
1201
2534
|
|
|
2535
|
+
/** The resident gate's script for the gate under test. */
|
|
2536
|
+
function gateServeScriptFor({ gateArg, kind, installed }) {
|
|
2537
|
+
if (gateArg && /\.mjs$/.test(gateArg)) return path.join(path.dirname(path.dirname(path.resolve(gateArg))), "gate-serve.mjs");
|
|
2538
|
+
if (kind === "installed" && installed) return path.join(path.dirname(path.dirname(installed.entry)), "gate-serve.mjs");
|
|
2539
|
+
return path.join(here, "gate-serve.mjs");
|
|
2540
|
+
}
|
|
2541
|
+
|
|
2542
|
+
/** The crate a one-crate edit changes in workspace `ws`: one with dependencies and no dependents (a leaf), its file and the workspace's dependency map. */
|
|
2543
|
+
export function crateEditInfo({ layout, tracked, ws = "rk" }) {
|
|
2544
|
+
const texts = {}; const fileOf = {};
|
|
2545
|
+
for (const f of layout.manifests) {
|
|
2546
|
+
const name = /\[package\][^[]*?\bname\s*=\s*"([^"]+)"/s.exec(layout.texts.get(f))?.[1];
|
|
2547
|
+
if (!name || cargoWorkspaceOf(f, layout.wsDirs) !== ws) continue;
|
|
2548
|
+
texts[name] = layout.texts.get(f); fileOf[name] = f;
|
|
2549
|
+
}
|
|
2550
|
+
const deps = crateDeps(texts);
|
|
2551
|
+
const dependents = (c) => Object.entries(deps).filter(([, ds]) => ds.includes(c)).map(([n]) => n);
|
|
2552
|
+
const leaf = Object.keys(deps).sort().find((c) => deps[c].length > 0 && dependents(c).length === 0);
|
|
2553
|
+
if (!leaf) return { why: `workspace ${ws} has no crate with a dependency and no dependents (a leaf to edit)` };
|
|
2554
|
+
const dir = path.posix.dirname(fileOf[leaf]);
|
|
2555
|
+
const file = [`${dir}/src/lib.rs`, `${dir}/src/main.rs`].find((f) => tracked.includes(f));
|
|
2556
|
+
return file ? { workspace: ws, crate: leaf, deps, file } : { why: `crate ${leaf} has no tracked src/lib.rs or src/main.rs` };
|
|
2557
|
+
}
|
|
2558
|
+
|
|
2559
|
+
/** NN31: the text of every file that could release, upload or promote a gate. */
|
|
2560
|
+
export function collectTooling(rootDir, managedRoot) {
|
|
2561
|
+
const dirs = [path.join(rootDir, "packages", "release"), path.join(rootDir, "packages", "release", "bin"), path.join(rootDir, "scripts"), path.join(rootDir, ".github", "workflows"), path.join(managedRoot, "agent-bin")];
|
|
2562
|
+
const files = {}; const searched = [];
|
|
2563
|
+
for (const d of dirs) {
|
|
2564
|
+
let names; try { names = fs.readdirSync(d, { withFileTypes: true }); } catch { continue; }
|
|
2565
|
+
for (const e of names) {
|
|
2566
|
+
if (!e.isFile() || /^gate-acceptance/.test(e.name) || /\.(png|jpg|zip|gz|dmg)$/.test(e.name)) continue;
|
|
2567
|
+
const f = path.join(d, e.name); searched.push(f);
|
|
2568
|
+
try { const st = fs.statSync(f); if (st.size < 2_000_000) files[f] = fs.readFileSync(f, "utf8"); } catch { /* unreadable: not searched */ }
|
|
2569
|
+
}
|
|
2570
|
+
}
|
|
2571
|
+
return { ...releaseToolingCallsVerify(files), searched };
|
|
2572
|
+
}
|
|
2573
|
+
|
|
2574
|
+
/** Real-condition controls (--prove): assertions applied to the cold run and the real edits, where the violation really happened. Each returns true when the assertion CAUGHT it. */
|
|
2575
|
+
export function coldControls({ cold, warmPrev, warmRows, crate, ws, coldCompileRows }) {
|
|
2576
|
+
const caught = {};
|
|
2577
|
+
if (cold?.rows) {
|
|
2578
|
+
caught.NN01 = !assertNoClassARan(cold.rows).ok;
|
|
2579
|
+
if (warmPrev) caught.NN03 = !assertOneFileEdit(warmPrev, cold.rows).ok;
|
|
2580
|
+
caught.NN04 = !assertOtherWorkspacesIdleAny(cold.rows, { workspace: ws ?? "rk" }).ok;
|
|
2581
|
+
caught.NN21 = !assertLockEditScope(cold.rows, { lockDir: ws ?? "rk" }).ok;
|
|
2582
|
+
caught.NN14 = !assertRulesCached(cold.log).ok;
|
|
2583
|
+
caught.NN15 = !assertAdviceCached(warmPrev ?? new Map(), cold.rows, {}).ok;
|
|
2584
|
+
caught.NN24 = !assertRestartWarm(cold.rows, { killed: true }).ok;
|
|
2585
|
+
if (warmRows) caught.NN29 = !assertIdentityIndependent(warmRows, cold.rows).ok;
|
|
2586
|
+
}
|
|
2587
|
+
if (coldCompileRows) {
|
|
2588
|
+
caught.NN02 = !assertNoClassBRan(coldCompileRows, null, { strict: true }).ok;
|
|
2589
|
+
if (crate) caught.NN20 = !assertCrateEditScope(coldCompileRows, crate).ok;
|
|
2590
|
+
}
|
|
2591
|
+
return caught;
|
|
2592
|
+
}
|
|
2593
|
+
|
|
1202
2594
|
async function main(argv) {
|
|
1203
2595
|
const opt = (name) => { const i = argv.indexOf(name); return i < 0 ? undefined : argv[i + 1]; };
|
|
1204
|
-
const known = new Set(["--fixture", "--host", "--steps", "--out", "--plan", "--gate", "--commit", "--leaf-file", "--manifest-file", "--kill-after-ms", "--allow-install", "--help"]);
|
|
2596
|
+
const known = new Set(["--fixture", "--host", "--steps", "--out", "--plan", "--gate", "--commit", "--leaf-file", "--manifest-file", "--kill-after-ms", "--allow-install", "--budgets", "--help", "--prove", "--verify-release", "--other-receipt", "--contract-file", "--pulse-compile", "--prove-out", "--nn", "--checks-only", "--s11-checks-only", "--kills"]);
|
|
1205
2597
|
for (const a of argv) if (a.startsWith("--") && !known.has(a)) { console.error(`gate-acceptance: unknown option ${a} (no cache bypass or other gate flag is ever passed)`); return 64; }
|
|
2598
|
+
if (argv.includes("--verify-release")) return verifyReleaseCli(argv);
|
|
1206
2599
|
const host = opt("--host") ?? (process.platform === "win32" ? "dell" : "mac");
|
|
1207
2600
|
if (!["mac", "dell"].includes(host)) { console.error("gate-acceptance: --host must be mac or dell"); return 64; }
|
|
1208
2601
|
const wanted = (opt("--steps") ?? STEPS.map((s) => s.id).join(",")).split(",").map((s) => s.trim()).filter(Boolean);
|
|
@@ -1211,8 +2604,9 @@ async function main(argv) {
|
|
|
1211
2604
|
if (allowInstall) console.error("gate-acceptance: --allow-install: --to dev and --to qualify INSTALL an app on this host. Installs need Adrian's approval; this flag is not that approval.");
|
|
1212
2605
|
if (argv.includes("--plan")) { console.log(formatPlan(buildPlan({ steps: wanted, allowInstall }))); return 0; }
|
|
1213
2606
|
const fixture = opt("--fixture");
|
|
2607
|
+
if (argv.includes("--prove")) return proveMain({ fixture, host, out: opt("--prove-out"), argv });
|
|
1214
2608
|
if (!fixture) { console.error("usage: node gate-acceptance.mjs --fixture <dir> [--host mac|dell] [--steps S0,S1,...] [--out <dir>] [--plan] [--gate <path>] [--commit <sha>] [--allow-install]"); return 64; }
|
|
1215
|
-
return execute({ fixture, host, wanted, gate: opt("--gate") ?? defaultGate(host), out: opt("--out"), commitArg: opt("--commit"), leafFile: opt("--leaf-file"), manifestFile: opt("--manifest-file"), killAfterMs: Number(opt("--kill-after-ms") ?? 3000), allowInstall });
|
|
2609
|
+
return execute({ fixture, host, wanted, gate: opt("--gate") ?? defaultGate(host), gateArg: opt("--gate"), budgetsFile: opt("--budgets"), out: opt("--out"), commitArg: opt("--commit"), leafFile: opt("--leaf-file"), manifestFile: opt("--manifest-file"), killAfterMs: Number(opt("--kill-after-ms") ?? 3000), allowInstall, otherReceiptFile: opt("--other-receipt"), contractFile: opt("--contract-file"), pulseCompile: argv.includes("--pulse-compile"), forceNN: opt("--nn")?.split(",").filter(Boolean), checksOnly: argv.includes("--checks-only"), s11ChecksOnly: argv.includes("--s11-checks-only"), killsFilter: opt("--kills")?.split(",").filter(Boolean) });
|
|
1216
2610
|
}
|
|
1217
2611
|
|
|
1218
2612
|
async function execute(options) {
|
|
@@ -1225,13 +2619,14 @@ async function execute(options) {
|
|
|
1225
2619
|
}
|
|
1226
2620
|
}
|
|
1227
2621
|
|
|
1228
|
-
async function executeRun({ fixture, host, wanted, gate, out, commitArg, leafFile, manifestFile, killAfterMs, allowInstall, g, scratch }) {
|
|
2622
|
+
async function executeRun({ fixture, host, wanted, gate, gateArg, budgetsFile, out, commitArg, leafFile, manifestFile, killAfterMs, allowInstall, otherReceiptFile, contractFile, pulseCompile, forceNN, checksOnly, s11ChecksOnly, killsFilter, g, scratch }) {
|
|
1229
2623
|
const startedAt = new Date().toISOString();
|
|
1230
2624
|
const platform = host === "dell" ? "win32" : "darwin";
|
|
1231
2625
|
const managedRoot = managedRootOf(host);
|
|
1232
2626
|
const outDir = out ?? path.join(scratch, "runs", `${host}-${startedAt.replace(/[:.]/g, "-")}`);
|
|
1233
2627
|
fs.mkdirSync(outDir, { recursive: true });
|
|
1234
|
-
const
|
|
2628
|
+
const budgetLoad = loadBudgets(budgetsFile ?? BUDGETS_FILE);
|
|
2629
|
+
const commit = commitArg ?? budgetLoad.budgets?.fixture?.commit ?? g.head();
|
|
1235
2630
|
if (!isCommit(commit)) throw new Error(`commit ${commit} is not a 40 hex sha`);
|
|
1236
2631
|
const clauseChecks = Object.fromEntries(Object.keys(CLAUSES).map((id) => [id, []]));
|
|
1237
2632
|
const runs = {};
|
|
@@ -1244,6 +2639,22 @@ async function executeRun({ fixture, host, wanted, gate, out, commitArg, leafFil
|
|
|
1244
2639
|
const gateFile = path.join(here, "bin", "rightkit-gate.mjs");
|
|
1245
2640
|
const gateIdentity = { launcher: gate, launcherSha256: (() => { try { return sha256(fs.readFileSync(gate)); } catch { return null; } })(), runnerPackageVersion: readJson(path.join(here, "package.json")).value?.version ?? null, packageGateSha256: (() => { try { return sha256(fs.readFileSync(gateFile)); } catch { return null; } })(), receiptGateSha256: null };
|
|
1246
2641
|
|
|
2642
|
+
// NN19: the gate under test. `--version` of the launcher is its only output and carries no stamp.
|
|
2643
|
+
const launcherProbe = () => {
|
|
2644
|
+
const exists = fs.existsSync(gate); let version = null; let text = "";
|
|
2645
|
+
if (exists) {
|
|
2646
|
+
try { text = fs.readFileSync(gate, "utf8").slice(0, 65536); } catch { /* a binary launcher: no text to read */ }
|
|
2647
|
+
try { const spec = launchSpec(gate, ["--version"]); const r = spawnSync(spec.command, spec.args, { encoding: "utf8", timeout: 60_000, windowsHide: true, ...spec.options }); if (r.status === 0) version = String(r.stdout).trim().split(/\r?\n/).pop() || null; } catch { /* reported as no version */ }
|
|
2648
|
+
}
|
|
2649
|
+
return { exists, version, text };
|
|
2650
|
+
};
|
|
2651
|
+
const probe = launcherProbe();
|
|
2652
|
+
const installedGate = findInstalledGate(managedRoot);
|
|
2653
|
+
ctx.gateIdentity = gateIdentityProblems({ gateArg, defaultGate: defaultGate(host), launcherExists: probe.exists, launcherVersion: probe.version, launcherText: probe.text, installed: installedGate, checkoutRoot: workspaceRootOf() });
|
|
2654
|
+
ctx.gateIdentityEvidence = `${gate} --version -> ${probe.version ?? "(none)"}; newest sealed install ${installedGate ? installedGate.version : "(none)"}`;
|
|
2655
|
+
gateIdentity.kind = ctx.gateIdentity.kind; gateIdentity.version = probe.version; gateIdentity.installedVersion = installedGate?.version ?? null;
|
|
2656
|
+
Object.assign(ctx, { wanted, host, budgets: budgetLoad.budgets, budgetProblem: budgetLoad.problem, cores: typeof os.availableParallelism === "function" ? os.availableParallelism() : os.cpus().length, jobsEnv: process.env.RK_GATE_JOBS });
|
|
2657
|
+
|
|
1247
2658
|
const key = repositoryKey(g.canonical, platform);
|
|
1248
2659
|
const ownerFile = ownershipFile({ platform, repository: key });
|
|
1249
2660
|
const readOwner = () => { try { return JSON.parse(fs.readFileSync(ownerFile, "utf8")); } catch { return null; } };
|
|
@@ -1257,11 +2668,14 @@ async function executeRun({ fixture, host, wanted, gate, out, commitArg, leafFil
|
|
|
1257
2668
|
};
|
|
1258
2669
|
const exitOk = (r) => ({ ok: r.exit === 0, problems: r.exit === 0 ? [] : [`exit ${r.exit}${r.timedOut ? " (timed out)" : ""}`] });
|
|
1259
2670
|
|
|
1260
|
-
async function doRun({ label, stage, commit: c = commit, args = [], ladder = false, step, extra = {} }) {
|
|
1261
|
-
const receiptPath = RECEIPT_STAGES.has(stage) ? path.join(outDir, `${label.replace(/[^\w.-]/g, "_")}.receipt.json`) : null;
|
|
2671
|
+
async function doRun({ label, stage, commit: c = commit, args = [], ladder = false, step, extra = {}, receipt = true, cwd = g.canonical, env = {}, gateCmd = gate, gateArgs = [], profile, workload = "fixture" }) {
|
|
2672
|
+
const receiptPath = receipt && RECEIPT_STAGES.has(stage) ? path.join(outDir, `${label.replace(/[^\w.-]/g, "_")}.receipt.json`) : null;
|
|
1262
2673
|
const full = ["--to", stage, "--commit", c, ...(receiptPath ? ["--receipt-out", receiptPath] : []), ...args];
|
|
1263
|
-
|
|
1264
|
-
|
|
2674
|
+
// Every gate invocation writes its own spawn ledger (GC-A27 NN07-NN12, NN16). RK_GATE_* never enters a cache key, so this changes no result.
|
|
2675
|
+
const ledgerPath = path.join(outDir, `${label.replace(/[^\w.-]/g, "_")}.ledger.jsonl`);
|
|
2676
|
+
fs.rmSync(ledgerPath, { force: true });
|
|
2677
|
+
const res = await runGate({ gate: gateCmd, cwd, args: [...gateArgs, ...full], env: { ...process.env, ...env, RK_GATE_SPAWN_LEDGER: ledgerPath } });
|
|
2678
|
+
return finishRun({ label, stage, commit: c, full, res, receiptPath, ladder, step, extra: { ledgerPath, workload, ...(profile ? { profile } : {}), ...(cwd !== g.canonical ? { noTree: true } : {}), ...extra } });
|
|
1265
2679
|
}
|
|
1266
2680
|
function finishRun({ label, stage, commit: c, full, res, receiptPath, ladder = false, step, extra = {} }) {
|
|
1267
2681
|
const logPath = path.join(outDir, `${label.replace(/[^\w.-]/g, "_")}.log`);
|
|
@@ -1273,7 +2687,9 @@ async function executeRun({ fixture, host, wanted, gate, out, commitArg, leafFil
|
|
|
1273
2687
|
if (receipt?.binding?.gate) gateIdentity.receiptGateSha256 = receipt.binding.gate;
|
|
1274
2688
|
const snapPath = receipt?.stages?.check?.snapshot?.path ?? receipt?.stages?.compile?.snapshot?.path;
|
|
1275
2689
|
const sourceIdentity = res.exit === 0 && snapPath ? readSourceIdentity(snapPath, c, g) : null;
|
|
1276
|
-
|
|
2690
|
+
let ledger = null;
|
|
2691
|
+
if (extra.ledgerPath && fs.existsSync(extra.ledgerPath)) ledger = parseLedger(fs.readFileSync(extra.ledgerPath, "utf8"));
|
|
2692
|
+
const run = { label, stage, commit: c, tree: extra.noTree ? null : g.tree(c), args: full, exit: res.exit, signal: res.signal, timedOut: res.timedOut === true, ms: res.ms, startedMs: res.startedMs, ledger, coverageStarts: reports.map((r) => r.startedAt), log: res.log, logPath, receipt, receiptPath, coveragePaths: cov, coverageProblems, rows: reports.length ? mergeCoverage(reports) : null, ladder, stageIndex: LADDER.indexOf(stage), timings: stageTimings(res.log), sourceIdentity, ...extra };
|
|
1277
2693
|
runs[label] = run; if (step) stepOf(step)?.notes.push(`${label}: exit ${res.exit}, ${(res.ms / 1000).toFixed(1)}s`);
|
|
1278
2694
|
return run;
|
|
1279
2695
|
}
|
|
@@ -1302,21 +2718,25 @@ async function executeRun({ fixture, host, wanted, gate, out, commitArg, leafFil
|
|
|
1302
2718
|
if (!allowInstall) stepOf("S1").notes.push(`--to ${INSTALL_STAGES.join(" and --to ")} not run: ${NEEDS_INSTALL_APPROVAL}`);
|
|
1303
2719
|
}
|
|
1304
2720
|
// S2 --------------------------------------------------------------------------------------------------------------------------------------
|
|
1305
|
-
|
|
2721
|
+
// Two warm pairs on the same commit: NN01/NN02 judge every one of them, NN05 compares the keys of the first pair with the second.
|
|
2722
|
+
if (wanted.includes("S2")) for (const [label, stage] of [["S2:check", "check"], ["S2:compile", "compile"], ["S2:check2", "check"], ["S2:compile2", "compile"]].filter(([, s]) => !checksOnly || s === "check")) { const r = await doRun({ label, stage, ladder: true, step: "S2", profile: `warm-${stage}` }); check("S2", `${label}: --to ${stage} exits 0`, exitOk(r)); }
|
|
1306
2723
|
|
|
1307
2724
|
// S3, S4 (ephemeral edits) ----------------------------------------------------------------------------------------------------------------
|
|
1308
2725
|
const tracked = g.tracked(commit);
|
|
1309
|
-
const layout = (wanted.includes("S4") || wanted.includes("S7")) ? g.cargoLayout(commit, tracked) : null;
|
|
2726
|
+
const layout = (wanted.includes("S4") || wanted.includes("S7") || wanted.includes("S11") || wanted.includes("S12") || wanted.includes("S17")) ? g.cargoLayout(commit, tracked) : null;
|
|
1310
2727
|
const editStep = async (id, name, file, edit, label, extraOf = () => ({})) => {
|
|
1311
2728
|
if (!wanted.includes(id)) return;
|
|
1312
|
-
if (!file) { stepOf(id).notes.push(`unchecked: ${NEEDS_FIXTURE}`); return; }
|
|
2729
|
+
if (!file) { stepOf(id).notes.push(`unchecked: ${NEEDS_FIXTURE}`); ctx[`${id.toLowerCase()}Why`] = `${id} made no run: the fixture has no tracked ${id === "S3" ? "rk/**/src/lib.rs (or pass --leaf-file)" : "rk/**/Cargo.toml of a non-workspace-root crate (or pass --manifest-file)"}`; return; }
|
|
1313
2730
|
const c = g.witnessCommit(commit, name, [{ path: file, content: edit(g.show(commit, file)) }]);
|
|
1314
|
-
const r = await doRun({ label, stage: "check", commit: c, ladder: true, step: id, extra: extraOf(file) });
|
|
2731
|
+
const r = await doRun({ label, stage: "check", commit: c, ladder: true, step: id, extra: extraOf(file), profile: "edited-check" });
|
|
1315
2732
|
check(id, `--to check on the edited commit exits 0`, exitOk(r));
|
|
1316
2733
|
};
|
|
1317
|
-
|
|
2734
|
+
// A fresh nonce per run: the same edit bytes as an earlier acceptance run would hit that run's cache entries, so "the edited row ran" could not be judged.
|
|
2735
|
+
const editNonce = `${Date.now()}-${process.pid}`;
|
|
2736
|
+
ctx.s3File = leafFile ?? tracked.find((f) => /^rk\/.*\/src\/lib\.rs$/.test(f));
|
|
2737
|
+
await editStep("S3", "s3-one-file", leafFile ?? tracked.find((f) => /^rk\/.*\/src\/lib\.rs$/.test(f)), (t) => `${t}${t.endsWith("\n") ? "" : "\n"}// gate-acceptance one-file edit ${editNonce}\n`, "S3:check");
|
|
1318
2738
|
const manifest = manifestFile ?? (layout ? layout.manifests.find((f) => /^rk\/.*\/Cargo\.toml$/.test(f) && !layout.wsDirs.includes(path.posix.dirname(f))) : undefined);
|
|
1319
|
-
await editStep("S4", "s4-manifest", manifest, (t) => `${t}${t.endsWith("\n") ? "" : "\n"}\n[package.metadata.gate-acceptance]\nedit = "manifest"\n`, "S4:check", (file) => {
|
|
2739
|
+
await editStep("S4", "s4-manifest", manifest, (t) => `${t}${t.endsWith("\n") ? "" : "\n"}\n[package.metadata.gate-acceptance]\nedit = "manifest ${editNonce}"\n`, "S4:check", (file) => {
|
|
1320
2740
|
const ws = cargoWorkspaceOf(file, layout.wsDirs);
|
|
1321
2741
|
return { manifestInfo: { workspace: ws, workspaces: [...new Set([...layout.wsDirs, ws])], crates: layout.crates } };
|
|
1322
2742
|
});
|
|
@@ -1388,20 +2808,164 @@ async function executeRun({ fixture, host, wanted, gate, out, commitArg, leafFil
|
|
|
1388
2808
|
// S8 kill and recover ---------------------------------------------------------------------------------------------------------------------
|
|
1389
2809
|
// Build ownership is held across Class A by design (build-ownership.mjs:3-4), so a SIGKILL during --to check leaves a record exactly like one
|
|
1390
2810
|
// during --to compile: every case asserts that the NEXT run reclaims it (the log's reclaim line) and passes.
|
|
1391
|
-
if (wanted.includes("S8")) for (const k of KILLS) {
|
|
2811
|
+
if (wanted.includes("S8")) for (const k of KILLS.filter((x) => !killsFilter || killsFilter.includes(x.id))) {
|
|
1392
2812
|
const label = `S8:${k.id}`; const logPath = path.join(outDir, `${label.replace(/[^\w.-]/g, "_")}.log`);
|
|
1393
|
-
const stage = k.id
|
|
2813
|
+
const stage = k.id.startsWith("K02") ? "check" : "compile"; const receiptPath = path.join(outDir, `${label.replace(/[^\w.-]/g, "_")}.receipt.json`);
|
|
1394
2814
|
const killed = await killDuring({ gate, cwd: g.canonical, args: ["--to", stage, "--commit", commit, "--receipt-out", receiptPath], signal: k.signal, waitFor: readOwner, afterMs: killAfterMs });
|
|
1395
2815
|
fs.writeFileSync(logPath, killed.log);
|
|
1396
2816
|
const before = readOwner();
|
|
1397
2817
|
const dry = before ? runDry(ownerFile) : { exit: null, text: "" };
|
|
1398
2818
|
const next = await doRun({ label: `${label}:next`, stage, ladder: true, step: "S8" });
|
|
1399
2819
|
const after = readOwner();
|
|
1400
|
-
|
|
1401
|
-
|
|
2820
|
+
// A fixture compile exits 1 for reasons that are not ownership (its Class B rows fail); a compile that reclaimed the dead record and reached planning passed the recovery.
|
|
2821
|
+
const reached = stage === "compile" && /class A scans \d+ at a time/.test(next.log) && !/build ownership [^\n]*(busy|refused)|RK_CHECK_ERROR/.test(next.log);
|
|
2822
|
+
const recovery = assertRecovery({ signal: k.signal, before, dry, next: { exit: reached ? 0 : next.exit, text: next.log }, after, exitedBySignal: exitedBySignal({ signal: killed.signal, exit: killed.exit, killSignal: k.signal, platform: process.platform }) || (k.signal === "SIGINT" && !killed.signal && killed.exit !== null && killed.exit !== 0) });
|
|
2823
|
+
runs[label] = { label, kill: k.id, killSignal: process.platform === "win32" ? "terminate" : k.signal, stage, recovery, logPath, ownerPath: ownerFile, exit: killed.exit, signal: killed.signal, log: killed.log, ladder: false, args: [] };
|
|
1402
2824
|
check("S8", `${k.id} ${k.signal}: dead owner reclaimed by the next run, which passes`, recovery);
|
|
1403
2825
|
}
|
|
1404
2826
|
|
|
2827
|
+
// S10 unit list (NN16) ----------------------------------------------------------------------------------------------------------------------
|
|
2828
|
+
// `--units-file` names units in the gate's own grammar (crates/rightkit-<x>, packages/<x>). The run shares one Class A and starts no per-unit format check.
|
|
2829
|
+
if (wanted.includes("S10")) {
|
|
2830
|
+
// The gate accepts --units-file only for the RightKit repository itself ("--units-file names RightKit units ... every other repository is built whole"), so the unit-list run is a read-only --to check of the RightKit checkout.
|
|
2831
|
+
const rkDir = path.join(workspaceRootOf(), "rightkit");
|
|
2832
|
+
let rkTracked = []; try { rkTracked = git(rkDir, ["ls-tree", "-r", "--name-only", "HEAD"]).split("\n").filter(Boolean); } catch { /* reported below */ }
|
|
2833
|
+
const units = unitSelectorsOf(rkTracked, 2);
|
|
2834
|
+
if (units.length < 2) {
|
|
2835
|
+
ctx.unitsWhy = `the RightKit checkout has ${units.length} unit(s) in the gate's unit grammar (crates/rightkit-<x>/Cargo.toml, packages/<x>/package.json); --units-file needs two`;
|
|
2836
|
+
check("S10", "the fixture names two units for --units-file", { ok: false, problems: [ctx.unitsWhy] });
|
|
2837
|
+
} else {
|
|
2838
|
+
const unitsFile = path.join(outDir, "units.json");
|
|
2839
|
+
fs.writeFileSync(unitsFile, `${JSON.stringify({ units })}\n`);
|
|
2840
|
+
const r = await doRun({ label: "S10:units", stage: "check", commit: "HEAD", cwd: rkDir, args: ["--units-file", unitsFile], ladder: false, step: "S10", extra: { units }, receipt: false });
|
|
2841
|
+
check("S10", "--to check --units-file exits 0", exitOk(r));
|
|
2842
|
+
}
|
|
2843
|
+
}
|
|
2844
|
+
|
|
2845
|
+
// S11 cold run ----------------------------------------------------------------------------------------------------------------------------
|
|
2846
|
+
// The gate's scan-result cache (<git common dir>/rightkit-gate-cache, rule verdicts inside) is MOVED ASIDE under scratch (never deleted) and put back afterwards.
|
|
2847
|
+
ctx.cellWhy = {}; ctx.proofs = {};
|
|
2848
|
+
const crateInfo = layout && (wanted.includes("S11") || wanted.includes("S12") || wanted.includes("S17")) ? crateEditInfo({ layout, tracked, ws: "rk" }) : null;
|
|
2849
|
+
if (crateInfo && !crateInfo.why) ctx.crateEdit = { workspace: crateInfo.workspace, crate: crateInfo.crate, deps: crateInfo.deps };
|
|
2850
|
+
if (wanted.includes("S11")) {
|
|
2851
|
+
const common = path.resolve(g.canonical, g.run(["rev-parse", "--git-common-dir"]).trim());
|
|
2852
|
+
const cacheDir = path.join(common, "rightkit-gate-cache");
|
|
2853
|
+
const asideRoot = path.join(scratch, `cold-aside-${Date.now()}`);
|
|
2854
|
+
fs.mkdirSync(asideRoot, { recursive: true });
|
|
2855
|
+
const aside = path.join(asideRoot, "rightkit-gate-cache");
|
|
2856
|
+
let moved = false;
|
|
2857
|
+
try {
|
|
2858
|
+
if (fs.existsSync(cacheDir)) { fs.renameSync(cacheDir, aside); moved = true; }
|
|
2859
|
+
check("S11", `the gate cache dir ${cacheDir} was moved aside to ${aside}`, { ok: moved, problems: moved ? [] : [`${cacheDir} does not exist: the run is not proven cold`] });
|
|
2860
|
+
for (const stage of (s11ChecksOnly ? ["check"] : ["check", "compile"])) { const r = await doRun({ label: `S11:${stage}`, stage, ladder: true, step: "S11", profile: `cold-${stage}` }); check("S11", `cold --to ${stage} wrote coverage`, { ok: r.rows !== null, problems: [`exit ${r.exit}, no readable coverage`] }); }
|
|
2861
|
+
} finally {
|
|
2862
|
+
let restored = !moved;
|
|
2863
|
+
if (moved) { try { if (fs.existsSync(cacheDir)) fs.renameSync(cacheDir, path.join(asideRoot, "created-during-the-cold-run")); fs.renameSync(aside, cacheDir); restored = true; } catch (e) { check("S11", "the gate cache dir is restored", { ok: false, problems: [e.message] }); } }
|
|
2864
|
+
check("S11", "the original gate cache dir is back in place", { ok: restored && (!moved || fs.existsSync(cacheDir)), problems: ["the cache dir was not restored"] });
|
|
2865
|
+
}
|
|
2866
|
+
Object.assign(ctx.proofs, Object.fromEntries(Object.entries(coldControls({ cold: runs["S11:check"], warmPrev: runs["S2:check2"]?.rows ?? runs["S1:check"]?.rows ?? null, warmRows: runs["S2:check2"]?.rows ?? null, crate: ctx.crateEdit, ws: "rk", coldCompileRows: runs["S11:compile"]?.rows ?? null })).map(([k, v]) => [k, { kind: "real-condition control: the cold run (every row really ran)", caught: v }])));
|
|
2867
|
+
}
|
|
2868
|
+
|
|
2869
|
+
// S12 compile-side edits ------------------------------------------------------------------------------------------------------------------
|
|
2870
|
+
if (wanted.includes("S12")) {
|
|
2871
|
+
const nonce2 = `${Date.now()}-${process.pid}`;
|
|
2872
|
+
if (!crateInfo || crateInfo.why) { ctx.cellWhy["fixture:edited-compile"] = crateInfo?.why ?? "no layout"; check("S12", "a crate to edit exists", { ok: false, problems: [crateInfo?.why ?? "no cargo layout"] }); }
|
|
2873
|
+
else {
|
|
2874
|
+
const c1 = g.witnessCommit(commit, "s12-crate", [{ path: crateInfo.file, content: `${g.show(commit, crateInfo.file)}\n// gate-acceptance crate edit ${nonce2}\n` }]);
|
|
2875
|
+
const r1 = await doRun({ label: "S12:crate", stage: "compile", commit: c1, ladder: true, step: "S12", profile: "edited-compile" });
|
|
2876
|
+
check("S12", "the crate-edit compile wrote coverage", { ok: r1.rows !== null, problems: [`exit ${r1.exit}, no readable coverage`] });
|
|
2877
|
+
}
|
|
2878
|
+
const lockFile = tracked.find((f) => f === "rk/Cargo.lock") ?? tracked.find((f) => /(^|\/)Cargo\.lock$/.test(f) && !/^app\//.test(f));
|
|
2879
|
+
if (!lockFile) check("S12", "a lockfile to edit exists", { ok: false, problems: ["the fixture tracks no Cargo.lock outside app/"] });
|
|
2880
|
+
else {
|
|
2881
|
+
ctx.lockDir = path.posix.dirname(lockFile);
|
|
2882
|
+
const c2 = g.witnessCommit(commit, "s12-lock", [{ path: lockFile, content: `${g.show(commit, lockFile)}\n# gate-acceptance lock edit ${nonce2}\n` }]);
|
|
2883
|
+
const r2 = await doRun({ label: "S12:lock", stage: "check", commit: c2, ladder: true, step: "S12", profile: "edited-check" });
|
|
2884
|
+
check("S12", "the lock-edit check wrote coverage", { ok: r2.rows !== null, problems: [`exit ${r2.exit}, no readable coverage`] });
|
|
2885
|
+
}
|
|
2886
|
+
const mf = manifestFile ?? (layout ? layout.manifests.find((f) => /^rk\/.*\/Cargo\.toml$/.test(f) && !layout.wsDirs.includes(path.posix.dirname(f))) : undefined);
|
|
2887
|
+
if (!mf) check("S12", "a manifest to edit exists", { ok: false, problems: [NEEDS_FIXTURE] });
|
|
2888
|
+
else {
|
|
2889
|
+
const c3 = g.witnessCommit(commit, "s12-manifest", [{ path: mf, content: `${g.show(commit, mf)}\n[package.metadata.gate-acceptance-compile]\nedit = "manifest ${nonce2}"\n` }]);
|
|
2890
|
+
const r3 = await doRun({ label: "S12:manifest", stage: "compile", commit: c3, ladder: true, step: "S12", profile: "edited-compile", extra: { manifestInfo: { workspace: cargoWorkspaceOf(mf, layout.wsDirs), workspaces: [...new Set([...layout.wsDirs, cargoWorkspaceOf(mf, layout.wsDirs)])], crates: layout.crates } } });
|
|
2891
|
+
check("S12", "the manifest-edit compile wrote coverage", { ok: r3.rows !== null, problems: [`exit ${r3.exit}, no readable coverage`] });
|
|
2892
|
+
}
|
|
2893
|
+
}
|
|
2894
|
+
|
|
2895
|
+
// S13 gate upgrade ------------------------------------------------------------------------------------------------------------------------
|
|
2896
|
+
if (wanted.includes("S13")) {
|
|
2897
|
+
const gates = listInstalledGates(managedRoot);
|
|
2898
|
+
const older = gates.find((x) => x.version !== gates[0]?.version);
|
|
2899
|
+
if (!older) {
|
|
2900
|
+
ctx.upgradeWhy = `needs two installed versions: ${gates.length} sealed gate(s) under ${path.join(managedRoot, "trusted-gates")} (${gates.map((x) => x.version).join(", ") || "none"})`;
|
|
2901
|
+
check("S13", "two sealed gate versions are installed", { ok: false, problems: [ctx.upgradeWhy] });
|
|
2902
|
+
} else {
|
|
2903
|
+
for (const [label, gt] of [["S13:prev", older], ["S13:next", gates[0]]]) { const r = await doRun({ label, stage: "check", ladder: true, step: "S13", gateCmd: process.execPath, gateArgs: [gt.entry], extra: { gateVersion: gt.version } }); check("S13", `${label} (${gt.version}) wrote coverage`, { ok: r.rows !== null, problems: [`exit ${r.exit}, no readable coverage`] }); }
|
|
2904
|
+
}
|
|
2905
|
+
}
|
|
2906
|
+
|
|
2907
|
+
// S14 resident restart --------------------------------------------------------------------------------------------------------------------
|
|
2908
|
+
if (wanted.includes("S14")) {
|
|
2909
|
+
const script = gateServeScriptFor({ gateArg, kind: ctx.gateIdentity.kind, installed: installedGate });
|
|
2910
|
+
const st = spawnSync(process.execPath, [script, "status"], { encoding: "utf8", timeout: 30_000 });
|
|
2911
|
+
const text = `${st.stdout ?? ""}${st.stderr ?? ""}`;
|
|
2912
|
+
const pid = Number(/"?\bpid"?\s*[:=]\s*(\d+)/.exec(text)?.[1]);
|
|
2913
|
+
ctx.restart = { killed: false, why: `the resident gate's \`status\` printed no pid (${script}): ${text.trim().slice(0, 160) || "no output"}` };
|
|
2914
|
+
if (Number.isInteger(pid) && pid > 1) {
|
|
2915
|
+
try {
|
|
2916
|
+
process.kill(pid, "SIGTERM");
|
|
2917
|
+
const until = Date.now() + 10_000;
|
|
2918
|
+
while (Date.now() < until) { try { process.kill(pid, 0); } catch { break; } await new Promise((r) => setTimeout(r, 100)); }
|
|
2919
|
+
let alive = true; try { process.kill(pid, 0); } catch { alive = false; }
|
|
2920
|
+
ctx.restart = alive ? { killed: false, why: `the resident gate (pid ${pid}) did not exit within 10 s of SIGTERM` } : { killed: true, pid };
|
|
2921
|
+
} catch (e) { ctx.restart = { killed: false, why: `cannot stop the resident gate: ${e.message}` }; }
|
|
2922
|
+
}
|
|
2923
|
+
check("S14", "the resident gate was stopped before the run", { ok: ctx.restart.killed, problems: [ctx.restart.why ?? ""] });
|
|
2924
|
+
const r = await doRun({ label: "S14:check", stage: "check", ladder: true, step: "S14" });
|
|
2925
|
+
check("S14", "the run after the restart wrote coverage", { ok: r.rows !== null, problems: [`exit ${r.exit}, no readable coverage`] });
|
|
2926
|
+
}
|
|
2927
|
+
|
|
2928
|
+
// S15 workloads ---------------------------------------------------------------------------------------------------------------------------
|
|
2929
|
+
if (wanted.includes("S15")) {
|
|
2930
|
+
for (const [wl, dir] of [["rightkit", workspaceRootOf() + "/rightkit"], ["heardright", workspaceRootOf() + "/heardright"]]) {
|
|
2931
|
+
if (!fs.existsSync(dir)) { ctx.cellWhy[`${wl}:warm-check`] = `${dir} does not exist`; check("S15", `${wl} checkout exists`, { ok: false, problems: [`${dir} does not exist`] }); continue; }
|
|
2932
|
+
const r = await doRun({ label: `S15:${wl}`, stage: "check", commit: "HEAD", cwd: dir, receipt: false, ladder: false, step: "S15", profile: "warm-check", workload: wl });
|
|
2933
|
+
check("S15", `${wl} --to check exits 0`, exitOk(r));
|
|
2934
|
+
}
|
|
2935
|
+
if (pulseCompile) {
|
|
2936
|
+
const dir = workspaceRootOf() + "/pulse";
|
|
2937
|
+
const r = await doRun({ label: "S15:pulse", stage: "compile", commit: "HEAD", cwd: dir, receipt: false, ladder: false, step: "S15", profile: "cold-compile", workload: "pulse" });
|
|
2938
|
+
check("S15", "pulse --to compile exits 0", exitOk(r));
|
|
2939
|
+
} else ctx.cellWhy["pulse:cold-compile"] = "the Pulse compile did not run: it is a real compile of another repository and runs only with --pulse-compile (Adrian's approval to compile)";
|
|
2940
|
+
}
|
|
2941
|
+
|
|
2942
|
+
// S16 per-run identities ------------------------------------------------------------------------------------------------------------------
|
|
2943
|
+
if (wanted.includes("S16")) {
|
|
2944
|
+
const tmp = fs.mkdtempSync(path.join(scratch, "ident-tmp-"));
|
|
2945
|
+
const r = await doRun({ label: "S16:ident", stage: "check", ladder: true, step: "S16", env: { CODEX_TOOL_CALL_ID: `fake-call-${Date.now()}`, TERM_SESSION_ID: `fake-session-${process.pid}`, TMPDIR: tmp, RK_GATE_RUN_NOTE: `identity-${Date.now()}` } });
|
|
2946
|
+
check("S16", "the run with different per-run identities wrote coverage", { ok: r.rows !== null, problems: [`exit ${r.exit}, no readable coverage`] });
|
|
2947
|
+
}
|
|
2948
|
+
|
|
2949
|
+
// S17 cached failure ----------------------------------------------------------------------------------------------------------------------
|
|
2950
|
+
// One witness commit that adds a real compile error to one fixture crate; the same commit runs twice (the failing rows must be hits the second
|
|
2951
|
+
// time), then once more with RUSTUP_TOOLCHAIN naming another installed toolchain (a keyed environment input: the failing rows must run again).
|
|
2952
|
+
if (wanted.includes("S17")) {
|
|
2953
|
+
if (!crateInfo || crateInfo.why) check("S17", "a crate to break exists", { ok: false, problems: [crateInfo?.why ?? "no cargo layout"] });
|
|
2954
|
+
else {
|
|
2955
|
+
const cf = g.witnessCommit(commit, "s17-fail", [{ path: crateInfo.file, content: `${g.show(commit, crateInfo.file)}\ncompile_error!("gate-acceptance NN41: a deterministic compile failure");\n` }]);
|
|
2956
|
+
const f1 = await doRun({ label: "S17:fail1", stage: "compile", commit: cf, ladder: true, step: "S17", profile: "edited-compile" });
|
|
2957
|
+
check("S17", "the failing commit's first compile wrote coverage", { ok: f1.rows !== null, problems: [`exit ${f1.exit}, no readable coverage`] });
|
|
2958
|
+
const f2 = await doRun({ label: "S17:fail2", stage: "compile", commit: cf, ladder: true, step: "S17", profile: "edited-compile" });
|
|
2959
|
+
check("S17", "the failing commit's second compile wrote coverage", { ok: f2.rows !== null, problems: [`exit ${f2.exit}, no readable coverage`] });
|
|
2960
|
+
const other = otherToolchain(f1.receipt?.binding?.toolchain?.rustc);
|
|
2961
|
+
if (!other) { ctx.identityChange = "no second installed toolchain found under RUSTUP_HOME/toolchains"; check("S17", "a second installed toolchain exists to change the identity", { ok: false, problems: [ctx.identityChange] }); }
|
|
2962
|
+
else {
|
|
2963
|
+
ctx.identityChange = `RUSTUP_TOOLCHAIN=${other}`;
|
|
2964
|
+
await doRun({ label: "S17:fail3", stage: "compile", commit: cf, ladder: true, step: "S17", profile: "edited-compile", env: { RUSTUP_TOOLCHAIN: other } });
|
|
2965
|
+
}
|
|
2966
|
+
}
|
|
2967
|
+
}
|
|
2968
|
+
|
|
1405
2969
|
// S9 ---------------------------------------------------------------------------------------------------------------------------------------
|
|
1406
2970
|
if (wanted.includes("S9")) {
|
|
1407
2971
|
const brokerEnd = runningBrokerProcess() ?? null; const owner = readOwner();
|
|
@@ -1423,9 +2987,39 @@ async function executeRun({ fixture, host, wanted, gate, out, commitArg, leafFil
|
|
|
1423
2987
|
let r; try { r = CHECKS[id](ctx); } catch (e) { r = { status: "fail", evidence: [], problems: [`assertion threw: ${e.message}`] }; }
|
|
1424
2988
|
clauseChecks[id].push(...(Array.isArray(r) ? r : [r]));
|
|
1425
2989
|
}
|
|
1426
|
-
const
|
|
2990
|
+
const contractPath = contractFile ?? CONTRACT_FILE;
|
|
2991
|
+
let contractText = ""; try { contractText = fs.readFileSync(contractPath, "utf8"); } catch { /* NN33 reports an empty contract */ }
|
|
2992
|
+
const rootDir = path.resolve(here, "..", "..");
|
|
2993
|
+
let gateCommit = null; try { gateCommit = git(rootDir, ["rev-parse", "HEAD"]).trim(); } catch { /* NN30 reports it */ }
|
|
2994
|
+
let otherReceipt = null; if (otherReceiptFile) { const j = readJson(otherReceiptFile); otherReceipt = j.value ?? { error: j.error }; }
|
|
2995
|
+
Object.assign(ctx, { forceNN, warmLabels: checksOnly ? ["S2:check", "S2:check2"] : undefined, extended: true, nnSet: NN_ALL, contractText, contractFile: contractPath, rootDir, runnerSha256: fileSha(RUNNER_FILE), contractSha256: fileSha(contractPath), fixtureCommit: commit, gateCommit, otherReceipt, otherReceiptPath: otherReceiptFile, tooling: collectTooling(rootDir, managedRoot) });
|
|
2996
|
+
let nonNegotiables = evaluateNonNegotiables(ctx);
|
|
2997
|
+
const notes = [`out ${outDir}`, "wall time is judged only by the NN18 budgets in ci/gate-acceptance-budgets.json"];
|
|
2998
|
+
if (ctx.gateIdentity.kind === "named") notes.push(`the gate under test is ${gate}, named by --gate: NOT the installed sealed gate; acceptance of the installed gate is still owed`);
|
|
1427
2999
|
if (!allowInstall) notes.push(`--to ${INSTALL_STAGES.join(" and --to ")} not run: ${NEEDS_INSTALL_APPROVAL}`);
|
|
1428
|
-
const
|
|
3000
|
+
const development = ctx.gateIdentity.kind === "named";
|
|
3001
|
+
const waivers = (Array.isArray(budgetLoad.budgets?.waivers) ? budgetLoad.budgets.waivers : []).filter(validWaiver);
|
|
3002
|
+
const build = (nn) => buildResult({ host, gate: gateIdentity, broker: { runtimeManifest: ctx.broker.manifest ? { path: ctx.broker.manifestPath, brokerDigest: ctx.broker.manifest.brokerDigest, version: ctx.broker.manifest.version } : null, pinsBrokerDigest: ctx.broker.pins?.brokerDigest ?? null, processAtStart: ctx.s0?.broker ?? null }, commit, steps: stepRecords, clauseChecks, startedAt, endedAt: new Date().toISOString(), notes, allowInstall, stepChecks, nonNegotiables: nn, nnIds: NN_ALL_IDS, development, waivers });
|
|
3003
|
+
let result = build(nonNegotiables);
|
|
3004
|
+
// NN34 and NN35 are judged from the finished result (a first build with their placeholders, then the real verdict).
|
|
3005
|
+
const post = (id, problems, evidence) => { const i = nonNegotiables.findIndex((n) => n.id === id); const base = nonNegotiables[i]; nonNegotiables[i] = { ...base, pending: undefined, status: problems.length ? "fail" : "pass", problems, checks: [{ label: "result", ok: problems.length === 0 }], evidence }; };
|
|
3006
|
+
const noEvidence = nonNegotiables.filter((n) => n.status === "pass" && !n.pending && (n.checks.length === 0 || n.evidence.length === 0)).map((n) => `${n.id} passed with no evidence`);
|
|
3007
|
+
const bareClause = result.clauses.filter((c) => c.status === "pass" && (c.assertions === 0 || c.evidence.length === 0)).map((c) => `clause ${c.id} passed with no evidence`);
|
|
3008
|
+
post("NN34", [...noEvidence, ...bareClause, ...(result.partial && /^PASS/.test(result.verdict) ? ["a partial run printed PASS"] : [])], ["the finished result"]);
|
|
3009
|
+
const unwaived = result.clauses.filter((c) => c.status === "unchecked" && !waivers.some((w) => w.clause === c.id)).map((c) => c.id);
|
|
3010
|
+
const badWaivers = (Array.isArray(budgetLoad.budgets?.waivers) ? budgetLoad.budgets.waivers : []).filter((w) => !validWaiver(w)).map((w) => `waiver ${JSON.stringify(w).slice(0, 80)} is not by Adrian by name with his words`);
|
|
3011
|
+
post("NN35", [...(/\d+ of \d+ asserted/.test(result.verdict) && /non-negotiables \d+ of \d+/.test(result.verdict) ? [] : ["the verdict omits `N of M` coverage"]), ...badWaivers], [`verdict: ${result.verdict.slice(0, 120)}`, `${unwaived.length} operative clause(s) unchecked and not waived: a release needs 0`]);
|
|
3012
|
+
result = build(nonNegotiables);
|
|
3013
|
+
result.releaseEligible = result.ok && !development && unwaived.length === 0;
|
|
3014
|
+
result.unwaivedUnchecked = unwaived;
|
|
3015
|
+
result.proofs = { ...ctx.proofs, ...(development ? { NN19: { kind: "real-condition control: a checkout gate run is a development run", caught: nonNegotiables.find((n) => n.id === "NN19")?.status === "fail" && !result.ok } } : {}), ...(result.partial ? { NN34: { kind: "real-condition control: a partial run", caught: !result.ok } } : {}) };
|
|
3016
|
+
let receiptPath = null;
|
|
3017
|
+
if (result.ok && !development) {
|
|
3018
|
+
const entry = findInstalledGate(managedRoot);
|
|
3019
|
+
const receipt = buildContractReceipt({ host, commit: gateCommit, gate: { kind: "installed", version: entry?.version ?? probe.version, sealedPath: entry?.entry ?? null, sealedSha256: entry?.sealedSha256 ?? null }, contractSha256: ctx.contractSha256, runnerSha256: ctx.runnerSha256, budgetsSha256: fileSha(budgetsFile ?? BUDGETS_FILE), fixtureCommit: commit, result });
|
|
3020
|
+
receiptPath = path.join(outDir, `contract-test-receipt.${host}.json`); fs.writeFileSync(receiptPath, `${JSON.stringify(receipt, null, 2)}\n`);
|
|
3021
|
+
}
|
|
3022
|
+
result.receipt = receiptPath ?? (development ? "none: a development run writes no receipt" : "none: the run did not pass");
|
|
1429
3023
|
result.timings = Object.fromEntries(Object.entries(runs).map(([k, v]) => [k, { ms: v.ms, stages: v.timings }]));
|
|
1430
3024
|
fs.writeFileSync(path.join(outDir, "result.json"), `${JSON.stringify(result, null, 2)}\n`);
|
|
1431
3025
|
const summary = formatSummary(result); fs.writeFileSync(path.join(outDir, "summary.txt"), `${summary}\n`);
|
|
@@ -1433,6 +3027,259 @@ async function executeRun({ fixture, host, wanted, gate, out, commitArg, leafFil
|
|
|
1433
3027
|
return result.ok ? 0 : 1;
|
|
1434
3028
|
}
|
|
1435
3029
|
|
|
3030
|
+
// ---------------------------------------------------------------------------------------------------------------------------------------------
|
|
3031
|
+
// --verify-release and --prove
|
|
3032
|
+
// ---------------------------------------------------------------------------------------------------------------------------------------------
|
|
3033
|
+
/** `node gate-acceptance.mjs --verify-release <receipt-mac> <receipt-dell> [--commit <gate commit>]`: exit 0 only when both hosts' receipts pass for one gate commit (NN30, NN31, NN35). Release, upload and trusted-gate promotion tooling must call this. */
|
|
3034
|
+
function verifyReleaseCli(argv) {
|
|
3035
|
+
const i = argv.indexOf("--verify-release");
|
|
3036
|
+
const files = [argv[i + 1], argv[i + 2]];
|
|
3037
|
+
if (!files[0] || !files[1] || files.some((f) => f.startsWith("--"))) { console.error("usage: node gate-acceptance.mjs --verify-release <receipt-mac> <receipt-dell> [--commit <sha>]"); return 64; }
|
|
3038
|
+
const read = files.map((f) => readJson(f));
|
|
3039
|
+
const problems = read.filter((r) => r.error).map((r) => r.error);
|
|
3040
|
+
const j = argv.indexOf("--commit");
|
|
3041
|
+
if (!problems.length) {
|
|
3042
|
+
const budgets = loadBudgets().budgets;
|
|
3043
|
+
const waivers = (Array.isArray(budgets?.waivers) ? budgets.waivers : []).filter(validWaiver);
|
|
3044
|
+
problems.push(...verifyReleaseReceipts(read[0].value, read[1].value, { commit: j < 0 ? null : argv[j + 1], contractSha256: fileSha(CONTRACT_FILE), runnerSha256: fileSha(RUNNER_FILE), waivers }).problems);
|
|
3045
|
+
}
|
|
3046
|
+
console.log(problems.length ? `verify-release REFUSED (${problems.length} problem(s))` : "verify-release OK: both hosts pass for one gate commit");
|
|
3047
|
+
for (const p of problems) console.log(` ${p}`);
|
|
3048
|
+
return problems.length ? 1 : 0;
|
|
3049
|
+
}
|
|
3050
|
+
|
|
3051
|
+
const GATE_INJECT_ANCHOR = " installSpawnLedger();\n";
|
|
3052
|
+
const spawnLine = (prog, args, opt = "{ cwd: process.cwd() }") => `__cp.spawnSync(${JSON.stringify(prog)}, ${JSON.stringify(args)}, ${opt});`;
|
|
3053
|
+
const CARGO = ["car", "go"].join("");
|
|
3054
|
+
/**
|
|
3055
|
+
* Mutant gates (--prove): a copy of the checkout's packages/release with ONE regression that reintroduces the violation of one non-negotiable. The
|
|
3056
|
+
* runner is run with --gate at the mutant; the NN must fail with a problem matching `expect` that the unmutated gate's run does not show.
|
|
3057
|
+
*/
|
|
3058
|
+
export const MUTANTS = Object.freeze([
|
|
3059
|
+
{ nn: "NN07", steps: "S2", what: "the gate starts the same `git rev-parse --show-toplevel` twice", inject: [spawnLine("git", ["rev-parse", "--show-toplevel"]), spawnLine("git", ["rev-parse", "--show-toplevel"])], expect: /identical child process/ },
|
|
3060
|
+
{ nn: "NN08", steps: "S2", what: "the gate runs the whole-workspace format check through cargo", inject: [spawnLine(CARGO, ["fmt", "--all", "--check"])], expect: /cargo fmt started/ },
|
|
3061
|
+
{ nn: "NN09", steps: "S2", what: "the gate asks the broker for a metadata read (`rustright cargo metadata`)", inject: [spawnLine("rustright", [CARGO, "metadata", "--no-deps"])], expect: /went through the broker/ },
|
|
3062
|
+
{ nn: "NN10", steps: "S2", what: "the gate starts a real metadata read on a warm run", inject: [spawnLine(CARGO, ["metadata", "--no-deps", "--format-version", "1"])], expect: /real cargo metadata/ },
|
|
3063
|
+
{ nn: "NN13", steps: "S2", what: "a --to check starts an ownership probe (`ps`)", inject: [spawnLine("ps", ["-p", "1"])], expect: /ownership probe/ },
|
|
3064
|
+
{ nn: "NN16", steps: "S10", what: "a unit-list run starts the per-unit format check through cargo", inject: [spawnLine(CARGO, ["fmt", "-p", "rk-core", "--check"])], expect: /cargo fmt started for a unit list/ },
|
|
3065
|
+
{ nn: "NN22", steps: "S2", what: "a warm run walks the tree with `find`", inject: [spawnLine("find", [".", "-maxdepth", "1"])], expect: /tree walk/ },
|
|
3066
|
+
{ nn: "NN25", steps: "S2", what: "a warm run starts `pnpm --version`", inject: [spawnLine("pnpm", ["--version"])], expect: /pnpm|version probe/ },
|
|
3067
|
+
{ nn: "NN26", steps: "S2", what: "the gate starts `node gate-serve.mjs ask` to ask the resident gate", inject: ['__cp.spawnSync(process.execPath, [process.getBuiltinModule("node:url").fileURLToPath(new URL("../gate-serve.mjs", import.meta.url)), "ask"], { timeout: 2000 });'], expect: /ask the resident gate/ },
|
|
3068
|
+
{ nn: "NN39", steps: "S11", extra: ["--s11-checks-only"], what: "the Class A lane count is forced to 1 in the code path (not an environment override)", patch: { find: "const jobs = Math.max(1, Number(o.env.RK_GATE_JOBS ?? defaultJobs) || defaultJobs);", replace: "const jobs = 1;" }, expect: /idle lane while work waited/ },
|
|
3069
|
+
{ nn: "NN17", steps: "S2", what: "the Class A lane count is forced to 1 in the code path", patch: { find: "const jobs = Math.max(1, Number(o.env.RK_GATE_JOBS ?? defaultJobs) || defaultJobs);", replace: "const jobs = 1;" }, expect: /lane\(s\) on a/ },
|
|
3070
|
+
{ nn: "NN05", steps: "S2", what: "a per-run value (a high-resolution clock reading) enters every Class A row key", patch: { find: "${rowShape(scan)}`; scanKeys.set(scan.id, full);", replace: "${rowShape(scan)}:${process.hrtime.bigint()}`; scanKeys.set(scan.id, full);" }, expect: /key differs between identical runs/ },
|
|
3071
|
+
{ nn: "NN06", steps: "S2", what: "every Class A row is environment-bound, so non-executing keys carry the environment digest", patch: { find: "function classAEnvironmentBound(scan) { return scan.executes === true || scan.tool === \"pnpm\"; }", replace: "function classAEnvironmentBound(scan) { return true; }" }, expect: /carries the environment digest/ },
|
|
3072
|
+
{ nn: "NN12", steps: "S2", what: "a warm run starts `pnpm install`", inject: [spawnLine("pnpm", ["install", "--offline"])], expect: /pnpm install started/ },
|
|
3073
|
+
{ nn: "NN29", steps: "S2,S16", what: "the tool-call id of the environment enters every Class A row key", patch: { find: "${rowShape(scan)}`; scanKeys.set(scan.id, full);", replace: "${rowShape(scan)}:${process.env.CODEX_TOOL_CALL_ID ?? \"\"}`; scanKeys.set(scan.id, full);" }, expect: /key differs between identical runs|reuse miss/ },
|
|
3074
|
+
{ nn: "NN32", steps: "S8", extra: ["--kills", "K02,K02-int"], what: "a dead owner's record is never judged reclaimable (judgeOwner always refuses)", patch: { file: "build-ownership.mjs", find: "if (owner.host !== host) throw busy(`held by pid ${owner.pid} on ${owner.host}`);", replace: "if (true) throw busy(`held by pid ${owner.pid} (MUTANT: a dead owner is never judged reclaimable)`);" }, expect: /reclaimed from|exited/ },
|
|
3075
|
+
{ nn: "NN40", steps: "S2", compile: true, control: true, what: "the gate starts per-crate `cargo rustdoc` again (two crates of the fixture workspace, two starts)", inject: [spawnLine("rustright", ["cargo", "rustdoc", "-p", "rk-core", "--lib", "--help"]), spawnLine("rustright", ["cargo", "rustdoc", "-p", "rk-util", "--lib", "--help"])], expect: /a cargo rustdoc started/ },
|
|
3076
|
+
{ nn: "NN41", steps: "S17", control: true, what: "the gate refuses to reuse a cached failure (every failing cache entry is dropped before the run)", inject: ['try { const __fs = process.getBuiltinModule("node:fs"); const __p = process.getBuiltinModule("node:path"); const __d = __p.join(process.cwd(), ".git", "rightkit-gate-cache"); for (const __f of __fs.readdirSync(__d)) { const __x = __p.join(__d, __f); try { if (JSON.parse(__fs.readFileSync(__x, "utf8"))?.row?.status === "fail") __fs.rmSync(__x); } catch { /* not an entry */ } } } catch { /* no cache dir */ }'], expect: /^S17: (clippy|check|check-features|doc):\S+: failed, .*ran again \(a failure must be a cache hit\)/ },
|
|
3077
|
+
{ nn: "NN42", steps: "S2", compile: true, control: true, what: "the stage sends one broker command per cross target (two single-target commands of one configuration)", inject: [spawnLine("rustright", ["cargo", "check", "--help", "--target", "aarch64-unknown-linux-gnu"]), spawnLine("rustright", ["cargo", "check", "--help", "--target", "x86_64-pc-windows-msvc"])], expect: /one per target/ },
|
|
3078
|
+
{ nn: "NN28", steps: "S2", what: "the gate polls for changes with `git status`", inject: [spawnLine("git", ["status", "--short"])], expect: /polling/ },
|
|
3079
|
+
]);
|
|
3080
|
+
|
|
3081
|
+
function copyRelease(dest) {
|
|
3082
|
+
const src = here;
|
|
3083
|
+
fs.mkdirSync(dest, { recursive: true });
|
|
3084
|
+
const a = spawnSync("rsync", ["-a", "--exclude", "node_modules", `${src}/`, `${dest}/`], { encoding: "utf8" });
|
|
3085
|
+
if (a.status !== 0) throw new Error(`rsync of ${src}: ${a.stderr}`);
|
|
3086
|
+
const nm = path.join(src, "node_modules");
|
|
3087
|
+
if (fs.existsSync(nm) && !fs.existsSync(path.join(dest, "node_modules"))) { const c = spawnSync("cp", ["-cRL", nm, path.join(dest, "node_modules")], { encoding: "utf8" }); if (c.status !== 0) throw new Error(`cp node_modules: ${c.stderr}`); }
|
|
3088
|
+
}
|
|
3089
|
+
/** Writes the mutant copy and returns `{ dir, entry, diff }`; the checkout is never touched. */
|
|
3090
|
+
export function makeMutant(root, m) {
|
|
3091
|
+
const dir = path.join(root, m.nn ?? "baseline"); const rel = path.join(dir, "release");
|
|
3092
|
+
copyRelease(rel);
|
|
3093
|
+
const entry = path.join(rel, "bin", "rightkit-gate.mjs");
|
|
3094
|
+
let diff = "(unmutated copy)";
|
|
3095
|
+
if (m.patch) {
|
|
3096
|
+
const target = path.join(rel, m.patch.file ?? path.join("bin", "rightkit-gate.mjs"));
|
|
3097
|
+
const text = fs.readFileSync(target, "utf8");
|
|
3098
|
+
if (text.split(m.patch.find).length !== 2) throw new Error(`mutant ${m.nn}: the patch anchor is not unique in ${path.basename(target)}`);
|
|
3099
|
+
fs.writeFileSync(target, text.replace(m.patch.find, () => m.patch.replace));
|
|
3100
|
+
diff = `--- ${m.patch.find}\n+++ ${m.patch.replace}`;
|
|
3101
|
+
}
|
|
3102
|
+
if (m.inject) {
|
|
3103
|
+
const text = fs.readFileSync(entry, "utf8");
|
|
3104
|
+
if (text.split(GATE_INJECT_ANCHOR).length !== 2) throw new Error(`mutant ${m.nn}: the anchor \`installSpawnLedger();\` is not unique in the gate`);
|
|
3105
|
+
const add = ` const __cp = process.getBuiltinModule("node:child_process"); // MUTANT ${m.nn}: ${m.what}\n${m.inject.map((l) => ` ${l}`).join("\n")}\n`;
|
|
3106
|
+
fs.writeFileSync(entry, text.replace(GATE_INJECT_ANCHOR, () => GATE_INJECT_ANCHOR + add));
|
|
3107
|
+
diff = `+++ bin/rightkit-gate.mjs (after installSpawnLedger();)\n${add.replace(/^/gm, "+")}`;
|
|
3108
|
+
}
|
|
3109
|
+
fs.chmodSync(entry, 0o755);
|
|
3110
|
+
fs.writeFileSync(path.join(dir, "mutation.diff"), `${diff}\n`);
|
|
3111
|
+
return { dir, entry, diff };
|
|
3112
|
+
}
|
|
3113
|
+
|
|
3114
|
+
/** An installed rustup toolchain other than the one the gate recorded (`rustc 1.96.1 (...)`): the newest remaining one, or null. */
|
|
3115
|
+
function otherToolchain(recordedRustc) {
|
|
3116
|
+
const home = process.env.RUSTUP_HOME || path.join(os.homedir(), ".rustup");
|
|
3117
|
+
let names = []; try { names = fs.readdirSync(path.join(home, "toolchains")); } catch { return null; }
|
|
3118
|
+
const rec = /rustc (\d+\.\d+\.\d+)/.exec(String(recordedRustc ?? ""))?.[1] ?? null;
|
|
3119
|
+
const ver = (n) => (/^(\d+)\.(\d+)\.(\d+)/.exec(n) ?? []).slice(1).map(Number);
|
|
3120
|
+
const cmp = (a, b) => { for (let i = 0; i < 3; i += 1) if ((a[i] ?? 0) !== (b[i] ?? 0)) return (b[i] ?? 0) - (a[i] ?? 0); return 0; };
|
|
3121
|
+
const cands = names.filter((n) => /^\d+\.\d+\.\d+/.test(n) && (!rec || !n.startsWith(`${rec}-`))).sort((a, b) => cmp(ver(a), ver(b)));
|
|
3122
|
+
return cands[0] ?? null;
|
|
3123
|
+
}
|
|
3124
|
+
const spawnRunner = (file, args) => runRunner(args, { cwd: path.dirname(file), file });
|
|
3125
|
+
function runRunner(args, { cwd, file = RUNNER_FILE }) {
|
|
3126
|
+
return new Promise((resolve) => {
|
|
3127
|
+
let out = "";
|
|
3128
|
+
const child = spawn(process.execPath, [file, ...args], { cwd, stdio: ["ignore", "pipe", "pipe"] });
|
|
3129
|
+
child.stdout.on("data", (d) => { out += d; }); child.stderr.on("data", (d) => { out += d; });
|
|
3130
|
+
child.on("close", (code) => resolve({ code, out }));
|
|
3131
|
+
child.on("error", (e) => resolve({ code: null, out: `${out}\n${e.message}` }));
|
|
3132
|
+
});
|
|
3133
|
+
}
|
|
3134
|
+
|
|
3135
|
+
/** `--prove`: every NN is shown to be able to fail, by a real-condition control, a mutant gate, or a real altered contract. Fails unless every NN is caught. */
|
|
3136
|
+
async function proveMain({ fixture, host, out }) {
|
|
3137
|
+
if (!fixture) { console.error("usage: node gate-acceptance.mjs --prove --fixture <dir> [--host mac|dell] [--prove-out <dir>]"); return 64; }
|
|
3138
|
+
const scratch = path.join(scratchRootOf(host), "gate-acceptance");
|
|
3139
|
+
const root = out ?? path.join(scratch, "prove", new Date().toISOString().replace(/[:.]/g, "-"));
|
|
3140
|
+
const mutRoot = path.join(scratch, "mutants");
|
|
3141
|
+
fs.mkdirSync(root, { recursive: true }); fs.mkdirSync(mutRoot, { recursive: true });
|
|
3142
|
+
const proofs = {}; const log = []; const controls = [];
|
|
3143
|
+
const note = (id, how, caught, detail) => { (proofs[id] ??= []).push({ how, caught, detail }); log.push(`${id} ${caught ? "CAUGHT" : "not caught"} by ${how}${detail ? `: ${detail}` : ""}`); };
|
|
3144
|
+
const resultOf = (dir) => { try { return JSON.parse(fs.readFileSync(path.join(dir, "result.json"), "utf8")); } catch { return null; } };
|
|
3145
|
+
const common = ["--fixture", fixture, "--host", host];
|
|
3146
|
+
|
|
3147
|
+
// NN33: the real runner against a real altered contract (a row removed; a row added).
|
|
3148
|
+
const real = fs.readFileSync(CONTRACT_FILE, "utf8");
|
|
3149
|
+
const variants = { "a row removed": real.split("\n").filter((l) => !/^\| NN20 \|/.test(l)).join("\n"), "a row added": real.replace(/^(\| NN38 \|.*)$/m, "$1\n| NN99 | An invented property | never |") };
|
|
3150
|
+
for (const [name, text] of Object.entries(variants)) {
|
|
3151
|
+
const f = path.join(root, `contract-${name.replace(/\s/g, "-")}.md`); fs.writeFileSync(f, text);
|
|
3152
|
+
const o = path.join(root, `nn33-${name.replace(/\s/g, "-")}`);
|
|
3153
|
+
await runRunner([...common, "--steps", "S0", "--nn", "NN33", "--contract-file", f, "--out", o], { cwd: here });
|
|
3154
|
+
const r = resultOf(o)?.nonNegotiables?.find((n) => n.id === "NN33");
|
|
3155
|
+
note("NN33", `the runner against a contract with ${name}`, r?.status === "fail" && /NN(20|99)/.test(r.problems.join()), r?.problems?.[0]);
|
|
3156
|
+
}
|
|
3157
|
+
// Controls: the real runner against an unmutated copy of the checkout gate, with the cache moved aside (S11) after warm runs (S2).
|
|
3158
|
+
const base = makeMutant(mutRoot, { nn: "baseline" });
|
|
3159
|
+
const co = path.join(root, "controls");
|
|
3160
|
+
const cr = await runRunner([...common, "--steps", "S2,S11", "--checks-only", "--nn", "NN19,NN11,NN27,NN38", "--gate", base.entry, "--out", co], { cwd: here });
|
|
3161
|
+
const cres = resultOf(co);
|
|
3162
|
+
if (!cres) log.push(`controls run produced no result (exit ${cr.code})`);
|
|
3163
|
+
for (const [id, p] of Object.entries(cres?.proofs ?? {})) note(id, p.kind, p.caught === true, p.caught ? "the assertion flagged the real violation" : "the assertion did NOT flag it");
|
|
3164
|
+
// Mutants.
|
|
3165
|
+
for (const m of MUTANTS) {
|
|
3166
|
+
let mm; try { mm = makeMutant(mutRoot, m); } catch (e) { note(m.nn, `mutant gate (${m.what})`, false, e.message); continue; }
|
|
3167
|
+
const o = path.join(root, `mutant-${m.nn}`);
|
|
3168
|
+
const args = [...common, "--steps", m.steps, "--nn", m.nn, "--gate", mm.entry, "--out", o]; if (m.steps === "S2" && !m.compile) args.push("--checks-only");
|
|
3169
|
+
if (m.extra) args.push(...m.extra);
|
|
3170
|
+
await runRunner(args, { cwd: here });
|
|
3171
|
+
const r = resultOf(o)?.nonNegotiables?.find((n) => n.id === m.nn);
|
|
3172
|
+
const hit = r?.status === "fail" && r.problems.some((p) => m.expect.test(p));
|
|
3173
|
+
if (m.control) {
|
|
3174
|
+
// The unmutated control: the same run against the unmutated copy of the gate must NOT show the mutant's failure.
|
|
3175
|
+
const oc = path.join(root, `control-${m.nn}`);
|
|
3176
|
+
await runRunner([...args.slice(0, args.indexOf("--gate")), "--gate", base.entry, "--out", oc, ...(m.extra ?? [])], { cwd: here });
|
|
3177
|
+
const cr2 = resultOf(oc)?.nonNegotiables?.find((n) => n.id === m.nn);
|
|
3178
|
+
const shown = cr2?.problems?.find((x) => m.expect.test(x));
|
|
3179
|
+
controls.push({ id: m.nn, ok: Boolean(cr2) && !shown, detail: !cr2 ? "no result" : shown ? `the unmutated gate SHOWS the failure: ${shown.slice(0, 200)}` : `the unmutated gate does not show it (verdict ${cr2.status}${cr2.status === "fail" ? `: ${cr2.problems[0]?.slice(0, 160)}` : ""})`, out: oc });
|
|
3180
|
+
log.push(`${m.nn} control (unmutated gate, same run): ${controls[controls.length - 1].ok ? "does not show the failure" : "SHOWS the failure"}: ${controls[controls.length - 1].detail}`);
|
|
3181
|
+
}
|
|
3182
|
+
note(m.nn, `mutant gate: ${m.what} (${mm.dir}/mutation.diff)`, hit, hit ? r.problems.find((p) => m.expect.test(p)).slice(0, 140) : r ? `verdict ${r.status}; ${r.problems.slice(0, 2).join(" | ").slice(0, 200)}` : "no result");
|
|
3183
|
+
}
|
|
3184
|
+
// Real gate evidence from the controls run (the unmutated checkout gate): a check that fails there on a violation or on missing evidence is shown to be able to fail.
|
|
3185
|
+
for (const id of ["NN11", "NN27", "NN38"]) {
|
|
3186
|
+
const r = cres?.nonNegotiables?.find((n) => n.id === id);
|
|
3187
|
+
const missing = id === "NN11";
|
|
3188
|
+
note(id, missing ? "the real gate lacks the evidence the check needs (missing evidence fails; weaker than a violation)" : "a real violation by the unmutated checkout gate", r?.status === "fail", r?.problems?.[0]?.slice(0, 200));
|
|
3189
|
+
}
|
|
3190
|
+
// NN18: the real runner against a real budgets file with a 1 ms budget.
|
|
3191
|
+
{
|
|
3192
|
+
const tight = JSON.parse(fs.readFileSync(BUDGETS_FILE, "utf8"));
|
|
3193
|
+
tight.hosts.mac.warmCheckMs = 1; tight.hosts.mac.stages.dependencyStep = 1;
|
|
3194
|
+
const f = path.join(root, "budgets-1ms.json"); fs.writeFileSync(f, `${JSON.stringify(tight, null, 2)}\n`);
|
|
3195
|
+
const o = path.join(root, "nn18-tight");
|
|
3196
|
+
await runRunner([...common, "--steps", "S2", "--checks-only", "--nn", "NN18", "--budgets", f, "--gate", base.entry, "--out", o], { cwd: here });
|
|
3197
|
+
const r = resultOf(o)?.nonNegotiables?.find((n) => n.id === "NN18");
|
|
3198
|
+
const hit = r?.status === "fail" && r.problems.find((p) => /took \d+ ms, budget 1 ms/.test(p));
|
|
3199
|
+
note("NN18", "the real runner against a budgets file with a 1 ms budget", Boolean(hit), hit ? hit.slice(0, 200) : r?.problems?.[0]);
|
|
3200
|
+
}
|
|
3201
|
+
// NN23: needs two distinct sealed versions; without them the check's own failure message is the proof.
|
|
3202
|
+
{
|
|
3203
|
+
const gates = listInstalledGates(managedRootOf(host));
|
|
3204
|
+
const distinct = new Set(gates.map((x) => x.version)).size;
|
|
3205
|
+
const o = path.join(root, "nn23");
|
|
3206
|
+
await runRunner([...common, "--steps", "S13", "--nn", "NN23", "--out", o], { cwd: here });
|
|
3207
|
+
const r = resultOf(o)?.nonNegotiables?.find((n) => n.id === "NN23");
|
|
3208
|
+
if (distinct < 2) note("NN23", `the failure message itself: ${distinct} distinct sealed version(s) installed, so a real upgrade cannot be run (weaker than a violation)`, r?.status === "fail" && /needs two installed versions/.test(r.problems.join()), r?.problems?.[0]?.slice(0, 200));
|
|
3209
|
+
else note("NN23", "a real upgrade between the two newest sealed gates", r?.status === "fail", r?.problems?.[0]?.slice(0, 200) ?? `the check passed on a real upgrade: it can fail only when keys change, so it is unproven`);
|
|
3210
|
+
}
|
|
3211
|
+
// NN30, NN31, NN35: real --verify-release refusals on receipts built from the real run's result.
|
|
3212
|
+
if (cres) {
|
|
3213
|
+
const inst = listInstalledGates(managedRootOf(host))[0] ?? null;
|
|
3214
|
+
const budgets = loadBudgets().budgets;
|
|
3215
|
+
const mk = (h, over = {}) => ({ ...buildContractReceipt({ host: h, commit: "a".repeat(40), gate: { kind: "installed", version: inst?.version ?? "0", sealedPath: inst?.entry ?? null, sealedSha256: inst?.sealedSha256 ?? "b".repeat(64) }, contractSha256: fileSha(CONTRACT_FILE), runnerSha256: fileSha(RUNNER_FILE), budgetsSha256: fileSha(BUDGETS_FILE), fixtureCommit: budgets?.fixture?.commit ?? "c".repeat(40), result: cres }), ...over });
|
|
3216
|
+
const w = (name, r) => { const f = path.join(root, `receipt-${name}.json`); fs.writeFileSync(f, `${JSON.stringify(r, null, 2)}\n`); return f; };
|
|
3217
|
+
const verify = async (a, b) => runRunner(["--verify-release", a, b], { cwd: here });
|
|
3218
|
+
const real1 = await verify(w("mac-real", mk("mac")), path.join(root, "receipt-dell-missing.json"));
|
|
3219
|
+
note("NN30", "--verify-release with the Dell receipt missing", real1.code === 1 && /ENOENT|cannot read/.test(real1.out), real1.out.split("\n").slice(0, 2).join(" | ").slice(0, 200));
|
|
3220
|
+
const real2 = await verify(w("mac-fail", mk("mac")), w("dell-fail", mk("dell")));
|
|
3221
|
+
note("NN30", "--verify-release with a failing receipt from each host (the real run's NOT PASSED result)", real2.code === 1 && /not a PASS/.test(real2.out), (real2.out.split("\n")[1] ?? "").trim().slice(0, 200));
|
|
3222
|
+
note("NN31", "--verify-release refuses a release whose receipts are not passes (what release, upload and promotion must call)", real2.code === 1 && /REFUSED/.test(real2.out), (real2.out.split("\n")[0] ?? "").slice(0, 200));
|
|
3223
|
+
const allPass = Object.fromEntries(NN_ALL_IDS.map((id) => [id, "pass"]));
|
|
3224
|
+
const unw = await verify(w("mac-unchecked", mk("mac", { ok: true, verdict: "PASS (forced for the proof)", nn: allPass })), w("dell-unchecked", mk("dell", { ok: true, verdict: "PASS (forced for the proof)", nn: allPass })));
|
|
3225
|
+
note("NN35", "--verify-release with passing receipts that leave operative clauses unchecked and unwaived", unw.code === 1 && /unchecked and not waived by Adrian/.test(unw.out), (unw.out.split("\n")[1] ?? "").trim().slice(0, 200));
|
|
3226
|
+
}
|
|
3227
|
+
// NN36 and NN37: real commits in a scratch clone of rightkit.
|
|
3228
|
+
{
|
|
3229
|
+
const lp = path.join(scratch, "lockproof"); const clone = path.join(lp, `clone-${Date.now()}`);
|
|
3230
|
+
fs.mkdirSync(lp, { recursive: true });
|
|
3231
|
+
const sh = (args, cwd = clone) => { const r = spawnSync("git", args, { cwd, encoding: "utf8" }); if (r.status !== 0) throw new Error(`git ${args.join(" ")}: ${r.stderr || r.stdout}`); return r.stdout; };
|
|
3232
|
+
try {
|
|
3233
|
+
sh(["clone", "--quiet", path.resolve(here, "..", ".."), clone], lp);
|
|
3234
|
+
const cp = spawnSync("cp", ["-cRL", path.join(here, "node_modules"), path.join(clone, "packages", "release", "node_modules")], { encoding: "utf8" });
|
|
3235
|
+
if (cp.status !== 0) throw new Error(`cp node_modules: ${cp.stderr}`);
|
|
3236
|
+
const cRunner = path.join(clone, "packages", "release", "gate-acceptance.mjs");
|
|
3237
|
+
const cBudgets = path.join(clone, "ci", "gate-acceptance-budgets.json");
|
|
3238
|
+
const judge = async (name) => { const o = path.join(root, `lock-${name}`); await spawnRunner(cRunner, [...common, "--steps", "S0", "--nn", "NN36,NN37", "--out", o]); return resultOf(o)?.nonNegotiables ?? []; };
|
|
3239
|
+
sh(["commit", "--allow-empty", "-q", "-m", "lock the contract test\n\nGate-Acceptance-Locked: lockproof baseline"]);
|
|
3240
|
+
const base36 = (await judge("1-locked")).find((n) => n.id === "NN36");
|
|
3241
|
+
log.push(`NN36 control (not a proof): locked baseline, nothing changed since: ${base36?.status} ${base36?.problems?.[0]?.slice(0, 160) ?? ""}`);
|
|
3242
|
+
fs.appendFileSync(cRunner, "\n// lockproof: a change to the runner with no approval line\n");
|
|
3243
|
+
sh(["commit", "-q", "-am", "runner: an unapproved change"]);
|
|
3244
|
+
const u36 = (await judge("2-unapproved")).find((n) => n.id === "NN36");
|
|
3245
|
+
note("NN36", "scratch clone: a real commit changes the runner without the approval line", u36?.status === "fail" && /without `Adrian-approved:/.test(u36.problems.join()), u36?.problems?.find((p) => /Adrian-approved/.test(p))?.slice(0, 200) ?? u36?.problems?.[0]);
|
|
3246
|
+
const b = JSON.parse(fs.readFileSync(cBudgets, "utf8")); b.hosts.mac.warmCheckMs = (b.hosts.mac.warmCheckMs ?? 1000) * 2;
|
|
3247
|
+
fs.writeFileSync(cBudgets, `${JSON.stringify(b, null, 2)}\n`);
|
|
3248
|
+
sh(["commit", "-q", "-am", "budgets: raise warmCheckMs\n\nAdrian-approved: lockproof (the approval line is present; the rise is the violation)"]);
|
|
3249
|
+
const r36 = (await judge("3-raised")).find((n) => n.id === "NN36");
|
|
3250
|
+
note("NN36", "scratch clone: a commit that cites approval but raises a budget", r36?.status === "fail" && /raised a budget/.test(r36.problems.join()), r36?.problems?.find((p) => /raised a budget/.test(p))?.slice(0, 200) ?? r36?.problems?.[0]);
|
|
3251
|
+
const n37a = (await judge("4-noreview")).find((n) => n.id === "NN37");
|
|
3252
|
+
note("NN37", "scratch clone: no independent review recorded", n37a?.status === "fail" && /no independent review/.test(n37a.problems.join()), n37a?.problems?.[0]?.slice(0, 200));
|
|
3253
|
+
const rs = fileSha(cRunner); const cs = fileSha(path.join(clone, "docs", "GATE-CONTRACT.md"));
|
|
3254
|
+
const b2 = JSON.parse(fs.readFileSync(cBudgets, "utf8")); b2.reviews = [{ runnerSha256: rs, contractSha256: cs, reviewer: "same", author: "same", adrianWords: "lockproof", verdict: "pass" }];
|
|
3255
|
+
fs.writeFileSync(cBudgets, `${JSON.stringify(b2, null, 2)}\n`); sh(["commit", "-q", "-am", "budgets: self review\n\nAdrian-approved: lockproof"]);
|
|
3256
|
+
const n37b = (await judge("5-selfreview")).find((n) => n.id === "NN37");
|
|
3257
|
+
note("NN37", "scratch clone: the reviewer is the author", n37b?.status === "fail" && /no independent review/.test(n37b.problems.join()), n37b?.problems?.[0]?.slice(0, 200));
|
|
3258
|
+
b2.reviews = [{ runnerSha256: rs, contractSha256: cs, reviewer: "other", author: "same", adrianWords: "lockproof", verdict: "pass" }];
|
|
3259
|
+
fs.writeFileSync(cBudgets, `${JSON.stringify(b2, null, 2)}\n`); sh(["commit", "-q", "-am", "budgets: independent review\n\nAdrian-approved: lockproof"]);
|
|
3260
|
+
const n37c = (await judge("6-review")).find((n) => n.id === "NN37");
|
|
3261
|
+
log.push(`NN37 control: with an independent review recorded the check is ${n37c?.status}`);
|
|
3262
|
+
} catch (e) { log.push(`lockproof failed: ${e.message}`); note("NN36", "scratch clone", false, e.message.slice(0, 200)); note("NN37", "scratch clone", false, e.message.slice(0, 200)); }
|
|
3263
|
+
}
|
|
3264
|
+
// NN32: the unmutated gate recovers real kills (information), after the mutant above left a stale record: reclaimed by this run.
|
|
3265
|
+
{
|
|
3266
|
+
const o = path.join(root, "kills-real");
|
|
3267
|
+
await runRunner([...common, "--steps", "S8", "--nn", "NN32", "--gate", base.entry, "--kills", "K01,K01-int,K02,K02-int", "--out", o], { cwd: here });
|
|
3268
|
+
const r = resultOf(o)?.nonNegotiables?.find((n) => n.id === "NN32");
|
|
3269
|
+
log.push(`NN32 real kills on the unmutated gate (SIGKILL compile, SIGINT compile, SIGKILL check, SIGINT check): ${r?.status} ${r?.problems?.[0]?.slice(0, 200) ?? ""}`);
|
|
3270
|
+
}
|
|
3271
|
+
const rows = NN_ALL_IDS.map((id) => ({ id, proven: (proofs[id] ?? []).some((p) => p.caught), proofs: proofs[id] ?? [] }));
|
|
3272
|
+
const unproven = rows.filter((r) => !r.proven).map((r) => r.id);
|
|
3273
|
+
const badControls = controls.filter((c) => !c.ok);
|
|
3274
|
+
const summary = { schema: "rightkit.gate-acceptance-prove/1", host, ok: unproven.length === 0 && badControls.length === 0, unproven, controls, rows, log };
|
|
3275
|
+
fs.writeFileSync(path.join(root, "prove-result.json"), `${JSON.stringify(summary, null, 2)}\n`);
|
|
3276
|
+
console.log(`prove ${summary.ok ? "OK" : "FAILED"}: ${rows.length - unproven.length} of ${rows.length} non-negotiables have a proof that they can fail; ${controls.length - badControls.length} of ${controls.length} unmutated controls are clean`);
|
|
3277
|
+
for (const c of controls) console.log(` control ${c.id} ${c.ok ? "clean" : "SHOWS THE FAILURE"}: ${c.detail}`);
|
|
3278
|
+
for (const r of rows) console.log(` ${r.id} ${r.proven ? "proven" : "UNPROVEN"}${r.proofs.filter((p) => p.caught).map((p) => ` [${p.how.slice(0, 70)}]`).join("")}`);
|
|
3279
|
+
console.log(`result: ${path.join(root, "prove-result.json")}`);
|
|
3280
|
+
return summary.ok ? 0 : 1;
|
|
3281
|
+
}
|
|
3282
|
+
|
|
1436
3283
|
function runDry(ownerFile) {
|
|
1437
3284
|
const r = spawnSync(process.execPath, [path.join(here, "ownership-recover.mjs"), ownerFile], { encoding: "utf8" });
|
|
1438
3285
|
return { exit: r.status, text: `${r.stdout ?? ""}${r.stderr ?? ""}` };
|