forgedock 1.59.2 → 1.60.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) 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 +12 -5
  7. package/bin/lean/conformance.test.mjs +30 -2
  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 +123 -17
  22. package/bin/lean/lean.test.mjs +154 -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 +5 -2
  32. package/bin/lean/preflight.test.mjs +7 -0
  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 +94 -0
  80. package/bin/lean/validate-catalog.test.mjs +42 -0
  81. package/bin/pool/agent.mjs +4 -1
  82. package/bin/pool/lane-tools.mjs +115 -0
  83. package/bin/pool/lane-tools.test.mjs +26 -0
  84. package/bin/pool/warm.mjs +1 -1
  85. package/docs/CONFIG.md +225 -1
  86. package/docs/ISSUE-WATCH.md +1 -0
  87. package/docs/design/visual-gate.md +10 -0
  88. package/docs/eval/adversarial-bench.md +1 -0
  89. package/package.json +1 -1
  90. package/pool/README.md +2 -0
  91. package/scripts/bench-adversarial.mjs +4 -0
  92. package/scripts/bench-lightlane.mjs +2 -1
  93. package/templates/github-actions/forge-conductor.scopes.json +7 -0
  94. package/templates/github-actions/forge-conductor.yml +57 -0
@@ -0,0 +1,129 @@
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 { syncStep, finishSync, syncBlocksRelease, syncValidated, diffRanges, duplicateFixes, staleMilestones, targetSet } from "./release-mergeback.mjs";
6
+ import { runTargetedPreflight } from "./release-preflight.mjs";
7
+
8
+ const LANE_DIFF = "diff --git a/src/a.js b/src/a.js\n--- a/src/a.js\n+++ b/src/a.js\n@@ -10,2 +10,3 @@\n x\n";
9
+ const OVERLAP = "--- a/src/a.js\n+++ b/src/a.js\n@@ -11,1 +11,1 @@\n";
10
+ const APART = "--- a/src/a.js\n+++ b/src/a.js\n@@ -90,1 +90,1 @@\n";
11
+
12
+ /** Fake io: records every git/gh call; `writes` are the mutating ones. */
13
+ function fake({ conflict = false, milestones = [] } = {}) {
14
+ const calls = [], writes = [];
15
+ const io = {
16
+ git(args) {
17
+ calls.push(["git", ...args]);
18
+ if (args[0] === "merge-tree") { if (conflict) { const e = new Error("conflict"); e.stdout = "CONFLICT (content): Merge conflict in src/conflict.js\n"; throw e; } return ""; }
19
+ if (args[0] === "diff" && args.includes("--name-only")) return "src/a.js\n";
20
+ if (args[0] === "diff") return LANE_DIFF;
21
+ if (args[0] === "ls-remote") return milestones.map((m) => `abc\trefs/heads/${m}`).join("\n");
22
+ if (args[0] === "rev-parse") return "deadbeef\n";
23
+ return "";
24
+ },
25
+ async gh(args) {
26
+ calls.push(["gh", ...args]);
27
+ if (args[0] === "pr" && args[1] === "list" && args.includes("--head")) return "[]";
28
+ if (args[0] === "pr" && args[1] === "create") { writes.push(args); return "https://github.com/o/r/pull/50"; }
29
+ if (args[0] === "pr" && args[1] === "merge") { writes.push(args); return ""; }
30
+ if (args[0] === "pr" && args[1] === "view") return '{"state":"MERGED"}';
31
+ if (args[0] === "pr" && args[1] === "list") return JSON.stringify([{ number: 61, headRefName: "fix/overlap" }, { number: 62, headRefName: "fix/apart" }]);
32
+ if (args[0] === "pr" && args[1] === "diff") return args[2] === "61" ? OVERLAP : APART;
33
+ return "";
34
+ },
35
+ async rehearse(cmd) { calls.push(["rehearse", cmd]); return { ok: true, code: 0 }; },
36
+ sleep: async () => {},
37
+ };
38
+ return { io, calls, writes };
39
+ }
40
+ const intakeLog = () => { const log = []; return { log, setIntake: async (p) => { log.push(p.paused); } }; };
41
+ const base = (io, extra = {}) => ({ io, repo: "o/r", def: "main", staging: "staging", config: { managed: true, preflight: { command: "node --test {files}", timeoutMs: 1000 } }, review: async () => ({ ok: true, verdict: "GATE_PASS" }), recordSync: async () => null, ...extra });
42
+
43
+ describe("merge-back (#5566)", () => {
44
+ it("a conflicting hunk yields a conflicted sync PR; the target has the file; blocks until covered, green and merged", async () => {
45
+ const { io } = fake({ conflict: true });
46
+ const rec = [];
47
+ const r = await syncStep(base(io, { recordSync: async (s) => rec.push(s), setIntake: intakeLog().setIntake }), { lane: "p0" });
48
+ assert.equal(r.pr, 50);
49
+ assert.equal(r.conflicted, true);
50
+ assert.ok(r.target.includes("src/conflict.js"));
51
+ assert.ok(r.target.includes("src/a.js"));
52
+ assert.equal(rec.length, 1);
53
+ assert.equal(r.blocks, true);
54
+ const sync = { ...r, conflicted: false, merged: false };
55
+ assert.equal(syncBlocksRelease({ sync }), true, "unmerged still blocks");
56
+ assert.equal(syncBlocksRelease({ sync: { ...sync, merged: true, preflight: { ok: true, covered: ["src/a.js"] } } }), true, "a preflight that misses the conflict file is unvalidated");
57
+ assert.equal(syncBlocksRelease({ sync: { ...sync, merged: true, preflight: { ok: true, covered: r.target } } }), false);
58
+ assert.equal(syncBlocksRelease({ sync: { ...sync, merged: true, preflight: { ok: false, covered: r.target } } }), true);
59
+ });
60
+
61
+ it("is false for train and p0 in the same state, and with no sync", () => {
62
+ const sync = { pr: 1, conflicted: true, target: ["a"], merged: false };
63
+ assert.equal(syncBlocksRelease({ sync }, "train"), false);
64
+ assert.equal(syncBlocksRelease({ sync }, "p0"), false);
65
+ assert.equal(syncBlocksRelease({ sync }, "release"), true);
66
+ assert.equal(syncBlocksRelease({}), false);
67
+ assert.equal(syncBlocksRelease(null), false);
68
+ });
69
+
70
+ it("flags a staging PR overlapping a lane hunk and not a disjoint one", async () => {
71
+ const { io } = fake();
72
+ const r = await syncStep(base(io), { lane: "train" });
73
+ assert.deepEqual(r.duplicates, [{ pr: 61, files: ["src/a.js"] }]);
74
+ assert.deepEqual(duplicateFixes(diffRanges(LANE_DIFF), [{ number: 9, hunks: diffRanges(APART) }]), []);
75
+ });
76
+
77
+ it("lists open milestone branches as stale-vs-main with the hazard note", async () => {
78
+ const { io } = fake({ milestones: ["milestone/a", "milestone/b"] });
79
+ const r = await syncStep(base(io), { lane: "p0" });
80
+ assert.deepEqual(r.milestones.map((m) => [m.branch, m.status]), [["milestone/a", "stale-vs-main"], ["milestone/b", "stale-vs-main"]]);
81
+ assert.match(r.milestones[0].note, /squash/);
82
+ assert.equal(staleMilestones({ git: () => { throw new Error("x"); } }).length, 0);
83
+ });
84
+
85
+ it("refuses squash and writes nothing", async () => {
86
+ const { io, calls } = fake();
87
+ const r = await syncStep(base(io, { policy: { merge: { method: "squash" } } }), { lane: "p0" });
88
+ assert.match(r.refused, /squash/);
89
+ assert.equal(calls.length, 0);
90
+ });
91
+
92
+ it("unmanaged: no io call at all", async () => {
93
+ const { io, calls } = fake();
94
+ const r = await syncStep(base(io, { config: { preflight: { command: "x {files}" } } }), { lane: "p0" });
95
+ assert.deepEqual(r, { skipped: true });
96
+ assert.deepEqual(await finishSync(base(io, { config: {} }), {}), { skipped: true });
97
+ assert.equal(calls.length, 0);
98
+ });
99
+
100
+ it("pauses intake on start and releases it on merge; a conflicted sync stays paused", async () => {
101
+ const { io, writes } = fake();
102
+ const a = intakeLog();
103
+ const r = await syncStep(base(io, { setIntake: a.setIntake, preflight: async (_c, { head, target }) => ({ ok: true, head, covered: target }) }), { lane: "p0" });
104
+ assert.deepEqual(a.log, [true]);
105
+ assert.equal(r.validated, true);
106
+ const f = await finishSync(base(io, { setIntake: a.setIntake }), r);
107
+ assert.equal(f.merged, true);
108
+ assert.deepEqual(a.log, [true, false]);
109
+ assert.ok(writes.some((w) => w[1] === "merge" && w.includes("--merge") && !w.includes("--squash")));
110
+ const c = fake({ conflict: true }), b = intakeLog();
111
+ const rc = await syncStep(base(c.io, { setIntake: b.setIntake }), { lane: "p0" });
112
+ const fc = await finishSync(base(c.io, { setIntake: b.setIntake }), rc);
113
+ assert.equal(fc.merged, false);
114
+ assert.deepEqual(b.log, [true]);
115
+ });
116
+
117
+ it("targeted preflight covers the target only when the command takes {files}", async () => {
118
+ const { io } = fake();
119
+ const t = ["a b.js", "c.js"];
120
+ const ok = await runTargetedPreflight({ io, config: { preflight: { command: "node --test {files}", timeoutMs: 1 } } }, { head: "h", target: t });
121
+ assert.deepEqual(ok.covered, t);
122
+ assert.match(ok.command, /'a b\.js' 'c\.js'/);
123
+ const bad = await runTargetedPreflight({ io, config: { preflight: { command: "npm test", timeoutMs: 1 } } }, { head: "h", target: t });
124
+ assert.equal(bad.ok, true);
125
+ assert.deepEqual(bad.covered, []);
126
+ assert.equal(syncValidated({ target: t, review: { ok: true }, preflight: bad }), false);
127
+ assert.deepEqual(targetSet({ conflicts: ["b"], changed: ["a", "b"] }), ["a", "b"]);
128
+ });
129
+ });
@@ -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
+ });