forgedock 1.52.0 → 1.54.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 (233) hide show
  1. package/.claude-plugin/marketplace.json +51 -0
  2. package/README.md +8 -2
  3. package/bin/auth/app-manifest.mjs +89 -0
  4. package/bin/auth/app-manifest.test.mjs +75 -0
  5. package/bin/auth/app-token.mjs +256 -0
  6. package/bin/auth/app-token.test.mjs +232 -0
  7. package/bin/brand.mjs +7 -0
  8. package/bin/config-history.mjs +151 -0
  9. package/bin/config-schema.mjs +115 -0
  10. package/bin/demo.mjs +65 -11
  11. package/bin/engine/outcome-codes.mjs +9 -3
  12. package/bin/engine/telemetry-seam.mjs +11 -3
  13. package/bin/engine/telemetry-seam.test.mjs +17 -0
  14. package/bin/engine-cli.mjs +110 -36
  15. package/bin/experiment.mjs +58 -6
  16. package/bin/first-run.mjs +122 -0
  17. package/bin/forge-utils.mjs +6 -2
  18. package/bin/forgedock.mjs +138 -142
  19. package/bin/help-text.mjs +144 -0
  20. package/bin/hooks/pre-tool-use.mjs +7 -0
  21. package/bin/journey.mjs +82 -83
  22. package/bin/lean/acceptance.mjs +313 -0
  23. package/bin/lean/acceptance.test.mjs +215 -0
  24. package/bin/lean/account-watch.mjs +28 -0
  25. package/bin/lean/account-watch.test.mjs +30 -0
  26. package/bin/lean/activation.mjs +38 -0
  27. package/bin/lean/activation.test.mjs +36 -1
  28. package/bin/lean/basered.mjs +115 -0
  29. package/bin/lean/basered.test.mjs +66 -0
  30. package/bin/lean/batch-health.mjs +114 -7
  31. package/bin/lean/batch-health.test.mjs +87 -1
  32. package/bin/lean/batch.mjs +41 -2
  33. package/bin/lean/batch.test.mjs +115 -11
  34. package/bin/lean/branchlock.mjs +54 -0
  35. package/bin/lean/branchlock.test.mjs +49 -0
  36. package/bin/lean/ceiling.mjs +72 -0
  37. package/bin/lean/ceiling.test.mjs +54 -0
  38. package/bin/lean/checkpoint-reconcile.mjs +43 -0
  39. package/bin/lean/checkpoint-reconcile.test.mjs +95 -0
  40. package/bin/lean/ci-budget.mjs +366 -0
  41. package/bin/lean/ci-budget.test.mjs +167 -0
  42. package/bin/lean/conformance.e2e.test.mjs +8 -1
  43. package/bin/lean/conformance.mjs +269 -38
  44. package/bin/lean/conformance.test.mjs +280 -7
  45. package/bin/lean/context.mjs +35 -6
  46. package/bin/lean/context.test.mjs +27 -1
  47. package/bin/lean/depcache.mjs +25 -1
  48. package/bin/lean/depcache.test.mjs +26 -0
  49. package/bin/lean/e2e.mjs +18 -2
  50. package/bin/lean/e2e.test.mjs +26 -1
  51. package/bin/lean/effects.mjs +47 -14
  52. package/bin/lean/execution.mjs +19 -3
  53. package/bin/lean/execution.test.mjs +63 -0
  54. package/bin/lean/facts.mjs +3 -3
  55. package/bin/lean/facts.test.mjs +5 -0
  56. package/bin/lean/findinglabel.mjs +16 -0
  57. package/bin/lean/findinglabel.test.mjs +39 -0
  58. package/bin/lean/fixround.mjs +14 -0
  59. package/bin/lean/fixround.test.mjs +25 -2
  60. package/bin/lean/gh-assoc.test.mjs +2 -1
  61. package/bin/lean/integration.mjs +100 -9
  62. package/bin/lean/integration.test.mjs +98 -0
  63. package/bin/lean/issuewatch-parity.mjs +64 -0
  64. package/bin/lean/issuewatch-parity.test.mjs +127 -0
  65. package/bin/lean/issuewatch-release.mjs +6 -2
  66. package/bin/lean/issuewatch-release.test.mjs +17 -1
  67. package/bin/lean/issuewatch.mjs +45 -6
  68. package/bin/lean/issuewatch.test.mjs +3 -2
  69. package/bin/lean/lanelock.mjs +14 -0
  70. package/bin/lean/lean.mjs +473 -100
  71. package/bin/lean/lean.test.mjs +686 -33
  72. package/bin/lean/light.mjs +48 -7
  73. package/bin/lean/light.test.mjs +37 -3
  74. package/bin/lean/limits.test.mjs +142 -9
  75. package/bin/lean/mechfix.mjs +124 -0
  76. package/bin/lean/mechfix.test.mjs +75 -0
  77. package/bin/lean/orchestrate-cancel.test.mjs +143 -0
  78. package/bin/lean/orchestrate.mjs +116 -28
  79. package/bin/lean/phaseledger.mjs +47 -5
  80. package/bin/lean/phaseledger.test.mjs +30 -1
  81. package/bin/lean/postdeploy-check.test.mjs +39 -0
  82. package/bin/lean/precheck.mjs +23 -4
  83. package/bin/lean/precheck.test.mjs +14 -1
  84. package/bin/lean/prereq.mjs +28 -0
  85. package/bin/lean/prereq.test.mjs +20 -0
  86. package/bin/lean/probe.mjs +4 -2
  87. package/bin/lean/prodparity.mjs +52 -0
  88. package/bin/lean/prodparity.test.mjs +67 -0
  89. package/bin/lean/prompts.mjs +77 -19
  90. package/bin/lean/quota.mjs +39 -0
  91. package/bin/lean/recovery.test.mjs +11 -1
  92. package/bin/lean/relaxation.mjs +73 -0
  93. package/bin/lean/relaxation.test.mjs +54 -0
  94. package/bin/lean/release-io.test.mjs +42 -0
  95. package/bin/lean/release-postmerge.mjs +125 -0
  96. package/bin/lean/release-preflight.mjs +58 -0
  97. package/bin/lean/release-preflight.test.mjs +114 -0
  98. package/bin/lean/release-rehearsal.mjs +64 -0
  99. package/bin/lean/release-rehearsal.test.mjs +93 -0
  100. package/bin/lean/release-review.e2e.test.mjs +77 -0
  101. package/bin/lean/release-review.mjs +254 -0
  102. package/bin/lean/release-review.test.mjs +307 -0
  103. package/bin/lean/release-snapshot.mjs +188 -0
  104. package/bin/lean/release-snapshot.test.mjs +190 -0
  105. package/bin/lean/release.mjs +296 -0
  106. package/bin/lean/release.test.mjs +387 -0
  107. package/bin/lean/render.mjs +1 -1
  108. package/bin/lean/replan.mjs +184 -0
  109. package/bin/lean/replan.test.mjs +110 -0
  110. package/bin/lean/resume.mjs +9 -7
  111. package/bin/lean/resume.test.mjs +16 -0
  112. package/bin/lean/rotator.mjs +150 -31
  113. package/bin/lean/rotator.test.mjs +105 -2
  114. package/bin/lean/sandbox-remote.mjs +9 -2
  115. package/bin/lean/schedd.mjs +83 -5
  116. package/bin/lean/schedd.test.mjs +108 -7
  117. package/bin/lean/selfreview.mjs +94 -0
  118. package/bin/lean/selfreview.test.mjs +58 -1
  119. package/bin/lean/selftest-gate.mjs +22 -0
  120. package/bin/lean/selftest-gate.test.mjs +18 -1
  121. package/bin/lean/selftest-journey.mjs +234 -0
  122. package/bin/lean/selftest-journey.test.mjs +130 -0
  123. package/bin/lean/selftest-live.mjs +2 -1
  124. package/bin/lean/seqlease.mjs +35 -1
  125. package/bin/lean/seqlease.test.mjs +15 -0
  126. package/bin/lean/seqreserve.e2e.test.mjs +135 -0
  127. package/bin/lean/seqreserve.mjs +73 -0
  128. package/bin/lean/seqreserve.test.mjs +134 -0
  129. package/bin/lean/sequence.mjs +35 -6
  130. package/bin/lean/seqversioned.mjs +147 -0
  131. package/bin/lean/stagestamp.mjs +28 -0
  132. package/bin/lean/stagestamp.test.mjs +32 -0
  133. package/bin/lean/surfaces.mjs +75 -0
  134. package/bin/lean/surfaces.test.mjs +59 -0
  135. package/bin/lean/toolplace.mjs +28 -0
  136. package/bin/lean/toolplace.test.mjs +24 -0
  137. package/bin/lean/toolstats.mjs +3 -1
  138. package/bin/lean/toolstats.test.mjs +11 -0
  139. package/bin/lean/validatebest.mjs +28 -0
  140. package/bin/lean/validatebest.test.mjs +27 -0
  141. package/bin/lean/verifier.mjs +3 -2
  142. package/bin/lean/verify.mjs +2 -1
  143. package/bin/lean/verify.test.mjs +6 -0
  144. package/bin/pool/agent.mjs +27 -4
  145. package/bin/pool/docker.mjs +5 -0
  146. package/bin/pool/router.mjs +74 -28
  147. package/bin/prereqs.mjs +111 -0
  148. package/bin/replay-timelapse.mjs +149 -0
  149. package/bin/review-staging.mjs +123 -16
  150. package/bin/review-staging.test.mjs +18 -0
  151. package/bin/runner.mjs +43 -6
  152. package/bin/splash-install.mjs +157 -0
  153. package/bin/stats/aggregate.mjs +8 -1
  154. package/bin/stats/conformance-outcomes.mjs +289 -0
  155. package/bin/stats/conformance-outcomes.test.mjs +274 -0
  156. package/bin/stats/depth.mjs +275 -0
  157. package/bin/stats/depth.test.mjs +158 -0
  158. package/bin/stats/efficiency.mjs +26 -5
  159. package/bin/stats/efficiency.test.mjs +45 -1
  160. package/bin/stats/experiment.mjs +7 -5
  161. package/bin/stats/first-review.mjs +77 -0
  162. package/bin/stats/first-review.test.mjs +36 -0
  163. package/bin/stats/firstmerge.mjs +40 -0
  164. package/bin/stats/firstmerge.test.mjs +41 -0
  165. package/bin/stats/github-source.mjs +53 -15
  166. package/bin/stats/index.mjs +147 -9
  167. package/bin/stats/local-source.mjs +12 -0
  168. package/bin/stats/origin.mjs +80 -0
  169. package/bin/stats/origin.test.mjs +58 -0
  170. package/bin/stats/query.mjs +69 -0
  171. package/bin/stats/render.mjs +3 -1
  172. package/bin/stats/scoreboard.mjs +137 -0
  173. package/bin/stats/scoreboard.test.mjs +87 -0
  174. package/bin/stats/selffiled.mjs +52 -0
  175. package/bin/stats/selffiled.test.mjs +71 -0
  176. package/bin/stats/stats.test.mjs +80 -0
  177. package/bin/tui.mjs +3 -2
  178. package/commands/bootstrap.md +15 -14
  179. package/commands/deploy-pr.md +18 -3
  180. package/commands/forge-stats.md +1 -1
  181. package/commands/forgedock-ci-setup.md +28 -0
  182. package/commands/forgedock-init.md +4 -5
  183. package/commands/issue.md +2 -0
  184. package/commands/milestone.md +9 -1
  185. package/commands/orchestrate.md +1 -1
  186. package/commands/replay.md +2 -0
  187. package/commands/review-pr-agents/security.md +4 -0
  188. package/commands/review-pr-staging.md +6 -1
  189. package/commands/work-on/build.md +4 -6
  190. package/commands/work-on/close.md +8 -0
  191. package/docs/CONFIG.md +170 -18
  192. package/docs/ISSUE-WATCH.md +25 -0
  193. package/docs/OUTCOME-CODES.md +4 -0
  194. package/docs/REPLAY.md +9 -0
  195. package/docs/SELFTEST.md +11 -0
  196. package/docs/STATS.md +61 -0
  197. package/docs/TELEMETRY.md +1 -1
  198. package/docs/eval/README.md +6 -0
  199. package/docs/eval/adversarial-bench.md +68 -0
  200. package/docs/eval/corpus/adversarial-v1.json +285 -0
  201. package/docs/eval/feature-bench.md +42 -0
  202. package/docs/eval/feature-specs/crud-auth/journeys/notes-crud-isolated.mjs +21 -0
  203. package/docs/eval/feature-specs/crud-auth/journeys/register-login.mjs +12 -0
  204. package/docs/eval/feature-specs/crud-auth/spec.md +15 -0
  205. package/docs/site/start-a-new-project.md +2 -1
  206. package/package.json +5 -2
  207. package/plugins/forgedock-splash/.claude-plugin/plugin.json +10 -0
  208. package/plugins/forgedock-splash/README.md +27 -0
  209. package/plugins/forgedock-splash/hooks/hooks.json +1 -0
  210. package/plugins/forgedock-splash/hooks/register.tsx +74 -0
  211. package/plugins/forgedock-splash/hooks/scene.ts +222 -0
  212. package/plugins/forgedock-splash/types/index.d.ts +10 -0
  213. package/pool/README.md +1 -1
  214. package/pool/image/cs-cred +14 -1
  215. package/scripts/backfill-finding-labels.mjs +50 -0
  216. package/scripts/backfill-finding-labels.test.mjs +36 -0
  217. package/scripts/bench-adversarial.mjs +216 -0
  218. package/scripts/bench-feature.mjs +170 -0
  219. package/scripts/bench-lightlane.mjs +2 -2
  220. package/scripts/bootstrap-create.mjs +2 -2
  221. package/scripts/bootstrap-validate.mjs +35 -2
  222. package/scripts/check-spec-size.sh +4 -3
  223. package/scripts/check-spec-size.test.sh +3 -0
  224. package/scripts/doctor-pipeline-state.sh +21 -6
  225. package/scripts/file-deferred-followups.sh +59 -251
  226. package/scripts/file-deferred-followups.test.sh +85 -206
  227. package/scripts/followup-route.mjs +12 -0
  228. package/scripts/owner-route-parity.test.sh +17 -1
  229. package/scripts/plan-validate-live.mjs +40 -6
  230. package/scripts/review-pr-side-effects.test.sh +40 -0
  231. package/scripts/review-pr-staging-scope.test.sh +1 -1
  232. package/scripts/review-staging-post.sh +23 -0
  233. package/scripts/review-staging-post.test.sh +8 -0
@@ -37,6 +37,7 @@ export const OUTCOME_CODES = Object.freeze({
37
37
  BASE_CONFLICT: "base.conflict",
38
38
  RATE_LIMITED: "rate_limited",
39
39
  BACKEND_AUTH: "backend.auth", // forge#5168: the claude CLI login failed ("Failed to authenticate"); deferred under the account hold, never engine-error, never the breaker
40
+ QUOTA_EXHAUSTED: "quota.exhausted", // forge#5236: no account has capacity (every login at its ceiling); deferred until the earliest reset, never backend.auth
40
41
  HOST_BUSY: "host.busy",
41
42
  GH_UNAVAILABLE: "gh.unavailable", // forge#4157: `gh` unreachable after retries during the --repo identity check; run deferred, nothing posted
42
43
  GH_AUTH: "gh.auth", // forge#4662: gh answered HTTP 401 and one token refresh did not fix it; run deferred, a rerun resumes
@@ -47,6 +48,7 @@ export const OUTCOME_CODES = Object.freeze({
47
48
  PATH_SWITCH_CONFLICT: "path.switch_conflict",
48
49
  ENGINE_ERROR: "engine.error",
49
50
  ENGINE_DCO_REWRITE: "engine.dco_rewrite", // forge#4997: the DCO sign-off rewrite of unpushed commits failed (git filter-branch); mechanical engine-error (not needs-human), relaunched by the batch runner
51
+ ENGINE_PUSH_DIVERGED: "engine.push_diverged", // forge#5202: the lane-branch push was rejected non-fast-forward, no other lane owns the branch, and the divergence is not the lane's own reconcilable checkpoints; mechanical engine-error (not needs-human), relaunched by the batch runner
50
52
  ENGINE_VALIDATE_RESULT_LOST: "engine.validate_result_lost", // forge#4708: a validate result recorded before a CI fix round is missing after it and could not be carried forward
51
53
  INFRA_DISK_QUOTA: "infra.disk_quota",
52
54
  INFRA_CLI_SPAWN_TRANSIENT: "infra.cli_spawn_transient",
@@ -59,12 +61,14 @@ export const OUTCOME_CODES = Object.freeze({
59
61
  ENV_LANE_LIMIT: "env.lane_limit", // forge#4690: the lane hit its own scope limit (TasksMax or MemoryMax) and was stopped; an environment error, never an engine-error, so the breaker ignores it
60
62
  ENV_CAPABILITY_REMOTE: "env.capability_remote", // forge#4542: a remote sandbox lane blocked only on a host-only capability (SOPS key, ops credentials, prod monitor SSH) the dispatching host has; recovered locally
61
63
  SANDBOX_START_FAILED: "sandbox.start_failed", // forge#4254: a lane sandbox could not start (a non-auth 4xx/config error or a non-HTTP start failure); needs-human, not relaunched
64
+ BASE_RED: "base.red", // forge#5239: a verify.invariants guard fails on the base too; the lane is deferred behind the introducing issue, never needs-human
62
65
  SANDBOX_CAPACITY: "sandbox.capacity", // forge#4254: the sandbox provider had no capacity; deferred with backoff
63
66
  SANDBOX_TRANSIENT: "sandbox.transient", // forge#5095: the sandbox provider answered a 5xx on launch (router/agent infrastructure); deferred with backoff, capped by max_deferrals, never needs-human
64
67
  SANDBOX_AUTH: "sandbox.auth", // forge#4685: the sandbox provider refused or lacked the credential (HTTP 401/403, no token); deferred, never needs-human
65
68
  SANDBOX_UNREACHABLE: "sandbox.unreachable", // forge#4672: the sandbox provider stayed unreachable past execution.unreachable_window_min; deferred, the sandbox is kept for adopt
66
69
  LEASE_HELD: "lease.held",
67
70
  DEPENDENCY_OPEN: "dependency.open",
71
+ DESIGN_INVALIDATED: "design.invalidated", // forge#5342: a lane found the plan wrong; one spike amendment filed, siblings held; the rework-share rollup counts it
68
72
  DEPENDENCY_UNREADABLE: "dependency.unreadable",
69
73
  DEPENDENCY_BLOCKED: "dependency.blocked",
70
74
  // Lane resolution refusals (#4125): before any lease, comment or worktree; terminal reason `lane-refused`.
@@ -197,12 +201,14 @@ export function codeForTerminalReason(reason) {
197
201
 
198
202
  /** forge#4906: a validate command timed out (exit 124) on the engine's rerun: infrastructure, not an unimplemented contract item. Kept outside OUTCOME_CODES (the base enum guard lists that enum); recoverable and mechanical like the other env codes. */
199
203
  export const ENV_VALIDATE_TIMEOUT = "env.validate_timeout";
204
+ /** forge#5371: a remote-placed lane's frozen validate failed in the sandbox; the host reruns it in a local recovery lane (a pass there is the change, a fail stays conformance.unimplemented). Outside OUTCOME_CODES like ENV_VALIDATE_TIMEOUT. */
205
+ export const ENV_VALIDATE_PLACEMENT = "env.validate_placement";
200
206
 
201
207
  /**
202
208
  * Batch recovery classes of a lane result (forge#4267). The batch runner recovers `recoverable` rows once
203
209
  * (`orchestration.recovery.max_attempts`) and re-queues them; only `human` rows are escalations.
204
210
  */
205
- export const RECOVERABLE_CODES = Object.freeze([OUTCOME_CODES.CI_RED, OUTCOME_CODES.BASE_CONFLICT, OUTCOME_CODES.BUILDER_BLOCK_UNTYPED, OUTCOME_CODES.CONTRACT_INVALID, OUTCOME_CODES.CONTRACT_INVALID_COMMAND, OUTCOME_CODES.ENV_TOOL_MISSING, OUTCOME_CODES.ENV_REPRO_UNRUNNABLE, ENV_VALIDATE_TIMEOUT, OUTCOME_CODES.ENV_CAPABILITY_REMOTE, OUTCOME_CODES.BUDGET_EXCEEDED, OUTCOME_CODES.CONFORMANCE_UNIMPLEMENTED, OUTCOME_CODES.CONFORMANCE_OMISSION, OUTCOME_CODES.CONFORMANCE_UNJUSTIFIED_DEFERRAL]);
211
+ export const RECOVERABLE_CODES = Object.freeze([OUTCOME_CODES.CI_RED, OUTCOME_CODES.BASE_CONFLICT, OUTCOME_CODES.BUILDER_BLOCK_UNTYPED, OUTCOME_CODES.CONTRACT_INVALID, OUTCOME_CODES.CONTRACT_INVALID_COMMAND, OUTCOME_CODES.ENV_TOOL_MISSING, OUTCOME_CODES.ENV_REPRO_UNRUNNABLE, ENV_VALIDATE_TIMEOUT, ENV_VALIDATE_PLACEMENT, OUTCOME_CODES.ENV_CAPABILITY_REMOTE, OUTCOME_CODES.BUDGET_EXCEEDED, OUTCOME_CODES.CONFORMANCE_UNIMPLEMENTED, OUTCOME_CODES.CONFORMANCE_OMISSION, OUTCOME_CODES.CONFORMANCE_UNJUSTIFIED_DEFERRAL]);
206
212
  /** `builder.blocked` is only reached by a typed human block: credentials, spend, promotion, customer, product-decision. */
207
213
  export const HUMAN_CODES = Object.freeze([OUTCOME_CODES.BUILDER_BLOCKED]);
208
214
 
@@ -234,7 +240,7 @@ function classifyNeedsHumanBase(row) {
234
240
  }
235
241
 
236
242
  /** forge#4725: mechanical/environment codes recover on their own budget (`recovery.mechanicalMaxAttempts`), apart from conformance failures. */
237
- export const MECHANICAL_CODES = Object.freeze([OUTCOME_CODES.BASE_CONFLICT, OUTCOME_CODES.CONTRACT_INVALID_COMMAND, OUTCOME_CODES.ENV_TOOL_MISSING, OUTCOME_CODES.ENV_REPRO_UNRUNNABLE, ENV_VALIDATE_TIMEOUT, OUTCOME_CODES.ENV_CAPABILITY_REMOTE]);
243
+ export const MECHANICAL_CODES = Object.freeze([OUTCOME_CODES.BASE_CONFLICT, OUTCOME_CODES.CONTRACT_INVALID_COMMAND, OUTCOME_CODES.ENV_TOOL_MISSING, OUTCOME_CODES.ENV_REPRO_UNRUNNABLE, ENV_VALIDATE_TIMEOUT, ENV_VALIDATE_PLACEMENT, OUTCOME_CODES.ENV_CAPABILITY_REMOTE]);
238
244
 
239
245
  /** `mechanical` | `conformance`: the recovery budget class of a lane result row (a conflicting `ci-pending` is a base conflict). */
240
246
  export function recoveryClassOf(row) {
@@ -243,7 +249,7 @@ export function recoveryClassOf(row) {
243
249
 
244
250
  /** The code a recovery lane works on: a conflicting `ci-pending` is recovered as a base conflict. */
245
251
  export function recoveryCodeOf(row) {
246
- return (row?.outcome ?? row?.terminalReason) === "ci-pending" ? OUTCOME_CODES.BASE_CONFLICT : normalizeCode(row?.code);
252
+ return (row?.outcome ?? row?.terminalReason) === "ci-pending" ? OUTCOME_CODES.BASE_CONFLICT : row?.code === ENV_VALIDATE_PLACEMENT ? ENV_VALIDATE_PLACEMENT : normalizeCode(row?.code); // #5371: kept outside OUTCOME_CODES, so normalizeCode alone would drop it
247
253
  }
248
254
 
249
255
  /** forge#4656: the label of a human-owned wait (an owner and an unblock condition are required in its comment). */
@@ -37,6 +37,14 @@ const prOf = (rec) => (Number.isSafeInteger(rec.pr) && rec.pr > 0 ? { pr: rec.pr
37
37
  /** "a:b,c:d" from [{from,to}] (forge#4165); undefined for a non-array so compact() drops it. An empty list is "". */
38
38
  const pairs = (v) => (Array.isArray(v) ? v.map((e) => `${e?.from}:${e?.to}`).join(",") : undefined);
39
39
  const nonEmpty = (v) => (v === "" ? "none" : v);
40
+ /** forge#5206: an experiment arm's applied overrides (`k=v,...`); "" (none applied) is "none" so compact() keeps it. */
41
+ const armOv = (v) => (typeof v === "string" ? nonEmpty(v) : undefined);
42
+ /** #5345: lean's first-round review record flattened to scalars (`fr_*`); `stats --first-review` rebuilds it. Lists are comma-joined. */
43
+ function firstReviewFlat(f) {
44
+ if (!f || typeof f !== "object") return {};
45
+ const list = (v) => (Array.isArray(v) ? nonEmpty(v.join(",").slice(0, 200)) : undefined), bit = (v) => (typeof v === "boolean" ? Number(v) : undefined);
46
+ return { fr_state: nonEmpty(f.state), fr_kinds: list(f.kinds) ?? "none", fr_rounds: f.rounds, fr_clean: bit(f.clean), fr_incomplete: bit(f.incomplete), fr_type: nonEmpty(f.type), fr_surfaces: list(f.surfaces) ?? "none" };
47
+ }
40
48
  /** Lean's forge#4165 extras of a STRUCTURE_DELTA record; {} for the implement-time counts-only shape. */
41
49
  function structureLists(rec) {
42
50
  if (!Array.isArray(rec.decisions) && !Array.isArray(rec.new_edges) && !Array.isArray(rec.deps_added)) return {};
@@ -61,15 +69,15 @@ export function mapRecord(rec, wallMs) {
61
69
  cost_usd_session: Number.isFinite(rec.cost_usd_session) ? Math.round(rec.cost_usd_session * 1e6) / 1e6 : undefined,
62
70
  input_tokens: tok(rec.usage, "input_tokens"), output_tokens: tok(rec.usage, "output_tokens"),
63
71
  cache_read_tokens: tok(rec.usage, "cache_read_input_tokens"), cache_creation_tokens: tok(rec.usage, "cache_creation_input_tokens"),
64
- baseline_tokens: rec.baseline_tokens, lane_profile: rec.lane_profile, experiment: rec.experiment, arm: rec.arm, // #4629
72
+ baseline_tokens: rec.baseline_tokens, lane_profile: rec.lane_profile, experiment: rec.experiment, arm: rec.arm, arm_overrides: armOv(rec.arm_overrides), // #4629, #5206
65
73
  }) };
66
74
  }
67
75
  if (rec.event === "RUN_TERMINAL") {
68
76
  return { event: "run_terminal", phase: null, ...prOf(rec), payload: compact({ reason: rec.reason, code: rec.code, wall_ms: wallMs, guard_added_ms: rec.guard_added_ms, // #4705
69
- milestone: rec.milestone, conformance_mode: rec.conformance_mode, shadow_would: rec.shadow_would,
77
+ milestone: rec.milestone, verified: typeof rec.verified === "boolean" ? Number(rec.verified) : undefined, conformance_mode: rec.conformance_mode, shadow_would: rec.shadow_would,
70
78
  builder_tier: rec.builder_tier, builder_class: rec.builder_class, builder_model: rec.builder_model, // #4394: the model per merge
71
79
  builder_escalated: typeof rec.builder_escalated === "boolean" ? Number(rec.builder_escalated) : undefined,
72
- experiment: rec.experiment, arm: rec.arm }) }; // #4629
80
+ experiment: rec.experiment, arm: rec.arm, arm_overrides: armOv(rec.arm_overrides), ...firstReviewFlat(rec.first_review) }) }; // #4629, #5206, #5345
73
81
  }
74
82
  if (rec.event === "SANDBOX_USAGE") {
75
83
  return { event: "sandbox_usage", phase: null, payload: compact({ provider: rec.provider, sandbox_id: rec.sandbox_id, minutes: rec.minutes,
@@ -67,6 +67,11 @@ describe("engine telemetry seam", () => {
67
67
  assert.deepEqual(calls[0][1], { reason: "needs-human", code: "review.escalated", wall_ms: 60000 });
68
68
  assert.equal(calls[0][2].phase, undefined);
69
69
  });
70
+ it("#5339: RUN_TERMINAL carries verified as 0/1, omitted when absent", () => {
71
+ assert.equal(mapRecord({ event: "RUN_TERMINAL", reason: "merged", verified: false, issue: 7 }, 10).payload.verified, 0);
72
+ assert.equal(mapRecord({ event: "RUN_TERMINAL", reason: "merged", verified: true, issue: 7 }, 10).payload.verified, 1);
73
+ assert.equal("verified" in mapRecord({ event: "RUN_TERMINAL", reason: "merged", issue: 7 }, 10).payload, false);
74
+ });
70
75
  it("maps STRUCTURE_DELTA (forge#4159) to structure_delta with scalar counts and 0/1 flags", () => {
71
76
  const m = mapRecord({ event: "STRUCTURE_DELTA", issue: 7, edges_added: 1, edges_removed: 0, import_files_added: 8, import_files_removed: 2, boundary_changed: true, boundary_loosened: false }, 10);
72
77
  assert.deepEqual(m, { event: "structure_delta", phase: "implement", payload: { edges_added: 1, edges_removed: 0, import_files_added: 8, import_files_removed: 2, boundary_changed: 1, boundary_loosened: 0 } });
@@ -121,3 +126,15 @@ describe("engine telemetry seam", () => {
121
126
  assert.equal(some.calls[0][2].repo, "a/b");
122
127
  });
123
128
  });
129
+
130
+ describe("first_review on run_terminal (#5345)", () => {
131
+ it("is flattened to scalar fr_* fields and read back by stats --first-review", async () => {
132
+ const { firstReviewLanes } = await import("../stats/first-review.mjs");
133
+ const first_review = { state: "fail", kinds: ["conformance.omission", "conformance.scope_creep"], rounds: 2, clean: false, incomplete: false, type: "bug", surfaces: ["auth"] };
134
+ const { payload } = mapRecord({ event: "RUN_TERMINAL", reason: "merged", code: 0, first_review }, 0);
135
+ assert.equal("first_review" in payload, false);
136
+ assert.deepEqual([payload.fr_state, payload.fr_kinds, payload.fr_rounds, payload.fr_clean, payload.fr_surfaces], ["fail", "conformance.omission,conformance.scope_creep", 2, 0, "auth"]);
137
+ const [lane] = firstReviewLanes([{ event: "run_terminal", issue: 7, ts: "2026-01-01", repo: "o/r", reason: "merged", ...payload }]);
138
+ assert.deepEqual([lane.clean, lane.rounds, lane.kinds, lane.surfaces, lane.type], [false, 2, first_review.kinds, ["auth"], "bug"]);
139
+ });
140
+ });
@@ -4,6 +4,7 @@
4
4
  * `forgedock resume-stalled [--dry-run] [--lane <lane>]` enumerates all in-flight
5
5
  * issues, calls scanStalls, and re-dispatches each stalled issue via run-issue.
6
6
  */
7
+ import { validateForgeYaml, formatFinding } from "./config-schema.mjs";
7
8
  import { execFile, spawn } from "node:child_process";
8
9
  import { promisify } from "node:util";
9
10
  import { readdirSync, statSync, readFileSync } from "node:fs";
@@ -13,7 +14,7 @@ import { localLaneCap } from "./lean/admission.mjs";
13
14
  import { memAvailableMb } from "./lean/heavy.mjs";
14
15
  import { liveOverload, formatOverload, formatHostLoad } from "./lean/hostload.mjs";
15
16
  import { join, resolve as resolvePath } from "node:path";
16
- import { runIssue, DEFAULT_MAX_ATTEMPTS, sanitizeLeaseHost } from "./engine.mjs";
17
+ import { runIssue, DEFAULT_MAX_ATTEMPTS, sanitizeLeaseHost, ENGINE_VERSION } from "./engine.mjs";
17
18
  import { makeProjector } from "./engine/projector.mjs";
18
19
  import { decomposedSubissues, isDecomposedRecord, isTrustedActor, parseDependsOn } from "./engine/phases.mjs";
19
20
  import { readLog, readLogFile, deriveState, runLogPath, migrateRunLogs } from "./engine/runlog.mjs";
@@ -24,17 +25,20 @@ import { makeEventEmitter, probeSweepEvents, experimentEvent } from "./engine/ev
24
25
  import { readExperiment } from "./experiment.mjs";
25
26
  import { readBranches, resolveLane, isDefaultLane, makeLaneCache } from "./lean/lane.mjs";
26
27
  import { parseVerify } from "./lean/verify.mjs";
28
+ import { coerceVerify as coerceCiVerify, budgetReportLine, recordHostCheck } from "./lean/ci-budget.mjs";
27
29
  import { normalizeKindModes } from "./lean/conformance.mjs";
28
30
  import { parseEnforceDomains } from "./lean/review-trigger.mjs";
29
31
  import { viewIssue } from "./lean/gh-assoc.mjs";
30
- import { otherLaneOwner } from "./lean/lanelock.mjs";
32
+ import { otherLaneOwner, clearLease } from "./lean/lanelock.mjs";
31
33
  import { parseExecution, detectNeeds, placementText } from "./lean/execution.mjs";
32
- import { openRotator } from "./lean/rotator.mjs";
34
+ import { openRotator, rotatorKind } from "./lean/rotator.mjs";
33
35
  import { relayPrefetchCommands } from "./lean/relay.mjs";
36
+ import { parseCeilingBySize } from "./lean/ceiling.mjs";
34
37
  import { parseTurnBudgets, formatTurnSummary, TURN_BUDGET_DEFAULTS } from "./lean/budget.mjs";
35
38
  import { writeAtomic as writeResultAtomic } from "./lean/batch.mjs";
36
39
  import { parseLightConfig, LIGHT_DEFAULTS } from "./lean/light.mjs";
37
40
  import { OUTCOME_CODES } from "./engine/outcome-codes.mjs";
41
+ import { USER_ERRORS } from "./help-text.mjs";
38
42
  import * as batchHealth from "./lean/batch-health.mjs";
39
43
  import * as _autoChildren from "./lean/autochildren.mjs";
40
44
 
@@ -290,6 +294,18 @@ export function readBaseMerge(cwd = process.cwd()) {
290
294
  export function readSequenceRegenerate(cwd = process.cwd()) {
291
295
  try { const l = parseForgeYaml(readFileSync(join(cwd, "forge.yaml"), "utf8"))?.lean ?? {}; return String(l.sequence_regenerate ?? l.regenerate ?? "").trim() || undefined; } catch { return undefined; }
292
296
  }
297
+ /**
298
+ * forge.yaml `lean.sequence.versioned` (#5235): versioned-dir sequence classes, `<dir>/v{N} -> companion[, companion]; ...`
299
+ * (`path` or `path=template` companions). The one-level parser flattens the block to `lean.versioned`; flat
300
+ * `lean.sequence_versioned` also works and wins. undefined when absent or unreadable.
301
+ */
302
+ export function readSequenceVersioned(cwd = process.cwd()) {
303
+ try { const l = parseForgeYaml(readFileSync(join(cwd, "forge.yaml"), "utf8"))?.lean ?? {}; return String(l.sequence_versioned ?? l.versioned ?? "").trim() || undefined; } catch { return undefined; }
304
+ }
305
+ /** #5340: forge.yaml `engine.shared_surfaces` (comma scalar or block list of globs, `glob => command` = generated registry), or undefined. */
306
+ export function readSharedSurfaces(cwd = process.cwd()) {
307
+ try { const v = parseForgeYaml(readFileSync(join(cwd, "forge.yaml"), "utf8"))?.engine?.shared_surfaces; const out = Array.isArray(v) ? v.map(String) : typeof v === "string" && v.trim() ? [v.trim()] : []; return out.length ? out : undefined; } catch { return undefined; }
308
+ }
293
309
  /** #4664: forge.yaml `followups.default_milestone` (milestone title for deferred follow-ups whose parent's milestone has shipped), or undefined. */
294
310
  export function readFollowupsDefaultMilestone(cwd = process.cwd()) {
295
311
  try { return String(parseForgeYaml(readFileSync(join(cwd, "forge.yaml"), "utf8"))?.followups?.default_milestone ?? "").trim() || undefined; } catch { return undefined; }
@@ -389,6 +405,7 @@ export function readHeavy(cwd = process.cwd()) {
389
405
  * `lane_limits_memory_max`/`lane_limits_cpu_quota`), plus `tasks_max` (#4690, default 1024). `engine.cli_idle_minutes` (default 15) and `engine.cli_max_minutes` (default 180).
390
406
  * `engine.cli_busy_minutes` (default 45, #4405): extra silence allowed while the builder has a live heavy step or heavy-queue entry.
391
407
  * #4390: `engine.context_ceiling_tokens` (default 120000 in runCore; 0 = off).
408
+ * #5346: `engine.context_ceiling_by_size` ("S=..,M=..,L=.."; a size without an entry uses context_ceiling_tokens).
392
409
  * #4392: `engine.turn_budget_s|m|l` (implement turn budget per lane size; defaults 25/60/100, always returned; 0 = off).
393
410
  */
394
411
  export function readCoreLimits(cwd = process.cwd()) {
@@ -404,6 +421,7 @@ export function readCoreLimits(cwd = process.cwd()) {
404
421
  ...(posNum(y.engine?.cli_max_minutes) ? { cliMaxMinutes: posNum(y.engine.cli_max_minutes) } : {}),
405
422
  ...(posNum(y.engine?.cli_busy_minutes) ? { cliBusyMinutes: posNum(y.engine.cli_busy_minutes) } : {}),
406
423
  ...(/^\d+$/.test(String(y.engine?.context_ceiling_tokens ?? "").trim()) ? { contextCeilingTokens: Number(y.engine.context_ceiling_tokens) } : {}),
424
+ ...(parseCeilingBySize(y.engine) ? { contextCeilingBySize: parseCeilingBySize(y.engine) } : {}), // #5346
407
425
  turnBudgets: parseTurnBudgets(y.engine) ?? { ...TURN_BUDGET_DEFAULTS }, // #4392: lanes are budgeted by default
408
426
  };
409
427
  } catch { return { laneLimits: {}, turnBudgets: { ...TURN_BUDGET_DEFAULTS } }; }
@@ -418,14 +436,14 @@ export function readMergeWait(cwd = process.cwd()) {
418
436
  /**
419
437
  * forge.yaml `verify:` section (#4167, block style: `verify:` then ` mode: ci`, ` workflow: verify.yml`, ` paths_input`,
420
438
  * ` skip_paths` comma-separated, ` max_rounds`, ` check_run: true` (#4270)) for the core path; undefined when the
421
- * section is absent or unreadable.
439
+ * section is absent or unreadable. ` guard_block: false` (#5239) lets verify.invariants fail without blocking the merge.
422
440
  */
423
441
  export function readVerify(cwd = process.cwd()) {
424
442
  try {
425
443
  const sec = parseForgeYaml(readFileSync(join(cwd, "forge.yaml"), "utf8"))?.verify;
426
444
  if (!sec || typeof sec !== "object") return undefined;
427
445
  const invariants = readInvariants(cwd), flaky = readYamlList(cwd, "verify", "flaky"), guard_command = readYamlMap(cwd, "verify", "guard_command");
428
- return parseVerify({ ...sec, ...(invariants ? { invariants } : {}), ...(flaky ? { flaky } : {}), ...(guard_command ? { guard_command } : {}) });
446
+ return coerceCiVerify(parseVerify({ ...sec, ...(invariants ? { invariants } : {}), ...(flaky ? { flaky } : {}), ...(guard_command ? { guard_command } : {}) }), { cwd }); // #5278: local-first never pushes for paid CI before review
429
447
  } catch { return undefined; }
430
448
  }
431
449
  /** #4542: forge.yaml `execution.host_capabilities` (+ patterns) for a lane's remote-block mapping; undefined when none are declared. */
@@ -543,11 +561,12 @@ export function readEnvConfig(cwd = process.cwd()) {
543
561
  const rm = readYamlMap(cwd, "validate", "recipes"); // #5020: y?.validate?.recipes, a block map {match regex: replacement} applied to frozen validate and repro commands
544
562
  const recipes = Object.entries(rm ?? {}).map(([match, replace]) => ({ match, replace }));
545
563
  const cf = readYamlMap(cwd, "verification", "coupled_files"); // #5079: {when glob: required glob[, glob]}
564
+ const pp = readYamlMap(cwd, "topology", "prod_parity"); // #5284: {path glob: command | "note: how to verify"} production-only facts
546
565
  const s = (v) => (typeof v === "string" && v.trim() ? v.trim() : undefined);
547
566
  const rr = s(y?.topology?.route_reachability); // #5087: repo-supplied command: exits non-zero when the ingress does not deliver the added route paths (args) to their service
548
567
  const kb = typeof e.sparse_max_kb === "string" && /^\d+$/.test(e.sparse_max_kb.trim()) ? Number(e.sparse_max_kb) : e.sparse_max_kb;
549
568
  return { ...(s(e.toolchain) ? { toolchainOverride: s(e.toolchain) } : {}), ...(s(e.setup) ? { envSetup: s(e.setup) } : {}),
550
- ...(Number.isInteger(kb) && kb >= 0 ? { sparseMaxKb: kb } : {}), ...(Object.keys(runners).length ? { testRunners: runners } : {}), ...(recipes.length ? { validateRecipes: recipes } : {}), ...(cf && Object.keys(cf).length ? { coupledFiles: cf } : {}), ...(rr ? { routeReachability: rr } : {}) };
569
+ ...(Number.isInteger(kb) && kb >= 0 ? { sparseMaxKb: kb } : {}), ...(Object.keys(runners).length ? { testRunners: runners } : {}), ...(recipes.length ? { validateRecipes: recipes } : {}), ...(cf && Object.keys(cf).length ? { coupledFiles: cf } : {}), ...(rr ? { routeReachability: rr } : {}), ...(pp && Object.keys(pp).length ? { prodParity: pp } : {}) };
551
570
  } catch { return {}; }
552
571
  }
553
572
  export const ENGINE_PATHS = ["core", "full", "lean", "auto"];
@@ -915,12 +934,12 @@ export async function runFromCli(argv, deps = {}) {
915
934
  if (pathFlag && !ENGINE_PATHS.includes(pathFlag)) throw new Error(`--path must be one of ${ENGINE_PATHS.join("|")}`);
916
935
  const enginePath = pathFlag ?? readEnginePath() ?? "core";
917
936
  if (enginePath !== "full" && (retry || waitLease)) {
918
- throw new Error("--retry and --wait-lease are not supported with the core path (a rerun resumes from the open PR or remote branch automatically); use --path full for them");
937
+ throw new Error(USER_ERRORS.retryUnsupported);
919
938
  }
920
939
  // The full path takes the lane as given (its spec runs classify-lane), so it must be explicit; no default.
921
- if (enginePath === "full" && !lane) throw new Error("--lane is required with --path full: staging or milestone/<slug>. No default to prevent accidental production targeting.");
940
+ if (enginePath === "full" && !lane) throw new Error(USER_ERRORS.laneRequired);
922
941
  // #4298: recovery lanes (#4267) exist only on the core path; the legacy full path would silently ignore --recover.
923
- if (enginePath === "full" && argv.includes("--recover")) throw new Error("--recover is not supported with --path full (recovery lanes run on the core path only)");
942
+ if (enginePath === "full" && argv.includes("--recover")) throw new Error(USER_ERRORS.recoverUnsupported);
924
943
  const io = deps.io ?? makeIo();
925
944
  const resultFile = flag(argv, "--result-file");
926
945
  // #4256: where the dispatcher placed this lane (hybrid execution), recorded in the lane's FORGE:STATE.
@@ -975,7 +994,7 @@ export async function runFromCli(argv, deps = {}) {
975
994
  if (enginePath !== "full") {
976
995
  // Core work-on (lean): one builder session, one reviewer, GitHub as the register.
977
996
  const leanRepo = logRepo;
978
- if (!leanRepo) throw new Error("core path needs the repo: pass --repo or run inside a checkout with a GitHub remote");
997
+ if (!leanRepo) throw new Error(USER_ERRORS.noRepo);
979
998
  const { runCore } = deps.leanModule ?? (await import("./lean/lean.mjs"));
980
999
  const leanIo = deps.leanIo ?? (await import("./lean/effects.mjs")).makeLeanIo({ repo: leanRepo });
981
1000
  // #4121: a batch lane reports its result through --result-file (written atomically, also for a thrown run).
@@ -998,10 +1017,10 @@ export async function runFromCli(argv, deps = {}) {
998
1017
  let lres;
999
1018
  try {
1000
1019
  lres = await runCore({ issue, repo: leanRepo, ...(lane ? { lane } : {}), laneOverride, branches: readBranches(), cwd: process.cwd(), dir, io: leanIo, path: enginePath, onProgress,
1001
- ...(readExecution(process.cwd())?.accountRotator ? { accountRotator: readExecution(process.cwd()).accountRotator } : {}), // #5094
1020
+ ...(rotatorKind({ execution: readExecution(process.cwd()), env }) ? { accountRotator: rotatorKind({ execution: readExecution(process.cwd()), env }) } : {}), // #5094, #5205: detected
1002
1021
  onTeardown: (fn) => { teardown = fn; }, ...(env.FORGEDOCK_BATCH_ID ? { batchId: env.FORGEDOCK_BATCH_ID } : {}), ...(placement ? { placement } : {}), ...(recover ? { recover } : {}),
1003
1022
  emitTelemetry: deps.emitTelemetry ?? composeEmit(makeEmitTelemetry({ repo: leanRepo }), makeEventEmitter({ repo: leanRepo, config: readEvents() }).emit),
1004
- admission: readAdmission(), heavy: readHeavy(), ...readCoreLimits(), ...readEnvConfig(), ...(readMergeWait() ? { mergeWait: readMergeWait() } : {}), ...(readConformanceMode() ? { conformance: readConformanceMode() } : {}), ...(readConformanceKinds() ? { conformanceKinds: readConformanceKinds() } : {}), ...(readConformanceMutation() ? { conformanceMutation: "report" } : {}), ...(readContextPack() ? { contextPack: readContextPack() } : {}), ...(readReviewIncomplete() ? { reviewIncomplete: readReviewIncomplete() } : {}), ...(readLaneInstructions() ? { laneInstructions: readLaneInstructions() } : {}), ...(readReproTest() ? { reproTest: readReproTest() } : {}), ...(readExplore() ? { explore: readExplore() } : {}), ...(readExperiment() ? { experiment: readExperiment() } : {}), light: readLight(), ...(readCloseParent() ? { closeParent: true } : {}), ...(readReviewTrigger() ? { reviewTrigger: readReviewTrigger() } : {}), ...(readVerify() ? { verify: readVerify() } : {}), ...readPrecheckOptions(), ...(model ? { builderModel: model } : {}), ...(readLeanSetting("reviewer_model") ? { reviewerModel: readLeanSetting("reviewer_model") } : {}), ...(readFixModel() ? { fixModel: readFixModel() } : {}), ...(readBuilderRouting() ? { builderRouting: readBuilderRouting() } : {}), ...(readVerifier() ? { verifier: readVerifier() } : {}), ...(readHostCaps() ? { hostCaps: readHostCaps() } : {}), ...readRelayCaps(), ...(readSequenceRegenerate() ? { sequenceRegenerate: readSequenceRegenerate() } : {}), ...(readBaseMerge() ? { baseMerge: readBaseMerge() } : {}), ...(readFollowupsDefaultMilestone() ? { followupsDefaultMilestone: readFollowupsDefaultMilestone() } : {}), ...(readFollowupsRollupLabel() ? { followupsRollupLabel: readFollowupsRollupLabel() } : {}) });
1023
+ admission: readAdmission(), heavy: readHeavy(), ...readCoreLimits(), ...readEnvConfig(), ...(readMergeWait() ? { mergeWait: readMergeWait() } : {}), ...(readConformanceMode() ? { conformance: readConformanceMode() } : {}), ...(readConformanceKinds() ? { conformanceKinds: readConformanceKinds() } : {}), ...(readConformanceMutation() ? { conformanceMutation: "report" } : {}), ...(readContextPack() ? { contextPack: readContextPack() } : {}), ...(readSequenceVersioned() ? { sequenceVersioned: readSequenceVersioned() } : {}), ...(readSharedSurfaces() ? { sharedSurfaces: readSharedSurfaces() } : {}), ...(readReviewIncomplete() ? { reviewIncomplete: readReviewIncomplete() } : {}), ...(readLaneInstructions() ? { laneInstructions: readLaneInstructions() } : {}), ...(readReproTest() ? { reproTest: readReproTest() } : {}), ...(readExplore() ? { explore: readExplore() } : {}), ...(readExperiment() ? { experiment: readExperiment() } : {}), light: readLight(), ...(readCloseParent() ? { closeParent: true } : {}), ...(readReviewTrigger() ? { reviewTrigger: readReviewTrigger() } : {}), ...(readVerify() ? { verify: readVerify() } : {}), ...readPrecheckOptions(), ...(model ? { builderModel: model } : {}), ...(readLeanSetting("reviewer_model") ? { reviewerModel: readLeanSetting("reviewer_model") } : {}), ...(readFixModel() ? { fixModel: readFixModel() } : {}), ...(readBuilderRouting() ? { builderRouting: readBuilderRouting() } : {}), ...(readVerifier() ? { verifier: readVerifier() } : {}), ...(readHostCaps() ? { hostCaps: readHostCaps() } : {}), ...readRelayCaps(), ...(readSequenceRegenerate() ? { sequenceRegenerate: readSequenceRegenerate() } : {}), ...(readBaseMerge() ? { baseMerge: readBaseMerge() } : {}), ...(readFollowupsDefaultMilestone() ? { followupsDefaultMilestone: readFollowupsDefaultMilestone() } : {}), ...(readFollowupsRollupLabel() ? { followupsRollupLabel: readFollowupsRollupLabel() } : {}) });
1005
1024
  } catch (e) { if (!interrupted) report({ terminalReason: "engine-error", detail: String(e?.message ?? e).slice(0, 500) }); throw e; }
1006
1025
  finally { if (!interrupted) for (const [sig, f] of Object.entries(handlers)) off(sig, f); }
1007
1026
  if (interrupted) return lres; // the signal handler reported and exits
@@ -1201,6 +1220,7 @@ function flag(argv, name) { const i = argv.indexOf(name); return i >= 0 ? argv[i
1201
1220
  * `--add <id> N...` (#4408) adds issues to that batch instead of starting a second one: they run under its K and DAG
1202
1221
  * (a running batch picks them up on its next pass, a stopped one on its next `--resume`); `--resume <id> N...` adds N too.
1203
1222
  * `--requeue <id> N... [--reason]` (#4550) returns a terminal issue (and the dependents skipped behind it) to pending after an operator decision.
1223
+ * #5203: it also releases a quota-paused pending issue (`paused (quota) until <ISO>`): its notBefore and the pool hold are cleared.
1204
1224
  * `--cancel <id>` (#4376) stops that one batch, never the shared daemon: it admits nothing more, its running local lanes get
1205
1225
  * SIGTERM (their teardown saves the work), remote lanes run to their result and the rest end `held`; `--resume <id>` continues it.
1206
1226
  */
@@ -1306,10 +1326,15 @@ async function addedEdges({ added, records, io, repo }) {
1306
1326
  */
1307
1327
  /** #5000: what happened to the batch after an add/requeue; never implies a run when no daemon hosts it. */
1308
1328
  const hostedLine = (id, res) => res.reopened ? `batch ${id}: finished batch reopened and hosted by the schedd`
1309
- : res.hosted ? `batch ${id}: hosted by the schedd; the runner picks it up on its next pass`
1329
+ : res.hosted ? `batch ${id}: hosted by the schedd; the runner picks it up on its next pass (within ~5s while lanes run; if it is finishing, the schedd re-hosts the batch)`
1310
1330
  : `batch ${id}: queued but NOT hosted (no schedd hosts it); run: forgedock orchestrate --resume ${id}`;
1311
1331
 
1312
- async function addToBatch({ id, tokens, root, io, viaDaemon = null, print = (l) => console.log(l) }) {
1332
+ /** #5314: `--add`/`--requeue` never exit 0 with nothing scheduled: no runner hosts the batch and none was started → a non-zero exit with the reason. */
1333
+ const unhostedFailure = (id, res, requireHost, result) => {
1334
+ if (requireHost && !res.hosted && !res.reopened) throw Object.assign(new Error(`batch ${id}: the issues are queued in the batch but NOTHING is scheduled: no schedd hosts it. Start the runner: forgedock orchestrate --resume ${id}`), { code: "batch.not-hosted", result });
1335
+ };
1336
+
1337
+ async function addToBatch({ id, tokens, root, io, viaDaemon = null, requireHost = false, print = (l) => console.log(l) }) {
1313
1338
  const batchMod = await import("./lean/batch.mjs");
1314
1339
  const b = batchMod.openBatch(root, id);
1315
1340
  if (!b.exists()) throw new Error(`no batch ${id} in ${root}`);
@@ -1342,6 +1367,7 @@ async function addToBatch({ id, tokens, root, io, viaDaemon = null, print = (l)
1342
1367
  print(`batch ${id}: added ${out.added.map((n) => `#${n}`).join(" ") || (out.requeued.length ? "" : "(none)")}${out.requeued.length ? `${out.added.length ? " " : ""}${out.requeued.map((n) => `requeued #${n}`).join(" ")}` : ""}${out.skipped.length ? `; skipped ${out.skipped.map((x) => `${/^\d+$/.test(String(x.issue)) ? "#" : ""}${x.issue} (${x.reason})`).join(", ")}` : ""}`);
1343
1368
  if (out.added.length || out.requeued.length) print(hostedLine(id, res));
1344
1369
  if (out.edges.length) print(`batch ${id}: edges ${out.edges.map((e) => `#${e.from} blocked by #${e.to}`).join(", ")}`);
1370
+ if (out.added.length || out.requeued.length) unhostedFailure(id, res, requireHost, out);
1345
1371
  return out;
1346
1372
  }
1347
1373
 
@@ -1373,7 +1399,7 @@ function baseWaitOf(waits, { io, leanIo, cwd, now = () => Date.now() }) {
1373
1399
  * when none runs) or directly. A held issue is not admitted (a running lane is not stopped); `--release` (or a `--resume` that
1374
1400
  * names it) lets it run again. @returns {{ok, batch, changed:number[]}}
1375
1401
  */
1376
- async function holdBatch({ op, id, tokens, root, viaDaemon = null, print = (l) => console.log(l) }) {
1402
+ async function holdBatch({ op, id, tokens, root, viaDaemon = null, takeover = null, print = (l) => console.log(l) }) {
1377
1403
  const issues = tokens.filter((t) => /^#?\d+$/.test(String(t))).map((t) => parseInt(String(t).replace("#", ""), 10));
1378
1404
  if (!id || String(id).startsWith("--") || !issues.length) throw new Error(ORCH_USAGE);
1379
1405
  let res = viaDaemon ? await viaDaemon(op, issues) : null;
@@ -1382,6 +1408,11 @@ async function holdBatch({ op, id, tokens, root, viaDaemon = null, print = (l) =
1382
1408
  if (!b.exists()) throw new Error(`no batch ${id} in ${root}`);
1383
1409
  res = { changed: op === "hold" ? b.holdIssues(issues) : b.releaseIssues(issues) };
1384
1410
  }
1411
+ if (op === "release" && takeover) { // #5241: a released issue deferred on a cancelled batch's lease is requeued at once
1412
+ const batchMod = await import("./lean/batch.mjs"), b = batchMod.openBatch(root, id), st = b.store.load(), repo = b.readPlan()?.repo ?? null;
1413
+ const dead = issues.filter((n) => st?.pending?.includes(n) && st?.results?.[n] === undefined && Number.isFinite(st?.notBefore?.[n]) && batchMod.cancelledOwners(root, repo, n, id).length);
1414
+ if (dead.length) await takeover(dead);
1415
+ }
1385
1416
  const list = (res.changed ?? []).map((n) => `#${n}`).join(" ") || "(none)";
1386
1417
  print(op === "hold" ? `batch ${id}: held ${list}; forgedock orchestrate --release ${id} <issue...> (or --resume ${id} <issue...>) re-admits them`
1387
1418
  : `batch ${id}: released ${list}`);
@@ -1394,7 +1425,7 @@ async function holdBatch({ op, id, tokens, root, viaDaemon = null, print = (l) =
1394
1425
  * written. Through the daemon (`viaDaemon`, null when none runs: the batch's `requeue` file, and a finished batch's report is
1395
1426
  * cleared so `--resume` runs it again). The runner applies the entries and posts the FORGE:DECISION.
1396
1427
  */
1397
- async function requeueBatch({ id, tokens, reason, root, io, viaDaemon = null, print = (l) => console.log(l) }) {
1428
+ async function requeueBatch({ id, tokens, reason, root, io, viaDaemon = null, requireHost = false, print = (l) => console.log(l) }) {
1398
1429
  if (!id || String(id).startsWith("--") || !tokens.length) throw new Error(ORCH_USAGE);
1399
1430
  const batchMod = await import("./lean/batch.mjs");
1400
1431
  const b = batchMod.openBatch(root, id);
@@ -1412,6 +1443,11 @@ async function requeueBatch({ id, tokens, reason, root, io, viaDaemon = null, pr
1412
1443
  else if ((v.labels ?? []).some((l) => (l?.name ?? l) === "needs-human")) refused.push({ issue: n, reason: "still labelled needs-human: record the decision and remove the label first" });
1413
1444
  else open.push(n);
1414
1445
  }
1446
+ // #5241: an issue deferred on a lease a cancelled batch's lane holds: the lease goes, so the requeue takes over at once
1447
+ for (const n of open) {
1448
+ if (!batchMod.cancelledOwners(root, repo, n, id).length || !b.store.load()?.pending?.includes(n)) continue;
1449
+ try { await clearLease({ projector: makeProjector(io, { repo: repo ?? undefined }), issue: n }); } catch { /* the lease expires */ }
1450
+ }
1415
1451
  const why = reason || "operator decision", by = "operator";
1416
1452
  let res = { requeued: [], refused: [] };
1417
1453
  if (open.length) {
@@ -1421,7 +1457,7 @@ async function requeueBatch({ id, tokens, reason, root, io, viaDaemon = null, pr
1421
1457
  const out = { ok: true, batch: id, requeued: res.requeued ?? [], refused: [...(res.refused ?? []), ...refused] };
1422
1458
  if (res.hosted !== undefined) { out.hosted = !!res.hosted; out.reopened = !!res.reopened; }
1423
1459
  print(`batch ${id}: ${out.requeued.map((n) => `requeued #${n}`).join(" ") || "requeued (none)"}${out.refused.length ? `; refused ${out.refused.map((x) => `${/^\d+$/.test(String(x.issue)) ? "#" : ""}${x.issue} (${x.reason})`).join(", ")}` : ""}`);
1424
- if (out.requeued.length) print(hostedLine(id, res));
1460
+ if (out.requeued.length) { print(hostedLine(id, res)); unhostedFailure(id, res, requireHost, out); }
1425
1461
  return out;
1426
1462
  }
1427
1463
 
@@ -1508,16 +1544,18 @@ async function orchestrateClient(argv, deps = {}) {
1508
1544
  }
1509
1545
  if (argv.includes("--requeue")) {
1510
1546
  const i = argv.indexOf("--requeue"), id = argv[i + 1];
1511
- return requeueBatch({ id, tokens: operandsOf(argv.slice(i + 2)), reason: flag(argv, "--reason"), root: await batchRootOf(), io: deps.io ?? makeIo(), viaDaemon: requeueVia(id) });
1547
+ return requeueBatch({ id, tokens: operandsOf(argv.slice(i + 2)), reason: flag(argv, "--reason"), root: await batchRootOf(), io: deps.io ?? makeIo(), viaDaemon: requeueVia(id), requireHost: true });
1512
1548
  }
1513
1549
  for (const op of ["hold", "release"]) if (argv.includes(`--${op}`)) {
1514
1550
  const id = flag(argv, `--${op}`);
1515
- return holdBatch({ op, id, tokens: operandsOf(argv.slice(argv.indexOf(`--${op}`) + 2)), root: await batchRootOf(), viaDaemon: holdVia(id) });
1551
+ const root = await batchRootOf(), io = deps.io ?? makeIo();
1552
+ return holdBatch({ op, id, tokens: operandsOf(argv.slice(argv.indexOf(`--${op}`) + 2)), root, viaDaemon: holdVia(id),
1553
+ takeover: (ns) => requeueBatch({ id, tokens: ns, reason: "--release: lease held by a cancelled batch", root, io, viaDaemon: requeueVia(id) }) });
1516
1554
  }
1517
1555
  if (argv.includes("--add")) {
1518
1556
  const i = argv.indexOf("--add"), id = argv[i + 1];
1519
1557
  if (!id || i + 2 >= argv.length) throw new Error(ORCH_USAGE);
1520
- return addToBatch({ id, tokens: operandsOf(argv.slice(i + 2)), root: await batchRootOf(), io: deps.io ?? makeIo(), viaDaemon: addVia(id) });
1558
+ return addToBatch({ id, tokens: operandsOf(argv.slice(i + 2)), root: await batchRootOf(), io: deps.io ?? makeIo(), viaDaemon: addVia(id), requireHost: true });
1521
1559
  }
1522
1560
  const resumeId = flag(argv, "--resume");
1523
1561
  const resumeExtra = resumeId ? operandsOf(argv.slice(argv.indexOf("--resume") + 2)) : [];
@@ -1533,7 +1571,7 @@ async function orchestrateClient(argv, deps = {}) {
1533
1571
  let sub = [...argv];
1534
1572
  if (!flag(sub, "--repo")) {
1535
1573
  const repo = await resolveDefaultRepo(deps.io ?? makeIo());
1536
- if (!repo) throw new Error("orchestrate needs the repo: pass --repo or run inside a checkout with a GitHub remote");
1574
+ if (!repo) throw new Error(USER_ERRORS.noRepoOrchestrate);
1537
1575
  sub = [...sub, "--repo", repo];
1538
1576
  }
1539
1577
  const pinned = schedd.batchEnv(process.env, readPinnedEnvConfig(process.cwd()));
@@ -1612,15 +1650,17 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
1612
1650
  if (argv.includes("--cancel")) return cancelBatch({ id: flag(argv, "--cancel"), root, stopRemote: argv.includes("--stop-remote"), print: (l) => sink.line(l) });
1613
1651
  if (argv.includes("--requeue")) {
1614
1652
  const i = argv.indexOf("--requeue");
1615
- return requeueBatch({ id: argv[i + 1], tokens: operandsOf(argv.slice(i + 2)), reason: flag(argv, "--reason"), root, io: deps.io ?? makeIo(), print: (l) => sink.line(l) });
1653
+ return requeueBatch({ id: argv[i + 1], tokens: operandsOf(argv.slice(i + 2)), reason: flag(argv, "--reason"), root, io: deps.io ?? makeIo(), requireHost: true, print: (l) => sink.line(l) });
1616
1654
  }
1617
1655
  for (const op of ["hold", "release"]) if (argv.includes(`--${op}`)) {
1618
- return holdBatch({ op, id: flag(argv, `--${op}`), tokens: operandsOf(argv.slice(argv.indexOf(`--${op}`) + 2)), root, print: (l) => sink.line(l) });
1656
+ const hid = flag(argv, `--${op}`);
1657
+ return holdBatch({ op, id: hid, tokens: operandsOf(argv.slice(argv.indexOf(`--${op}`) + 2)), root, print: (l) => sink.line(l),
1658
+ takeover: (ns) => requeueBatch({ id: hid, tokens: ns, reason: "--release: lease held by a cancelled batch", root, io: deps.io ?? makeIo(), print: (l) => sink.line(l) }) });
1619
1659
  }
1620
1660
  if (argv.includes("--add")) {
1621
1661
  const i = argv.indexOf("--add");
1622
1662
  if (!argv[i + 1] || i + 2 >= argv.length) throw new Error(ORCH_USAGE);
1623
- return addToBatch({ id: argv[i + 1], tokens: operandsOf(argv.slice(i + 2)), root, io: deps.io ?? makeIo(), print: (l) => sink.line(l) });
1663
+ return addToBatch({ id: argv[i + 1], tokens: operandsOf(argv.slice(i + 2)), root, io: deps.io ?? makeIo(), requireHost: true, print: (l) => sink.line(l) });
1624
1664
  }
1625
1665
  const resumeId = flag(argv, "--resume");
1626
1666
  const resumeExtra = resumeId ? operandsOf(argv.slice(argv.indexOf("--resume") + 2)) : [];
@@ -1639,7 +1679,7 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
1639
1679
  // #5031: a resume (operator or schedd restart) keeps the base waits recorded at start; a landed commit releases on the first check
1640
1680
  for (const [n, l] of Object.entries(plan.baseWaits ?? {})) if (Array.isArray(l) && l.length) baseWaits.set(Number(n), l.filter((w) => w && typeof w.sha === "string" && typeof w.base === "string"));
1641
1681
  }
1642
- const issues = issuesOf(argv);
1682
+ let issues = issuesOf(argv);
1643
1683
  if (!issues.length) throw new Error(ORCH_USAGE);
1644
1684
  const parallel = parallelOf(argv);
1645
1685
  // The lanes' env: a resumed daemon batch uses the env its plan kept, over the daemon's own.
@@ -1653,7 +1693,7 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
1653
1693
  const model = flag(argv, "--model");
1654
1694
  const io = deps.io ?? makeIo();
1655
1695
  const repo = flag(argv, "--repo") ?? plan?.repo ?? (await resolveDefaultRepo(io));
1656
- if (!repo) throw new Error("orchestrate needs the repo: pass --repo or run inside a checkout with a GitHub remote");
1696
+ if (!repo) throw new Error(USER_ERRORS.noRepoOrchestrate);
1657
1697
  const cwd = plan?.cwd ?? callerCwd;
1658
1698
  await assertLaneNotDefault(io, lane, repo, cwd);
1659
1699
  if (!deps.allowTmpfs && process.env.FORGEDOCK_BATCH_ALLOW_TMPFS !== "1") batchMod.assertDiskPath(root);
@@ -1685,6 +1725,21 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
1685
1725
  throw refusal;
1686
1726
  }
1687
1727
  }
1728
+ // #5241: an issue already pending or running in another active batch of the repo is skipped (naming it), unless --force <reason>
1729
+ if (!force) {
1730
+ const taken = new Map(issues.map((n) => [n, batchMod.activeBatchOf(root, repo, n)]).filter(([, b]) => b));
1731
+ for (const [n, b] of taken) sink.line(`skipped: #${n} is already in active batch ${b}; --force "<reason>" starts it here anyway`);
1732
+ if (taken.size) {
1733
+ if (taken.size === issues.length) throw new Error(`every issue is already in an active batch (${[...new Set(taken.values())].join(", ")}); pass --force "<reason>" to start them anyway`);
1734
+ const out = []; // drop the skipped operands, keeping each valued flag with its value
1735
+ for (let i = 0; i < argv.length; i++) {
1736
+ if (ORCH_VALUED.includes(argv[i])) { out.push(argv[i], argv[++i]); continue; }
1737
+ if (/^#?\d+$/.test(argv[i]) && taken.has(parseInt(argv[i].replace("#", ""), 10))) continue;
1738
+ out.push(argv[i]);
1739
+ }
1740
+ argv = out; issues = issuesOf(argv);
1741
+ }
1742
+ }
1688
1743
  const base = deps.batchId ?? batchMod.newBatchId();
1689
1744
  batch = batchMod.openBatch(root, base);
1690
1745
  for (let i = 2; batch.exists(); i++) batch = batchMod.openBatch(root, `${base}.${i}`); // never resume by accident
@@ -1745,8 +1800,8 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
1745
1800
  const { runCore } = deps.leanModule;
1746
1801
  const emitTelemetry = deps.emitTelemetry ?? makeEmitTelemetry({ repo });
1747
1802
  lanes = { adopt: null, runOne: (n, ln, ctx = {}) => runCore({ issue: n, repo, lane: ln, laneOverride, ...(ctx.placement ? { placement: { ...ctx.placement, mode: execMode() } } : {}), ...(ctx.recover ? { recover: ctx.recover } : {}), branches, cwd, dir, io: leanIo, agentId: `orch_${process.pid}_${n}`, emitTelemetry, batchId: batch.id,
1748
- ...(readExecution(cwd)?.accountRotator ? { accountRotator: readExecution(cwd).accountRotator } : {}), // #5094
1749
- admission: readAdmission(cwd), heavy: readHeavy(cwd), ...readCoreLimits(cwd), ...readEnvConfig(cwd), ...(readMergeWait(cwd) ? { mergeWait: readMergeWait(cwd) } : {}), ...(readConformanceMode(cwd) ? { conformance: readConformanceMode(cwd) } : {}), ...(readConformanceKinds(cwd) ? { conformanceKinds: readConformanceKinds(cwd) } : {}), ...(readConformanceMutation(cwd) ? { conformanceMutation: "report" } : {}), ...(readContextPack(cwd) ? { contextPack: readContextPack(cwd) } : {}), ...(readReviewIncomplete(cwd) ? { reviewIncomplete: readReviewIncomplete(cwd) } : {}), ...(readLaneInstructions(cwd) ? { laneInstructions: readLaneInstructions(cwd) } : {}), ...(readReproTest(cwd) ? { reproTest: readReproTest(cwd) } : {}), ...(readExplore(cwd) ? { explore: readExplore(cwd) } : {}), ...(readExperiment(cwd) ? { experiment: readExperiment(cwd) } : {}), light: readLight(cwd), ...(readCloseParent(cwd) ? { closeParent: true } : {}), ...(readReviewTrigger(cwd) ? { reviewTrigger: readReviewTrigger(cwd) } : {}), ...(readVerify(cwd) ? { verify: readVerify(cwd) } : {}), ...readPrecheckOptions(cwd), ...(model ? { builderModel: model } : {}), ...(readLeanSetting("reviewer_model", cwd) ? { reviewerModel: readLeanSetting("reviewer_model", cwd) } : {}), ...(readFixModel(cwd) ? { fixModel: readFixModel(cwd) } : {}), ...(readBuilderRouting(cwd) ? { builderRouting: readBuilderRouting(cwd) } : {}), ...(readVerifier(cwd) ? { verifier: readVerifier(cwd) } : {}), ...(readHostCaps(cwd) ? { hostCaps: readHostCaps(cwd) } : {}), ...readRelayCaps(), ...(readSequenceRegenerate(cwd) ? { sequenceRegenerate: readSequenceRegenerate(cwd) } : {}), ...(readBaseMerge(cwd) ? { baseMerge: readBaseMerge(cwd) } : {}), ...(readFollowupsDefaultMilestone(cwd) ? { followupsDefaultMilestone: readFollowupsDefaultMilestone(cwd) } : {}), ...(readFollowupsRollupLabel(cwd) ? { followupsRollupLabel: readFollowupsRollupLabel(cwd) } : {}) }) };
1803
+ ...(rotatorKind({ execution: readExecution(cwd), env }) ? { accountRotator: rotatorKind({ execution: readExecution(cwd), env }) } : {}), // #5094, #5205: detected
1804
+ admission: readAdmission(cwd), heavy: readHeavy(cwd), ...readCoreLimits(cwd), ...readEnvConfig(cwd), ...(readMergeWait(cwd) ? { mergeWait: readMergeWait(cwd) } : {}), ...(readConformanceMode(cwd) ? { conformance: readConformanceMode(cwd) } : {}), ...(readConformanceKinds(cwd) ? { conformanceKinds: readConformanceKinds(cwd) } : {}), ...(readConformanceMutation(cwd) ? { conformanceMutation: "report" } : {}), ...(readContextPack(cwd) ? { contextPack: readContextPack(cwd) } : {}), ...(readSequenceVersioned(cwd) ? { sequenceVersioned: readSequenceVersioned(cwd) } : {}), ...(readSharedSurfaces(cwd) ? { sharedSurfaces: readSharedSurfaces(cwd) } : {}), ...(readReviewIncomplete(cwd) ? { reviewIncomplete: readReviewIncomplete(cwd) } : {}), ...(readLaneInstructions(cwd) ? { laneInstructions: readLaneInstructions(cwd) } : {}), ...(readReproTest(cwd) ? { reproTest: readReproTest(cwd) } : {}), ...(readExplore(cwd) ? { explore: readExplore(cwd) } : {}), ...(readExperiment(cwd) ? { experiment: readExperiment(cwd) } : {}), light: readLight(cwd), ...(readCloseParent(cwd) ? { closeParent: true } : {}), ...(readReviewTrigger(cwd) ? { reviewTrigger: readReviewTrigger(cwd) } : {}), ...(readVerify(cwd) ? { verify: readVerify(cwd) } : {}), ...readPrecheckOptions(cwd), ...(model ? { builderModel: model } : {}), ...(readLeanSetting("reviewer_model", cwd) ? { reviewerModel: readLeanSetting("reviewer_model", cwd) } : {}), ...(readFixModel(cwd) ? { fixModel: readFixModel(cwd) } : {}), ...(readBuilderRouting(cwd) ? { builderRouting: readBuilderRouting(cwd) } : {}), ...(readVerifier(cwd) ? { verifier: readVerifier(cwd) } : {}), ...(readHostCaps(cwd) ? { hostCaps: readHostCaps(cwd) } : {}), ...readRelayCaps(), ...(readSequenceRegenerate(cwd) ? { sequenceRegenerate: readSequenceRegenerate(cwd) } : {}), ...(readBaseMerge(cwd) ? { baseMerge: readBaseMerge(cwd) } : {}), ...(readFollowupsDefaultMilestone(cwd) ? { followupsDefaultMilestone: readFollowupsDefaultMilestone(cwd) } : {}), ...(readFollowupsRollupLabel(cwd) ? { followupsRollupLabel: readFollowupsRollupLabel(cwd) } : {}) }) };
1750
1805
  } else {
1751
1806
  const laneScript = deps.laneScript ?? fileURLToPath(new URL("./forgedock.mjs", import.meta.url));
1752
1807
  // #4690: lanes learn K (the default MemoryMax is derived from it); one line says so when no scope caps them.
@@ -1842,7 +1897,9 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
1842
1897
  // #4376: a cancel stops detached host lanes by SIGTERM to their group (pid-reuse checked by the result path); sandboxes run on unless `--cancel --stop-remote` (#4612).
1843
1898
  const { killLedgerPid } = await import("./lean/effects.mjs");
1844
1899
  const stopLane = deps.stopLane ?? ((n, rec) => (rec?.remote || rec?.handle ? remoteStop?.(n, rec) ?? false : rec?.pid ? killLedgerPid(rec.pid, batch.resultFile(n)) : false));
1845
- lanes = { ...lanes, stopLane };
1900
+ // #5241: a cancelled lane that ended gives its issue lease back, unless a live lane of another batch runs the issue.
1901
+ const releaseLease = deps.releaseLease ?? (leanIo?.projector ? async (n) => { await clearLease({ projector: leanIo.projector, issue: n, shouldClear: () => !batchMod.batchesOwning(root, repo, n, { exceptId: batch.id }).some((o) => !o.cancelled && o.running) }); } : null);
1902
+ lanes = { ...lanes, stopLane, releaseLease };
1846
1903
  }
1847
1904
  const orch = deps.orchestration ?? readOrchestration(cwd);
1848
1905
  // #4965: --auto-children overrides forge.yaml; it is part of plan.argv, so --resume keeps it
@@ -1852,11 +1909,13 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
1852
1909
  // #4304: recovery lanes run on the core path only (run-issue throws on --recover with full), so a full-path repo gets none.
1853
1910
  const recoveryOn = Boolean(orch.recovery?.maxAttempts) && (deps.enginePath !== undefined ? deps.enginePath : readEnginePath(cwd)) !== "full";
1854
1911
  if (orch.recovery?.maxAttempts && !recoveryOn) sink.line("recovery: off (engine.path is full; recovery lanes run on the core path only)");
1912
+ // #5315: a forge.yaml key that is unknown, ignored by this engine path, mistyped or a deprecated alias is named at batch start, never silent.
1913
+ try { for (const f of validateForgeYaml(readFileSync(join(cwd, "forge.yaml"), "utf8"), { path: deps.enginePath !== undefined ? deps.enginePath : readEnginePath(cwd) })) sink.line(`config: ${formatFinding(f)}`); } catch { /* no forge.yaml: nothing to validate */ }
1855
1914
  // #4190: usage-limit holds live in the host store keyed by the account the next lane would use.
1856
1915
  const limitsMod = await import("./lean/limits.mjs");
1857
1916
  const limits = deps.limits ?? limitsMod.openLimits(limitsMod.limitsFile(env));
1858
1917
  // #5094: with an account rotator the identity is its current account, and admissions hold only when every account is exhausted.
1859
- const rotator = deps.rotator !== undefined ? deps.rotator : openRotator({ kind: readExecution(cwd)?.accountRotator });
1918
+ const rotator = deps.rotator !== undefined ? deps.rotator : openRotator({ kind: rotatorKind({ execution: readExecution(cwd), env }), env }); // #5205: detected
1860
1919
  const identity = deps.identity ?? (() => limitsMod.laneBackendId(env, rotator));
1861
1920
  const maint = deps.maintenance !== undefined ? deps.maintenance : readMaintenance(cwd);
1862
1921
  const schedMod = await import("./lean/sched.mjs");
@@ -1902,7 +1961,9 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
1902
1961
  let integration = deps.integration;
1903
1962
  if (integration === undefined) {
1904
1963
  const { makeIntegration } = await import("./lean/integration.mjs");
1905
- integration = makeIntegration({ repo, io: leanIo, cfg: await readIntegration(cwd), pattern: branches.featurePattern ?? undefined,
1964
+ // forge#5336: the epic journeys run after each child merge (real runs only: injected test seams keep their own io).
1965
+ const journeys = deps.leanIo || deps.leanModule || deps.laneScript ? null : (await import("./lean/acceptance.mjs")).makeJourneyRunner({ repo, io: leanIo, cwd });
1966
+ integration = makeIntegration({ repo, io: leanIo, cfg: await readIntegration(cwd), pattern: branches.featurePattern ?? undefined, journeys, skeleton: !!journeys, // #5337: the skeleton hold rides the same real-run guard
1906
1967
  sleep: (ms) => new Promise((r) => setTimeout(r, ms)), onEvent: (e) => console.log(`#${e.issue} → ${e.detail}`) });
1907
1968
  try { await integration?.prime(); } catch { /* streaks unknown: nothing is held */ }
1908
1969
  }
@@ -1971,6 +2032,7 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
1971
2032
  }
1972
2033
  let rows, childFields = null; // #4965: the host gh's accepted `issue list --json` fields, read once from its help
1973
2034
  const healthCheck = (checkpoint) => batchHealth.runCheck({ batch, checkpoint, config: healthConf, repo, now: healthNow,
2035
+ resolve: (cands) => batchHealth.resolvedOnGithub(cands, (a) => leanIo.gh(a), repo),
1974
2036
  alert: (text, health) => batchHealth.deliverAlert({ text, batchId: batch.id, health, sink, gh: (a) => leanIo.gh(a), repo, config: healthConf, epics: epicsOf(argv), ...(deps.notify ? { notify: deps.notify } : {}) }) });
1975
2037
  let healthTimers = { cancel: () => {} };
1976
2038
  try { healthTimers = batchHealth.scheduleChecks({ batch, created: healthCreated, config: healthConf, now: healthNow, ...(deps.healthTimer ? { setTimer: deps.healthTimer.set, clearTimer: deps.healthTimer.clear } : {}), check: healthCheck }); } catch { /* health is advisory */ }
@@ -2000,6 +2062,10 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
2000
2062
  relabelNeedsHuman: deps.relabelNeedsHuman ?? makeRelabelNeedsHuman({ gh: (a) => leanIo.gh(a), repo }),
2001
2063
  // #4481: a requeued or resumed issue that was closed or whose lane PR merged meanwhile is not run again
2002
2064
  dispatchCheck: deps.dispatchCheck !== undefined ? deps.dispatchCheck : makeDispatchCheck({ gh: (a) => leanIo.gh(a), repo }),
2065
+ // #5204: the engine version is saved with the batch state, so a resume after an upgrade names it on each interrupted lane
2066
+ version: ENGINE_VERSION,
2067
+ // #5204: an interrupted, requeued lane runs nothing until it is dispatched again: workflow:building comes off (best effort)
2068
+ onInterrupted: deps.onInterrupted ?? (async (n) => leanIo.gh(["issue", "edit", String(n), "-R", repo, "--remove-label", "workflow:building"]).catch(() => {})),
2003
2069
  // #4387: an out-of-set dependency labelled needs-human is not pulled into the batch
2004
2070
  issueLabels: labelNames,
2005
2071
  // #4725: a closed (completed) dependency is satisfied even when it still carries a stale needs-human label
@@ -2058,6 +2124,7 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
2058
2124
  const { batchEfficiency, formatEfficiencyLines } = await import("./stats/efficiency.mjs");
2059
2125
  report.push(...formatEfficiencyLines(await (deps.efficiency ?? batchEfficiency)({ batchDir: batch.dir, runsDir: dir, repo, gh: (a) => leanIo.gh(a), rows })));
2060
2126
  } catch (e) { report.push(`efficiency: n/a (${String(e?.message ?? e).split("\n")[0].slice(0, 160)})`); }
2127
+ report.push(await budgetReportLine({ cwd, repo, gh: (a) => leanIo.gh(a) })); // #5278: month usage, projection and any auto switch to local-first
2061
2128
  const shadowLine = formatShadowSummary(rows); // #4398
2062
2129
  if (shadowLine) report.push(shadowLine);
2063
2130
  const decompLine = formatDecompositionSummary(rows); // #4396
@@ -2077,7 +2144,7 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
2077
2144
  const ok = rows.every((r) => ["merged", "invalid", "decomposed"].includes(r.outcome));
2078
2145
  // #4917: a batch with any pending issue is not finished: no report, so a resume or the daemon picks it up
2079
2146
  let unfinished = false;
2080
- try { unfinished = batch.pendingIssues().length > 0 && !batch.readCancel(); } catch { unfinished = false; } // a cancel ends the batch for good
2147
+ try { unfinished = (batch.pendingIssues().length > 0 || batch.unrunAdds().length > 0 || batch.unrunRequeues().length > 0) && !batch.readCancel(); } catch { unfinished = false; } // a cancel ends the batch for good
2081
2148
  if (!unfinished) try { batch.writeReport({ rows, crossLane, ok, reclaimed, report: report.join("\n") }); } catch { /* the report is a cache of the rows */ }
2082
2149
  try { await healthCheck("end"); } catch { /* #5167: health never fails a batch */ }
2083
2150
  return { rows, crossLane, batch: batch.id, reclaimed, ok };
@@ -2302,7 +2369,7 @@ export async function poolFromCli(argv, deps = {}) {
2302
2369
  export async function limitsFromCli(argv, deps = {}) {
2303
2370
  const limitsMod = await import("./lean/limits.mjs");
2304
2371
  const limits = deps.limits ?? limitsMod.openLimits(limitsMod.limitsFile());
2305
- const rotator = deps.rotator !== undefined ? deps.rotator : openRotator({ kind: readExecution(process.cwd())?.accountRotator }); // #5094
2372
+ const rotator = deps.rotator !== undefined ? deps.rotator : openRotator({ kind: rotatorKind({ execution: readExecution(process.cwd()), env: process.env }) }); // #5094, #5205: detected
2306
2373
  const current = (deps.identity ?? (() => limitsMod.laneBackendId(process.env, rotator)))();
2307
2374
  const usage = "usage: forgedock limits show | forgedock limits clear <id>|--all";
2308
2375
  const [sub, arg] = argv;
@@ -2310,7 +2377,7 @@ export async function limitsFromCli(argv, deps = {}) {
2310
2377
  const holds = limits.list();
2311
2378
  if (!holds.length) console.log(`no usage-limit holds (this account: ${current})`);
2312
2379
  for (const h of holds) console.log(`${h.id === current ? "*" : " "} ${h.id} until ${new Date(h.until).toISOString()} source ${h.source ?? "-"}`);
2313
- for (const a of rotator?.accounts ?? []) console.log(` ${rotator.kind} account ${a.n} (${rotator.accountIdentity(a.n)}): 5h ${a.fiveHourPct}% resets ${new Date(a.fiveHourResetMs).toISOString()}`);
2380
+ for (const a of rotator?.accounts ?? []) console.log(` ${rotator.kind} account ${a.n} (${rotator.accountIdentity(a.n)}): 5h ${a.stale ? "(stale)" : `${a.fiveHourPct}%`} resets ${new Date(a.fiveHourResetMs).toISOString()}`); // #5205: a passed reset is unknown, not its old %
2314
2381
  return { holds, current };
2315
2382
  }
2316
2383
  if (sub === "clear") {
@@ -2399,7 +2466,9 @@ export async function checkFromCli(argv, deps = {}) {
2399
2466
  const picked = pre.planPrecheck({ testMap, files, learned, maxMinutes, verify });
2400
2467
  const par = String(env.FORGE_HOST_PARALLELISM ?? "").trim(), pinned = /^\d+$/.test(par) && Number(par) > 0;
2401
2468
  const runCommand = deps.runCommand ?? (await import("./lean/effects.mjs")).runCheckCommand;
2402
- const r = await pre.selfCheck({ contract, plan: { mode: verify.mode, commands: picked.commands, budgetMs: picked.budgetMs, perCommandMs: picked.perCommandMs },
2469
+ const { selfReviewFindings } = await import("./lean/selfreview.mjs"); // #5345: the reviewer's deterministic checks, before any reviewer
2470
+ const review = selfReviewFindings({ contract, result: await readJson(".forge-lean/result.json"), changedFiles: files });
2471
+ const r = await pre.selfCheck({ review, contract, plan: { mode: verify.mode, commands: picked.commands, budgetMs: picked.budgetMs, perCommandMs: picked.perCommandMs },
2403
2472
  parallelism: pinned ? Number(par) : 1, now: deps.now,
2404
2473
  run: ({ command, timeoutMs, workers }) => runCommand({ command, cwd: repo, timeoutMs, env: pinned ? { FORGE_HOST_PARALLELISM: String(workers) } : null }) });
2405
2474
  // #4390: each failure's full output goes to .forge-lean/logs/ (git-excluded); the table shows its tail, ids and the path
@@ -2417,8 +2486,12 @@ export async function checkFromCli(argv, deps = {}) {
2417
2486
  let fingerprint = null;
2418
2487
  try { fingerprint = await pre.worktreeFingerprint({ git, base }); } catch { /* recorded without one: the engine reads it as skipped */ }
2419
2488
  const strip = (x) => (x.status ? { ...(x.id ? { id: x.id } : {}), command: x.command, status: x.status } : { ...(x.id ? { id: x.id } : {}), command: x.command, rc: x.rc, ms: x.ms });
2420
- const record = { v: 1, at: new Date((deps.now ?? Date.now)()).toISOString(), base, fingerprint, ok: r.ok, validate: r.validate.map(strip), commands: [...r.commands.map(strip), ...r.deferred.map((command) => ({ command, status: "deferred-to-ci" }))] };
2489
+ const record = { v: 1, at: new Date((deps.now ?? Date.now)()).toISOString(), base, fingerprint, ok: r.ok, ...(r.review?.length ? { review: r.review.map((f) => ({ code: f.code, detail: f.detail })) } : {}), validate: r.validate.map(strip), commands: [...r.commands.map(strip), ...r.deferred.map((command) => ({ command, status: "deferred-to-ci" }))] };
2421
2490
  try { await (deps.writeFile ?? ((p, t) => fsp.writeFile(p, t)))(join(repo, pre.SELF_CHECK_FILE), `${JSON.stringify(record)}\n`); } catch { /* .forge-lean missing: still print */ }
2491
+ try { // #5278: parity row for the local green -> remote red hit rate; the attested status in ci.mode local-attested
2492
+ const suites = [...record.validate, ...record.commands].filter((x) => !x.status).map((x) => ({ name: x.id ?? x.command, ok: x.rc === 0 }));
2493
+ await recordHostCheck({ cwd: repo, head: String(await git(["rev-parse", "HEAD"])).trim(), ok: r.ok, suites });
2494
+ } catch { /* best effort */ }
2422
2495
  out(o.json ? JSON.stringify({ ...r, base, fingerprint }, null, 2) : pre.formatCheckTable(r));
2423
2496
  return { ...r, base, fingerprint, files, exitCode: r.ok ? 0 : 1 };
2424
2497
  }
@@ -2447,6 +2520,7 @@ export async function schedFromCli(argv, deps = {}) {
2447
2520
  for (const e of st.slots) console.log(` running ${who(e)} dispatcher ${e.pid}${e.lanePid ? ` lane ${e.lanePid}` : ""}`);
2448
2521
  for (const e of st.queue) console.log(` queued ${who(e)} dispatcher ${e.pid}`);
2449
2522
  for (const l of schedMod.remoteLines(st)) console.log(l); // #4964
2523
+ try { for (const l of (await import("./lean/batch-health.mjs")).summaryLines((await import("./lean/batch.mjs")).batchRoot())) console.log(l); } catch { /* advisory */ } // #5314
2450
2524
  return st;
2451
2525
  }
2452
2526
  if (sub === "cap") {