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,159 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * The service-scoped bug-fix train lane (#5570, epic #5549 Phase 5; I3, I4, Q9): a wave of single-service bug fixes branches from what
5
+ * is live (`laneStartGuard`, #5565), is re-checked against its real diff at CUT (`recomputeAtCut`: widening demotes the wave to the
6
+ * release lane or ejects the issue, narrowing is accepted), lands on the default branch with `Forge-Lane`/`Forge-Release`/`Forge-Epoch`
7
+ * trailers, then deploys through the `service` pipeline with the merge sha and unit set. The roll-set comes from `rollSet` (#5559),
8
+ * never from the classification record. Rung 1 of the ladder (#5563) runs on failure with the previous per-unit digests recorded first.
9
+ * A web/edge unit keeps the wave in VERIFYING until the injected `ctx.purge({units, sha})` seam reports `{ok: true}`.
10
+ */
11
+ import { readTarget, deployStep } from "./release-deploy.mjs";
12
+ import { runRollback, takeFence } from "./release-rollback.mjs";
13
+ import { claimDeploy, releaseDeploy, recordTrain } from "./release-ledger.mjs";
14
+ import { buildDispatchArgs } from "./release-control.mjs";
15
+ import { fenced, laneTrailers } from "./release-fence.mjs";
16
+ import { laneStartGuard } from "./release-p0.mjs";
17
+ import { rollSet } from "./release-plan.mjs";
18
+ import { matchesAny } from "./release-unitmap.mjs";
19
+ import { MIGRATION_PATHS } from "./release-config.mjs";
20
+
21
+ const json = (s) => { try { return JSON.parse(String(s ?? "")); } catch { return null; } };
22
+ const noMigration = (m) => !m || m === "none" || m === "false";
23
+
24
+ /**
25
+ * CUT-time recompute of one issue from its real diff against its classification record `{units, migrations, contract}`.
26
+ * @returns {{action: "keep"|"demote"|"eject", units: string[], migrations: boolean, contract: boolean, pipeline: string, widened: string[], narrowed: string[], why?: string}}
27
+ * Widening by a migration, a contract file or a pipeline that forces `full` demotes the wave; a new unit ejects the issue.
28
+ */
29
+ export function recomputeAtCut(policy, record, diff) {
30
+ const files = diff ?? [];
31
+ const roll = rollSet(policy, files);
32
+ const migrations = files.some((f) => matchesAny(MIGRATION_PATHS, f));
33
+ const contract = roll.contract.atomic;
34
+ const had = new Set(record?.units ?? []);
35
+ const widened = [], narrowed = [];
36
+ for (const u of roll.units) if (!had.has(u)) widened.push(`unit:${u}`);
37
+ for (const u of had) if (!roll.units.includes(u)) narrowed.push(`unit:${u}`);
38
+ if (migrations && noMigration(record?.migrations)) widened.push("migration");
39
+ if (contract && !record?.contract) widened.push("contract");
40
+ if (!migrations && !noMigration(record?.migrations)) narrowed.push("migration");
41
+ const base = { units: roll.units, migrations, contract, pipeline: roll.pipeline, widened, narrowed };
42
+ if (widened.includes("migration") || widened.includes("contract") || roll.pipeline === "full") {
43
+ return { ...base, action: "demote", why: roll.pipeline === "full" && !widened.length ? `the diff forces the full pipeline (${roll.forced.join(", ") || roll.no_service.join(", ")})` : `diff widened past the record: ${widened.join(", ")}` };
44
+ }
45
+ if (widened.length) return { ...base, action: "eject", why: `diff widened past the record: ${widened.join(", ")}` };
46
+ return { ...base, action: "keep" };
47
+ }
48
+
49
+ /** `train/<date>-<n>` from `branches.train` (placeholders `<date>`, `<n>`; default pattern when unset). */
50
+ export function trainBranch(policy, date, n) {
51
+ const name = String(policy?.branches?.train || "train/<date>-<n>").replace("<date>", date).replace("<n>", String(n));
52
+ return /^[A-Za-z0-9._/-]+$/.test(name) && !name.includes("..") ? name : null;
53
+ }
54
+
55
+ /** Units in dispatch order: contract producer first (atomic), then the rest sorted. */
56
+ const dispatchOrder = (roll) => [...roll.contract.order, ...roll.units.filter((u) => !roll.contract.order.includes(u))];
57
+
58
+ /**
59
+ * Run a train wave. `ctx`: {io, repo, def, state, save, config: {deploy, ...}, policy, actor, host, purge?, date, n};
60
+ * `wave`: [{issue, pr, record}]. @returns {Promise<{status: "live"|"verifying"|"demoted"|"rolled-back"|"refused"|"queued"|"blocked"|"stopped", reason?, branch?, ejected?, units?, rollback?}>}
61
+ */
62
+ export async function runReleaseTrain(ctx, wave) {
63
+ const { io, state, policy } = ctx;
64
+ const L = { claimDeploy, releaseDeploy, takeFence, recordTrain, deployStep, runRollback, ...(ctx.ledger ?? {}) }; // overridable for tests
65
+ const d = ctx.config.deploy, pipe = d?.pipelines?.service;
66
+ if (!pipe?.workflow) return { status: "refused", reason: "deploy.pipelines.service is not configured" };
67
+ const name = trainBranch(policy, ctx.date, ctx.n);
68
+ if (!name) return { status: "refused", reason: "invalid train branch name" };
69
+ // CUT: recompute each issue from its PR's real files before anything is created (I3, I4)
70
+ const kept = [], ejected = [];
71
+ for (const w of wave) {
72
+ const files = (json(await io.gh(["pr", "view", String(w.pr), "--repo", ctx.repo, "--json", "files"]))?.files ?? []).map((f) => f.path);
73
+ const r = recomputeAtCut(policy, w.record, files);
74
+ if (r.action === "demote") return { status: "demoted", reason: `#${w.issue}: ${r.why}; the wave moves to the release lane` };
75
+ if (r.action === "eject") ejected.push({ issue: w.issue, reason: r.why }); else kept.push({ ...w, files });
76
+ }
77
+ if (!kept.length) return { status: "demoted", reason: "every issue was ejected at CUT", ejected };
78
+ const files = [...new Set(kept.flatMap((w) => w.files))].sort();
79
+ const roll = rollSet(policy, files);
80
+ const units = dispatchOrder(roll);
81
+ const g = await laneStartGuard({ ...ctx, deploy: d, release: state.id }, "train");
82
+ if (g.refused) return { status: "refused", reason: g.refused };
83
+ const live = await readTarget(io, d.live_release_command);
84
+ const tr = (state.train ??= {});
85
+ Object.assign(tr, { branch: name, live: g.live, units, order: roll.contract.order, previous: Object.fromEntries(units.map((u) => [u, live?.images?.[u] ?? null])), state: "CREATED" }); // frozen rollback inputs (#5560)
86
+ ctx.save();
87
+ io.git(["push", "--quiet", "origin", `${g.live}:refs/heads/${name}`]);
88
+ for (const w of kept) {
89
+ io.git(["fetch", "--quiet", "origin", `+refs/heads/${name}:refs/remotes/origin/${name}`]);
90
+ const tip = io.git(["rev-parse", `refs/remotes/origin/${name}`]).trim();
91
+ const f = await fenced(ctx.fence, { action: "merge", key: `train:${name}:${w.pr}` }, async () => {
92
+ await io.gh(["pr", "edit", String(w.pr), "--repo", ctx.repo, "--base", name]);
93
+ return io.gh(["pr", "merge", String(w.pr), "--repo", ctx.repo, "--merge"]);
94
+ });
95
+ if (f.refused) return { status: "refused", branch: name, reason: f.refused };
96
+ tr.merged = [...(tr.merged ?? []), w.pr]; tr.tip = tip; ctx.save();
97
+ }
98
+ io.git(["fetch", "--quiet", "origin", `+refs/heads/${name}:refs/remotes/origin/${name}`]);
99
+ const regen = (policy?.contracts ?? []).filter((c) => c.regenerate && files.some((f) => matchesAny(c.paths, f)));
100
+ if (regen.length) { // contract wave: regenerate artefacts before the push so they are in the wave
101
+ io.git(["checkout", "-q", "-B", name, `origin/${name}`]);
102
+ for (const c of regen) {
103
+ const r = await io.rehearse(c.regenerate, { timeout: 600_000 });
104
+ if (!r?.ok) return { status: "refused", branch: name, reason: `contracts regenerate failed for ${c.producer}: ${String(r?.output ?? "").slice(-200)}` };
105
+ }
106
+ if (String(io.git(["status", "--porcelain"]) ?? "").trim()) { io.git(["add", "-A"]); io.git(["commit", "-q", "-m", `chore(train): regenerate contract artefacts for ${name}`]); io.git(["push", "--quiet", "origin", name]); }
107
+ }
108
+ const lctx = io.api ? { io, repo: ctx.repo, credential: "driver" } : null;
109
+ const dctx = { ...ctx, staging: ctx.def, git: io.git, config: { ...ctx.config, deployPipeline: "service", trainDispatch: { units } } };
110
+ try { buildDispatchArgs({ workflow: pipe.workflow, repo: ctx.repo, ref: ctx.def, inputs: { ...(pipe.inputs ?? {}), merge_sha: "0".repeat(40), units: units.join(",") } }); } catch (e) { return { status: "refused", branch: name, reason: e.message }; }
111
+ if (io.api) {
112
+ const fl = await L.takeFence(dctx, io.holder ?? `host-${process.pid}`);
113
+ if (fl.refused) return { status: "refused", reason: fl.refused };
114
+ dctx.fence = fl.fence;
115
+ }
116
+ if (lctx) {
117
+ const c = await L.claimDeploy(lctx, { release: state.id, actor: ctx.actor, reason: `train ${name}`, now: io.now?.() });
118
+ if (c.queued) return { status: "queued", branch: name, reason: c.queued };
119
+ if (c.lost) return { status: "refused", reason: "could not claim the deploy slot in the ledger" };
120
+ }
121
+ try { // landing: merge-then-deploy, the merge carries the lane trailers
122
+ const url = String(await io.gh(["pr", "create", "--repo", ctx.repo, "--base", ctx.def, "--head", name, "--title", `train: land ${name} on ${ctx.def}`, "--body", `Landing PR for train wave ${name}.`]) ?? "");
123
+ const pr = Number(/\/pull\/(\d+)/.exec(url)?.[1]) || null;
124
+ const head = io.git(["rev-parse", `refs/remotes/origin/${name}`]).trim();
125
+ const m = await fenced(dctx.fence, { action: "merge", key: `train:land:${name}:${head}` }, (epoch) => io.gh(["pr", "merge", String(pr), "--repo", ctx.repo, "--merge", "--match-head-commit", head, "--body", laneTrailers({ lane: "train", release: state.id, epoch })]));
126
+ if (m.refused) return { status: "refused", branch: name, reason: m.refused };
127
+ const v = json(await io.gh(["pr", "view", String(pr), "--repo", ctx.repo, "--json", "state,mergeCommit"]));
128
+ const sha = v?.mergeCommit?.oid;
129
+ if (!sha) return { status: "stopped", branch: name, reason: `landing PR #${pr} has no merge commit yet` };
130
+ Object.assign(tr, { landingPr: pr, merge: sha, state: "LANDED" });
131
+ state.steps["release-pr"] = { done: true, result: { pr, issues: kept.map((w) => w.issue) } };
132
+ state.steps["post-merge"] = { done: true, result: { merge: sha } };
133
+ state.lane = "train"; ctx.save();
134
+ if (lctx) await L.recordTrain(lctx, { release: state.id, state: "LANDED", branch: name, merge: sha, units }, io.now?.()); // also notes the rollout record is invalidated
135
+ const out = await L.deployStep(dctx);
136
+ if (out.blocked || out.stopped) {
137
+ const rolled = state.deploy?.target && state.deploy?.runId && !out.stopped;
138
+ const reason = out.reason ?? out.why;
139
+ if (!rolled) return { status: out.blocked ? "blocked" : "stopped", branch: name, reason };
140
+ const rb = await L.runRollback({ ...dctx, policy, actor: ctx.actor, host: ctx.host, trainDigests: tr.previous }, { reason, to: "flag" });
141
+ tr.rollback = { rung: rb.rung, ok: rb.ok, digests: tr.previous }; tr.state = "ROLLED_BACK"; ctx.save();
142
+ return { status: "rolled-back", branch: name, reason, rollback: rb };
143
+ }
144
+ if (out.skipped) return { status: "refused", reason: "deploy.pipelines is empty; nothing to deploy" };
145
+ const edge = units.filter((u) => ["web", "edge"].includes(policy?.units?.[u]?.surface));
146
+ if (edge.length) {
147
+ const p = ctx.purge ? await ctx.purge({ units: edge, sha }) : null;
148
+ if (!p?.ok) {
149
+ tr.state = "VERIFYING"; tr.verifying = ctx.purge ? `purge for ${edge.join(", ")} did not report success${p?.reason ? `: ${p.reason}` : ""}` : `no purge seam configured for web/edge unit(s) ${edge.join(", ")}`; ctx.save();
150
+ return { status: "verifying", branch: name, reason: tr.verifying, units, ...(ejected.length ? { ejected } : {}) };
151
+ }
152
+ }
153
+ tr.state = "LIVE"; ctx.save();
154
+ if (lctx) await L.recordTrain(lctx, { release: state.id, state: "LIVE", branch: name, merge: sha, units }, io.now?.());
155
+ return { status: "live", branch: name, units, landingPr: pr, ...(ejected.length ? { ejected } : {}) };
156
+ } finally {
157
+ if (lctx) await L.releaseDeploy(lctx, state.id).catch(() => null);
158
+ }
159
+ }
@@ -0,0 +1,139 @@
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 { recomputeAtCut, runReleaseTrain, trainBranch } from "./release-train.mjs";
6
+ import { rollSet } from "./release-plan.mjs";
7
+ import { laneTrailers } from "./release-fence.mjs";
8
+
9
+ const policy = {
10
+ branches: { train: "train/<date>-<n>" },
11
+ units: { api: { paths: ["svc/api/**"] }, web: { paths: ["svc/web/**"], surface: "web" }, worker: { paths: ["svc/worker/**"] }, fx: { paths: ["svc/fx/**"], service_pipeline: false } },
12
+ couplings: [{ paths: ["shared/**"], affects: ["api", "web", "worker"] }],
13
+ contracts: [{ producer: "api", consumers: ["web"], paths: ["contract/**"], additive_only: true, regenerate: "make gen" }],
14
+ };
15
+ const rec = { units: ["api"], migrations: "none", contract: false };
16
+
17
+ describe("recomputeAtCut (I3)", () => {
18
+ it("keeps an unchanged diff", () => assert.equal(recomputeAtCut(policy, rec, ["svc/api/a.js"]).action, "keep"));
19
+ it("demotes a migration file", () => { const r = recomputeAtCut(policy, rec, ["svc/api/a.js", "svc/api/migrations/001.sql"]); assert.equal(r.action, "demote"); assert.ok(r.widened.includes("migration")); });
20
+ it("demotes a contract file", () => assert.equal(recomputeAtCut(policy, rec, ["contract/x.json"]).action, "demote"));
21
+ it("ejects a new unit", () => { const r = recomputeAtCut(policy, rec, ["svc/api/a.js", "svc/worker/w.js"]); assert.equal(r.action, "eject"); assert.deepEqual(r.widened, ["unit:worker"]); });
22
+ it("demotes when the diff forces the full pipeline", () => assert.equal(recomputeAtCut(policy, { ...rec, units: ["fx"] }, ["svc/fx/a.js"]).action, "demote"));
23
+ it("accepts narrowing", () => { const r = recomputeAtCut(policy, { ...rec, units: ["api", "worker"] }, ["svc/api/a.js"]); assert.equal(r.action, "keep"); assert.deepEqual(r.narrowed, ["unit:worker"]); });
24
+ });
25
+
26
+ describe("roll-set property (I4)", () => {
27
+ it("the recomputed unit set covers every unit owning or coupled to a file; shared yields the full consumer set", () => {
28
+ const corpus = ["svc/api/a.js", "svc/web/b.js", "svc/worker/c.js", "shared/x.js", "docs/readme.md"];
29
+ for (const f of corpus) {
30
+ const r = recomputeAtCut(policy, { units: [] }, [f]);
31
+ const want = [...Object.entries(policy.units).filter(([, u]) => u.paths.some((p) => f.startsWith(p.replace("**", "")))).map(([id]) => id), ...(f.startsWith("shared/") ? ["api", "web", "worker"] : [])];
32
+ for (const u of want) assert.ok(r.units.includes(u), `${f} -> ${u}`);
33
+ }
34
+ assert.deepEqual(recomputeAtCut(policy, { units: [] }, ["shared/x.js"]).units, ["api", "web", "worker"]);
35
+ });
36
+ });
37
+
38
+ describe("trailers and branch", () => {
39
+ it("laneTrailers carries lane, release and epoch", () => assert.equal(laneTrailers({ lane: "train", release: "r1", epoch: 7 }), "Forge-Lane: train\nForge-Release: r1\nForge-Epoch: 7"));
40
+ it("trainBranch expands the pattern and rejects bad names", () => { assert.equal(trainBranch(policy, "2026-11-13", 2), "train/2026-11-13-2"); assert.equal(trainBranch({ branches: { train: "a b" } }, "d", 1), null); });
41
+ });
42
+
43
+ /** Fake io: a wave of PRs with the given files; records every git/gh call. Live == default (rev-parse returns one sha). */
44
+ function world({ files = { 11: ["svc/api/a.js"] }, dirty = false, regenOk = true } = {}) {
45
+ const calls = { git: [], gh: [], rehearse: [] };
46
+ const A = "a".repeat(40), B = "b".repeat(40);
47
+ const io = {
48
+ git: (a) => { calls.git.push(a); if (a[0] === "rev-parse") return `${A}\n`; if (a[0] === "status") return dirty ? " M gen.json" : ""; return ""; },
49
+ gh: async (a) => {
50
+ calls.gh.push(a);
51
+ if (a[0] === "pr" && a[1] === "view" && a.includes("files")) return JSON.stringify({ files: (files[a[2]] ?? []).map((path) => ({ path })) });
52
+ if (a[0] === "pr" && a[1] === "create") return "https://github.com/o/r/pull/99";
53
+ if (a[0] === "pr" && a[1] === "view") return JSON.stringify({ state: "MERGED", mergeCommit: { oid: B } });
54
+ return "";
55
+ },
56
+ rehearse: async (c) => { calls.rehearse.push(c); return c === "live" ? { ok: true, output: JSON.stringify({ sha: A, units: { api: "sha256:old-api", web: "sha256:old-web" } }) } : { ok: c === "make gen" ? regenOk : true, output: "" }; },
57
+ now: () => 0, sleep: async () => {},
58
+ };
59
+ return { io, calls };
60
+ }
61
+ const mkctx = (w, extra = {}, pol = policy) => {
62
+ const state = { id: "rel-1", steps: {} };
63
+ const seen = { deploy: [], rollback: [] };
64
+ const ctx = { io: w.io, repo: "o/r", def: "main", state, save() {}, policy: pol, date: "2026-11-13", n: 1, config: { deploy: { live_release_command: "live", pipelines: { service: { workflow: "svc.yml", inputs: {} } } } }, ...extra };
65
+ ctx.ledger = { deployStep: async (c) => { seen.deploy.push(c); return extra.deployResult ?? {}; }, ...(extra.ledger ?? {}) };
66
+ return { state, ctx, seen };
67
+ };
68
+ const wave = [{ issue: 5, pr: 11, record: rec }];
69
+
70
+ describe("runReleaseTrain", () => {
71
+ it("demotes at CUT before creating any branch", async () => {
72
+ const w = world({ files: { 11: ["svc/api/migrations/1.sql"] } }); const { ctx } = mkctx(w);
73
+ const r = await runReleaseTrain(ctx, wave);
74
+ assert.equal(r.status, "demoted");
75
+ assert.ok(!w.calls.git.some((a) => a[0] === "push"));
76
+ });
77
+ it("ejects a widened issue and demotes when none remain", async () => {
78
+ const w = world({ files: { 11: ["svc/api/a.js", "svc/worker/w.js"] } }); const { ctx } = mkctx(w);
79
+ const r = await runReleaseTrain(ctx, wave);
80
+ assert.equal(r.status, "demoted"); assert.equal(r.ejected[0].issue, 5);
81
+ });
82
+ it("creates train/<date>-<n> from live, lands with the lane trailers and dispatches merge sha + units", async () => {
83
+ const w = world(); const { ctx, state, seen } = mkctx(w);
84
+ const r = await runReleaseTrain(ctx, wave);
85
+ assert.equal(r.status, "live");
86
+ assert.deepEqual(w.calls.git.find((a) => a[0] === "push"), ["push", "--quiet", "origin", `${"a".repeat(40)}:refs/heads/train/2026-11-13-1`]);
87
+ const merge = w.calls.gh.find((a) => a[1] === "merge" && a.includes("--body"));
88
+ assert.equal(merge[merge.indexOf("--body") + 1], "Forge-Lane: train\nForge-Release: rel-1");
89
+ assert.equal(state.lane, "train"); assert.deepEqual(state.train.previous, { api: "sha256:old-api" });
90
+ assert.equal(state.steps["post-merge"].result.merge, "b".repeat(40));
91
+ assert.deepEqual(seen.deploy[0].config.trainDispatch, { units: ["api"] });
92
+ assert.equal(seen.deploy[0].config.deployPipeline, "service");
93
+ });
94
+ it("a contract wave orders the producer first and runs regenerate before the push", async () => {
95
+ const w = world({ files: { 11: ["contract/x.json"] }, dirty: true });
96
+ const { ctx, state } = mkctx(w);
97
+ const r = await runReleaseTrain(ctx, [{ issue: 5, pr: 11, record: { units: ["api", "web"], migrations: "none", contract: true } }]);
98
+ assert.deepEqual(state.train.order, ["api", "web"]); assert.deepEqual(state.train.units, ["api", "web"]);
99
+ assert.ok(w.calls.rehearse.includes("make gen"));
100
+ const ci = w.calls.git.findIndex((a) => a[0] === "commit"), pi = w.calls.git.findIndex((a, i) => a[0] === "push" && i > ci);
101
+ assert.ok(ci >= 0 && pi > ci, "regenerate commit precedes the push");
102
+ assert.equal(r.status, "verifying"); // web is a web surface and no purge seam is set
103
+ });
104
+ it("a failing regenerate refuses", async () => {
105
+ const w = world({ files: { 11: ["contract/x.json"] }, regenOk: false }); const { ctx } = mkctx(w);
106
+ const r = await runReleaseTrain(ctx, [{ issue: 5, pr: 11, record: { units: ["api", "web"], contract: true } }]);
107
+ assert.equal(r.status, "refused");
108
+ });
109
+ it("on a deploy failure invokes rung 1 (flag) with the recorded digests", async () => {
110
+ const w = world(); const calls = [];
111
+ const { ctx, state } = mkctx(w, { deployResult: { blocked: true, reason: "smoke failed" } });
112
+ state.deploy = { target: { sha: "a".repeat(40) }, runId: 7, merge: "b".repeat(40) };
113
+ ctx.ledger.runRollback = async (c, a) => { calls.push({ digests: c.trainDigests, to: a.to }); return { rung: "flag", ok: true }; };
114
+ const r = await runReleaseTrain(ctx, wave);
115
+ assert.equal(r.status, "rolled-back");
116
+ assert.deepEqual(calls, [{ digests: { api: "sha256:old-api" }, to: "flag" }]);
117
+ });
118
+ it("refuses without deploy.pipelines.service", async () => {
119
+ const w = world(); const { ctx } = mkctx(w); ctx.config.deploy.pipelines = {};
120
+ assert.equal((await runReleaseTrain(ctx, wave)).status, "refused");
121
+ });
122
+ });
123
+
124
+ describe("web wave purge gate", () => {
125
+ const webWave = [{ issue: 5, pr: 11, record: { units: ["web"], migrations: "none", contract: false } }];
126
+ const run = (purge) => { const w = world({ files: { 11: ["svc/web/a.js"] } }); const m = mkctx(w, { purge }); return runReleaseTrain(m.ctx, webWave).then((r) => ({ r, state: m.state })); };
127
+ it("without a purge seam stays VERIFYING and never reaches live", async () => {
128
+ const { r, state } = await run(undefined);
129
+ assert.equal(r.status, "verifying"); assert.match(r.reason, /no purge seam/); assert.equal(state.train.state, "VERIFYING");
130
+ });
131
+ it("a failing purge stays VERIFYING with the reason", async () => {
132
+ const { r } = await run(async () => ({ ok: false, reason: "cdn 503" }));
133
+ assert.equal(r.status, "verifying"); assert.match(r.reason, /cdn 503/);
134
+ });
135
+ it("a successful purge proceeds to live", async () => {
136
+ let got; const { r, state } = await run(async (a) => { got = a; return { ok: true }; });
137
+ assert.equal(r.status, "live"); assert.deepEqual(got.units, ["web"]); assert.equal(state.train.state, "LIVE");
138
+ });
139
+ });
@@ -12,6 +12,7 @@ import { existsSync, mkdirSync, readFileSync, readdirSync } from "node:fs";
12
12
  import { execFileSync } from "node:child_process";
13
13
  import { homedir } from "node:os";
14
14
  import { join } from "node:path";
15
+ import { createInterface } from "node:readline";
15
16
  import { writeAtomic, assertDiskPath, batchRoot, listBatches, openBatch, isLaneAlive } from "./batch.mjs";
16
17
  import { readBranches, DEFAULT_STAGING_BRANCH } from "./lane.mjs";
17
18
  import { ghRunner } from "./issuewatch.mjs";
@@ -24,7 +25,7 @@ import { rehearsalStep, parseRehearsalConfig } from "./release-rehearsal.mjs";
24
25
  import { budgetReportLine, releaseRuns, detectBudget, readCiPolicy } from "./ci-budget.mjs";
25
26
  import { parseNightlyConfig, readNightly, blocksRelease, fileNightlyRed } from "./release-nightly.mjs";
26
27
  import { parseBudgetConfig, applyOnExceed, waveReport, trailingMedian, historyFromRoot, gateHistoryFromRoot, releaseMinutes } from "./release-minutes.mjs";
27
- import { cutSnapshot, writeRecord, checkChain, verifyRelease, DEFAULT_PATTERN } from "./release-snapshot.mjs";
28
+ import { cutSnapshot, writeRecord, checkChain, verifyRelease, defaultBehind, DEFAULT_PATTERN } from "./release-snapshot.mjs";
28
29
  import { createReleaseLedger, writeRelease, readLedger, acquireLease, heartbeat } from "./release-ledger.mjs";
29
30
  import { fenced, epochTrailer } from "./release-fence.mjs";
30
31
  import { holdCheck, exemptionsSection, runControl, VERBS as CONTROL_VERBS } from "./release-control.mjs";
@@ -33,6 +34,8 @@ import { readActive } from "./release-ledger.mjs";
33
34
  import { statusFromCli, policyFromYaml } from "./release-status.mjs";
34
35
  import { parseFixConfig } from "./release-fixloop.mjs";
35
36
  import { hostPreflightStep, markReadyStep, parsePreflightConfig } from "./release-preflight.mjs";
37
+ import { roleRefusal } from "./release-credentials.mjs";
38
+ import { mergeGuard } from "./release-gate.mjs";
36
39
 
37
40
  export const RELEASE_STEPS = ["preflight", "host-preflight", "release-pr", "review", "fixes", "mark-ready", "rehearsal", "promotion", "post-merge", "deploy"];
38
41
  const ID_RE = /^r\d{8}-\d{6}-\d+$/;
@@ -79,6 +82,14 @@ const off2 = (v) => ["false", "off", "no", "0", ""].includes(String(v ?? "").tri
79
82
  * (p0 never). Every read is best effort: unreadable facts proceed. @returns {{blocked?, reason?, ciMode?}}
80
83
  */
81
84
  export async function managedGate({ io, repo, config, lane, root }) {
85
+ if (lane === "release" && config.managed && io.api) { // #5566: a conflicted or unvalidated merge-back holds the release (never trains or p0)
86
+ try {
87
+ const { syncBlocksRelease } = await import("./release-mergeback.mjs");
88
+ const { readActive } = await import("./release-ledger.mjs");
89
+ const active = await readActive({ io, repo, credential: "driver" });
90
+ if (syncBlocksRelease(active, lane)) return { blocked: true, reason: `merge-back sync PR #${active.sync?.pr ?? "?"} is ${active.sync?.conflicted ? "conflicted" : "unvalidated or unmerged"}; merge it green before a release starts` };
91
+ } catch { /* best effort: an unreadable ledger proceeds */ }
92
+ }
82
93
  if (config.nightly) {
83
94
  try {
84
95
  const n = await readNightly({ gh: (a) => io.gh(a), repo, cfg: config.nightly, now: io.now() });
@@ -286,6 +297,11 @@ async function promotionStep(ctx) {
286
297
  const chain = checkChain({ git: io.git, record: state.release, sha: head, staging: ctx.staging, exact: true });
287
298
  if (!chain.ok) return { stopped: true, why: `release head ${head} is not snapshot + recorded cherry-picks: ${chain.why}`, head };
288
299
  }
300
+ if (state.release && ctx.config.managed && io.git) { // #5565: a p0 may have landed on the default branch after the cut; the merge refuses until it is in the head (recut brings it in)
301
+ let behind = false; try { behind = defaultBehind({ git: io.git, def: ctx.def, head }); } catch { /* unreadable: the chain check above already read the repo */ }
302
+ if (behind) return { stopped: true, why: `${ctx.def} is not an ancestor of release head ${String(head).slice(0, 8)}: a p0 landed after the cut; recut the release (release.fix_mode: recut) to merge ${ctx.def} in`, head };
303
+ }
304
+ if (ctx.fence) return managedPromotion(ctx, { pr, head });
289
305
  let gate = await gateState({ io, repo, pr, head });
290
306
  if (gate.marker !== "pass") return { stopped: true, why: `no FORGE:GATE_PASS on #${pr} (last marker: ${gate.marker ?? "none"})`, head };
291
307
  if (gate.deployGate !== "success" && gate.deployGate !== "failure") gate = await awaitGate({ io, repo, pr, head, gate, fence: ctx.fence });
@@ -303,6 +319,28 @@ async function promotionStep(ctx) {
303
319
  return { merged: true, head, gate };
304
320
  }
305
321
 
322
+ const MERGE_FLAG = { "merge-commit": "--merge", squash: "--squash", rebase: "--rebase" };
323
+
324
+ /** #5561 (I1, I12): the managed merge. The gate is the `forge/release-gate` check run from the configured app, never the GATE_PASS marker. */
325
+ export async function managedPromotion(ctx, { pr, head }) {
326
+ const { io, repo, state, opts } = ctx;
327
+ const refusedRole = roleRefusal(ctx.fence.lctx.credential, "merge", { branch: ctx.def });
328
+ if (refusedRole) return { refused: refusedRole, head };
329
+ const { readPolicy } = await import("./release-config.mjs"); // lazy: release-config imports this module
330
+ const policy = readPolicy({ io, defaultBranch: ctx.def }).policy;
331
+ const g = await (io.mergeGuard ?? mergeGuard)({ io, repo, head, state, policy, staging: ctx.staging });
332
+ if (!g.ok) {
333
+ if (policy && /failure|not green/.test(g.why)) await rerunInfraFlakes({ io, repo, head, fence: ctx.fence, policy }); // #5568: transient infra only; the next resume re-checks the guard
334
+ return { stopped: true, why: `merge guard: ${g.why}`, head };
335
+ }
336
+ const flag = MERGE_FLAG[policy.merge?.method ?? "merge-commit"];
337
+ const cmd = `gh pr merge ${pr} --repo ${repo} ${flag} --match-head-commit ${head}`;
338
+ if (!opts.merge && !ctx.config.autoMerge) { io.print(`Release gate passed on #${pr}. Merge when ready:\n ${cmd}`); return { stopped: true, why: "release gate passed; promotion is opt-in (--merge or release.auto_merge)", cmd, head }; }
339
+ const f = await fenced(ctx.fence, { action: "merge", key: `merge:${pr}:${head}` }, (epoch) => io.gh(["pr", "merge", String(pr), "--repo", repo, flag, "--match-head-commit", head, "--body", [`Forge-Release: ${state.id}`, ...(epoch != null ? [epochTrailer(epoch)] : [])].join("\n")]));
340
+ if (f.refused) return { refused: f.refused, head };
341
+ return { merged: true, head };
342
+ }
343
+
306
344
  const OPTIONAL_STEPS = ["host-preflight", "mark-ready", "deploy"];
307
345
 
308
346
  const STEP_FNS = {
@@ -355,12 +393,14 @@ export async function runRelease({ io, repo, opts = {}, config = {}, branches =
355
393
  ctx.fence = { lctx, lease: l.lease, record, now: () => new Date(io.now()).toISOString() };
356
394
  return null;
357
395
  };
358
- 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) };
396
+ const ctx = { laneStrip: [], io, repo, opts: state.opts, config, state, staging: branches.staging || DEFAULT_STAGING_BRANCH, def: branches.default || "main", git: io.git, save: () => rel.save(state) };
397
+ ctx.rollbackTrigger = (t) => { state.rollbackPending = { reason: t.reason, sha: t.sha }; rel.save(state); io.print?.(`release ${id}: rollback trigger recorded; run \`forgedock release rollback ${id} --reason "${String(t.reason).replace(/"/g, "'")}"\``); }; // #5563
359
398
  if (lctx) { // #5567: the fix loop's HELD goes through the control path; an infra-flake rerun through the fenced rerun
360
399
  ctx.hold = (ask) => runControl("hold", [id, "--reason", ask], { io, repo, policy: null, actor: holder, host: holder });
361
400
  ctx.rerunInfra = ({ head }) => rerunInfraFlakes({ io, repo, head, fence: ctx.fence, policy: config.policy });
362
401
  }
363
402
  ctx.save();
403
+ if (lctx && io.git) { const { readPolicy } = await import("./release-config.mjs"); ctx.laneStrip = readPolicy({ io, defaultBranch: ctx.def }).policy?.credentials?.lane_env_strip ?? []; }
364
404
  let out;
365
405
  try {
366
406
  for (const step of RELEASE_STEPS) {
@@ -397,7 +437,8 @@ export async function runRelease({ io, repo, opts = {}, config = {}, branches =
397
437
  try {
398
438
  if (tf && existsSync(tf) && existsSync(join(process.cwd(), ".forge/gates.yaml"))) {
399
439
  const recs = (await import("./release-gates.mjs")).parseTelemetry(readFileSync(tf, "utf8"));
400
- if (recs.length) state.gates = [...(state.gates ?? []), ...recs];
440
+ const gs = state.regates?.at(-1)?.gate_sha; // #5584: which gate-script sha evaluated these gates
441
+ if (recs.length) state.gates = [...(state.gates ?? []), ...recs.map((r) => (gs && !r.gate_sha ? { ...r, gate_sha: gs } : r))];
401
442
  }
402
443
  } catch { /* best effort */ }
403
444
  }
@@ -437,7 +478,7 @@ export function realReleaseIo({ env = process.env, exec = execFileSync, print =
437
478
  }
438
479
 
439
480
  const flag = (argv, f) => { const i = argv.indexOf(f); return i >= 0 ? argv[i + 1] : null; };
440
- export const RELEASE_USAGE = "usage: forgedock release [--repo owner/repo] [--merge] [--watch] [--resume <id>] | forgedock release verify <sha | release id> [--repo owner/repo] | forgedock release status [<id>] [--watch] [--interval s] [--json] | forgedock release explain <id | #issue | PR> [--json] | forgedock release check-config [--ref <git ref>] | forgedock release init | forgedock release control <hold|resume|cancel|lane|exempt|freeze|unfreeze> ... --reason <text> [--repo owner/repo] [--json] (the verbs also work as `forgedock release <verb>`) | forgedock release gates [check [--base <ref>] | demote] [--since 30d] [--json] | forgedock release gates record <release-id> --file <jsonl> | forgedock release report";
481
+ export const RELEASE_USAGE = "usage: forgedock release [--repo owner/repo] [--merge] [--watch] [--resume <id>] | forgedock release p0 <#issue | --branch B> [--units a,b] [--preempt] [--yes] | forgedock release verify <sha | release id> [--repo owner/repo] | forgedock release recover <release id> [--repo owner/repo] | forgedock release rollback <release id> --reason <text> [--to flag|unit|full] [--later id,id] [--repo owner/repo] [--json] | forgedock release plan [--lane auto|train|release|p0] [--milestone <slug>] [--issues N,N] [--repo owner/repo] [--json] | forgedock release start [--plan <id|hash>] [--approve] [--wave train|release|all] [--milestone <slug>] [--repo owner/repo] | forgedock release go <id> [--plan|--merge|--activate <key>] [--repo owner/repo] | forgedock release status [<id>] [--watch] [--interval s] [--json] | forgedock release explain <id | #issue | PR> [--json] | forgedock release check-config [--ref <git ref>] [--coverage] | forgedock release init [--conductor] | forgedock release control <hold|resume|cancel|lane|exempt|freeze|unfreeze> ... --reason <text> [--repo owner/repo] [--json] (the verbs also work as `forgedock release <verb>`) | forgedock release gates [check [--base <ref>] | demote] [--since 30d] [--json] | forgedock release gates record <release-id> --file <jsonl> | forgedock release report";
441
482
 
442
483
  /** `forgedock release ...`; @returns the process exit code (0 done or stopped at GATE_PASS, 1 refused, 3 blocked on a manual step). */
443
484
  export async function releaseFromCli(argv, deps = {}) {
@@ -456,6 +497,82 @@ export async function releaseFromCli(argv, deps = {}) {
456
497
  const r = await verifyReleaseById({ io, state, save: () => rel.save(state), def, policy: readPolicy({ io, defaultBranch: def, cwd }).policy, lane: flag(argv, "--lane") ?? state.lane });
457
498
  return r.verified ? 0 : BLOCKED_EXIT;
458
499
  }
500
+ if (argv[0] === "plan") { // #5559: the read-only release planner; loaded lazily like the other managed-release modules
501
+ const { planFromCli } = await import("./release-plan.mjs");
502
+ const { readPolicy } = await import("./release-config.mjs");
503
+ const def = readBranches(cwd).default || "main", rp = readPolicy({ io, defaultBranch: def, cwd });
504
+ let raw = ""; try { raw = readFileSync(join(cwd, "forge.yaml"), "utf8"); } catch { /* no forge.yaml: defaults */ }
505
+ const rc = readReleaseConfig(raw), repo = flag(argv, "--repo") ?? JSON.parse(String(await io.gh(["repo", "view", "--json", "nameWithOwner"]))).nameWithOwner;
506
+ const ctx = { io, repo, credential: "driver" };
507
+ return planFromCli([...argv.slice(1).filter((a, i, all) => a !== "--repo" && all[i - 1] !== "--repo"), "--repo", repo], {
508
+ io, policy: rp.policy, policySha: rp.sha, managed: !!rc.managed, newId: newReleaseId(io.now()), history: historyFromRoot(releaseRoot(env)), budget: { cfg: parseBudgetConfig(parseForgeYaml(raw)?.budget) },
509
+ readLanes: rc.managed && io.api ? async () => (await readActive(ctx).catch(() => ({}))).lanes : undefined,
510
+ ledger: async ({ id, plan }) => { await createReleaseLedger(ctx, id, { v: 1, id, repo, kind: "plan", status: "planned", plan }); },
511
+ });
512
+ }
513
+ if (argv[0] === "start" || argv[0] === "go") { // #5571: the managed runner and the typed approval; loaded lazily like the other managed-release modules
514
+ const { startFromCli, goFromCli } = await import("./release-start.mjs");
515
+ const { readPolicy } = await import("./release-config.mjs");
516
+ const { runReleaseTrain } = await import("./release-train.mjs");
517
+ const { verifyReleaseById } = await import("./release-verify.mjs");
518
+ const { syncValidated } = await import("./release-mergeback.mjs");
519
+ const { PLAN_LABEL } = await import("./release-plan.mjs");
520
+ const def = readBranches(cwd).default || "main", rp = readPolicy({ io, defaultBranch: def, cwd });
521
+ let raw = ""; try { raw = readFileSync(join(cwd, "forge.yaml"), "utf8"); } catch { /* no forge.yaml: defaults */ }
522
+ const rc = readReleaseConfig(raw), rest = argv.slice(1), repo = flag(rest, "--repo") ?? JSON.parse(String(await io.gh(["repo", "view", "--json", "nameWithOwner"]))).nameWithOwner;
523
+ const ctx = { io, repo, credential: "driver" }, root = releaseRoot(env), managed = !!rc.managed && !!io.api;
524
+ const ledger = { read: (id) => readLedger(ctx, id), create: (id, st) => createReleaseLedger(ctx, id, st), write: (id, st, head) => writeRelease(ctx, id, st, head), list: async () => (await (await import("./release-ledger.mjs")).listLedgers({ io, repo })).map((l) => l.id ?? l) };
525
+ const tracker = async () => JSON.parse(String(await io.gh(["issue", "list", "--repo", repo, "--label", PLAN_LABEL, "--state", "open", "--json", "number,comments"])) || "[]");
526
+ const post = async (body) => { const t = (await tracker())[0]; if (!t) throw new Error(`no open issue labelled ${PLAN_LABEL} to carry the decision`); await io.gh(["issue", "comment", String(t.number), "--repo", repo, "--body", body]); };
527
+ if (argv[0] === "go") return goFromCli(rest, { io, ledger, post, managed, actor: deps.actor });
528
+ const id = newReleaseId(io.now()), state = { id };
529
+ const prOf = async (n) => Number(JSON.parse(String(await io.gh(["pr", "list", "--repo", repo, "--state", "open", "--search", `#${n} in:body`, "--json", "number"])) || "[]")[0]?.number) || null;
530
+ const { takeFence } = await import("./release-rollback.mjs"), { readRollouts, detectNewOffKeys } = await import("./activation.mjs");
531
+ const rollouts = readRollouts(cwd);
532
+ const takeWaveFence = async (st) => { // the wave lease; intents land in the plan state; the lease comment goes on the plan tracker
533
+ const t = (await tracker())[0];
534
+ return takeFence({ io, repo, state: { id: st.id, steps: { "release-pr": { result: { pr: t?.number } } }, intents: (st.intents ??= []) }, save: () => {} }, io.holder ?? `host-${process.pid}`);
535
+ };
536
+ const runners = {
537
+ rollouts: async (w, plan) => { // feature wave: new default-off rollout keys come from the wave PRs' diffs of the forge.yaml rollouts.files registry
538
+ const feature = w.issues.some((n) => String(plan.issues?.[n]?.reason ?? "").startsWith("feature"));
539
+ if (!feature || !rollouts) return { feature, added: [], offKeys: [] };
540
+ const diffs = await Promise.all(w.issues.map(async (n) => { const pr = await prOf(n); return pr ? String(await io.gh(["pr", "diff", String(pr), "--repo", repo])) : ""; }));
541
+ const offKeys = detectNewOffKeys(rollouts, diffs.join("\n"));
542
+ return { feature, added: offKeys, offKeys };
543
+ },
544
+ train: async (w) => runReleaseTrain({ io, repo, def, state, save: () => {}, config: { deploy: rp.policy?.deploy }, policy: rp.policy, actor: deps.actor, host: deps.host, date: new Date(io.now()).toISOString().slice(0, 10), n: 1 }, await Promise.all(w.issues.map(async (n) => ({ issue: n, pr: await prOf(n), record: {} })))),
545
+ release: async (w, o) => { const r = await runRelease({ io, repo, opts: { merge: true, lane: "release" }, config: { ...rc, policy: rp.policy, deploy: rp.policy?.deploy, verify: rp.policy?.verify, verifyRisk: o.soak }, branches: readBranches(cwd), root, id }); return { status: r.status === "done" ? "done" : r.status, reason: r.reason }; },
546
+ verify: async (w, r) => ({ verified: r.status === "done" || (await verifyReleaseById({ io, state, save: () => {}, def, policy: rp.policy, lane: "train" })).verified }),
547
+ mergeback: async () => ({ validated: syncValidated(state.sync) || state.sync == null }),
548
+ };
549
+ return startFromCli(rest, { io, policy: rp.policy, policySha: rp.sha, managed, newId: id, history: historyFromRoot(root), budget: { cfg: parseBudgetConfig(parseForgeYaml(raw)?.budget) }, ledger, runners, takeFence: takeWaveFence,
550
+ decisions: async () => (await tracker()).flatMap((i) => (i.comments ?? []).map((c) => ({ author: c.author?.login, body: c.body }))), post, actor: deps.actor });
551
+ }
552
+ if (argv[0] === "rollback") { // #5563: the rollback ladder; loaded lazily like the other managed-release modules
553
+ const { rollbackFromCli } = await import("./release-rollback.mjs");
554
+ const { readPolicy } = await import("./release-config.mjs");
555
+ if (!ID_RE.test(String(argv[1] ?? ""))) throw new Error(`rollback needs a release id; ${RELEASE_USAGE}`);
556
+ const def = readBranches(cwd).default || "main";
557
+ return rollbackFromCli(argv.slice(1), { io, rel: openRelease(releaseRoot(env), argv[1]), policy: readPolicy({ io, defaultBranch: def, cwd }).policy, def, actor: deps.actor, host: deps.host });
558
+ }
559
+ if (argv[0] === "p0") { // #5565: the managed P0 lane; loaded lazily like the other managed-release modules
560
+ const { p0FromCli } = await import("./release-p0.mjs");
561
+ const { readPolicy } = await import("./release-config.mjs");
562
+ const def = readBranches(cwd).default || "main", policy = readPolicy({ io, defaultBranch: def, cwd }).policy;
563
+ let raw = ""; try { raw = readFileSync(join(cwd, "forge.yaml"), "utf8"); } catch { /* no forge.yaml: defaults */ }
564
+ const rc = readReleaseConfig(raw), id = newReleaseId(io.now());
565
+ const config = { ...rc, deploy: policy?.deploy, verify: policy?.verify, verifySoak: policy?.lanes?.p0?.soak_min };
566
+ const ask = deps.ask ?? ((q) => new Promise((res) => { const rl = createInterface({ input: process.stdin, output: process.stdout }); rl.question(q, (a) => { rl.close(); res(a); }); }));
567
+ return p0FromCli(argv.slice(1), { io, rel: openRelease(releaseRoot(env), id), id, config, policy, def, actor: deps.actor, host: deps.host, ask });
568
+ }
569
+ if (argv[0] === "recover") { // #5564: the conductor's host-less recovery; loaded lazily like the other managed-release modules
570
+ const { recoverFromCli } = await import("./release-conductor.mjs");
571
+ const { readPolicy } = await import("./release-config.mjs");
572
+ if (!ID_RE.test(String(argv[1] ?? ""))) throw new Error(`recover needs a release id; ${RELEASE_USAGE}`);
573
+ const def = readBranches(cwd).default || "main";
574
+ return recoverFromCli(argv.slice(1), { io, policy: readPolicy({ io, defaultBranch: def, cwd }).policy ?? {}, def, actor: deps.actor ?? env.GITHUB_ACTOR, host: deps.host });
575
+ }
459
576
  if (argv[0] === "gates") { // #5583: catalogue, telemetry report, admission check; release-gates is loaded lazily
460
577
  const g = await import("./release-gates.mjs");
461
578
  const { readPolicy } = await import("./release-config.mjs");
@@ -485,7 +602,9 @@ export async function releaseFromCli(argv, deps = {}) {
485
602
  const { controlFromCli } = await import("./release-control.mjs");
486
603
  const { readPolicy } = await import("./release-config.mjs");
487
604
  const policy = readPolicy({ io, defaultBranch: readBranches(cwd).default || "main", cwd }).policy;
488
- return controlFromCli(cv, argv.slice(argv[0] === "control" ? 2 : 1), { io, policy, actor: deps.actor, host: deps.host });
605
+ const cargs = argv.slice(argv[0] === "control" ? 2 : 1);
606
+ const rel = cv === "regate" && cargs[0] && ID_RE.test(cargs[0]) ? openRelease(releaseRoot(env), cargs[0]) : undefined; // #5584: regate reads the release's recorded deploy target
607
+ return controlFromCli(cv, cargs, { io, policy, actor: deps.actor, host: deps.host, rel });
489
608
  }
490
609
  if (argv[0] === "control") throw new Error(`unknown control verb ${argv[1] ?? ""}; ${RELEASE_USAGE}`);
491
610
  const unknown = argv.filter((a, i) => a.startsWith("--") && !["--repo", "--merge", "--watch", "--resume", "--lane", "--interval"].includes(a) && !(argv[i - 1] === "--resume" || argv[i - 1] === "--repo" || argv[i - 1] === "--lane" || argv[i - 1] === "--interval"));
@@ -505,6 +624,9 @@ export async function releaseFromCli(argv, deps = {}) {
505
624
  const { readPolicy } = await import("./release-config.mjs");
506
625
  const pol = readPolicy({ io, defaultBranch: readBranches(cwd).default || "main", cwd }).policy;
507
626
  if (pol?.deploy) config.deploy = pol.deploy;
627
+ const { conductorGuard } = await import("./release-conductor.mjs"); // #5564: a configured conductor must exist on the default branch
628
+ const noConductor = conductorGuard({ io, policy: pol, def: readBranches(cwd).default || "main" });
629
+ if (noConductor) { io.print(`release: refused: ${noConductor}`); return 1; }
508
630
  config.policy = pol; config.fix = parseFixConfig(pol?.ci?.fix); // #5567: ci.fix.max_rounds / co_start / full_run_workflow
509
631
  config.deployPipeline = pol?.lanes?.[flag(argv, "--lane")]?.pipeline ?? "full"; // service/hotfix lanes dispatch with unit inputs
510
632
  if (pol?.verify) { // #5562: verification layers; risk class picks the soak minutes
@@ -58,6 +58,17 @@ describe("unmanaged release carries no epoch (#5553)", () => {
58
58
  });
59
59
  });
60
60
 
61
+ describe("legacy managed promotion without a fence (#5561 regression)", () => {
62
+ it("a failing deploy-gate still reads the policy to rerun infra flakes (as before the managed split)", async () => {
63
+ const mod = await import("./release.mjs");
64
+ const io = fakeIo({ gate: "failure" });
65
+ const shown = [];
66
+ io.git = (a) => { if (a[0] === "show") shown.push(a[1]); throw new Error("no git"); };
67
+ await mod.runRelease({ io, repo: REPO, root: tmp(), mounts: DISK, id: newReleaseId(), opts: { merge: true }, config: { managed: true }, branches: { staging: "staging", default: "main" }, steps: mod.withStubs({ review: ok, fixes: ok, "post-merge": ok }) });
68
+ assert.ok(shown.some((x) => x.startsWith("origin/main:")), "policy read for the flake rerun");
69
+ });
70
+ });
71
+
61
72
  describe("release job (#5211)", () => {
62
73
  const promote = async (world, { opts = {}, config = {} } = {}) => {
63
74
  const io = fakeIo(world), root = tmp(), id = newReleaseId();
@@ -489,3 +500,72 @@ describe("release control routing (#5556)", () => {
489
500
  await assert.rejects(releaseFromCli(["control", "nope"], { io: { print() {}, gh: async () => "" }, cwd: tmp() }), /unknown control verb/);
490
501
  });
491
502
  });
503
+
504
+ describe("managed merge (#5561)", () => {
505
+ const LEASE = { holder: "A", epoch: 3 };
506
+ const fence = (lctxCred = "driver") => ({ lctx: { repo: REPO, credential: lctxCred, io: { api: async (_m, path) => {
507
+ if (/active\.json/.test(path)) return { content: Buffer.from(JSON.stringify({ epoch: 3, lease: LEASE })).toString("base64") };
508
+ throw Object.assign(new Error("404 Not Found"), { status: 404 });
509
+ } } }, lease: { ...LEASE, release: "r1" }, now: () => "t", record: async () => {} });
510
+ const mk = (over = {}, method) => {
511
+ const merges = [];
512
+ const io = { print() {}, git: () => `schema: 1\nmerge: {method: ${method ?? "merge-commit"}}\n`, gh: async (a) => { merges.push(a); return ""; }, mergeGuard: async () => ({ ok: true }), ...over };
513
+ return { merges, ctx: { io, repo: REPO, state: { id: "r20240101-000000-1" }, opts: { merge: true }, config: { managed: true }, def: "main", staging: "staging", fence: fence() } };
514
+ };
515
+ it("merge carries --match-head-commit, Forge-Release and Forge-Epoch trailers", async () => {
516
+ const { ctx, merges } = mk();
517
+ const { managedPromotion } = await import("./release.mjs");
518
+ assert.deepEqual(await managedPromotion(ctx, { pr: 7, head: HEAD }), { merged: true, head: HEAD });
519
+ assert.deepEqual(merges[0], ["pr", "merge", "7", "--repo", REPO, "--merge", "--match-head-commit", HEAD, "--body", "Forge-Release: r20240101-000000-1\nForge-Epoch: 3"]);
520
+ });
521
+ it("merge.method picks the gh flag", async () => {
522
+ const { managedPromotion } = await import("./release.mjs");
523
+ for (const [m, flag] of [["squash", "--squash"], ["rebase", "--rebase"]]) {
524
+ const { ctx, merges } = mk({}, m);
525
+ await managedPromotion(ctx, { pr: 7, head: HEAD });
526
+ assert.ok(merges[0].includes(flag), m);
527
+ }
528
+ });
529
+ it("a refused guard (moved head, stale approval, no gate status, unreadable gate) merges nothing", async () => {
530
+ const { managedPromotion } = await import("./release.mjs");
531
+ const { ctx, merges } = mk({ mergeGuard: async () => ({ ok: false, why: "no forge/release-gate on x" }) });
532
+ const r = await managedPromotion(ctx, { pr: 7, head: HEAD });
533
+ assert.match(r.why, /merge guard: no forge\/release-gate/);
534
+ assert.equal(merges.length, 0);
535
+ });
536
+ it("I12: a lane-role context cannot merge", async () => {
537
+ const { managedPromotion } = await import("./release.mjs");
538
+ const { ctx, merges } = mk();
539
+ ctx.fence = fence("lane");
540
+ assert.match((await managedPromotion(ctx, { pr: 7, head: HEAD })).refused, /role lane may not merge/);
541
+ assert.equal(merges.length, 0);
542
+ });
543
+ });
544
+
545
+ describe("release plan routing (#5559)", () => {
546
+ const POLICY_TEXT = "schema: 1\nbranches: {default: main}\nplan: {approval: wait}\nlanes: {release: {pipeline: existing}}\nmerge: {approval: confirm}\nunits:\n api: {paths: [\"api/**\"]}\ntrust: {actors: [owner]}\ndeploy: {live_release_command: \"echo live\"}\n";
547
+ const issue = { number: 5, title: "t", body: "", labels: [], createdAt: "2026-01-01T00:00:00Z", updatedAt: "2026-01-02T00:00:00Z", comments: [{ author: { login: "b" }, body: "<!-- FORGE:CLASSIFY -->\n```json\n{\"type\":\"bug\",\"severity\":\"P2\",\"exists_in\":\"live\",\"confidence\":0.9,\"files\":[\"api/a.py\"]}\n```" }] };
548
+ const mkIo = (out, gh) => ({ print: (l) => out.push(l), gh: async (a) => { gh.push(a); return a[0] === "issue" ? JSON.stringify([issue]) : JSON.stringify({ nameWithOwner: "o/r" }); }, git: (a) => { if (a[0] === "show") return POLICY_TEXT; throw new Error("none"); }, rehearse: async () => ({ ok: true, output: "abc1234" }), now: () => 1 });
549
+ it("`release plan --json` is read-only and lists the plan; the bare release options still reject unknown flags", async () => {
550
+ const out = [], gh = [];
551
+ assert.equal(await releaseFromCli(["plan", "--json"], { io: mkIo(out, gh), cwd: tmp(), env: { ...process.env, FORGEDOCK_RELEASE_DIR: tmp() } }), 0);
552
+ const p = JSON.parse(out[0]);
553
+ assert.equal(p.schema, "forgedock.release.plan/v1"); assert.equal(p.issues[5].lane, "train"); assert.equal(p.live_sha, "abc1234");
554
+ assert.ok(gh.every((a) => a[0] === "issue" || a[0] === "repo"));
555
+ await assert.rejects(releaseFromCli(["--bogus"], { io: mkIo([], []), cwd: tmp() }), /unknown option/);
556
+ });
557
+ });
558
+
559
+ describe("release start|go routing (#5571)", () => {
560
+ const POLICY_TEXT = "schema: 1\nbranches: {default: main}\nlanes: {release: {pipeline: existing}}\nunits:\n api: {paths: [\"api/**\"]}\ntrust: {actors: [owner]}\n";
561
+ const mkIo = (out, gh) => ({ print: (l) => out.push(l), gh: async (a) => { gh.push(a); return a[0] === "repo" ? JSON.stringify({ nameWithOwner: "o/r" }) : "[]"; }, git: (a) => (a[0] === "show" ? POLICY_TEXT : "abc1234\n"), now: () => 1_700_000_000_000 });
562
+ const opts = (out, gh) => ({ io: mkIo(out, gh), cwd: tmp(), env: { ...process.env, FORGEDOCK_RELEASE_DIR: tmp() } });
563
+ it("an unmanaged `start` and `go <id>` make no GitHub writes; `go` needs an id; a bad --wave is rejected", async () => {
564
+ const out = [], gh = [];
565
+ assert.equal(await releaseFromCli(["start"], opts(out, gh)), 0);
566
+ assert.equal(await releaseFromCli(["go", "r1"], opts(out, gh)), 0);
567
+ assert.ok(out.every((l) => /unmanaged/.test(l)) && gh.every((a) => a[0] === "repo"));
568
+ await assert.rejects(releaseFromCli(["go"], opts([], [])), /release id/);
569
+ await assert.rejects(releaseFromCli(["start", "--wave", "x"], opts([], [])), /--wave/);
570
+ });
571
+ });