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
@@ -0,0 +1,83 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * Scheduled hygiene outside batches (#5421): `forgedock gc --apply` (owned scope only) on a systemd user timer, with a cron
5
+ * entry as the fallback, driven by forge.yaml `hygiene.schedule` ("6h", "30m", "2d"). Installed by `doctor --fix` and
6
+ * `forgedock init`. An empty schedule or `hygiene.auto_gc: false` removes the entry. All I/O is injected (`exec`, `fs`).
7
+ */
8
+ import * as nodeFs from "node:fs";
9
+ import { createHash } from "node:crypto";
10
+ import { execFile } from "node:child_process";
11
+ import { promisify } from "node:util";
12
+ import { homedir } from "node:os";
13
+ import { dirname, join, resolve } from "node:path";
14
+ import { fileURLToPath } from "node:url";
15
+ import { parseDuration } from "./gc.mjs";
16
+
17
+ const pexec = promisify(execFile);
18
+ const CRON_TAG = "# forgedock-gc";
19
+
20
+ /** Unit basename for one repo: `forgedock-gc-<8 hex of the repo path>`. */
21
+ export const unitName = (cwd) => `forgedock-gc-${createHash("sha1").update(resolve(cwd)).digest("hex").slice(0, 8)}`;
22
+
23
+ const q = (s) => `"${String(s).replace(/(["\\$`])/g, "\\$1")}"`;
24
+ const forgedockBin = () => join(dirname(fileURLToPath(import.meta.url)), "forgedock.mjs");
25
+
26
+ /** systemd service + timer text. OnUnitActiveSec is the schedule; Persistent catches up a run missed while the host was off. */
27
+ export function renderSystemd({ schedule, cwd, node = process.execPath, bin = forgedockBin() }) {
28
+ const min = Math.max(1, Math.round(parseDuration(schedule) / 60000));
29
+ return {
30
+ service: `[Unit]\nDescription=ForgeDock owned-resource GC (${resolve(cwd)})\n\n[Service]\nType=oneshot\nWorkingDirectory=${resolve(cwd)}\nExecStart=${q(node)} ${q(bin)} gc --apply\n`,
31
+ timer: `[Unit]\nDescription=ForgeDock owned-resource GC every ${schedule}\n\n[Timer]\nOnBootSec=5min\nOnUnitActiveSec=${min}min\nPersistent=true\n\n[Install]\nWantedBy=timers.target\n`,
32
+ };
33
+ }
34
+
35
+ /** One crontab line (tagged so it can be replaced or removed): minutes < 60, whole hours < 24, else daily. */
36
+ export function renderCron({ schedule, cwd, node = process.execPath, bin = forgedockBin() }) {
37
+ const min = Math.max(1, Math.round(parseDuration(schedule) / 60000));
38
+ const when = min < 60 ? `*/${min} * * * *` : min < 1440 ? `0 */${Math.max(1, Math.round(min / 60))} * * *` : "0 0 * * *";
39
+ return `${when} cd ${q(resolve(cwd))} && ${q(node)} ${q(bin)} gc --apply >/dev/null 2>&1 ${CRON_TAG} ${resolve(cwd)}`;
40
+ }
41
+
42
+ /**
43
+ * Install (or remove) the schedule. `enabled` is hygiene.auto_gc. Returns {status, kind, detail}; status is
44
+ * installed | removed | off | failed. Never throws.
45
+ */
46
+ export async function installGcSchedule({ schedule = "", enabled = true, cwd = process.cwd(), home = homedir(), platform = process.platform, fs = nodeFs, exec = async (cmd, args, input) => { const p = pexec(cmd, args, { timeout: 30000 }); if (input != null) p.child.stdin.end(input); return (await p).stdout; }, node, bin } = {}) {
47
+ const name = unitName(cwd);
48
+ const dir = join(home, ".config", "systemd", "user");
49
+ const want = enabled && !!schedule;
50
+ const opts = { schedule, cwd, ...(node ? { node } : {}), ...(bin ? { bin } : {}) };
51
+ try {
52
+ if (platform === "linux") {
53
+ let hasSystemd = false;
54
+ try { await exec("systemctl", ["--user", "show-environment"]); hasSystemd = true; } catch { hasSystemd = false; }
55
+ if (hasSystemd) {
56
+ if (!want) {
57
+ if (!fs.existsSync(join(dir, `${name}.timer`))) return { status: "off", kind: "systemd", detail: "no schedule set" };
58
+ try { await exec("systemctl", ["--user", "disable", "--now", `${name}.timer`]); } catch { /* already gone */ }
59
+ for (const f of [`${name}.timer`, `${name}.service`]) fs.rmSync(join(dir, f), { force: true });
60
+ return { status: "removed", kind: "systemd", detail: `removed ${name}.timer` };
61
+ }
62
+ const { service, timer } = renderSystemd(opts);
63
+ fs.mkdirSync(dir, { recursive: true });
64
+ fs.writeFileSync(join(dir, `${name}.service`), service);
65
+ fs.writeFileSync(join(dir, `${name}.timer`), timer);
66
+ await exec("systemctl", ["--user", "daemon-reload"]);
67
+ await exec("systemctl", ["--user", "enable", "--now", `${name}.timer`]);
68
+ return { status: "installed", kind: "systemd", detail: `${name}.timer every ${schedule}` };
69
+ }
70
+ }
71
+ // cron fallback: replace our tagged line for this repo, keep every other line.
72
+ let cur = "";
73
+ try { cur = String(await exec("crontab", ["-l"])); } catch { cur = ""; }
74
+ const mine = (l) => l.trimEnd().endsWith(`${CRON_TAG} ${resolve(cwd)}`); // end-anchored: `/work/repo` must not match `/work/repo2`
75
+ const rest = cur.split("\n").filter((l) => l.trim() && !mine(l));
76
+ if (!want && rest.length === cur.split("\n").filter((l) => l.trim()).length) return { status: "off", kind: "cron", detail: "no schedule set" };
77
+ const next = [...rest, ...(want ? [renderCron(opts)] : [])];
78
+ await exec("crontab", ["-"], next.join("\n") + "\n");
79
+ return want ? { status: "installed", kind: "cron", detail: `crontab entry every ${schedule}` } : { status: "removed", kind: "cron", detail: "removed crontab entry" };
80
+ } catch (e) {
81
+ return { status: "failed", kind: "unknown", detail: String(e?.message ?? e).slice(0, 200) };
82
+ }
83
+ }
package/bin/gc.mjs CHANGED
@@ -57,7 +57,9 @@ export function parseGcArgs(argv = []) {
57
57
  }
58
58
 
59
59
  /** forge.yaml `hygiene:` defaults (#4183). TTLs in hours; `max_host_load_ratio` is the near-ceiling trigger for orchestrate GC. */
60
- export const HYGIENE_DEFAULTS = Object.freeze({ container_ttl_hours: 6, worktree_ttl_hours: 24, tmp_ttl_hours: 6, delete_merged_branches: true, max_host_load_ratio: 0.8, auto_gc: true });
60
+ export const HYGIENE_DEFAULTS = Object.freeze({ container_ttl_hours: 6, worktree_ttl_hours: 24, tmp_ttl_hours: 6, delete_merged_branches: true, max_host_load_ratio: 0.8, auto_gc: true, schedule: "", min_free_gb: 5 });
61
+ /** Compose projects a lane starts are named `forgedock-lane-<issue>` (#5421); their containers and volumes are owned by that name. */
62
+ export const LANE_COMPOSE_RE = /^forgedock-lane-\d+/;
61
63
 
62
64
  /** Top-level forge.yaml `hygiene:` block (block form only); each missing or invalid value falls back to its default. */
63
65
  export function readHygiene(cwd = process.cwd(), { fs = nodeFs } = {}) {
@@ -67,7 +69,13 @@ export function readHygiene(cwd = process.cwd(), { fs = nodeFs } = {}) {
67
69
  const hours = (k) => { const v = h[k], n = Number(v); return v !== undefined && v !== "" && Number.isFinite(n) && n >= 0 ? n : HYGIENE_DEFAULTS[k]; };
68
70
  const bool = (k) => { const v = String(h[k] ?? "").trim().toLowerCase(); return v === "true" ? true : v === "false" ? false : HYGIENE_DEFAULTS[k]; };
69
71
  const ratio = Number(h.max_host_load_ratio);
72
+ // #5421: `schedule` ("6h", "30m", "2d"; empty/off/invalid = no timer) and the free-disk threshold in GB (0 = off).
73
+ const sched = String(h.schedule ?? "").trim().toLowerCase();
74
+ let schedule = "";
75
+ if (sched && sched !== "off" && sched !== "false") { try { parseDuration(sched); schedule = sched; } catch { schedule = ""; } }
76
+ const gb = Number(h.min_free_gb);
70
77
  return {
78
+ schedule, min_free_gb: h.min_free_gb !== undefined && h.min_free_gb !== "" && Number.isFinite(gb) && gb >= 0 ? gb : HYGIENE_DEFAULTS.min_free_gb,
71
79
  container_ttl_hours: hours("container_ttl_hours"), worktree_ttl_hours: hours("worktree_ttl_hours"), tmp_ttl_hours: hours("tmp_ttl_hours"),
72
80
  delete_merged_branches: bool("delete_merged_branches"), auto_gc: bool("auto_gc"),
73
81
  max_host_load_ratio: h.max_host_load_ratio !== undefined && h.max_host_load_ratio !== "" && ratio > 0 && ratio <= 1 ? ratio : HYGIENE_DEFAULTS.max_host_load_ratio,
@@ -108,6 +116,7 @@ export function makeGcProbes({ cwd = process.cwd(), home = homedir() } = {}) {
108
116
  ledgerRoot: home === homedir() ? defaultLedgerRoot() : join(home, ".forge", "ledger"),
109
117
  forgeTmpRoot: join(home, ".forge", "tmp"),
110
118
  worktreeRoot: join(cwd, ".claude", "worktrees"),
119
+ legacyWorktreeRoot: join(cwd, ".forge", "worktrees"),
111
120
  protectedBranches: ["main", "master", "staging", b.default, b.staging].filter(Boolean),
112
121
  alive: pidAlive, ppid: (pid) => ppidFromProc(pid), procsInDir: (d) => procsInDir(d),
113
122
  killPid: async (pid, marker) => killLedgerPid(pid, marker),
@@ -272,7 +281,8 @@ export async function planGc({ probes, scopes = new Set(GC_SCOPES), olderThanMs
272
281
  // ---- 2. docker: labelled forgedock.owner=1 is owned; everything else is "not owned" ----
273
282
  if (want("container") || want("volume")) {
274
283
  const ownedBy = (labels, createdMs, type) => {
275
- if (labels["forgedock.owner"] !== "1") return { owned: false, action: "report", reason: "not owned" };
284
+ const lane = LANE_COMPOSE_RE.test(String(labels["com.docker.compose.project"] ?? "")); // #5421: lane compose project by name
285
+ if (labels["forgedock.owner"] !== "1" && !lane) return { owned: false, action: "report", reason: "not owned" };
276
286
  let exp = Number(labels["forgedock.expires"]);
277
287
  if (Number.isFinite(exp) && exp > 0 && exp < 1e12) exp *= 1000;
278
288
  if (Number.isFinite(exp) && exp > 0 && exp < now) return { owned: true, action: "reclaim", reason: "forgedock label, expired" };
@@ -294,7 +304,7 @@ export async function planGc({ probes, scopes = new Set(GC_SCOPES), olderThanMs
294
304
  try {
295
305
  const vols = jsonLines(await P.docker(["volume", "ls", "--format", "{{json .}}"]));
296
306
  const created = new Map();
297
- const labelled = vols.filter((v) => parseLabels(v.Labels)["forgedock.owner"] === "1").map((v) => v.Name);
307
+ const labelled = vols.filter((v) => { const l = parseLabels(v.Labels); return l["forgedock.owner"] === "1" || LANE_COMPOSE_RE.test(String(l["com.docker.compose.project"] ?? "")); }).map((v) => v.Name);
298
308
  if (labelled.length) {
299
309
  try { for (const l of String(await P.docker(["volume", "inspect", "--format", "{{.Name}}\t{{.CreatedAt}}", ...labelled])).split("\n")) { const [n, t] = l.split("\t"); if (n) created.set(n, Date.parse(t)); } }
300
310
  catch { /* age unknown: kept unless expired */ }
@@ -329,6 +339,27 @@ export async function planGc({ probes, scopes = new Set(GC_SCOPES), olderThanMs
329
339
  }
330
340
  }
331
341
 
342
+ // ---- 3b. legacy <repo>/.forge/worktrees/* (#5421): reported; reclaimed only when clean, HEAD on a remote, no live process ----
343
+ if (want("worktree") && worktreeListOk && P.legacyWorktreeRoot) {
344
+ let names = [];
345
+ try { names = fs.readdirSync(P.legacyWorktreeRoot); } catch { /* no legacy root */ }
346
+ for (const n of names) {
347
+ const dir = resolve(join(P.legacyWorktreeRoot, n));
348
+ if (seen.has(`worktree:${dir}`) || liveIds.has(`worktree:${dir}`)) continue;
349
+ try { if (!fs.lstatSync(dir).isDirectory()) continue; } catch { continue; }
350
+ const reg = registered.has(dir);
351
+ const it = { type: "worktree", id: dir, sizeBytes: P.dirSize?.(dir) ?? null, ageMs: age(mtime(dir)), owned: false, action: "report", reason: "", registered: reg, legacy: true };
352
+ const procs = P.procsInDir?.(dir) ?? [];
353
+ const w = await workIn(dir);
354
+ if (procs.length) it.reason = "legacy orchestrator dir, live process inside";
355
+ else if (w) it.reason = `legacy orchestrator dir, ${w}`;
356
+ else if (w === null) it.reason = "legacy orchestrator dir, cannot inspect";
357
+ else if (!(it.ageMs >= ttl("worktree"))) it.reason = "legacy orchestrator dir, younger than TTL";
358
+ else { it.owned = true; it.action = "reclaim"; it.reason = "legacy orchestrator dir, clean and on a remote"; }
359
+ add(it);
360
+ }
361
+ }
362
+
332
363
  // ---- 4. branches: feat/issue-<n>-lean, local and origin, abandoned (closed or invalid issue) and older than TTL ----
333
364
  if (want("branch")) {
334
365
  const scan = async (ref, local) => {
@@ -398,7 +429,20 @@ export async function planGc({ probes, scopes = new Set(GC_SCOPES), olderThanMs
398
429
  if (!st.isDirectory()) { add({ type: "tmp", id: resolve(p), sizeBytes: st.size, ageMs: age(st.mtimeMs), owned: false, action: "report", reason: "unrecognised entry" }); continue; }
399
430
  let kids = []; try { kids = fs.readdirSync(p); } catch { /* unreadable */ }
400
431
  const scratch = kids.length > 0 && kids.every((k) => /^\d+$/.test(k));
401
- if (!scratch) { add({ type: "tmp", id: resolve(p), sizeBytes: P.dirSize?.(p) ?? null, ageMs: age(st.mtimeMs), owned: false, action: "report", reason: "unrecognised entry" }); continue; }
432
+ if (!scratch) {
433
+ // #5421: a top-level scratch dir with a run-owner marker follows the run-dir rule (stale, owner dead on this host).
434
+ let own = null; try { own = JSON.parse(fs.readFileSync(join(p, RUN_OWNER), "utf8")); } catch { /* unmarked */ }
435
+ if (own) {
436
+ const dir = resolve(p), it = { type: "tmp", id: dir, sizeBytes: P.dirSize?.(dir) ?? null, ageMs: age(Number(own.created)), owned: true, action: "report", reason: "", runDir: true };
437
+ if (!(it.ageMs >= ttl("tmp"))) it.reason = "younger than TTL";
438
+ else if (own.host !== P.host) it.reason = "owner on another host";
439
+ else if (Number.isSafeInteger(own.pid) && P.alive(own.pid)) it.reason = "owner alive";
440
+ else { it.action = "reclaim"; it.reason = "stale marked scratch, owner dead"; }
441
+ add(it);
442
+ continue;
443
+ }
444
+ add({ type: "tmp", id: resolve(p), sizeBytes: P.dirSize?.(p) ?? null, ageMs: age(st.mtimeMs), owned: false, action: "report", reason: "unrecognised entry" }); continue;
445
+ }
402
446
  for (const k of kids) {
403
447
  const dir = resolve(join(p, k));
404
448
  if (seen.has(`tmp:${dir}`) || liveIds.has(`tmp:${dir}`)) continue;
@@ -492,7 +536,7 @@ export async function applyGc(plan, probes, { deadline = null, now = () => Date.
492
536
  case "worktree":
493
537
  if (it.registered) await git(["worktree", "remove", "--force", it.id]);
494
538
  else if (fs.existsSync(it.id)) {
495
- if (!isDirectChild(P.worktreeRoot, it.id)) throw new Error("not a direct child of the worktree root");
539
+ if (!isDirectChild(P.worktreeRoot, it.id) && !(it.legacy && P.legacyWorktreeRoot && isDirectChild(P.legacyWorktreeRoot, it.id))) throw new Error("not a direct child of the worktree root");
496
540
  fs.rmSync(it.id, { recursive: true, force: true });
497
541
  }
498
542
  prune = true;
@@ -592,7 +636,7 @@ export async function runOwnedGc({ probes, hygiene = HYGIENE_DEFAULTS, scopes =
592
636
  * doctor's "Resource hygiene" line (#4183): owned counts/sizes per type, reclaimable count, and unowned items older than
593
637
  * their type TTL (reported only, never touched). warn when something is reclaimable (and not applied) or unowned-stale.
594
638
  */
595
- export function hygieneCheck(plan, { applied = null, ttlMs = plan?.ttlMs ?? hygieneTtls() } = {}) {
639
+ export function hygieneCheck(plan, { applied = null, ttlMs = plan?.ttlMs ?? hygieneTtls(), disk = null } = {}) {
596
640
  const items = plan?.items ?? [];
597
641
  const parts = [];
598
642
  for (const t of GC_TYPES) {
@@ -608,8 +652,12 @@ export function hygieneCheck(plan, { applied = null, ttlMs = plan?.ttlMs ?? hygi
608
652
  else bits.push(`${reclaimable} reclaimable`);
609
653
  if (stale) bits.push(`${stale} unowned stale (report only)`);
610
654
  const pending = applied ? applied.failed.length + (applied.deferred?.length ?? 0) : reclaimable;
611
- const status = pending > 0 || stale > 0 ? "warn" : "pass";
655
+ // #5421: free disk below hygiene.min_free_gb warns, with the owned bytes a reclaim would free.
656
+ const ownedBytes = items.filter((i) => i.owned && i.action === "reclaim").reduce((s, i) => s + (i.sizeBytes ?? 0), 0);
657
+ const low = !!disk && Number.isFinite(disk.freeGb) && Number.isFinite(disk.minFreeGb) && disk.minFreeGb > 0 && disk.freeGb < disk.minFreeGb;
658
+ if (low) bits.push(`free disk ${disk.freeGb.toFixed(1)} GB < ${disk.minFreeGb} GB (hygiene.min_free_gb); ${fmtSize(ownedBytes)} owned reclaimable`);
659
+ const status = pending > 0 || stale > 0 || low ? "warn" : "pass";
612
660
  let detail = bits.join("; ");
613
661
  if (!applied && reclaimable > 0) detail += ". Run: npx forgedock doctor --fix (or: npx forgedock gc --apply)";
614
- return { status, detail, reclaimable, stale };
662
+ return { status, detail, reclaimable, stale, lowDisk: low, ownedBytes };
615
663
  }
package/bin/help-text.mjs CHANGED
@@ -67,7 +67,7 @@ export const FULL_COMMAND_GROUPS = [
67
67
  ["npx forgedock run-issue <issue> [--lane <lane>] [--lane-override] [--path core|full] [--retry] [--wait-lease]", "Work one issue from claim to merge (the lane comes from the issue: its milestone, else staging; --lane only asserts it). --retry reopens a failed run, or one needing a human once the label is cleared; --wait-lease waits for another holder of the issue; exit status 75 means deferred, nothing was lost"],
68
68
  ["npx forgedock plan validate --live [--repo owner/repo] [--json]", "Re-run the bootstrap dependency-order rules on live GitHub state: each cross-milestone Depends-on edge is ok, held or invalid (fails on invalid)"],
69
69
  ["npx forgedock orchestrate <issue...> [--parallel K] [--lane L]", "Work on several issues with bounded concurrency and Depends-on ordering; each issue on its own lane, cross-lane dependencies reported"],
70
- ["npx forgedock orchestrate --resume <id> [N...] | --set-parallel <id> K | --set-max-remote <id> N | --set-placement <id> remote|hybrid|local | --add <id> N... | --requeue <id> N... [--reason \"...\"] | --cancel <id> | --hold <id> N... | --release <id> N... | --show-env <id> | --set-env <id> KEY=VAL | --unset-env <id> KEY", "Reattach to a running or finished batch (a finished one replays its report, an interrupted one resumes), change its concurrency or placement live, add, requeue, hold or release single issues, stop one batch without stopping the background scheduler, or print, set or unset the batch environment (secrets redacted; applies to newly started lanes)"],
70
+ ["npx forgedock orchestrate --resume <id> [N...] | --set-parallel <id> K | --set-max-remote <id> N | --set-placement <id> remote|hybrid|local | --add <id> N... | --requeue <id> N... [--reason \"...\"] | --cancel <id> | --hold <id> N... [--for 4h] [--reason \"...\"] | --adopt <issue> | --gc-orphans | --release <id> N... | --show-env <id> | --set-env <id> KEY=VAL | --unset-env <id> KEY", "Reattach to a running or finished batch (a finished one replays its report, an interrupted one resumes), change its concurrency or placement live, add, requeue, hold (with an owner and an optional expiry, --for) or release single issues, adopt an open hand-built PR, cancel orphaned batches (--gc-orphans), stop one batch without stopping the background scheduler, or print, set or unset the batch environment (secrets redacted; applies to newly started lanes)"],
71
71
  ["npx forgedock triage <issue...> [--lane L] [--dry-run]", "Already-fixed pre-filter: close issues a merged PR or green CI already resolved; print the rest"],
72
72
  ["npx forgedock probe [issue...] [--dry-run]", "Run declared acceptance probes for closed issues whose fix is on the default branch; a fail reopens the issue"],
73
73
  ["npx forgedock acceptance check|run|gate", "Feature-level acceptance: validate an epic's journeys, run them on the milestone branch, gate ship/close on a green run"],
@@ -202,6 +202,7 @@ const LABEL_TRANSITIONS = {
202
202
  "workflow:remediating": ["workflow:in-review", "workflow:awaiting-merge", "workflow:merged", "workflow:invalid"], // #3541/#3565: remediation → re-review/merge; evidenced reversal allowed
203
203
  "workflow:awaiting-merge": ["workflow:merged", "workflow:in-review", "workflow:remediating", "workflow:invalid"], // #1810/#3565: merge queue; evidenced reversal allowed
204
204
  "workflow:merged": [], // terminal — no successors
205
+ "workflow:merged-unverified": [], // terminal — a human decides (#5443)
205
206
  "workflow:invalid": [], // terminal
206
207
  "workflow:decomposed": [], // terminal
207
208
  };
@@ -26,7 +26,7 @@
26
26
 
27
27
  import { execFileSync } from "child_process";
28
28
  import { join, resolve } from "path";
29
- import { readdirSync, existsSync } from "fs";
29
+ import { readdirSync, existsSync, readFileSync } from "fs";
30
30
 
31
31
  // ---------------------------------------------------------------------------
32
32
  // Field factory helpers
@@ -474,10 +474,80 @@ export async function detectConfig(cwd = process.cwd()) {
474
474
  remoteDetected,
475
475
  ...repoState,
476
476
  stagingMissing: stagingBranchField.source !== "git branch -r",
477
+ sandboxes: detectSandboxes(gitRoot),
477
478
  },
478
479
  };
479
480
  }
480
481
 
482
+ // ---------------------------------------------------------------------------
483
+ // verify.sandboxes proposal (#5450)
484
+ // ---------------------------------------------------------------------------
485
+
486
+ const COMPOSE_FILES = ["docker-compose.test.yml", "docker-compose.test.yaml", "compose.test.yml", "docker-compose.yml", "docker-compose.yaml", "compose.yml", "compose.yaml"];
487
+ const MIGRATION_DIRS = ["migrations", "db/migrate", "db/migrations", "alembic", "prisma/migrations", "drizzle", "supabase/migrations"];
488
+ const TEST_MARKERS = ["pytest.ini", "conftest.py", "tox.ini", "jest.config.js", "jest.config.ts", "vitest.config.ts", "vitest.config.js"];
489
+
490
+ /** Services (name -> image|null) from a compose file's text; indentation-based, no YAML dependency. */
491
+ function composeServices(text) {
492
+ const out = {};
493
+ let inServices = false, cur = null;
494
+ for (const line of String(text).split("\n")) {
495
+ if (/^\S/.test(line)) { inServices = /^services\s*:/.test(line); cur = null; continue; }
496
+ if (!inServices) continue;
497
+ const svc = /^ {1,4}([A-Za-z0-9_.-]+)\s*:\s*$/.exec(line);
498
+ if (svc) { cur = svc[1]; out[cur] = null; continue; }
499
+ const img = /^\s+image\s*:\s*["']?([^\s"']+)/.exec(line);
500
+ if (img && cur) out[cur] = img[1];
501
+ }
502
+ return out;
503
+ }
504
+
505
+ /**
506
+ * Propose `verify.sandboxes` from compose files, migration directories and test markers. Pure over `fs` ({existsSync, readFileSync});
507
+ * returns `{name: "{ image: ... }"}` one-line entries (the forge.yaml form), `{}` when nothing is detected. Postgres/redis
508
+ * services become image entries; other compose services become compose entries that need them; migrations without a compose
509
+ * postgres propose one with a migrate `init` placeholder. A proposal only: init writes it commented.
510
+ */
511
+ export function detectSandboxes(cwd, fs = { existsSync, readFileSync }) {
512
+ const out = {};
513
+ const compose = COMPOSE_FILES.find((f) => fs.existsSync(join(cwd, f)));
514
+ const hasMigrations = MIGRATION_DIRS.some((d) => fs.existsSync(join(cwd, d)));
515
+ const hasTests = TEST_MARKERS.some((f) => fs.existsSync(join(cwd, f)));
516
+ if (compose) {
517
+ let svcs = {};
518
+ try { svcs = composeServices(fs.readFileSync(join(cwd, compose), "utf8")); } catch { /* unreadable: no proposal from it */ }
519
+ const infra = [];
520
+ for (const [name, image] of Object.entries(svcs)) {
521
+ const base = String(image ?? "").split(":")[0].split("/").pop();
522
+ if (base === "postgres" || base === "redis") { out[base] = `{ image: ${image} }`; infra.push(base); }
523
+ }
524
+ for (const [name, image] of Object.entries(svcs)) {
525
+ const base = String(image ?? "").split(":")[0].split("/").pop();
526
+ if (base === "postgres" || base === "redis" || !/^[a-z][a-z0-9_-]*$/.test(name)) continue;
527
+ out[name] = `{ compose: ${compose}, service: ${name}${infra.length ? `, needs: [${infra.join(", ")}]` : ""} }`;
528
+ }
529
+ }
530
+ if (hasMigrations && !out.postgres && (hasTests || compose)) out.postgres = '{ image: postgres:16, init: "<your migrate command> $SANDBOX_URL" }';
531
+ else if (hasMigrations && out.postgres && !out.postgres.includes("init:")) out.postgres = out.postgres.replace(/ }$/, ', init: "<your migrate command> $SANDBOX_URL" }');
532
+ return out;
533
+ }
534
+
535
+ /** The commented forge.yaml block for a detected proposal; "" when there is none. */
536
+ export function sandboxesProposalYaml(sandboxes) {
537
+ const names = Object.keys(sandboxes ?? {});
538
+ if (!names.length) return "";
539
+ return `
540
+ # =============================================================================
541
+ # TEST SANDBOXES (proposed by init, uncomment to enable; see docs/CONFIG.md verify.sandboxes)
542
+ # =============================================================================
543
+ # A lane creates these only when a contract validate entry names them in env.
544
+ #
545
+ # verify:
546
+ # sandboxes:
547
+ ${names.map((n) => `# ${n}: ${sandboxes[n]}`).join("\n")}
548
+ `;
549
+ }
550
+
481
551
  // ---------------------------------------------------------------------------
482
552
  // Minimal forge.yaml template builder
483
553
  // ---------------------------------------------------------------------------
@@ -531,6 +601,7 @@ export function buildMinimalForgeYaml({
531
601
  worktreeBase,
532
602
  defaultBranch,
533
603
  stagingBranch,
604
+ sandboxes = {},
534
605
  }) {
535
606
  const e = escapeYamlScalar;
536
607
  const descLine = description
@@ -570,5 +641,5 @@ branches:
570
641
  default: "${e(defaultBranch)}"
571
642
  staging: "${e(stagingBranch)}"
572
643
  feature_pattern: "milestone/{slug}"
573
- `;
644
+ ${sandboxesProposalYaml(sandboxes)}`;
574
645
  }
package/bin/labels.json CHANGED
@@ -54,6 +54,11 @@
54
54
  "color": "0E8A16",
55
55
  "description": "Pipeline: PR merged, issue closed. Managed by ForgeDock."
56
56
  },
57
+ {
58
+ "name": "workflow:merged-unverified",
59
+ "color": "FBCA04",
60
+ "description": "Pipeline: PR merged but verification failed, needs a human decision. Managed by ForgeDock."
61
+ },
57
62
  {
58
63
  "name": "workflow:decomposed",
59
64
  "color": "BFD4F2",
@@ -61,7 +61,7 @@ export async function checkAdmission({ cfg = {}, host }) {
61
61
  * mem/tmp <= min / ratio). Orchestrate runs owned-resource GC before an admission when this is true. A failed or
62
62
  * non-finite probe never counts as near.
63
63
  */
64
- export async function nearCeiling({ cfg = {}, host, ratio = 0.8 } = {}) {
64
+ export async function nearCeiling({ cfg = {}, host, ratio = 0.8, minFreeGb = null } = {}) {
65
65
  const c = { ...ADMISSION_DEFAULTS, ...Object.fromEntries(Object.entries(cfg ?? {}).filter(([, v]) => v !== undefined && v !== null)) };
66
66
  if (c.enabled === false || !host) return false;
67
67
  const r = Number.isFinite(ratio) && ratio > 0 && ratio <= 1 ? ratio : 0.8;
@@ -69,6 +69,7 @@ export async function nearCeiling({ cfg = {}, host, ratio = 0.8 } = {}) {
69
69
  const maxLoad = typeof c.max_load_per_core === "number" && Number.isFinite(c.max_load_per_core) ? c.max_load_per_core : null; // off by default (#4169)
70
70
  const load = maxLoad === null ? null : await safe(host.loadAvg1), cores = maxLoad === null ? null : await safe(host.cores);
71
71
  if (load !== null && cores && load / cores >= r * maxLoad) return true;
72
+ if ((await diskLow({ host, minFreeGb: Number.isFinite(minFreeGb) && minFreeGb > 0 ? minFreeGb / r : null })).low) return true; // #5421
72
73
  const mem = await safe(host.memAvailableMb);
73
74
  if (mem !== null && mem <= c.min_free_mem_mb / r) return true;
74
75
  let paths = [];
@@ -76,3 +77,22 @@ export async function nearCeiling({ cfg = {}, host, ratio = 0.8 } = {}) {
76
77
  for (const p of paths) { const free = await safe(host.freeMb, p); if (free !== null && free <= c.min_free_tmp_mb / r) return true; }
77
78
  return false;
78
79
  }
80
+
81
+ /**
82
+ * Free-disk check (#5421): the filesystems holding the worktree root and `~/.forge` (`host.hygienePaths()`, else
83
+ * `host.tmpPaths()`) against `minFreeGb` (hygiene.min_free_gb). A failed probe never counts as low; null/0 is off.
84
+ * @returns {Promise<{low: boolean, reasons: string[]}>}
85
+ */
86
+ export async function diskLow({ host, minFreeGb = null } = {}) {
87
+ const min = Number(minFreeGb);
88
+ if (!host || !Number.isFinite(min) || min <= 0) return { low: false, reasons: [] };
89
+ let paths = [];
90
+ try { paths = (await (host.hygienePaths ?? host.tmpPaths)?.call(host)) ?? []; } catch { paths = []; }
91
+ const reasons = [];
92
+ for (const p of paths) {
93
+ let mb = null;
94
+ try { const v = await host.freeMb?.(p); mb = Number.isFinite(v) ? v : null; } catch { mb = null; }
95
+ if (mb !== null && mb / 1024 < min) reasons.push(`disk ${p} ${(mb / 1024).toFixed(1)} GB < ${min} GB`);
96
+ }
97
+ return { low: reasons.length > 0, reasons };
98
+ }
@@ -0,0 +1,43 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * #5448: blast-radius regression checks. `verify.baselines` (forge.yaml) declares suites that validate runs whenever a
5
+ * matching path changes; a contract `regression` set (existing tests of callers, shared modules, sibling configs) is
6
+ * folded into `validate` at freeze so the existing validate machinery runs it.
7
+ */
8
+ import { matchesGlob } from "./verify.mjs";
9
+
10
+ /** `[{when, run}]` or a `{glob: command}` map as `[{when, run}]`; entries missing either half are dropped. */
11
+ export function parseBaselines(v) {
12
+ const rows = Array.isArray(v) ? v : v && typeof v === "object" ? Object.entries(v).map(([when, run]) => ({ when, run })) : [];
13
+ const out = [];
14
+ for (const r of rows) {
15
+ const when = String(r?.when ?? "").trim(), run = String(r?.run ?? "").trim();
16
+ if (when && run) out.push({ when, run });
17
+ }
18
+ return out;
19
+ }
20
+
21
+ /** The baselines whose `when` glob matches at least one changed file, each command once. */
22
+ export function matchBaselines(changedFiles = [], baselines = []) {
23
+ const seen = new Set();
24
+ return baselines.filter((b) => !seen.has(b.run) && (changedFiles ?? []).some((f) => matchesGlob(f, b.when)) && seen.add(b.run));
25
+ }
26
+
27
+ /** Precheck failures (no `code`; precheck adds it) for baseline runs `[{when, run, rc, output}]` that did not exit 0. */
28
+ export function baselineFailures(runs = []) {
29
+ return (runs ?? []).filter((r) => r.rc !== 0).map((r) => ({ kind: "baseline_failed",
30
+ detail: `baseline suite \`${r.run}\` (declared for \`${r.when}\`) failed with exit ${r.rc}: ${String(r.output ?? "").trim().split("\n").slice(-8).join(" | ").slice(0, 400)}` }));
31
+ }
32
+
33
+ /** Fold `contract.regression` ([{id, command, covers}]) into `validate` as G# entries; an id or command already there is skipped. */
34
+ export function foldRegression(contract) {
35
+ const reg = Array.isArray(contract?.regression) ? contract.regression : [];
36
+ if (!reg.length) return contract;
37
+ const validate = Array.isArray(contract.validate) ? [...contract.validate] : [];
38
+ for (const g of reg) {
39
+ if (!g?.id || !g?.command || validate.some((v) => v?.id === g.id || v?.command === g.command)) continue;
40
+ validate.push({ id: g.id, command: g.command, regression: true });
41
+ }
42
+ return { ...contract, validate };
43
+ }
@@ -0,0 +1,33 @@
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 { parseBaselines, matchBaselines, baselineFailures, foldRegression } from "./baselines.mjs";
6
+ import { parseVerify } from "./verify.mjs";
7
+ import { precheck } from "./conformance.mjs";
8
+
9
+ describe("baselines (#5448)", () => {
10
+ it("parses the array and the map forms; parseVerify carries them", () => {
11
+ const want = [{ when: "shared/content/**", run: "make stealth-baseline" }];
12
+ assert.deepEqual(parseBaselines(want), want);
13
+ assert.deepEqual(parseBaselines({ "shared/content/**": "make stealth-baseline" }), want);
14
+ assert.deepEqual(parseVerify({ baselines: { "shared/content/**": "make stealth-baseline" } }).baselines, want);
15
+ assert.equal(parseVerify({}).baselines, undefined);
16
+ });
17
+ it("a shared-module change selects the baseline once; an unrelated change selects none", () => {
18
+ const b = parseBaselines({ "shared/content/**": "make stealth-baseline", "shared/**": "make stealth-baseline" });
19
+ assert.equal(matchBaselines(["shared/content/a.py", "shared/content/b.py"], b).length, 1);
20
+ assert.deepEqual(matchBaselines(["docs/readme.md"], b), []);
21
+ });
22
+ it("a failing baseline fails precheck as a regression; a passing one does not", () => {
23
+ const run = { when: "shared/**", run: "make stealth-baseline" };
24
+ const c = { requirements: [], deliverables: [], validate: [] };
25
+ const fail = precheck({ contract: c, result: {}, changedFiles: [], baselineFailures: baselineFailures([{ ...run, rc: 2, output: "vendor x red" }]) });
26
+ assert.ok(fail.failures.some((f) => f.kind === "baseline_failed" && /vendor x red/.test(f.detail)));
27
+ assert.equal(baselineFailures([{ ...run, rc: 0 }]).length, 0);
28
+ });
29
+ it("folds the regression set into validate once", () => {
30
+ const c = { validate: [{ id: "V1", command: "a" }], regression: [{ id: "G1", command: "b" }, { id: "G2", command: "a" }] };
31
+ assert.deepEqual(foldRegression(c).validate.map((v) => v.id), ["V1", "G1"]);
32
+ });
33
+ });
@@ -15,6 +15,8 @@ import { join } from "node:path";
15
15
  import { listBatches, openBatch, REQUEUABLE, writeAtomic } from "./batch.mjs";
16
16
 
17
17
  export const DEFAULT_HEALTH = Object.freeze({ rootFailed: true, terminalShare: 0.5, stalled: true, checksMin: Object.freeze([15, 60]), issue: null, notifyCommand: null });
18
+ /** #5469: a hold older than this many hours is flagged (`config.holdHours` overrides). */
19
+ export const DEFAULT_HOLD_HOURS = 4;
18
20
  /** Outcomes that end a row well: never counted against the batch. */
19
21
  export const GOOD_END = new Set(["merged", "invalid", "decomposed"]);
20
22
  export const REFUSALS_FILE = "refusals.json";
@@ -48,7 +50,7 @@ export function rootsOf(state) {
48
50
  * stall); `refused`: a refusal record (the launch never started); `resolved` (#5243): issues already
49
51
  * resolved on GitHub (merged by hand), counted as good ends. Pure.
50
52
  */
51
- export function evaluateHealth(state, { held = [], refused = null, config = DEFAULT_HEALTH, batchId = "<id>", repo = null, resolved = [] } = {}) {
53
+ export function evaluateHealth(state, { held = [], refused = null, config = DEFAULT_HEALTH, batchId = "<id>", repo = null, resolved = [], stateless = [], holdInfo = null, now = Date.now() } = {}) {
52
54
  const causes = [], recovery = [];
53
55
  if (refused) {
54
56
  causes.push({ code: "refused", issues: refused.issues ?? [], detail: refused.message ?? "launch refused" });
@@ -78,8 +80,14 @@ export function evaluateHealth(state, { held = [], refused = null, config = DEFA
78
80
  if (config.stalled && !running.size && waiting.length && state?.phase !== "setup" && !state?.cancelled) {
79
81
  causes.push({ code: "stalled", issues: waiting, detail: `0 lanes running while ${waiting.length} issue${waiting.length === 1 ? "" : "s"} pending${state?.breaker ? " (breaker tripped)" : ""}` });
80
82
  }
83
+ // #5466: a finished lane with a needs-human comment but no state label looks untouched to a person and to issue-watch.
84
+ if (stateless.length) causes.push({ code: "stateless", issues: stateless, detail: `${stateless.map((n) => `#${n}`).join(", ")}: needs-human comment but no state label; re-add needs-human (or /recover-orphans)` });
85
+ // #5469: a hold older than `holdHours` is flagged (hold-info records its owner and since); the legacy plain hold has no age
86
+ const holdHours = Number(config.holdHours) > 0 ? Number(config.holdHours) : DEFAULT_HOLD_HOURS, holdMs = holdHours * 3600000;
87
+ const stale = Object.entries(holdInfo ?? {}).filter(([n, e]) => heldSet.has(Number(n)) && Date.parse(e?.since) <= now - holdMs);
88
+ if (stale.length) causes.push({ code: "stale-hold", issues: stale.map(([n]) => Number(n)), detail: `held by operator for over ${holdHours}h: ${stale.slice(0, 6).map(([n, e]) => `#${n} (${e.owner}, since ${e.since})`).join(", ")}; forgedock orchestrate --release ${batchId} <issue...>` });
81
89
  if (!causes.length) return { healthy: true, causes, recovery };
82
- const failed = [...new Set(causes.filter((c) => c.code !== "stalled").flatMap((c) => c.issues))];
90
+ const failed = [...new Set(causes.filter((c) => c.code !== "stalled" && c.code !== "stale-hold" && c.code !== "stateless").flatMap((c) => c.issues))];
83
91
  const requeue = failed.filter((n) => REQUEUABLE(outcomeOf(n))), relaunch = failed.filter((n) => !REQUEUABLE(outcomeOf(n)));
84
92
  if (requeue.length) recovery.push(`forgedock orchestrate --requeue ${batchId} ${requeue.join(" ")} --reason "batch unhealthy"`);
85
93
  if (relaunch.length) recovery.push(`forgedock orchestrate ${relaunch.join(" ")}${repo ? ` --repo ${repo}` : ""} # after fixing the cause (see lanes/<n>.log)`);
@@ -111,7 +119,7 @@ export function scheduleLine(batchId, created, checksMin = DEFAULT_HEALTH.checks
111
119
  * One checkpoint: evaluate the batch, persist it, and call `alert(text, health)` on the first unhealthy result only.
112
120
  * @returns the evaluation, plus `alerted` when this call raised the alert
113
121
  */
114
- export async function runCheck({ batch, checkpoint, config = DEFAULT_HEALTH, repo = null, now = () => Date.now(), alert = async () => {}, resolve = null }) {
122
+ export async function runCheck({ batch, checkpoint, config = DEFAULT_HEALTH, repo = null, now = () => Date.now(), alert = async () => {}, resolve = null, statelessOf = null }) {
115
123
  const state = batch.store.load() ?? {};
116
124
  let held = [];
117
125
  try { held = batch.readHeld?.() ?? []; } catch { held = []; }
@@ -122,7 +130,11 @@ export async function runCheck({ batch, checkpoint, config = DEFAULT_HEALTH, rep
122
130
  const cand = (state.order ?? []).map(Number).filter((n) => res[n]?.outcome !== undefined && !GOOD_END.has(res[n].outcome) && !run.has(n)).map((n) => ({ issue: n, outcome: res[n].outcome }));
123
131
  try { if (cand.length) resolved = (await resolve(cand) ?? []).map(Number); } catch { resolved = []; }
124
132
  }
125
- const health = evaluateHealth(state, { held, config, batchId: batch.id, repo, resolved });
133
+ let stateless = [];
134
+ try { if (statelessOf) stateless = (await statelessOf(state) ?? []).map(Number); } catch { stateless = []; }
135
+ let holdInfo = null;
136
+ try { holdInfo = batch.readHoldInfo?.() ?? null; } catch { holdInfo = null; }
137
+ const health = evaluateHealth(state, { held, config, batchId: batch.id, repo, resolved, stateless, holdInfo, now: now() });
126
138
  const prev = readHealth(batch.dir) ?? {};
127
139
  const at = new Date(now()).toISOString();
128
140
  const next = { ...prev, checks: { ...(prev.checks ?? {}), [checkpoint]: at }, last: { at, checkpoint, healthy: health.healthy, ...(resolved.length ? { resolved } : {}), causes: health.causes, recovery: health.recovery } };
@@ -227,6 +239,31 @@ export function statusLines(root, { now = Date.now(), batch = null } = {}) {
227
239
  return out;
228
240
  }
229
241
 
242
+ /**
243
+ * #5466: open issues that carry a FORGE:NEEDS_HUMAN comment but no state label (needs-human, parked:*, remediation-queue,
244
+ * workflow:*): they look untouched to a person and to issue-watch. `issues` is `[{number, state, labels: [name], comments: [body]}]`.
245
+ * @returns issue numbers
246
+ */
247
+ export function statelessNeedsHuman(issues) {
248
+ const stateLabel = (l) => l === "needs-human" || l.startsWith("needs-human:") || l.startsWith("parked:") || l === "remediation-queue" || l.startsWith("workflow:");
249
+ return (issues ?? []).filter((i) => String(i?.state ?? "OPEN").toUpperCase() === "OPEN"
250
+ && (i.comments ?? []).some((c) => String(c).includes("<!-- FORGE:NEEDS_HUMAN"))
251
+ && !(i.labels ?? []).some((l) => stateLabel(String(l)))).map((i) => i.number);
252
+ }
253
+
254
+ /** #5466: the batch's open issues that GitHub shows stateless (see `statelessNeedsHuman`). A read failure skips the issue. */
255
+ export async function statelessOnGithub(state, gh, repo) {
256
+ const run = new Set(Object.keys(state?.running ?? {}).map(Number));
257
+ const rows = [];
258
+ for (const n of (state?.order ?? []).map(Number).filter((x) => !run.has(x))) {
259
+ try {
260
+ const v = JSON.parse(await gh(["issue", "view", String(n), "-R", repo, "--json", "number,state,labels,comments"]));
261
+ rows.push({ number: n, state: v.state, labels: (v.labels ?? []).map((l) => l.name), comments: (v.comments ?? []).map((c) => c.body) });
262
+ } catch { /* unreadable: not flagged */ }
263
+ }
264
+ return statelessNeedsHuman(rows);
265
+ }
266
+
230
267
  /**
231
268
  * #5243: which `[{issue, outcome}]` rows GitHub shows as resolved: the issue is CLOSED with a MERGED closing PR, or a
232
269
  * `needs-human` row whose label was removed with a `FORGE:DECISION` comment. Any read failure leaves the row unresolved.
@@ -279,11 +316,11 @@ export const readFirstHour = (dir) => readJson(join(dir, FIRST_HOUR_FILE));
279
316
  export const appendBatchLog = (dir, text) => { try { appendFileSync(join(dir, BATCH_LOG_FILE), `${text}\n`, { mode: 0o600 }); } catch { /* advisory */ } };
280
317
 
281
318
  /** The first-hour report of one batch: dispatched / running / merged / stuck, and why. Pure. */
282
- export function firstHourReport(state, { batchId, now = Date.now(), held = [], stall = null } = {}) {
319
+ export function firstHourReport(state, { batchId, now = Date.now(), held = [], stall = null, holdInfo = null } = {}) {
283
320
  const order = (state?.order ?? []).map(Number), results = state?.results ?? {}, running = Object.keys(state?.running ?? {}).map(Number);
284
321
  const merged = order.filter((n) => GOOD_END.has(results[n]?.outcome)), heldSet = new Set(held.map(Number));
285
322
  const stuck = order.filter((n) => !running.includes(n) && !GOOD_END.has(results[n]?.outcome) && (results[n] !== undefined || (state?.pending ?? []).map(Number).includes(n)));
286
- const why = (n) => results[n]?.outcome ? `#${n} ${results[n].outcome}` : heldSet.has(n) ? `#${n} held` : Number(state?.notBefore?.[n]) > now ? `#${n} waiting on a retry` : `#${n} pending`;
323
+ const why = (n) => results[n]?.outcome ? `#${n} ${results[n].outcome}` : heldSet.has(n) ? `#${n} held${holdInfo?.[n] ? ` (${holdInfo[n].owner}, since ${holdInfo[n].since})` : ""}` : Number(state?.notBefore?.[n]) > now ? `#${n} waiting on a retry` : `#${n} pending`;
287
324
  const dispatched = order.filter((n) => results[n] !== undefined || running.includes(n)).length;
288
325
  const counts = { total: order.length, dispatched, running: running.length, merged: merged.length, stuck: stuck.length };
289
326
  const reasons = [...stuck.map(why), ...(stall ? [stall.detail] : [])];