forgedock 1.52.0 → 1.54.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 (233) hide show
  1. package/.claude-plugin/marketplace.json +51 -0
  2. package/README.md +8 -2
  3. package/bin/auth/app-manifest.mjs +89 -0
  4. package/bin/auth/app-manifest.test.mjs +75 -0
  5. package/bin/auth/app-token.mjs +256 -0
  6. package/bin/auth/app-token.test.mjs +232 -0
  7. package/bin/brand.mjs +7 -0
  8. package/bin/config-history.mjs +151 -0
  9. package/bin/config-schema.mjs +115 -0
  10. package/bin/demo.mjs +65 -11
  11. package/bin/engine/outcome-codes.mjs +9 -3
  12. package/bin/engine/telemetry-seam.mjs +11 -3
  13. package/bin/engine/telemetry-seam.test.mjs +17 -0
  14. package/bin/engine-cli.mjs +110 -36
  15. package/bin/experiment.mjs +58 -6
  16. package/bin/first-run.mjs +122 -0
  17. package/bin/forge-utils.mjs +6 -2
  18. package/bin/forgedock.mjs +138 -142
  19. package/bin/help-text.mjs +144 -0
  20. package/bin/hooks/pre-tool-use.mjs +7 -0
  21. package/bin/journey.mjs +82 -83
  22. package/bin/lean/acceptance.mjs +313 -0
  23. package/bin/lean/acceptance.test.mjs +215 -0
  24. package/bin/lean/account-watch.mjs +28 -0
  25. package/bin/lean/account-watch.test.mjs +30 -0
  26. package/bin/lean/activation.mjs +38 -0
  27. package/bin/lean/activation.test.mjs +36 -1
  28. package/bin/lean/basered.mjs +115 -0
  29. package/bin/lean/basered.test.mjs +66 -0
  30. package/bin/lean/batch-health.mjs +114 -7
  31. package/bin/lean/batch-health.test.mjs +87 -1
  32. package/bin/lean/batch.mjs +41 -2
  33. package/bin/lean/batch.test.mjs +115 -11
  34. package/bin/lean/branchlock.mjs +54 -0
  35. package/bin/lean/branchlock.test.mjs +49 -0
  36. package/bin/lean/ceiling.mjs +72 -0
  37. package/bin/lean/ceiling.test.mjs +54 -0
  38. package/bin/lean/checkpoint-reconcile.mjs +43 -0
  39. package/bin/lean/checkpoint-reconcile.test.mjs +95 -0
  40. package/bin/lean/ci-budget.mjs +366 -0
  41. package/bin/lean/ci-budget.test.mjs +167 -0
  42. package/bin/lean/conformance.e2e.test.mjs +8 -1
  43. package/bin/lean/conformance.mjs +269 -38
  44. package/bin/lean/conformance.test.mjs +280 -7
  45. package/bin/lean/context.mjs +35 -6
  46. package/bin/lean/context.test.mjs +27 -1
  47. package/bin/lean/depcache.mjs +25 -1
  48. package/bin/lean/depcache.test.mjs +26 -0
  49. package/bin/lean/e2e.mjs +18 -2
  50. package/bin/lean/e2e.test.mjs +26 -1
  51. package/bin/lean/effects.mjs +47 -14
  52. package/bin/lean/execution.mjs +19 -3
  53. package/bin/lean/execution.test.mjs +63 -0
  54. package/bin/lean/facts.mjs +3 -3
  55. package/bin/lean/facts.test.mjs +5 -0
  56. package/bin/lean/findinglabel.mjs +16 -0
  57. package/bin/lean/findinglabel.test.mjs +39 -0
  58. package/bin/lean/fixround.mjs +14 -0
  59. package/bin/lean/fixround.test.mjs +25 -2
  60. package/bin/lean/gh-assoc.test.mjs +2 -1
  61. package/bin/lean/integration.mjs +100 -9
  62. package/bin/lean/integration.test.mjs +98 -0
  63. package/bin/lean/issuewatch-parity.mjs +64 -0
  64. package/bin/lean/issuewatch-parity.test.mjs +127 -0
  65. package/bin/lean/issuewatch-release.mjs +6 -2
  66. package/bin/lean/issuewatch-release.test.mjs +17 -1
  67. package/bin/lean/issuewatch.mjs +45 -6
  68. package/bin/lean/issuewatch.test.mjs +3 -2
  69. package/bin/lean/lanelock.mjs +14 -0
  70. package/bin/lean/lean.mjs +473 -100
  71. package/bin/lean/lean.test.mjs +686 -33
  72. package/bin/lean/light.mjs +48 -7
  73. package/bin/lean/light.test.mjs +37 -3
  74. package/bin/lean/limits.test.mjs +142 -9
  75. package/bin/lean/mechfix.mjs +124 -0
  76. package/bin/lean/mechfix.test.mjs +75 -0
  77. package/bin/lean/orchestrate-cancel.test.mjs +143 -0
  78. package/bin/lean/orchestrate.mjs +116 -28
  79. package/bin/lean/phaseledger.mjs +47 -5
  80. package/bin/lean/phaseledger.test.mjs +30 -1
  81. package/bin/lean/postdeploy-check.test.mjs +39 -0
  82. package/bin/lean/precheck.mjs +23 -4
  83. package/bin/lean/precheck.test.mjs +14 -1
  84. package/bin/lean/prereq.mjs +28 -0
  85. package/bin/lean/prereq.test.mjs +20 -0
  86. package/bin/lean/probe.mjs +4 -2
  87. package/bin/lean/prodparity.mjs +52 -0
  88. package/bin/lean/prodparity.test.mjs +67 -0
  89. package/bin/lean/prompts.mjs +77 -19
  90. package/bin/lean/quota.mjs +39 -0
  91. package/bin/lean/recovery.test.mjs +11 -1
  92. package/bin/lean/relaxation.mjs +73 -0
  93. package/bin/lean/relaxation.test.mjs +54 -0
  94. package/bin/lean/release-io.test.mjs +42 -0
  95. package/bin/lean/release-postmerge.mjs +125 -0
  96. package/bin/lean/release-preflight.mjs +58 -0
  97. package/bin/lean/release-preflight.test.mjs +114 -0
  98. package/bin/lean/release-rehearsal.mjs +64 -0
  99. package/bin/lean/release-rehearsal.test.mjs +93 -0
  100. package/bin/lean/release-review.e2e.test.mjs +77 -0
  101. package/bin/lean/release-review.mjs +254 -0
  102. package/bin/lean/release-review.test.mjs +307 -0
  103. package/bin/lean/release-snapshot.mjs +188 -0
  104. package/bin/lean/release-snapshot.test.mjs +190 -0
  105. package/bin/lean/release.mjs +296 -0
  106. package/bin/lean/release.test.mjs +387 -0
  107. package/bin/lean/render.mjs +1 -1
  108. package/bin/lean/replan.mjs +184 -0
  109. package/bin/lean/replan.test.mjs +110 -0
  110. package/bin/lean/resume.mjs +9 -7
  111. package/bin/lean/resume.test.mjs +16 -0
  112. package/bin/lean/rotator.mjs +150 -31
  113. package/bin/lean/rotator.test.mjs +105 -2
  114. package/bin/lean/sandbox-remote.mjs +9 -2
  115. package/bin/lean/schedd.mjs +83 -5
  116. package/bin/lean/schedd.test.mjs +108 -7
  117. package/bin/lean/selfreview.mjs +94 -0
  118. package/bin/lean/selfreview.test.mjs +58 -1
  119. package/bin/lean/selftest-gate.mjs +22 -0
  120. package/bin/lean/selftest-gate.test.mjs +18 -1
  121. package/bin/lean/selftest-journey.mjs +234 -0
  122. package/bin/lean/selftest-journey.test.mjs +130 -0
  123. package/bin/lean/selftest-live.mjs +2 -1
  124. package/bin/lean/seqlease.mjs +35 -1
  125. package/bin/lean/seqlease.test.mjs +15 -0
  126. package/bin/lean/seqreserve.e2e.test.mjs +135 -0
  127. package/bin/lean/seqreserve.mjs +73 -0
  128. package/bin/lean/seqreserve.test.mjs +134 -0
  129. package/bin/lean/sequence.mjs +35 -6
  130. package/bin/lean/seqversioned.mjs +147 -0
  131. package/bin/lean/stagestamp.mjs +28 -0
  132. package/bin/lean/stagestamp.test.mjs +32 -0
  133. package/bin/lean/surfaces.mjs +75 -0
  134. package/bin/lean/surfaces.test.mjs +59 -0
  135. package/bin/lean/toolplace.mjs +28 -0
  136. package/bin/lean/toolplace.test.mjs +24 -0
  137. package/bin/lean/toolstats.mjs +3 -1
  138. package/bin/lean/toolstats.test.mjs +11 -0
  139. package/bin/lean/validatebest.mjs +28 -0
  140. package/bin/lean/validatebest.test.mjs +27 -0
  141. package/bin/lean/verifier.mjs +3 -2
  142. package/bin/lean/verify.mjs +2 -1
  143. package/bin/lean/verify.test.mjs +6 -0
  144. package/bin/pool/agent.mjs +27 -4
  145. package/bin/pool/docker.mjs +5 -0
  146. package/bin/pool/router.mjs +74 -28
  147. package/bin/prereqs.mjs +111 -0
  148. package/bin/replay-timelapse.mjs +149 -0
  149. package/bin/review-staging.mjs +123 -16
  150. package/bin/review-staging.test.mjs +18 -0
  151. package/bin/runner.mjs +43 -6
  152. package/bin/splash-install.mjs +157 -0
  153. package/bin/stats/aggregate.mjs +8 -1
  154. package/bin/stats/conformance-outcomes.mjs +289 -0
  155. package/bin/stats/conformance-outcomes.test.mjs +274 -0
  156. package/bin/stats/depth.mjs +275 -0
  157. package/bin/stats/depth.test.mjs +158 -0
  158. package/bin/stats/efficiency.mjs +26 -5
  159. package/bin/stats/efficiency.test.mjs +45 -1
  160. package/bin/stats/experiment.mjs +7 -5
  161. package/bin/stats/first-review.mjs +77 -0
  162. package/bin/stats/first-review.test.mjs +36 -0
  163. package/bin/stats/firstmerge.mjs +40 -0
  164. package/bin/stats/firstmerge.test.mjs +41 -0
  165. package/bin/stats/github-source.mjs +53 -15
  166. package/bin/stats/index.mjs +147 -9
  167. package/bin/stats/local-source.mjs +12 -0
  168. package/bin/stats/origin.mjs +80 -0
  169. package/bin/stats/origin.test.mjs +58 -0
  170. package/bin/stats/query.mjs +69 -0
  171. package/bin/stats/render.mjs +3 -1
  172. package/bin/stats/scoreboard.mjs +137 -0
  173. package/bin/stats/scoreboard.test.mjs +87 -0
  174. package/bin/stats/selffiled.mjs +52 -0
  175. package/bin/stats/selffiled.test.mjs +71 -0
  176. package/bin/stats/stats.test.mjs +80 -0
  177. package/bin/tui.mjs +3 -2
  178. package/commands/bootstrap.md +15 -14
  179. package/commands/deploy-pr.md +18 -3
  180. package/commands/forge-stats.md +1 -1
  181. package/commands/forgedock-ci-setup.md +28 -0
  182. package/commands/forgedock-init.md +4 -5
  183. package/commands/issue.md +2 -0
  184. package/commands/milestone.md +9 -1
  185. package/commands/orchestrate.md +1 -1
  186. package/commands/replay.md +2 -0
  187. package/commands/review-pr-agents/security.md +4 -0
  188. package/commands/review-pr-staging.md +6 -1
  189. package/commands/work-on/build.md +4 -6
  190. package/commands/work-on/close.md +8 -0
  191. package/docs/CONFIG.md +170 -18
  192. package/docs/ISSUE-WATCH.md +25 -0
  193. package/docs/OUTCOME-CODES.md +4 -0
  194. package/docs/REPLAY.md +9 -0
  195. package/docs/SELFTEST.md +11 -0
  196. package/docs/STATS.md +61 -0
  197. package/docs/TELEMETRY.md +1 -1
  198. package/docs/eval/README.md +6 -0
  199. package/docs/eval/adversarial-bench.md +68 -0
  200. package/docs/eval/corpus/adversarial-v1.json +285 -0
  201. package/docs/eval/feature-bench.md +42 -0
  202. package/docs/eval/feature-specs/crud-auth/journeys/notes-crud-isolated.mjs +21 -0
  203. package/docs/eval/feature-specs/crud-auth/journeys/register-login.mjs +12 -0
  204. package/docs/eval/feature-specs/crud-auth/spec.md +15 -0
  205. package/docs/site/start-a-new-project.md +2 -1
  206. package/package.json +5 -2
  207. package/plugins/forgedock-splash/.claude-plugin/plugin.json +10 -0
  208. package/plugins/forgedock-splash/README.md +27 -0
  209. package/plugins/forgedock-splash/hooks/hooks.json +1 -0
  210. package/plugins/forgedock-splash/hooks/register.tsx +74 -0
  211. package/plugins/forgedock-splash/hooks/scene.ts +222 -0
  212. package/plugins/forgedock-splash/types/index.d.ts +10 -0
  213. package/pool/README.md +1 -1
  214. package/pool/image/cs-cred +14 -1
  215. package/scripts/backfill-finding-labels.mjs +50 -0
  216. package/scripts/backfill-finding-labels.test.mjs +36 -0
  217. package/scripts/bench-adversarial.mjs +216 -0
  218. package/scripts/bench-feature.mjs +170 -0
  219. package/scripts/bench-lightlane.mjs +2 -2
  220. package/scripts/bootstrap-create.mjs +2 -2
  221. package/scripts/bootstrap-validate.mjs +35 -2
  222. package/scripts/check-spec-size.sh +4 -3
  223. package/scripts/check-spec-size.test.sh +3 -0
  224. package/scripts/doctor-pipeline-state.sh +21 -6
  225. package/scripts/file-deferred-followups.sh +59 -251
  226. package/scripts/file-deferred-followups.test.sh +85 -206
  227. package/scripts/followup-route.mjs +12 -0
  228. package/scripts/owner-route-parity.test.sh +17 -1
  229. package/scripts/plan-validate-live.mjs +40 -6
  230. package/scripts/review-pr-side-effects.test.sh +40 -0
  231. package/scripts/review-pr-staging-scope.test.sh +1 -1
  232. package/scripts/review-staging-post.sh +23 -0
  233. package/scripts/review-staging-post.test.sh +8 -0
@@ -2,7 +2,7 @@
2
2
  // SPDX-License-Identifier: AGPL-3.0-or-later
3
3
  import { describe, it } from "node:test";
4
4
  import assert from "node:assert/strict";
5
- import { readRollouts, detectNewOffKeys, activationFailures, dormancyReport, coversFlag } from "./activation.mjs";
5
+ import { readRollouts, detectNewOffKeys, activationFailures, dormancyReport, coversFlag, rolloutModes, liveDeferralBlocks } from "./activation.mjs";
6
6
  import { precheck } from "./conformance.mjs";
7
7
 
8
8
  const cfg = { files: ["config/rollouts.json"], days: 14 };
@@ -73,3 +73,38 @@ describe("dormancy report (#4769)", () => {
73
73
  assert.deepEqual(r.map((x) => x.flag), ["egress_country_exploration", "clearance_exit_routing"]);
74
74
  });
75
75
  });
76
+
77
+ describe("#5240 rolloutModes", () => {
78
+ const files = { "config/rollouts.json": '{\n "t4_retry_byte_gate": "shadow",\n "other_flag": "on",\n "unused": "off"\n}', "svc/retry.py": "if rollout('t4_retry_byte_gate'):\n pass\nother_flag_x = 1", "svc/b.py": "other_flag()" };
79
+ const read = (f) => { if (!(f in files)) throw new Error("ENOENT"); return files[f]; };
80
+ it("reports the mode of flags a changed file names; shadow/off are not live", () => {
81
+ assert.deepEqual(rolloutModes(cfg, ["svc/retry.py", "svc/b.py"], read), [{ flag: "other_flag", mode: "on", live: true }, { flag: "t4_retry_byte_gate", mode: "shadow", live: false }]);
82
+ });
83
+ it("is empty without a registry, an unreadable registry, or a change that names no flag", () => {
84
+ assert.deepEqual(rolloutModes(null, ["svc/retry.py"], read), []);
85
+ assert.deepEqual(rolloutModes(cfg, ["svc/retry.py"], () => { throw new Error("x"); }), []);
86
+ assert.deepEqual(rolloutModes(cfg, ["gone.py"], read), []);
87
+ });
88
+ });
89
+
90
+ describe("liveDeferralBlocks (#5285)", () => {
91
+ const c = { requirements: [{ id: "R1", disposition: "deliver" }, { id: "R3", disposition: "defer", bucket: "post-deploy", why: "live acceptance run" }] };
92
+ it("a live rollout with deferred live acceptance blocks (the #38819 replay)", () => {
93
+ assert.deepEqual(liveDeferralBlocks(c, [{ flag: "alterlab_google_pool", mode: "on", live: true }]), [{ id: "R3", flag: "alterlab_google_pool" }]);
94
+ });
95
+ it("a default-off (inert) rollout or no rollout ships with the deferral", () => {
96
+ assert.deepEqual(liveDeferralBlocks(c, [{ flag: "alterlab_google_pool", mode: "off", live: false }]), []);
97
+ assert.deepEqual(liveDeferralBlocks(c, []), []);
98
+ });
99
+ it("a deferral that is not about live verification does not block", () => {
100
+ assert.deepEqual(liveDeferralBlocks({ requirements: [{ id: "R2", disposition: "defer", bucket: "owner:rotate key", why: "needs a credential" }] }, [{ flag: "f", mode: "on", live: true }]), []);
101
+ });
102
+ });
103
+
104
+ describe("liveDeferralBlocks transferred requirements (#5339)", () => {
105
+ it("a live rollout with a post-deploy e2e/manual requirement transferred to the epic blocks, even without a live bucket", () => {
106
+ const c = { requirements: [{ id: "R2", quote: "Search works against the live web [type:e2e]", disposition: "post-deploy", bucket: "date:2027-01-01" }] };
107
+ assert.deepEqual(liveDeferralBlocks(c, [{ flag: "pool", mode: "on", live: true }]), [{ id: "R2", flag: "pool" }]);
108
+ assert.deepEqual(liveDeferralBlocks(c, [{ flag: "pool", mode: "off", live: false }]), []);
109
+ });
110
+ });
@@ -0,0 +1,115 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * Base red (#5239): a still-failing repo-wide guard command (verify.invariants) is run once on the merge base. Failing there
5
+ * too means the base is already red: the lane is deferred (`base.red`) behind the commit that broke it, never sent
6
+ * needs-human; failing only on the lane tree blocks the merge. Attribution is deterministic (git log on the files the
7
+ * failure names, then the issue number in the commit message), 0 LLM calls.
8
+ */
9
+ import * as nodeFs from "node:fs";
10
+ import { tmpdir } from "node:os";
11
+ import { join } from "node:path";
12
+
13
+ const TIMEOUT_RC = 124, MISSING_RC = 127;
14
+ const FILE_RE = /(?:^|[\s"'`(=:])((?:\.{0,2}\/)?[\w.-]+(?:\/[\w.-]+)+\.(?:py|mjs|cjs|js|jsx|ts|tsx|go|rs|rb|sh|ya?ml|json))\b/g;
15
+ const TEST_RE = /(?:^|[/_.-])(?:tests?|spec)(?:[/_.-]|$)/i;
16
+
17
+ /** Split failed `{command, rc}` rows by their base run `{command, rc}`: base red only when the base run itself failed (a timeout or missing runner is no evidence, so the failure stays the lane's). */
18
+ export function classifyBaseRed({ failed = [], baseRuns = [] } = {}) {
19
+ const byCmd = new Map((baseRuns ?? []).map((b) => [b?.command, b]));
20
+ const laneOwn = [], baseRed = [];
21
+ for (const f of failed ?? []) {
22
+ const b = byCmd.get(f.command), rc = Number(b?.rc);
23
+ (b && Number.isInteger(rc) && rc !== 0 && rc !== TIMEOUT_RC && rc !== MISSING_RC ? baseRed : laneOwn).push(f);
24
+ }
25
+ return { laneOwn, baseRed };
26
+ }
27
+
28
+ /** Repo-relative file paths named in a command and its failure output, non-test paths first (the guarded code, not the guard). */
29
+ export function baseRedPaths(rows = []) {
30
+ const seen = new Set(), src = [], tests = [];
31
+ for (const r of rows) {
32
+ for (const text of [r?.command, String(r?.output ?? "").slice(-20000)]) {
33
+ for (const m of String(text ?? "").matchAll(FILE_RE)) {
34
+ const p = m[1].replace(/^\.\//, "");
35
+ if (p.startsWith("/") || p.startsWith("..") || seen.has(p)) continue;
36
+ seen.add(p); (TEST_RE.test(p) ? tests : src).push(p);
37
+ }
38
+ }
39
+ }
40
+ return { src: src.slice(0, 20), tests: tests.slice(0, 20) };
41
+ }
42
+
43
+ /** Issue number a commit stands for: a closing keyword, else an `issue-N` branch name (merge commit), else the last `(#N)` of the subject. */
44
+ export function issueOf(subject = "", body = "") {
45
+ const text = `${subject}\n${body}`;
46
+ const close = [...text.matchAll(/\b(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)\s+#(\d+)/gi)].pop();
47
+ if (close) return Number(close[1]);
48
+ const br = text.match(/\bissue-(\d+)\b/);
49
+ if (br) return Number(br[1]);
50
+ const sub = [...String(subject).matchAll(/\(#(\d+)\)/g)].pop();
51
+ return sub ? Number(sub[1]) : null;
52
+ }
53
+
54
+ /** The newest commit on `base` touching a file the failures name (guarded code first, else the tests): {sha, subject, issue, files} or null. Never throws. */
55
+ export async function attribute({ failed = [], git, base } = {}) {
56
+ try {
57
+ const { src, tests } = baseRedPaths(failed);
58
+ for (const files of [src, tests]) {
59
+ if (!files.length) continue;
60
+ const out = String(await git(["log", "-1", "--format=%H%x1f%s%x1f%b", base, "--", ...files]).catch(() => "")).trim();
61
+ const [sha, subject = "", body = ""] = out.split("\x1f");
62
+ if (/^[0-9a-f]{40}$/.test(sha ?? "")) return { sha, subject, issue: issueOf(subject, body), files };
63
+ }
64
+ } catch { /* unattributable */ }
65
+ return null;
66
+ }
67
+
68
+ /** Run each command once on a detached worktree of `mergeBase`, returning `[{command, rc}]`; removed afterwards. Empty when the worktree cannot be made (every failure then stays the lane's). */
69
+ export async function runOnBase({ commands = [], git, runCommand, mergeBase, cwd, env, timeoutMs, fs = nodeFs } = {}) {
70
+ let dir = null;
71
+ const out = [];
72
+ try {
73
+ dir = fs.mkdtempSync(join(tmpdir(), "basered-"));
74
+ await git(["worktree", "add", "--detach", dir, mergeBase]);
75
+ try { if (fs.existsSync(join(cwd, "node_modules"))) fs.symlinkSync(join(cwd, "node_modules"), join(dir, "node_modules")); } catch { /* best effort */ }
76
+ for (const command of commands) {
77
+ let r;
78
+ try { r = await runCommand({ command, cwd: dir, timeoutMs, env }); } catch (e) { r = { rc: MISSING_RC, output: String(e?.message ?? e) }; }
79
+ out.push({ command, rc: Number.isInteger(r?.rc) ? r.rc : 1 });
80
+ }
81
+ } catch { /* no base tree: no verdict */ } finally {
82
+ if (dir) {
83
+ try { await git(["worktree", "remove", "--force", dir]); } catch { /* best effort */ }
84
+ try { fs.rmSync(dir, { recursive: true, force: true }); } catch { /* best effort */ }
85
+ }
86
+ }
87
+ return out;
88
+ }
89
+
90
+ /** Comment body that marks the introducing issue (or the new tracking issue) as the cause of a red base. */
91
+ export function baseRedNote({ base, att, laneIssue, commands }) {
92
+ const cmds = commands.map((c) => `- \`${c}\``).join("\n");
93
+ return `<!-- FORGE:BASE_RED -->\n## Base is red\nThese guard command(s) fail on \`${base}\`${att ? ` at \`${att.sha.slice(0, 12)}\` or earlier; last change to the files they name: \`${att.sha.slice(0, 12)}\` ${att.subject}` : ""}:\n${cmds}\n\nLane #${laneIssue} is deferred behind the fix; it is not needs-human. Fix the base (or reopen this issue) and the lane resumes.`;
94
+ }
95
+
96
+ /**
97
+ * File or reopen against the introducing issue. `ghc(args)` runs gh (writes retried by the caller's wrapper). An attributed
98
+ * issue gets a comment and is reopened when closed; no issue number files a new `base-red` tracking issue. Returns the
99
+ * issue number, or null when GitHub could not be written (the lane still defers).
100
+ */
101
+ export async function reportBaseRed({ ghc, repo, base, att, laneIssue, commands }) {
102
+ const body = baseRedNote({ base, att, laneIssue, commands });
103
+ try {
104
+ if (att?.issue) {
105
+ let state = "";
106
+ try { state = String(await ghc(["issue", "view", String(att.issue), "-R", repo, "--json", "state", "-q", ".state"])).trim().toUpperCase(); } catch { /* comment anyway */ }
107
+ if (state === "CLOSED") await ghc(["issue", "reopen", String(att.issue), "-R", repo]);
108
+ await ghc(["issue", "comment", String(att.issue), "-R", repo, "--body", body]);
109
+ return att.issue;
110
+ }
111
+ const url = String(await ghc(["issue", "create", "-R", repo, "--title", `fix: ${base} is red on guard command ${commands[0] ?? ""}`.slice(0, 120), "--body", body])).trim();
112
+ const n = url.match(/\/issues\/(\d+)/);
113
+ return n ? Number(n[1]) : null;
114
+ } catch { return null; }
115
+ }
@@ -0,0 +1,66 @@
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 { classifyBaseRed, baseRedPaths, issueOf, attribute, runOnBase, reportBaseRed } from "./basered.mjs";
6
+
7
+ const SHA = "13834f1c51".padEnd(40, "0");
8
+
9
+ describe("base red (#5239)", () => {
10
+ it("classifyBaseRed: base red only when the base run itself failed", () => {
11
+ const failed = [{ command: "a" }, { command: "b" }, { command: "c" }, { command: "d" }];
12
+ const r = classifyBaseRed({ failed, baseRuns: [{ command: "a", rc: 1 }, { command: "b", rc: 0 }, { command: "c", rc: 124 }] });
13
+ assert.deepEqual(r.baseRed.map((f) => f.command), ["a"]);
14
+ assert.deepEqual(r.laneOwn.map((f) => f.command), ["b", "c", "d"]);
15
+ assert.deepEqual(classifyBaseRed({ failed, baseRuns: [] }).baseRed, [], "no base run: the failure stays the lane's");
16
+ });
17
+
18
+ it("baseRedPaths lists the guarded code before the guard's own test file", () => {
19
+ const p = baseRedPaths([{ command: "pytest services/api/tests/test_rate_limit_rejection_sites_guard.py", output: "bare 429 at services/api/app/routers/listing_feeds.py:41" }]);
20
+ assert.deepEqual(p.src, ["services/api/app/routers/listing_feeds.py"]);
21
+ assert.deepEqual(p.tests, ["services/api/tests/test_rate_limit_rejection_sites_guard.py"]);
22
+ });
23
+
24
+ it("issueOf prefers a closing keyword, then the issue branch, then the last (#N)", () => {
25
+ assert.equal(issueOf("feat: x (#40001)", "Closes #39805"), 39805);
26
+ assert.equal(issueOf("Merge pull request #39996 from o/feat/issue-39805-lean", ""), 39805);
27
+ assert.equal(issueOf("feat(api): feeds (#39805)", ""), 39805);
28
+ assert.equal(issueOf("chore: nothing", ""), null);
29
+ });
30
+
31
+ it("attribute names the newest base commit touching the guarded code, else the tests; null when none", async () => {
32
+ const calls = [];
33
+ const git = async (a) => { calls.push(a); return a.includes("services/api/app/routers/listing_feeds.py") ? `${SHA}\x1ffeat(api): listing feeds (#39805)\x1f` : ""; };
34
+ const failed = [{ command: "pytest t/test_guard.py", output: "bare 429 at services/api/app/routers/listing_feeds.py" }];
35
+ const att = await attribute({ failed, git, base: "origin/staging" });
36
+ assert.equal(att.sha, SHA); assert.equal(att.issue, 39805);
37
+ assert.deepEqual(calls[0].slice(0, 5), ["log", "-1", "--format=%H%x1f%s%x1f%b", "origin/staging", "--"]);
38
+ assert.equal(await attribute({ failed: [{ command: "make guard", output: "" }], git, base: "origin/staging" }), null);
39
+ assert.equal(await attribute({ failed, git: async () => { throw new Error("boom"); }, base: "b" }), null);
40
+ });
41
+
42
+ it("runOnBase runs each command in a detached base worktree and removes it", async () => {
43
+ const calls = [], cwds = [];
44
+ const git = async (a) => { calls.push(a.slice(0, 3).join(" ")); return ""; };
45
+ const out = await runOnBase({ commands: ["x", "y"], git, mergeBase: "origin/staging", cwd: "/nonexistent", timeoutMs: 1000,
46
+ runCommand: async ({ command, cwd }) => { cwds.push(cwd); return { rc: command === "x" ? 1 : 0 }; } });
47
+ assert.deepEqual(out, [{ command: "x", rc: 1 }, { command: "y", rc: 0 }]);
48
+ assert.match(calls[0], /^worktree add --detach$|^worktree add --detach /);
49
+ assert.ok(calls.some((c) => c.startsWith("worktree remove --force")));
50
+ assert.equal(cwds[0], cwds[1]);
51
+ assert.deepEqual(await runOnBase({ commands: ["x"], git: async () => { throw new Error("no"); }, runCommand: async () => ({ rc: 0 }), mergeBase: "b", cwd: "/x" }), [], "no base tree: no verdict");
52
+ });
53
+
54
+ it("reportBaseRed reopens a closed introducing issue and comments; files a new issue when unattributable", async () => {
55
+ const gh = [];
56
+ const ghc = async (a) => { gh.push(a); return a[1] === "view" ? "CLOSED\n" : a[1] === "create" ? "https://github.com/o/r/issues/77\n" : ""; };
57
+ const n = await reportBaseRed({ ghc, repo: "o/r", base: "staging", att: { sha: SHA, subject: "feat", issue: 39805 }, laneIssue: 5, commands: ["pytest g"] });
58
+ assert.equal(n, 39805);
59
+ assert.deepEqual(gh.map((a) => a[1]), ["view", "reopen", "comment"]);
60
+ assert.match(gh[2].at(-1), /FORGE:BASE_RED[\s\S]*Lane #5 is deferred/);
61
+ gh.length = 0;
62
+ assert.equal(await reportBaseRed({ ghc, repo: "o/r", base: "staging", att: null, laneIssue: 5, commands: ["pytest g"] }), 77);
63
+ assert.equal(gh[0][1], "create");
64
+ assert.equal(await reportBaseRed({ ghc: async () => { throw new Error("x"); }, repo: "o/r", base: "s", att: null, laneIssue: 5, commands: ["c"] }), null);
65
+ });
66
+ });
@@ -9,7 +9,7 @@
9
9
  * dir records the checkpoints done and the alert, so a restarted daemon re-arms only the remaining checks and never alerts
10
10
  * twice. A refused launch has no batch dir: it is recorded in `<batch root>/refusals.json`. `forgedock status` reads both.
11
11
  */
12
- import { readFileSync } from "node:fs";
12
+ import { appendFileSync, existsSync, readFileSync } from "node:fs";
13
13
  import { spawn as spawnProc } from "node:child_process";
14
14
  import { join } from "node:path";
15
15
  import { listBatches, openBatch, REQUEUABLE, writeAtomic } from "./batch.mjs";
@@ -45,9 +45,10 @@ export function rootsOf(state) {
45
45
 
46
46
  /**
47
47
  * `{healthy, causes:[{code, issues, detail}], recovery:[cmd]}` for one batch state. `held`: operator-held issues (not a
48
- * stall); `refused`: a refusal record (the launch never started). Pure.
48
+ * stall); `refused`: a refusal record (the launch never started); `resolved` (#5243): issues already
49
+ * resolved on GitHub (merged by hand), counted as good ends. Pure.
49
50
  */
50
- export function evaluateHealth(state, { held = [], refused = null, config = DEFAULT_HEALTH, batchId = "<id>", repo = null } = {}) {
51
+ export function evaluateHealth(state, { held = [], refused = null, config = DEFAULT_HEALTH, batchId = "<id>", repo = null, resolved = [] } = {}) {
51
52
  const causes = [], recovery = [];
52
53
  if (refused) {
53
54
  causes.push({ code: "refused", issues: refused.issues ?? [], detail: refused.message ?? "launch refused" });
@@ -61,7 +62,8 @@ export function evaluateHealth(state, { held = [], refused = null, config = DEFA
61
62
  const results = state?.results ?? {};
62
63
  const outcomeOf = (n) => results[n]?.outcome;
63
64
  // Terminal and not good: a final row not running and not waiting again (a held row stays pending but counts).
64
- const bad = (n) => { const o = outcomeOf(n); return o !== undefined && !GOOD_END.has(o) && !running.has(n) && (!pending.has(n) || o === "held"); };
65
+ const done = new Set([...resolved].map(Number));
66
+ const bad = (n) => { const o = outcomeOf(n); return o !== undefined && !done.has(n) && !GOOD_END.has(o) && !running.has(n) && (!pending.has(n) || o === "held"); };
65
67
  const merged = order.filter((n) => outcomeOf(n) === "merged").length;
66
68
  const failedRoots = rootsOf(state).filter(bad);
67
69
  if (config.rootFailed && failedRoots.length) causes.push({ code: "root-failed", issues: failedRoots, detail: `root ${failedRoots.map((n) => `#${n} ${outcomeOf(n)}`).join(", ")}` });
@@ -109,14 +111,21 @@ export function scheduleLine(batchId, created, checksMin = DEFAULT_HEALTH.checks
109
111
  * One checkpoint: evaluate the batch, persist it, and call `alert(text, health)` on the first unhealthy result only.
110
112
  * @returns the evaluation, plus `alerted` when this call raised the alert
111
113
  */
112
- export async function runCheck({ batch, checkpoint, config = DEFAULT_HEALTH, repo = null, now = () => Date.now(), alert = async () => {} }) {
114
+ export async function runCheck({ batch, checkpoint, config = DEFAULT_HEALTH, repo = null, now = () => Date.now(), alert = async () => {}, resolve = null }) {
113
115
  const state = batch.store.load() ?? {};
114
116
  let held = [];
115
117
  try { held = batch.readHeld?.() ?? []; } catch { held = []; }
116
- const health = evaluateHealth(state, { held, config, batchId: batch.id, repo });
118
+ // #5243: the local rows are a cache; a failed row whose issue GitHub shows as merged by hand is resolved, not failed.
119
+ let resolved = [];
120
+ if (resolve) {
121
+ const res = state.results ?? {}, run = new Set(Object.keys(state.running ?? {}).map(Number));
122
+ 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
+ try { if (cand.length) resolved = (await resolve(cand) ?? []).map(Number); } catch { resolved = []; }
124
+ }
125
+ const health = evaluateHealth(state, { held, config, batchId: batch.id, repo, resolved });
117
126
  const prev = readHealth(batch.dir) ?? {};
118
127
  const at = new Date(now()).toISOString();
119
- const next = { ...prev, checks: { ...(prev.checks ?? {}), [checkpoint]: at }, last: { at, checkpoint, healthy: health.healthy, causes: health.causes, recovery: health.recovery } };
128
+ const next = { ...prev, checks: { ...(prev.checks ?? {}), [checkpoint]: at }, last: { at, checkpoint, healthy: health.healthy, ...(resolved.length ? { resolved } : {}), causes: health.causes, recovery: health.recovery } };
120
129
  const fire = !health.healthy && !prev.alertedAt;
121
130
  if (fire) Object.assign(next, { alertedAt: at, alert: formatAlert({ batchId: batch.id, checkpoint, health }) });
122
131
  try { writeHealth(batch.dir, next); } catch { /* health is advisory */ }
@@ -217,3 +226,101 @@ export function statusLines(root, { now = Date.now(), batch = null } = {}) {
217
226
  for (const r of readRefusals(root, { now })) out.push(` LAUNCH REFUSED ${r.at}: ${String(r.message ?? "").slice(0, 300)}`);
218
227
  return out;
219
228
  }
229
+
230
+ /**
231
+ * #5243: which `[{issue, outcome}]` rows GitHub shows as resolved: the issue is CLOSED with a MERGED closing PR, or a
232
+ * `needs-human` row whose label was removed with a `FORGE:DECISION` comment. Any read failure leaves the row unresolved.
233
+ * @returns issue numbers
234
+ */
235
+ export async function resolvedOnGithub(cands, gh, repo) {
236
+ const out = [];
237
+ for (const { issue, outcome } of cands) {
238
+ try {
239
+ const v = JSON.parse(await gh(["issue", "view", String(issue), "-R", repo, "--json", "state,labels,comments,closedByPullRequestsReferences"]));
240
+ let ok = false;
241
+ if (String(v.state).toUpperCase() === "CLOSED") {
242
+ for (const ref of v.closedByPullRequestsReferences ?? []) {
243
+ const pr = JSON.parse(await gh(["pr", "view", String(ref.number), "-R", repo, "--json", "state"]));
244
+ if (String(pr.state).toUpperCase() === "MERGED") { ok = true; break; }
245
+ }
246
+ } else if (outcome === "needs-human") {
247
+ ok = !(v.labels ?? []).some((l) => l.name === "needs-human") && (v.comments ?? []).some((c) => /<!--\s*FORGE:DECISION/.test(c.body ?? ""));
248
+ }
249
+ if (ok) out.push(issue);
250
+ } catch { /* unresolved */ }
251
+ }
252
+ return out;
253
+ }
254
+
255
+ export const DEFAULT_STALL_MIN = 10;
256
+ /**
257
+ * #5314: dispatch stall. A batch with ready pending issues, free capacity and no progress for `windowMin` minutes. Ready: pending,
258
+ * not held, no retry-at in the future, every in-batch dependency ended well. Independent of the runner (it may be dead), so the
259
+ * schedd polls it. `hosted`: a runner is alive. @returns null (healthy) or `{code, ready, idleMin, hosted, detail}`. Pure.
260
+ */
261
+ export function evaluateDispatchStall(state, { held = [], parallel = null, hosted = false, lastProgressMs = null, now = Date.now(), windowMin = DEFAULT_STALL_MIN, cancelled = false, reported = false } = {}) {
262
+ if (!state || cancelled || reported || lastProgressMs === null) return null;
263
+ if (state.breaker && !state.breaker.transport) return null; // an operator --resume clears it; a re-host would stop again at once
264
+ const order = new Set((state.order ?? []).map(Number)), results = state.results ?? {}, heldSet = new Set(held.map(Number));
265
+ const running = Object.keys(state.running ?? {}).length;
266
+ const k = Number.isInteger(parallel) && parallel > 0 ? parallel : Number.isInteger(state.parallel) && state.parallel > 0 ? state.parallel : 1;
267
+ const ready = (state.pending ?? []).map(Number).filter((n) => !heldSet.has(n) && results[n] === undefined && !(Number(state.notBefore?.[n]) > now)
268
+ && (state.deps?.[n] ?? []).every((d) => !order.has(Number(d)) || Number(d) === n || GOOD_END.has(results[d]?.outcome)));
269
+ const idleMin = Math.floor((now - lastProgressMs) / 60000);
270
+ if (!ready.length || running >= k || idleMin < windowMin) return null;
271
+ return { code: "dispatch-stalled", ready, idleMin, hosted, detail: `${ready.length} ready issue${ready.length === 1 ? "" : "s"} (${list(ready.slice(0, 8))}${ready.length > 8 ? ", …" : ""}) pending with ${k - running} free lane${k - running === 1 ? "" : "s"} and no dispatch for ${idleMin} min; ${hosted ? "the runner is alive but not dispatching" : "no runner hosts the batch"}` };
272
+ }
273
+
274
+ export const FIRST_HOUR_FILE = "first-hour.json";
275
+ export const BATCH_LOG_FILE = "batch.log";
276
+ export const FIRST_HOUR_MIN = 60;
277
+ export const readFirstHour = (dir) => readJson(join(dir, FIRST_HOUR_FILE));
278
+ /** Append one line to the batch's operator-readable log. Best effort. */
279
+ export const appendBatchLog = (dir, text) => { try { appendFileSync(join(dir, BATCH_LOG_FILE), `${text}\n`, { mode: 0o600 }); } catch { /* advisory */ } };
280
+
281
+ /** 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 } = {}) {
283
+ const order = (state?.order ?? []).map(Number), results = state?.results ?? {}, running = Object.keys(state?.running ?? {}).map(Number);
284
+ const merged = order.filter((n) => GOOD_END.has(results[n]?.outcome)), heldSet = new Set(held.map(Number));
285
+ 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`;
287
+ const dispatched = order.filter((n) => results[n] !== undefined || running.includes(n)).length;
288
+ const counts = { total: order.length, dispatched, running: running.length, merged: merged.length, stuck: stuck.length };
289
+ const reasons = [...stuck.map(why), ...(stall ? [stall.detail] : [])];
290
+ const summary = `first hour: ${dispatched}/${order.length} dispatched, ${running.length} running, ${merged.length} merged, ${stuck.length} stuck${reasons.length ? ` (${reasons.slice(0, 6).join("; ")})` : ""}`;
291
+ return { batch: batchId, at: new Date(now).toISOString(), counts, summary, lines: [`batch ${batchId}: ${summary}`, ...reasons.slice(0, 12).map((r) => ` ${r}`)] };
292
+ }
293
+
294
+ /** Persist the first-hour report once (batch dir + `batch.log`); false when it already exists. */
295
+ export function writeFirstHour(batch, report) {
296
+ if (existsSync(join(batch.dir, FIRST_HOUR_FILE))) return false;
297
+ try { writeAtomic(join(batch.dir, FIRST_HOUR_FILE), JSON.stringify(report) + "\n", { private: true }); } catch { return false; }
298
+ for (const l of report.lines) appendBatchLog(batch.dir, `${report.at} ${l}`);
299
+ return true;
300
+ }
301
+
302
+ /** The one needs-you item of a stall: recorded in `health.json` (shown by status) per distinct ready set. @returns true when newly raised */
303
+ export function recordStallAlert(batch, stall, { now = Date.now() } = {}) {
304
+ const sig = stall.ready.join(","), prev = readHealth(batch.dir) ?? {};
305
+ if (prev.stall?.sig === sig) return false;
306
+ const at = new Date(now).toISOString();
307
+ const text = `BATCH UNHEALTHY ${batch.id} (dispatch-stalled)\n cause: dispatch-stalled: ${stall.detail}\n recovery:\n forgedock orchestrate --resume ${batch.id}\n forgedock orchestrate --cancel ${batch.id}`;
308
+ try { writeHealth(batch.dir, { ...prev, stall: { at, sig, detail: stall.detail }, ...(prev.alertedAt ? {} : { alertedAt: at, alert: text }) }); } catch { return false; }
309
+ appendBatchLog(batch.dir, `${at} ${text.split("\n").slice(0, 2).join(" | ")}`);
310
+ return true;
311
+ }
312
+
313
+ /** `sched show` lines: per unfinished batch, its first-hour summary and any dispatch stall. */
314
+ export function summaryLines(root, { now = Date.now() } = {}) {
315
+ const out = [];
316
+ for (const id of listBatches(root)) {
317
+ try {
318
+ const b = openBatch(root, id);
319
+ if (b.readReport() || b.readCancel()) continue;
320
+ const fh = readFirstHour(b.dir), h = readHealth(b.dir);
321
+ if (fh?.summary) out.push(` batch ${id}: ${fh.summary}`);
322
+ if (h?.stall && now - Date.parse(h.stall.at) < 24 * 3600 * 1000) out.push(` batch ${id}: DISPATCH STALLED since ${h.stall.at}: ${h.stall.detail}`);
323
+ } catch { /* an unreadable batch has no line */ }
324
+ }
325
+ return out;
326
+ }
@@ -7,7 +7,8 @@ import { join } from "node:path";
7
7
  import { tmpDir } from "../tests/_tmp.mjs";
8
8
  import { openBatch } from "./batch.mjs";
9
9
  import { DEFAULT_HEALTH, parseHealthConfig, rootsOf, evaluateHealth, formatAlert, runCheck, scheduleChecks, scheduleLine, runNotify, deliverAlert,
10
- recordRefusal, readRefusals, statusLines, REFUSAL_KEEP } from "./batch-health.mjs";
10
+ resolvedOnGithub, recordRefusal, readRefusals, statusLines, REFUSAL_KEEP,
11
+ evaluateDispatchStall, firstHourReport, writeFirstHour, readFirstHour, recordStallAlert, summaryLines } from "./batch-health.mjs";
11
12
 
12
13
  // #1 and #3 are roots; #2 depends on #1, #4 on #3.
13
14
  const base = (results, extra = {}) => ({ order: [1, 2, 3, 4], deps: { 2: [1], 4: [3] }, results, running: {}, pending: [], ...extra });
@@ -154,3 +155,88 @@ describe("#5167 channels and refusals", () => {
154
155
  assert.ok(existsSync(join(root, "refusals.json")));
155
156
  });
156
157
  });
158
+
159
+ describe("#5243 health re-reads GitHub before declaring root-failed", () => {
160
+ const st = base({ 1: { outcome: "needs-human" }, 2: { outcome: "skipped" }, 3: { outcome: "merged" }, 4: { outcome: "merged" } });
161
+ const mkBatch = () => { const dir = tmpDir("bh5243-"); return { id: "b1", dir, store: { load: () => st } }; };
162
+
163
+ it("a root merged by hand is resolved: healthy, no requeue suggestion", async () => {
164
+ const r = await runCheck({ batch: mkBatch(), checkpoint: "T+60", resolve: async (c) => c.map((x) => x.issue) });
165
+ assert.equal(r.healthy, true);
166
+ assert.equal(r.alerted, false);
167
+ assert.ok(!r.recovery.some((x) => /requeue/.test(x)));
168
+ });
169
+
170
+ it("an unresolved root, or a failing resolver, still alerts with the requeue command", async () => {
171
+ for (const resolve of [async () => [], async () => { throw new Error("gh down"); }]) {
172
+ const r = await runCheck({ batch: mkBatch(), checkpoint: "T+60", resolve });
173
+ assert.equal(r.healthy, false);
174
+ assert.ok(r.recovery.some((x) => /--requeue b1 1/.test(x)));
175
+ }
176
+ });
177
+
178
+ it("resolvedOnGithub: closed with merged PR, or needs-human label removed with a FORGE:DECISION", async () => {
179
+ const views = {
180
+ 1: { state: "CLOSED", labels: [], comments: [], closedByPullRequestsReferences: [{ number: 9 }] },
181
+ 2: { state: "CLOSED", labels: [], comments: [], closedByPullRequestsReferences: [{ number: 10 }] },
182
+ 3: { state: "OPEN", labels: [], comments: [{ body: "<!-- FORGE:DECISION x -->" }] },
183
+ 4: { state: "OPEN", labels: [{ name: "needs-human" }], comments: [{ body: "<!-- FORGE:DECISION x -->" }] },
184
+ 5: { state: "OPEN", labels: [], comments: [] },
185
+ };
186
+ const gh = async (a) => { if (a[0] === "pr") return JSON.stringify({ state: a[2] === "9" ? "MERGED" : "CLOSED" }); if (a[2] === "6") throw new Error("boom"); return JSON.stringify(views[a[2]]); };
187
+ const cands = [1, 2, 3, 4, 5, 6].map((issue) => ({ issue, outcome: "needs-human" }));
188
+ assert.deepEqual(await resolvedOnGithub(cands, gh, "o/r"), [1, 3]);
189
+ });
190
+ });
191
+
192
+ describe("#5314 dispatch stall and first-hour report", () => {
193
+ const NOW = 10_000_000, MIN = 60000;
194
+ const st = (extra = {}) => ({ order: [1, 2, 3], deps: { 3: [1] }, results: { 1: { outcome: "merged" } }, running: {}, pending: [2, 3], parallel: 2, ...extra });
195
+ const stall = (state, o = {}) => evaluateDispatchStall(state, { lastProgressMs: NOW - 12 * MIN, now: NOW, windowMin: 10, ...o });
196
+
197
+ it("ready pending issues, a free lane and no progress for the window: stalled, naming the batch's ready issues and who hosts", () => {
198
+ const r = stall(st());
199
+ assert.equal(r.code, "dispatch-stalled");
200
+ assert.deepEqual(r.ready, [2, 3]);
201
+ assert.match(r.detail, /no runner hosts the batch/);
202
+ assert.match(stall(st(), { hosted: true }).detail, /runner is alive but not dispatching/);
203
+ });
204
+
205
+ it("not stalled: recent progress, full lanes, held, retry-at ahead, unmet dependency, cancelled, reported, tripped breaker", () => {
206
+ assert.equal(stall(st(), { lastProgressMs: NOW - 2 * MIN }), null);
207
+ assert.equal(stall(st({ running: { 9: {} }, parallel: 1 })), null);
208
+ assert.equal(stall(st(), { held: [2, 3] }), null);
209
+ assert.equal(stall(st({ notBefore: { 2: NOW + MIN, 3: NOW + MIN } })), null);
210
+ assert.deepEqual(stall(st({ results: {} }))?.ready, [2], "#3 waits on #1");
211
+ assert.equal(stall(st(), { cancelled: true }), null);
212
+ assert.equal(stall(st(), { reported: true }), null);
213
+ assert.equal(stall(st({ breaker: { errors: 3 } })), null);
214
+ assert.equal(stall(st(), { lastProgressMs: null }), null);
215
+ });
216
+
217
+ it("the first-hour report counts dispatched / running / merged / stuck with reasons, is written once, and reaches summaryLines", () => {
218
+ const root = tmpDir("first-hour-"), b = openBatch(root, "b1");
219
+ b.writePlan({ daemon: true, repo: "o/r" });
220
+ const state = st({ running: { 2: {} }, pending: [3], results: { 1: { outcome: "merged" } } });
221
+ b.store.save(state);
222
+ const rep = firstHourReport(state, { batchId: "b1", now: NOW, held: [3] });
223
+ assert.deepEqual(rep.counts, { total: 3, dispatched: 2, running: 1, merged: 1, stuck: 1 });
224
+ assert.match(rep.summary, /2\/3 dispatched, 1 running, 1 merged, 1 stuck \(#3 held\)/);
225
+ assert.equal(writeFirstHour(b, rep), true);
226
+ assert.equal(writeFirstHour(b, rep), false, "once per batch");
227
+ assert.equal(readFirstHour(b.dir).summary, rep.summary);
228
+ assert.match(readFileSync(join(b.dir, "batch.log"), "utf8"), /first hour: 2\/3 dispatched/);
229
+ assert.ok(summaryLines(root, { now: NOW }).some((l) => l.includes("batch b1: first hour")));
230
+ });
231
+
232
+ it("recordStallAlert raises one needs-you item per ready set and statusLines shows it", () => {
233
+ const root = tmpDir("stall-alert-"), b = openBatch(root, "b1");
234
+ b.writePlan({ daemon: true, repo: "o/r" });
235
+ const s1 = stall(st());
236
+ assert.equal(recordStallAlert(b, s1, { now: NOW }), true);
237
+ assert.equal(recordStallAlert(b, s1, { now: NOW }), false);
238
+ assert.equal(recordStallAlert(b, { ...s1, ready: [2] }, { now: NOW }), true, "a different ready set is a new item");
239
+ assert.ok(statusLines(root, { now: Date.now() }).some((l) => /BATCH UNHEALTHY b1/.test(l) || /dispatch-stalled/.test(l)));
240
+ assert.ok(summaryLines(root, { now: Date.parse(new Date(NOW).toISOString()) }).some((l) => /DISPATCH STALLED/.test(l)));
241
+ });
242
+ });
@@ -110,6 +110,39 @@ export function listBatches(root) {
110
110
  return names.filter((n) => ID_RE.test(n) && existsSync(join(root, n, "plan.json"))).sort();
111
111
  }
112
112
 
113
+ /** #5241: a batch whose state has not moved for this long is not counted active (a killed host leaves no report). */
114
+ export const ACTIVE_BATCH_STALE_MS = 3 * 60 * 60 * 1000;
115
+
116
+ /**
117
+ * #5241: the batches of `repo` that own `issue`: `cancelled` ones (a `cancel` file) and `active` ones (no report, not
118
+ * cancelled, state saved within `staleMs`) holding it pending or running. `exceptId` is never counted.
119
+ * @returns {Array<{id:string, cancelled:boolean, running:boolean}>}
120
+ */
121
+ export function batchesOwning(root, repo, issue, { exceptId = null, now = Date.now(), staleMs = ACTIVE_BATCH_STALE_MS } = {}) {
122
+ const out = [];
123
+ for (const id of listBatches(root)) {
124
+ if (id === exceptId) continue;
125
+ let b, plan, st;
126
+ try { b = openBatch(root, id); plan = b.readPlan(); st = b.store.load(); } catch { continue; }
127
+ if (!plan || (repo && plan.repo && plan.repo !== repo) || !st) continue;
128
+ const inOrder = (st.order ?? []).includes(issue);
129
+ if (!inOrder) continue;
130
+ const running = st.running != null && Object.hasOwn(st.running, String(issue));
131
+ if (b.readCancel()) { out.push({ id, cancelled: true, running }); continue; }
132
+ const last = b.lastProgressMs();
133
+ const live = !b.readReport() && last !== null && now - last <= staleMs;
134
+ if (live && (running || (Array.isArray(st.pending) && st.pending.includes(issue)))) out.push({ id, cancelled: false, running });
135
+ }
136
+ return out;
137
+ }
138
+ /** #5241: cancelled batches of `repo` that include `issue` and no live batch runs it (the lease holder is theirs). */
139
+ export const cancelledOwners = (root, repo, issue, exceptId = null, opts = {}) => {
140
+ const all = batchesOwning(root, repo, issue, { ...opts, exceptId });
141
+ return all.some((o) => !o.cancelled && o.running) ? [] : all.filter((o) => o.cancelled).map((o) => o.id);
142
+ };
143
+ /** #5241: the id of an active (uncancelled) batch of `repo` already holding `issue`, else null. */
144
+ export const activeBatchOf = (root, repo, issue, opts = {}) => batchesOwning(root, repo, issue, opts).find((o) => !o.cancelled)?.id ?? null;
145
+
113
146
  /** Handle on one batch directory. */
114
147
  export function openBatch(root, id) {
115
148
  if (!ID_RE.test(String(id ?? ""))) throw new Error(`invalid batch id ${JSON.stringify(id)}`);
@@ -177,7 +210,8 @@ export function openBatch(root, id) {
177
210
  },
178
211
  /**
179
212
  * `--requeue` (#4550): record that each issue returns to pending. Refused: not a positive integer, not in the batch's
180
- * `order`, no terminal result yet (`not terminal`; a final `engine-error` is terminal, #5168), or already requeued and not yet applied. The needs-human label and
213
+ * `order`, no terminal result yet (`not terminal`; a final `engine-error` is terminal, #5168; a quota-paused pending issue is
214
+ * accepted and released, #5203), or already requeued and not yet applied. The needs-human label and
181
215
  * closed checks need GitHub and live in the CLI. @returns {{requeued:number[], refused:Array<{issue, reason}>}}
182
216
  */
183
217
  requeue: (list, { reason = "operator decision", by = "operator" } = {}) => {
@@ -185,13 +219,18 @@ export function openBatch(root, id) {
185
219
  const order = new Set(st.order ?? []), applied = new Set(st.requeueApplied ?? []);
186
220
  const entries = readRequeueFile(f("requeue"));
187
221
  const pend = new Set(entries.filter((e) => !applied.has(requeueKey(e))).map((e) => e.issue));
222
+ // #5203: a quota-paused issue (pending, no result, a `quota` entry) is released by --requeue: its notBefore is cleared
223
+ const quotaPaused = (n) => st.results?.[n] === undefined && Array.isArray(st.pending) && st.pending.includes(n) && !!st.quota?.[n];
224
+ // #5241: a pending issue waiting out a deferral (notBefore) whose lease a cancelled batch of the repo holds is released too
225
+ const leaseOrphaned = (n) => st.results?.[n] === undefined && Array.isArray(st.pending) && st.pending.includes(n) && Number.isFinite(st.notBefore?.[n])
226
+ && cancelledOwners(dirname(dir), readJson(f("plan.json"))?.repo, n, id).length > 0;
188
227
  const requeued = [], refused = [];
189
228
  for (const x of Array.isArray(list) ? list : []) {
190
229
  const n = typeof x === "number" ? x : typeof x === "string" && /^#?\d+$/.test(x.trim()) ? parseInt(x.trim().replace("#", ""), 10) : NaN;
191
230
  if (!Number.isSafeInteger(n) || n < 1) refused.push({ issue: x, reason: "not an integer" });
192
231
  else if (!order.has(n)) refused.push({ issue: n, reason: "not in batch" });
193
232
  else if (pend.has(n)) refused.push({ issue: n, reason: "already requeued" });
194
- else if (!REQUEUABLE(st.results?.[n]?.outcome)) refused.push({ issue: n, reason: "not terminal" });
233
+ else if (!REQUEUABLE(st.results?.[n]?.outcome) && !quotaPaused(n) && !leaseOrphaned(n)) refused.push({ issue: n, reason: "not terminal" });
195
234
  else { pend.add(n); requeued.push(n); }
196
235
  }
197
236
  if (requeued.length) {