forgedock 1.52.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 (93) 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 +53 -16
  4. package/bin/experiment.mjs +58 -6
  5. package/bin/forge-utils.mjs +6 -2
  6. package/bin/forgedock.mjs +15 -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 +195 -22
  21. package/bin/lean/conformance.test.mjs +152 -5
  22. package/bin/lean/effects.mjs +8 -4
  23. package/bin/lean/execution.mjs +19 -3
  24. package/bin/lean/execution.test.mjs +39 -0
  25. package/bin/lean/findinglabel.mjs +16 -0
  26. package/bin/lean/findinglabel.test.mjs +39 -0
  27. package/bin/lean/issuewatch-release.mjs +6 -2
  28. package/bin/lean/issuewatch-release.test.mjs +16 -0
  29. package/bin/lean/issuewatch.mjs +11 -1
  30. package/bin/lean/lanelock.mjs +14 -0
  31. package/bin/lean/lean.mjs +165 -34
  32. package/bin/lean/lean.test.mjs +289 -9
  33. package/bin/lean/light.mjs +48 -7
  34. package/bin/lean/light.test.mjs +37 -3
  35. package/bin/lean/limits.test.mjs +142 -9
  36. package/bin/lean/orchestrate-cancel.test.mjs +143 -0
  37. package/bin/lean/orchestrate.mjs +96 -26
  38. package/bin/lean/postdeploy-check.test.mjs +39 -0
  39. package/bin/lean/prompts.mjs +8 -7
  40. package/bin/lean/quota.mjs +39 -0
  41. package/bin/lean/recovery.test.mjs +10 -0
  42. package/bin/lean/relaxation.mjs +73 -0
  43. package/bin/lean/relaxation.test.mjs +54 -0
  44. package/bin/lean/release-postmerge.mjs +119 -0
  45. package/bin/lean/release-rehearsal.mjs +63 -0
  46. package/bin/lean/release-rehearsal.test.mjs +93 -0
  47. package/bin/lean/release-review.e2e.test.mjs +77 -0
  48. package/bin/lean/release-review.mjs +198 -0
  49. package/bin/lean/release-review.test.mjs +180 -0
  50. package/bin/lean/release.mjs +228 -0
  51. package/bin/lean/release.test.mjs +292 -0
  52. package/bin/lean/rotator.mjs +150 -31
  53. package/bin/lean/rotator.test.mjs +105 -2
  54. package/bin/lean/sandbox-remote.mjs +9 -2
  55. package/bin/lean/schedd.mjs +49 -4
  56. package/bin/lean/schedd.test.mjs +87 -6
  57. package/bin/lean/verifier.mjs +3 -2
  58. package/bin/lean/verify.mjs +2 -1
  59. package/bin/lean/verify.test.mjs +6 -0
  60. package/bin/pool/agent.mjs +18 -4
  61. package/bin/pool/router.mjs +66 -24
  62. package/bin/review-staging.mjs +23 -0
  63. package/bin/stats/conformance-outcomes.mjs +208 -0
  64. package/bin/stats/conformance-outcomes.test.mjs +188 -0
  65. package/bin/stats/depth.mjs +218 -0
  66. package/bin/stats/depth.test.mjs +133 -0
  67. package/bin/stats/experiment.mjs +7 -5
  68. package/bin/stats/github-source.mjs +2 -2
  69. package/bin/stats/index.mjs +64 -2
  70. package/bin/stats/local-source.mjs +11 -0
  71. package/bin/stats/query.mjs +69 -0
  72. package/bin/stats/selffiled.mjs +52 -0
  73. package/bin/stats/selffiled.test.mjs +71 -0
  74. package/commands/orchestrate.md +1 -1
  75. package/commands/review-pr-agents/security.md +4 -0
  76. package/commands/review-pr-staging.md +2 -0
  77. package/commands/work-on/build.md +4 -6
  78. package/docs/CONFIG.md +65 -8
  79. package/docs/ISSUE-WATCH.md +2 -0
  80. package/docs/OUTCOME-CODES.md +3 -0
  81. package/docs/STATS.md +44 -0
  82. package/docs/TELEMETRY.md +1 -1
  83. package/package.json +1 -1
  84. package/pool/README.md +1 -1
  85. package/pool/image/cs-cred +14 -1
  86. package/scripts/backfill-finding-labels.mjs +50 -0
  87. package/scripts/backfill-finding-labels.test.mjs +36 -0
  88. package/scripts/doctor-pipeline-state.sh +21 -6
  89. package/scripts/file-deferred-followups.sh +59 -251
  90. package/scripts/file-deferred-followups.test.sh +85 -206
  91. package/scripts/followup-route.mjs +12 -0
  92. package/scripts/owner-route-parity.test.sh +17 -1
  93. package/scripts/review-pr-side-effects.test.sh +40 -0
@@ -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
+ }
@@ -0,0 +1,292 @@
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 { readFileSync, existsSync } from "node:fs";
6
+ import { join } from "node:path";
7
+ import { tmpDir } from "../tests/_tmp.mjs";
8
+ import { releaseFromCli, readReleaseConfig, openRelease, newReleaseId } from "./release.mjs";
9
+ import { reviewStep, fixStep } from "./release-review.mjs";
10
+ import { postMergeStep } from "./release-postmerge.mjs";
11
+
12
+ const DISK = [{ mount: "/", type: "ext4" }]; // CI /tmp can be tmpfs, which assertDiskPath refuses
13
+ const tmp = () => tmpDir("release-");
14
+ const REPO = "o/r", HEAD = "a".repeat(40);
15
+
16
+ /** io fake; `world` tunes the gh answers. */
17
+ function fakeIo(world = {}) {
18
+ const calls = [], par = [], printed = [];
19
+ const w = { lanes: [], openStaging: [], batches: [], releasePr: [{ number: 7, headRefOid: HEAD, url: "u" }], comments: [{ body: "FORGE:GATE_PASS" }], gate: "success", ...world };
20
+ const io = {
21
+ calls, par, printed, now: () => 1_700_000_000_000, print: (l) => printed.push(l),
22
+ sleeps: [], ran: [], sleep: async (ms) => { io.sleeps.push(ms); },
23
+ run: async (cmd) => { io.ran.push(cmd); return { ok: io.ran.length >= (w.artifactOkAt ?? 1) }; },
24
+ runningLanes: async () => w.lanes,
25
+ batches: async () => w.batches,
26
+ setParallel: async (id, k) => { par.push([id, k]); },
27
+ gh: async (a) => {
28
+ calls.push(a);
29
+ const j = a.join(" ");
30
+ const pm = w.pm?.(a); if (pm !== undefined) return pm;
31
+ if (a[0] === "pr" && a[1] === "list" && a.includes("--state") && a[a.indexOf("--state") + 1] === "open") return JSON.stringify(a.includes("--head") ? w.releasePr : w.openStaging);
32
+ if (a[0] === "pr" && a[1] === "list") return JSON.stringify([]);
33
+ if (a[0] === "pr" && a[1] === "create") return "https://github.com/o/r/pull/9";
34
+ if (a[0] === "pr" && a[1] === "view" && j.includes("--json state,mergeCommit,headRefOid")) return JSON.stringify({ state: w.prState ?? "OPEN", mergeCommit: w.prState === "MERGED" ? { oid: "m".repeat(40) } : null, headRefOid: HEAD });
35
+ if (j.includes("--json headRefOid")) return JSON.stringify({ headRefOid: HEAD });
36
+ if (j.includes("--json comments")) return JSON.stringify({ comments: w.comments });
37
+ if (a[0] === "api") return JSON.stringify(w.gate ? [{ name: "forge/deploy-gate", conclusion: w.gate }] : []);
38
+ if (a[0] === "pr" && a[1] === "merge") return "";
39
+ throw new Error(`unexpected gh ${j}`);
40
+ },
41
+ };
42
+ return io;
43
+ }
44
+ const ok = async () => ({ ok: true });
45
+
46
+ describe("release job (#5211)", () => {
47
+ const promote = async (world, { opts = {}, config = {} } = {}) => {
48
+ const io = fakeIo(world), root = tmp(), id = newReleaseId();
49
+ // Real preflight/release-pr/promotion, with review/fixes/post-merge replaced by no-ops.
50
+ const mod = await import("./release.mjs");
51
+ const out = await mod.runRelease({ io, repo: REPO, root, mounts: DISK, id, opts, config, branches: { staging: "staging", default: "main" }, steps: mod.withStubs({ review: ok, fixes: ok, "post-merge": ok }) });
52
+ return { io, out, root, id };
53
+ };
54
+
55
+ it("R3: stops at GATE_PASS without --merge / auto_merge and prints the command; never merges", async () => {
56
+ const { io, out } = await promote({});
57
+ assert.equal(out.status, "stopped");
58
+ assert.ok(io.printed.some((l) => l.includes(`gh pr merge 7 --repo ${REPO} --merge --match-head-commit ${HEAD}`)));
59
+ assert.ok(!io.calls.some((a) => a[0] === "pr" && a[1] === "merge"));
60
+ });
61
+
62
+ it("R3: --merge merges with --match-head-commit when forge/deploy-gate is success", async () => {
63
+ const { io, out } = await promote({}, { opts: { merge: true } });
64
+ assert.equal(out.status, "done");
65
+ assert.ok(io.calls.some((a) => a[1] === "merge" && a.includes("--match-head-commit") && a.includes(HEAD)));
66
+ });
67
+
68
+ it("R3: release.auto_merge merges too; a non-success deploy-gate does not", async () => {
69
+ const a = await promote({}, { config: { autoMerge: true } });
70
+ assert.equal(a.out.status, "done");
71
+ for (const gate of ["pending", "failure", null]) {
72
+ const b = await promote({ gate }, { opts: { merge: true } });
73
+ assert.equal(b.out.status, "stopped", String(gate));
74
+ assert.ok(!b.io.calls.some((c) => c[1] === "merge"));
75
+ }
76
+ });
77
+
78
+ it("#5266: a release PR merged by hand moves to post-merge with the merge sha, without the opt-in stop", async () => {
79
+ const io = fakeIo({ prState: "MERGED" }), root = tmp(), id = newReleaseId();
80
+ const mod = await import("./release.mjs");
81
+ let seen = null;
82
+ const out = await mod.runRelease({ io, repo: REPO, root, mounts: DISK, id, opts: {}, config: {}, branches: { staging: "staging", default: "main" }, steps: mod.withStubs({ review: ok, fixes: ok, "post-merge": async (c) => { seen = c.state.steps.promotion.result; return {}; } }) });
83
+ assert.equal(out.status, "done");
84
+ assert.equal(seen.alreadyMerged, true);
85
+ assert.equal(seen.mergeCommit, "m".repeat(40));
86
+ });
87
+
88
+ it("#5266: --merge resume on an already-merged PR does not call gh pr merge", async () => {
89
+ const { io, out } = await promote({ prState: "MERGED" }, { opts: { merge: true } });
90
+ assert.equal(out.status, "done");
91
+ assert.ok(!io.calls.some((a) => a[0] === "pr" && a[1] === "merge"));
92
+ });
93
+
94
+ it("#5266: a release PR closed without merging stops", async () => {
95
+ const { io, out } = await promote({ prState: "CLOSED" }, { opts: { merge: true } });
96
+ assert.equal(out.status, "stopped");
97
+ assert.ok(!io.calls.some((a) => a[0] === "pr" && a[1] === "merge"));
98
+ });
99
+
100
+ it("R3: no GATE_PASS marker never merges", async () => {
101
+ const { io, out } = await promote({ comments: [{ body: "FORGE:GATE_FAILURE" }] }, { opts: { merge: true } });
102
+ assert.equal(out.status, "stopped");
103
+ assert.ok(!io.calls.some((c) => c[1] === "merge"));
104
+ });
105
+
106
+ it("preflight refuses while a lane runs; nothing is held", async () => {
107
+ const { io, out } = await promote({ lanes: [{ batch: "b1", issue: 3 }], batches: [{ id: "b1", k: 4 }] });
108
+ assert.equal(out.status, "refused");
109
+ assert.match(out.reason, /b1#3/);
110
+ assert.deepEqual(io.par, []);
111
+ });
112
+
113
+ it("preflight refuses while PRs to the staging branch are open", async () => {
114
+ const { io, out } = await promote({ openStaging: [{ number: 12 }], batches: [{ id: "b1", k: 4 }] });
115
+ assert.equal(out.status, "refused");
116
+ assert.match(out.reason, /#12/);
117
+ assert.deepEqual(io.par, []);
118
+ });
119
+
120
+ it("preflight holds batches at K=1 and restores the previous K at the end", async () => {
121
+ const { io, out, root, id } = await promote({ batches: [{ id: "b1", k: 4 }, { id: "b2", k: 2 }] });
122
+ assert.equal(out.status, "stopped");
123
+ assert.deepEqual(io.par, [["b1", 1], ["b2", 1], ["b1", 4], ["b2", 2]]);
124
+ assert.ok(openRelease(root, id).load().held.every((h) => h.restored));
125
+ });
126
+
127
+ it("release PR: reuses an open one; otherwise creates it with the bundle list", async () => {
128
+ const a = await promote({});
129
+ assert.ok(!a.io.calls.some((c) => c[1] === "create"));
130
+ const b = await promote({ releasePr: [] });
131
+ const create = b.io.calls.find((c) => c[1] === "create");
132
+ assert.ok(create && create.includes("--head") && create.includes("staging") && create.includes("main"));
133
+ });
134
+
135
+ it("R5: a killed job resumes from the last completed step", async () => {
136
+ const io = fakeIo(), root = tmp(), id = newReleaseId();
137
+ const mod = await import("./release.mjs");
138
+ const ran = [];
139
+ const rec = (n, fn) => async (ctx) => { ran.push(n); return fn(ctx); };
140
+ const base = mod.withStubs({ review: ok, fixes: ok, "post-merge": ok });
141
+ const kill = async () => { throw new Error("killed"); };
142
+ const first = { ...base, preflight: rec("preflight", base.preflight), "release-pr": rec("release-pr", base["release-pr"]), review: kill };
143
+ await assert.rejects(() => mod.runRelease({ io, repo: REPO, root, mounts: DISK, id, opts: { merge: true }, config: {}, branches: {}, steps: first }), /killed/);
144
+ const st = openRelease(root, id).load();
145
+ assert.deepEqual(Object.keys(st.steps), ["preflight", "release-pr"]);
146
+ const second = { ...base, preflight: rec("preflight2", base.preflight), "release-pr": rec("release-pr2", base["release-pr"]) };
147
+ const out = await mod.runRelease({ io, repo: REPO, root, mounts: DISK, id, opts: { merge: true }, config: {}, branches: {}, steps: second });
148
+ assert.equal(out.status, "done");
149
+ assert.deepEqual(ran, ["preflight", "release-pr"]); // preflight/release-pr not run again
150
+ });
151
+
152
+ it("unfinished steps return a blocked result that names the manual path; the job exits blocked", async () => {
153
+ for (const r of [await reviewStep({}), await fixStep({})]) { assert.equal(r.blocked, true); assert.match(r.reason, /manual path/); }
154
+ const io = fakeIo(), root = tmp();
155
+ io.review = { pre: async () => ({ code: 1, data: null, lines: ["stopped"] }) }; // the review step runs against a seam, never a real repo
156
+ const out = await (await import("./release.mjs")).runRelease({ io, repo: REPO, root, mounts: DISK, id: newReleaseId(), opts: {}, config: {}, branches: {} });
157
+ assert.equal(out.status, "blocked");
158
+ assert.equal(out.step, "review");
159
+ });
160
+
161
+ it("state is written atomically under FORGEDOCK_RELEASE_DIR and is private", async () => {
162
+ const root = tmp(), id = newReleaseId();
163
+ openRelease(root, id, DISK).save({ v: 1 });
164
+ assert.deepEqual(JSON.parse(readFileSync(join(root, id, "state.json"), "utf8")), { v: 1 });
165
+ assert.ok(!existsSync(join(root, id, `state.json.tmp-${process.pid}`)));
166
+ assert.throws(() => openRelease(root, "../x"), /invalid release id/);
167
+ });
168
+
169
+ it("readReleaseConfig reads auto_merge / artifact_check / version_sync", () => {
170
+ assert.deepEqual(readReleaseConfig("release:\n auto_merge: true\n artifact_check: npm view x\n version_sync: true\n"), { autoMerge: true, artifactCheck: "npm view x", versionSync: true, publishWorkflow: null });
171
+ assert.deepEqual(readReleaseConfig(""), { autoMerge: false, artifactCheck: null, versionSync: false, publishWorkflow: null });
172
+ assert.equal(readReleaseConfig("release:\n publish_workflow: pub.yml\n").publishWorkflow, "pub.yml");
173
+ });
174
+
175
+ it("CLI: rejects unknown options and exits 3 on a blocked step, naming the resume command", async () => {
176
+ const root = tmp(), io = fakeIo();
177
+ await assert.rejects(() => releaseFromCli(["--bogus"], { io, env: { FORGEDOCK_RELEASE_DIR: root }, cwd: root, mounts: DISK }), /unknown option/);
178
+ const code = await releaseFromCli(["--repo", REPO], { io, env: { FORGEDOCK_RELEASE_DIR: root }, cwd: root, mounts: DISK });
179
+ assert.equal(code, 3);
180
+ assert.ok(io.printed.some((l) => /forgedock release --resume r\d/.test(l)));
181
+ });
182
+ });
183
+
184
+ describe("release post-merge step (#5213)", () => {
185
+ const SHA = "b".repeat(40);
186
+ const PKG = Buffer.from(JSON.stringify({ version: "1.2.3" })).toString("base64");
187
+ /** gh answers for the post-merge calls; `o` tunes them. */
188
+ const pmWorld = (o = {}) => {
189
+ const st = { runs: o.runs ?? [[{ databaseId: 5, status: "completed", conclusion: "success" }]], runCalls: 0, dispatched: 0, syncPrs: o.syncPrs ?? [], created: 0 };
190
+ return {
191
+ st,
192
+ pm: (a) => {
193
+ const j = a.join(" ");
194
+ if (a[0] === "pr" && a[1] === "view" && j.includes("mergeCommit")) return JSON.stringify({ state: o.prState ?? "MERGED", mergeCommit: { oid: SHA } });
195
+ if (a[0] === "run" && a[1] === "list") { assert.ok(j.includes(`--commit ${SHA}`) && j.includes(`--workflow ${o.wf ?? "publish.yml"}`)); const r = st.runs[Math.min(st.runCalls++, st.runs.length - 1)]; return JSON.stringify(r); }
196
+ if (a[0] === "workflow" && a[1] === "run") { st.dispatched++; assert.ok(a.includes("main")); return ""; }
197
+ if (a[0] === "api" && j.includes("contents/package.json")) return PKG;
198
+ if (a[0] === "api" && j.includes("branches/chore/sync-version-1.2.3")) { if (o.noBranch) throw new Error("404"); return "x"; }
199
+ if (a[0] === "pr" && a[1] === "list" && j.includes("chore/sync-version")) return JSON.stringify(st.syncPrs);
200
+ if (a[0] === "pr" && a[1] === "create") { st.created++; assert.ok(a.includes("staging") && a.includes("chore/sync-version-1.2.3")); return "https://github.com/o/r/pull/30"; }
201
+ if (a[0] === "pr" && a[1] === "view" && j.includes("statusCheckRollup")) return JSON.stringify({ state: "OPEN", headRefOid: "c".repeat(40), statusCheckRollup: o.checks ?? [{ conclusion: "SUCCESS" }] });
202
+ if (a[0] === "pr" && a[1] === "merge" && Number(a[2]) >= 30) return "";
203
+ return undefined;
204
+ },
205
+ };
206
+ };
207
+ const run = (o = {}, config = {}) => {
208
+ const w = pmWorld(o), io = fakeIo({ pm: w.pm, ...o });
209
+ const ctx = { io, repo: REPO, def: "main", staging: "staging", config: { postMerge: { publishPolls: 2, runPolls: 2, branchPolls: 2, checkPolls: 2, artifactTries: 3 }, ...config }, state: { steps: { "release-pr": { result: { pr: 7 } } } } };
210
+ return postMergeStep(ctx).then((out) => ({ out, io, st: w.st }));
211
+ };
212
+
213
+ it("R1: a publish run for the merge commit is confirmed; nothing is dispatched", async () => {
214
+ const { out, st } = await run();
215
+ assert.equal(out.published, true);
216
+ assert.equal(out.run, 5);
217
+ assert.equal(st.dispatched, 0);
218
+ });
219
+
220
+ it("R2: no run appears -> one is dispatched on the default branch, then awaited", async () => {
221
+ const { out, st } = await run({ runs: [[], [], [{ databaseId: 8, status: "completed", conclusion: "success" }]] });
222
+ assert.equal(out.published, true);
223
+ assert.equal(out.dispatched, true);
224
+ assert.equal(st.dispatched, 1);
225
+ });
226
+
227
+ it("R2: a custom release.publish_workflow is used", async () => {
228
+ const { out } = await run({ wf: "pub.yml" }, { publishWorkflow: "pub.yml" });
229
+ assert.equal(out.published, true);
230
+ });
231
+
232
+ it("blocked when no run appears even after the dispatch, or the run fails or never finishes", async () => {
233
+ const a = await run({ runs: [[]] });
234
+ assert.equal(a.out.blocked, true); assert.equal(a.st.dispatched, 1);
235
+ const b = await run({ runs: [[{ databaseId: 1, status: "completed", conclusion: "failure" }]] });
236
+ assert.match(b.out.reason, /failure/);
237
+ const c = await run({ runs: [[{ databaseId: 1, status: "in_progress", conclusion: null }]] });
238
+ assert.match(c.out.reason, /did not finish/);
239
+ });
240
+
241
+ it("stopped (not blocked) while the release PR is not merged", async () => {
242
+ const { out, st } = await run({ prState: "OPEN" });
243
+ assert.equal(out.stopped, true);
244
+ assert.equal(st.runCalls, 0);
245
+ });
246
+
247
+ it("R3: artifact_check is polled with exponential backoff until it passes; exhausting it blocks", async () => {
248
+ const a = await run({ artifactOkAt: 3 }, { artifactCheck: "npm view x@1" });
249
+ assert.equal(a.out.artifact, true);
250
+ assert.deepEqual(a.io.ran, ["npm view x@1", "npm view x@1", "npm view x@1"]);
251
+ assert.deepEqual(a.io.sleeps.slice(-2), [5000, 10000]);
252
+ const b = await run({ artifactOkAt: 99 }, { artifactCheck: "npm view x@1" });
253
+ assert.equal(b.out.blocked, true);
254
+ assert.match(b.out.reason, /artifact_check/);
255
+ });
256
+
257
+ it("R4: version_sync opens the sync PR to staging and merges it with --match-head-commit when green", async () => {
258
+ const { out, st, io } = await run({}, { versionSync: true });
259
+ assert.equal(st.created, 1);
260
+ assert.equal(out.sync.merged, true);
261
+ assert.ok(io.calls.some((a) => a[1] === "merge" && a.includes("30") && a.includes("--match-head-commit") && a.includes("c".repeat(40))));
262
+ });
263
+
264
+ it("version_sync reuses an open sync PR, skips a merged one, and never merges red or check-less PRs", async () => {
265
+ const open = await run({ syncPrs: [{ number: 31, state: "OPEN" }] }, { versionSync: true });
266
+ assert.equal(open.st.created, 0);
267
+ assert.ok(open.io.calls.some((a) => a[1] === "merge" && a.includes("31")));
268
+ const merged = await run({ syncPrs: [{ number: 32, state: "MERGED" }] }, { versionSync: true });
269
+ assert.equal(merged.out.sync.merged, true);
270
+ assert.ok(!merged.io.calls.some((a) => a[1] === "merge"));
271
+ for (const checks of [[], [{ conclusion: "FAILURE" }], [{ conclusion: "SUCCESS" }, { status: "IN_PROGRESS", state: "PENDING" }]]) {
272
+ const r = await run({ syncPrs: [{ number: 33, state: "OPEN" }], checks }, { versionSync: true });
273
+ assert.equal(r.out.blocked, true, JSON.stringify(checks));
274
+ assert.ok(!r.io.calls.some((a) => a[1] === "merge"));
275
+ }
276
+ const nb = await run({ noBranch: true }, { versionSync: true });
277
+ assert.equal(nb.out.blocked, true);
278
+ });
279
+
280
+ it("R1: through the job, a blocked post-merge is retried on resume and finishes once the run exists", async () => {
281
+ const mod = await import("./release.mjs");
282
+ const root = tmp(), id = newReleaseId();
283
+ const world = (runs) => pmWorld({ runs });
284
+ const go = async (runs) => {
285
+ const io = fakeIo({ pm: world(runs).pm });
286
+ const config = { postMerge: { publishPolls: 1, runPolls: 1 } };
287
+ return mod.runRelease({ io, repo: REPO, root, mounts: DISK, id, opts: { merge: true }, config, branches: { staging: "staging", default: "main" }, steps: mod.withStubs({ review: ok, fixes: ok }) });
288
+ };
289
+ assert.equal((await go([[{ databaseId: 1, status: "completed", conclusion: "failure" }]])).status, "blocked");
290
+ assert.equal((await go([[{ databaseId: 2, status: "completed", conclusion: "success" }]])).status, "done");
291
+ });
292
+ });