@rightkit/release 0.6.45 → 0.6.47
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/affected-units.mjs +190 -0
- package/bin/rightkit-gate.mjs +629 -132
- package/build-ownership.mjs +206 -41
- package/cargo-width.mjs +49 -0
- package/ci-compile-admission.mjs +57 -0
- package/committed-cargo-workspace.mjs +58 -0
- package/cross-targets.mjs +18 -2
- package/dependency-identity.mjs +98 -0
- package/deterministic-scans.mjs +256 -57
- package/gate-acceptance.mjs +1443 -0
- package/gate-coverage.mjs +17 -6
- package/gate-serve.mjs +239 -0
- package/handle-revocation.mjs +100 -0
- package/handle-revocation.rust-vector.json +1 -0
- package/handle-revocation.vectors.json +53 -0
- package/local-publish.mjs +109 -34
- package/managed-cargo.mjs +11 -0
- package/node-check-cache.mjs +95 -0
- package/owner-process-proof.mjs +14 -0
- package/ownership-mark.mjs +10 -1
- package/ownership-recover.mjs +78 -0
- package/package.json +2 -1
- package/performance-diagnostic.mjs +19 -0
- package/provenance-verify.mjs +35 -0
- package/publication-gate.mjs +62 -29
- package/publish-cargo.mjs +19 -4
- package/qualification-verify.mjs +12 -2
- package/rightkit-drift.mjs +4 -3
- package/rightkit-versions.json +1 -1
- package/snapshot-broker.mjs +1 -1
- package/snapshot-check.mjs +91 -12
- package/snapshot-dependency-reuse.mjs +230 -0
- package/snapshot-metadata.mjs +1 -1
- package/snapshot-request.mjs +12 -5
- package/snapshot.mjs +41 -6
- package/stage-sidecar.mjs +20 -4
- package/stamp-relay.mjs +37 -0
- package/unit-gate.mjs +25 -5
- package/unit-list-compile.mjs +277 -0
|
@@ -0,0 +1,1443 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// End-to-end acceptance runner for the gate (rightkit#1514). It drives the real gate against the witness fixture and asserts every operative clause of
|
|
3
|
+
// docs/GATE-CONTRACT.md from that run's OWN artifacts: the door receipt (--receipt-out), the per-scan coverage reports, the log, the owner record and
|
|
4
|
+
// git. Spec: /Volumes/D/scratch/gate-acceptance/criteria.md (clause table, run sequence S0-S9, negatives, kill-and-recover).
|
|
5
|
+
//
|
|
6
|
+
// node gate-acceptance.mjs --fixture <dir> [--host mac|dell] [--steps S0,S1,...] [--out <dir>] [--plan] [--gate <path>] [--commit <sha>] [--allow-install]
|
|
7
|
+
//
|
|
8
|
+
// Rules this file keeps:
|
|
9
|
+
// * Three states per clause: "pass", "fail", "unchecked". A clause with no evidence available is "unchecked", never "pass". A skipped scan row is never a pass.
|
|
10
|
+
// * Fail closed: an unknown field, a missing artifact or a malformed value is a "fail" with the reason, never skipped over.
|
|
11
|
+
// * Every assertion names its clause id and the evidence path (or evidence source) it read.
|
|
12
|
+
// * No cache bypass flag is ever passed to do work (N13 passes the two retired bypasses only to prove the gate refuses them) and nothing is pushed or published. Nothing is installed by default: `--to dev` and `--to qualify` install
|
|
13
|
+
// apps, so they run only with `--allow-install` (which needs Adrian's approval); without it their clauses are "unchecked: needs install approval".
|
|
14
|
+
// Negative inputs are ephemeral `git commit-tree` commits under refs/witness/<case> (no branch, no worktree, no checkout write); the refs are deleted
|
|
15
|
+
// at the end. The one checkout write is S6's dirty-checkout setup, which refuses a dirty fixture and restores it exactly.
|
|
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
|
+
// count of unchecked clauses ("PASS (N of 67 asserted, M unchecked)"), never as a bare PASS.
|
|
18
|
+
// * Timing is relative and informational only: the contract gives no latency threshold, so wall time never fails a clause.
|
|
19
|
+
// The pure assertion functions are exported and tested by gate-acceptance.test.mjs; `--plan` prints the steps and clause mapping and runs nothing.
|
|
20
|
+
import { createHash } from "node:crypto";
|
|
21
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
22
|
+
import fs from "node:fs";
|
|
23
|
+
import path from "node:path";
|
|
24
|
+
import { fileURLToPath } from "node:url";
|
|
25
|
+
import { keyPath, repoKey } from "./snapshot.mjs";
|
|
26
|
+
import { ownershipFile, runningBrokerProcess } from "./build-ownership.mjs";
|
|
27
|
+
import { RUNTIME_MANIFEST_FILE } from "./broker-handshake.mjs";
|
|
28
|
+
import { resolveBrokerClient } from "./broker-client.mjs";
|
|
29
|
+
import { managedRuntimeClient } from "./managed-roots.mjs";
|
|
30
|
+
|
|
31
|
+
export const RESULT_SCHEMA = "rightkit.gate-acceptance/1";
|
|
32
|
+
export const COVERAGE_SCHEMA = "rightkit.gate-coverage/1";
|
|
33
|
+
export const RECEIPT_SCHEMA = "rightkit.gate-receipt/1";
|
|
34
|
+
export const SOURCE_IDENTITY_SCHEMA = "rightkit.source-identity.v1";
|
|
35
|
+
export const RENDER_RECEIPT_SCHEMA = "rightkit.render-views/1";
|
|
36
|
+
export const OWNERSHIP_SCHEMA = "rightkit.build-ownership/1";
|
|
37
|
+
|
|
38
|
+
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
39
|
+
const sha256 = (data) => createHash("sha256").update(data).digest("hex");
|
|
40
|
+
const isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
|
|
41
|
+
const isSha = (v) => typeof v === "string" && /^[0-9a-f]{64}$/.test(v);
|
|
42
|
+
const isCommit = (v) => typeof v === "string" && /^[0-9a-f]{40}$/.test(v);
|
|
43
|
+
|
|
44
|
+
// ---------------------------------------------------------------------------------------------------------------------------------------------
|
|
45
|
+
// Clause registry: the 67 operative rows of criteria.md section 1 (id, evidence tag, title). `implemented` clauses have an assertion in CHECKS below;
|
|
46
|
+
// every other clause is reported "unchecked" with the reason from UNCHECKED_WHY (the gate writes no evidence the runner may read, or the fixture
|
|
47
|
+
// rows the case needs do not exist yet).
|
|
48
|
+
// ---------------------------------------------------------------------------------------------------------------------------------------------
|
|
49
|
+
const ROWS = [
|
|
50
|
+
["GC-A01", "M", "warm only; one snapshot dir; one worktree; no cache bypass"], ["GC-A02", "M", "stash never a build source, never left behind"],
|
|
51
|
+
["GC-A03", "P", "Class A covers the closure plus file-only scans"], ["GC-A04", "M", "build is from the selected commit via the snapshot"],
|
|
52
|
+
["GC-A05", "M", "broker runs no gate"], ["GC-A06", "P", "runs on the real broker of the host"], ["GC-A07", "P", "no debug build; QA marker only in dev"],
|
|
53
|
+
["GC-A08", "M", "cargo test compiles in the broker, runs outside"], ["GC-A09", "M", "no test-mode feature"], ["GC-A10", "P", "QA journeys with mandatory [snapshot]"],
|
|
54
|
+
["GC-A11", "P", "Class A and non-compiling cargo run direct"], ["GC-A12", "G", "tsc once in Class A"], ["GC-A13", "M", "unexplained rebuild never fails; cause evidence recorded"],
|
|
55
|
+
["GC-A14", "M", "every crate clippy-checked for all three OS targets"], ["GC-A15", "M", "one output and one warm cache per app per host; release profile"],
|
|
56
|
+
["GC-A16", "G", "dev builds signed, not notarized"], ["GC-A18", "P", "Class B batched per workspace, bisected"], ["GC-A19", "M", "audit scans cached by lock+config+advisory+day"],
|
|
57
|
+
["GC-A21", "M", "UTC-stamped log, stage timings, per-scan coverage JSON"], ["GC-A22-render", "M", "--to render builds and runs the declared target, PNGs and receipt"],
|
|
58
|
+
["GC-A22-classA", "M", "ghsa-audit, freshness advice, feature-coverage, secret-scan, store proof"], ["GC-A23", "M", "deterministic .rightkit-source-identity.json"],
|
|
59
|
+
["GC-A24", "M", "Class A is change-driven, rows keyed on own inputs"],
|
|
60
|
+
["GC-T01", "P", "origin host compile proves only what it compiled"], ["GC-T02", "P", "Mac and Windows artifacts built natively"], ["GC-T03", "G", "private qualification runs locally"],
|
|
61
|
+
["GC-T04", "M", "compile only through the broker, no direct fallback"], ["GC-T05", "M", "Class A completes before the first compile"], ["GC-T06", "M", "commit-only build, exact snapshot, per-repository lock"],
|
|
62
|
+
["GC-T07", "G", "qualification policy pinned by digest"], ["GC-T10", "P", "product manifest declares target kinds"], ["GC-T11", "P", "sign once, qualify sealed bytes"],
|
|
63
|
+
["GC-T12", "P", "one signing identity per product"], ["GC-T13", "P", "same gate for human and agent callers"], ["GC-T14", "M", "one checkout, one snapshot dir, one output dir; no bypass"],
|
|
64
|
+
["GC-T16", "M", "every cargo call keeps going"], ["GC-T17", "G", "broker trusts a published gate (contract conflict, unreconciled)"], ["GC-T18", "M", "fixture-files.json skips only per-file format scans"],
|
|
65
|
+
["GC-T19", "M", "rule tier by stage"], ["GC-T20", "M", "commit and push run no gate and no hook"], ["GC-T24", "M", "unit-list plans, dependency-first, broker argv shapes"],
|
|
66
|
+
["GC-I01", "M", "snapshot root and repository key"], ["GC-I02", "M", "gate creates no output dir; broker-pinned target"], ["GC-I03", "M", "Class A check route, tree id before and after"],
|
|
67
|
+
["GC-I04", "M", "request carries commit, snapshot, declaredInputs, ownership"], ["GC-I05", "M", "receipt fields"], ["GC-I06", "P", "broker lease from admission to reap"],
|
|
68
|
+
["GC-I08", "P", "native tool adapters"], ["GC-I11", "M", "clippy route keeps scope and aggregates FAILED"], ["GC-I12", "M", "broker admits only <data root>/snapshots/<repo-key>"],
|
|
69
|
+
["GC-I13", "P", "refusal at admission leaves a durable REAPED completion"], ["GC-I14", "M", "absent declared input recorded"], ["GC-I15", "P", "installed broker executable path rule"],
|
|
70
|
+
["GC-I16", "M", "broker config path"], ["GC-I17", "M", "answering broker's roots on the wire"], ["GC-I18", "M", "pinned digest is the answering broker's"],
|
|
71
|
+
["GC-I19", "M", "lease status shape and aggregate rule"], ["GC-I20", "P", "scan tools only from enrolled executables"], ["GC-I21", "P", "gate-owned dirs registered in the census"],
|
|
72
|
+
["GC-I22", "M", "vendored vectors are byte copies"],
|
|
73
|
+
["GC-Q01", "P", "origin record fields"], ["GC-Q02", "P", "compile digests apart from artifact identity"], ["GC-Q03", "G", "native build record"], ["GC-Q04", "G", "final sealed digest bound to coverage"],
|
|
74
|
+
["GC-Q05", "G", "private qualification evidence"], ["GC-1A-R2", "M", "build outside broker only with a recorded exception"], ["GC-1A-R4", "M", "committed build definition lists every Cargo workspace"],
|
|
75
|
+
].map(([id, ev, title]) => Object.freeze({ id, ev, title }));
|
|
76
|
+
export const CLAUSES = Object.freeze(Object.fromEntries(ROWS.map((r) => [r.id, r])));
|
|
77
|
+
|
|
78
|
+
const NO_EVIDENCE = "the gate writes no artifact the runner may read for this clause (criteria.md section 5)";
|
|
79
|
+
const NEEDS_BROKER_RECEIPTS = "needs broker receipts (argv, transformations, testExecutables); the door receipt does not carry them and the receipt-dir path of a stage run is not named by the contract";
|
|
80
|
+
const NEEDS_HOST_TOOL = "needs a host tool (codesign, signtool, stapler, find) or the installed app; not read by this runner";
|
|
81
|
+
const NEEDS_FIXTURE = "needs fixture rows (criteria.md section 2, F1-F14) that do not exist in the witness fixture yet";
|
|
82
|
+
export const NEEDS_INSTALL_APPROVAL = "needs install approval";
|
|
83
|
+
/** Clauses whose evidence comes from `--to dev` or `--to qualify`, both of which install an app: unchecked unless `--allow-install` ran them. */
|
|
84
|
+
export const INSTALL_CLAUSES = Object.freeze(["GC-A07", "GC-A10", "GC-A16", "GC-T03", "GC-T07", "GC-T11", "GC-T12", "GC-Q04", "GC-Q05"]);
|
|
85
|
+
export const UNCHECKED_WHY = Object.freeze({
|
|
86
|
+
"GC-A03": NEEDS_FIXTURE, "GC-A05": NEEDS_BROKER_RECEIPTS, "GC-A06": "needs HANDSHAKE and STATUS from a live broker query; the runner reads the runtime manifest and pins only (see GC-I18)", "GC-A07": NEEDS_HOST_TOOL,
|
|
87
|
+
"GC-A08": NEEDS_BROKER_RECEIPTS, "GC-A09": NEEDS_FIXTURE, "GC-A10": NEEDS_FIXTURE, "GC-A11": NO_EVIDENCE, "GC-A12": NO_EVIDENCE, "GC-A13": "needs the compile freshness object, which sits in broker receipts not in the door receipt",
|
|
88
|
+
"GC-A14": NEEDS_BROKER_RECEIPTS, "GC-A16": NO_EVIDENCE, "GC-A18": NEEDS_BROKER_RECEIPTS, "GC-T01": "needs executor/target fields of a per-stage broker receipt",
|
|
89
|
+
"GC-T02": NEEDS_HOST_TOOL, "GC-T03": NO_EVIDENCE, "GC-T07": NO_EVIDENCE, "GC-T10": NEEDS_FIXTURE, "GC-T11": "needs sealed digests at seal, qualify and promote points",
|
|
90
|
+
"GC-T12": NEEDS_HOST_TOOL, "GC-T13": "needs a second run under an agent environment", "GC-T16": NEEDS_BROKER_RECEIPTS, "GC-T17": "contract conflict with BROKER BR30/item 18; no assertion until reconciled",
|
|
91
|
+
"GC-T18": NEEDS_FIXTURE, "GC-T24": "needs a --changed or --units-file run and its receipt-dir; not part of S0-S9", "GC-I02": NEEDS_BROKER_RECEIPTS,
|
|
92
|
+
"GC-I04": NEEDS_BROKER_RECEIPTS, "GC-I06": NO_EVIDENCE, "GC-I08": NEEDS_FIXTURE, "GC-I11": "needs a `rightkit-gate clippy` run and its receipt",
|
|
93
|
+
"GC-I12": "needs `rustright doctor --json`; not run by this runner (read-only, but an agent hook forbids it here)", "GC-I13": "needs a refusal the gate does not pre-empt (fixture N14) and a SNAPSHOT_LEASE_STATUS query", "GC-I14": NEEDS_FIXTURE,
|
|
94
|
+
"GC-I16": "needs `rustright doctor --json`; not run by this runner", "GC-I17": "needs a live STATUS query", "GC-I19": "needs a live SNAPSHOT_LEASE_STATUS query", "GC-I20": NEEDS_FIXTURE, "GC-I21": NO_EVIDENCE,
|
|
95
|
+
"GC-Q01": NO_EVIDENCE, "GC-Q02": NO_EVIDENCE, "GC-Q03": NO_EVIDENCE, "GC-Q04": NO_EVIDENCE, "GC-Q05": NO_EVIDENCE, "GC-1A-R2": NEEDS_FIXTURE, "GC-1A-R4": "covered by negative N26 when --steps S7 runs",
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
// ---------------------------------------------------------------------------------------------------------------------------------------------
|
|
99
|
+
// Pure assertion helpers. Each returns { ok, problems[] } (or a richer record); `problems` is empty on success.
|
|
100
|
+
// ---------------------------------------------------------------------------------------------------------------------------------------------
|
|
101
|
+
|
|
102
|
+
/** Unknown or missing keys of `obj` against `{ required, optional }`; fail closed on both. */
|
|
103
|
+
export function strictKeys(obj, { required = [], optional = [] }, where) {
|
|
104
|
+
if (!isObject(obj)) return [`${where}: not an object`];
|
|
105
|
+
const problems = [];
|
|
106
|
+
for (const k of required) if (!(k in obj)) problems.push(`${where}: missing field "${k}"`);
|
|
107
|
+
const known = new Set([...required, ...optional]);
|
|
108
|
+
for (const k of Object.keys(obj)) if (!known.has(k)) problems.push(`${where}: unknown field "${k}"`);
|
|
109
|
+
return problems;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const ROW_REQUIRED = ["id", "class", "coverage", "status", "key", "reason"];
|
|
113
|
+
const ROW_OPTIONAL = ["code", "timing", "scanElapsedMs", "retryTiming", "batchAttempts", "batchedWith"];
|
|
114
|
+
const COVERAGE_VALUES = new Set(["hit", "ran", "skipped"]);
|
|
115
|
+
|
|
116
|
+
/** GC-A21: the schema of one coverage report (gate-coverage.mjs buildCoverageReport). Fail closed on any unknown field. */
|
|
117
|
+
export function validateCoverage(report) {
|
|
118
|
+
const problems = strictKeys(report, { required: ["schema", "commit", "startedAt", "endedAt", "totals", "scans"], optional: ["cacheDisabled"] }, "coverage");
|
|
119
|
+
if (problems.length && !isObject(report)) return { ok: false, problems };
|
|
120
|
+
if (report.schema !== COVERAGE_SCHEMA) problems.push(`coverage.schema is ${JSON.stringify(report.schema)}, expected ${COVERAGE_SCHEMA}`);
|
|
121
|
+
if ("cacheDisabled" in report) problems.push(`coverage.cacheDisabled is set (${JSON.stringify(report.cacheDisabled)}): the run bypassed the cache`);
|
|
122
|
+
if (!Array.isArray(report.scans)) { problems.push("coverage.scans is not an array"); return { ok: false, problems }; }
|
|
123
|
+
problems.push(...strictKeys(report.totals, { required: ["planned", "hit", "ran", "skipped"] }, "coverage.totals"));
|
|
124
|
+
const count = { hit: 0, ran: 0, skipped: 0 };
|
|
125
|
+
const seen = new Set();
|
|
126
|
+
for (const [i, row] of report.scans.entries()) {
|
|
127
|
+
const where = `coverage.scans[${i}]${isObject(row) && typeof row.id === "string" ? ` (${row.id})` : ""}`;
|
|
128
|
+
const bad = strictKeys(row, { required: ROW_REQUIRED, optional: ROW_OPTIONAL }, where);
|
|
129
|
+
problems.push(...bad);
|
|
130
|
+
if (!isObject(row)) continue;
|
|
131
|
+
if (typeof row.id !== "string" || !row.id) problems.push(`${where}: id is not a non-empty string`);
|
|
132
|
+
else if (seen.has(row.id)) problems.push(`${where}: duplicate scan id`);
|
|
133
|
+
else seen.add(row.id);
|
|
134
|
+
if (!COVERAGE_VALUES.has(row.coverage)) { problems.push(`${where}: coverage ${JSON.stringify(row.coverage)} is not hit|ran|skipped`); continue; }
|
|
135
|
+
count[row.coverage] += 1;
|
|
136
|
+
if (typeof row.status !== "string" || !row.status) problems.push(`${where}: status is not a non-empty string`);
|
|
137
|
+
if (typeof row.reason !== "string" || !row.reason) problems.push(`${where}: reason is not a non-empty string`);
|
|
138
|
+
if (!(row.key === null || (typeof row.key === "string" && row.key))) problems.push(`${where}: key is neither null nor a string`);
|
|
139
|
+
if (row.coverage === "hit" && row.status !== "pass") problems.push(`${where}: a hit row has status ${JSON.stringify(row.status)}, expected pass`);
|
|
140
|
+
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
|
+
}
|
|
142
|
+
if (isObject(report.totals)) {
|
|
143
|
+
if (report.totals.planned !== report.scans.length) problems.push(`coverage.totals.planned ${report.totals.planned} != ${report.scans.length} rows`);
|
|
144
|
+
for (const k of ["hit", "ran", "skipped"]) if (report.totals[k] !== count[k]) problems.push(`coverage.totals.${k} ${report.totals[k]} != ${count[k]} rows`);
|
|
145
|
+
if (report.totals.hit + report.totals.ran + report.totals.skipped !== report.totals.planned) problems.push("coverage.totals: hit+ran+skipped != planned");
|
|
146
|
+
}
|
|
147
|
+
return { ok: problems.length === 0, problems };
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Merges the reports of one run (a stage may write one per pass) into a map id -> row. A row that was really answered (hit or ran) wins over a
|
|
152
|
+
* "not-in-pass" skip of the same scan in another pass; two real answers for one id keep the later one.
|
|
153
|
+
*/
|
|
154
|
+
export function mergeCoverage(reports) {
|
|
155
|
+
const rows = new Map();
|
|
156
|
+
const notInPass = (r) => r.coverage === "skipped" && r.status === "not-in-pass";
|
|
157
|
+
for (const report of reports) for (const row of report.scans) {
|
|
158
|
+
const prev = rows.get(row.id);
|
|
159
|
+
if (!prev || notInPass(prev) || !notInPass(row)) rows.set(row.id, row);
|
|
160
|
+
}
|
|
161
|
+
return rows;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** Rows of a pass that carry no answer: skipped for any reason except "class not part of this pass". They are never counted as a pass. */
|
|
165
|
+
export function skippedRows(rows) {
|
|
166
|
+
return [...rows.values()].filter((r) => r.coverage === "skipped" && r.status !== "not-in-pass");
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** GC-A21: every non-JSON log line carries a UTC stamp; JSON and the one `verdict deterministic` marker line are exempt. */
|
|
170
|
+
const UTC_STAMP = /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?Z /;
|
|
171
|
+
export function checkUtcStamps(text) {
|
|
172
|
+
const problems = [];
|
|
173
|
+
const lines = String(text).split(/\r?\n/);
|
|
174
|
+
let checked = 0;
|
|
175
|
+
for (const [i, line] of lines.entries()) {
|
|
176
|
+
if (!line.trim()) continue;
|
|
177
|
+
if (/^rightkit-gate: verdict deterministic/.test(line)) continue;
|
|
178
|
+
if (/^\s*[{}\[\]"]/.test(line)) continue; // pretty-printed JSON body
|
|
179
|
+
checked += 1;
|
|
180
|
+
if (!UTC_STAMP.test(line)) problems.push(`log line ${i + 1} has no UTC stamp: ${line.slice(0, 120)}`);
|
|
181
|
+
}
|
|
182
|
+
if (checked === 0) problems.push("the log has no lines to check");
|
|
183
|
+
return { ok: problems.length === 0, problems, checked };
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** `[stage] passed in N.Ns` and `failed in` lines of a log: [{ stage, ok, seconds }]. */
|
|
187
|
+
export function stageTimings(text) {
|
|
188
|
+
const out = [];
|
|
189
|
+
for (const m of String(text).matchAll(/\[([a-z:]+)\] (passed|failed) in (\d+(?:\.\d+)?)s/g)) out.push({ stage: m[1], ok: m[2] === "passed", seconds: Number(m[3]) });
|
|
190
|
+
return out;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** Coverage report paths a log names: "coverage report <file>: N planned scan(s), ...". */
|
|
194
|
+
export function coveragePaths(text) {
|
|
195
|
+
return [...String(text).matchAll(/coverage report (.+?): \d+ planned scan/g)].map((m) => m[1]);
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** The reclaim line of a gate: "build ownership held <handle> (reclaimed from <from>: <proofs>)". null when the run reclaimed nothing. */
|
|
199
|
+
export function reclaimLine(text) {
|
|
200
|
+
const m = /build ownership (held|joined) (\S+) \(reclaimed from (.+?): (.*)\)\s*$/m.exec(String(text));
|
|
201
|
+
return m ? { mode: m[1], handle: m[2], from: m[3].trim(), proofs: m[4] } : null;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
const STAGE_FIELDS = ["ok", "at", "ruleTier", "direct", "qualifyOwed", "outputs", "snapshot", "ownership", "platform", "sealed", "manifestSha256", "voided", "track", "qaReceiptDigest", "tier"];
|
|
205
|
+
const BINDING_FIELDS = ["tree", "locks", "gate", "toolchain", "executor"];
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* GC-A04, GC-I05 (door half), GC-A05: the door receipt `--receipt-out` writes. `expectedTree` is `git rev-parse <commit>^{tree}`. Fail closed on unknown
|
|
209
|
+
* fields; `verdict` and `refreshed` must be absent (the broker never writes them into a gate receipt).
|
|
210
|
+
*/
|
|
211
|
+
export function validateDoorReceipt(receipt, { commit, expectedTree, stages = [] }) {
|
|
212
|
+
const problems = strictKeys(receipt, { required: ["schema", "commit", "app", "binding", "stages"], optional: ["brokerException"] }, "receipt");
|
|
213
|
+
if (!isObject(receipt)) return { ok: false, problems };
|
|
214
|
+
if (receipt.schema !== RECEIPT_SCHEMA) problems.push(`receipt.schema is ${JSON.stringify(receipt.schema)}, expected ${RECEIPT_SCHEMA}`);
|
|
215
|
+
if (receipt.commit !== commit) problems.push(`receipt.commit ${receipt.commit} != ${commit}`);
|
|
216
|
+
if ("brokerException" in receipt) problems.push("receipt.brokerException is set: the run was built outside the broker");
|
|
217
|
+
for (const banned of ["verdict", "refreshed"]) if (banned in receipt) problems.push(`receipt carries "${banned}" (refused by the gate)`);
|
|
218
|
+
problems.push(...strictKeys(receipt.binding, { required: BINDING_FIELDS }, "receipt.binding"));
|
|
219
|
+
if (isObject(receipt.binding)) {
|
|
220
|
+
if (receipt.binding.tree !== expectedTree) problems.push(`receipt.binding.tree ${receipt.binding.tree} != ${expectedTree} (commit^{tree})`);
|
|
221
|
+
if (!isSha(receipt.binding.gate)) problems.push("receipt.binding.gate is not a sha256");
|
|
222
|
+
}
|
|
223
|
+
if (!isObject(receipt.stages)) { problems.push("receipt.stages is not an object"); return { ok: false, problems }; }
|
|
224
|
+
for (const stage of stages) {
|
|
225
|
+
const s = receipt.stages[stage];
|
|
226
|
+
const where = `receipt.stages.${stage}`;
|
|
227
|
+
if (!isObject(s)) { problems.push(`${where}: missing`); continue; }
|
|
228
|
+
problems.push(...strictKeys(s, { required: ["ok", "at"], optional: STAGE_FIELDS.slice(2) }, where));
|
|
229
|
+
if (s.ok !== true) problems.push(`${where}.ok is ${JSON.stringify(s.ok)}`);
|
|
230
|
+
if ("voided" in s) problems.push(`${where}.voided is ${JSON.stringify(s.voided)}`);
|
|
231
|
+
if (!Number.isFinite(Date.parse(s.at))) problems.push(`${where}.at is not a timestamp`);
|
|
232
|
+
if (stage !== "check" && !isObject(s.snapshot)) problems.push(`${where}.snapshot is missing`);
|
|
233
|
+
if (isObject(s.snapshot)) {
|
|
234
|
+
if (s.snapshot.tree !== expectedTree) problems.push(`${where}.snapshot.tree ${s.snapshot.tree} != ${expectedTree}`);
|
|
235
|
+
if (s.snapshot.intactAfter !== true) problems.push(`${where}.snapshot.intactAfter is ${JSON.stringify(s.snapshot.intactAfter)} (the snapshot must still be exactly the commit's bytes at stage exit)`);
|
|
236
|
+
if (typeof s.snapshot.path !== "string" || !s.snapshot.path) problems.push(`${where}.snapshot.path is missing`);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
return { ok: problems.length === 0, problems };
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/**
|
|
243
|
+
* Whether the compile of a run really ran in that run. A recorded compile that "stands" is reused (`[compile] already passed ...`; the contract's E7
|
|
244
|
+
* says no redundant compile is required, and the receipt keeps the OLD stage `at`), so only a run whose log has `[compile] passed in` and no
|
|
245
|
+
* `already passed` line for the compile proves anything about ordering or about what a compile reads.
|
|
246
|
+
*/
|
|
247
|
+
export function compileRanFresh(log) {
|
|
248
|
+
const t = String(log ?? "");
|
|
249
|
+
return /\[compile\] passed in/.test(t) && !/\[compile\] already passed/.test(t);
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* GC-T05: Class A (stage check) is finished before the compile stage starts. With `log` (the run's own log) the proof is: the compile really ran in
|
|
254
|
+
* this run, the `[check] passed in` line's UTC stamp is not later than the receipt's compile `at` (the moment the compile stage began), and the check
|
|
255
|
+
* stage is ok. A reused compile is returned as `{ ok: false, skipped: true }`: nothing about ordering can be read from another run's `at`.
|
|
256
|
+
* Without `log` only the receipt timestamps are compared (kept for callers that hold no log).
|
|
257
|
+
*/
|
|
258
|
+
export function classABeforeCompile(receipt, log = null) {
|
|
259
|
+
const check = Date.parse(receipt?.stages?.check?.at);
|
|
260
|
+
const compile = Date.parse(receipt?.stages?.compile?.at);
|
|
261
|
+
if (!Number.isFinite(check) || !Number.isFinite(compile)) return { ok: false, problems: ["receipt.stages.check.at and receipt.stages.compile.at are both needed"] };
|
|
262
|
+
if (receipt.stages.check.ok !== true) return { ok: false, problems: [`receipt.stages.check.ok is ${JSON.stringify(receipt.stages.check.ok)}`] };
|
|
263
|
+
if (log === null) return check <= compile ? { ok: true, problems: [] } : { ok: false, problems: [`check at ${receipt.stages.check.at} is after compile at ${receipt.stages.compile.at}`] };
|
|
264
|
+
if (!compileRanFresh(log)) return { ok: false, skipped: true, problems: ["the compile was reused from an earlier run (`[compile] already passed`); its recorded `at` is not this run's, so no ordering can be read"] };
|
|
265
|
+
const m = /^(\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?Z) rightkit-gate: \[check\] passed in/m.exec(String(log));
|
|
266
|
+
if (!m) return { ok: false, problems: ["the log has no stamped `[check] passed in` line"] };
|
|
267
|
+
const checkEnd = Date.parse(m[1]);
|
|
268
|
+
return checkEnd <= compile ? { ok: true, problems: [] } : { ok: false, problems: [`Class A ended at ${m[1]}, after the compile stage began at ${receipt.stages.compile.at}`] };
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/** GC-A15, GC-A07: the output dirs a receipt records (stage outputs.dirs) are one set across stages, and none is a debug dir. */
|
|
272
|
+
export function outputDirsProblems(receipt) {
|
|
273
|
+
const problems = [];
|
|
274
|
+
const sets = [];
|
|
275
|
+
for (const [stage, s] of Object.entries(receipt?.stages ?? {})) {
|
|
276
|
+
const dirs = s?.outputs?.dirs;
|
|
277
|
+
if (dirs === undefined) continue;
|
|
278
|
+
if (!Array.isArray(dirs) || dirs.some((d) => typeof d !== "string")) { problems.push(`receipt.stages.${stage}.outputs.dirs is malformed`); continue; }
|
|
279
|
+
sets.push([stage, [...dirs].sort()]);
|
|
280
|
+
if (s.outputs.truncated === true) problems.push(`receipt.stages.${stage}.outputs.truncated is true`);
|
|
281
|
+
for (const d of dirs) if (/(^|[\\/])debug([\\/]|$)/.test(d)) problems.push(`receipt.stages.${stage}.outputs.dirs names a debug directory: ${d}`);
|
|
282
|
+
}
|
|
283
|
+
if (sets.length === 0) problems.push("no stage of the receipt records outputs.dirs");
|
|
284
|
+
for (const [stage, dirs] of sets.slice(1)) if (JSON.stringify(dirs) !== JSON.stringify(sets[0][1])) problems.push(`output dirs of ${stage} differ from ${sets[0][0]}`);
|
|
285
|
+
return { ok: problems.length === 0, problems };
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/**
|
|
289
|
+
* The key GC-I01 names: sha256 of the canonical repository path, first 16 hex digits, over the path as the gate keys it. On Windows that is the
|
|
290
|
+
* verbatim `\\?\` spelling, so this imports the gate's own `keyPath` and `repoKey` (snapshot.mjs) instead of hashing the bare path.
|
|
291
|
+
*/
|
|
292
|
+
export const repositoryKey = (canonicalPath, platform = process.platform) => repoKey(keyPath(canonicalPath, platform));
|
|
293
|
+
|
|
294
|
+
/** GC-A23: the snapshot's `.rightkit-source-identity.json`. `trees` is `{ dir: tree id }` recomputed from git by the caller. */
|
|
295
|
+
export function validateSourceIdentity(identity, { commit, trees }) {
|
|
296
|
+
const problems = strictKeys(identity, { required: ["schema", "commit", "trees"] }, "source-identity");
|
|
297
|
+
if (!isObject(identity)) return { ok: false, problems };
|
|
298
|
+
if (identity.schema !== SOURCE_IDENTITY_SCHEMA) problems.push(`source-identity.schema is ${JSON.stringify(identity.schema)}`);
|
|
299
|
+
if (identity.commit !== commit) problems.push(`source-identity.commit ${identity.commit} != ${commit}`);
|
|
300
|
+
if (!isObject(identity.trees)) return { ok: false, problems: [...problems, "source-identity.trees is not an object"] };
|
|
301
|
+
if (!("" in identity.trees)) problems.push('source-identity.trees has no "" (root) entry');
|
|
302
|
+
for (const [dir, tree] of Object.entries(trees)) if (identity.trees[dir] !== tree) problems.push(`source-identity.trees[${JSON.stringify(dir)}] is ${identity.trees[dir]}, git says ${tree}`);
|
|
303
|
+
for (const dir of Object.keys(identity.trees)) if (!(dir in trees)) problems.push(`source-identity.trees has an unexpected entry ${JSON.stringify(dir)}`);
|
|
304
|
+
return { ok: problems.length === 0, problems };
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/** GC-A22 render: the receipt a `--to render` run stores. `png(name)` returns the PNG bytes of a case (or null). */
|
|
308
|
+
export function validateRenderReceipt(receipt, { commit, png }) {
|
|
309
|
+
const problems = strictKeys(receipt, { required: ["schema", "commit", "tree", "appDir", "package", "bin", "features", "executable", "buildOutputDir", "host", "startedAt", "endedAt", "cases"], optional: ["buildRequestId"] }, "render-receipt");
|
|
310
|
+
if (!isObject(receipt)) return { ok: false, problems };
|
|
311
|
+
if (receipt.schema !== RENDER_RECEIPT_SCHEMA) problems.push(`render-receipt.schema is ${JSON.stringify(receipt.schema)}`);
|
|
312
|
+
if (receipt.commit !== commit) problems.push(`render-receipt.commit ${receipt.commit} != ${commit}`);
|
|
313
|
+
if (!isSha(receipt.executable?.sha256)) problems.push("render-receipt.executable.sha256 is not a sha256");
|
|
314
|
+
if (typeof receipt.executable?.path !== "string" || typeof receipt.buildOutputDir !== "string" || !receipt.executable.path.startsWith(receipt.buildOutputDir)) problems.push("render-receipt.executable.path does not lie inside buildOutputDir");
|
|
315
|
+
if (!Array.isArray(receipt.cases) || receipt.cases.length === 0) { problems.push("render-receipt.cases is empty"); return { ok: false, problems }; }
|
|
316
|
+
for (const c of receipt.cases) {
|
|
317
|
+
const where = `render-receipt.cases[${c?.name}]`;
|
|
318
|
+
problems.push(...strictKeys(c, { required: ["name", "png", "sha256", "bytes", "width", "height"] }, where));
|
|
319
|
+
const bytes = isObject(c) ? png(c.png) : null;
|
|
320
|
+
if (!bytes) { problems.push(`${where}: PNG ${c?.png} cannot be read`); continue; }
|
|
321
|
+
if (!(bytes.length > 24 && bytes.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])))) { problems.push(`${where}: not a PNG (bad magic)`); continue; }
|
|
322
|
+
if (sha256(bytes) !== c.sha256 || bytes.length !== c.bytes) problems.push(`${where}: sha256 or size differs from the receipt`);
|
|
323
|
+
if (bytes.readUInt32BE(16) !== c.width || bytes.readUInt32BE(20) !== c.height) problems.push(`${where}: PNG width/height differ from the receipt`);
|
|
324
|
+
}
|
|
325
|
+
return { ok: problems.length === 0, problems };
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/** GC-I22: vendored vector files equal the sha256 their vectors-source.json pins and RustRight's own bytes; a missing upstream directory fails, it is not skipped. */
|
|
329
|
+
export function vectorsProblems({ source, files, upstream = null, upstreamDir = null }) {
|
|
330
|
+
const problems = strictKeys(source, { required: ["schema", "note", "source", "files"] }, "vectors-source");
|
|
331
|
+
if (!isObject(source?.files)) return { ok: false, problems: [...problems, "vectors-source.files missing"] };
|
|
332
|
+
for (const [name, meta] of Object.entries(source.files)) {
|
|
333
|
+
const bytes = files[name];
|
|
334
|
+
if (!bytes) { problems.push(`${name}: pinned but not vendored`); continue; }
|
|
335
|
+
if (sha256(bytes) !== meta.sha256) problems.push(`${name}: vendored sha256 ${sha256(bytes).slice(0, 12)} != pinned ${String(meta.sha256).slice(0, 12)}`);
|
|
336
|
+
if (!upstream) continue;
|
|
337
|
+
if (!upstream[name]) problems.push(`${name}: RustRight's docs/contracts has no copy to compare with`);
|
|
338
|
+
else if (sha256(upstream[name]) !== sha256(bytes)) problems.push(`${name}: differs from RustRight's docs/contracts copy`);
|
|
339
|
+
}
|
|
340
|
+
if (!upstream) problems.push(`RustRight's docs/contracts${upstreamDir ? ` (${upstreamDir})` : ""} was not found: the vendored vectors cannot be compared with their source`);
|
|
341
|
+
for (const name of Object.keys(files)) if (name !== "vectors-source.json" && !(name in source.files)) problems.push(`${name}: vendored but not pinned`);
|
|
342
|
+
return { ok: problems.length === 0, problems };
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/** GC-I18 (static half): the digest the gate pins is the installed runtime's. */
|
|
346
|
+
export function brokerDigestProblems({ manifest, pins }) {
|
|
347
|
+
const problems = [];
|
|
348
|
+
if (!isObject(manifest) || !isSha(manifest.brokerDigest)) problems.push("runtime manifest has no brokerDigest sha256");
|
|
349
|
+
if (!isObject(pins) || !isSha(pins.brokerDigest)) problems.push("broker pins record has no brokerDigest sha256");
|
|
350
|
+
if (!problems.length && manifest.brokerDigest !== pins.brokerDigest) problems.push(`pins brokerDigest ${pins.brokerDigest.slice(0, 12)} != runtime manifest brokerDigest ${manifest.brokerDigest.slice(0, 12)}`);
|
|
351
|
+
return { ok: problems.length === 0, problems };
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
const WARM_UNCACHED_CLASS_A = /^(pnpm-lockfile|advisory-exceptions)(:|$)/;
|
|
355
|
+
|
|
356
|
+
/**
|
|
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 that is not an uncached family answered `hit` (a `ran` there is a failure, a skipped row is a failure);
|
|
359
|
+
* - the two uncached families (pnpm-lockfile, advisory-exceptions) ran, never hit;
|
|
360
|
+
* - the key of every row equals the first run's key byte for byte.
|
|
361
|
+
*/
|
|
362
|
+
export function assertWarmRerun(prev, next) {
|
|
363
|
+
const problems = [];
|
|
364
|
+
let hits = 0;
|
|
365
|
+
for (const [id, row] of next) {
|
|
366
|
+
if (row.coverage === "skipped" && row.status === "not-in-pass") continue;
|
|
367
|
+
const uncached = row.class === "A" && WARM_UNCACHED_CLASS_A.test(id);
|
|
368
|
+
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
|
+
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
|
+
if (row.class === "A" && row.coverage === "hit") hits += 1;
|
|
372
|
+
const before = prev.get(id);
|
|
373
|
+
if (row.class === "A" && before && before.key !== row.key) problems.push(`${id}: key changed between runs on one commit (${before.key} -> ${row.key})`);
|
|
374
|
+
if (row.class === "A" && !before) problems.push(`${id}: not present in the first run`);
|
|
375
|
+
}
|
|
376
|
+
if (hits === 0) problems.push("no Class A row hit: the rerun proves nothing about warmth");
|
|
377
|
+
return { ok: problems.length === 0, problems, hits };
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
/**
|
|
381
|
+
* S3 (GC-A24): one `.rs` edit. Exactly one `rustfmt` row `ran` (that file's), plus any per-file rows that read it (secret-scan, licence); every other
|
|
382
|
+
* Class A key equals the previous run. `perFile` is a RegExp of the row ids allowed to run besides rustfmt.
|
|
383
|
+
*/
|
|
384
|
+
export function assertOneFileEdit(prev, next, { perFile = /^(secret-scan|licen[cs]e)/ } = {}) {
|
|
385
|
+
const problems = [];
|
|
386
|
+
const ranA = [...next.values()].filter((r) => r.class === "A" && r.coverage === "ran" && !WARM_UNCACHED_CLASS_A.test(r.id));
|
|
387
|
+
const rustfmt = ranA.filter((r) => r.id.startsWith("rustfmt"));
|
|
388
|
+
if (rustfmt.length !== 1) problems.push(`${rustfmt.length} rustfmt rows ran, expected exactly 1 (${rustfmt.map((r) => r.id).join(", ")})`);
|
|
389
|
+
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`);
|
|
390
|
+
// A row that ran because its input changed has a new key; a ran row that kept its key is an unexplained miss (and a row without a key cannot show a change).
|
|
391
|
+
for (const r of ranA) {
|
|
392
|
+
const before = prev.get(r.id);
|
|
393
|
+
if (!before) problems.push(`${r.id}: ran but is absent from the previous run, so no changed key can be shown`);
|
|
394
|
+
else if (r.key === null || before.key === r.key) problems.push(`${r.id}: ran with ${r.key === null ? "no cache key" : "the same key as the previous run"}: an edit changes the key of every row that reads it`);
|
|
395
|
+
}
|
|
396
|
+
for (const [id, row] of next) {
|
|
397
|
+
if (row.class !== "A" || row.coverage === "skipped") continue;
|
|
398
|
+
const before = prev.get(id);
|
|
399
|
+
if (row.coverage === "hit" && before && before.key !== row.key) problems.push(`${id}: key changed but the row answered hit`);
|
|
400
|
+
if (row.coverage === "hit" && !before) problems.push(`${id}: hit but absent from the previous run`);
|
|
401
|
+
}
|
|
402
|
+
return { ok: problems.length === 0, problems, ran: ranA.map((r) => r.id) };
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
const metadataLabel = (id) => (id === "cargo-metadata" ? "." : id.startsWith("cargo-metadata:") ? id.slice("cargo-metadata:".length) : null);
|
|
406
|
+
const packageListUnit = (id) => (id.startsWith("cargo-package-list:") ? id.slice("cargo-package-list:".length) : id === "cargo-package-list" ? "" : null);
|
|
407
|
+
|
|
408
|
+
/**
|
|
409
|
+
* S4 (GC-A19): a manifest edit reruns `cargo-metadata` and `cargo-package-list` for the edited manifest's workspace ONLY. `workspace` is that
|
|
410
|
+
* workspace's directory ("." for the root), `workspaces` every workspace directory of the commit and `crates` `{ workspaceDir: [crate names] }`.
|
|
411
|
+
* The workspace's own `cargo-metadata` row must have run with a new key; any `cargo-metadata` or `cargo-package-list` row of another workspace that
|
|
412
|
+
* ran, and any such row that cannot be attributed to a workspace, fails.
|
|
413
|
+
*/
|
|
414
|
+
export function assertManifestEdit(prev, next, { workspace, workspaces = [], crates = {} } = {}) {
|
|
415
|
+
const problems = [];
|
|
416
|
+
if (typeof workspace !== "string") return { ok: false, problems: ["the edited manifest's workspace is not known"], ran: [] };
|
|
417
|
+
const wsOfLabel = (label) => {
|
|
418
|
+
if (workspaces.includes(label)) return label;
|
|
419
|
+
const byCrate = workspaces.find((w) => w === `crates/${label}`);
|
|
420
|
+
return byCrate ?? null;
|
|
421
|
+
};
|
|
422
|
+
const crateWs = (unit) => {
|
|
423
|
+
const name = unit.includes(":") ? unit.slice(unit.lastIndexOf(":") + 1) : unit;
|
|
424
|
+
const owners = Object.entries(crates).filter(([, names]) => names.includes(name)).map(([w]) => w);
|
|
425
|
+
return owners.length === 1 ? owners[0] : null;
|
|
426
|
+
};
|
|
427
|
+
const ran = [];
|
|
428
|
+
let ownMetadata = false;
|
|
429
|
+
for (const row of next.values()) {
|
|
430
|
+
const label = metadataLabel(row.id);
|
|
431
|
+
const unit = packageListUnit(row.id);
|
|
432
|
+
if (label === null && unit === null) continue;
|
|
433
|
+
const ws = label !== null ? (workspaces.length === 0 && label === "." ? "." : wsOfLabel(label)) : crateWs(unit);
|
|
434
|
+
const own = ws === workspace;
|
|
435
|
+
if (row.coverage === "skipped" && row.status !== "not-in-pass") problems.push(`${row.id}: skipped (${row.reason}); a skipped row is never a pass`);
|
|
436
|
+
if (row.coverage === "ran") {
|
|
437
|
+
ran.push(row.id);
|
|
438
|
+
if (ws === null) problems.push(`${row.id}: ran but belongs to no known workspace`);
|
|
439
|
+
else if (!own) problems.push(`${row.id}: ran for workspace ${JSON.stringify(ws)}, which the edit (workspace ${JSON.stringify(workspace)}) does not touch`);
|
|
440
|
+
else {
|
|
441
|
+
const before = prev?.get(row.id);
|
|
442
|
+
if (!before || before.key === row.key) problems.push(`${row.id}: ran without a changed key (${before ? "same key as before" : "absent before"})`);
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
if (own && label !== null) {
|
|
446
|
+
ownMetadata = true;
|
|
447
|
+
if (row.coverage !== "ran") problems.push(`${row.id}: the edited workspace's cargo-metadata answered ${row.coverage}, expected ran`);
|
|
448
|
+
}
|
|
449
|
+
if (own && unit !== null && row.coverage === "hit") problems.push(`${row.id}: a cargo-package-list row of the edited workspace answered hit`);
|
|
450
|
+
}
|
|
451
|
+
if (!ownMetadata) problems.push(`no cargo-metadata row for workspace ${JSON.stringify(workspace)} exists in the run`);
|
|
452
|
+
return { ok: problems.length === 0, problems, ran };
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
/**
|
|
456
|
+
* A negative case: exit non-zero, every named signal in the output, and "zero later work": no stage after the failing one passed. `signals` are
|
|
457
|
+
* the exact rule codes the gate emits (RegExp or string; every one must match). `expectRows` name coverage rows the gate must have reported for the
|
|
458
|
+
* scan that refused: `{ id: string|RegExp, coverage, status }`; they are read from `rows` (the run's merged coverage report, id -> row), and no report
|
|
459
|
+
* is a failure. `laterStages` are stage names that must not have `passed in` lines. A bare word in the log is never a signal.
|
|
460
|
+
*/
|
|
461
|
+
export function assertNegative({ exit, text, signals = [], laterStages = [], receipt = null, rows = null, expectRows = [] }) {
|
|
462
|
+
const problems = [];
|
|
463
|
+
if (exit === 0) problems.push("exit 0: the gate accepted a broken input");
|
|
464
|
+
if (exit === null) problems.push("the gate did not exit (killed or timed out)");
|
|
465
|
+
for (const s of signals) if (!(s instanceof RegExp ? s.test(text) : text.includes(s))) problems.push(`output does not name ${s}`);
|
|
466
|
+
if (expectRows.length) {
|
|
467
|
+
if (!rows || rows.size === 0) problems.push("no coverage report was read, so the scan that refused cannot be named");
|
|
468
|
+
else for (const want of expectRows) {
|
|
469
|
+
const hit = [...rows.values()].find((r) => (want.id instanceof RegExp ? want.id.test(r.id) : r.id === want.id) && r.coverage === want.coverage && r.status === want.status);
|
|
470
|
+
if (!hit) problems.push(`no coverage row ${want.id} ${want.coverage}/${want.status}: ${[...rows.values()].filter((r) => (want.id instanceof RegExp ? want.id.test(r.id) : r.id === want.id)).map((r) => `${r.id} ${r.coverage}/${r.status}`).join(", ") || "none with that id"}`);
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
const passed = new Set(stageTimings(text).filter((t) => t.ok).map((t) => t.stage));
|
|
474
|
+
for (const stage of laterStages) {
|
|
475
|
+
if (passed.has(stage)) problems.push(`stage ${stage} passed after the failure`);
|
|
476
|
+
if (receipt?.stages?.[stage]?.ok === true) problems.push(`receipt.stages.${stage}.ok is true after the failure`);
|
|
477
|
+
}
|
|
478
|
+
return { ok: problems.length === 0, problems };
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
/** The release-tier app-check rules (app-check.mjs: tierOf) and the baseline-growth finding; each prints `FAIL <rule> (<gap>): ...` / `UNAPPROVED baseline entry`. */
|
|
482
|
+
export const RELEASE_TIER_RULES = Object.freeze(["mandatory-foundation", "ownership-exceptions", "trust-policy-exclude", "commit-citations"]);
|
|
483
|
+
|
|
484
|
+
/** S1: a refused `--to qualify` must name a release-tier rule by the exact line the check prints, and record no ok qualify stage. */
|
|
485
|
+
export function qualifyRefusal({ exit, text, receipt = null }) {
|
|
486
|
+
const problems = [];
|
|
487
|
+
if (exit === 0) problems.push("exit 0: not a refusal");
|
|
488
|
+
if (exit === null) problems.push("the gate did not exit (killed or timed out)");
|
|
489
|
+
const named = RELEASE_TIER_RULES.filter((id) => new RegExp(`\\bFAIL ${id} \\(`).test(text));
|
|
490
|
+
if (/\bUNAPPROVED baseline entry\b/.test(text)) named.push("UNAPPROVED");
|
|
491
|
+
if (!named.length) problems.push("the refusal names no release-tier rule (expected a `FAIL <rule> (<gap>)` line for one of " + `${RELEASE_TIER_RULES.join(", ")}` + " or `UNAPPROVED baseline entry`)");
|
|
492
|
+
if (receipt?.stages?.qualify?.ok === true) problems.push("the receipt records qualify ok after a refusal");
|
|
493
|
+
return { ok: problems.length === 0, problems, named };
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
const SIGNUM = Object.freeze({ SIGINT: 2, SIGKILL: 9, SIGTERM: 15 });
|
|
497
|
+
/** Whether a stopped gate was stopped by `killSignal`: the signal itself, or 128+n (a shell wrapper); on Windows the code `taskkill /F` gives (1). */
|
|
498
|
+
export function exitedBySignal({ signal, exit, killSignal, platform = process.platform }) {
|
|
499
|
+
if (platform === "win32") return exit === 1 && (signal === null || signal === undefined);
|
|
500
|
+
if (signal) return signal === killSignal;
|
|
501
|
+
return exit !== null && exit === 128 + (SIGNUM[killSignal] ?? -1000);
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
/**
|
|
505
|
+
* Kill-and-recover (K01, SIGKILL; also the SIGINT variant): `before` is the owner record read right after the kill (or null when none), `dry` the
|
|
506
|
+
* ownership-recover.mjs dry-run `{ exit, text }`, `next` the following gate run `{ exit, text }`, `after` the owner record read after it (null: removed).
|
|
507
|
+
* Pass when the next run starts without any operator step and either reclaims (log names the reclaim, handle replaced) or finds nothing held
|
|
508
|
+
* (SIGINT released it). A record that survives a SIGKILL must be explained by the dry run and reclaimed by the next run.
|
|
509
|
+
*/
|
|
510
|
+
export function assertRecovery({ signal, before, dry, next, after, exitedBySignal = true }) {
|
|
511
|
+
const problems = [];
|
|
512
|
+
if (!exitedBySignal) problems.push(`the gate was not stopped by ${signal}`);
|
|
513
|
+
if (signal === "SIGKILL" && !before) problems.push("no owner record stood after SIGKILL: the gate released nothing, so it must have been killed before acquiring; the case proved nothing");
|
|
514
|
+
if (before) {
|
|
515
|
+
if (!isObject(before) || typeof before.handle !== "string" || !Number.isInteger(before.pid)) problems.push("the owner record is malformed (no handle or pid)");
|
|
516
|
+
if (dry?.exit !== 0 || !/recover: recoverable:/.test(dry?.text ?? "")) problems.push(`ownership-recover.mjs dry run did not explain a recoverable record (exit ${dry?.exit}): ${(dry?.text ?? "").split("\n").filter((l) => /recover:/.test(l)).slice(-2).join(" | ").slice(0, 240)}`);
|
|
517
|
+
const claim = reclaimLine(next?.text ?? "");
|
|
518
|
+
if (!claim) problems.push("the next run's log has no 'reclaimed from' line");
|
|
519
|
+
else if (isObject(before) && claim.handle === before.handle) problems.push("the next run holds the dead owner's own handle: the record was not replaced");
|
|
520
|
+
if (isObject(before) && isObject(after) && after.handle === before.handle) problems.push("the owner record still carries the dead handle after the next run");
|
|
521
|
+
}
|
|
522
|
+
if (next?.exit !== 0) problems.push(`the next run exited ${next?.exit}`);
|
|
523
|
+
return { ok: problems.length === 0, problems };
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
/** S9: two git listings taken at different times must be byte equal. */
|
|
527
|
+
export function sameListing(name, a, b) {
|
|
528
|
+
return a === b ? { ok: true, problems: [] } : { ok: false, problems: [`${name} changed: ${JSON.stringify(a).slice(0, 160)} -> ${JSON.stringify(b).slice(0, 160)}`] };
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
/** S9 and GC-A01: the one-worktree rule (`git worktree list --porcelain` has one `worktree ` row). */
|
|
532
|
+
export const worktreeCount = (porcelain) => String(porcelain).split(/\r?\n/).filter((l) => l.startsWith("worktree ")).length;
|
|
533
|
+
|
|
534
|
+
/** GC-A01 and N13: a bypass refusal names the retired option and ran nothing. */
|
|
535
|
+
export function bypassRefused({ exit, text }) {
|
|
536
|
+
const problems = [];
|
|
537
|
+
if (exit === 0 || exit === null) problems.push(`exit ${exit}: the bypass was not refused`);
|
|
538
|
+
if (!/retired/.test(text)) problems.push("the refusal text does not say the option is retired");
|
|
539
|
+
if (/\[(check|compile)\] (passed|failed) in/.test(text)) problems.push("a stage ran under a refused bypass");
|
|
540
|
+
return { ok: problems.length === 0, problems };
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
/** S9: no publish or upload happened (GC-T22 negative): log markers of an upload that completed. */
|
|
544
|
+
export function publicationMarkers(text) {
|
|
545
|
+
return String(text).split(/\r?\n/).filter((l) => /\b(uploaded to|upload complete|published release|gh release create|r2 put)\b/i.test(l)).slice(0, 5);
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
/**
|
|
549
|
+
* GC-A01, GC-T14: every directory of the snapshot root that belongs to this repository (its name starts with the repository key: the snapshot, a
|
|
550
|
+
* leftover `.staging`, any second spelling) must be exactly `<key>`; and no directory that was not there at S0 may have appeared besides it.
|
|
551
|
+
* `before` and `after` are directory-name listings of `<managed root>/snapshots` (`before` null: S0 did not run).
|
|
552
|
+
*/
|
|
553
|
+
export function snapshotDirProblems({ key, before = null, after }) {
|
|
554
|
+
const problems = [];
|
|
555
|
+
const ours = after.filter((n) => n.startsWith(key));
|
|
556
|
+
if (!ours.includes(key)) problems.push(`the snapshot dir ${key} does not exist`);
|
|
557
|
+
for (const n of ours) if (n !== key) problems.push(`a second snapshot dir for the repository: ${n}`);
|
|
558
|
+
if (before) for (const n of after) if (!before.includes(n) && !n.startsWith(key)) problems.push(`a new snapshot dir appeared during the run: ${n}`);
|
|
559
|
+
return { ok: problems.length === 0, problems, dirs: ours };
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
/** GC-T20: no hook of the fixture's hooks directory (`.sample` files excepted) mentions the gate. `files` is `{ name: text }`. */
|
|
563
|
+
export function hookProblems({ files, hooksPath = null }) {
|
|
564
|
+
const problems = [];
|
|
565
|
+
for (const [name, text] of Object.entries(files)) {
|
|
566
|
+
if (name.endsWith(".sample")) continue;
|
|
567
|
+
if (/rightkit-gate|rightkit-host-gate|rightkit_gate|gate\.mjs/i.test(String(text))) problems.push(`hook ${name} runs the gate`);
|
|
568
|
+
}
|
|
569
|
+
return { ok: problems.length === 0, problems };
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
/**
|
|
573
|
+
* S6 (GC-A04, GC-A02, GC-T06): proof, read while the checkout is dirty, that the snapshot of the compile holds the COMMIT's bytes and not the
|
|
574
|
+
* checkout's. `commitBytes` is the edited file as the commit has it, `checkoutBytes` as the dirty checkout has it, `snapshotBytes` as the snapshot
|
|
575
|
+
* has it (null: absent), `untrackedInSnapshot` whether the untracked file reached the snapshot, `identityProblems` the source-identity check of the
|
|
576
|
+
* snapshot against the commit's trees, and `receiptTree`/`expectedTree` the tree the compile bound against `commit^{tree}`.
|
|
577
|
+
*/
|
|
578
|
+
export function dirtyProof({ commitBytes, checkoutBytes, snapshotBytes, untrackedInSnapshot, identityProblems = [], receiptTree, expectedTree }) {
|
|
579
|
+
const problems = [...identityProblems];
|
|
580
|
+
if (!Buffer.isBuffer(commitBytes) || !Buffer.isBuffer(checkoutBytes)) problems.push("the commit's or the checkout's bytes of the edited file are missing");
|
|
581
|
+
else if (commitBytes.equals(checkoutBytes)) problems.push("the checkout file equals the commit's: the checkout was not dirty, so the case proves nothing");
|
|
582
|
+
if (!Buffer.isBuffer(snapshotBytes)) problems.push("the snapshot does not hold the edited file");
|
|
583
|
+
else {
|
|
584
|
+
if (Buffer.isBuffer(commitBytes) && !snapshotBytes.equals(commitBytes)) problems.push("the snapshot's file differs from the commit's bytes");
|
|
585
|
+
if (Buffer.isBuffer(checkoutBytes) && snapshotBytes.equals(checkoutBytes)) problems.push("the snapshot's file carries the dirty checkout's bytes");
|
|
586
|
+
}
|
|
587
|
+
if (untrackedInSnapshot) problems.push("the untracked checkout file reached the snapshot");
|
|
588
|
+
if (receiptTree !== expectedTree) problems.push(`the compile's tree ${receiptTree} != commit^{tree} ${expectedTree}`);
|
|
589
|
+
return { ok: problems.length === 0, problems };
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
/**
|
|
593
|
+
* How to start a gate launcher. A `.cmd`/`.bat` launcher cannot be spawned directly on Windows (Node refuses it): it goes through `cmd.exe /d /s /c`
|
|
594
|
+
* with verbatim arguments. Every argument and the launcher path must be free of cmd metacharacters (`" % ^ & | < > CR LF`); one that is not throws.
|
|
595
|
+
*/
|
|
596
|
+
export function launchSpec(gate, args, { platform = process.platform, comspec = process.env.ComSpec || "cmd.exe" } = {}) {
|
|
597
|
+
if (platform !== "win32" || !/\.(cmd|bat)$/i.test(gate)) return { command: gate, args, options: {} };
|
|
598
|
+
const unsafe = /["%^&|<>\r\n]/;
|
|
599
|
+
for (const a of [gate, ...args]) if (unsafe.test(a)) throw new Error(`argument ${JSON.stringify(a)} is not safe to pass through cmd.exe`);
|
|
600
|
+
const quote = (a) => (a === "" || /\s/.test(a) ? `"${a}"` : a);
|
|
601
|
+
return { command: comspec, args: ["/d", "/s", "/c", `"${[gate, ...args].map(quote).join(" ")}"`], options: { windowsVerbatimArguments: true } };
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
// ---------------------------------------------------------------------------------------------------------------------------------------------
|
|
605
|
+
// The run sequence (criteria.md section 3) and the clauses each step asserts.
|
|
606
|
+
// ---------------------------------------------------------------------------------------------------------------------------------------------
|
|
607
|
+
export const LADDER = Object.freeze(["check", "compile", "test", "render", "dev", "package", "qualify"]);
|
|
608
|
+
/** Stages that install an app on the host; they run only with `--allow-install` (Adrian's approval), never by default. */
|
|
609
|
+
export const INSTALL_STAGES = Object.freeze(["dev", "qualify"]);
|
|
610
|
+
export const ladderStages = ({ allowInstall = false } = {}) => LADDER.filter((s) => allowInstall || !INSTALL_STAGES.includes(s));
|
|
611
|
+
const RECEIPT_STAGES = new Set(["check", "compile", "package", "qualify"]);
|
|
612
|
+
|
|
613
|
+
export const NEGATIVES = Object.freeze([
|
|
614
|
+
{ id: "N01", title: "misformatted .rs", signals: [], expectRows: [{ id: /^rustfmt:/, coverage: "ran", status: "fail" }], later: ["compile"], clauses: ["GC-T05"], build: "misformat-rs" },
|
|
615
|
+
{ id: "N02", title: "secret-shaped string in a tracked file", signals: [], expectRows: [{ id: "secret-scan", coverage: "ran", status: "fail" }], later: ["compile"], clauses: ["GC-T05", "GC-A22-classA"], build: "secret-file" },
|
|
616
|
+
{ id: "N13", title: "--no-cache and RK_GATE_CACHE=0 refused", signals: [], later: ["check"], clauses: ["GC-A01", "GC-T14"], build: "bypass" },
|
|
617
|
+
{ id: "N15", title: "[profile.dev] in a Cargo.toml", signals: [/\[profile-extra\]/, "[profile.dev] is not allowed"], later: ["compile"], clauses: ["GC-A15"], build: "profile-dev" },
|
|
618
|
+
{ id: "N26", title: "extra Cargo workspace not in ci/gate.config.json", signals: [/RK_CARGO_WORKSPACE_LIST_DIFFERS/], later: ["compile"], clauses: ["GC-1A-R4"], build: "extra-workspace" },
|
|
619
|
+
{ id: "N27", title: "--no-broker x with no exception entry", signals: [/RK_BROKER_EXCEPTION_MISSING/], later: ["compile"], clauses: ["GC-1A-R2"], build: "no-broker", args: ["--no-broker", "acceptance-no-such-exception"] },
|
|
620
|
+
]);
|
|
621
|
+
export const NEGATIVES_UNCHECKED = Object.freeze({
|
|
622
|
+
N03: "needs a Cargo.toml/Cargo.lock pair edit the fixture's resolver must agree with", N04: NEEDS_FIXTURE, N05: NEEDS_FIXTURE, N06: NEEDS_FIXTURE, N07: NEEDS_FIXTURE, N08: NEEDS_FIXTURE, N09: NEEDS_FIXTURE,
|
|
623
|
+
N10: "snapshot tamper is a write into the gate's snapshot dir; run by hand under the lead's approval", N11: "covered by S6", N12: "needs a build window (the `slow` crate, F2)", N14: NEEDS_FIXTURE, N16: NEEDS_FIXTURE,
|
|
624
|
+
N17: NEEDS_FIXTURE, N18: "needs a broker endpoint override the runner does not set", N19: NEEDS_FIXTURE, N20: NEEDS_FIXTURE, N21: NEEDS_FIXTURE, N22: NEEDS_FIXTURE, N23: NEEDS_FIXTURE, N24: NEEDS_FIXTURE,
|
|
625
|
+
N25: NEEDS_FIXTURE, N28: NEEDS_FIXTURE, N29: NEEDS_FIXTURE, N30: NEEDS_FIXTURE, N31: NEEDS_FIXTURE, N33: NEEDS_FIXTURE, N34: NEEDS_FIXTURE, N35: NEEDS_FIXTURE, N36: NEEDS_FIXTURE, N37: NEEDS_FIXTURE,
|
|
626
|
+
});
|
|
627
|
+
export const KILLS = Object.freeze([
|
|
628
|
+
{ id: "K01", signal: "SIGKILL", at: "owner record exists (build ownership held) plus --kill-after-ms, during --to compile", clauses: ["GC-T06"] },
|
|
629
|
+
{ id: "K01-int", signal: "SIGINT", at: "same point as K01", clauses: ["GC-T06"] },
|
|
630
|
+
{ 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"] },
|
|
631
|
+
]);
|
|
632
|
+
export const KILLS_UNCHECKED = Object.freeze({
|
|
633
|
+
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
|
+
});
|
|
635
|
+
|
|
636
|
+
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 rows hit with first-run keys; only pnpm-lockfile and advisory-exceptions run" },
|
|
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: "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
|
+
]);
|
|
648
|
+
|
|
649
|
+
/** The plan `--plan` prints (and tests read): steps, runs and the clause mapping, with implemented vs unchecked. */
|
|
650
|
+
export function buildPlan({ steps = STEPS.map((s) => s.id), allowInstall = false } = {}) {
|
|
651
|
+
const chosen = STEPS.filter((s) => steps.includes(s.id));
|
|
652
|
+
const implemented = new Set(Object.keys(CHECKS));
|
|
653
|
+
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
|
+
return { schema: "rightkit.gate-acceptance-plan/1", allowInstall, installStagesSkipped: allowInstall ? [] : [...INSTALL_STAGES], steps: chosen, negativesUnchecked: NEGATIVES_UNCHECKED, killsUnchecked: KILLS_UNCHECKED, clauses };
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
/** The reason a clause that needs `--to dev` / `--to qualify` evidence is unchecked while installs are not approved; null otherwise. */
|
|
658
|
+
export const installReason = (id, allowInstall) => (!allowInstall && INSTALL_CLAUSES.includes(id) ? NEEDS_INSTALL_APPROVAL : null);
|
|
659
|
+
|
|
660
|
+
export function formatPlan(plan) {
|
|
661
|
+
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}`);
|
|
663
|
+
const impl = plan.clauses.filter((c) => c.implemented);
|
|
664
|
+
const un = plan.clauses.filter((c) => !c.implemented);
|
|
665
|
+
out.push("", `clauses: ${plan.clauses.length} total, ${impl.length} asserted, ${un.length} unchecked by design`);
|
|
666
|
+
out.push(`asserted: ${impl.map((c) => `${c.id}(${c.ev})`).join(" ")}`);
|
|
667
|
+
out.push(`unchecked: ${un.map((c) => `${c.id}(${c.ev})`).join(" ")}`);
|
|
668
|
+
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
|
+
out.push(`negatives not built: ${Object.keys(plan.negativesUnchecked).join(" ")}`, `kills not built: ${Object.keys(plan.killsUnchecked).join(" ")}`);
|
|
670
|
+
return out.join("\n");
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
// ---------------------------------------------------------------------------------------------------------------------------------------------
|
|
674
|
+
// Clause assertions. Each CHECKS entry is `(ctx) => { status: "pass"|"fail"|"unchecked", evidence: [..], problems: [..] }` or a list of them. `ctx.runs`
|
|
675
|
+
// holds the runs of the sequence by label; a clause needing a run that is absent is "unchecked". The summary of a clause across checks is: any fail
|
|
676
|
+
// -> fail; else all real checks pass and no blocking "missing" part -> pass; else unchecked.
|
|
677
|
+
// ---------------------------------------------------------------------------------------------------------------------------------------------
|
|
678
|
+
const verdict = (res, evidence) => ({ status: res.ok ? "pass" : "fail", evidence, problems: res.problems });
|
|
679
|
+
const unchecked = (why) => ({ status: "unchecked", evidence: [], problems: [why] });
|
|
680
|
+
/** An unchecked part that keeps the clause from passing although other parts passed. */
|
|
681
|
+
const missing = (why) => ({ status: "unchecked", blocksPass: true, evidence: [], problems: [why] });
|
|
682
|
+
const needRun = (ctx, label) => ctx.runs[label] ?? null;
|
|
683
|
+
const expectedFailure = (r) => Boolean(r.negative) || r.refusal !== undefined;
|
|
684
|
+
const firstRows = (ctx, ...labels) => { for (const l of labels) if (ctx.runs[l]?.rows) return ctx.runs[l]; return null; };
|
|
685
|
+
|
|
686
|
+
/** GC-I15: the broker process (pid and start) is the same at S0 and S9; the gate launched none. */
|
|
687
|
+
export function brokerUnchanged(a, b) {
|
|
688
|
+
if (!a || !b) return { ok: false, problems: ["the broker process was not established at S0 or at S9"] };
|
|
689
|
+
return a.pid === b.pid && a.startedMs === b.startedMs ? { ok: true, problems: [] } : { ok: false, problems: [`broker pid/start changed: ${JSON.stringify(a)} -> ${JSON.stringify(b)}`] };
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
/** GC-T19: the check stage's recorded rule tier is the tier the stage owes (compile below qualify, release at qualify). */
|
|
693
|
+
export function ruleTierProblems(receipt, stage) {
|
|
694
|
+
const tier = receipt?.stages?.check?.ruleTier;
|
|
695
|
+
const want = stage === "qualify" || stage === "release" ? "release" : "compile";
|
|
696
|
+
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
|
+
}
|
|
698
|
+
|
|
699
|
+
export const CHECKS = {
|
|
700
|
+
"GC-A21": (ctx) => {
|
|
701
|
+
const out = [];
|
|
702
|
+
for (const [label, run] of Object.entries(ctx.runs)) {
|
|
703
|
+
if (!run.ladder) continue;
|
|
704
|
+
if (run.args.includes("--route")) continue;
|
|
705
|
+
if (run.exit !== 0 && !expectedFailure(run)) out.push({ label, status: "fail", evidence: [run.logPath], problems: [`the run exited ${run.exit}${run.timedOut ? " (timed out)" : ""}`] });
|
|
706
|
+
const stamps = checkUtcStamps(run.log);
|
|
707
|
+
out.push({ label, ...verdict(stamps, [`${run.logPath} (every line)`]) });
|
|
708
|
+
if (run.exit === 0 && ["check", "compile", "package", "qualify"].includes(run.stage)) {
|
|
709
|
+
// A reused stage prints `[stage] already passed ...` instead of a timing line; only a stage that ran owes `passed in`.
|
|
710
|
+
const reused = new RegExp(`\\[${run.stage}\\] already passed`).test(run.log);
|
|
711
|
+
const timings = stageTimings(run.log).filter((t) => t.stage === run.stage);
|
|
712
|
+
if (!reused || timings.length) out.push({ label, ...verdict({ ok: timings.length > 0 && timings.every((t) => t.ok), problems: timings.length ? [] : [`no "[${run.stage}] passed in" line`] }, [`${run.logPath} ([${run.stage}] passed in)`]) });
|
|
713
|
+
}
|
|
714
|
+
if (run.coverageProblems.length) out.push({ label, status: "fail", evidence: run.coveragePaths, problems: run.coverageProblems });
|
|
715
|
+
else if (run.coveragePaths.length) out.push({ label, status: "pass", evidence: run.coveragePaths, problems: [] });
|
|
716
|
+
else if (run.exit === 0 && run.stage !== "render") out.push({ label, status: "fail", evidence: [run.logPath], problems: ["the log names no coverage report"] });
|
|
717
|
+
}
|
|
718
|
+
return out.length ? out : unchecked("no ladder run executed");
|
|
719
|
+
},
|
|
720
|
+
"GC-A04": (ctx) => {
|
|
721
|
+
const out = [];
|
|
722
|
+
for (const [label, run] of Object.entries(ctx.runs)) {
|
|
723
|
+
if (!run.receiptPath || expectedFailure(run)) continue;
|
|
724
|
+
if (run.exit !== 0) { out.push({ label, status: "fail", evidence: [run.logPath], problems: [`the run exited ${run.exit}${run.timedOut ? " (timed out)" : ""}: no receipt can stand for it`] }); continue; }
|
|
725
|
+
if (!run.receipt) { out.push({ label, status: "fail", evidence: [run.receiptPath], problems: ["the run exited 0 but wrote no readable receipt (--receipt-out)"] }); continue; }
|
|
726
|
+
const stages = LADDER.filter((s) => RECEIPT_STAGES.has(s) && run.stageIndex >= LADDER.indexOf(s)).filter((s) => run.receipt.stages?.[s]);
|
|
727
|
+
out.push({ label, ...verdict(validateDoorReceipt(run.receipt, { commit: run.commit, expectedTree: run.tree, stages }), [run.receiptPath]) });
|
|
728
|
+
}
|
|
729
|
+
if (ctx.s6) out.push(ctx.s6.fresh && ctx.s6.proof ? { label: "S6", ...verdict(ctx.s6.proof, ["the S6 snapshot file vs the commit's blob, the checkout's dirty file and its source identity"]) } : unchecked(`S6: ${ctx.s6.why ?? "the dirty-checkout proof was not made"}`));
|
|
730
|
+
return out.length ? out : unchecked("no run wrote a receipt (--receipt-out)");
|
|
731
|
+
},
|
|
732
|
+
"GC-T05": (ctx) => {
|
|
733
|
+
const out = []; let reused = 0;
|
|
734
|
+
for (const [label, run] of Object.entries(ctx.runs)) {
|
|
735
|
+
if (!run.receipt || run.exit !== 0 || !run.receipt.stages?.compile || expectedFailure(run)) continue;
|
|
736
|
+
const r = classABeforeCompile(run.receipt, run.log);
|
|
737
|
+
if (r.skipped) { reused += 1; continue; }
|
|
738
|
+
out.push({ label, ...verdict(r, [`${run.receiptPath} (stages.compile.at), ${run.logPath} ([check] passed in stamp)`]) });
|
|
739
|
+
}
|
|
740
|
+
for (const [label, run] of Object.entries(ctx.runs)) if (run.negative && ["N01", "N02"].includes(run.negative)) out.push({ label, ...verdict(run.negativeResult, [run.logPath]) });
|
|
741
|
+
return out.length ? out : unchecked(`no compile ran in a run of its own${reused ? ` (${reused} run(s) reused a recorded compile) ` : ""} and no Class A negative ran`);
|
|
742
|
+
},
|
|
743
|
+
"GC-A15": (ctx) => {
|
|
744
|
+
const run = [...Object.values(ctx.runs)].reverse().find((r) => r.receipt && r.exit === 0 && !expectedFailure(r) && Object.values(r.receipt.stages ?? {}).some((s) => s?.outputs));
|
|
745
|
+
const out = [];
|
|
746
|
+
if (run) out.push({ status: outputDirsProblems(run.receipt).ok ? "pass" : "fail", evidence: [run.receiptPath], problems: outputDirsProblems(run.receipt).problems });
|
|
747
|
+
const n15 = Object.values(ctx.runs).find((r) => r.negative === "N15");
|
|
748
|
+
if (n15) out.push({ ...verdict(n15.negativeResult, [n15.logPath]) });
|
|
749
|
+
return out.length ? out : unchecked("no receipt records stage outputs");
|
|
750
|
+
},
|
|
751
|
+
"GC-A23": (ctx) => {
|
|
752
|
+
// Read right after each run (the snapshot is re-synced by every later step), never at the end.
|
|
753
|
+
const out = [];
|
|
754
|
+
for (const [label, run] of Object.entries(ctx.runs)) {
|
|
755
|
+
if (!run.sourceIdentity) continue;
|
|
756
|
+
const si = run.sourceIdentity;
|
|
757
|
+
if (si.error) { out.push({ label, status: "fail", evidence: [si.file], problems: [si.error] }); continue; }
|
|
758
|
+
out.push({ label, ...verdict(validateSourceIdentity(si.identity, { commit: run.commit, trees: si.trees }), [`${si.file} (read right after ${label})`, "git rev-parse <commit>:<dir>"]) });
|
|
759
|
+
}
|
|
760
|
+
return out.length ? out : unchecked("no run produced a receipt that names a snapshot path");
|
|
761
|
+
},
|
|
762
|
+
"GC-A22-render": (ctx) => {
|
|
763
|
+
const run = needRun(ctx, "S1:render");
|
|
764
|
+
if (!run) return unchecked("--to render was not run");
|
|
765
|
+
if (run.exit !== 0) return { status: "fail", evidence: [run.logPath], problems: [`--to render exited ${run.exit}`] };
|
|
766
|
+
const dir = (/(?:render(?:ed)?|stored|wrote|receipt)[^\n]*?(\S*rightkit-gate-render\S*)/.exec(run.log) ?? [])[1]?.replace(/[,.;)]+$/, "");
|
|
767
|
+
if (!dir) return { status: "fail", evidence: [run.logPath], problems: ["the log names no rightkit-gate-render directory"] };
|
|
768
|
+
const file = path.join(dir.endsWith(".json") ? path.dirname(dir) : dir, "render-receipt.json");
|
|
769
|
+
let receipt;
|
|
770
|
+
try { receipt = JSON.parse(fs.readFileSync(file, "utf8")); } catch (e) { return { status: "fail", evidence: [file], problems: [`cannot read ${file}: ${e.message}`] }; }
|
|
771
|
+
return verdict(validateRenderReceipt(receipt, { commit: run.commit, png: (rel) => { try { return fs.readFileSync(path.join(path.dirname(file), rel)); } catch { return null; } } }), [file]);
|
|
772
|
+
},
|
|
773
|
+
"GC-I22": (ctx) => {
|
|
774
|
+
const dir = path.join(here, "test-support", "vectors");
|
|
775
|
+
let source; const files = {};
|
|
776
|
+
try { source = JSON.parse(fs.readFileSync(path.join(dir, "vectors-source.json"), "utf8")); for (const n of fs.readdirSync(dir)) if (n.endsWith(".json")) files[n] = fs.readFileSync(path.join(dir, n)); } catch (e) { return { status: "fail", evidence: [dir], problems: [e.message] }; }
|
|
777
|
+
const up = ctx.rustrightContracts;
|
|
778
|
+
let upstream = null;
|
|
779
|
+
if (up && fs.existsSync(up)) { upstream = {}; for (const n of Object.keys(files)) { try { upstream[n] = fs.readFileSync(path.join(up, n)); } catch { /* reported as "no copy" by vectorsProblems */ } } }
|
|
780
|
+
return verdict(vectorsProblems({ source, files: { ...files }, upstream, upstreamDir: up }), [path.join(dir, "vectors-source.json"), up ?? "RustRight docs/contracts"]);
|
|
781
|
+
},
|
|
782
|
+
"GC-I18": (ctx) => {
|
|
783
|
+
const m = ctx.broker.manifest; const p = ctx.broker.pins;
|
|
784
|
+
if (!m || !p) return { status: "fail", evidence: [ctx.broker.manifestPath ?? "runtime-manifest.json", ctx.broker.pinsPath ?? "pins/broker-<platform>.json"], problems: [ctx.broker.problem ?? "runtime manifest or pins record unreadable"] };
|
|
785
|
+
return verdict(brokerDigestProblems({ manifest: m, pins: p }), [ctx.broker.manifestPath, ctx.broker.pinsPath]);
|
|
786
|
+
},
|
|
787
|
+
"GC-I01": (ctx) => {
|
|
788
|
+
const key = repositoryKey(ctx.git.canonical, ctx.platform);
|
|
789
|
+
const dir = path.join(ctx.managedRoot, "snapshots", key);
|
|
790
|
+
const out = [];
|
|
791
|
+
out.push({ ...verdict({ ok: fs.existsSync(dir), problems: fs.existsSync(dir) ? [] : [`${dir} does not exist`] }, [dir]) });
|
|
792
|
+
const run = Object.values(ctx.runs).find((r) => r.receipt?.stages?.check?.snapshot?.path);
|
|
793
|
+
if (run) { const sp = run.receipt.stages.check.snapshot.path; const ok = path.resolve(sp).startsWith(path.resolve(dir)); out.push({ ...verdict({ ok, problems: ok ? [] : [`receipt snapshot path ${sp} is not under ${dir}`] }, [run.receiptPath]) }); }
|
|
794
|
+
return out;
|
|
795
|
+
},
|
|
796
|
+
"GC-A01": (ctx) => {
|
|
797
|
+
const out = [];
|
|
798
|
+
const n13 = Object.values(ctx.runs).filter((r) => r.negative === "N13");
|
|
799
|
+
for (const r of n13) out.push({ ...verdict(r.negativeResult, [r.logPath]) });
|
|
800
|
+
if (ctx.s9) {
|
|
801
|
+
const wt = worktreeCount(ctx.s9.worktree);
|
|
802
|
+
out.push({ ...verdict({ ok: wt === 1, problems: wt === 1 ? [] : [`${wt} worktrees listed, expected 1`] }, ["git worktree list --porcelain"]) });
|
|
803
|
+
out.push({ ...verdict(ctx.s9.snapshotDirCheck, [path.join(ctx.managedRoot, "snapshots")]) });
|
|
804
|
+
}
|
|
805
|
+
return out.length ? out : unchecked("neither N13 nor S9 ran");
|
|
806
|
+
},
|
|
807
|
+
"GC-T14": (ctx) => CHECKS["GC-A01"](ctx),
|
|
808
|
+
"GC-A02": (ctx) => {
|
|
809
|
+
const out = [];
|
|
810
|
+
if (ctx.s9) out.push({ ...sameVerdict(sameListing("git stash list", ctx.s0?.stash, ctx.s9.stash), ["git stash list at S0 and S9"], ctx.s0) });
|
|
811
|
+
if (ctx.s6?.stash) out.push({ ...verdict(ctx.s6.stash, ["git stash list before and after S6"]) });
|
|
812
|
+
if (ctx.s6?.restore) out.push({ ...verdict(ctx.s6.restore, ["the S6 checkout restore"]) });
|
|
813
|
+
return out.length ? out : unchecked("S6 and S9 did not run");
|
|
814
|
+
},
|
|
815
|
+
"GC-T06": (ctx) => {
|
|
816
|
+
const out = [];
|
|
817
|
+
for (const [label, run] of Object.entries(ctx.runs)) if (run.recovery) out.push({ label, ...verdict(run.recovery, [run.logPath, run.ownerPath ?? "owner.json"]) });
|
|
818
|
+
if (ctx.s6?.fresh && ctx.s6.proof) out.push({ label: "S6", ...verdict(ctx.s6.proof, ["S6: a dirty tree and an unpushed commit build the commit's bytes"]) });
|
|
819
|
+
if (ctx.s9) out.push({ ...verdict(ctx.s9.ownerClean, [ctx.s9.ownerPath]) });
|
|
820
|
+
return out.length ? out : unchecked("S6, S8 and S9 did not run");
|
|
821
|
+
},
|
|
822
|
+
"GC-A19": (ctx) => {
|
|
823
|
+
const out = [];
|
|
824
|
+
const s4 = needRun(ctx, "S4:check");
|
|
825
|
+
const base = firstRows(ctx, "S2:check", "S1:check");
|
|
826
|
+
if (s4?.rows && base && s4.manifestInfo) out.push({ ...verdict(assertManifestEdit(base.rows, s4.rows, s4.manifestInfo), [...base.coveragePaths, ...s4.coveragePaths]) });
|
|
827
|
+
const s2 = needRun(ctx, "S2:check");
|
|
828
|
+
if (s2?.rows) {
|
|
829
|
+
const aud = [...s2.rows.values()].filter((r) => /^(cargo-deny|cargo-audit|pnpm-audit|ghsa-audit)/.test(r.id));
|
|
830
|
+
const bad = aud.filter((r) => r.coverage === "ran");
|
|
831
|
+
out.push({ ...verdict({ ok: aud.length > 0 && bad.length === 0, problems: aud.length === 0 ? ["no audit rows in the warm rerun"] : bad.map((r) => `${r.id}: ran on an unchanged commit (key ${r.key})`) }, s2.coveragePaths) });
|
|
832
|
+
}
|
|
833
|
+
return out.length ? out : unchecked("S2 and S4 did not run");
|
|
834
|
+
},
|
|
835
|
+
"GC-A24": (ctx) => {
|
|
836
|
+
const out = [];
|
|
837
|
+
const s1 = needRun(ctx, "S1:check"); const s2 = needRun(ctx, "S2:check"); const s3 = needRun(ctx, "S3:check");
|
|
838
|
+
if (s1?.rows && s2?.rows) out.push({ ...verdict(assertWarmRerun(s1.rows, s2.rows), [...s1.coveragePaths, ...s2.coveragePaths]) });
|
|
839
|
+
if (s2?.rows && s3?.rows) out.push({ ...verdict(assertOneFileEdit(s2.rows, s3.rows), [...s2.coveragePaths, ...s3.coveragePaths]) });
|
|
840
|
+
for (const [label, run] of Object.entries(ctx.runs)) if (run.kill === "K02") out.push({ label, ...verdict(run.recovery, [run.logPath]) });
|
|
841
|
+
return out.length ? out : unchecked("S1/S2/S3 coverage pairs are missing");
|
|
842
|
+
},
|
|
843
|
+
"GC-T04": (ctx) => {
|
|
844
|
+
const out = [];
|
|
845
|
+
for (const [label, run] of Object.entries(ctx.runs)) {
|
|
846
|
+
if (!run.receipt || run.exit !== 0 || expectedFailure(run)) continue;
|
|
847
|
+
const problems = [];
|
|
848
|
+
if (run.receipt.binding?.executor !== "broker") problems.push(`receipt.binding.executor is ${JSON.stringify(run.receipt.binding?.executor)}, expected "broker"`);
|
|
849
|
+
if ("brokerException" in run.receipt) problems.push("receipt.brokerException is set");
|
|
850
|
+
out.push({ label, ...verdict({ ok: problems.length === 0, problems }, [`${run.receiptPath} (binding.executor)`]) });
|
|
851
|
+
}
|
|
852
|
+
return out.length ? out : unchecked("no run wrote a receipt");
|
|
853
|
+
},
|
|
854
|
+
"GC-T19": (ctx) => {
|
|
855
|
+
const out = []; let release = false;
|
|
856
|
+
for (const [label, run] of Object.entries(ctx.runs)) {
|
|
857
|
+
if (!run.ladder || expectedFailure(run) && run.refusal === undefined) continue;
|
|
858
|
+
if (run.refusal !== undefined) { if (run.refusal.ok) { release = true; out.push({ label, status: "pass", evidence: [run.logPath], problems: [] }); } else out.push({ label, ...verdict(run.refusal, [run.logPath]) }); continue; }
|
|
859
|
+
if (!run.receipt || run.exit !== 0 || !run.receipt.stages?.check) continue;
|
|
860
|
+
if (run.stage === "qualify") release = true;
|
|
861
|
+
out.push({ label, ...verdict(ruleTierProblems(run.receipt, run.stage), [`${run.receiptPath} (stages.check.ruleTier)`]) });
|
|
862
|
+
}
|
|
863
|
+
if (!out.length) return unchecked("no run recorded a check stage");
|
|
864
|
+
if (!release) out.push(missing(ctx.allowInstall ? "no --to qualify run: the release-tier half is unchecked" : `release-tier half (--to qualify): ${NEEDS_INSTALL_APPROVAL}`));
|
|
865
|
+
return out;
|
|
866
|
+
},
|
|
867
|
+
"GC-A22-classA": (ctx) => {
|
|
868
|
+
const src = firstRows(ctx, "S1:check", "S1:compile", "S2:check");
|
|
869
|
+
const out = [];
|
|
870
|
+
if (src) {
|
|
871
|
+
const find = (re) => [...src.rows.values()].filter((r) => re.test(r.id));
|
|
872
|
+
for (const [name, re, need] of [["ghsa-audit", /^ghsa-audit(:|$)/, true], ["secret-scan", /^secret-scan$/, true], ["feature-coverage", /^feature-coverage$/, false]]) {
|
|
873
|
+
const rows = find(re);
|
|
874
|
+
if (!rows.length) { out.push(need ? { status: "fail", evidence: src.coveragePaths, problems: [`no ${name} row in the coverage report`] } : missing(`no ${name} row: the fixture has no crate with declared features (${NEEDS_FIXTURE})`)); continue; }
|
|
875
|
+
const bad = rows.filter((r) => !(["hit", "ran"].includes(r.coverage) && r.status === "pass")).map((r) => `${r.id}: ${r.coverage}/${r.status}${r.reason ? ` (${r.reason})` : ""}`);
|
|
876
|
+
out.push({ status: bad.length ? "fail" : "pass", evidence: src.coveragePaths, problems: bad });
|
|
877
|
+
}
|
|
878
|
+
} else out.push(unchecked("no coverage report (S1 check did not run)"));
|
|
879
|
+
const n02 = Object.values(ctx.runs).find((r) => r.negative === "N02");
|
|
880
|
+
if (n02) out.push({ ...verdict(n02.negativeResult, [n02.logPath]) });
|
|
881
|
+
return out;
|
|
882
|
+
},
|
|
883
|
+
"GC-I03": (ctx) => {
|
|
884
|
+
const out = [];
|
|
885
|
+
for (const [label, run] of Object.entries(ctx.runs)) {
|
|
886
|
+
if (!run.receipt || run.exit !== 0 || expectedFailure(run)) continue;
|
|
887
|
+
const problems = [];
|
|
888
|
+
for (const stage of ["check", "compile"]) {
|
|
889
|
+
const sn = run.receipt.stages?.[stage]?.snapshot;
|
|
890
|
+
if (stage === "check" && !run.receipt.stages?.check) { problems.push("receipt.stages.check is missing"); continue; }
|
|
891
|
+
if (run.receipt.stages?.[stage] === undefined) continue;
|
|
892
|
+
if (!isObject(sn)) problems.push(`receipt.stages.${stage}.snapshot is missing`);
|
|
893
|
+
else { if (sn.tree !== run.tree) problems.push(`${stage}: snapshot tree ${sn.tree} != commit^{tree} ${run.tree}`); if (sn.intactAfter !== true) problems.push(`${stage}: snapshot.intactAfter is ${JSON.stringify(sn.intactAfter)}`); }
|
|
894
|
+
}
|
|
895
|
+
out.push({ label, ...verdict({ ok: problems.length === 0, problems }, [`${run.receiptPath} (door half: snapshot tree at stage exit vs commit^{tree})`]) });
|
|
896
|
+
}
|
|
897
|
+
return out.length ? out : unchecked("no run wrote a receipt");
|
|
898
|
+
},
|
|
899
|
+
"GC-I05": (ctx) => {
|
|
900
|
+
const out = [];
|
|
901
|
+
for (const [label, run] of Object.entries(ctx.runs)) {
|
|
902
|
+
if (!run.receipt || run.exit !== 0 || expectedFailure(run) || !run.receiptPath) continue;
|
|
903
|
+
const stages = LADDER.filter((s) => RECEIPT_STAGES.has(s) && run.stageIndex >= LADDER.indexOf(s)).filter((s) => run.receipt.stages?.[s]);
|
|
904
|
+
out.push({ label, ...verdict(validateDoorReceipt(run.receipt, { commit: run.commit, expectedTree: run.tree, stages }), [`${run.receiptPath} (door half: no verdict/refreshed, strict fields; the broker's receipt fields are not read)`]) });
|
|
905
|
+
}
|
|
906
|
+
return out.length ? out : unchecked("no run wrote a receipt");
|
|
907
|
+
},
|
|
908
|
+
"GC-I15": (ctx) => {
|
|
909
|
+
if (!ctx.s0 || !ctx.s9) return unchecked("S0 and S9 did not both run");
|
|
910
|
+
return verdict(brokerUnchanged(ctx.s0.broker, ctx.s9.broker), ["runningBrokerProcess() at S0 and at S9 (pid and start time)"]);
|
|
911
|
+
},
|
|
912
|
+
"GC-T20": (ctx) => (ctx.hooks ? verdict(hookProblems(ctx.hooks), [`${ctx.hooks.dir} (the hooks half only; the no-gate-process-on-commit half is not run)`]) : unchecked("the fixture's hooks were not read")),
|
|
913
|
+
};
|
|
914
|
+
const negativeCheck = (negId) => (ctx) => {
|
|
915
|
+
const run = Object.values(ctx.runs).find((r) => r.negative === negId);
|
|
916
|
+
return run ? { ...verdict(run.negativeResult, [run.logPath]) } : unchecked(`negative ${negId} was not run`);
|
|
917
|
+
};
|
|
918
|
+
CHECKS["GC-1A-R2"] = negativeCheck("N27");
|
|
919
|
+
CHECKS["GC-1A-R4"] = negativeCheck("N26");
|
|
920
|
+
const sameVerdict = (res, evidence, s0) => (s0 ? verdict(res, evidence) : unchecked("S0 listing missing"));
|
|
921
|
+
|
|
922
|
+
/** The per-clause verdict out of its checks: any fail -> fail; all real checks pass and nothing blocks -> pass; otherwise unchecked (never pass without evidence). */
|
|
923
|
+
export function summarizeClause(id, checks, { allowInstall = true } = {}) {
|
|
924
|
+
const list = checks ?? [];
|
|
925
|
+
const ev = list.flatMap((c) => c.evidence ?? []);
|
|
926
|
+
const problems = list.flatMap((c) => (c.problems ?? []).map((p) => (c.label ? `${c.label}: ${p}` : p)));
|
|
927
|
+
const real = list.filter((c) => c.status !== "unchecked");
|
|
928
|
+
const blockers = list.filter((c) => c.status === "unchecked" && c.blocksPass);
|
|
929
|
+
let status = "unchecked";
|
|
930
|
+
if (list.some((c) => c.status === "fail")) status = "fail";
|
|
931
|
+
else if (real.length > 0 && real.every((c) => c.status === "pass") && blockers.length === 0) status = "pass";
|
|
932
|
+
let reason = null;
|
|
933
|
+
if (status === "unchecked") reason = installReason(id, allowInstall) ?? (list.length ? problems.join("; ") : (UNCHECKED_WHY[id] ?? NO_EVIDENCE));
|
|
934
|
+
return { id, ev: CLAUSES[id]?.ev ?? null, status, evidence: [...new Set(ev)], problems: status === "unchecked" ? [] : problems, ...(reason ? { reason } : {}), assertions: real.length };
|
|
935
|
+
}
|
|
936
|
+
|
|
937
|
+
/** Steps a PASS tolerates as unchecked: unchecked by design (S5). Any other selected step that did not pass blocks the verdict. */
|
|
938
|
+
const BY_DESIGN_UNCHECKED = new Set(STEPS.filter((s) => s.byDesignUnchecked).map((s) => s.id));
|
|
939
|
+
|
|
940
|
+
export function buildResult({ host, gate, broker, commit, steps, clauseChecks, startedAt, endedAt, notes = [], allowInstall = true, stepChecks = [] }) {
|
|
941
|
+
const clauses = Object.keys(CLAUSES).map((id) => summarizeClause(id, clauseChecks[id], { allowInstall }));
|
|
942
|
+
const counts = { pass: 0, fail: 0, unchecked: 0 };
|
|
943
|
+
for (const c of clauses) counts[c.status] += 1;
|
|
944
|
+
const stepsOut = steps.map((s) => ({ ...s, status: s.checks.some((c) => c === "fail") ? "fail" : s.checks.length && s.checks.every((c) => c === "pass") ? "pass" : "unchecked" }));
|
|
945
|
+
const blockers = [
|
|
946
|
+
...clauses.filter((c) => c.status === "fail").map((c) => `clause ${c.id} failed`),
|
|
947
|
+
...stepsOut.filter((s) => s.status === "fail").map((s) => `step ${s.id} failed`),
|
|
948
|
+
...stepsOut.filter((s) => s.status === "unchecked" && !BY_DESIGN_UNCHECKED.has(s.id)).map((s) => `step ${s.id} did not run as specified`),
|
|
949
|
+
...stepChecks.filter((c) => !c.ok).map((c) => `${c.step} check "${c.name}" failed`),
|
|
950
|
+
];
|
|
951
|
+
if (counts.pass === 0) blockers.push("no clause passed");
|
|
952
|
+
const partial = stepsOut.length < STEPS.length;
|
|
953
|
+
const ok = blockers.length === 0;
|
|
954
|
+
const asserted = counts.pass + counts.fail;
|
|
955
|
+
const tail = `${asserted} of ${clauses.length} asserted, ${counts.unchecked} unchecked`;
|
|
956
|
+
const verdictText = ok ? `PASS (${tail}${partial ? `; partial run: steps ${stepsOut.map((s) => s.id).join(",")} only` : ""})` : `NOT PASSED (${tail}; ${counts.fail} failed clause(s); ${blockers.length} blocker(s))`;
|
|
957
|
+
return { schema: RESULT_SCHEMA, host, gate, broker, fixtureCommit: commit, startedAt, endedAt, steps: stepsOut, stepChecks, clauses, totals: { clauses: clauses.length, ...counts }, ok, verdict: verdictText, blockers, partial, notes };
|
|
958
|
+
}
|
|
959
|
+
|
|
960
|
+
export function formatSummary(result) {
|
|
961
|
+
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
|
+
for (const b of result.blockers) lines.push(` BLOCKER ${b}`);
|
|
963
|
+
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(", ")}]`);
|
|
964
|
+
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
|
+
for (const s of result.steps) lines.push(` ${s.id} ${s.status} ${s.title}`);
|
|
966
|
+
return lines.join("\n");
|
|
967
|
+
}
|
|
968
|
+
|
|
969
|
+
// ---------------------------------------------------------------------------------------------------------------------------------------------
|
|
970
|
+
// Runtime: git, the gate, the kill cases. Nothing below runs during `--plan` or in the pure tests (the dirty-checkout helpers are exported and tested
|
|
971
|
+
// against a temporary repository).
|
|
972
|
+
// ---------------------------------------------------------------------------------------------------------------------------------------------
|
|
973
|
+
const IDENT = Object.freeze({ GIT_AUTHOR_NAME: "gate-acceptance", GIT_AUTHOR_EMAIL: "gate-acceptance@invalid", GIT_COMMITTER_NAME: "gate-acceptance", GIT_COMMITTER_EMAIL: "gate-acceptance@invalid" });
|
|
974
|
+
|
|
975
|
+
function git(cwd, args, { env = {}, input, buffer = false } = {}) {
|
|
976
|
+
const r = spawnSync("git", args, { cwd, encoding: buffer ? "buffer" : "utf8", env: { ...process.env, ...env }, input, maxBuffer: 1 << 28 });
|
|
977
|
+
if (r.status !== 0) throw new Error(`git ${args.join(" ")}: ${String(r.stderr || r.stdout || "").trim() || `exit ${r.status}`}`);
|
|
978
|
+
return r.stdout;
|
|
979
|
+
}
|
|
980
|
+
|
|
981
|
+
/** Workspace directory a Cargo manifest belongs to: the nearest ancestor directory in `wsDirs`, else the manifest's own directory (a standalone package). */
|
|
982
|
+
export function cargoWorkspaceOf(file, wsDirs) {
|
|
983
|
+
const dir = path.posix.dirname(file);
|
|
984
|
+
for (let d = dir; ; d = path.posix.dirname(d)) {
|
|
985
|
+
if (wsDirs.includes(d)) return d;
|
|
986
|
+
if (d === "." || d === "/") break;
|
|
987
|
+
}
|
|
988
|
+
return dir;
|
|
989
|
+
}
|
|
990
|
+
|
|
991
|
+
function gitTools(fixture, scratch) {
|
|
992
|
+
const canonical = fs.realpathSync.native(fixture);
|
|
993
|
+
const created = [];
|
|
994
|
+
const self = {
|
|
995
|
+
canonical,
|
|
996
|
+
run: (args, o) => git(canonical, args, o),
|
|
997
|
+
head: () => git(canonical, ["rev-parse", "HEAD"]).trim(),
|
|
998
|
+
tree: (commit) => git(canonical, ["rev-parse", `${commit}^{tree}`]).trim(),
|
|
999
|
+
stash: () => git(canonical, ["stash", "list"]),
|
|
1000
|
+
worktrees: () => git(canonical, ["worktree", "list", "--porcelain"]),
|
|
1001
|
+
status: () => git(canonical, ["status", "--short"]),
|
|
1002
|
+
tracked: (commit) => git(canonical, ["ls-tree", "-r", "--name-only", commit]).split("\n").filter(Boolean),
|
|
1003
|
+
sourceTrees(commit) {
|
|
1004
|
+
const dirs = new Set([""]);
|
|
1005
|
+
for (const f of self.tracked(commit)) if (/(^|\/)(Cargo\.toml|Package\.swift|package\.json)$/.test(f)) dirs.add(path.posix.dirname(f) === "." ? "" : path.posix.dirname(f));
|
|
1006
|
+
const trees = {};
|
|
1007
|
+
for (const d of dirs) trees[d] = git(canonical, ["rev-parse", d === "" ? `${commit}^{tree}` : `${commit}:${d}`]).trim();
|
|
1008
|
+
return trees;
|
|
1009
|
+
},
|
|
1010
|
+
show: (commit, file) => git(canonical, ["show", `${commit}:${file}`]),
|
|
1011
|
+
blob: (commit, file) => git(canonical, ["cat-file", "blob", `${commit}:${file}`], { buffer: true }),
|
|
1012
|
+
/** The Cargo layout of `commit`: workspace directories and `{ workspaceDir: [crate names] }` (for S4's "that workspace only"). */
|
|
1013
|
+
cargoLayout(commit, tracked = self.tracked(commit)) {
|
|
1014
|
+
const manifests = tracked.filter((f) => /(^|\/)Cargo\.toml$/.test(f));
|
|
1015
|
+
const texts = new Map(manifests.map((f) => [f, self.show(commit, f)]));
|
|
1016
|
+
const wsDirs = manifests.filter((f) => /^\s*\[workspace\]/m.test(texts.get(f))).map((f) => path.posix.dirname(f));
|
|
1017
|
+
const crates = {};
|
|
1018
|
+
for (const f of manifests) {
|
|
1019
|
+
const name = /\[package\][^[]*?\bname\s*=\s*"([^"]+)"/s.exec(texts.get(f))?.[1];
|
|
1020
|
+
if (!name) continue;
|
|
1021
|
+
(crates[cargoWorkspaceOf(f, wsDirs)] ??= []).push(name);
|
|
1022
|
+
}
|
|
1023
|
+
return { manifests, wsDirs, crates, texts };
|
|
1024
|
+
},
|
|
1025
|
+
/** An ephemeral commit on `base` with `edits` ({path, content}); referenced under refs/witness/<name>; no branch, no checkout, no worktree. The temporary index lives under the scratch root. */
|
|
1026
|
+
witnessCommit(base, name, edits) {
|
|
1027
|
+
fs.mkdirSync(scratch, { recursive: true });
|
|
1028
|
+
const idx = path.join(fs.mkdtempSync(path.join(scratch, "idx-")), "index");
|
|
1029
|
+
const env = { GIT_INDEX_FILE: idx };
|
|
1030
|
+
try {
|
|
1031
|
+
git(canonical, ["read-tree", base], { env });
|
|
1032
|
+
for (const e of edits) {
|
|
1033
|
+
const blob = git(canonical, ["hash-object", "-w", "--stdin"], { input: e.content }).trim();
|
|
1034
|
+
git(canonical, ["update-index", "--add", "--cacheinfo", `100644,${blob},${e.path}`], { env });
|
|
1035
|
+
}
|
|
1036
|
+
const tree = git(canonical, ["write-tree"], { env }).trim();
|
|
1037
|
+
const commit = git(canonical, ["commit-tree", tree, "-p", base, "-m", `gate-acceptance ${name}`], { env: IDENT }).trim();
|
|
1038
|
+
git(canonical, ["update-ref", `refs/witness/${name}`, commit]);
|
|
1039
|
+
created.push(name);
|
|
1040
|
+
return commit;
|
|
1041
|
+
} finally { fs.rmSync(path.dirname(idx), { recursive: true, force: true }); }
|
|
1042
|
+
},
|
|
1043
|
+
/** Deletes every refs/witness/<name> this run created; returns the problems (empty when all are gone). */
|
|
1044
|
+
dropWitnessRefs() {
|
|
1045
|
+
const problems = [];
|
|
1046
|
+
for (const name of created.splice(0)) { try { git(canonical, ["update-ref", "-d", `refs/witness/${name}`]); } catch (e) { problems.push(e.message); } }
|
|
1047
|
+
return problems;
|
|
1048
|
+
},
|
|
1049
|
+
};
|
|
1050
|
+
return self;
|
|
1051
|
+
}
|
|
1052
|
+
|
|
1053
|
+
// --- S6: the dirty checkout ---------------------------------------------------------------------------------------------------------------------
|
|
1054
|
+
const stashEntries = (repo) => git(repo, ["stash", "list", "--format=%H %gd"]).split("\n").filter(Boolean).map((l) => { const [sha, gd] = l.split(" "); return { sha, gd }; });
|
|
1055
|
+
|
|
1056
|
+
/** A checkout is clean when `git status --porcelain --untracked-files=all` prints nothing. */
|
|
1057
|
+
export function assertCleanCheckout(repo) {
|
|
1058
|
+
const st = git(repo, ["status", "--porcelain", "--untracked-files=all"]);
|
|
1059
|
+
return st.trim() === "" ? { ok: true, problems: [] } : { ok: false, problems: [`the checkout is not clean: ${st.trim().split("\n")[0]}${st.trim().split("\n").length > 1 ? ` (+${st.trim().split("\n").length - 1} more)` : ""}`] };
|
|
1060
|
+
}
|
|
1061
|
+
|
|
1062
|
+
/**
|
|
1063
|
+
* Makes `repo` dirty for S6: refuses a dirty checkout; edits tracked `file`, adds the untracked file, pushes both into a new stash, then edits and adds
|
|
1064
|
+
* them again so the checkout is dirty AND a stash of ours stands. Returns the state `restoreDirtyCheckout` needs. A failure part-way restores before throwing.
|
|
1065
|
+
*/
|
|
1066
|
+
export function makeDirtyCheckout(repo, { file, untracked }) {
|
|
1067
|
+
const clean = assertCleanCheckout(repo);
|
|
1068
|
+
if (!clean.ok) throw new Error(`refusing to make a dirty checkout: ${clean.problems[0]}`);
|
|
1069
|
+
const abs = path.join(repo, file); const absU = path.join(repo, untracked);
|
|
1070
|
+
if (fs.existsSync(absU)) throw new Error(`refusing: ${untracked} exists`);
|
|
1071
|
+
const state = { repo, file, untracked, original: fs.readFileSync(abs), stashBefore: stashEntries(repo).map((e) => e.sha), stashSha: null };
|
|
1072
|
+
try {
|
|
1073
|
+
fs.writeFileSync(abs, Buffer.concat([state.original, Buffer.from("\ngate-acceptance dirty edit\n")]));
|
|
1074
|
+
fs.writeFileSync(absU, "untracked\n");
|
|
1075
|
+
git(repo, ["stash", "push", "--include-untracked", "-m", "gate-acceptance-s6"], { env: IDENT });
|
|
1076
|
+
const after = stashEntries(repo);
|
|
1077
|
+
if (after.length !== state.stashBefore.length + 1) throw new Error("git stash push did not create a stash");
|
|
1078
|
+
state.stashSha = after[0].sha;
|
|
1079
|
+
fs.writeFileSync(abs, Buffer.concat([state.original, Buffer.from("\ngate-acceptance second dirty edit\n")]));
|
|
1080
|
+
fs.writeFileSync(absU, "untracked again\n");
|
|
1081
|
+
return state;
|
|
1082
|
+
} catch (e) {
|
|
1083
|
+
const r = restoreDirtyCheckout(repo, state);
|
|
1084
|
+
e.message += r.ok ? " (the checkout was restored)" : ` (the restore also failed: ${r.problems.join("; ")})`;
|
|
1085
|
+
throw e;
|
|
1086
|
+
}
|
|
1087
|
+
}
|
|
1088
|
+
|
|
1089
|
+
/**
|
|
1090
|
+
* Restores what `makeDirtyCheckout` changed: removes the untracked file, restores the tracked file from the index, drops OUR stash only (found by its
|
|
1091
|
+
* hash, so a stash that stood before is never touched), then verifies the checkout is clean, the stash list holds exactly the hashes it held before
|
|
1092
|
+
* and the tracked file's bytes are the original ones.
|
|
1093
|
+
*/
|
|
1094
|
+
export function restoreDirtyCheckout(repo, state) {
|
|
1095
|
+
const problems = [];
|
|
1096
|
+
const attempt = (what, fn) => { try { fn(); } catch (e) { problems.push(`${what}: ${e.message}`); } };
|
|
1097
|
+
attempt("remove the untracked file", () => fs.rmSync(path.join(repo, state.untracked), { force: true }));
|
|
1098
|
+
attempt("restore the tracked file", () => git(repo, ["checkout", "--", state.file]));
|
|
1099
|
+
if (state.stashSha) attempt("drop the gate-acceptance stash", () => {
|
|
1100
|
+
const entry = stashEntries(repo).find((e) => e.sha === state.stashSha);
|
|
1101
|
+
if (!entry) throw new Error("it is not in the stash list");
|
|
1102
|
+
git(repo, ["stash", "drop", entry.gd]);
|
|
1103
|
+
});
|
|
1104
|
+
attempt("verify", () => {
|
|
1105
|
+
const clean = assertCleanCheckout(repo);
|
|
1106
|
+
if (!clean.ok) problems.push(...clean.problems);
|
|
1107
|
+
const now = stashEntries(repo).map((e) => e.sha);
|
|
1108
|
+
if (JSON.stringify(now) !== JSON.stringify(state.stashBefore)) problems.push(`the stash list is ${JSON.stringify(now)}, it held ${JSON.stringify(state.stashBefore)}`);
|
|
1109
|
+
if (!fs.readFileSync(path.join(repo, state.file)).equals(state.original)) problems.push(`${state.file} differs from its original bytes`);
|
|
1110
|
+
});
|
|
1111
|
+
return { ok: problems.length === 0, problems };
|
|
1112
|
+
}
|
|
1113
|
+
|
|
1114
|
+
const managedRootOf = (host) => (host === "dell" ? "D:\\.rightkit-managed" : "/Volumes/D/.rightkit-managed");
|
|
1115
|
+
const scratchRootOf = (host) => (host === "dell" ? "D:\\scratch" : "/Volumes/D/scratch");
|
|
1116
|
+
const defaultGate = (host) => (host === "dell" ? "D:\\.rightkit-managed\\agent-bin\\rightkit-host-gate.cmd" : "/Volumes/D/.rightkit-managed/agent-bin/rightkit-host-gate");
|
|
1117
|
+
/** The workspace root that holds rightkit/ and rustright/ (this file is rightkit/packages/release/gate-acceptance.mjs). */
|
|
1118
|
+
export const workspaceRootOf = (dir = here) => path.resolve(dir, "..", "..", "..");
|
|
1119
|
+
|
|
1120
|
+
const listDirs = (dir) => { try { return fs.readdirSync(dir, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name).sort(); } catch { return []; } };
|
|
1121
|
+
|
|
1122
|
+
function launch({ gate, args, cwd, env }) {
|
|
1123
|
+
const spec = launchSpec(gate, args);
|
|
1124
|
+
return spawn(spec.command, spec.args, { cwd, env, stdio: ["ignore", "pipe", "pipe"], detached: process.platform !== "win32", windowsHide: true, ...spec.options });
|
|
1125
|
+
}
|
|
1126
|
+
|
|
1127
|
+
/** Signals the launcher and everything it started (its process group; taskkill /T on Windows, where only the kill variant exists). */
|
|
1128
|
+
function signalGroup(child, signal) {
|
|
1129
|
+
try {
|
|
1130
|
+
if (process.platform === "win32") spawnSync("taskkill", ["/T", "/F", "/PID", String(child.pid)]);
|
|
1131
|
+
else process.kill(-child.pid, signal);
|
|
1132
|
+
} catch { try { child.kill(signal); } catch { /* already gone */ } }
|
|
1133
|
+
}
|
|
1134
|
+
|
|
1135
|
+
/** Runs the gate to completion: `{ exit, signal, log, ms, timedOut }`. The environment is the caller's own; no flag or variable weakens the gate. A timeout kills the whole process group. */
|
|
1136
|
+
function runGate({ gate, cwd, args, env = process.env, timeoutMs = 3_600_000 }) {
|
|
1137
|
+
return new Promise((resolve) => {
|
|
1138
|
+
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; }
|
|
1140
|
+
const timer = setTimeout(() => { timedOut = true; signalGroup(child, "SIGKILL"); }, timeoutMs);
|
|
1141
|
+
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 }); });
|
|
1144
|
+
});
|
|
1145
|
+
}
|
|
1146
|
+
|
|
1147
|
+
/** Starts the gate, waits for `waitFor()` to return truthy (the owner record) plus `afterMs`, then signals its process group. */
|
|
1148
|
+
function killDuring({ gate, cwd, args, signal, waitFor, afterMs }) {
|
|
1149
|
+
return new Promise((resolve) => {
|
|
1150
|
+
let log = ""; let done = false; let child;
|
|
1151
|
+
try { child = launch({ gate, args, cwd, env: process.env }); } catch (e) { resolve({ exit: null, signal: null, log: `spawn error: ${e.message}` }); return; }
|
|
1152
|
+
child.stdout.on("data", (d) => { log += d; }); child.stderr.on("data", (d) => { log += d; });
|
|
1153
|
+
child.on("close", (exit, sig) => { done = true; clearInterval(poll); clearTimeout(cap); resolve({ exit, signal: sig, log }); });
|
|
1154
|
+
child.on("error", (e) => { done = true; clearInterval(poll); clearTimeout(cap); resolve({ exit: null, signal: null, log: `${log}\nspawn error: ${e.message}` }); });
|
|
1155
|
+
let armedAt = null;
|
|
1156
|
+
const poll = setInterval(() => {
|
|
1157
|
+
if (done) return;
|
|
1158
|
+
if (armedAt === null && waitFor()) armedAt = Date.now();
|
|
1159
|
+
if (armedAt !== null && Date.now() - armedAt >= afterMs) { clearInterval(poll); signalGroup(child, signal); }
|
|
1160
|
+
}, 100);
|
|
1161
|
+
const cap = setTimeout(() => { if (!done) signalGroup(child, "SIGKILL"); }, 30 * 60_000); // the owner record never appeared: the case proves nothing
|
|
1162
|
+
});
|
|
1163
|
+
}
|
|
1164
|
+
|
|
1165
|
+
function readJson(file) { try { return { value: JSON.parse(fs.readFileSync(file, "utf8")) }; } catch (e) { return { error: `${file}: ${e.message}` }; } }
|
|
1166
|
+
const readOrNull = (file) => { try { return fs.readFileSync(file); } catch { return null; } };
|
|
1167
|
+
|
|
1168
|
+
/** The installed broker's runtime manifest and the gate's pins record. The client and its manifest are found the way the gate finds them (broker-handshake.mjs): `managedRuntimeClient`, the agent shim resolved, the manifest beside the real client. */
|
|
1169
|
+
function brokerIdentity(host, managedRoot) {
|
|
1170
|
+
const platform = host === "dell" ? "win32" : "darwin";
|
|
1171
|
+
const pinsPath = path.join(managedRoot, "pins", `broker-${platform}.json`);
|
|
1172
|
+
const pins = readJson(pinsPath);
|
|
1173
|
+
let manifestPath = null; const problems = [];
|
|
1174
|
+
try {
|
|
1175
|
+
const client = managedRuntimeClient(process.env, platform);
|
|
1176
|
+
if (!client) throw new Error("no installed RustRight client was found");
|
|
1177
|
+
const exe = resolveBrokerClient(client, { platform }).file;
|
|
1178
|
+
const real = platform === "win32" ? exe : fs.realpathSync.native(exe);
|
|
1179
|
+
const paths = platform === "win32" ? path.win32 : path.posix;
|
|
1180
|
+
manifestPath = paths.join(paths.dirname(real), RUNTIME_MANIFEST_FILE);
|
|
1181
|
+
} catch (e) { problems.push(`cannot locate the installed client's runtime manifest: ${e.message}`); }
|
|
1182
|
+
const manifest = manifestPath ? readJson(manifestPath) : { error: problems.join("; ") };
|
|
1183
|
+
return { pinsPath, pins: pins.value ?? null, manifestPath, manifest: manifest.value ?? null, problem: [pins.error, manifest.error].filter(Boolean).join("; ") || undefined };
|
|
1184
|
+
}
|
|
1185
|
+
|
|
1186
|
+
/** The fixture's hooks as GC-T20 reads them: `{ dir, hooksPath, files }`. */
|
|
1187
|
+
function readHooks(g) {
|
|
1188
|
+
let hooksPath = null; let dir = null; const files = {};
|
|
1189
|
+
try { hooksPath = g.run(["config", "--get", "core.hooksPath"]).trim() || null; } catch { /* not set */ }
|
|
1190
|
+
try { dir = path.resolve(g.canonical, g.run(["rev-parse", "--git-path", "hooks"]).trim()); } catch { /* unreadable: reported by the empty dir */ }
|
|
1191
|
+
const read = hooksPath ? path.resolve(g.canonical, hooksPath) : dir;
|
|
1192
|
+
if (read) for (const e of (() => { try { return fs.readdirSync(read, { withFileTypes: true }); } catch { return []; } })()) if (e.isFile()) { try { files[e.name] = fs.readFileSync(path.join(read, e.name), "utf8").slice(0, 1 << 20); } catch { files[e.name] = ""; } }
|
|
1193
|
+
return { dir: read ?? "<git hooks dir>", hooksPath, files };
|
|
1194
|
+
}
|
|
1195
|
+
|
|
1196
|
+
/** The snapshot's `.rightkit-source-identity.json`, read at the moment of the run (every later step re-syncs the snapshot). */
|
|
1197
|
+
function readSourceIdentity(snapshotPath, commit, g) {
|
|
1198
|
+
const file = path.join(snapshotPath, ".rightkit-source-identity.json");
|
|
1199
|
+
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
|
+
}
|
|
1201
|
+
|
|
1202
|
+
async function main(argv) {
|
|
1203
|
+
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"]);
|
|
1205
|
+
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; }
|
|
1206
|
+
const host = opt("--host") ?? (process.platform === "win32" ? "dell" : "mac");
|
|
1207
|
+
if (!["mac", "dell"].includes(host)) { console.error("gate-acceptance: --host must be mac or dell"); return 64; }
|
|
1208
|
+
const wanted = (opt("--steps") ?? STEPS.map((s) => s.id).join(",")).split(",").map((s) => s.trim()).filter(Boolean);
|
|
1209
|
+
for (const s of wanted) if (!STEPS.some((x) => x.id === s)) { console.error(`gate-acceptance: unknown step ${s}`); return 64; }
|
|
1210
|
+
const allowInstall = argv.includes("--allow-install");
|
|
1211
|
+
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
|
+
if (argv.includes("--plan")) { console.log(formatPlan(buildPlan({ steps: wanted, allowInstall }))); return 0; }
|
|
1213
|
+
const fixture = opt("--fixture");
|
|
1214
|
+
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 });
|
|
1216
|
+
}
|
|
1217
|
+
|
|
1218
|
+
async function execute(options) {
|
|
1219
|
+
const scratch = path.join(scratchRootOf(options.host), "gate-acceptance");
|
|
1220
|
+
fs.mkdirSync(scratch, { recursive: true });
|
|
1221
|
+
const g = gitTools(options.fixture, scratch);
|
|
1222
|
+
try { return await executeRun({ ...options, g, scratch }); } finally {
|
|
1223
|
+
const problems = g.dropWitnessRefs();
|
|
1224
|
+
if (problems.length) console.error(`gate-acceptance: could not delete a refs/witness ref: ${problems.join("; ")}`);
|
|
1225
|
+
}
|
|
1226
|
+
}
|
|
1227
|
+
|
|
1228
|
+
async function executeRun({ fixture, host, wanted, gate, out, commitArg, leafFile, manifestFile, killAfterMs, allowInstall, g, scratch }) {
|
|
1229
|
+
const startedAt = new Date().toISOString();
|
|
1230
|
+
const platform = host === "dell" ? "win32" : "darwin";
|
|
1231
|
+
const managedRoot = managedRootOf(host);
|
|
1232
|
+
const outDir = out ?? path.join(scratch, "runs", `${host}-${startedAt.replace(/[:.]/g, "-")}`);
|
|
1233
|
+
fs.mkdirSync(outDir, { recursive: true });
|
|
1234
|
+
const commit = commitArg ?? g.head();
|
|
1235
|
+
if (!isCommit(commit)) throw new Error(`commit ${commit} is not a 40 hex sha`);
|
|
1236
|
+
const clauseChecks = Object.fromEntries(Object.keys(CLAUSES).map((id) => [id, []]));
|
|
1237
|
+
const runs = {};
|
|
1238
|
+
const stepChecks = [];
|
|
1239
|
+
const stepRecords = STEPS.filter((s) => wanted.includes(s.id)).map((s) => ({ id: s.id, title: s.title, checks: [], notes: [] }));
|
|
1240
|
+
const stepOf = (id) => stepRecords.find((s) => s.id === id);
|
|
1241
|
+
const ctx = { runs, git: g, managedRoot, platform, allowInstall, broker: brokerIdentity(host, managedRoot), rustrightContracts: path.join(workspaceRootOf(), "rustright", "docs", "contracts"), hooks: readHooks(g), s0: null, s6: null, s9: null };
|
|
1242
|
+
const stages = ladderStages({ allowInstall });
|
|
1243
|
+
|
|
1244
|
+
const gateFile = path.join(here, "bin", "rightkit-gate.mjs");
|
|
1245
|
+
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
|
+
|
|
1247
|
+
const key = repositoryKey(g.canonical, platform);
|
|
1248
|
+
const ownerFile = ownershipFile({ platform, repository: key });
|
|
1249
|
+
const readOwner = () => { try { return JSON.parse(fs.readFileSync(ownerFile, "utf8")); } catch { return null; } };
|
|
1250
|
+
const snapRoot = path.join(managedRoot, "snapshots");
|
|
1251
|
+
|
|
1252
|
+
/** A step-only check: it feeds the step status AND the verdict (stepChecks), so it can never be dropped. */
|
|
1253
|
+
const check = (step, name, res) => {
|
|
1254
|
+
stepOf(step)?.checks.push(res.ok ? "pass" : "fail");
|
|
1255
|
+
stepChecks.push({ step, name, ok: res.ok, problems: res.problems });
|
|
1256
|
+
if (!res.ok) stepOf(step)?.notes.push(`${name}: ${res.problems[0]}`);
|
|
1257
|
+
};
|
|
1258
|
+
const exitOk = (r) => ({ ok: r.exit === 0, problems: r.exit === 0 ? [] : [`exit ${r.exit}${r.timedOut ? " (timed out)" : ""}`] });
|
|
1259
|
+
|
|
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;
|
|
1262
|
+
const full = ["--to", stage, "--commit", c, ...(receiptPath ? ["--receipt-out", receiptPath] : []), ...args];
|
|
1263
|
+
const res = await runGate({ gate, cwd: g.canonical, args: full });
|
|
1264
|
+
return finishRun({ label, stage, commit: c, full, res, receiptPath, ladder, step, extra });
|
|
1265
|
+
}
|
|
1266
|
+
function finishRun({ label, stage, commit: c, full, res, receiptPath, ladder = false, step, extra = {} }) {
|
|
1267
|
+
const logPath = path.join(outDir, `${label.replace(/[^\w.-]/g, "_")}.log`);
|
|
1268
|
+
fs.writeFileSync(logPath, res.log);
|
|
1269
|
+
const cov = coveragePaths(res.log); const reports = []; const coverageProblems = [];
|
|
1270
|
+
for (const p of cov) { const j = readJson(p); if (j.error) { coverageProblems.push(`cannot read coverage ${j.error}`); continue; } const v = validateCoverage(j.value); if (!v.ok) coverageProblems.push(...v.problems.map((x) => `${p}: ${x}`)); reports.push(j.value); }
|
|
1271
|
+
let receipt = null;
|
|
1272
|
+
if (receiptPath && fs.existsSync(receiptPath)) { const j = readJson(receiptPath); if (j.value) receipt = j.value; else coverageProblems.push(`cannot read receipt ${j.error}`); }
|
|
1273
|
+
if (receipt?.binding?.gate) gateIdentity.receiptGateSha256 = receipt.binding.gate;
|
|
1274
|
+
const snapPath = receipt?.stages?.check?.snapshot?.path ?? receipt?.stages?.compile?.snapshot?.path;
|
|
1275
|
+
const sourceIdentity = res.exit === 0 && snapPath ? readSourceIdentity(snapPath, c, g) : null;
|
|
1276
|
+
const run = { label, stage, commit: c, tree: g.tree(c), args: full, exit: res.exit, signal: res.signal, timedOut: res.timedOut === true, ms: res.ms, 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
|
+
runs[label] = run; if (step) stepOf(step)?.notes.push(`${label}: exit ${res.exit}, ${(res.ms / 1000).toFixed(1)}s`);
|
|
1278
|
+
return run;
|
|
1279
|
+
}
|
|
1280
|
+
|
|
1281
|
+
// S0 -------------------------------------------------------------------------------------------------------------------------------------
|
|
1282
|
+
if (wanted.includes("S0") || wanted.includes("S9")) {
|
|
1283
|
+
const brokerNow = runningBrokerProcess() ?? null;
|
|
1284
|
+
ctx.s0 = { stash: g.stash(), status: g.status(), worktree: g.worktrees(), broker: brokerNow, owner: readOwner(), snapshots: listDirs(snapRoot) };
|
|
1285
|
+
}
|
|
1286
|
+
if (wanted.includes("S0")) {
|
|
1287
|
+
for (const id of ["GC-I22", "GC-I18", "GC-I01"]) { const r = CHECKS[id](ctx); for (const c of Array.isArray(r) ? r : [r]) { clauseChecks[id].push(c); if (id !== "GC-I01") { stepOf("S0").checks.push(c.status === "unchecked" ? "unchecked" : c.status); stepChecks.push({ step: "S0", name: id, ok: c.status === "pass", problems: c.problems }); } } }
|
|
1288
|
+
check("S0", "the fixture checkout is clean", ctx.s0.status.trim() === "" ? { ok: true, problems: [] } : { ok: false, problems: [`fixture checkout is not clean: ${ctx.s0.status.trim().split("\n")[0]}`] });
|
|
1289
|
+
check("S0", "no owner record stands before the run", ctx.s0.owner ? { ok: false, problems: [`an owner record stands before the run: ${JSON.stringify({ handle: ctx.s0.owner.handle, pid: ctx.s0.owner.pid })}`] } : { ok: true, problems: [] });
|
|
1290
|
+
}
|
|
1291
|
+
|
|
1292
|
+
// S1 --------------------------------------------------------------------------------------------------------------------------------------
|
|
1293
|
+
if (wanted.includes("S1")) {
|
|
1294
|
+
for (const stage of stages) {
|
|
1295
|
+
const r = await doRun({ label: `S1:${stage}`, stage, ladder: true, step: "S1" });
|
|
1296
|
+
if (stage === "qualify" && r.exit !== 0) {
|
|
1297
|
+
r.refusal = qualifyRefusal({ exit: r.exit, text: r.log, receipt: r.receipt });
|
|
1298
|
+
check("S1", "--to qualify refuses by naming a release-tier rule", r.refusal);
|
|
1299
|
+
} else check("S1", `--to ${stage} exits 0`, exitOk(r));
|
|
1300
|
+
if (r.exit !== 0 && stage !== "qualify") { stepOf("S1").notes.push(`ladder stopped at ${stage}: exit ${r.exit}`); break; }
|
|
1301
|
+
}
|
|
1302
|
+
if (!allowInstall) stepOf("S1").notes.push(`--to ${INSTALL_STAGES.join(" and --to ")} not run: ${NEEDS_INSTALL_APPROVAL}`);
|
|
1303
|
+
}
|
|
1304
|
+
// S2 --------------------------------------------------------------------------------------------------------------------------------------
|
|
1305
|
+
if (wanted.includes("S2")) for (const stage of ["check", "compile"]) { const r = await doRun({ label: `S2:${stage}`, stage, ladder: true, step: "S2" }); check("S2", `--to ${stage} exits 0`, exitOk(r)); }
|
|
1306
|
+
|
|
1307
|
+
// S3, S4 (ephemeral edits) ----------------------------------------------------------------------------------------------------------------
|
|
1308
|
+
const tracked = g.tracked(commit);
|
|
1309
|
+
const layout = (wanted.includes("S4") || wanted.includes("S7")) ? g.cargoLayout(commit, tracked) : null;
|
|
1310
|
+
const editStep = async (id, name, file, edit, label, extraOf = () => ({})) => {
|
|
1311
|
+
if (!wanted.includes(id)) return;
|
|
1312
|
+
if (!file) { stepOf(id).notes.push(`unchecked: ${NEEDS_FIXTURE}`); return; }
|
|
1313
|
+
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) });
|
|
1315
|
+
check(id, `--to check on the edited commit exits 0`, exitOk(r));
|
|
1316
|
+
};
|
|
1317
|
+
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\n`, "S3:check");
|
|
1318
|
+
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) => {
|
|
1320
|
+
const ws = cargoWorkspaceOf(file, layout.wsDirs);
|
|
1321
|
+
return { manifestInfo: { workspace: ws, workspaces: [...new Set([...layout.wsDirs, ws])], crates: layout.crates } };
|
|
1322
|
+
});
|
|
1323
|
+
if (wanted.includes("S5")) stepOf("S5").notes.push("unchecked by design: a lock edit needs the fixture's own resolver; not generated by this runner");
|
|
1324
|
+
|
|
1325
|
+
// S6 dirty checkout ------------------------------------------------------------------------------------------------------------------------
|
|
1326
|
+
if (wanted.includes("S6")) {
|
|
1327
|
+
const s6 = { fresh: false, proof: null, why: null, stash: null, restore: null };
|
|
1328
|
+
ctx.s6 = s6;
|
|
1329
|
+
const file = tracked.includes("README.md") ? "README.md" : tracked.find((f) => /\.(md|txt)$/.test(f));
|
|
1330
|
+
const untrackedName = ".gate-acceptance-untracked";
|
|
1331
|
+
const clean = assertCleanCheckout(g.canonical);
|
|
1332
|
+
if (!file) { s6.why = "no tracked README.md or text file to make dirty"; stepOf("S6").notes.push(`unchecked: ${s6.why}`); }
|
|
1333
|
+
else if (!clean.ok) { s6.why = clean.problems[0]; check("S6", "the fixture is clean before S6 (S6 refuses to start otherwise)", clean); }
|
|
1334
|
+
else {
|
|
1335
|
+
const stashBefore = g.stash(); let state = null;
|
|
1336
|
+
try {
|
|
1337
|
+
// A commit whose compile is not recorded yet, so the dirty checkout meets a REAL compile (a recorded compile would be reused, not run).
|
|
1338
|
+
const c6 = g.witnessCommit(commit, "s6-dirty", [{ path: "docs/gate-acceptance-s6.txt", content: "gate-acceptance S6: a commit whose compile is not recorded\n" }]);
|
|
1339
|
+
state = makeDirtyCheckout(g.canonical, { file, untracked: untrackedName });
|
|
1340
|
+
const r = await doRun({ label: "S6:compile", stage: "compile", commit: c6, ladder: true, step: "S6" });
|
|
1341
|
+
s6.fresh = r.exit === 0 && compileRanFresh(r.log);
|
|
1342
|
+
const snapPath = r.receipt?.stages?.compile?.snapshot?.path;
|
|
1343
|
+
if (r.exit === 0 && snapPath) {
|
|
1344
|
+
const si = r.sourceIdentity;
|
|
1345
|
+
const identityProblems = si?.error ? [si.error] : si ? validateSourceIdentity(si.identity, { commit: c6, trees: si.trees }).problems : ["no source identity was read"];
|
|
1346
|
+
s6.proof = dirtyProof({ commitBytes: g.blob(c6, file), checkoutBytes: readOrNull(path.join(g.canonical, file)), snapshotBytes: readOrNull(path.join(snapPath, file)), untrackedInSnapshot: fs.existsSync(path.join(snapPath, untrackedName)), identityProblems, receiptTree: r.receipt?.binding?.tree, expectedTree: g.tree(c6) });
|
|
1347
|
+
}
|
|
1348
|
+
s6.why = s6.fresh ? null : r.exit !== 0 ? `the compile exited ${r.exit}` : "the compile was already recorded for this commit (`[compile] already passed`): no compile ran on the dirty checkout";
|
|
1349
|
+
check("S6", "--to compile on the dirty checkout exits 0", exitOk(r));
|
|
1350
|
+
if (s6.proof) check("S6", "the snapshot holds the commit's bytes, not the dirty checkout's", s6.proof);
|
|
1351
|
+
if (r.exit === 0 && !s6.fresh) stepOf("S6").checks.push("unchecked");
|
|
1352
|
+
} catch (e) { s6.why = e.message; check("S6", "dirty-checkout setup and run", { ok: false, problems: [e.message] }); }
|
|
1353
|
+
finally {
|
|
1354
|
+
if (state) { s6.restore = restoreDirtyCheckout(g.canonical, state); check("S6", "the checkout and stash list are restored exactly", s6.restore); }
|
|
1355
|
+
s6.stash = sameListing("git stash list", stashBefore, g.stash());
|
|
1356
|
+
if (!s6.stash.ok) check("S6", "git stash list is unchanged by S6", s6.stash);
|
|
1357
|
+
}
|
|
1358
|
+
}
|
|
1359
|
+
}
|
|
1360
|
+
|
|
1361
|
+
// S7 negatives ----------------------------------------------------------------------------------------------------------------------------
|
|
1362
|
+
if (wanted.includes("S7")) for (const n of NEGATIVES) {
|
|
1363
|
+
const rs = tracked.find((f) => /\.rs$/.test(f)); const toml = (layout?.manifests ?? tracked.filter((f) => /(^|\/)Cargo\.toml$/.test(f))).find((f) => !/\[workspace\]/.test(g.show(commit, f)));
|
|
1364
|
+
const recipes = {
|
|
1365
|
+
"misformat-rs": rs && [{ path: rs, content: `${g.show(commit, rs)}\nfn gate_acceptance_misformatted ( ) {let x=1;}\n` }],
|
|
1366
|
+
"secret-file": [{ path: "docs/gate-acceptance-secret.txt", content: `token = "${["gh", "p_"].join("")}${"A1b2C3d4E5f6G7h8I9j0K1l2M3n4O5p6Q7r8"}"\n` }],
|
|
1367
|
+
"profile-dev": toml && [{ path: toml, content: `${g.show(commit, toml)}\n[profile.dev]\nopt-level = 1\n` }],
|
|
1368
|
+
"extra-workspace": [{ path: "gate-acceptance-extra/Cargo.toml", content: "[workspace]\nmembers = []\n" }],
|
|
1369
|
+
bypass: null, "no-broker": null,
|
|
1370
|
+
};
|
|
1371
|
+
const recipe = recipes[n.build];
|
|
1372
|
+
let c = commit;
|
|
1373
|
+
if (n.build === "bypass") {
|
|
1374
|
+
const a = await runGate({ gate, cwd: g.canonical, args: ["--to", "check", "--commit", commit, "--no-cache"] });
|
|
1375
|
+
const envRun = await runGate({ gate, cwd: g.canonical, args: ["--to", "check", "--commit", commit], env: { ...process.env, RK_GATE_CACHE: "0" } });
|
|
1376
|
+
const r1 = finishRun({ label: "N13:flag", stage: "check", commit, full: ["--no-cache"], res: a, receiptPath: null, step: "S7", extra: { negative: "N13", negativeResult: bypassRefused({ exit: a.exit, text: a.log }) } });
|
|
1377
|
+
const r2 = finishRun({ label: "N13:env", stage: "check", commit, full: ["RK_GATE_CACHE=0"], res: envRun, receiptPath: null, step: "S7", extra: { negative: "N13", negativeResult: bypassRefused({ exit: envRun.exit, text: envRun.log }) } });
|
|
1378
|
+
check("S7", "N13 --no-cache refused", r1.negativeResult); check("S7", "N13 RK_GATE_CACHE=0 refused", r2.negativeResult);
|
|
1379
|
+
continue;
|
|
1380
|
+
}
|
|
1381
|
+
if (recipe === undefined || recipe === null && n.build !== "no-broker") { stepOf("S7").notes.push(`${n.id}: unchecked: no tracked file to edit (${NEEDS_FIXTURE})`); stepOf("S7").checks.push("unchecked"); continue; }
|
|
1382
|
+
if (recipe) c = g.witnessCommit(commit, n.id.toLowerCase(), recipe);
|
|
1383
|
+
const r = await doRun({ label: `${n.id}`, stage: "compile", commit: c, args: n.args ?? [], ladder: false, step: "S7", extra: { negative: n.id } });
|
|
1384
|
+
r.negativeResult = assertNegative({ exit: r.exit, text: r.log, signals: n.signals, laterStages: n.later, receipt: r.receipt, rows: r.rows, expectRows: n.expectRows ?? [] });
|
|
1385
|
+
check("S7", `${n.id} ${n.title}`, r.negativeResult);
|
|
1386
|
+
}
|
|
1387
|
+
|
|
1388
|
+
// S8 kill and recover ---------------------------------------------------------------------------------------------------------------------
|
|
1389
|
+
// 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
|
+
// 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) {
|
|
1392
|
+
const label = `S8:${k.id}`; const logPath = path.join(outDir, `${label.replace(/[^\w.-]/g, "_")}.log`);
|
|
1393
|
+
const stage = k.id === "K02" ? "check" : "compile"; const receiptPath = path.join(outDir, `${label.replace(/[^\w.-]/g, "_")}.receipt.json`);
|
|
1394
|
+
const killed = await killDuring({ gate, cwd: g.canonical, args: ["--to", stage, "--commit", commit, "--receipt-out", receiptPath], signal: k.signal, waitFor: readOwner, afterMs: killAfterMs });
|
|
1395
|
+
fs.writeFileSync(logPath, killed.log);
|
|
1396
|
+
const before = readOwner();
|
|
1397
|
+
const dry = before ? runDry(ownerFile) : { exit: null, text: "" };
|
|
1398
|
+
const next = await doRun({ label: `${label}:next`, stage, ladder: true, step: "S8" });
|
|
1399
|
+
const after = readOwner();
|
|
1400
|
+
const recovery = assertRecovery({ signal: k.signal, before, dry, next: { exit: next.exit, text: next.log }, after, exitedBySignal: exitedBySignal({ signal: killed.signal, exit: killed.exit, killSignal: k.signal, platform: process.platform }) });
|
|
1401
|
+
runs[label] = { label, kill: k.id, stage, recovery, logPath, ownerPath: ownerFile, exit: killed.exit, signal: killed.signal, log: killed.log, ladder: false, args: [] };
|
|
1402
|
+
check("S8", `${k.id} ${k.signal}: dead owner reclaimed by the next run, which passes`, recovery);
|
|
1403
|
+
}
|
|
1404
|
+
|
|
1405
|
+
// S9 ---------------------------------------------------------------------------------------------------------------------------------------
|
|
1406
|
+
if (wanted.includes("S9")) {
|
|
1407
|
+
const brokerEnd = runningBrokerProcess() ?? null; const owner = readOwner();
|
|
1408
|
+
const snapshotDirCheck = snapshotDirProblems({ key, before: ctx.s0?.snapshots ?? null, after: listDirs(snapRoot) });
|
|
1409
|
+
ctx.s9 = { stash: g.stash(), status: g.status(), worktree: g.worktrees(), snapshotDirCheck, broker: brokerEnd, ownerPath: ownerFile, ownerClean: { ok: owner === null, problems: owner === null ? [] : [`owner record stands after the run: handle ${owner.handle}, pid ${owner.pid}`] } };
|
|
1410
|
+
check("S9", "git status --short equals S0", sameListing("git status --short", ctx.s0.status, ctx.s9.status));
|
|
1411
|
+
check("S9", "git worktree list equals S0", sameListing("git worktree list", ctx.s0.worktree, ctx.s9.worktree));
|
|
1412
|
+
check("S9", "git stash list equals S0", sameListing("git stash list", ctx.s0.stash, ctx.s9.stash));
|
|
1413
|
+
check("S9", "no owner record stands", ctx.s9.ownerClean);
|
|
1414
|
+
check("S9", "one snapshot dir for the repository and no new one", snapshotDirCheck);
|
|
1415
|
+
check("S9", "the broker process is the one of S0", brokerUnchanged(ctx.s0.broker, brokerEnd));
|
|
1416
|
+
const markers = Object.values(runs).flatMap((r) => publicationMarkers(r.log ?? ""));
|
|
1417
|
+
check("S9", "no upload or publish marker in any log", { ok: markers.length === 0, problems: markers.map((m) => `upload or publish marker in a log: ${m.slice(0, 120)}`) });
|
|
1418
|
+
}
|
|
1419
|
+
|
|
1420
|
+
// clause evaluation -----------------------------------------------------------------------------------------------------------------------
|
|
1421
|
+
for (const id of Object.keys(CHECKS)) {
|
|
1422
|
+
if (["GC-I22", "GC-I18"].includes(id) && wanted.includes("S0")) continue; // already evaluated at S0
|
|
1423
|
+
let r; try { r = CHECKS[id](ctx); } catch (e) { r = { status: "fail", evidence: [], problems: [`assertion threw: ${e.message}`] }; }
|
|
1424
|
+
clauseChecks[id].push(...(Array.isArray(r) ? r : [r]));
|
|
1425
|
+
}
|
|
1426
|
+
const notes = [`out ${outDir}`, "timing is relative and informational: the contract gives no latency threshold"];
|
|
1427
|
+
if (!allowInstall) notes.push(`--to ${INSTALL_STAGES.join(" and --to ")} not run: ${NEEDS_INSTALL_APPROVAL}`);
|
|
1428
|
+
const result = 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 });
|
|
1429
|
+
result.timings = Object.fromEntries(Object.entries(runs).map(([k, v]) => [k, { ms: v.ms, stages: v.timings }]));
|
|
1430
|
+
fs.writeFileSync(path.join(outDir, "result.json"), `${JSON.stringify(result, null, 2)}\n`);
|
|
1431
|
+
const summary = formatSummary(result); fs.writeFileSync(path.join(outDir, "summary.txt"), `${summary}\n`);
|
|
1432
|
+
console.log(summary); console.log(`result: ${path.join(outDir, "result.json")}`);
|
|
1433
|
+
return result.ok ? 0 : 1;
|
|
1434
|
+
}
|
|
1435
|
+
|
|
1436
|
+
function runDry(ownerFile) {
|
|
1437
|
+
const r = spawnSync(process.execPath, [path.join(here, "ownership-recover.mjs"), ownerFile], { encoding: "utf8" });
|
|
1438
|
+
return { exit: r.status, text: `${r.stdout ?? ""}${r.stderr ?? ""}` };
|
|
1439
|
+
}
|
|
1440
|
+
|
|
1441
|
+
if (process.argv[1] && fs.realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
|
1442
|
+
main(process.argv.slice(2)).then((code) => process.exit(code), (e) => { console.error(`gate-acceptance: ${e.stack ?? e}`); process.exit(2); });
|
|
1443
|
+
}
|