forgedock 1.68.0 → 1.69.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 (52) 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 +6 -1
  6. package/bin/lean/conformance.test.mjs +6 -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/lane-audit-llm.mjs +51 -4
  18. package/bin/lean/lane-audit-llm.test.mjs +57 -0
  19. package/bin/lean/lane-audit.mjs +1 -1
  20. package/bin/lean/lean.mjs +63 -26
  21. package/bin/lean/lean.test.mjs +99 -19
  22. package/bin/lean/live-execution.mjs +3 -0
  23. package/bin/lean/live-execution.test.mjs +23 -0
  24. package/bin/lean/orchestrate-dispatch-placement.test.mjs +81 -0
  25. package/bin/lean/orchestrate-envhold.test.mjs +15 -1
  26. package/bin/lean/orchestrate.mjs +27 -9
  27. package/bin/lean/preflight.mjs +10 -3
  28. package/bin/lean/preflight.test.mjs +21 -1
  29. package/bin/lean/prompts.mjs +1 -0
  30. package/bin/lean/release-deploy.mjs +35 -5
  31. package/bin/lean/release-deploy.test.mjs +50 -3
  32. package/bin/lean/release-flakes.mjs +34 -0
  33. package/bin/lean/release-flakes.test.mjs +28 -0
  34. package/bin/lean/release.mjs +2 -1
  35. package/bin/lean/sandbox-remote.mjs +35 -4
  36. package/bin/lean/schedd.mjs +2 -2
  37. package/bin/pool/agent.mjs +105 -15
  38. package/bin/pool/cli.mjs +22 -4
  39. package/bin/pool/docker.mjs +2 -0
  40. package/bin/pool/image-manifest.mjs +24 -0
  41. package/bin/pool/image-manifest.test.mjs +20 -0
  42. package/bin/pool/lane-tools.mjs +23 -4
  43. package/bin/pool/lane-tools.test.mjs +27 -7
  44. package/bin/pool/project-layer.mjs +142 -0
  45. package/bin/pool/project-layer.test.mjs +73 -0
  46. package/bin/pool/router.mjs +20 -6
  47. package/bin/pool/version.mjs +45 -2
  48. package/bin/stats/tool-parks.mjs +29 -0
  49. package/bin/stats/tool-parks.test.mjs +21 -0
  50. package/package.json +1 -1
  51. package/pool/image/Dockerfile +1 -1
  52. 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.`;
@@ -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}` };
@@ -20,6 +20,7 @@ function world(o = {}) {
20
20
  if (a[0] === "run" && a[1] === "list") { const r = w.runs[Math.min(w.reran ?? 0, w.runs.length - 1)]; return JSON.stringify(r ? [r] : []); }
21
21
  if (a[0] === "run" && a[1] === "view") return w.log;
22
22
  if (a[0] === "run" && a[1] === "rerun") { w.reran = (w.reran ?? 0) + 1; return ""; }
23
+ if (a[0] === "issue") { w.issues = w.issues ?? []; w.issues.push({ a, at: w.reran ?? 0 }); return a[1] === "list" ? "[]" : a[1] === "create" ? "https://github.com/o/r/issues/77" : ""; }
23
24
  if (a[0] === "workflow" || a[0] === "pr") return "";
24
25
  throw new Error(`unexpected gh ${a.join(" ")}`);
25
26
  },
@@ -67,7 +68,7 @@ describe("release deploy stages (#5560)", () => {
67
68
  it("rerun_max bounds the reruns, then escalates", async () => {
68
69
  const { w, io } = world({ live: [OLD], log: "429 Too Many Requests", runs: [{ databaseId: 9, status: "completed", conclusion: "failure" }] });
69
70
  const out = await deployStep(mk(io));
70
- assert.match(out.reason, /recovery spent/); assert.equal(w.reran, 2);
71
+ assert.match(out.reason, /recovery spent/); assert.equal(w.reran, 1);
71
72
  });
72
73
  it("max_attempts bounds the actions", async () => {
73
74
  const { w, io } = world({ live: [OLD], log: "429 Too Many Requests", runs: [{ databaseId: 9, status: "completed", conclusion: "failure" }] });
@@ -111,7 +112,8 @@ describe("release deploy stages (#5560)", () => {
111
112
  const c = mk(io);
112
113
  try { await deployStep(c); } catch { /* killed */ }
113
114
  const out = await deployStep(c);
114
- assert.equal(out.live, true, dieOn);
115
+ if (dieOn === "run rerun") assert.ok(out.blocked, dieOn); // #6015: a crash after the counted rerun leaves a second recorded failure: stop, never a third attempt
116
+ else assert.equal(out.live, true, dieOn);
115
117
  assert.ok((w.reran ?? 0) <= 1, `${dieOn}: one rerun`);
116
118
  assert.equal(w.gh.filter((g) => g.startsWith("workflow run")).length, 0, dieOn);
117
119
  }
@@ -152,7 +154,7 @@ describe("deploy observation and recovery (#5560)", () => {
152
154
  assert.equal((await deployStep(mk(ok.io))).live, true); assert.equal(ok.w.reran, undefined);
153
155
  const bad = world({ live: [OLD], runs: [{ databaseId: 9, status: "completed", conclusion: "cancelled" }], log: "the runner received a shutdown signal" });
154
156
  const out = await deployStep(mk(bad.io));
155
- assert.equal(bad.w.reran, 2); assert.match(out.reason, /recovery spent/);
157
+ assert.equal(bad.w.reran, 1); assert.match(out.reason, /recovery spent/);
156
158
  });
157
159
  it("shared INFRA_SIGNATURES count as transient without any configured signature", async () => {
158
160
  const { w, io } = world({ live: [OLD, SHA], log: "fatal: ECONNRESET", runs: [{ databaseId: 9, status: "completed", conclusion: "failure" }, { databaseId: 9, status: "completed", conclusion: "success" }] });
@@ -223,3 +225,48 @@ describe("deploy helpers", () => {
223
225
  assert.ok(validatePolicy({ ...base, deploy: { ...POLICY, recovery: { rerun_max: "2" } } }).some((f) => /rerun_max/.test(f)));
224
226
  });
225
227
  });
228
+
229
+ describe("deploy failure classification and one issue (#6015)", () => {
230
+ const FAIL = [{ databaseId: 9, status: "completed", conclusion: "failure" }];
231
+ const creates = (w) => (w.issues ?? []).filter((i) => i.a[1] === "create");
232
+ it("two failed attempts yield exactly one issue and no third rerun", async () => {
233
+ const { w, io } = world({ live: [OLD], log: "build\tCompile\t2026 429 Too Many Requests", runs: FAIL });
234
+ const out = await deployStep(mk(io));
235
+ assert.equal(creates(w).length, 1); assert.equal(w.reran, 1); assert.equal(out.hold?.kind, "deploy-failed"); assert.match(out.reason, /issues\/77/);
236
+ assert.equal((w.issues ?? []).filter((i) => i.a[1] === "comment").length, 1);
237
+ const again = await deployStep(mk(io, { state: { steps: { "post-merge": { result: { merge: SHA } } }, deploy: undefined } })); // a fresh state still finds the marker, never a third rerun beyond the cap
238
+ assert.ok((w.reran ?? 0) <= 2); assert.ok(again.blocked || again.live === undefined);
239
+ });
240
+ it("the cap cannot be raised above 2 by deploy.recovery", async () => {
241
+ const { w, io } = world({ live: [OLD], log: "429 Too Many Requests", runs: FAIL });
242
+ await deployStep(mk(io, {}, { ...POLICY, recovery: { rerun_max: 9, max_attempts: 9, signatures: ["429"] } }));
243
+ assert.equal(w.reran, 1);
244
+ });
245
+ it("a secrets decrypt or SSH failure is never rerun, but the issue is filed", async () => {
246
+ for (const [log, cls] of [["deploy\tDecrypt secrets\t2026 sops: failed to decrypt ETIMEDOUT", "secrets"], ["deploy\tDeploy via SSH\t2026 ssh: connect to host x port 22: ETIMEDOUT", "ssh"]]) {
247
+ const { w, io } = world({ live: [OLD], log, runs: FAIL });
248
+ const c = mk(io); const out = await deployStep(c);
249
+ assert.equal(w.reran, undefined, cls); assert.equal(out.hold?.kind, cls); assert.equal(creates(w).length, 1);
250
+ assert.equal(c.state.deploy.failures[0].class, cls); assert.equal(c.state.deploy.failures[0].runId, 9);
251
+ }
252
+ });
253
+ it("the issue is filed before the rerun", async () => {
254
+ const { w, io } = world({ live: [OLD, SHA], log: "ECONNRESET", runs: [...FAIL, { databaseId: 9, status: "completed", conclusion: "success" }] });
255
+ const order = []; const g = io.gh;
256
+ io.gh = async (a) => { if (a[0] === "issue" && a[1] === "create") order.push("issue"); if (a[1] === "rerun") order.push("rerun"); return g(a); };
257
+ const out = await deployStep(mk(io));
258
+ assert.deepEqual(order, ["issue", "rerun"]); assert.equal(out.live, true);
259
+ });
260
+ it("a class is rerun once only", async () => {
261
+ const { w, io } = world({ live: [OLD], log: "ECONNRESET", runs: FAIL });
262
+ const c = mk(io, {}, { ...POLICY, recovery: { rerun_max: 2, max_attempts: 3 } });
263
+ c.state.deploy = { phase: "DEPLOYING", attempts: 1, reruns: 1, rerunClasses: ["infra"], failures: [{ class: "infra", step: null, runId: 9, excerpt: "x", rerunsAt: 0 }] };
264
+ await deployStep(c); assert.equal(w.reran, undefined);
265
+ });
266
+ it("a failing issue filing blocks the rerun", async () => {
267
+ const { w, io } = world({ live: [OLD], log: "ECONNRESET", runs: FAIL }); const g = io.gh;
268
+ io.gh = async (a) => { if (a[0] === "issue") throw new Error("HTTP 500"); return g(a); };
269
+ const out = await deployStep(mk(io));
270
+ assert.match(out.reason, /tracking issue/); assert.equal(w.reran, undefined);
271
+ });
272
+ });
@@ -40,6 +40,40 @@ export function classifyFailure(text) {
40
40
  const hit = INFRA_SIGNATURES.find(([, re]) => re.test(String(text ?? "")));
41
41
  return hit ? { class: "infra", signature: hit[0] } : { class: "unknown", signature: null };
42
42
  }
43
+ /** #6015: a deploy or rehearsal workflow is never a CI flake: its failures go through release-deploy recover (classify, file, bounded rerun). */
44
+ export const isDeployWorkflow = (name) => /deploy|rehears|migrat/i.test(String(name ?? ""));
45
+
46
+ const STEP_SECRETS = /decrypt|sops|secrets?\b|age[- ]key|gpg/i, STEP_SSH = /\bssh\b|scp\b|rsync/i;
47
+ const LOG_SECRETS = /failed to decrypt|decryption failed|sops.*(error|failed)|no matching keys|cannot decrypt|age: error/i;
48
+ const LOG_SSH = /permission denied \(publickey|ssh: connect to host|ssh_exchange_identification|kex_exchange_identification|host key verification failed|ssh: .*(timed out|refused)/i;
49
+
50
+ /** The step named by the first `--log-failed` line (`job<TAB>step<TAB>time line`) or the first failed step of `steps` [{name, conclusion}]. */
51
+ function failedStepName(steps, log) {
52
+ const s = (steps ?? []).find((x) => x?.conclusion === "failure" || x?.conclusion === "timed_out");
53
+ if (s?.name) return String(s.name);
54
+ const m = /^[^\t\n]*\t([^\t\n]+)\t/m.exec(String(log ?? ""));
55
+ return m ? m[1].trim() : null;
56
+ }
57
+
58
+ /**
59
+ * #6015: name the failed deploy step (DEPLOY_FREEZE / LIVE_CHECK semantics of #5560 via `reason`). Pure.
60
+ * Secrets decrypt, SSH, rehearsal, migration, freeze and live-check failures are never transient; only a network/infra signature
61
+ * (shared INFRA_SIGNATURES or `sigs`) in some other step is. @returns {{class, transient: boolean, step: string|null, excerpt: string}}
62
+ */
63
+ export function classifyFailedStep({ steps, log, reason, sigs } = {}) {
64
+ const text = String(log ?? ""), step = failedStepName(steps, text), name = step ?? "";
65
+ const excerpt = text.trim().slice(-400), out = (cls, transient = false) => ({ class: cls, transient, step, excerpt });
66
+ if (/DEPLOY_FREEZE|\bfreeze\b/i.test(String(reason ?? ""))) return out("freeze");
67
+ if (/LIVE_CHECK/.test(String(reason ?? ""))) return out("live-check");
68
+ if (STEP_SECRETS.test(name) || LOG_SECRETS.test(text)) return out("secrets");
69
+ if (STEP_SSH.test(name) || (!step && LOG_SSH.test(text))) return out("ssh");
70
+ if (/rehears/i.test(name)) return out("rehearsal");
71
+ if (/migrat/i.test(name) || (!step && /migrat/i.test(text))) return out("migration");
72
+ const configured = (sigs ?? []).some((x) => { try { return new RegExp(x, "i").test(text); } catch { return text.includes(x); } });
73
+ if (INFRA_SIGNATURES.some(([, re]) => re.test(text)) || configured) return out("infra", true);
74
+ return /migrat/i.test(text) ? out("migration") : out("deterministic");
75
+ }
76
+
43
77
  export const signatureHash = (check, test, signature) => createHash("sha256").update([check, test ?? "", signature ?? ""].join("\0")).digest("hex").slice(0, 16);
44
78
 
45
79
  /** Same-SHA flips in `runs` [{sha, check, test?, conclusion, id, at}]: a check that failed and then passed on one sha. */
@@ -145,3 +145,31 @@ t6014("#6014: attempt cap refuses a third rerun, records attempt and forfeited r
145
145
  assert6014.equal(e.attempt, 2); assert6014.match(e.reuse_forfeited, /reuse forfeited/);
146
146
  assert6014.equal("attempt" in flakeEntry({ check: "c", kind: "infra", at: "t" }), false);
147
147
  });
148
+
149
+ describe("classifyFailedStep and deploy-class reruns (#6015)", async () => {
150
+ const { classifyFailedStep, isDeployWorkflow } = await import("./release-flakes.mjs");
151
+ const L = (step, msg) => `deploy\t${step}\t2026-01-01T00:00:00Z ${msg}`;
152
+ it("names the class and transience of the failed step", () => {
153
+ const k = (o) => { const r = classifyFailedStep(o); return [r.class, r.transient]; };
154
+ assert.deepEqual(k({ log: L("Decrypt secrets", "sops: failed to decrypt") }), ["secrets", false]);
155
+ assert.deepEqual(k({ log: L("Deploy via SSH", "ssh: connect to host h port 22: Connection timed out ETIMEDOUT") }), ["ssh", false]);
156
+ assert.deepEqual(k({ log: L("Migration Rehearsal", "ECONNRESET") }), ["rehearsal", false]);
157
+ assert.deepEqual(k({ log: L("Run migrations", "failed") }), ["migration", false]);
158
+ assert.deepEqual(k({ log: L("Pull images", "ECONNRESET") }), ["infra", true]);
159
+ assert.deepEqual(k({ log: L("Build", "tsc error") }), ["deterministic", false]);
160
+ assert.deepEqual(k({ log: "", reason: "LIVE_CHECK failed" }), ["live-check", false]);
161
+ assert.deepEqual(k({ log: "", reason: "the run set DEPLOY_FREEZE" }), ["freeze", false]);
162
+ assert.equal(classifyFailedStep({ steps: [{ name: "Deploy via SSH", conclusion: "failure" }], log: "" }).step, "Deploy via SSH");
163
+ });
164
+ it("matches no deploy class for ordinary CI names", () => {
165
+ assert.equal(isDeployWorkflow("Migration Rehearsal"), true); assert.equal(isDeployWorkflow("Deploy production"), true);
166
+ assert.equal(isDeployWorkflow("unit"), false); assert.equal(isDeployWorkflow("lint"), false);
167
+ });
168
+ it("rerunInfraFlakes skips deploy-class runs", async () => {
169
+ const calls = [];
170
+ const io = { now: () => NOW, api: async () => ({}), gh: async (a) => { calls.push(a); return a[1] === "list" ? JSON.stringify([{ databaseId: 5, name: "Deploy production" }]) : "Unable to upload artifact"; } };
171
+ const fence = { lctx: { io, repo: "o/r", credential: "driver" }, lease: { holder: "A", epoch: 1, release: "r1" }, record: async () => {}, now: () => "t" };
172
+ const r = await rerunInfraFlakes({ io, repo: "o/r", head: "abc", fence, policy: { ci: { rerun_budget_min: 30 } } });
173
+ assert.deepEqual(r.reran, []); assert.match(r.skipped[0].why, /deploy-class/); assert.equal(calls.filter((c) => c[1] === "rerun").length, 0);
174
+ });
175
+ });
@@ -29,7 +29,7 @@ import { cutSnapshot, writeRecord, checkChain, verifyRelease, defaultBehind, DEF
29
29
  import { createReleaseLedger, writeRelease, readLedger, acquireLease, heartbeat, recordReleaseRound } from "./release-ledger.mjs";
30
30
  import { fenced, epochTrailer } from "./release-fence.mjs";
31
31
  import { holdCheck, exemptionsSection, runControl, VERBS as CONTROL_VERBS } from "./release-control.mjs";
32
- import { parseFlakeConfig, classifyFailure, planRerun, flakeEntry, recordFlakes, readFlakes } from "./release-flakes.mjs";
32
+ import { parseFlakeConfig, classifyFailure, planRerun, flakeEntry, recordFlakes, readFlakes, isDeployWorkflow } from "./release-flakes.mjs";
33
33
  import { readActive } from "./release-ledger.mjs";
34
34
  import { statusFromCli, policyFromYaml } from "./release-status.mjs";
35
35
  import { parseFixConfig } from "./release-fixloop.mjs";
@@ -286,6 +286,7 @@ export async function rerunInfraFlakes({ io, repo, head, fence, policy }) {
286
286
  const at = new Date(io.now?.() ?? Date.now()).toISOString(), entries = [];
287
287
  let spentMin = 0;
288
288
  for (const r of runs) {
289
+ if (isDeployWorkflow(r.name)) { out.skipped.push({ name: r.name, why: "deploy-class: handled by release-deploy recover" }); continue; } // #6015: never a log-regex rerun
289
290
  const log = String(await io.gh(["run", "view", String(r.databaseId), "--repo", repo, "--log-failed"]).catch(() => "")).slice(-20_000);
290
291
  const c = classifyFailure(log);
291
292
  const [d] = planRerun({ jobs: [{ key: `${head}:${r.name}`, name: r.name, class: c.class, attempt: r.attempt }], done, spentMin, budgetMin: cfg.rerunBudgetMin });
@@ -16,7 +16,7 @@
16
16
  * or a session gateway fronts. Tests use an in-memory transport.
17
17
  */
18
18
  import { execFileSync } from "node:child_process";
19
- import { appendFileSync, mkdirSync } from "node:fs";
19
+ import { appendFileSync, mkdirSync, writeFileSync } from "node:fs";
20
20
  import { homedir } from "node:os";
21
21
  import { dirname, join } from "node:path";
22
22
  import { mergeRemoteLog } from "../engine/runlog.mjs";
@@ -105,6 +105,8 @@ export function httpTransport({ endpoint, token = null, fetchFn = globalThis.fet
105
105
  },
106
106
  async logs(id, cursor = 0) { const r = await call("GET", `${p(id)}/logs?cursor=${encodeURIComponent(cursor)}`); return r.ok ? { text: String(r.data?.text ?? ""), cursor: r.data?.cursor ?? cursor } : { text: "", cursor }; },
107
107
  async result(id) { const r = await call("GET", `${p(id)}/result`); if (r.status === 401) throw Object.assign(fail("result", r), { transient: true }); if (r.ok && r.data?.disk_pressure === true) return { terminalReason: "deferred", code: OUTCOME_CODES.SANDBOX_DISK_PRESSURE, retryInSeconds: 120, cost_usd: 0, detail: `sandbox ${id} was stopped to save the host drive (disk pressure); worktree and volume kept, requeued to resume` }; /* #5891 */ if (r.ok && r.data?.drained === true) return { terminalReason: "deferred", code: OUTCOME_CODES.SANDBOX_CAPACITY, retryInSeconds: 60, cost_usd: 0, detail: `sandbox ${id} was drained to free capacity for reserved work (${String(r.data.reason ?? "").slice(0, 120)}); rescheduled` }; /* #5856 */ if (r.ok && r.data && typeof r.data === "object") { const v = r.data.engineVersion ?? r.data.engine_version ?? r.data.forge_version ?? /ForgeDock\s*[·-]\s*v?(\d+\.\d+(?:\.\d+)?)/.exec(String(r.data.banner ?? r.data.log ?? ""))?.[1]; const pv = v ?? placedEngine.get(id); return pv && !r.data.engineVersion ? { ...r.data, engineVersion: String(pv) } : r.data; } return null; }, /* #5931 */
108
+ /** #6117: the lane's run log (jsonl text, capped) and the last ~200 lines of its stderr/stdout; null from a pool without the endpoint (404/405) or any error. Kept by the agent for a grace period after destroy. */
109
+ async runlog(id) { const r = await call("GET", `${p(id)}/runlog`); return r.ok && r.data && typeof r.data === "object" ? { runLog: String(r.data.run_log ?? ""), tail: String(r.data.tail ?? "") } : null; },
108
110
  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
109
111
  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); },
110
112
  async destroy(id) { const r = await call("DELETE", p(id)); if (r.ok || r.status === 404) return true; throw fail("destroy", r); },
@@ -259,13 +261,41 @@ export function remoteProvider({ batch, repo, settings = {}, name = "remote", tr
259
261
  }
260
262
  return b64 ? { CS_RELAY_PREFETCH_B64: b64 } : {};
261
263
  };
264
+ /** Appends the sandbox log chunk past the handle's cursor to the lane log. {ok, bytes}: ok=false when the pool could not answer. */
262
265
  const pullLogs = async (h) => {
263
- if (!transport.logs) return;
266
+ if (!transport.logs) return { ok: false, bytes: 0 };
264
267
  try {
265
268
  const { text, cursor } = (await transport.logs(h.id, h.logCursor ?? 0)) ?? {};
266
269
  if (text) { const f = batch.logFile(h.issue); mkdirSync(dirname(f), { recursive: true }); appendFileSync(f, redact(text, [...known])); }
267
270
  if (cursor !== undefined) h.logCursor = cursor;
268
- } catch { /* the next poll retries */ }
271
+ return { ok: true, bytes: text ? String(text).length : 0 };
272
+ } catch { return { ok: false, bytes: 0 }; /* the next poll retries */ }
273
+ };
274
+ /** #6117: `<n>.runlog.jsonl` beside the lane log (`<n>.log`): the sandbox's own run log, so an env park stays triageable after teardown. */
275
+ const runLogFile = (issue) => { const f = batch.logFile(issue); return /\.log$/.test(f) ? f.replace(/\.log$/, ".runlog.jsonl") : `${f}.runlog.jsonl`; };
276
+ const keepRunLog = (h, runLog) => {
277
+ if (!runLog) return;
278
+ try { const f = runLogFile(h.issue); mkdirSync(dirname(f), { recursive: true }); writeFileSync(f, redact(String(runLog), [...known])); } catch { /* evidence only */ }
279
+ mergeRemoteLog(env.FORGE_RUNS_DIR || join(homedir(), ".forge", "runs"), h.issue, runLog, { repo });
280
+ };
281
+ /**
282
+ * #6117: everything the sandbox still holds, copied to the dispatcher BEFORE it is destroyed: the rest of the lane log
283
+ * (chunks past the cursor, until drained), the run log, and (when the log could not be drained) the stderr tail.
284
+ * Runs on every terminal path (teardown is their one choke point) and never throws.
285
+ */
286
+ const collectEvidence = async (h) => {
287
+ try {
288
+ let drained = false;
289
+ for (let i = 0; i < 64; i++) { const r = await pullLogs(h); drained = r.ok; if (!r.ok || r.bytes === 0) break; }
290
+ if (typeof transport.runlog !== "function") return;
291
+ const e = await transport.runlog(h.id).catch(() => null);
292
+ if (!e) return;
293
+ keepRunLog(h, e.runLog);
294
+ if (!drained && e.tail) {
295
+ const f = batch.logFile(h.issue); mkdirSync(dirname(f), { recursive: true });
296
+ appendFileSync(f, redact(`\n[sandbox ${h.id}] last lines of its log (the live stream could not be drained before teardown):\n${e.tail}${e.tail.endsWith("\n") ? "" : "\n"}`, [...known]));
297
+ }
298
+ } catch { /* teardown goes on */ }
269
299
  };
270
300
  return {
271
301
  name,
@@ -330,7 +360,7 @@ export function remoteProvider({ batch, repo, settings = {}, name = "remote", tr
330
360
  if (r) { await pullLogs(h); await minutesOf(h); }
331
361
  if (!r) return null;
332
362
  const { runLog, ...rest } = r; // #5697: the lane's run log goes to the host run log, not into the result
333
- if (runLog) mergeRemoteLog(env.FORGE_RUNS_DIR || join(homedir(), ".forge", "runs"), h.issue, runLog, { repo });
363
+ keepRunLog(h, runLog); // #6117: the host run log and `<n>.runlog.jsonl` beside the lane log
334
364
  return rest;
335
365
  },
336
366
  /** #5991: is the pool agent of this handle answering? Unknown (null) without transport support; transport errors propagate. */
@@ -357,6 +387,7 @@ export function remoteProvider({ batch, repo, settings = {}, name = "remote", tr
357
387
  /** #5241: why the last `stop(h)` returned false (null when it succeeded or never ran), so a cancel can report it. */
358
388
  stopReason: (h) => stopWhy.get(h?.id) ?? null,
359
389
  async teardown(h) {
390
+ await collectEvidence(h); // #6117: the run log and the log tail leave the sandbox before it is destroyed
360
391
  await minutesOf(h);
361
392
  try { return (await transport.destroy(h.id)) !== false; } catch { return false; }
362
393
  },
@@ -78,7 +78,7 @@ export function batchVerdicts(root, { now = Date.now(), windowMin = DEFAULT_STAL
78
78
  try {
79
79
  const b = openBatch(root, id);
80
80
  if (!b.readPlan()?.daemon || b.isTerminal()) continue;
81
- const state = b.store.peek(), stall = evaluateDispatchStall(state, { held: b.readHeld(), parallel: b.readParallel(), hosted: false, paused: b.readPause?.() ?? null, lastProgressMs: b.lastProgressMs(), now, windowMin, lanesAliveMs: lanesAlive(b, state) });
81
+ const state = b.store.peek(), stall = evaluateDispatchStall(state, { held: b.readHeld(), parallel: b.readParallel(), hosted: false, paused: b.readPause?.() ?? null, lastProgressMs: b.lastDispatchClockMs(), now, windowMin, lanesAliveMs: lanesAlive(b, state) });
82
82
  const decision = stall ? decideStallAction(stall, { recovery: readHealth(b.dir)?.stallRecovery ?? null, hosted: false, now, windowMin }) : null;
83
83
  out.push(batchVerdict(id, stall, decision));
84
84
  } catch { /* one unreadable batch has no verdict */ }
@@ -657,7 +657,7 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
657
657
  if (b.isTerminal() && (!Number.isFinite(created) || now - created >= 24 * 3600_000)) continue; // nothing left to report or re-host
658
658
  const reported = !!b.readReport(), cancelled = !!b.readCancel(), state = b.store.peek(), isHosted = hosted.has(id) || starting.has(id);
659
659
  await efficiencyTick(b, plan, state, { now, reported, cancelled }); // #5987: advisory; never throws, never changes dispatch
660
- const stallOpts = { held: b.readHeld(), paused: b.readPause?.() ?? null, parallel: b.readParallel(), hosted: isHosted, lastProgressMs: b.lastProgressMs(), now, windowMin: stallMin, cancelled, reported, lanesAliveMs: lanesAlive(b, state) };
660
+ const stallOpts = { held: b.readHeld(), paused: b.readPause?.() ?? null, parallel: b.readParallel(), hosted: isHosted, lastProgressMs: b.lastDispatchClockMs(), now, windowMin: stallMin, cancelled, reported, lanesAliveMs: lanesAlive(b, state) };
661
661
  let stall = evaluateDispatchStall(state, stallOpts);
662
662
  if (stall && preflight) { // #5745: name the preflight gate holding admission (advisory; dispatch decisions are unchanged)
663
663
  let gates = [];