@rightkit/release 0.6.57 → 0.6.62

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/README.md +4 -0
  2. package/acceptance-admission.mjs +104 -0
  3. package/acceptance-launch.mjs +234 -0
  4. package/acceptance-lines.mjs +1254 -0
  5. package/acceptance-result.mjs +77 -0
  6. package/acceptance-rows.mjs +47 -0
  7. package/admission-files.mjs +2 -0
  8. package/affected-units.mjs +17 -0
  9. package/app-check.mjs +6 -2
  10. package/app-closure.mjs +3 -1
  11. package/bin/rightkit-gate.mjs +552 -124
  12. package/broker-admission.mjs +45 -2
  13. package/broker-pins.mjs +11 -1
  14. package/broker-toolchain.mjs +113 -0
  15. package/cargo-profile-contract.mjs +7 -2
  16. package/class-a-cache-history.mjs +170 -0
  17. package/cli/right-release.mjs +0 -0
  18. package/code-closure.mjs +24 -0
  19. package/config-inspect.mjs +6 -0
  20. package/consumer-contracts.mjs +3 -1
  21. package/contract-nn.json +166 -0
  22. package/deterministic-scans.mjs +835 -112
  23. package/feature-coverage.mjs +109 -82
  24. package/feature-partition.mjs +76 -0
  25. package/forbidden-literals.mjs +78 -0
  26. package/gate/calls.mjs +121 -0
  27. package/gate/compile.mjs +190 -0
  28. package/gate/crate-results.mjs +127 -0
  29. package/gate/run-calls.mjs +241 -0
  30. package/gate/tests.mjs +234 -0
  31. package/gate-coverage.mjs +12 -3
  32. package/gate-release-admission.mjs +200 -0
  33. package/gate-seam.mjs +100 -4
  34. package/gate-serve.mjs +179 -34
  35. package/gate-stages.mjs +59 -0
  36. package/legacy-contract-receipt.mjs +809 -0
  37. package/local-publish.mjs +2 -4
  38. package/local-runtime.mjs +2 -2
  39. package/nsis-payload.mjs +4 -3
  40. package/ownership-applicability.mjs +5 -0
  41. package/ownership-class-rules.mjs +19 -8
  42. package/ownership-mandatory-set.json +15 -21
  43. package/ownership-mandatory-set.mjs +19 -4
  44. package/package.json +14 -8
  45. package/probe-memo.mjs +252 -0
  46. package/publication-artifacts.mjs +56 -2
  47. package/publish-local-npm.mjs +3 -0
  48. package/publish-update.mjs +2 -2
  49. package/receipt-signature.mjs +40 -0
  50. package/release.mjs +47 -29
  51. package/resident-answers.mjs +66 -0
  52. package/rightkit-ownership.json +20 -11
  53. package/rightkit-versions.json +349 -183
  54. package/runtime-bundle-stage.mjs +146 -0
  55. package/scan-digest.mjs +28 -4
  56. package/seam-broker.mjs +8 -1
  57. package/shell-contract.mjs +23 -2
  58. package/snapshot-changes.mjs +106 -0
  59. package/snapshot-check.mjs +17 -13
  60. package/snapshot-dependency-reuse.mjs +186 -14
  61. package/snapshot-git.mjs +17 -1
  62. package/snapshot-metadata.mjs +155 -3
  63. package/snapshot.mjs +89 -12
  64. package/spawn-ledger.mjs +21 -2
  65. package/stage-sidecar.mjs +231 -19
  66. package/suite-trust-roots.mjs +2 -2
  67. package/test-env.mjs +26 -0
  68. package/tool-version-memo.mjs +46 -0
  69. package/win-package-recipe.mjs +11 -0
  70. package/bin/darwin/rightkit-swap +0 -0
  71. package/gate-acceptance.mjs +0 -3362
package/README.md CHANGED
@@ -967,6 +967,10 @@ files, base Tauri config content & app-specific default-feature restrictions rem
967
967
 
968
968
  `right-release init --name <Product Name> --id <reverse.dns.bundle.id> [--slug <lowercase>] [--dir <root>] [--dry-run]` renames the desktop app template identity in place (see `init-command.mjs`); it runs no gate or build. Besides the text files it renames `Cargo.lock` and re-sorts it the way cargo writes it (so `cargo --locked` accepts the renamed lock), carries the renamed lock's new digest into each `<lock> sha256 <hex>` / `sha256=<hex>` field of a notice `notice-lock-digest` (CA-14) judges whose lock resolves to it (the same text in reports, evidence, archives or source is left alone), recomputes the digests in `legal/legal-manifest.json` for the documents the rename changed (a changed material document means `legal-snapshot` must run again), keeps the `r2-rightapps` distribution service name, and prints the steps only a person can do: `pnpm install`, the doctor, the legal host and text, and registering the new repository on each host (`ownership-repositories.json` and its byte copy under `packages/build-control-policy`, then `right-release ownership trust-refresh` on the Mac and the Dell, which needs a person with administrator rights).
969
969
 
970
+ ### Release config inspection
971
+
972
+ `import { inspectReleaseConfig } from "@rightkit/release/config-inspect.mjs"` exposes the strict synchronous M24 JSON loader for read-only consumers. `inspectReleaseConfig(file)` returns `{ config, configPath, appRoot, sha256, inputs, lineOf }` after template expansion and pipeline admission. It accepts no loader options, refuses legacy executable config files and throws the loader's errors; it reads declared input files but runs no config commands.
973
+
970
974
  The release config is `right-release.config.json` (M24, `release-config.mjs`): every command that reads one defaults to it when it sits beside the working directory, loads a `.json` path through the strict loader, and still imports a legacy `right-release.config.mjs` for an app that has not moved. `{{localAppData}}` in a JSON config is `%LOCALAPPDATA%` on Windows and `<home>/AppData/Local` elsewhere.
971
975
 
972
976
  `right-release pe digest <file> [--algorithm sha256|sha384|sha512] [--json]` prints the signature-independent PE content digest (Authenticode image hash: CheckSum, certificate table entry and certificate data excluded, so signing, re-signing and timestamping do not change it). `right-release pe imports <file> [--allow dll,...] [--allow-file <path>] [--json]` lists regular and delay-load imports and exits 1 when any is outside the allow list (case-insensitive; a trailing `*` allows a prefix such as `api-ms-win-*`; no allow list refuses every import). SDK: `peContentDigest(bytes)` and `verifyImportClosure(bytes, allowedDlls)` in `pe-content.mjs`.
@@ -0,0 +1,104 @@
1
+ // Admission of a gate-package release judged by the twelve-line result (docs/GATE-CONTRACT.md GC-A27, rightkit#1514 step 9; design table
2
+ // D:/scratch/loop-review/twelve-line-step9/design-table.md). Run where the archive is about to be published, with no broker: it judges only what it is handed.
3
+ // It refuses unless every one of the following holds (default refuse).
4
+ // 1. The record is a rightkit.acceptance-result/1 (the judge's --result file).
5
+ // 2. Its lines are exactly the checkout's GC-A27 table: the twelve ids, in order, with the sentences character for character.
6
+ // 3. Every verdict is "pass" and `pass` says so.
7
+ // 4. The files that judged the run (acceptance-lines.mjs, its test, acceptance-launch.mjs) hash to this checkout's.
8
+ // 5. The contract text is this checkout's.
9
+ // 6. It is for the release commit and that commit's tree.
10
+ // 7. The host is one the committed pipeline file pins (key, key id, host, broker digest).
11
+ // 8. The run was of the archive's gate: the sealed gate's manifest and source record hash to gate.sealedSha256 and name exactly the archive in question.
12
+ // 9. The broker's claims: the list is not empty; each claim is in the bundle with the listed hash, is only { id, publication }, carries the pinned broker's
13
+ // signature for that host and build, is for that job id, and names the result's commit and tree.
14
+ // What this proves, and no more: real jobs of this commit and tree went through that host's broker, and the judge, as this checkout has it, found every line
15
+ // true from that run's own records. A publication claim carries no time and the gate's nonces in a twelve-line run are not derived from the run, so a claim is
16
+ // bound to the result by its signed commit and tree, not by the run. The verdict is the judge's own judgement and the result says so (nnBasis).
17
+ import fs from "node:fs";
18
+ import path from "node:path";
19
+ import { fileURLToPath } from "node:url";
20
+ import { createHash } from "node:crypto";
21
+ import { archiveIdentity, archiveOfSeal } from "./legacy-contract-receipt.mjs";
22
+ import { readAcceptanceLines } from "./acceptance-lines.mjs";
23
+ import { verifyPublicationClaim } from "./receipt-signature.mjs";
24
+
25
+ export const ACCEPTANCE_RESULT_SCHEMA = "rightkit.acceptance-result/1";
26
+ /** The files the twelve-line judgement is made of, relative to the package. */
27
+ export const JUDGE_FILES = Object.freeze(["acceptance-lines.mjs", "acceptance-lines.test.mjs", "acceptance-launch.mjs"]);
28
+ const here = path.dirname(fileURLToPath(import.meta.url));
29
+ const sha256 = (bytes) => createHash("sha256").update(bytes).digest("hex");
30
+ const PLATFORM_OF = Object.freeze({ mac: "darwin", dell: "win32" });
31
+
32
+ /** The sha256 of each judge file in `dir` (this package by default); a file that cannot be read is null. */
33
+ export function judgeFileHashes(dir = here) {
34
+ return Object.fromEntries(JUDGE_FILES.map((name) => { try { return [name, sha256(fs.readFileSync(path.join(dir, name)))]; } catch { return [name, null]; } }));
35
+ }
36
+
37
+ /**
38
+ * `result`: the parsed acceptance result. `readJob(requestId)`: the bytes of that job's claim from the bundle (throws when absent). `archiveBytes`: the archive in
39
+ * question. `commit`, `tree`: the release commit and its tree. `pipeline`: ci/rk-pipeline.json (parsed). `contractText`, `contractSha256`: of this checkout.
40
+ * `judgeFiles`: judgeFileHashes() of this checkout. `manifestBytes`, `sourceBytes`: the sealed gate's manifest and source record. Returns { ok, problems, facts }.
41
+ */
42
+ export function admitAcceptanceResult({ result, readJob, archiveBytes, commit, tree, pipeline, contractText, contractSha256, judgeFiles, manifestBytes = null, sourceBytes = null }) {
43
+ const problems = [];
44
+ const facts = { host: result?.host ?? null, version: null, sealedSha256: result?.gate?.sealedSha256 ?? null, archiveSha256: null, jobsListed: 0, jobsVerified: 0, signedSteps: [], nnBasis: "twelve-line-judge" };
45
+ // 1
46
+ if (result?.schema !== ACCEPTANCE_RESULT_SCHEMA) { problems.push(`the record's schema is ${JSON.stringify(result?.schema ?? null)}, not ${ACCEPTANCE_RESULT_SCHEMA}`); return { ok: false, problems, facts }; }
47
+ // 2 and 3: the twelve lines as the checkout's table has them, every one a pass
48
+ let want = []; try { want = readAcceptanceLines(contractText); } catch (e) { problems.push(`this checkout's GC-A27 table cannot be read (${e.message})`); }
49
+ const lines = Array.isArray(result.lines) ? result.lines : [];
50
+ if (want.length && (lines.length !== want.length || want.some((w, i) => lines[i]?.id !== w.id))) problems.push(`the result does not carry the twelve lines ${want.map((w) => w.id).join(", ")} in that order (it carries ${lines.map((l) => l?.id).join(", ") || "none"})`);
51
+ else for (const [i, w] of want.entries()) {
52
+ if (lines[i].text !== w.text) problems.push(`${w.id}: the sentence in the result is not this checkout's text`);
53
+ if (lines[i].verdict !== "pass") problems.push(`${w.id} is ${lines[i].verdict}, not "pass"`);
54
+ }
55
+ if (result.pass !== true) problems.push(`the result's pass is ${JSON.stringify(result.pass ?? null)}, not true`);
56
+ // 4 and 5: judged by this checkout's judge, against this checkout's contract
57
+ for (const name of JUDGE_FILES) {
58
+ const have = result.judgeFiles?.[name]; const mine = judgeFiles?.[name] ?? null;
59
+ if (typeof have !== "string" || mine === null || have !== mine) problems.push(`judge file ${name} is ${have ?? "absent"} in the result, this checkout's is ${mine ?? "absent"}`);
60
+ }
61
+ if (result.contractSha256 !== contractSha256) problems.push(`the contract the result was judged against (${String(result.contractSha256).slice(0, 12)}) is not this checkout's (${String(contractSha256).slice(0, 12)})`);
62
+ // 6
63
+ if (!commit || !/^[0-9a-f]{40}$/.test(commit)) problems.push("no release commit was given");
64
+ else if (result.commit !== commit) problems.push(`the result is for commit ${String(result.commit).slice(0, 12)}, the release commit is ${commit.slice(0, 12)}`);
65
+ if (!tree) problems.push("no tree for the release commit was given");
66
+ else if (result.tree !== tree) problems.push(`the result's tree ${String(result.tree).slice(0, 12)} is not the release commit's tree ${tree.slice(0, 12)}`);
67
+ // 7
68
+ const platform = PLATFORM_OF[result.host];
69
+ const pins = platform ? pipeline?.attestation?.[platform] : null;
70
+ if (!platform) problems.push(`the result is from ${JSON.stringify(result.host ?? null)}, not a host this repository names`);
71
+ else if (!pins || typeof pins.publicKey !== "string" || typeof pins.keyId !== "string" || typeof pins.host !== "string" || typeof pins.brokerDigest !== "string") problems.push(`ci/rk-pipeline.json has no complete attestation.${platform} (publicKey, keyId, host, brokerDigest)`);
72
+ // 8: the run was of the archive's gate
73
+ let archive = null;
74
+ try { archive = archiveIdentity(archiveBytes); facts.archiveSha256 = archive.sha256; } catch (e) { problems.push(`the archive in question cannot be hashed (${e.message})`); }
75
+ if (!manifestBytes || !sourceBytes) problems.push("the sealed gate's manifest and source record were not handed over, so nothing ties the archive to the run's gate");
76
+ else {
77
+ const linked = archiveOfSeal({ sealedSha256: result.gate?.sealedSha256, manifestBytes, sourceBytes });
78
+ for (const p of linked.problems) problems.push(`seal to archive: ${p}`);
79
+ if (linked.ok) {
80
+ facts.version = linked.archive.version ?? null;
81
+ if (archive && (linked.archive.sha256 !== archive.sha256 || linked.archive.integrity !== archive.integrity)) problems.push(`seal to archive: the tested gate was installed from the archive ${linked.archive.sha256}, the archive in question is ${archive.sha256}`);
82
+ }
83
+ }
84
+ if (typeof result.gate?.sealedSha256 !== "string" || !/^[0-9a-f]{64}$/.test(result.gate.sealedSha256)) problems.push("the result names no sealed gate (gate.sealedSha256), so the run is not tied to an installed gate");
85
+ // 9: the broker's claims
86
+ const jobs = Array.isArray(result.jobs) ? result.jobs : null;
87
+ if (!jobs) problems.push("the result lists no broker jobs (jobs is missing)");
88
+ else if (jobs.length === 0) problems.push("the result lists no broker job at all: nothing in it is signed");
89
+ for (const [i, job] of (jobs ?? []).entries()) {
90
+ facts.jobsListed += 1;
91
+ const name = `job ${job?.requestId ?? `#${i + 1}`}`;
92
+ if (typeof job?.requestId !== "string" || !/^[A-Za-z0-9._-]{1,128}$/.test(job.requestId)) { problems.push(`${name}: its job id cannot name a file`); continue; }
93
+ if (typeof job.claimSha256 !== "string") { problems.push(`${name}: it carries no claim hash`); continue; }
94
+ let bytes; try { bytes = readJob(job.requestId); } catch (e) { problems.push(`${name}: its claim is not in the bundle (${e.code ?? e.message})`); continue; }
95
+ if (sha256(bytes) !== job.claimSha256) { problems.push(`${name}: the claim in the bundle is not the one listed (sha256 differs)`); continue; }
96
+ let doc; try { doc = JSON.parse(String(bytes)); } catch { problems.push(`${name}: its claim is not JSON`); continue; }
97
+ if (Object.keys(doc ?? {}).some((k) => k !== "id" && k !== "publication")) { problems.push(`${name}: the bundle holds more than the claim (only id and publication may be handed over)`); continue; }
98
+ let payload; try { payload = verifyPublicationClaim(doc, pins, job.requestId); } catch (e) { problems.push(`${name}: ${e.code ? `${e.code}: ` : ""}${e.message}`); continue; }
99
+ if (payload.gate?.commit !== result.commit) { problems.push(`${name}: the broker signed commit ${String(payload.gate?.commit).slice(0, 12)}, the result is for ${String(result.commit).slice(0, 12)}`); continue; }
100
+ if (payload.gate?.tree !== result.tree) { problems.push(`${name}: the broker signed tree ${String(payload.gate?.tree).slice(0, 12)}, the result is for ${String(result.tree).slice(0, 12)}`); continue; }
101
+ facts.jobsVerified += 1;
102
+ }
103
+ return { ok: problems.length === 0, problems, facts };
104
+ }
@@ -0,0 +1,234 @@
1
+ // The launcher of a gate run judged by the twelve lines (GATE-CONTRACT GC-A27, rightkit#1514 step 3). The acceptance test takes nothing from
2
+ // the gate's own reporting (Adrian, 2026-11-21), so this launcher, not the gate, records the run: it owns the selected commit, the run id, the
3
+ // clock, the exit, the run lock, the Class A lane count, the time limit pinned before the gate starts, the run kind (derived from the stage the gate
4
+ // is asked for, never a label), the snapshot root, and its own record of the previous launched run (the baseline commit, and a fingerprint of the
5
+ // gate code, tools and environment that git cannot show). It keeps the gate's output for people. After the gate ends it exports the operating
6
+ // system's record of every program that started and exited in the run's window.
7
+ //
8
+ // node acceptance-launch.mjs --out <run dir> --commit <sha> --receipts <broker receipts dir> [--kind <stage>] [--limits <file>] [--lanes <n>]
9
+ // [--repo <dir>] [--gate <bin/rightkit-gate.mjs>] [--lock <file>] -- <gate arguments>
10
+ //
11
+ // The run folder holds launch.json (this record), before/receipts.txt, processes.json and gate.log. Beside the run folder: acceptance-launch.lock
12
+ // (the live run) and acceptance-launch.last.json (the last launched run, kept after it ends, so the next run has its predecessor and baseline even
13
+ // when the launcher's lock was released). A live holder refuses the run (exit 3, nothing started). A dead holder is the run before this one, killed:
14
+ // this run takes the lock over (one rename, so exactly one successor wins) and names it in `previous`.
15
+ import { execFileSync, spawn } from "node:child_process";
16
+ import crypto from "node:crypto";
17
+ import fs from "node:fs";
18
+ import os from "node:os";
19
+ import path from "node:path";
20
+ import { fileURLToPath } from "node:url";
21
+
22
+ export const LAUNCH_SCHEMA = "rightkit.acceptance-launch/3";
23
+ const here = path.dirname(fileURLToPath(import.meta.url));
24
+ const mono = () => process.hrtime.bigint().toString();
25
+ const alive = (pid) => { if (!Number.isInteger(pid) || pid <= 0) return false; try { process.kill(pid, 0); return true; } catch (e) { return e.code === "EPERM"; } };
26
+ const sha256 = (b) => crypto.createHash("sha256").update(b).digest("hex");
27
+
28
+ /**
29
+ * Takes the run lock. Returns { previous } (the dead holder this run took over, or null) or { refused } when a live run holds it or another launcher
30
+ * claimed the same dead holder first. Takeover is one exclusive create (open with wx, which Windows maps to CREATE_NEW) of a claim file named by the dead
31
+ * holder's own identity (its run id, or its lock file's write time when it cannot be read): of any number of launchers that saw the same dead holder
32
+ * exactly one creates the claim, the others get EEXIST and do not start. A launcher that saw the holder after it was replaced sees a live holder, or a
33
+ * different identity, and so claims a different file. Nothing is deleted by a contender but the dead holder's own lock, moved aside.
34
+ */
35
+ export function takeLaunchLock(file, holder, { isAlive = alive, fsApi = fs } = {}) {
36
+ fsApi.mkdirSync(path.dirname(file), { recursive: true });
37
+ const create = () => { try { fsApi.writeFileSync(file, `${JSON.stringify(holder)}
38
+ `, { flag: "wx" }); return true; } catch (e) { if (e.code !== "EEXIST") throw e; return false; } };
39
+ if (create()) return { previous: null };
40
+ let held = null; try { held = JSON.parse(fsApi.readFileSync(file, "utf8")); } catch { held = null; }
41
+ let written = 0; try { written = Math.trunc(fsApi.statSync(file).mtimeMs * 1000); } catch { written = 0; }
42
+ if (held && isAlive(held.pid)) return { refused: `run ${held.runId} (pid ${held.pid}) holds ${file}` };
43
+ const identity = `${held?.runId ?? "unreadable"}.${held?.pid ?? 0}.${written}`.replace(/[^\w.-]/g, "_");
44
+ const claim = `${file}.successor.${identity}`;
45
+ try { fsApi.writeFileSync(claim, `${JSON.stringify({ runId: holder.runId, pid: holder.pid })}
46
+ `, { flag: "wx" }); }
47
+ catch (e) { if (e.code === "EEXIST") return { refused: `another launcher already claimed the successor of ${held?.runId ?? "the unreadable holder"} (${path.basename(claim)})` }; throw e; }
48
+ // This launcher alone holds the claim for that dead holder. The holder is read again: a live run at the path now is not the one that was claimed.
49
+ let now = null; try { now = JSON.parse(fsApi.readFileSync(file, "utf8")); } catch { now = null; }
50
+ if (now && isAlive(now.pid) && now.runId !== held?.runId) return { refused: `run ${now.runId} (pid ${now.pid}) holds ${file}` };
51
+ const aside = `${file}.dead.${identity}`;
52
+ try { fsApi.renameSync(file, aside); } catch (e) { if (e.code === "ENOENT") return { refused: `${file} was taken over before this launcher moved it` }; throw e; }
53
+ if (!create()) return { refused: `another launcher created ${file} after the dead holder was moved aside` };
54
+ return { previous: held ? { runId: held.runId ?? null, out: held.out ?? null, pid: held.pid ?? null, reclaimed: true } : { runId: null, out: null, pid: null, reclaimed: true, unreadable: true } };
55
+ }
56
+
57
+ /**
58
+ * What git cannot show about a run, recorded before it starts: the gate code (the tree id of packages/release at the selected commit), the node and
59
+ * platform, and the version output of the tools the gate runs. Two runs are the same kind of baseline only when every field is present and equal.
60
+ */
61
+ export function fingerprintOf({ repo, commit, run = execFileSync, platform = process.platform }) {
62
+ const probe = (cmd, args) => { try { return String(run(cmd, args, { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], windowsHide: true, timeout: 20_000 })).trim().split(/\r?\n/)[0]; } catch { return null; } };
63
+ const gateCodeTree = probe("git", ["-C", repo, "rev-parse", `${commit}:packages/release`]);
64
+ const tools = Object.fromEntries([["rustc", ["-vV"]], ["rustfmt", ["--version"]], ["cargo", ["--version"]], ["cargo-deny", ["--version"]], ["pnpm", ["--version"]], ["git", ["--version"]]].map(([c, a]) => [c, probe(c, a)]));
65
+ return { gateCodeTree, node: process.version, platform, tools };
66
+ }
67
+ const complete = (f) => !!f && f.gateCodeTree !== null && Object.values(f.tools ?? {}).every((v) => typeof v === "string") && typeof f.node === "string";
68
+ export const sameFingerprint = (a, b) => complete(a) && complete(b) && JSON.stringify(a) === JSON.stringify(b);
69
+
70
+ /**
71
+ * The operating system's record of the programs that started and exited in [from, to]: Windows Security events 4688 and 4689, read with
72
+ * Get-WinEvent (Event Log Readers is enough). The record says how far the log had advanced (its newest event) and whether it reaches back to the
73
+ * run's start (its oldest), and every event it keeps has a process id and a time.
74
+ */
75
+ /**
76
+ * The Security log's events as the system tool wevtutil writes them, parsed here: no PowerShell object in between. One query gives every event of the run's window (the record
77
+ * ids prove none was lost), one the oldest event and one the newest. Windows PowerShell 5.1's ConvertTo-Json left a quote unescaped inside a command line that was itself JSON
78
+ * and broke a whole run's record (run7: a 6.4 MB document failed to parse at 3.29 MB), and Get-WinEvent with ToXml took over 60 ms an event (a 150 s window took 359 s);
79
+ * wevtutil takes seconds, and XML escaping keeps every character of a command line exact.
80
+ */
81
+ const XML_ENTITIES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'" };
82
+ const unxml = (s) => String(s).replace(/&#x([0-9a-f]+);/gi, (_, h) => String.fromCodePoint(Number.parseInt(h, 16))).replace(/&#(\d+);/g, (_, d) => String.fromCodePoint(Number(d))).replace(/&(amp|lt|gt|quot|apos);/g, (_, n) => XML_ENTITIES[n]);
83
+ /** wevtutil's XML text into [{ id, recordId, time, data }], `data` holding each named Data value (null when it has no text). */
84
+ export function parseWevtutilEvents(text) {
85
+ const out = [];
86
+ for (const m of String(text).matchAll(/<Event[ >][\s\S]*?<\/Event>/g)) {
87
+ const x = m[0];
88
+ const id = /<EventID[^>]*>(\d+)<\/EventID>/.exec(x); const rec = /<EventRecordID>(\d+)<\/EventRecordID>/.exec(x); const time = /<TimeCreated[^>]*SystemTime=['"]([^'"]+)['"]/.exec(x);
89
+ const data = {};
90
+ for (const d of x.matchAll(/<Data Name=['"]([^'"]+)['"]\s*(?:\/>|>([\s\S]*?)<\/Data>)/g)) data[d[1]] = d[2] === undefined || d[2] === "" ? null : unxml(d[2]);
91
+ out.push({ id: id ? Number(id[1]) : null, recordId: rec ? Number(rec[1]) : null, time: time ? time[1] : null, data });
92
+ }
93
+ return out;
94
+ }
95
+ export function exportWindowsProcesses(from, to, { run = execFileSync } = {}) {
96
+ const problems = []; let oldest; let newest; let all;
97
+ const wev = (args) => run("wevtutil.exe", ["qe", "Security", ...args, "/f:xml"], { encoding: "utf8", windowsHide: true, maxBuffer: 1024 * 1024 * 1024 });
98
+ try {
99
+ oldest = parseWevtutilEvents(wev(["/c:1", "/rd:false"]))[0]?.time ?? null;
100
+ newest = parseWevtutilEvents(wev(["/c:1", "/rd:true"]))[0]?.time ?? null;
101
+ all = parseWevtutilEvents(wev([`/q:*[System[TimeCreated[@SystemTime>='${from}' and @SystemTime<='${to}']]]`]));
102
+ }
103
+ catch (e) { return { kind: "windows-security", from, to, newest: null, continuous: false, events: [], problems: [`the Security log could not be read (${String(e.stderr || e.message).trim().split(/\r?\n/)[0]})`] }; }
104
+ const ids = all.map((e) => e.recordId).filter(Number.isInteger).sort((a, b) => a - b);
105
+ const continuous = all.every((e) => Number.isInteger(e.recordId)) && (ids.length <= 1 || ids[ids.length - 1] - ids[0] + 1 === ids.length);
106
+ const raw = { oldest, newest, continuous, records: ids.length, events: all.filter((e) => e.id === 4688 || e.id === 4689) };
107
+ if (!(Date.parse(raw?.oldest) <= Date.parse(from))) problems.push(`the Security log's oldest event (${raw?.oldest}) is newer than the run's start, so events may have been overwritten`);
108
+ if (raw?.continuous !== true) problems.push(`the Security log's record ids have a break inside the run's window (${raw?.records ?? "?"} records), so a start or exit may have been lost`);
109
+ if (!(Date.parse(raw?.newest) >= Date.parse(to) - 5000) && !(Date.parse(raw?.newest) >= Date.parse(from))) problems.push(`the Security log's newest event (${raw?.newest}) is older than the run's window`);
110
+ // A value that is not a hex or decimal number is unknown (null), never zero: a missing exit status must not read as success.
111
+ const hex = (v) => (typeof v === "string" && /^0x[0-9a-f]+$/i.test(v) ? Number.parseInt(v, 16) : typeof v === "string" && /^\d+$/.test(v) ? Number(v) : typeof v === "number" ? v : null);
112
+ const events = (Array.isArray(raw?.events) ? raw.events : raw?.events ? [raw.events] : []).map((e) => e.id === 4688
113
+ ? { id: 4688, time: e.time, pid: hex(e.data.NewProcessId), ppid: hex(e.data.ProcessId), exe: e.data.NewProcessName, commandLine: e.data.CommandLine ?? null }
114
+ : { id: 4689, time: e.time, pid: hex(e.data.ProcessId), exe: e.data.ProcessName, exit: hex(e.data.Status) });
115
+ const bad = events.filter((e) => !Number.isInteger(e.pid) || !Number.isFinite(Date.parse(e.time)) || (e.id === 4688 && !Number.isInteger(e.ppid)));
116
+ if (bad.length) problems.push(`${bad.length} event(s) have no usable process id, parent or time`);
117
+ if (events.some((e) => e.id === 4688 && (e.commandLine === null || e.commandLine === undefined))) problems.push("start events carry no command line (ProcessCreationIncludeCmdLine_Enabled is off)");
118
+ return { kind: "windows-security", from, to, newest: raw?.newest ?? null, continuous: raw?.continuous === true, events, problems };
119
+ }
120
+
121
+ /** The stage the launched gate is asked for: its `--to` value (the gate's own default is the check stage). */
122
+ export const kindOf = (gateArgs) => { const i = gateArgs.indexOf("--to"); return i < 0 ? "check" : gateArgs[i + 1] ?? null; };
123
+
124
+ /**
125
+ * A recursive listing of a folder as the file system shows it: relative path (forward slashes) -> [size, mtime in ms]. A folder that does not exist is an empty,
126
+ * known listing; one that cannot be read, or that holds more files than `cap`, is null (unknown). Nothing in it is read.
127
+ */
128
+ export function listFolder(dir, { cap = 200_000 } = {}) {
129
+ if (!dir) return null;
130
+ try { if (!fs.existsSync(dir)) return {}; } catch { return null; }
131
+ const out = {}; let n = 0;
132
+ const walk = (d, rel) => {
133
+ for (const e of fs.readdirSync(d, { withFileTypes: true })) {
134
+ const r = rel ? `${rel}/${e.name}` : e.name; const f = path.join(d, e.name);
135
+ if (e.isDirectory()) walk(f, r);
136
+ else if (e.isFile()) { n += 1; if (n > cap) throw new Error("too many files"); const st = fs.statSync(f); out[r] = [st.size, Math.trunc(st.mtimeMs)]; }
137
+ }
138
+ };
139
+ try { walk(dir, ""); } catch { return null; }
140
+ return out;
141
+ }
142
+ /** The gate's scan-result store, as the gate would choose it (RK_GATE_CACHE_DIR, else <git common dir>/rightkit-gate-cache), or null when the common dir cannot be found. */
143
+ export function cacheStoreDir(repo, env = process.env, run = execFileSync) {
144
+ if (env.RK_GATE_CACHE_DIR) return path.resolve(repo, env.RK_GATE_CACHE_DIR);
145
+ try { const common = String(run("git", ["-C", repo, "rev-parse", "--git-common-dir"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], windowsHide: true })).trim(); return common ? path.join(path.resolve(repo, common), "rightkit-gate-cache") : null; } catch { return null; }
146
+ }
147
+ /** The folders of the snapshot root that came into being or changed since `sinceMs`, each listed (the stat record of the snapshots at the gate's exit). */
148
+ export function statSnapshots(root, sinceMs, { cap = 200_000, entries = null } = {}) {
149
+ if (!root) return { root: null, dirs: {}, known: false };
150
+ let names; try { names = (entries ?? fs.readdirSync(root, { withFileTypes: true })).filter((e) => e.isDirectory()); } catch { return { root, dirs: {}, known: false }; }
151
+ const dirs = {}; let total = 0; let known = true;
152
+ for (const e of names) {
153
+ let st; try { st = fs.statSync(path.join(root, e.name)); } catch { known = false; continue; }
154
+ const files = listFolder(path.join(root, e.name), { cap: cap - total });
155
+ if (files === null) { dirs[e.name] = null; known = false; continue; }
156
+ total += Object.keys(files).length; dirs[e.name] = files;
157
+ }
158
+ return { root, dirs, known };
159
+ }
160
+
161
+ /** Starts one gate run and records it. Resolves with the gate's exit (or 128 + signal number). */
162
+ export async function launch({ out, commit, kind = null, receiptsDir, limits = null, lanes = null, repo = process.cwd(), gate = path.join(here, "bin", "rightkit-gate.mjs"), lock = null, gateArgs = [], env = process.env, spawnImpl = spawn, host = os.hostname(), exportProcesses = null, platform = process.platform, fingerprint = null, snapshotsRoot = null }) {
163
+ if (!out || !/^[0-9a-f]{40}$/.test(String(commit ?? "")) || !receiptsDir) throw new Error("launch needs --out, a full --commit sha and --receipts");
164
+ const derived = kindOf(gateArgs);
165
+ if (kind !== null && kind !== derived) throw new Error(`--kind ${kind} does not match the stage the gate is asked for (--to ${derived}); the time limit is chosen by what is run`);
166
+ const before = path.join(out, "before"); fs.mkdirSync(before, { recursive: true });
167
+ const runId = crypto.randomBytes(32).toString("hex");
168
+ const dir = path.dirname(path.resolve(out)); const lockFile = lock ?? path.join(dir, "acceptance-launch.lock"); const lastFile = path.join(dir, "acceptance-launch.last.json");
169
+ const taken = takeLaunchLock(lockFile, { runId, pid: process.pid, out: path.resolve(out), startedAt: new Date().toISOString() });
170
+ if (taken.refused) { process.stderr.write(`acceptance-launch: refused: ${taken.refused}; nothing started\n`); return 3; }
171
+ // The limit and the lanes are pinned now, before the gate runs, never chosen afterwards.
172
+ let limitMs = null; let limitsSha256 = null;
173
+ if (limits) { const body = fs.readFileSync(limits); limitsSha256 = sha256(body); const v = JSON.parse(body.toString("utf8"))[`${host}/${derived}`]; limitMs = Number.isFinite(v) ? v : null; }
174
+ const laneCount = Number.isInteger(lanes) && lanes > 0 ? lanes : (typeof os.availableParallelism === "function" ? os.availableParallelism() : os.cpus().length);
175
+ // The previous launched run, from the launcher's own record: its identity (whether or not the lock was released), the baseline commit, and whether
176
+ // this run is the same kind of baseline (gate code, tools, node and platform equal).
177
+ let last = null; try { last = JSON.parse(fs.readFileSync(lastFile, "utf8")); } catch { last = null; }
178
+ const fp = fingerprint ?? fingerprintOf({ repo, commit, platform });
179
+ const baseline = last ? { commit: last.commit ?? null, out: last.out ?? null, runId: last.runId ?? null, exit: last.exit ?? null, signal: last.signal ?? null, stable: sameFingerprint(last.fingerprint, fp) } : null;
180
+ const previous = taken.previous ?? (last ? { runId: last.runId ?? null, out: last.out ?? null, pid: null, reclaimed: false, fromLastRun: true, exit: last.exit ?? null, signal: last.signal ?? null } : null);
181
+ const list = (d) => { try { return fs.readdirSync(d).filter((n) => n.endsWith(".json")); } catch { return []; } };
182
+ fs.writeFileSync(path.join(before, "receipts.txt"), `${list(receiptsDir).join("\n")}\n`);
183
+ // The gate's scan-result store as the file system shows it before the run, the launcher's own listing (nothing in it is read).
184
+ // A run folder reused after a crash must not offer the earlier run's listings.
185
+ for (const stale of ["cache-store-after.json", "snapshot-stat.json"]) fs.rmSync(path.join(out, stale), { force: true });
186
+ const storeDir = cacheStoreDir(repo, env); const storeBefore = listFolder(storeDir);
187
+ fs.writeFileSync(path.join(before, "cache-store.json"), `${JSON.stringify({ dir: storeDir, files: storeBefore })}\n`);
188
+ const files = { log: path.join(out, "gate.log"), launch: path.join(out, "launch.json") };
189
+ const args = [gate, ...gateArgs, "--commit", commit];
190
+ let snapRoot = snapshotsRoot; if (snapRoot === null) { try { snapRoot = (await import("./snapshot.mjs")).snapshotRoot({ platform, env }); } catch { snapRoot = null; } }
191
+ const record = { schema: LAUNCH_SCHEMA, runId, commit, kind: derived, host, gate: { path: path.resolve(repo, gate), args }, launcherPid: process.pid, gatePid: null, lanes: laneCount, lanesSource: lanes ? "--lanes, handed to the gate as RK_GATE_JOBS" : "this host's cores, handed to the gate as RK_GATE_JOBS", limitMs, limitsSha256, receiptsDir: path.resolve(receiptsDir), snapshotsRoot: snapRoot, fingerprint: fp, baseline, startedAt: null, startMono: null, endedAt: null, endMono: null, exit: null, signal: null, previous };
192
+ const save = () => fs.writeFileSync(files.launch, `${JSON.stringify(record, null, 2)}\n`);
193
+ const logFd = fs.openSync(files.log, "a");
194
+ record.startedAt = new Date().toISOString(); record.startMono = mono();
195
+ const child = spawnImpl(process.execPath, args, { cwd: repo, windowsHide: true, stdio: ["ignore", logFd, logFd], env: { ...env, RK_GATE_JOBS: String(laneCount) } });
196
+ record.gatePid = Number.isInteger(child.pid) ? child.pid : null;
197
+ save();
198
+ const forward = (sig) => { try { child.kill(sig); } catch { /* already gone */ } };
199
+ process.on("SIGINT", forward); process.on("SIGTERM", forward);
200
+ const [code, signal] = await new Promise((resolve) => { child.once("error", () => resolve([null, null])); child.once("exit", (c, s) => resolve([c, s])); });
201
+ process.off("SIGINT", forward); process.off("SIGTERM", forward);
202
+ record.endedAt = new Date().toISOString(); record.endMono = mono(); record.exit = code; record.signal = signal ?? null;
203
+ // The snapshot root is read once, with its entry kinds: the locks and the stat record of the snapshots both come from that one read.
204
+ const rootEntries = (() => { try { return snapRoot ? fs.readdirSync(snapRoot, { withFileTypes: true }) : null; } catch { return null; } })();
205
+ const locksNow = (d) => (rootEntries === null ? null : rootEntries.map((e) => e.name).filter((n) => n.endsWith(".lock")).map((n) => path.join(d, n)));
206
+ // One read of the snapshot root decides both what was found and whether it could be read.
207
+ const seenLocks = snapRoot ? locksNow(snapRoot) : null;
208
+ record.afterRun = { observedAt: new Date().toISOString(), locks: seenLocks ?? [], locksKnown: seenLocks !== null, rootAlive: alive(record.gatePid) };
209
+ // At the gate's exit, before anything can change: the store listed again, and the stat record of the snapshots this run made or touched.
210
+ const storeAfter = listFolder(storeDir);
211
+ fs.writeFileSync(path.join(out, "cache-store-after.json"), `${JSON.stringify({ dir: storeDir, files: storeAfter })}\n`);
212
+ const snaps = rootEntries === null ? { root: snapRoot, dirs: {}, known: false } : statSnapshots(snapRoot, Date.parse(record.startedAt), { entries: rootEntries });
213
+ fs.writeFileSync(path.join(out, "snapshot-stat.json"), `${JSON.stringify(snaps)}\n`);
214
+ record.cacheStore = { dir: storeDir, beforeKnown: storeBefore !== null, afterKnown: storeAfter !== null }; record.snapshotStat = { root: snaps.root, folders: Object.keys(snaps.dirs), known: snaps.known };
215
+ save();
216
+ try { fs.closeSync(logFd); } catch { /* closed */ }
217
+ // The operating system's record of the run's programs, a little either side of the gate's own span.
218
+ const from = new Date(Date.parse(record.startedAt) - 2000).toISOString(); const to = new Date(Date.now() + 2000).toISOString();
219
+ const exported = exportProcesses ? exportProcesses(from, to) : platform === "win32" ? exportWindowsProcesses(from, to) : { kind: null, from, to, newest: null, continuous: false, events: [], problems: [`no process record is collected on ${platform} yet (eslogger on the Mac)`] };
220
+ fs.writeFileSync(path.join(out, "processes.json"), `${JSON.stringify(exported)}\n`);
221
+ // This run is now the last launched run, kept apart from the lock so the next run has its identity whether or not anything was released.
222
+ const tmp = `${lastFile}.${process.pid}.tmp`; fs.writeFileSync(tmp, `${JSON.stringify({ runId, out: path.resolve(out), commit, fingerprint: fp, host, endedAt: record.endedAt, exit: code, signal: signal ?? null })}\n`); fs.renameSync(tmp, lastFile);
223
+ try { const held = JSON.parse(fs.readFileSync(lockFile, "utf8")); if (held.runId === runId) fs.rmSync(lockFile, { force: true }); } catch { /* not ours any more */ }
224
+ return code ?? (signal ? 128 + (os.constants.signals[signal] ?? 0) : 1);
225
+ }
226
+
227
+ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
228
+ const argv = process.argv.slice(2); const cut = argv.indexOf("--");
229
+ const own = cut < 0 ? argv : argv.slice(0, cut); const gateArgs = cut < 0 ? [] : argv.slice(cut + 1);
230
+ const opt = (name) => { const i = own.indexOf(name); return i < 0 ? null : own[i + 1]; };
231
+ if (gateArgs.includes("--commit")) { console.error("acceptance-launch: the launcher owns --commit; give it before --"); process.exit(2); }
232
+ launch({ out: opt("--out"), commit: opt("--commit"), kind: opt("--kind"), receiptsDir: opt("--receipts"), limits: opt("--limits"), lanes: opt("--lanes") ? Number(opt("--lanes")) : null, repo: opt("--repo") ?? process.cwd(), gate: opt("--gate") ?? undefined, lock: opt("--lock"), gateArgs })
233
+ .then((code) => process.exit(code), (e) => { console.error(`acceptance-launch: ${e.message}`); process.exit(2); });
234
+ }