forgedock 1.51.0 → 1.53.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 (103) hide show
  1. package/bin/engine/outcome-codes.mjs +3 -0
  2. package/bin/engine/telemetry-seam.mjs +4 -2
  3. package/bin/engine-cli.mjs +61 -17
  4. package/bin/experiment.mjs +58 -6
  5. package/bin/forge-utils.mjs +6 -2
  6. package/bin/forgedock.mjs +25 -1
  7. package/bin/lean/account-watch.mjs +28 -0
  8. package/bin/lean/account-watch.test.mjs +30 -0
  9. package/bin/lean/activation.mjs +20 -0
  10. package/bin/lean/activation.test.mjs +14 -1
  11. package/bin/lean/basered.mjs +115 -0
  12. package/bin/lean/basered.test.mjs +66 -0
  13. package/bin/lean/batch-health.mjs +40 -6
  14. package/bin/lean/batch-health.test.mjs +34 -1
  15. package/bin/lean/batch.mjs +41 -2
  16. package/bin/lean/batch.test.mjs +104 -2
  17. package/bin/lean/checkpoint-reconcile.mjs +43 -0
  18. package/bin/lean/checkpoint-reconcile.test.mjs +95 -0
  19. package/bin/lean/conformance.e2e.test.mjs +1 -1
  20. package/bin/lean/conformance.mjs +205 -23
  21. package/bin/lean/conformance.test.mjs +164 -3
  22. package/bin/lean/context.mjs +27 -17
  23. package/bin/lean/context.test.mjs +15 -0
  24. package/bin/lean/effects.mjs +11 -7
  25. package/bin/lean/execution.mjs +19 -3
  26. package/bin/lean/execution.test.mjs +39 -0
  27. package/bin/lean/findinglabel.mjs +16 -0
  28. package/bin/lean/findinglabel.test.mjs +39 -0
  29. package/bin/lean/heavy.mjs +6 -3
  30. package/bin/lean/hostload.mjs +78 -0
  31. package/bin/lean/hostload.test.mjs +117 -0
  32. package/bin/lean/hotspots-remote.e2e.test.mjs +71 -0
  33. package/bin/lean/issuewatch-release.mjs +6 -2
  34. package/bin/lean/issuewatch-release.test.mjs +16 -0
  35. package/bin/lean/issuewatch.mjs +11 -1
  36. package/bin/lean/lanelock.mjs +14 -0
  37. package/bin/lean/lean.mjs +171 -36
  38. package/bin/lean/lean.test.mjs +302 -10
  39. package/bin/lean/light.mjs +48 -7
  40. package/bin/lean/light.test.mjs +37 -3
  41. package/bin/lean/limits.test.mjs +142 -9
  42. package/bin/lean/orchestrate-cancel.test.mjs +143 -0
  43. package/bin/lean/orchestrate.mjs +110 -26
  44. package/bin/lean/postdeploy-check.test.mjs +39 -0
  45. package/bin/lean/prompts.mjs +8 -7
  46. package/bin/lean/quota.mjs +39 -0
  47. package/bin/lean/recovery.test.mjs +10 -0
  48. package/bin/lean/relaxation.mjs +73 -0
  49. package/bin/lean/relaxation.test.mjs +54 -0
  50. package/bin/lean/release-postmerge.mjs +119 -0
  51. package/bin/lean/release-rehearsal.mjs +63 -0
  52. package/bin/lean/release-rehearsal.test.mjs +93 -0
  53. package/bin/lean/release-review.e2e.test.mjs +77 -0
  54. package/bin/lean/release-review.mjs +198 -0
  55. package/bin/lean/release-review.test.mjs +180 -0
  56. package/bin/lean/release.mjs +228 -0
  57. package/bin/lean/release.test.mjs +292 -0
  58. package/bin/lean/rotator.mjs +150 -31
  59. package/bin/lean/rotator.test.mjs +105 -2
  60. package/bin/lean/sandbox-remote.mjs +9 -2
  61. package/bin/lean/schedd.mjs +56 -6
  62. package/bin/lean/schedd.test.mjs +108 -6
  63. package/bin/lean/verifier.mjs +3 -2
  64. package/bin/lean/verify.mjs +2 -1
  65. package/bin/lean/verify.test.mjs +6 -0
  66. package/bin/pool/agent.mjs +18 -4
  67. package/bin/pool/router.mjs +68 -25
  68. package/bin/review-staging.mjs +23 -0
  69. package/bin/stats/conformance-outcomes.mjs +208 -0
  70. package/bin/stats/conformance-outcomes.test.mjs +188 -0
  71. package/bin/stats/depth.mjs +218 -0
  72. package/bin/stats/depth.test.mjs +133 -0
  73. package/bin/stats/experiment.mjs +7 -5
  74. package/bin/stats/github-source.mjs +2 -2
  75. package/bin/stats/index.mjs +64 -2
  76. package/bin/stats/local-source.mjs +11 -0
  77. package/bin/stats/query.mjs +69 -0
  78. package/bin/stats/selffiled.mjs +52 -0
  79. package/bin/stats/selffiled.test.mjs +71 -0
  80. package/commands/orchestrate.md +1 -1
  81. package/commands/review-pr-agents/security.md +4 -0
  82. package/commands/review-pr-staging.md +2 -0
  83. package/commands/work-on/build.md +4 -6
  84. package/docs/CONFIG.md +66 -8
  85. package/docs/ISSUE-WATCH.md +2 -0
  86. package/docs/OUTCOME-CODES.md +3 -0
  87. package/docs/STATS.md +44 -0
  88. package/docs/TELEMETRY.md +1 -1
  89. package/package.json +1 -1
  90. package/pool/README.md +1 -1
  91. package/pool/image/cs-cred +14 -1
  92. package/pool/install/install-agent.ps1 +6 -2
  93. package/scripts/backfill-finding-labels.mjs +50 -0
  94. package/scripts/backfill-finding-labels.test.mjs +36 -0
  95. package/scripts/doctor-pipeline-state.sh +21 -6
  96. package/scripts/file-deferred-followups.sh +60 -238
  97. package/scripts/file-deferred-followups.test.sh +99 -187
  98. package/scripts/followup-route.mjs +12 -0
  99. package/scripts/hotspots.sh +12 -8
  100. package/scripts/hotspots.test.sh +22 -0
  101. package/scripts/owner-route-parity.test.sh +17 -1
  102. package/scripts/prior-attempts.test.mjs +1 -1
  103. package/scripts/review-pr-side-effects.test.sh +40 -0
@@ -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
+ });
@@ -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,28 @@ 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
+ }
@@ -7,7 +7,7 @@ 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 } from "./batch-health.mjs";
11
11
 
12
12
  // #1 and #3 are roots; #2 depends on #1, #4 on #3.
13
13
  const base = (results, extra = {}) => ({ order: [1, 2, 3, 4], deps: { 2: [1], 4: [3] }, results, running: {}, pending: [], ...extra });
@@ -154,3 +154,36 @@ describe("#5167 channels and refusals", () => {
154
154
  assert.ok(existsSync(join(root, "refusals.json")));
155
155
  });
156
156
  });
157
+
158
+ describe("#5243 health re-reads GitHub before declaring root-failed", () => {
159
+ const st = base({ 1: { outcome: "needs-human" }, 2: { outcome: "skipped" }, 3: { outcome: "merged" }, 4: { outcome: "merged" } });
160
+ const mkBatch = () => { const dir = tmpDir("bh5243-"); return { id: "b1", dir, store: { load: () => st } }; };
161
+
162
+ it("a root merged by hand is resolved: healthy, no requeue suggestion", async () => {
163
+ const r = await runCheck({ batch: mkBatch(), checkpoint: "T+60", resolve: async (c) => c.map((x) => x.issue) });
164
+ assert.equal(r.healthy, true);
165
+ assert.equal(r.alerted, false);
166
+ assert.ok(!r.recovery.some((x) => /requeue/.test(x)));
167
+ });
168
+
169
+ it("an unresolved root, or a failing resolver, still alerts with the requeue command", async () => {
170
+ for (const resolve of [async () => [], async () => { throw new Error("gh down"); }]) {
171
+ const r = await runCheck({ batch: mkBatch(), checkpoint: "T+60", resolve });
172
+ assert.equal(r.healthy, false);
173
+ assert.ok(r.recovery.some((x) => /--requeue b1 1/.test(x)));
174
+ }
175
+ });
176
+
177
+ it("resolvedOnGithub: closed with merged PR, or needs-human label removed with a FORGE:DECISION", async () => {
178
+ const views = {
179
+ 1: { state: "CLOSED", labels: [], comments: [], closedByPullRequestsReferences: [{ number: 9 }] },
180
+ 2: { state: "CLOSED", labels: [], comments: [], closedByPullRequestsReferences: [{ number: 10 }] },
181
+ 3: { state: "OPEN", labels: [], comments: [{ body: "<!-- FORGE:DECISION x -->" }] },
182
+ 4: { state: "OPEN", labels: [{ name: "needs-human" }], comments: [{ body: "<!-- FORGE:DECISION x -->" }] },
183
+ 5: { state: "OPEN", labels: [], comments: [] },
184
+ };
185
+ 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]]); };
186
+ const cands = [1, 2, 3, 4, 5, 6].map((issue) => ({ issue, outcome: "needs-human" }));
187
+ assert.deepEqual(await resolvedOnGithub(cands, gh, "o/r"), [1, 3]);
188
+ });
189
+ });
@@ -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) {
@@ -881,6 +881,54 @@ describe("#4504: a resume settles lanes that ended while no dispatcher ran", ()
881
881
  });
882
882
  });
883
883
 
884
+ describe("#5204: lanes interrupted by an upgrade are logged and requeued, never dropped", () => {
885
+ const stateOf = (running, extra = {}) => ({ v: 1, order: Object.keys(running).map(Number), deps: Object.fromEntries(Object.keys(running).map((k) => [k, []])), lanes: {}, crossSeen: [], results: {},
886
+ running, pending: [], notBefore: {}, requeues: {}, deferrals: {}, engineErrors: {}, prefilter: {}, errorTimes: [], breaker: null, ...extra });
887
+ it("#5204: a resume after an upgrade logs an interrupted row and requeues a lane that ended without a result", async () => {
888
+ let saved = stateOf({ 3: { startedAt: 1, pid: 33 }, 5: { startedAt: 1, remote: true }, 6: { startedAt: 1, pid: 66 }, 7: { startedAt: 1 } }, { engineVersion: "1.51.0" });
889
+ const logged = [], updates = [], decisions = [], interrupted = [], adopted = [];
890
+ const store = { load: () => saved, save: (s) => { saved = s; }, log: (r) => logged.push(r) };
891
+ const adopt = async (n, rec) => { adopted.push(n); if (n === 6) throw new Error("ledger unreadable"); return null; };
892
+ const launched = [];
893
+ const rows = await orchestrate({ issues: [], parallel: 3, pollMs: 5, readBody: async () => "", store, adopt, version: "1.52.0",
894
+ onUpdate: (r) => updates.push(r), decide: (d) => decisions.push(d),
895
+ onInterrupted: async (n, detail) => { interrupted.push([n, detail.cause]); if (n === 3) throw new Error("gh down"); }, // errors are swallowed
896
+ runOne: async (n) => { launched.push(n); return { terminalReason: "merged", pr: 100 + n }; } });
897
+ assert.deepEqual(adopted.sort(), [3, 5, 6], "a handle-less remote record is still adopted (the ledger seam); a record with nothing to adopt is not");
898
+ const ir = logged.filter((r) => r.code === "run.interrupted");
899
+ assert.deepEqual(ir.map((r) => r.issue).sort(), [3, 5, 6, 7], "one interrupted row per requeued lane");
900
+ for (const r of ir) {
901
+ assert.equal(r.outcome, "deferred");
902
+ assert.equal(r.pr, null); assert.equal(r.cost_usd, 0); assert.equal(r.minutes, 0);
903
+ assert.match(r.detail, /^interrupted: upgrade v1\.51\.0→v1\.52\.0; .+; requeued$/);
904
+ }
905
+ assert.match(ir.find((r) => r.issue === 6).detail, /adopt failed: ledger unreadable/, "the adopt error is kept");
906
+ assert.match(ir.find((r) => r.issue === 7).detail, /no adoptable pid or handle/);
907
+ assert.match(ir.find((r) => r.issue === 3).detail, /ended without a result/);
908
+ assert.deepEqual(updates.filter((r) => r.code === "run.interrupted").length, 4, "onUpdate sees the same rows");
909
+ assert.deepEqual(decisions.filter((d) => d.what === "requeued (interrupted)").map((d) => d.issue).sort(), [3, 5, 6, 7]);
910
+ assert.deepEqual(interrupted.map(([n]) => n).sort(), [3, 5, 6, 7]);
911
+ assert.ok(interrupted.every(([, c]) => c === "upgrade v1.51.0→v1.52.0"));
912
+ assert.deepEqual(launched.sort(), [3, 5, 6, 7], "each requeued lane runs once");
913
+ assert.deepEqual(rows.map((r) => [r.issue, r.outcome]).sort((a, b) => a[0] - b[0]), [[3, "merged"], [5, "merged"], [6, "merged"], [7, "merged"]], "the interrupted row is not a result");
914
+ assert.deepEqual(saved.deferrals, {}, "no deferral consumed");
915
+ assert.deepEqual(saved.engineErrors, {}, "no engine-error consumed");
916
+ assert.equal(saved.engineVersion, "1.52.0", "the running engine version is saved");
917
+ });
918
+ it("#5204: without a version change the cause is a dispatcher restart; a lane with a result is settled, not interrupted", async () => {
919
+ let saved = stateOf({ 1: { startedAt: 1, pid: 11 }, 2: { startedAt: 1, pid: 22 } }, { engineVersion: "1.52.0" });
920
+ const logged = [];
921
+ const store = { load: () => saved, save: (s) => { saved = s; }, log: (r) => logged.push(r) };
922
+ const adopt = async (n) => (n === 1 ? { terminalReason: "merged", pr: 101 } : null);
923
+ const rows = await orchestrate({ issues: [], parallel: 2, pollMs: 5, readBody: async () => "", store, adopt, version: "1.52.0",
924
+ runOne: async (n) => ({ terminalReason: "merged", pr: 100 + n }) });
925
+ const ir = logged.filter((r) => r.code === "run.interrupted");
926
+ assert.deepEqual(ir.map((r) => r.issue), [2]);
927
+ assert.match(ir[0].detail, /^interrupted: dispatcher restart; the lane ended without a result; requeued$/);
928
+ assert.deepEqual(rows.map((r) => [r.issue, r.outcome, r.pr]), [[1, "merged", 101], [2, "merged", 102]]);
929
+ });
930
+ });
931
+
884
932
  describe("#4528: a full sandbox pool (sandbox.capacity) is never capped", () => {
885
933
  it("sandbox.capacity is uncapped and honours retryInSeconds; other codes still cap at maxDeferrals", () => {
886
934
  assert.deepEqual(deferPolicy({ code: "sandbox.capacity" }, { now: 0, deferrals: 99 }), { delayMs: 60000, host: true });
@@ -1520,14 +1568,35 @@ describe("#5161 transient engine-error retries", () => {
1520
1568
  });
1521
1569
  });
1522
1570
 
1571
+ describe("#5242 an add that lands after the last dispatch pass keeps the batch open", () => {
1572
+ it("a run that receives an add in its post-loop tail writes no report.json, so the add is not stranded", async () => {
1573
+ const batchRoot = tmpDir("tail-add-batch-");
1574
+ const leanIo = { gh: async (a) => (a[0] === "issue" && a[1] === "view" ? JSON.stringify({ body: "", milestone: null, comments: [], author: { login: "x" } }) : a[0] === "repo" ? "main\n" : "[]"), git: async (a) => (a[0] === "ls-remote" ? "abc\tref\n" : "") };
1575
+ const deps = { dir: tmpDir("tail-add-run-"), batchRoot, allowTmpfs: true, emitTelemetry: async () => {}, leanIo, pollMs: 5, preflight: null,
1576
+ io: { gh: async (a) => (a[0] === "issue" ? JSON.stringify({ body: "", state: "OPEN" }) : "o/r\n"), git: async () => "" },
1577
+ alertConfig: { get tailAdd() { openBatch(batchRoot, readdirSync(batchRoot)[0]).addIssues([9]); return null; } }, // read by the post-loop alerts step
1578
+ leanModule: { runCore: async (o) => ({ terminalReason: "merged", pr: o.issue, cost_usd: 0, wall_ms: 1 }) } };
1579
+ const adm = tmpDir("tail-add-adm-"), prevCwd = process.cwd();
1580
+ writeFileSync(join(adm, "forge.yaml"), "engine:\n admission_enabled: false\n");
1581
+ process.chdir(adm);
1582
+ const l = console.log; console.log = () => {};
1583
+ try { await orchestrateFromCli(["1", "--repo", "o/r", "--no-prefilter"], deps); } finally { console.log = l; process.chdir(prevCwd); }
1584
+ const b = openBatch(batchRoot, readdirSync(batchRoot)[0]);
1585
+ assert.deepEqual(b.unrunAdds(), [9], "the add was never drained");
1586
+ assert.equal(b.readReport(), null, "the batch stays open for a re-host or --resume");
1587
+ });
1588
+ });
1589
+
1523
1590
  describe("#5167 early batch health in runBatch", () => {
1524
1591
  // #1 and #3 are roots, #2 depends on #1. #3 runs until `release`; the captured T+15 timer fires while it runs.
1525
- const mk = ({ fail }) => {
1592
+ const mk = ({ fail, merged = false }) => {
1526
1593
  const timers = [], comments = [], notes = [], gate = { open: null };
1527
1594
  const released = new Promise((r) => { gate.open = r; });
1528
1595
  const bodies = { 1: "", 2: "Depends on #1", 3: "" };
1529
1596
  const leanIo = { gh: async (a) => {
1530
1597
  if (a[0] === "issue" && a[1] === "comment") { if (/FORGE:BATCH-HEALTH/.test(a.at(-1))) comments.push(a); return ""; }
1598
+ if (merged && a[0] === "issue" && a[1] === "view" && a.some((x) => /closedByPullRequestsReferences/.test(x))) return JSON.stringify({ state: "CLOSED", labels: [], comments: [], closedByPullRequestsReferences: [{ number: 99 }] });
1599
+ if (merged && a[0] === "pr" && a[1] === "view") return JSON.stringify({ state: "MERGED" });
1531
1600
  if (a[0] === "issue" && a[1] === "view") return JSON.stringify({ body: bodies[a[2]] ?? "", milestone: { title: "M Two" }, comments: [], author: { login: "x" } });
1532
1601
  return a[0] === "repo" ? "main\n" : "[]";
1533
1602
  }, git: async (a) => (a[0] === "ls-remote" ? "abc\tref\n" : "") };
@@ -1544,9 +1613,32 @@ describe("#5167 early batch health in runBatch", () => {
1544
1613
  };
1545
1614
  const capture = async (fn) => { const lines = [], l = console.log; console.log = (...a) => lines.push(a.join(" ")); try { await fn(); } finally { console.log = l; } return lines; };
1546
1615
 
1616
+ it("#5243 roots whose issues were merged by hand raise no BATCH UNHEALTHY and no requeue suggestion", async () => {
1617
+ const { deps, timers, comments, gate } = mk({ fail: true, merged: true });
1618
+ let id = null;
1619
+ const adm = tmpDir("bh-adm-"), prevCwd = process.cwd();
1620
+ writeFileSync(join(adm, "forge.yaml"), "engine:\n admission_enabled: false\n");
1621
+ process.chdir(adm);
1622
+ const lines = await capture(async () => {
1623
+ const run = orchestrateFromCli(["1", "2", "3", "--repo", "o/r", "--no-prefilter", "--parallel", "3"], deps);
1624
+ try {
1625
+ await until(() => { id = readdirSyncSafe(deps.batchRoot)[0]; return id && JSON.parse(readFileSync(join(deps.batchRoot, id, "state.json"), "utf8")).results?.[1]; });
1626
+ await timers[0].fn();
1627
+ await until(() => existsSync(join(deps.batchRoot, id, "health.json")), 5000);
1628
+ } finally { gate.open(); await run; process.chdir(prevCwd); }
1629
+ });
1630
+ assert.ok(!lines.some((l) => /BATCH UNHEALTHY|--requeue/.test(l)), lines.join("\n"));
1631
+ assert.equal(comments.length, 0);
1632
+ assert.equal(JSON.parse(readFileSync(join(deps.batchRoot, id, "health.json"), "utf8")).alertedAt, undefined);
1633
+ });
1634
+
1547
1635
  it("#5167 roots ending engine-error raise one BATCH UNHEALTHY at T+15 with recovery commands, on every channel", async () => {
1548
1636
  const { deps, timers, comments, notes, gate } = mk({ fail: true });
1549
1637
  let id = null;
1638
+ // Three concurrent roots must not depend on host memory: the live local lane cap (#4777) reads forge.yaml from the cwd.
1639
+ const adm = tmpDir("bh-adm-"), prevCwd = process.cwd();
1640
+ writeFileSync(join(adm, "forge.yaml"), "engine:\n admission_enabled: false\n");
1641
+ process.chdir(adm);
1550
1642
  const lines = await capture(async () => {
1551
1643
  const run = orchestrateFromCli(["1", "2", "3", "--repo", "o/r", "--no-prefilter", "--parallel", "3"], deps);
1552
1644
  try {
@@ -1555,7 +1647,7 @@ describe("#5167 early batch health in runBatch", () => {
1555
1647
  await timers[0].fn();
1556
1648
  await until(() => existsSync(join(deps.batchRoot, id, "health.json")) && JSON.parse(readFileSync(join(deps.batchRoot, id, "health.json"), "utf8")).alertedAt, 5000);
1557
1649
  await until(() => notes.length === 1, 5000);
1558
- } finally { gate.open(); await run; }
1650
+ } finally { gate.open(); await run; process.chdir(prevCwd); }
1559
1651
  });
1560
1652
  assert.ok(lines.some((l) => /^health checks: T\+15 \d\d:\d\dZ, T\+60 \d\d:\d\dZ, and at batch end; forgedock status --batch /.test(l)), lines.join("\n"));
1561
1653
  const alerts = lines.filter((l) => /^BATCH UNHEALTHY /.test(l));
@@ -1616,6 +1708,16 @@ describe("#5168: --requeue accepts engine-error; a claude login failure is held,
1616
1708
  assert.equal(rows.find((x) => x.issue === 1).requeued.prior[0].outcome, "engine-error");
1617
1709
  });
1618
1710
 
1711
+ it("#5203 --requeue accepts a quota-paused pending issue; other pending issues stay refused not terminal", () => {
1712
+ const b = openBatch(tmpDir("batch-requeue-5203-"), "b1");
1713
+ b.writePlan({ argv: ["1"], repo: "o/r" });
1714
+ b.store.save({ order: [1, 2, 3], pending: [1, 2], results: { 3: { outcome: "merged" } }, notBefore: { 1: 9e12, 2: 9e12 }, quota: { 1: { cost_usd: 0, minutes: 1, resumeAt: 9e12, rotations: 0 } } });
1715
+ const r = b.requeue([1, 2, 3], { reason: "accounts usable", by: "operator" });
1716
+ assert.deepEqual(r.requeued, [1]);
1717
+ assert.deepEqual(r.refused, [{ issue: 2, reason: "not terminal" }, { issue: 3, reason: "not terminal" }]);
1718
+ assert.deepEqual(b.readRequeued().map((e) => e.issue), [1]);
1719
+ });
1720
+
1619
1721
  it("#5168 deferPolicy holds backend.auth like a usage limit: never capped, never counted", () => {
1620
1722
  assert.deepEqual(deferPolicy({ code: "backend.auth", retryInSeconds: 900 }, { now: 0, deferrals: 99, maxDeferrals: 3 }), { delayMs: 900_000, hold: true });
1621
1723
  assert.equal(deferPolicy({ code: "backend.auth" }, { now: 0 }).hold, true);
@@ -0,0 +1,43 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * #5202: the engine pushes a `wip(forge): checkpoint` commit mid-run (context ceiling, timeout, turn budget). A fresh builder
5
+ * session may then amend or squash it locally, so origin/<branch> is no longer an ancestor of HEAD and the next plain push is
6
+ * rejected non-fast-forward. Before a push, when every remote-only commit is such a checkpoint that this worktree produced or
7
+ * held (it is in the local reflog), it is merged in with `-s ours`: HEAD keeps the lane's own newer tree, the checkpoint stays in
8
+ * history (never lost) and the push stays a plain fast-forward (never force). Deterministic, 0 LLM calls; never throws.
9
+ */
10
+ const CHECKPOINT_PREFIX = "wip(forge): checkpoint";
11
+ const SEP = "\x1f";
12
+
13
+ /**
14
+ * @param {object} o
15
+ * @param {(args: string[]) => Promise<string>} o.git runs git in the lane worktree
16
+ * @param {string} o.branch the lane's own branch
17
+ * @returns {Promise<{state: "none"|"ok"|"reconciled"|"foreign"|"error", commits?: {sha: string, subject: string}[], sha?: string, error?: string}>}
18
+ */
19
+ export async function reconcileCheckpoints({ git, branch }) {
20
+ const out = async (args) => String(await git(args) ?? "").trim();
21
+ const ok = async (args) => { try { await git(args); return true; } catch { return false; } };
22
+ try {
23
+ try { await git(["fetch", "origin", branch]); } catch { /* offline or not pushed yet: the tracking ref we have decides */ }
24
+ const remote = `refs/remotes/origin/${branch}`;
25
+ if (!(await ok(["rev-parse", "--verify", "-q", remote]))) return { state: "none" };
26
+ if (await ok(["merge-base", "--is-ancestor", remote, "HEAD"])) return { state: "ok" };
27
+ const commits = (await out(["log", `--format=%H${SEP}%s`, `HEAD..${remote}`])).split("\n").filter(Boolean).map((l) => {
28
+ const [sha, subject = ""] = l.split(SEP);
29
+ return { sha: sha.trim(), subject };
30
+ });
31
+ if (!commits.length) return { state: "ok" };
32
+ const known = new Set();
33
+ for (const ref of [`refs/heads/${branch}`, "HEAD"]) {
34
+ try { for (const s of (await out(["log", "-g", "--format=%H", ref])).split("\n")) if (s.trim()) known.add(s.trim()); } catch { /* no reflog */ }
35
+ }
36
+ if (commits.some((c) => !c.subject.startsWith(CHECKPOINT_PREFIX) || !known.has(c.sha))) return { state: "foreign", commits };
37
+ const tip = await out(["rev-parse", remote]);
38
+ await git(["merge", "-s", "ours", "--no-edit", "-m", `merge(forge): keep pushed checkpoint ${tip.slice(0, 10)} in history`, remote]);
39
+ return { state: "reconciled", commits, sha: tip };
40
+ } catch (e) {
41
+ return { state: "error", error: String(e?.stderr ?? e?.message ?? e).slice(0, 300) };
42
+ }
43
+ }