forgedock 1.59.2 → 1.60.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 (97) hide show
  1. package/bin/engine/outcome-codes.mjs +3 -3
  2. package/bin/engine-cli.mjs +50 -10
  3. package/bin/labels.json +5 -0
  4. package/bin/lean/batch.mjs +21 -2
  5. package/bin/lean/batch.test.mjs +116 -1
  6. package/bin/lean/conformance.mjs +19 -6
  7. package/bin/lean/conformance.test.mjs +37 -3
  8. package/bin/lean/depcache.mjs +34 -15
  9. package/bin/lean/depcache.test.mjs +100 -1
  10. package/bin/lean/design-gate.mjs +15 -10
  11. package/bin/lean/design-gate.test.mjs +21 -0
  12. package/bin/lean/effects.mjs +18 -2
  13. package/bin/lean/execution.mjs +23 -5
  14. package/bin/lean/execution.test.mjs +81 -1
  15. package/bin/lean/gatewatch.test.mjs +5 -5
  16. package/bin/lean/issuewatch-triage.mjs +68 -0
  17. package/bin/lean/issuewatch-triage.test.mjs +98 -0
  18. package/bin/lean/issuewatch.mjs +34 -6
  19. package/bin/lean/issuewatch.test.mjs +11 -0
  20. package/bin/lean/lanelock.mjs +5 -4
  21. package/bin/lean/lean.mjs +144 -21
  22. package/bin/lean/lean.test.mjs +180 -6
  23. package/bin/lean/orchestrate-cancel.test.mjs +33 -0
  24. package/bin/lean/orchestrate-hostfallback.test.mjs +41 -0
  25. package/bin/lean/orchestrate-recovering.test.mjs +42 -0
  26. package/bin/lean/orchestrate.mjs +23 -10
  27. package/bin/lean/pagegate.mjs +50 -12
  28. package/bin/lean/pagegate.test.mjs +38 -1
  29. package/bin/lean/phaseledger.mjs +65 -2
  30. package/bin/lean/phaseledger.test.mjs +70 -2
  31. package/bin/lean/preflight.mjs +67 -3
  32. package/bin/lean/preflight.test.mjs +37 -1
  33. package/bin/lean/prompts.mjs +2 -1
  34. package/bin/lean/recovery.test.mjs +11 -6
  35. package/bin/lean/release-classify.mjs +143 -0
  36. package/bin/lean/release-classify.test.mjs +130 -0
  37. package/bin/lean/release-conductor.mjs +163 -0
  38. package/bin/lean/release-conductor.test.mjs +194 -0
  39. package/bin/lean/release-config.mjs +60 -8
  40. package/bin/lean/release-config.test.mjs +43 -1
  41. package/bin/lean/release-control.mjs +22 -5
  42. package/bin/lean/release-control.test.mjs +22 -0
  43. package/bin/lean/release-credentials.mjs +40 -0
  44. package/bin/lean/release-credentials.test.mjs +42 -0
  45. package/bin/lean/release-deploy.mjs +3 -3
  46. package/bin/lean/release-deploy.test.mjs +8 -0
  47. package/bin/lean/release-docs.test.mjs +93 -0
  48. package/bin/lean/release-fence.mjs +2 -0
  49. package/bin/lean/release-gate.mjs +88 -0
  50. package/bin/lean/release-gate.test.mjs +116 -0
  51. package/bin/lean/release-gates.mjs +5 -1
  52. package/bin/lean/release-ledger.mjs +47 -1
  53. package/bin/lean/release-ledger.test.mjs +33 -1
  54. package/bin/lean/release-mergeback.mjs +148 -0
  55. package/bin/lean/release-mergeback.test.mjs +129 -0
  56. package/bin/lean/release-p0.mjs +193 -0
  57. package/bin/lean/release-p0.test.mjs +127 -0
  58. package/bin/lean/release-plan.mjs +267 -0
  59. package/bin/lean/release-plan.test.mjs +202 -0
  60. package/bin/lean/release-preflight.mjs +16 -0
  61. package/bin/lean/release-regate.mjs +141 -0
  62. package/bin/lean/release-regate.test.mjs +149 -0
  63. package/bin/lean/release-review.mjs +5 -3
  64. package/bin/lean/release-rollback.mjs +277 -0
  65. package/bin/lean/release-rollback.test.mjs +245 -0
  66. package/bin/lean/release-snapshot.mjs +48 -9
  67. package/bin/lean/release-snapshot.test.mjs +43 -1
  68. package/bin/lean/release-start.mjs +164 -0
  69. package/bin/lean/release-start.test.mjs +171 -0
  70. package/bin/lean/release-status.mjs +6 -2
  71. package/bin/lean/release-train.mjs +159 -0
  72. package/bin/lean/release-train.test.mjs +139 -0
  73. package/bin/lean/release.mjs +127 -5
  74. package/bin/lean/release.test.mjs +80 -0
  75. package/bin/lean/sandbox-remote.mjs +2 -0
  76. package/bin/lean/schedd-load.test.mjs +82 -0
  77. package/bin/lean/schedd.mjs +67 -31
  78. package/bin/lean/schedd.test.mjs +80 -1
  79. package/bin/lean/validate-catalog.mjs +110 -0
  80. package/bin/lean/validate-catalog.test.mjs +55 -0
  81. package/bin/pool/agent.mjs +12 -1
  82. package/bin/pool/lane-tools.mjs +146 -0
  83. package/bin/pool/lane-tools.test.mjs +26 -0
  84. package/bin/pool/router.mjs +3 -1
  85. package/bin/pool/warm.mjs +14 -3
  86. package/docs/CONFIG.md +225 -1
  87. package/docs/ISSUE-WATCH.md +1 -0
  88. package/docs/design/visual-gate.md +10 -0
  89. package/docs/eval/adversarial-bench.md +1 -0
  90. package/package.json +1 -1
  91. package/pool/README.md +2 -0
  92. package/scripts/acceptance-red-green.sh +5 -2
  93. package/scripts/acceptance-red-green.test.sh +11 -0
  94. package/scripts/bench-adversarial.mjs +4 -0
  95. package/scripts/bench-lightlane.mjs +2 -1
  96. package/templates/github-actions/forge-conductor.scopes.json +7 -0
  97. package/templates/github-actions/forge-conductor.yml +57 -0
@@ -0,0 +1,193 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * The managed P0 lane (#5565, epic #5549 Phase 4; I10, I11, I14, I26): a production fix branches from what is live, deploys first
5
+ * through the `hotfix` pipeline (#5560 step runner, #5562 verification, #5563 rollback on failure), then lands on the default
6
+ * branch so no code is live without being on it. `laneStartGuard` is the live-vs-default rule fast lanes (#5570) call.
7
+ * Every effect goes through `io` (`git`, `gh`, `rehearse`, `api`), so the module is testable with fake io. The engine never sets a
8
+ * human break-glass input on a dispatch: `buildDispatchArgs` rejects them and the pipeline inputs are checked up front.
9
+ */
10
+ import { readTarget, deployStep } from "./release-deploy.mjs";
11
+ import { runRollback, takeFence } from "./release-rollback.mjs";
12
+ import { claimDeploy, releaseDeploy, recordP0Divergence } from "./release-ledger.mjs";
13
+ import { buildDispatchArgs } from "./release-control.mjs";
14
+ import { applyOnExceed } from "./release-minutes.mjs";
15
+ import { fenced } from "./release-fence.mjs";
16
+
17
+ export const FAST_LANES = ["train"];
18
+ export const P0_BOUNDS = { pollMs: 20_000, queuePolls: 30 };
19
+ const short = (s) => String(s ?? "").slice(0, 8);
20
+ const json = (s) => JSON.parse(String(s || "null"));
21
+ const ok = (fn) => { try { fn(); return true; } catch { return false; } };
22
+
23
+ /** default == live: live is an ancestor of `origin/<def>` and the trees are identical. @returns {{equal: boolean, live, def, why?}} */
24
+ export function divergence({ io, def, live }) {
25
+ const ref = `origin/${def}`;
26
+ ok(() => io.git(["fetch", "--quiet", "origin", def]));
27
+ const anc = ok(() => io.git(["merge-base", "--is-ancestor", live, ref]));
28
+ let same = false;
29
+ try { same = io.git(["rev-parse", `${live}^{tree}`]).trim() === io.git(["rev-parse", `${ref}^{tree}`]).trim(); } catch { same = false; }
30
+ if (anc && same) return { equal: true, live, def };
31
+ return { equal: false, live, def, why: `${def} (${short(ref)}) != live ${short(live)}: ${anc ? "the trees differ" : "live is not an ancestor of it"}` };
32
+ }
33
+
34
+ const deployOf = (ctx) => ctx.deploy ?? ctx.config?.deploy ?? ctx.policy?.deploy;
35
+
36
+ /**
37
+ * Lane start guard (I10). A fast lane (train) refuses while the default branch != live; p0 is exempt, bases on live and records the
38
+ * divergence in the ledger; other lanes are not guarded. `ctx`: {io, repo, def, deploy|config.deploy|policy.deploy, release?, recordDivergence?}.
39
+ * @returns {Promise<{ok: true, lane, live?, base?, divergence?}|{refused: string}>}
40
+ */
41
+ export async function laneStartGuard(ctx, lane) {
42
+ if (lane !== "p0" && !FAST_LANES.includes(lane)) return { ok: true, lane };
43
+ const cmd = deployOf(ctx)?.live_release_command;
44
+ const live = await readTarget(ctx.io, cmd);
45
+ if (!live) return { refused: `${lane}: cannot read the live sha (deploy.live_release_command is unset or returned nothing); nothing was started` };
46
+ const d = divergence({ io: ctx.io, def: ctx.def, live: live.sha });
47
+ if (lane !== "p0") return d.equal ? { ok: true, lane, live: live.sha } : { refused: `${lane} lane refused: ${d.why}; land or roll back the live difference first (I10)` };
48
+ if (!d.equal) {
49
+ const rec = { release: ctx.release ?? null, live: live.sha, def: ctx.def, why: d.why };
50
+ const lctx = ctx.io.api ? { io: ctx.io, repo: ctx.repo, credential: "driver" } : null;
51
+ const record = ctx.recordDivergence ?? (lctx ? (r) => recordP0Divergence(lctx, r, ctx.io.now?.()) : null);
52
+ if (record) await record(rec);
53
+ }
54
+ return { ok: true, lane, live: live.sha, base: live.sha, ...(d.equal ? {} : { divergence: d.why }) };
55
+ }
56
+
57
+ /** Typed `go` unless `--yes`. @returns {Promise<boolean>} */
58
+ export async function confirmGo({ yes, ask, plan }) {
59
+ if (yes) return true;
60
+ if (!ask) return false;
61
+ return String(await ask(`${plan}\nType go to deploy: `)).trim() === "go";
62
+ }
63
+
64
+ /** The fix branch: `p0/issue-<n>` cut from the live sha (never the default branch), or the given branch, which must descend from live. */
65
+ async function ensureBranch({ io, issue, branch, live }) {
66
+ const name = branch ?? `p0/issue-${issue}`;
67
+ if (!/^[A-Za-z0-9._/-]+$/.test(name) || name.includes("..")) return { refused: `invalid branch name ${JSON.stringify(name)}` };
68
+ const exists = !!String(io.git(["ls-remote", "--heads", "origin", name]) ?? "").trim();
69
+ if (!exists) {
70
+ if (branch) return { refused: `branch ${name} does not exist on origin` };
71
+ io.git(["push", "--quiet", "origin", `${live}:refs/heads/${name}`]);
72
+ }
73
+ io.git(["fetch", "--quiet", "origin", `+refs/heads/${name}:refs/remotes/origin/${name}`]);
74
+ const tip = io.git(["rev-parse", `refs/remotes/origin/${name}`]).trim();
75
+ if (!ok(() => io.git(["merge-base", "--is-ancestor", live, tip]))) return { refused: `branch ${name} is not based on live ${short(live)}; a p0 bases on what is live, not the default branch` };
76
+ const fullLive = ok(() => io.git(["rev-parse", live])) ? io.git(["rev-parse", live]).trim() : live;
77
+ return { branch: name, tip, created: !exists, empty: tip === fullLive };
78
+ }
79
+
80
+ /** The landing PR to the default branch (idempotent: an open one for the branch is reused). @returns {Promise<number|null>} */
81
+ async function landingPr({ io, repo, def, branch, issue }) {
82
+ const open = json(await io.gh(["pr", "list", "--repo", repo, "--head", branch, "--base", def, "--state", "open", "--json", "number"])) ?? [];
83
+ if (open[0]) return open[0].number;
84
+ const out = String(await io.gh(["pr", "create", "--repo", repo, "--base", def, "--head", branch, "--title", `p0: land ${branch} on ${def}`, "--body", `Landing PR for the p0 fix deployed from \`${branch}\`${issue ? ` (#${issue})` : ""}. No code may be live without being on ${def} (I10).`]));
85
+ return Number(/\/pull\/(\d+)/.exec(out)?.[1]) || null;
86
+ }
87
+
88
+ /** WAVE_DONE (I11): a p0 wave is done only once its landing PR is merged to the default branch and live == default. @returns {Promise<{done: boolean, why?: string}>} */
89
+ export async function waveDone(ctx) {
90
+ const pr = ctx.state?.p0?.landingPr;
91
+ if (!pr) return { done: false, why: "no landing PR: the p0 is not merged to the default branch" };
92
+ const v = json(await ctx.io.gh(["pr", "view", String(pr), "--repo", ctx.repo, "--json", "state"]));
93
+ if (v?.state !== "MERGED") return { done: false, why: `landing PR #${pr} is ${v?.state ?? "unreadable"}, not merged to ${ctx.def}` };
94
+ const live = await readTarget(ctx.io, deployOf(ctx)?.live_release_command);
95
+ if (!live) return { done: false, why: "cannot read the live sha" };
96
+ const d = divergence({ io: ctx.io, def: ctx.def, live: live.sha });
97
+ return d.equal ? { done: true } : { done: false, why: d.why };
98
+ }
99
+
100
+ /** Cancel the in-flight runs of `workflow` (preempt only; fenced, audited by the ledger claim). */
101
+ async function cancelRuns(ctx, workflow) {
102
+ const { io, repo } = ctx;
103
+ const runs = json(await io.gh(["run", "list", "--repo", repo, "--workflow", workflow, "--status", "in_progress", "--json", "databaseId"])) ?? [];
104
+ for (const r of runs) {
105
+ const f = await fenced(ctx.fence, { action: "cancel-run", key: `${ctx.state.id}:p0:cancel:${r.databaseId}` }, () => io.gh(["run", "cancel", String(r.databaseId), "--repo", repo]));
106
+ if (f.refused) return f.refused;
107
+ }
108
+ return null;
109
+ }
110
+
111
+ /**
112
+ * Run a p0. `ctx`: {io, repo, def, state, save, config: {deploy, verify?, budget?, tracker?}, policy?, actor?, host?}; `args`: {issue?, branch?, units?, preempt?}.
113
+ * @returns {Promise<{status: "live"|"rolled-back"|"queued"|"refused"|"stopped"|"blocked", reason?, branch?, landingPr?, wave?, rollback?}>}
114
+ */
115
+ export async function runP0(ctx, { issue = null, branch = null, units = null, preempt = false }) {
116
+ const { io, state } = ctx;
117
+ const L = { claimDeploy, releaseDeploy, takeFence, ...(ctx.ledger ?? {}) }; // overridable for tests
118
+ const d = ctx.config.deploy, pipe = d?.pipelines?.hotfix;
119
+ const b = { ...P0_BOUNDS, ...(ctx.config.p0Bounds ?? {}) };
120
+ if (!pipe?.workflow) return { status: "refused", reason: "deploy.pipelines.hotfix is not configured" };
121
+ const inputs = { ...(pipe.inputs ?? {}), ...(units ? { units } : {}) };
122
+ try { buildDispatchArgs({ workflow: pipe.workflow, repo: ctx.repo, ref: ctx.def, inputs }); } catch (e) { return { status: "refused", reason: e.message }; }
123
+ const p0 = (state.p0 ??= { issue, units });
124
+ p0.budget = applyOnExceed({ lane: "p0", forecast: ctx.forecast, remaining: ctx.remaining, cfg: ctx.config.budget }); // I14: never blocks
125
+ const g = await laneStartGuard({ ...ctx, deploy: d, release: state.id }, "p0");
126
+ if (g.refused) return { status: "refused", reason: g.refused };
127
+ p0.live = g.live; if (g.divergence) p0.divergence = g.divergence;
128
+ const br = await ensureBranch({ io, issue, branch, live: g.live });
129
+ if (br.refused) return { status: "refused", reason: br.refused };
130
+ p0.branch = br.branch; ctx.save();
131
+ if (br.empty) return { status: "stopped", branch: br.branch, reason: `${br.branch} is at live ${short(g.live)} with no fix commits; push the fix, then run \`forgedock release p0 --branch ${br.branch}\`` };
132
+
133
+ state.steps["release-pr"] = { done: true, result: { pr: ctx.config.tracker ?? issue, issues: issue ? [issue] : [] } };
134
+ state.steps["post-merge"] = { done: true, result: { merge: br.tip } };
135
+ state.lane = "p0";
136
+ const dctx = { ...ctx, deployRef: br.branch, staging: ctx.def, git: io.git, config: { ...ctx.config, deployPipeline: "hotfix", deploy: { ...d, pipelines: { ...d.pipelines, hotfix: { ...pipe, inputs } } }, verifyRisk: "p0" } };
137
+ if (io.api) {
138
+ const f = await L.takeFence(dctx, io.holder ?? `host-${process.pid}`);
139
+ if (f.refused) return { status: "refused", reason: f.refused };
140
+ dctx.fence = f.fence;
141
+ }
142
+ const lctx = io.api ? { io, repo: ctx.repo, credential: "driver" } : null;
143
+ if (lctx) { // one deploy at a time: queue behind a DEPLOYING release, never cancel it unless --preempt
144
+ let c = null;
145
+ for (let i = 0; i <= b.queuePolls; i++) {
146
+ c = await L.claimDeploy(lctx, { release: state.id, preempt, actor: ctx.actor, reason: `p0 ${br.branch}`, now: io.now?.() });
147
+ if (!c.queued) break;
148
+ if (i < b.queuePolls) await io.sleep(b.pollMs);
149
+ }
150
+ if (c.queued) return { status: "queued", branch: br.branch, reason: c.queued };
151
+ if (c.lost) return { status: "refused", reason: "could not claim the deploy slot in the ledger" };
152
+ if (c.preempted) { const why = await cancelRuns(dctx, pipe.workflow); if (why) return { status: "refused", reason: why }; p0.preempted = c.preempted; }
153
+ }
154
+ try {
155
+ const out = await deployStep(dctx);
156
+ if (out.blocked || out.stopped) {
157
+ const rolled = state.deploy?.target && state.deploy?.runId && !out.stopped;
158
+ const reason = out.reason ?? out.why;
159
+ if (!rolled) return { status: out.blocked ? "blocked" : "stopped", branch: br.branch, reason };
160
+ const rb = await runRollback({ ...dctx, policy: ctx.policy, actor: ctx.actor, host: ctx.host }, { reason });
161
+ p0.rollback = { rung: rb.rung, ok: rb.ok };
162
+ return { status: "rolled-back", branch: br.branch, reason, rollback: rb };
163
+ }
164
+ if (out.skipped) return { status: "refused", reason: "deploy.pipelines is empty; nothing to deploy" };
165
+ p0.landingPr = await landingPr({ io, repo: ctx.repo, def: ctx.def, branch: br.branch, issue }); ctx.save();
166
+ const wave = await waveDone({ ...ctx, deploy: d });
167
+ let sync; // #5566: once the landing PR is merged, sync the default branch back into the integration branch (managed only)
168
+ if (wave.done && ctx.config.managed) { const { syncStep } = await import("./release-mergeback.mjs"); sync = await syncStep(ctx, { lane: "p0" }); }
169
+ return { status: "live", branch: br.branch, landingPr: p0.landingPr, wave, ...(sync ? { sync } : {}) };
170
+ } finally {
171
+ if (lctx) await L.releaseDeploy(lctx, state.id).catch(() => null);
172
+ }
173
+ }
174
+
175
+ /** `forgedock release p0 <#issue | --branch B> [--units a,b] [--preempt] [--yes] [--repo R]`; @returns 0 live, 1 refused, 3 queued/stopped/blocked/rolled back. */
176
+ export async function p0FromCli(argv, { io, rel, id, config, policy, def, actor, host, ask }) {
177
+ const flag = (f) => { const i = argv.indexOf(f); return i >= 0 && !argv[i + 1]?.startsWith("--") ? argv[i + 1] : null; };
178
+ const positional = argv.find((a, i) => !a.startsWith("--") && !["--branch", "--units", "--repo"].includes(argv[i - 1]));
179
+ const issue = positional && /^#?\d+$/.test(positional) ? Number(positional.replace("#", "")) : null;
180
+ const branch = flag("--branch");
181
+ const refuse = (m) => { io.print(`release p0: refused: ${m}`); return 1; };
182
+ if (!issue && !branch) return refuse("a p0 needs #<issue> or --branch <B>");
183
+ if (issue && branch) return refuse("pass either #<issue> or --branch, not both");
184
+ const repo = flag("--repo") ?? JSON.parse(String(await io.gh(["repo", "view", "--json", "nameWithOwner"]))).nameWithOwner;
185
+ const units = flag("--units"), preempt = argv.includes("--preempt");
186
+ if (!await confirmGo({ yes: argv.includes("--yes"), ask, plan: `p0 ${issue ? `#${issue}` : branch}${units ? ` units ${units}` : ""}: base on live, deploy via the hotfix pipeline, then land on ${def}${preempt ? "; --preempt cancels an in-flight deploy" : ""}` })) return refuse("not confirmed (type go, or pass --yes)");
187
+ const state = rel.load() ?? { v: 1, id, repo, startedAt: new Date(io.now()).toISOString(), steps: {}, held: [] };
188
+ const ctx = { io, repo, def, state, save: () => rel.save(state), config, policy, actor, host };
189
+ const r = await runP0(ctx, { issue, branch, units, preempt });
190
+ io.print(`release p0 ${id}: ${r.status}${r.reason ? `: ${r.reason}` : ""}${r.landingPr ? ` (landing PR #${r.landingPr}${r.wave?.done ? ", wave done" : `, wave not done: ${r.wave?.why}`})` : ""}`);
191
+ state.status = r.status; ctx.save();
192
+ return r.status === "live" ? 0 : r.status === "refused" ? 1 : 3;
193
+ }
@@ -0,0 +1,127 @@
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 { readFileSync, writeFileSync } from "node:fs";
7
+ import { join } from "node:path";
8
+ import { tmpDir } from "../tests/_tmp.mjs";
9
+ import { laneStartGuard, waveDone, confirmGo, runP0, divergence, P0_BOUNDS } from "./release-p0.mjs";
10
+ import { buildDispatchArgs } from "./release-control.mjs";
11
+ import { applyOnExceed } from "./release-minutes.mjs";
12
+
13
+ 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" };
14
+ const mk = (cwd) => (args) => execFileSync("git", args, { cwd, encoding: "utf8", env: { ...process.env, ...ENV }, stdio: ["pipe", "pipe", "pipe"] });
15
+
16
+ /** origin (bare) + work clone on main; `live` is the first commit, main may be ahead of it. */
17
+ function repoWorld({ ahead = false } = {}) {
18
+ const root = tmpDir("p0-"), origin = join(root, "o.git"), work = join(root, "w");
19
+ execFileSync("git", ["init", "-q", "--bare", "-b", "main", origin]);
20
+ execFileSync("git", ["clone", "-q", origin, work], { env: { ...process.env, ...ENV } });
21
+ const git = mk(work);
22
+ git(["checkout", "-q", "-b", "main"]);
23
+ writeFileSync(join(work, "a.txt"), "1\n"); git(["add", "."]); git(["commit", "-qm", "one"]);
24
+ const live = git(["rev-parse", "HEAD"]).trim();
25
+ if (ahead) { writeFileSync(join(work, "b.txt"), "2\n"); git(["add", "."]); git(["commit", "-qm", "two"]); }
26
+ git(["push", "-q", "origin", "main"]);
27
+ return { git, live };
28
+ }
29
+ const deploy = { live_release_command: "live", pipelines: { hotfix: { workflow: "hotfix.yml", inputs: {} } } };
30
+ const ctxFor = (w, extra = {}) => {
31
+ const recorded = [];
32
+ return { recorded, io: { git: w.git, rehearse: async () => ({ ok: true, output: w.live }), gh: async () => "[]" }, repo: "o/r", def: "main", deploy, recordDivergence: async (r) => { recorded.push(r); }, ...extra };
33
+ };
34
+
35
+ describe("laneStartGuard (I10)", () => {
36
+ it("train is refused with the divergence in the message when default is ahead of live", async () => {
37
+ const w = repoWorld({ ahead: true });
38
+ const r = await laneStartGuard(ctxFor(w), "train");
39
+ assert.match(r.refused, /train lane refused: main .* != live/);
40
+ });
41
+ it("train starts when default == live", async () => {
42
+ const w = repoWorld();
43
+ assert.equal((await laneStartGuard(ctxFor(w), "train")).ok, true);
44
+ });
45
+ it("p0 in the same state proceeds, bases on live and records the divergence", async () => {
46
+ const w = repoWorld({ ahead: true });
47
+ const c = ctxFor(w, { release: "r1" });
48
+ const r = await laneStartGuard(c, "p0");
49
+ assert.equal(r.ok, true); assert.equal(r.base, w.live); assert.match(r.divergence, /!= live/);
50
+ assert.equal(c.recorded.length, 1); assert.equal(c.recorded[0].live, w.live);
51
+ });
52
+ it("an unreadable live sha refuses a guarded lane; other lanes are not guarded", async () => {
53
+ const w = repoWorld();
54
+ const c = ctxFor(w); c.io.rehearse = async () => ({ ok: false, output: "" });
55
+ assert.match((await laneStartGuard(c, "p0")).refused, /cannot read the live sha/);
56
+ assert.equal((await laneStartGuard(c, "feature")).ok, true);
57
+ });
58
+ });
59
+
60
+ describe("WAVE_DONE (I11)", () => {
61
+ const wctx = (w, state, view) => ({ ...ctxFor(w), state, io: { ...ctxFor(w).io, gh: async () => JSON.stringify(view) } });
62
+ it("refuses with no landing PR and while the PR is unmerged", async () => {
63
+ const w = repoWorld();
64
+ assert.equal((await waveDone(wctx(w, {}, {}))).done, false);
65
+ const r = await waveDone(wctx(w, { p0: { landingPr: 5 } }, { state: "OPEN" }));
66
+ assert.equal(r.done, false); assert.match(r.why, /not merged/);
67
+ });
68
+ it("refuses merged-but-live != default, passes when equal", async () => {
69
+ const ahead = repoWorld({ ahead: true });
70
+ assert.match((await waveDone(wctx(ahead, { p0: { landingPr: 5 } }, { state: "MERGED" }))).why, /!= live/);
71
+ const eq = repoWorld();
72
+ assert.deepEqual(await waveDone(wctx(eq, { p0: { landingPr: 5 } }, { state: "MERGED" })), { done: true });
73
+ assert.equal(divergence({ io: { git: eq.git }, def: "main", live: eq.live }).equal, true);
74
+ });
75
+ });
76
+
77
+ describe("confirmation, budget and dispatch allowlist", () => {
78
+ it("asks for a typed go unless --yes", async () => {
79
+ assert.equal(await confirmGo({ yes: true }), true);
80
+ assert.equal(await confirmGo({ yes: false, ask: async () => "go", plan: "p" }), true);
81
+ assert.equal(await confirmGo({ yes: false, ask: async () => "yes", plan: "p" }), false);
82
+ assert.equal(await confirmGo({ yes: false }), false);
83
+ });
84
+ it("budget never blocks a p0", () => {
85
+ assert.equal(applyOnExceed({ lane: "p0", forecast: 999, remaining: 1, cfg: { onExceed: "stop" } }).action, "proceed");
86
+ });
87
+ it("the dispatch builder rejects both break-glass inputs; the module never sets them", () => {
88
+ for (const k of ["override_freeze", "acknowledge_hotfix_revert"]) assert.throws(() => buildDispatchArgs({ workflow: "w.yml", repo: "o/r", ref: "main", inputs: { [k]: "true" } }), /break-glass/);
89
+ const src = readFileSync(new URL("./release-p0.mjs", import.meta.url), "utf8");
90
+ assert.doesNotMatch(src, /override_freeze|acknowledge_hotfix_revert/);
91
+ });
92
+ it("runP0 refuses pipeline inputs carrying a break-glass key", async () => {
93
+ const state = { id: "r1", steps: {} };
94
+ const cfg = { deploy: { ...deploy, pipelines: { hotfix: { workflow: "h.yml", inputs: { override_freeze: "true" } } } } };
95
+ const r = await runP0({ io: {}, repo: "o/r", def: "main", state, save() {}, config: cfg }, { issue: 1 });
96
+ assert.equal(r.status, "refused"); assert.match(r.reason, /break-glass/);
97
+ });
98
+ });
99
+
100
+ describe("runP0 concurrency (I10)", () => {
101
+ async function run(claim, preempt) {
102
+ const w = repoWorld({ ahead: true });
103
+ const tip = w.git(["rev-parse", "HEAD"]).trim();
104
+ const calls = { gh: [], claims: [] };
105
+ const io = {
106
+ git: (a) => { if (a[0] === "ls-remote") return "x\trefs/heads/p0/issue-1\n"; if (a[0] === "rev-parse" && a[1] === "refs/remotes/origin/p0/issue-1") return `${tip}\n`; if (a[0] === "fetch" && a[3]?.startsWith("+")) return ""; return w.git(a); },
107
+ rehearse: async () => ({ ok: true, output: w.live }), sleep: async () => {}, now: () => 1, api: async () => ({}),
108
+ gh: async (a) => { calls.gh.push(a.join(" ")); if (a[0] === "run" && a[1] === "list") return JSON.stringify([{ databaseId: 9 }]); return "[]"; },
109
+ };
110
+ const state = { id: "r1", steps: {} };
111
+ const ledger = { takeFence: async () => ({ fence: null }), claimDeploy: async (_c, o) => { calls.claims.push(o); return claim(o); }, releaseDeploy: async () => ({}) };
112
+ const r = await runP0({ io, repo: "o/r", def: "main", state, save() {}, ledger, config: { deploy, p0Bounds: { pollMs: 0, queuePolls: 2 } } }, { issue: 1, preempt }).catch((e) => ({ status: "threw", reason: e.message }));
113
+ return { r, calls };
114
+ }
115
+ it("queues behind a DEPLOYING release and never cancels without --preempt", async () => {
116
+ const { r, calls } = await run(() => ({ queued: "release r0 is DEPLOYING" }), false);
117
+ assert.equal(r.status, "queued");
118
+ assert.equal(calls.claims.length, 3); assert.ok(calls.claims.every((c) => c.preempt === false));
119
+ assert.ok(!calls.gh.some((c) => c.startsWith("run cancel")));
120
+ });
121
+ it("--preempt cancels the in-flight runs, audited through the claim", async () => {
122
+ const { calls } = await run(() => ({ ok: true, preempted: "r0" }), true);
123
+ assert.equal(calls.claims[0].preempt, true);
124
+ assert.ok(calls.gh.some((c) => c.startsWith("run cancel 9")));
125
+ });
126
+ it("exposes bounds", () => assert.ok(P0_BOUNDS.queuePolls > 0));
127
+ });
@@ -0,0 +1,267 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * `forgedock release plan` (#5559): a deterministic, read-only dry run. A snapshot of open issues + the default-branch policy + the live sha
5
+ * becomes ordered waves, exclusions with machine-readable reason keys and a `plan_hash` an approval binds to (I2).
6
+ * `buildPlan` is pure (no clock, no I/O): the same inputs give a byte-identical plan whatever the input order. Effects (gh, git, ledger) live in `planFromCli`.
7
+ */
8
+ import { createHash } from "node:crypto";
9
+ import { resolvePath } from "./release-unitmap.mjs";
10
+ import { deriveFacts, riskOf } from "./release-classify.mjs";
11
+ import { priorityOf } from "./issuewatch-release.mjs";
12
+ import { trailingMedian, applyOnExceed, parseBudgetConfig } from "./release-minutes.mjs";
13
+
14
+ export const PLAN_SCHEMA = "forgedock.release.plan/v1";
15
+ export const PLAN_LABEL = "release-plan"; // tracking issue(s) whose comments carry FORGE:DECISION plan <hash>; never a candidate
16
+ export const DECISION_RE = /<!--\s*FORGE:DECISION\s+plan\s+([0-9a-f]{64})\s*-->/i;
17
+ export const BATCH_SKIP_LABELS = ["needs-human", "post-deploy", "workflow:merged", "awaiting-promotion", "host-task"];
18
+ export const EXCLUSION_KEYS = ["epic", "plan.skip_labels", "design_gate", "dependency_open", "ready_no", "unclassified", "dependency_cycle", "max_issues", "lane_force_exclude", "p0"];
19
+ export const LANE_FORCE_TTL_MS = 24 * 3_600_000; // a `lane --force` decision without `until` is honoured this long after `at`
20
+ const SEV = { P0: 0, P1: 1, P2: 2, P3: 3 };
21
+
22
+ const sha = (s) => createHash("sha256").update(s).digest("hex");
23
+ /** JSON with sorted object keys: the byte-stable form the hash and the output use. */
24
+ export const stableJson = (v) => JSON.stringify(v, (_k, x) => (x && typeof x === "object" && !Array.isArray(x) ? Object.fromEntries(Object.keys(x).sort().map((k) => [k, x[k]])) : x));
25
+ const names = (i) => (i.labels ?? []).map((l) => (typeof l === "string" ? l : l?.name)).filter(Boolean);
26
+ const depsOf = (i) => [...new Set([...String(i.body ?? "").matchAll(/^\s*(?:[-*]\s*)?\**depends on\**:?\s*(.+)$/gim)].flatMap((m) => [...m[1].matchAll(/#(\d+)/g)].map((x) => +x[1])).filter((n) => n !== i.number))].sort((a, b) => a - b);
27
+
28
+ /** The latest `FORGE:CLASSIFY` record in an issue's comments (JSON body), or null. */
29
+ export function recordOf(comments) {
30
+ const c = (comments ?? []).map((x) => String(x?.body ?? "")).filter((b) => b.includes("FORGE:CLASSIFY")).at(-1);
31
+ if (!c) return null;
32
+ let body = c; // drop every <!-- ... --> span (an unterminated one drops the rest) without a regex sanitizer
33
+ for (let i = body.indexOf("<!--"); i >= 0; i = body.indexOf("<!--", i)) { const j = body.indexOf("-->", i + 4); body = body.slice(0, i) + (j < 0 ? "" : body.slice(j + 3)); }
34
+ try { const o = JSON.parse(body.slice(body.indexOf("{"), body.lastIndexOf("}") + 1)); return o && typeof o === "object" ? o : null; } catch { return null; }
35
+ }
36
+
37
+ /**
38
+ * The units a set of changed files rolls (design 4.4), as one pure function. `units` is a superset of the units owning or coupled to the files and of every
39
+ * contract producer and consumer touched; `contract.order` is producer first; `pipeline` is `full` when any `forces` entry or a `service_pipeline: false` unit is involved.
40
+ */
41
+ export function rollSet(policy, files) {
42
+ const res = (files ?? []).map((f) => resolvePath(policy, f));
43
+ const units = new Set(), contracts = [], forced = [];
44
+ for (const r of res) {
45
+ r.units.forEach((u) => units.add(u));
46
+ r.affects.forEach((u) => units.add(u)); // shared paths roll the full couplings consumer set
47
+ for (const c of r.contracts) { if (!contracts.includes(c)) contracts.push(c); }
48
+ for (const f of r.forces) forced.push(f.reason ?? f.pipeline ?? "forces");
49
+ }
50
+ const order = [];
51
+ for (const c of contracts) { for (const u of [c.producer, ...(c.consumers ?? [])]) { if (u) { units.add(u); if (!order.includes(u)) order.push(u); } } }
52
+ const all = [...units].sort();
53
+ const noService = all.filter((u) => policy?.units?.[u]?.service_pipeline === false);
54
+ const hosts = {};
55
+ for (const u of all) {
56
+ const h = policy?.units?.[u]?.hosts;
57
+ if (Array.isArray(h) && h.length) hosts[u] = h.length > 1 && policy.units[u].single_host_ok ? [h[0]] : [...h]; // a two-host unit rolls on both unless single_host_ok
58
+ }
59
+ const additive = contracts.every((c) => c.additive_only === true);
60
+ return {
61
+ units: all,
62
+ contract: { atomic: contracts.length > 0, order, additive_only: additive, release_only: contracts.length > 0 && !additive },
63
+ pipeline: !all.length && !forced.length ? "none" : forced.length || noService.length ? "full" : "service",
64
+ forced: [...new Set(forced)].sort(), no_service: noService, hosts,
65
+ };
66
+ }
67
+
68
+ /** `lane --force` entries (`{force, actor, at, until?}`) still in force at `now` and from a trusted actor (when `trust.actors` is set). */
69
+ export function honouredLanes(lanes, policy, now) {
70
+ const trusted = policy?.trust?.actors ?? [], out = {};
71
+ for (const [n, e] of Object.entries(lanes ?? {})) {
72
+ if (!e?.actor || !["train", "release", "p0", "exclude"].includes(e.force)) continue;
73
+ if (trusted.length && !trusted.includes(e.actor)) continue;
74
+ const end = Date.parse(e.until ?? "") || (Date.parse(e.at ?? "") + LANE_FORCE_TTL_MS);
75
+ if (!(end > now)) continue; // expired or no usable timestamp
76
+ out[n] = { force: e.force, actor: e.actor, until: new Date(end).toISOString() };
77
+ }
78
+ return out;
79
+ }
80
+
81
+ function sccs(nodes, edges) { // Tarjan; edges: n -> [dependency numbers]
82
+ let idx = 0; const st = [], on = new Set(), low = new Map(), num = new Map(), out = [];
83
+ const visit = (v) => {
84
+ num.set(v, idx); low.set(v, idx++); st.push(v); on.add(v);
85
+ for (const w of edges.get(v) ?? []) {
86
+ if (!num.has(w)) { visit(w); low.set(v, Math.min(low.get(v), low.get(w))); } else if (on.has(w)) low.set(v, Math.min(low.get(v), num.get(w)));
87
+ }
88
+ if (low.get(v) === num.get(v)) { const c = []; let w; do { w = st.pop(); on.delete(w); c.push(w); } while (w !== v); out.push(c); }
89
+ };
90
+ for (const v of nodes) if (!num.has(v)) visit(v);
91
+ return out;
92
+ }
93
+
94
+ /**
95
+ * @param {{issues: object[], policy: object, policySha: string, liveSha: string|null, lanes?: object, now?: number, investigate?: (issue) => object|null, verifiedLive?: (n: number) => boolean}} input
96
+ * issues: `{number, title, body, labels, createdAt, updatedAt, comments?}`; PRs (`pullRequest`/`pull_request`/`isPullRequest`) are never candidates.
97
+ * @returns the plan: `{schema, plan_hash, policy_sha, live_sha, snapshot, waves, issues, excluded}`.
98
+ */
99
+ export function buildPlan({ issues, policy, policySha, liveSha, lanes = {}, now = 0, investigate, verifiedLive }) {
100
+ const pool = (issues ?? []).filter((i) => !(i.pullRequest || i.pull_request || i.isPullRequest) && !names(i).includes(PLAN_LABEL)).sort((a, b) => a.number - b.number);
101
+ const byNum = new Map(pool.map((i) => [i.number, i]));
102
+ const forces = honouredLanes(lanes, policy, now);
103
+ const snapshot = pool.map((i) => ({ number: i.number, updated_at: i.updatedAt ?? null, body_sha: sha(String(i.body ?? "")) }));
104
+ const hashed = { snapshot, policy_sha: policySha ?? null, live_sha: liveSha ?? null, ...(Object.keys(forces).length ? { lane_forces: forces } : {}) };
105
+ const excluded = new Map(), info = new Map();
106
+ const exclude = (n, key, detail) => { if (!excluded.has(n)) excluded.set(n, { number: n, key, detail }); };
107
+ const skip = [...new Set([...(policy?.plan?.skip_labels ?? BATCH_SKIP_LABELS), "hold"])], min = policy?.classify?.min_confidence;
108
+ const alive = [];
109
+ for (const i of pool) {
110
+ const n = i.number, ls = names(i);
111
+ if (ls.includes("epic")) { exclude(n, "epic", "epics are not built"); continue; }
112
+ const hit = ls.filter((l) => skip.includes(l) || l.startsWith("parked:"));
113
+ if (hit.length) { exclude(n, "plan.skip_labels", `labelled ${hit.join(", ")}`); continue; }
114
+ if (policy?.plan?.require_design_gate !== false && ls.includes("design:needed") && !ls.includes("design:approved")) { exclude(n, "design_gate", "design:needed without design:approved"); continue; }
115
+ let rec = recordOf(i.comments);
116
+ if (rec?.ready === false || ls.includes("ready:no")) { exclude(n, "ready_no", "classified ready: no"); continue; }
117
+ const low = (r) => !r || (min !== undefined && !(Number(r.confidence) >= min));
118
+ if (low(rec) && investigate) { const r = investigate(i); if (r && typeof r === "object") rec = { ...(rec ?? {}), ...r }; }
119
+ if (low(rec)) { exclude(n, "unclassified", rec ? `confidence ${rec.confidence ?? "unknown"} below classify.min_confidence ${min}` : "no FORGE:CLASSIFY record"); continue; }
120
+ if (forces[n]?.force === "exclude") { exclude(n, "lane_force_exclude", `lane --force exclude by ${forces[n].actor}`); continue; }
121
+ info.set(n, { rec });
122
+ alive.push(n);
123
+ }
124
+ // dependencies: a dependency that is excluded (or not verified live) blocks; cycles are found among the survivors
125
+ const edges = new Map();
126
+ for (const n of alive) {
127
+ edges.set(n, depsOf(byNum.get(n)).filter((d) => byNum.has(d)));
128
+ }
129
+ let live = new Set(alive);
130
+ for (const comp of sccs(alive, new Map([...edges].map(([k, v]) => [k, v.filter((d) => live.has(d))])))) {
131
+ if (comp.length > 1) comp.sort((a, b) => a - b).forEach((n) => { exclude(n, "dependency_cycle", `cycle ${comp.map((x) => `#${x}`).join(" -> ")}`); live.delete(n); });
132
+ }
133
+ for (let changed = true; changed;) {
134
+ changed = false;
135
+ for (const n of [...live]) {
136
+ const bad = depsOf(byNum.get(n)).filter((d) => (byNum.has(d) && !live.has(d)) || (!byNum.has(d) && verifiedLive && !verifiedLive(d)));
137
+ if (bad.length) { exclude(n, "dependency_open", `depends on ${bad.map((d) => `#${d}`).join(", ")} (unresolved, not verified live nor in an earlier wave)`); live.delete(n); changed = true; }
138
+ }
139
+ }
140
+ // topological order: dependency first, then severity, then age
141
+ const sev = (n) => SEV[info.get(n).rec.severity ?? priorityOf(byNum.get(n))] ?? 3;
142
+ const rank = (a, b) => sev(a) - sev(b) || String(byNum.get(a).createdAt ?? "").localeCompare(String(byNum.get(b).createdAt ?? "")) || a - b;
143
+ const pending = new Map([...live].map((n) => [n, new Set(depsOf(byNum.get(n)).filter((d) => live.has(d)))]));
144
+ const order = [];
145
+ while (pending.size) {
146
+ const ready = [...pending].filter(([, d]) => !d.size).map(([n]) => n).sort(rank);
147
+ const n = ready[0];
148
+ order.push(n); pending.delete(n); for (const d of pending.values()) d.delete(n);
149
+ }
150
+ // lane assignment, first match wins (design 4.5)
151
+ const plan = new Map(), trainMax = policy?.lanes?.train?.train_max_units ?? 3, unitsMax = policy?.lanes?.train?.units_max ?? trainMax;
152
+ for (const n of order) {
153
+ const { rec } = info.get(n), files = Array.isArray(rec.files) ? rec.files : [];
154
+ const rs = files.length ? rollSet(policy, files) : { ...rollSet(policy, []), units: [...(rec.units ?? [])].sort() };
155
+ const facts = files.length ? deriveFacts(policy, files, { diffLines: Number(rec.diff_lines) || 0 }) : null;
156
+ const risk = facts ? riskOf(policy, facts).risk : (rec.risk ?? "low");
157
+ const migrations = facts ? facts.migrations : (rec.migrations ?? "none");
158
+ const e = { number: n, lane: "release", reason: "", risk, units: rs.units, pipeline: rs.pipeline, severity: rec.severity ?? priorityOf(byNum.get(n)) ?? "P3" };
159
+ if (rs.contract.atomic) e.atomic = { order: rs.contract.order, additive_only: rs.contract.additive_only };
160
+ if (Object.keys(rs.hosts).length) e.hosts = rs.hosts;
161
+ const forced = forces[n];
162
+ const bug = rec.type === "bug";
163
+ if (forced && forced.force !== "exclude") { e.lane = forced.force; e.reason = `lane --force ${forced.force} by ${forced.actor} until ${forced.until}`; e.forced = true; }
164
+ else if (bug && e.severity === "P0") { exclude(n, "p0", "call p0"); continue; }
165
+ else if (bug) {
166
+ const why = [];
167
+ if (rec.exists_in !== "live") why.push(rec.exists_in === "staging-only" ? "staging-only" : `exists_in=${rec.exists_in ?? "unknown"}`);
168
+ if (migrations !== "none") why.push(`migrations=${migrations}`);
169
+ if (rs.contract.atomic || rec.contract_changed) why.push("contract change");
170
+ if (rs.units.length > unitsMax) why.push(`rolled set ${rs.units.length} > units_max ${unitsMax}`);
171
+ if (risk === "high") why.push("risk high");
172
+ e.lane = why.length ? "release" : "train"; e.reason = why.length ? why.join("; ") : "bug live, no migrations, no contract change, small rolled set";
173
+ } else if (rec.type === "docs" && !rs.units.length) { e.reason = "docs-only"; e.docs_only = true; }
174
+ else e.reason = `${rec.type ?? "unknown"} rolls with the release wave`;
175
+ if (rs.contract.release_only && e.lane === "train") { e.lane = "release"; e.reason = "contract change is not additive-only"; }
176
+ const late = depsOf(byNum.get(n)).find((d) => plan.get(d)?.lane === "release");
177
+ if (e.lane === "train" && late !== undefined) { e.lane = "release"; e.reason = `depends on #${late} (release wave)`; }
178
+ plan.set(n, e);
179
+ }
180
+ // waves: train waves (overflow opens the next), then the release wave
181
+ const waves = [], trainIds = order.filter((n) => plan.get(n)?.lane === "train");
182
+ const maxIssues = policy?.lanes?.train?.train_max_issues ?? 15;
183
+ let cur = null;
184
+ for (const n of trainIds) {
185
+ const u = plan.get(n).units;
186
+ const merged = cur ? new Set([...cur.units, ...u]) : null;
187
+ if (!cur || cur.issues.length >= maxIssues || merged.size > trainMax) { cur = { lane: "train", issues: [], units: [] }; waves.push(cur); }
188
+ cur.issues.push(n); cur.units = [...new Set([...cur.units, ...u])].sort();
189
+ }
190
+ const rel = order.filter((n) => plan.get(n)?.lane === "release");
191
+ if (rel.length) waves.push({ lane: "release", issues: rel, units: [...new Set(rel.flatMap((n) => plan.get(n).units))].sort() });
192
+ const cap = policy?.plan?.max_issues ?? 60;
193
+ let left = cap;
194
+ for (const w of waves) {
195
+ const keep = w.issues.slice(0, Math.max(0, left)); left -= keep.length;
196
+ for (const n of w.issues.slice(keep.length)) { exclude(n, "max_issues", `plan.max_issues ${cap} reached`); plan.delete(n); }
197
+ w.issues = keep; w.units = [...new Set(keep.flatMap((n) => plan.get(n).units))].sort();
198
+ }
199
+ const kept = waves.filter((w) => w.issues.length);
200
+ let t = 0;
201
+ kept.forEach((w) => { w.id = w.lane === "train" ? `train-${++t}` : "release"; });
202
+ return {
203
+ schema: PLAN_SCHEMA, plan_hash: sha(stableJson(hashed)), policy_sha: policySha ?? null, live_sha: liveSha ?? null, snapshot,
204
+ waves: kept, issues: Object.fromEntries([...plan].sort((a, b) => a[0] - b[0]).map(([n, e]) => [n, e])),
205
+ excluded: [...excluded.values()].sort((a, b) => a.number - b.number), lane_forces: forces,
206
+ };
207
+ }
208
+
209
+ /** The approval state of `plan` from typed decision comments (`{author, body}`): only an actor in `trust.actors` counts (none trusted = nobody). */
210
+ export function approvalOf(plan, decisions, policy) {
211
+ const trusted = policy?.trust?.actors ?? [], ignored = [];
212
+ let stale = false, by = null;
213
+ for (const d of decisions ?? []) {
214
+ const m = DECISION_RE.exec(String(d?.body ?? ""));
215
+ if (!m) continue;
216
+ if (!trusted.includes(d.author)) { ignored.push(d.author ?? "unknown"); continue; }
217
+ if (m[1].toLowerCase() === plan.plan_hash) by = d.author; else stale = true;
218
+ }
219
+ return { state: by ? "approved" : stale ? "stale" : "none", by, ignored };
220
+ }
221
+
222
+ /** Minutes forecast per wave from the trailing median of the lane's history, and the `budget.on_exceed` action. Not part of the hash. */
223
+ export function forecastPlan(plan, history, { remaining = null, cfg = parseBudgetConfig(null) } = {}) {
224
+ const per = plan.waves.map((w) => ({ wave: w.id, minutes: trailingMedian(history ?? [], w.lane) }));
225
+ const known = per.filter((p) => p.minutes != null);
226
+ const forecast = known.length ? known.reduce((s, p) => s + p.minutes, 0) : null;
227
+ return { per_wave: per, forecast, remaining, ...applyOnExceed({ lane: "release", forecast, remaining, cfg }) };
228
+ }
229
+
230
+ export function renderReleasePlan(plan, { approval, forecast, lane = "auto" } = {}) {
231
+ const out = [`release plan ${plan.plan_hash.slice(0, 12)} policy ${String(plan.policy_sha ?? "none").slice(0, 7)} live ${String(plan.live_sha ?? "unknown").slice(0, 7)}`];
232
+ for (const w of plan.waves.filter((x) => lane === "auto" || x.lane === lane)) {
233
+ out.push(`wave ${w.id} (${w.issues.length} issue(s); units ${w.units.join(",") || "none"})`);
234
+ for (const n of w.issues) { const e = plan.issues[n]; out.push(` #${n} ${e.lane} risk=${e.risk} ${e.reason}`); }
235
+ }
236
+ for (const x of plan.excluded.filter((e) => lane === "auto" || (lane === "p0" && e.key === "p0"))) out.push(`${x.key === "p0" ? "call p0" : "excluded"}: #${x.number} [${x.key}] ${x.detail}`);
237
+ if (forecast) out.push(`forecast: ${forecast.forecast ?? "unknown"} min (${forecast.action}: ${forecast.why})`);
238
+ if (approval) out.push(`approval: ${approval.state}${approval.by ? ` by ${approval.by}` : ""}${approval.ignored.length ? ` (ignored untrusted: ${approval.ignored.join(", ")})` : ""}`);
239
+ return out;
240
+ }
241
+
242
+ const flagOf = (argv, f) => { const i = argv.indexOf(f); return i >= 0 ? argv[i + 1] : null; };
243
+
244
+ /**
245
+ * `forgedock release plan [--lane auto|train|release|p0] [--milestone <slug>] [--issues N,N] [--repo R] [--json]`. Read-only (gh issue list, the live-release command);
246
+ * only with `managed` the plan record is committed to a `forge-ledger/<id>` branch through the ledger writer. @returns the exit code.
247
+ */
248
+ export async function planFromCli(argv, { io, policy, policySha, managed = false, newId, history = [], budget = {}, readLanes, ledger }) {
249
+ const lane = flagOf(argv, "--lane") ?? "auto";
250
+ if (!["auto", "train", "release", "p0"].includes(lane)) throw new Error(`release plan: --lane must be auto|train|release|p0`);
251
+ if (!policy || !policySha) { io.print("release plan: refused: no valid .forge/release.yaml on the default branch (run release check-config)"); return 1; }
252
+ const repo = flagOf(argv, "--repo") ?? JSON.parse(String(await io.gh(["repo", "view", "--json", "nameWithOwner"]))).nameWithOwner;
253
+ const ms = flagOf(argv, "--milestone"), only = flagOf(argv, "--issues");
254
+ const list = JSON.parse(String(await io.gh(["issue", "list", "--repo", repo, "--state", "open", "--limit", "500", ...(ms ? ["--milestone", ms] : []), "--json", "number,title,body,labels,createdAt,updatedAt,comments"])) || "[]");
255
+ const picked = only ? new Set(only.split(",").map((s) => +s.replace("#", "")).filter(Boolean)) : null;
256
+ const decisions = list.filter((i) => names(i).includes(PLAN_LABEL)).flatMap((i) => (i.comments ?? []).map((c) => ({ author: c.author?.login ?? c.user?.login, body: c.body })));
257
+ const { readTarget } = await import("./release-deploy.mjs");
258
+ const liveSha = (await readTarget(io, policy.deploy?.live_release_command))?.sha ?? null;
259
+ const lanes = (readLanes ? await readLanes() : null) ?? {};
260
+ const plan = buildPlan({ issues: picked ? list.filter((i) => picked.has(i.number) || names(i).includes(PLAN_LABEL)) : list, policy, policySha, liveSha, lanes, now: io.now?.() ?? 0 });
261
+ const approval = approvalOf(plan, decisions, policy);
262
+ const fc = forecastPlan(plan, history, { remaining: budget.remaining ?? null, cfg: budget.cfg });
263
+ if (argv.includes("--json")) io.print(stableJson({ ...plan, approval, forecast: fc }));
264
+ else renderReleasePlan(plan, { approval, forecast: fc, lane }).forEach((l) => io.print(l));
265
+ if (managed && ledger && newId) await ledger({ id: newId, repo, plan, approval });
266
+ return 0;
267
+ }