forgedock 1.60.0 → 1.61.0

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 (78) hide show
  1. package/bin/config-schema.mjs +44 -1
  2. package/bin/engine/runlog.mjs +52 -0
  3. package/bin/engine-cli.mjs +9 -4
  4. package/bin/env/bench.mjs +38 -0
  5. package/bin/env/cli.mjs +134 -0
  6. package/bin/env/env.mjs +339 -0
  7. package/bin/forgedock.mjs +32 -3
  8. package/bin/help-text.mjs +2 -0
  9. package/bin/lean/ci-budget.mjs +3 -1
  10. package/bin/lean/ci-classify.mjs +74 -0
  11. package/bin/lean/ci-classify.test.mjs +147 -0
  12. package/bin/lean/ci-emit.mjs +175 -0
  13. package/bin/lean/ci-emit.test.mjs +177 -0
  14. package/bin/lean/ci-preflight.mjs +183 -0
  15. package/bin/lean/ci-preflight.test.mjs +122 -0
  16. package/bin/lean/ci-runner-health.mjs +213 -0
  17. package/bin/lean/ci-runner-health.test.mjs +113 -0
  18. package/bin/lean/ci-watch.mjs +79 -0
  19. package/bin/lean/ci-watch.test.mjs +80 -0
  20. package/bin/lean/conformance.mjs +7 -1
  21. package/bin/lean/conformance.test.mjs +7 -1
  22. package/bin/lean/depcache.mjs +38 -8
  23. package/bin/lean/deploy-stages.mjs +514 -0
  24. package/bin/lean/deploy-stages.test.mjs +580 -0
  25. package/bin/lean/effects.mjs +50 -0
  26. package/bin/lean/execution.mjs +8 -1
  27. package/bin/lean/lean.mjs +61 -12
  28. package/bin/lean/lean.test.mjs +87 -0
  29. package/bin/lean/preflight.mjs +62 -1
  30. package/bin/lean/preflight.test.mjs +30 -1
  31. package/bin/lean/release-deploy.mjs +12 -6
  32. package/bin/lean/release-flakes.mjs +16 -0
  33. package/bin/lean/release-flakes.test.mjs +15 -0
  34. package/bin/lean/release-gates.mjs +24 -1
  35. package/bin/lean/release-ledger.mjs +21 -0
  36. package/bin/lean/release-minutes-timing.test.mjs +57 -0
  37. package/bin/lean/release-minutes.mjs +98 -0
  38. package/bin/lean/release-promote.mjs +444 -0
  39. package/bin/lean/release-promote.test.mjs +470 -0
  40. package/bin/lean/release-rollback.mjs +14 -6
  41. package/bin/lean/release.mjs +31 -2
  42. package/bin/lean/sandbox-remote.mjs +11 -3
  43. package/bin/lean/testengine-recall.mjs +82 -0
  44. package/bin/lean/testengine-recall.test.mjs +103 -0
  45. package/bin/lean/testengine-shard.mjs +150 -0
  46. package/bin/lean/testengine-shard.test.mjs +111 -0
  47. package/bin/lean/testengine.mjs +486 -0
  48. package/bin/lean/testengine.test.mjs +303 -0
  49. package/bin/lean/validate-catalog.mjs +16 -0
  50. package/bin/lean/validate-catalog.test.mjs +14 -1
  51. package/bin/lean/verify-settle.test.mjs +156 -0
  52. package/bin/lean/verify.mjs +98 -3
  53. package/bin/pool/agent.mjs +65 -6
  54. package/bin/pool/ci-events.mjs +183 -0
  55. package/bin/pool/ci-events.test.mjs +143 -0
  56. package/bin/pool/docker.mjs +7 -0
  57. package/bin/pool/lane-tools.mjs +32 -0
  58. package/bin/pool/router.mjs +21 -1
  59. package/bin/pool/warm.mjs +14 -3
  60. package/bin/stats/ci-awareness.mjs +66 -0
  61. package/bin/stats/index.mjs +44 -3
  62. package/bin/stats/release-ledger.test.mjs +226 -0
  63. package/bin/stats/release.mjs +365 -1
  64. package/bin/stats/stats.test.mjs +36 -0
  65. package/docs/CI.md +31 -0
  66. package/docs/CONFIG.md +235 -2
  67. package/docs/ENV-LIBRARY.md +172 -0
  68. package/docs/STATS.md +43 -0
  69. package/docs/ci-events.md +88 -0
  70. package/docs/test-engine.md +98 -0
  71. package/package.json +1 -1
  72. package/pool/README.md +1 -0
  73. package/pool/image/entrypoint.sh +15 -3
  74. package/pool/services/docker-compose.yml +53 -0
  75. package/pool/services/git-mirror.sh +22 -0
  76. package/scripts/acceptance-red-green.sh +5 -2
  77. package/scripts/acceptance-red-green.test.sh +11 -0
  78. package/templates/github-actions/forge-env/action.yml +65 -0
@@ -0,0 +1,183 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * `forgedock ci preflight [--json]` (#5691): cheap deterministic CI checks that run before the long suites. No LLM anywhere.
5
+ * - Checks: workflow lint, lockfile drift, generated-artifact drift, env drift, tool presence. Each returns
6
+ * {name, status: pass|fail|skip, reason}; a check whose tool or config is absent is skipped, never failed.
7
+ * - Budget: one shared deadline (default 60 s, forge.yaml `ci.preflight.timeout_s`); a check starting after it is skipped.
8
+ * - Config: the one-level forge.yaml parser flattens `ci.preflight.*` under `ci`, so the keys read are `ci.generated[]`
9
+ * (`"<command> :: <path> [<path>...]"`), `ci.tools[]` and `ci.timeout_s`. No key, no extra checks: only auto-detected ones run.
10
+ * - Events: with FORGE_CI_EVENTS_URL set, each failed check is POSTed as a best-effort `step_failed` event (#5688 data contract).
11
+ * Exit 1 only when a check fails. Every effect goes through the injected deps (run, which, fetch, out, env, now).
12
+ */
13
+ import { existsSync, readdirSync, readFileSync } from "node:fs";
14
+ import { spawnSync } from "node:child_process";
15
+ import { delimiter, join } from "node:path";
16
+ import { parseForgeYaml } from "../forge-utils.mjs";
17
+
18
+ export const PREFLIGHT_USAGE = "usage: forgedock ci preflight [--json]";
19
+ export const DEFAULT_BUDGET_S = 60;
20
+
21
+ const str = (v) => (v === undefined || v === null ? "" : String(v).trim());
22
+ const list = (v) => (Array.isArray(v) ? v.map(str).filter(Boolean) : str(v) ? [str(v)] : []);
23
+ const oneLine = (s) => str(s).split("\n").map((l) => l.trim()).find(Boolean)?.slice(0, 200) ?? "no output";
24
+ const pass = (name, reason = "ok") => ({ name, status: "pass", reason });
25
+ const fail = (name, reason) => ({ name, status: "fail", reason: oneLine(reason) });
26
+ const skip = (name, reason) => ({ name, status: "skip", reason });
27
+
28
+ /** forge.yaml `ci` section -> {generated: [{cmd, paths}], tools, timeoutS}; junk keeps the defaults. */
29
+ export function parseCiPreflightConfig(cwd) {
30
+ let sec = null;
31
+ try { sec = parseForgeYaml(readFileSync(join(cwd, "forge.yaml"), "utf8"))?.ci; } catch { /* no forge.yaml: defaults */ }
32
+ const s = sec && typeof sec === "object" ? sec : {};
33
+ const generated = list(s.generated).map((e) => { const [cmd, rest = ""] = e.split("::"); return { cmd: str(cmd), paths: str(rest).split(/\s+/).filter(Boolean) }; }).filter((g) => g.cmd);
34
+ const t = Number(str(s.timeout_s));
35
+ return { generated, tools: list(s.tools), timeoutS: Number.isFinite(t) && t > 0 ? t : DEFAULT_BUDGET_S };
36
+ }
37
+
38
+ const defaultRun = (cmd, args, { cwd, timeoutMs }) => {
39
+ const r = spawnSync(cmd, args, { cwd, encoding: "utf8", timeout: Math.max(1, timeoutMs), stdio: ["ignore", "pipe", "pipe"] });
40
+ return { code: r.error ? 127 : (r.status ?? 1), out: `${r.stdout ?? ""}${r.stderr ?? ""}` };
41
+ };
42
+ const defaultWhich = (cmd, env = process.env) => String(env.PATH ?? "").split(delimiter).some((d) => d && existsSync(join(d, cmd)));
43
+
44
+ function workflowFiles(cwd) {
45
+ const dir = join(cwd, ".github", "workflows");
46
+ try { return readdirSync(dir).filter((f) => /\.ya?ml$/.test(f)).sort().map((f) => ({ file: `.github/workflows/${f}`, text: readFileSync(join(dir, f), "utf8") })); } catch { return []; }
47
+ }
48
+
49
+ /** First syntax problem of a workflow file, or null: a deliberately small scan used only when actionlint is absent. */
50
+ export function yamlProblem(text) {
51
+ const lines = text.split(/\r?\n/);
52
+ let block = -1;
53
+ for (let i = 0; i < lines.length; i++) {
54
+ const l = lines[i];
55
+ const ind = l.match(/^\s*/)[0];
56
+ if (block >= 0 && (ind.length > block || !l.trim())) continue;
57
+ block = -1;
58
+ if (!l.trim() || /^\s*#/.test(l)) continue;
59
+ if (/^ *\t/.test(l)) return `line ${i + 1}: tab used for indentation`;
60
+ const body = l.replace(/\s#.*$/, "");
61
+ if (/[:-]\s*[|>][+-]?\d?\s*$/.test(body)) { block = ind.length; continue; }
62
+ const val = body.match(/^\s*(?:-\s+)?[\w.'"-]+:\s+(.+)$/)?.[1] ?? body.match(/^\s*-\s+(.+)$/)?.[1];
63
+ if (val === undefined) continue;
64
+ if (/^"/.test(val) && !/^"(?:[^"\\]|\\.)*"\s*$/.test(val)) return `line ${i + 1}: unterminated double quote`;
65
+ if (/^'/.test(val) && !/^'(?:[^']|'')*'\s*$/.test(val)) return `line ${i + 1}: unterminated single quote`;
66
+ if (/^[[{]/.test(val)) {
67
+ const stripped = val.replace(/"[^"]*"|'[^']*'|\$\{\{.*?\}\}/g, "");
68
+ if ((stripped.match(/\[/g) ?? []).length !== (stripped.match(/\]/g) ?? []).length || (stripped.match(/\{/g) ?? []).length !== (stripped.match(/\}/g) ?? []).length) return `line ${i + 1}: unbalanced flow bracket`;
69
+ }
70
+ }
71
+ return null;
72
+ }
73
+
74
+ /** Keys set under a workflow `env:` map to a secrets/vars expression: app config that `.env.example` must list. */
75
+ export function workflowEnvKeys(text) {
76
+ const keys = new Set(), lines = text.split(/\r?\n/);
77
+ for (let i = 0; i < lines.length; i++) {
78
+ const m = lines[i].match(/^(\s*)env:\s*$/);
79
+ if (!m) continue;
80
+ for (let j = i + 1; j < lines.length; j++) {
81
+ const k = lines[j].match(/^(\s+)([A-Za-z_][A-Za-z0-9_]*):\s*(.*)$/);
82
+ if (!k && lines[j].trim() && !/^\s*#/.test(lines[j])) break;
83
+ if (!k) continue;
84
+ if (k[1].length <= m[1].length) break;
85
+ if (/\$\{\{\s*(secrets|vars)\./.test(k[3]) && !/^GITHUB_/.test(k[2])) keys.add(k[2]);
86
+ }
87
+ }
88
+ return keys;
89
+ }
90
+
91
+ /** Runs every check; @returns {ok, budgetMs, elapsedMs, checks}. `deps`: {run, which, now, env}. */
92
+ export function runCiPreflight(cwd, deps = {}) {
93
+ const now = deps.now ?? Date.now, env = deps.env ?? process.env, run = deps.run ?? defaultRun, which = deps.which ?? ((c) => defaultWhich(c, env));
94
+ const cfg = parseCiPreflightConfig(cwd), budgetMs = cfg.timeoutS * 1000, start = now();
95
+ const left = () => budgetMs - (now() - start);
96
+ const exec = (cmd, args) => run(cmd, args, { cwd, timeoutMs: left() });
97
+ const guard = (name, fn) => {
98
+ if (left() <= 0) return [skip(name, `budget of ${cfg.timeoutS}s exhausted`)];
99
+ try { return fn(); } catch (e) { return [fail(name, `check crashed: ${e?.message ?? e}`)]; }
100
+ };
101
+ const checks = [];
102
+
103
+ checks.push(...guard("workflow-lint", () => {
104
+ const files = workflowFiles(cwd);
105
+ if (!files.length) return [skip("workflow-lint", "no .github/workflows/*.yml")];
106
+ if (which("actionlint")) { const r = exec("actionlint", []); return [r.code === 0 ? pass("workflow-lint", "actionlint clean") : fail("workflow-lint", r.out)]; }
107
+ for (const f of files) { const p = yamlProblem(f.text); if (p) return [fail("workflow-lint", `${f.file}: ${p}`)]; }
108
+ return [pass("workflow-lint", `${files.length} workflow file(s) parse (actionlint absent)`)];
109
+ }));
110
+
111
+ const pkg = existsSync(join(cwd, "package.json")), pyproject = existsSync(join(cwd, "pyproject.toml"));
112
+ const locks = [
113
+ { eco: "pnpm", when: pkg && existsSync(join(cwd, "pnpm-lock.yaml")), cmd: "pnpm", args: ["install", "--frozen-lockfile", "--lockfile-only"] },
114
+ { eco: "npm", when: pkg && existsSync(join(cwd, "package-lock.json")), cmd: "npm", args: ["ci", "--dry-run", "--ignore-scripts"] },
115
+ { eco: "uv", when: pyproject && existsSync(join(cwd, "uv.lock")), cmd: "uv", args: ["lock", "--check"] },
116
+ { eco: "poetry", when: pyproject && existsSync(join(cwd, "poetry.lock")), cmd: "poetry", args: ["check", "--lock"] },
117
+ ].filter((l) => l.when);
118
+ if (!locks.length) checks.push(skip("lockfile", "no package.json/pyproject.toml with a lockfile"));
119
+ for (const l of locks) {
120
+ checks.push(...guard(`lockfile:${l.eco}`, () => {
121
+ if (!which(l.cmd)) return [skip(`lockfile:${l.eco}`, `${l.cmd} not on PATH`)];
122
+ const r = exec(l.cmd, l.args);
123
+ return [r.code === 0 ? pass(`lockfile:${l.eco}`, "lockfile in sync") : fail(`lockfile:${l.eco}`, `lockfile drift: ${oneLine(r.out)}`)];
124
+ }));
125
+ }
126
+
127
+ if (!cfg.generated.length) checks.push(skip("generated", "no ci.preflight.generated configured"));
128
+ cfg.generated.forEach((g, i) => {
129
+ const name = cfg.generated.length > 1 ? `generated:${i + 1}` : "generated";
130
+ checks.push(...guard(name, () => {
131
+ const r = exec("sh", ["-c", g.cmd]);
132
+ if (r.code !== 0) return [fail(name, `generator failed (${g.cmd}): ${oneLine(r.out)}`)];
133
+ if (!g.paths.length) return [skip(name, "no paths declared to diff")];
134
+ const d = exec("git", ["diff", "--exit-code", "--", ...g.paths]);
135
+ return [d.code === 0 ? pass(name, `${g.paths.join(" ")} up to date`) : fail(name, `stale generated artifact: ${g.paths.join(" ")} differs after \`${g.cmd}\``)];
136
+ }));
137
+ });
138
+
139
+ checks.push(...guard("env-drift", () => {
140
+ const ex = join(cwd, ".env.example");
141
+ const used = new Set(workflowFiles(cwd).flatMap((f) => [...workflowEnvKeys(f.text)]));
142
+ if (!existsSync(ex)) return [skip("env-drift", "no .env.example")];
143
+ if (!used.size) return [skip("env-drift", "no workflow env: keys from secrets/vars")];
144
+ const have = new Set(readFileSync(ex, "utf8").split(/\r?\n/).map((l) => l.match(/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/)?.[1]).filter(Boolean));
145
+ const missing = [...used].filter((k) => !have.has(k)).sort();
146
+ return [missing.length ? fail("env-drift", `workflow env key(s) missing from .env.example: ${missing.join(", ")}`) : pass("env-drift", `${used.size} key(s) listed in .env.example`)];
147
+ }));
148
+
149
+ if (!cfg.tools.length) checks.push(skip("tools", "no ci.preflight.tools configured"));
150
+ else checks.push(...guard("tools", () => {
151
+ const missing = cfg.tools.filter((t) => !which(t));
152
+ return [missing.length ? fail("tools", `missing tool(s) on PATH: ${missing.join(", ")}`) : pass("tools", `${cfg.tools.join(", ")} present`)];
153
+ }));
154
+
155
+ return { ok: !checks.some((c) => c.status === "fail"), budgetMs, elapsedMs: now() - start, checks };
156
+ }
157
+
158
+ /** Best-effort `step_failed` event per failed check; never throws and never changes the result. */
159
+ export async function emitEvents(result, { env = process.env, fetchImpl = globalThis.fetch } = {}) {
160
+ const url = str(env.FORGE_CI_EVENTS_URL);
161
+ if (!url || typeof fetchImpl !== "function") return 0;
162
+ let sent = 0;
163
+ for (const c of result.checks.filter((x) => x.status === "fail")) {
164
+ const body = { type: "step_failed", step: `preflight:${c.name}`, class: "deterministic-setup", reason: c.reason, repo: env.GITHUB_REPOSITORY ?? null, sha: env.GITHUB_SHA ?? null };
165
+ try { await fetchImpl(url, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body), signal: AbortSignal.timeout(2000) }); sent++; } catch { /* best effort */ }
166
+ }
167
+ return sent;
168
+ }
169
+
170
+ /** `forgedock ci preflight [--json]`; @returns the exit code. `deps`: {out, cwd, run, which, now, env, fetchImpl}. */
171
+ export async function ciPreflightFromCli(argv, deps = {}) {
172
+ const out = deps.out ?? ((l) => console.log(l)), cwd = deps.cwd ?? process.cwd();
173
+ const unknown = argv.find((a) => a !== "--json");
174
+ if (unknown) throw new Error(`unknown argument ${unknown}; ${PREFLIGHT_USAGE}`);
175
+ const res = runCiPreflight(cwd, deps);
176
+ await emitEvents(res, deps);
177
+ if (argv.includes("--json")) out(JSON.stringify(res));
178
+ else {
179
+ for (const c of res.checks) out(`${c.status.toUpperCase().padEnd(4)} ${c.name}: ${c.reason}`);
180
+ out(`preflight: ${res.ok ? "ok" : "FAILED"} in ${res.elapsedMs} ms (budget ${res.budgetMs / 1000} s)`);
181
+ }
182
+ return res.ok ? 0 : 1;
183
+ }
@@ -0,0 +1,122 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ import { test } from "node:test";
4
+ import assert from "node:assert/strict";
5
+ import { mkdirSync, writeFileSync } from "node:fs";
6
+ import { execFileSync } from "node:child_process";
7
+ import { join } from "node:path";
8
+ import { tmpDir } from "../tests/_tmp.mjs";
9
+ import { runCiPreflight, ciPreflightFromCli, emitEvents, parseCiPreflightConfig, yamlProblem, workflowEnvKeys } from "./ci-preflight.mjs";
10
+ import { ciFromCli } from "./ci-budget.mjs";
11
+
12
+ const GOOD_WF = "name: ci\non: push\njobs:\n t:\n runs-on: ubuntu-latest\n env:\n API_KEY: ${{ secrets.API_KEY }}\n steps:\n - run: echo hi\n";
13
+ const put = (root, rel, text) => { mkdirSync(join(root, rel, ".."), { recursive: true }); writeFileSync(join(root, rel), text); };
14
+ /** Fixture repo: kind node-pnpm | py-uv | py-poetry, all clean, with a workflow and a matching .env.example. */
15
+ function fixture(kind, { forge = "" } = {}) {
16
+ const root = tmpDir("cipf-");
17
+ put(root, ".github/workflows/ci.yml", GOOD_WF);
18
+ put(root, ".env.example", "API_KEY=\n");
19
+ if (kind === "node-pnpm") { put(root, "package.json", "{}"); put(root, "pnpm-lock.yaml", "lockfileVersion: 9\n"); }
20
+ if (kind === "py-uv") { put(root, "pyproject.toml", "[project]\nname='x'\n"); put(root, "uv.lock", "version = 1\n"); }
21
+ if (kind === "py-poetry") { put(root, "pyproject.toml", "[tool.poetry]\nname='x'\n"); put(root, "poetry.lock", "# lock\n"); }
22
+ if (forge) put(root, "forge.yaml", forge);
23
+ return root;
24
+ }
25
+ const ALL = () => true;
26
+ const okRun = () => ({ code: 0, out: "" });
27
+ const by = (res, name) => res.checks.find((c) => c.name === name);
28
+ const statuses = (res) => Object.fromEntries(res.checks.map((c) => [c.name, c.status]));
29
+
30
+ test("clean fixtures: every check passes or skips, within budget", () => {
31
+ for (const [kind, lock] of [["node-pnpm", "lockfile:pnpm"], ["py-uv", "lockfile:uv"], ["py-poetry", "lockfile:poetry"]]) {
32
+ const res = runCiPreflight(fixture(kind), { run: okRun, which: ALL });
33
+ assert.equal(res.ok, true, kind);
34
+ assert.equal(by(res, lock).status, "pass");
35
+ assert.ok(res.checks.every((c) => c.status !== "fail") && res.elapsedMs < 60000);
36
+ assert.equal(by(res, "generated").status, "skip");
37
+ assert.equal(by(res, "tools").status, "skip");
38
+ }
39
+ });
40
+
41
+ test("each injected defect fails only its own check, with a one-line reason", () => {
42
+ const cases = {
43
+ "workflow-lint": (r) => put(r, ".github/workflows/ci.yml", 'name: "oops\non: push\n'),
44
+ "lockfile:pnpm": null,
45
+ "env-drift": (r) => put(r, ".env.example", "OTHER=\n"),
46
+ tools: null,
47
+ };
48
+ for (const [name, mutate] of Object.entries(cases)) {
49
+ const root = fixture("node-pnpm", { forge: name === "tools" ? "ci:\n tools:\n - nosuchtool\n" : "" });
50
+ mutate?.(root);
51
+ const run = (cmd) => (name === "lockfile:pnpm" && cmd === "pnpm" ? { code: 1, out: "ERR_PNPM_OUTDATED_LOCKFILE\nmore" } : { code: 0, out: "" });
52
+ const res = runCiPreflight(root, { run, which: (c) => c !== "nosuchtool" && c !== "actionlint" });
53
+ const bad = res.checks.filter((c) => c.status === "fail");
54
+ assert.deepEqual(bad.map((c) => c.name), [name], name);
55
+ assert.ok(!bad[0].reason.includes("\n"));
56
+ assert.equal(res.ok, false);
57
+ }
58
+ });
59
+
60
+ test("stale generated artifact (real git): fails after the generator rewrites a tracked path; clean when unchanged", () => {
61
+ const root = fixture("node-pnpm", { forge: 'ci:\n generated:\n - echo "v2" > sdk.txt :: sdk.txt\n' });
62
+ put(root, "sdk.txt", "v1\n");
63
+ const git = (...a) => execFileSync("git", ["-c", "user.email=t@t", "-c", "user.name=t", ...a], { cwd: root, stdio: "ignore" });
64
+ git("init", "-q"); git("add", "-A"); git("commit", "-qm", "init");
65
+ const res = runCiPreflight(root, { which: () => false });
66
+ const g = by(res, "generated");
67
+ assert.equal(g.status, "fail"); assert.match(g.reason, /stale generated artifact: sdk\.txt/);
68
+ assert.ok(res.elapsedMs < 60000, `SDK-drift replay took ${res.elapsedMs} ms (budget 60000)`);
69
+ writeFileSync(join(root, "sdk.txt"), "v2\n"); git("commit", "-qam", "regen");
70
+ assert.equal(by(runCiPreflight(root, { which: () => false }), "generated").status, "pass");
71
+ });
72
+
73
+ test("missing optional tools are skipped with a reason and exit 0", async () => {
74
+ const root = fixture("node-pnpm"); const lines = [];
75
+ const code = await ciPreflightFromCli([], { cwd: root, out: (l) => lines.push(l), which: () => false, run: () => { throw new Error("must not run"); } });
76
+ assert.equal(code, 0);
77
+ const res = runCiPreflight(root, { which: () => false, run: okRun });
78
+ assert.equal(by(res, "lockfile:pnpm").status, "skip"); assert.match(by(res, "lockfile:pnpm").reason, /not on PATH/);
79
+ assert.equal(by(res, "workflow-lint").status, "pass"); // YAML fallback when actionlint is absent
80
+ assert.ok(lines.some((l) => /^SKIP\s+lockfile:pnpm/.test(l)));
81
+ });
82
+
83
+ test("no forge.yaml key: no configured checks, only auto-detected ones; empty repo skips everything", () => {
84
+ assert.deepEqual(parseCiPreflightConfig(fixture("node-pnpm")), { generated: [], tools: [], timeoutS: 60 });
85
+ const empty = runCiPreflight(tmpDir("cipf-"), { run: okRun, which: ALL });
86
+ assert.equal(empty.ok, true);
87
+ assert.ok(empty.checks.every((c) => c.status === "skip"), JSON.stringify(statuses(empty)));
88
+ const cfg = parseCiPreflightConfig(fixture("py-uv", { forge: "ci:\n mode: remote\n timeout_s: 5\n tools: [a, b]\n generated:\n - gen :: a.txt b.txt\n" }));
89
+ assert.deepEqual(cfg, { generated: [{ cmd: "gen", paths: ["a.txt", "b.txt"] }], tools: ["a", "b"], timeoutS: 5 });
90
+ });
91
+
92
+ test("budget: a check starting after the deadline is skipped", () => {
93
+ let t = 0;
94
+ const res = runCiPreflight(fixture("node-pnpm", { forge: "ci:\n timeout_s: 1\n" }), { run: okRun, which: ALL, now: () => (t += 600) });
95
+ assert.ok(res.checks.some((c) => c.status === "skip" && /budget of 1s exhausted/.test(c.reason)));
96
+ });
97
+
98
+ test("yamlProblem and workflowEnvKeys", () => {
99
+ assert.equal(yamlProblem(GOOD_WF), null);
100
+ assert.match(yamlProblem("a:\n\tb: 1\n"), /tab/);
101
+ assert.match(yamlProblem("a: [1, 2\n"), /unbalanced/);
102
+ assert.equal(yamlProblem("run: |\n echo 'it's\n x: \"open\n"), null); // block scalar bodies are not scanned
103
+ assert.deepEqual([...workflowEnvKeys(GOOD_WF)], ["API_KEY"]);
104
+ });
105
+
106
+ test("events: step_failed POSTed per failed check only when FORGE_CI_EVENTS_URL is set; fetch errors are swallowed", async () => {
107
+ const res = { checks: [{ name: "a", status: "fail", reason: "r" }, { name: "b", status: "pass", reason: "ok" }] };
108
+ assert.equal(await emitEvents(res, { env: {}, fetchImpl: () => assert.fail("no url") }), 0);
109
+ const calls = [];
110
+ assert.equal(await emitEvents(res, { env: { FORGE_CI_EVENTS_URL: "http://x/ci/events", GITHUB_SHA: "abc" }, fetchImpl: async (u, o) => { calls.push([u, JSON.parse(o.body)]); } }), 1);
111
+ assert.equal(calls[0][1].type, "step_failed"); assert.equal(calls[0][1].step, "preflight:a"); assert.equal(calls[0][1].sha, "abc");
112
+ assert.equal(await emitEvents(res, { env: { FORGE_CI_EVENTS_URL: "http://x" }, fetchImpl: async () => { throw new Error("down"); } }), 0);
113
+ });
114
+
115
+ test("cli: --json output, exit 1 on a failure, unknown option throws; ci budget routing intact", async () => {
116
+ const root = fixture("node-pnpm", { forge: "ci:\n tools:\n - nosuchtool\n" }); const lines = [];
117
+ const code = await ciFromCli(["preflight", "--json"], { cwd: root, out: (l) => lines.push(l), preflight: { which: () => false, run: okRun } });
118
+ assert.equal(code, 1);
119
+ const j = JSON.parse(lines[0]); assert.equal(j.ok, false); assert.equal(j.checks.find((c) => c.name === "tools").status, "fail");
120
+ await assert.rejects(ciPreflightFromCli(["--bogus"], { cwd: root }), /unknown argument --bogus/);
121
+ await assert.rejects(ciFromCli(["nope"], {}), /usage: forgedock ci preflight/);
122
+ });
@@ -0,0 +1,213 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * `forgedock ci runner-health [--recover] [--json] [--repo owner/repo] [--print-units]` (#5693, parent #5687): health check and
5
+ * watchdog recovery for the self-hosted GitHub Actions runner services on this host. No LLM anywhere.
6
+ * - Findings: (a) a runner busy on a job whose run is completed/cancelled, (b) a runner service not active, (c) an orphaned runner
7
+ * container older than the job timeout, (d) disk free below `min_disk_gb` (default 10) or memory available below 1 GB.
8
+ * - Events: each finding is POSTed best effort as a `runner_unhealthy` event (#5688 bus, via ci-emit createPoster).
9
+ * - Recovery (`--recover`; the default is a dry run that prints the plan): restart only the affected runner's service for (a)/(b),
10
+ * `docker rm -f` only the orphaned containers for (c). Never reboots, never touches other services. At most one restart per
11
+ * service per 10 min (state file under the ci-budget cache dir). Every action is logged through `out`.
12
+ * - Config (forge.yaml `ci`, one-level parser): `repo`, `services[]`, `min_disk_gb`, `recover`, `job_timeout_min` (default 360).
13
+ * A nested `runners:` object is read too. `recover: true` only makes the timer unit pass `--recover`.
14
+ * Exit 1 when there is a finding. Every effect goes through the injected deps (gh, docker, systemctl, disk, memory, fetchImpl, now).
15
+ */
16
+ import { readFileSync, writeFileSync, mkdirSync, statfsSync } from "node:fs";
17
+ import { spawnSync } from "node:child_process";
18
+ import { dirname, join } from "node:path";
19
+ import { fileURLToPath } from "node:url";
20
+ import { parseForgeYaml } from "../forge-utils.mjs";
21
+ import { createPoster } from "./ci-emit.mjs";
22
+ import { cacheDir } from "./ci-budget.mjs";
23
+
24
+ export const RUNNER_HEALTH_USAGE = "usage: forgedock ci runner-health [--recover] [--json] [--repo owner/repo] [--print-units]";
25
+ export const DEFAULT_MIN_DISK_GB = 10, MIN_MEM_GB = 1, DEFAULT_JOB_TIMEOUT_MIN = 360, RESTART_COOLDOWN_MS = 10 * 60 * 1000;
26
+ const GB = 1024 ** 3;
27
+
28
+ const str = (v) => (v === undefined || v === null ? "" : String(v).trim());
29
+ const list = (v) => (Array.isArray(v) ? v.map(str).filter(Boolean) : str(v) ? [str(v)] : []);
30
+ const num = (v, d) => { const n = Number(str(v)); return str(v) && Number.isFinite(n) && n > 0 ? n : d; };
31
+
32
+ /** forge.yaml `ci` section -> {repo, services, minDiskGb, recover, jobTimeoutMin}; junk keeps the defaults. */
33
+ export function parseRunnerHealthConfig(cwd) {
34
+ let sec = null;
35
+ try { sec = parseForgeYaml(readFileSync(join(cwd, "forge.yaml"), "utf8"))?.ci; } catch { /* no forge.yaml: defaults */ }
36
+ const base = sec && typeof sec === "object" ? sec : {};
37
+ const s = base.runners && typeof base.runners === "object" ? { ...base, ...base.runners } : base;
38
+ return {
39
+ repo: str(s.repo), services: list(s.services), minDiskGb: num(s.min_disk_gb, DEFAULT_MIN_DISK_GB),
40
+ recover: /^(true|yes|on|1)$/i.test(str(s.recover)), jobTimeoutMin: num(s.job_timeout_min, DEFAULT_JOB_TIMEOUT_MIN),
41
+ };
42
+ }
43
+
44
+ const run = (cmd, args) => {
45
+ const r = spawnSync(cmd, args, { encoding: "utf8", timeout: 30000, stdio: ["ignore", "pipe", "pipe"] });
46
+ return { code: r.error ? 127 : (r.status ?? 1), out: `${r.stdout ?? ""}`, err: `${r.stderr ?? ""}` };
47
+ };
48
+ const defaultDeps = {
49
+ gh: async (args) => { const r = run("gh", args); if (r.code) throw new Error(r.err.trim() || `gh exit ${r.code}`); return r.out; },
50
+ docker: async (args) => run("docker", args),
51
+ systemctl: async (args) => run("systemctl", args),
52
+ diskGb: () => { const s = statfsSync("/"); return (s.bavail * s.bsize) / GB; },
53
+ memGb: () => { const m = /MemAvailable:\s+(\d+) kB/.exec(readFileSync("/proc/meminfo", "utf8")); return m ? (Number(m[1]) * 1024) / GB : Infinity; },
54
+ };
55
+
56
+ const finding = (kind, job, reason, extra = {}) => ({ kind, job, reason, ...extra });
57
+ const serviceFor = (runnerName, services) => services.find((s) => s.includes(`.${runnerName}.`) || s === runnerName || s === `${runnerName}.service`) ?? null;
58
+
59
+ /** (a): busy runners whose job sits in a completed/cancelled run. Needs the repo; a gh failure yields no (a) findings. */
60
+ async function stuckRunners({ gh, repo, services }) {
61
+ const runners = JSON.parse(await gh(["api", `repos/${repo}/actions/runners`, "--paginate"])).runners ?? [];
62
+ const busy = new Map(runners.filter((r) => r.busy).map((r) => [r.name, r]));
63
+ if (!busy.size) return [];
64
+ const runs = JSON.parse(await gh(["api", `repos/${repo}/actions/runs?per_page=50`])).workflow_runs ?? [];
65
+ const out = [];
66
+ for (const wr of runs) {
67
+ if (!busy.size) break;
68
+ if (wr.status !== "completed" && wr.conclusion !== "cancelled") continue;
69
+ const jobs = JSON.parse(await gh(["api", `repos/${repo}/actions/runs/${wr.id}/jobs?filter=latest`])).jobs ?? [];
70
+ for (const j of jobs) {
71
+ if (j.status === "completed" || !busy.has(j.runner_name)) continue;
72
+ const name = j.runner_name;
73
+ out.push(finding("stuck-run", name, `runner ${name} busy on job ${j.id} of ${wr.conclusion ?? wr.status} run ${wr.id}`, { service: serviceFor(name, services), run_id: wr.id }));
74
+ busy.delete(name);
75
+ }
76
+ }
77
+ return out;
78
+ }
79
+
80
+ const parseCreated = (s) => Date.parse(str(s).replace(/\s+[A-Z]{2,5}$/, "").replace(/^(\S+) (\S+) ([+-]\d{4}).*$/, "$1T$2$3"));
81
+ const RUNNER_LABEL_RE = /actions[._]runner|github[._]actions|github[._]runner/i;
82
+
83
+ /** (c): runner-labelled containers created more than the job timeout ago. */
84
+ async function orphanContainers({ docker, timeoutMin, nowMs }) {
85
+ const r = await docker(["ps", "--format", "{{json .}}"]);
86
+ if (r.code) return [];
87
+ const out = [];
88
+ for (const line of r.out.split("\n").filter(Boolean)) {
89
+ let c; try { c = JSON.parse(line); } catch { continue; }
90
+ if (!RUNNER_LABEL_RE.test(str(c.Labels))) continue;
91
+ const created = parseCreated(c.CreatedAt);
92
+ if (Number.isFinite(created) && nowMs - created > timeoutMin * 60000) out.push(finding("orphan-container", str(c.ID), `container ${c.ID} older than ${timeoutMin} min job timeout`, { id: str(c.ID) }));
93
+ }
94
+ return out;
95
+ }
96
+
97
+ /** Detect (a)-(d); each detector failing on its own (gh down, no docker) is skipped, never thrown. */
98
+ export async function detectRunnerHealth(cfg, deps = {}) {
99
+ const d = { ...defaultDeps, ...deps }, nowMs = (d.now ?? Date.now)();
100
+ const findings = [], skipped = [];
101
+ const guard = async (name, fn) => { try { findings.push(...await fn()); } catch (e) { skipped.push(`${name}: ${str(e.message).slice(0, 120)}`); } };
102
+ if (cfg.repo) await guard("stuck-run", () => stuckRunners({ gh: d.gh, repo: cfg.repo, services: cfg.services }));
103
+ else skipped.push("stuck-run: no repo configured");
104
+ await guard("service", async () => {
105
+ const out = [];
106
+ for (const svc of cfg.services) {
107
+ const r = await d.systemctl(["is-active", svc]);
108
+ if (str(r.out) !== "active") out.push(finding("service-down", svc, `service ${svc} is ${str(r.out) || "not active"}`, { service: svc }));
109
+ }
110
+ return out;
111
+ });
112
+ await guard("orphan-container", () => orphanContainers({ docker: d.docker, timeoutMin: cfg.jobTimeoutMin, nowMs }));
113
+ await guard("disk", async () => { const g = d.diskGb(); return g < cfg.minDiskGb ? [finding("low-disk", "host", `disk free ${g.toFixed(1)} GB < ${cfg.minDiskGb} GB`)] : []; });
114
+ await guard("memory", async () => { const g = d.memGb(); return g < MIN_MEM_GB ? [finding("low-memory", "host", `memory available ${g.toFixed(2)} GB < ${MIN_MEM_GB} GB`)] : []; });
115
+ return { findings, skipped };
116
+ }
117
+
118
+ /** Recovery plan: one restart per affected service (a)/(b), one rm per orphaned container (c). Disk and memory have no action. */
119
+ export function planRecovery(findings) {
120
+ const plan = [], seen = new Set();
121
+ for (const f of findings) {
122
+ if ((f.kind === "stuck-run" || f.kind === "service-down") && f.service && !seen.has(f.service)) { seen.add(f.service); plan.push({ action: "restart", service: f.service, why: f.reason }); }
123
+ if (f.kind === "orphan-container") plan.push({ action: "rm-container", id: f.id, why: f.reason });
124
+ }
125
+ return plan;
126
+ }
127
+
128
+ const stateFile = (dir) => join(dir, "runner-health-restarts.json");
129
+ const readState = (dir) => { try { return JSON.parse(readFileSync(stateFile(dir), "utf8")) ?? {}; } catch { return {}; } };
130
+
131
+ /** Executes the plan; returns one result line per step. Restarts honour the per-service cooldown. */
132
+ export async function applyRecovery(plan, { docker, systemctl, dir, nowMs, out }) {
133
+ const state = readState(dir), results = [];
134
+ for (const p of plan) {
135
+ let msg;
136
+ if (p.action === "restart") {
137
+ const last = Number(state[p.service] ?? 0);
138
+ if (nowMs - last < RESTART_COOLDOWN_MS) msg = `skip restart ${p.service}: restarted ${Math.round((nowMs - last) / 1000)} s ago (cooldown ${RESTART_COOLDOWN_MS / 60000} min)`;
139
+ else {
140
+ const r = await systemctl(["restart", p.service]);
141
+ if (r.code === 0) { state[p.service] = nowMs; msg = `restarted ${p.service}`; } else msg = `restart ${p.service} failed (exit ${r.code})`;
142
+ }
143
+ } else {
144
+ const r = await docker(["rm", "-f", p.id]);
145
+ msg = r.code === 0 ? `removed container ${p.id}` : `remove container ${p.id} failed (exit ${r.code})`;
146
+ }
147
+ results.push({ ...p, result: msg });
148
+ out(`recover: ${msg}`);
149
+ }
150
+ try { mkdirSync(dir, { recursive: true }); writeFileSync(stateFile(dir), JSON.stringify(state)); } catch { /* cache only */ }
151
+ return results;
152
+ }
153
+
154
+ /** systemd oneshot service + 2 min timer that runs this check (the issuewatch-install.mjs renderWatchdog shape). */
155
+ export function renderRunnerHealthUnits({ node = process.execPath, cli = join(dirname(fileURLToPath(import.meta.url)), "..", "forgedock.mjs"), cwd = process.cwd(), recover = false } = {}) {
156
+ const q = (s) => `"${String(s).replace(/(["\\])/g, "\\$1").replace(/[$%]/g, (c) => c + c)}"`;
157
+ const service = `[Unit]
158
+ Description=forgedock ci runner-health
159
+
160
+ [Service]
161
+ Type=oneshot
162
+ WorkingDirectory=${cwd}
163
+ ExecStart=${[node, cli, "ci", "runner-health", ...(recover ? ["--recover"] : [])].map(q).join(" ")}
164
+ `;
165
+ const timer = `[Unit]
166
+ Description=forgedock ci runner-health every 2 min
167
+
168
+ [Timer]
169
+ OnBootSec=60
170
+ OnUnitActiveSec=2min
171
+
172
+ [Install]
173
+ WantedBy=timers.target
174
+ `;
175
+ return { service, timer };
176
+ }
177
+
178
+ /** `forgedock ci runner-health ...`; @returns the exit code (1 when anything is unhealthy). */
179
+ export async function ciRunnerHealthFromCli(argv, deps = {}) {
180
+ const out = deps.out ?? ((l) => console.log(l)), cwd = deps.cwd ?? process.cwd(), env = deps.env ?? process.env;
181
+ const valued = ["--repo"], flags = ["--recover", "--json", "--print-units"];
182
+ const unknown = argv.find((a, i) => !flags.includes(a) && !valued.includes(a) && !valued.includes(argv[i - 1] ?? ""));
183
+ if (unknown) throw new Error(`unknown argument ${unknown}; ${RUNNER_HEALTH_USAGE}`);
184
+ const cfg = parseRunnerHealthConfig(cwd);
185
+ const ri = argv.indexOf("--repo");
186
+ if (ri >= 0) cfg.repo = str(argv[ri + 1]);
187
+ else if (!cfg.repo) cfg.repo = str(env.GITHUB_REPOSITORY);
188
+ if (argv.includes("--print-units")) {
189
+ const u = renderRunnerHealthUnits({ cwd, recover: cfg.recover });
190
+ out(`# forgedock-ci-runner-health.service\n${u.service}\n# forgedock-ci-runner-health.timer\n${u.timer}`);
191
+ return 0;
192
+ }
193
+ const d = { ...defaultDeps, ...deps }, nowMs = (deps.now ?? Date.now)();
194
+ const { findings, skipped } = await detectRunnerHealth(cfg, d);
195
+ const poster = createPoster({ env, fetchImpl: deps.fetchImpl ?? globalThis.fetch, warn: deps.warn });
196
+ for (const f of findings) {
197
+ poster.post("runner_unhealthy", { repo: cfg.repo || "unknown", sha: "runner-health", run_id: String(f.run_id ?? "runner-health"), job: f.job, step: f.kind, class: "infra", lines: [f.reason] });
198
+ }
199
+ await poster.drain();
200
+ const plan = planRecovery(findings);
201
+ const doRecover = argv.includes("--recover");
202
+ let actions = [];
203
+ if (doRecover && plan.length) actions = await applyRecovery(plan, { docker: d.docker, systemctl: d.systemctl, dir: deps.dir ?? cacheDir(env), nowMs, out });
204
+ if (argv.includes("--json")) out(JSON.stringify({ ok: !findings.length, findings, skipped, plan: doRecover ? undefined : plan, actions: doRecover ? actions : undefined }));
205
+ else {
206
+ for (const f of findings) out(`UNHEALTHY ${f.kind} ${f.job}: ${f.reason}`);
207
+ for (const s of skipped) out(`SKIP ${s}`);
208
+ if (!doRecover) for (const p of plan) out(`plan (dry run, pass --recover to act): ${p.action} ${p.service ?? p.id}`);
209
+ out(`runner-health: ${findings.length ? `${findings.length} finding(s)` : "healthy"}`);
210
+ }
211
+ return findings.length ? 1 : 0;
212
+ }
213
+
@@ -0,0 +1,113 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ import { test } from "node:test";
4
+ import assert from "node:assert/strict";
5
+ import { writeFileSync } from "node:fs";
6
+ import { join } from "node:path";
7
+ import { tmpDir } from "../tests/_tmp.mjs";
8
+ import { ciFromCli } from "./ci-budget.mjs";
9
+ import { ciRunnerHealthFromCli, detectRunnerHealth, planRecovery, applyRecovery, renderRunnerHealthUnits, parseRunnerHealthConfig, RESTART_COOLDOWN_MS } from "./ci-runner-health.mjs";
10
+
11
+ const NOW = Date.parse("2026-11-15T12:00:00Z");
12
+ const cfg = { repo: "o/r", services: ["actions.runner.o-r.r1.service", "actions.runner.o-r.r2.service"], minDiskGb: 10, jobTimeoutMin: 360 };
13
+ const ghFor = ({ busy = [], runs = [], jobs = {} } = {}) => async (a) => {
14
+ const u = a.join(" ");
15
+ if (/actions\/runners/.test(u)) return JSON.stringify({ runners: busy.map((name) => ({ name, busy: true })).concat([{ name: "idle", busy: false }]) });
16
+ if (/actions\/runs\?/.test(u)) return JSON.stringify({ workflow_runs: runs });
17
+ const m = /actions\/runs\/(\d+)\/jobs/.exec(u);
18
+ if (m) return JSON.stringify({ jobs: jobs[m[1]] ?? [] });
19
+ throw new Error(`unexpected ${u}`);
20
+ };
21
+ const cwdWith = () => { const d = tmpDir("crh-"); writeFileSync(join(d, "forge.yaml"), `ci:\n repo: o/r\n services:\n${cfg.services.map((x) => ` - ${x}`).join("\n")}\n`); return d; };
22
+ const healthy = (o = {}) => ({
23
+ now: () => NOW, gh: ghFor(), diskGb: () => 50, memGb: () => 8,
24
+ systemctl: async () => ({ code: 0, out: "active\n" }),
25
+ docker: async () => ({ code: 0, out: "" }),
26
+ ...o,
27
+ });
28
+ const kinds = async (o, c = cfg) => (await detectRunnerHealth(c, healthy(o))).findings.map((f) => f.kind);
29
+
30
+ test("healthy fixture: no findings, no events, exit 0", async () => {
31
+ const posts = [], lines = [];
32
+ const code = await ciRunnerHealthFromCli([], { cwd: tmpDir("crh-"), env: { FORGEDOCK_CI_EVENTS_URL: "http://x/ci/events", GITHUB_REPOSITORY: "o/r" }, out: (l) => lines.push(l), fetchImpl: async (u, i) => { posts.push(i.body); return { status: 202 }; }, ...healthy() });
33
+ assert.equal(code, 0); assert.equal(posts.length, 0); assert.match(lines.at(-1), /healthy/);
34
+ });
35
+
36
+ test("(a) busy runner on a cancelled run is stuck, mapped to its own service", async () => {
37
+ const o = { gh: ghFor({ busy: ["r1"], runs: [{ id: 7, status: "completed", conclusion: "cancelled" }], jobs: { 7: [{ id: 70, status: "in_progress", runner_name: "r1" }] } }) };
38
+ const r = await detectRunnerHealth(cfg, healthy(o));
39
+ assert.deepEqual(r.findings.map((f) => [f.kind, f.service]), [["stuck-run", "actions.runner.o-r.r1.service"]]);
40
+ // busy on a live run: not stuck
41
+ assert.deepEqual(await kinds({ gh: ghFor({ busy: ["r1"], runs: [{ id: 8, status: "in_progress", conclusion: null }] }) }), []);
42
+ });
43
+
44
+ test("(b) inactive service", async () => {
45
+ const f = (await detectRunnerHealth(cfg, healthy({ systemctl: async (a) => ({ code: 3, out: a[1].includes(".r2.") ? "failed\n" : "active\n" }) }))).findings;
46
+ assert.deepEqual(f.map((x) => [x.kind, x.service]), [["service-down", cfg.services[1]]]);
47
+ });
48
+
49
+ test("(c) only old runner-labelled containers are orphaned", async () => {
50
+ const row = (ID, CreatedAt, Labels) => JSON.stringify({ ID, CreatedAt, Labels });
51
+ const docker = async () => ({ code: 0, out: [row("old1", "2026-11-15 01:00:00 +0000 UTC", "com.github.actions.runner=r1"), row("new1", "2026-11-15 11:00:00 +0000 UTC", "com.github.actions.runner=r1"), row("other", "2026-11-01 01:00:00 +0000 UTC", "app=db")].join("\n") });
52
+ const f = (await detectRunnerHealth(cfg, healthy({ docker }))).findings;
53
+ assert.deepEqual(f.map((x) => x.id), ["old1"]);
54
+ });
55
+
56
+ test("(d) low disk and low memory", async () => {
57
+ assert.deepEqual(await kinds({ diskGb: () => 3 }), ["low-disk"]);
58
+ assert.deepEqual(await kinds({ memGb: () => 0.4 }), ["low-memory"]);
59
+ assert.deepEqual(await kinds({ diskGb: () => 5 }, { ...cfg, minDiskGb: 4 }), []);
60
+ });
61
+
62
+ test("each finding posts one runner_unhealthy event the bus accepts", async () => {
63
+ const { validateEvent } = await import("../pool/ci-events.mjs");
64
+ const posts = [];
65
+ const code = await ciRunnerHealthFromCli(["--json"], { cwd: tmpDir("crh-"), env: { FORGEDOCK_CI_EVENTS_URL: "http://x/ci/events", GITHUB_REPOSITORY: "o/r" }, out: () => {}, fetchImpl: async (u, i) => { posts.push(JSON.parse(i.body)); return { status: 202 }; }, ...healthy({ diskGb: () => 1, memGb: () => 0.1 }) });
66
+ assert.equal(code, 1); assert.equal(posts.length, 2);
67
+ for (const p of posts) { assert.equal(validateEvent(p).type, "runner_unhealthy"); assert.equal(p.class, "infra"); }
68
+ });
69
+
70
+ test("dry run is the default: prints the plan and acts on nothing", async () => {
71
+ const calls = [], lines = [];
72
+ const o = healthy({ systemctl: async (a) => { calls.push(a); return { code: 3, out: "inactive\n" }; }, docker: async (a) => { calls.push(a); return { code: 0, out: "" }; } });
73
+ await ciRunnerHealthFromCli(["--repo", "o/r"], { cwd: cwdWith(), env: {}, out: (l) => lines.push(l), dir: tmpDir("crh-d-"), ...o });
74
+ assert.ok(calls.every((a) => a[0] === "is-active" || a[0] === "ps"));
75
+ assert.ok(lines.some((l) => /plan \(dry run/.test(l)));
76
+ });
77
+
78
+ test("--recover restarts only the affected service and removes only orphans", async () => {
79
+ const calls = [], dir = tmpDir("crh-d-");
80
+ const row = JSON.stringify({ ID: "old1", CreatedAt: "2026-11-15 01:00:00 +0000 UTC", Labels: "com.github.actions.runner=r1" });
81
+ const systemctl = async (a) => { calls.push(["sc", ...a]); return { code: 0, out: a[0] === "is-active" ? (a[1].includes(".r2.") ? "failed\n" : "active\n") : "" }; };
82
+ const docker = async (a) => { calls.push(["dk", ...a]); return { code: 0, out: a[0] === "ps" ? row : "" }; };
83
+ await ciRunnerHealthFromCli(["--recover"], { cwd: cwdWith(), env: {}, out: () => {}, dir, ...healthy({ systemctl, docker }), now: () => NOW });
84
+ assert.deepEqual(calls.filter((c) => c[1] === "restart" || c[1] === "rm"), [["sc", "restart", cfg.services[1]], ["dk", "rm", "-f", "old1"]]);
85
+ });
86
+
87
+ test("recovery is idempotent and rate limited to one restart per service per 10 min", async () => {
88
+ const calls = [], dir = tmpDir("crh-d-"), lines = [];
89
+ const deps = { systemctl: async (a) => { calls.push(a); return { code: 0, out: "" }; }, docker: async () => ({ code: 0, out: "" }), dir, out: (l) => lines.push(l) };
90
+ const plan = planRecovery([{ kind: "service-down", service: "s1", reason: "x" }, { kind: "stuck-run", service: "s1", reason: "y" }]);
91
+ assert.equal(plan.length, 1);
92
+ await applyRecovery(plan, { ...deps, nowMs: NOW });
93
+ await applyRecovery(plan, { ...deps, nowMs: NOW + 60000 });
94
+ assert.equal(calls.length, 1); assert.ok(lines.some((l) => /cooldown/.test(l)));
95
+ await applyRecovery(plan, { ...deps, nowMs: NOW + RESTART_COOLDOWN_MS + 1 });
96
+ assert.equal(calls.length, 2);
97
+ });
98
+
99
+ test("timer unit runs every 2 min; --recover only when configured; config parses", () => {
100
+ const u = renderRunnerHealthUnits({ node: "/n", cli: "/c.mjs", cwd: "/w", recover: true });
101
+ assert.match(u.timer, /OnUnitActiveSec=2min/); assert.match(u.service, /"ci" "runner-health" "--recover"/);
102
+ assert.doesNotMatch(renderRunnerHealthUnits({ node: "/n", cli: "/c.mjs", cwd: "/w" }).service, /--recover/);
103
+ const dir = tmpDir("crh-");
104
+ writeFileSync(join(dir, "forge.yaml"), "ci:\n repo: o/r\n min_disk_gb: 20\n recover: true\n services:\n - a.service\n - b.service\n");
105
+ assert.deepEqual(parseRunnerHealthConfig(dir), { repo: "o/r", services: ["a.service", "b.service"], minDiskGb: 20, recover: true, jobTimeoutMin: 360 });
106
+ });
107
+
108
+ test("ci runner-health routes through ciFromCli; unknown argument throws", async () => {
109
+ const lines = [];
110
+ const code = await ciFromCli(["runner-health", "--print-units"], { out: (l) => lines.push(l), cwd: tmpDir("crh-") });
111
+ assert.equal(code, 0); assert.match(lines.join("\n"), /OnUnitActiveSec=2min/);
112
+ await assert.rejects(() => ciRunnerHealthFromCli(["--bogus"], {}), /unknown argument/);
113
+ });