forgedock 1.51.0 → 1.53.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/bin/engine/outcome-codes.mjs +3 -0
  2. package/bin/engine/telemetry-seam.mjs +4 -2
  3. package/bin/engine-cli.mjs +61 -17
  4. package/bin/experiment.mjs +58 -6
  5. package/bin/forge-utils.mjs +6 -2
  6. package/bin/forgedock.mjs +25 -1
  7. package/bin/lean/account-watch.mjs +28 -0
  8. package/bin/lean/account-watch.test.mjs +30 -0
  9. package/bin/lean/activation.mjs +20 -0
  10. package/bin/lean/activation.test.mjs +14 -1
  11. package/bin/lean/basered.mjs +115 -0
  12. package/bin/lean/basered.test.mjs +66 -0
  13. package/bin/lean/batch-health.mjs +40 -6
  14. package/bin/lean/batch-health.test.mjs +34 -1
  15. package/bin/lean/batch.mjs +41 -2
  16. package/bin/lean/batch.test.mjs +104 -2
  17. package/bin/lean/checkpoint-reconcile.mjs +43 -0
  18. package/bin/lean/checkpoint-reconcile.test.mjs +95 -0
  19. package/bin/lean/conformance.e2e.test.mjs +1 -1
  20. package/bin/lean/conformance.mjs +205 -23
  21. package/bin/lean/conformance.test.mjs +164 -3
  22. package/bin/lean/context.mjs +27 -17
  23. package/bin/lean/context.test.mjs +15 -0
  24. package/bin/lean/effects.mjs +11 -7
  25. package/bin/lean/execution.mjs +19 -3
  26. package/bin/lean/execution.test.mjs +39 -0
  27. package/bin/lean/findinglabel.mjs +16 -0
  28. package/bin/lean/findinglabel.test.mjs +39 -0
  29. package/bin/lean/heavy.mjs +6 -3
  30. package/bin/lean/hostload.mjs +78 -0
  31. package/bin/lean/hostload.test.mjs +117 -0
  32. package/bin/lean/hotspots-remote.e2e.test.mjs +71 -0
  33. package/bin/lean/issuewatch-release.mjs +6 -2
  34. package/bin/lean/issuewatch-release.test.mjs +16 -0
  35. package/bin/lean/issuewatch.mjs +11 -1
  36. package/bin/lean/lanelock.mjs +14 -0
  37. package/bin/lean/lean.mjs +171 -36
  38. package/bin/lean/lean.test.mjs +302 -10
  39. package/bin/lean/light.mjs +48 -7
  40. package/bin/lean/light.test.mjs +37 -3
  41. package/bin/lean/limits.test.mjs +142 -9
  42. package/bin/lean/orchestrate-cancel.test.mjs +143 -0
  43. package/bin/lean/orchestrate.mjs +110 -26
  44. package/bin/lean/postdeploy-check.test.mjs +39 -0
  45. package/bin/lean/prompts.mjs +8 -7
  46. package/bin/lean/quota.mjs +39 -0
  47. package/bin/lean/recovery.test.mjs +10 -0
  48. package/bin/lean/relaxation.mjs +73 -0
  49. package/bin/lean/relaxation.test.mjs +54 -0
  50. package/bin/lean/release-postmerge.mjs +119 -0
  51. package/bin/lean/release-rehearsal.mjs +63 -0
  52. package/bin/lean/release-rehearsal.test.mjs +93 -0
  53. package/bin/lean/release-review.e2e.test.mjs +77 -0
  54. package/bin/lean/release-review.mjs +198 -0
  55. package/bin/lean/release-review.test.mjs +180 -0
  56. package/bin/lean/release.mjs +228 -0
  57. package/bin/lean/release.test.mjs +292 -0
  58. package/bin/lean/rotator.mjs +150 -31
  59. package/bin/lean/rotator.test.mjs +105 -2
  60. package/bin/lean/sandbox-remote.mjs +9 -2
  61. package/bin/lean/schedd.mjs +56 -6
  62. package/bin/lean/schedd.test.mjs +108 -6
  63. package/bin/lean/verifier.mjs +3 -2
  64. package/bin/lean/verify.mjs +2 -1
  65. package/bin/lean/verify.test.mjs +6 -0
  66. package/bin/pool/agent.mjs +18 -4
  67. package/bin/pool/router.mjs +68 -25
  68. package/bin/review-staging.mjs +23 -0
  69. package/bin/stats/conformance-outcomes.mjs +208 -0
  70. package/bin/stats/conformance-outcomes.test.mjs +188 -0
  71. package/bin/stats/depth.mjs +218 -0
  72. package/bin/stats/depth.test.mjs +133 -0
  73. package/bin/stats/experiment.mjs +7 -5
  74. package/bin/stats/github-source.mjs +2 -2
  75. package/bin/stats/index.mjs +64 -2
  76. package/bin/stats/local-source.mjs +11 -0
  77. package/bin/stats/query.mjs +69 -0
  78. package/bin/stats/selffiled.mjs +52 -0
  79. package/bin/stats/selffiled.test.mjs +71 -0
  80. package/commands/orchestrate.md +1 -1
  81. package/commands/review-pr-agents/security.md +4 -0
  82. package/commands/review-pr-staging.md +2 -0
  83. package/commands/work-on/build.md +4 -6
  84. package/docs/CONFIG.md +66 -8
  85. package/docs/ISSUE-WATCH.md +2 -0
  86. package/docs/OUTCOME-CODES.md +3 -0
  87. package/docs/STATS.md +44 -0
  88. package/docs/TELEMETRY.md +1 -1
  89. package/package.json +1 -1
  90. package/pool/README.md +1 -1
  91. package/pool/image/cs-cred +14 -1
  92. package/pool/install/install-agent.ps1 +6 -2
  93. package/scripts/backfill-finding-labels.mjs +50 -0
  94. package/scripts/backfill-finding-labels.test.mjs +36 -0
  95. package/scripts/doctor-pipeline-state.sh +21 -6
  96. package/scripts/file-deferred-followups.sh +60 -238
  97. package/scripts/file-deferred-followups.test.sh +99 -187
  98. package/scripts/followup-route.mjs +12 -0
  99. package/scripts/hotspots.sh +12 -8
  100. package/scripts/hotspots.test.sh +22 -0
  101. package/scripts/owner-route-parity.test.sh +17 -1
  102. package/scripts/prior-attempts.test.mjs +1 -1
  103. package/scripts/review-pr-side-effects.test.sh +40 -0
@@ -0,0 +1,180 @@
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 { reviewStep, fixStep, missingReviewers, SPEC_PANEL, MAX_DELTA_PASSES, MAX_FIX_ROUNDS, realSeam } from "./release-review.mjs";
6
+ import { reviewStagingJson } from "../review-staging.mjs";
7
+
8
+ const H1 = "a".repeat(40), H2 = "b".repeat(40);
9
+ const manifest = (head, delta = null) => ({ pr: 7, headSha: head, bundle: [1, 2], scopeMode: "full", contextFile: "/sd/review-ctx-7.json", launchedFile: "/sd/7_launched", briefs: [{ domain: "security", path: "/sd/brief-security.md" }], delta });
10
+ const fin = (extra = {}) => ({ code: 0, data: { head: H1, toFile: [], notes: [], ...extra }, lines: [] });
11
+
12
+ /** Seam fake: `heads` is what headOf answers in turn; `fins` what finalize answers in turn. */
13
+ function fakeSeam({ heads = [H1], fins = [fin()], summary, lanes = [] } = {}) {
14
+ const log = [], agents = [];
15
+ let h = 0, f = 0, l = 0, n = 100;
16
+ return {
17
+ log, agents,
18
+ pre: async (a) => { log.push(["pre", a.delta]); return { code: 0, data: manifest(a.delta ? heads[heads.length - 1] : H1, a.delta ? { from: a.delta, files: ["x"] } : null), lines: [] }; },
19
+ finalize: async () => { log.push(["finalize"]); return fins[Math.min(f++, fins.length - 1)]; },
20
+ summary: async (a) => { log.push(["summary", a.filed]); return summary ?? { code: 0, data: { verdict: "APPROVE FOR DEPLOY", marker: "FORGE:GATE_PASS", ciFailing: 0 }, lines: [] }; },
21
+ headOf: async () => heads[Math.min(h++, heads.length - 1)],
22
+ readFile: (p) => `brief ${p}`,
23
+ markLaunched: (file, domains) => log.push(["launched", domains]),
24
+ saveTestGate: () => "/sd/7_test_gate_output.txt",
25
+ runAgent: async (a) => { agents.push(a.role + (a.prompt.includes("findings block required") ? ":reask" : "")); return { text: "ok" }; },
26
+ fileIssue: async ({ item }) => { log.push(["file", item.title]); return n++; },
27
+ fileCiIssue: async () => { log.push(["ci-issue"]); return n++; },
28
+ addNotes: async (pr, notes) => log.push(["notes", notes]),
29
+ runLane: async (a) => { log.push(["lane", a.issue, a.lane]); return lanes[l++] ?? { terminalReason: "merged" }; },
30
+ };
31
+ }
32
+ const ctx = (seam, steps = {}) => ({ io: { review: seam }, repo: "o/r", def: "main", staging: "staging", state: { steps: { "release-pr": { result: { pr: 7 } }, ...steps } }, save() {} });
33
+
34
+ describe("reviewStep", () => {
35
+ it("realSeam exposes every effect the steps use, matching the fake seam", () => {
36
+ const real = Object.keys(realSeam({ repo: "o/r", def: "main", env: {}, cwd: "/tmp" })).sort();
37
+ assert.deepEqual(real, Object.keys(fakeSeam()).filter((k) => k !== "log" && k !== "agents").sort());
38
+ });
39
+
40
+ it("runs the briefs and the spec panel in parallel, then test gate, finalize and summary in order", async () => {
41
+ const s = fakeSeam();
42
+ const r = await reviewStep(ctx(s));
43
+ assert.equal(r.marker, "FORGE:GATE_PASS");
44
+ assert.deepEqual(s.agents.slice().sort(), ["release-review-security", "release-test-gate", ...SPEC_PANEL.map((p) => `release-review-${p.domain}`)].sort());
45
+ assert.deepEqual(s.log.map((e) => e[0]), ["pre", "launched", "finalize", "summary"]);
46
+ assert.deepEqual(s.log[1][1], ["security", ...SPEC_PANEL.map((p) => p.domain)]);
47
+ });
48
+
49
+ it("R2: a head move triggers a --delta pass from the reviewed sha and never finalizes at the moved head", async () => {
50
+ const s = fakeSeam({ heads: [H2, H2] });
51
+ const r = await reviewStep(ctx(s));
52
+ const pres = s.log.filter((e) => e[0] === "pre");
53
+ assert.deepEqual(pres.map((e) => e[1]), [null, H1], "second pass is --delta <reviewed sha>");
54
+ assert.equal(s.log.filter((e) => e[0] === "finalize").length, 1, "finalize ran once, after the delta pass");
55
+ assert.ok(s.log.findIndex((e) => e[0] === "finalize") > s.log.findLastIndex((e) => e[0] === "pre"));
56
+ assert.equal(r.verdict, "APPROVE FOR DEPLOY");
57
+ // the delta pass credits the spec panel: only the briefs are re-run
58
+ assert.equal(s.agents.filter((a) => a === "release-review-material-change").length, 1);
59
+ });
60
+
61
+ it("a finalize refusal for a moved head also becomes a delta pass", async () => {
62
+ const s = fakeSeam({ fins: [{ code: 1, data: null, lines: ["REVIEW_RESULT: status: BLOCKED, blocker: head moved since the review (aaaaaaa -> bbbbbbb)"] }, fin()] });
63
+ await reviewStep(ctx(s));
64
+ assert.equal(s.log.filter((e) => e[0] === "pre").length, 2);
65
+ });
66
+
67
+ it("blocks when the head keeps moving", async () => {
68
+ const s = fakeSeam();
69
+ let i = 0;
70
+ s.headOf = async () => String(++i).padStart(40, "c");
71
+ const r = await reviewStep(ctx(s));
72
+ assert.equal(r.blocked, true);
73
+ assert.match(r.reason, new RegExp(`${MAX_DELTA_PASSES} delta passes`));
74
+ });
75
+
76
+ it("re-asks only the reviewer with a missing findings block, once, then finalizes", async () => {
77
+ const s = fakeSeam({ fins: [{ code: 1, data: null, lines: ["REVIEW DELIVERY FAILURE: missing findings comment(s) for: security code-quality"] }, fin()] });
78
+ const r = await reviewStep(ctx(s));
79
+ assert.equal(r.blocked, undefined);
80
+ assert.deepEqual(s.agents.filter((a) => a.endsWith(":reask")).sort(), ["release-review-code-quality:reask", "release-review-security:reask"]);
81
+ });
82
+
83
+ it("a second miss is a degraded panel (blocked, no further re-ask)", async () => {
84
+ const bad = { code: 1, data: null, lines: ["REVIEW DELIVERY FAILURE: no structured findings block from: security."] };
85
+ const s = fakeSeam({ fins: [bad] });
86
+ const r = await reviewStep(ctx(s));
87
+ assert.equal(r.blocked, true);
88
+ assert.match(r.reason, /degraded panel/);
89
+ assert.equal(s.agents.filter((a) => a.endsWith(":reask")).length, 1);
90
+ assert.equal(s.log.filter((e) => e[0] === "summary").length, 0);
91
+ });
92
+
93
+ it("files each FILE item, lists NOTEs in the PR body, then summarises with --filed", async () => {
94
+ const s = fakeSeam({ fins: [fin({ toFile: [{ title: "a", severity: "HIGH" }, { title: "b", severity: "LOW" }], notes: ["- n1"] })] });
95
+ const r = await reviewStep(ctx(s));
96
+ assert.deepEqual(s.log.slice(-4).map((e) => e[0]), ["file", "file", "notes", "summary"]);
97
+ assert.deepEqual(s.log.at(-1)[1], [100, 101]);
98
+ assert.deepEqual(r.blocking, [100], "only CRITICAL/HIGH findings block");
99
+ });
100
+
101
+ it("blocks when filing fails, before any summary is posted", async () => {
102
+ const s = fakeSeam({ fins: [fin({ toFile: [{ title: "a", severity: "HIGH" }] })] });
103
+ s.fileIssue = async () => null;
104
+ const r = await reviewStep(ctx(s));
105
+ assert.equal(r.blocked, true);
106
+ assert.equal(s.log.filter((e) => e[0] === "summary").length, 0);
107
+ });
108
+
109
+ it("blocks without a release PR", async () => {
110
+ assert.equal((await reviewStep({ ...ctx(fakeSeam()), state: { steps: {} } })).blocked, true);
111
+ });
112
+ });
113
+
114
+ describe("fixStep", () => {
115
+ const failed = { pr: 7, head: H1, verdict: "BLOCK DEPLOY", marker: "FORGE:GATE_FAILURE", blocking: [101], filed: [101], ciFailing: 0 };
116
+
117
+ it("does nothing on GATE_PASS", async () => {
118
+ const s = fakeSeam();
119
+ const r = await fixStep(ctx(s, { review: { result: { ...failed, verdict: "APPROVE FOR DEPLOY", marker: "FORGE:GATE_PASS" } } }));
120
+ assert.equal(r.blocked, undefined);
121
+ assert.equal(s.log.length, 0);
122
+ });
123
+
124
+ it("runs a lane on the staging branch per blocking issue, then a delta review from the reviewed head", async () => {
125
+ const s = fakeSeam({ heads: [H2] });
126
+ const c = ctx(s, { review: { result: failed } });
127
+ const r = await fixStep(c);
128
+ assert.deepEqual(s.log[0], ["lane", 101, "staging"]);
129
+ assert.deepEqual(s.log[1], ["pre", H1]);
130
+ assert.equal(r.verdict, "APPROVE FOR DEPLOY");
131
+ });
132
+
133
+ it("is bounded: blocks once the rounds are spent", async () => {
134
+ const bad = { code: 0, data: { verdict: "BLOCK DEPLOY", marker: "FORGE:GATE_FAILURE", ciFailing: 0 }, lines: [] };
135
+ const s = fakeSeam({ heads: [H2], summary: bad, fins: [fin({ toFile: [{ title: "x", severity: "CRITICAL" }] })] });
136
+ const r = await fixStep(ctx(s, { review: { result: failed } }));
137
+ assert.equal(r.blocked, true);
138
+ assert.equal(s.log.filter((e) => e[0] === "lane").length, MAX_FIX_ROUNDS);
139
+ });
140
+
141
+ it("blocks when a lane does not merge", async () => {
142
+ const s = fakeSeam({ lanes: [{ terminalReason: "needs-human" }] });
143
+ assert.equal((await fixStep(ctx(s, { review: { result: failed } }))).blocked, true);
144
+ });
145
+
146
+ it("red CI with no finding files one CI issue and runs a lane on it, then reviews the delta", async () => {
147
+ const s = fakeSeam({ heads: [H2] });
148
+ const r = await fixStep(ctx(s, { review: { result: { ...failed, blocking: [], ciFailing: 2 } } }));
149
+ assert.deepEqual(s.log.slice(0, 3), [["ci-issue"], ["lane", 100, "staging"], ["pre", H1]]);
150
+ assert.equal(r.blocked, undefined);
151
+ });
152
+
153
+ it("a blocking finding and red CI together get a lane each", async () => {
154
+ const s = fakeSeam({ heads: [H2] });
155
+ await fixStep(ctx(s, { review: { result: { ...failed, ciFailing: 1 } } }));
156
+ assert.deepEqual(s.log.filter((e) => e[0] === "lane").map((e) => e[1]), [101, 100]);
157
+ });
158
+
159
+ it("blocks when the verdict is not a pass but there is nothing to fix", async () => {
160
+ assert.match((await fixStep(ctx(fakeSeam(), { review: { result: { ...failed, blocking: [], ciFailing: 0 } } }))).reason, /nothing to fix|neither/);
161
+ });
162
+ });
163
+
164
+ describe("missingReviewers", () => {
165
+ it("reads the names from the delivery and extract messages", () => {
166
+ assert.deepEqual(missingReviewers(["x", "REVIEW DELIVERY FAILURE: missing findings comment(s) for: a b-c"]), ["a", "b-c"]);
167
+ assert.deepEqual(missingReviewers(["REVIEW DELIVERY FAILURE: no structured findings block from: a, b. Re-dispatch them once"]), ["a", "b"]);
168
+ assert.deepEqual(missingReviewers(["nothing"]), []);
169
+ });
170
+ });
171
+
172
+ describe("reviewStagingJson (library entry)", () => {
173
+ const io = (gh) => ({ root: "/r", env: {}, cwd: "/c", run: async () => ({ code: 0, stdout: "", stderr: "" }), gh, readFile: () => { throw new Error("nofile"); }, writeFile() {}, rm() {}, mkdir() {}, out: () => assert.fail("printed"), err: () => assert.fail("printed") });
174
+ it("returns a stop as {code, lines} without printing and never throws", async () => {
175
+ const r = await reviewStagingJson(["--summary"], io(async () => { throw new Error("no gh"); }));
176
+ assert.equal(r.data, null);
177
+ assert.ok(r.code >= 1);
178
+ assert.ok(r.lines.length > 0);
179
+ });
180
+ });
@@ -0,0 +1,228 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * `forgedock release [--repo R] [--merge] [--watch] [--resume <id>]` (#5208): the staging -> default release as one durable,
5
+ * resumable job. State lives in `~/.forge/releases/<id>/state.json` (or `FORGEDOCK_RELEASE_DIR`), written like a batch
6
+ * (tmp + fsync + rename, never tmpfs). Steps run in order and each completed step is recorded, so `--resume <id>` continues
7
+ * from the last completed one. Every effect goes through `io`, so the steps are unit-testable. Review, fixes and post-merge
8
+ * live in release-review.mjs / release-postmerge.mjs (stubs that block until their parts land). Promotion is opt-in: without
9
+ * `--merge` or forge.yaml `release.auto_merge: true` the job stops at GATE_PASS and prints the merge command.
10
+ */
11
+ import { existsSync, mkdirSync, readFileSync } from "node:fs";
12
+ import { execFileSync } from "node:child_process";
13
+ import { homedir } from "node:os";
14
+ import { join } from "node:path";
15
+ import { writeAtomic, assertDiskPath, batchRoot, listBatches, openBatch, isLaneAlive } from "./batch.mjs";
16
+ import { readBranches, DEFAULT_STAGING_BRANCH } from "./lane.mjs";
17
+ import { ghRunner } from "./issuewatch.mjs";
18
+ import { parseForgeYaml } from "../forge-utils.mjs";
19
+ import { reviewStep, fixStep } from "./release-review.mjs";
20
+ import { postMergeStep } from "./release-postmerge.mjs";
21
+ import { rehearsalStep, parseRehearsalConfig } from "./release-rehearsal.mjs";
22
+
23
+ export const RELEASE_STEPS = ["preflight", "release-pr", "review", "fixes", "rehearsal", "promotion", "post-merge"];
24
+ const ID_RE = /^r\d{8}-\d{6}-\d+$/;
25
+ const BLOCKED_EXIT = 3;
26
+
27
+ export function releaseRoot(env = process.env) {
28
+ return env.FORGEDOCK_RELEASE_DIR || join(homedir(), ".forge", "releases");
29
+ }
30
+ export function newReleaseId(now = Date.now(), pid = process.pid) {
31
+ return `r${new Date(now).toISOString().replace(/[-:]/g, "").replace("T", "-").slice(0, 15)}-${pid}`;
32
+ }
33
+
34
+ /** Handle on one release directory; every write is atomic. */
35
+ export function openRelease(root, id, mounts) {
36
+ if (!ID_RE.test(String(id ?? ""))) throw new Error(`invalid release id ${JSON.stringify(id)}`);
37
+ const file = join(root, id, "state.json");
38
+ return {
39
+ id, file,
40
+ exists: () => existsSync(file),
41
+ load: () => { try { return JSON.parse(readFileSync(file, "utf8")); } catch { return null; } },
42
+ save: (state) => { assertDiskPath(root, mounts); mkdirSync(join(root, id), { recursive: true }); writeAtomic(file, JSON.stringify(state, null, 2) + "\n", { private: true }); },
43
+ };
44
+ }
45
+
46
+ /** forge.yaml `release.*` of `raw`: `{autoMerge, artifactCheck, versionSync, publishWorkflow, rehearsal}` (#5253). */
47
+ export function readReleaseConfig(raw) {
48
+ let r = {};
49
+ try { r = parseForgeYaml(String(raw ?? ""))?.release ?? {}; } catch { r = {}; }
50
+ const off = (v) => ["false", "off", "no", "0", ""].includes(String(v ?? "").trim().toLowerCase());
51
+ return { autoMerge: !off(r.auto_merge), artifactCheck: r.artifact_check || null, versionSync: !off(r.version_sync), publishWorkflow: r.publish_workflow || null, ...rehearsalKey(r) };
52
+ }
53
+
54
+ /** `{rehearsal}` only when configured, so the config of a repo without it keeps its shape. */
55
+ const rehearsalKey = (r) => { const rehearsal = parseRehearsalConfig(r); return rehearsal ? { rehearsal } : {}; };
56
+
57
+ const json = (s) => JSON.parse(String(s || "null"));
58
+
59
+ /** The bundle list of PRs merged into `base` since the last release PR (the newest merged head->base PR). */
60
+ export async function bundleList({ io, repo, head, base }) {
61
+ const last = json(await io.gh(["pr", "list", "--repo", repo, "--base", base, "--head", head, "--state", "merged", "--limit", "1", "--json", "mergedAt"]))?.[0]?.mergedAt;
62
+ const merged = json(await io.gh(["pr", "list", "--repo", repo, "--base", head, "--state", "merged", "--limit", "200", "--json", "number,title,mergedAt"])) ?? [];
63
+ return merged.filter((p) => !last || p.mergedAt > last).sort((a, b) => a.number - b.number);
64
+ }
65
+
66
+ const bundleBody = (list) => `## Release bundle\n\n${list.length ? list.map((p) => `- #${p.number} ${p.title}`).join("\n") : "_No merged PRs found since the last release._"}\n`;
67
+
68
+ async function preflightStep(ctx) {
69
+ const { io, repo, state, staging } = ctx;
70
+ const lanes = await io.runningLanes(repo);
71
+ if (lanes.length) return { refused: `lanes of ${repo} are running (${lanes.map((l) => `${l.batch}#${l.issue}`).join(", ")}); wait or cancel them` };
72
+ const open = json(await io.gh(["pr", "list", "--repo", repo, "--base", staging, "--state", "open", "--json", "number"])) ?? [];
73
+ if (open.length) return { refused: `open PRs target ${staging}: ${open.map((p) => `#${p.number}`).join(", ")}; merge or close them first` };
74
+ // Hold: K=1 on every unfinished batch of the repo; the previous K is recorded so it can be restored, also after a kill.
75
+ state.held ??= [];
76
+ for (const b of await io.batches(repo)) {
77
+ if (state.held.some((h) => h.batch === b.id)) continue;
78
+ state.held.push({ batch: b.id, k: b.k });
79
+ ctx.save();
80
+ await io.setParallel(b.id, 1);
81
+ }
82
+ return { held: state.held.length };
83
+ }
84
+
85
+ /** Restore every held batch to its recorded K; best effort, recorded as it goes. */
86
+ export async function restoreBatches(ctx) {
87
+ const { io, state } = ctx;
88
+ for (const h of state.held ?? []) {
89
+ if (h.restored) continue;
90
+ try { await io.setParallel(h.batch, h.k ?? 1); h.restored = true; } catch (e) { io.print(`release: could not restore K=${h.k} on batch ${h.batch}: ${e.message}`); }
91
+ }
92
+ ctx.save();
93
+ }
94
+
95
+ async function releasePrStep(ctx) {
96
+ const { io, repo, staging, def } = ctx;
97
+ const found = json(await io.gh(["pr", "list", "--repo", repo, "--base", def, "--head", staging, "--state", "open", "--json", "number,headRefOid,url"]))?.[0];
98
+ if (found) return { pr: found.number, head: found.headRefOid, url: found.url, reused: true };
99
+ const list = await bundleList({ io, repo, head: staging, base: def });
100
+ const url = String(await io.gh(["pr", "create", "--repo", repo, "--base", def, "--head", staging, "--title", `Release: ${staging} -> ${def}`, "--body", bundleBody(list)])).trim();
101
+ const n = Number(/\/pull\/(\d+)/.exec(url)?.[1]);
102
+ if (!Number.isSafeInteger(n)) throw new Error(`gh pr create returned no PR url: ${url}`);
103
+ const v = json(await io.gh(["pr", "view", String(n), "--repo", repo, "--json", "headRefOid"]));
104
+ return { pr: n, head: v?.headRefOid, url, reused: false, bundle: list.length };
105
+ }
106
+
107
+ /** GATE_PASS marker on the PR and the `forge/deploy-gate` conclusion at `head`. */
108
+ export async function gateState({ io, repo, pr, head }) {
109
+ const comments = json(await io.gh(["pr", "view", String(pr), "--repo", repo, "--json", "comments"]))?.comments ?? [];
110
+ const bodies = comments.map((c) => String(c.body ?? ""));
111
+ let marker = null;
112
+ for (const b of bodies) { if (b.includes("FORGE:GATE_PASS")) marker = "pass"; else if (b.includes("FORGE:GATE_FAILURE")) marker = "failure"; }
113
+ const checks = json(await io.gh(["api", `repos/${repo}/commits/${head}/check-runs`, "--jq", "[.check_runs[] | {name, conclusion}]"])) ?? [];
114
+ const gate = checks.find((c) => c.name === "forge/deploy-gate");
115
+ return { marker, deployGate: gate?.conclusion ?? null };
116
+ }
117
+
118
+ async function promotionStep(ctx) {
119
+ const { io, repo, state, opts } = ctx;
120
+ const { pr } = state.steps["release-pr"].result;
121
+ const view = json(await io.gh(["pr", "view", String(pr), "--repo", repo, "--json", "state,mergeCommit,headRefOid"]));
122
+ const head = view?.headRefOid;
123
+ // Already merged (by hand, or by a crashed --merge run): hand the merge sha to post-merge; never gate or merge again.
124
+ if (view?.state === "MERGED" && view?.mergeCommit?.oid) return { merged: true, alreadyMerged: true, mergeCommit: view.mergeCommit.oid, head };
125
+ if (view?.state === "CLOSED") return { stopped: true, why: `release PR #${pr} was closed without merging`, head };
126
+ const gate = await gateState({ io, repo, pr, head });
127
+ if (gate.marker !== "pass") return { stopped: true, why: `no FORGE:GATE_PASS on #${pr} (last marker: ${gate.marker ?? "none"})`, head };
128
+ const cmd = `gh pr merge ${pr} --repo ${repo} --merge --match-head-commit ${head}`;
129
+ if (!opts.merge && !ctx.config.autoMerge) { io.print(`GATE_PASS on #${pr}. Merge when ready:\n ${cmd}`); return { stopped: true, why: "GATE_PASS; promotion is opt-in (--merge or release.auto_merge)", cmd, head, gate }; }
130
+ if (gate.deployGate !== "success") return { stopped: true, why: `forge/deploy-gate is ${gate.deployGate ?? "absent"}, not success`, head, gate };
131
+ await io.gh(["pr", "merge", String(pr), "--repo", repo, "--merge", "--match-head-commit", head]);
132
+ return { merged: true, head, gate };
133
+ }
134
+
135
+ const STEP_FNS = {
136
+ preflight: preflightStep,
137
+ "release-pr": releasePrStep,
138
+ review: (ctx) => reviewStep(ctx),
139
+ fixes: (ctx) => fixStep(ctx),
140
+ rehearsal: (ctx) => rehearsalStep(ctx),
141
+ promotion: promotionStep,
142
+ "post-merge": (ctx) => postMergeStep(ctx),
143
+ };
144
+
145
+ /** The step table with `over` replacing steps by name (tests stub the steps that need a real repo). */
146
+ export const withStubs = (over = {}) => ({ ...STEP_FNS, ...over });
147
+
148
+ /**
149
+ * Run the job: each step not yet done, in order. A step result with `refused`, `blocked` or `stopped` ends the run and is not
150
+ * marked done (the next resume retries it). Batches are restored on every exit that ends the job (finished, refused, thrown).
151
+ * @returns {{id, status: "done"|"refused"|"blocked"|"stopped", step?, reason?}}
152
+ */
153
+ export async function runRelease({ io, repo, opts = {}, config = {}, branches = {}, root, id, steps = STEP_FNS, mounts }) {
154
+ const rel = openRelease(root, id, mounts);
155
+ const state = rel.load() ?? { v: 1, id, repo, startedAt: new Date(io.now()).toISOString(), steps: {}, held: [] };
156
+ state.opts = { merge: !!(opts.merge || state.opts?.merge) };
157
+ const ctx = { io, repo, opts: state.opts, config, state, staging: branches.staging || DEFAULT_STAGING_BRANCH, def: branches.default || "main", save: () => rel.save(state) };
158
+ ctx.save();
159
+ let out;
160
+ try {
161
+ for (const step of RELEASE_STEPS) {
162
+ if (state.steps[step]?.done) continue;
163
+ const result = await steps[step](ctx);
164
+ if (result?.refused) { out = { id, status: "refused", step, reason: result.refused }; break; }
165
+ if (result?.blocked) { out = { id, status: "blocked", step, reason: result.reason }; break; }
166
+ if (result?.stopped) { state.steps[step] = { done: false, at: new Date(io.now()).toISOString(), result }; out = { id, status: "stopped", step, reason: result.why }; break; }
167
+ state.steps[step] = { done: true, at: new Date(io.now()).toISOString(), result };
168
+ ctx.save();
169
+ }
170
+ out ??= { id, status: "done" };
171
+ } finally {
172
+ // A stop at GATE_PASS ends the release hold as well: nothing else is waiting on the batches.
173
+ await restoreBatches(ctx);
174
+ }
175
+ state.status = out.status; ctx.save();
176
+ return out;
177
+ }
178
+
179
+ /** Real effects. `runningLanes`/`batches` read the batch dirs of `repo` (a plan without `repo` is taken as this repo's). */
180
+ export function realReleaseIo({ env = process.env, exec = execFileSync, print = (l) => console.log(l) } = {}) {
181
+ const gh = ghRunner(exec, print);
182
+ const root = batchRoot(env);
183
+ const mine = (b, repo) => { const r = b.readPlan()?.repo; return !r || r === repo; };
184
+ const unfinished = (repo) => listBatches(root).map((id) => openBatch(root, id)).filter((b) => !b.readReport() && mine(b, repo));
185
+ return {
186
+ gh: (args) => gh(args), print, now: () => Date.now(),
187
+ sleep: (ms) => new Promise((r) => setTimeout(r, ms)),
188
+ run: async (cmd) => { try { exec("sh", ["-c", cmd], { stdio: "ignore", timeout: 120_000 }); return { ok: true }; } catch { return { ok: false }; } },
189
+ rehearse: async (cmd, { timeout } = {}) => {
190
+ try { return { ok: true, code: 0, output: String(exec("sh", ["-c", cmd], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], timeout, maxBuffer: 16 << 20 })) }; }
191
+ catch (e) { return { ok: false, code: e.status ?? null, timedOut: e.code === "ETIMEDOUT", output: `${e.stdout ?? ""}${e.stderr ?? ""}` || String(e.message) }; }
192
+ },
193
+ runningLanes: (repo) => unfinished(repo).flatMap((b) => Object.entries(b.state.load()?.lanes ?? {})
194
+ .filter(([n, rec]) => rec?.pid && isLaneAlive(rec.pid, b.resultFile(n)) && !existsSync(b.resultFile(n)))
195
+ .map(([n]) => ({ batch: b.id, issue: n }))),
196
+ batches: (repo) => unfinished(repo).map((b) => ({ id: b.id, k: b.readParallel() ?? 1 })),
197
+ setParallel: async (id, k) => {
198
+ const { orchestrateFromCli } = await import("../engine-cli.mjs");
199
+ await orchestrateFromCli(["--set-parallel", id, String(k)]);
200
+ },
201
+ };
202
+ }
203
+
204
+ const flag = (argv, f) => { const i = argv.indexOf(f); return i >= 0 ? argv[i + 1] : null; };
205
+ export const RELEASE_USAGE = "usage: forgedock release [--repo owner/repo] [--merge] [--watch] [--resume <id>]";
206
+
207
+ /** `forgedock release ...`; @returns the process exit code (0 done or stopped at GATE_PASS, 1 refused, 3 blocked on a manual step). */
208
+ export async function releaseFromCli(argv, deps = {}) {
209
+ const cwd = deps.cwd ?? process.cwd(), env = deps.env ?? process.env;
210
+ const io = deps.io ?? realReleaseIo({ env });
211
+ const unknown = argv.filter((a, i) => a.startsWith("--") && !["--repo", "--merge", "--watch", "--resume"].includes(a) && !(argv[i - 1] === "--resume" || argv[i - 1] === "--repo"));
212
+ if (unknown.length) throw new Error(`unknown option ${unknown[0]}; ${RELEASE_USAGE}`);
213
+ const root = releaseRoot(env);
214
+ const resume = flag(argv, "--resume");
215
+ let id = resume ?? newReleaseId(io.now());
216
+ let repo = flag(argv, "--repo");
217
+ if (resume) {
218
+ const st = openRelease(root, resume).load();
219
+ if (!st) throw new Error(`no release ${resume} in ${root}`);
220
+ repo ??= st.repo;
221
+ }
222
+ repo ??= JSON.parse(String(await io.gh(["repo", "view", "--json", "nameWithOwner"]))).nameWithOwner;
223
+ let raw = ""; try { raw = readFileSync(join(cwd, "forge.yaml"), "utf8"); } catch { /* no forge.yaml: defaults */ }
224
+ const r = await runRelease({ io, repo, opts: { merge: argv.includes("--merge") }, config: readReleaseConfig(raw), branches: readBranches(cwd), root, id, mounts: deps.mounts });
225
+ const line = r.status === "done" ? `release ${id}: done` : `release ${id}: ${r.status} at ${r.step}: ${r.reason} (resume: forgedock release --resume ${id})`;
226
+ io.print(line);
227
+ return r.status === "refused" ? 1 : r.status === "blocked" ? BLOCKED_EXIT : 0;
228
+ }