forgedock 1.53.0 → 1.54.1

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 (186) hide show
  1. package/.claude-plugin/marketplace.json +51 -0
  2. package/README.md +8 -2
  3. package/bin/auth/app-manifest.mjs +89 -0
  4. package/bin/auth/app-manifest.test.mjs +75 -0
  5. package/bin/auth/app-token.mjs +258 -0
  6. package/bin/auth/app-token.test.mjs +240 -0
  7. package/bin/brand.mjs +7 -0
  8. package/bin/config-history.mjs +151 -0
  9. package/bin/config-schema.mjs +115 -0
  10. package/bin/demo.mjs +65 -11
  11. package/bin/engine/outcome-codes.mjs +6 -3
  12. package/bin/engine/telemetry-seam.mjs +8 -2
  13. package/bin/engine/telemetry-seam.test.mjs +17 -0
  14. package/bin/engine-cli.mjs +57 -20
  15. package/bin/first-run.mjs +122 -0
  16. package/bin/forgedock.mjs +128 -146
  17. package/bin/help-text.mjs +144 -0
  18. package/bin/hooks/pre-tool-use.mjs +7 -0
  19. package/bin/journey.mjs +82 -83
  20. package/bin/lean/acceptance.mjs +313 -0
  21. package/bin/lean/acceptance.test.mjs +215 -0
  22. package/bin/lean/activation.mjs +18 -0
  23. package/bin/lean/activation.test.mjs +23 -1
  24. package/bin/lean/batch-health.mjs +74 -1
  25. package/bin/lean/batch-health.test.mjs +54 -1
  26. package/bin/lean/batch.test.mjs +11 -9
  27. package/bin/lean/branchlock.mjs +54 -0
  28. package/bin/lean/branchlock.test.mjs +49 -0
  29. package/bin/lean/ceiling.mjs +72 -0
  30. package/bin/lean/ceiling.test.mjs +54 -0
  31. package/bin/lean/ci-budget.mjs +366 -0
  32. package/bin/lean/ci-budget.test.mjs +167 -0
  33. package/bin/lean/conformance.e2e.test.mjs +7 -0
  34. package/bin/lean/conformance.mjs +77 -19
  35. package/bin/lean/conformance.test.mjs +129 -3
  36. package/bin/lean/context.mjs +35 -6
  37. package/bin/lean/context.test.mjs +27 -1
  38. package/bin/lean/depcache.mjs +25 -1
  39. package/bin/lean/depcache.test.mjs +26 -0
  40. package/bin/lean/e2e.mjs +18 -2
  41. package/bin/lean/e2e.test.mjs +26 -1
  42. package/bin/lean/effects.mjs +40 -11
  43. package/bin/lean/execution.test.mjs +24 -0
  44. package/bin/lean/facts.mjs +3 -3
  45. package/bin/lean/facts.test.mjs +5 -0
  46. package/bin/lean/fixround.mjs +14 -0
  47. package/bin/lean/fixround.test.mjs +25 -2
  48. package/bin/lean/gh-assoc.test.mjs +2 -1
  49. package/bin/lean/integration.mjs +100 -9
  50. package/bin/lean/integration.test.mjs +98 -0
  51. package/bin/lean/issuewatch-parity.mjs +64 -0
  52. package/bin/lean/issuewatch-parity.test.mjs +127 -0
  53. package/bin/lean/issuewatch-release.test.mjs +1 -1
  54. package/bin/lean/issuewatch.mjs +34 -5
  55. package/bin/lean/issuewatch.test.mjs +3 -2
  56. package/bin/lean/lean.mjs +316 -74
  57. package/bin/lean/lean.test.mjs +397 -24
  58. package/bin/lean/mechfix.mjs +136 -0
  59. package/bin/lean/mechfix.test.mjs +95 -0
  60. package/bin/lean/orchestrate.mjs +20 -2
  61. package/bin/lean/phaseledger.mjs +47 -5
  62. package/bin/lean/phaseledger.test.mjs +30 -1
  63. package/bin/lean/precheck.mjs +23 -4
  64. package/bin/lean/precheck.test.mjs +14 -1
  65. package/bin/lean/prereq.mjs +28 -0
  66. package/bin/lean/prereq.test.mjs +20 -0
  67. package/bin/lean/probe.mjs +4 -2
  68. package/bin/lean/prodparity.mjs +52 -0
  69. package/bin/lean/prodparity.test.mjs +67 -0
  70. package/bin/lean/prompts.mjs +69 -12
  71. package/bin/lean/recovery.test.mjs +1 -1
  72. package/bin/lean/release-io.test.mjs +42 -0
  73. package/bin/lean/release-postmerge.mjs +6 -0
  74. package/bin/lean/release-preflight.mjs +58 -0
  75. package/bin/lean/release-preflight.test.mjs +114 -0
  76. package/bin/lean/release-rehearsal.mjs +8 -7
  77. package/bin/lean/release-review.mjs +67 -11
  78. package/bin/lean/release-review.test.mjs +128 -1
  79. package/bin/lean/release-snapshot.mjs +188 -0
  80. package/bin/lean/release-snapshot.test.mjs +190 -0
  81. package/bin/lean/release.mjs +87 -13
  82. package/bin/lean/release.test.mjs +104 -0
  83. package/bin/lean/render.mjs +1 -1
  84. package/bin/lean/replan.mjs +184 -0
  85. package/bin/lean/replan.test.mjs +110 -0
  86. package/bin/lean/resume.mjs +9 -7
  87. package/bin/lean/resume.test.mjs +16 -0
  88. package/bin/lean/schedd.mjs +34 -1
  89. package/bin/lean/schedd.test.mjs +21 -1
  90. package/bin/lean/selfreview.mjs +94 -0
  91. package/bin/lean/selfreview.test.mjs +58 -1
  92. package/bin/lean/selftest-gate.mjs +22 -0
  93. package/bin/lean/selftest-gate.test.mjs +18 -1
  94. package/bin/lean/selftest-journey.mjs +234 -0
  95. package/bin/lean/selftest-journey.test.mjs +130 -0
  96. package/bin/lean/selftest-live.mjs +2 -1
  97. package/bin/lean/seqlease.mjs +35 -1
  98. package/bin/lean/seqlease.test.mjs +15 -0
  99. package/bin/lean/seqreserve.e2e.test.mjs +135 -0
  100. package/bin/lean/seqreserve.mjs +73 -0
  101. package/bin/lean/seqreserve.test.mjs +134 -0
  102. package/bin/lean/sequence.mjs +35 -6
  103. package/bin/lean/seqversioned.mjs +147 -0
  104. package/bin/lean/stagestamp.mjs +28 -0
  105. package/bin/lean/stagestamp.test.mjs +32 -0
  106. package/bin/lean/surfaces.mjs +75 -0
  107. package/bin/lean/surfaces.test.mjs +59 -0
  108. package/bin/lean/toolplace.mjs +28 -0
  109. package/bin/lean/toolplace.test.mjs +24 -0
  110. package/bin/lean/toolstats.mjs +3 -1
  111. package/bin/lean/toolstats.test.mjs +11 -0
  112. package/bin/lean/validatebest.mjs +28 -0
  113. package/bin/lean/validatebest.test.mjs +27 -0
  114. package/bin/pool/agent.mjs +9 -0
  115. package/bin/pool/docker.mjs +5 -0
  116. package/bin/pool/router.mjs +8 -4
  117. package/bin/prereqs.mjs +111 -0
  118. package/bin/replay-timelapse.mjs +149 -0
  119. package/bin/review-staging.mjs +100 -16
  120. package/bin/review-staging.test.mjs +18 -0
  121. package/bin/runner.mjs +49 -7
  122. package/bin/splash-install.mjs +157 -0
  123. package/bin/stats/aggregate.mjs +8 -1
  124. package/bin/stats/conformance-outcomes.mjs +100 -19
  125. package/bin/stats/conformance-outcomes.test.mjs +87 -1
  126. package/bin/stats/depth.mjs +88 -31
  127. package/bin/stats/depth.test.mjs +63 -38
  128. package/bin/stats/efficiency.mjs +26 -5
  129. package/bin/stats/efficiency.test.mjs +45 -1
  130. package/bin/stats/first-review.mjs +77 -0
  131. package/bin/stats/first-review.test.mjs +36 -0
  132. package/bin/stats/firstmerge.mjs +40 -0
  133. package/bin/stats/firstmerge.test.mjs +41 -0
  134. package/bin/stats/github-source.mjs +51 -13
  135. package/bin/stats/index.mjs +91 -15
  136. package/bin/stats/local-source.mjs +1 -0
  137. package/bin/stats/origin.mjs +80 -0
  138. package/bin/stats/origin.test.mjs +58 -0
  139. package/bin/stats/render.mjs +3 -1
  140. package/bin/stats/scoreboard.mjs +137 -0
  141. package/bin/stats/scoreboard.test.mjs +87 -0
  142. package/bin/stats/stats.test.mjs +80 -0
  143. package/bin/tui.mjs +3 -2
  144. package/commands/bootstrap.md +15 -14
  145. package/commands/deploy-pr.md +18 -3
  146. package/commands/forge-stats.md +1 -1
  147. package/commands/forgedock-ci-setup.md +28 -0
  148. package/commands/forgedock-init.md +4 -5
  149. package/commands/issue.md +2 -0
  150. package/commands/milestone.md +9 -1
  151. package/commands/replay.md +2 -0
  152. package/commands/review-pr-staging.md +4 -1
  153. package/commands/work-on/close.md +8 -0
  154. package/docs/CI.md +1 -1
  155. package/docs/CONFIG.md +105 -10
  156. package/docs/ISSUE-WATCH.md +23 -0
  157. package/docs/OUTCOME-CODES.md +1 -0
  158. package/docs/REPLAY.md +9 -0
  159. package/docs/SELFTEST.md +11 -0
  160. package/docs/STATS.md +19 -2
  161. package/docs/eval/README.md +6 -0
  162. package/docs/eval/adversarial-bench.md +68 -0
  163. package/docs/eval/corpus/adversarial-v1.json +285 -0
  164. package/docs/eval/feature-bench.md +42 -0
  165. package/docs/eval/feature-specs/crud-auth/journeys/notes-crud-isolated.mjs +21 -0
  166. package/docs/eval/feature-specs/crud-auth/journeys/register-login.mjs +12 -0
  167. package/docs/eval/feature-specs/crud-auth/spec.md +15 -0
  168. package/docs/site/start-a-new-project.md +2 -1
  169. package/package.json +5 -2
  170. package/plugins/forgedock-splash/.claude-plugin/plugin.json +10 -0
  171. package/plugins/forgedock-splash/README.md +27 -0
  172. package/plugins/forgedock-splash/hooks/hooks.json +1 -0
  173. package/plugins/forgedock-splash/hooks/register.tsx +74 -0
  174. package/plugins/forgedock-splash/hooks/scene.ts +222 -0
  175. package/plugins/forgedock-splash/types/index.d.ts +10 -0
  176. package/scripts/bench-adversarial.mjs +216 -0
  177. package/scripts/bench-feature.mjs +170 -0
  178. package/scripts/bench-lightlane.mjs +2 -2
  179. package/scripts/bootstrap-create.mjs +2 -2
  180. package/scripts/bootstrap-validate.mjs +35 -2
  181. package/scripts/check-spec-size.sh +4 -3
  182. package/scripts/check-spec-size.test.sh +3 -0
  183. package/scripts/plan-validate-live.mjs +40 -6
  184. package/scripts/review-pr-staging-scope.test.sh +1 -1
  185. package/scripts/review-staging-post.sh +23 -0
  186. package/scripts/review-staging-post.test.sh +8 -0
@@ -0,0 +1,215 @@
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 { parseAcceptance, validateEpic, declaredAcceptance, renderAcceptanceComment, acceptanceResultOf, gateMilestone, gateByRef, transferToEpic, transferOf, transferName, runMilestoneJourneys, makeJourneyRunner, acceptanceFromCli } from "./acceptance.mjs";
6
+ import { makeIntegration } from "./integration.mjs";
7
+
8
+ const F = "```";
9
+ const block = (inner) => `Epic\n\n${F}forge-acceptance\n${inner}\n${F}\n`;
10
+ const J1 = block("journey: create a task and get a result\nrun: ./j.sh\npass: exit 0\ntimeout: 60");
11
+ const HEAD = "a".repeat(40), OLD = "b".repeat(40);
12
+ const owner = { author_association: "OWNER", user: { type: "User", login: "me" } };
13
+ const bot = { user: { type: "Bot", login: "forge[bot]" }, author_association: "NONE" };
14
+ const rec = (head, results, site = "milestone") => ({ ...bot, body: renderAcceptanceComment({ head, at: "t", site, rows: Object.entries(results).map(([name, result]) => ({ name, result, exit: result === "pass" ? 0 : 1, ms: 1, output: "x" })) }) });
15
+ const epic = (declared, comments = []) => ({ number: 7, declared, comments });
16
+ const decl = declaredAcceptance({ body: J1, ...owner });
17
+
18
+ describe("acceptance parsing and the creation gate", () => {
19
+ it("parses journeys with defaults and post-deploy", () => {
20
+ const a = parseAcceptance(block("journey: a\nrun: x\njourney: b\nrun: y\npass: /ok/i\nwhen: post-deploy"));
21
+ assert.deepEqual(a.errors, []);
22
+ assert.equal(a.journeys[0].when, "milestone");
23
+ assert.deepEqual(a.journeys[1].pass, { kind: "regex", re: "ok", flags: "i" });
24
+ assert.equal(a.journeys[1].when, "post-deploy");
25
+ });
26
+ it("rejects an epic without a runnable journey", () => {
27
+ assert.equal(validateEpic("## Epic\nno journeys").ok, false);
28
+ assert.equal(validateEpic(block("journey: a")).ok, false, "no run command");
29
+ assert.equal(validateEpic(block("journey: a\nrun: x\nwhen: never")).ok, false);
30
+ assert.equal(validateEpic(`${F}\n${J1}\n${F}`.replace(/forge-acceptance/, "forge-probe")).ok, false);
31
+ assert.equal(validateEpic(J1).ok, true);
32
+ });
33
+ it("a quoted block (inside another fence) is not a declaration", () => {
34
+ assert.equal(validateEpic(`~~~md\n${J1}\n~~~`).ok, false);
35
+ });
36
+ it("only declarers' journeys count", () => {
37
+ assert.deepEqual(declaredAcceptance({ body: J1, ...bot }), { untrusted: true });
38
+ assert.equal(declaredAcceptance({ body: J1, ...owner }).journeys.length, 1);
39
+ assert.equal(declaredAcceptance({ body: "x", ...owner, comments: [{ body: J1, ...owner }] }).source, "comment");
40
+ });
41
+ });
42
+
43
+ describe("acceptance gate", () => {
44
+ it("blocks a journey that never ran, is red, or ran on an older head", () => {
45
+ const never = gateMilestone({ epics: [epic(decl)], head: HEAD });
46
+ assert.equal(never.ok, false); assert.match(never.reasons[0], /never run/);
47
+ const red = gateMilestone({ epics: [epic(decl, [rec(HEAD, { "create a task and get a result": "fail" })])], head: HEAD });
48
+ assert.match(red.reasons[0], /is red/);
49
+ const stale = gateMilestone({ epics: [epic(decl, [rec(OLD, { "create a task and get a result": "pass" })])], head: HEAD });
50
+ assert.match(stale.reasons[0], /has not run on/);
51
+ });
52
+ it("passes a green run on the head; an epic with no journey blocks", () => {
53
+ assert.equal(gateMilestone({ epics: [epic(decl, [rec(HEAD, { "create a task and get a result": "pass" })])], head: HEAD }).ok, true);
54
+ assert.equal(gateMilestone({ epics: [epic(null)], head: HEAD }).ok, false);
55
+ });
56
+ it("an untrusted (non-bot-marker) result comment does not count", () => {
57
+ const forged = { ...rec(HEAD, { "create a task and get a result": "pass" }), user: { type: "User", login: "rando" }, author_association: "NONE" };
58
+ assert.equal(gateMilestone({ epics: [epic(decl, [forged])], head: HEAD }).ok, false);
59
+ });
60
+ it("post-deploy journeys hold the epic at close, not at ship", () => {
61
+ const d = declaredAcceptance({ body: block("journey: live\nrun: curl x\nwhen: post-deploy"), ...owner });
62
+ assert.equal(gateMilestone({ epics: [epic(d)], head: HEAD, stage: "ship" }).ok, true);
63
+ const c = gateMilestone({ epics: [epic(d)], head: HEAD, stage: "close" });
64
+ assert.equal(c.ok, false); assert.match(c.reasons[0], /post-deploy journey "live"/);
65
+ assert.equal(gateMilestone({ epics: [epic(d, [rec(OLD, { live: "pass" }, "post-deploy")])], head: HEAD, stage: "close" }).ok, true);
66
+ });
67
+ it("result comment round-trips head, time and result", () => {
68
+ const r = acceptanceResultOf(rec(HEAD, { a: "pass", b: "fail" }).body);
69
+ assert.equal(r.head, HEAD); assert.equal(r.at, "t"); assert.equal(r.result, "fail"); assert.equal(r.results.b.result, "fail");
70
+ assert.equal(acceptanceResultOf("no"), null);
71
+ });
72
+ });
73
+
74
+ /** gh stub: milestone "M One" (#3) with epic #7, comments `comments`. */
75
+ function world({ comments = [], body = J1, author = owner, labels = true } = {}) {
76
+ const w = { calls: [], posted: [] };
77
+ const epicIssue = { number: 7, state: "open", body, ...author, labels: [{ name: "epic" }] };
78
+ w.io = {
79
+ gh: async (a) => {
80
+ w.calls.push(a);
81
+ if (/milestones\?state=all/.test(a[1])) return JSON.stringify([{ number: 3, title: "M One", description: "" }]);
82
+ if (/issues\?milestone=3/.test(a[1])) return labels ? JSON.stringify([epicIssue]) : "[]";
83
+ if (/issues\/7\/comments/.test(a[1])) return comments.map((c) => JSON.stringify(c)).join("\n");
84
+ if (/\/branches\//.test(a[1])) return `${HEAD}\n`;
85
+ if (a[0] === "issue" && a[1] === "comment") { w.posted.push(a[a.indexOf("--body") + 1]); return ""; }
86
+ if (a[0] === "issue" && a[1] === "edit") return "";
87
+ throw new Error(`unexpected gh ${a.join(" ")}`);
88
+ },
89
+ git: async () => `${HEAD}\n`,
90
+ };
91
+ return w;
92
+ }
93
+
94
+ describe("gateByRef, run and CLI", () => {
95
+ it("a milestone cannot ship while its journey never ran (ship and close)", async () => {
96
+ for (const stage of ["ship", "close"]) {
97
+ const w = world();
98
+ const g = await gateByRef({ io: w.io, repo: "o/r", title: "M One", stage });
99
+ assert.equal(g.gated, true); assert.equal(g.ok, false);
100
+ }
101
+ });
102
+ it("no epic means not gated; an unreadable head fails closed", async () => {
103
+ assert.equal((await gateByRef({ io: world({ labels: false }).io, repo: "o/r", title: "M One" })).gated, false);
104
+ assert.equal((await gateByRef({ io: world().io, repo: "o/r", title: "Nope" })).gated, false);
105
+ const w = world(); const gh = w.io.gh; w.io.gh = async (a) => { if (/\/branches\//.test(a[1])) throw new Error("404"); return gh(a); };
106
+ const g = await gateByRef({ io: w.io, repo: "o/r", branch: "milestone/m-one" });
107
+ assert.equal(g.ok, false); assert.match(g.reasons[0], /fail closed/);
108
+ });
109
+ it("close after ship: a deleted milestone branch uses the last recorded milestone run (#5393)", async () => {
110
+ const pd = declaredAcceptance({ body: block("journey: create a task and get a result\nrun: ./j.sh\njourney: live\nrun: ./l.sh\nwhen: post-deploy"), ...owner });
111
+ const gone = (w) => { const gh = w.io.gh; w.io.gh = async (a) => { if (/\/branches\//.test(a[1])) throw new Error("404"); return gh(a); }; return w; };
112
+ const ok = [rec(HEAD, { "create a task and get a result": "pass" }), rec(OLD, { live: "pass" }, "post-deploy")];
113
+ assert.equal(gateMilestone({ epics: [epic(pd, ok)], head: null, stage: "close" }).ok, true);
114
+ assert.equal(gateMilestone({ epics: [epic(pd, [ok[0]])], head: null, stage: "close" }).ok, false, "post-deploy journey still required");
115
+ assert.match(gateMilestone({ epics: [epic(pd, [rec(HEAD, { "create a task and get a result": "fail" }), ok[1]])], head: null, stage: "close" }).reasons[0], /is red/);
116
+ assert.equal(gateMilestone({ epics: [epic(pd, [ok[1]])], head: null, stage: "close" }).ok, false, "no milestone run");
117
+ const w = gone(world({ comments: [{ ...bot, body: rec(HEAD, { "create a task and get a result": "pass" }).body }] }));
118
+ assert.equal((await gateByRef({ io: w.io, repo: "o/r", title: "M One", stage: "close" })).ok, true);
119
+ const w2 = gone(world());
120
+ assert.equal((await gateByRef({ io: w2.io, repo: "o/r", title: "M One", stage: "close" })).ok, false);
121
+ assert.match((await gateByRef({ io: gone(world()).io, repo: "o/r", title: "M One", stage: "ship" })).reasons[0], /fail closed/);
122
+ });
123
+ it("runs journeys, posts the result on the epic with the head, and the gate then passes", async () => {
124
+ const w = world();
125
+ const res = await runMilestoneJourneys({ io: w.io, repo: "o/r", milestone: { number: 3, title: "M One", branch: "milestone/m-one" }, cwd: "/x", head: HEAD, now: () => "2026-11-10T00:00:00Z",
126
+ spawn: async () => ({ code: 0, stdout: "ok", stderr: "", timedOut: false }) });
127
+ assert.equal(res[0].result, "pass");
128
+ assert.equal(w.posted.length, 1);
129
+ const r = acceptanceResultOf(w.posted[0]);
130
+ assert.equal(r.head, HEAD); assert.equal(r.at, "2026-11-10T00:00:00Z"); assert.equal(r.result, "pass");
131
+ const w2 = world({ comments: [{ ...bot, body: w.posted[0] }] });
132
+ assert.equal((await gateByRef({ io: w2.io, repo: "o/r", title: "M One" })).ok, true);
133
+ });
134
+ it("a failing journey posts fail", async () => {
135
+ const w = world();
136
+ const res = await runMilestoneJourneys({ io: w.io, repo: "o/r", milestone: { number: 3, title: "M One", branch: "b" }, cwd: "/x", head: HEAD, spawn: async () => ({ code: 1, stdout: "", stderr: "boom", timedOut: false }) });
137
+ assert.equal(res[0].result, "fail"); assert.match(w.posted[0], /: fail/);
138
+ });
139
+ it("CLI check/gate exit codes", async () => {
140
+ const out = [];
141
+ const print = (t) => out.push(t);
142
+ assert.equal(await acceptanceFromCli(["check", "--body-file", "f"], { print, readFile: () => "no journeys" }), 1);
143
+ assert.equal(await acceptanceFromCli(["check", "--body-file", "f"], { print, readFile: () => J1 }), 0);
144
+ assert.equal(await acceptanceFromCli(["gate", "--milestone", "M One", "--repo", "o/r"], { print, io: world().io, cwd: "/nonexistent" }), 1);
145
+ assert.match(out.at(-1), /BLOCKED/);
146
+ });
147
+ });
148
+
149
+ describe("makeJourneyRunner structured result (#5337)", () => {
150
+ it("stays a string when nothing ran, and resolves {summary, red, ran, head} after a run", async () => {
151
+ const none = world({ labels: false });
152
+ assert.equal(await makeJourneyRunner({ repo: "o/r", io: none.io })({ title: "M One", branch: "milestone/m-one", number: 3 }), "no journey declared");
153
+ const w = world();
154
+ const git = w.io.git;
155
+ w.io.git = async (a, o) => (a[0] === "rev-parse" ? `${HEAD}\n` : git(a, o));
156
+ const r = await makeJourneyRunner({ repo: "o/r", io: w.io, cwd: process.cwd() })({ title: "M One", branch: "milestone/m-one", number: 3 });
157
+ assert.equal(typeof r.summary, "string");
158
+ assert.equal(r.head, HEAD);
159
+ assert.equal(typeof r.red, "boolean");
160
+ assert.equal(typeof r.ran, "boolean");
161
+ });
162
+ });
163
+
164
+ describe("integration seam runs journeys after a child merge", () => {
165
+ it("calls journeys without an integration cfg and survives its failure", async () => {
166
+ const calls = [], events = [];
167
+ const io = { gh: async (a) => (/milestones\?state=all/.test(a[1]) ? JSON.stringify([{ number: 3, title: "M One", description: "" }]) : "{}") };
168
+ const ig = makeIntegration({ repo: "o/r", io, cfg: null, journeys: async (m) => { calls.push(m); return "ok"; }, onEvent: (e) => events.push(e.detail) });
169
+ await ig.onMerged(1, {}, { milestone: "M One", pr: 5 });
170
+ await ig.settle();
171
+ assert.deepEqual(calls, [{ title: "M One", branch: "milestone/m-one", number: 3 }]);
172
+ assert.equal(ig.holds(1, { lane: "milestone/m-one" }), null);
173
+ const bad = makeIntegration({ repo: "o/r", io, cfg: null, journeys: async () => { throw new Error("x"); }, onEvent: (e) => events.push(e.detail) });
174
+ await bad.onMerged(1, {}, { milestone: "M One" }); await bad.settle();
175
+ assert.ok(events.some((e) => /journey run failed/.test(e)));
176
+ });
177
+ });
178
+
179
+ describe("transferred requirements (#5339)", () => {
180
+ const rows = (name, result) => [{ name, result, exit: result === "pass" ? 0 : 1, ms: 1 }];
181
+ const declPd = declaredAcceptance({ body: block("journey: smoke\nrun: ./j.sh\nwhen: post-deploy"), ...owner });
182
+ const tcomment = { ...bot, body: ["<!-- FORGE:TRANSFERRED -->", "## t", JSON.stringify({ issue: 5339, req: "R1", quote: "q", at: "t" })].join("\n") };
183
+ const pd = (results) => ({ ...bot, body: renderAcceptanceComment({ head: HEAD, at: "t", site: "post-deploy", rows: Object.entries(results).map(([name, result]) => ({ name, result, exit: result === "pass" ? 0 : 1, ms: 1 })) }) });
184
+ it("blocks the epic's close until a post-deploy journey named for the requirement passes; ship is not blocked", () => {
185
+ const passSmoke = pd({ smoke: "pass" });
186
+ const open = gateMilestone({ epics: [epic(declPd, [tcomment, passSmoke])], head: HEAD, stage: "close" });
187
+ assert.equal(open.ok, false);
188
+ assert.match(open.reasons.join(), /R1 transferred from #5339 has not been run/);
189
+ assert.equal(gateMilestone({ epics: [epic(declPd, [tcomment])], head: HEAD, stage: "ship" }).ok, true);
190
+ assert.equal(gateMilestone({ epics: [epic(declPd, [tcomment, passSmoke, pd({ [transferName(5339, "R1")]: "fail" })])], head: HEAD, stage: "close" }).ok, false);
191
+ assert.equal(gateMilestone({ epics: [epic(declPd, [tcomment, passSmoke, pd({ [transferName(5339, "R1")]: "pass" })])], head: HEAD, stage: "close" }).ok, true);
192
+ });
193
+ it("transferToEpic posts one FORGE:TRANSFERRED comment per requirement, idempotently, and returns null without an epic", async () => {
194
+ const posted = [];
195
+ let existing = [];
196
+ const gh = async (a) => {
197
+ const u = a.join(" ");
198
+ if (u.includes("/milestones")) return JSON.stringify([{ number: 3, title: "Feature X", state: "open" }]);
199
+ if (u.includes("issues?milestone=")) return JSON.stringify([{ number: 7, state: "open", body: "", user: owner.user, author_association: "OWNER" }]);
200
+ if (u.includes("/comments")) return existing.map((b) => JSON.stringify({ body: b, ...bot })).join("\n");
201
+ if (a[0] === "issue" && a[1] === "comment") { posted.push(a[a.indexOf("--body") + 1]); return ""; }
202
+ return "[]";
203
+ };
204
+ const reqs = [{ id: "R1", quote: "Live search works [type:e2e]" }];
205
+ const n = await transferToEpic({ io: { gh }, repo: "o/r", milestoneTitle: "Feature X", issue: 5339, reqs });
206
+ assert.equal(n, 7);
207
+ assert.equal(posted.length, 1);
208
+ assert.deepEqual([transferOf(posted[0]).issue, transferOf(posted[0]).req], [5339, "R1"]);
209
+ existing = [posted[0]];
210
+ await transferToEpic({ io: { gh }, repo: "o/r", milestoneTitle: "Feature X", issue: 5339, reqs });
211
+ assert.equal(posted.length, 1, "idempotent");
212
+ assert.equal(await transferToEpic({ io: { gh }, repo: "o/r", milestoneTitle: null, issue: 5339, reqs }), null);
213
+ assert.equal(await transferToEpic({ io: { gh: async () => "[]" }, repo: "o/r", milestoneTitle: "Feature X", issue: 5339, reqs }), null);
214
+ });
215
+ });
@@ -94,3 +94,21 @@ export function rolloutModes(cfg, changedFiles, read) {
94
94
  for (const f of changedFiles ?? []) { if (inRegistry(cfg, f)) continue; try { texts.push(String(read(f))); } catch { /* deleted or unreadable */ } }
95
95
  return [...modes].filter(([flag]) => texts.some((t) => flagRe(flag).test(t))).map(([flag, mode]) => ({ flag, mode, live: LIVE_MODES.test(mode) })).sort((a, b) => a.flag.localeCompare(b.flag));
96
96
  }
97
+
98
+ const LIVE_ACCEPTANCE_RE = /\b(?:live|production|prod|post-deploy|real[- ]browser|measur\w*)\b/i;
99
+ /**
100
+ * #5285: a requirement deferred for live or post-deploy verification while a live (default-on) rollout is touched ships
101
+ * unverified in production. `modes` is rolloutModes' output; returns `[{id, flag}]` of the deferred rows that block close.
102
+ */
103
+ export function liveDeferralBlocks(contract, modes) {
104
+ const live = (modes ?? []).filter((m) => m.live).map((m) => m.flag);
105
+ if (!live.length) return [];
106
+ const out = [];
107
+ for (const r of contract?.requirements ?? []) {
108
+ if (r?.disposition !== "defer" && r?.disposition !== "post-deploy") continue;
109
+ if (r.transferred || /\[type:(?:e2e|manual)\]/i.test(String(r.quote ?? ""))) { out.push({ id: r.id, flag: live.join(", ") }); continue; } // #5339: transferred to the epic, still unrun
110
+ const b = String(r.bucket ?? "");
111
+ if (r.disposition === "post-deploy" || b === "post-deploy" || b === "verify-now" || b === "host" || LIVE_ACCEPTANCE_RE.test(`${r.quote ?? ""} ${r.why ?? ""}`)) out.push({ id: r.id, flag: live.join(", ") });
112
+ }
113
+ return out;
114
+ }
@@ -2,7 +2,7 @@
2
2
  // SPDX-License-Identifier: AGPL-3.0-or-later
3
3
  import { describe, it } from "node:test";
4
4
  import assert from "node:assert/strict";
5
- import { readRollouts, detectNewOffKeys, activationFailures, dormancyReport, coversFlag, rolloutModes } from "./activation.mjs";
5
+ import { readRollouts, detectNewOffKeys, activationFailures, dormancyReport, coversFlag, rolloutModes, liveDeferralBlocks } from "./activation.mjs";
6
6
  import { precheck } from "./conformance.mjs";
7
7
 
8
8
  const cfg = { files: ["config/rollouts.json"], days: 14 };
@@ -86,3 +86,25 @@ describe("#5240 rolloutModes", () => {
86
86
  assert.deepEqual(rolloutModes(cfg, ["gone.py"], read), []);
87
87
  });
88
88
  });
89
+
90
+ describe("liveDeferralBlocks (#5285)", () => {
91
+ const c = { requirements: [{ id: "R1", disposition: "deliver" }, { id: "R3", disposition: "defer", bucket: "post-deploy", why: "live acceptance run" }] };
92
+ it("a live rollout with deferred live acceptance blocks (the #38819 replay)", () => {
93
+ assert.deepEqual(liveDeferralBlocks(c, [{ flag: "alterlab_google_pool", mode: "on", live: true }]), [{ id: "R3", flag: "alterlab_google_pool" }]);
94
+ });
95
+ it("a default-off (inert) rollout or no rollout ships with the deferral", () => {
96
+ assert.deepEqual(liveDeferralBlocks(c, [{ flag: "alterlab_google_pool", mode: "off", live: false }]), []);
97
+ assert.deepEqual(liveDeferralBlocks(c, []), []);
98
+ });
99
+ it("a deferral that is not about live verification does not block", () => {
100
+ assert.deepEqual(liveDeferralBlocks({ requirements: [{ id: "R2", disposition: "defer", bucket: "owner:rotate key", why: "needs a credential" }] }, [{ flag: "f", mode: "on", live: true }]), []);
101
+ });
102
+ });
103
+
104
+ describe("liveDeferralBlocks transferred requirements (#5339)", () => {
105
+ it("a live rollout with a post-deploy e2e/manual requirement transferred to the epic blocks, even without a live bucket", () => {
106
+ const c = { requirements: [{ id: "R2", quote: "Search works against the live web [type:e2e]", disposition: "post-deploy", bucket: "date:2027-01-01" }] };
107
+ assert.deepEqual(liveDeferralBlocks(c, [{ flag: "pool", mode: "on", live: true }]), [{ id: "R2", flag: "pool" }]);
108
+ assert.deepEqual(liveDeferralBlocks(c, [{ flag: "pool", mode: "off", live: false }]), []);
109
+ });
110
+ });
@@ -9,7 +9,7 @@
9
9
  * dir records the checkpoints done and the alert, so a restarted daemon re-arms only the remaining checks and never alerts
10
10
  * twice. A refused launch has no batch dir: it is recorded in `<batch root>/refusals.json`. `forgedock status` reads both.
11
11
  */
12
- import { readFileSync } from "node:fs";
12
+ import { appendFileSync, existsSync, readFileSync } from "node:fs";
13
13
  import { spawn as spawnProc } from "node:child_process";
14
14
  import { join } from "node:path";
15
15
  import { listBatches, openBatch, REQUEUABLE, writeAtomic } from "./batch.mjs";
@@ -251,3 +251,76 @@ export async function resolvedOnGithub(cands, gh, repo) {
251
251
  }
252
252
  return out;
253
253
  }
254
+
255
+ export const DEFAULT_STALL_MIN = 10;
256
+ /**
257
+ * #5314: dispatch stall. A batch with ready pending issues, free capacity and no progress for `windowMin` minutes. Ready: pending,
258
+ * not held, no retry-at in the future, every in-batch dependency ended well. Independent of the runner (it may be dead), so the
259
+ * schedd polls it. `hosted`: a runner is alive. @returns null (healthy) or `{code, ready, idleMin, hosted, detail}`. Pure.
260
+ */
261
+ export function evaluateDispatchStall(state, { held = [], parallel = null, hosted = false, lastProgressMs = null, now = Date.now(), windowMin = DEFAULT_STALL_MIN, cancelled = false, reported = false } = {}) {
262
+ if (!state || cancelled || reported || lastProgressMs === null) return null;
263
+ if (state.breaker && !state.breaker.transport) return null; // an operator --resume clears it; a re-host would stop again at once
264
+ const order = new Set((state.order ?? []).map(Number)), results = state.results ?? {}, heldSet = new Set(held.map(Number));
265
+ const running = Object.keys(state.running ?? {}).length;
266
+ const k = Number.isInteger(parallel) && parallel > 0 ? parallel : Number.isInteger(state.parallel) && state.parallel > 0 ? state.parallel : 1;
267
+ const ready = (state.pending ?? []).map(Number).filter((n) => !heldSet.has(n) && results[n] === undefined && !(Number(state.notBefore?.[n]) > now)
268
+ && (state.deps?.[n] ?? []).every((d) => !order.has(Number(d)) || Number(d) === n || GOOD_END.has(results[d]?.outcome)));
269
+ const idleMin = Math.floor((now - lastProgressMs) / 60000);
270
+ if (!ready.length || running >= k || idleMin < windowMin) return null;
271
+ return { code: "dispatch-stalled", ready, idleMin, hosted, detail: `${ready.length} ready issue${ready.length === 1 ? "" : "s"} (${list(ready.slice(0, 8))}${ready.length > 8 ? ", …" : ""}) pending with ${k - running} free lane${k - running === 1 ? "" : "s"} and no dispatch for ${idleMin} min; ${hosted ? "the runner is alive but not dispatching" : "no runner hosts the batch"}` };
272
+ }
273
+
274
+ export const FIRST_HOUR_FILE = "first-hour.json";
275
+ export const BATCH_LOG_FILE = "batch.log";
276
+ export const FIRST_HOUR_MIN = 60;
277
+ export const readFirstHour = (dir) => readJson(join(dir, FIRST_HOUR_FILE));
278
+ /** Append one line to the batch's operator-readable log. Best effort. */
279
+ export const appendBatchLog = (dir, text) => { try { appendFileSync(join(dir, BATCH_LOG_FILE), `${text}\n`, { mode: 0o600 }); } catch { /* advisory */ } };
280
+
281
+ /** The first-hour report of one batch: dispatched / running / merged / stuck, and why. Pure. */
282
+ export function firstHourReport(state, { batchId, now = Date.now(), held = [], stall = null } = {}) {
283
+ const order = (state?.order ?? []).map(Number), results = state?.results ?? {}, running = Object.keys(state?.running ?? {}).map(Number);
284
+ const merged = order.filter((n) => GOOD_END.has(results[n]?.outcome)), heldSet = new Set(held.map(Number));
285
+ const stuck = order.filter((n) => !running.includes(n) && !GOOD_END.has(results[n]?.outcome) && (results[n] !== undefined || (state?.pending ?? []).map(Number).includes(n)));
286
+ const why = (n) => results[n]?.outcome ? `#${n} ${results[n].outcome}` : heldSet.has(n) ? `#${n} held` : Number(state?.notBefore?.[n]) > now ? `#${n} waiting on a retry` : `#${n} pending`;
287
+ const dispatched = order.filter((n) => results[n] !== undefined || running.includes(n)).length;
288
+ const counts = { total: order.length, dispatched, running: running.length, merged: merged.length, stuck: stuck.length };
289
+ const reasons = [...stuck.map(why), ...(stall ? [stall.detail] : [])];
290
+ const summary = `first hour: ${dispatched}/${order.length} dispatched, ${running.length} running, ${merged.length} merged, ${stuck.length} stuck${reasons.length ? ` (${reasons.slice(0, 6).join("; ")})` : ""}`;
291
+ return { batch: batchId, at: new Date(now).toISOString(), counts, summary, lines: [`batch ${batchId}: ${summary}`, ...reasons.slice(0, 12).map((r) => ` ${r}`)] };
292
+ }
293
+
294
+ /** Persist the first-hour report once (batch dir + `batch.log`); false when it already exists. */
295
+ export function writeFirstHour(batch, report) {
296
+ if (existsSync(join(batch.dir, FIRST_HOUR_FILE))) return false;
297
+ try { writeAtomic(join(batch.dir, FIRST_HOUR_FILE), JSON.stringify(report) + "\n", { private: true }); } catch { return false; }
298
+ for (const l of report.lines) appendBatchLog(batch.dir, `${report.at} ${l}`);
299
+ return true;
300
+ }
301
+
302
+ /** The one needs-you item of a stall: recorded in `health.json` (shown by status) per distinct ready set. @returns true when newly raised */
303
+ export function recordStallAlert(batch, stall, { now = Date.now() } = {}) {
304
+ const sig = stall.ready.join(","), prev = readHealth(batch.dir) ?? {};
305
+ if (prev.stall?.sig === sig) return false;
306
+ const at = new Date(now).toISOString();
307
+ const text = `BATCH UNHEALTHY ${batch.id} (dispatch-stalled)\n cause: dispatch-stalled: ${stall.detail}\n recovery:\n forgedock orchestrate --resume ${batch.id}\n forgedock orchestrate --cancel ${batch.id}`;
308
+ try { writeHealth(batch.dir, { ...prev, stall: { at, sig, detail: stall.detail }, ...(prev.alertedAt ? {} : { alertedAt: at, alert: text }) }); } catch { return false; }
309
+ appendBatchLog(batch.dir, `${at} ${text.split("\n").slice(0, 2).join(" | ")}`);
310
+ return true;
311
+ }
312
+
313
+ /** `sched show` lines: per unfinished batch, its first-hour summary and any dispatch stall. */
314
+ export function summaryLines(root, { now = Date.now() } = {}) {
315
+ const out = [];
316
+ for (const id of listBatches(root)) {
317
+ try {
318
+ const b = openBatch(root, id);
319
+ if (b.readReport() || b.readCancel()) continue;
320
+ const fh = readFirstHour(b.dir), h = readHealth(b.dir);
321
+ if (fh?.summary) out.push(` batch ${id}: ${fh.summary}`);
322
+ if (h?.stall && now - Date.parse(h.stall.at) < 24 * 3600 * 1000) out.push(` batch ${id}: DISPATCH STALLED since ${h.stall.at}: ${h.stall.detail}`);
323
+ } catch { /* an unreadable batch has no line */ }
324
+ }
325
+ return out;
326
+ }
@@ -7,7 +7,8 @@ import { join } from "node:path";
7
7
  import { tmpDir } from "../tests/_tmp.mjs";
8
8
  import { openBatch } from "./batch.mjs";
9
9
  import { DEFAULT_HEALTH, parseHealthConfig, rootsOf, evaluateHealth, formatAlert, runCheck, scheduleChecks, scheduleLine, runNotify, deliverAlert,
10
- resolvedOnGithub, recordRefusal, readRefusals, statusLines, REFUSAL_KEEP } from "./batch-health.mjs";
10
+ resolvedOnGithub, recordRefusal, readRefusals, statusLines, REFUSAL_KEEP,
11
+ evaluateDispatchStall, firstHourReport, writeFirstHour, readFirstHour, recordStallAlert, summaryLines } from "./batch-health.mjs";
11
12
 
12
13
  // #1 and #3 are roots; #2 depends on #1, #4 on #3.
13
14
  const base = (results, extra = {}) => ({ order: [1, 2, 3, 4], deps: { 2: [1], 4: [3] }, results, running: {}, pending: [], ...extra });
@@ -187,3 +188,55 @@ describe("#5243 health re-reads GitHub before declaring root-failed", () => {
187
188
  assert.deepEqual(await resolvedOnGithub(cands, gh, "o/r"), [1, 3]);
188
189
  });
189
190
  });
191
+
192
+ describe("#5314 dispatch stall and first-hour report", () => {
193
+ const NOW = 10_000_000, MIN = 60000;
194
+ const st = (extra = {}) => ({ order: [1, 2, 3], deps: { 3: [1] }, results: { 1: { outcome: "merged" } }, running: {}, pending: [2, 3], parallel: 2, ...extra });
195
+ const stall = (state, o = {}) => evaluateDispatchStall(state, { lastProgressMs: NOW - 12 * MIN, now: NOW, windowMin: 10, ...o });
196
+
197
+ it("ready pending issues, a free lane and no progress for the window: stalled, naming the batch's ready issues and who hosts", () => {
198
+ const r = stall(st());
199
+ assert.equal(r.code, "dispatch-stalled");
200
+ assert.deepEqual(r.ready, [2, 3]);
201
+ assert.match(r.detail, /no runner hosts the batch/);
202
+ assert.match(stall(st(), { hosted: true }).detail, /runner is alive but not dispatching/);
203
+ });
204
+
205
+ it("not stalled: recent progress, full lanes, held, retry-at ahead, unmet dependency, cancelled, reported, tripped breaker", () => {
206
+ assert.equal(stall(st(), { lastProgressMs: NOW - 2 * MIN }), null);
207
+ assert.equal(stall(st({ running: { 9: {} }, parallel: 1 })), null);
208
+ assert.equal(stall(st(), { held: [2, 3] }), null);
209
+ assert.equal(stall(st({ notBefore: { 2: NOW + MIN, 3: NOW + MIN } })), null);
210
+ assert.deepEqual(stall(st({ results: {} }))?.ready, [2], "#3 waits on #1");
211
+ assert.equal(stall(st(), { cancelled: true }), null);
212
+ assert.equal(stall(st(), { reported: true }), null);
213
+ assert.equal(stall(st({ breaker: { errors: 3 } })), null);
214
+ assert.equal(stall(st(), { lastProgressMs: null }), null);
215
+ });
216
+
217
+ it("the first-hour report counts dispatched / running / merged / stuck with reasons, is written once, and reaches summaryLines", () => {
218
+ const root = tmpDir("first-hour-"), b = openBatch(root, "b1");
219
+ b.writePlan({ daemon: true, repo: "o/r" });
220
+ const state = st({ running: { 2: {} }, pending: [3], results: { 1: { outcome: "merged" } } });
221
+ b.store.save(state);
222
+ const rep = firstHourReport(state, { batchId: "b1", now: NOW, held: [3] });
223
+ assert.deepEqual(rep.counts, { total: 3, dispatched: 2, running: 1, merged: 1, stuck: 1 });
224
+ assert.match(rep.summary, /2\/3 dispatched, 1 running, 1 merged, 1 stuck \(#3 held\)/);
225
+ assert.equal(writeFirstHour(b, rep), true);
226
+ assert.equal(writeFirstHour(b, rep), false, "once per batch");
227
+ assert.equal(readFirstHour(b.dir).summary, rep.summary);
228
+ assert.match(readFileSync(join(b.dir, "batch.log"), "utf8"), /first hour: 2\/3 dispatched/);
229
+ assert.ok(summaryLines(root, { now: NOW }).some((l) => l.includes("batch b1: first hour")));
230
+ });
231
+
232
+ it("recordStallAlert raises one needs-you item per ready set and statusLines shows it", () => {
233
+ const root = tmpDir("stall-alert-"), b = openBatch(root, "b1");
234
+ b.writePlan({ daemon: true, repo: "o/r" });
235
+ const s1 = stall(st());
236
+ assert.equal(recordStallAlert(b, s1, { now: NOW }), true);
237
+ assert.equal(recordStallAlert(b, s1, { now: NOW }), false);
238
+ assert.equal(recordStallAlert(b, { ...s1, ready: [2] }, { now: NOW }), true, "a different ready set is a new item");
239
+ assert.ok(statusLines(root, { now: Date.now() }).some((l) => /BATCH UNHEALTHY b1/.test(l) || /dispatch-stalled/.test(l)));
240
+ assert.ok(summaryLines(root, { now: Date.parse(new Date(NOW).toISOString()) }).some((l) => /DISPATCH STALLED/.test(l)));
241
+ });
242
+ });
@@ -446,6 +446,9 @@ describe("#4402: the batch report prints the efficiency lines, fail-soft", () =>
446
446
  });
447
447
  });
448
448
 
449
+ // #5314: with no daemon the CLI queues the issues, then fails loudly (nothing is scheduled); the queued result rides on the error.
450
+ const queued = (p) => p.catch((e) => { if (e?.code === "batch.not-hosted") return e.result; throw e; });
451
+
449
452
  describe("#4408: issues added to a running batch (forgedock orchestrate --add)", () => {
450
453
  const gate = () => { let open; const p = new Promise((r) => { open = r; }); return { p, open }; };
451
454
  it("one lane running: an added independent issue starts on the next pass, an added one that Depends on the running issue waits for its merge", async () => {
@@ -545,7 +548,7 @@ describe("#4408: issues added to a running batch (forgedock orchestrate --add)",
545
548
  assert.deepEqual(b.unrunAdds(), [2, 3, 5]);
546
549
  const views = [];
547
550
  const io = { gh: async (a) => { if (a[0] === "api") return "OWNER\n"; views.push(a); if (a[2] === "8") throw new Error("gh down"); return JSON.stringify({ state: a[2] === "7" ? "CLOSED" : "OPEN" }); } };
548
- const res = await quiet(() => orchestrateFromCli(["--add", "b1", "6", "7", "8", "3", "x"], { batchRoot: root, io }));
551
+ const res = await queued(quiet(() => orchestrateFromCli(["--add", "b1", "6", "7", "8", "3", "x"], { batchRoot: root, io })));
549
552
  assert.deepEqual(res.added, [6]);
550
553
  assert.deepEqual(res.skipped.map((x) => [x.issue, x.reason]).sort(), [[3, "already in batch"], [7, "closed"], [8, "unreadable"], ["x", "not an integer"]]);
551
554
  assert.ok(views.every((a) => a.includes("-R") && a.includes("o/r")), "state read against the batch's repo");
@@ -566,7 +569,7 @@ describe("#4408: issues added to a running batch (forgedock orchestrate --add)",
566
569
  await assert.rejects(quiet(() => orchestrateFromCli(["--resume", "b1", "--parallel", "5", "6", "--lane", "staging"], { batchRoot: root, io })), /usage/);
567
570
  assert.deepEqual(views, ["6"]);
568
571
  assert.deepEqual(b.readAdded(), [6]);
569
- const res = await quiet(() => orchestrateFromCli(["--add", "b1", "7", "--parallel", "5"], { batchRoot: root, io }));
572
+ const res = await queued(quiet(() => orchestrateFromCli(["--add", "b1", "7", "--parallel", "5"], { batchRoot: root, io })));
570
573
  assert.deepEqual(res.added, [7]);
571
574
  assert.deepEqual(res.skipped, []);
572
575
  assert.deepEqual(b.readAdded(), [6, 7]);
@@ -1065,13 +1068,13 @@ describe("#4550: forgedock orchestrate --requeue", () => {
1065
1068
  assert.match(bad.refused[1].reason, /needs-human/);
1066
1069
  assert.deepEqual(b.readRequeued(), []);
1067
1070
  assert.ok(b.readReport(), "nothing changed");
1068
- const ok = await quiet(() => orchestrateFromCli(["--requeue", "b1", "5", "--reason", "decided"], { batchRoot: root, io }));
1071
+ const ok = await queued(quiet(() => orchestrateFromCli(["--requeue", "b1", "5", "--reason", "decided"], { batchRoot: root, io })));
1069
1072
  assert.deepEqual(ok.requeued, [5]);
1070
1073
  assert.equal(b.readRequeued()[0].reason, "decided");
1071
1074
  assert.equal(b.readReport(), null, "the finished batch is reopened for --resume");
1072
1075
  });
1073
1076
 
1074
- it("#5000: --add/--requeue on a finished batch without a daemon clear the report and say it is not hosted", async () => {
1077
+ it("#5000/#5314: --add/--requeue on a finished batch without a daemon queue the issue and fail loudly (nothing is scheduled)", async () => {
1075
1078
  const root = tmpDir("batch-add-finished-");
1076
1079
  const b = openBatch(root, "b1");
1077
1080
  b.writePlan({ argv: ["1"], repo: "o/r" });
@@ -1080,14 +1083,13 @@ describe("#4550: forgedock orchestrate --requeue", () => {
1080
1083
  const io = { gh: async () => JSON.stringify({ state: "OPEN", labels: [], body: "", author: { login: "a" } }) };
1081
1084
  const lines = [];
1082
1085
  const run = async (argv) => { const l = console.log; console.log = (x) => lines.push(String(x)); try { return await orchestrateFromCli(argv, { batchRoot: root, io }); } finally { console.log = l; } };
1083
- const add = await run(["--add", "b1", "7"]);
1084
- assert.deepEqual(add.added, [7]);
1086
+ await assert.rejects(run(["--add", "b1", "7"]), /NOTHING is scheduled.*--resume b1/);
1087
+ assert.deepEqual(b.readAdded(), [7], "the add itself is kept");
1085
1088
  assert.equal(b.readReport(), null, "a plain add reopens the finished batch for --resume");
1086
- assert.ok(lines.some((l) => /NOT hosted.*--resume b1/.test(l)), "the CLI says nothing is scheduled yet");
1089
+ assert.ok(lines.some((l) => /NOT hosted.*--resume b1/.test(l)));
1087
1090
  b.writeReport({ rows: [], report: "x" });
1088
1091
  lines.length = 0;
1089
- const rq = await run(["--requeue", "b1", "5"]);
1090
- assert.deepEqual(rq.requeued, [5]);
1092
+ await assert.rejects(run(["--requeue", "b1", "5"]), /NOTHING is scheduled/);
1091
1093
  assert.equal(b.readReport(), null);
1092
1094
  assert.ok(lines.some((l) => /NOT hosted.*--resume b1/.test(l)));
1093
1095
  });
@@ -0,0 +1,54 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * One writer per lane branch (#5333): a lock file in the repo's shared git dir, so every worktree and every engine
5
+ * process on the host sees it. A builder session (implement, recovery, fix-up) holds it while it may commit.
6
+ * Also the lane's teardown ordering helper: a worktree is removed only after its builder processes have exited.
7
+ */
8
+ import { closeSync, mkdirSync, openSync, readFileSync, unlinkSync, writeSync } from "node:fs";
9
+ import { join } from "node:path";
10
+ import { pidAlive } from "./sched.mjs";
11
+
12
+ export const LOCK_DIR = "forge-branch-locks";
13
+
14
+ const lockPath = (gitCommonDir, branch) => join(gitCommonDir, LOCK_DIR, encodeURIComponent(String(branch)));
15
+ const readHolder = (p) => { try { const j = JSON.parse(readFileSync(p, "utf8")); return j && typeof j === "object" ? j : null; } catch { return null; } };
16
+
17
+ /**
18
+ * Take the writer lock of `branch`. The same `owner` re-enters. A holder whose pid is dead is taken over. Otherwise wait up to
19
+ * `waitMs` (0: do not wait), then report the holder.
20
+ * @returns {Promise<{ok: true, release: () => void} | {ok: false, holder: object|null}>}
21
+ */
22
+ export async function acquireBranchLock({ gitCommonDir, branch, owner, pid = process.pid, alive = pidAlive, waitMs = 0, pollMs = 500, sleep = (ms) => new Promise((r) => setTimeout(r, ms)), now = Date.now }) {
23
+ const p = lockPath(gitCommonDir, branch);
24
+ mkdirSync(join(gitCommonDir, LOCK_DIR), { recursive: true });
25
+ const deadline = now() + waitMs;
26
+ for (;;) {
27
+ try {
28
+ const fd = openSync(p, "wx");
29
+ try { writeSync(fd, JSON.stringify({ owner, pid, branch, at: now() })); } finally { closeSync(fd); }
30
+ return { ok: true, release: () => { if (readHolder(p)?.owner === owner) { try { unlinkSync(p); } catch { /* already gone */ } } } };
31
+ } catch (e) {
32
+ if (e?.code !== "EEXIST") throw e;
33
+ }
34
+ const holder = readHolder(p);
35
+ if (holder?.owner === owner) return { ok: true, release: () => {} }; // re-entrant: the outer holder releases
36
+ if (!holder || !alive(holder.pid)) { try { unlinkSync(p); } catch { /* raced: retry */ } continue; } // stale or unreadable: take over
37
+ if (now() >= deadline) return { ok: false, holder };
38
+ await sleep(pollMs);
39
+ }
40
+ }
41
+
42
+ /**
43
+ * Wait until none of `pids` is alive: SIGTERM was already sent; after `graceMs` escalate to SIGKILL, then wait `killMs` more.
44
+ * @returns {Promise<number[]>} the pids still alive (empty: all exited)
45
+ */
46
+ export async function waitPidsExit(pids, { alive, kill, sleep = (ms) => new Promise((r) => setTimeout(r, ms)), graceMs = 5000, killMs = 3000, stepMs = 250 }) {
47
+ const live = () => pids.filter((x) => alive(x));
48
+ let left = live();
49
+ for (let t = 0; left.length && t < graceMs; t += stepMs) { await sleep(stepMs); left = live(); }
50
+ if (!left.length) return [];
51
+ for (const x of left) { try { kill(x, "SIGKILL"); } catch { /* gone */ } }
52
+ for (let t = 0; left.length && t < killMs; t += stepMs) { await sleep(stepMs); left = live(); }
53
+ return left;
54
+ }
@@ -0,0 +1,49 @@
1
+ import { describe, it } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { existsSync, writeFileSync, mkdirSync } from "node:fs";
4
+ import { join } from "node:path";
5
+ import { acquireBranchLock, waitPidsExit, LOCK_DIR } from "./branchlock.mjs";
6
+ import { tmpDir } from "../tests/_tmp.mjs";
7
+
8
+ const common = () => tmpDir("branchlock-");
9
+
10
+ describe("branch writer lock (#5333)", () => {
11
+ it("two sessions cannot hold the same lane branch at once; the second reports the holder", async () => {
12
+ const dir = common();
13
+ const a = await acquireBranchLock({ gitCommonDir: dir, branch: "feat/issue-7-lean", owner: "A", alive: () => true });
14
+ assert.equal(a.ok, true);
15
+ const b = await acquireBranchLock({ gitCommonDir: dir, branch: "feat/issue-7-lean", owner: "B", alive: () => true });
16
+ assert.equal(b.ok, false);
17
+ assert.equal(b.holder.owner, "A");
18
+ });
19
+ it("another branch is independent; release lets the waiter in", async () => {
20
+ const dir = common();
21
+ const a = await acquireBranchLock({ gitCommonDir: dir, branch: "x", owner: "A", alive: () => true });
22
+ assert.equal((await acquireBranchLock({ gitCommonDir: dir, branch: "y", owner: "B", alive: () => true })).ok, true);
23
+ let waited = 0;
24
+ const b = await acquireBranchLock({ gitCommonDir: dir, branch: "x", owner: "B", alive: () => true, waitMs: 1000, pollMs: 10, sleep: async () => { if (++waited === 2) a.release(); } });
25
+ assert.equal(b.ok, true);
26
+ assert.ok(waited >= 2);
27
+ });
28
+ it("the same owner re-enters without releasing the outer hold", async () => {
29
+ const dir = common();
30
+ const a = await acquireBranchLock({ gitCommonDir: dir, branch: "x", owner: "A", alive: () => true });
31
+ const again = await acquireBranchLock({ gitCommonDir: dir, branch: "x", owner: "A", alive: () => true });
32
+ again.release();
33
+ assert.equal(existsSync(join(dir, LOCK_DIR, "x")), true);
34
+ a.release();
35
+ assert.equal(existsSync(join(dir, LOCK_DIR, "x")), false);
36
+ });
37
+ it("a lock whose holder died is taken over", async () => {
38
+ const dir = common();
39
+ mkdirSync(join(dir, LOCK_DIR));
40
+ writeFileSync(join(dir, LOCK_DIR, "x"), JSON.stringify({ owner: "dead", pid: 999999 }));
41
+ assert.equal((await acquireBranchLock({ gitCommonDir: dir, branch: "x", owner: "B", alive: () => false })).ok, true);
42
+ });
43
+ it("waitPidsExit escalates to SIGKILL and reports survivors", async () => {
44
+ const alive = new Set([1, 2]), kills = [];
45
+ const left = await waitPidsExit([1, 2], { alive: (p) => alive.has(p), kill: (p, s) => { kills.push([p, s]); if (p === 1) alive.delete(p); }, sleep: async () => {}, graceMs: 500, killMs: 500 });
46
+ assert.deepEqual(left, [2]);
47
+ assert.deepEqual(kills, [[1, "SIGKILL"], [2, "SIGKILL"]]);
48
+ });
49
+ });