forgedock 1.54.1 → 1.55.1
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/bin/config-schema.mjs +12 -0
- package/bin/engine/events.mjs +1 -0
- package/bin/engine/events.test.mjs +5 -1
- package/bin/engine/outcome-codes.mjs +3 -0
- package/bin/engine-cli.mjs +126 -34
- package/bin/forge-utils.mjs +37 -5
- package/bin/forgedock.mjs +54 -2
- package/bin/gc-schedule.mjs +83 -0
- package/bin/gc.mjs +66 -10
- package/bin/help-text.mjs +1 -1
- package/bin/hooks/pre-tool-use.mjs +1 -0
- package/bin/init-detect.mjs +73 -2
- package/bin/labels.json +5 -0
- package/bin/lean/admission.mjs +21 -1
- package/bin/lean/baselines.mjs +43 -0
- package/bin/lean/baselines.test.mjs +33 -0
- package/bin/lean/batch-health.mjs +43 -6
- package/bin/lean/batch-health.test.mjs +41 -1
- package/bin/lean/batch.mjs +41 -4
- package/bin/lean/batch.test.mjs +106 -3
- package/bin/lean/conformance.mjs +131 -12
- package/bin/lean/conformance.test.mjs +172 -3
- package/bin/lean/depcache.mjs +23 -2
- package/bin/lean/depcache.test.mjs +22 -0
- package/bin/lean/docsgate.mjs +137 -0
- package/bin/lean/docsgate.test.mjs +78 -0
- package/bin/lean/effects.mjs +31 -2
- package/bin/lean/enumerating.mjs +39 -13
- package/bin/lean/enumerating.test.mjs +20 -0
- package/bin/lean/execution.test.mjs +3 -3
- package/bin/lean/fastforward.mjs +93 -0
- package/bin/lean/fastforward.test.mjs +73 -0
- package/bin/lean/guardgate.mjs +38 -7
- package/bin/lean/guardgate.test.mjs +39 -0
- package/bin/lean/issuewatch-install.mjs +92 -0
- package/bin/lean/issuewatch-install.test.mjs +31 -0
- package/bin/lean/issuewatch-parity.mjs +33 -3
- package/bin/lean/issuewatch-parity.test.mjs +30 -5
- package/bin/lean/issuewatch-reconcile.mjs +123 -0
- package/bin/lean/issuewatch-reconcile.test.mjs +30 -0
- package/bin/lean/issuewatch-verify.mjs +51 -9
- package/bin/lean/issuewatch.mjs +153 -33
- package/bin/lean/issuewatch.test.mjs +243 -22
- package/bin/lean/lean.mjs +381 -75
- package/bin/lean/lean.test.mjs +437 -20
- package/bin/lean/light.mjs +11 -3
- package/bin/lean/light.test.mjs +27 -0
- package/bin/lean/lightlane.mjs +8 -3
- package/bin/lean/lightlane.test.mjs +20 -0
- package/bin/lean/mechfix.mjs +21 -2
- package/bin/lean/mechfix.test.mjs +28 -1
- package/bin/lean/orchestrate-children.test.mjs +10 -0
- package/bin/lean/orchestrate-owned.test.mjs +73 -0
- package/bin/lean/orchestrate.mjs +28 -4
- package/bin/lean/overlap.mjs +20 -0
- package/bin/lean/overlap.test.mjs +49 -0
- package/bin/lean/pagegate.mjs +152 -0
- package/bin/lean/pagegate.test.mjs +77 -0
- package/bin/lean/parked-relabel.mjs +32 -0
- package/bin/lean/parked-relabel.test.mjs +45 -0
- package/bin/lean/phaseledger.mjs +17 -2
- package/bin/lean/postdeploy-check.mjs +27 -0
- package/bin/lean/postdeploy-check.test.mjs +13 -1
- package/bin/lean/postrun.mjs +32 -0
- package/bin/lean/postrun.test.mjs +41 -0
- package/bin/lean/preflight.mjs +46 -0
- package/bin/lean/preflight.test.mjs +30 -1
- package/bin/lean/prompts.mjs +36 -6
- package/bin/lean/recovery.test.mjs +16 -0
- package/bin/lean/release-review.mjs +12 -1
- package/bin/lean/release-review.test.mjs +14 -0
- package/bin/lean/release.mjs +23 -2
- package/bin/lean/release.test.mjs +28 -1
- package/bin/lean/render.mjs +17 -6
- package/bin/lean/reproquality.mjs +116 -0
- package/bin/lean/reproquality.test.mjs +85 -0
- package/bin/lean/review-trigger.mjs +8 -3
- package/bin/lean/sandbox-budget.test.mjs +27 -0
- package/bin/lean/schedd.mjs +40 -11
- package/bin/lean/schedd.test.mjs +12 -1
- package/bin/lean/testadequacy.mjs +97 -0
- package/bin/lean/testadequacy.test.mjs +92 -0
- package/bin/lean/testsandbox.mjs +202 -0
- package/bin/lean/testsandbox.test.mjs +157 -0
- package/bin/lean/toolplace.mjs +5 -2
- package/bin/lean/toolplace.test.mjs +6 -0
- package/bin/lean/verify.mjs +6 -1
- package/bin/lean/verify.test.mjs +18 -2
- package/bin/lean/warmtree.mjs +77 -0
- package/bin/lean/warmtree.test.mjs +81 -0
- package/bin/review-staging.mjs +51 -9
- package/bin/stats/conformance-outcomes.mjs +12 -2
- package/bin/stats/depth.mjs +24 -1
- package/bin/stats/depth.test.mjs +21 -1
- package/bin/stats/index.mjs +5 -2
- package/bin/stats/query.mjs +2 -1
- package/commands/cleanup.md +18 -0
- package/commands/fd-introspect.md +19 -0
- package/commands/milestone.md +5 -1
- package/commands/pipeline-health/phase-2-metrics.md +4 -0
- package/commands/recover-orphans.md +31 -1
- package/commands/review-pr-staging.md +9 -0
- package/commands/review-pr.md +2 -0
- package/docs/CONFIG.md +26 -1
- package/docs/EVENTS.md +1 -0
- package/docs/ISSUE-WATCH.md +12 -3
- package/docs/eval/adversarial-bench.md +1 -1
- package/docs/eval/published/adversarial-2026-11-11.md +58 -0
- package/package.json +1 -1
- package/scripts/bench-lightlane.mjs +3 -2
- package/scripts/hotspots.sh +7 -4
- package/scripts/hotspots.test.sh +12 -0
- package/scripts/recover-orphans-stateless.test.sh +79 -0
- package/scripts/transition-label.sh +2 -0
- package/templates/workflows/forgedock-reopen-clean.yml +33 -0
package/bin/lean/guardgate.mjs
CHANGED
|
@@ -174,16 +174,47 @@ export async function runGuards({ selected, mergeBase, contract, guardCommand, g
|
|
|
174
174
|
const fresh = lane.filter((n) => !prior.includes(n));
|
|
175
175
|
return fresh.length ? { fresh } : { skip: "fails on base" };
|
|
176
176
|
};
|
|
177
|
+
/** Write the base copy of a job's test next to the lane's tree; false (with the skip recorded) when it cannot be made. */
|
|
178
|
+
const materialize = async (j) => {
|
|
179
|
+
let body;
|
|
180
|
+
try { body = await git(["show", `${mergeBase}:${j.path}`]); } catch { skipped.push(`#${j.guard.issue} ${j.path}: not on base`); return false; }
|
|
181
|
+
const abs = join(cwd, j.copy);
|
|
182
|
+
try { fs.mkdirSync(dirname(abs), { recursive: true }); fs.writeFileSync(abs, body); made.push(abs); return true; } catch (e) { skipped.push(`#${j.guard.issue} ${j.path}: ${String(e?.message ?? e).slice(0, 80)}`); return false; }
|
|
183
|
+
};
|
|
184
|
+
let batches = 0;
|
|
185
|
+
/** #5436: jobs whose command differs only by a trailing path run as one invocation over the union of their base copies. Green = every job passed; anything else leaves the jobs to the per-file runs (attribution and the baseline comparison stay per file). Returns the jobs it settled. */
|
|
186
|
+
const runBatches = async () => {
|
|
187
|
+
const groups = new Map();
|
|
188
|
+
for (const j of jobs) {
|
|
189
|
+
const s = `@@guard@@${extname(j.path)}`, key = commandFor(s, contract, guardCommand);
|
|
190
|
+
if (!key || !key.endsWith(s) || key.indexOf(s) !== key.lastIndexOf(s)) continue;
|
|
191
|
+
const prefix = key.slice(0, key.length - s.length);
|
|
192
|
+
groups.set(prefix, [...(groups.get(prefix) ?? []), j]);
|
|
193
|
+
}
|
|
194
|
+
const settled = new Set();
|
|
195
|
+
await Promise.all([...groups].filter(([, js]) => new Set(js.map((j) => j.path)).size > 1).map(async ([prefix, js]) => {
|
|
196
|
+
if (capMs - (now() - t0) <= 0) return;
|
|
197
|
+
const ready = [];
|
|
198
|
+
for (const j of js) { if (await materialize(j)) ready.push(j); else settled.add(j); }
|
|
199
|
+
const copies = [...new Set(ready.map((j) => j.copy))];
|
|
200
|
+
if (copies.length < 2) return;
|
|
201
|
+
const command = `${prefix}${copies.join(" ")}`;
|
|
202
|
+
let r;
|
|
203
|
+
try { r = await runCommand({ command, cwd, timeoutMs: capMs - (now() - t0), env }); } catch (e) { r = { rc: 127, output: String(e?.message ?? e) }; }
|
|
204
|
+
if (r?.rc !== 0) return;
|
|
205
|
+
batches++;
|
|
206
|
+
for (const j of ready) { settled.add(j); runs.push({ issue: j.guard.issue, why: j.guard.why, test: j.path, command, rc: 0, output: String(r?.output ?? ""), failed: null }); }
|
|
207
|
+
}));
|
|
208
|
+
return settled;
|
|
209
|
+
};
|
|
177
210
|
try {
|
|
178
|
-
const
|
|
211
|
+
const done = await runBatches();
|
|
212
|
+
const queue = jobs.filter((j) => !done.has(j));
|
|
179
213
|
const work = async () => {
|
|
180
214
|
for (let j = queue.shift(); j; j = queue.shift()) {
|
|
181
215
|
const left = capMs - (now() - t0);
|
|
182
216
|
if (left <= 0) { skipped.push(`#${j.guard.issue} ${j.path}: over the ${Math.round(capMs / 1000)}s guard cap`); continue; }
|
|
183
|
-
|
|
184
|
-
try { body = await git(["show", `${mergeBase}:${j.path}`]); } catch { skipped.push(`#${j.guard.issue} ${j.path}: not on base`); continue; }
|
|
185
|
-
const abs = join(cwd, j.copy);
|
|
186
|
-
try { fs.mkdirSync(dirname(abs), { recursive: true }); fs.writeFileSync(abs, body); made.push(abs); } catch (e) { skipped.push(`#${j.guard.issue} ${j.path}: ${String(e?.message ?? e).slice(0, 80)}`); continue; }
|
|
217
|
+
if (!(await materialize(j))) continue;
|
|
187
218
|
let r;
|
|
188
219
|
try { r = await runCommand({ command: j.command, cwd, timeoutMs: left, env }); } catch (e) { r = { rc: 127, output: String(e?.message ?? e) }; }
|
|
189
220
|
if (r?.rc === TIMEOUT_RC) { skipped.push(`#${j.guard.issue} ${j.path}: over the ${Math.round(capMs / 1000)}s guard cap`); continue; }
|
|
@@ -198,7 +229,7 @@ export async function runGuards({ selected, mergeBase, contract, guardCommand, g
|
|
|
198
229
|
runs.push({ issue: j.guard.issue, why: j.guard.why, test: j.path, command: j.command, rc, output, failed });
|
|
199
230
|
}
|
|
200
231
|
};
|
|
201
|
-
await Promise.all(Array.from({ length: Math.max(1, Math.min(parallelism,
|
|
232
|
+
await Promise.all(Array.from({ length: Math.max(1, Math.min(parallelism, queue.length)) }, work));
|
|
202
233
|
} finally {
|
|
203
234
|
for (const p of made) { try { fs.rmSync(p, { force: true }); } catch { /* best effort */ } }
|
|
204
235
|
const t = base ? await base : null;
|
|
@@ -208,7 +239,7 @@ export async function runGuards({ selected, mergeBase, contract, guardCommand, g
|
|
|
208
239
|
try { await git(["worktree", "prune"]); } catch { /* best effort */ }
|
|
209
240
|
}
|
|
210
241
|
}
|
|
211
|
-
return { failures: guardFailures(runs), runs, skipped, ms: now() - t0 };
|
|
242
|
+
return { failures: guardFailures(runs), runs, skipped, batches, ms: now() - t0 };
|
|
212
243
|
}
|
|
213
244
|
|
|
214
245
|
/** The only override of a guard_broken failure, named for the builder (#4883); leads the detail so the resume prompt's truncation keeps it. */
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
3
|
import test from "node:test";
|
|
4
4
|
import assert from "node:assert/strict";
|
|
5
|
+
import * as nodeFs from "node:fs";
|
|
5
6
|
import { execFileSync, spawnSync } from "node:child_process";
|
|
6
7
|
import { existsSync, mkdirSync, readdirSync, writeFileSync } from "node:fs";
|
|
7
8
|
import { join } from "node:path";
|
|
@@ -295,3 +296,41 @@ test("failingNames reads TAP, spec and pytest output and ignores skips", () => {
|
|
|
295
296
|
assert.deepEqual(failingNames("FAILED tests/t.py::test_x - assert 1 == 2"), ["tests/t.py::test_x"]);
|
|
296
297
|
assert.equal(failingNames("all fine"), null);
|
|
297
298
|
});
|
|
299
|
+
|
|
300
|
+
test("guards sharing one runner run as one invocation over the union of base copies; a red batch falls back per file (#5436)", async () => {
|
|
301
|
+
const guard = (issue, path) => ({ v: 1, issue, pr: issue, merge_sha: "a".repeat(40), tests: [{ path, ids: [] }], hunks: [], why: `g${issue}` });
|
|
302
|
+
const selected = [{ guard: guard(1, "src/a.test.mjs"), reason: "r" }, { guard: guard(2, "src/b.test.mjs"), reason: "r" }, { guard: guard(3, "src/a.test.mjs"), reason: "r" }];
|
|
303
|
+
const fs = { ...nodeFs, mkdirSync() {}, writeFileSync() {}, rmSync() {} };
|
|
304
|
+
const git = async () => "body";
|
|
305
|
+
const calls = [];
|
|
306
|
+
const green = await runGuards({ selected, mergeBase: "base", contract: {}, git, fs, cwd: "/w", env: {}, runCommand: async (a) => { calls.push(a.command); return { rc: 0, output: "ok" }; } });
|
|
307
|
+
assert.deepEqual(calls, ["node --test src/a.test__guardbase.mjs src/b.test__guardbase.mjs"]);
|
|
308
|
+
assert.equal(green.runs.length, 3);
|
|
309
|
+
assert.equal(green.batches, 1);
|
|
310
|
+
assert.equal(green.failures.length, 0);
|
|
311
|
+
const seen = [];
|
|
312
|
+
const red = await runGuards({ selected: selected.slice(0, 2), mergeBase: "base", contract: {}, git, fs, cwd: "/w", env: {}, runCommand: async (a) => {
|
|
313
|
+
seen.push(a.command);
|
|
314
|
+
return a.cwd !== "/w" || /a\.test__guardbase\.mjs$/.test(a.command) ? { rc: 0, output: "ok" } : { rc: 1, output: "not ok 1 - b\n" };
|
|
315
|
+
} });
|
|
316
|
+
assert.equal(seen[0], "node --test src/a.test__guardbase.mjs src/b.test__guardbase.mjs");
|
|
317
|
+
assert.ok(seen.length > 2, "the failed batch reran per file");
|
|
318
|
+
assert.equal(red.batches, 0);
|
|
319
|
+
assert.deepEqual(red.failures.map((f) => f.guard), ["#2"], "the failing guard is still attributed to its own test");
|
|
320
|
+
});
|
|
321
|
+
|
|
322
|
+
test("a template that does not end in the path is never batched", async () => {
|
|
323
|
+
const guard = (issue, path) => ({ v: 1, issue, pr: issue, merge_sha: "a".repeat(40), tests: [{ path, ids: [] }], hunks: [], why: "w" });
|
|
324
|
+
const fs = { ...nodeFs, mkdirSync() {}, writeFileSync() {}, rmSync() {} };
|
|
325
|
+
const calls = [];
|
|
326
|
+
await runGuards({ selected: [{ guard: guard(1, "a.test.mjs"), reason: "r" }, { guard: guard(2, "b.test.mjs"), reason: "r" }], mergeBase: "b", contract: {}, guardCommand: { ".mjs": "run {path} --quiet" }, git: async () => "x", fs, cwd: "/w", env: {}, runCommand: async (a) => { calls.push(a.command); return { rc: 0, output: "" }; } });
|
|
327
|
+
assert.deepEqual(calls.sort(), ["run a.test__guardbase.mjs --quiet", "run b.test__guardbase.mjs --quiet"]);
|
|
328
|
+
});
|
|
329
|
+
|
|
330
|
+
test("a template that repeats the path is never batched", async () => {
|
|
331
|
+
const guard = (issue, path) => ({ v: 1, issue, pr: issue, merge_sha: "a".repeat(40), tests: [{ path, ids: [] }], hunks: [], why: "w" });
|
|
332
|
+
const fs = { ...nodeFs, mkdirSync() {}, writeFileSync() {}, rmSync() {} };
|
|
333
|
+
const calls = [];
|
|
334
|
+
await runGuards({ selected: [{ guard: guard(1, "a.test.mjs"), reason: "r" }, { guard: guard(2, "b.test.mjs"), reason: "r" }], mergeBase: "b", contract: {}, guardCommand: { ".mjs": "run {path} {path}" }, git: async () => "x", fs, cwd: "/w", env: {}, runCommand: async (a) => { calls.push(a.command); return { rc: 0, output: "" }; } });
|
|
335
|
+
assert.ok(calls.every((c) => !c.includes("a.test__guardbase.mjs") || !c.includes("b.test__guardbase.mjs")), "no single invocation spans both files");
|
|
336
|
+
});
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
/**
|
|
4
|
+
* `forgedock issue-watch install` (#5465): run one watch as a supervised unit, like `forgedock-schedd` (pool/install/install-schedd.sh).
|
|
5
|
+
* systemd user unit with `Restart=on-failure` (a finished watch exits 0 and stays down) plus a watchdog timer that runs
|
|
6
|
+
* `issue-watch watchdog` to alert on a dead heartbeat; launchd agent with `KeepAlive.SuccessfulExit=false` on macOS. No LLM calls.
|
|
7
|
+
*/
|
|
8
|
+
import { mkdirSync, writeFileSync } from "node:fs";
|
|
9
|
+
import { spawnSync } from "node:child_process";
|
|
10
|
+
import { homedir } from "node:os";
|
|
11
|
+
import { join } from "node:path";
|
|
12
|
+
|
|
13
|
+
const safe = (s) => String(s).replace(/[^\w.-]/g, "_");
|
|
14
|
+
const quote = (s) => (/[\s"\\]/.test(s) ? `"${s.replace(/(["\\])/g, "\\$1")}"` : s);
|
|
15
|
+
|
|
16
|
+
export const watchUnitName = (name) => `forgedock-issue-watch-${safe(name)}`;
|
|
17
|
+
|
|
18
|
+
/** The argv after `forgedock.mjs` that runs the watch. */
|
|
19
|
+
const runArgs = ({ name, repo, interval }) => ["issue-watch", "run", "--name", name, ...(repo ? ["--repo", repo] : []), ...(interval ? ["--interval", String(interval)] : [])];
|
|
20
|
+
|
|
21
|
+
export function renderSystemdUnit({ node, cli, name, repo, interval, cwd }) {
|
|
22
|
+
return `[Unit]
|
|
23
|
+
Description=forgedock issue-watch ${name}
|
|
24
|
+
StartLimitIntervalSec=0
|
|
25
|
+
|
|
26
|
+
[Service]
|
|
27
|
+
WorkingDirectory=${cwd}
|
|
28
|
+
ExecStart=${[node, cli, ...runArgs({ name, repo, interval })].map(quote).join(" ")}
|
|
29
|
+
Restart=on-failure
|
|
30
|
+
RestartSec=30
|
|
31
|
+
|
|
32
|
+
[Install]
|
|
33
|
+
WantedBy=default.target
|
|
34
|
+
`;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function renderWatchdog({ node, cli, name, cwd }) {
|
|
38
|
+
const service = `[Unit]
|
|
39
|
+
Description=forgedock issue-watch ${name} watchdog
|
|
40
|
+
|
|
41
|
+
[Service]
|
|
42
|
+
Type=oneshot
|
|
43
|
+
WorkingDirectory=${cwd}
|
|
44
|
+
ExecStart=${[node, cli, "issue-watch", "watchdog"].map(quote).join(" ")}
|
|
45
|
+
`;
|
|
46
|
+
const timer = `[Unit]
|
|
47
|
+
Description=forgedock issue-watch ${name} watchdog
|
|
48
|
+
|
|
49
|
+
[Timer]
|
|
50
|
+
OnBootSec=60
|
|
51
|
+
OnUnitActiveSec=60s
|
|
52
|
+
|
|
53
|
+
[Install]
|
|
54
|
+
WantedBy=timers.target
|
|
55
|
+
`;
|
|
56
|
+
return { service, timer };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function renderLaunchdPlist({ node, cli, name, repo, interval, cwd }) {
|
|
60
|
+
const args = [node, cli, ...runArgs({ name, repo, interval })].map((a) => ` <string>${String(a).replace(/&/g, "&").replace(/</g, "<")}</string>`).join("\n");
|
|
61
|
+
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
62
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
63
|
+
<plist version="1.0"><dict>
|
|
64
|
+
<key>Label</key><string>com.forgedock.issue-watch.${safe(name)}</string>
|
|
65
|
+
<key>ProgramArguments</key><array>
|
|
66
|
+
${args}
|
|
67
|
+
</array>
|
|
68
|
+
<key>WorkingDirectory</key><string>${cwd}</string>
|
|
69
|
+
<key>RunAtLoad</key><true/>
|
|
70
|
+
<key>KeepAlive</key><dict><key>SuccessfulExit</key><false/></dict>
|
|
71
|
+
<key>ThrottleInterval</key><integer>30</integer>
|
|
72
|
+
</dict></plist>
|
|
73
|
+
`;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Writes and starts the unit; `{files, platform}`. `run(cmd, args)` and `write(path, text)` are injectable. */
|
|
77
|
+
export function installWatchUnit({ name, repo, interval, cwd = process.cwd(), node = process.execPath, cli, platform = process.platform, home = homedir(), run = (c, a) => spawnSync(c, a, { stdio: "ignore" }), write = (p, t) => { mkdirSync(join(p, ".."), { recursive: true }); writeFileSync(p, t); } }) {
|
|
78
|
+
const o = { node, cli, name, repo, interval, cwd }, files = [];
|
|
79
|
+
if (platform === "darwin") {
|
|
80
|
+
const f = join(home, "Library", "LaunchAgents", `com.forgedock.issue-watch.${safe(name)}.plist`);
|
|
81
|
+
write(f, renderLaunchdPlist(o)); files.push(f);
|
|
82
|
+
run("launchctl", ["unload", f]); run("launchctl", ["load", "-w", f]);
|
|
83
|
+
return { files, platform };
|
|
84
|
+
}
|
|
85
|
+
if (platform !== "linux") throw new Error(`issue-watch install: unsupported platform ${platform} (systemd or launchd only)`);
|
|
86
|
+
const dir = join(home, ".config", "systemd", "user"), u = watchUnitName(name), w = renderWatchdog(o);
|
|
87
|
+
for (const [n, t] of [[`${u}.service`, renderSystemdUnit(o)], [`${u}-watchdog.service`, w.service], [`${u}-watchdog.timer`, w.timer]]) { write(join(dir, n), t); files.push(join(dir, n)); }
|
|
88
|
+
run("systemctl", ["--user", "daemon-reload"]);
|
|
89
|
+
run("systemctl", ["--user", "enable", "--now", `${u}.service`]);
|
|
90
|
+
run("systemctl", ["--user", "enable", "--now", `${u}-watchdog.timer`]);
|
|
91
|
+
return { files, platform };
|
|
92
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
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 { renderSystemdUnit, renderWatchdog, renderLaunchdPlist, installWatchUnit, watchUnitName } from "./issuewatch-install.mjs";
|
|
6
|
+
|
|
7
|
+
const o = { node: "/usr/bin/node", cli: "/x/forgedock.mjs", name: "nomilestone", repo: "o/r", cwd: "/work dir" };
|
|
8
|
+
|
|
9
|
+
test("#5465 systemd unit restarts on failure and runs the named watch from the repo dir", () => {
|
|
10
|
+
const u = renderSystemdUnit(o);
|
|
11
|
+
assert.match(u, /^Restart=on-failure$/m);
|
|
12
|
+
assert.match(u, /^WorkingDirectory=\/work dir$/m);
|
|
13
|
+
assert.match(u, /ExecStart=\/usr\/bin\/node \/x\/forgedock\.mjs issue-watch run --name nomilestone --repo o\/r$/m);
|
|
14
|
+
assert.match(renderWatchdog(o).service, /issue-watch watchdog/);
|
|
15
|
+
assert.match(renderWatchdog(o).timer, /OnUnitActiveSec=60s/);
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
test("#5465 launchd plist keeps the agent alive only after a failed exit", () => {
|
|
19
|
+
const p = renderLaunchdPlist(o);
|
|
20
|
+
assert.match(p, /<key>SuccessfulExit<\/key><false\/>/);
|
|
21
|
+
assert.match(p, /<string>issue-watch<\/string>/);
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
test("#5465 installWatchUnit writes three systemd files and enables them; other platforms are refused", () => {
|
|
25
|
+
const written = [], ran = [];
|
|
26
|
+
const r = installWatchUnit({ ...o, platform: "linux", home: "/h", run: (c, a) => ran.push([c, ...a].join(" ")), write: (p) => written.push(p) });
|
|
27
|
+
assert.equal(written.length, 3); assert.equal(r.files.length, 3);
|
|
28
|
+
assert.ok(written[0].endsWith(`${watchUnitName("nomilestone")}.service`));
|
|
29
|
+
assert.ok(ran.some((l) => /enable --now forgedock-issue-watch-nomilestone\.service/.test(l)));
|
|
30
|
+
assert.throws(() => installWatchUnit({ ...o, platform: "win32" }), /unsupported platform/);
|
|
31
|
+
});
|
|
@@ -6,13 +6,14 @@
|
|
|
6
6
|
* and the heartbeat liveness read by `issue-watch status` and doctor. No LLM calls; gh and the clock are injected.
|
|
7
7
|
*/
|
|
8
8
|
import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
|
|
9
|
+
import { writeAtomic } from "./batch.mjs";
|
|
9
10
|
import { join } from "node:path";
|
|
10
11
|
import { RELEASE_STEPS } from "./release.mjs";
|
|
11
12
|
|
|
12
13
|
export const DEFAULT_SKIP_LABELS = ["epic", "needs-human", "post-deploy", "workflow:merged", "awaiting-promotion", "host-task"];
|
|
13
14
|
/** A release job that has not written its end `status` for this long is taken as dead, not in flight. */
|
|
14
15
|
export const RELEASE_STALE_MS = 6 * 3600 * 1000;
|
|
15
|
-
/** A heartbeat older than this many passes is reported
|
|
16
|
+
/** A heartbeat older than this many passes is reported dead. */
|
|
16
17
|
export const HEARTBEAT_PASSES = 3;
|
|
17
18
|
|
|
18
19
|
/** True when a listed item is a pull request (GitHub shares the number space; the bash watcher claimed PRs). */
|
|
@@ -52,13 +53,42 @@ export function releaseInFlight({ root, repo = null, now = Date.now(), staleMs =
|
|
|
52
53
|
return best;
|
|
53
54
|
}
|
|
54
55
|
|
|
55
|
-
/** `{state: "running"|"paused"|"
|
|
56
|
+
/** `{state: "running"|"paused"|"dead"|"exited"|"done"|"unknown", reason, ageMs}` from a watch's status.json: never a process grep. */
|
|
56
57
|
export function watchLiveness(status, now = Date.now()) {
|
|
57
58
|
if (!status) return { state: "unknown", reason: "no status yet", ageMs: null };
|
|
58
59
|
const beat = Date.parse(status.heartbeat ?? "");
|
|
59
60
|
if (status.phase === "done") return { state: "done", reason: "watch finished", ageMs: Number.isFinite(beat) ? now - beat : null };
|
|
61
|
+
if (status.phase === "exited") return { state: "exited", reason: status.exitReason ?? "exited", ageMs: Number.isFinite(beat) ? now - beat : null };
|
|
60
62
|
if (!Number.isFinite(beat)) return { state: "unknown", reason: "no heartbeat recorded", ageMs: null };
|
|
61
63
|
const ageMs = Math.max(0, now - beat), limit = HEARTBEAT_PASSES * (status.heartbeatEveryMs || 300000) + 60000;
|
|
62
|
-
if (ageMs > limit) return { state: "
|
|
64
|
+
if (ageMs > limit) return { state: "dead", reason: `last heartbeat ${Math.round(ageMs / 60000)}m ago, over ${Math.round(limit / 60000)}m: the watch is not running`, ageMs };
|
|
63
65
|
return status.paused ? { state: "paused", reason: status.paused.reason, ageMs } : { state: "running", reason: "heartbeat fresh", ageMs };
|
|
64
66
|
}
|
|
67
|
+
|
|
68
|
+
/** #5465: `[{repo, name, dir, status, live}]` for every watch under `root` (`<root>/<owner>__<repo>/<name>/status.json`). */
|
|
69
|
+
export function listWatches(root, now = Date.now()) {
|
|
70
|
+
const out = [];
|
|
71
|
+
try {
|
|
72
|
+
for (const r of readdirSync(root)) for (const n of readdirSync(join(root, r), { withFileTypes: true })) {
|
|
73
|
+
if (!n.isDirectory()) continue;
|
|
74
|
+
const dir = join(root, r, n.name);
|
|
75
|
+
let status = null; try { status = JSON.parse(readFileSync(join(dir, "status.json"), "utf8")); } catch { continue; }
|
|
76
|
+
out.push({ repo: status.repo ?? r.replace("__", "/"), name: status.name ?? n.name, dir, status, live: watchLiveness(status, now) });
|
|
77
|
+
}
|
|
78
|
+
} catch { /* no watch root yet */ }
|
|
79
|
+
return out;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* #5465: alert once per dead heartbeat. `emit(type, data, {repo})` posts the `watch.dead` event; the heartbeat that was alerted
|
|
84
|
+
* is saved as `deadAlerted` in status.json so a later pass stays quiet until the watch lives and dies again. Returns the dead watches.
|
|
85
|
+
*/
|
|
86
|
+
export async function alertDeadWatches({ root, now = Date.now(), emit }) {
|
|
87
|
+
const dead = listWatches(root, now).filter((w) => w.live.state === "dead");
|
|
88
|
+
for (const w of dead) {
|
|
89
|
+
if (w.status.deadAlerted === w.status.heartbeat) continue;
|
|
90
|
+
try { await emit("watch.dead", { watch: w.name, repo: w.repo, reason: w.live.reason, age_s: Math.round(w.live.ageMs / 1000) }, { repo: w.repo }); } catch { continue; }
|
|
91
|
+
try { writeAtomic(join(w.dir, "status.json"), JSON.stringify({ ...w.status, deadAlerted: w.status.heartbeat }) + "\n"); } catch { /* the next pass alerts again */ }
|
|
92
|
+
}
|
|
93
|
+
return dead;
|
|
94
|
+
}
|
|
@@ -6,7 +6,7 @@ import { mkdirSync, writeFileSync, readFileSync, utimesSync } from "node:fs";
|
|
|
6
6
|
import { join } from "node:path";
|
|
7
7
|
import { tmpDir } from "../tests/_tmp.mjs";
|
|
8
8
|
import { loadWatches, validateWatch, planClaims, tick, runWatch, formatStatus, formatClaimPlan } from "./issuewatch.mjs";
|
|
9
|
-
import { isPullRequest, closingPrIssues, releaseInFlight, watchLiveness, DEFAULT_SKIP_LABELS } from "./issuewatch-parity.mjs";
|
|
9
|
+
import { isPullRequest, closingPrIssues, releaseInFlight, watchLiveness, listWatches, alertDeadWatches, DEFAULT_SKIP_LABELS } from "./issuewatch-parity.mjs";
|
|
10
10
|
|
|
11
11
|
const NOW = Date.parse("2026-11-10T12:00:00Z");
|
|
12
12
|
const iss = (n, o = {}) => ({ number: n, title: `t${n}`, body: "", labels: [], milestone: null, author: { login: "me" }, createdAt: "2026-11-09T00:00:00Z", ...o });
|
|
@@ -86,17 +86,18 @@ test("#5313 a release in flight pauses the watch (no claims), the next pass resu
|
|
|
86
86
|
writeFileSync(join(env, "releases", "r20261110-110000-9", "state.json"), JSON.stringify({ repo: "o/r", status: "done", steps: {} })); // the job ends
|
|
87
87
|
s = await pass();
|
|
88
88
|
assert.equal(s.paused, null); assert.deepEqual(io.batchOps[0], ["start", [1]]);
|
|
89
|
-
assert.match(formatStatus(s, watch, io.now()), /state:
|
|
89
|
+
assert.match(formatStatus(s, watch, io.now()), /state: exited \(single pass/);
|
|
90
90
|
});
|
|
91
91
|
|
|
92
|
-
test("#5313 watchLiveness: a fresh heartbeat runs, an old one is
|
|
92
|
+
test("#5313 watchLiveness: a fresh heartbeat runs, an old one is dead, a finished watch is done", () => {
|
|
93
93
|
const beat = (ms) => new Date(NOW - ms).toISOString();
|
|
94
94
|
assert.equal(watchLiveness({ phase: "running", heartbeat: beat(1000), heartbeatEveryMs: 300000 }, NOW).state, "running");
|
|
95
|
-
assert.equal(watchLiveness({ phase: "running", heartbeat: beat(3600000), heartbeatEveryMs: 300000 }, NOW).state, "
|
|
95
|
+
assert.equal(watchLiveness({ phase: "running", heartbeat: beat(3600000), heartbeatEveryMs: 300000 }, NOW).state, "dead");
|
|
96
96
|
assert.equal(watchLiveness({ phase: "running", heartbeat: beat(1000), paused: { reason: "release r1 in flight" } }, NOW).state, "paused");
|
|
97
97
|
assert.equal(watchLiveness({ phase: "done", heartbeat: beat(9e9) }, NOW).state, "done");
|
|
98
98
|
assert.equal(watchLiveness(null, NOW).state, "unknown");
|
|
99
|
-
assert.match(formatStatus({ ...state(), heartbeat: beat(3600000), heartbeatEveryMs: 300000 }, validateWatch("w", {}), NOW), /state:
|
|
99
|
+
assert.match(formatStatus({ ...state(), heartbeat: beat(3600000), heartbeatEveryMs: 300000 }, validateWatch("w", {}), NOW), /state: DEAD/);
|
|
100
|
+
assert.equal(watchLiveness({ phase: "exited", exitReason: "crashed: x", heartbeat: beat(1000) }, NOW).state, "exited");
|
|
100
101
|
});
|
|
101
102
|
|
|
102
103
|
test("#5313 a batch that reported between the settle check and the add is never added to: a new batch starts", async () => {
|
|
@@ -125,3 +126,27 @@ test("#5313 the follow-up rules and skip reasons show in the --dry-run plan: def
|
|
|
125
126
|
assert.match(out, /skip #3: skip label epic/);
|
|
126
127
|
assert.match(out, /skip #4: pull request/);
|
|
127
128
|
});
|
|
129
|
+
|
|
130
|
+
test("#5442 a design:needed issue is skipped with design_pending, whatever skip_labels says; design:approved lifts it", async () => {
|
|
131
|
+
const io = bind(fakeIo(tmpDir("iwp-"), [iss(1), iss(2, { labels: lbl("design:needed") }), iss(3, { labels: lbl("design:needed", "design:approved") })]));
|
|
132
|
+
for (const cfg of [{}, { mode: "batch" }, { mode: "batch", skip_labels: [] }]) {
|
|
133
|
+
const plan = await planClaims({ watch: validateWatch("w", cfg), repo: "o/r", io, state: state() });
|
|
134
|
+
assert.deepEqual(plan.claim.map((c) => c.number).sort(), [1, 3]);
|
|
135
|
+
assert.ok(plan.skip.some((s) => s.number === 2 && /^design_pending/.test(s.reason)));
|
|
136
|
+
assert.match(formatClaimPlan(plan), /skip #2: design_pending/);
|
|
137
|
+
}
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
test("#5465 a killed watch shows DEAD within 3 heartbeats and the watchdog alerts once per dead heartbeat", async () => {
|
|
141
|
+
const root = tmpDir("iw-"), now = Date.parse("2026-11-11T14:00:00Z"), dir = join(root, "o__r", "w");
|
|
142
|
+
mkdirSync(dir, { recursive: true });
|
|
143
|
+
const beat = (ms) => new Date(now - ms).toISOString();
|
|
144
|
+
writeFileSync(join(dir, "status.json"), JSON.stringify({ ...state(), heartbeat: beat(3 * 300000 + 120000), heartbeatEveryMs: 300000 }));
|
|
145
|
+
const sent = [], emit = async (type, data) => { sent.push([type, data]); };
|
|
146
|
+
assert.equal(listWatches(root, now)[0].live.state, "dead");
|
|
147
|
+
assert.equal((await alertDeadWatches({ root, now, emit })).length, 1);
|
|
148
|
+
await alertDeadWatches({ root, now, emit });
|
|
149
|
+
assert.equal(sent.length, 1); assert.equal(sent[0][0], "watch.dead"); assert.equal(sent[0][1].watch, "w");
|
|
150
|
+
writeFileSync(join(dir, "status.json"), JSON.stringify({ ...state(), heartbeat: beat(1000), heartbeatEveryMs: 300000 }));
|
|
151
|
+
assert.equal((await alertDeadWatches({ root, now, emit })).length, 0);
|
|
152
|
+
});
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
/**
|
|
4
|
+
* #5467: reconcile an issue-watch's claims with the batch result and the issue labels. Each claim is `merged | needs-human(code) |
|
|
5
|
+
* parked(code) | running | stranded`. A final batch result leaves `inflight` at once (a long-lived batch that has not reported must not
|
|
6
|
+
* keep it for hours); a mechanical park (`needs-human` row with a terminal code) gets one budgeted `run-issue --recover` lane, and only
|
|
7
|
+
* when that fails becomes `needs-human` with the reason stated; a needs-human/parked claim a person cleared (label gone, plus a trusted
|
|
8
|
+
* FORGE:DECISION or a newer comment) is released so the next pass re-claims it. `status --stuck` lists the old claims. Gh, the clock and the
|
|
9
|
+
* lane launch are injected; the state callbacks (`fail`, `settle`, `release`) belong to the caller.
|
|
10
|
+
*/
|
|
11
|
+
import { classifyNeedsHuman, REMEDIATION_QUEUE_LABEL } from "../engine/outcome-codes.mjs";
|
|
12
|
+
|
|
13
|
+
const HOUR_MS = 3600_000;
|
|
14
|
+
const MERGED = new Set(["merged", "done", "complete", "completed", "closed"]);
|
|
15
|
+
const NEEDS_HUMAN_LABEL = "needs-human";
|
|
16
|
+
export const STUCK_HOURS = 24;
|
|
17
|
+
|
|
18
|
+
/** `{kind, code}` for one batch result row; `running` when there is no final row. Pure. */
|
|
19
|
+
export function classifyClaim(row) {
|
|
20
|
+
if (!row || typeof row !== "object") return { kind: "running", code: null };
|
|
21
|
+
const outcome = String(row.outcome ?? row.terminalReason ?? "");
|
|
22
|
+
if (MERGED.has(outcome)) return { kind: "merged", code: null };
|
|
23
|
+
if (outcome === "needs-human") {
|
|
24
|
+
const code = typeof row.code === "string" && row.code !== "" ? row.code : null;
|
|
25
|
+
// a code a person must settle (HUMAN_CODES) stays needs-human; any other code is a mechanical park the engine's own lanes already gave up on
|
|
26
|
+
return code && classifyNeedsHuman(row) !== "human" && code !== "unclassified" ? { kind: "parked", code } : { kind: "needs-human", code };
|
|
27
|
+
}
|
|
28
|
+
if (outcome === "" || outcome === "pending" || outcome === "running") return { kind: "running", code: null };
|
|
29
|
+
return { kind: "stranded", code: outcome };
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Settle every inflight claim whose batch result is final. `results` is state.json `results` of the watch's batch. Merged claims go to
|
|
34
|
+
* `settle` (verified once closed), the rest to `fail`; `state.outcomes[n]` keeps the classification. @returns {number[]} the issues settled.
|
|
35
|
+
*/
|
|
36
|
+
export function reconcileClaims({ state, results, now, fail, settle }) {
|
|
37
|
+
state.outcomes ??= {};
|
|
38
|
+
const done = [];
|
|
39
|
+
for (const n of [...state.inflight]) {
|
|
40
|
+
const c = classifyClaim(results?.[n]);
|
|
41
|
+
if (c.kind === "running") continue;
|
|
42
|
+
state.outcomes[n] = { ...c, at: now };
|
|
43
|
+
(c.kind === "merged" ? settle : fail)(n);
|
|
44
|
+
done.push(n);
|
|
45
|
+
}
|
|
46
|
+
return done;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const labelsOf = (v) => (v?.labels ?? []).map((l) => String(l?.name ?? l));
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* One remediation lane per parked claim, at most `watch.max_remediations` per watch. A launched lane is polled each pass: exit 0 hands
|
|
53
|
+
* the issue to verification, any other exit makes it `needs-human` with the reason in a comment. A restarted watch re-launches a
|
|
54
|
+
* running lane (run-issue resumes from GitHub) without spending budget again.
|
|
55
|
+
*/
|
|
56
|
+
export async function remediateStep({ watch, repo, io, state, handles, lanes = {}, now, settle, fail }) {
|
|
57
|
+
if (!io.remediate) return;
|
|
58
|
+
state.remediated ??= {};
|
|
59
|
+
const key = (n) => `remediate:${n}`;
|
|
60
|
+
for (const [n, o] of Object.entries(state.outcomes ?? {})) {
|
|
61
|
+
if (o.kind !== "parked" || state.remediated[n]) continue;
|
|
62
|
+
if (Object.keys(state.remediated).length >= (watch.max_remediations ?? 10)) break;
|
|
63
|
+
state.remediated[n] = { code: o.code, at: now, status: "running" };
|
|
64
|
+
handles.set(key(n), io.remediate(Number(n), state.lanes?.[n] ?? lanes[n], o.code));
|
|
65
|
+
}
|
|
66
|
+
for (const [n, r] of Object.entries(state.remediated)) {
|
|
67
|
+
if (r.status !== "running") continue;
|
|
68
|
+
let h = handles.get(key(n));
|
|
69
|
+
if (!h) { handles.set(key(n), io.remediate(Number(n), state.lanes?.[n] ?? lanes[n], r.code)); continue; }
|
|
70
|
+
const res = h.poll();
|
|
71
|
+
if (!res) continue;
|
|
72
|
+
handles.delete(key(n));
|
|
73
|
+
if (res.code === 0) { r.status = "done"; settle(Number(n)); continue; }
|
|
74
|
+
r.status = "failed";
|
|
75
|
+
const reason = `remediation lane for \`${r.code}\` exited ${res.code}`;
|
|
76
|
+
state.outcomes[n] = { kind: "needs-human", code: r.code, at: now, reason };
|
|
77
|
+
try {
|
|
78
|
+
await io.gh(["issue", "edit", String(n), "-R", repo, "--add-label", NEEDS_HUMAN_LABEL, "--remove-label", REMEDIATION_QUEUE_LABEL]);
|
|
79
|
+
await io.gh(["issue", "comment", String(n), "-R", repo, "--body", `## Needs human\nissue-watch ${watch.name} remediated this parked issue once (${reason}); a person has to take it from here.`]);
|
|
80
|
+
} catch { /* the label/comment retry is the next human pass; the state already records the reason */ }
|
|
81
|
+
fail(Number(n));
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* A needs-human/parked claim whose block a person cleared (no `needs-human`/`parked:*` label, a trusted FORGE:DECISION or a comment newer
|
|
87
|
+
* than the outcome) is released through `release(n)` so the next pass selects it again. A claim under remediation is left alone.
|
|
88
|
+
* @returns {number[]} the issues released.
|
|
89
|
+
*/
|
|
90
|
+
export async function reclaimStep({ repo, io, state, trusted, release }) {
|
|
91
|
+
const out = [];
|
|
92
|
+
for (const [n, o] of Object.entries(state.outcomes ?? {})) {
|
|
93
|
+
if (!["needs-human", "parked"].includes(o.kind) || state.remediated?.[n]?.status === "running") continue;
|
|
94
|
+
let v;
|
|
95
|
+
try { v = JSON.parse(String(await io.gh(["issue", "view", n, "-R", repo, "--json", "state,labels,comments"]))); } catch { continue; }
|
|
96
|
+
if (v.state === "CLOSED" || labelsOf(v).some((l) => l === NEEDS_HUMAN_LABEL || l.startsWith("parked:"))) continue;
|
|
97
|
+
const cleared = (v.comments ?? []).some((c) => trusted(c) && (/FORGE:DECISION/.test(String(c.body ?? "")) || Date.parse(c.createdAt) > o.at));
|
|
98
|
+
if (!cleared) continue;
|
|
99
|
+
release(Number(n));
|
|
100
|
+
delete state.outcomes[n]; delete state.remediated?.[n];
|
|
101
|
+
out.push(Number(n));
|
|
102
|
+
}
|
|
103
|
+
return out;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Counts of the claims by reconciled kind: `{merged, "needs-human", parked, running, stranded}`. */
|
|
107
|
+
export function claimCounts(state) {
|
|
108
|
+
const c = { merged: (state.merged ?? []).length, "needs-human": 0, parked: 0, running: (state.inflight ?? []).length, stranded: 0 };
|
|
109
|
+
for (const o of Object.values(state.outcomes ?? {})) if (o.kind in c && o.kind !== "merged" && o.kind !== "running") c[o.kind]++;
|
|
110
|
+
return c;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** `[{issue, ageHours, why}]` of claims older than `hours` with no merged issue, oldest first. */
|
|
114
|
+
export function stuckClaims(state, now, hours = STUCK_HOURS) {
|
|
115
|
+
const merged = new Set([...(state.merged ?? []), ...(state.verified ?? [])]);
|
|
116
|
+
return (state.claimed ?? []).filter((n) => !merged.has(n)).map((n) => {
|
|
117
|
+
const at = state.claimedAt?.[n] ?? state.started ?? now, o = state.outcomes?.[n], r = state.remediated?.[n];
|
|
118
|
+
const why = o ? `${o.kind}${o.code ? ` (${o.code})` : ""}${o.reason ? `: ${o.reason}` : ""}${r ? `; remediation ${r.status}` : ""}` : state.inflight?.includes(n) ? "running in its lane" : "no batch result";
|
|
119
|
+
return { issue: n, ageHours: Math.floor((now - at) / HOUR_MS), why };
|
|
120
|
+
}).filter((r) => r.ageHours >= hours).sort((a, b) => b.ageHours - a.ageHours);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export const formatStuck = (rows, hours = STUCK_HOURS) => rows.length ? rows.map((r) => `#${r.issue} claimed ${r.ageHours}h ago, no merged PR: ${r.why}`).join("\n") : `no claims older than ${hours}h without a merged PR`;
|
|
@@ -0,0 +1,30 @@
|
|
|
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 { classifyClaim, reconcileClaims, claimCounts, stuckClaims, formatStuck } from "./issuewatch-reconcile.mjs";
|
|
6
|
+
|
|
7
|
+
test("classifyClaim: merged, parked (terminal code), needs-human, running, stranded", () => {
|
|
8
|
+
assert.deepEqual(classifyClaim({ outcome: "merged" }), { kind: "merged", code: null });
|
|
9
|
+
assert.deepEqual(classifyClaim({ outcome: "needs-human", code: "conformance.unimplemented" }), { kind: "parked", code: "conformance.unimplemented" });
|
|
10
|
+
assert.equal(classifyClaim({ outcome: "needs-human" }).kind, "needs-human");
|
|
11
|
+
assert.equal(classifyClaim(undefined).kind, "running");
|
|
12
|
+
assert.deepEqual(classifyClaim({ outcome: "engine-error" }), { kind: "stranded", code: "engine-error" });
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
test("reconcileClaims settles merged, fails the rest, leaves running claims inflight", () => {
|
|
16
|
+
const state = { inflight: [1, 2, 3], merged: [] };
|
|
17
|
+
const settled = [], failed = [];
|
|
18
|
+
const done = reconcileClaims({ state, results: { 1: { outcome: "merged" }, 2: { outcome: "needs-human", code: "ci.red" } }, now: 5, fail: (n) => failed.push(n), settle: (n) => settled.push(n) });
|
|
19
|
+
assert.deepEqual(done, [1, 2]); assert.deepEqual(settled, [1]); assert.deepEqual(failed, [2]);
|
|
20
|
+
assert.equal(state.outcomes[2].kind, "parked");
|
|
21
|
+
assert.equal(claimCounts({ ...state, inflight: [3] }).parked, 1);
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
test("stuckClaims lists only old unmerged claims with the reason", () => {
|
|
25
|
+
const now = 100 * 3600_000;
|
|
26
|
+
const s = { claimed: [1, 2, 3], merged: [3], inflight: [1], claimedAt: { 1: 0, 2: 99 * 3600_000, 3: 0 }, outcomes: {} };
|
|
27
|
+
const rows = stuckClaims(s, now, 24);
|
|
28
|
+
assert.deepEqual(rows.map((r) => r.issue), [1]);
|
|
29
|
+
assert.match(formatStuck(rows), /#1 claimed 100h ago, no merged PR: running in its lane/);
|
|
30
|
+
});
|
|
@@ -4,9 +4,11 @@
|
|
|
4
4
|
* Merge verification for `forgedock issue-watch`: an issue the watch claimed counts as verified only when its result
|
|
5
5
|
* checks out after it closed, not because it closed. Checks, in order: a PR from `feat/issue-<n>-lean` merged into the
|
|
6
6
|
* issue's lane; the PR does not carry `review-degraded`; the issue's latest trusted FORGE:REVIEW passed (enforced
|
|
7
|
-
* `CONFORMS`, shadow `would PASS`, or a `review.trigger` skip;
|
|
7
|
+
* `CONFORMS`, shadow `would PASS`, or a `review.trigger` skip; an enforced NONCONFORMING/BLOCK/FAIL fails; a shadow
|
|
8
|
+
* `would BLOCK` is advisory, as its label says: the lane merges by design, so it is recorded in the evidence, not reopened); every required check of the
|
|
8
9
|
* lane is green on the merged head; the merge commit is on the lane; no check on the merge commit failed
|
|
9
|
-
* (`forgedock/verify` is report-only
|
|
10
|
+
* (`forgedock/verify` is report-only; a `cancelled`/`stale` check, superseded by a newer run, is resolved against the newest
|
|
11
|
+
* descendant run of the same check on the lane). A failure reopens the issue with `needs-human` and the evidence; nothing is
|
|
10
12
|
* reverted, a human decides. No LLM calls.
|
|
11
13
|
*/
|
|
12
14
|
import { isTrustedIssueComment } from "./prefilter.mjs";
|
|
@@ -14,6 +16,8 @@ import { requiredChecksFor } from "./effects.mjs";
|
|
|
14
16
|
|
|
15
17
|
export const VERIFY_MARKER = "FORGE:WATCH_VERIFY";
|
|
16
18
|
const OK_STATES = new Set(["success", "neutral", "skipped"]);
|
|
19
|
+
const SUPERSEDED_STATES = new Set(["cancelled", "stale"]);
|
|
20
|
+
const DESCENDANTS_READ = 10;
|
|
17
21
|
const REPORT_ONLY_CHECKS = new Set(["forgedock/verify"]);
|
|
18
22
|
const labelNames = (x) => new Set((x?.labels ?? []).map((l) => (typeof l === "string" ? l : l?.name)).filter(Boolean));
|
|
19
23
|
|
|
@@ -38,11 +42,39 @@ export async function checkStates({ gh, repo, sha }) {
|
|
|
38
42
|
return [...runs.values()].map(({ name, state }) => ({ name, state }));
|
|
39
43
|
}
|
|
40
44
|
|
|
41
|
-
/**
|
|
45
|
+
/**
|
|
46
|
+
* Settle superseded (`cancelled`/`stale`) checks of `sha` against the lane's newer commits: per check name the newest
|
|
47
|
+
* descendant that ran it decides. Returns `{green: [evidence], red: [name=state@sha], pending: [name]}`; a name no descendant
|
|
48
|
+
* has run yet is pending. Unreadable descendants = none.
|
|
49
|
+
*/
|
|
50
|
+
async function resolveSuperseded({ gh, repo, lane, sha, names }) {
|
|
51
|
+
const out = { green: [], red: [], pending: [] };
|
|
52
|
+
if (!names.length) return out;
|
|
53
|
+
let desc = [];
|
|
54
|
+
try { desc = String(await gh(["api", `repos/${repo}/compare/${sha}...${lane}`, "--jq", ".commits[].sha"])).split("\n").map((x) => x.trim()).filter(Boolean).reverse().slice(0, DESCENDANTS_READ); } catch { desc = []; }
|
|
55
|
+
const open = new Set(names);
|
|
56
|
+
for (const d of desc) {
|
|
57
|
+
if (!open.size) break;
|
|
58
|
+
const at = await checkStates({ gh, repo, sha: d });
|
|
59
|
+
for (const n of [...open]) {
|
|
60
|
+
const x = at.find((c) => c.name === n);
|
|
61
|
+
if (!x || SUPERSEDED_STATES.has(x.state)) continue;
|
|
62
|
+
open.delete(n);
|
|
63
|
+
if (OK_STATES.has(x.state)) out.green.push(`${n} superseded by a ${x.state} run on ${d.slice(0, 12)}`);
|
|
64
|
+
else if (x.state === "pending") out.pending.push(n);
|
|
65
|
+
else out.red.push(`${n}=${x.state} on ${d.slice(0, 12)}`);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
out.pending.push(...open);
|
|
69
|
+
return out;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** The latest trusted FORGE:REVIEW's verdict: pass | shadow-block | block | null (no review record). An unrecognised verdict is a block. */
|
|
42
73
|
export function reviewVerdict(comments = []) {
|
|
43
74
|
const body = String(comments.filter((c) => isTrustedIssueComment(c) && /<!--\s*FORGE:REVIEW\b/.test(String(c?.body ?? ""))).at(-1)?.body ?? "");
|
|
44
75
|
if (!body) return null;
|
|
45
|
-
if (
|
|
76
|
+
if (/\*\*Verdict:\*\*\s*(?:NON-?CONFORM|BLOCK|FAIL)/i.test(body)) return "block";
|
|
77
|
+
if (/would BLOCK/i.test(body)) return "shadow-block";
|
|
46
78
|
if (/\*\*Verdict:\*\*\s*CONFORMS|would PASS|Skipped by `review\.trigger/.test(body)) return "pass";
|
|
47
79
|
return "block";
|
|
48
80
|
}
|
|
@@ -64,14 +96,21 @@ export async function verifyMerge({ gh, repo, lane, issue, comments, requiredChe
|
|
|
64
96
|
if (pr.baseRefName !== lane) return fail(`PR #${pr.number} targets ${pr.baseRefName}, not ${lane}`, { pr: pr.number });
|
|
65
97
|
if (labelNames(pr).has("review-degraded")) return fail(`PR #${pr.number} merged with an incomplete review (review-degraded)`, { pr: pr.number });
|
|
66
98
|
const verdict = reviewVerdict(comments);
|
|
67
|
-
if (verdict !== "pass") return fail(verdict === "block" ? "the latest FORGE:REVIEW did not pass (
|
|
68
|
-
ev.push("FORGE:REVIEW passed");
|
|
99
|
+
if (verdict !== "pass" && verdict !== "shadow-block") return fail(verdict === "block" ? "the latest FORGE:REVIEW did not pass (enforced NONCONFORMING)" : "no trusted FORGE:REVIEW on the issue", { pr: pr.number });
|
|
100
|
+
ev.push(verdict === "pass" ? "FORGE:REVIEW passed" : "FORGE:REVIEW shadow `would BLOCK` (advisory: shadow mode does not enforce; see the review comment)");
|
|
69
101
|
let required = [];
|
|
70
102
|
try { required = (await requiredChecks(lane)) ?? []; } catch { required = []; }
|
|
71
103
|
if (required.length && pr.headRefOid) {
|
|
72
104
|
const at = await checkStates({ gh, repo, sha: pr.headRefOid });
|
|
73
105
|
const stateOf = (n) => at.find((x) => x.name === n)?.state ?? "missing";
|
|
74
|
-
|
|
106
|
+
let bad = required.filter((n) => !OK_STATES.has(stateOf(n)));
|
|
107
|
+
const sup = bad.filter((n) => SUPERSEDED_STATES.has(stateOf(n)));
|
|
108
|
+
if (sup.length && sha) {
|
|
109
|
+
const r = await resolveSuperseded({ gh, repo, lane, sha, names: sup });
|
|
110
|
+
bad = bad.filter((n) => !sup.includes(n) || r.pending.includes(n) || r.red.some((x) => x.startsWith(`${n}=`)));
|
|
111
|
+
if (r.pending.length) return { status: "pending", evidence: [...ev, `required check(s) cancelled on the head, no newer ${lane} run finished: ${r.pending.join(", ")}`], pr: pr.number, sha };
|
|
112
|
+
ev.push(...r.green);
|
|
113
|
+
}
|
|
75
114
|
if (bad.length) return fail(`required check(s) not green on the merged head ${pr.headRefOid.slice(0, 12)}: ${bad.map((n) => `${n}=${stateOf(n)}`).join(", ")}`, { pr: pr.number });
|
|
76
115
|
ev.push(`required checks green on the head: ${required.join(", ")}`);
|
|
77
116
|
} else ev.push("no required checks on the lane");
|
|
@@ -82,9 +121,12 @@ export async function verifyMerge({ gh, repo, lane, issue, comments, requiredChe
|
|
|
82
121
|
if (rel !== "behind" && rel !== "identical") return fail(`merge commit ${sha.slice(0, 12)} is not on ${lane} (compare: ${rel})`, { pr: pr.number, sha });
|
|
83
122
|
ev.push(`merge commit is on ${lane}`);
|
|
84
123
|
const post = (await checkStates({ gh, repo, sha })).filter((x) => !REPORT_ONLY_CHECKS.has(x.name));
|
|
85
|
-
const red = post.filter((x) => !OK_STATES.has(x.state) && x.state !== "pending");
|
|
124
|
+
const red = post.filter((x) => !OK_STATES.has(x.state) && x.state !== "pending" && !SUPERSEDED_STATES.has(x.state));
|
|
86
125
|
if (red.length) return fail(`${lane} CI red on the merge commit: ${red.map((x) => `${x.name}=${x.state}`).join(", ")}`, { pr: pr.number, sha });
|
|
87
|
-
const
|
|
126
|
+
const sup = await resolveSuperseded({ gh, repo, lane, sha, names: post.filter((x) => SUPERSEDED_STATES.has(x.state)).map((x) => x.name) });
|
|
127
|
+
if (sup.red.length) return fail(`${lane} CI red: a cancelled check on the merge commit was superseded by a failing run: ${sup.red.join(", ")}`, { pr: pr.number, sha });
|
|
128
|
+
ev.push(...sup.green);
|
|
129
|
+
const pending = [...post.filter((x) => x.state === "pending"), ...sup.pending.map((name) => ({ name }))];
|
|
88
130
|
if (pending.length) return { status: "pending", evidence: [...ev, `${lane} CI pending: ${pending.map((x) => x.name).join(", ")}`], pr: pr.number, sha };
|
|
89
131
|
ev.push(post.length ? `${lane} CI green on the merge commit (${post.length} check(s))` : "no CI ran on the merge commit");
|
|
90
132
|
return { status: "verified", evidence: ev, pr: pr.number, sha };
|