forgedock 1.63.0 → 1.65.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 (89) hide show
  1. package/bin/config-schema.mjs +3 -0
  2. package/bin/engine/outcome-codes.mjs +5 -0
  3. package/bin/engine-cli.mjs +88 -12
  4. package/bin/env/cli.mjs +18 -1
  5. package/bin/lean/basered.mjs +56 -11
  6. package/bin/lean/basered.test.mjs +58 -5
  7. package/bin/lean/batch-health.mjs +46 -4
  8. package/bin/lean/batch-health.test.mjs +55 -1
  9. package/bin/lean/batch.mjs +8 -1
  10. package/bin/lean/batch.test.mjs +71 -6
  11. package/bin/lean/ceiling.mjs +47 -3
  12. package/bin/lean/ceiling.test.mjs +32 -1
  13. package/bin/lean/clear-breaker.mjs +15 -0
  14. package/bin/lean/clear-breaker.test.mjs +100 -0
  15. package/bin/lean/conformance.e2e.test.mjs +32 -6
  16. package/bin/lean/conformance.mjs +57 -13
  17. package/bin/lean/conformance.test.mjs +93 -1
  18. package/bin/lean/execution.mjs +18 -8
  19. package/bin/lean/execution.test.mjs +44 -3
  20. package/bin/lean/issuewatch-reconcile.mjs +2 -0
  21. package/bin/lean/issuewatch-reconcile.test.mjs +25 -0
  22. package/bin/lean/issuewatch.mjs +3 -0
  23. package/bin/lean/lanecheck.test.mjs +13 -1
  24. package/bin/lean/lean.mjs +157 -28
  25. package/bin/lean/lean.test.mjs +289 -21
  26. package/bin/lean/live-execution.mjs +25 -0
  27. package/bin/lean/live-execution.test.mjs +35 -1
  28. package/bin/lean/merged-park.mjs +76 -0
  29. package/bin/lean/merged-park.test.mjs +64 -0
  30. package/bin/lean/mergetrain.mjs +357 -0
  31. package/bin/lean/mergetrain.test.mjs +348 -0
  32. package/bin/lean/mirror-bundle.mjs +84 -0
  33. package/bin/lean/orchestrate-envhold.test.mjs +62 -0
  34. package/bin/lean/orchestrate-stacking.test.mjs +23 -1
  35. package/bin/lean/orchestrate-train.test.mjs +130 -0
  36. package/bin/lean/orchestrate-transient-git.test.mjs +53 -0
  37. package/bin/lean/orchestrate.mjs +170 -13
  38. package/bin/lean/prompts.mjs +4 -3
  39. package/bin/lean/release-review.mjs +8 -1
  40. package/bin/lean/release-review.test.mjs +42 -2
  41. package/bin/lean/release-status.test.mjs +53 -1
  42. package/bin/lean/release.mjs +6 -3
  43. package/bin/lean/render.mjs +6 -1
  44. package/bin/lean/sandbox-provider.contract.test.mjs +6 -0
  45. package/bin/lean/sandbox-remote.mjs +43 -3
  46. package/bin/lean/sched.mjs +19 -2
  47. package/bin/lean/sched.test.mjs +33 -1
  48. package/bin/lean/schedd-health.mjs +2 -1
  49. package/bin/lean/schedd-health.test.mjs +7 -0
  50. package/bin/lean/schedd.mjs +58 -7
  51. package/bin/lean/schedd.test.mjs +78 -1
  52. package/bin/lean/stacking.mjs +45 -0
  53. package/bin/lean/stacking.test.mjs +25 -1
  54. package/bin/lean/statuscomment.mjs +14 -8
  55. package/bin/lean/statuscomment.test.mjs +18 -1
  56. package/bin/lean/validate-catalog.mjs +1 -1
  57. package/bin/lean/validate-catalog.test.mjs +3 -0
  58. package/bin/lean/worktree.mjs +8 -3
  59. package/bin/lean/worktree.test.mjs +18 -0
  60. package/bin/pool/agent.mjs +309 -33
  61. package/bin/pool/cache-sweep.mjs +4 -2
  62. package/bin/pool/cli.mjs +125 -6
  63. package/bin/pool/disk.mjs +43 -0
  64. package/bin/pool/docker.mjs +11 -0
  65. package/bin/pool/health.mjs +95 -0
  66. package/bin/pool/mirror-seed.mjs +103 -0
  67. package/bin/pool/router.mjs +301 -27
  68. package/bin/runner.mjs +3 -1
  69. package/bin/stats/chains.mjs +101 -0
  70. package/bin/stats/chains.test.mjs +53 -0
  71. package/bin/stats/efficiency.mjs +7 -6
  72. package/bin/stats/efficiency.test.mjs +48 -7
  73. package/bin/stats/index.mjs +11 -3
  74. package/bin/stats/stats.test.mjs +9 -0
  75. package/docs/CONFIG.md +8 -1
  76. package/docs/OUTCOME-CODES.md +4 -0
  77. package/package.json +1 -1
  78. package/pool/README.md +10 -0
  79. package/pool/image/Dockerfile +2 -1
  80. package/pool/image/entrypoint.sh +25 -6
  81. package/pool/image/mirror.sh +71 -0
  82. package/pool/install/install-agent-linux.sh +57 -5
  83. package/pool/install/install-agent-macos.sh +148 -0
  84. package/pool/install/install-agent.ps1 +11 -0
  85. package/pool/install/install-agent.sh +59 -7
  86. package/pool/install/uninstall-agent-linux.sh +75 -0
  87. package/pool/install/uninstall-agent-macos.sh +60 -0
  88. package/pool/install/uninstall-agent.ps1 +1 -0
  89. package/scripts/transition-label.sh +11 -0
@@ -0,0 +1,348 @@
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 { codeForTerminalReason } from "../engine/outcome-codes.mjs";
6
+ import { createMergeTrain, formatTrainSummary, judgeChecks, p50, waitP90, rollupStates } from "./mergetrain.mjs";
7
+
8
+ const H = "a".repeat(40);
9
+ /** A fake gh over `prs`: {pr: {state, head, mergeable, mergeState, base, branch, checks}}; records every call. */
10
+ function fake(prs, { mergeError = null } = {}) {
11
+ const calls = [];
12
+ const gh = async (a) => {
13
+ calls.push(a);
14
+ const sub = a.slice(0, 2).join(" ");
15
+ if (sub === "pr view") {
16
+ const p = prs[a[2]];
17
+ if (a.includes("headRefOid") && !a.join(",").includes("state,")) return JSON.stringify({ headRefOid: p.head });
18
+ if (a.join(",").endsWith("state")) return JSON.stringify({ state: p.state ?? "OPEN" });
19
+ return JSON.stringify({ state: p.state ?? "OPEN", headRefOid: p.head, headRefName: p.branch ?? `feat/${a[2]}`, mergeable: p.mergeable ?? "MERGEABLE", mergeStateStatus: p.mergeState ?? "CLEAN", baseRefName: p.base ?? "staging", statusCheckRollup: p.checks ?? [] });
20
+ }
21
+ if (sub === "pr merge") { if (mergeError) throw mergeError; prs[a[2]].state = "MERGED"; return ""; }
22
+ if (sub === "pr update-branch") { prs[a[2]].mergeState = "CLEAN"; prs[a[2]].head = "b".repeat(40); return ""; }
23
+ if (sub === "issue view") return JSON.stringify({ labels: [{ name: "workflow:in-progress" }] });
24
+ return "";
25
+ };
26
+ return { gh, calls };
27
+ }
28
+ const ok = (name) => ({ name, conclusion: "SUCCESS" });
29
+ const entry = (issue, pr, extra = {}) => ({ issue, pr, head: H, required: ["build"], policy: "required", lane: "staging", ...extra });
30
+
31
+ describe("mergetrain (#5836)", () => {
32
+ it("merges a green PR at the reviewed head, then closes, labels and deletes the branch", async () => {
33
+ const f = fake({ 5: { head: H, checks: [ok("build")] } });
34
+ const t = createMergeTrain({ gh: f.gh, repo: "o/r" }); t.add(entry(1, 5));
35
+ const ev = await t.tick();
36
+ assert.deepEqual(ev.map((e) => [e.kind, e.issue]), [["merged", 1]]);
37
+ assert.deepEqual(f.calls.find((a) => a[1] === "merge").slice(-2), ["--match-head-commit", H]);
38
+ assert.ok(f.calls.some((a) => a[0] === "issue" && a[1] === "close" && a.includes("completed")));
39
+ assert.ok(f.calls.some((a) => a[0] === "issue" && a[1] === "edit" && a.includes("workflow:merged")));
40
+ assert.ok(f.calls.some((a) => a.join(" ").includes("DELETE repos/o/r/git/refs/heads/feat/5")));
41
+ assert.equal(t.size(), 0);
42
+ });
43
+ it("merges at most one PR per base per poll; another base merges in the same poll", async () => {
44
+ const f = fake({ 5: { head: H, checks: [ok("build")] }, 6: { head: H, checks: [ok("build")] }, 7: { head: H, base: "milestone/x", checks: [ok("build")] } });
45
+ const t = createMergeTrain({ gh: f.gh, repo: "o/r" }); t.add(entry(1, 5)); t.add(entry(2, 6)); t.add(entry(3, 7, { lane: "milestone/x" }));
46
+ assert.deepEqual((await t.tick()).map((e) => e.issue), [1, 3]);
47
+ assert.deepEqual((await t.tick()).map((e) => e.issue), [2]);
48
+ });
49
+ it("keeps a pending PR waiting and does not merge it", async () => {
50
+ const f = fake({ 5: { head: H, checks: [{ name: "build", status: "IN_PROGRESS", conclusion: "" }] } });
51
+ const t = createMergeTrain({ gh: f.gh, repo: "o/r" }); t.add(entry(1, 5));
52
+ assert.deepEqual(await t.tick(), []);
53
+ assert.equal(t.size(), 1);
54
+ assert.ok(!f.calls.some((a) => a[1] === "merge"));
55
+ });
56
+ it("updates a green PR that is behind its base, then merges once the head is current", async () => {
57
+ const f = fake({ 5: { head: H, mergeState: "BEHIND", checks: [ok("build")] } });
58
+ const t = createMergeTrain({ gh: f.gh, repo: "o/r" }); t.add(entry(1, 5));
59
+ assert.deepEqual(await t.tick(), []);
60
+ assert.ok(f.calls.some((a) => a.slice(0, 3).join(" ") === "pr update-branch 5"));
61
+ assert.equal(t.stats().syncs, 1);
62
+ assert.equal(t.snapshot().entries[0].head, "b".repeat(40), "the train adopts the synced head");
63
+ });
64
+ it("hands a red PR back as ci.red naming the failing checks and their URLs", async () => {
65
+ const f = fake({ 5: { head: H, checks: [{ name: "build", conclusion: "FAILURE", detailsUrl: "https://ci/run/9" }] } });
66
+ const t = createMergeTrain({ gh: f.gh, repo: "o/r" }); t.add(entry(1, 5));
67
+ const [e] = await t.tick();
68
+ assert.equal(e.kind, "handback"); assert.equal(e.code, "ci.red");
69
+ assert.match(e.detail, /- build https:\/\/ci\/run\/9/);
70
+ assert.equal(t.stats().handedBack["ci.red"], 1);
71
+ assert.ok(!f.calls.some((a) => a[1] === "merge"));
72
+ });
73
+ it("hands a conflicting PR back as base.conflict and a moved head as merge.head_mismatch", async () => {
74
+ const f = fake({ 5: { head: H, mergeable: "CONFLICTING", checks: [ok("build")] }, 6: { head: "c".repeat(40), checks: [ok("build")] } });
75
+ const t = createMergeTrain({ gh: f.gh, repo: "o/r" }); t.add(entry(1, 5)); t.add(entry(2, 6));
76
+ assert.deepEqual((await t.tick()).map((e) => e.code), ["base.conflict", "merge.head_mismatch"]);
77
+ assert.ok(!f.calls.some((a) => a[1] === "merge"));
78
+ });
79
+ it("a merge refused because the head moved is handed back; a transient failure is retried", async () => {
80
+ const moved = fake({ 5: { head: H, checks: [ok("build")] } }, { mergeError: Object.assign(new Error("Head branch was modified"), { stderr: "" }) });
81
+ const t = createMergeTrain({ gh: moved.gh, repo: "o/r" }); t.add(entry(1, 5));
82
+ assert.equal((await t.tick())[0].code, "merge.head_mismatch");
83
+ const flaky = fake({ 5: { head: H, checks: [ok("build")] } }, { mergeError: new Error("502 bad gateway") });
84
+ const t2 = createMergeTrain({ gh: flaky.gh, repo: "o/r" }); t2.add(entry(1, 5));
85
+ assert.deepEqual(await t2.tick(), []); assert.equal(t2.size(), 1);
86
+ });
87
+ it("persists through snapshot and restore, with stats and the p50 wait", async () => {
88
+ let clock = 0;
89
+ const f = fake({ 5: { head: H, checks: [ok("build")] }, 6: { head: H, base: "other", checks: [ok("build")] } });
90
+ const t = createMergeTrain({ gh: f.gh, repo: "o/r", now: () => clock }); t.add(entry(1, 5)); t.add(entry(2, 6, { lane: "other" }));
91
+ clock = 60000; await t.tick();
92
+ const snap = JSON.parse(JSON.stringify(t.snapshot()));
93
+ const t2 = createMergeTrain({ gh: f.gh, repo: "o/r" }); t2.restore(snap);
94
+ assert.equal(t2.stats().merged, 2); assert.deepEqual(t2.stats().waits, [60000, 60000]);
95
+ assert.equal(p50([30000, 60000, 90000]), 60000); assert.equal(p50([]), null);
96
+ });
97
+ it("pr-ready carries the awaiting_merge code", () => assert.equal(codeForTerminalReason("pr-ready"), "awaiting_merge"));
98
+ it("formats the batch report line", () => {
99
+ assert.equal(formatTrainSummary({ merged: 3, handedBack: { "ci.red": 1, "base.conflict": 1 }, waits: [60000, 120000], syncs: 2 }), "merge train: merged 3, handed back 2 (base.conflict 1, ci.red 1), wait p50 1.0 min p90 2.0 min, base-syncs 2 (lane 0), base.conflict 1 (lane 0)");
100
+ assert.equal(formatTrainSummary({ merged: 0, handedBack: {}, waits: [], syncs: 0 }), null);
101
+ });
102
+ it("judges policy all and required checks", () => {
103
+ const st = rollupStates([ok("a"), { name: "b", status: "IN_PROGRESS" }]);
104
+ assert.equal(judgeChecks(st, { required: ["a"] }).green, true);
105
+ assert.equal(judgeChecks(st, { required: ["a", "missing"] }).green, false);
106
+ assert.equal(judgeChecks(st, { policy: "all" }).green, false);
107
+ });
108
+ });
109
+
110
+ /** #5837: a fake gh with candidate-ref support on top of `fake`. `conflict` = PR heads whose candidate merge 409s. */
111
+ function batchWorld(prs, { conflict = [], runs = [{ name: "build", status: "completed", conclusion: "success" }], mergeRefuse = null } = {}) {
112
+ const f = fake(prs); const refs = new Set(); let checkRuns = runs;
113
+ const gh = async (a) => {
114
+ const s = a.join(" ");
115
+ if (s.includes("/git/ref/heads/") && !s.includes("forge-train")) return JSON.stringify({ object: { sha: "c".repeat(40) } });
116
+ if (s.includes("/git/ref/heads/forge-train")) { f.calls.push(a); return JSON.stringify({ object: { sha: "d".repeat(40) } }); }
117
+ if (s.startsWith("api -X POST repos/o/r/git/refs")) { f.calls.push(a); refs.add(a[5].slice(15)); return "{}"; }
118
+ if (s.startsWith("api -X POST repos/o/r/merges")) { f.calls.push(a); const head = a.find((x) => x.startsWith("head=")).slice(5); if (conflict.includes(head)) throw Object.assign(new Error("Merge conflict (HTTP 409)"), { stderr: "" }); return "{}"; }
119
+ if (s.startsWith("api -X DELETE repos/o/r/git/refs/heads/forge-train")) { f.calls.push(a); refs.delete(a[3].split("/heads/")[1]); return ""; }
120
+ if (s.startsWith("api -X POST repos/o/r/actions")) { f.calls.push(a); return ""; }
121
+ if (s.includes("/check-runs")) { f.calls.push(a); return JSON.stringify({ check_runs: checkRuns }); }
122
+ if (s.includes("compare/")) return JSON.stringify({ files: [{ filename: "x.js" }] });
123
+ if (a[0] === "pr" && a[1] === "view" && a.includes("files")) return JSON.stringify({ files: [{ path: "x.js" }, { path: "y.js" }] });
124
+ if (a[0] === "pr" && a[1] === "merge" && mergeRefuse === a[2]) { f.calls.push(a); throw new Error("base branch policy prohibits the merge"); }
125
+ return f.gh(a);
126
+ };
127
+ return { gh, calls: f.calls, refs, setRuns: (r) => { checkRuns = r; } };
128
+ }
129
+ const hd = (c) => c.repeat(40);
130
+ const bprs = () => ({ 5: { head: hd("1"), mergeState: "BEHIND", checks: [ok("build")] }, 6: { head: hd("2"), mergeState: "BEHIND", checks: [ok("build")] }, 7: { head: hd("3"), mergeState: "BEHIND", checks: [ok("build")] } });
131
+ const eb = (issue, pr, head) => entry(issue, pr, { head });
132
+ const fill = (t) => { t.add(eb(1, 5, hd("1"))); t.add(eb(2, 6, hd("2"))); t.add(eb(3, 7, hd("3"))); };
133
+
134
+ describe("mergetrain batches (#5837)", () => {
135
+ it("N BEHIND PRs share one candidate CI run, no update-branch, merged FIFO at their heads", async () => {
136
+ const w = batchWorld(bprs()); let clock = 0;
137
+ const t = createMergeTrain({ gh: w.gh, repo: "o/r", batchSize: 4, now: () => ++clock }); fill(t);
138
+ assert.deepEqual(await t.tick(), []); // builds + validating
139
+ assert.ok(w.refs.size === 1 && [...w.refs][0].startsWith("forge-train/staging/"));
140
+ const merges = w.calls.filter((a) => a[0] === "api" && a[3] === "repos/o/r/merges");
141
+ assert.equal(merges.length, 3);
142
+ assert.ok(merges.every((a) => a.includes("base=" + [...w.refs][0])), "merge into the candidate, never a rebase");
143
+ assert.equal(t.snapshot().batches[0].state, "validating");
144
+ assert.deepEqual(await t.tick(), []); // candidate checks green -> merging
145
+ const all = await t.tick(); // merges the batch in order
146
+ assert.deepEqual(all.map((e) => e.issue), [1, 2, 3]);
147
+ const pm = w.calls.filter((a) => a[1] === "merge").map((a) => [a[2], a.at(-1)]);
148
+ assert.deepEqual(pm.slice(0, 3), [["5", hd("1")], ["6", hd("2")], ["7", hd("3")]]);
149
+ assert.equal(w.calls.filter((a) => a[1] === "update-branch").length, 0);
150
+ assert.equal(w.refs.size, 0, "candidate ref deleted when finished");
151
+ assert.equal(t.stats().candidateRuns, 1);
152
+ assert.equal(t.stats().merged, 3);
153
+ assert.match(formatTrainSummary(t.stats()), /batches 1, candidate CI runs 1/);
154
+ });
155
+ it("a conflict on the candidate removes only that PR, as base.conflict with the files; the rest merge", async () => {
156
+ const w = batchWorld(bprs(), { conflict: [hd("2")] }); let clock = 0;
157
+ const t = createMergeTrain({ gh: w.gh, repo: "o/r", batchSize: 4, now: () => ++clock }); fill(t);
158
+ const ev = await t.tick();
159
+ assert.deepEqual(ev.map((e) => [e.kind, e.issue, e.code]), [["handback", 2, "base.conflict"]]);
160
+ assert.match(ev[0].detail, /x\.js/);
161
+ assert.deepEqual(t.snapshot().batches[0].prs.map((p) => p.pr), [5, 7]);
162
+ await t.tick(); await t.tick();
163
+ assert.deepEqual(w.calls.filter((a) => a[1] === "merge").map((a) => a[2]), ["5", "7"]);
164
+ });
165
+ it("a protection refusal keeps the PR in the train and holds order", async () => {
166
+ const w = batchWorld(bprs(), { mergeRefuse: "5" }); let clock = 0;
167
+ const t = createMergeTrain({ gh: w.gh, repo: "o/r", batchSize: 4, now: () => ++clock }); fill(t);
168
+ await t.tick(); await t.tick(); await t.tick();
169
+ assert.equal(t.size(), 3);
170
+ assert.deepEqual([...new Set(w.calls.filter((a) => a[1] === "merge").map((a) => a[2]))], ["5"]);
171
+ });
172
+ it("a restored validating batch re-reads the candidate checks and does not rebuild it", async () => {
173
+ const w = batchWorld(bprs(), { runs: [{ name: "build", status: "in_progress", conclusion: null }] }); let clock = 0;
174
+ const t = createMergeTrain({ gh: w.gh, repo: "o/r", batchSize: 4, now: () => ++clock }); fill(t);
175
+ await t.tick();
176
+ const snap = JSON.parse(JSON.stringify(t.snapshot()));
177
+ const before = w.calls.filter((a) => a[3] === "repos/o/r/git/refs" || a[3] === "repos/o/r/merges").length;
178
+ const t2 = createMergeTrain({ gh: w.gh, repo: "o/r", batchSize: 4, saved: snap, now: () => ++clock });
179
+ await t2.tick();
180
+ assert.equal(w.calls.filter((a) => a[3] === "repos/o/r/git/refs" || a[3] === "repos/o/r/merges").length, before);
181
+ assert.equal(t2.snapshot().batches[0].state, "validating");
182
+ assert.equal(t2.stats().candidateRuns, 1);
183
+ });
184
+ it("a candidate red on the bare base tip too deletes the ref, hands back nothing and goes on serially, without re-batching (#5838)", async () => {
185
+ const w = batchWorld(bprs(), { runs: [{ name: "build", status: "completed", conclusion: "failure" }] }); let clock = 0;
186
+ const t = createMergeTrain({ gh: w.gh, repo: "o/r", batchSize: 4, now: () => ++clock }); fill(t);
187
+ assert.deepEqual([...await t.tick(), ...await t.tick(), ...await t.tick()], []);
188
+ assert.equal(w.refs.size, 0);
189
+ assert.equal(t.snapshot().batches.length, 0);
190
+ assert.equal(t.stats().candidateRed, 1);
191
+ await t.tick();
192
+ assert.equal(w.calls.filter((a) => a[3] === "repos/o/r/git/refs").length, 1, "no second candidate");
193
+ assert.ok(w.calls.some((a) => a[1] === "update-branch"), "serial sync resumed");
194
+ });
195
+ it("batchSize 1 keeps the serial train: no candidate calls", async () => {
196
+ const w = batchWorld(bprs());
197
+ const t = createMergeTrain({ gh: w.gh, repo: "o/r" }); fill(t);
198
+ await t.tick();
199
+ assert.ok(!w.calls.some((a) => a[0] === "api" && String(a[3]).includes("merges")));
200
+ assert.equal(t.stats().batches, 0);
201
+ });
202
+ it("the summary line stays unchanged without batches", () => {
203
+ assert.ok(!/batches/.test(formatTrainSummary({ merged: 1, handedBack: {}, waits: [0], syncs: 0 })));
204
+ });
205
+ });
206
+
207
+ /** #5838: candidate refs whose sha names the PR heads merged into them; `bad(heads)` says whether `build` fails on that tree. */
208
+ function bisectWorld(prs, { bad, baseRed = false, rerunGreen = false, stuck = null } = {}) {
209
+ const f = fake(prs); const refs = new Map(); const reruns = new Set(); let ids = 100; const runIds = new Map();
210
+ const shaOf = (r) => `t_${r.replaceAll("/", "~")}_${refs.get(r).join(",")}`;
211
+ const runOf = (sha) => { if (!runIds.has(sha)) runIds.set(sha, ids++); return runIds.get(sha); };
212
+ const gh = async (a) => {
213
+ const s = a.join(" ");
214
+ if (s.includes("/git/ref/heads/") && !s.includes("forge-train")) return JSON.stringify({ object: { sha: "base" } });
215
+ if (s.includes("/git/ref/heads/forge-train")) return JSON.stringify({ object: { sha: shaOf(s.split("/git/ref/heads/")[1]) } });
216
+ if (s.startsWith("api -X POST repos/o/r/git/refs")) { f.calls.push(a); refs.set(a[5].slice(15), []); return "{}"; }
217
+ if (s.startsWith("api -X POST repos/o/r/merges")) { f.calls.push(a); refs.get(a.find((x) => x.startsWith("base=")).slice(5)).push(a.find((x) => x.startsWith("head=")).slice(5, 6)); return "{}"; }
218
+ if (s.startsWith("api -X DELETE repos/o/r/git/refs/heads/forge-train")) { f.calls.push(a); refs.delete(a[3].split("/heads/")[1]); return ""; }
219
+ if (s.startsWith("api -X POST repos/o/r/actions/jobs/")) { f.calls.push(a); reruns.add(Number(a[3].split("/")[5])); return ""; }
220
+ if (s.includes("/check-runs")) {
221
+ f.calls.push(a);
222
+ const sha = a[1].split("/")[4];
223
+ if (sha === "base") return JSON.stringify({ check_runs: [{ id: 1, name: "build", status: "completed", conclusion: baseRed ? "failure" : "success", html_url: "https://ci/base" }] });
224
+ const heads = sha.split("_")[2].split(",");
225
+ if (stuck && stuck(heads)) return JSON.stringify({ check_runs: [{ id: runOf(sha), name: "build", status: "in_progress", conclusion: null }] });
226
+ const id = runOf(sha), out = [{ id, name: "build", status: "completed", conclusion: bad(heads) ? "failure" : "success", html_url: `https://ci/${heads.join("")}` }];
227
+ if (reruns.has(id)) out.push({ id: id + 1000, name: "build", status: "completed", conclusion: rerunGreen || !bad(heads) ? "success" : "failure", html_url: `https://ci/${heads.join("")}/rerun` });
228
+ return JSON.stringify({ check_runs: out });
229
+ }
230
+ return f.gh(a);
231
+ };
232
+ return { gh, calls: f.calls, refs };
233
+ }
234
+ const four = () => Object.fromEntries([5, 6, 7, 8].map((pr, i) => [pr, { head: hd(String(i + 1)), checks: [ok("build")] }]));
235
+ const fill4 = (t) => [5, 6, 7, 8].forEach((pr, i) => t.add(eb(i + 1, pr, hd(String(i + 1)))));
236
+ const ticks = async (t, n) => { const out = []; for (let i = 0; i < n; i++) out.push(...await t.tick()); return out; };
237
+
238
+ describe("mergetrain bisection (#5838)", () => {
239
+ it("isolates the culprit of 4 within ceil(log2 4)+1 runs; only it is handed back, the innocents merge in the next batch", async () => {
240
+ const w = bisectWorld(four(), { bad: (h) => h.includes("3") }); let clock = 0;
241
+ const t = createMergeTrain({ gh: w.gh, repo: "o/r", batchSize: 4, now: () => ++clock }); fill4(t);
242
+ const ev = await ticks(t, 6);
243
+ const hb = ev.filter((e) => e.kind === "handback");
244
+ assert.deepEqual(hb.map((e) => [e.issue, e.code]), [[3, "ci.red"]]);
245
+ const batchId = [...w.calls.filter((a) => a[3] === "repos/o/r/git/refs")][0][5].split("/").at(-1);
246
+ assert.deepEqual(hb[0].culprit, { pr: 7, check: "build", url: "https://ci/3", batch: batchId });
247
+ assert.match(hb[0].detail, new RegExp(`broke the merged tree of train batch ${batchId}.*build`));
248
+ const runsSpent = t.stats().candidateRuns - 1; // the original candidate run is not a bisection step
249
+ assert.ok(runsSpent <= Math.ceil(Math.log2(4)) + 1, `spent ${runsSpent}`);
250
+ assert.equal(t.stats().bisections, 1); assert.equal(t.stats().culprits, 1);
251
+ // half candidates hold the FIFO first half: PRs 5,6 then 7
252
+ assert.deepEqual(w.calls.filter((a) => a[3] === "repos/o/r/merges" && /bisect/.test(a.at(-1))).map((a) => a.at(-1).split("#")[1]), ["5", "6", "7"]);
253
+ const rest = await ticks(t, 4);
254
+ assert.deepEqual(rest.filter((e) => e.kind === "merged").map((e) => e.issue), [1, 2, 4]);
255
+ assert.equal(t.stats().batches, 2, "the innocents shared a second batch");
256
+ assert.equal(w.calls.filter((a) => a[1] === "update-branch").length, 0, "no serial fallback, no lane rerun");
257
+ assert.equal(w.refs.size, 0, "every candidate ref deleted");
258
+ assert.match(formatTrainSummary(t.stats()), /batches 2, candidate CI runs \d+ \(1 red\), bisections 1, culprits 1/);
259
+ });
260
+ it("a red base tip calls onBaseRed, hands back no PR and builds no candidate on that tip again", async () => {
261
+ const w = bisectWorld(four(), { bad: () => true, baseRed: true }); let clock = 0; const reported = [];
262
+ const t = createMergeTrain({ gh: w.gh, repo: "o/r", batchSize: 4, now: () => ++clock, onBaseRed: async (r) => { reported.push(r); } }); fill4(t);
263
+ const ev = await ticks(t, 4);
264
+ assert.ok(!ev.some((e) => e.kind === "handback"));
265
+ assert.equal(reported.length, 1);
266
+ assert.equal(reported[0].baseSha, "base"); assert.deepEqual(reported[0].checks.map((c) => c.name), ["build"]);
267
+ assert.equal(t.stats().bisections, 0); assert.equal(t.stats().redBase, 1); assert.equal(t.size(), 4);
268
+ await ticks(t, 2);
269
+ assert.equal(w.calls.filter((a) => a[3] === "repos/o/r/git/refs").length, 1, "no new candidate on the red tip");
270
+ assert.equal(JSON.parse(JSON.stringify(t.snapshot())).redBases.staging, "base");
271
+ });
272
+ it("a known-flaky check green on its one rerun merges the batch without bisection", async () => {
273
+ const w = bisectWorld(four(), { bad: () => true, rerunGreen: true }); let clock = 0;
274
+ const t = createMergeTrain({ gh: w.gh, repo: "o/r", batchSize: 4, now: () => ++clock, flaky: ["build"] }); fill4(t);
275
+ const ev = await ticks(t, 4);
276
+ assert.equal(w.calls.filter((a) => String(a[3]).includes("/actions/jobs/")).length, 1, "rerun once");
277
+ assert.deepEqual(ev.map((e) => e.kind), ["merged", "merged", "merged", "merged"]);
278
+ assert.equal(t.stats().bisections, 0); assert.equal(t.stats().culprits, 0);
279
+ });
280
+ it("a half that never finishes exhausts the budget: the whole batch falls back to serial phase-1 merging", async () => {
281
+ const w = bisectWorld(four(), { bad: (h) => h.includes("3"), stuck: (h) => h.length === 2 }); let clock = 0;
282
+ const t = createMergeTrain({ gh: w.gh, repo: "o/r", batchSize: 4, batchTimeoutMs: 5, now: () => (clock += 3) }); fill4(t);
283
+ const ev = await ticks(t, 6);
284
+ assert.ok(!ev.some((e) => e.kind === "handback"));
285
+ assert.equal(t.snapshot().batches.length, 0);
286
+ assert.ok(t.snapshot().entries.every((e) => e.noBatch), "every member serial");
287
+ });
288
+ it("a spent run budget goes serial instead of building another half", async () => {
289
+ const w = bisectWorld(four(), { bad: (h) => h.includes("3") }); let clock = 0;
290
+ const saved = { entries: [5, 6, 7, 8].map((pr, i) => ({ ...eb(i + 1, pr, hd(String(i + 1))), since: 1 })), stats: { merged: 0, handedBack: {}, waits: [], syncs: 0, batches: 1, candidateRuns: 3 },
291
+ batches: [{ id: "x", base: "staging", baseSha: "base", prs: [5, 6, 7, 8].map((pr, i) => ({ issue: i + 1, pr, head: hd(String(i + 1)) })), candidate: "forge-train/staging/x", candSha: "t_forge-train~staging~x_1,2,3,4", state: "bisecting", startedAt: 1,
292
+ bisect: { runs: 3, budget: 3, failed: [{ name: "build", url: "u" }], frame: [3, 4], step: "probe", stale: [], at: 1, halves: 2 } }] };
293
+ const t = createMergeTrain({ gh: w.gh, repo: "o/r", batchSize: 4, saved, now: () => ++clock });
294
+ assert.deepEqual(await t.tick(), []);
295
+ assert.ok(t.snapshot().entries.every((e) => e.noBatch)); assert.equal(t.snapshot().batches.length, 0);
296
+ assert.equal(w.calls.filter((a) => a[3] === "repos/o/r/git/refs").length, 0);
297
+ });
298
+ it("a resume mid-bisection re-reads the half's checks and rebuilds nothing; a phase-2a snapshot still restores", async () => {
299
+ const w = bisectWorld(four(), { bad: (h) => h.includes("3") }); let clock = 0;
300
+ const t = createMergeTrain({ gh: w.gh, repo: "o/r", batchSize: 4, now: () => ++clock }); fill4(t);
301
+ await ticks(t, 3); // build, red -> rerun, rerun red -> probe
302
+ await t.tick(); // probe green -> first half built
303
+ const snap = JSON.parse(JSON.stringify(t.snapshot()));
304
+ assert.equal(snap.batches[0].bisect.step, "half");
305
+ const built = w.calls.filter((a) => a[3] === "repos/o/r/git/refs" || a[3] === "repos/o/r/merges").length;
306
+ const t2 = createMergeTrain({ gh: w.gh, repo: "o/r", batchSize: 4, saved: snap, now: () => ++clock });
307
+ await t2.tick();
308
+ assert.equal(w.calls.filter((a) => a[3] === "repos/o/r/git/refs" || a[3] === "repos/o/r/merges").length, built + 2, "only the next half (one ref + one merge)");
309
+ assert.deepEqual(t2.snapshot().batches[0].bisect.frame, [3, 4]);
310
+ const old = createMergeTrain({ gh: w.gh, repo: "o/r", saved: { entries: [], stats: { merged: 1, handedBack: {}, waits: [], syncs: 0, batches: 1, candidateRuns: 1 }, batches: [] } });
311
+ assert.deepEqual([old.stats().bisections, old.stats().culprits], [0, 0]);
312
+ });
313
+ });
314
+
315
+ describe("mergetrain phase 3 (#5839)", () => {
316
+ it("replays the post-merge record: notes are posted and a keepOpen record leaves the issue open", async () => {
317
+ const f = fake({ 5: { head: H, checks: [ok("build")] }, 6: { head: H, checks: [ok("build")], base: "main" } });
318
+ const t = createMergeTrain({ gh: f.gh, repo: "o/r" });
319
+ t.add(entry(1, 5, { postMerge: { keepOpen: true, notes: [{ marker: "FORGE:TRACKED", body: "left open" }] } }));
320
+ await t.tick();
321
+ assert.ok(f.calls.some((a) => a[0] === "issue" && a[1] === "comment" && a.join(" ").includes("FORGE:TRACKED")));
322
+ assert.ok(!f.calls.some((a) => a[0] === "issue" && a[1] === "close"), "keepOpen: not closed");
323
+ t.add(entry(2, 6, { lane: "main" }));
324
+ await t.tick();
325
+ assert.ok(f.calls.some((a) => a[0] === "issue" && a[1] === "close"), "a plain entry closes");
326
+ });
327
+ it("counts base.conflict hand-backs and lane-side counts per batch; p90 in the report line", async () => {
328
+ const f = fake({ 5: { head: H, mergeable: "CONFLICTING", checks: [ok("build")] } });
329
+ const t = createMergeTrain({ gh: f.gh, repo: "o/r" }); t.add(entry(1, 5, { laneSide: { syncs: 2, baseConflicts: 1 } }));
330
+ const ev = await t.tick();
331
+ assert.equal(ev[0].code, "base.conflict");
332
+ const st = t.stats();
333
+ assert.equal(st.baseConflicts, 1); assert.deepEqual(st.laneSide, { syncs: 2, baseConflicts: 1 });
334
+ assert.match(formatTrainSummary({ ...st, waits: [60000, 120000, 600000] }), /p90 10\.0 min.*base\.conflict 1 \(lane 1\)/);
335
+ assert.equal(waitP90([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]), 9);
336
+ });
337
+ it("snapshot round-trips the record and counts; a phase-2 snapshot restores as zero", () => {
338
+ const t = createMergeTrain({ gh: async () => "", repo: "o/r" });
339
+ t.add(entry(1, 5, { postMerge: { keepOpen: false, notes: [] }, laneSide: { syncs: 1, baseConflicts: 0 } }));
340
+ const snap = JSON.parse(JSON.stringify(t.snapshot()));
341
+ const t2 = createMergeTrain({ gh: async () => "", repo: "o/r", saved: snap });
342
+ assert.deepEqual(t2.snapshot().entries[0].postMerge, { keepOpen: false, notes: [] }); assert.equal(t2.stats().laneSide.syncs, 1);
343
+ const old = { entries: [], stats: { merged: 2, handedBack: {}, waits: [], syncs: 1 } };
344
+ const t3 = createMergeTrain({ gh: async () => "", repo: "o/r", saved: old });
345
+ assert.deepEqual([t3.stats().baseConflicts, t3.stats().laneSide], [0, { syncs: 0, baseConflicts: 0 }]);
346
+ t3.restore(old); assert.equal(t3.stats().baseConflicts, 0);
347
+ });
348
+ });
@@ -0,0 +1,84 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * #5949: dispatcher side of repo seeding. Builds an incremental `git bundle` from the dispatching host's own clone (everything the
5
+ * agent's mirror lacks; `--all`-equivalent when the mirror is absent) and uploads it through the pool router in checksummed,
6
+ * resumable chunks (`transport.mirrors` / `transport.seed`). Any failure throws; the caller falls back to the GitHub path.
7
+ */
8
+ import { execFile } from "node:child_process";
9
+ import { createHash } from "node:crypto";
10
+ import { promisify } from "node:util";
11
+
12
+ const run = promisify(execFile);
13
+ /** Decoded bytes per chunk (the agent and router cap it at 512 KB). */
14
+ export const CHUNK = 384 * 1024;
15
+ const MAX_CHUNK_RETRIES = 3;
16
+ const sha256 = (buf) => createHash("sha256").update(buf).digest("hex");
17
+ const git = async (cwd, args, opts = {}) => (await run("git", args, { cwd, encoding: opts.binary ? "buffer" : "utf8", maxBuffer: 1 << 30 })).stdout;
18
+
19
+ /** The refs to ship: origin's branches (the agent maps them to refs/heads/*; local branches only when there are none) and tags; never the origin/HEAD symref. */
20
+ async function wantRefs(repoDir) {
21
+ const list = async (...pats) => (await git(repoDir, ["for-each-ref", "--format=%(refname)", ...pats])).split("\n").filter(Boolean);
22
+ const origin = (await list("refs/remotes/origin")).filter((r) => r !== "refs/remotes/origin/HEAD");
23
+ return [...(origin.length ? origin : await list("refs/heads")), ...(await list("refs/tags"))];
24
+ }
25
+
26
+ /**
27
+ * The bundle bytes for `repoDir` given the agent's `tips` ({ref: sha} or "absent"), or null when the agent already has everything.
28
+ * Tips the dispatcher's repo does not contain are skipped as exclusions (the bundle is then larger, never invalid).
29
+ */
30
+ export async function buildBundle(repoDir, tips) {
31
+ const refs = await wantRefs(repoDir);
32
+ if (!refs.length) throw new Error("local repo has no refs to bundle");
33
+ const excl = [];
34
+ if (tips && typeof tips === "object") {
35
+ for (const sha of new Set(Object.values(tips))) {
36
+ try { await git(repoDir, ["cat-file", "-e", `${sha}^{commit}`]); excl.push(`^${sha}`); } catch { /* unknown here: not excluded */ }
37
+ }
38
+ }
39
+ try { return await git(repoDir, ["bundle", "create", "-", ...refs, ...excl], { binary: true }); }
40
+ catch (e) { if (/empty bundle/i.test(String(e.stderr))) return null; throw e; }
41
+ }
42
+
43
+ /** Size of the whole repo's packed objects in bytes (what a full transfer would move). */
44
+ async function repoBytes(repoDir) {
45
+ try { const o = await git(repoDir, ["count-objects", "-v"]); const n = (k) => Number(new RegExp(`^${k}: (\\d+)`, "m").exec(o)?.[1] ?? 0); return (n("size") + n("size-pack")) * 1024; } catch { return 0; }
46
+ }
47
+
48
+ /**
49
+ * Seed the agent mirror of `slug` for sandbox `id`. Returns {sent, bytes, chunks, full, ms, upToDate}. Throws on any failure;
50
+ * an older router/agent without the endpoints (404/405 from `transport.mirrors`) throws `{unsupported: true}`.
51
+ */
52
+ export async function seedMirror({ transport, id, slug, cacheKey = null, repoDir, now = () => Date.now() }) {
53
+ if (typeof transport.mirrors !== "function" || typeof transport.seed !== "function") throw Object.assign(new Error("transport has no mirror seeding"), { unsupported: true });
54
+ const t0 = now();
55
+ if (!(await wantRefs(repoDir).catch(() => [])).length) throw new Error("local repo has no refs to bundle"); // nothing to seed from: no round trip
56
+ const q = await transport.mirrors(id, { slug, cache_key: cacheKey });
57
+ const tips = q?.mirrors?.[slug];
58
+ if (tips === undefined) throw Object.assign(new Error("agent answered /mirrors without this repo"), { unsupported: true });
59
+ const full = tips === "absent";
60
+ const bundle = await buildBundle(repoDir, full ? null : tips);
61
+ if (!bundle) return { sent: false, bytes: 0, chunks: 0, full, ms: now() - t0, upToDate: true };
62
+ const upload = sha256(bundle), base = { slug, cache_key: cacheKey, upload };
63
+ let offset = (await transport.mirrors(id, { slug, cache_key: cacheKey, upload }))?.upload_offset ?? 0, chunks = 0, sent = 0;
64
+ if (!Number.isInteger(offset) || offset < 0 || offset > bundle.length) offset = 0;
65
+ while (offset < bundle.length) {
66
+ const buf = bundle.subarray(offset, offset + CHUNK);
67
+ const body = { ...base, offset, data_b64: buf.toString("base64"), sha256: sha256(buf) };
68
+ let res = null;
69
+ for (let attempt = 0; attempt < MAX_CHUNK_RETRIES && res === null; attempt++) {
70
+ try { res = await transport.seed(id, body); }
71
+ catch (e) {
72
+ if (e.status === 409 && Number.isInteger(e.offset)) { res = { offset: e.offset, resumed: true }; break; } // the agent has a different length: resume from its offset
73
+ if (e.status && e.status < 500 && e.status !== 429) throw e;
74
+ if (attempt === MAX_CHUNK_RETRIES - 1) throw e;
75
+ }
76
+ }
77
+ if (!res.resumed) { sent += buf.length; chunks++; }
78
+ offset = res.offset;
79
+ }
80
+ await transport.seed(id, { ...base, finish: { size: bundle.length, sha256: upload } });
81
+ const ms = now() - t0, whole = await repoBytes(repoDir);
82
+ const saved_ms = sent > 0 && ms > 0 && whole > sent ? Math.round(((whole - sent) / sent) * ms) : null; // estimate: the whole repo at this upload's own rate
83
+ return { sent: true, bytes: sent, bundle_bytes: bundle.length, chunks, full, ms, saved_ms, upToDate: false };
84
+ }
@@ -243,3 +243,65 @@ describe("#5755 one env issue per signature", () => {
243
243
  assert.equal(byIssue[1].envHold.envIssue, undefined);
244
244
  });
245
245
  });
246
+
247
+ describe("#5859 agent restart: correlated sandbox loss is sandbox.lost, not engine-error", () => {
248
+ const LOST = (n, agent = "legion") => ({ terminalReason: "engine-error", detail: `sandbox fake-${n} exited without a result`, lostWithoutResult: true, agent });
249
+ const BREAKER = { errors: 3, window_min: 10 };
250
+
251
+ it("agent restart: 20 lanes lost on one agent are sandbox.lost, not engine-errors", async () => {
252
+ const issues = Array.from({ length: 20 }, (_, i) => i + 1);
253
+ const script = Object.fromEntries(issues.map((n) => [n, [LOST(n), MERGED]]));
254
+ const store = memStore(), logged = [];
255
+ store.log = (ev) => logged.push(ev);
256
+ let probes = 0; // the agent is still booting for its first two probes, then reports a fresh boot
257
+ const r = await harness({ script, issues, parallel: 20, store, envHold: undefined,
258
+ extra: { envHold: null, breaker: BREAKER, remote: { agentHealthy: async () => ++probes > 2 } } });
259
+ assert.ok(!r.updates.some((u) => u.outcome === "breaker"), "the breaker never trips");
260
+ const lost = r.updates.filter((u) => u.code === "sandbox.lost");
261
+ assert.deepEqual([...new Set(lost.map((u) => u.issue))].sort((a, b) => a - b), issues, "all 20 requeued with sandbox.lost");
262
+ for (const n of issues) assert.equal(r.byIssue[n].outcome, "merged", `#${n} admitted again once the agent is healthy`);
263
+ assert.equal(r.calls.length, 40, "each lane relaunched exactly once");
264
+ const st = store.load();
265
+ assert.deepEqual(st.engineErrors, {}, "relaunch counters unchanged");
266
+ assert.deepEqual(st.errorTimes, [], "nothing counted by the breaker");
267
+ assert.equal(st.breaker, null);
268
+ const ev = logged.filter((e) => e.event === "agent.restarted");
269
+ assert.equal(ev.length, 1, "one batch-level event");
270
+ assert.equal(ev[0].requeued, 20);
271
+ assert.match(ev[0].detail, /^agent legion restarted at \d{4}-.*Z; 20 lanes requeued$/);
272
+ assert.equal(r.updates.filter((u) => u.event === "agent.restarted").length, 1);
273
+ assert.equal(st.agentRestarts.length, 1);
274
+ assert.equal(st.agentRestarts[0].requeued, 20);
275
+ assert.ok(probes >= 3, "admission waited for the agent's healthy probe");
276
+ });
277
+
278
+ it("agent restart: failure after healthy is an ordinary engine-error", async () => {
279
+ const store = memStore();
280
+ const r = await harness({ script: { 1: [LOST(1), LOST(1), MERGED], 2: [LOST(2), MERGED], 3: [LOST(3), MERGED] }, issues: [1, 2, 3], parallel: 3, store,
281
+ envHold: undefined, extra: { envHold: null, breaker: { errors: 5, window_min: 10 } } });
282
+ assert.deepEqual(r.calls.filter((c) => c.n === 1).length, 3, "#1: sandbox.lost requeue, then the ordinary single relaunch");
283
+ assert.ok(r.updates.some((u) => u.issue === 1 && /^relaunching once: sandbox fake-1/.test(u.detail ?? "")));
284
+ const st = store.load();
285
+ assert.deepEqual(st.engineErrors, { 1: 1 });
286
+ assert.equal(st.errorTimes.length, 1, "the second loss of #1 counts toward the breaker");
287
+ for (const n of [1, 2, 3]) assert.equal(r.byIssue[n].outcome, "merged");
288
+ });
289
+
290
+ it("two unrelated sandbox exits stay engine-errors", async () => {
291
+ const store = memStore();
292
+ const r = await harness({ script: { 1: [LOST(1), MERGED], 2: [LOST(2, "box2"), MERGED], 3: [LOST(3), MERGED] }, issues: [1, 2, 3], parallel: 3, store,
293
+ envHold: undefined, extra: { envHold: null, breaker: { errors: 5, window_min: 10 } } });
294
+ // #1 and #3 share an agent (2 < 3), #2 is on another: no restart
295
+ assert.ok(!r.updates.some((u) => u.code === "sandbox.lost" || u.event === "agent.restarted"));
296
+ const st = store.load();
297
+ assert.deepEqual(st.engineErrors, { 1: 1, 2: 1, 3: 1 });
298
+ assert.equal(st.errorTimes.length, 3, "each counts toward the breaker as today");
299
+ assert.equal(st.agentRestarts, undefined);
300
+ });
301
+
302
+ it("two lost lanes with a 3-error breaker still trip it", async () => {
303
+ const r = await harness({ script: { 1: [LOST(1), EE("real bug")], 2: [LOST(2, "box2"), EE("real bug 2")] }, issues: [1, 2], parallel: 2,
304
+ envHold: undefined, extra: { envHold: null, breaker: { errors: 2, window_min: 10 } } });
305
+ assert.ok(r.updates.some((u) => u.outcome === "breaker"));
306
+ });
307
+ });
@@ -39,6 +39,7 @@ describe("orchestrate stacking (#5831)", () => {
39
39
  assert.deepEqual(h.calls.map((c) => [c.n, !!c.ctx.plan]), [[1, false], [2, true], [2, false]]);
40
40
  assert.deepEqual(h.calls[2].ctx.planned, { contractHash: HASH, baseSha: SHA });
41
41
  assert.deepEqual(h.updates.filter((u) => u.issue === 2).map((u) => u.outcome), ["planned", "merged"]);
42
+ assert.ok(h.updates.find((u) => u.issue === 2 && u.outcome === "merged").plan_minutes >= 0, "#5834: plan lane minutes ride the final row");
42
43
  assert.deepEqual(h.events.filter((e) => e.event?.startsWith("STACK_")).map((e) => e.event), ["STACK_PLAN_START", "STACK_PLANNED"]);
43
44
  });
44
45
  it("plan: one plan lane per issue; a failed plan lane is plan-failed, not counted, and the build lane runs without ctx.planned", async () => {
@@ -91,6 +92,8 @@ describe("orchestrate stacked builds, phase 2 (#5832)", () => {
91
92
  assert.equal(ev.issue, 2); assert.equal(ev.stacked, true);
92
93
  const row = h.updates.find((u) => u.issue === 2 && u.outcome === "merged");
93
94
  assert.equal(row.stacked, true); assert.equal(row.stackedOn.dependency, 1);
95
+ assert.deepEqual(row.deps, [1], "#5834: the row carries its in-batch edges");
96
+ assert.ok(Number.isFinite(row.admitted_at) && row.ended_at >= row.admitted_at, "#5834: admission and end timestamps");
94
97
  });
95
98
  it("full: nothing is stacked before the dependency is PR-ready (it falls back to waiting for the merge)", async () => {
96
99
  let ready = false;
@@ -118,5 +121,24 @@ describe("orchestrate stacked builds, phase 2 (#5832)", () => {
118
121
  assert.deepEqual(saved.stackedTried, [2]);
119
122
  assert.equal(saved.stacked[2].dependency, 1);
120
123
  });
124
+ it("cascade (#5833): a stack.replan end requeues the dependent as a normal lane; the row records the cascade and its rework", async () => {
125
+ let gate; const g = new Promise((r) => { gate = r; });
126
+ const calls = [];
127
+ const runOne = async (n, lane, ctx = {}) => {
128
+ calls.push({ n, ctx });
129
+ if (n === 1) { await g; return { terminalReason: "merged", cost_usd: 0 }; }
130
+ if (ctx.plan) return { terminalReason: "planned", planned: { contractHash: HASH, baseSha: SHA } };
131
+ if (ctx.stackedOn) { gate(); return { terminalReason: "deferred", code: "stack.replan", cascade: "replan", cascades: ["replan"], cascade_cost_usd: 0.25, cascade_minutes: 2, cost_usd: 0.25, detail: "dependency ended unsatisfied" }; }
132
+ return { terminalReason: "merged", cost_usd: 0 };
133
+ };
134
+ const updates = [], events = [];
135
+ const store = { load: () => null, save: () => {}, log: (r) => events.push(r) };
136
+ await orchestrate({ issues: [1, 2], parallel: 2, readBody: body, runOne, stacking: "full", readPrReady: async () => RD, store, onUpdate: (r) => updates.push(r), maxDeferrals: 2 });
137
+ const cas = updates.find((u) => u.issue === 2 && u.cascade);
138
+ assert.equal(cas.cascade, "replan"); assert.equal(cas.stacked, true); assert.equal(cas.cascade_cost_usd, 0.25);
139
+ assert.ok(events.some((e) => e.event === "STACK_CASCADE" && e.issue === 2 && e.cascade === "replan"));
140
+ const later = calls.filter((c) => c.n === 2 && !c.ctx.plan && !c.ctx.stackedOn);
141
+ assert.equal(later.length, 1, "rebuilt as a normal lane");
142
+ assert.equal(updates.filter((u) => u.issue === 2).pop().outcome, "merged");
143
+ });
121
144
  });
122
-