forgedock 1.54.0 → 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 (114) hide show
  1. package/bin/auth/app-token.mjs +2 -0
  2. package/bin/auth/app-token.test.mjs +9 -1
  3. package/bin/engine/events.mjs +1 -0
  4. package/bin/engine/events.test.mjs +5 -1
  5. package/bin/engine/outcome-codes.mjs +3 -0
  6. package/bin/engine-cli.mjs +126 -34
  7. package/bin/forgedock.mjs +56 -4
  8. package/bin/gc-schedule.mjs +83 -0
  9. package/bin/gc.mjs +56 -8
  10. package/bin/help-text.mjs +1 -1
  11. package/bin/hooks/pre-tool-use.mjs +1 -0
  12. package/bin/init-detect.mjs +73 -2
  13. package/bin/labels.json +5 -0
  14. package/bin/lean/admission.mjs +21 -1
  15. package/bin/lean/baselines.mjs +43 -0
  16. package/bin/lean/baselines.test.mjs +33 -0
  17. package/bin/lean/batch-health.mjs +43 -6
  18. package/bin/lean/batch-health.test.mjs +41 -1
  19. package/bin/lean/batch.mjs +41 -4
  20. package/bin/lean/batch.test.mjs +106 -3
  21. package/bin/lean/conformance.mjs +131 -12
  22. package/bin/lean/conformance.test.mjs +172 -3
  23. package/bin/lean/depcache.mjs +23 -2
  24. package/bin/lean/depcache.test.mjs +22 -0
  25. package/bin/lean/docsgate.mjs +137 -0
  26. package/bin/lean/docsgate.test.mjs +78 -0
  27. package/bin/lean/effects.mjs +31 -2
  28. package/bin/lean/enumerating.mjs +39 -13
  29. package/bin/lean/enumerating.test.mjs +20 -0
  30. package/bin/lean/execution.test.mjs +3 -3
  31. package/bin/lean/fastforward.mjs +93 -0
  32. package/bin/lean/fastforward.test.mjs +73 -0
  33. package/bin/lean/guardgate.mjs +38 -7
  34. package/bin/lean/guardgate.test.mjs +39 -0
  35. package/bin/lean/issuewatch-install.mjs +92 -0
  36. package/bin/lean/issuewatch-install.test.mjs +31 -0
  37. package/bin/lean/issuewatch-parity.mjs +33 -3
  38. package/bin/lean/issuewatch-parity.test.mjs +30 -5
  39. package/bin/lean/issuewatch-reconcile.mjs +123 -0
  40. package/bin/lean/issuewatch-reconcile.test.mjs +30 -0
  41. package/bin/lean/issuewatch-verify.mjs +51 -9
  42. package/bin/lean/issuewatch.mjs +153 -33
  43. package/bin/lean/issuewatch.test.mjs +243 -22
  44. package/bin/lean/lean.mjs +381 -75
  45. package/bin/lean/lean.test.mjs +437 -20
  46. package/bin/lean/light.mjs +11 -3
  47. package/bin/lean/light.test.mjs +27 -0
  48. package/bin/lean/lightlane.mjs +8 -3
  49. package/bin/lean/lightlane.test.mjs +20 -0
  50. package/bin/lean/mechfix.mjs +35 -4
  51. package/bin/lean/mechfix.test.mjs +48 -1
  52. package/bin/lean/orchestrate-children.test.mjs +10 -0
  53. package/bin/lean/orchestrate-owned.test.mjs +73 -0
  54. package/bin/lean/orchestrate.mjs +28 -4
  55. package/bin/lean/overlap.mjs +20 -0
  56. package/bin/lean/overlap.test.mjs +49 -0
  57. package/bin/lean/pagegate.mjs +152 -0
  58. package/bin/lean/pagegate.test.mjs +77 -0
  59. package/bin/lean/parked-relabel.mjs +32 -0
  60. package/bin/lean/parked-relabel.test.mjs +45 -0
  61. package/bin/lean/phaseledger.mjs +17 -2
  62. package/bin/lean/postdeploy-check.mjs +27 -0
  63. package/bin/lean/postdeploy-check.test.mjs +13 -1
  64. package/bin/lean/postrun.mjs +32 -0
  65. package/bin/lean/postrun.test.mjs +41 -0
  66. package/bin/lean/preflight.mjs +46 -0
  67. package/bin/lean/preflight.test.mjs +30 -1
  68. package/bin/lean/prompts.mjs +36 -6
  69. package/bin/lean/recovery.test.mjs +16 -0
  70. package/bin/lean/release.mjs +30 -3
  71. package/bin/lean/release.test.mjs +36 -0
  72. package/bin/lean/render.mjs +17 -6
  73. package/bin/lean/reproquality.mjs +116 -0
  74. package/bin/lean/reproquality.test.mjs +85 -0
  75. package/bin/lean/review-trigger.mjs +8 -3
  76. package/bin/lean/sandbox-budget.test.mjs +27 -0
  77. package/bin/lean/schedd.mjs +40 -11
  78. package/bin/lean/schedd.test.mjs +12 -1
  79. package/bin/lean/testadequacy.mjs +97 -0
  80. package/bin/lean/testadequacy.test.mjs +92 -0
  81. package/bin/lean/testsandbox.mjs +202 -0
  82. package/bin/lean/testsandbox.test.mjs +157 -0
  83. package/bin/lean/toolplace.mjs +5 -2
  84. package/bin/lean/toolplace.test.mjs +6 -0
  85. package/bin/lean/verify.mjs +6 -1
  86. package/bin/lean/verify.test.mjs +18 -2
  87. package/bin/lean/warmtree.mjs +77 -0
  88. package/bin/lean/warmtree.test.mjs +81 -0
  89. package/bin/runner.mjs +6 -1
  90. package/bin/stats/conformance-outcomes.mjs +12 -2
  91. package/bin/stats/depth.mjs +24 -1
  92. package/bin/stats/depth.test.mjs +21 -1
  93. package/bin/stats/index.mjs +5 -2
  94. package/bin/stats/query.mjs +2 -1
  95. package/commands/cleanup.md +18 -0
  96. package/commands/fd-introspect.md +19 -0
  97. package/commands/milestone.md +5 -1
  98. package/commands/pipeline-health/phase-2-metrics.md +4 -0
  99. package/commands/recover-orphans.md +31 -1
  100. package/commands/review-pr-staging.md +9 -0
  101. package/commands/review-pr.md +2 -0
  102. package/docs/CI.md +1 -1
  103. package/docs/CONFIG.md +26 -1
  104. package/docs/EVENTS.md +1 -0
  105. package/docs/ISSUE-WATCH.md +12 -3
  106. package/docs/eval/adversarial-bench.md +1 -1
  107. package/docs/eval/published/adversarial-2026-11-11.md +58 -0
  108. package/package.json +1 -1
  109. package/scripts/bench-lightlane.mjs +3 -2
  110. package/scripts/hotspots.sh +7 -4
  111. package/scripts/hotspots.test.sh +12 -0
  112. package/scripts/recover-orphans-stateless.test.sh +79 -0
  113. package/scripts/transition-label.sh +2 -0
  114. package/templates/workflows/forgedock-reopen-clean.yml +33 -0
@@ -17,23 +17,26 @@ import { fileURLToPath } from "node:url";
17
17
  import { writeAtomic, batchRoot, openBatch, listBatches } from "./batch.mjs";
18
18
  import { milestoneSlug, readBranches, isDefaultLane, defaultBranches, DEFAULT_STAGING_BRANCH, DEFAULT_FEATURE_PATTERN } from "./lane.mjs";
19
19
  import { postDeployOnly } from "./prefilter.mjs";
20
+ import { designHold } from "./pagegate.mjs"; // #5442
20
21
  import { releaseTick, formatDryRun } from "./issuewatch-release.mjs";
21
22
  import { releaseRoot } from "./release.mjs";
22
23
  import { loadPolicy } from "./decision-engine.mjs";
23
24
  import { decisionContext, decisionsActive, decisionStep, decisionCounts, formatDecisionDryRun, claimsUsed } from "./issuewatch-decisions.mjs";
25
+ import { reconcileClaims, remediateStep, reclaimStep, claimCounts, stuckClaims, formatStuck } from "./issuewatch-reconcile.mjs";
24
26
  import { APP_SLUG } from "../init-repo.mjs";
25
27
  import { noComments } from "./render.mjs";
26
28
  import { listAssociations } from "./gh-assoc.mjs";
27
29
  import { verifyMerge, verifyComment } from "./issuewatch-verify.mjs";
28
- import { DEFAULT_SKIP_LABELS, isPullRequest, searchesPullRequests, skipLabelHit, closingPrIssues, releaseInFlight, watchLiveness } from "./issuewatch-parity.mjs";
30
+ import { DEFAULT_SKIP_LABELS, isPullRequest, searchesPullRequests, skipLabelHit, closingPrIssues, releaseInFlight, watchLiveness, alertDeadWatches } from "./issuewatch-parity.mjs";
29
31
 
30
- const WATCH_KEYS = ["milestone", "labels", "exclude_labels", "search", "title_regex", "since", "version", "lane", "max_issues", "max_inflight", "until", "mode", "parallel", "include_followups", "postdeploy_rollup", "threshold", "immediate", "max_release_issues", "theme_map", "tracker", "sweep_needs_human", "max_launches", "trust_app", "trust_app_labels", "skip_labels", "release_pause"];
32
+ const WATCH_KEYS = ["milestone", "labels", "exclude_labels", "search", "title_regex", "since", "version", "lane", "max_issues", "max_inflight", "until", "mode", "parallel", "include_followups", "postdeploy_rollup", "threshold", "immediate", "max_release_issues", "theme_map", "tracker", "sweep_needs_human", "max_launches", "trust_app", "trust_app_labels", "skip_labels", "release_pause", "max_remediations"];
31
33
  export const TRUSTED = new Set(["OWNER", "MEMBER", "COLLABORATOR"]);
32
34
  const NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
33
35
  const RETRIES = 3;
34
36
  const readFile = (f) => readFileSync(f, "utf8");
35
37
  const JUDGE_TIMEOUT_MS = 120_000; // a hung `claude --print` must not stall the watch round
36
38
  const CLAUDE_MAX_BUFFER = 8 * 1024 * 1024;
39
+ const PENDING_START_MS = 10 * 60000; // #5425: how long a slow `orchestrate` start may take to create its batch before the claims are released
37
40
  const VERIFY_WAIT_MS = 60 * 60000; // how long a merge commit's CI may stay pending before verification fails
38
41
  const readJson = (f) => { try { return JSON.parse(readFileSync(f, "utf8")); } catch { return null; } };
39
42
 
@@ -78,10 +81,12 @@ export function validateWatch(name, cfg = {}) {
78
81
  if (!Number.isInteger(n) || n < 1) throw new Error(`watch ${name}: ${k} must be a positive integer`);
79
82
  return n;
80
83
  };
84
+ const parallel = int("parallel", 4);
81
85
  const w = { name, milestone: cfg.milestone || null, labels: list(cfg.labels), exclude_labels: list(cfg.exclude_labels), search: cfg.search || null, title_regex: cfg.title_regex || null,
82
- since: cfg.since || null, version: cfg.version ? String(cfg.version) : null, lane: cfg.lane || null, max_issues: int("max_issues", null), max_inflight: int("max_inflight", 4),
83
- until: cfg.until || null, mode: cfg.mode || "per-issue", parallel: int("parallel", 4), include_followups: cfg.include_followups || "none", postdeploy_rollup: cfg.postdeploy_rollup ? Number(String(cfg.postdeploy_rollup).replace("#", "")) : null,
84
- max_launches: int("max_launches", null), sweep_needs_human: cfg.sweep_needs_human === true || String(cfg.sweep_needs_human).toLowerCase() === "true",
86
+ since: cfg.since || null, version: cfg.version ? String(cfg.version) : null, lane: cfg.lane || null, max_issues: int("max_issues", null), max_inflight: int("max_inflight", cfg.mode === "batch" ? parallel : 4), // #5425: a batch watch takes up to its K at once
87
+ until: cfg.until || null, mode: cfg.mode || "per-issue", parallel, include_followups: cfg.include_followups || "none", postdeploy_rollup: cfg.postdeploy_rollup ? Number(String(cfg.postdeploy_rollup).replace("#", "")) : null,
88
+ max_launches: int("max_launches", null), max_remediations: int("max_remediations", 10), // #5467: remediation lanes per watch
89
+ sweep_needs_human: cfg.sweep_needs_human === true || String(cfg.sweep_needs_human).toLowerCase() === "true",
85
90
  trust_app: cfg.trust_app === true || String(cfg.trust_app).toLowerCase() === "true", trust_app_labels: list(cfg.trust_app_labels),
86
91
  skip_labels: cfg.skip_labels === undefined ? (cfg.mode === "batch" ? DEFAULT_SKIP_LABELS : []) : list(cfg.skip_labels), // #5313: the bash watcher's skip list; batch watches take it by default
87
92
  release_pause: cfg.release_pause === undefined ? cfg.mode === "batch" : /^true$/i.test(String(cfg.release_pause)) };
@@ -146,9 +151,24 @@ export function selectorMiss(issue, sel) {
146
151
  return null;
147
152
  }
148
153
 
154
+ /**
155
+ * #5469: `Map<issue, PR number>` of open PRs to `repo` that close an issue from a head branch the pipeline did not use
156
+ * (anything but `feat/issue-<n>-lean`): the hand-built PRs `orchestrate --adopt` takes over. A failed read is an empty map.
157
+ */
158
+ export async function foreignClosingPrs(gh, repo) {
159
+ const out = new Map();
160
+ try {
161
+ for (const pr of JSON.parse(String(await gh(["pr", "list", "-R", repo, "--state", "open", "--limit", "200", "--json", "number,headRefName,closingIssuesReferences"]))) ?? [])
162
+ for (const r of pr.closingIssuesReferences ?? []) if (pr.headRefName && pr.headRefName !== `feat/issue-${r.number}-lean` && !out.has(r.number)) out.set(r.number, pr.number);
163
+ } catch { /* no adoption without a clean read */ }
164
+ return out;
165
+ }
166
+
149
167
  /** #5313: why the bash watcher's rules skip `issue` (a PR, a skip label, an open closing PR), or null. */
150
168
  export function parityMiss(issue, watch, closing = new Map()) {
151
169
  if (isPullRequest(issue)) return "pull request (a watch claims issues only)";
170
+ const dh = designHold(issue.labels); // #5442: page work waits for an approved design, whatever skip_labels says
171
+ if (dh) return `design_pending: ${dh} (run /design; design:approved lifts the hold)`;
152
172
  const l = skipLabelHit(issue, watch.skip_labels);
153
173
  if (l) return `skip label ${l}`;
154
174
  return closing.has(issue.number) ? `open closing PR #${closing.get(issue.number)}` : null;
@@ -282,6 +302,13 @@ async function verifyClosed({ n, repo, io, state, now, lane }) {
282
302
  const done = (state.escalation[n] ??= {});
283
303
  if (!done.comment) { await io.gh(["issue", "comment", String(n), "-R", repo, "--body", verifyComment(r, now)]); done.comment = true; }
284
304
  if (!done.label) { await io.gh(["issue", "edit", String(n), "-R", repo, "--add-label", "needs-human"]); done.label = true; }
305
+ // #5484: the merged -> merged-unverified swap is best effort and separate, so a repo without the label (or without the
306
+ // right to create it) still gets needs-human and the reopen. Create first (--force), as parked-relabel.mjs does.
307
+ if (!done.swap) {
308
+ try { await io.gh(["label", "create", "workflow:merged-unverified", "-R", repo, "--force", "--color", "FBCA04", "--description", "Pipeline: PR merged but verification failed, needs a human decision. Managed by ForgeDock."]); } catch { /* exists, or no rights: the edit says */ }
309
+ try { await io.gh(["issue", "edit", String(n), "-R", repo, "--add-label", "workflow:merged-unverified", "--remove-label", "workflow:merged"]); } catch { /* reopen-clean workflow strips workflow:merged where installed */ }
310
+ done.swap = true;
311
+ }
285
312
  await io.gh(["issue", "reopen", String(n), "-R", repo]);
286
313
  delete state.escalation[n];
287
314
  settled(); state.merged.push(n); state.unverified.push(n);
@@ -290,6 +317,20 @@ async function verifyClosed({ n, repo, io, state, now, lane }) {
290
317
  // ── the watch ────────────────────────────────────────────────────────────────────────────────────────────────
291
318
  const fresh = (watch, repo) => ({ name: watch.name, repo, phase: "running", started: null, claimed: [], inflight: [], merged: [], verified: [], unverified: [], closed: [], failed: [], folded: [], retries: {}, lanes: {}, batch: null, laneFor: {} });
292
319
 
320
+ /** #5425: drop `nums` from the repo-wide registry (under its lock) so a later pass or another watch can claim them again. */
321
+ export function releaseClaims(rdir, nums, name) {
322
+ const lock = join(rdir, "claims.lock");
323
+ mkdirSync(rdir, { recursive: true });
324
+ for (let i = 0; ; i++) {
325
+ try { mkdirSync(lock); break; } catch (e) { if (e.code !== "EEXIST" || i > 200) throw e; sleepSync(10); }
326
+ }
327
+ try {
328
+ const f = join(rdir, "claims.json"), claims = readJson(f) ?? {};
329
+ for (const n of nums) if (claims[n] === name) delete claims[n];
330
+ writeAtomic(f, JSON.stringify(claims) + "\n");
331
+ } finally { rmdirSync(lock); }
332
+ }
333
+
293
334
  /**
294
335
  * One pass. `io`: `gh(args)→string`, `now()→ms`, `launch(issue,lane)→{poll()→null|{code}}` (per-issue), `batch.{add(id,issues),start(issues,parallel,lane)→id,reported(id)→bool}` (batch mode).
295
336
  * Settles inflight issues, applies the caps, claims new ones. Mutates and returns `state`; `state.phase === "done"` when a capped watch has drained.
@@ -306,10 +347,11 @@ export async function tick({ watch, repo, io, state, dir, branches = {}, default
306
347
  for (const k of ["unverified", "closed"]) state[k] ??= [];
307
348
  const verify = (n) => verifyClosed({ n, repo, io, state, now, lane: state.lanes[n] ?? branches.staging ?? DEFAULT_STAGING_BRANCH });
308
349
 
350
+ if (watch.mode === "batch" && state.batch) reconcileClaims({ state, results: io.batch.results?.(state.batch), now, fail, settle }); // #5467: a final batch result leaves inflight now, not when the batch reports
309
351
  for (const n of [...state.inflight]) {
310
352
  if (watch.mode === "batch") { if (await closed(n)) settle(n); continue; }
311
353
  const h = handles.get(n);
312
- if (!h) { handles.set(n, io.launch(n, state.lanes[n])); continue; } // a restarted watch re-launches (run-issue resumes from GitHub)
354
+ if (!h) { handles.set(n, state.adopt?.[n] ? io.launch(n, state.lanes[n], { adopt: true }) : io.launch(n, state.lanes[n])); continue; } // a restarted watch re-launches (run-issue resumes from GitHub)
313
355
  const r = h.poll();
314
356
  if (!r) continue;
315
357
  handles.delete(n);
@@ -317,15 +359,30 @@ export async function tick({ watch, repo, io, state, dir, branches = {}, default
317
359
  else if (r.code === 75 && (state.retries[n] = (state.retries[n] ?? 0) + 1) <= RETRIES) handles.set(n, io.launch(n, state.lanes[n]));
318
360
  else fail(n);
319
361
  }
362
+ if (watch.mode === "batch") {
363
+ await remediateStep({ watch, repo, io, state, handles, now, settle, fail });
364
+ await reclaimStep({ repo, io, state, trusted: (c) => TRUSTED.has(c?.authorAssociation), release: (n) => { releaseClaims(repoDir(repo, io.env), [n], watch.name); state.claimed = state.claimed.filter((x) => x !== n); delete state.lanes[n]; unsettle(state, n); } });
365
+ }
320
366
  for (const n of [...(state.pendingVerify ?? [])]) if (await closed(n)) await verify(n);
321
367
  if (watch.mode === "batch" && state.batch && io.batch.reported(state.batch)) { state.inflight.forEach(fail); state.batch = null; }
322
368
 
369
+ if (watch.mode === "batch" && state.pendingStart) { // #5425: a slow `orchestrate` start: adopt its batch when it shows up, else release the claims after a while
370
+ const ps = state.pendingStart, id = io.batch.find?.(ps.before ?? []);
371
+ if (id) { state.batch = id; state.pendingStart = null; }
372
+ else if (now - ps.at > PENDING_START_MS) {
373
+ releaseClaims(repoDir(repo, io.env), ps.issues, watch.name);
374
+ state.claimed = state.claimed.filter((n) => !ps.issues.includes(n)); state.inflight = state.inflight.filter((n) => !ps.issues.includes(n));
375
+ for (const n of ps.issues) delete state.lanes[n];
376
+ state.pendingStart = null;
377
+ }
378
+ }
379
+
323
380
  const used = claimsUsed(state); // the decision stage (#4793) draws on the same caps
324
381
  const capped = (watch.max_issues && used.issues >= watch.max_issues) || (watch.max_launches && used.launches >= watch.max_launches) || (watch.until && now >= Date.parse(watch.until));
325
382
  if (capped && state.phase === "running") state.phase = "draining";
326
- if (state.phase === "draining") { if (!state.inflight.length && !Object.keys(state.verifyFrom ?? {}).length) state.phase = "done"; return state; } // a merge mid-verification holds the drain
383
+ if (state.phase === "draining") { if (!state.inflight.length && !Object.keys(state.verifyFrom ?? {}).length && !Object.values(state.remediated ?? {}).some((r) => r.status === "running")) state.phase = "done"; return state; } // a merge mid-verification holds the drain
327
384
 
328
- const room = roomFor(watch, state);
385
+ const room = state.pendingStart ? 0 : roomFor(watch, state); // a pending start holds new claims
329
386
  const plan = await planClaims({ watch, repo, io, state, branches, defaults, room });
330
387
  for (const i of plan.folds) await fold({ issue: i, watch, repo, io, state });
331
388
  const taken = [];
@@ -333,13 +390,22 @@ export async function tick({ watch, repo, io, state, dir, branches = {}, default
333
390
  if (taken.length >= room) break;
334
391
  const lane = laneFor(i, watch, { branches, defaults });
335
392
  if (!claimIssue(repoDir(repo, io.env), i.number, watch.name)) continue;
336
- state.claimed.push(i.number); state.inflight.push(i.number); state.lanes[i.number] = lane; taken.push({ n: i.number, lane });
393
+ state.claimed.push(i.number); (state.claimedAt ??= {})[i.number] = now; state.inflight.push(i.number); state.lanes[i.number] = lane; taken.push({ n: i.number, lane });
337
394
  }
338
395
  if (taken.length && watch.mode === "batch") {
339
396
  const nums = taken.map((t) => t.n);
340
397
  if (state.batch && io.batch.reported(state.batch)) { state.inflight.filter((n) => !nums.includes(n)).forEach(fail); state.batch = null; } // #5313: it reported since the check above; never add to a finished batch
341
- if (state.batch) io.batch.add(state.batch, nums); else state.batch = await io.batch.start(nums, watch.parallel, taken[0].lane);
342
- } else for (const t of taken) handles.set(t.n, io.launch(t.n, t.lane));
398
+ state.batch ??= io.batch.running?.(taken[0].lane) ?? null; // #5425: another running batch of this repo and lane takes the claims
399
+ if (state.batch) io.batch.add(state.batch, nums);
400
+ else {
401
+ try { state.batch = await io.batch.start(nums, watch.parallel, taken[0].lane); } catch (e) { // #5425: the claims are kept; a later pass adopts the batch or releases them
402
+ state.pendingStart = { issues: nums, at: now, before: e?.before ?? [], error: String(e?.message ?? e).slice(0, 200) };
403
+ }
404
+ }
405
+ } else for (const t of taken) {
406
+ if (plan.adopt?.has(t.n)) { (state.adopt ??= {})[t.n] = true; handles.set(t.n, io.launch(t.n, t.lane, { adopt: true })); } // #5469
407
+ else handles.set(t.n, io.launch(t.n, t.lane));
408
+ }
343
409
  return state;
344
410
  }
345
411
 
@@ -356,10 +422,14 @@ export async function planClaims({ watch, repo, io, state, branches = {}, defaul
356
422
  const found = [], folds = [], skip = [], why = new Map();
357
423
  const assoc = await listAssociations(io.gh, repo); // #4859: not a `gh issue list` field
358
424
  const closing = await closingPrIssues(io.gh, repo); // #5313
425
+ const foreign = watch.mode === "batch" || !closing.size ? new Map() : await foreignClosingPrs(io.gh, repo); // #5469: a hand-built PR is adopted, not skipped
426
+ const adopt = new Set();
359
427
  for (const raw of JSON.parse(String(await io.gh(args)))) {
360
428
  const i = { ...raw, authorAssociation: assoc.get(raw.number) };
361
- const parity = parityMiss(i, watch, closing);
429
+ const adoptable = foreign.has(i.number) && closing.get(i.number) === foreign.get(i.number);
430
+ const parity = parityMiss(i, watch, adoptable ? new Map() : closing);
362
431
  if (parity) { skip.push({ number: i.number, reason: parity }); continue; }
432
+ if (adoptable) adopt.add(i.number);
363
433
  const miss = selectorMiss(i, watch);
364
434
  if (miss) { skip.push({ number: i.number, reason: miss }); continue; }
365
435
  const c = classifyWhy(i, watch);
@@ -377,9 +447,9 @@ export async function planClaims({ watch, repo, io, state, branches = {}, defaul
377
447
  let lane;
378
448
  try { lane = laneFor(i, watch, { branches, defaults }); } catch (e) { skip.push({ number: i.number, reason: String(e?.message ?? e) }); continue; }
379
449
  if (claim.length >= room) { skip.push({ number: i.number, reason: `over capacity (room ${Math.max(0, room)})` }); continue; }
380
- claim.push({ number: i.number, lane, reason: why.get(i.number) });
450
+ claim.push({ number: i.number, lane, reason: why.get(i.number), ...(adopt.has(i.number) ? { adopt: true } : {}) });
381
451
  }
382
- return { candidates, claim, fold: folds.map((i) => i.number), folds, skip };
452
+ return { candidates, claim, adopt, fold: folds.map((i) => i.number), folds, skip };
383
453
  }
384
454
 
385
455
  /** The per-issue/batch `--dry-run` lines of a planClaims result. */
@@ -425,10 +495,13 @@ async function fold({ issue, watch, repo, io, state }) {
425
495
  export function formatStatus(s, watch, now = Date.now()) {
426
496
  const sel = ["milestone", "labels", "exclude_labels", "search", "title_regex", "since", "version", "lane"].filter((k) => (Array.isArray(watch[k]) ? watch[k].length : watch[k])).map((k) => `${k}=${[].concat(watch[k]).join(",")}`).join(" ") || "(all trusted issues)";
427
497
  const left = watch.until ? `${Math.max(0, Math.round((Date.parse(watch.until) - now) / 60000))}m` : "forever";
428
- const live = s.heartbeat || s.paused ? watchLiveness(s, now) : null;
429
- return [`watch ${s.name} (${s.repo}) [${s.phase}, ${watch.mode}]`, ...(live ? [` state: ${live.state}${live.state === "paused" || live.state === "stale" ? ` (${live.reason})` : ""} last heartbeat: ${s.heartbeat ?? "never"}${live.ageMs != null ? ` (${Math.round(live.ageMs / 1000)}s ago)` : ""}`] : []), ` selector: ${sel}`,
498
+ const live = s.heartbeat || s.paused || s.phase === "exited" ? watchLiveness(s, now) : null;
499
+ return [`watch ${s.name} (${s.repo}) [${s.phase}, ${watch.mode}]`, ...(live ? [` state: ${live.state === "dead" ? "DEAD" : live.state}${["paused", "dead", "exited"].includes(live.state) ? ` (${live.reason})` : ""} last heartbeat: ${s.heartbeat ?? "never"}${live.ageMs != null ? ` (${Math.round(live.ageMs / 1000)}s ago)` : ""}`] : []), ` selector: ${sel}`,
500
+ ` reconciled: ${Object.entries(claimCounts(s)).map(([k, v]) => `${k} ${v}`).join(" ")}`,
430
501
  ` claims: ${s.claimed.length}/${watch.max_issues ?? "∞"} inflight: ${s.inflight.length} merged: ${s.merged.length} verified: ${s.verified.length} unverified: ${(s.unverified ?? []).length} closed unmerged: ${(s.closed ?? []).length} failed: ${s.failed.length}`, ` time remaining: ${left}`,
431
502
  ...(s.decisions ? [(({ decided, evidence, folded, external_kept: kept }) => ` needs-human decisions: decided ${decided} evidence-gathered ${evidence} folded ${folded} external-kept ${kept}`)(decisionCounts(s))] : []),
503
+ ...(s.passError ? [` last pass failed: ${s.passError}`] : []), // #5425
504
+ ...(s.pendingStart ? [` batch start pending for ${s.pendingStart.issues.length} claim(s) since ${new Date(s.pendingStart.at).toISOString()}: ${s.pendingStart.error}`] : []),
432
505
  ...(s.decisionError ? [` needs-human decisions: last round failed: ${s.decisionError}`] : []), // release #5068 CQ-1
433
506
  ...(watch.mode === "release" ? [` pool: ${(s.pool ?? []).length} releases: ${(s.releases ?? []).length + (s.release ? 1 : 0)}${s.release ? ` active: ${s.release.theme} (${s.release.issues.length} issues, batch ${s.release.batch})` : ""} llm-classified: ${s.llm ?? 0}`] : [])].join("\n");
434
507
  }
@@ -463,16 +536,25 @@ export function decisionLaunch({ i, watch, repo, io, state, handles, branches, d
463
536
  }
464
537
 
465
538
  /** Run until done (capped) or `once`; writes status.json each pass. */
466
- export async function runWatch({ watch, repo, io, dir, branches, defaults, once = false, intervalMs = 300000, release = () => {}, cwd }) {
539
+ export async function runWatch({ watch, repo, io, dir, branches, defaults, once = false, intervalMs = 300000, release = () => {}, cwd, signals = false }) {
467
540
  const state = readJson(join(dir, "status.json")) ?? fresh(watch, repo);
541
+ if (state.phase === "exited") { state.phase = "running"; delete state.exitReason; delete state.exitedAt; } // a supervised restart resumes the watch
468
542
  const handles = new Map();
469
543
  const ctx = decisionContext({ loadPolicy, readFile, cwd: cwd ?? process.cwd() });
470
544
  const shared = { matches: matchesSelectors, fold, labelNames, isBot, TRUSTED };
471
545
  const launch = (i) => decisionLaunch({ i, watch, repo, io, state, handles, branches, defaults });
546
+ // #5465: whatever ends the process, status.json says so instead of staying `running` with a dying heartbeat
547
+ const markExit = (reason) => {
548
+ if (state.phase === "done") return;
549
+ state.phase = "exited"; state.exitReason = String(reason).slice(0, 200); state.exitedAt = new Date(io.now()).toISOString();
550
+ try { writeAtomic(join(dir, "status.json"), JSON.stringify(state) + "\n"); } catch { /* the heartbeat goes stale and status shows DEAD */ }
551
+ };
552
+ const onSignal = (sig) => { markExit(`stopped by ${sig}`); release(); process.exit(0); };
553
+ if (signals) for (const sig of ["SIGTERM", "SIGINT"]) process.once(sig, () => onSignal(sig));
472
554
  try {
473
555
  do {
474
556
  state.heartbeat = new Date(io.now()).toISOString(); state.heartbeatEveryMs = intervalMs; // #5313: liveness lives in the state, not a process grep
475
- const rel = watch.release_pause && state.phase === "running" ? (io.releaseInFlight ?? releaseInFlight)({ root: releaseRoot(io.env), repo, now: io.now() }) : null;
557
+ let rel = null; try { rel = watch.release_pause && state.phase === "running" ? (io.releaseInFlight ?? releaseInFlight)({ root: releaseRoot(io.env), repo, now: io.now() }) : null; } catch { /* unreadable release state: not paused */ }
476
558
  if (rel) { // a release job holds staging: no claims, retries or decisions until it ends; the next pass resumes by itself
477
559
  state.paused = { reason: `release ${rel.id} in flight${rel.step ? ` (${rel.step})` : ""}`, release: rel.id, since: state.paused?.since ?? state.heartbeat };
478
560
  writeAtomic(join(dir, "status.json"), JSON.stringify(state) + "\n");
@@ -483,12 +565,21 @@ export async function runWatch({ watch, repo, io, dir, branches, defaults, once
483
565
  if (state.phase === "running" && decisionsActive(watch, ctx.policy)) { // #4793: a failed round must not stop the watch
484
566
  try { await decisionStep({ watch, repo, io, state, ctx, shared, launch }); state.decisionError = null; } catch (e) { state.decisionError = String(e?.message ?? e).slice(0, 200); }
485
567
  }
486
- if (watch.mode === "release") await releaseStep({ watch, repo, io, state, dir, branches, defaults, cwd }); else await tick({ watch, repo, io, state, dir, branches, defaults, handles });
568
+ let passErr = null;
569
+ try { // #5425: an error in one pass is recorded and shown by `status`; the next pass runs
570
+ if (watch.mode === "release") await releaseStep({ watch, repo, io, state, dir, branches, defaults, cwd }); else await tick({ watch, repo, io, state, dir, branches, defaults, handles });
571
+ state.passError = null;
572
+ } catch (e) {
573
+ passErr = e; state.passError = `${new Date(io.now()).toISOString()} ${String(e?.message ?? e).slice(0, 200)}`;
574
+ console.error(`issue-watch ${watch.name}: pass failed: ${String(e?.message ?? e)}`);
575
+ }
487
576
  writeAtomic(join(dir, "status.json"), JSON.stringify(state) + "\n");
488
- if (state.phase === "done" || once) break;
577
+ if (passErr && once) throw passErr;
578
+ if (state.phase === "done") break;
579
+ if (once) { markExit("single pass (--once)"); break; }
489
580
  await io.sleep(intervalMs);
490
581
  } while (true);
491
- } finally { release(); }
582
+ } catch (e) { markExit(`crashed: ${String(e?.message ?? e)}`); throw e; } finally { if (signals) for (const sig of ["SIGTERM", "SIGINT"]) process.removeAllListeners(sig); release(); }
492
583
  return state;
493
584
  }
494
585
 
@@ -497,7 +588,7 @@ const judgePrompt = ({ decision, options, policy, policyPath, precedent }) => `Y
497
588
  const CLI = join(dirname(fileURLToPath(import.meta.url)), "..", "forgedock.mjs");
498
589
  function realIo(repo, env = process.env) {
499
590
  const gh = ghRunner(execFileSync, (l) => console.error(l));
500
- const root = batchRoot(env);
591
+ const root = batchRoot(env), findNew = (before) => listBatches(root).find((b) => !before.includes(b)) ?? null;
501
592
  return { env, gh, now: () => Date.now(), sleep: (ms) => new Promise((r) => setTimeout(r, ms)),
502
593
  classify: (issues, themes) => { // the one LLM judgment of release mode: issues no theme_map rule classifies
503
594
  const prompt = `Classify each GitHub issue into exactly one theme of [${themes.join(", ")}], or "general" when none fits. Reply with only a JSON object {"<number>": "<theme>"}.\n\n${issues.map((i) => `#${i.number} ${i.title}\n${String(i.body ?? "").slice(0, 600)}`).join("\n---\n")}`;
@@ -507,9 +598,15 @@ function realIo(repo, env = process.env) {
507
598
  const prompt = judgePrompt({ decision, options, policy, policyPath, precedent });
508
599
  return JSON.parse(/\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}/.exec(execFileSync("claude", ["--print"], { input: prompt, encoding: "utf8", maxBuffer: CLAUDE_MAX_BUFFER, timeout: JUDGE_TIMEOUT_MS }))[0]);
509
600
  },
510
- launch: (n, lane) => {
601
+ remediate: (n, lane, code) => { // #5467: one recovery lane for a mechanical park
602
+ let res = null;
603
+ const p = spawn(process.execPath, [CLI, "run-issue", String(n), ...(lane ? ["--lane", lane] : []), "--recover", String(code), "--recover-attempt", "1"], { detached: true, windowsHide: true, stdio: "ignore", cwd: process.cwd(), env });
604
+ p.on("close", (c) => { res = { code: c ?? 1 }; }); p.on("error", () => { res = { code: 1 }; });
605
+ return { poll: () => res };
606
+ },
607
+ launch: (n, lane, opts = {}) => {
511
608
  let res = null;
512
- const p = spawn(process.execPath, [CLI, "run-issue", String(n), "--lane", lane], { detached: true, windowsHide: true, stdio: "ignore", cwd: process.cwd(), env });
609
+ const p = spawn(process.execPath, [CLI, "run-issue", String(n), "--lane", lane, ...(opts.adopt ? ["--adopt"] : [])], { detached: true, windowsHide: true, stdio: "ignore", cwd: process.cwd(), env });
513
610
  p.on("close", (code) => { res = { code: code ?? 1 }; }); p.on("error", () => { res = { code: 1 }; });
514
611
  return { poll: () => res };
515
612
  },
@@ -526,12 +623,16 @@ function realIo(repo, env = process.env) {
526
623
  add: (id, issues) => openBatch(root, id).addIssues(issues),
527
624
  // release #5068 MAT-1: the CLI path checks the label, reopens a finished batch and hosts it on the schedd
528
625
  requeue: (id, n, reason) => (spawnSync(process.execPath, [CLI, "orchestrate", "--requeue", id, String(n), "--reason", reason], { cwd: process.cwd(), env, encoding: "utf8", timeout: 120000, windowsHide: true }).stdout ?? "").match(new RegExp(`requeued #${n}\\b`)) !== null,
626
+ results: (id) => openBatch(root, id).store.load()?.results ?? null, // #5467: the per-issue lane results, final as they land
529
627
  reported: (id) => existsSync(join(root, id, "report.json")),
628
+ find: findNew,
629
+ // #5425: a running (started, not reported, not cancelled) batch of this repo and lane
630
+ running: (lane) => listBatches(root).find((b) => { const p = openBatch(root, b).readPlan(), a = p?.argv ?? []; return p?.repo === repo && a[a.indexOf("--lane") + 1] === lane && existsSync(join(root, b, "state.json")) && !existsSync(join(root, b, "report.json")) && !existsSync(join(root, b, "cancel")); }) ?? null,
530
631
  start: async (issues, parallel, lane) => {
531
- const before = new Set(listBatches(root));
632
+ const before = listBatches(root);
532
633
  spawn(process.execPath, [CLI, "orchestrate", ...issues.map(String), "--parallel", String(parallel), "--lane", lane, "--repo", repo], { detached: true, windowsHide: true, stdio: "ignore", cwd: process.cwd(), env }).unref();
533
- for (let i = 0; i < 60; i++) { const id = listBatches(root).find((b) => !before.has(b)); if (id) return id; await new Promise((r) => setTimeout(r, 1000)); }
534
- throw new Error("orchestrate did not create a batch within 60s");
634
+ for (let i = 0; i < 60; i++) { const id = findNew(before); if (id) return id; await new Promise((r) => setTimeout(r, 1000)); }
635
+ throw Object.assign(new Error("orchestrate did not create a batch within 60s"), { before }); // #5425: tick keeps a pending-start record
535
636
  },
536
637
  } };
537
638
  }
@@ -547,14 +648,20 @@ export function ghFailureEffect(args) {
547
648
  return "the error is raised to its caller (that step fails)";
548
649
  }
549
650
 
651
+ export const GH_RETRIES = 3;
652
+ export const GH_BACKOFF_MS = 2000;
653
+ /** #5465: a network or server hiccup worth retrying (TLS/handshake timeout, reset, DNS, HTTP 5xx, 429, secondary rate limit), not a 4xx. */
654
+ export const isTransientGhError = (text) => /TLS handshake timeout|i\/o timeout|ECONNRESET|ECONNREFUSED|ETIMEDOUT|EAI_AGAIN|connection reset|connection refused|unexpected EOF|no such host|temporary failure|HTTP (5\d\d|429)\b|secondary rate limit|abuse detection|timeout awaiting/i.test(String(text ?? ""));
655
+
550
656
  /**
551
657
  * #5088: `gh(args)→stdout` over `exec` (execFileSync's signature) with gh's stderr captured instead of leaked. A failure
552
658
  * throws an Error naming the call (`.status`, `.stderr` kept); an HTTP 401/403 first `warn`s one line with the call and
553
659
  * its effect on the pass (ghFailureEffect).
554
660
  */
555
- export function ghRunner(exec, warn = () => {}) {
661
+ export function ghRunner(exec, warn = () => {}, { retries = GH_RETRIES, sleep = sleepSync, delayMs = GH_BACKOFF_MS } = {}) {
556
662
  return (args) => {
557
- try { return exec("gh", args, { encoding: "utf8", maxBuffer: 64 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] }); } catch (e) {
663
+ for (let attempt = 0; ; attempt++) try { return exec("gh", args, { encoding: "utf8", maxBuffer: 64 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] }); } catch (e) {
664
+ if (attempt < retries && isTransientGhError(`${e?.stderr ?? ""}\n${e?.message ?? ""}`)) { sleep(delayMs * 2 ** attempt); continue; } // #5465
558
665
  const call = args.slice(0, 3).join(" "), stderr = String(e?.stderr ?? "");
559
666
  const first = stderr.split("\n").map((l) => l.trim()).find(Boolean) ?? String(e?.message ?? e).split("\n")[0];
560
667
  const code = /HTTP (40[13])\b/.exec(stderr)?.[1];
@@ -569,20 +676,33 @@ const flag = (argv, f) => { const i = argv.indexOf(f); return i >= 0 ? argv[i +
569
676
  /** `forgedock issue-watch run [--name w] [--repo o/r] [--once] [--interval s] | status [--name w] [--repo o/r]`; `--dry-run` writes nothing: mode release prints the would-cut set, per-issue/batch the would-claim/fold/skip plan (#5088) and the needs-human classification. */
570
677
  export async function issueWatchFromCli(argv, deps = {}) {
571
678
  const [op] = argv;
572
- const usage = "usage: forgedock issue-watch run [--name <w>] [--repo owner/repo] [--once] [--interval <s>] [--dry-run] | status [--name <w>] [--repo owner/repo]";
573
- if (!["run", "status"].includes(op)) throw new Error(usage);
679
+ const usage = "usage: forgedock issue-watch run [--name <w>] [--repo owner/repo] [--once] [--interval <s>] [--dry-run] | status [--name <w>] [--repo owner/repo] [--stuck [--hours <n>]] | install [--name <w>] [--repo owner/repo] [--interval <s>] | watchdog";
680
+ if (!["run", "status", "install", "watchdog"].includes(op)) throw new Error(usage);
574
681
  const cwd = deps.cwd ?? process.cwd(), env = deps.env ?? process.env, print = deps.print ?? ((l) => console.log(l));
575
682
  let raw = ""; try { raw = readFileSync(join(cwd, "forge.yaml"), "utf8"); } catch { /* no forge.yaml: the default watch */ }
576
683
  const watches = loadWatches(raw);
684
+ if (op === "watchdog") { // #5465: alert (events.webhook_url) once for every watch whose heartbeat is dead; run by the install timer
685
+ const { makeEventEmitter } = await import("../engine/events.mjs"), { readEvents } = await import("../engine-cli.mjs");
686
+ const dead = await alertDeadWatches({ root: watchRoot(env), now: (deps.now ?? Date.now)(), emit: deps.emit ?? ((type, data, ctx) => makeEventEmitter({ repo: ctx.repo, config: readEvents(cwd) }).emitEvent(type, data, ctx)) });
687
+ for (const w of dead) print(`watch ${w.name} (${w.repo}) DEAD: ${w.live.reason}`);
688
+ return { ok: true, dead: dead.length };
689
+ }
577
690
  const name = flag(argv, "--name") ?? (Object.keys(watches).length === 1 ? Object.keys(watches)[0] : "default");
578
691
  const watch = watches[name] ?? (name === "default" ? validateWatch("default", {}) : null);
579
692
  if (!watch) throw new Error(`no watch ${name} in forge.yaml issue_watch.watches`);
693
+ if (op === "install") {
694
+ const { installWatchUnit } = await import("./issuewatch-install.mjs");
695
+ const r = installWatchUnit({ name, repo: flag(argv, "--repo"), interval: flag(argv, "--interval"), cwd, cli: CLI, ...(deps.install ?? {}) });
696
+ print(`issue-watch ${name}: installed ${r.files.join(", ")}`);
697
+ return { ok: true, ...r };
698
+ }
580
699
  const io = deps.io ?? realIo(null, env);
581
700
  const repo = flag(argv, "--repo") ?? JSON.parse(String(await io.gh(["repo", "view", "--json", "nameWithOwner"]))).nameWithOwner;
582
701
  const dir = watchDir(repo, name, env);
583
702
  if (op === "status") {
584
703
  const s = readJson(join(dir, "status.json"));
585
- print(s ? formatStatus(s, watch, io.now()) : `watch ${name}: no status yet`);
704
+ if (s && argv.includes("--stuck")) print(formatStuck(stuckClaims(s, io.now(), Number(flag(argv, "--hours")) || undefined), Number(flag(argv, "--hours")) || undefined)); // #5467
705
+ else print(s ? formatStatus(s, watch, io.now()) : `watch ${name}: no status yet`);
586
706
  return { ok: true };
587
707
  }
588
708
  const ctx = decisionContext({ loadPolicy, readFile, cwd }), shared = { matches: matchesSelectors, fold, labelNames, isBot, TRUSTED };
@@ -610,7 +730,7 @@ export async function issueWatchFromCli(argv, deps = {}) {
610
730
  const real = deps.io ?? realIo(repo, env);
611
731
  const branches = readBranches(cwd);
612
732
  const defaults = await defaultBranches({ repo, io: { gh: async (a) => real.gh(a) }, branches });
613
- const state = await runWatch({ watch, repo, io: real, dir, branches, defaults, cwd, once: argv.includes("--once"), intervalMs: (Number(flag(argv, "--interval")) || 300) * 1000, release });
733
+ const state = await runWatch({ watch, repo, io: real, dir, branches, defaults, cwd, once: argv.includes("--once"), signals: true, intervalMs: (Number(flag(argv, "--interval")) || 300) * 1000, release });
614
734
  print(formatStatus(state, watch, real.now()));
615
735
  return { ok: true, state };
616
736
  }