forgedock 1.55.1 → 1.57.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 (133) hide show
  1. package/bin/config-schema.mjs +1 -1
  2. package/bin/engine/outcome-codes.mjs +1 -0
  3. package/bin/engine/phases.mjs +4 -3
  4. package/bin/engine-cli.mjs +58 -10
  5. package/bin/forgedock.mjs +52 -3
  6. package/bin/gc.mjs +43 -6
  7. package/bin/help-text.mjs +3 -1
  8. package/bin/lean/batch-health.mjs +5 -1
  9. package/bin/lean/batch-health.test.mjs +7 -1
  10. package/bin/lean/batch.mjs +7 -2
  11. package/bin/lean/batch.test.mjs +45 -0
  12. package/bin/lean/conformance.e2e.test.mjs +3 -2
  13. package/bin/lean/conformance.mjs +88 -17
  14. package/bin/lean/conformance.test.mjs +98 -3
  15. package/bin/lean/decisions.mjs +86 -1
  16. package/bin/lean/decisions.test.mjs +21 -1
  17. package/bin/lean/depcache.mjs +124 -13
  18. package/bin/lean/depcache.test.mjs +121 -3
  19. package/bin/lean/design-gate.mjs +144 -0
  20. package/bin/lean/design-gate.test.mjs +169 -0
  21. package/bin/lean/effects-cap.test.mjs +17 -0
  22. package/bin/lean/effects.mjs +58 -13
  23. package/bin/lean/heavy.mjs +25 -8
  24. package/bin/lean/hostload.test.mjs +28 -0
  25. package/bin/lean/intake.mjs +97 -0
  26. package/bin/lean/intake.test.mjs +105 -0
  27. package/bin/lean/interfaces.mjs +181 -0
  28. package/bin/lean/interfaces.test.mjs +192 -0
  29. package/bin/lean/issuewatch-install.mjs +52 -12
  30. package/bin/lean/issuewatch-install.test.mjs +50 -0
  31. package/bin/lean/issuewatch-parity.mjs +12 -2
  32. package/bin/lean/issuewatch-parity.test.mjs +26 -0
  33. package/bin/lean/issuewatch-reconcile.mjs +29 -1
  34. package/bin/lean/issuewatch-reconcile.test.mjs +21 -0
  35. package/bin/lean/issuewatch.mjs +34 -3
  36. package/bin/lean/issuewatch.test.mjs +49 -1
  37. package/bin/lean/lanecheck.test.mjs +15 -4
  38. package/bin/lean/lean.mjs +80 -25
  39. package/bin/lean/lean.test.mjs +149 -3
  40. package/bin/lean/orchestrate-blocked.test.mjs +18 -2
  41. package/bin/lean/orchestrate-owned.test.mjs +14 -5
  42. package/bin/lean/orchestrate.mjs +26 -4
  43. package/bin/lean/orphan-pr.mjs +125 -0
  44. package/bin/lean/orphan-pr.test.mjs +145 -0
  45. package/bin/lean/pagegate.mjs +35 -12
  46. package/bin/lean/pagegate.test.mjs +39 -1
  47. package/bin/lean/preflight.mjs +35 -1
  48. package/bin/lean/preflight.test.mjs +27 -1
  49. package/bin/lean/prompts.mjs +2 -1
  50. package/bin/lean/reap.test.mjs +39 -0
  51. package/bin/lean/recovery.test.mjs +25 -0
  52. package/bin/lean/release-config.mjs +158 -0
  53. package/bin/lean/release-config.test.mjs +109 -0
  54. package/bin/lean/release-control.mjs +148 -0
  55. package/bin/lean/release-control.test.mjs +143 -0
  56. package/bin/lean/release-fence.mjs +50 -0
  57. package/bin/lean/release-fence.test.mjs +105 -0
  58. package/bin/lean/release-flakes.mjs +139 -0
  59. package/bin/lean/release-flakes.test.mjs +116 -0
  60. package/bin/lean/release-ledger.mjs +160 -0
  61. package/bin/lean/release-ledger.test.mjs +226 -0
  62. package/bin/lean/release-minutes.mjs +92 -0
  63. package/bin/lean/release-minutes.test.mjs +99 -0
  64. package/bin/lean/release-nightly.mjs +75 -0
  65. package/bin/lean/release-nightly.test.mjs +48 -0
  66. package/bin/lean/release-postmerge.mjs +45 -21
  67. package/bin/lean/release-review.e2e.test.mjs +1 -0
  68. package/bin/lean/release-review.mjs +54 -7
  69. package/bin/lean/release-review.test.mjs +76 -7
  70. package/bin/lean/release-unitmap.mjs +35 -0
  71. package/bin/lean/release-unitmap.test.mjs +41 -0
  72. package/bin/lean/release.mjs +177 -19
  73. package/bin/lean/release.test.mjs +80 -16
  74. package/bin/lean/render.mjs +3 -1
  75. package/bin/lean/run-issue-placement.test.mjs +82 -0
  76. package/bin/lean/sandbox-remote.mjs +16 -0
  77. package/bin/lean/schedd.mjs +1 -1
  78. package/bin/lean/seam.mjs +115 -0
  79. package/bin/lean/seam.test.mjs +118 -0
  80. package/bin/lean/selftest-journey.mjs +40 -2
  81. package/bin/lean/selftest-journey.test.mjs +43 -3
  82. package/bin/lean/statuscomment.mjs +168 -0
  83. package/bin/lean/statuscomment.test.mjs +133 -0
  84. package/bin/lean/ui-quality.mjs +57 -0
  85. package/bin/lean/ui-quality.test.mjs +55 -0
  86. package/bin/lean/visual-gate.test.mjs +63 -0
  87. package/bin/pool/agent.mjs +16 -2
  88. package/bin/pool/router.mjs +5 -1
  89. package/bin/review-staging.mjs +8 -5
  90. package/bin/stats/card.mjs +117 -0
  91. package/bin/stats/card.test.mjs +109 -0
  92. package/bin/stats/conformance-outcomes.test.mjs +2 -1
  93. package/bin/stats/depth.mjs +1 -1
  94. package/bin/stats/gh-retry.test.mjs +152 -0
  95. package/bin/stats/github-source.mjs +147 -14
  96. package/bin/stats/index.mjs +35 -2
  97. package/bin/stats/stats.test.mjs +31 -3
  98. package/bin/vendor/js-yaml/LICENSE +21 -0
  99. package/bin/vendor/js-yaml/PIN.md +7 -0
  100. package/bin/vendor/js-yaml/js-yaml.mjs +3851 -0
  101. package/commands/design-render-critique-loop.md +2 -0
  102. package/commands/design.md +2 -0
  103. package/commands/incident-response.md +4 -0
  104. package/commands/issue.md +1 -1
  105. package/commands/milestone.md +1 -1
  106. package/commands/pipeline-status.md +13 -0
  107. package/commands/review-pr-agents/frontend.md +1 -0
  108. package/commands/review-pr-staging.md +5 -0
  109. package/docs/CONFIG.md +75 -1
  110. package/docs/ISSUE-WATCH.md +7 -0
  111. package/docs/OUTCOME-CODES.md +1 -0
  112. package/docs/STATS.md +10 -0
  113. package/docs/design/visual-gate.md +25 -0
  114. package/docs/eval/adversarial-bench.md +2 -2
  115. package/docs/eval/corpus/adversarial-v1.json +3 -3
  116. package/docs/site/start-a-new-project.md +7 -0
  117. package/docs/spec/forge-protocol-v1.md +31 -0
  118. package/package.json +1 -1
  119. package/pool/README.md +2 -0
  120. package/scripts/acceptance-red-green.sh +15 -1
  121. package/scripts/acceptance-red-green.test.sh +12 -0
  122. package/scripts/bench-adversarial.mjs +4 -0
  123. package/scripts/bench-lightlane.mjs +4 -1
  124. package/scripts/bootstrap-create.mjs +8 -2
  125. package/scripts/ci-local.test.sh +3 -3
  126. package/scripts/fixtures/ci-local/gha-dorny/.github/workflows/ci.yml +4 -0
  127. package/scripts/plan-validate-live.mjs +9 -6
  128. package/scripts/review-prepare.sh +7 -1
  129. package/scripts/review-roster.sh +5 -2
  130. package/scripts/review-roster.test.sh +9 -0
  131. package/scripts/visual-gate.mjs +64 -0
  132. package/templates/bootstrap/technical-spike.md +17 -0
  133. package/templates/contracts/seam-check.mjs +236 -0
@@ -1,11 +1,13 @@
1
1
  // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
2
  // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ import { parseStatus } from "./statuscomment.mjs";
3
4
  import { foldRegression } from "./baselines.mjs";
4
5
  import { describe, it } from "node:test";
5
6
  import { laneBackendId } from "./limits.mjs";
6
7
  import { parseExperiment, assignArm } from "../experiment.mjs";
7
8
  import assert from "node:assert/strict";
8
9
  import { tmpDir } from "../tests/_tmp.mjs";
10
+ import { normaliseDecision, writeDecisionIndex } from "./decisions.mjs"; // #5338
9
11
  import { execFileSync } from "node:child_process";
10
12
  import { writeFileSync, existsSync, readFileSync, mkdirSync, symlinkSync, readdirSync, chmodSync } from "node:fs";
11
13
  import { join } from "node:path";
@@ -71,9 +73,18 @@ const bad = (note = "src/foo.js:9 still wrong", verdict = "NONCONFORMING") => co
71
73
  const genericPass = () => fence({ verdict: "PASS", fixes_issue: true, regression: false, reason: "looks good" });
72
74
 
73
75
  /** In-memory world with fake gh, git, fs and runner. */
76
+ /** #5592: `w.comments` stays the list of logical per-marker comments (what the lane wrote), whether it posted them or edited them into the FORGE:STATUS comment. */
77
+ function statusLogical(w, body) {
78
+ w.statusBody = body;
79
+ for (const [key, { markers, text }] of parseStatus(body)) {
80
+ if (w.statusSections[key] === text) continue;
81
+ w.statusSections[key] = text;
82
+ w.comments.push(`${markers.map((m) => `<!-- ${m} -->`).join("\n")}\n${text}`);
83
+ }
84
+ }
74
85
  function world(o = {}) {
75
86
  const w = {
76
- comments: [], labels: [], closed: [], edits: [], prs: [], merges: [], calls: [], telemetry: [], files: {}, head: "aaaa1111aaaa1111", followups: [], prEdits: [], patches: [],
87
+ comments: [], rawComments: [], statusPatches: [], statusSections: {}, labels: [], closed: [], edits: [], prs: [], merges: [], calls: [], telemetry: [], files: {}, head: "aaaa1111aaaa1111", followups: [], prEdits: [], patches: [],
77
88
  contract: o.contract ?? CONTRACT, issueComments: o.issueComments, issueStates: o.issueStates,
78
89
  changed: o.changed ?? ["src/foo.js", "test/foo.test.js"], reviews: [...(o.reviews ?? [])], waits: [...(o.waits ?? [])], clock: 0,
79
90
  result: o.result ?? { status: "fixed", summary: "fixed foo", evidence: [], tests: ["test/foo.test.js"] },
@@ -91,17 +102,19 @@ function world(o = {}) {
91
102
  const k = a.slice(0, 2).join(" ");
92
103
  if (opts?.env) (w.ghEnvs ??= []).push(opts.env);
93
104
  if (k === "pr view" && a.at(-1) === "state" && a.at(-2) === "--json") return JSON.stringify({ state: o.prState ?? "OPEN" });
105
+ if (a[0] === "api" && a.includes("PATCH") && a.some((x) => /\/comments\/9000$/.test(x))) { statusLogical(w, a[a.indexOf("-f") + 1].replace(/^body=/, "")); w.statusPatches.push(a); return "{}"; } // #5592: the one FORGE:STATUS comment
94
106
  if (a[0] === "api" && a.includes("PATCH")) { w.patches.push(a); return "{}"; }
95
107
  if (a[0] === "api") return a.some((x) => /\/comments$/.test(x)) ? (w.issueComments ?? []).map((c) => JSON.stringify(c)).join("\n") : "";
96
108
  if (k === "pr list") return JSON.stringify(w.prList);
97
109
  if (k === "repo view") return `${o.defaultBranch ?? "main"}\n`;
98
110
  if (k === "issue view" && a.includes("milestone")) { w.seq.push("lane"); return JSON.stringify({ milestone: o.milestone ? { title: o.milestone } : null }); }
99
- if (k === "issue view" && o.issueBodies && a[2] === "7" && a.some((x) => String(x).startsWith("number,title,body,state,comments"))) { const b = o.issueBodies.length > 1 ? o.issueBodies.shift() : o.issueBodies[0]; return JSON.stringify({ number: 7, title: o.title ?? "foo breaks", body: b, state: "OPEN", comments: o.viewComments ?? [] }); }
111
+ if (k === "issue view" && o.issueBodies && a[2] === "7" && a.some((x) => String(x).startsWith("number,title,body,state,comments"))) { const b = o.issueBodies.length > 1 ? o.issueBodies.shift() : o.issueBodies[0]; return JSON.stringify({ number: 7, title: o.title ?? "foo breaks", body: b, state: "OPEN", comments: o.viewComments ?? [], ...(o.labels ? { labels: o.labels } : {}) }); }
100
112
  if (k === "issue view") return JSON.stringify({ number: Number(a[2]), title: a[2] === "7" && o.title ? o.title : "foo breaks", body: a[2] === "7" && o.body ? o.body : ISSUE_BODY, state: w.issueStates?.[a[2]] ?? "OPEN", comments: [], ...(o.labels && a[2] === "7" ? { labels: o.labels } : {}) });
101
113
  if (k === "pr edit") { w.prEdits.push(a); return ""; }
102
114
  if (k === "label create") { w.labelCreates = [...(w.labelCreates ?? []), a]; return ""; }
103
115
  if (k === "issue comment" && w.commentErrors.length) throw new Error(w.commentErrors.shift());
104
- if (k === "issue comment") { w.comments.push(a[a.indexOf("--body") + 1]); w.seq.push("comment"); return `https://github.com/o/r/issues/7#issuecomment-${w.comments.length}\n`; }
116
+ if (k === "issue comment" && a[a.indexOf("--body") + 1].startsWith("<!-- FORGE:STATUS -->")) { w.rawComments.push(a[a.indexOf("--body") + 1]); statusLogical(w, a[a.indexOf("--body") + 1]); w.seq.push("comment"); return "https://github.com/o/r/issues/7#issuecomment-9000\n"; }
117
+ if (k === "issue comment") { w.comments.push(a[a.indexOf("--body") + 1]); w.rawComments.push(a[a.indexOf("--body") + 1]); w.seq.push("comment"); return `https://github.com/o/r/issues/7#issuecomment-${w.comments.length}\n`; }
105
118
  if (k === "issue close") { w.closed.push(a); w.seq.push("close"); return ""; }
106
119
  if (k === "issue edit") { w.edits.push(a); return ""; }
107
120
  if (k === "pr create") { w.prs.push(a); w.seq.push("pr"); return "https://github.com/o/r/pull/77\n"; }
@@ -295,6 +308,16 @@ describe("core work-on", () => {
295
308
  assert.equal(reviewers(w).length, 0);
296
309
  });
297
310
 
311
+ it("#5518 already-fixed on a resumed lane closes the issue: the lane's own open PR is not a close blocker, another own PR still is", async () => {
312
+ const own = { number: 77, headRefOid: "x", headRefName: "feat/issue-7-lean", baseRefName: "staging", body: "Closes #7" };
313
+ const w = world({ changed: [], prList: [own], remote: "abc\trefs/heads/feat/issue-7-lean", result: { status: "already-fixed", summary: "done upstream", evidence: ["a.js:1"], tests: [] } });
314
+ assert.equal((await run(w)).terminalReason, "invalid");
315
+ assert.deepEqual(w.closed.map((a) => a[a.indexOf("--reason") + 1]), ["completed"]);
316
+ const w2 = world({ changed: [], prList: [own, { number: 78, headRefName: "feat/other", body: "<!-- FORGE:ISSUE_PR issue=7 -->" }], remote: "abc\trefs/heads/feat/issue-7-lean", result: { status: "already-fixed", summary: "done upstream", evidence: ["a.js:1"], tests: [] } });
317
+ await run(w2);
318
+ assert.equal(w2.closed.length, 0, "a different open PR for the issue still blocks");
319
+ });
320
+
298
321
  it("already-fixed with evidence also closes, as completed (#5152)", async () => {
299
322
  const w = world({ changed: [], result: { status: "already-fixed", summary: "done upstream", evidence: ["a.js:1"], tests: [] } });
300
323
  assert.equal((await run(w)).terminalReason, "invalid");
@@ -1857,6 +1880,31 @@ describe("conformance shadow mode (the default)", () => {
1857
1880
  assert.equal(readdirSync(dir).length, 1);
1858
1881
  } finally { if (prev === undefined) delete process.env.FORGEDOCK_DECISIONS_DIR; else process.env.FORGEDOCK_DECISIONS_DIR = prev; }
1859
1882
  });
1883
+ it("#5338 a merged supersedes decision on an interface reopens its closed consumers, notifies open ones and files one issue per named consumer", async () => {
1884
+ const dir = tmpDir("ifc-"); const prev = process.env.FORGEDOCK_DECISIONS_DIR; process.env.FORGEDOCK_DECISIONS_DIR = dir;
1885
+ try {
1886
+ const seeded = normaliseDecision({ id: "i40-1", choice: "Interface web -> api: POST /v1/search", anchors: ["src/"], issue: 40, consumers: ["#12", "#13", "search-sdk"], seam: { kind: "payload", auth: "k", payload: { fields: ["q"] }, provider: ["src/"], consumer: ["web/"] } });
1887
+ writeDecisionIndex("o/r", [seeded]);
1888
+ const amendments = [{ kind: "decision", why: "v2", decision: { choice: "Interface web -> api: POST /v2/search", anchors: ["src/db.ts"], supersedes: "i40-1" } }];
1889
+ const w = world({ amendments, issueStates: { 12: "CLOSED", 13: "OPEN" } });
1890
+ const base = w.io.gh, calls = [];
1891
+ w.io.gh = async (a, opts) => {
1892
+ const k = a.slice(0, 2).join(" ");
1893
+ if (k === "issue reopen") { calls.push(a.join(" ")); return ""; }
1894
+ if (k === "issue list") return "[]";
1895
+ if (k === "issue create") { calls.push(a.join(" ")); return "https://github.com/o/r/issues/99\n"; }
1896
+ return base(a, opts);
1897
+ };
1898
+ const r = await runShadow(w);
1899
+ assert.equal(r.terminalReason, "merged");
1900
+ assert.ok(calls.includes("issue reopen 12 -R o/r"), "the closed consumer is reopened");
1901
+ assert.ok(!calls.some((c) => c.startsWith("issue reopen 13")), "an open consumer is only told");
1902
+ assert.ok(calls.some((c) => c.startsWith("issue create") && /Adapt search-sdk to interface change/.test(c)), "one issue for the named consumer");
1903
+ assert.ok(w.comments.some((c) => c.includes("FORGE:INTERFACE_CHANGED") && c.includes("consumer=#12")));
1904
+ assert.ok(w.comments.some((c) => c.includes("FORGE:INTERFACE_CHANGED") && c.includes("consumer=#13")));
1905
+ assert.ok(w.comments.some((c) => /Interface i40-1 superseded by d\S+: #12 reopened #12, #13 notified #13, search-sdk filed #99/.test(c)), "the trajectory records it");
1906
+ } finally { if (prev === undefined) delete process.env.FORGEDOCK_DECISIONS_DIR; else process.env.FORGEDOCK_DECISIONS_DIR = prev; }
1907
+ });
1860
1908
  it("#4160 scope creep found by the precheck stays recorded-only in shadow", async () => {
1861
1909
  const w = world({ changed: ["src/foo.js", "src/billing.js", "test/foo.test.js"], reviews: [conf({}, CONTRACT, ["src/foo.js", "src/billing.js", "test/foo.test.js"])] });
1862
1910
  assert.equal((await runShadow(w)).terminalReason, "merged");
@@ -2271,6 +2319,14 @@ describe("bug lanes freeze a red-green repro_test (#4271)", () => {
2271
2319
  }
2272
2320
  });
2273
2321
 
2322
+ it("#5544 test-only fix whose base version fails is merged, not already-fixed", async () => {
2323
+ const contract = { ...CONTRACT, repro_test: RT, deliverables: [{ id: "D1", path: "test/foo.test.js", change: "fix the test", requirements: ["R1"] }] }; // the bug is in the test itself
2324
+ const w = rworld([{ base: "RAN", head: "RAN", pristine: "FAILED" }], { changed: ["test/foo.test.js"], contract });
2325
+ const r = await run(w);
2326
+ assert.equal(r.terminalReason, "merged"); assert.equal(w.merges.length, 1);
2327
+ assert.equal(w.closed.some((c) => /Already fixed on the base/.test(c.join(" "))), false, "not closed as already fixed");
2328
+ });
2329
+
2274
2330
  it("a repro test the harness cannot run on head (or no harness result) is env.repro_unrunnable: recoverable, no resume, no reviewer (#4334)", async () => {
2275
2331
  for (const conformance of ["enforce", "shadow"]) {
2276
2332
  for (const rg of [{ base: "SKIPPED", head: "UNRUNNABLE" }, null]) {
@@ -8567,3 +8623,93 @@ describe("#5469: --adopt takes over a hand-built open PR", () => {
8567
8623
  assert.equal(r.terminalReason, "merged");
8568
8624
  });
8569
8625
  });
8626
+
8627
+ describe("design gate routing in the lane (#5330 R11, R13, R15)", () => {
8628
+ const PAGE = "web/app/hands/page.tsx";
8629
+ const pageContract = { ...CONTRACT, deliverables: [{ id: "D1", path: PAGE, change: "new hands page", requirements: ["R1"] }] };
8630
+ const dg = (gate = "blocking") => ({ system: [], routes: ["web/app/**/page.tsx"], exclude: [], gate, specLabel: "design:approved", neededLabel: "design:needed", viewports: [390, 1440], requireVisual: true });
8631
+ const mk = (o = {}) => world({ contract: pageContract, changed: [PAGE, "test/foo.test.js"], reviews: [conf({}, pageContract, [PAGE, "test/foo.test.js"])], ...o });
8632
+
8633
+ it("blocking: a predicted new page under design.routes with no FORGE:DESIGN_SPEC stops pending /design, before any build", async () => {
8634
+ const w = mk(), r = await run(w, { designConfig: dg("blocking") });
8635
+ assert.equal(r.terminalReason, "needs-human");
8636
+ assert.equal(r.code, OUTCOME_CODES.DESIGN_SPEC_REQUIRED);
8637
+ assert.ok(w.comments.some((c) => c.includes("FORGE:NEEDS_HUMAN") && /Run \/design/.test(c) && c.includes(PAGE)));
8638
+ assert.equal(builders(w).length, 1, "only the plan call ran; the implement call never started");
8639
+ });
8640
+
8641
+ it("the design:approved label lifts the hold: the lane builds", async () => {
8642
+ const w = mk({ labels: [{ name: "design:approved" }] }), r = await run(w, { designConfig: dg("blocking") });
8643
+ assert.notEqual(r.code, OUTCOME_CODES.DESIGN_SPEC_REQUIRED);
8644
+ assert.ok(builders(w).length >= 2);
8645
+ });
8646
+
8647
+ it("advisory: routed to /design in the implement prompt, never blocked", async () => {
8648
+ const w = mk(), r = await run(w, { designConfig: dg("advisory") });
8649
+ assert.notEqual(r.code, OUTCOME_CODES.DESIGN_SPEC_REQUIRED);
8650
+ assert.ok(builders(w).some((c) => /Design gate: page web\/app\/hands\/page\.tsx/.test(c[4])));
8651
+ });
8652
+
8653
+ it("opt-in: with no design.routes the lane is today's (no design prompt, no block)", async () => {
8654
+ for (const extra of [{}, { designConfig: { ...dg(), routes: [] } }]) {
8655
+ const w = mk(), r = await run(w, extra);
8656
+ assert.notEqual(r.code, OUTCOME_CODES.DESIGN_SPEC_REQUIRED);
8657
+ assert.ok(!builders(w).some((c) => /Design gate:/.test(c[4])));
8658
+ }
8659
+ });
8660
+ });
8661
+
8662
+ describe("#5592 (8) comment and label spam", () => {
8663
+ const BOTC = { author: { login: "rapiercraft-forgedock" }, authorAssociation: "CONTRIBUTOR" };
8664
+ const SEP = "<!-- FORGE:STATUS:SEP -->";
8665
+ const oldStatus = `<!-- FORGE:STATUS -->\n${SEP}\n<!-- FORGE:STARTED -->\nStarted work on #7 (base \`staging\`).\n${SEP}\n<!-- FORGE:TRAJECTORY -->\n<!-- FORGE:WORK-ON -->\nold run trajectory`;
8666
+ const statusComments = (w) => w.rawComments.filter((c) => c.startsWith("<!-- FORGE:STATUS -->"));
8667
+
8668
+ it("a fresh run puts STARTED, TRAJECTORY (and LANE_BRANCH/CONTEXT/DECISION) into ONE status comment, edited in place", async () => {
8669
+ const w = world();
8670
+ const r = await run(w);
8671
+ assert.equal(r.terminalReason, "merged");
8672
+ assert.equal(statusComments(w).length, 1, "the status comment is created once");
8673
+ assert.ok(w.statusPatches.length >= 1, "later machine-state markers PATCH it");
8674
+ const body = w.statusBody;
8675
+ assert.match(body, /<!-- FORGE:STARTED -->\nStarted work on #7/);
8676
+ assert.match(body, /<!-- FORGE:TRAJECTORY -->\n<!-- FORGE:WORK-ON -->/);
8677
+ assert.ok(!w.rawComments.some((c) => c.startsWith("<!-- FORGE:STARTED") || c.startsWith("<!-- FORGE:TRAJECTORY")), "no separate STARTED / TRAJECTORY comment");
8678
+ assert.ok(w.rawComments.length <= 10, `a run posts at most 10 comments, got ${w.rawComments.length}: ${w.rawComments.map((c) => c.split("\n")[0]).join(" | ")}`);
8679
+ });
8680
+
8681
+ it("a requeued run edits the existing trusted status comment: STARTED and TRAJECTORY are replaced, nothing new is posted for them", async () => {
8682
+ const w = world({ issueBodies: [ISSUE_BODY], viewComments: [{ ...BOTC, url: "https://github.com/o/r/issues/7#issuecomment-9000", body: oldStatus }] });
8683
+ w.statusSections = {};
8684
+ const r = await run(w);
8685
+ assert.equal(r.terminalReason, "merged");
8686
+ assert.equal(statusComments(w).length, 0, "no second status comment");
8687
+ assert.ok(w.statusPatches.length >= 2);
8688
+ assert.doesNotMatch(w.statusBody, /old run trajectory/, "the newest run's trajectory replaced the old one");
8689
+ assert.equal((w.statusBody.match(/<!-- FORGE:TRAJECTORY -->/g) ?? []).length, 1);
8690
+ });
8691
+
8692
+ it("an untrusted comment carrying the status marker is never edited", async () => {
8693
+ const w = world({ issueBodies: [ISSUE_BODY], viewComments: [{ author: { login: "drive-by" }, authorAssociation: "NONE", url: "https://github.com/o/r/issues/7#issuecomment-9000", body: oldStatus }] });
8694
+ await run(w);
8695
+ assert.equal(statusComments(w).length, 1, "a fresh status comment is posted instead");
8696
+ assert.ok(!w.statusPatches.some((a) => a.some((x) => /comments\/9000$/.test(x)) && false));
8697
+ });
8698
+
8699
+ it("start clears needs-human, needs-human:external, parked:* and remediation-queue; other labels stay", async () => {
8700
+ const w = world({ issueBodies: [ISSUE_BODY], labels: [{ name: "bug" }, { name: "needs-human" }, { name: "needs-human:external" }, { name: "parked:ci.red" }, { name: "remediation-queue" }] });
8701
+ await run(w);
8702
+ const rm = w.edits.find((e) => e.includes("--remove-label") && e.some((x) => /needs-human/.test(x)));
8703
+ assert.ok(rm, "labels cleared");
8704
+ assert.deepEqual(rm[rm.indexOf("--remove-label") + 1].split(","), ["needs-human", "needs-human:external", "parked:ci.red", "remediation-queue"]);
8705
+ });
8706
+
8707
+ it("a merged run re-reads the labels and clears a parked label added meanwhile", async () => {
8708
+ const w = world();
8709
+ const gh = w.io.gh;
8710
+ w.io.gh = async (a, o) => (a[0] === "issue" && a[1] === "view" && a.includes("labels") && a[a.indexOf("--json") + 1] === "labels" ? JSON.stringify({ labels: [{ name: "parked:ci.red" }] }) : gh(a, o));
8711
+ const r = await run(w);
8712
+ assert.equal(r.terminalReason, "merged");
8713
+ assert.ok(w.edits.some((e) => e.join(" ") === "issue edit 7 -R o/r --remove-label parked:ci.red"));
8714
+ });
8715
+ });
@@ -42,7 +42,7 @@ describe("#4773: Blocked by edges and the blocked label", () => {
42
42
  it("a blocked-labelled issue is admitted but not dispatched; removing the label releases it on the next tick", async () => {
43
43
  let blocked = [1];
44
44
  const started = [], log = [];
45
- const done = orchestrate({ issues: [1, 2], parallel: 3, pollMs: 5, readBody: async () => "", getBlocked: async () => blocked, onUpdate: (r) => log.push(r),
45
+ const done = orchestrate({ issues: [1, 2], parallel: 3, pollMs: 5, readBody: async () => "", blockedRefreshMs: 0, getBlocked: async () => blocked, onUpdate: (r) => log.push(r),
46
46
  runOne: async (n) => { started.push(n); return merged; } });
47
47
  await until(() => started.includes(2));
48
48
  await new Promise((r) => setTimeout(r, 40));
@@ -57,7 +57,7 @@ describe("#4773: Blocked by edges and the blocked label", () => {
57
57
  it("a failed label read keeps the last set instead of releasing", async () => {
58
58
  let fail = false, set = [1], reads = 0;
59
59
  const started = [];
60
- const done = orchestrate({ issues: [1], parallel: 1, pollMs: 5, readBody: async () => "", getBlocked: async () => { reads++; if (fail) throw new Error("gh down"); return set; },
60
+ const done = orchestrate({ issues: [1], parallel: 1, pollMs: 5, readBody: async () => "", blockedRefreshMs: 0, getBlocked: async () => { reads++; if (fail) throw new Error("gh down"); return set; },
61
61
  runOne: async (n) => { started.push(n); return merged; } });
62
62
  await until(() => reads > 0);
63
63
  fail = true;
@@ -166,4 +166,20 @@ describe("#5162: failed roots hold their subtree; only real cycles are cycles",
166
166
  const lines = formatOutcomeLists([{ issue: 1, outcome: "engine-error" }, { issue: 2, outcome: "held", root: 1 }, { issue: 3, outcome: "held", root: 1 }]);
167
167
  assert.ok(lines.some((l) => /held subtree: #1 \(engine-error\) holds #2 #3; release: forgedock orchestrate --requeue <batch> 1/.test(l)), lines.join("\n"));
168
168
  });
169
+
170
+ it("the blocked-label list is read at most once per blockedRefreshMs, not on every pass", async () => {
171
+ let reads = 0, t = 0;
172
+ const started = [];
173
+ let open;
174
+ const g = new Promise((r) => { open = r; });
175
+ const done = orchestrate({ issues: [1, 2], parallel: 1, pollMs: 5, now: () => t, blockedRefreshMs: 60000, readBody: async () => "",
176
+ getBlocked: async () => { reads++; return []; }, runOne: async (n) => { started.push(n); if (n === 1) await g; return merged; } });
177
+ await until(() => started.includes(1));
178
+ await new Promise((r) => setTimeout(r, 60));
179
+ assert.equal(reads, 1, "many passes inside the window make one read");
180
+ t = 60001;
181
+ open();
182
+ await done;
183
+ assert.ok(reads >= 2, "a pass after the window reads again");
184
+ });
169
185
  });
@@ -43,15 +43,24 @@ describe("cross-batch ownership (#5471)", () => {
43
43
  assert.equal(ownerOf(root, "o/r", 6, "bB"), null);
44
44
  assert.deepEqual(b.readAdded(), [5, 6]);
45
45
  });
46
- it("requeue refuses an issue another live batch runs, held counts as owned", async () => {
46
+ it("requeue refuses an issue another live batch runs; a batch that only holds it does not own it (#5592)", async () => {
47
47
  const root = tmpDir("owned-requeue-");
48
48
  seed(root, "bA", { order: [5, 7], pending: [7], running: { 5: {} }, held: [7] });
49
49
  const b = seed(root, "bB", { order: [5, 7], results: { 5: { outcome: "needs-human" }, 7: { outcome: "needs-human" } } });
50
- assert.equal(ownerOf(root, "o/r", 7, "bB"), "bA");
50
+ assert.equal(ownerOf(root, "o/r", 7, "bB"), null, "held only: not an owner");
51
51
  const res = await queued(quiet(() => orchestrateFromCli(["--requeue", "bB", "5", "7", "--reason", "r"], { batchRoot: root, io })));
52
- assert.deepEqual(res.requeued, []);
53
- assert.deepEqual(res.refused.map((x) => [x.issue, x.reason]), [[5, "owned by bA"], [7, "owned by bA"]]);
54
- assert.deepEqual(b.readRequeued(), []);
52
+ assert.deepEqual(res.requeued, [7]);
53
+ assert.deepEqual(res.refused.map((x) => [x.issue, x.reason]), [[5, "owned by bA"]]);
54
+ assert.deepEqual(b.readRequeued().map((e) => e.issue), [7]);
55
+ });
56
+ it("#5592: held in A, force-started in B: B requeues it; A's refusal names B instead of a bare 'not terminal'", async () => {
57
+ const root = tmpDir("owned-moved-");
58
+ const a = seed(root, "bA", { order: [7], pending: [7], held: [7] });
59
+ seed(root, "bB", { order: [7], results: { 7: { outcome: "needs-human" } } });
60
+ const res = await queued(quiet(() => orchestrateFromCli(["--requeue", "bB", "7", "--reason", "r"], { batchRoot: root, io })));
61
+ assert.deepEqual(res.requeued, [7]);
62
+ seed(root, "bC", { order: [7], running: { 7: {} } });
63
+ assert.deepEqual(a.requeue([7]).refused.map((x) => x.reason), ["not terminal: held here, run by bC; requeue it there"]);
55
64
  });
56
65
  it("dispatch defers an issue another batch runs (or holds pending with a lower id) and admits it once the owner is done", async () => {
57
66
  const root = tmpDir("owned-dispatch-");
@@ -308,7 +308,7 @@ const toMap = (o) => new Map(Object.entries(o ?? {}).map(([k, v]) => [Number(k),
308
308
  /**
309
309
  * @returns {Promise<Array<{issue:number, outcome:string, pr:?number, cost_usd:number, minutes:number, detail?:string}>>}
310
310
  */
311
- export async function orchestrate({ issues, parallel = 3, runOne, readBody, prefilter = null, resolveLane = null, now = () => Date.now(), onUpdate = () => {}, onCrossLane = () => {},
311
+ export async function orchestrate({ issues, parallel = 3, runOne, readBody, prefilter = null, resolveLane = null, now = () => Date.now(), blockedRefreshMs = 60000, onUpdate = () => {}, onCrossLane = () => {},
312
312
  store = null, adopt = null, getParallel = null, getAdded = null, getRequeued = null, breaker = null, maxDeferrals = DEFAULT_MAX_DEFERRALS, sleep = cancellableSleep, pollMs = 5000,
313
313
  classify = null, maintenance = null, limits = null, identity = () => "default", batchId = null, drift = null, integration = null, sched = null, priorityOf = null, remote = null, beforeAdmit = null, preflight = null,
314
314
  recovery = null, decide = () => {}, conflicting = null, relabelNeedsHuman = null, onExit = null, issueLabels = null, issueState = null, getCancelled = null, getHeld = null, expireHolds = null, getHoldInfo = null, getBlocked = null, trusted = null, getGates = null, stopLane = null, releaseLease = null, stopRetryMs = STOP_RETRY_MS, stopTimeoutMs = STOP_TIMEOUT_MS,
@@ -415,6 +415,9 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
415
415
  const mechMax = recoveryMax && Number.isInteger(recovery?.mechanicalMaxAttempts) && recovery.mechanicalMaxAttempts > 0 ? Math.max(recovery.mechanicalMaxAttempts, recoveryMax) : recoveryMax;
416
416
  const REPEAT_ENV_CODES = [OUTCOME_CODES.ENV_REPRO_UNRUNNABLE, OUTCOME_CODES.ENV_TOOL_MISSING]; // #5232: deterministic for a frozen command (a timeout is load, not listed)
417
417
  const sigOf = (d) => String(d ?? "").replace(/\s+/g, " ").trim();
418
+ // #5592: env.tool_missing repeats are the same defect when the same tools are missing, whatever else the detail says (probe lines, ids, paths vary per run)
419
+ const toolsOf = (d) => { const m = /(?:host|sandbox) is missing ([^\n]+?), so validate command/i.exec(String(d ?? "")); return m ? m[1].split(/\s*,\s*/).sort().join(",") : null; };
420
+ const envSig = (code, d) => (code === OUTCOME_CODES.ENV_TOOL_MISSING ? toolsOf(d) : null) ?? sigOf(d);
418
421
  const maxFor = (cls) => (cls === "mechanical" ? mechMax : recoveryMax);
419
422
  const classUsed = toMap(saved?.recoveryClasses); // `${issue}:${class}` -> recovery lanes launched in that class
420
423
  const recoveries = toMap(saved?.recoveries); // issue -> recovery lanes launched (#4267)
@@ -626,6 +629,8 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
626
629
  if (!remote?.offlineFallback) return false;
627
630
  const after = Number.isInteger(remote.capacityFallbackAfter) && remote.capacityFallbackAfter > 0 ? remote.capacityFallbackAfter : CAPACITY_FALLBACK_AFTER;
628
631
  if ((capDefers.get(n) ?? 0) < after) return false;
632
+ // #5592: an overloaded host holds every local admission (host_overloaded), so falling back would park the lane indefinitely: keep retrying the pool
633
+ if (overload) { try { if (overload()?.overloaded) return false; } catch { /* unknown load: the headroom guard decides */ } }
629
634
  if (typeof remote.headroom !== "function") return true;
630
635
  try { return remote.headroom()?.ok !== false; } catch { return false; }
631
636
  };
@@ -915,7 +920,10 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
915
920
  try { await relabelNeedsHuman({ issue: n, evidence: evidence() }); } catch { /* best effort */ }
916
921
  }
917
922
  }
918
- if (recoveryMax && ["needs-human", "ci-pending", "budget-exceeded"].includes(row.outcome)) {
923
+ // #5526: the hold is re-read here (it is only read once per pass): a held issue's terminal outcome starts no recovery lane.
924
+ const heldNow = recoveryMax && ["needs-human", "ci-pending", "budget-exceeded"].includes(row.outcome) && (refreshHeld(), opHeld.has(n));
925
+ if (heldNow) decided({ issue: n, what: `no recovery lane for #${n}: ${heldByOperator(n)}`, why: firstLine(row.detail) || row.outcome, alternative: "recover while the operator holds it" });
926
+ if (recoveryMax && !heldNow && ["needs-human", "ci-pending", "budget-exceeded"].includes(row.outcome)) {
919
927
  let isConflicting = false;
920
928
  if (row.outcome === "ci-pending" && typeof conflicting === "function" && Number.isInteger(row.pr)) {
921
929
  try { isConflicting = (await conflicting(n, row.pr)) === true; } catch { isConflicting = false; }
@@ -924,12 +932,18 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
924
932
  if (prior) { const pk = `${n}:${recoveryClassOf({ code: prior.code })}`; classUsed.set(pk, Math.max(classUsed.get(pk) ?? 0, prior.attempt)); } // state saved before #4725 has no class counts
925
933
  const cls = recoveryClassOf(facts), max = maxFor(cls), used = classUsed.get(`${n}:${cls}`) ?? 0;
926
934
  // #5232: a deterministic env defect of the frozen command that a recovery attempt repeated verbatim is not rebuilt again
927
- const repeatEnv = prior && REPEAT_ENV_CODES.includes(row.code) && prior.code === row.code && sigOf(prior.detail) === sigOf(row.detail);
935
+ const repeatEnv = prior && REPEAT_ENV_CODES.includes(row.code) && prior.code === row.code && envSig(row.code, prior.detail) === envSig(row.code, row.detail);
936
+ // #5592: a first env.tool_missing that ran on this host (not a remote sandbox) would be replayed with the identical frozen contract on the same host and fail identically: not launched as-is
937
+ const sameHostReplay = !repeatEnv && !prior && row.code === OUTCOME_CODES.ENV_TOOL_MISSING && row.placement?.where !== "remote" && toolsOf(row.detail) !== null;
938
+ if (sameHostReplay) {
939
+ row.detail = `Environment defect: the run already executed on the host that lacks ${toolsOf(row.detail)}, and a recovery would replay the identical frozen contract on that same host, so none is launched. Install the tool or fix the dependency install on the host (or amend the contract's validate/env), then requeue.\n${String(row.detail ?? "")}`;
940
+ decided({ issue: n, what: `no recovery for ${row.code}: the frozen contract would fail identically on the same host`, why: firstLine(row.detail), alternative: "requeue a recovery lane that replays the same frozen contract on the same host" });
941
+ }
928
942
  if (repeatEnv) {
929
943
  row.detail = `Environment defect: the recovery attempt failed with the same \`${row.code}\` as the run before it, so no further rebuild is spent; run the command below on the host with the project's real dependencies.\n${String(row.detail ?? "")}`;
930
944
  decided({ issue: n, what: `no further recovery for ${row.code}: the same failure repeated`, why: firstLine(row.detail), alternative: "requeue another recovery lane that rebuilds against the same frozen command" });
931
945
  }
932
- if (!repeatEnv && classifyNeedsHuman(facts) === "recoverable" && used < max) {
946
+ if (!repeatEnv && !sameHostReplay && classifyNeedsHuman(facts) === "recoverable" && used < max) {
933
947
  const code = recoveryCodeOf(facts), attempt = used + 1;
934
948
  classUsed.set(`${n}:${cls}`, attempt);
935
949
  // #4315: the full lane detail is kept (never firstLine) for the relabel when the batch stops before this attempt
@@ -1014,6 +1028,8 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1014
1028
  try { gone = (await dispatchCheck(n)) ?? null; } catch { gone = null; }
1015
1029
  if (!["merged", "invalid", "deferred"].includes(gone?.outcome)) gone = null; // #4920: deferred = another lane owns the issue (lease or open PR on GitHub)
1016
1030
  }
1031
+ // #5526: a hold placed since the pass read is honoured at launch: the issue goes back to pending, no lane
1032
+ if (!cancelled && !halted) { refreshHeld(); if (opHeld.has(n)) { running.delete(n); runRecs.delete(n); releaseSlot(n); endRemote(n); requeue(n, 0); save(); return; } }
1017
1033
  if (halted) return; // #4454: stopped before launch; no pid, so a resume queues it again
1018
1034
  let r;
1019
1035
  if (cancelled) r = { terminalReason: "deferred", code: "run.interrupted", cost_usd: 0, detail: "cancelled before launch" }; // #4376
@@ -1264,6 +1280,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1264
1280
  const fmt = (ns) => ns.map((n) => `#${n}`).join(", ");
1265
1281
  const held = [...next].filter((n) => !opHeld.has(n)), freed = [...opHeld].filter((n) => !next.has(n));
1266
1282
  opHeld = next;
1283
+ for (const n of held) if (running.has(n)) update({ issue: n, outcome: "hold", detail: `#${n} held after launch: lane still running` }); // #5526
1267
1284
  if (held.length) {
1268
1285
  decided({ issue: null, what: `held ${fmt(held)} (forgedock orchestrate --hold)`, why: "operator request", alternative: "cancel the batch" });
1269
1286
  update({ issue: null, outcome: "hold", detail: fmt(held) });
@@ -1291,8 +1308,11 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1291
1308
  baseDone.add(n);
1292
1309
  }
1293
1310
  };
1311
+ let blockedReadAt = -Infinity; // #5592 follow-up: the label list is one `gh issue list` per call; a waiting batch makes several passes a second
1294
1312
  const refreshBlocked = async () => {
1295
1313
  if (!getBlocked) return;
1314
+ if (now() - blockedReadAt < blockedRefreshMs) return;
1315
+ blockedReadAt = now();
1296
1316
  let got;
1297
1317
  try { got = await getBlocked(); } catch { return; }
1298
1318
  const next = new Set((Array.isArray(got) ? got : [...(got ?? [])]).filter((n) => Number.isSafeInteger(n) && n > 0));
@@ -1518,6 +1538,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1518
1538
  if (n === null) { budgetHeld = ready.length > 0; break; }
1519
1539
  const g = grant(n, wanted);
1520
1540
  if (g === "busy") continue; // #4481: not ready any more this pass (notBefore), so `ready` drops it
1541
+ if (!g && (notBefore.get(n) ?? 0) > t) continue; // #5592: this issue waits on its own (host overload, pool slots): the issues behind it are still tried
1521
1542
  if (!g) break;
1522
1543
  pending.splice(pending.indexOf(n), 1);
1523
1544
  if (lanes.get(n)?.ok !== false) { dispatch.started++; if (clsOf(classes, n).maintenance) dispatch.maint++; }
@@ -1533,6 +1554,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1533
1554
  if (running.size >= K()) break;
1534
1555
  const g = grant(n, wanted);
1535
1556
  if (g === "busy") continue; // #4481
1557
+ if (!g && (notBefore.get(n) ?? 0) > t) continue; // #5592: per-issue wait, not a full host queue
1536
1558
  if (!g) break;
1537
1559
  pending.splice(pending.indexOf(n), 1); start(n); started++;
1538
1560
  }
@@ -0,0 +1,125 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * Orphan-PR sweep (#5505). A lane PR targets the lane base (`staging`), so GitHub never links it to its issue
5
+ * (`closingIssuesReferences` is empty) and nothing closed it when the issue was resolved another way. The issue → PR link is
6
+ * derived here from the lane branch `feat/issue-<n>-lean` or a `FORGE:ISSUE_PR` marker in the PR body, never from GitHub's link.
7
+ * Deterministic, no model call. Each open PR whose issue is closed is classified, in order:
8
+ * backport-pending (kept) > not_planned > duplicate > superseded > undelivered.
9
+ */
10
+ export const BACKPORT_LABEL = "backport-pending";
11
+ export const ALERT_AGE_MS = 24 * 3600 * 1000;
12
+ const MARK = (n) => `<!-- FORGE:ISSUE_PR issue=${n} -->`;
13
+
14
+ /** Issue number a PR was built for, or null (not a ForgeDock PR). */
15
+ export function parseIssueLink(pr) {
16
+ const m = /^feat\/issue-(\d+)-lean$/.exec(String(pr?.headRefName ?? "")) ?? /FORGE:ISSUE_PR issue=(\d+)/.exec(String(pr?.body ?? ""));
17
+ return m ? Number(m[1]) : null;
18
+ }
19
+ export const issuePrMarker = MARK;
20
+
21
+ /** Pure: `{ kind, detail }` for one open PR whose issue is closed. `ctx`: { issue:{stateReason,labels}, preferred, merged, onBase, base }. */
22
+ export function classifyOrphanPr(pr, ctx) {
23
+ const labels = (ctx.issue?.labels ?? []).map((l) => (typeof l === "string" ? l : l?.name));
24
+ if (labels.includes(BACKPORT_LABEL)) return { kind: "backport-pending", detail: "the backport is still pending" };
25
+ if (/^(not_planned|duplicate)$/i.test(String(ctx.issue?.stateReason ?? ""))) return { kind: "not_planned", detail: "the issue was closed as not planned" };
26
+ if (ctx.merged) return { kind: "duplicate", detail: `PR #${ctx.merged} for the same issue is merged` };
27
+ if (ctx.preferred && ctx.preferred !== pr.number) return { kind: "duplicate", detail: `PR #${ctx.preferred} is the preferred PR for the same issue` };
28
+ if (ctx.onBase) return { kind: "superseded", detail: `an equivalent change is already on \`${ctx.base}\` (${ctx.onBase})` };
29
+ return { kind: "undelivered", detail: `the change is not on \`${ctx.base}\`` };
30
+ }
31
+
32
+ /** `{ count, oldestAgeMs, alert }` over rows with an `ageMs`; alert when any orphan is older than 24h. Kept PRs (backport-pending) and cleanup rows (backport-merged) do not count. */
33
+ const NOT_ORPHAN_KINDS = new Set(["backport-pending", "backport-merged"]);
34
+ export function orphanTelemetry(rows) {
35
+ const r = (rows ?? []).filter((x) => x.kind && !NOT_ORPHAN_KINDS.has(x.kind));
36
+ const oldestAgeMs = r.reduce((m, x) => Math.max(m, x.ageMs ?? 0), 0);
37
+ return { count: r.length, oldestAgeMs, alert: r.length > 0 && oldestAgeMs > ALERT_AGE_MS };
38
+ }
39
+
40
+ const json = async (io, args) => { try { const v = JSON.parse(String(await io.gh(args)) || "null"); return v; } catch { return null; } };
41
+
42
+ /** Open PRs (other than `exceptPr`) built for `issue`; empty when the close is `not planned`/`duplicate` or gh fails (fail open). */
43
+ export async function openPrBlockingClose({ repo, io, issue, reason = "completed", exceptPr = null }) {
44
+ if (/not.?planned|duplicate/i.test(reason)) return [];
45
+ const prs = await json(io, ["pr", "list", "-R", repo, "--state", "open", "--limit", "200", "--json", "number,headRefName,body"]);
46
+ return (prs ?? []).filter((p) => p.number !== exceptPr && parseIssueLink(p) === issue).map((p) => p.number);
47
+ }
48
+
49
+ /** One live PR per issue: close every other open PR of `issue` as superseded by `newPr`. Returns the closed numbers. */
50
+ export async function supersedeOlderPrs({ repo, io, issue, newPr, dryRun = false }) {
51
+ const prs = await json(io, ["pr", "list", "-R", repo, "--state", "open", "--limit", "200", "--json", "number,headRefName,body"]);
52
+ const old = (prs ?? []).filter((p) => p.number !== newPr && parseIssueLink(p) === issue).map((p) => p.number);
53
+ if (!dryRun) for (const n of old) await io.gh(["pr", "close", String(n), "-R", repo, "--comment", `Superseded by #${newPr}: one live PR per issue (#${issue}).`]);
54
+ return old;
55
+ }
56
+
57
+ /** Sweep every open PR to `base` whose issue is closed; one row per PR. Never throws; an unreadable PR is an `error` row. */
58
+ export async function sweepOrphanPrs({ repo, cwd = process.cwd(), io, base = "staging", dryRun = false, onResult = null } = {}) {
59
+ const now = io.now?.() ?? Date.now();
60
+ const rows = [];
61
+ const open = await json(io, ["pr", "list", "-R", repo, "--state", "open", "--base", base, "--limit", "200", "--json", "number,headRefName,body,createdAt"]);
62
+ const merged = await json(io, ["pr", "list", "-R", repo, "--state", "merged", "--base", base, "--limit", "200", "--json", "number,headRefName,body"]);
63
+ const byIssue = new Map();
64
+ for (const p of open ?? []) { const n = parseIssueLink(p); if (n) byIssue.set(n, [...(byIssue.get(n) ?? []), p]); }
65
+ const mergedFor = new Map();
66
+ for (const p of merged ?? []) { const n = parseIssueLink(p); if (n && !mergedFor.has(n)) mergedFor.set(n, p.number); }
67
+ for (const [issue, prs] of [...byIssue].sort((a, b) => a[0] - b[0])) {
68
+ const iss = await json(io, ["issue", "view", String(issue), "-R", repo, "--json", "state,stateReason,labels"]);
69
+ if (!iss || String(iss.state).toUpperCase() !== "CLOSED") continue;
70
+ const preferred = Math.max(...prs.map((p) => p.number));
71
+ for (const pr of prs.sort((a, b) => a.number - b.number)) {
72
+ let row = { pr: pr.number, issue, kind: null, ageMs: Math.max(0, now - Date.parse(pr.createdAt ?? now)) };
73
+ try {
74
+ let onBase = null;
75
+ try {
76
+ await io.git(["fetch", "-q", "origin", base, pr.headRefName], { cwd });
77
+ const cherry = String(await io.git(["cherry", `origin/${base}`, `origin/${pr.headRefName}`], { cwd })).split("\n").filter(Boolean);
78
+ if (!cherry.some((l) => l.startsWith("+"))) onBase = String(await io.git(["rev-parse", "--short=12", `origin/${base}`], { cwd })).trim();
79
+ } catch { onBase = null; } // unknown: never close as superseded on a git failure
80
+ const c = classifyOrphanPr(pr, { issue: iss, preferred, merged: mergedFor.get(issue), onBase, base });
81
+ row = { ...row, ...c };
82
+ if (c.kind !== "backport-pending" && !dryRun) {
83
+ let note = `Closing: issue #${issue} is closed and this PR is orphaned (${c.kind}): ${c.detail}.`;
84
+ if (c.kind === "undelivered") {
85
+ const marker = `FORGE:ORPHAN_PR pr=${pr.number}`;
86
+ const found = await json(io, ["issue", "list", "-R", repo, "--state", "all", "--search", `"${marker}" in:body`, "--json", "number"]);
87
+ let ref = found?.[0]?.number ? `#${found[0].number}` : null;
88
+ if (!ref) { const out = String(await io.gh(["issue", "create", "-R", repo, "--title", `Follow-up: undelivered work from PR #${pr.number} (issue #${issue})`, "--body", `PR #${pr.number} (branch \`${pr.headRefName}\`) was never merged and issue #${issue} is closed. Its change is not on \`${base}\`.\n\n<!-- ${marker} -->`])).trim(); ref = /(\d+)$/.test(out) ? `#${/(\d+)$/.exec(out)[1]}` : out; }
89
+ row.followup = ref;
90
+ note += ` Follow-up filed: ${ref} (branch \`${pr.headRefName}\` is kept).`;
91
+ }
92
+ await io.gh(["pr", "close", String(pr.number), "-R", repo, "--comment", note]);
93
+ row.closed = true;
94
+ }
95
+ } catch (e) { row = { ...row, kind: "error", detail: String(e?.message ?? e).slice(0, 160) }; }
96
+ rows.push(row);
97
+ try { if (!dryRun) await onResult?.(row); } catch { /* an event sink never fails the sweep */ }
98
+ }
99
+ }
100
+ if (!dryRun) await clearBackportPending({ repo, io, rows });
101
+ return rows;
102
+ }
103
+
104
+ /** A closed issue labelled `backport-pending` whose backport PR (a `hotfix/*` or `backport/*` head naming it) is merged and none open: unlabel and close it. */
105
+ async function clearBackportPending({ repo, io, rows }) {
106
+ const issues = await json(io, ["issue", "list", "-R", repo, "--state", "all", "--label", BACKPORT_LABEL, "--limit", "100", "--json", "number,state"]);
107
+ for (const i of issues ?? []) {
108
+ try {
109
+ const prs = (await json(io, ["pr", "list", "-R", repo, "--state", "all", "--search", `#${i.number} in:title,body`, "--limit", "20", "--json", "number,state,headRefName"])) ?? [];
110
+ const bp = prs.filter((p) => /^(hotfix|backport)\//.test(p.headRefName));
111
+ if (!bp.length || bp.some((p) => p.state === "OPEN") || !bp.some((p) => p.state === "MERGED")) continue;
112
+ await io.gh(["issue", "edit", String(i.number), "-R", repo, "--remove-label", BACKPORT_LABEL]);
113
+ if (String(i.state).toUpperCase() === "OPEN") await io.gh(["issue", "close", String(i.number), "-R", repo, "--reason", "completed", "--comment", `The backport merged (PR #${bp.find((p) => p.state === "MERGED").number}); closing.`]);
114
+ rows.push({ issue: i.number, kind: "backport-merged", detail: "label cleared" });
115
+ } catch { /* retried on the next sweep */ }
116
+ }
117
+ }
118
+
119
+ /** One line, e.g. `orphan PRs: closed 2 (superseded #4); ALERT oldest 30h`; "" when nothing orphaned. */
120
+ export function formatOrphanSummary(rows) {
121
+ const t = orphanTelemetry(rows);
122
+ const closed = (rows ?? []).filter((r) => r.closed);
123
+ if (!t.count && !closed.length) return "";
124
+ return `orphan PRs: ${t.count} found, ${closed.length} closed${closed.length ? ` (${closed.map((r) => `${r.kind} #${r.pr}`).join(", ")})` : ""}${t.alert ? `; ALERT oldest ${Math.round(t.oldestAgeMs / 3600000)}h` : ""}`;
125
+ }