forgedock 1.55.1 → 1.57.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 (133) hide show
  1. package/bin/config-schema.mjs +1 -1
  2. package/bin/engine/outcome-codes.mjs +1 -0
  3. package/bin/engine/phases.mjs +4 -3
  4. package/bin/engine-cli.mjs +58 -10
  5. package/bin/forgedock.mjs +52 -3
  6. package/bin/gc.mjs +43 -6
  7. package/bin/help-text.mjs +3 -1
  8. package/bin/lean/batch-health.mjs +5 -1
  9. package/bin/lean/batch-health.test.mjs +7 -1
  10. package/bin/lean/batch.mjs +7 -2
  11. package/bin/lean/batch.test.mjs +45 -0
  12. package/bin/lean/conformance.e2e.test.mjs +3 -2
  13. package/bin/lean/conformance.mjs +88 -17
  14. package/bin/lean/conformance.test.mjs +98 -3
  15. package/bin/lean/decisions.mjs +86 -1
  16. package/bin/lean/decisions.test.mjs +21 -1
  17. package/bin/lean/depcache.mjs +124 -13
  18. package/bin/lean/depcache.test.mjs +121 -3
  19. package/bin/lean/design-gate.mjs +144 -0
  20. package/bin/lean/design-gate.test.mjs +169 -0
  21. package/bin/lean/effects-cap.test.mjs +17 -0
  22. package/bin/lean/effects.mjs +58 -13
  23. package/bin/lean/heavy.mjs +25 -8
  24. package/bin/lean/hostload.test.mjs +28 -0
  25. package/bin/lean/intake.mjs +97 -0
  26. package/bin/lean/intake.test.mjs +105 -0
  27. package/bin/lean/interfaces.mjs +181 -0
  28. package/bin/lean/interfaces.test.mjs +192 -0
  29. package/bin/lean/issuewatch-install.mjs +52 -12
  30. package/bin/lean/issuewatch-install.test.mjs +50 -0
  31. package/bin/lean/issuewatch-parity.mjs +12 -2
  32. package/bin/lean/issuewatch-parity.test.mjs +26 -0
  33. package/bin/lean/issuewatch-reconcile.mjs +29 -1
  34. package/bin/lean/issuewatch-reconcile.test.mjs +21 -0
  35. package/bin/lean/issuewatch.mjs +34 -3
  36. package/bin/lean/issuewatch.test.mjs +49 -1
  37. package/bin/lean/lanecheck.test.mjs +15 -4
  38. package/bin/lean/lean.mjs +80 -25
  39. package/bin/lean/lean.test.mjs +149 -3
  40. package/bin/lean/orchestrate-blocked.test.mjs +18 -2
  41. package/bin/lean/orchestrate-owned.test.mjs +14 -5
  42. package/bin/lean/orchestrate.mjs +26 -4
  43. package/bin/lean/orphan-pr.mjs +125 -0
  44. package/bin/lean/orphan-pr.test.mjs +145 -0
  45. package/bin/lean/pagegate.mjs +35 -12
  46. package/bin/lean/pagegate.test.mjs +39 -1
  47. package/bin/lean/preflight.mjs +35 -1
  48. package/bin/lean/preflight.test.mjs +27 -1
  49. package/bin/lean/prompts.mjs +2 -1
  50. package/bin/lean/reap.test.mjs +39 -0
  51. package/bin/lean/recovery.test.mjs +25 -0
  52. package/bin/lean/release-config.mjs +158 -0
  53. package/bin/lean/release-config.test.mjs +109 -0
  54. package/bin/lean/release-control.mjs +148 -0
  55. package/bin/lean/release-control.test.mjs +143 -0
  56. package/bin/lean/release-fence.mjs +50 -0
  57. package/bin/lean/release-fence.test.mjs +105 -0
  58. package/bin/lean/release-flakes.mjs +139 -0
  59. package/bin/lean/release-flakes.test.mjs +116 -0
  60. package/bin/lean/release-ledger.mjs +160 -0
  61. package/bin/lean/release-ledger.test.mjs +226 -0
  62. package/bin/lean/release-minutes.mjs +92 -0
  63. package/bin/lean/release-minutes.test.mjs +99 -0
  64. package/bin/lean/release-nightly.mjs +75 -0
  65. package/bin/lean/release-nightly.test.mjs +48 -0
  66. package/bin/lean/release-postmerge.mjs +45 -21
  67. package/bin/lean/release-review.e2e.test.mjs +1 -0
  68. package/bin/lean/release-review.mjs +54 -7
  69. package/bin/lean/release-review.test.mjs +76 -7
  70. package/bin/lean/release-unitmap.mjs +35 -0
  71. package/bin/lean/release-unitmap.test.mjs +41 -0
  72. package/bin/lean/release.mjs +177 -19
  73. package/bin/lean/release.test.mjs +80 -16
  74. package/bin/lean/render.mjs +3 -1
  75. package/bin/lean/run-issue-placement.test.mjs +82 -0
  76. package/bin/lean/sandbox-remote.mjs +16 -0
  77. package/bin/lean/schedd.mjs +1 -1
  78. package/bin/lean/seam.mjs +115 -0
  79. package/bin/lean/seam.test.mjs +118 -0
  80. package/bin/lean/selftest-journey.mjs +40 -2
  81. package/bin/lean/selftest-journey.test.mjs +43 -3
  82. package/bin/lean/statuscomment.mjs +168 -0
  83. package/bin/lean/statuscomment.test.mjs +133 -0
  84. package/bin/lean/ui-quality.mjs +57 -0
  85. package/bin/lean/ui-quality.test.mjs +55 -0
  86. package/bin/lean/visual-gate.test.mjs +63 -0
  87. package/bin/pool/agent.mjs +16 -2
  88. package/bin/pool/router.mjs +5 -1
  89. package/bin/review-staging.mjs +8 -5
  90. package/bin/stats/card.mjs +117 -0
  91. package/bin/stats/card.test.mjs +109 -0
  92. package/bin/stats/conformance-outcomes.test.mjs +2 -1
  93. package/bin/stats/depth.mjs +1 -1
  94. package/bin/stats/gh-retry.test.mjs +152 -0
  95. package/bin/stats/github-source.mjs +147 -14
  96. package/bin/stats/index.mjs +35 -2
  97. package/bin/stats/stats.test.mjs +31 -3
  98. package/bin/vendor/js-yaml/LICENSE +21 -0
  99. package/bin/vendor/js-yaml/PIN.md +7 -0
  100. package/bin/vendor/js-yaml/js-yaml.mjs +3851 -0
  101. package/commands/design-render-critique-loop.md +2 -0
  102. package/commands/design.md +2 -0
  103. package/commands/incident-response.md +4 -0
  104. package/commands/issue.md +1 -1
  105. package/commands/milestone.md +1 -1
  106. package/commands/pipeline-status.md +13 -0
  107. package/commands/review-pr-agents/frontend.md +1 -0
  108. package/commands/review-pr-staging.md +5 -0
  109. package/docs/CONFIG.md +75 -1
  110. package/docs/ISSUE-WATCH.md +7 -0
  111. package/docs/OUTCOME-CODES.md +1 -0
  112. package/docs/STATS.md +10 -0
  113. package/docs/design/visual-gate.md +25 -0
  114. package/docs/eval/adversarial-bench.md +2 -2
  115. package/docs/eval/corpus/adversarial-v1.json +3 -3
  116. package/docs/site/start-a-new-project.md +7 -0
  117. package/docs/spec/forge-protocol-v1.md +31 -0
  118. package/package.json +1 -1
  119. package/pool/README.md +2 -0
  120. package/scripts/acceptance-red-green.sh +15 -1
  121. package/scripts/acceptance-red-green.test.sh +12 -0
  122. package/scripts/bench-adversarial.mjs +4 -0
  123. package/scripts/bench-lightlane.mjs +4 -1
  124. package/scripts/bootstrap-create.mjs +8 -2
  125. package/scripts/ci-local.test.sh +3 -3
  126. package/scripts/fixtures/ci-local/gha-dorny/.github/workflows/ci.yml +4 -0
  127. package/scripts/plan-validate-live.mjs +9 -6
  128. package/scripts/review-prepare.sh +7 -1
  129. package/scripts/review-roster.sh +5 -2
  130. package/scripts/review-roster.test.sh +9 -0
  131. package/scripts/visual-gate.mjs +64 -0
  132. package/templates/bootstrap/technical-spike.md +17 -0
  133. package/templates/contracts/seam-check.mjs +236 -0
@@ -19,8 +19,15 @@ import { parseForgeYaml } from "../forge-utils.mjs";
19
19
  import { reviewStep, fixStep } from "./release-review.mjs";
20
20
  import { postMergeStep } from "./release-postmerge.mjs";
21
21
  import { rehearsalStep, parseRehearsalConfig } from "./release-rehearsal.mjs";
22
- import { budgetReportLine, releaseRuns } from "./ci-budget.mjs";
22
+ import { budgetReportLine, releaseRuns, detectBudget, readCiPolicy } from "./ci-budget.mjs";
23
+ import { parseNightlyConfig, readNightly, blocksRelease, fileNightlyRed } from "./release-nightly.mjs";
24
+ import { parseBudgetConfig, applyOnExceed, waveReport, trailingMedian, historyFromRoot, releaseMinutes } from "./release-minutes.mjs";
23
25
  import { cutSnapshot, writeRecord, checkChain, verifyRelease, DEFAULT_PATTERN } from "./release-snapshot.mjs";
26
+ import { createReleaseLedger, writeRelease, readLedger, acquireLease, heartbeat } from "./release-ledger.mjs";
27
+ import { fenced, epochTrailer } from "./release-fence.mjs";
28
+ import { holdCheck, exemptionsSection, VERBS as CONTROL_VERBS } from "./release-control.mjs";
29
+ import { parseFlakeConfig, classifyFailure, planRerun, flakeEntry, recordFlakes, readFlakes } from "./release-flakes.mjs";
30
+ import { readActive } from "./release-ledger.mjs";
24
31
  import { hostPreflightStep, markReadyStep, parsePreflightConfig } from "./release-preflight.mjs";
25
32
 
26
33
  export const RELEASE_STEPS = ["preflight", "host-preflight", "release-pr", "review", "fixes", "mark-ready", "rehearsal", "promotion", "post-merge"];
@@ -51,9 +58,51 @@ export function readReleaseConfig(raw) {
51
58
  let r = {};
52
59
  try { r = parseForgeYaml(String(raw ?? ""))?.release ?? {}; } catch { r = {}; }
53
60
  const off = (v) => ["false", "off", "no", "0", ""].includes(String(v ?? "").trim().toLowerCase());
54
- return { autoMerge: !off(r.auto_merge), artifactCheck: r.artifact_check || null, versionSync: !off(r.version_sync), publishWorkflow: r.publish_workflow || null, ...optKeys(r), ...snapshotKeys(r) };
61
+ return { autoMerge: !off(r.auto_merge), artifactCheck: r.artifact_check || null, versionSync: !off(r.version_sync), publishWorkflow: r.publish_workflow || null, ...(r.managed !== undefined && !off(r.managed) ? { managed: true } : {}), ...managedKeys(raw, r), ...freezeKeys(raw, r), ...optKeys(r), ...snapshotKeys(r) };
55
62
  }
56
63
 
64
+ /** `{nightly, budget}` (#5569) only when `release.managed` is on: the forge.yaml `nightly:` and `budget:` blocks. */
65
+ const managedKeys = (raw, r) => {
66
+ if (r.managed === undefined || off2(r.managed)) return {};
67
+ let y = {}; try { y = parseForgeYaml(String(raw ?? "")) ?? {}; } catch { y = {}; }
68
+ return { nightly: parseNightlyConfig(y.nightly), budget: parseBudgetConfig(y.budget) };
69
+ };
70
+ const off2 = (v) => ["false", "off", "no", "0", ""].includes(String(v ?? "").trim().toLowerCase());
71
+
72
+ /**
73
+ * Managed gate before the first step (#5569; there is no APPROVED state, so this is where it applies): a red nightly blocks only
74
+ * `lane: release` (T0-T2 reds and unskippable classes), and a forecast over the month's remaining minutes applies `budget.on_exceed`
75
+ * (p0 never). Every read is best effort: unreadable facts proceed. @returns {{blocked?, reason?, ciMode?}}
76
+ */
77
+ export async function managedGate({ io, repo, config, lane, root }) {
78
+ if (config.nightly) {
79
+ try {
80
+ const n = await readNightly({ gh: (a) => io.gh(a), repo, cfg: config.nightly, now: io.now() });
81
+ if (n?.reds.length) await fileNightlyRed({ gh: (a) => io.gh(a), repo, reds: n.reds, run: n.run });
82
+ const hit = blocksRelease({ lane, reds: n?.reds ?? [], cfg: config.nightly });
83
+ if (hit.length) return { blocked: true, reason: `nightly is red: ${hit.map((r) => r.name).join(", ")}` };
84
+ } catch { /* best effort */ }
85
+ }
86
+ if (config.budget) {
87
+ try {
88
+ const forecast = trailingMedian(historyFromRoot(root), lane);
89
+ const facts = await detectBudget({ gh: (a) => io.gh(a), repo, policy: config.ciPolicy, now: io.now() });
90
+ const remaining = facts.budget != null && facts.mtd != null ? facts.budget * (1 - (config.ciPolicy?.reservePct ?? 10) / 100) - facts.mtd : null;
91
+ const r = applyOnExceed({ lane, forecast, remaining, cfg: config.budget });
92
+ if (r.action === "hold") return { blocked: true, reason: `budget hold: ${r.why}` };
93
+ if (r.action === "local-first") return { ciMode: "local-first", why: r.why };
94
+ } catch { /* best effort */ }
95
+ }
96
+ return {};
97
+ }
98
+
99
+ /** `{intakeAutoResume, tracker}` only when configured (#5555): forge.yaml `freeze.intake_auto_resume`, `release.tracker`. */
100
+ const freezeKeys = (raw, r) => {
101
+ let f = {}; try { f = parseForgeYaml(String(raw ?? ""))?.freeze ?? {}; } catch { f = {}; }
102
+ const on = f.intake_auto_resume !== undefined && !["false", "off", "no", "0", ""].includes(String(f.intake_auto_resume).trim().toLowerCase());
103
+ return { ...(on ? { intakeAutoResume: true } : {}), ...(r.tracker ? { tracker: r.tracker } : {}) };
104
+ };
105
+
57
106
  /** `{mode, branchPattern, fixMode}` only when configured (#5276): mode `snapshot` cuts release/<id>; anything else is `freeze`. */
58
107
  const snapshotKeys = (r) => {
59
108
  const pick = (v, ok, dflt) => (ok.includes(String(v).trim().toLowerCase()) ? String(v).trim().toLowerCase() : dflt);
@@ -123,7 +172,7 @@ async function snapshotPrStep(ctx) {
123
172
  const found = json(await io.gh(["pr", "list", "--repo", repo, "--base", def, "--head", branch, "--state", "open", "--json", "number,headRefOid,url"]))?.[0];
124
173
  if (found) return { pr: found.number, head: found.headRefOid, url: found.url, reused: true, branch };
125
174
  const list = state.releaseBundle ?? [];
126
- const url = String(await io.gh(["pr", "create", "--repo", repo, "--base", def, "--head", branch, "--title", `Release: ${branch} -> ${def}`, "--body", bundleBody(list)])).trim();
175
+ const url = String(await io.gh(["pr", "create", "--repo", repo, "--base", def, "--head", branch, "--title", `Release: ${branch} -> ${def}`, "--body", bundleBody(list) + await exemptionBody(ctx)])).trim();
127
176
  const n = Number(/\/pull\/(\d+)/.exec(url)?.[1]);
128
177
  if (!Number.isSafeInteger(n)) throw new Error(`gh pr create returned no PR url: ${url}`);
129
178
  state.steps["release-pr"] = { done: false, result: { pr: n } }; // writeRecord reads the PR number from here
@@ -138,13 +187,19 @@ async function releasePrStep(ctx) {
138
187
  const found = json(await io.gh(["pr", "list", "--repo", repo, "--base", def, "--head", staging, "--state", "open", "--json", "number,headRefOid,url"]))?.[0];
139
188
  if (found) return { pr: found.number, head: found.headRefOid, url: found.url, reused: true };
140
189
  const list = await bundleList({ io, repo, head: staging, base: def });
141
- const url = String(await io.gh(["pr", "create", "--repo", repo, "--base", def, "--head", staging, "--title", `Release: ${staging} -> ${def}`, "--body", bundleBody(list), ...(ctx.config.preflight ? ["--draft"] : [])])).trim();
190
+ const url = String(await io.gh(["pr", "create", "--repo", repo, "--base", def, "--head", staging, "--title", `Release: ${staging} -> ${def}`, "--body", bundleBody(list) + await exemptionBody(ctx), ...(ctx.config.preflight ? ["--draft"] : [])])).trim();
142
191
  const n = Number(/\/pull\/(\d+)/.exec(url)?.[1]);
143
192
  if (!Number.isSafeInteger(n)) throw new Error(`gh pr create returned no PR url: ${url}`);
144
193
  const v = json(await io.gh(["pr", "view", String(n), "--repo", repo, "--json", "headRefOid"]));
145
194
  return { pr: n, head: v?.headRefOid, url, reused: false, bundle: list.length };
146
195
  }
147
196
 
197
+ /** The live operator exemptions as a PR-body section (#5568, I20); "" when unmanaged, none, or `_active` is unreadable. */
198
+ async function exemptionBody({ io, repo, config }) {
199
+ if (!config.managed || !io.api) return "";
200
+ try { return exemptionsSection((await readActive({ io, repo, credential: "driver" })).exemptions, io.now?.()); } catch { return ""; }
201
+ }
202
+
148
203
  /** GATE_PASS marker on the PR and the `forge/deploy-gate` conclusion at `head`. */
149
204
  export async function gateState({ io, repo, pr, head }) {
150
205
  const comments = json(await io.gh(["pr", "view", String(pr), "--repo", repo, "--json", "comments"]))?.comments ?? [];
@@ -165,16 +220,49 @@ export async function gateState({ io, repo, pr, head }) {
165
220
  const GATE_POLLS = 12, GATE_POLL_MS = 10_000;
166
221
 
167
222
  /** Re-run the newest gate-marker-check run on `head`: the bot's GATE_PASS comment never triggers it, so the status would stay pending. */
168
- async function retriggerGate({ io, repo, head }) {
223
+ async function retriggerGate({ io, repo, head, fence }) {
169
224
  try {
170
225
  const runs = json(await io.gh(["run", "list", "--repo", repo, "--workflow", "gate-marker-check.yml", "--commit", head, "--json", "databaseId", "--limit", "1"])) ?? [];
171
- if (runs[0]?.databaseId) await io.gh(["run", "rerun", String(runs[0].databaseId), "--repo", repo]);
172
- } catch { /* a run still in progress cannot be rerun, and it re-reads the markers anyway: just wait */ }
226
+ if (!runs[0]?.databaseId) return null;
227
+ const f = await fenced(fence, { action: "rerun", key: `rerun:${runs[0].databaseId}` }, () => io.gh(["run", "rerun", String(runs[0].databaseId), "--repo", repo]));
228
+ return f.refused ?? null; // #5553: a fenced host stops here
229
+ } catch { return null; /* a run still in progress cannot be rerun, and it re-reads the markers anyway: just wait */ }
230
+ }
231
+
232
+ /**
233
+ * #5568 (5.5): `rerun --failed` once per job for failed runs on `head` whose failures all carry a known infra signature, inside
234
+ * `ci.rerun_budget_min`; every decision (rerun or not, and why) is recorded in `flakes.json`. Best effort: never throws.
235
+ * @returns {{reran: string[], skipped: object[]}}
236
+ */
237
+ export async function rerunInfraFlakes({ io, repo, head, fence, policy }) {
238
+ const out = { reran: [], skipped: [] };
239
+ try {
240
+ const cfg = parseFlakeConfig(policy);
241
+ if (!fence?.lctx || !(cfg.rerunBudgetMin > 0)) return out;
242
+ const prior = await readFlakes(fence.lctx), done = prior.filter((f) => f.rerun).map((f) => `${f.sha}:${f.check}`);
243
+ const runs = json(await io.gh(["run", "list", "--repo", repo, "--commit", head, "--status", "failure", "--json", "databaseId,name", "--limit", "20"])) ?? [];
244
+ const at = new Date(io.now?.() ?? Date.now()).toISOString(), entries = [];
245
+ let spentMin = 0;
246
+ for (const r of runs) {
247
+ const log = String(await io.gh(["run", "view", String(r.databaseId), "--repo", repo, "--log-failed"]).catch(() => "")).slice(-20_000);
248
+ const c = classifyFailure(log);
249
+ const [d] = planRerun({ jobs: [{ key: `${head}:${r.name}`, name: r.name, class: c.class }], done, spentMin, budgetMin: cfg.rerunBudgetMin });
250
+ if (d.rerun) {
251
+ const f = await fenced(fence, { action: "rerun", key: `rerun-failed:${r.databaseId}` }, () => io.gh(["run", "rerun", String(r.databaseId), "--repo", repo, "--failed"]));
252
+ if (f.refused) { out.skipped.push({ name: r.name, why: f.refused }); continue; }
253
+ out.reran.push(r.name);
254
+ } else out.skipped.push({ name: r.name, why: d.why });
255
+ entries.push(flakeEntry({ check: r.name, signature: c.signature, kind: c.class === "infra" ? "infra" : "decision", sha: head, runIds: [r.databaseId], at, rerun: d.rerun }));
256
+ }
257
+ await recordFlakes(fence.lctx, entries.filter((e) => e.kind === "infra"));
258
+ } catch { /* best effort */ }
259
+ return out;
173
260
  }
174
261
 
175
262
  /** Re-trigger the gate, then poll (bounded) until `forge/deploy-gate` is success or failure; @returns the last gateState. */
176
- async function awaitGate({ io, repo, pr, head, gate }) {
177
- await retriggerGate({ io, repo, head });
263
+ async function awaitGate({ io, repo, pr, head, gate, fence }) {
264
+ const refused = await retriggerGate({ io, repo, head, fence });
265
+ if (refused) return { ...gate, fenced: refused };
178
266
  for (let i = 0; i < GATE_POLLS && gate.deployGate !== "success" && gate.deployGate !== "failure"; i++) {
179
267
  await io.sleep(GATE_POLL_MS);
180
268
  gate = await gateState({ io, repo, pr, head });
@@ -196,11 +284,18 @@ async function promotionStep(ctx) {
196
284
  }
197
285
  let gate = await gateState({ io, repo, pr, head });
198
286
  if (gate.marker !== "pass") return { stopped: true, why: `no FORGE:GATE_PASS on #${pr} (last marker: ${gate.marker ?? "none"})`, head };
199
- if (gate.deployGate !== "success" && gate.deployGate !== "failure") gate = await awaitGate({ io, repo, pr, head, gate });
287
+ if (gate.deployGate !== "success" && gate.deployGate !== "failure") gate = await awaitGate({ io, repo, pr, head, gate, fence: ctx.fence });
288
+ if (gate.fenced) return { refused: gate.fenced, head };
289
+ if (gate.deployGate === "failure" && ctx.config.managed && io.git) { // #5568: policy loaded lazily (release-config imports this module)
290
+ const { readPolicy } = await import("./release-config.mjs");
291
+ const policy = readPolicy({ io, defaultBranch: ctx.def }).policy;
292
+ await rerunInfraFlakes({ io, repo, head, fence: ctx.fence, policy });
293
+ }
200
294
  const cmd = `gh pr merge ${pr} --repo ${repo} --merge --match-head-commit ${head}`;
201
295
  if (!opts.merge && !ctx.config.autoMerge) { io.print(`GATE_PASS on #${pr}. Merge when ready:\n ${cmd}`); return { stopped: true, why: "GATE_PASS; promotion is opt-in (--merge or release.auto_merge)", cmd, head, gate }; }
202
296
  if (gate.deployGate !== "success") return { stopped: true, why: `forge/deploy-gate is ${gate.deployGate ?? "absent"}, not success${gate.deployGate === "failure" ? "" : ` after ${GATE_POLLS} polls`}`, head, gate };
203
- await io.gh(["pr", "merge", String(pr), "--repo", repo, "--merge", "--match-head-commit", head]);
297
+ const f = await fenced(ctx.fence, { action: "merge", key: `merge:${pr}:${head}` }, (epoch) => io.gh(["pr", "merge", String(pr), "--repo", repo, "--merge", "--match-head-commit", head, ...(epoch != null ? ["--body", epochTrailer(epoch)] : [])]));
298
+ if (f.refused) return { refused: f.refused, head, gate };
204
299
  return { merged: true, head, gate };
205
300
  }
206
301
 
@@ -228,14 +323,44 @@ export const withStubs = (over = {}) => ({ ...STEP_FNS, ...over });
228
323
  */
229
324
  export async function runRelease({ io, repo, opts = {}, config = {}, branches = {}, root, id, steps = STEP_FNS, mounts }) {
230
325
  const rel = openRelease(root, id, mounts);
231
- const state = rel.load() ?? { v: 1, id, repo, startedAt: new Date(io.now()).toISOString(), steps: {}, held: [] };
326
+ // #5550: managed releases read the ledger first (it is authoritative; the local file is a cache); off = no ledger call at all.
327
+ const lctx = config.managed && io.api ? { io, repo, credential: "driver" } : null;
328
+ const led = lctx ? await readLedger(lctx, id) : null;
329
+ if (led?.rejected) return { id, status: "refused", step: "ledger", reason: `ledger of ${id} rejected: ${led.rejected}` };
330
+ let ledgerHead = led?.head ?? null;
331
+ const mirror = async (s) => { // best effort: a lost race means another writer owns the release, which stops this run
332
+ const r = ledgerHead ? await writeRelease(lctx, id, s, ledgerHead) : await createReleaseLedger(lctx, id, s);
333
+ if (r.ok) ledgerHead = r.sha; else throw new Error(`release ${id}: ledger write lost the race (another writer holds the release)`);
334
+ };
335
+ const state = led?.state ?? rel.load() ?? { v: 1, id, repo, startedAt: new Date(io.now()).toISOString(), steps: {}, held: [] };
232
336
  state.opts = { merge: !!(opts.merge || state.opts?.merge) };
337
+ if (lctx) {
338
+ state.lane = opts.lane || state.lane || "release";
339
+ if (!Object.values(state.steps).some((x) => x?.done)) {
340
+ const g = await managedGate({ io, repo, config, lane: state.lane, root });
341
+ if (g.blocked) return { id, status: "blocked", step: "gate", reason: g.reason };
342
+ if (g.ciMode) { state.ciMode = g.ciMode; io.print?.(`release ${id}: ${g.why}; host checks run before paid CI`); }
343
+ }
344
+ }
345
+ const holder = io.holder ?? `host-${process.pid}`;
346
+ const takeLease = async () => { // #5553: the epoch fences every irreversible effect; the release PR carries the heartbeat comment
347
+ const l = await acquireLease(lctx, { holder, release: id, issue: state.steps["release-pr"].result.pr, ttlS: config.leaseTtlS ?? 120, now: io.now() });
348
+ if (!l.ok) return l.refused ?? "lease lost the race";
349
+ const record = async (rec) => { const a = (state.intents ??= []); const i = a.findIndex((x) => x.key === rec.key); if (i < 0) a.push(rec); else a[i] = rec; ctx.save(); await mirror(state); };
350
+ ctx.fence = { lctx, lease: l.lease, record, now: () => new Date(io.now()).toISOString() };
351
+ return null;
352
+ };
233
353
  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) };
234
354
  ctx.save();
235
355
  let out;
236
356
  try {
237
357
  for (const step of RELEASE_STEPS) {
238
358
  if (state.steps[step]?.done) continue;
359
+ if (lctx && !ctx.fence && state.steps["release-pr"]?.done) { const why = await takeLease(); if (why) { out = { id, status: "refused", step: "lease", reason: why }; break; } }
360
+ if (ctx.fence) { // #5556 (I24): a hold stops the run before the next step; an unreadable _active already ends it above
361
+ const held = await holdCheck(lctx, id).catch(() => null);
362
+ if (held) { out = { id, status: "refused", step, reason: held }; break; }
363
+ }
239
364
  const result = await steps[step](ctx);
240
365
  if (result?.refused) { out = { id, status: "refused", step, reason: result.refused }; break; }
241
366
  if (result?.blocked) { out = { id, status: "blocked", step, reason: result.reason }; break; }
@@ -243,13 +368,23 @@ export async function runRelease({ io, repo, opts = {}, config = {}, branches =
243
368
  if (result?.stopped) { state.steps[step] = { done: false, at: new Date(io.now()).toISOString(), result }; out = { id, status: "stopped", step, reason: result.why }; break; }
244
369
  state.steps[step] = { done: true, at: new Date(io.now()).toISOString(), result };
245
370
  ctx.save();
371
+ if (lctx) await mirror(state);
372
+ if (lctx && !ctx.fence && step === "release-pr") { const why = await takeLease(); if (why) { out = { id, status: "refused", step: "lease", reason: why }; break; } }
373
+ if (ctx.fence) { // an unreadable _active ends the run too (I5): the next irreversible step would refuse anyway
374
+ const hb = await heartbeat(lctx, ctx.fence.lease).catch((e) => ({ unreadable: e.message }));
375
+ if (hb.fenced || hb.unreadable) { out = { id, status: "refused", step, reason: hb.fenced ? "fenced: another host took over the release lease" : `cannot read _active (${hb.unreadable})` }; break; }
376
+ }
246
377
  }
247
378
  out ??= { id, status: "done" };
248
379
  } finally {
249
380
  // A stop at GATE_PASS ends the release hold as well: nothing else is waiting on the batches.
250
381
  await restoreBatches(ctx);
251
382
  }
383
+ if (lctx) { // #5569: Actions minutes of this release (sum of ceil per job), mirrored to the ledger below
384
+ try { const m = await releaseMinutes({ gh: (a) => io.gh(a), repo, sinceMs: Date.parse(state.startedAt) }); if (m) state.minutes = { runs: m.runs, total: m.minutes }; } catch { /* best effort */ }
385
+ }
252
386
  state.status = out.status; ctx.save();
387
+ if (lctx) await mirror(state);
253
388
  return out;
254
389
  }
255
390
 
@@ -260,7 +395,11 @@ export function realReleaseIo({ env = process.env, exec = execFileSync, print =
260
395
  const mine = (b, repo) => { const r = b.readPlan()?.repo; return !r || r === repo; };
261
396
  const unfinished = (repo) => listBatches(root).map((id) => openBatch(root, id)).filter((b) => !b.readReport() && mine(b, repo));
262
397
  return {
263
- gh: (args) => gh(args), print, now: () => Date.now(),
398
+ gh: (args) => gh(args), print,
399
+ api: (method, path, body) => { // JSON in and out for the ledger (#5550); the error carries the HTTP status
400
+ try { return JSON.parse(String(exec("gh", ["api", "-X", method, path, ...(body ? ["--input", "-"] : [])], { encoding: "utf8", input: body ? JSON.stringify(body) : undefined, maxBuffer: 64 << 20, stdio: ["pipe", "pipe", "pipe"] })) || "null"); }
401
+ catch (e) { throw Object.assign(new Error(`gh api ${method} ${path} failed: ${String(e?.stderr ?? e?.message ?? e).split("\n")[0]}`), { status: Number(/HTTP (\d{3})/.exec(String(e?.stderr ?? ""))?.[1]) || undefined }); }
402
+ }, now: () => Date.now(),
264
403
  git: (args, { env: extra, input } = {}) => exec("git", args, { cwd, encoding: "utf8", input, env: { ...env, ...extra }, maxBuffer: 64 << 20, stdio: ["pipe", "pipe", "pipe"] }),
265
404
  sleep: (ms) => new Promise((r) => setTimeout(r, ms)),
266
405
  run: async (cmd) => { try { exec("sh", ["-c", cmd], { stdio: "ignore", timeout: 120_000 }); return { ok: true }; } catch { return { ok: false }; } },
@@ -280,31 +419,50 @@ export function realReleaseIo({ env = process.env, exec = execFileSync, print =
280
419
  }
281
420
 
282
421
  const flag = (argv, f) => { const i = argv.indexOf(f); return i >= 0 ? argv[i + 1] : null; };
283
- export const RELEASE_USAGE = "usage: forgedock release [--repo owner/repo] [--merge] [--watch] [--resume <id>] | forgedock release verify <sha> [--repo owner/repo]";
422
+ export const RELEASE_USAGE = "usage: forgedock release [--repo owner/repo] [--merge] [--watch] [--resume <id>] | forgedock release verify <sha> [--repo owner/repo] | 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 report";
284
423
 
285
424
  /** `forgedock release ...`; @returns the process exit code (0 done or stopped at GATE_PASS, 1 refused, 3 blocked on a manual step). */
286
425
  export async function releaseFromCli(argv, deps = {}) {
287
426
  const cwd = deps.cwd ?? process.cwd(), env = deps.env ?? process.env;
288
427
  const io = deps.io ?? realReleaseIo({ env, cwd });
428
+ if (argv[0] === "report") { // #5569: monthly model vs measured minutes of the first 3 managed waves
429
+ let y = {}; try { y = parseForgeYaml(readFileSync(join(cwd, "forge.yaml"), "utf8")) ?? {}; } catch { /* defaults */ }
430
+ for (const l of waveReport(historyFromRoot(releaseRoot(env)), parseBudgetConfig(y.budget)).lines) io.print(l);
431
+ return 0;
432
+ }
289
433
  if (argv[0] === "verify") return verifyFromCli(argv.slice(1), { io, cwd });
290
- const unknown = argv.filter((a, i) => a.startsWith("--") && !["--repo", "--merge", "--watch", "--resume"].includes(a) && !(argv[i - 1] === "--resume" || argv[i - 1] === "--repo"));
434
+ if (argv[0] === "check-config" || argv[0] === "init") { // #5551: policy file, loaded lazily (release-config imports this module)
435
+ const { checkConfigFromCli, initFromCli } = await import("./release-config.mjs");
436
+ return (argv[0] === "init" ? initFromCli : checkConfigFromCli)(argv.slice(1), { io, cwd });
437
+ }
438
+ const cv = argv[0] === "control" ? argv[1] : argv[0]; // #5556: one implementation, the bare verbs are aliases
439
+ if (CONTROL_VERBS.includes(cv)) {
440
+ const { controlFromCli } = await import("./release-control.mjs");
441
+ const { readPolicy } = await import("./release-config.mjs");
442
+ const policy = readPolicy({ io, defaultBranch: readBranches(cwd).default || "main", cwd }).policy;
443
+ return controlFromCli(cv, argv.slice(argv[0] === "control" ? 2 : 1), { io, policy, actor: deps.actor, host: deps.host });
444
+ }
445
+ if (argv[0] === "control") throw new Error(`unknown control verb ${argv[1] ?? ""}; ${RELEASE_USAGE}`);
446
+ const unknown = argv.filter((a, i) => a.startsWith("--") && !["--repo", "--merge", "--watch", "--resume", "--lane"].includes(a) && !(argv[i - 1] === "--resume" || argv[i - 1] === "--repo" || argv[i - 1] === "--lane"));
291
447
  if (unknown.length) throw new Error(`unknown option ${unknown[0]}; ${RELEASE_USAGE}`);
292
448
  const root = releaseRoot(env);
293
449
  const resume = flag(argv, "--resume");
294
450
  let id = resume ?? newReleaseId(io.now());
295
451
  let repo = flag(argv, "--repo");
452
+ let raw = ""; try { raw = readFileSync(join(cwd, "forge.yaml"), "utf8"); } catch { /* no forge.yaml: defaults */ }
453
+ const config = readReleaseConfig(raw);
454
+ if (config.managed) config.ciPolicy = readCiPolicy(cwd);
296
455
  if (resume) {
297
456
  const st = openRelease(root, resume).load();
298
- if (!st) throw new Error(`no release ${resume} in ${root}`);
299
- repo ??= st.repo;
457
+ if (!st && !config.managed) throw new Error(`no release ${resume} in ${root}`); // managed: the ledger may hold it (another host)
458
+ repo ??= st?.repo;
300
459
  }
301
460
  repo ??= JSON.parse(String(await io.gh(["repo", "view", "--json", "nameWithOwner"]))).nameWithOwner;
302
- let raw = ""; try { raw = readFileSync(join(cwd, "forge.yaml"), "utf8"); } catch { /* no forge.yaml: defaults */ }
303
461
  const budget = async (since) => { // #5278: the Actions-minutes line (and any auto switch to local-first); never fails the job
304
462
  try { io.print(await budgetReportLine({ cwd, repo, gh: (a) => io.gh(a), now: io.now(), release: since ? await releaseRuns({ gh: (a) => io.gh(a), repo, sinceMs: since }) : null })); } catch { /* best effort */ }
305
463
  };
306
464
  await budget(null);
307
- const r = await runRelease({ io, repo, opts: { merge: argv.includes("--merge") }, config: readReleaseConfig(raw), branches: readBranches(cwd), root, id, mounts: deps.mounts });
465
+ const r = await runRelease({ io, repo, opts: { merge: argv.includes("--merge"), lane: flag(argv, "--lane") }, config, branches: readBranches(cwd), root, id, mounts: deps.mounts });
308
466
  const line = r.status === "done" ? `release ${id}: done` : `release ${id}: ${r.status} at ${r.step}: ${r.reason} (resume: forgedock release --resume ${id})`;
309
467
  io.print(line);
310
468
  try { await budget(Date.parse(openRelease(root, id).load()?.startedAt) || null); } catch { /* best effort */ }
@@ -46,6 +46,18 @@ function fakeIo(world = {}) {
46
46
  }
47
47
  const ok = async () => ({ ok: true });
48
48
 
49
+ describe("unmanaged release carries no epoch (#5553)", () => {
50
+ it("promotion merges with the plain argv and makes no ledger call", async () => {
51
+ const mod = await import("./release.mjs");
52
+ const io = fakeIo();
53
+ io.api = async () => { throw new Error("no ledger call expected"); };
54
+ const out = await mod.runRelease({ io, repo: REPO, root: tmp(), mounts: DISK, id: newReleaseId(), opts: { merge: true }, config: {}, branches: { staging: "staging", default: "main" }, steps: mod.withStubs({ review: ok, fixes: ok, "post-merge": ok }) });
55
+ assert.equal(out.status, "done");
56
+ const merge = io.calls.find((a) => a[0] === "pr" && a[1] === "merge");
57
+ assert.deepEqual(merge, ["pr", "merge", "7", "--repo", REPO, "--merge", "--match-head-commit", HEAD]);
58
+ });
59
+ });
60
+
49
61
  describe("release job (#5211)", () => {
50
62
  const promote = async (world, { opts = {}, config = {} } = {}) => {
51
63
  const io = fakeIo(world), root = tmp(), id = newReleaseId();
@@ -208,6 +220,18 @@ describe("release job (#5211)", () => {
208
220
  assert.equal(readReleaseConfig("release:\n publish_workflow: pub.yml\n").publishWorkflow, "pub.yml");
209
221
  });
210
222
 
223
+ it("#5550: managed is off by default (config shape unchanged) and then no ledger call or GitHub write is made", async () => {
224
+ assert.equal("managed" in readReleaseConfig("release:\n auto_merge: true\n"), false);
225
+ assert.equal(readReleaseConfig("release:\n managed: false\n").managed, undefined);
226
+ assert.equal(readReleaseConfig("release:\n managed: true\n").managed, true);
227
+ const apiCalls = [], ghCalls = [], io = { print() {}, now: () => 1_700_000_000_000, runningLanes: async () => [], batches: async () => [], setParallel: async () => {}, gh: async (a) => { ghCalls.push(a); return ""; }, api: async (...a) => { apiCalls.push(a); return {}; } };
228
+ const ok = async () => ({});
229
+ const out = await (await import("./release.mjs")).runRelease({ io, repo: REPO, root: tmp(), mounts: DISK, id: newReleaseId(), opts: {}, config: {}, branches: {}, steps: { preflight: ok, "host-preflight": ok, "release-pr": ok, review: ok, fixes: ok, "mark-ready": ok, rehearsal: ok, promotion: ok, "post-merge": ok } });
230
+ assert.equal(out.status, "done");
231
+ assert.deepEqual(apiCalls, []);
232
+ assert.deepEqual(ghCalls, []);
233
+ });
234
+
211
235
  it("CLI: rejects unknown options and exits 3 on a blocked step, naming the resume command", async () => {
212
236
  const root = tmp(), io = fakeIo();
213
237
  await assert.rejects(() => releaseFromCli(["--bogus"], { io, env: { FORGEDOCK_RELEASE_DIR: root }, cwd: root, mounts: DISK }), /unknown option/);
@@ -222,7 +246,7 @@ describe("release post-merge step (#5213)", () => {
222
246
  const PKG = Buffer.from(JSON.stringify({ version: "1.2.3" })).toString("base64");
223
247
  /** gh answers for the post-merge calls; `o` tunes them. */
224
248
  const pmWorld = (o = {}) => {
225
- const st = { runs: o.runs ?? [[{ databaseId: 5, status: "completed", conclusion: "success" }]], runCalls: 0, dispatched: 0, syncPrs: o.syncPrs ?? [], created: 0 };
249
+ const st = { runs: o.runs ?? [[{ databaseId: 5, status: "completed", conclusion: "success" }]], runCalls: 0, dispatched: 0, syncPrs: o.syncPrs ?? [], created: 0, bodies: [], views: 0 };
226
250
  return {
227
251
  st,
228
252
  pm: (a) => {
@@ -230,19 +254,24 @@ describe("release post-merge step (#5213)", () => {
230
254
  if (a[0] === "pr" && a[1] === "view" && j.includes("mergeCommit")) return JSON.stringify({ state: o.prState ?? "MERGED", mergeCommit: { oid: SHA } });
231
255
  if (a[0] === "run" && a[1] === "list") { assert.ok(j.includes(`--commit ${SHA}`) && j.includes(`--workflow ${o.wf ?? "publish.yml"}`)); const r = st.runs[Math.min(st.runCalls++, st.runs.length - 1)]; return JSON.stringify(r); }
232
256
  if (a[0] === "workflow" && a[1] === "run") { st.dispatched++; assert.ok(a.includes("main")); return ""; }
233
- if (a[0] === "api" && j.includes("contents/package.json")) return PKG;
257
+ if (a[0] === "api" && j.includes("contents/package.json?ref=staging") && a.includes("--jq")) return Buffer.from(JSON.stringify({ version: o.stagingVersion ?? "1.2.2" })).toString("base64");
258
+ if (a[0] === "api" && j.includes("contents/package.json") && a.includes("--jq")) return PKG;
259
+ if (a[0] === "api" && j.includes("git/ref/heads/staging")) return "s".repeat(40);
260
+ if (a[0] === "api" && a.includes("POST") && j.includes("git/refs")) { st.refs = (st.refs ?? 0) + 1; return ""; }
261
+ if (a[0] === "api" && a.includes("PUT")) { (st.puts ??= []).push(a); return ""; }
262
+ if (a[0] === "api" && j.includes("contents/") && j.includes("ref=staging")) return JSON.stringify({ sha: "f".repeat(40), content: Buffer.from(JSON.stringify({ name: "x", version: "1.2.2" })).toString("base64") });
234
263
  if (a[0] === "api" && j.includes("branches/chore/sync-version-1.2.3")) { if (o.noBranch) throw new Error("404"); return "x"; }
235
264
  if (a[0] === "pr" && a[1] === "list" && j.includes("chore/sync-version")) return JSON.stringify(st.syncPrs);
236
- if (a[0] === "pr" && a[1] === "create") { st.created++; assert.ok(a.includes("staging") && a.includes("chore/sync-version-1.2.3")); return "https://github.com/o/r/pull/30"; }
237
- if (a[0] === "pr" && a[1] === "view" && j.includes("statusCheckRollup")) return JSON.stringify({ state: "OPEN", headRefOid: "c".repeat(40), statusCheckRollup: o.checks ?? [{ conclusion: "SUCCESS" }] });
238
- if (a[0] === "pr" && a[1] === "merge" && Number(a[2]) >= 30) return "";
265
+ if (a[0] === "pr" && a[1] === "create") { st.created++; st.bodies.push(a[a.indexOf("--body") + 1]); assert.ok(a.includes("staging") && a.includes("chore/sync-version-1.2.3")); return "https://github.com/o/r/pull/30"; }
266
+ if (a[0] === "pr" && a[1] === "view" && j.includes("--json state") && Number(a[2]) >= 30) return JSON.stringify({ state: st.views++ >= (o.mergesAfter ?? 0) ? (o.final ?? "MERGED") : "OPEN" });
267
+ if (a[0] === "pr" && a[1] === "merge" && Number(a[2]) >= 30) { if (o.autoFails) throw new Error("auto merge is not allowed"); return ""; }
239
268
  return undefined;
240
269
  },
241
270
  };
242
271
  };
243
272
  const run = (o = {}, config = {}) => {
244
273
  const w = pmWorld(o), io = fakeIo({ pm: w.pm, ...o });
245
- const ctx = { io, repo: REPO, def: "main", staging: "staging", config: { postMerge: { publishPolls: 2, runPolls: 2, branchPolls: 2, checkPolls: 2, artifactTries: 3 }, ...config }, state: { steps: { "release-pr": { result: { pr: 7 } } } } };
274
+ const ctx = { io, repo: REPO, def: "main", staging: "staging", config: { postMerge: { publishPolls: 2, runPolls: 2, branchPolls: 2, autoPolls: 2, artifactTries: 3 }, ...config }, state: { steps: { "release-pr": { result: { pr: 7 } } } } };
246
275
  return postMergeStep(ctx).then((out) => ({ out, io, st: w.st }));
247
276
  };
248
277
 
@@ -290,27 +319,46 @@ describe("release post-merge step (#5213)", () => {
290
319
  assert.match(b.out.reason, /artifact_check/);
291
320
  });
292
321
 
293
- it("R4: version_sync opens the sync PR to staging and merges it with --match-head-commit when green", async () => {
322
+ it("R4: version_sync opens the sync PR then enables auto-merge; staging already synced makes no calls", async () => {
294
323
  const { out, st, io } = await run({}, { versionSync: true });
295
324
  assert.equal(st.created, 1);
325
+ assert.match(st.bodies[0], /^docs-not-needed: \S/m);
296
326
  assert.equal(out.sync.merged, true);
297
- assert.ok(io.calls.some((a) => a[1] === "merge" && a.includes("30") && a.includes("--match-head-commit") && a.includes("c".repeat(40))));
327
+ assert.equal(out.sync.pr, 30);
328
+ const kinds = io.calls.filter((a) => a[0] === "pr" && (a[1] === "create" || a[1] === "merge")).map((a) => a[1]);
329
+ assert.deepEqual(kinds, ["create", "merge"]);
330
+ assert.ok(io.calls.some((a) => a[1] === "merge" && a.includes("--merge") && a.includes("--auto") && !a.includes("--match-head-commit")));
331
+ const synced = await run({ stagingVersion: "1.2.3" }, { versionSync: true });
332
+ assert.equal(synced.out.sync.skipped, true);
333
+ assert.ok(!synced.io.calls.some((a) => (a[0] === "pr" && ["create", "merge", "list"].includes(a[1])) || a[0] === "api" && a.join(" ").includes("branches/")));
334
+ assert.equal(synced.st.created, 0);
298
335
  });
299
336
 
300
- it("version_sync reuses an open sync PR, skips a merged one, and never merges red or check-less PRs", async () => {
337
+ it("version_sync reuses an open sync PR and skips a merged one", async () => {
301
338
  const open = await run({ syncPrs: [{ number: 31, state: "OPEN" }] }, { versionSync: true });
302
339
  assert.equal(open.st.created, 0);
303
- assert.ok(open.io.calls.some((a) => a[1] === "merge" && a.includes("31")));
340
+ assert.ok(open.io.calls.some((a) => a[1] === "merge" && a.includes("31") && a.includes("--auto")));
304
341
  const merged = await run({ syncPrs: [{ number: 32, state: "MERGED" }] }, { versionSync: true });
305
342
  assert.equal(merged.out.sync.merged, true);
306
343
  assert.ok(!merged.io.calls.some((a) => a[1] === "merge"));
307
- for (const checks of [[], [{ conclusion: "FAILURE" }], [{ conclusion: "SUCCESS" }, { status: "IN_PROGRESS", state: "PENDING" }]]) {
308
- const r = await run({ syncPrs: [{ number: 33, state: "OPEN" }], checks }, { versionSync: true });
309
- assert.equal(r.out.blocked, true, JSON.stringify(checks));
310
- assert.ok(!r.io.calls.some((a) => a[1] === "merge"));
344
+ });
345
+
346
+ it("R5: a missing sync branch is cut from staging with a version-only commit, then the PR opens", async () => {
347
+ const { out, st } = await run({ noBranch: true }, { versionSync: true });
348
+ assert.equal(st.refs, 1);
349
+ assert.deepEqual(st.puts.map((a) => a.find((x) => x.startsWith("sha="))), ["sha=" + "f".repeat(40), "sha=" + "f".repeat(40)]);
350
+ assert.equal(st.created, 1);
351
+ assert.equal(out.sync.merged, true);
352
+ });
353
+
354
+ it("R4: an auto-merge that is not done in time, is closed, or cannot be enabled is a warning, not blocked", async () => {
355
+ for (const o of [{ mergesAfter: 99 }, { final: "CLOSED" }, { autoFails: true }]) {
356
+ const { out, io } = await run(o, { versionSync: true });
357
+ assert.equal(out.published, true, JSON.stringify(o));
358
+ assert.equal(out.sync.merged, false);
359
+ assert.match(out.sync.warning, /version-sync PR #30/);
360
+ assert.ok(io.printed.some((l) => l.includes("WARNING")));
311
361
  }
312
- const nb = await run({ noBranch: true }, { versionSync: true });
313
- assert.equal(nb.out.blocked, true);
314
362
  });
315
363
 
316
364
  it("R1: through the job, a blocked post-merge is retried on resume and finishes once the run exists", async () => {
@@ -421,3 +469,19 @@ describe("snapshot releases (#5276)", () => {
421
469
  assert.deepEqual((await step(undefined)).pushes, []);
422
470
  });
423
471
  });
472
+
473
+
474
+ describe("release control routing (#5556)", () => {
475
+ it("`release hold` and `release control hold` share one implementation and refuse without --reason", async () => {
476
+ for (const argv of [["hold", "r20260101-000000-1"], ["control", "hold", "r20260101-000000-1"]]) {
477
+ const out = [];
478
+ const io = { print: (l) => out.push(l), gh: async () => JSON.stringify({ nameWithOwner: "o/r" }), api: async () => { throw new Error("no api"); }, git: () => { throw new Error("none"); }, now: () => 1 };
479
+ assert.equal(await releaseFromCli([...argv, "--json"], { io, cwd: tmp() }), 1);
480
+ assert.match(out[0], /forgedock.release.control\/v1/);
481
+ assert.match(out[0], /--reason is required/);
482
+ }
483
+ });
484
+ it("an unknown control verb is an error", async () => {
485
+ await assert.rejects(releaseFromCli(["control", "nope"], { io: { print() {}, gh: async () => "" }, cwd: tmp() }), /unknown control verb/);
486
+ });
487
+ });
@@ -2,6 +2,8 @@
2
2
  // SPDX-License-Identifier: AGPL-3.0-or-later
3
3
  /** Fixed comment templates for the core work-on. Pure functions, no model calls. Missing fields read "not reported". */
4
4
 
5
+ import { visualSection } from "./ui-quality.mjs";
6
+
5
7
  export const NR = "not reported";
6
8
  export const MAX_COMMENT_CHARS = 60000;
7
9
 
@@ -192,7 +194,7 @@ export function renderPrBody({ issue, investigation, contract, implementation, r
192
194
  // #4404: requirements measured outside the lane; the change delivers their instrumentation, the named job the result
193
195
  const oob = (contract?.requirements ?? []).filter((r) => r?.verify === "out_of_band");
194
196
  const outOfBand = oob.length ? `\n\n## Verified out of band\n${oob.map((r) => `- ${escl(r.id)}: ${escl(r.quote)} (job ${r.evidence ? `\`${escl(r.evidence).replace(/`/g, "'")}\`` : "not named"})`).join("\n")}` : "";
195
- return `## Root cause\n${root}\n\n## Deliverables\n${deliver}\n\n## Verification\n${verify}${remaining}${outOfBand}\n\nCloses #${issue}`;
197
+ return `## Root cause\n${root}\n\n## Deliverables\n${deliver}\n\n## Verification\n${verify}${remaining}${outOfBand}${visualSection(implementation)}\n\nCloses #${issue}`;
196
198
  }
197
199
 
198
200
  // ---- trajectory ----
@@ -0,0 +1,82 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ // #5542: `run-issue` follows forge.yaml `execution:` like `orchestrate`, and `--local` keeps the lane on this host.
4
+ import { describe, it } from "node:test";
5
+ import assert from "node:assert/strict";
6
+ import { readFileSync } from "node:fs";
7
+ import { join } from "node:path";
8
+ import { tmpDir } from "../tests/_tmp.mjs";
9
+ import { parseExecution, openExecutionBudget } from "./execution.mjs";
10
+ import { makeLedger } from "./ledger.mjs";
11
+ import { runFromCli } from "../engine-cli.mjs";
12
+
13
+ const logs = async (fn) => { const out = [], l = console.log; console.log = (x) => out.push(String(x)); try { return { res: await fn(), out }; } finally { console.log = l; } };
14
+
15
+ function fakeProvider(finish) {
16
+ const p = { name: "fake", calls: [], live: new Set(), results: {}, idFor: (n) => `fake-${n}`,
17
+ async start({ issue }) { p.calls.push(["start", issue]); p.results[issue] = finish(issue); return { provider: "fake", id: `fake-${issue}`, issue }; },
18
+ async status() { return "exited"; }, async fetchResult(h) { return p.results[h.issue] ?? null; }, async teardown() { return true; } };
19
+ return p;
20
+ }
21
+
22
+ const leanIo = { gh: async (a) => (a.includes("milestone") ? JSON.stringify({ milestone: null }) : a[0] === "repo" ? "main\n" : JSON.stringify({ body: "" })),
23
+ git: async (a) => (a[0] === "ls-remote" ? "abc\trefs/heads/staging\n" : a[0] === "rev-parse" ? ".git\n" : "") };
24
+ const setup = (name, prov, extra = {}) => {
25
+ const work = tmpDir(name);
26
+ const ran = [];
27
+ return { work, ran, deps: { env: {}, batchRoot: join(work, "batches"), allowTmpfs: true, pollMs: 5, orchestration: { breaker: null, maxDeferrals: 3 }, io: { gh: async () => "o/r\n" }, leanIo, sched: null, maintenance: null,
28
+ executionBudget: openExecutionBudget({ file: join(work, "budget.json") }), emitTelemetry: () => {}, dir: join(work, "runs"), batchId: `rp-${name}`,
29
+ execution: parseExecution({ mode: "remote", max_remote: "1", provider: "container" }), sandboxProvider: prov,
30
+ sandboxLedger: (n) => makeLedger({ root: join(work, "ledger"), batch: `rp-${name}`, lane: `sandbox-${n}`, owner: "t", issue: n }),
31
+ ...extra } };
32
+ };
33
+ const core = (ran) => ({ runCore: async (o) => { ran.push(o.placement ?? null); return { terminalReason: "merged", pr: 1 }; } });
34
+
35
+ describe("run-issue placement (#5542)", () => {
36
+ it("remote execution routes run-issue to the provider", async () => {
37
+ const prov = fakeProvider((n) => ({ terminalReason: "merged", pr: 100 + n, cost_usd: 0 }));
38
+ const { deps, work } = setup("remote", prov);
39
+ const rf = join(work, "result.json");
40
+ const { res, out } = await logs(() => runFromCli(["7", "--repo", "o/r", "--no-prefilter", "--result-file", rf], deps));
41
+ assert.deepEqual(prov.calls.filter((c) => c[0] === "start").map((c) => c[1]), [7]);
42
+ assert.equal(res.terminalReason, "merged");
43
+ assert.ok(out.some((l) => /^placement: remote/.test(l)), out.join("\n"));
44
+ });
45
+
46
+ it("--local forces local placement", async () => {
47
+ const prov = fakeProvider(() => ({ terminalReason: "merged" }));
48
+ const { deps, ran } = setup("local", prov, {});
49
+ const { out } = await logs(() => runFromCli(["7", "--repo", "o/r", "--lane", "staging", "--local"], { ...deps, leanModule: core(ran) }));
50
+ assert.equal(ran.length, 1);
51
+ assert.deepEqual(prov.calls, []);
52
+ assert.ok(out.includes("placement: local (--local)"));
53
+ });
54
+
55
+ it("an already placed lane (--placement) is not re-delegated", async () => {
56
+ const prov = fakeProvider(() => ({ terminalReason: "merged" }));
57
+ const { deps, ran } = setup("placed", prov);
58
+ await logs(() => runFromCli(["7", "--repo", "o/r", "--lane", "staging", "--placement", "remote", "--placement-reason", "mode remote"], { ...deps, leanModule: core(ran) }));
59
+ assert.equal(ran.length, 1);
60
+ assert.equal(ran[0].where, "remote");
61
+ assert.deepEqual(prov.calls, []);
62
+ });
63
+
64
+ it("no execution config runs locally and says so", async () => {
65
+ const prov = fakeProvider(() => ({ terminalReason: "merged" }));
66
+ const { deps, ran } = setup("none", prov, { execution: undefined });
67
+ const { out } = await logs(() => runFromCli(["7", "--repo", "o/r", "--lane", "staging"], { ...deps, leanModule: core(ran) }));
68
+ assert.equal(ran.length, 1);
69
+ assert.ok(out.some((l) => /^placement: local/.test(l)));
70
+ });
71
+
72
+ it("remote run-issue result file carries bench fields", async () => {
73
+ const prov = fakeProvider((n) => ({ terminalReason: "merged", pr: `https://x/pull/${n}`, cost_usd: 1.5, wall_ms: 1200, model_ms: 900 }));
74
+ const { deps, work } = setup("bench", prov);
75
+ const rf = join(work, "result.json");
76
+ await logs(() => runFromCli(["8", "--repo", "o/r", "--no-prefilter", "--result-file", rf], deps));
77
+ const r = JSON.parse(readFileSync(rf, "utf8"));
78
+ assert.equal(r.terminalReason, "merged");
79
+ assert.equal(r.cost_usd, 1.5); assert.equal(r.wall_ms, 1200); assert.equal(r.model_ms, 900);
80
+ assert.match(String(r.pr), /8$/);
81
+ });
82
+ });
@@ -47,6 +47,7 @@ export function isActionsEndpoint(endpoint) {
47
47
  * (`token` is a string, or a function called per request, #5144).
48
48
  * 429/503 on launch is a retryable capacity error (`Retry-After` seconds). Error text never carries the token.
49
49
  * Optional `POST /sandboxes/:id/stop` (#4612) asks the pool to SIGTERM the lane so its teardown checkpoints and it reports `deferred run.interrupted`; 2xx = sent, 404/405 = unsupported or gone (never a DELETE fallback).
50
+ * `GET /agents -> {sandboxes}` is the router's live sandbox list (#5422, `inventory()`; malformed or any error throws).
50
51
  * Optional relay (#4778): `GET /sandboxes/:id/relay -> {requests: [{rid, argv}]}` lists a sandbox's pending read-only capability
51
52
  * requests (404/405 or malformed = none, an older router) and `POST /sandboxes/:id/relay/:rid` `{rc, stdout, stderr}` answers one.
52
53
  * Optional `GET /status -> {free: N, online?, total?}` is the pool's free slots (#4540); without `online` the agents of `GET /agents` give it (#4788). Anything else (404, error, malformed) is unknown (null).
@@ -94,6 +95,21 @@ export function httpTransport({ endpoint, token = null, fetchFn = globalThis.fet
94
95
  async usage(id) { const r = await call("GET", `${p(id)}/usage`); return r.ok && Number.isFinite(Number(r.data?.minutes)) ? { minutes: Number(r.data.minutes), ...(typeof r.data.agent === "string" && r.data.agent ? { agent: r.data.agent } : {}) } : null; }, // agent: #4549, optional
95
96
  async stop(id) { const r = await call("POST", `${p(id)}/stop`); if (r.ok) return true; if (r.status === 404 || r.status === 405) return false; throw fail("stop", r); },
96
97
  async destroy(id) { const r = await call("DELETE", p(id)); if (r.ok || r.status === 404) return true; throw fail("destroy", r); },
98
+ /** #5422: the sandboxes the router knows (`GET /agents` -> `sandboxes`, id -> {agent, issue, batch}) as [{id, issue}]. Anything but a well-formed answer throws: an unknown list is never an empty one. */
99
+ async inventory() {
100
+ const r = await call("GET", "/agents");
101
+ if (!r.ok) throw fail("inventory", r);
102
+ const m = r.data?.sandboxes;
103
+ if (!m || typeof m !== "object" || Array.isArray(m)) throw new Error("sandbox inventory: malformed router answer");
104
+ return Object.entries(m).map(([id, x]) => ({ id, issue: x?.issue ?? null, disk_used_mb: Number.isFinite(x?.disk_used_mb) ? x.disk_used_mb : null })); // #5535: null = old agent
105
+ },
106
+ /** #5535: each pool agent's free disk from `GET /agents` -> `agents[]` as [{name, disk_free_gb|null}]; a bad answer throws. */
107
+ async agentDisk() {
108
+ const r = await call("GET", "/agents");
109
+ if (!r.ok) throw fail("agent disk", r);
110
+ if (!Array.isArray(r.data?.agents)) throw new Error("agent disk: malformed router answer");
111
+ return r.data.agents.map((a) => ({ name: String(a?.name ?? "?"), disk_free_gb: Number.isFinite(a?.disk_free_gb) ? a.disk_free_gb : null }));
112
+ },
97
113
  async relayPending(id) { const r = await call("GET", `${p(id)}/relay`); return r.ok && Array.isArray(r.data?.requests) ? r.data.requests : []; },
98
114
  async relayAnswer(id, rid, out) { const r = await call("POST", `${p(id)}/relay/${encodeURIComponent(rid)}`, out); if (!r.ok) throw fail("relay answer", r); return true; },
99
115
  async capacity() {