forgedock 1.61.1 → 1.62.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 (134) hide show
  1. package/bin/config-schema.mjs +10 -1
  2. package/bin/engine/outcome-codes.mjs +4 -0
  3. package/bin/engine-cli.mjs +160 -18
  4. package/bin/env/env.mjs +6 -4
  5. package/bin/forge-home-check.mjs +91 -0
  6. package/bin/forgedock.mjs +50 -7
  7. package/bin/gc.mjs +2 -0
  8. package/bin/hooks/pre-tool-use.mjs +4 -0
  9. package/bin/journey.mjs +55 -5
  10. package/bin/lean/admission.mjs +16 -5
  11. package/bin/lean/batch-health.mjs +55 -16
  12. package/bin/lean/batch-health.test.mjs +67 -1
  13. package/bin/lean/batch.mjs +8 -0
  14. package/bin/lean/batch.test.mjs +5 -0
  15. package/bin/lean/ceiling.mjs +20 -0
  16. package/bin/lean/ceiling.test.mjs +33 -2
  17. package/bin/lean/ci-gate.mjs +240 -0
  18. package/bin/lean/ci-gate.test.mjs +227 -0
  19. package/bin/lean/ci-precheck.mjs +178 -0
  20. package/bin/lean/ci-precheck.test.mjs +149 -0
  21. package/bin/lean/conformance.mjs +118 -20
  22. package/bin/lean/conformance.test.mjs +193 -3
  23. package/bin/lean/context.test.mjs +7 -6
  24. package/bin/lean/dag.mjs +128 -0
  25. package/bin/lean/dag.test.mjs +131 -0
  26. package/bin/lean/decisions.mjs +5 -4
  27. package/bin/lean/decisions.test.mjs +11 -0
  28. package/bin/lean/delguard.mjs +84 -0
  29. package/bin/lean/delguard.test.mjs +104 -0
  30. package/bin/lean/depcache.mjs +125 -17
  31. package/bin/lean/depcache.test.mjs +111 -0
  32. package/bin/lean/design-gate.mjs +5 -5
  33. package/bin/lean/design-gate.test.mjs +14 -0
  34. package/bin/lean/effects.mjs +81 -7
  35. package/bin/lean/execution.mjs +81 -15
  36. package/bin/lean/execution.test.mjs +156 -3
  37. package/bin/lean/forgedock-lane-workflow.test.mjs +35 -0
  38. package/bin/lean/guardgate.mjs +30 -7
  39. package/bin/lean/guardgate.test.mjs +44 -1
  40. package/bin/lean/guards.test.mjs +1 -1
  41. package/bin/lean/heavy.test.mjs +87 -0
  42. package/bin/lean/hotarea.mjs +73 -0
  43. package/bin/lean/hotarea.test.mjs +73 -0
  44. package/bin/lean/issuewatch-reconcile.mjs +20 -1
  45. package/bin/lean/issuewatch-reconcile.test.mjs +30 -0
  46. package/bin/lean/lanecheck.mjs +27 -3
  47. package/bin/lean/lanecheck.test.mjs +47 -5
  48. package/bin/lean/laneconfine.mjs +83 -0
  49. package/bin/lean/laneconfine.test.mjs +113 -0
  50. package/bin/lean/lean.mjs +398 -91
  51. package/bin/lean/lean.test.mjs +792 -26
  52. package/bin/lean/live-reconcile.mjs +169 -0
  53. package/bin/lean/live-reconcile.test.mjs +176 -0
  54. package/bin/lean/orchestrate-envhold.test.mjs +245 -0
  55. package/bin/lean/orchestrate-hostfallback.test.mjs +39 -0
  56. package/bin/lean/orchestrate.mjs +207 -17
  57. package/bin/lean/outcomeevidence.mjs +104 -0
  58. package/bin/lean/outcomeevidence.test.mjs +78 -0
  59. package/bin/lean/page-capture.mjs +68 -0
  60. package/bin/lean/page-capture.test.mjs +44 -0
  61. package/bin/lean/pagegate.mjs +46 -7
  62. package/bin/lean/pagegate.test.mjs +66 -1
  63. package/bin/lean/postdeploy-check.mjs +18 -4
  64. package/bin/lean/postdeploy-check.test.mjs +32 -1
  65. package/bin/lean/prefilter.mjs +36 -4
  66. package/bin/lean/prefilter.test.mjs +31 -1
  67. package/bin/lean/preflight.mjs +22 -0
  68. package/bin/lean/preflight.test.mjs +19 -1
  69. package/bin/lean/probe.mjs +18 -0
  70. package/bin/lean/probe.test.mjs +40 -0
  71. package/bin/lean/prompts.mjs +41 -4
  72. package/bin/lean/recovery.test.mjs +20 -0
  73. package/bin/lean/recurrence.mjs +133 -0
  74. package/bin/lean/recurrence.test.mjs +99 -0
  75. package/bin/lean/release-config.mjs +2 -1
  76. package/bin/lean/release-config.test.mjs +18 -0
  77. package/bin/lean/release-control.mjs +4 -2
  78. package/bin/lean/release-control.test.mjs +15 -0
  79. package/bin/lean/release-merge-hold.mjs +65 -0
  80. package/bin/lean/release-merge-hold.test.mjs +69 -0
  81. package/bin/lean/release-review.mjs +26 -9
  82. package/bin/lean/release-review.test.mjs +53 -0
  83. package/bin/lean/release-status.mjs +3 -1
  84. package/bin/lean/release-status.test.mjs +11 -0
  85. package/bin/lean/release.test.mjs +26 -1
  86. package/bin/lean/render.mjs +8 -7
  87. package/bin/lean/repro-output.test.mjs +45 -0
  88. package/bin/lean/routing.mjs +49 -0
  89. package/bin/lean/routing.test.mjs +54 -1
  90. package/bin/lean/run-issue-placement.test.mjs +30 -1
  91. package/bin/lean/sandbox-actions.mjs +121 -0
  92. package/bin/lean/sandbox-actions.test.mjs +94 -0
  93. package/bin/lean/sandbox-provider.contract.test.mjs +22 -1
  94. package/bin/lean/sandbox-remote.mjs +3 -1
  95. package/bin/lean/schedd-health.mjs +14 -2
  96. package/bin/lean/schedd-health.test.mjs +13 -0
  97. package/bin/lean/schedd.mjs +43 -17
  98. package/bin/lean/schedd.test.mjs +61 -1
  99. package/bin/lean/toolchain.mjs +16 -6
  100. package/bin/lean/toolplace.mjs +12 -0
  101. package/bin/lean/weakguard.mjs +105 -0
  102. package/bin/lean/weakguard.test.mjs +59 -0
  103. package/bin/lean/winspawn.mjs +61 -0
  104. package/bin/lean/winspawn.test.mjs +45 -0
  105. package/bin/lean/worktree.mjs +3 -1
  106. package/bin/lean/worktree.test.mjs +11 -0
  107. package/bin/pool/agent.mjs +215 -15
  108. package/bin/pool/cache-sweep.mjs +74 -0
  109. package/bin/pool/cli.mjs +11 -3
  110. package/bin/pool/docker.mjs +33 -2
  111. package/bin/pool/health.mjs +38 -0
  112. package/bin/pool/lane-tools.mjs +23 -4
  113. package/bin/pool/lane-tools.test.mjs +12 -1
  114. package/bin/pool/router.mjs +21 -3
  115. package/bin/runner.mjs +37 -0
  116. package/bin/splash-scene.mjs +356 -0
  117. package/bin/win-hide-children.mjs +114 -0
  118. package/commands/orchestrate.md +18 -27
  119. package/commands/review-pr-agents/infra.md +1 -0
  120. package/commands/review-pr-staging.md +2 -2
  121. package/docs/CONFIG.md +60 -3
  122. package/docs/OUTCOME-CODES.md +3 -0
  123. package/package.json +1 -1
  124. package/plugins/forgedock-splash/.claude-plugin/plugin.json +1 -1
  125. package/plugins/forgedock-splash/README.md +1 -1
  126. package/plugins/forgedock-splash/hooks/scene.ts +142 -8
  127. package/pool/README.md +6 -0
  128. package/pool/image/entrypoint.sh +1 -0
  129. package/scripts/acceptance-red-green.sh +8 -3
  130. package/scripts/acceptance-red-green.test.sh +8 -0
  131. package/scripts/check-spec-size.sh +3 -1
  132. package/scripts/gen-splash-scene.mjs +24 -0
  133. package/scripts/review-staging-pre.sh +8 -3
  134. package/scripts/review-staging-pre.test.sh +2 -0
@@ -21,7 +21,7 @@
21
21
  * before scheduling, so a live lane does not hold up the others.
22
22
  * `deferred` is a scheduling fact, not an end: each typed code is requeued with its retry-at (`deferPolicy`), a usage
23
23
  * limit (and #5168 a claude login failure, `backend.auth`) holds admissions for that account until its reset, and deferrals other than a wait (`host.busy`,
24
- * `sandbox.capacity`, #4528; `sandbox.unreachable`, #4788; `rate_limited`, #4784; `backend.auth`, #5168; `quota.exhausted`, #5236) stop after `maxDeferrals`.
24
+ * `sandbox.capacity`, #4528; `sandbox.unreachable`, #4788; `rate_limited`, #4784; `backend.auth`, #5168; `backend.cli_failed`, #5762, a capped short retry; `quota.exhausted`, #5236) stop after `maxDeferrals`.
25
25
  * #5161: an engine-error whose detail is a transport/gateway failure (`isTransientEngineError`) is requeued with backoff
26
26
  * (`transientRetryDelayMs`) up to `transientRetries` times, not counted against `ENGINE_ERROR_RELAUNCHES`; then it ends engine-error.
27
27
  * #5112: with `remote.offlineFallback` (`execution.fallback_local`), an issue deferred `remote.capacityFallbackAfter` times (default
@@ -36,6 +36,9 @@
36
36
  * and the pool hold (`drainRequeues`). An `engine-error` is
37
37
  * relaunched once; `breaker` ({errors, window_min}) stops admissions after a burst and lets running lanes finish, the
38
38
  * rest stay pending (outcome `held`) for a resume. `getParallel()` is read on every pass, so K can change live.
39
+ * #5805: with `envHold: {version(), envFingerprint(), missingTools(tools)}` an engine-error whose signature repeats (`failureSignature`,
40
+ * per engine version) and an env defect the host still has (`env.tool_missing` / `env.repro_unrunnable`) end `held` with `envHold`
41
+ * instead of relaunching or ending; an engine version change, a batch env change or the tool appearing re-admits them (watchEnvHolds).
39
42
  * #5138: `remote.max`, `remote.fallbackLocal` and `remote.place` are read on every grant too (engine-cli puts live getters on
40
43
  * them, live-execution.mjs), so `--set-max-remote` / `--set-placement` change a running batch; running lanes are not stopped.
41
44
  * `getChildren()` + `autoChildren {mode, pollS, epics}` (#4965, `orchestration.auto_add_children`): with mode `epic`|`all`, at most once per `pollS`
@@ -48,6 +51,7 @@
48
51
  * when only held issues (and their dependents) remain and nothing runs, the batch ends with them `held` ("held by operator"), and a `--resume <id> <issue...>` naming them (or `--release`) re-admits them.
49
52
  * `getBlocked()` (#4773, the `blocked` label) is read on every pass: the issues it returns are in the batch but not dispatched; removing the label
50
53
  * releases them on the next pass (the batch polls while only blocked issues wait). `trusted(n)` gates `Blocked by`/`Depends on` edges to a trusted body author.
54
+ * `logicalDeps(n)` (#5824) adds the plan's logical edges (bin/lean/dag.mjs: a dependency's new contract deliverable the issue names).
51
55
  *
52
56
  * Maintenance budget (#4197), off unless `maintenance: {share, whenIdle}` is passed: `classify(issue)` gives each issue
53
57
  * `{maintenance, priority}` (persisted as `classes`) and admission follows `pickNext`: P0/P1 features, then a maintenance
@@ -121,7 +125,7 @@
121
125
  * the queue order except that decomposed sub-issues go first. A settled row carries `est_minutes` (estimated vs. actual).
122
126
  */
123
127
  import { parseDependsOn } from "../engine/phases.mjs";
124
- import { classifyNeedsHuman, recoveryCodeOf, recoveryClassOf, OUTCOME_CODES, ENV_VALIDATE_PLACEMENT, MECHANICAL_CODES } from "../engine/outcome-codes.mjs";
128
+ import { classifyNeedsHuman, recoveryCodeOf, recoveryClassOf, OUTCOME_CODES, ENV_VALIDATE_PLACEMENT, ENV_VALIDATE_TIMEOUT, MECHANICAL_CODES } from "../engine/outcome-codes.mjs";
125
129
  import { detectGateDeadlock, formatGateDeadlock } from "./gatewatch.mjs";
126
130
  import { recoveryEvidence } from "./render.mjs";
127
131
  import { renderAlerts } from "../stats/render.mjs";
@@ -138,8 +142,8 @@ import { openPrerequisites } from "./prereq.mjs";
138
142
 
139
143
  // A dependency that finished like this no longer blocks its dependents.
140
144
  const SATISFIED = new Set(["merged", "invalid"]);
141
- // #5162: a dependent of a root that ended like this is held (resumable), not skipped.
142
- const HOLD_ROOT = new Set(["needs-human", "engine-error", "deferred", "budget-exceeded"]);
145
+ // #5162: a dependent of a root that ended like this is held (resumable), not skipped. #5805: also behind a root held on an engine/env change.
146
+ const HOLD_ROOT = new Set(["needs-human", "engine-error", "deferred", "budget-exceeded", "held"]);
143
147
  /** #5162: members of a real dependency cycle (a nontrivial SCC or a self-loop) among `nodes`; `edgesOf(n)` lists n's dependencies. */
144
148
  export function cyclicNodes(nodes, edgesOf) {
145
149
  const inSet = new Set(nodes), idx = new Map(), low = new Map(), stack = [], on = new Set(), out = new Set();
@@ -186,6 +190,16 @@ export const DEFAULT_TRANSIENT_RETRIES = 4;
186
190
  export const TRANSIENT_BACKOFF_S = 30;
187
191
  export const TRANSIENT_BACKOFF_MAX_S = 15 * 60;
188
192
  export const transientRetryDelayMs = (k) => Math.min(TRANSIENT_BACKOFF_S * 4 ** (Math.max(1, k) - 1), TRANSIENT_BACKOFF_MAX_S) * 1000;
193
+ // #5805: an engine/env-caused failure that would repeat is held (outcome `held`, row `envHold`) instead of relaunched or ended;
194
+ // 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.
195
+ export const ENV_HOLD_MAX_MS = 24 * 3600_000;
196
+ export const ENV_WATCH_MS = 30_000;
197
+ /** #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. */
198
+ export function failureSignature(code, detail) {
199
+ const line = String(detail ?? "").split("\n").find((l) => l.trim()) ?? "";
200
+ const msg = line.replace(/\d{4}-\d\d-\d\dT[\d:.]+Z?/g, "<t>").replace(/\b[0-9a-f]{8,}\b/gi, "<h>").replace(/\d+/g, "<n>").replace(/\s+/g, " ").trim().slice(0, 240);
201
+ return `${code || "engine-error"}|${msg}`;
202
+ }
189
203
  // A dependency-open whose dependencies already finished satisfied (GitHub not yet closed): wait before relaunching.
190
204
  export const DEP_REQUEUE_DELAY_S = 60;
191
205
 
@@ -246,6 +260,7 @@ export function deferPolicy(r, { now, deferrals = 0, maxDeferrals = DEFAULT_MAX_
246
260
  }
247
261
  // #5168: a failed claude login is an account condition, not an engine fault: held like a usage limit, never capped.
248
262
  if (code === "backend.auth") return { delayMs: (posNum(r?.retryInSeconds) ?? RATE_LIMIT_FALLBACK_S) * 1000, hold: true };
263
+ // #5762: backend.cli_failed (the CLI exited without reaching the API) is a plain capped retry: no account hold.
249
264
  const k = deferrals + 1;
250
265
  if (k > maxDeferrals) return { capped: true };
251
266
  if (posNum(r?.retryInSeconds)) return { delayMs: r.retryInSeconds * 1000 };
@@ -314,7 +329,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
314
329
  classify = null, maintenance = null, limits = null, identity = () => "default", batchId = null, drift = null, integration = null, sched = null, priorityOf = null, remote = null, beforeAdmit = null, preflight = null,
315
330
  recovery = null, decide = () => {}, conflicting = null, relabelNeedsHuman = null, markRecovering = null, onExit = null, issueLabels = null, issueState = null, getCancelled = null, getHeld = null, expireHolds = null, getHoldInfo = null, getBlocked = null, trusted = null, getGates = null, stopLane = null, releaseLease = null, stopRetryMs = STOP_RETRY_MS, stopTimeoutMs = STOP_TIMEOUT_MS,
316
331
  estimate = null, starveMs = DEFAULT_STARVE_MS, setupConcurrency = DEFAULT_SETUP_CONCURRENCY, signal = null, dispatchCheck = null, syncParked = null, syncEveryMs = DEFAULT_SYNC_EVERY_MS, lifecycle = null,
317
- getChildren = null, autoChildren = null, baseWait = null, rotator = null, transientRetries = DEFAULT_TRANSIENT_RETRIES, overload = null, version = null, onInterrupted = null }) {
332
+ getChildren = null, autoChildren = null, baseWait = null, rotator = null, transientRetries = DEFAULT_TRANSIENT_RETRIES, overload = null, version = null, onInterrupted = null, envHold = null, envIssue = null, logicalDeps = null }) {
318
333
  const saved = store?.load?.() ?? null;
319
334
  const order = saved ? [...saved.order] : [];
320
335
  const set = new Set(order);
@@ -333,6 +348,21 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
333
348
  const engineErrors = toMap(saved?.engineErrors);
334
349
  const transients = toMap(saved?.transientRetries); // #5161: issue -> transient engine-error retries taken
335
350
  const transientMax = Number.isInteger(transientRetries) && transientRetries >= 0 ? transientRetries : DEFAULT_TRANSIENT_RETRIES;
351
+ // #5805: engine/env holds (off unless `envHold` is passed). `engineSigs`: issue -> signature of its relaunched engine-error;
352
+ // `deterministic`: `version|signature` seen twice (never relaunched again on that version); `toolReadmits`: `issue|signature`
353
+ // already re-admitted because the probe found the tool (a lane that still misses it waits for an engine or env change instead).
354
+ const ehOn = !!envHold || !!envIssue;
355
+ // #5755: env.* failures are one engine/env defect per signature: `envSigs` signature -> {issues, number} (the env issue the `envIssue` seam
356
+ // 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.
357
+ const envSigs = toMap(saved?.envSigs);
358
+ const engineSigs = toMap(saved?.engineSigs);
359
+ const deterministic = new Set(saved?.deterministicSigs ?? []);
360
+ const toolReadmits = new Set(saved?.toolReadmits ?? []);
361
+ const ehMaxMs = Number(envHold?.maxMs) > 0 ? Number(envHold.maxMs) : ENV_HOLD_MAX_MS;
362
+ const ehWatchMs = Number(envHold?.watchMs) > 0 ? Number(envHold.watchMs) : ENV_WATCH_MS;
363
+ const curVersion = () => { try { return envHold?.version?.() ?? version ?? null; } catch { return version ?? null; } };
364
+ const curEnv = () => { try { return envHold?.envFingerprint?.() ?? null; } catch { return null; } };
365
+ const missingTools = async (tools) => { if (typeof envHold?.missingTools !== "function") return null; try { const m = await envHold.missingTools(tools); return Array.isArray(m) ? m : null; } catch { return null; } };
336
366
  const checked = toMap(saved?.prefilter); // issue -> pre-filter result
337
367
  const estimates = toMap(saved?.estimates); // #4409: issue -> estimated lane minutes; only with `estimate`
338
368
  const enqueued = toMap(saved?.enqueued); // #4409: issue -> when it last entered the queue (starvation guard)
@@ -388,9 +418,10 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
388
418
  if (!remote) return null;
389
419
  // #4542: a lane recovering from a remote capability block runs on the host, which has the capability.
390
420
  // #4785: a tool-missing recovery too: the sandbox that lacked the tool is not chosen again.
421
+ // #5727: a tool no lane_tools recipe can install is never retried in another sandbox (toolNoRecipe), only on the host below
391
422
  // #5423: the lane now provisions the sandbox before ending tool_missing, so the first tool-missing recovery of a remote run retries remotely (not parked behind host load); a repeat goes to the host
392
423
  const rec = recovering.get(n);
393
- if (rec?.code === OUTCOME_CODES.ENV_TOOL_MISSING && rec.where === "remote" && (rec.attempt ?? 1) <= 1 && !budgetLocal) return { where: "remote", reason: "retry remotely after sandbox provisioning" };
424
+ if (rec?.code === OUTCOME_CODES.ENV_TOOL_MISSING && rec.where === "remote" && !rec.toolNoRecipe && (rec.attempt ?? 1) <= 1 && !budgetLocal) return { where: "remote", reason: "retry remotely after sandbox provisioning" };
394
425
  // #5652: with host fallback off (execution.host_fallback / host.role: orchestrator) the host is orchestrator-only: no re-placement here
395
426
  if (hostFallbackOn() && [OUTCOME_CODES.ENV_CAPABILITY_REMOTE, OUTCOME_CODES.ENV_TOOL_MISSING].includes(recovering.get(n)?.code)) return { where: "local", reason: `host capability: recovering ${recovering.get(n).code}` };
396
427
  // #5371: a mechanical recovery never repeats the placement of the run that failed (a remote sandbox env defect recurs there), and a remote validate failure is rerun on the host
@@ -421,10 +452,13 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
421
452
  // #5592: env.tool_missing repeats are the same defect when the same tools are missing, whatever else the detail says (probe lines, ids, paths vary per run)
422
453
  const toolsOf = (d) => { const m = /(?:host|sandbox) is missing ([^\n]+?), so validate command/i.exec(String(d ?? "")); return m ? m[1].split(/\s*,\s*/).sort().join(",") : null; };
423
454
  const envSig = (code, d) => (code === OUTCOME_CODES.ENV_TOOL_MISSING ? toolsOf(d) : null) ?? sigOf(d);
455
+ const ENV_ALL_CODES = [...REPEAT_ENV_CODES, ENV_VALIDATE_TIMEOUT, OUTCOME_CODES.ENV_CAPABILITY_REMOTE]; // #5755
456
+ const envKey = (code, d) => `${code}|${code === OUTCOME_CODES.ENV_TOOL_MISSING && toolsOf(d) ? toolsOf(d) : failureSignature(code, d).split("|").slice(1).join("|")}`;
424
457
  const maxFor = (cls) => (cls === "mechanical" ? mechMax : recoveryMax);
425
458
  const classUsed = toMap(saved?.recoveryClasses); // `${issue}:${class}` -> recovery lanes launched in that class
426
459
  const recoveries = toMap(saved?.recoveries); // issue -> recovery lanes launched (#4267)
427
460
  const recovering = toMap(saved?.recovering); // issue -> {code, attempt, detail, outcome, ...} of the recovery lane queued or running
461
+ const freeRecovered = new Set(); // #5727: issues whose one free (no-attempt) recovery for a recipe-less remote tool miss was spent
428
462
  const requeueApplied = new Set(saved?.requeueApplied ?? []); // #4550: `--requeue` entries already applied (batch `requeue` file)
429
463
  const requeuedInfo = toMap(saved?.requeued); // #4550: issue -> {reason, by, at, prior: [earlier rows]}
430
464
  const everRelabelled = new Set(saved?.relabelled ?? []); // #4656: issues the runner already relabelled; never parked on top
@@ -444,9 +478,57 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
444
478
  ...(recoveries.size || recovering.size ? { recoveries: toObj(recoveries), recovering: toObj(recovering), recoveryClasses: toObj(classUsed) } : {}),
445
479
  ...(requeueApplied.size ? { requeueApplied: [...requeueApplied], requeued: toObj(requeuedInfo) } : {}),
446
480
  ...(relabelled.size ? { relabelled: [...relabelled] } : {}), ...(cancelled ? { cancelled } : {}),
447
- ...(estimate ? { estimates: toObj(estimates), enqueued: toObj(enqueued) } : {}), ...(heads.size ? { heads: [...heads] } : {}) });
481
+ ...(estimate ? { estimates: toObj(estimates), enqueued: toObj(enqueued) } : {}), ...(heads.size ? { heads: [...heads] } : {}),
482
+ ...(engineSigs.size ? { engineSigs: toObj(engineSigs) } : {}), ...(deterministic.size ? { deterministicSigs: [...deterministic] } : {}), ...(toolReadmits.size ? { toolReadmits: [...toolReadmits] } : {}), ...(envSigs.size ? { envSigs: toObj(envSigs) } : {}) });
448
483
  };
449
484
  const update = (row) => { store?.log?.(row); onUpdate(row); };
485
+ /** #5755: records `issue` on its signature and files or updates the one env issue (seam `envIssue.ensure`); the issue number, or null when none could be filed. */
486
+ const fileEnvIssue = async ({ sig, code, issue, tools, evidence }) => {
487
+ const e = envSigs.get(sig) ?? { issues: [], number: null };
488
+ if (!e.issues.includes(issue)) e.issues.push(issue);
489
+ if (!e.text) e.text = firstLine(evidence).slice(0, 240); // the raw line: the signature digit-normalises its tokens
490
+ envSigs.set(sig, e);
491
+ try {
492
+ const r = await envIssue.ensure({ sig, code, issues: [...e.issues], tools, evidence, number: e.number });
493
+ const no = Number.isInteger(r) ? r : r?.number;
494
+ if (Number.isInteger(no) && no > 0) e.number = no;
495
+ } catch { /* best effort: without an env issue the existing flow applies */ }
496
+ save();
497
+ return e.number;
498
+ };
499
+ const envBodies = new Map();
500
+ /** #5755: once 2 issues hit one env signature, a pending issue whose contract needs it is held on the env issue instead of admitted (seam `envIssue.needs(n, sig)`, else its body names a missing tool). */
501
+ const gateEnvSigs = async () => {
502
+ if (!envIssue || tripped || cancelled) return;
503
+ const gated = [...envSigs].filter(([, e]) => e.issues.length >= 2 && e.number);
504
+ if (!gated.length) return;
505
+ for (const n of [...pending]) {
506
+ if (results.has(n) || running.has(n)) continue;
507
+ for (const [sig, e] of gated) {
508
+ let need = false;
509
+ try {
510
+ if (typeof envIssue.needs === "function") need = (await envIssue.needs(n, sig, e)) === true;
511
+ else {
512
+ // the contract text (frozen contract when known, else the issue body) is matched against the signature's tools, or for other env codes its path/command tokens
513
+ if (!envBodies.has(n)) envBodies.set(n, `${String(await readBody(n) ?? "")}\n${JSON.stringify(remote?.contractOf?.(n) ?? "")}`);
514
+ const esc = (t) => t.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
515
+ const toks = sig.startsWith(`${OUTCOME_CODES.ENV_TOOL_MISSING}|`) ? sig.split("|")[1].split(",") : (e.text ?? "").split(/[\s,;:'"`()]+/).filter((t) => t.length >= 4 && /[/.\\]/.test(t) && !/^\d/.test(t));
516
+ need = toks.some((t) => t && new RegExp(`(^|[^\\w-])${esc(t)}($|[^\\w-])`).test(envBodies.get(n)));
517
+ }
518
+ } catch { need = false; }
519
+ if (!need) continue;
520
+ pending.splice(pending.indexOf(n), 1);
521
+ const tools = sig.startsWith(`${OUTCOME_CODES.ENV_TOOL_MISSING}|`) ? sig.split("|")[1].split(",") : null;
522
+ if (!e.issues.includes(n)) e.issues.push(n);
523
+ const final = { issue: n, outcome: "held", cost_usd: 0, minutes: 0, detail: `waiting on env issue #${e.number}: ${sig.split("|")[0]} hit ${e.issues.length - 1} issues; admitted again when it closes`,
524
+ envHold: { kind: tools ? "tool" : "env", sig, from: "pending", version: curVersion(), env: curEnv(), ...(tools ? { tools } : {}), envIssue: e.number, since: now() }, waiting: true };
525
+ results.set(n, final); save();
526
+ decided({ issue: n, what: `held: not admitted, its contract needs the env that env issue #${e.number} tracks (${sig})`, why: `${e.issues.length} issues hit the same signature`, alternative: "admit it into the same env failure" });
527
+ update(final);
528
+ break;
529
+ }
530
+ }
531
+ };
450
532
  const classifyOne = async (n) => {
451
533
  if (!budget) return;
452
534
  let c = null;
@@ -467,9 +549,12 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
467
549
  estimates.set(n, Number.isFinite(v) && v > 0 ? v : EST_DEFAULT_MIN.M);
468
550
  };
469
551
  // #4773: a declaration line is an edge only when the body's author is trusted (the engine's admission applies the same rule).
552
+ // #5824: `logicalDeps(n)` adds the plan's code-derived logical edges (bin/lean/dag.mjs), trusted or not.
470
553
  const declared = async (n, body) => {
471
- if (typeof trusted === "function") { let ok = false; try { ok = (await trusted(n)) === true; } catch { ok = false; } if (!ok) return []; }
472
- return parseDeps(body, n);
554
+ let extra = [];
555
+ try { extra = typeof logicalDeps === "function" ? (logicalDeps(n) ?? []).filter((d) => Number.isSafeInteger(d) && d > 0 && d !== n) : []; } catch { extra = []; }
556
+ if (typeof trusted === "function") { let ok = false; try { ok = (await trusted(n)) === true; } catch { ok = false; } if (!ok) return extra; }
557
+ return [...new Set([...parseDeps(body, n), ...extra])];
473
558
  };
474
559
  // #5112: a dependency that ended `decomposed` (sub-issues joined, mode not off) is its sub-issues, to a fixpoint; used on every edge write.
475
560
  const throughDecomposed = (ds) => {
@@ -782,6 +867,22 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
782
867
  }
783
868
  if (sandboxUse.has(n)) row.sandbox = { ...sandboxUse.get(n), ...(sandboxUse.get(n).by_agent ? { by_agent: { ...sandboxUse.get(n).by_agent } } : {}) };
784
869
  const done = () => { running.delete(n); runRecs.delete(n); releaseSlot(n); endRemote(n); };
870
+ // #5805: an engine/env-caused end that would repeat as-is: held with its signature, re-admitted by watchEnvHolds, never terminal.
871
+ const holdEnv = ({ kind, sig, tools = null, why, envIssueNo = null }) => {
872
+ const p = recovering.get(n);
873
+ if (p) { // a recovery lane that hit an engine-error: its earlier attempts' cost stays on the row
874
+ recovering.delete(n);
875
+ row.cost_usd = Math.round(((Number(row.cost_usd) || 0) + (Number(p.cost_usd) || 0)) * 1e6) / 1e6;
876
+ row.minutes = Math.round(((Number(row.minutes) || 0) + (Number(p.minutes) || 0)) * 10) / 10;
877
+ }
878
+ 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`] : [])];
879
+ const final = { ...row, outcome: "held", detail: `waiting on engine/env change: ${why}; re-admitted on ${triggers.join(" or ")}\n${String(row.detail ?? "")}`,
880
+ envHold: { kind, sig, from: row.outcome, version: curVersion(), env: curEnv(), ...(tools?.length ? { tools } : {}), ...(envIssueNo ? { envIssue: envIssueNo } : {}), since: now() }, waiting: true };
881
+ results.set(n, final); done(); save();
882
+ decided({ issue: n, what: `held: waiting on engine/env change (${why})`, why: firstLine(row.detail) || row.outcome,
883
+ 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" });
884
+ update(final);
885
+ };
785
886
  if (row.outcome === "dependency-open" && depList.length) {
786
887
  // #4387: a parked dependency is not pulled in again (fail-open on an unreadable label).
787
888
  let parked;
@@ -892,12 +993,21 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
892
993
  return;
893
994
  }
894
995
  row.detail = `gave up after ${transientMax} transient retries: ${row.detail ?? ""}`;
996
+ } else if (ehOn && deterministic.has(`${curVersion()}|${failureSignature(r?.code, row.detail)}`)) {
997
+ // #5805: this exact engine-error already repeated on this engine version: a relaunch would hit it again
998
+ return holdEnv({ kind: "engine", sig: failureSignature(r?.code, row.detail), why: `the same engine-error already repeated on engine v${curVersion() ?? "?"}` });
895
999
  } else if ((engineErrors.get(n) ?? 0) < ENGINE_ERROR_RELAUNCHES) {
896
1000
  engineErrors.set(n, (engineErrors.get(n) ?? 0) + 1);
1001
+ if (ehOn) engineSigs.set(n, failureSignature(r?.code, row.detail));
897
1002
  requeue(n, 0); done(); save();
898
1003
  decided({ issue: n, what: "relaunch once after engine-error", why: firstLine(row.detail) || "engine-error", alternative: "end the issue engine-error and skip its dependents" });
899
1004
  update({ ...row, detail: `relaunching once: ${row.detail ?? ""}` });
900
1005
  return;
1006
+ } else if (ehOn && engineSigs.get(n) === failureSignature(r?.code, row.detail)) {
1007
+ // #5805: the relaunch failed identically: deterministic for this engine version, held (not terminal) until the engine or env changes
1008
+ const sig = failureSignature(r?.code, row.detail);
1009
+ deterministic.add(`${curVersion()}|${sig}`);
1010
+ return holdEnv({ kind: "engine", sig, why: `the relaunch failed with the same engine-error on engine v${curVersion() ?? "?"}` });
901
1011
  }
902
1012
  }
903
1013
  if (row.outcome === "decomposed" && subs.length && joinsDecomposed(autoChildren?.mode ?? "decomposed")) {
@@ -925,6 +1035,20 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
925
1035
  }
926
1036
  }
927
1037
  // #5526: the hold is re-read here (it is only read once per pass): a held issue's terminal outcome starts no recovery lane.
1038
+ // #5755: an env.* needs-human end is the engine's defect: one env issue per signature, the product issue held on it (waiting-dependency), no needs-human.
1039
+ if (envIssue && row.outcome === "needs-human" && ENV_ALL_CODES.includes(row.code)) {
1040
+ const tools = row.code === OUTCOME_CODES.ENV_TOOL_MISSING ? toolsOf(row.detail) : null;
1041
+ const sig = envKey(row.code, row.detail);
1042
+ const no = await fileEnvIssue({ sig, code: row.code, issue: n, tools: tools ? tools.split(",") : null, evidence: String(row.detail ?? "") });
1043
+ // A security issue is not parked behind an env fix and never sits in remediation-queue: it keeps its needs-human for a person.
1044
+ let names = []; try { names = typeof issueLabels === "function" ? ((await issueLabels(n)) ?? []) : []; } catch { names = []; }
1045
+ if (names.some((l) => /security/i.test(String(l?.name ?? l)))) {
1046
+ row.securityEscalated = true;
1047
+ row.detail = `Security issue escalated: ${row.code} is an env defect tracked${no ? ` on env issue #${no}` : ""}; it is not parked in the remediation queue.\n${String(row.detail ?? "")}`;
1048
+ if (typeof relabelNeedsHuman === "function") { try { await relabelNeedsHuman({ issue: n, evidence: `Security issue escalated: \`${row.code}\` env defect${no ? ` (env issue #${no})` : ""}:\n${String(row.detail ?? "")}` }); } catch { /* best effort */ } }
1049
+ decided({ issue: n, what: `escalated: ${row.code} on a security issue, not held or queued for remediation`, why: firstLine(row.detail), alternative: "hold it on the env issue like other product issues" });
1050
+ } else return holdEnv({ kind: tools ? "tool" : "env", sig, tools: tools ? tools.split(",") : null, envIssueNo: no, why: no ? `${row.code}: env issue #${no} owns the fix` : `${row.code}: the env issue could not be filed; held, never needs-human` });
1051
+ }
928
1052
  const heldNow = recoveryMax && ["needs-human", "ci-pending", "budget-exceeded"].includes(row.outcome) && (refreshHeld(), opHeld.has(n));
929
1053
  if (heldNow) decided({ issue: n, what: `no recovery lane for #${n}: ${heldByOperator(n)}`, why: firstLine(row.detail) || row.outcome, alternative: "recover while the operator holds it" });
930
1054
  if (recoveryMax && !heldNow && ["needs-human", "ci-pending", "budget-exceeded"].includes(row.outcome)) {
@@ -933,12 +1057,27 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
933
1057
  try { isConflicting = (await conflicting(n, row.pr)) === true; } catch { isConflicting = false; }
934
1058
  }
935
1059
  const facts = { ...row, issueEdited: r?.issueEdited === true, quoteMismatch: r?.quoteMismatch === true, conflicting: isConflicting };
936
- if (prior) { const pk = `${n}:${recoveryClassOf({ code: prior.code })}`; classUsed.set(pk, Math.max(classUsed.get(pk) ?? 0, prior.attempt)); } // state saved before #4725 has no class counts
1060
+ if (prior) { const pk = `${n}:${recoveryClassOf({ code: prior.code })}`; classUsed.set(pk, Math.max(classUsed.get(pk) ?? 0, prior.free ? prior.attempt - 1 : prior.attempt)); } // #5727: a free recovery spent no attempt // state saved before #4725 has no class counts
937
1061
  const cls = recoveryClassOf(facts), max = maxFor(cls), used = classUsed.get(`${n}:${cls}`) ?? 0;
938
1062
  // #5232: a deterministic env defect of the frozen command that a recovery attempt repeated verbatim is not rebuilt again
939
1063
  const repeatEnv = prior && REPEAT_ENV_CODES.includes(row.code) && prior.code === row.code && envSig(row.code, prior.detail) === envSig(row.code, row.detail);
940
1064
  // #5592: a first env.tool_missing that ran on this host (not a remote sandbox) would be replayed with the identical frozen contract on the same host and fail identically: not launched as-is
941
1065
  const sameHostReplay = !repeatEnv && !prior && row.code === OUTCOME_CODES.ENV_TOOL_MISSING && row.placement?.where !== "remote" && toolsOf(row.detail) !== null;
1066
+ // #5805: an env defect the host still has is held until the engine, the batch env or the host changes, not ended or re-run.
1067
+ // A tool-missing recovery that would run on the host (not the #5423 remote retry) is not launched while the probe still misses the tool.
1068
+ const envNoHost = !hostFallbackOn() && row.placement?.where === "remote" && [OUTCOME_CODES.ENV_CAPABILITY_REMOTE, OUTCOME_CODES.ENV_TOOL_MISSING].includes(row.code);
1069
+ const lacking = row.code === OUTCOME_CODES.ENV_TOOL_MISSING ? toolsOf(row.detail) : null;
1070
+ if (ehOn && !envNoHost && !row.securityEscalated) {
1071
+ let stillLacks = false;
1072
+ if (!repeatEnv && !sameHostReplay && lacking && classifyNeedsHuman(facts) === "recoverable" && used < max && !(row.placement?.where === "remote" && used === 0 && !budgetLocal)) {
1073
+ const miss = await missingTools(lacking.split(","));
1074
+ stillLacks = !!miss?.length;
1075
+ }
1076
+ if (repeatEnv || sameHostReplay || stillLacks) {
1077
+ return holdEnv({ kind: lacking ? "tool" : "env", sig: `${row.code}|${envSig(row.code, row.detail)}`, tools: lacking ? lacking.split(",") : null,
1078
+ why: repeatEnv ? `the recovery repeated the same ${row.code}` : `the host ${sameHostReplay ? "that ran it " : "still "}lacks ${lacking}` });
1079
+ }
1080
+ }
942
1081
  if (sameHostReplay) {
943
1082
  row.detail = `Environment defect: the run already executed on the host that lacks ${toolsOf(row.detail)}, and a recovery would replay the identical frozen contract on that same host, so none is launched. Install the tool or fix the dependency install on the host (or amend the contract's validate/env), then requeue.\n${String(row.detail ?? "")}`;
944
1083
  decided({ issue: n, what: `no recovery for ${row.code}: the frozen contract would fail identically on the same host`, why: firstLine(row.detail), alternative: "requeue a recovery lane that replays the same frozen contract on the same host" });
@@ -951,11 +1090,13 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
951
1090
  const noHostRecovery = !hostFallbackOn() && row.placement?.where === "remote" && [OUTCOME_CODES.ENV_CAPABILITY_REMOTE, OUTCOME_CODES.ENV_TOOL_MISSING].includes(row.code);
952
1091
  if (noHostRecovery) decided({ issue: n, what: `no host re-placement for ${row.code}: host fallback is off (execution.host_fallback / host.role: orchestrator)`, why: firstLine(row.detail), alternative: "re-place the lane on the host" });
953
1092
  if (!repeatEnv && !noHostRecovery && !sameHostReplay && classifyNeedsHuman(facts) === "recoverable" && used < max) {
1093
+ // #5727: the first remote end on a tool no recipe can install, before any build work, is re-placed on the host without spending an attempt
1094
+ const free = !prior && r?.toolNoRecipe === true && row.code === OUTCOME_CODES.ENV_TOOL_MISSING && row.placement?.where === "remote" && !freeRecovered.has(n);
954
1095
  const code = recoveryCodeOf(facts), attempt = used + 1;
955
- classUsed.set(`${n}:${cls}`, attempt);
1096
+ if (free) freeRecovered.add(n); else classUsed.set(`${n}:${cls}`, attempt);
956
1097
  // #4315: the full lane detail is kept (never firstLine) for the relabel when the batch stops before this attempt
957
1098
  recoveries.set(n, (recoveries.get(n) ?? 0) + 1); recovering.set(n, { code, attempt, max, cost_usd: Number(row.cost_usd) || 0, minutes: Number(row.minutes) || 0,
958
- detail: String(row.detail ?? ""), outcome: row.outcome, ...(row.placement?.where ? { where: row.placement.where } : {}), ...(row.code ? { result_code: row.code } : {}), prev_attempt: prior?.attempt ?? 0 });
1099
+ detail: String(row.detail ?? ""), outcome: row.outcome, ...(row.placement?.where ? { where: row.placement.where } : {}), ...(free ? { free: true, toolNoRecipe: true } : r?.toolNoRecipe === true ? { toolNoRecipe: true } : {}), ...(row.code ? { result_code: row.code } : {}), prev_attempt: prior?.attempt ?? 0 });
959
1100
  requeue(n, 0); done(); save();
960
1101
  // #5647: the first lane labelled needs-human before the batch chose to recover; swap it for workflow:recovering while the recovery runs
961
1102
  if (typeof markRecovering === "function") { try { await markRecovering({ issue: n, code, attempt, max }); } catch { /* best effort: needs-human stays */ } }
@@ -974,7 +1115,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
974
1115
  try { await relabelNeedsHuman({ issue: n, evidence: `Implement turn budget overrun (\`budget.exceeded\`) not recovered in this batch:\n${String(row.detail ?? "")}` }); } catch { /* best effort */ }
975
1116
  }
976
1117
  // #4656: a mechanical terminal park (recovery spent or none applies) moves to the remediation queue, not the human queue.
977
- if (row.outcome === "needs-human" && !row.parkedQueued && !everRelabelled.has(n) && typeof relabelNeedsHuman === "function" && (cls => cls === "parked" || (cls === "recoverable" && prior))(classifyNeedsHuman({ ...row, issueEdited: r?.issueEdited === true }, { parked: true }))) { // a recoverable row with a finished recovery has used its attempts
1118
+ if (row.outcome === "needs-human" && !row.parkedQueued && !row.securityEscalated && !everRelabelled.has(n) && typeof relabelNeedsHuman === "function" && (cls => cls === "parked" || (cls === "recoverable" && prior))(classifyNeedsHuman({ ...row, issueEdited: r?.issueEdited === true }, { parked: true }))) { // a recoverable row with a finished recovery has used its attempts
978
1119
  try { const res = await relabelNeedsHuman({ issue: n, parked: { code: row.code, pr: Number.isInteger(row.pr) ? row.pr : null }, evidence: `Mechanical park \`${row.code}\`${Number.isInteger(row.pr) ? ` (PR #${row.pr})` : ""}:\n${String(row.detail ?? "")}` }); if (res !== false && res !== "failed" && res !== "skipped") row.parkedQueued = true; else if (res === false || res === "failed") { const ev = { event: "relabel.failed", issue: n, batch: batchId ?? null, detail: `parked relabel failed (${row.code}): needs-human kept` }; try { store?.log?.(ev); } catch { /* best effort */ } onUpdate(ev); } } catch { /* best effort */ }
979
1120
  }
980
1121
  results.set(n, row);
@@ -1231,7 +1372,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1231
1372
  }
1232
1373
  }
1233
1374
  for (const m of moved) {
1234
- for (const x of [requeues, deferrals, capDefers, engineErrors, transients, recoveries, recovering]) x.delete(m);
1375
+ for (const x of [requeues, deferrals, capDefers, engineErrors, engineSigs, transients, recoveries, recovering]) x.delete(m);
1235
1376
  relabelled.delete(m);
1236
1377
  if (m === e.issue) requeuedInfo.set(m, { reason: e.reason, by: e.by, at: e.at, prior: [...(requeuedInfo.get(m)?.prior ?? []), priors.get(m)] });
1237
1378
  if (!pending.includes(m)) requeue(m, 0);
@@ -1399,13 +1540,54 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1399
1540
  if (moved.length) results.delete(root);
1400
1541
  for (const [m, r] of [...results]) if (r?.outcome === "held" && r.root === root) { results.delete(m); moved.push(m); }
1401
1542
  for (const m of moved) {
1402
- for (const x of [requeues, deferrals, capDefers, engineErrors, transients, recoveries, recovering]) x.delete(m);
1543
+ for (const x of [requeues, deferrals, capDefers, engineErrors, engineSigs, transients, recoveries, recovering]) x.delete(m);
1403
1544
  relabelled.delete(m);
1404
1545
  if (!pending.includes(m)) requeue(m, 0);
1405
1546
  update({ issue: m, outcome: "readmitted", detail: m === root ? why : `dependency #${root} ${why}`, trigger: root });
1406
1547
  }
1407
1548
  if (moved.length) { save(); decided({ issue: root, what: `released held subtree of #${root}: ${moved.filter((m) => m !== root).map((m) => `#${m}`).join(", ") || "none"}`, why, alternative: "leave it held until a --requeue" }); }
1408
1549
  };
1550
+ // #5805: held engine/env failures are re-checked (every ehWatchMs, and at once when nothing else runs): a changed engine version, a
1551
+ // changed batch env (--set-env) or a probe that now finds every missing tool re-admits the issue and its held dependents, like --requeue.
1552
+ let envWatchAt = null;
1553
+ const envHeld = () => [...results.values()].filter((r) => r?.outcome === "held" && r.envHold);
1554
+ const envWaiting = () => ehOn && !cancelled && !tripped && !budgetStop && envHeld().some((r) => now() - (Number(r.envHold.since) || 0) < ehMaxMs);
1555
+ let envClosedAt = null;
1556
+ const watchEnvHolds = async (force = false) => {
1557
+ if (!ehOn || cancelled) return;
1558
+ const rows = envHeld();
1559
+ if (!rows.length || (!force && envWatchAt !== null && now() - envWatchAt < ehWatchMs)) return;
1560
+ envWatchAt = now();
1561
+ const v = curVersion(), fp = curEnv(), checkClosed = dispatchCheck && (envClosedAt === null || now() - envClosedAt >= WATCH_EVERY_MS);
1562
+ if (checkClosed) envClosedAt = now();
1563
+ for (const r of rows) {
1564
+ const n = r.issue, h = r.envHold;
1565
+ if (running.has(n) || results.get(n) !== r) continue;
1566
+ if (checkClosed) { // closed or merged outside the batch: no longer waited on
1567
+ let g = null;
1568
+ try { g = (await dispatchCheck(n)) ?? null; } catch { g = null; }
1569
+ if (g && (g.final || SATISFIED.has(g.outcome))) {
1570
+ const { waiting, envHold: _h, ...rest } = r;
1571
+ results.set(n, { ...rest, outcome: SATISFIED.has(g.outcome) ? g.outcome : "invalid", pr: Number.isInteger(g.pr) ? g.pr : rest.pr, detail: g.detail ?? `closed while waiting on engine/env change` });
1572
+ update(results.get(n));
1573
+ if (SATISFIED.has(g.outcome)) releaseHeld(n, false, "merged or closed"); else save();
1574
+ continue;
1575
+ }
1576
+ }
1577
+ let why = null;
1578
+ 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`; }
1579
+ if (!why && v && h.version && v !== h.version) why = `engine version changed v${h.version} → v${v}`;
1580
+ if (why) { /* env issue closed */ } else if (fp && h.env && fp !== h.env) why = "batch env changed (--set-env)";
1581
+ 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}`); }
1582
+ if (why) { engineSigs.delete(n); releaseHeld(n, true, `re-admitted: ${why}`); continue; }
1583
+ 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
1584
+ const { waiting, ...rest } = r;
1585
+ const [head, ...tail] = String(rest.detail ?? "").split("\n");
1586
+ results.set(n, { ...rest, detail: [`${head}; no engine/env change within ${Math.round(ehMaxMs / 3600_000 * 10) / 10}h (forgedock orchestrate --requeue retries it)`, ...tail].join("\n") });
1587
+ save(); update(results.get(n));
1588
+ }
1589
+ }
1590
+ };
1409
1591
  const restoredHeld = new Set([...results.values()].filter((r) => r?.outcome === "held" && Number.isInteger(r.root)).map((r) => r.root)); // roots held by an earlier run of this batch
1410
1592
  const watchHeldRoots = async () => {
1411
1593
  for (const root of new Set([...results.values()].filter((r) => r?.outcome === "held" && Number.isInteger(r.root)).map((r) => r.root))) {
@@ -1474,6 +1656,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1474
1656
  if (back.size) save();
1475
1657
  };
1476
1658
  const K = () => { let k = null; try { k = getParallel?.(); } catch { k = null; } return Number.isInteger(k) && k >= 1 ? k : parallel; };
1659
+ let firstPass = true; // #5805: a resume (e.g. after an upgrade) re-checks the engine/env holds at once
1477
1660
  try {
1478
1661
  for (;;) {
1479
1662
  if (signal?.aborted) throw halt();
@@ -1481,7 +1664,12 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1481
1664
  await drainRequeues();
1482
1665
  checkCancel();
1483
1666
  await watchBlockers(!pending.length && !running.size);
1484
- if (!pending.length && !running.size) break;
1667
+ await watchEnvHolds(firstPass || (!pending.length && !running.size)); // #5805
1668
+ firstPass = false;
1669
+ if (!pending.length && !running.size) {
1670
+ if (envWaiting() && !signal?.aborted) { await nap(ehWatchMs); continue; } // #5805: only engine/env holds remain: keep re-checking them
1671
+ break;
1672
+ }
1485
1673
  // Resolve skips first: a dependency that finished unsatisfied (or never can) skips its dependents.
1486
1674
  for (let again = true; again;) { // #4595: to a fixpoint, so a chain's tail is skipped on its blocker, not as a "cycle"
1487
1675
  again = false;
@@ -1521,6 +1709,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1521
1709
  if (pfNoted.size && !keys.size) update({ issue: null, outcome: "preflight", detail: "preflight cleared; admissions resumed" });
1522
1710
  pfNoted = keys;
1523
1711
  }
1712
+ await gateEnvSigs(); // #5755
1524
1713
  const isReady = (n) => {
1525
1714
  if (pfAll || (pfRemote && isRemote(n))) return false;
1526
1715
  if (opHeld.has(n)) { opHeldHit.add(n); return false; }
@@ -1614,6 +1803,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1614
1803
  if (getHeld && running.size) wake = Math.min(wake ?? pollMs, pollMs); // #4592: a release while only lanes run
1615
1804
  if (syncParked && running.size && parkedPrs().length) wake = Math.min(wake ?? syncEveryMs, Math.max(0, syncEveryMs - (t - (lastParkedSync ?? t)))); // #4525
1616
1805
  if (running.size && watchable()) wake = Math.min(wake ?? WATCH_EVERY_MS, WATCH_EVERY_MS); // #4595: re-check the blockers of skipped rows
1806
+ if (running.size && envWaiting()) wake = Math.min(wake ?? ehWatchMs, ehWatchMs); // #5805: re-check engine/env holds while lanes run
1617
1807
  if (tripped) wake = null;
1618
1808
  if (getCancelled && running.size && (!cancelled || [...running.keys()].some((n) => { const x = stopSent.get(n); return x && !(x.accepted && x.reported); }))) wake = Math.min(wake ?? pollMs, pollMs); // #5241: a cancel keeps polling a lane whose stop is unconfirmed // #4376: notice a cancel while lanes run
1619
1809
  if (running.size) {
@@ -1743,7 +1933,7 @@ export function formatTable(rows) {
1743
1933
  // #4255: sandbox minutes and cost next to the token cost, only when some lane ran in a sandbox.
1744
1934
  const sbx = rows.some((r) => r?.sandbox);
1745
1935
  const head = ["issue", "outcome", "PR", "cost", ...(sbx ? ["sbx-min", "sbx-$"] : []), "min"];
1746
- const body = rows.map((r) => [`#${r.issue}`, r.quota?.resumeAt && ["held", "paused"].includes(r.outcome) ? `paused (quota) until ${r.quota.resumeAt}` : (r.waiting && /^dependency #(\d+) /.test(r.detail ?? "") ? `waiting on #${/^dependency #(\d+) /.exec(r.detail)[1]}` : r.outcome) + (["skipped", "held"].includes(r.outcome) && r.detail ? ` (${r.detail})` : r.prefilter?.closed || r.prefilter?.parked ? " (pre-filter)" : ""), r.pr ? `#${r.pr}` : "-", `$${(r.cost_usd ?? 0).toFixed(2)}`,
1936
+ const body = rows.map((r) => [`#${r.issue}`, r.quota?.resumeAt && ["held", "paused"].includes(r.outcome) ? `paused (quota) until ${r.quota.resumeAt}` : (r.waiting && /^dependency #(\d+) /.test(r.detail ?? "") ? `waiting on #${/^dependency #(\d+) /.exec(r.detail)[1]}` : r.outcome) + (["skipped", "held"].includes(r.outcome) && r.detail ? ` (${String(r.detail).split("\n")[0]})` : r.prefilter?.closed || r.prefilter?.parked ? " (pre-filter)" : ""), r.pr ? `#${r.pr}` : "-", `$${(r.cost_usd ?? 0).toFixed(2)}`,
1747
1937
  ...(sbx ? (r.sandbox ? [(Number(r.sandbox.minutes) || 0).toFixed(1), `$${(Number(r.sandbox.cost_usd) || 0).toFixed(2)}`] : ["-", "-"]) : []), String(r.minutes ?? 0)]);
1748
1938
  const w = head.map((h, i) => Math.max(h.length, ...body.map((b) => b[i].length)));
1749
1939
  const line = (c) => c.map((x, i) => x.padEnd(w[i])).join(" ").trimEnd();
@@ -0,0 +1,104 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * #5752: declared outcome-evidence areas. forge.yaml `outcome_evidence: {paths: {area: globs}, corpus: {area: globs}}`.
5
+ * Absent or no `paths` area = off. A lane whose non-test changed files match an area must record a before/after measurement on
6
+ * recorded real inputs (a replay corpus, production samples) in its result: `outcome_evidence: [{area, metric, corpus, before,
7
+ * after, better}]`; and a post-deploy check of such a lane must be a metric with a baseline, not a string match. Failures are
8
+ * conformance.unimplemented rows (no new outcome code), each naming the area, the files and the required shape.
9
+ * Deterministic, 0 LLM calls, repo-agnostic like docsgate.mjs.
10
+ */
11
+ import { OUTCOME_CODES } from "../engine/outcome-codes.mjs";
12
+ import { globToRegex } from "../../scripts/ci-local/lib.mjs";
13
+ import { CHECKS_FILE } from "./postdeploy-check.mjs";
14
+
15
+ const TEST_RE = /(?:^|\/)(?:__tests__|tests?)\/|\.(?:test|spec)\.[cm]?[jt]sx?$|(?:^|\/)test_[^/]*\.py$|_test\.(?:py|go)$/;
16
+ const norm = (p) => String(p ?? "").trim().replace(/^\.\//, "");
17
+ const list = (v) => (Array.isArray(v) ? v : typeof v === "string" ? v.replace(/^\[|\]$/g, "").split(",") : []).map((x) => String(x ?? "").trim().replace(/^(["'])(.*)\1$/, "$2").trim()).filter(Boolean);
18
+ const areaMap = (raw) => {
19
+ const out = {};
20
+ if (raw && typeof raw === "object" && !Array.isArray(raw)) for (const [k, v] of Object.entries(raw)) { const g = list(v).map(norm); if (k.trim() && g.length) out[k.trim()] = g; }
21
+ return out;
22
+ };
23
+ const anyGlob = (globs, f) => (globs ?? []).some((g) => globToRegex(g).test(f));
24
+ const num = (v) => (typeof v === "number" ? v : typeof v === "string" && v.trim() !== "" ? Number(v) : NaN);
25
+ const BETTER = ["higher", "lower"];
26
+
27
+ /** forge.yaml outcome_evidence: section -> {paths: {area: globs}, corpus: {area: globs}} or null when off. */
28
+ export function parseOutcomeEvidenceConfig(raw) {
29
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
30
+ const paths = areaMap(raw.paths);
31
+ if (!Object.keys(paths).length) return null;
32
+ return { paths, corpus: areaMap(raw.corpus) };
33
+ }
34
+
35
+ /** Touched areas `{area: [files]}`: non-test changed files matching an area's globs (corpus files themselves do not count). */
36
+ export function touchedAreas(cfg, files) {
37
+ const out = {};
38
+ if (!cfg) return out;
39
+ const corpusGlobs = Object.values(cfg.corpus ?? {}).flat();
40
+ for (const f0 of files ?? []) {
41
+ const f = norm(f0);
42
+ if (!f || TEST_RE.test(f) || anyGlob(corpusGlobs, f)) continue;
43
+ for (const [area, globs] of Object.entries(cfg.paths)) if (anyGlob(globs, f)) (out[area] ??= []).push(f);
44
+ }
45
+ return out;
46
+ }
47
+
48
+ const shape = (area, cfg) => `result.outcome_evidence: [{"area":"${area}","metric":"<name>","corpus":"<recorded real inputs${cfg.corpus?.[area]?.length ? ` matching ${cfg.corpus[area].join(", ")}` : ""}>","before":<number>,"after":<number>,"better":"higher|lower"}]`;
49
+
50
+ /** The reason a row cannot stand as evidence for `area`, or null when it is well formed. */
51
+ function rowProblem(row, area, cfg, exists) {
52
+ if (typeof row.metric !== "string" || !row.metric.trim()) return "metric is missing (name what was measured)";
53
+ const corpus = norm(row.corpus);
54
+ if (!corpus) return "corpus is missing (the recorded real inputs measured: a replay corpus or production samples, not mocks)";
55
+ if (cfg.corpus?.[area]?.length && !anyGlob(cfg.corpus[area], corpus)) return `corpus ${corpus} is not a declared corpus for this area (${cfg.corpus[area].join(", ")})`;
56
+ if (exists && !exists(corpus)) return `corpus ${corpus} does not exist in the tree`;
57
+ if (!Number.isFinite(num(row.before)) || !Number.isFinite(num(row.after))) return `before (${JSON.stringify(row.before ?? null)}) and after (${JSON.stringify(row.after ?? null)}) must be numbers`;
58
+ if (row.better !== undefined && !BETTER.includes(row.better)) return `better must be "higher" or "lower", not ${JSON.stringify(row.better)}`;
59
+ return null;
60
+ }
61
+
62
+ /** The raw post-deploy checks entries {id: entry} at each git ref (later refs win); parseChecks drops the baseline field this gate reads. */
63
+ export async function rawChecksAt(git, refs) {
64
+ const out = {};
65
+ for (const ref of refs) {
66
+ try { const j = JSON.parse(String(await git(["show", `${ref}:${CHECKS_FILE}`]))); if (j && typeof j === "object" && !Array.isArray(j)) for (const [id, v] of Object.entries(j)) out[id] = v && typeof v === "object" ? v : { run: v }; } catch { /* no file at this ref */ }
67
+ }
68
+ return out;
69
+ }
70
+
71
+ /** A post-deploy check's baseline is a metric: {metric, value: number, better?}. */
72
+ const baselineOk = (b) => b && typeof b === "object" && typeof b.metric === "string" && b.metric.trim() && Number.isFinite(num(b.value)) && (b.better === undefined || BETTER.includes(b.better));
73
+
74
+ /**
75
+ * Blocking failures (conformance.unimplemented) for touched areas: `outcome_evidence_missing` (no result row for the area),
76
+ * `outcome_evidence_invalid` (no metric, corpus not real/declared/present, non-numeric values), `outcome_evidence_regressed`
77
+ * (after is worse than before), `outcome_evidence_baseline_missing` (a post-deploy check of this lane with no metric baseline).
78
+ * `checks` is the post-deploy checks map {id: entry}; `exists(path)` tells whether a file is in the lane tree.
79
+ */
80
+ export function outcomeEvidenceFailures({ cfg, files = [], result = null, exists = null, checks = null, contract = null }) {
81
+ if (!cfg) return [];
82
+ const touched = touchedAreas(cfg, files), areas = Object.keys(touched);
83
+ if (!areas.length) return [];
84
+ const C = OUTCOME_CODES.CONFORMANCE_UNIMPLEMENTED, out = [];
85
+ const rows = (Array.isArray(result?.outcome_evidence) ? result.outcome_evidence : []).filter((r) => r && typeof r === "object");
86
+ for (const area of areas) {
87
+ const fs = touched[area], where = `outcome-evidence area '${area}' (forge.yaml outcome_evidence.paths) touched by ${fs.slice(0, 5).join(", ")}${fs.length > 5 ? ` (+${fs.length - 5} more)` : ""}`;
88
+ const mine = rows.filter((r) => String(r.area ?? "").trim() === area);
89
+ if (!mine.length) { out.push({ code: C, kind: "outcome_evidence_missing", area, detail: `${where} has no before/after measurement on recorded real inputs: add ${shape(area, cfg)}` }); continue; }
90
+ for (const row of mine) {
91
+ const bad = rowProblem(row, area, cfg, exists);
92
+ if (bad) { out.push({ code: C, kind: "outcome_evidence_invalid", area, detail: `${where}: outcome_evidence row ${bad}; expected ${shape(area, cfg)}` }); continue; }
93
+ const before = num(row.before), after = num(row.after), better = row.better ?? "higher";
94
+ if (better === "higher" ? after < before : after > before) out.push({ code: C, kind: "outcome_evidence_regressed", area, detail: `${where}: ${row.metric} on ${norm(row.corpus)} got worse (before ${before}, after ${after}, ${better} is better)` });
95
+ }
96
+ }
97
+ for (const r of contract?.requirements ?? []) {
98
+ if (r?.disposition !== "post-deploy" || !r.check) continue;
99
+ const entry = checks?.[r.check];
100
+ if (!entry) continue; // an unknown check id is check_unknown's finding
101
+ if (!baselineOk(entry.baseline)) out.push({ code: C, kind: "outcome_evidence_baseline_missing", area: areas.join(", "), detail: `${r.id} post-deploy check '${r.check}' covers outcome-evidence area ${areas.map((a) => `'${a}'`).join(", ")} but has no metric baseline: give it "baseline": {"metric":"<name>","value":<number>,"better":"higher|lower"} in .forge/post-deploy-checks.json, a metric with a baseline, not a string match` });
102
+ }
103
+ return out;
104
+ }