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,190 @@
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 { execFileSync } from "node:child_process";
6
+ import { writeFileSync } from "node:fs";
7
+ import { join } from "node:path";
8
+ import { tmpDir } from "../tests/_tmp.mjs";
9
+ import { cutSnapshot, pickFixes, recut, checkChain, verifyRelease, cleanupSnapshot, parseRecord, withRecord, branchName, patternPrefix } from "./release-snapshot.mjs";
10
+
11
+ const ENV = { GIT_AUTHOR_NAME: "t", GIT_AUTHOR_EMAIL: "t@t", GIT_COMMITTER_NAME: "t", GIT_COMMITTER_EMAIL: "t@t", GIT_CONFIG_GLOBAL: "/dev/null", GIT_CONFIG_NOSYSTEM: "1" };
12
+ const mk = (cwd) => (args, { env, input } = {}) => execFileSync("git", args, { cwd, encoding: "utf8", input, env: { ...process.env, ...ENV, ...env }, stdio: ["pipe", "pipe", "pipe"] });
13
+
14
+ /** A bare origin and a clone with main = staging = one commit; `commit` adds a file commit on staging and pushes it. */
15
+ function repo() {
16
+ const root = tmpDir("snap-"), origin = join(root, "origin.git"), work = join(root, "work");
17
+ execFileSync("git", ["init", "--bare", "-b", "main", origin], { env: { ...process.env, ...ENV } });
18
+ execFileSync("git", ["clone", "-q", origin, work], { env: { ...process.env, ...ENV }, stdio: "ignore" });
19
+ const git = mk(work);
20
+ git(["checkout", "-q", "-b", "main"]);
21
+ writeFileSync(join(work, "a.txt"), "a\n"); git(["add", "."]); git(["commit", "-qm", "init"]); git(["push", "-q", "origin", "main"]);
22
+ git(["checkout", "-q", "-b", "staging"]); git(["push", "-q", "origin", "staging"]);
23
+ const commit = (file, text, msg) => { writeFileSync(join(work, file), text); git(["add", "."]); git(["commit", "-qm", msg]); git(["push", "-q", "origin", "staging"]); return git(["rev-parse", "HEAD"]).trim(); };
24
+ return { git, work, origin, commit };
25
+ }
26
+
27
+ /** gh fake: merged staging PRs (`prs`), release-blocker issue numbers, and the body of the release PR. */
28
+ function fakeGh({ prs = [], issues = [], released = [] } = {}) {
29
+ const w = { body: "", edits: 0, prs, issues };
30
+ const gh = async (a) => {
31
+ const j = a.join(" ");
32
+ if (j.startsWith("pr list") && j.includes("--json headRefName")) return JSON.stringify(released.map((headRefName) => ({ headRefName })));
33
+ if (j.startsWith("pr list") && j.includes("closingIssuesReferences")) return JSON.stringify(w.prs);
34
+ if (j.startsWith("issue list")) return JSON.stringify(w.issues.map((number) => ({ number })));
35
+ if (j.startsWith("pr view") && j.includes("--json body")) return JSON.stringify({ body: w.body });
36
+ if (j.startsWith("pr edit")) { w.body = a[a.indexOf("--body") + 1]; w.edits++; return ""; }
37
+ if (a[0] === "api") return JSON.stringify([{ number: 9, body: w.body }]);
38
+ throw new Error(`unexpected gh ${j}`);
39
+ };
40
+ return { gh, w };
41
+ }
42
+
43
+ const setup = async (opts = {}) => {
44
+ const r = repo();
45
+ const { gh, w } = fakeGh(opts);
46
+ const io = { gh, now: () => Date.parse("2026-11-10T12:00:00Z") };
47
+ const ctx = { io, git: r.git, repo: "o/r", staging: "staging", def: "main", state: { id: "r1", steps: { "release-pr": { result: { pr: 9 } } } }, save() {} };
48
+ return { ...r, io, w, ctx };
49
+ };
50
+ const cut = async (s) => {
51
+ const c = await cutSnapshot({ io: s.io, git: s.git, repo: "o/r", staging: "staging", def: "main", id: "r1", bundle: [{ number: 3, closingIssuesReferences: [{ number: 30 }] }] });
52
+ s.ctx.state.release = c.record;
53
+ return c;
54
+ };
55
+
56
+ describe("snapshot cut (#5276)", () => {
57
+ it("branch names come from the pattern; the prefix is what counts as in flight", () => {
58
+ assert.equal(branchName("release/{date}-{n}", Date.parse("2026-11-10T00:00:00Z"), 2), "release/20261110-2");
59
+ assert.equal(patternPrefix("release/{date}-{n}"), "release/");
60
+ assert.throws(() => branchName("bad name/{n}", 0, 1), /invalid branch name/);
61
+ });
62
+
63
+ it("R5: cuts release/<id> at the staging tip and records snapshot, range, bundle and issues; later staging commits do not move it", async () => {
64
+ const s = await setup();
65
+ const tip = s.commit("b.txt", "b\n", "feat: b");
66
+ const c = await cut(s);
67
+ assert.equal(c.branch, "release/20261110-1");
68
+ assert.equal(c.record.snapshot, tip);
69
+ assert.deepEqual([c.record.bundle, c.record.issues, c.record.picks], [[3], [30], []]);
70
+ s.commit("c.txt", "c\n", "feat: c (merged during the release)");
71
+ assert.equal(s.git(["ls-remote", "origin", "refs/heads/release/20261110-1"]).split("\t")[0], tip);
72
+ assert.deepEqual(checkChain({ git: s.git, record: c.record, sha: tip, staging: "staging", exact: true }), { ok: true, picks: 0 });
73
+ });
74
+
75
+ it("R11: a second release branch in flight refuses the cut", async () => {
76
+ const s = await setup();
77
+ await cut(s);
78
+ const again = await cutSnapshot({ io: s.io, git: s.git, repo: "o/r", staging: "staging", def: "main", id: "r2" });
79
+ assert.match(again.refused, /already in flight \(release\/20261110-1\)/);
80
+ });
81
+
82
+ it("numbers the branch after the day's earlier release PRs", async () => {
83
+ const s = await setup({ released: ["release/20261110-1", "release/20261109-1"] });
84
+ assert.equal((await cut(s)).branch, "release/20261110-2");
85
+ });
86
+ });
87
+
88
+ describe("cherry-picks and the verifier (#5276)", () => {
89
+ const blockerWorld = async () => {
90
+ const s = await setup();
91
+ s.commit("b.txt", "b\n", "feat: b");
92
+ const c = await cut(s);
93
+ const fix = s.commit("fix.txt", "fixed\n", "fix: blocker (#31)\n\nbody line");
94
+ s.w.prs = [{ number: 40, mergeCommit: { oid: fix }, mergedAt: "2026-11-10T13:00:00Z", labels: [{ name: "release-blocker" }], closingIssuesReferences: [] }];
95
+ return { s, c, fix };
96
+ };
97
+
98
+ it("R2: a merged release-blocker fix is cherry-picked onto the branch and recorded in FORGE:RELEASE (state and PR body)", async () => {
99
+ const { s, c, fix } = await blockerWorld();
100
+ const out = await pickFixes(s.ctx);
101
+ assert.deepEqual(out, { picked: [40] });
102
+ const [pick] = s.ctx.state.release.picks;
103
+ assert.equal(pick.orig, fix);
104
+ assert.equal(s.git(["ls-remote", "origin", `refs/heads/${c.branch}`]).split("\t")[0], pick.sha);
105
+ assert.match(s.git(["log", "-1", "--format=%B", pick.sha]), new RegExp(`\\(cherry picked from commit ${fix}\\)`));
106
+ assert.equal(s.git(["show", `${pick.sha}:fix.txt`]), "fixed\n");
107
+ assert.deepEqual(parseRecord(s.w.body).picks.map((p) => p.orig), [fix]);
108
+ assert.deepEqual(await pickFixes(s.ctx), { picked: [] }, "idempotent: a fix already on the branch is not picked twice");
109
+ assert.deepEqual(checkChain({ git: s.git, record: s.ctx.state.release, sha: pick.sha, staging: "staging", exact: true }), { ok: true, picks: 1 });
110
+ });
111
+
112
+ it("picks a fix that closes a named issue even without the label", async () => {
113
+ const { s } = await blockerWorld();
114
+ s.w.prs = s.w.prs.map((p) => ({ ...p, labels: [], closingIssuesReferences: [{ number: 31 }] }));
115
+ assert.deepEqual(await pickFixes(s.ctx), { picked: [] });
116
+ assert.deepEqual(await pickFixes(s.ctx, { issues: [31] }), { picked: [40] });
117
+ });
118
+
119
+ it("R3: a commit pushed to the release branch that is not a recorded cherry-pick fails the check", async () => {
120
+ const { s } = await blockerWorld();
121
+ await pickFixes(s.ctx);
122
+ const rec = s.ctx.state.release;
123
+ // a hand-pushed commit on top of the recorded head
124
+ s.git(["checkout", "-q", "-B", "tmp", rec.picks[0].sha]);
125
+ writeFileSync(join(s.work, "evil.txt"), "x\n"); s.git(["add", "."]); s.git(["commit", "-qm", "sneaky"]);
126
+ const evil = s.git(["rev-parse", "HEAD"]).trim();
127
+ assert.match(checkChain({ git: s.git, record: rec, sha: evil, staging: "staging", exact: true }).why, /1 commit\(s\)|2 commit\(s\)/);
128
+ // a commit that names a staging commit as its source but carries other changes
129
+ s.git(["checkout", "-q", "-B", "tmp2", rec.snapshot]);
130
+ writeFileSync(join(s.work, "evil.txt"), "x\n"); s.git(["add", "."]); s.git(["commit", "-qm", `fix\n\n(cherry picked from commit ${rec.picks[0].orig})`]);
131
+ const fake = s.git(["rev-parse", "HEAD"]).trim();
132
+ const forged = { ...rec, picks: [{ ...rec.picks[0], sha: fake }] };
133
+ assert.match(checkChain({ git: s.git, record: forged, sha: fake, staging: "staging", exact: true }).why, /differs from the cherry-pick/);
134
+ // a recorded pick whose source is not a staging commit
135
+ const off = { ...rec, picks: [{ ...rec.picks[0], orig: rec.picks[0].sha }] };
136
+ assert.match(checkChain({ git: s.git, record: off, sha: rec.picks[0].sha, staging: "staging", exact: true }).why, /is not a staging commit/);
137
+ });
138
+
139
+ it("an earlier head is a valid prefix unless the check is exact", async () => {
140
+ const { s } = await blockerWorld();
141
+ await pickFixes(s.ctx);
142
+ const rec = s.ctx.state.release;
143
+ assert.equal(checkChain({ git: s.git, record: rec, sha: rec.snapshot, staging: "staging" }).ok, true);
144
+ assert.match(checkChain({ git: s.git, record: rec, sha: rec.snapshot, staging: "staging", exact: true }).why, /0 of 1/);
145
+ });
146
+
147
+ it("a conflicting pick returns an error and leaves the branch and record alone", async () => {
148
+ const s = await setup();
149
+ await cut(s);
150
+ const fix = s.commit("a.txt", "fixed\n", "fix: touches a");
151
+ s.git(["checkout", "-q", "-B", "side", "main"]); writeFileSync(join(s.work, "a.txt"), "other\n"); s.git(["commit", "-qam", "diverge"]);
152
+ s.ctx.state.release.snapshot = s.git(["rev-parse", "HEAD"]).trim(); // a branch head whose a.txt differs from the fix's parent
153
+ s.w.prs = [{ number: 41, mergeCommit: { oid: fix }, mergedAt: "t", labels: [{ name: "release-blocker" }], closingIssuesReferences: [] }];
154
+ const out = await pickFixes(s.ctx);
155
+ assert.match(out.err, /#41 .* conflicts/);
156
+ assert.deepEqual(s.ctx.state.release.picks, []);
157
+ });
158
+
159
+ it("recut moves the branch to the staging tip and resets the picks", async () => {
160
+ const { s, c } = await blockerWorld();
161
+ await pickFixes(s.ctx);
162
+ const tip = s.commit("d.txt", "d\n", "feat: d");
163
+ assert.deepEqual(await recut(s.ctx), { recut: true, snapshot: tip });
164
+ assert.deepEqual(s.ctx.state.release.picks, []);
165
+ assert.equal(s.git(["ls-remote", "origin", `refs/heads/${c.branch}`]).split("\t")[0], tip);
166
+ assert.equal(parseRecord(s.w.body).snapshot, tip);
167
+ });
168
+
169
+ it("R10: verifyRelease reads the record from the PR that contains the sha, then checks the chain", async () => {
170
+ const { s } = await blockerWorld();
171
+ await pickFixes(s.ctx);
172
+ const rec = s.ctx.state.release, head = rec.picks[0].sha;
173
+ assert.deepEqual(await verifyRelease({ io: s.io, git: s.git, repo: "o/r", staging: "staging", sha: head }), { ok: true, picks: 1, pr: 9 });
174
+ s.w.body = "no record";
175
+ assert.match((await verifyRelease({ io: s.io, git: s.git, repo: "o/r", staging: "staging", sha: head })).why, /no pull request/);
176
+ });
177
+
178
+ it("R9: cleanup deletes the release branch and tolerates a missing one", async () => {
179
+ const { s, c } = await blockerWorld();
180
+ assert.deepEqual(cleanupSnapshot({ git: s.git, branch: c.branch }), { deleted: true });
181
+ assert.equal(s.git(["ls-remote", "origin", `refs/heads/${c.branch}`]).trim(), "");
182
+ assert.equal(cleanupSnapshot({ git: s.git, branch: c.branch }).deleted, false);
183
+ });
184
+
185
+ it("the record marker replaces itself instead of piling up", () => {
186
+ const once = withRecord("body", { v: 1, a: 1 }), twice = withRecord(once, { v: 1, a: 2 });
187
+ assert.equal(twice.match(/FORGE:RELEASE/g).length, 1);
188
+ assert.equal(parseRecord(twice).a, 2);
189
+ });
190
+ });
@@ -19,8 +19,11 @@ import { parseForgeYaml } from "../forge-utils.mjs";
19
19
  import { reviewStep, fixStep } from "./release-review.mjs";
20
20
  import { postMergeStep } from "./release-postmerge.mjs";
21
21
  import { rehearsalStep, parseRehearsalConfig } from "./release-rehearsal.mjs";
22
+ import { budgetReportLine, releaseRuns } from "./ci-budget.mjs";
23
+ import { cutSnapshot, writeRecord, checkChain, verifyRelease, DEFAULT_PATTERN } from "./release-snapshot.mjs";
24
+ import { hostPreflightStep, markReadyStep, parsePreflightConfig } from "./release-preflight.mjs";
22
25
 
23
- export const RELEASE_STEPS = ["preflight", "release-pr", "review", "fixes", "rehearsal", "promotion", "post-merge"];
26
+ export const RELEASE_STEPS = ["preflight", "host-preflight", "release-pr", "review", "fixes", "mark-ready", "rehearsal", "promotion", "post-merge"];
24
27
  const ID_RE = /^r\d{8}-\d{6}-\d+$/;
25
28
  const BLOCKED_EXIT = 3;
26
29
 
@@ -43,23 +46,34 @@ export function openRelease(root, id, mounts) {
43
46
  };
44
47
  }
45
48
 
46
- /** forge.yaml `release.*` of `raw`: `{autoMerge, artifactCheck, versionSync, publishWorkflow, rehearsal}` (#5253). */
49
+ /** forge.yaml `release.*` of `raw`: `{autoMerge, artifactCheck, versionSync, publishWorkflow, rehearsal, preflight, mode, branchPattern, fixMode}` (#5253, #5276, #5277). */
47
50
  export function readReleaseConfig(raw) {
48
51
  let r = {};
49
52
  try { r = parseForgeYaml(String(raw ?? ""))?.release ?? {}; } catch { r = {}; }
50
53
  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) };
54
+ return { autoMerge: !off(r.auto_merge), artifactCheck: r.artifact_check || null, versionSync: !off(r.version_sync), publishWorkflow: r.publish_workflow || null, ...optKeys(r), ...snapshotKeys(r) };
52
55
  }
53
56
 
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 } : {}; };
57
+ /** `{mode, branchPattern, fixMode}` only when configured (#5276): mode `snapshot` cuts release/<id>; anything else is `freeze`. */
58
+ const snapshotKeys = (r) => {
59
+ const pick = (v, ok, dflt) => (ok.includes(String(v).trim().toLowerCase()) ? String(v).trim().toLowerCase() : dflt);
60
+ return {
61
+ ...(r.mode ? { mode: pick(r.mode, ["snapshot", "freeze"], "freeze") } : {}),
62
+ ...(r.branch_pattern ? { branchPattern: String(r.branch_pattern) } : {}),
63
+ ...(r.fix_mode ? { fixMode: pick(r.fix_mode, ["cherry-pick", "recut"], "cherry-pick") } : {}),
64
+ };
65
+ };
66
+ export const isSnapshot = (config) => config?.mode === "snapshot";
67
+
68
+ /** `{rehearsal}` / `{preflight}` only when configured, so the config of a repo without them keeps its shape. */
69
+ const optKeys = (r) => { const rehearsal = parseRehearsalConfig(r), preflight = parsePreflightConfig(r); return { ...(rehearsal ? { rehearsal } : {}), ...(preflight ? { preflight } : {}) }; };
56
70
 
57
71
  const json = (s) => JSON.parse(String(s || "null"));
58
72
 
59
73
  /** The bundle list of PRs merged into `base` since the last release PR (the newest merged head->base PR). */
60
74
  export async function bundleList({ io, repo, head, base }) {
61
75
  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"])) ?? [];
76
+ const merged = json(await io.gh(["pr", "list", "--repo", repo, "--base", head, "--state", "merged", "--limit", "200", "--json", "number,title,mergedAt,closingIssuesReferences"])) ?? [];
63
77
  return merged.filter((p) => !last || p.mergedAt > last).sort((a, b) => a.number - b.number);
64
78
  }
65
79
 
@@ -67,6 +81,8 @@ const bundleBody = (list) => `## Release bundle\n\n${list.length ? list.map((p)
67
81
 
68
82
  async function preflightStep(ctx) {
69
83
  const { io, repo, state, staging } = ctx;
84
+ // Snapshot mode: lanes keep merging to staging; the release is cut from a fixed SHA, so nothing is refused or held (#5276).
85
+ if (isSnapshot(ctx.config)) return { snapshot: true, held: 0 };
70
86
  const lanes = await io.runningLanes(repo);
71
87
  if (lanes.length) return { refused: `lanes of ${repo} are running (${lanes.map((l) => `${l.batch}#${l.issue}`).join(", ")}); wait or cancel them` };
72
88
  const open = json(await io.gh(["pr", "list", "--repo", repo, "--base", staging, "--state", "open", "--json", "number"])) ?? [];
@@ -92,12 +108,37 @@ export async function restoreBatches(ctx) {
92
108
  ctx.save();
93
109
  }
94
110
 
111
+ /** Snapshot mode: cut release/<id> (once; a resume reuses the recorded branch) and open release/<id> -> default. */
112
+ async function snapshotPrStep(ctx) {
113
+ const { io, repo, staging, def, state } = ctx;
114
+ if (!io.git) throw new Error("snapshot releases need io.git");
115
+ if (!state.release) {
116
+ const bundle = await bundleList({ io, repo, head: staging, base: def });
117
+ const cut = await cutSnapshot({ io, git: io.git, repo, staging, def, pattern: ctx.config.branchPattern ?? DEFAULT_PATTERN, id: state.id, bundle });
118
+ if (cut.refused) return { refused: cut.refused };
119
+ state.release = cut.record; state.releaseBundle = bundle;
120
+ ctx.save();
121
+ }
122
+ const { branch } = state.release;
123
+ const found = json(await io.gh(["pr", "list", "--repo", repo, "--base", def, "--head", branch, "--state", "open", "--json", "number,headRefOid,url"]))?.[0];
124
+ if (found) return { pr: found.number, head: found.headRefOid, url: found.url, reused: true, branch };
125
+ const list = state.releaseBundle ?? [];
126
+ const url = String(await io.gh(["pr", "create", "--repo", repo, "--base", def, "--head", branch, "--title", `Release: ${branch} -> ${def}`, "--body", bundleBody(list)])).trim();
127
+ const n = Number(/\/pull\/(\d+)/.exec(url)?.[1]);
128
+ if (!Number.isSafeInteger(n)) throw new Error(`gh pr create returned no PR url: ${url}`);
129
+ state.steps["release-pr"] = { done: false, result: { pr: n } }; // writeRecord reads the PR number from here
130
+ await writeRecord(ctx);
131
+ const v = json(await io.gh(["pr", "view", String(n), "--repo", repo, "--json", "headRefOid"]));
132
+ return { pr: n, head: v?.headRefOid, url, reused: false, bundle: list.length, branch };
133
+ }
134
+
95
135
  async function releasePrStep(ctx) {
136
+ if (isSnapshot(ctx.config)) return snapshotPrStep(ctx);
96
137
  const { io, repo, staging, def } = ctx;
97
138
  const found = json(await io.gh(["pr", "list", "--repo", repo, "--base", def, "--head", staging, "--state", "open", "--json", "number,headRefOid,url"]))?.[0];
98
139
  if (found) return { pr: found.number, head: found.headRefOid, url: found.url, reused: true };
99
140
  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();
141
+ const url = String(await io.gh(["pr", "create", "--repo", repo, "--base", def, "--head", staging, "--title", `Release: ${staging} -> ${def}`, "--body", bundleBody(list), ...(ctx.config.preflight ? ["--draft"] : [])])).trim();
101
142
  const n = Number(/\/pull\/(\d+)/.exec(url)?.[1]);
102
143
  if (!Number.isSafeInteger(n)) throw new Error(`gh pr create returned no PR url: ${url}`);
103
144
  const v = json(await io.gh(["pr", "view", String(n), "--repo", repo, "--json", "headRefOid"]));
@@ -111,7 +152,13 @@ export async function gateState({ io, repo, pr, head }) {
111
152
  let marker = null;
112
153
  for (const b of bodies) { if (b.includes("FORGE:GATE_PASS")) marker = "pass"; else if (b.includes("FORGE:GATE_FAILURE")) marker = "failure"; }
113
154
  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");
155
+ let gate = checks.find((c) => c.name === "forge/deploy-gate");
156
+ // gate-marker-check.yml posts forge/deploy-gate as a commit STATUS (POST /statuses), not a check run: read the
157
+ // combined status too, or promotion never sees the gate it waits for.
158
+ if (!gate) {
159
+ const statuses = json(await io.gh(["api", `repos/${repo}/commits/${head}/status`, "--jq", "[.statuses[] | {name: .context, conclusion: .state}]"])) ?? [];
160
+ gate = statuses.find((c) => c.name === "forge/deploy-gate");
161
+ }
115
162
  return { marker, deployGate: gate?.conclusion ?? null };
116
163
  }
117
164
 
@@ -123,6 +170,10 @@ async function promotionStep(ctx) {
123
170
  // Already merged (by hand, or by a crashed --merge run): hand the merge sha to post-merge; never gate or merge again.
124
171
  if (view?.state === "MERGED" && view?.mergeCommit?.oid) return { merged: true, alreadyMerged: true, mergeCommit: view.mergeCommit.oid, head };
125
172
  if (view?.state === "CLOSED") return { stopped: true, why: `release PR #${pr} was closed without merging`, head };
173
+ if (state.release) {
174
+ const chain = checkChain({ git: io.git, record: state.release, sha: head, staging: ctx.staging, exact: true });
175
+ if (!chain.ok) return { stopped: true, why: `release head ${head} is not snapshot + recorded cherry-picks: ${chain.why}`, head };
176
+ }
126
177
  const gate = await gateState({ io, repo, pr, head });
127
178
  if (gate.marker !== "pass") return { stopped: true, why: `no FORGE:GATE_PASS on #${pr} (last marker: ${gate.marker ?? "none"})`, head };
128
179
  const cmd = `gh pr merge ${pr} --repo ${repo} --merge --match-head-commit ${head}`;
@@ -132,11 +183,15 @@ async function promotionStep(ctx) {
132
183
  return { merged: true, head, gate };
133
184
  }
134
185
 
186
+ const OPTIONAL_STEPS = ["host-preflight", "mark-ready"];
187
+
135
188
  const STEP_FNS = {
136
189
  preflight: preflightStep,
190
+ "host-preflight": hostPreflightStep,
137
191
  "release-pr": releasePrStep,
138
192
  review: (ctx) => reviewStep(ctx),
139
193
  fixes: (ctx) => fixStep(ctx),
194
+ "mark-ready": markReadyStep,
140
195
  rehearsal: (ctx) => rehearsalStep(ctx),
141
196
  promotion: promotionStep,
142
197
  "post-merge": (ctx) => postMergeStep(ctx),
@@ -154,7 +209,7 @@ export async function runRelease({ io, repo, opts = {}, config = {}, branches =
154
209
  const rel = openRelease(root, id, mounts);
155
210
  const state = rel.load() ?? { v: 1, id, repo, startedAt: new Date(io.now()).toISOString(), steps: {}, held: [] };
156
211
  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) };
212
+ const ctx = { io, repo, opts: state.opts, config, state, staging: branches.staging || DEFAULT_STAGING_BRANCH, def: branches.default || "main", git: io.git, save: () => rel.save(state) };
158
213
  ctx.save();
159
214
  let out;
160
215
  try {
@@ -163,6 +218,7 @@ export async function runRelease({ io, repo, opts = {}, config = {}, branches =
163
218
  const result = await steps[step](ctx);
164
219
  if (result?.refused) { out = { id, status: "refused", step, reason: result.refused }; break; }
165
220
  if (result?.blocked) { out = { id, status: "blocked", step, reason: result.reason }; break; }
221
+ if (result?.skipped && OPTIONAL_STEPS.includes(step)) continue; // unconfigured: leaves no trace in the state
166
222
  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
223
  state.steps[step] = { done: true, at: new Date(io.now()).toISOString(), result };
168
224
  ctx.save();
@@ -177,20 +233,21 @@ export async function runRelease({ io, repo, opts = {}, config = {}, branches =
177
233
  }
178
234
 
179
235
  /** 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) } = {}) {
236
+ export function realReleaseIo({ env = process.env, exec = execFileSync, print = (l) => console.log(l), cwd = process.cwd() } = {}) {
181
237
  const gh = ghRunner(exec, print);
182
238
  const root = batchRoot(env);
183
239
  const mine = (b, repo) => { const r = b.readPlan()?.repo; return !r || r === repo; };
184
240
  const unfinished = (repo) => listBatches(root).map((id) => openBatch(root, id)).filter((b) => !b.readReport() && mine(b, repo));
185
241
  return {
186
242
  gh: (args) => gh(args), print, now: () => Date.now(),
243
+ git: (args, { env: extra, input } = {}) => exec("git", args, { cwd, encoding: "utf8", input, env: { ...env, ...extra }, maxBuffer: 64 << 20, stdio: ["pipe", "pipe", "pipe"] }),
187
244
  sleep: (ms) => new Promise((r) => setTimeout(r, ms)),
188
245
  run: async (cmd) => { try { exec("sh", ["-c", cmd], { stdio: "ignore", timeout: 120_000 }); return { ok: true }; } catch { return { ok: false }; } },
189
246
  rehearse: async (cmd, { timeout } = {}) => {
190
247
  try { return { ok: true, code: 0, output: String(exec("sh", ["-c", cmd], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], timeout, maxBuffer: 16 << 20 })) }; }
191
248
  catch (e) { return { ok: false, code: e.status ?? null, timedOut: e.code === "ETIMEDOUT", output: `${e.stdout ?? ""}${e.stderr ?? ""}` || String(e.message) }; }
192
249
  },
193
- runningLanes: (repo) => unfinished(repo).flatMap((b) => Object.entries(b.state.load()?.lanes ?? {})
250
+ runningLanes: (repo) => unfinished(repo).flatMap((b) => Object.entries(b.store.load()?.lanes ?? {})
194
251
  .filter(([n, rec]) => rec?.pid && isLaneAlive(rec.pid, b.resultFile(n)) && !existsSync(b.resultFile(n)))
195
252
  .map(([n]) => ({ batch: b.id, issue: n }))),
196
253
  batches: (repo) => unfinished(repo).map((b) => ({ id: b.id, k: b.readParallel() ?? 1 })),
@@ -202,12 +259,13 @@ export function realReleaseIo({ env = process.env, exec = execFileSync, print =
202
259
  }
203
260
 
204
261
  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>]";
262
+ export const RELEASE_USAGE = "usage: forgedock release [--repo owner/repo] [--merge] [--watch] [--resume <id>] | forgedock release verify <sha> [--repo owner/repo]";
206
263
 
207
264
  /** `forgedock release ...`; @returns the process exit code (0 done or stopped at GATE_PASS, 1 refused, 3 blocked on a manual step). */
208
265
  export async function releaseFromCli(argv, deps = {}) {
209
266
  const cwd = deps.cwd ?? process.cwd(), env = deps.env ?? process.env;
210
- const io = deps.io ?? realReleaseIo({ env });
267
+ const io = deps.io ?? realReleaseIo({ env, cwd });
268
+ if (argv[0] === "verify") return verifyFromCli(argv.slice(1), { io, cwd });
211
269
  const unknown = argv.filter((a, i) => a.startsWith("--") && !["--repo", "--merge", "--watch", "--resume"].includes(a) && !(argv[i - 1] === "--resume" || argv[i - 1] === "--repo"));
212
270
  if (unknown.length) throw new Error(`unknown option ${unknown[0]}; ${RELEASE_USAGE}`);
213
271
  const root = releaseRoot(env);
@@ -221,8 +279,24 @@ export async function releaseFromCli(argv, deps = {}) {
221
279
  }
222
280
  repo ??= JSON.parse(String(await io.gh(["repo", "view", "--json", "nameWithOwner"]))).nameWithOwner;
223
281
  let raw = ""; try { raw = readFileSync(join(cwd, "forge.yaml"), "utf8"); } catch { /* no forge.yaml: defaults */ }
282
+ const budget = async (since) => { // #5278: the Actions-minutes line (and any auto switch to local-first); never fails the job
283
+ try { io.print(await budgetReportLine({ cwd, repo, gh: (a) => io.gh(a), now: io.now(), release: since ? await releaseRuns({ gh: (a) => io.gh(a), repo, sinceMs: since }) : null })); } catch { /* best effort */ }
284
+ };
285
+ await budget(null);
224
286
  const r = await runRelease({ io, repo, opts: { merge: argv.includes("--merge") }, config: readReleaseConfig(raw), branches: readBranches(cwd), root, id, mounts: deps.mounts });
225
287
  const line = r.status === "done" ? `release ${id}: done` : `release ${id}: ${r.status} at ${r.step}: ${r.reason} (resume: forgedock release --resume ${id})`;
226
288
  io.print(line);
289
+ try { await budget(Date.parse(openRelease(root, id).load()?.startedAt) || null); } catch { /* best effort */ }
227
290
  return r.status === "refused" ? 1 : r.status === "blocked" ? BLOCKED_EXIT : 0;
228
291
  }
292
+
293
+ /** `forgedock release verify <sha> [--repo R]`: exit 0 when the release head is the snapshot plus its recorded cherry-picks of staging commits, else 1. */
294
+ async function verifyFromCli(argv, { io, cwd }) {
295
+ const sha = argv.find((a, i) => !a.startsWith("--") && argv[i - 1] !== "--repo");
296
+ if (!sha || !/^[0-9a-f]{7,40}$/i.test(sha)) throw new Error(`release verify needs a commit sha; ${RELEASE_USAGE}`);
297
+ const repo = flag(argv, "--repo") ?? JSON.parse(String(await io.gh(["repo", "view", "--json", "nameWithOwner"]))).nameWithOwner;
298
+ const full = io.git(["rev-parse", sha]).trim();
299
+ const r = await verifyRelease({ io, git: io.git, repo, staging: readBranches(cwd).staging || DEFAULT_STAGING_BRANCH, sha: full });
300
+ io.print(r.ok ? `release verify ${full}: ok (snapshot + ${r.picks} cherry-pick(s), PR #${r.pr})` : `release verify ${full}: FAILED: ${r.why}`);
301
+ return r.ok ? 0 : 1;
302
+ }
@@ -34,6 +34,7 @@ function fakeIo(world = {}) {
34
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
35
  if (j.includes("--json headRefOid")) return JSON.stringify({ headRefOid: HEAD });
36
36
  if (j.includes("--json comments")) return JSON.stringify({ comments: w.comments });
37
+ if (a[0] === "api" && /\/commits\/[^/]+\/status$/.test(a[1])) return JSON.stringify(w.statusGate ? [{ name: "forge/deploy-gate", conclusion: w.statusGate }] : []);
37
38
  if (a[0] === "api") return JSON.stringify(w.gate ? [{ name: "forge/deploy-gate", conclusion: w.gate }] : []);
38
39
  if (a[0] === "pr" && a[1] === "merge") return "";
39
40
  throw new Error(`unexpected gh ${j}`);
@@ -75,6 +76,14 @@ describe("release job (#5211)", () => {
75
76
  }
76
77
  });
77
78
 
79
+ it("forge/deploy-gate posted as a commit status (gate-marker-check.yml) counts: no check run, status success -> merges", async () => {
80
+ const ok = await promote({ gate: null, statusGate: "success" }, { opts: { merge: true } });
81
+ assert.equal(ok.out.status, "done");
82
+ assert.ok(ok.io.calls.some((a) => a[1] === "merge" && a.includes("--match-head-commit")));
83
+ const pend = await promote({ gate: null, statusGate: "pending" }, { opts: { merge: true } });
84
+ assert.equal(pend.out.status, "stopped");
85
+ });
86
+
78
87
  it("#5266: a release PR merged by hand moves to post-merge with the merge sha, without the opt-in stop", async () => {
79
88
  const io = fakeIo({ prState: "MERGED" }), root = tmp(), id = newReleaseId();
80
89
  const mod = await import("./release.mjs");
@@ -290,3 +299,98 @@ describe("release post-merge step (#5213)", () => {
290
299
  assert.equal((await go([[{ databaseId: 2, status: "completed", conclusion: "success" }]])).status, "done");
291
300
  });
292
301
  });
302
+
303
+ describe("snapshot releases (#5276)", () => {
304
+ const S = "5".repeat(40), F = "f".repeat(40);
305
+ /** git fake for a clean cut and an unmodified chain; `revList` is what `rev-list snapshot..head` answers. */
306
+ const gitFake = (revList = "") => (a) => {
307
+ if (a[0] === "rev-parse" && a[1].startsWith("refs/remotes/")) return `${S}\n`;
308
+ if (a[0] === "rev-list") return revList;
309
+ return "";
310
+ };
311
+ const snapWorld = (extra = {}) => ({
312
+ releasePr: [], git: gitFake(), lanes: [{ batch: "b1", issue: 7 }], openStaging: [{ number: 5 }], batches: [{ id: "b1", k: 20 }],
313
+ pm: (a) => (a[1] === "view" && a.includes("body") ? JSON.stringify({ body: "" }) : a[1] === "edit" ? "" : undefined), ...extra,
314
+ });
315
+ const go = async (world, config = { mode: "snapshot" }, opts = { merge: true }) => {
316
+ const io = fakeIo(world);
317
+ if (world.git) io.git = world.git;
318
+ const mod = await import("./release.mjs");
319
+ const out = await mod.runRelease({ io, repo: REPO, root: tmp(), mounts: DISK, id: newReleaseId(), opts, config, branches: { staging: "staging", default: "main" }, steps: mod.withStubs({ review: ok, fixes: ok, "post-merge": ok }) });
320
+ return { io, out };
321
+ };
322
+
323
+ it("readReleaseConfig reads mode / branch_pattern / fix_mode only when set; unknown values fall back", () => {
324
+ assert.deepEqual(readReleaseConfig("release:\n mode: snapshot\n branch_pattern: \"rel/{date}-{n}\"\n fix_mode: recut\n"), { autoMerge: false, artifactCheck: null, versionSync: false, publishWorkflow: null, mode: "snapshot", branchPattern: "rel/{date}-{n}", fixMode: "recut" });
325
+ assert.deepEqual(readReleaseConfig("release:\n mode: weird\n fix_mode: nope\n").mode, "freeze");
326
+ assert.equal(readReleaseConfig("release:\n fix_mode: nope\n").fixMode, "cherry-pick");
327
+ assert.equal("mode" in readReleaseConfig(""), false);
328
+ });
329
+
330
+ it("R1/R6: with lanes running and PRs open on staging, the cut refuses nothing, leaves every K alone and opens release/<id> -> main", async () => {
331
+ const { io, out } = await go(snapWorld());
332
+ assert.equal(out.status, "done");
333
+ assert.deepEqual(io.par, [], "no batch K was set (no hold, no restore)");
334
+ const create = io.calls.find((a) => a[1] === "create");
335
+ assert.equal(create[create.indexOf("--head") + 1], "release/20231114-1");
336
+ assert.equal(create[create.indexOf("--base") + 1], "main");
337
+ assert.ok(!io.calls.some((a) => (a[1] === "create" || a.includes("open")) && a[a.indexOf("--head") + 1] === "staging"), "staging is never the PR head");
338
+ });
339
+
340
+ it("R8: promotion still merges with --match-head-commit", async () => {
341
+ const { io } = await go(snapWorld());
342
+ assert.ok(io.calls.some((a) => a[1] === "merge" && a.includes("--merge") && a.includes("--match-head-commit") && a.includes(HEAD)));
343
+ });
344
+
345
+ it("R3: a commit on the release branch that is not a recorded cherry-pick stops promotion; nothing is merged", async () => {
346
+ const { io, out } = await go(snapWorld({ git: gitFake(`${F} ${S}\n`) }));
347
+ assert.equal(out.status, "stopped");
348
+ assert.match(out.reason, /not snapshot \+ recorded cherry-picks: 1 commit\(s\)/);
349
+ assert.ok(!io.calls.some((a) => a[1] === "merge"));
350
+ });
351
+
352
+ it("R11: a release branch already in flight refuses the cut", async () => {
353
+ const world = snapWorld({ git: (a) => (a[0] === "ls-remote" ? `${S}\trefs/heads/release/20231114-1\n` : "") });
354
+ const { out } = await go(world);
355
+ assert.equal(out.status, "refused");
356
+ assert.match(out.reason, /already in flight/);
357
+ });
358
+
359
+ it("R4: freeze mode (and no mode) keeps the refusal on running lanes, the K=1 hold and staging as PR head", async () => {
360
+ for (const config of [{ mode: "freeze" }, {}]) {
361
+ const { io, out } = await go({ lanes: [{ batch: "b1", issue: 7 }] }, config);
362
+ assert.equal(out.status, "refused");
363
+ assert.match(out.reason, /lanes of o\/r are running/);
364
+ }
365
+ const { io, out } = await go({ batches: [{ id: "b1", k: 20 }], releasePr: [] }, { mode: "freeze" });
366
+ assert.equal(out.status, "done");
367
+ assert.deepEqual(io.par, [["b1", 1], ["b1", 20]]);
368
+ const create = io.calls.find((a) => a[1] === "create");
369
+ assert.equal(create[create.indexOf("--head") + 1], "staging");
370
+ });
371
+
372
+ it("R10: `release verify <sha>` exits 0 for a head that is the snapshot, 1 for a PR without a record", async () => {
373
+ const rec = { v: 1, snapshot: S, picks: [] };
374
+ const mk = (body) => { const io = fakeIo({ pm: (a) => (a[0] === "api" ? JSON.stringify([{ number: 9, body }]) : undefined) }); io.git = gitFake(); io.git = ((g) => (a, o) => (a[0] === "rev-parse" && !a[1].startsWith("refs/") ? `${S}\n` : g(a, o)))(io.git); return io; };
375
+ const good = mk(`x\n<!-- FORGE:RELEASE ${JSON.stringify(rec)} -->`);
376
+ assert.equal(await releaseFromCli(["verify", S.slice(0, 12), "--repo", REPO], { io: good, cwd: tmp() }), 0);
377
+ assert.ok(good.printed.some((l) => /: ok \(snapshot \+ 0 cherry-pick/.test(l)));
378
+ const bad = mk("no record");
379
+ assert.equal(await releaseFromCli(["verify", S, "--repo", REPO], { io: bad, cwd: tmp() }), 1);
380
+ await assert.rejects(releaseFromCli(["verify"], { io: bad, cwd: tmp() }), /needs a commit sha/);
381
+ });
382
+
383
+ it("R9: post-merge deletes release/<id> after a snapshot release, and touches no branch otherwise", async () => {
384
+ const pm = (a) => (a[1] === "view" ? JSON.stringify({ state: "MERGED", mergeCommit: { oid: "b".repeat(40) } }) : a[0] === "run" ? JSON.stringify([{ databaseId: 5, status: "completed", conclusion: "success" }]) : undefined);
385
+ const step = async (release) => {
386
+ const io = fakeIo({ pm }), pushes = [];
387
+ io.git = (a) => { pushes.push(a); return ""; };
388
+ const out = await postMergeStep({ io, repo: REPO, def: "main", staging: "staging", config: {}, state: { release, steps: { "release-pr": { result: { pr: 7 } } } } });
389
+ return { out, pushes };
390
+ };
391
+ const snap = await step({ branch: "release/20231114-1" });
392
+ assert.equal(snap.out.published, true);
393
+ assert.deepEqual(snap.pushes, [["push", "--quiet", "origin", "--delete", "release/20231114-1"]]);
394
+ assert.deepEqual((await step(undefined)).pushes, []);
395
+ });
396
+ });
@@ -125,7 +125,7 @@ const CONTRACT_BLOCK_RE = /<summary>contract\.json \(sha256 ([0-9a-f]{12})(?:, i
125
125
  export function renderContract(c, hash, { compact = false, scope = null } = {}) {
126
126
  const json = `<details><summary>contract.json (sha256 ${hash}${scope ? `, issue ${scope}` : ""})</summary>\n\n\`\`\`json\n${contractJson(c)}\n\`\`\`\n</details>`;
127
127
  if (compact) return `## Builder Contract (frozen \`${hash}\`)\n\n${c.requirements.length} requirement(s), ${(c.deliverables ?? []).length} deliverable(s); the tables are omitted because the contract is large.\n\n${json}`;
128
- const disp = (r) => `${r.disposition}${r.verify === "out_of_band" ? `, verified out of band${r.evidence ? ` (${escl(r.evidence)})` : ""}` : ""}${r.tracked ? ` → ${r.tracked}` : ["defer", "post-deploy"].includes(r.disposition) ? " (filed after review accepts it)" : ""}${r.why ? ` (${escl(r.why)})` : ""}`;
128
+ const disp = (r) => `${r.disposition === "post-deploy" && /\[type:(?:e2e|manual)\]/i.test(String(r.quote ?? "")) ? "post-deploy, transferred to the epic (not met)" : r.disposition}${r.verify === "out_of_band" ? `, verified out of band${r.evidence ? ` (${escl(r.evidence)})` : ""}` : ""}${r.tracked ? ` → ${r.tracked}` : ["defer", "post-deploy"].includes(r.disposition) ? " (filed after review accepts it)" : ""}${r.why ? ` (${escl(r.why)})` : ""}`;
129
129
  const req = c.requirements.map((r) => `| ${esc(r.id)} | ${esc(r.quote)} | ${esc(disp(r))} |`).join("\n");
130
130
  const del = (c.deliverables ?? []).map((d) => `| ${esc(d.id)} | \`${esc(d.path)}\` | ${esc(d.change)} | ${esc((d.requirements ?? []).join(", "))} |`).join("\n");
131
131
  const dec = Array.isArray(c.decisions) && c.decisions.length // forge#4165: decision provenance