forgedock 1.68.0 → 1.70.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 (68) hide show
  1. package/bin/engine-cli.mjs +4 -9
  2. package/bin/lean/advisory.test.mjs +14 -5
  3. package/bin/lean/batch.mjs +11 -1
  4. package/bin/lean/capsample.mjs +25 -0
  5. package/bin/lean/conformance.mjs +9 -1
  6. package/bin/lean/conformance.test.mjs +7 -0
  7. package/bin/lean/depcache.mjs +2 -0
  8. package/bin/lean/effects.mjs +15 -1
  9. package/bin/lean/envgap.mjs +18 -0
  10. package/bin/lean/envgap.test.mjs +12 -1
  11. package/bin/lean/execution.mjs +3 -0
  12. package/bin/lean/execution.test.mjs +21 -0
  13. package/bin/lean/failure-stop.mjs +12 -1
  14. package/bin/lean/failure-stop.test.mjs +14 -1
  15. package/bin/lean/hostconfig.mjs +54 -0
  16. package/bin/lean/hostconfig.test.mjs +67 -0
  17. package/bin/lean/issuewatch-parity.test.mjs +1 -1
  18. package/bin/lean/lane-audit-llm.mjs +51 -4
  19. package/bin/lean/lane-audit-llm.test.mjs +57 -0
  20. package/bin/lean/lane-audit.mjs +1 -1
  21. package/bin/lean/lean.mjs +63 -26
  22. package/bin/lean/lean.test.mjs +100 -19
  23. package/bin/lean/live-execution.mjs +3 -0
  24. package/bin/lean/live-execution.test.mjs +23 -0
  25. package/bin/lean/orchestrate-dispatch-placement.test.mjs +81 -0
  26. package/bin/lean/orchestrate-envhold.test.mjs +15 -1
  27. package/bin/lean/orchestrate.mjs +27 -9
  28. package/bin/lean/preflight.mjs +10 -3
  29. package/bin/lean/preflight.test.mjs +21 -1
  30. package/bin/lean/prompts.mjs +1 -0
  31. package/bin/lean/release-cigreen.mjs +204 -0
  32. package/bin/lean/release-cigreen.test.mjs +115 -0
  33. package/bin/lean/release-deploy.mjs +35 -5
  34. package/bin/lean/release-deploy.test.mjs +50 -3
  35. package/bin/lean/release-fixloop.mjs +1 -1
  36. package/bin/lean/release-flakes.mjs +34 -0
  37. package/bin/lean/release-flakes.test.mjs +28 -0
  38. package/bin/lean/release-ledger.test.mjs +4 -4
  39. package/bin/lean/release-preflight.test.mjs +2 -2
  40. package/bin/lean/release-rehearsal.test.mjs +1 -1
  41. package/bin/lean/release-review.e2e.test.mjs +4 -3
  42. package/bin/lean/release-review.mjs +136 -56
  43. package/bin/lean/release-review.test.mjs +97 -12
  44. package/bin/lean/release-status.mjs +3 -2
  45. package/bin/lean/release-status.test.mjs +2 -2
  46. package/bin/lean/release.mjs +6 -3
  47. package/bin/lean/release.test.mjs +33 -12
  48. package/bin/lean/sandbox-remote.mjs +35 -4
  49. package/bin/lean/schedd.mjs +2 -2
  50. package/bin/pool/agent.mjs +105 -15
  51. package/bin/pool/cli.mjs +22 -4
  52. package/bin/pool/docker.mjs +2 -0
  53. package/bin/pool/image-manifest.mjs +24 -0
  54. package/bin/pool/image-manifest.test.mjs +20 -0
  55. package/bin/pool/lane-tools.mjs +23 -4
  56. package/bin/pool/lane-tools.test.mjs +27 -7
  57. package/bin/pool/project-layer.mjs +142 -0
  58. package/bin/pool/project-layer.test.mjs +73 -0
  59. package/bin/pool/router.mjs +20 -6
  60. package/bin/pool/version.mjs +45 -2
  61. package/bin/review-staging.mjs +63 -21
  62. package/bin/stats/tool-parks.mjs +29 -0
  63. package/bin/stats/tool-parks.test.mjs +21 -0
  64. package/commands/review-pr-staging.md +1 -1
  65. package/docs/CONFIG.md +20 -0
  66. package/package.json +1 -1
  67. package/pool/image/Dockerfile +1 -1
  68. package/scripts/ci-local.test.sh +3 -2
@@ -217,6 +217,9 @@ export const transientRetryDelayMs = (k) => Math.min(TRANSIENT_BACKOFF_S * 4 **
217
217
  // the batch stays open up to ENV_HOLD_MAX_MS re-checking every ENV_WATCH_MS for an engine version change, a batch env change or the tool.
218
218
  export const ENV_HOLD_MAX_MS = 24 * 3600_000;
219
219
  export const ENV_WATCH_MS = 30_000;
220
+ /** #6123: after a re-admit (env issue closed / tool probe passed) ends in the same env signature, the next re-admit waits 15 m, then 1 h, then 4 h. */
221
+ export const ENV_READMIT_BACKOFF_MS = [15 * 60_000, 3600_000, 4 * 3600_000];
222
+ export const envReadmitBackoffMs = (k) => ENV_READMIT_BACKOFF_MS[Math.min(Math.max(1, k), ENV_READMIT_BACKOFF_MS.length) - 1];
220
223
  /** #5805: `code|first message line`, with times, hex ids and numbers normalised, so a pid or path id does not make a repeat look new. */
221
224
  export function failureSignature(code, detail) {
222
225
  const line = String(detail ?? "").split("\n").find((l) => l.trim()) ?? "";
@@ -381,6 +384,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
381
384
  // `deterministic`: `version|signature` seen twice (never relaunched again on that version); `toolReadmits`: `issue|signature`
382
385
  // already re-admitted because the probe found the tool (a lane that still misses it waits for an engine or env change instead).
383
386
  const ehOn = !!envHold || !!envIssue;
387
+ const envReadmits = new Map(); // #6123: issue -> {sig, count, at} of the last env-issue/tool-probe re-admit
384
388
  // #5755: env.* failures are one engine/env defect per signature: `envSigs` signature -> {issues, number} (the env issue the `envIssue` seam
385
389
  // filed or updated); affected product issues are held on it (never needs-human) and 2+ issues on a signature stop admitting lanes that need it.
386
390
  const envSigs = toMap(saved?.envSigs);
@@ -457,7 +461,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
457
461
  let budgetLocal = false; // the execution budget refused a remote lane under on_budget local: the rest run on the host
458
462
  // #4256: where a lane goes before capacity: `remote.place` (hybrid) or `remote.isRemote` (remote mode).
459
463
  const hostFallbackOn = () => remote?.hostFallback !== false; // #5652: unset keeps the host re-placement
460
- const placeOf = (n) => {
464
+ const placeRaw = (n) => {
461
465
  if (!remote) return null;
462
466
  // #4542: a lane recovering from a remote capability block runs on the host, which has the capability.
463
467
  // #4785: a tool-missing recovery too: the sandbox that lacked the tool is not chosen again.
@@ -488,6 +492,13 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
488
492
  return remote.isRemote?.(n) ? { where: "remote", reason: "mode remote" } : { where: "local", reason: "local" };
489
493
  } catch { return hostFallbackOn() ? { where: "local", reason: "placement failed" } : { where: "remote", reason: "placement failed, host fallback off: retry remotely" }; } // #5746
490
494
  };
495
+ // #5746: in remote mode the host is orchestrator-only unless host_fallback is true: whatever branch below picks the host (a `needs`
496
+ // capability, a host pin, a failed placement), the lane is placed remotely instead. An operator's live `--set-placement local` is not a fallback.
497
+ const placeOf = (n) => {
498
+ const p = placeRaw(n);
499
+ if (p?.where === "local" && remote?.mode === "remote" && !hostFallbackOn() && p.reason !== "live placement: local") return { where: "remote", reason: `host fallback off, not on the host: ${p.reason}` };
500
+ return p;
501
+ };
491
502
  const isRemote = (n) => placeOf(n)?.where === "remote";
492
503
  const placed = new Map(); // issue -> {where, reason} granted this pass, picked up by start()
493
504
  const sandboxUse = toMap(saved?.sandbox); // issue -> {minutes, cost_usd, attempts} (#4255)
@@ -1091,8 +1102,13 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1091
1102
  row.minutes = Math.round(((Number(row.minutes) || 0) + (Number(p.minutes) || 0)) * 10) / 10;
1092
1103
  }
1093
1104
  const triggers = [...(envIssueNo ? [`env issue #${envIssueNo} closing`] : []), "an engine upgrade", ...(envHold?.envFingerprint ? ["a --set-env"] : []), ...(tools?.length && envHold?.missingTools ? [`${tools.join(", ")} found on the host`] : [])];
1094
- const final = { ...row, outcome: "held", detail: `waiting on engine/env change: ${why}; re-admitted on ${triggers.join(" or ")}\n${String(row.detail ?? "")}`,
1095
- envHold: { kind, sig, from: row.outcome, version: curVersion(), env: curEnv(), ...(tools?.length ? { tools } : {}), ...(envIssueNo ? { envIssue: envIssueNo } : {}), since: now() }, waiting: true };
1105
+ // #6123: the previous re-admit (env issue closed / tool found) ended in this same signature: back off before the next one
1106
+ const prior = envReadmits.get(n);
1107
+ let notBefore = null;
1108
+ if (prior && prior.sig === sig) { prior.count += 1; notBefore = now() + envReadmitBackoffMs(prior.count); }
1109
+ else if (prior) envReadmits.delete(n);
1110
+ const final = { ...row, outcome: "held", detail: `waiting on engine/env change: ${why}; re-admitted on ${triggers.join(" or ")}${notBefore ? ` (not before ${new Date(notBefore).toISOString()}: the same ${sig.split("|")[0]} repeated after a re-admit)` : ""}\n${String(row.detail ?? "")}`,
1111
+ envHold: { kind, sig, from: row.outcome, version: curVersion(), env: curEnv(), ...(tools?.length ? { tools } : {}), ...(envIssueNo ? { envIssue: envIssueNo } : {}), ...(notBefore ? { notBefore } : {}), since: now() }, waiting: true };
1096
1112
  results.set(n, final); done(); save();
1097
1113
  decided({ issue: n, what: `held: waiting on engine/env change (${why})`, why: firstLine(row.detail) || row.outcome,
1098
1114
  alternative: kind === "engine" ? "relaunch into the same engine-error, or end engine-error and wait for a manual --requeue" : "launch a recovery that fails the same way, or end needs-human and wait for a manual --requeue" });
@@ -1462,7 +1478,8 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1462
1478
  }
1463
1479
  const lane = ln?.lane;
1464
1480
  if (relabelled.delete(n)) save(); // #4315: the recovery lane launches after all; it removes needs-human itself
1465
- const pl = placed.get(n);
1481
+ // #5746: every running entry records where it runs; a lane admitted without a recorded placement (a requeue path) is derived, never left blank
1482
+ const pl = placed.get(n) ?? (remote ? (remoteRun.has(n) ? { where: "remote", reason: "mode remote" } : (placeOf(n) ?? undefined)) : undefined);
1466
1483
  placed.delete(n);
1467
1484
  const queueMs = Number.isFinite(enqueued.get(n)) ? Math.max(0, now() - enqueued.get(n)) : null; // #4908: queue_wait in the phase ledger
1468
1485
  heads.delete(n); enqueued.delete(n); busyNoted.delete(n);
@@ -1972,8 +1989,9 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1972
1989
  continue;
1973
1990
  }
1974
1991
  }
1975
- let why = null;
1976
- if (h.envIssue && typeof envIssue?.isClosed === "function") { let c = false; try { c = (await envIssue.isClosed(h.envIssue)) === true; } catch { c = false; } if (c) why = `env issue #${h.envIssue} closed`; }
1992
+ let why = null, probeOrIssue = false;
1993
+ const backedOff = Number(h.notBefore) > now(); // #6123
1994
+ if (!backedOff && h.envIssue && typeof envIssue?.isClosed === "function") { let c = false; try { c = (await envIssue.isClosed(h.envIssue)) === true; } catch { c = false; } if (c) { why = `env issue #${h.envIssue} closed`; probeOrIssue = true; } }
1977
1995
  // R6/R8: a remote lane runs on a pool agent, so its engine is the agent's, not this host's. While every placeable agent is below the engine
1978
1996
  // the lane needs, the hold stays; an agent upgrade (not the orchestrator's) is the trigger.
1979
1997
  const av = r.placement?.where === "remote" ? await agentVersionOf() : null;
@@ -1983,8 +2001,8 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1983
2001
  else if (needMM && vmm2(av) === needMM && v && h.version && v !== h.version) why = `engine version changed v${h.version} → v${v}`;
1984
2002
  } else if (!why && v && h.version && v !== h.version) why = `engine version changed v${h.version} → v${v}`;
1985
2003
  if (why) { /* env issue closed */ } else if (fp && h.env && fp !== h.env) why = "batch env changed (--set-env)";
1986
- else if (h.tools?.length && !toolReadmits.has(`${n}|${h.sig}`) && (await missingTools(h.tools))?.length === 0) { why = `${h.tools.join(", ")} now found on the host`; toolReadmits.add(`${n}|${h.sig}`); }
1987
- if (why) { if (!(await gateAdmit(n))) continue; engineSigs.delete(n); releaseHeld(n, true, `re-admitted: ${why}`); continue; }
2004
+ else if (!backedOff && h.tools?.length && !toolReadmits.has(`${n}|${h.sig}`) && (await missingTools(h.tools))?.length === 0) { why = `${h.tools.join(", ")} now found on the host`; toolReadmits.add(`${n}|${h.sig}`); probeOrIssue = true; }
2005
+ if (why) { if (!(await gateAdmit(n))) continue; engineSigs.delete(n); if (probeOrIssue) envReadmits.set(n, { sig: h.sig, count: envReadmits.get(n)?.sig === h.sig ? envReadmits.get(n).count : 0, at: now() }); releaseHeld(n, true, `re-admitted: ${why}`); continue; }
1988
2006
  if (now() - (Number(h.since) || 0) >= ehMaxMs && !/no engine\/env change within/.test(r.detail ?? "")) { // the wait is over: the row stays held (resumable, --requeue), the batch may end
1989
2007
  const { waiting, ...rest } = r;
1990
2008
  const [head, ...tail] = String(rest.detail ?? "").split("\n");
@@ -2507,7 +2525,7 @@ export function formatTable(rows) {
2507
2525
  */
2508
2526
  export function phasesOf(r, rec) {
2509
2527
  if (!r?.phases || typeof r.phases !== "object" || !Object.keys(r.phases).length) return null;
2510
- return { ...(Number.isFinite(rec?.queueMs) && rec.queueMs > 0 ? { queue_wait: { ms: Math.round(rec.queueMs) } } : {}), ...r.phases };
2528
+ return { ...(Number.isFinite(rec?.queueMs) && rec.queueMs > 0 ? { queue_wait: { ms: Math.round(rec.queueMs), ...((r.sandbox?.agent ?? r.agent) ? { worker: r.sandbox?.agent ?? r.agent } : {}) } } : {}), ...r.phases };
2511
2529
  }
2512
2530
 
2513
2531
  export function formatWaitSummary(rows, heavyStats = null) {
@@ -13,6 +13,7 @@ import { builtinModules } from "node:module";
13
13
  import { existsSync } from "node:fs";
14
14
  import { join, dirname, delimiter, posix } from "node:path";
15
15
  import { missingTool } from "./conformance.mjs";
16
+ import { hostPoetryConfigProblem } from "./hostconfig.mjs";
16
17
 
17
18
  export const PREFLIGHT_CAP = 20;
18
19
  const KIND_NAME = { command: "command", "python-module": "Python module", "node-module": "Node package", path: "path", "env-var": "env var" };
@@ -101,7 +102,7 @@ function moduleNeeds(exe, args) {
101
102
  /**
102
103
  * The probes for `contract.validate[]`: {probes: [{ids, tool, kind, interp, needs, probe}], dropped}. `needs` is the command
103
104
  * probe (tool) a module probe depends on: skip the module probe when its interpreter is missing. A name `repoHas(name)` holds
104
- * or a deliverable's change text names (the change adds it) is not probed; paths and `$...` words are never probed.
105
+ * or a deliverable's change text names (the change adds it) is not probed; nor is a tool `provided(name)` (the image manifest, #6037); paths and `$...` words are never probed.
105
106
  */
106
107
  /** #5020: the contract's runnable commands: each validate entry plus the repro_test, which fails the same ways. */
107
108
  export function contractCommands(contract) {
@@ -109,10 +110,10 @@ export function contractCommands(contract) {
109
110
  const t = contract?.repro_test;
110
111
  return t && typeof t === "object" && typeof t.command === "string" && t.command.trim() ? [...out, { id: "repro_test", command: t.command }] : out;
111
112
  }
112
- export function preflightProbes(contract, { repoHas = () => false, cap = PREFLIGHT_CAP } = {}) {
113
+ export function preflightProbes(contract, { repoHas = () => false, provided = () => false, cap = PREFLIGHT_CAP } = {}) {
113
114
  const changes = (Array.isArray(contract?.deliverables) ? contract.deliverables : []).map((d) => String(d?.change ?? "")).join("\n");
114
115
  const named = (name) => new RegExp(`(^|[^\\w@/.-])${name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?![\\w/-])`).test(changes);
115
- const skip = (name) => !name || name.includes("/") && !name.startsWith("@") || name.startsWith("$") || repoHas(name) || named(name);
116
+ const skip = (name) => !name || provided(name) || name.includes("/") && !name.startsWith("@") || name.startsWith("$") || repoHas(name) || named(name);
116
117
  const byKey = new Map();
117
118
  const add = (id, kind, tool, interp = null) => {
118
119
  const key = `${kind}|${tool}|${interp ?? ""}`;
@@ -517,3 +518,9 @@ export function venvPythonRewrite(command, files = [], exists = () => false) {
517
518
  });
518
519
  return changed ? out.join("") : String(command ?? "");
519
520
  }
521
+
522
+ /** #5917: host config defects (not contract misses): a poisoned poetry config fails every host validate as if the change were wrong. */
523
+ export function hostEnvDefects(opts = {}) {
524
+ const p = hostPoetryConfigProblem(opts);
525
+ return p ? [p] : [];
526
+ }
@@ -4,7 +4,7 @@ import { describe, it } from "node:test";
4
4
  import assert from "node:assert/strict";
5
5
  import { mkdirSync, writeFileSync } from "node:fs";
6
6
  import { join, delimiter } from "node:path";
7
- import { manifestDepOwner, venvPythonRewrite, testRunnerProblems, shellSegments, pythonImports, nodeImports, preflightProbes, preflightProblems, runProbeMiss, unsetEnvVars, runPreflight, knownToContract, contractCommands, depInstallFailures, toolMissingInstalls, testRunSummary, projectBinDirs, withLocalBins, collectOnlyCommand, collectImportMiss, declaredEnv } from "./preflight.mjs";
7
+ import { manifestDepOwner, venvPythonRewrite, testRunnerProblems, shellSegments, pythonImports, nodeImports, preflightProbes, preflightProblems, runProbeMiss, unsetEnvVars, runPreflight, knownToContract, contractCommands, depInstallFailures, toolMissingInstalls, testRunSummary, projectBinDirs, withLocalBins, collectOnlyCommand, collectImportMiss, declaredEnv, hostEnvDefects } from "./preflight.mjs";
8
8
  import { runCheckCommand } from "./effects.mjs";
9
9
  import { repoTracks } from "./conformance.mjs";
10
10
  import { tmpDir } from "../tests/_tmp.mjs";
@@ -281,3 +281,23 @@ describe("#5753 collect-only import preflight and tracked-dir env names", () =>
281
281
  assert.deepEqual(declaredEnv(c), ["shared", "pytest"], "without tracked paths the name is unchanged");
282
282
  });
283
283
  });
284
+
285
+ describe("hostEnvDefects (#5917)", () => {
286
+ it("surfaces a poisoned poetry host config as an env defect, not a miss", () => {
287
+ const d = tmpDir("preflight-poetry-"); writeFileSync(join(d, "config.toml"), "[virtualenvs]\ncreate = false\n");
288
+ const r = hostEnvDefects({ env: { POETRY_CONFIG_DIR: d } });
289
+ assert.equal(r.length, 1);
290
+ assert.equal(r[0].code, "env.host_poetry_config");
291
+ assert.deepEqual(hostEnvDefects({ env: { POETRY_CONFIG_DIR: tmpDir("preflight-empty-") } }), []);
292
+ });
293
+ });
294
+
295
+ describe("#6037 provided() skips image-manifest command probes", () => {
296
+ it("skips provided tools, still probes others and modules", () => {
297
+ const c = C("shellcheck x.sh && yq . a.yml && ripgrep foo && python3 -c 'import yaml'");
298
+ const provided = (n) => ["shellcheck", "yq", "python3"].includes(n);
299
+ assert.deepEqual(needs(c, { provided }), [["command", "ripgrep", null, "V1"], ["python-module", "yaml", "python3", "V1"]]);
300
+ assert.deepEqual(needs(c), needs(c, {}));
301
+ assert.ok(needs(c).some((p) => p[1] === "shellcheck"));
302
+ });
303
+ });
@@ -473,6 +473,7 @@ const BLOCK_RULES = `"blocked" needs a typed "block" in ${RESULT_FILE}, one of:
473
473
  - {"kind":"split-required","subissues":[{"title":"","body":"","depends_on":[0],"files":["<path>"]}],"size":{"files":N,"lines":N}}: too big for one change. The engine files the sub-issues (depends_on = indexes of earlier sub-issues; files = the files or dirs each will edit, also accepted as "paths") only when every sub-issue's files are disjoint from the others' or the whole change's size estimate exceeds ${SPLIT_MIN_FILES} files or ${SPLIT_MIN_LINES} lines; otherwise keep one lane: an ordered checklist in the contract with a validate per item. In an admitted split, siblings editing the same hub (barrel or index export list, union type, shared fixture, index doc) get its slots pre-staged in the earliest sub-issue, which the others depend on, or their own per-feature files; the engine serialises sub-issues still sharing a file.
474
474
  - {"kind":"design-invalidated","decision":"<what no longer holds>","why":"","epic":N}: the design is wrong; the engine files one amendment and holds open siblings.
475
475
  - {"kind":"human","why":"${HUMAN_BLOCK_REASONS.join("|")}"}: only an external action agents cannot take, or a product decision too critical for agents. Optional "remainder":[{"title","body"}]: the agent-doable rest, filed as its own issue.
476
+ Merging the base into this lane's own branch is the engine's base-sync, never "blocked" or human: say so in the summary and carry on.
476
477
  "An upstream issue must land first", "needs a split" and "needs prod data that read-only monitoring can read" are never "human".
477
478
  A check that times out (rc 124) is host load, never a block: run the narrowest targeted command for your changed files and say the full one could not finish.
478
479
  Remote sandbox lacking a host-only capability (sops, prod_monitor, ops_credentials): name it in the summary.`;
@@ -0,0 +1,204 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * `ci-green` step of `forgedock release`. The default, ForgeDock-owned release flow is the v1.0 contract restored (commands/review-pr-staging.md
5
+ * at dcfb86bf): open-finding gate -> CI green -> ONE review pass on the green head -> verdict. CI comes first because a CI failure after the
6
+ * review moves the head and voids it (drift: #4358, #4360, #5212, #5567).
7
+ *
8
+ * The step runs the open-finding gate (an open review-finding issue blocks the release first), then waits for every required check of the
9
+ * release PR head (branch protection and rulesets of the default branch plus forge.yaml gate.required_checks; forgedock/verify, forge/deploy-gate
10
+ * and the gate-marker check are excluded). A failed check is rerun ONCE (reusing the #5502/#6014 attempt cap); if the rerun passes it is a flake:
11
+ * green, and a `flaky-test` issue is filed naming the test when the log shows it. A check still red after its rerun gets ONE fix round (`fixRound`:
12
+ * a CI fix in the release PR), then CI is awaited again. Timings (`ci_green_min`, `review_min`, `fix_rounds`, `review_passes`) go to `state.timing`,
13
+ * which release status prints and the ledger mirrors. There is no switch to turn the step off.
14
+ */
15
+ import { ciState, requiredSet, reviewStagingJson, reviewStagingIo } from "../review-staging.mjs";
16
+ import { requiredChecksRead } from "./effects.mjs";
17
+ import { attemptGuard, classifyFailure } from "./release-flakes.mjs";
18
+
19
+ export const CI_GREEN_POLL_MS = 30_000;
20
+ export const CI_GREEN_MAX_WAIT_MIN = 40;
21
+ const SEVERITY_ORDER = ["CRITICAL", "HIGH", "MEDIUM", "LOW"];
22
+ const json = (s) => JSON.parse(String(s || "null"));
23
+
24
+ /** forge.yaml `release.ci_green.max_wait_min` and `release.block_severity` (lowest blocking severity; default high) -> `{ciGreen, blockSeverity}`; only set keys are returned. */
25
+ export function ciGreenKeys(r) {
26
+ const out = {};
27
+ const wait = Number(r?.ci_green?.max_wait_min ?? r?.ci_green_max_wait_min);
28
+ if (Number.isFinite(wait) && wait > 0) out.ciGreen = { maxWaitMin: Math.min(wait, 240) };
29
+ const sev = String(r?.block_severity ?? "").trim().toUpperCase();
30
+ if (SEVERITY_ORDER.includes(sev)) out.blockSeverity = sev;
31
+ if (/^(true|on|yes|1)$/i.test(String(r?.review_fixes ?? ""))) out.reviewFixes = true; // compatibility knob, default off: the #5212 review fix lanes and delta passes
32
+ return out;
33
+ }
34
+
35
+ /** Set of severities that block: CRITICAL down to `config.blockSeverity` (default HIGH). */
36
+ export function blockSetOf(config) {
37
+ const at = SEVERITY_ORDER.indexOf(config?.blockSeverity);
38
+ return new Set(SEVERITY_ORDER.slice(0, at >= 0 ? at + 1 : 2));
39
+ }
40
+
41
+ /** `state.timing[key]`: minutes (1 decimal) added for `ms`, or a raw count with `raw`, or the value itself with `set`. */
42
+ export function addTiming(ctx, key, n, { raw = false, set = false } = {}) {
43
+ const t = (ctx.state.timing ??= {});
44
+ t[key] = set ? n : raw ? (t[key] ?? 0) + n : Math.round(((t[key] ?? 0) + n / 60_000) * 10) / 10;
45
+ ctx.save?.();
46
+ }
47
+
48
+ /** Best-effort test name from a failed log: tap `not ok`, node test runner, jest/mocha, pytest/cargo style lines. */
49
+ export function flakyTestName(log) {
50
+ const text = String(log ?? "");
51
+ const pats = [/^\s*not ok \d+ - (.+)$/m, /^\s*(?:✖|✗|×) (.+?)(?: \(\d[^)]*\))?\s*$/m, /^\s*● (.+)$/m, /^\s*(?:FAILED|FAIL) (\S+(?:::\S+)*)/m, /^\s*test (\S+) \.\.\. FAILED/m, /^\s*\d+\) (.+)$/m];
52
+ for (const re of pats) { const m = re.exec(text); if (m?.[1]?.trim()) return m[1].trim().slice(0, 120); }
53
+ return null;
54
+ }
55
+
56
+ const runIdOf = (link) => /\/actions\/runs\/(\d+)/.exec(String(link ?? ""))?.[1] ?? null;
57
+ const bucketOf = (status, conclusion) => {
58
+ if (status && status !== "completed") return "pending";
59
+ if (["success", "neutral", "skipped"].includes(conclusion)) return "pass";
60
+ if (conclusion === "cancelled") return "cancel";
61
+ return conclusion ? "fail" : "pending";
62
+ };
63
+
64
+ /** Real effects of ci-green. Tests inject `ctx.io.ciGreen` with the same shape. */
65
+ export function realCiSeam(ctx) {
66
+ const { io, repo } = ctx;
67
+ const gh = (a) => io.gh(a);
68
+ return {
69
+ sleep: (ms) => io.sleep(ms),
70
+ now: () => io.now?.() ?? Date.now(),
71
+ // The open-finding gate first (review-staging --gate-only: bundle PR set + open review-finding issues). @returns null when it passes, else the reason.
72
+ openGate: async (pr) => {
73
+ const r = await reviewStagingJson([String(pr), "--gate-only"], { ...reviewStagingIo(), cwd: ctx.cwd ?? process.cwd(), env: process.env });
74
+ return r.code === 0 ? null : String((r.lines ?? []).filter(Boolean).slice(-3).join(" | ")).slice(0, 400) || `exit ${r.code}`;
75
+ },
76
+ isDraft: async (pr) => Boolean(json(await gh(["pr", "view", String(pr), "--repo", repo, "--json", "isDraft"]))?.isDraft),
77
+ headOf: async (pr) => String(await gh(["pr", "view", String(pr), "--repo", repo, "--json", "headRefOid", "--jq", ".headRefOid"])).trim(),
78
+ checks: async ({ head }) => {
79
+ const runs = json(await gh(["api", `repos/${repo}/commits/${head}/check-runs?per_page=100`, "--jq", "[.check_runs[] | {name, status, conclusion, link: .details_url}]"])) ?? [];
80
+ let statuses = [];
81
+ try { statuses = json(await gh(["api", `repos/${repo}/commits/${head}/status`, "--jq", "[.statuses[] | {name: .context, state, link: .target_url}]"])) ?? []; } catch { /* check runs alone */ }
82
+ return [
83
+ ...runs.map((k) => ({ name: k.name, bucket: bucketOf(k.status, k.conclusion), link: k.link })),
84
+ ...statuses.map((k) => ({ name: k.name, bucket: k.state === "success" ? "pass" : k.state === "pending" ? "pending" : "fail", link: k.link })),
85
+ ];
86
+ },
87
+ required: async () => {
88
+ const read = await requiredChecksRead({ gh, repo, lane: ctx.def });
89
+ return requiredSet(read, ctx.config?.requiredChecks ?? []);
90
+ },
91
+ runAttempt: async (id) => { try { return json(await gh(["run", "view", id, "--repo", repo, "--json", "attempt"]))?.attempt ?? null; } catch { return null; } },
92
+ failedLog: async (id) => { try { return String(await gh(["run", "view", id, "--repo", repo, "--log-failed"])).slice(-20_000); } catch { return ""; } },
93
+ rerunFailed: (id) => gh(["run", "rerun", id, "--repo", repo, "--failed"]),
94
+ fileFlake: async ({ check, test, signature, tail, sha, pr }) => {
95
+ const title = `Flaky test: ${test ?? check}`;
96
+ try {
97
+ const hit = json(await gh(["issue", "list", "--repo", repo, "--state", "open", "--search", `"${title}" in:title`, "--json", "number,title"]))?.find((i) => i.title === title);
98
+ if (hit) return hit.number;
99
+ } catch { /* no lookup: file a new one */ }
100
+ const body = [`Required check \`${check}\` failed on release PR #${pr} at ${String(sha).slice(0, 7)} and passed on one rerun, so the release treated it as green and went on.`, test ? `Test: \`${test}\`` : "The log did not show a test name.", signature ? `Failure signature: ${signature}` : "", "", "```", String(tail ?? "").slice(-1200), "```"].filter((l) => l !== "").join("\n");
101
+ try { await gh(["label", "create", "flaky-test", "--repo", repo, "--color", "FBCA04", "--description", "A test that fails and then passes on rerun", "--force"]); } catch { /* the label is best effort */ }
102
+ for (const labels of [["--label", "flaky-test"], []]) {
103
+ try { return Number(/\/issues\/(\d+)/.exec(String(await gh(["issue", "create", "--repo", repo, "--title", title, "--body", body, ...labels])))?.[1]) || null; } catch { /* retry without the label */ }
104
+ }
105
+ return null;
106
+ },
107
+ };
108
+ }
109
+ const ciSeamOf = (ctx) => ctx.io.ciGreen ?? (ctx.ciSeam ??= realCiSeam(ctx));
110
+
111
+ /** Per-head bookkeeping: checks already rerun, the first failure of each (test name, signature) and the flakes already filed. */
112
+ const headRec = (state, head) => ((state.ciGreen ??= { heads: {}, flakes: [] }).heads[head] ??= { reran: [], firstFail: {}, filed: [] });
113
+
114
+ /**
115
+ * Wait until every required check of `pr`'s head is green. @returns
116
+ * `{ok: true, head, flakes}` | `{red: true, head, failing}` (still red after its one rerun) | `{blocked: true, reason}` (timed out).
117
+ */
118
+ async function waitGreen(ctx, pr, seam) {
119
+ const { state } = ctx;
120
+ const deadline = seam.now() + (ctx.config?.ciGreen?.maxWaitMin ?? CI_GREEN_MAX_WAIT_MIN) * 60_000;
121
+ for (;;) {
122
+ const head = await seam.headOf(pr);
123
+ const [checks, required] = [await seam.checks({ pr, head }), await seam.required()];
124
+ const st = ciState(checks, required);
125
+ const rec = headRec(state, head);
126
+ if (st.green) {
127
+ const flakes = [];
128
+ for (const [check, ff] of Object.entries(rec.firstFail)) {
129
+ if (rec.filed.includes(check)) continue;
130
+ const issue = await seam.fileFlake({ check, test: ff.test, signature: ff.signature, tail: ff.tail, sha: head, pr });
131
+ rec.filed.push(check);
132
+ state.ciGreen.flakes.push({ check, test: ff.test ?? null, issue: issue ?? null, sha: head });
133
+ flakes.push({ check, test: ff.test ?? null, issue: issue ?? null });
134
+ }
135
+ if (flakes.length) ctx.io.print?.(`release: ci-green: ${flakes.map((f) => `${f.check} (passed on rerun${f.issue ? `, flaky-test #${f.issue}` : ""})`).join("; ")}`);
136
+ ctx.save?.();
137
+ return { ok: true, head, flakes };
138
+ }
139
+ if (st.pending.length) {
140
+ if (seam.now() >= deadline) return { blocked: true, reason: `required checks of #${pr} still pending after ${ctx.config?.ciGreen?.maxWaitMin ?? CI_GREEN_MAX_WAIT_MIN} min (${st.pending.join(", ")}); re-run the release once CI finishes` };
141
+ await seam.sleep(CI_GREEN_POLL_MS);
142
+ continue;
143
+ }
144
+ const fresh = st.failing.filter((n) => !rec.reran.includes(n));
145
+ if (!fresh.length) return { red: true, head, failing: st.failing };
146
+ // First failure of these checks: one rerun of each failed run, never past the attempt cap. A status context has no run: it stays red.
147
+ const ids = new Map();
148
+ for (const name of fresh) {
149
+ rec.reran.push(name);
150
+ const row = checks.find((k) => k.name === name && (k.bucket === "fail" || k.bucket === "cancel"));
151
+ const id = runIdOf(row?.link);
152
+ if (!id) continue;
153
+ if (row.bucket === "fail") {
154
+ const log = await seam.failedLog(id);
155
+ rec.firstFail[name] = { test: flakyTestName(log), signature: classifyFailure(log).signature ?? null, tail: log.slice(-1200) };
156
+ }
157
+ ids.set(id, name);
158
+ }
159
+ ctx.save?.();
160
+ let reran = 0;
161
+ for (const id of ids.keys()) {
162
+ if (!attemptGuard({ attempt: await seam.runAttempt(id) }).allow) continue;
163
+ await seam.rerunFailed(id);
164
+ reran++;
165
+ }
166
+ if (!reran) return { red: true, head, failing: st.failing };
167
+ ctx.io.print?.(`release: ci-green: rerunning ${[...ids.values()].join(", ")} once`);
168
+ await seam.sleep(CI_GREEN_POLL_MS);
169
+ }
170
+ }
171
+
172
+ /**
173
+ * Wait for CI green on `pr`; on a real red run the fix path once (unless `noFix`) and wait again. Time spent is added to `ci_green_min`.
174
+ * @returns `{ok, head}` | `{red, failing}` (only with `noFix` or after the fix round) | `{blocked, reason}`
175
+ */
176
+ export async function ciGreenWait(ctx, pr, { noFix = false } = {}) {
177
+ const seam = ciSeamOf(ctx);
178
+ const t0 = Date.now();
179
+ try {
180
+ if (await seam.isDraft?.(pr)) return { ok: true, skipped: "draft" }; // host preflight mode: no Actions CI until mark-ready
181
+ for (;;) {
182
+ const w = await waitGreen(ctx, pr, seam);
183
+ if (!w.red || noFix) return w;
184
+ if (Object.values(ctx.state.fixloop?.heads ?? {}).some((h) => !h.second)) return { blocked: true, reason: `required checks of #${pr} are red again after the fix round (${w.failing.join(", ")}); the one fix round is spent` };
185
+ const { fixRound, seamOf } = await import("./release-review.mjs");
186
+ const f = await fixRound(ctx, seamOf(ctx), { pr, head: w.head, blocking: [], items: [], guards: [], ciFailing: w.failing.length });
187
+ if (f.blocked) return f;
188
+ }
189
+ } finally { addTiming(ctx, "ci_green_min", Date.now() - t0); }
190
+ }
191
+
192
+ /** The `ci-green` release step. A draft release PR (host preflight mode) has no Actions CI yet, so it is recorded as skipped there. */
193
+ export async function ciGreenStep(ctx) {
194
+ const pr = ctx.state?.steps?.["release-pr"]?.result?.pr;
195
+ if (!pr) return { blocked: true, reason: "no release PR recorded by the release-pr step" };
196
+ const seam = ciSeamOf(ctx);
197
+ const gate = await seam.openGate?.(pr); // 1. the open-finding gate: an open review-finding issue blocks the release before CI or any reviewer
198
+ if (gate) return { blocked: true, reason: `open-finding gate: ${gate}; merge or close the open review-finding issues, then re-run the release` };
199
+ if (await seam.isDraft?.(pr)) return { green: false, skipped: "draft PR: CI starts at mark-ready, host preflight runs first" };
200
+ const w = await ciGreenWait(ctx, pr);
201
+ if (w.blocked) return w;
202
+ if (w.red) return { blocked: true, reason: `required checks of #${pr} are red: ${w.failing.join(", ")}` };
203
+ return { green: true, head: w.head, flakes: w.flakes, minutes: ctx.state.timing?.ci_green_min ?? 0 };
204
+ }
@@ -0,0 +1,115 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ // #6164: the default ci-green step: wait for required checks, rerun a failed check once, flake = green + issue, real red = one fix round.
4
+ import { describe, it } from "node:test";
5
+ import assert from "node:assert/strict";
6
+ import { ciGreenStep, ciGreenWait, flakyTestName, blockSetOf, ciGreenKeys, addTiming } from "./release-cigreen.mjs";
7
+ import { RELEASE_STEPS, readReleaseConfig } from "./release.mjs";
8
+
9
+ const H = "c".repeat(40);
10
+ const link = (id) => `https://github.com/o/r/actions/runs/${id}/job/1`;
11
+ /** Seam over a script of check snapshots: `snaps[i]` is what the i-th `checks` call returns (the last repeats). */
12
+ function seam(snaps, o = {}) {
13
+ const log = []; let i = 0, t = 0;
14
+ return {
15
+ log,
16
+ now: () => t, sleep: async (ms) => { t += ms; log.push("sleep"); },
17
+ isDraft: async () => o.draft ?? false,
18
+ headOf: async () => H,
19
+ checks: async () => snaps[Math.min(i++, snaps.length - 1)],
20
+ required: async () => o.required ?? ["build"],
21
+ runAttempt: async () => o.attempt ?? 1,
22
+ failedLog: async () => o.log ?? "not ok 3 - parses the thing\n error: boom",
23
+ rerunFailed: async (id) => { log.push(`rerun:${id}`); },
24
+ fileFlake: async (a) => { log.push(`flake:${a.check}:${a.test}`); return 77; },
25
+ };
26
+ }
27
+ const ctx = (s, extra = {}) => ({ io: { ciGreen: s, print() {} }, repo: "o/r", def: "main", config: {}, state: { steps: { "release-pr": { done: true, result: { pr: 7 } } } }, save() {}, ...extra });
28
+ const row = (bucket, id = 1) => ({ name: "build", bucket, link: link(id) });
29
+
30
+ describe("ci-green step (#6164)", () => {
31
+ it("is a default release step between release-pr and review", () => {
32
+ const i = RELEASE_STEPS.indexOf("ci-green");
33
+ assert.equal(RELEASE_STEPS[i - 1], "release-pr"); assert.equal(RELEASE_STEPS[i + 1], "review");
34
+ });
35
+ it("waits while required checks are pending, then continues when green", async () => {
36
+ const s = seam([[row("pending")], [row("pending")], [row("pass")]]);
37
+ const r = await ciGreenStep(ctx(s));
38
+ assert.equal(r.green, true); assert.equal(s.log.filter((x) => x === "sleep").length, 2);
39
+ });
40
+ it("a required check that has not reported yet is pending, not green", async () => {
41
+ const s = seam([[], [row("pass")]]);
42
+ assert.equal((await ciGreenStep(ctx(s))).green, true); assert.equal(s.log.length, 1);
43
+ });
44
+ it("blocks when checks stay pending past the wait cap", async () => {
45
+ const r = await ciGreenStep(ctx(seam([[row("pending")]]), { config: { ciGreen: { maxWaitMin: 1 } } }));
46
+ assert.equal(r.blocked, true); assert.match(r.reason, /still pending after 1 min \(build\)/);
47
+ });
48
+ it("a failure that passes on one rerun is green, files a flaky-test issue naming the test, and does not block", async () => {
49
+ const s = seam([[row("fail", 5)], [row("pending", 5)], [row("pass", 5)]]);
50
+ const c = ctx(s);
51
+ const r = await ciGreenStep(c);
52
+ assert.equal(r.green, true);
53
+ assert.deepEqual(s.log.filter((x) => x !== "sleep"), ["rerun:5", "flake:build:parses the thing"]);
54
+ assert.deepEqual(r.flakes, [{ check: "build", test: "parses the thing", issue: 77 }]);
55
+ assert.equal(c.state.ciGreen.flakes.length, 1);
56
+ });
57
+ it("a check still red after its one rerun is real: one fix round, then wait again; green afterwards continues", async () => {
58
+ const s = seam([[row("fail", 5)], [row("fail", 5)], [row("pass", 6)]]);
59
+ const c = ctx(s, { io: { ciGreen: s, print() {}, review: {} } });
60
+ let fixed = 0;
61
+ c.fixRoundStub = () => { fixed++; c.state.fixloop = { heads: { [H]: { rounds: 1 } } }; return { head: "d".repeat(40) }; };
62
+ const r = await ciGreenWait(c, 7, { noFix: true });
63
+ assert.equal(r.red, true); assert.deepEqual(r.failing, ["build"]); assert.equal(fixed, 0, "noFix never starts a fix");
64
+ assert.deepEqual(s.log.filter((x) => x.startsWith("rerun")), ["rerun:5"], "rerun exactly once");
65
+ });
66
+ it("red after the fix round is spent blocks instead of fixing again", async () => {
67
+ const s = seam([[row("fail", 5)]]);
68
+ const c = ctx(s); c.state.fixloop = { heads: { [H]: { rounds: 1 } } };
69
+ c.state.ciGreen = { heads: { [H]: { reran: ["build"], firstFail: {}, filed: [] } }, flakes: [] };
70
+ const r = await ciGreenWait(c, 7);
71
+ assert.equal(r.blocked, true); assert.match(r.reason, /one fix round is spent/);
72
+ });
73
+ it("respects the rerun attempt cap (#6014): no rerun past it, the check stays red", async () => {
74
+ const s = seam([[row("fail", 5)]], { attempt: 3 });
75
+ const r = await ciGreenWait(ctx(s), 7, { noFix: true });
76
+ assert.equal(r.red, true); assert.ok(!s.log.some((x) => x.startsWith("rerun")));
77
+ });
78
+ it("a draft release PR (host preflight mode) is skipped: CI starts at mark-ready", async () => {
79
+ const r = await ciGreenStep(ctx(seam([[row("fail")]], { draft: true })));
80
+ assert.match(r.skipped, /draft/);
81
+ });
82
+ it("the open-finding gate runs first: an open review-finding issue blocks before any CI is read", async () => {
83
+ const s = seam([[row("pass")]]); let read = 0; const checks = s.checks; s.checks = async (a) => { read++; return checks(a); };
84
+ s.openGate = async () => "RESULT: BLOCK DEPLOY (open finding #12)";
85
+ const r = await ciGreenStep(ctx(s));
86
+ assert.equal(r.blocked, true); assert.match(r.reason, /^open-finding gate: .*#12/); assert.equal(read, 0);
87
+ s.openGate = async () => null;
88
+ assert.equal((await ciGreenStep(ctx(s))).green, true);
89
+ });
90
+ it("records ci_green_min in state.timing", async () => {
91
+ const c = ctx(seam([[row("pass")]]));
92
+ await ciGreenStep(c);
93
+ assert.equal(typeof c.state.timing.ci_green_min, "number");
94
+ addTiming(c, "review_passes", 2, { raw: true }); assert.equal(c.state.timing.review_passes, 2);
95
+ });
96
+ });
97
+
98
+ describe("helpers (#6164)", () => {
99
+ it("flakyTestName reads tap, node runner, jest, pytest and cargo logs", () => {
100
+ assert.equal(flakyTestName("ok 1 - a\nnot ok 2 - writes the file"), "writes the file");
101
+ assert.equal(flakyTestName(" ✖ retries once (12.3ms)"), "retries once");
102
+ assert.equal(flakyTestName(" ● suite › case"), "suite › case");
103
+ assert.equal(flakyTestName("FAILED tests/test_a.py::test_b - boom"), "tests/test_a.py::test_b");
104
+ assert.equal(flakyTestName("test mod::it_works ... FAILED"), "mod::it_works");
105
+ assert.equal(flakyTestName("no pattern here"), null);
106
+ });
107
+ it("block severity defaults to CRITICAL+HIGH; forge.yaml only tightens or loosens it", () => {
108
+ assert.deepEqual([...blockSetOf({})], ["CRITICAL", "HIGH"]);
109
+ assert.deepEqual([...blockSetOf({ blockSeverity: "CRITICAL" })], ["CRITICAL"]);
110
+ assert.deepEqual([...blockSetOf({ blockSeverity: "MEDIUM" })], ["CRITICAL", "HIGH", "MEDIUM"]);
111
+ assert.deepEqual(ciGreenKeys({ block_severity: "medium", ci_green_max_wait_min: "25" }), { blockSeverity: "MEDIUM", ciGreen: { maxWaitMin: 25 } });
112
+ assert.deepEqual(ciGreenKeys({}), {}, "no key switches the flow off; absent keys leave the defaults");
113
+ assert.deepEqual(readReleaseConfig("release:\n block_severity: critical\n").blockSeverity, "CRITICAL");
114
+ });
115
+ });
@@ -13,11 +13,12 @@
13
13
  */
14
14
  import { fenced } from "./release-fence.mjs";
15
15
  import { buildDispatchArgs } from "./release-control.mjs";
16
- import { INFRA_SIGNATURES } from "./release-flakes.mjs";
16
+ import { INFRA_SIGNATURES, classifyFailedStep } from "./release-flakes.mjs";
17
+ import { BLOCKER_LABEL } from "./release-rehearsal.mjs";
17
18
  import { verifyStep, verifyConfigured } from "./release-verify.mjs";
18
19
  import { engineOn, runStages } from "./deploy-stages.mjs";
19
20
 
20
- export const BOUNDS = { pollMs: 10_000, runPollMs: 20_000, defaultStageS: 3600, rerunMax: 2, maxAttempts: 3 };
21
+ export const BOUNDS = { pollMs: 10_000, runPollMs: 20_000, defaultStageS: 3600, rerunMax: 2, maxAttempts: 3, failureMax: 2 };
21
22
  const json = (s) => JSON.parse(String(s || "null"));
22
23
  const blocked = (reason) => ({ blocked: true, reason });
23
24
  const tail = (s, n = 400) => String(s ?? "").trim().slice(-n);
@@ -103,6 +104,25 @@ export function classifyDeploy(log, sigs) {
103
104
  return /migrat/i.test(log) ? "migration" : "deterministic";
104
105
  }
105
106
 
107
+ /** #6015: one open tracking issue per release+sha (marker lookup, then create or comment), filed before any rerun. @returns the issue url or number. */
108
+ async function recordDeployIssue(ctx, fails, latest) {
109
+ const { io, repo, state } = ctx, st = state.deploy;
110
+ const mark = `<!-- FORGE:DEPLOY_FAILURE release=${ctx.fence?.lease?.release ?? state.id ?? "-"} sha=${st.merge ?? "-"} -->`;
111
+ const line = (f, i) => `${i + 1}. run ${f.runId}: class \`${f.class}\`, step \`${f.step ?? "unknown"}\`\n\n\`\`\`\n${f.excerpt}\n\`\`\``;
112
+ if (!st.issue) {
113
+ const open = json(await io.gh(["issue", "list", "--repo", repo, "--label", BLOCKER_LABEL, "--state", "open", "--limit", "100", "--json", "number,body"])) ?? [];
114
+ const found = open.find((i) => String(i.body ?? "").includes(mark));
115
+ if (found) st.issue = String(found.number);
116
+ }
117
+ if (st.issue) {
118
+ if (st.issueCommented !== latest.runId + ":" + latest.rerunsAt) await io.gh(["issue", "comment", st.issue, "--repo", repo, "--body", `Deploy failure ${fails.length}:\n${line(latest, fails.length - 1)}`]);
119
+ } else {
120
+ st.issue = String(await io.gh(["issue", "create", "--repo", repo, "--label", BLOCKER_LABEL, "--title", `release-blocker: deploy failed at ${String(st.merge ?? "").slice(0, 12)}`, "--body", `${mark}\nProduction deploy failed; the engine reruns only a transient class once and stops after 2 failures.\n\n${fails.map(line).join("\n\n")}\n`])).trim();
121
+ }
122
+ st.issueCommented = latest.runId + ":" + latest.rerunsAt; ctx.save();
123
+ return st.issue;
124
+ }
125
+
106
126
  const hold = (reason, kind) => ({ blocked: `${reason} (owner ask: decide rollback or fix; label needs-agent when no host is attached)`, hold: { kind, label: "needs-agent" } });
107
127
 
108
128
  /**
@@ -116,10 +136,20 @@ async function recover(ctx, d, run, why, freezeNow, b, workflow) {
116
136
  if (freezeNow) return { blocked: `${why}; ${d.freeze_variable} is set, so the engine never reruns or redispatches the deploy (I26): roll back, or a human runs the workflow with override_freeze` };
117
137
  if (!run || !["failure", "timed_out", "cancelled"].includes(run.conclusion)) return { blocked: `${why}; nothing to rerun (a run that finished without changing live is not retried)` };
118
138
  if (run.conclusion === "cancelled" && await superseded({ io, repo, workflow }, run)) return { blocked: `${why}; run ${run.databaseId} was cancelled by a newer run of the concurrency group: expected, not rerun` };
119
- if (st.reruns >= rerunMax || st.attempts >= maxAttempts) return { blocked: `${why}; recovery spent (${st.reruns}/${rerunMax} reruns, ${st.attempts}/${maxAttempts} actions): hand off to the rollback ladder (#5563)` };
120
139
  let log = ""; try { log = String(await io.gh(["run", "view", String(run.databaseId), "--repo", repo, "--log-failed"])); } catch { /* unreadable log: not transient */ }
121
- const cls = classifyDeploy(log, rec.signatures);
122
- if (cls !== "transient") return hold(`${why}; ${cls === "migration" ? "migration failure" : "deterministic build failure"}, never retried blindly: ${tail(log, 200)}`, cls);
140
+ const c = classifyFailedStep({ log, sigs: rec.signatures });
141
+ const cls = c.class === "infra" ? "transient" : c.class === "migration" ? "migration" : "deterministic";
142
+ const fails = (st.failures ??= []);
143
+ if (!fails.length || fails[fails.length - 1].rerunsAt !== st.reruns) fails.push({ class: c.class, step: c.step, runId: run.databaseId, excerpt: c.excerpt, rerunsAt: st.reruns }); // a resume with no rerun in between is the same failure
144
+ ctx.save();
145
+ let issue; try { issue = await recordDeployIssue(ctx, fails, fails[fails.length - 1]); } catch (e) { return { blocked: `${why}; could not file the deploy tracking issue (${tail(e?.message, 120)}), so nothing is rerun` }; }
146
+ const at = issue ? ` (tracking issue ${issue})` : "";
147
+ const cap = Math.min(b.failureMax ?? BOUNDS.failureMax, BOUNDS.failureMax); // never raised by deploy.recovery
148
+ if (fails.length >= cap) return hold(`${why}; the deploy failed ${fails.length} times, stopping${at}: recovery spent, hand off to the rollback ladder (#5563); ${fails.map((f) => `${f.class}/${f.step ?? "?"}`).join(", ")}`, "deploy-failed");
149
+ if (st.reruns >= Math.min(rerunMax, BOUNDS.rerunMax) || st.attempts >= maxAttempts) return { blocked: `${why}; recovery spent (${st.reruns}/${rerunMax} reruns, ${st.attempts}/${maxAttempts} actions)${at}: hand off to the rollback ladder (#5563)` };
150
+ if (cls !== "transient") return hold(`${why}; ${c.class} failure at step ${c.step ?? "?"}, never retried blindly${at}: ${tail(log, 200)}`, c.class === "migration" ? "migration" : c.class === "deterministic" ? "deterministic" : c.class);
151
+ if ((st.rerunClasses ??= []).includes(c.class)) return hold(`${why}; ${c.class} already rerun once${at}`, "deploy-failed");
152
+ st.rerunClasses.push(c.class);
123
153
  st.reruns += 1; st.attempts += 1; ctx.save(); // counted before the act: a crash can only spend budget, never exceed it
124
154
  const f = await fenced(ctx.fence, { action: "rerun", key: idemKey(ctx, `rerun:${run.databaseId}:${st.reruns}`) }, () => io.gh(["run", "rerun", String(run.databaseId), "--repo", repo, "--failed"]));
125
155
  if (f.refused) return { blocked: `rerun ${f.refused}` };