forgedock 1.54.1 → 1.55.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 (110) hide show
  1. package/bin/engine/events.mjs +1 -0
  2. package/bin/engine/events.test.mjs +5 -1
  3. package/bin/engine/outcome-codes.mjs +3 -0
  4. package/bin/engine-cli.mjs +126 -34
  5. package/bin/forgedock.mjs +54 -2
  6. package/bin/gc-schedule.mjs +83 -0
  7. package/bin/gc.mjs +56 -8
  8. package/bin/help-text.mjs +1 -1
  9. package/bin/hooks/pre-tool-use.mjs +1 -0
  10. package/bin/init-detect.mjs +73 -2
  11. package/bin/labels.json +5 -0
  12. package/bin/lean/admission.mjs +21 -1
  13. package/bin/lean/baselines.mjs +43 -0
  14. package/bin/lean/baselines.test.mjs +33 -0
  15. package/bin/lean/batch-health.mjs +43 -6
  16. package/bin/lean/batch-health.test.mjs +41 -1
  17. package/bin/lean/batch.mjs +41 -4
  18. package/bin/lean/batch.test.mjs +106 -3
  19. package/bin/lean/conformance.mjs +131 -12
  20. package/bin/lean/conformance.test.mjs +172 -3
  21. package/bin/lean/depcache.mjs +23 -2
  22. package/bin/lean/depcache.test.mjs +22 -0
  23. package/bin/lean/docsgate.mjs +137 -0
  24. package/bin/lean/docsgate.test.mjs +78 -0
  25. package/bin/lean/effects.mjs +31 -2
  26. package/bin/lean/enumerating.mjs +39 -13
  27. package/bin/lean/enumerating.test.mjs +20 -0
  28. package/bin/lean/execution.test.mjs +3 -3
  29. package/bin/lean/fastforward.mjs +93 -0
  30. package/bin/lean/fastforward.test.mjs +73 -0
  31. package/bin/lean/guardgate.mjs +38 -7
  32. package/bin/lean/guardgate.test.mjs +39 -0
  33. package/bin/lean/issuewatch-install.mjs +92 -0
  34. package/bin/lean/issuewatch-install.test.mjs +31 -0
  35. package/bin/lean/issuewatch-parity.mjs +33 -3
  36. package/bin/lean/issuewatch-parity.test.mjs +30 -5
  37. package/bin/lean/issuewatch-reconcile.mjs +123 -0
  38. package/bin/lean/issuewatch-reconcile.test.mjs +30 -0
  39. package/bin/lean/issuewatch-verify.mjs +51 -9
  40. package/bin/lean/issuewatch.mjs +153 -33
  41. package/bin/lean/issuewatch.test.mjs +243 -22
  42. package/bin/lean/lean.mjs +381 -75
  43. package/bin/lean/lean.test.mjs +437 -20
  44. package/bin/lean/light.mjs +11 -3
  45. package/bin/lean/light.test.mjs +27 -0
  46. package/bin/lean/lightlane.mjs +8 -3
  47. package/bin/lean/lightlane.test.mjs +20 -0
  48. package/bin/lean/mechfix.mjs +21 -2
  49. package/bin/lean/mechfix.test.mjs +28 -1
  50. package/bin/lean/orchestrate-children.test.mjs +10 -0
  51. package/bin/lean/orchestrate-owned.test.mjs +73 -0
  52. package/bin/lean/orchestrate.mjs +28 -4
  53. package/bin/lean/overlap.mjs +20 -0
  54. package/bin/lean/overlap.test.mjs +49 -0
  55. package/bin/lean/pagegate.mjs +152 -0
  56. package/bin/lean/pagegate.test.mjs +77 -0
  57. package/bin/lean/parked-relabel.mjs +32 -0
  58. package/bin/lean/parked-relabel.test.mjs +45 -0
  59. package/bin/lean/phaseledger.mjs +17 -2
  60. package/bin/lean/postdeploy-check.mjs +27 -0
  61. package/bin/lean/postdeploy-check.test.mjs +13 -1
  62. package/bin/lean/postrun.mjs +32 -0
  63. package/bin/lean/postrun.test.mjs +41 -0
  64. package/bin/lean/preflight.mjs +46 -0
  65. package/bin/lean/preflight.test.mjs +30 -1
  66. package/bin/lean/prompts.mjs +36 -6
  67. package/bin/lean/recovery.test.mjs +16 -0
  68. package/bin/lean/release.mjs +23 -2
  69. package/bin/lean/release.test.mjs +28 -1
  70. package/bin/lean/render.mjs +17 -6
  71. package/bin/lean/reproquality.mjs +116 -0
  72. package/bin/lean/reproquality.test.mjs +85 -0
  73. package/bin/lean/review-trigger.mjs +8 -3
  74. package/bin/lean/sandbox-budget.test.mjs +27 -0
  75. package/bin/lean/schedd.mjs +40 -11
  76. package/bin/lean/schedd.test.mjs +12 -1
  77. package/bin/lean/testadequacy.mjs +97 -0
  78. package/bin/lean/testadequacy.test.mjs +92 -0
  79. package/bin/lean/testsandbox.mjs +202 -0
  80. package/bin/lean/testsandbox.test.mjs +157 -0
  81. package/bin/lean/toolplace.mjs +5 -2
  82. package/bin/lean/toolplace.test.mjs +6 -0
  83. package/bin/lean/verify.mjs +6 -1
  84. package/bin/lean/verify.test.mjs +18 -2
  85. package/bin/lean/warmtree.mjs +77 -0
  86. package/bin/lean/warmtree.test.mjs +81 -0
  87. package/bin/stats/conformance-outcomes.mjs +12 -2
  88. package/bin/stats/depth.mjs +24 -1
  89. package/bin/stats/depth.test.mjs +21 -1
  90. package/bin/stats/index.mjs +5 -2
  91. package/bin/stats/query.mjs +2 -1
  92. package/commands/cleanup.md +18 -0
  93. package/commands/fd-introspect.md +19 -0
  94. package/commands/milestone.md +5 -1
  95. package/commands/pipeline-health/phase-2-metrics.md +4 -0
  96. package/commands/recover-orphans.md +31 -1
  97. package/commands/review-pr-staging.md +9 -0
  98. package/commands/review-pr.md +2 -0
  99. package/docs/CONFIG.md +26 -1
  100. package/docs/EVENTS.md +1 -0
  101. package/docs/ISSUE-WATCH.md +12 -3
  102. package/docs/eval/adversarial-bench.md +1 -1
  103. package/docs/eval/published/adversarial-2026-11-11.md +58 -0
  104. package/package.json +1 -1
  105. package/scripts/bench-lightlane.mjs +3 -2
  106. package/scripts/hotspots.sh +7 -4
  107. package/scripts/hotspots.test.sh +12 -0
  108. package/scripts/recover-orphans-stateless.test.sh +79 -0
  109. package/scripts/transition-label.sh +2 -0
  110. package/templates/workflows/forgedock-reopen-clean.yml +33 -0
@@ -43,18 +43,42 @@ export function exportNames(text, path = "") {
43
43
  return [...out];
44
44
  }
45
45
 
46
- /** Line (1-based) of the first literal/key mention of any of `names` in `text`, and the distinct names mentioned. */
47
- function mentions(text, names) {
46
+ const PATH_CONTEXT = /\.[cm]?[jt]sx?\b|readdir|import\(/;
47
+ const SUFFIXED = /\.[cm]?[jt]sx?["'`]$/;
48
+ /** Local names bound by an ES import (named, default or namespace). */
49
+ function importedNames(text) {
50
+ const out = new Set();
51
+ for (const m of text.matchAll(/import\s+(?:([A-Za-z_$][\w$]*)\s*,?\s*)?(?:\*\s+as\s+([A-Za-z_$][\w$]*)|\{([^}]*)\})?\s*from\s*["']/g)) {
52
+ for (const n of [m[1], m[2]]) if (n) out.add(n);
53
+ for (const part of (m[3] ?? "").split(",")) { const n = /([A-Za-z_$][\w$]*)\s*$/.exec(part.trim())?.[1]; if (n) out.add(n); }
54
+ }
55
+ return out;
56
+ }
57
+
58
+ /**
59
+ * Line (1-based) of the first literal/key mention of any of `names` in `text`, and the distinct names mentioned. `dir` (files groups,
60
+ * #5480): a bare word that merely equals a stem is not a mention; it needs an extension, or readdir / import( / the directory's name
61
+ * within two lines, and a line asserting `.has(x)` of an imported Set is never one.
62
+ */
63
+ function mentions(text, names, dir) {
48
64
  const hit = new Set();
49
65
  let line = 0;
66
+ const rows = dir ? text.split("\n") : [], imported = dir ? importedNames(text) : null;
67
+ const dirRe = dir ? new RegExp(`(?<![\\w$])${esc(dir)}(?![\\w$])`) : null;
50
68
  for (const n of names) {
51
69
  if (n.length < MIN_NAME) continue;
52
- const re = new RegExp(`(["'\`])${esc(n)}\\1|(?:^|[{,\\s])${esc(n)}\\s*:(?!:)`, "m");
53
- const m = re.exec(text);
54
- if (!m) continue;
55
- hit.add(n);
56
- const l = text.slice(0, m.index).split("\n").length;
57
- if (!line || l < line) line = l;
70
+ const re = new RegExp(`(["'\`])${esc(n)}${dir ? "(?:\\.[cm]?[jt]sx?)?" : ""}\\1|(?:^|[{,\\s])${esc(n)}\\s*:(?!:)`, "gm");
71
+ for (const m of text.matchAll(re)) {
72
+ const l = text.slice(0, m.index).split("\n").length;
73
+ if (dir) {
74
+ if ([...rows[l - 1].matchAll(/([A-Za-z_$][\w$]*)\.has\(/g)].some((x) => imported.has(x[1]))) continue;
75
+ const near = rows.slice(Math.max(0, l - 3), l + 2).join("\n");
76
+ if (!SUFFIXED.test(m[0]) && !PATH_CONTEXT.test(near) && !dirRe.test(near)) continue;
77
+ }
78
+ hit.add(n);
79
+ if (!line || l < line) line = l;
80
+ break;
81
+ }
58
82
  }
59
83
  return { hit, line };
60
84
  }
@@ -98,14 +122,14 @@ async function loadTests(git, cwd) {
98
122
  }
99
123
 
100
124
  /** Tests enumerating one group: [{test, line, why}]. `exports` groups also match Object.keys/entries of an import of `module`. */
101
- function enumerators(tests, { module, names, kind }, pkgs) {
125
+ function enumerators(tests, { module, names, kind, strict }, pkgs) {
102
126
  const out = [];
103
127
  const usable = names.filter((n) => n.length >= MIN_NAME);
104
128
  if (usable.length < 2) return out;
105
129
  const need = Math.min(3, usable.length);
106
130
  for (const t of tests) {
107
131
  if (t.path === module) continue;
108
- const { hit, line } = mentions(t.text, usable);
132
+ const { hit, line } = mentions(t.text, usable, kind === "files" && strict ? basename(module) : undefined);
109
133
  if (hit.size >= need) { out.push({ test: t.path, line, why: `literal list of ${hit.size} sibling ${kind === "files" ? "file names" : "export names"}` }); continue; }
110
134
  if (kind !== "exports") continue;
111
135
  for (const b of importBindings(t.text, t.path, module, pkgs)) {
@@ -116,6 +140,8 @@ function enumerators(tests, { module, names, kind }, pkgs) {
116
140
  return out.slice(0, MAX_TESTS_PER_MODULE);
117
141
  }
118
142
 
143
+ /** #5480: a directory of source files has stems that collide with common words, so its lists need path context; data files (locale namespaces) do not. */
144
+ const strictDir = (files, dir) => files.some((f) => dirname(f) === dir && SOURCE_RE.test(f) && !isTestPath(f));
119
145
  const fileGroup = (files, dir, exclude = new Set()) => [...new Set(files.filter((f) => dirname(f) === dir && !isTestPath(f) && !exclude.has(f) && stem(f) !== "index").map(stem))];
120
146
 
121
147
  /**
@@ -132,8 +158,8 @@ export async function enumeratingTests({ git, cwd, paths = [] }) {
132
158
  if (tracked.has(raw) && SOURCE_RE.test(raw) && !isTestPath(raw)) {
133
159
  let text = ""; try { text = fs.readFileSync(join(cwd, raw), "utf8"); } catch { /* sparse */ }
134
160
  groups.push({ module: raw, names: exportNames(text, raw), kind: "exports" });
135
- groups.push({ module: dirname(raw), names: fileGroup(files, dirname(raw)), kind: "files" });
136
- } else if (files.some((f) => dirname(f) === raw)) groups.push({ module: raw, names: fileGroup(files, raw), kind: "files" });
161
+ groups.push({ module: dirname(raw), names: fileGroup(files, dirname(raw)), kind: "files", strict: strictDir(files, dirname(raw)) });
162
+ } else if (files.some((f) => dirname(f) === raw)) groups.push({ module: raw, names: fileGroup(files, raw), kind: "files", strict: strictDir(files, raw) });
137
163
  for (const g of groups) for (const e of enumerators(tests, g, pkgs)) {
138
164
  const k = `${g.module}\0${e.test}`;
139
165
  if (!seen.has(k)) { seen.add(k); out.push({ module: g.module, ...e }); }
@@ -169,7 +195,7 @@ export async function missingEntries({ git, cwd, base }) {
169
195
  const newFiles = [...added].filter((f) => !isTestPath(f) && !SKIP_RE.test(f));
170
196
  for (const dir of [...new Set(newFiles.map(dirname))]) {
171
197
  const fresh = newFiles.filter((f) => dirname(f) === dir).map(stem).filter((s) => s.length >= MIN_NAME && s !== "index");
172
- if (fresh.length) groups.push({ module: dir, names: fileGroup(files, dir, added), fresh, kind: "files" });
198
+ if (fresh.length) groups.push({ module: dir, names: fileGroup(files, dir, added), fresh, kind: "files", strict: strictDir(files, dir) });
173
199
  }
174
200
  const out = [];
175
201
  for (const g of groups.slice(0, MAX_MODULES)) {
@@ -95,3 +95,23 @@ describe("enumerating tests (#4322)", () => {
95
95
  assert.deepEqual(await enumeratingTests({ git: bad, cwd: d, paths: ["x"] }), []);
96
96
  });
97
97
  });
98
+
99
+ describe("#5480 bare words that equal sibling stems are not a directory enumeration", () => {
100
+ const SRC = { "bin/lean/run.mjs": "", "bin/lean/watch.mjs": "", "bin/lean/release.mjs": "", "bin/lean/fresh.mjs": "export const fresh = 1;\n" };
101
+ const base = (extra) => repo({ ...Object.fromEntries(Object.entries(SRC).filter(([k]) => !k.endsWith("fresh.mjs"))), ...extra });
102
+ const add = async (d) => { put(d, { "bin/lean/fresh.mjs": SRC["bin/lean/fresh.mjs"] }); sh(d, "checkout", "-qb", "lane"); sh(d, "add", "-A"); sh(d, "commit", "-qm", "lane"); return missingEntries({ git: gitIn(d), cwd: d, base: "main" }); };
103
+ it("bare-word stems are not an enumeration (unrelated lists, imported Set membership)", async () => {
104
+ const d = base({
105
+ "bin/auth/a.test.mjs": "import { CMDS } from './x.mjs';\nfor (const c of [\"run\", \"watch\", \"release\"]) assert.ok(CMDS.has(c), c);\n",
106
+ "bin/lean/guards.test.mjs": "const guards = [\"run\", \"watch\", \"release\"];\n",
107
+ });
108
+ assert.deepEqual(await add(d), []);
109
+ });
110
+ it("a literal list of file names, with a suffix or readdir, still is one", async () => {
111
+ const d = base({
112
+ "bin/lean/a.test.mjs": "const FILES = [\"run.mjs\", \"watch.mjs\", \"release.mjs\"];\n",
113
+ "bin/lean/b.test.mjs": "const got = readdirSync(dir);\nassert.deepEqual(got, [\"run\", \"watch\", \"release\"]);\n",
114
+ });
115
+ assert.deepEqual((await add(d)).map((m) => m.test).sort(), ["bin/lean/a.test.mjs", "bin/lean/b.test.mjs"]);
116
+ });
117
+ });
@@ -878,7 +878,7 @@ describe("host capabilities in placement (#4542)", () => {
878
878
  assert.deepEqual(detectNeeds(t, exec), ["promtool"]);
879
879
  });
880
880
 
881
- it("#4785 orchestrate: a remote lane that ends env.tool_missing is relaunched locally", async () => {
881
+ it("#4785/#5423 orchestrate: a remote lane that ends env.tool_missing is retried remotely once (sandbox provisioned), see recovery.test.mjs for the host fallback", async () => {
882
882
  const calls = [];
883
883
  const rows = await orchestrate({ issues: [5], parallel: 2, recovery: { maxAttempts: 1 }, readBody: async () => "",
884
884
  remote: { max: 2, isRemote: () => true, place: () => ({ where: "remote", reason: "mode remote" }), admit: () => ({ ok: true }), onBudget: "stop", costPerMinute: 0 },
@@ -886,8 +886,8 @@ describe("host capabilities in placement (#4542)", () => {
886
886
  calls.push({ placement: ctx.placement?.where, reason: ctx.placement?.reason, recover: ctx.recover?.code ?? null });
887
887
  return ctx.recover ? { terminalReason: "merged", pr: 9 } : { terminalReason: "needs-human", code: "env.tool_missing", detail: "promtool: command not found" };
888
888
  } });
889
- assert.deepEqual(calls.map((c) => [c.placement, c.recover]), [["remote", null], ["local", "env.tool_missing"]]);
890
- assert.equal(calls[1].reason, "host capability: recovering env.tool_missing");
889
+ assert.deepEqual(calls.map((c) => [c.placement, c.recover]), [["remote", null], ["remote", "env.tool_missing"]]);
890
+ assert.equal(calls[1].reason, "retry remotely after sandbox provisioning");
891
891
  assert.equal(rows.find((r) => r.issue === 5).outcome, "merged");
892
892
  });
893
893
 
@@ -0,0 +1,93 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * Investigation decides pipeline depth (#5426, builds on the light lane #4450). By default (forge.yaml `lean.light.source:
5
+ * investigation`; `text` is the kill-switch) the first builder call is investigation-only: it writes investigation.md and `.forge-lean/triage.json`
6
+ * ({files, size, risk, decision_needed}). Eligibility for the light lane is then computed from those grounded findings
7
+ * (predicted non-test files, size, risk, hotspot) by the same `lightEligibility` rules; the text heuristic over the issue body
8
+ * stays only as a `pre_text_*` shadow signal. An eligible issue fast-forwards: one implement session, deterministic gates
9
+ * (`runLightStep`), merge; the stages it skips are named. Anything else continues into the full lane's contract step.
10
+ * `source: investigation` with `mode: shadow` changes nothing: it logs FASTFORWARD_ELIGIBILITY after the normal plan session.
11
+ * Pure helpers and prompts: no I/O, no model call.
12
+ */
13
+ import { lightEligibility, LIGHT_SOURCES } from "./light.mjs";
14
+ import { builderPlanPrompt, LEAN_DIR, CONTRACT_FILE } from "./prompts.mjs";
15
+
16
+ export const TRIAGE_FILE = `${LEAN_DIR}/triage.json`;
17
+
18
+ /** `lean.light.source` of a parsed light config: investigation (default; investigate always, the verdict picks the depth) or text (the kill-switch). */
19
+ export const fastForwardSource = (cfg) => (LIGHT_SOURCES.includes(cfg?.source) ? cfg.source : "investigation");
20
+
21
+ const PATH_RE = /[A-Za-z0-9_@.][A-Za-z0-9_@.\-]*(?:\/[A-Za-z0-9_@.\-]+)*\.[A-Za-z0-9]{1,8}\b/g;
22
+ const SECTION_RE = /^###\s+Affected Files\s*$([\s\S]*?)(?=^###\s|(?![\s\S]))/m;
23
+ const uniq = (xs) => [...new Set(xs)];
24
+
25
+ /** Paths named in the `### Affected Files` section of investigation.md (deterministic fallback when triage.json is absent). */
26
+ export function affectedFilesOf(md) {
27
+ const sec = SECTION_RE.exec(String(md ?? ""))?.[1] ?? "";
28
+ const out = [];
29
+ for (const line of sec.split("\n")) {
30
+ if (!/^\s*[-*]/.test(line)) continue;
31
+ const first = line.replace(/^\s*[-*]\s*/, "").replace(/`/g, "").match(PATH_RE)?.[0]; // the first token names the file; later ones are prose
32
+ if (first && !/^\d/.test(first) && (first.includes("/") || /\.(m?[jt]sx?|py|go|rs|md|json|ya?ml|sh|css|sql)$/.test(first))) out.push(first.replace(/^\.\//, ""));
33
+ }
34
+ return uniq(out);
35
+ }
36
+
37
+ /**
38
+ * triage.json text + investigation.md -> {files, size, risk, decisionNeeded, source}. A malformed or absent triage falls back to
39
+ * the Affected Files section with an unknown size; a size outside S|M|L is unknown.
40
+ */
41
+ export function parseTriage(triageRaw, md = "") {
42
+ let t = null;
43
+ try { const j = JSON.parse(String(triageRaw ?? "")); t = j && typeof j === "object" && !Array.isArray(j) ? j : null; } catch { /* fall back */ }
44
+ const files = t && Array.isArray(t.files) ? uniq(t.files.map((f) => String(f ?? "").trim().replace(/^\.\//, "")).filter(Boolean)) : affectedFilesOf(md);
45
+ const size = ["S", "M", "L"].includes(String(t?.size ?? "").toUpperCase()) ? String(t.size).toUpperCase() : null;
46
+ return { files, size, risk: t?.risk === true, decisionNeeded: t?.decision_needed === true, source: t ? "triage" : "affected_files" };
47
+ }
48
+
49
+ /** Eligibility from the investigation's findings; the text verdict is recorded as the shadow `pre_text_*` signal. */
50
+ export function fastForwardEligibility({ title = "", body = "", labels = [], triage = null, textFiles = [], riskPaths = [], hotspots = [], cfg = {} } = {}) {
51
+ const t = triage ?? { files: [], size: null, risk: false, decisionNeeded: false };
52
+ const text = lightEligibility({ title, body, labels, predictedFiles: textFiles, cfg: { ...cfg, mode: cfg.mode === "off" ? "off" : "shadow" } });
53
+ const extraHard = [
54
+ ...(t.risk ? [{ code: "risk", detail: "the investigation flagged the change as risky" }] : []),
55
+ ...(t.decisionNeeded ? [{ code: "decision", detail: "the investigation says a decision is needed" }] : []),
56
+ ];
57
+ return lightEligibility({ title, body, labels, predictedFiles: t.files, riskPaths, hotspots, cfg, source: "investigation", size: t.size, extraHard, preText: text.verdict });
58
+ }
59
+
60
+ /** The stages a fast-forwarded lane skips and why: [{stage, why}]. */
61
+ export function skippedStages(elig = null) {
62
+ const why = `investigation predicts a small change (${elig?.signals?.find((s) => s.code === "files_named")?.detail ?? "?"} non-test file(s), no risk path or hotspot)`;
63
+ return ["plan", "contract freeze", "multi-session review"].map((stage) => ({ stage, why }));
64
+ }
65
+
66
+ /** One line for the trajectory and the FORGE:LITE receipt. */
67
+ export const skippedLine = (elig) => `Fast-forward: skipped ${skippedStages(elig).map((x) => x.stage).join(", ")}; ${skippedStages(elig)[0].why}`;
68
+
69
+ const TRIAGE_RULE = `3. Write ${TRIAGE_FILE}: {"files":["<non-test file you predict will change>"],"size":"S|M|L","risk":false,"decision_needed":false}. "files" are repo-relative non-test paths from your Affected Files; size S = a small fix in at most a couple of files; risk true when the fix touches auth, security, payments, migrations, CI or public API shape; decision_needed true when a design or product choice must be made first. The engine reads it to pick the pipeline depth.
70
+
71
+ Stop after the files above. Do not write ${CONTRACT_FILE} yet: the engine tells you whether to continue.`;
72
+
73
+ /** Call 1 when source is investigation: step 1 of the plan prompt (investigation, close rules, block rules) plus the triage file. */
74
+ export function investigationOnlyPrompt(n, opts = {}) {
75
+ const full = builderPlanPrompt(n, opts);
76
+ const cut = full.indexOf("\n2. Otherwise write"), blocks = full.indexOf('"blocked" needs a typed');
77
+ if (cut < 0 || blocks < 0) return full;
78
+ return `${full.slice(0, cut)}\n2. Do not write the contract yet.\n${TRIAGE_RULE}\n\n${full.slice(blocks)}`;
79
+ }
80
+
81
+ /** Call 2 (same session) when the issue is not fast-forwarded: the contract step of the plan prompt. */
82
+ export function contractStepPrompt(n, opts = {}) {
83
+ const full = builderPlanPrompt(n, opts);
84
+ const cut = full.indexOf("2. Otherwise write");
85
+ return `Your investigation is written and the engine is continuing with the full lane. This is still PLANNING ONLY: no code edits, no commits.\n\n${cut < 0 ? full : full.slice(cut)}`;
86
+ }
87
+
88
+ /** The light build prompt's lead-in when it resumes the investigation session. */
89
+ export const FF_BUILD_LEAD = `The investigation step is complete and the engine fast-forwards this issue (small, no risk path): the planning-only rule no longer applies. Implement the fix now.\n\n`;
90
+
91
+ /** The FASTFORWARD_ELIGIBILITY run-log event (read by `stats --depth`); `shadow` = logged beside a normal full-lane plan session. */
92
+ export const fastForwardEvent = (elig, triage, { shadow = false } = {}) => ({ event: "FASTFORWARD_ELIGIBILITY", mode: elig.mode, verdict: elig.verdict, eligible: elig.eligible, light: elig.light, shadow,
93
+ files: triage.files.length, size: triage.size, triage: triage.source, reasons: elig.reasons, signals: elig.signals });
@@ -0,0 +1,73 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ import { describe, it } from "node:test";
4
+ import assert from "node:assert/strict";
5
+ import { affectedFilesOf, parseTriage, fastForwardEligibility, skippedStages, skippedLine, investigationOnlyPrompt, contractStepPrompt, fastForwardSource, TRIAGE_FILE } from "./fastforward.mjs";
6
+ import { parseLightConfig } from "./light.mjs";
7
+
8
+ const CFG = { mode: "on", maxLines: 40, maxFiles: 2 };
9
+ const MD = "### Affected Files\n- `bin/lean/light.mjs`: eligibility\n- bin/lean/light.test.mjs\n- docs/CONFIG.md (see section 3)\n\n### Sibling Sweep\n- other/file.mjs\n";
10
+ const triage = (o = {}) => ({ files: ["src/a.mjs"], size: "S", risk: false, decisionNeeded: false, ...o });
11
+ const codes = (e) => e.reasons.map((r) => r.code);
12
+
13
+ describe("triage parsing (#5426)", () => {
14
+ it("reads paths from the Affected Files section only, first token per bullet", () => {
15
+ assert.deepEqual(affectedFilesOf(MD), ["bin/lean/light.mjs", "bin/lean/light.test.mjs", "docs/CONFIG.md"]);
16
+ assert.deepEqual(affectedFilesOf("no section"), []);
17
+ });
18
+ it("prefers triage.json, falls back to Affected Files on junk, and treats a bad size as unknown", () => {
19
+ assert.deepEqual(parseTriage('{"files":["./a.js","a.js","b.js"],"size":"s","risk":true,"decision_needed":true}', MD), { files: ["a.js", "b.js"], size: "S", risk: true, decisionNeeded: true, source: "triage" });
20
+ const f = parseTriage("not json", MD);
21
+ assert.equal(f.source, "affected_files"); assert.equal(f.size, null); assert.equal(f.files.length, 3);
22
+ assert.equal(parseTriage('{"files":[],"size":"XL"}', "").size, null);
23
+ });
24
+ it("lean.light.source: investigation by default, text is the kill-switch", () => {
25
+ assert.equal(fastForwardSource(parseLightConfig({})), "investigation");
26
+ assert.equal(fastForwardSource(parseLightConfig({ source: "Text" })), "text");
27
+ assert.equal(fastForwardSource(parseLightConfig({ light_source: "bogus" })), "investigation");
28
+ assert.equal("source" in parseLightConfig({}), false);
29
+ });
30
+ });
31
+
32
+ describe("eligibility from the investigation (#5426)", () => {
33
+ it("an issue naming no file and no size label qualifies when the investigation predicts one small file", () => {
34
+ const e = fastForwardEligibility({ title: "bug: x", body: "It breaks.", triage: triage(), cfg: CFG });
35
+ assert.equal(e.verdict, "eligible"); assert.equal(e.light, true);
36
+ assert.ok(e.signals.some((s) => s.code === "source_investigation"));
37
+ assert.ok(e.signals.some((s) => s.code === "pre_text_ambiguous"), "the text heuristic is only a shadow signal");
38
+ });
39
+ it("the text heuristic never decides: text-eligible but the investigation predicts 3 files is ineligible", () => {
40
+ const body = "```\nrepro\n```\nbin/a.mjs";
41
+ const e = fastForwardEligibility({ body, textFiles: ["bin/a.mjs"], triage: triage({ files: ["a.mjs", "b.mjs", "c.mjs"] }), cfg: CFG });
42
+ assert.equal(e.verdict, "ineligible"); assert.ok(codes(e).includes("files"));
43
+ assert.ok(e.signals.some((s) => s.code === "pre_text_eligible"));
44
+ });
45
+ it("risk path, hotspot, size M, flagged risk and decision are each hard reasons", () => {
46
+ assert.ok(codes(fastForwardEligibility({ triage: triage({ files: ["src/auth/login.mjs"] }), cfg: CFG })).includes("risk_path"));
47
+ assert.ok(codes(fastForwardEligibility({ triage: triage(), hotspots: [{ path: "src/a.mjs", lines: 3000, over: true }], cfg: CFG })).includes("hotspot"));
48
+ assert.ok(codes(fastForwardEligibility({ triage: triage({ size: "M" }), cfg: CFG })).includes("size"));
49
+ assert.ok(codes(fastForwardEligibility({ triage: triage({ risk: true }), cfg: CFG })).includes("risk"));
50
+ assert.ok(codes(fastForwardEligibility({ triage: triage({ decisionNeeded: true }), cfg: CFG })).includes("decision"));
51
+ });
52
+ it("no predicted files is ambiguous, not eligible; shadow mode never runs light; off is off", () => {
53
+ assert.equal(fastForwardEligibility({ triage: triage({ files: [] }), cfg: CFG }).verdict, "ambiguous");
54
+ const s = fastForwardEligibility({ triage: triage(), cfg: { ...CFG, mode: "shadow" } });
55
+ assert.equal(s.eligible, true); assert.equal(s.light, false);
56
+ assert.equal(fastForwardEligibility({ triage: triage(), cfg: { ...CFG, mode: "off" } }).verdict, "off");
57
+ });
58
+ });
59
+
60
+ describe("fast-forward prompts and trajectory (#5426)", () => {
61
+ it("names the skipped stages and why", () => {
62
+ const e = fastForwardEligibility({ triage: triage(), cfg: CFG });
63
+ assert.deepEqual(skippedStages(e).map((x) => x.stage), ["plan", "contract freeze", "multi-session review"]);
64
+ assert.match(skippedLine(e), /Fast-forward: skipped plan, contract freeze.*1 non-test file/);
65
+ });
66
+ it("investigation-only keeps the close and block rules but defers the contract; the contract step carries it", () => {
67
+ const a = investigationOnlyPrompt(7), b = contractStepPrompt(7);
68
+ assert.match(a, /Write \.forge-lean\/investigation\.md/); assert.ok(a.includes(TRIAGE_FILE)); assert.match(a, /"blocked" needs a typed/);
69
+ assert.ok(!a.includes('{"requirements":['));
70
+ assert.ok(b.includes('{"requirements":[') && b.includes('"blocked" needs a typed'));
71
+ assert.ok(!/1\. Write \.forge-lean\/investigation\.md/.test(b));
72
+ });
73
+ });
@@ -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 queue = jobs.slice();
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
- let body;
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, jobs.length)) }, work));
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, "&amp;").replace(/</g, "&lt;")}</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 stale. */
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"|"stale"|"done"|"unknown", reason, ageMs}` from a watch's status.json: never a process grep. */
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: "stale", reason: `last heartbeat ${Math.round(ageMs / 60000)}m ago, over ${Math.round(limit / 60000)}m: the watch is not running`, ageMs };
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
+ }