oxe-cc 1.21.1 → 1.22.2

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 (514) hide show
  1. package/.cursor/commands/oxe-alm.md +47 -0
  2. package/.cursor/commands/oxe-ask.md +1 -1
  3. package/.cursor/commands/oxe-capabilities.md +1 -1
  4. package/.cursor/commands/oxe-checkpoint.md +1 -1
  5. package/.cursor/commands/oxe-compact.md +1 -1
  6. package/.cursor/commands/oxe-dashboard.md +1 -1
  7. package/.cursor/commands/oxe-debug.md +1 -1
  8. package/.cursor/commands/oxe-discuss.md +1 -1
  9. package/.cursor/commands/oxe-execute.md +3 -1
  10. package/.cursor/commands/oxe-forensics.md +1 -1
  11. package/.cursor/commands/oxe-help.md +1 -1
  12. package/.cursor/commands/oxe-loop.md +1 -1
  13. package/.cursor/commands/oxe-milestone.md +1 -1
  14. package/.cursor/commands/oxe-next.md +1 -1
  15. package/.cursor/commands/oxe-obs.md +1 -1
  16. package/.cursor/commands/oxe-plan-agent.md +1 -1
  17. package/.cursor/commands/oxe-plan.md +3 -1
  18. package/.cursor/commands/oxe-project.md +1 -1
  19. package/.cursor/commands/oxe-quick.md +6 -4
  20. package/.cursor/commands/oxe-research.md +1 -1
  21. package/.cursor/commands/oxe-retro.md +1 -1
  22. package/.cursor/commands/oxe-review-pr.md +1 -1
  23. package/.cursor/commands/oxe-route.md +1 -1
  24. package/.cursor/commands/oxe-scan.md +1 -1
  25. package/.cursor/commands/oxe-security.md +1 -1
  26. package/.cursor/commands/oxe-session.md +1 -1
  27. package/.cursor/commands/oxe-ship.md +8 -8
  28. package/.cursor/commands/oxe-skill.md +1 -1
  29. package/.cursor/commands/oxe-spec.md +5 -3
  30. package/.cursor/commands/oxe-ui-review.md +1 -1
  31. package/.cursor/commands/oxe-ui-spec.md +1 -1
  32. package/.cursor/commands/oxe-update.md +1 -1
  33. package/.cursor/commands/oxe-validate-gaps.md +1 -1
  34. package/.cursor/commands/oxe-verify-audit.md +1 -1
  35. package/.cursor/commands/oxe-verify.md +1 -1
  36. package/.cursor/commands/oxe-workflow-authoring.md +1 -1
  37. package/.cursor/commands/oxe-workstream.md +1 -1
  38. package/.cursor/commands/oxe.md +4 -2
  39. package/.github/copilot-instructions.md +177 -177
  40. package/.github/dependabot.yml +31 -31
  41. package/.github/prompts/oxe-alm.prompt.md +47 -0
  42. package/.github/prompts/oxe-ask.prompt.md +1 -1
  43. package/.github/prompts/oxe-capabilities.prompt.md +1 -1
  44. package/.github/prompts/oxe-checkpoint.prompt.md +1 -1
  45. package/.github/prompts/oxe-compact.prompt.md +1 -1
  46. package/.github/prompts/oxe-dashboard.prompt.md +1 -1
  47. package/.github/prompts/oxe-debug.prompt.md +1 -1
  48. package/.github/prompts/oxe-discuss.prompt.md +1 -1
  49. package/.github/prompts/oxe-execute.prompt.md +3 -1
  50. package/.github/prompts/oxe-forensics.prompt.md +1 -1
  51. package/.github/prompts/oxe-help.prompt.md +1 -1
  52. package/.github/prompts/oxe-loop.prompt.md +1 -1
  53. package/.github/prompts/oxe-milestone.prompt.md +1 -1
  54. package/.github/prompts/oxe-next.prompt.md +1 -1
  55. package/.github/prompts/oxe-obs.prompt.md +1 -1
  56. package/.github/prompts/oxe-plan-agent.prompt.md +1 -1
  57. package/.github/prompts/oxe-plan.prompt.md +3 -1
  58. package/.github/prompts/oxe-project.prompt.md +1 -1
  59. package/.github/prompts/oxe-quick.prompt.md +6 -4
  60. package/.github/prompts/oxe-research.prompt.md +1 -1
  61. package/.github/prompts/oxe-retro.prompt.md +1 -1
  62. package/.github/prompts/oxe-review-pr.prompt.md +1 -1
  63. package/.github/prompts/oxe-route.prompt.md +1 -1
  64. package/.github/prompts/oxe-scan.prompt.md +1 -1
  65. package/.github/prompts/oxe-security.prompt.md +1 -1
  66. package/.github/prompts/oxe-session.prompt.md +1 -1
  67. package/.github/prompts/oxe-ship.prompt.md +7 -7
  68. package/.github/prompts/oxe-skill.prompt.md +1 -1
  69. package/.github/prompts/oxe-spec.prompt.md +4 -2
  70. package/.github/prompts/oxe-ui-review.prompt.md +1 -1
  71. package/.github/prompts/oxe-ui-spec.prompt.md +1 -1
  72. package/.github/prompts/oxe-update.prompt.md +1 -1
  73. package/.github/prompts/oxe-validate-gaps.prompt.md +1 -1
  74. package/.github/prompts/oxe-verify-audit.prompt.md +1 -1
  75. package/.github/prompts/oxe-verify.prompt.md +1 -1
  76. package/.github/prompts/oxe-workflow-authoring.prompt.md +1 -1
  77. package/.github/prompts/oxe-workstream.prompt.md +1 -1
  78. package/.github/prompts/oxe.prompt.md +4 -2
  79. package/.github/workflows/ci.yml +163 -163
  80. package/.github/workflows/release.yml +151 -120
  81. package/AGENTS.md +108 -102
  82. package/CHANGELOG.md +1971 -1042
  83. package/LICENSE +21 -21
  84. package/QUICKSTART.md +99 -99
  85. package/README.md +703 -673
  86. package/bin/banner.txt +18 -18
  87. package/bin/lib/commands/ops-commands.cjs +751 -0
  88. package/bin/lib/commands/spec-program-commands.cjs +337 -0
  89. package/bin/lib/operational/alm-refine-runtime.cjs +791 -0
  90. package/bin/lib/operational/child-env.cjs +52 -0
  91. package/bin/lib/operational/promote-runtime.cjs +1187 -0
  92. package/bin/lib/oxe-acceptance-audit.cjs +195 -0
  93. package/bin/lib/oxe-adr.cjs +145 -0
  94. package/bin/lib/oxe-agent-coord.cjs +246 -0
  95. package/bin/lib/oxe-agent-install.cjs +679 -677
  96. package/bin/lib/oxe-alm-admin.cjs +215 -0
  97. package/bin/lib/oxe-alm-metrics.cjs +143 -0
  98. package/bin/lib/oxe-alm-prs.cjs +274 -0
  99. package/bin/lib/oxe-alm-refine.cjs +1099 -0
  100. package/bin/lib/oxe-alm.cjs +1289 -0
  101. package/bin/lib/oxe-anchor-copy.cjs +218 -0
  102. package/bin/lib/oxe-api-surface.cjs +96 -0
  103. package/bin/lib/oxe-artifact-catalog.cjs +376 -376
  104. package/bin/lib/oxe-artifact-refs.cjs +72 -0
  105. package/bin/lib/oxe-attention.cjs +97 -0
  106. package/bin/lib/oxe-autoresume.cjs +448 -0
  107. package/bin/lib/oxe-budget.cjs +154 -117
  108. package/bin/lib/oxe-change-folder.cjs +130 -0
  109. package/bin/lib/oxe-change.cjs +389 -230
  110. package/bin/lib/oxe-channels.cjs +82 -0
  111. package/bin/lib/oxe-ci-adapter.cjs +304 -0
  112. package/bin/lib/oxe-cited-paths.cjs +180 -0
  113. package/bin/lib/oxe-cli-errors.cjs +76 -0
  114. package/bin/lib/oxe-cli-output.cjs +111 -0
  115. package/bin/lib/oxe-command-registry.cjs +31 -31
  116. package/bin/lib/oxe-commit-convention.cjs +104 -85
  117. package/bin/lib/oxe-complexity.cjs +106 -0
  118. package/bin/lib/oxe-console-decode.cjs +23 -0
  119. package/bin/lib/oxe-context-engine.cjs +874 -874
  120. package/bin/lib/oxe-coordinator-queue.cjs +67 -0
  121. package/bin/lib/oxe-core-command-handlers.cjs +84 -82
  122. package/bin/lib/oxe-criteria-ids.cjs +87 -0
  123. package/bin/lib/oxe-criterion-coverage.cjs +93 -58
  124. package/bin/lib/oxe-cross-card-conflicts.cjs +639 -0
  125. package/bin/lib/oxe-customize.cjs +146 -0
  126. package/bin/lib/oxe-dashboard.cjs +737 -737
  127. package/bin/lib/oxe-decisions.cjs +217 -0
  128. package/bin/lib/oxe-deferred.cjs +80 -0
  129. package/bin/lib/oxe-deps-audit.cjs +136 -0
  130. package/bin/lib/oxe-diff-reviewer.cjs +105 -0
  131. package/bin/lib/oxe-dir-info.cjs +157 -0
  132. package/bin/lib/oxe-docs-check.cjs +124 -0
  133. package/bin/lib/oxe-docs-publish.cjs +81 -0
  134. package/bin/lib/oxe-dom-hooks.cjs +902 -0
  135. package/bin/lib/oxe-dossier.cjs +355 -281
  136. package/bin/lib/oxe-e2e-ready.cjs +360 -0
  137. package/bin/lib/oxe-env-sanitize.cjs +160 -0
  138. package/bin/lib/oxe-event-bus.cjs +118 -118
  139. package/bin/lib/oxe-failure-cost.cjs +144 -0
  140. package/bin/lib/oxe-file-size-guard.cjs +849 -0
  141. package/bin/lib/oxe-findings.cjs +86 -0
  142. package/bin/lib/oxe-git-root.cjs +97 -0
  143. package/bin/lib/oxe-grill-cases.cjs +148 -0
  144. package/bin/lib/oxe-grill.cjs +533 -0
  145. package/bin/lib/oxe-grooming.cjs +115 -0
  146. package/bin/lib/oxe-guard.cjs +180 -0
  147. package/bin/lib/oxe-handoff.cjs +97 -0
  148. package/bin/lib/oxe-install-resolve.cjs +134 -134
  149. package/bin/lib/oxe-integration-checks.cjs +285 -0
  150. package/bin/lib/oxe-intent-context.cjs +101 -0
  151. package/bin/lib/oxe-journey.cjs +403 -0
  152. package/bin/lib/oxe-known-failures.cjs +138 -0
  153. package/bin/lib/oxe-local-config.cjs +77 -0
  154. package/bin/lib/oxe-manifest.cjs +124 -124
  155. package/bin/lib/oxe-memory-kernel.cjs +190 -188
  156. package/bin/lib/oxe-merge-train.cjs +277 -0
  157. package/bin/lib/oxe-model-resolve.cjs +74 -0
  158. package/bin/lib/oxe-model-tiers.cjs +65 -0
  159. package/bin/lib/oxe-nfr.cjs +125 -0
  160. package/bin/lib/oxe-npm-version.cjs +66 -66
  161. package/bin/lib/oxe-onboard.cjs +640 -0
  162. package/bin/lib/oxe-open-defects.cjs +121 -0
  163. package/bin/lib/oxe-operational.cjs +12112 -2115
  164. package/bin/lib/oxe-origin-guard.cjs +102 -0
  165. package/bin/lib/oxe-origin.cjs +380 -0
  166. package/bin/lib/oxe-pack-removed.cjs +208 -0
  167. package/bin/lib/oxe-parallel-run.cjs +81 -0
  168. package/bin/lib/oxe-parallel.cjs +234 -0
  169. package/bin/lib/oxe-phase-extras.cjs +185 -0
  170. package/bin/lib/oxe-phase-gates.cjs +688 -280
  171. package/bin/lib/oxe-plan-build.cjs +1580 -0
  172. package/bin/lib/oxe-plan-json.cjs +1107 -433
  173. package/bin/lib/oxe-plan-merge.cjs +253 -0
  174. package/bin/lib/oxe-plan-mutate.cjs +320 -0
  175. package/bin/lib/oxe-plan-repair.cjs +479 -0
  176. package/bin/lib/oxe-plan-review.cjs +256 -0
  177. package/bin/lib/oxe-plan-skeleton.cjs +494 -0
  178. package/bin/lib/oxe-plan-staleness.cjs +125 -0
  179. package/bin/lib/oxe-plugin-cli.cjs +97 -95
  180. package/bin/lib/oxe-plugins.cjs +432 -432
  181. package/bin/lib/oxe-policy-rules.cjs +144 -0
  182. package/bin/lib/oxe-prd.cjs +129 -0
  183. package/bin/lib/oxe-preflight.cjs +384 -0
  184. package/bin/lib/oxe-presets.cjs +216 -0
  185. package/bin/lib/oxe-process.cjs +67 -67
  186. package/bin/lib/oxe-program-members.cjs +97 -0
  187. package/bin/lib/oxe-program.cjs +245 -205
  188. package/bin/lib/oxe-progress-run.cjs +80 -0
  189. package/bin/lib/oxe-project-env.cjs +352 -178
  190. package/bin/lib/oxe-project-health.cjs +3426 -2962
  191. package/bin/lib/oxe-promote-helpers.cjs +1561 -0
  192. package/bin/lib/oxe-provider-antigravity.cjs +114 -0
  193. package/bin/lib/oxe-provider-grok.cjs +48 -0
  194. package/bin/lib/oxe-questions.cjs +115 -0
  195. package/bin/lib/oxe-quick.cjs +537 -0
  196. package/bin/lib/oxe-ratchets.cjs +132 -0
  197. package/bin/lib/oxe-rationality.cjs +587 -556
  198. package/bin/lib/oxe-real-regression.cjs +97 -0
  199. package/bin/lib/oxe-recovery.cjs +160 -0
  200. package/bin/lib/oxe-reevaluate.cjs +198 -0
  201. package/bin/lib/oxe-release-ops.cjs +361 -0
  202. package/bin/lib/oxe-release.cjs +622 -593
  203. package/bin/lib/oxe-repair.cjs +153 -0
  204. package/bin/lib/oxe-repo-map.cjs +136 -0
  205. package/bin/lib/oxe-repo-rules.cjs +121 -108
  206. package/bin/lib/oxe-research-provenance.cjs +96 -0
  207. package/bin/lib/oxe-resume.cjs +406 -0
  208. package/bin/lib/oxe-review.cjs +403 -0
  209. package/bin/lib/oxe-rfc.cjs +192 -0
  210. package/bin/lib/oxe-risk-decision.cjs +141 -0
  211. package/bin/lib/oxe-runtime-semantics.cjs +521 -514
  212. package/bin/lib/oxe-scorecard.cjs +627 -164
  213. package/bin/lib/oxe-scratch.cjs +81 -0
  214. package/bin/lib/oxe-seams.cjs +159 -0
  215. package/bin/lib/oxe-semver.cjs +83 -0
  216. package/bin/lib/oxe-ship-pr.cjs +272 -0
  217. package/bin/lib/oxe-signal.cjs +173 -0
  218. package/bin/lib/oxe-skill-loader.cjs +131 -131
  219. package/bin/lib/oxe-spec-check.cjs +249 -0
  220. package/bin/lib/oxe-spec-ears.cjs +98 -0
  221. package/bin/lib/oxe-spec-edit.cjs +411 -0
  222. package/bin/lib/oxe-spec-freeze.cjs +378 -0
  223. package/bin/lib/oxe-spec-probe.cjs +146 -0
  224. package/bin/lib/oxe-spec-stress.cjs +146 -0
  225. package/bin/lib/oxe-spike.cjs +98 -98
  226. package/bin/lib/oxe-state.cjs +87 -0
  227. package/bin/lib/oxe-stub-check.cjs +355 -0
  228. package/bin/lib/oxe-suite-impact.cjs +1160 -0
  229. package/bin/lib/oxe-sync.cjs +347 -0
  230. package/bin/lib/oxe-system-design.cjs +138 -0
  231. package/bin/lib/oxe-task-gates.cjs +139 -0
  232. package/bin/lib/oxe-telemetry.cjs +201 -0
  233. package/bin/lib/oxe-test-precheck.cjs +508 -0
  234. package/bin/lib/oxe-test-rigor.cjs +663 -0
  235. package/bin/lib/oxe-test-scope.cjs +883 -0
  236. package/bin/lib/oxe-trace.cjs +168 -0
  237. package/bin/lib/oxe-turns.cjs +64 -0
  238. package/bin/lib/oxe-ui-evidence.cjs +187 -0
  239. package/bin/lib/oxe-ui-verify.cjs +55 -0
  240. package/bin/lib/oxe-unsafe-commands.cjs +94 -0
  241. package/bin/lib/oxe-verdicts.cjs +131 -0
  242. package/bin/lib/oxe-verify-cache.cjs +132 -0
  243. package/bin/lib/oxe-verify-dryrun.cjs +541 -152
  244. package/bin/lib/oxe-verify-remote.cjs +208 -0
  245. package/bin/lib/oxe-vitest-batch.cjs +149 -0
  246. package/bin/lib/oxe-workflow-budget.cjs +99 -0
  247. package/bin/lib/oxe-workflow-eval.cjs +118 -0
  248. package/bin/lib/oxe-workflows.cjs +147 -145
  249. package/bin/lib/oxe-worktree-deps.cjs +241 -0
  250. package/bin/lib/oxe-worktree-gc.cjs +655 -0
  251. package/bin/oxe-cc.js +3861 -100
  252. package/commands/oxe/alm.md +54 -0
  253. package/commands/oxe/ask.md +1 -1
  254. package/commands/oxe/capabilities.md +1 -1
  255. package/commands/oxe/checkpoint.md +1 -1
  256. package/commands/oxe/compact.md +1 -1
  257. package/commands/oxe/dashboard.md +1 -1
  258. package/commands/oxe/debug.md +1 -1
  259. package/commands/oxe/discuss.md +1 -1
  260. package/commands/oxe/execute.md +3 -1
  261. package/commands/oxe/forensics.md +1 -1
  262. package/commands/oxe/help.md +1 -1
  263. package/commands/oxe/loop.md +1 -1
  264. package/commands/oxe/milestone.md +1 -1
  265. package/commands/oxe/next.md +1 -1
  266. package/commands/oxe/obs.md +1 -1
  267. package/commands/oxe/oxe.md +3 -1
  268. package/commands/oxe/plan-agent.md +1 -1
  269. package/commands/oxe/plan.md +3 -1
  270. package/commands/oxe/project.md +1 -1
  271. package/commands/oxe/quick.md +4 -4
  272. package/commands/oxe/research.md +1 -1
  273. package/commands/oxe/retro.md +1 -1
  274. package/commands/oxe/review-pr.md +1 -1
  275. package/commands/oxe/route.md +1 -1
  276. package/commands/oxe/scan.md +1 -1
  277. package/commands/oxe/security.md +1 -1
  278. package/commands/oxe/session.md +1 -1
  279. package/commands/oxe/ship.md +6 -6
  280. package/commands/oxe/skill.md +1 -1
  281. package/commands/oxe/spec.md +6 -3
  282. package/commands/oxe/ui-review.md +1 -1
  283. package/commands/oxe/ui-spec.md +1 -1
  284. package/commands/oxe/update.md +1 -1
  285. package/commands/oxe/validate-gaps.md +1 -1
  286. package/commands/oxe/verify-audit.md +1 -1
  287. package/commands/oxe/verify.md +1 -1
  288. package/commands/oxe/workflow-authoring.md +1 -1
  289. package/commands/oxe/workstream.md +1 -1
  290. package/docs/ADLC-COVERAGE.md +55 -0
  291. package/docs/CONTENT-MIGRATION-AUDIT.md +49 -49
  292. package/docs/HAPPY-PATH.md +106 -0
  293. package/docs/INCIDENT-PLAYBOOK.md +181 -181
  294. package/docs/INTEGRATION.md +182 -182
  295. package/docs/QUALITY-GATES.md +46 -46
  296. package/docs/RELEASE-READINESS.md +93 -87
  297. package/docs/ROLES.md +129 -129
  298. package/docs/RUNTIME-SMOKE-MATRIX.md +137 -137
  299. package/docs/TEAM-ADOPTION.md +153 -153
  300. package/docs/WALKTHROUGH.md +241 -241
  301. package/docs/adr/D-1-isolamento-read-only-e-sanitizacao-centralizada-de-env-vars.md +29 -0
  302. package/docs/adr/D-2-junction-segura-de-node-modules-condicionada-a-sha-256-de-pa.md +29 -0
  303. package/docs/adr/D-3-preflight-local-5s-impacto-estatico-e2e-e-leitura-explicita.md +29 -0
  304. package/docs/adr/D-4-governanca-de-release-unificada-retomada-idempotente-pos-rei.md +29 -0
  305. package/docs/adr/D-5-core-agnostico-vs-presets-declarativos-de-dominio.md +29 -0
  306. package/docs/adr/D-6-decomposicao-strangler-fig-de-oxe-cc-e-oxe-operational.md +29 -0
  307. package/docs/adr/D-7-paridade-pre-push-com-phase-gates-path-aware-json-compacto-e.md +28 -0
  308. package/docs/adr/D-F1F4-1-paridade-pre-push-compactacao-json-sync-version-pins-e-quali.md +44 -0
  309. package/docs/adr/README.md +19 -0
  310. package/docs/cli-errors.md +20 -0
  311. package/docs/oxespace-1.5/BACKLOG.md +2056 -273
  312. package/docs/oxespace-1.5/HANDOFF-1.21.2.md +140 -0
  313. package/docs/oxevoice/BACKLOG.md +244 -244
  314. package/lib/runtime/compiler/graph-compiler.d.ts +2 -0
  315. package/lib/runtime/compiler/graph-compiler.js +11 -2
  316. package/lib/runtime/delivery/promotion-pipeline.d.ts +1 -0
  317. package/lib/runtime/delivery/promotion-pipeline.js +53 -0
  318. package/lib/runtime/events/catalog.d.ts +1 -1
  319. package/lib/runtime/events/catalog.js +18 -0
  320. package/lib/runtime/executor/action-tool-map.d.ts +3 -1
  321. package/lib/runtime/executor/action-tool-map.js +4 -1
  322. package/lib/runtime/executor/adapters/antigravity-cli.d.ts +103 -0
  323. package/lib/runtime/executor/adapters/antigravity-cli.js +530 -0
  324. package/lib/runtime/executor/adapters/claude-cli.d.ts +29 -0
  325. package/lib/runtime/executor/adapters/claude-cli.js +92 -14
  326. package/lib/runtime/executor/adapters/grok-cli.d.ts +89 -0
  327. package/lib/runtime/executor/adapters/grok-cli.js +351 -0
  328. package/lib/runtime/executor/adapters/registry.d.ts +6 -1
  329. package/lib/runtime/executor/adapters/registry.js +22 -2
  330. package/lib/runtime/executor/adapters/types.d.ts +1 -1
  331. package/lib/runtime/executor/built-in-tools.d.ts +56 -0
  332. package/lib/runtime/executor/built-in-tools.js +219 -17
  333. package/lib/runtime/executor/index.d.ts +9 -2
  334. package/lib/runtime/executor/index.js +23 -1
  335. package/lib/runtime/executor/llm-task-executor.d.ts +76 -3
  336. package/lib/runtime/executor/llm-task-executor.js +514 -31
  337. package/lib/runtime/executor/node-context.d.ts +11 -0
  338. package/lib/runtime/executor/node-context.js +10 -0
  339. package/lib/runtime/executor/node-prompt-builder.js +2 -0
  340. package/lib/runtime/executor/quota-patterns.d.ts +7 -0
  341. package/lib/runtime/executor/quota-patterns.js +39 -0
  342. package/lib/runtime/executor/shell-argv.d.ts +11 -0
  343. package/lib/runtime/executor/shell-argv.js +89 -2
  344. package/lib/runtime/executor/stream-completion.d.ts +16 -0
  345. package/lib/runtime/executor/stream-completion.js +72 -4
  346. package/lib/runtime/index.d.ts +1 -1
  347. package/lib/runtime/index.js +3 -1
  348. package/lib/runtime/models/failure.d.ts +1 -1
  349. package/lib/runtime/models/run.d.ts +1 -1
  350. package/lib/runtime/program/program-model.d.ts +20 -2
  351. package/lib/runtime/program/program-model.js +73 -6
  352. package/lib/runtime/projection/projection-engine.d.ts +6 -0
  353. package/lib/runtime/projection/projection-engine.js +30 -2
  354. package/lib/runtime/reducers/run-state-reducer.js +43 -5
  355. package/lib/runtime/scheduler/run-journal.d.ts +8 -0
  356. package/lib/runtime/scheduler/scheduler.d.ts +211 -2
  357. package/lib/runtime/scheduler/scheduler.js +982 -98
  358. package/lib/runtime/verification/runner-timeout.d.ts +7 -0
  359. package/lib/runtime/verification/runner-timeout.js +17 -0
  360. package/lib/runtime/verification/test-report-parsers.d.ts +2 -1
  361. package/lib/runtime/verification/test-report-parsers.js +9 -1
  362. package/lib/runtime/verification/verification-compiler.d.ts +46 -2
  363. package/lib/runtime/verification/verification-compiler.js +335 -33
  364. package/lib/runtime/verification/verification-manifest.d.ts +2 -0
  365. package/lib/runtime/verification/verification-manifest.js +15 -1
  366. package/lib/runtime/workspace/index.d.ts +2 -1
  367. package/lib/runtime/workspace/index.js +3 -1
  368. package/lib/runtime/workspace/strategies/ephemeral-container.d.ts +9 -0
  369. package/lib/runtime/workspace/strategies/ephemeral-container.js +37 -10
  370. package/lib/runtime/workspace/strategies/git-worktree.d.ts +15 -1
  371. package/lib/runtime/workspace/strategies/git-worktree.js +53 -1
  372. package/lib/sdk/README.md +82 -82
  373. package/lib/sdk/index.cjs +828 -815
  374. package/lib/sdk/index.d.ts +982 -982
  375. package/lib/sdk/index.types.ts +933 -933
  376. package/oxe/agents/oxe-assumptions-analyzer.md +136 -136
  377. package/oxe/agents/oxe-codebase-mapper.md +142 -142
  378. package/oxe/agents/oxe-debugger.md +145 -145
  379. package/oxe/agents/oxe-executor.md +139 -139
  380. package/oxe/agents/oxe-integration-checker.md +142 -142
  381. package/oxe/agents/oxe-plan-checker.md +143 -143
  382. package/oxe/agents/oxe-planner.md +151 -151
  383. package/oxe/agents/oxe-research-synthesizer.md +146 -146
  384. package/oxe/agents/oxe-researcher.md +163 -163
  385. package/oxe/agents/oxe-ui-auditor.md +151 -151
  386. package/oxe/agents/oxe-ui-checker.md +157 -157
  387. package/oxe/agents/oxe-ui-researcher.md +179 -179
  388. package/oxe/agents/oxe-validation-auditor.md +154 -154
  389. package/oxe/agents/oxe-verifier.md +132 -132
  390. package/oxe/migrations/config-migrations.json +15 -0
  391. package/oxe/personas/README.md +91 -91
  392. package/oxe/personas/architect.md +149 -149
  393. package/oxe/personas/db-specialist.md +149 -149
  394. package/oxe/personas/debugger.md +155 -155
  395. package/oxe/personas/executor.md +164 -164
  396. package/oxe/personas/planner.md +165 -165
  397. package/oxe/personas/researcher.md +148 -148
  398. package/oxe/personas/ui-specialist.md +164 -164
  399. package/oxe/personas/verifier.md +174 -174
  400. package/oxe/schemas/plan.schema.json +101 -85
  401. package/oxe/schemas/role-plan.schema.json +50 -0
  402. package/oxe/schemas/swarm-run.schema.json +130 -130
  403. package/oxe/templates/CONFIG.md +290 -105
  404. package/oxe/templates/DISCUSS.template.md +45 -44
  405. package/oxe/templates/EXECUTION-RUNTIME.template.md +68 -68
  406. package/oxe/templates/FIXTURE-PACK.template.json +41 -41
  407. package/oxe/templates/FIXTURE-PACK.template.md +30 -30
  408. package/oxe/templates/GLOSSARY.template.md +9 -0
  409. package/oxe/templates/IMPLEMENTATION-PACK.template.json +68 -68
  410. package/oxe/templates/IMPLEMENTATION-PACK.template.md +48 -48
  411. package/oxe/templates/PLAN.template.md +151 -151
  412. package/oxe/templates/PLUGINS.md +108 -108
  413. package/oxe/templates/PRD.template.md +53 -0
  414. package/oxe/templates/REFERENCE-ANCHORS.template.md +39 -35
  415. package/oxe/templates/RESEARCH.template.md +65 -57
  416. package/oxe/templates/RFC.template.md +43 -0
  417. package/oxe/templates/SPEC.template.md +119 -119
  418. package/oxe/templates/STATE-REFERENCE.md +125 -125
  419. package/oxe/templates/STATE.md +30 -30
  420. package/oxe/templates/SUMMARY.template.md +50 -50
  421. package/oxe/templates/VISUAL-INPUTS.template.json +27 -27
  422. package/oxe/templates/VISUAL-INPUTS.template.md +36 -36
  423. package/oxe/templates/config.template.json +38 -38
  424. package/oxe/templates/finding-rules.json +22 -0
  425. package/oxe/templates/stress-methods.md +33 -0
  426. package/oxe/workflows/agent-mode.md +150 -150
  427. package/oxe/workflows/alm.md +50 -0
  428. package/oxe/workflows/compact/plan.md +149 -0
  429. package/oxe/workflows/compact/spec.md +114 -0
  430. package/oxe/workflows/compact.md +45 -44
  431. package/oxe/workflows/conduct.md +149 -149
  432. package/oxe/workflows/debug.md +43 -43
  433. package/oxe/workflows/discuss.md +98 -86
  434. package/oxe/workflows/distill.md +164 -164
  435. package/oxe/workflows/execute.md +273 -269
  436. package/oxe/workflows/forensics.md +53 -53
  437. package/oxe/workflows/help.md +364 -355
  438. package/oxe/workflows/lean/execute.md +43 -0
  439. package/oxe/workflows/lean/plan.md +60 -0
  440. package/oxe/workflows/lean/spec.md +61 -0
  441. package/oxe/workflows/memory.md +163 -163
  442. package/oxe/workflows/next.md +47 -45
  443. package/oxe/workflows/oxe.md +168 -150
  444. package/oxe/workflows/plan.md +563 -556
  445. package/oxe/workflows/quick.md +199 -185
  446. package/oxe/workflows/references/alm-refine.md +55 -0
  447. package/oxe/workflows/references/azure-in-plan.md +5 -0
  448. package/oxe/workflows/references/change-management.md +48 -0
  449. package/oxe/workflows/references/flow-robustness-contract.md +80 -80
  450. package/oxe/workflows/references/grill.md +74 -0
  451. package/oxe/workflows/references/next-step-footer.md +33 -0
  452. package/oxe/workflows/references/plan-json-acceptance-program.md +174 -143
  453. package/oxe/workflows/references/product-docs-alm.md +51 -0
  454. package/oxe/workflows/references/workflow-runtime-contracts.json +1167 -1151
  455. package/oxe/workflows/research.md +67 -66
  456. package/oxe/workflows/route.md +32 -32
  457. package/oxe/workflows/scan.md +356 -355
  458. package/oxe/workflows/ship.md +93 -142
  459. package/oxe/workflows/size-budget.json +62 -0
  460. package/oxe/workflows/spec.md +615 -619
  461. package/oxe/workflows/swarm/board.md +119 -119
  462. package/oxe/workflows/swarm/scout.md +170 -170
  463. package/oxe/workflows/swarm-mode.md +280 -280
  464. package/oxe/workflows/ui-review.md +37 -37
  465. package/oxe/workflows/ui-spec.md +32 -32
  466. package/oxe/workflows/verify.md +273 -255
  467. package/package.json +134 -132
  468. package/packages/runtime/package.json +18 -18
  469. package/packages/runtime/src/compiler/graph-compiler.ts +349 -336
  470. package/packages/runtime/src/context/context-pack-builder.ts +339 -339
  471. package/packages/runtime/src/delivery/promotion-pipeline.ts +397 -342
  472. package/packages/runtime/src/events/catalog.ts +63 -45
  473. package/packages/runtime/src/executor/action-tool-map.ts +52 -50
  474. package/packages/runtime/src/executor/adapters/antigravity-cli.ts +619 -0
  475. package/packages/runtime/src/executor/adapters/claude-cli.ts +367 -285
  476. package/packages/runtime/src/executor/adapters/grok-cli.ts +392 -0
  477. package/packages/runtime/src/executor/adapters/http-openai.ts +16 -16
  478. package/packages/runtime/src/executor/adapters/registry.ts +53 -33
  479. package/packages/runtime/src/executor/adapters/types.ts +24 -24
  480. package/packages/runtime/src/executor/built-in-tools.ts +525 -333
  481. package/packages/runtime/src/executor/index.ts +23 -16
  482. package/packages/runtime/src/executor/llm-task-executor.ts +854 -336
  483. package/packages/runtime/src/executor/node-context.ts +226 -210
  484. package/packages/runtime/src/executor/node-prompt-builder.ts +69 -67
  485. package/packages/runtime/src/executor/quota-patterns.ts +41 -0
  486. package/packages/runtime/src/executor/shell-argv.ts +144 -66
  487. package/packages/runtime/src/executor/stream-completion.ts +230 -160
  488. package/packages/runtime/src/index.ts +56 -54
  489. package/packages/runtime/src/models/failure.ts +22 -13
  490. package/packages/runtime/src/models/run.ts +25 -24
  491. package/packages/runtime/src/plugins/capability-adapter.ts +313 -313
  492. package/packages/runtime/src/plugins/plugin-abi.ts +106 -106
  493. package/packages/runtime/src/plugins/plugin-registry.ts +241 -241
  494. package/packages/runtime/src/program/index.ts +1 -1
  495. package/packages/runtime/src/program/program-model.ts +293 -233
  496. package/packages/runtime/src/projection/projection-engine.ts +386 -361
  497. package/packages/runtime/src/reducers/run-state-reducer.ts +365 -329
  498. package/packages/runtime/src/scheduler/multi-agent-coordinator.ts +1017 -1017
  499. package/packages/runtime/src/scheduler/run-journal.ts +107 -105
  500. package/packages/runtime/src/scheduler/scheduler.ts +2081 -1144
  501. package/packages/runtime/src/verification/contract-exports.ts +203 -203
  502. package/packages/runtime/src/verification/index.ts +3 -3
  503. package/packages/runtime/src/verification/runner-timeout.ts +17 -0
  504. package/packages/runtime/src/verification/test-report-parsers.ts +204 -198
  505. package/packages/runtime/src/verification/verification-compiler.ts +1074 -766
  506. package/packages/runtime/src/verification/verification-manifest.ts +296 -281
  507. package/packages/runtime/src/workspace/index.ts +6 -5
  508. package/packages/runtime/src/workspace/strategies/ephemeral-container.ts +159 -126
  509. package/packages/runtime/src/workspace/strategies/git-worktree.ts +190 -150
  510. package/packages/runtime/tsconfig.json +24 -23
  511. package/vscode-extension/.vscodeignore +9 -9
  512. package/vscode-extension/LICENSE +21 -21
  513. package/vscode-extension/package.json +193 -193
  514. package/vscode-extension/src/extension.js +320 -320
@@ -1,1144 +1,2081 @@
1
- import path from 'path';
2
- import fs from 'fs';
3
- import { appendEvent } from '../events/bus';
4
- import type { OxeEvent } from '../events/envelope';
5
- import type { EventInput } from '../events/bus';
6
- import type { ExecutionGraph, GraphNode } from '../compiler/graph-compiler';
7
- import type { WorkspaceManager, WorkspaceRequest } from '../workspace/workspace-manager';
8
- import type { WorkspaceLease } from '../models/workspace';
9
- import type { GateManager } from '../gate/gate-manager';
10
- import type { PolicyEngine, PersistedPolicyDecision, PolicyContext } from '../policy/policy-engine';
11
- import { savePolicyDecision } from '../policy/policy-engine';
12
- import type { PluginRegistry } from '../plugins/plugin-registry';
13
- import type { AuditTrail } from '../audit/audit-trail';
14
- import type { RunQuota, QuotaViolation } from '../audit/audit-trail';
15
- import { checkQuota, consumeQuota } from '../audit/audit-trail';
16
- import {
17
- saveJournal,
18
- loadJournal,
19
- deleteJournal,
20
- createJournal,
21
- } from './run-journal';
22
- import type { RunJournal } from './run-journal';
23
- import type { FailureClass } from '../models/failure';
24
- import { listMemos } from '../decision/decision-memo';
25
- import type { RollbackPlan } from '../decision/decision-memo';
26
- import { runCapabilityAsync } from '../plugins/capability-adapter';
27
- import { verifyRun } from '../verification/verification-compiler';
28
- import type { AcceptanceCheckSuite, CheckResult } from '../verification/verification-compiler';
29
-
30
- export interface TaskResult {
31
- success: boolean;
32
- failure_class: FailureClass;
33
- evidence: string[];
34
- output: string;
35
- completed_by?: string;
36
- }
37
-
38
- export interface TaskExecutor {
39
- execute(
40
- node: GraphNode,
41
- lease: WorkspaceLease,
42
- runId: string,
43
- attemptNumber: number,
44
- options?: { previousError?: string | null; maxTurns?: number | null }
45
- ): Promise<TaskResult>;
46
- }
47
-
48
- /**
49
- * Turn/cost ceiling of a run (1.21, OXB-023), kept by the caller from the executor's usage. The scheduler checks it
50
- * between attempts — never killing one mid-way — and caps the next attempt to the turns that are left, so the run
51
- * cannot go past the turn ceiling.
52
- */
53
- export interface RunBudget {
54
- /** Why no further attempt may start, or null while there is budget. */
55
- exhausted(): string | null;
56
- /** Turns still allowed (the next attempt's cap), or null when turns are unlimited. */
57
- remainingTurns(): number | null;
58
- }
59
-
60
- export interface SchedulerOptions {
61
- maxRunDurationMs?: number; // default: 30 min
62
- staleProgressMs?: number; // default: 5 min without any task completing
63
- }
64
-
65
- export interface SchedulerContext {
66
- projectRoot: string;
67
- sessionId: string | null;
68
- runId: string;
69
- executor: TaskExecutor;
70
- workspaceManager: WorkspaceManager;
71
- gateManager?: GateManager;
72
- policyEngine?: PolicyEngine;
73
- pluginRegistry?: PluginRegistry;
74
- auditTrail?: AuditTrail;
75
- quota?: RunQuota;
76
- budget?: RunBudget;
77
- policyActor?: string;
78
- onEvent?: (event: OxeEvent) => void;
79
- options?: SchedulerOptions;
80
- }
81
-
82
- export interface RunResult {
83
- run_id: string;
84
- status: 'completed' | 'failed' | 'blocked' | 'cancelled' | 'paused' | 'aborted';
85
- completed: string[];
86
- failed: string[];
87
- blocked: string[];
88
- pending_gates?: string[];
89
- reason?: string;
90
- }
91
-
92
- type NodeStatus = 'pending' | 'ready' | 'running' | 'completed' | 'failed' | 'blocked';
93
-
94
- export class Scheduler {
95
- private cancelled = false;
96
- private paused = false;
97
- private journal: RunJournal | null = null;
98
- private ctx: SchedulerContext | null = null;
99
- private runStartMs = 0;
100
- private lastProgressMs = 0;
101
-
102
- private recordProgress(): void {
103
- this.lastProgressMs = Date.now();
104
- }
105
-
106
- private async executeRollback(plan: RollbackPlan, ctx: SchedulerContext): Promise<void> {
107
- try {
108
- switch (plan.strategy) {
109
- case 'revert_commit':
110
- await runCapabilityAsync('git', ['revert', 'HEAD', '--no-edit'], {}, ctx.projectRoot, 30_000);
111
- break;
112
- case 'restore_workspace':
113
- await runCapabilityAsync('git', ['checkout', '.'], {}, ctx.projectRoot, 30_000);
114
- break;
115
- case 'undo_patch':
116
- for (const p of plan.steps) {
117
- await runCapabilityAsync('git', ['checkout', 'HEAD', '--', p], {}, ctx.projectRoot, 10_000);
118
- }
119
- break;
120
- case 'no_rollback':
121
- default:
122
- break;
123
- }
124
- this.emit(ctx, { type: 'RollbackExecuted', payload: { strategy: plan.strategy } });
125
- } catch (err) {
126
- this.emit(ctx, { type: 'RollbackFailed', payload: { strategy: plan.strategy, error: String(err) } });
127
- }
128
- }
129
-
130
- async run(graph: ExecutionGraph, ctx: SchedulerContext): Promise<RunResult> {
131
- this.cancelled = false;
132
- this.paused = false;
133
- this.ctx = ctx;
134
- this.runStartMs = Date.now();
135
- this.lastProgressMs = Date.now();
136
-
137
- const status = new Map<string, NodeStatus>();
138
- for (const id of graph.nodes.keys()) status.set(id, 'pending');
139
-
140
- const completed: string[] = [];
141
- const failed: string[] = [];
142
- const blocked: string[] = [];
143
-
144
- // Plan hash drift detection: abort if the graph was recompiled since ACTIVE-RUN was saved
145
- const activeRunPath = ctx.sessionId
146
- ? path.join(ctx.projectRoot, '.oxe', ctx.sessionId, 'execution', 'ACTIVE-RUN.json')
147
- : path.join(ctx.projectRoot, '.oxe', 'ACTIVE-RUN.json');
148
- if (fs.existsSync(activeRunPath)) {
149
- try {
150
- const activeRun = JSON.parse(fs.readFileSync(activeRunPath, 'utf8')) as Record<string, unknown>;
151
- const savedHash = activeRun.plan_hash as string | undefined;
152
- const currentHash = graph.metadata.plan_hash;
153
- if (savedHash && savedHash !== currentHash) {
154
- return {
155
- run_id: ctx.runId,
156
- status: 'aborted',
157
- completed: [],
158
- failed: [],
159
- blocked: [],
160
- reason: `plan_drift: graph recompiled (${savedHash} → ${currentHash}). Run /oxe-plan --replan to realign.`,
161
- };
162
- }
163
- } catch {
164
- // ACTIVE-RUN not parseable — continue without drift check
165
- }
166
- }
167
-
168
- this.journal = createJournal(ctx.runId);
169
- saveJournal(ctx.projectRoot, ctx.runId, this.journal);
170
-
171
- this.emit(ctx, { type: 'RunStarted', payload: { run_id: ctx.runId } });
172
- ctx.auditTrail?.record('run_started', ctx.policyActor ?? 'runtime', {
173
- runId: ctx.runId,
174
- detail: { session_id: ctx.sessionId ?? null },
175
- });
176
-
177
- const maxRunMs = ctx.options?.maxRunDurationMs ?? 30 * 60_000;
178
- const staleMs = ctx.options?.staleProgressMs ?? 5 * 60_000;
179
-
180
- for (const wave of graph.waves) {
181
- if (this.cancelled) break;
182
-
183
- // Global run timeout
184
- if (Date.now() - this.runStartMs > maxRunMs) {
185
- return this.abortRun(ctx, 'global_timeout', completed, failed, blocked);
186
- }
187
-
188
- // Stale progress timeout (no task completed in staleMs)
189
- if (Date.now() - this.lastProgressMs > staleMs) {
190
- return this.abortRun(ctx, 'no_progress_timeout', completed, failed, blocked);
191
- }
192
-
193
- // Respect pause: persist journal and return paused result
194
- if (this.paused) {
195
- this.journal.scheduler_state = 'paused';
196
- this.journal.paused_at = new Date().toISOString();
197
- this.journal.completed_work_items = completed.slice();
198
- this.journal.failed_work_items = failed.slice();
199
- this.journal.blocked_work_items = blocked.slice();
200
- this.journal.partial_result = { run_id: ctx.runId, completed, failed, blocked };
201
- saveJournal(ctx.projectRoot, ctx.runId, this.journal);
202
- ctx.auditTrail?.record('run_paused', ctx.policyActor ?? 'runtime', {
203
- runId: ctx.runId,
204
- detail: { completed, failed, blocked },
205
- });
206
- return { run_id: ctx.runId, status: 'paused', completed, failed, blocked, pending_gates: this.journal.pending_gates.slice() };
207
- }
208
-
209
- const waveFailed = await this.runWave(
210
- wave.node_ids,
211
- graph,
212
- ctx,
213
- status,
214
- completed,
215
- failed,
216
- blocked
217
- );
218
-
219
- // Sync journal after each wave
220
- this.journal.completed_work_items = completed.slice();
221
- this.journal.failed_work_items = failed.slice();
222
- this.journal.blocked_work_items = blocked.slice();
223
- saveJournal(ctx.projectRoot, ctx.runId, this.journal);
224
-
225
- if (waveFailed) {
226
- // Execute rollback plan if one was created for this run
227
- const memos = listMemos(ctx.projectRoot, ctx.runId);
228
- for (const memo of memos) {
229
- if (memo.rollback_plan.strategy !== 'no_rollback') {
230
- await this.executeRollback(memo.rollback_plan, ctx);
231
- break; // apply at most one rollback plan per wave failure
232
- }
233
- }
234
- break;
235
- }
236
- }
237
-
238
- // Any remaining pending nodes become blocked
239
- for (const [id, s] of status) {
240
- if (s === 'pending') {
241
- status.set(id, 'blocked');
242
- blocked.push(id);
243
- this.emit(ctx, {
244
- type: 'WorkItemBlocked',
245
- work_item_id: id,
246
- payload: { reason: 'upstream_wave_failed' },
247
- });
248
- }
249
- }
250
-
251
- const finalStatus: RunResult['status'] = this.cancelled
252
- ? 'cancelled'
253
- : failed.length > 0
254
- ? 'failed'
255
- : blocked.length > 0
256
- ? 'blocked'
257
- : 'completed';
258
-
259
- this.emit(ctx, {
260
- type: 'RunCompleted',
261
- payload: { run_id: ctx.runId, status: finalStatus },
262
- });
263
- ctx.auditTrail?.record('run_completed', ctx.policyActor ?? 'runtime', {
264
- runId: ctx.runId,
265
- detail: {
266
- status: finalStatus,
267
- completed: completed.length,
268
- failed: failed.length,
269
- blocked: blocked.length,
270
- pending_gates: this.journal.pending_gates.slice(),
271
- },
272
- });
273
-
274
- this.journal.scheduler_state = this.cancelled
275
- ? 'cancelled'
276
- : finalStatus === 'blocked' || finalStatus === 'failed'
277
- ? finalStatus
278
- : 'completed';
279
- this.journal.completed_work_items = completed.slice();
280
- this.journal.failed_work_items = failed.slice();
281
- this.journal.blocked_work_items = blocked.slice();
282
- saveJournal(ctx.projectRoot, ctx.runId, this.journal);
283
-
284
- return {
285
- run_id: ctx.runId,
286
- status: finalStatus,
287
- completed,
288
- failed,
289
- blocked,
290
- pending_gates: this.journal.pending_gates.slice(),
291
- };
292
- }
293
-
294
- /**
295
- * Recover a previously paused run by loading its journal and re-running
296
- * only the work items that haven't completed yet.
297
- */
298
- async recover(runId: string, ctx: SchedulerContext, graph: ExecutionGraph): Promise<RunResult | null> {
299
- const journal = loadJournal(ctx.projectRoot, runId);
300
- // Paused, blocked (gates since approved), aborted (timeout) and failed runs can all be resumed;
301
- // only completed/cancelled runs have nothing left to do.
302
- if (!journal || !RECOVERABLE_JOURNAL_STATES.has(journal.scheduler_state)) return null;
303
-
304
- // Restore state from journal
305
- this.cancelled = false;
306
- this.paused = false;
307
- this.ctx = ctx;
308
- this.journal = { ...journal, scheduler_state: 'running', paused_at: null };
309
-
310
- const restoredCompleted = new Set(journal.completed_work_items);
311
- const restoredFailed = new Set(journal.failed_work_items);
312
- const restoredBlocked = new Set(journal.blocked_work_items);
313
-
314
- const status = new Map<string, NodeStatus>();
315
- for (const id of graph.nodes.keys()) {
316
- if (restoredCompleted.has(id)) status.set(id, 'completed');
317
- else if (restoredFailed.has(id)) status.set(id, 'failed');
318
- else if (restoredBlocked.has(id)) status.set(id, 'blocked');
319
- else status.set(id, 'pending');
320
- }
321
-
322
- const completed = [...restoredCompleted];
323
- const failed = [...restoredFailed];
324
- const blocked = [...restoredBlocked];
325
-
326
- saveJournal(ctx.projectRoot, runId, this.journal);
327
-
328
- this.emit(ctx, { type: 'RunStarted', payload: { run_id: ctx.runId, recovered: true } });
329
-
330
- for (const wave of graph.waves) {
331
- if (this.cancelled) break;
332
- if (this.paused) {
333
- this.journal.scheduler_state = 'paused';
334
- this.journal.paused_at = new Date().toISOString();
335
- this.journal.completed_work_items = completed.slice();
336
- this.journal.failed_work_items = failed.slice();
337
- this.journal.blocked_work_items = blocked.slice();
338
- this.journal.partial_result = { run_id: ctx.runId, completed, failed, blocked };
339
- saveJournal(ctx.projectRoot, ctx.runId, this.journal);
340
- ctx.auditTrail?.record('run_paused', ctx.policyActor ?? 'runtime', {
341
- runId: ctx.runId,
342
- detail: { recovered: true, completed, failed, blocked },
343
- });
344
- return { run_id: ctx.runId, status: 'paused', completed, failed, blocked, pending_gates: this.journal.pending_gates.slice() };
345
- }
346
-
347
- // Skip waves fully completed
348
- const allDone = wave.node_ids.every(
349
- (id) => restoredCompleted.has(id) || restoredFailed.has(id) || restoredBlocked.has(id)
350
- );
351
- if (allDone) continue;
352
-
353
- const waveFailed = await this.runWave(
354
- wave.node_ids,
355
- graph,
356
- ctx,
357
- status,
358
- completed,
359
- failed,
360
- blocked
361
- );
362
-
363
- this.journal.completed_work_items = completed.slice();
364
- this.journal.failed_work_items = failed.slice();
365
- this.journal.blocked_work_items = blocked.slice();
366
- saveJournal(ctx.projectRoot, ctx.runId, this.journal);
367
-
368
- if (waveFailed) break;
369
- }
370
-
371
- for (const [id, s] of status) {
372
- if (s === 'pending') {
373
- status.set(id, 'blocked');
374
- blocked.push(id);
375
- this.emit(ctx, {
376
- type: 'WorkItemBlocked',
377
- work_item_id: id,
378
- payload: { reason: 'upstream_wave_failed' },
379
- });
380
- }
381
- }
382
-
383
- const finalStatus: RunResult['status'] = this.cancelled
384
- ? 'cancelled'
385
- : failed.length > 0
386
- ? 'failed'
387
- : blocked.length > 0
388
- ? 'blocked'
389
- : 'completed';
390
-
391
- this.emit(ctx, {
392
- type: 'RunCompleted',
393
- payload: { run_id: ctx.runId, status: finalStatus, recovered: true },
394
- });
395
- ctx.auditTrail?.record('run_recovered', ctx.policyActor ?? 'runtime', {
396
- runId: ctx.runId,
397
- detail: {
398
- status: finalStatus,
399
- completed: completed.length,
400
- failed: failed.length,
401
- blocked: blocked.length,
402
- pending_gates: this.journal.pending_gates.slice(),
403
- },
404
- });
405
-
406
- this.journal.scheduler_state = this.cancelled
407
- ? 'cancelled'
408
- : finalStatus === 'blocked' || finalStatus === 'failed'
409
- ? finalStatus
410
- : 'completed';
411
- this.journal.completed_work_items = completed.slice();
412
- this.journal.failed_work_items = failed.slice();
413
- this.journal.blocked_work_items = blocked.slice();
414
- saveJournal(ctx.projectRoot, ctx.runId, this.journal);
415
- deleteJournal(ctx.projectRoot, ctx.runId);
416
-
417
- return {
418
- run_id: ctx.runId,
419
- status: finalStatus,
420
- completed,
421
- failed,
422
- blocked,
423
- pending_gates: this.journal.pending_gates.slice(),
424
- };
425
- }
426
-
427
- private isConcurrentSafe(nodeId: string, graph: ExecutionGraph, ctx: SchedulerContext): boolean {
428
- const node = graph.nodes.get(nodeId)!;
429
- if (node.mutation_scope.length > 0) return false;
430
- // A node that may write files but declares no scope is not provably safe to run in parallel
431
- // (an empty scope used to mean "run everything in parallel, in place").
432
- if (nodeMayMutate(node)) return false;
433
- const primaryAction = pickPrimaryAction(node, ctx.pluginRegistry);
434
- if (!primaryAction) return true;
435
- const provider = ctx.pluginRegistry?.toolProviderFor(primaryAction.type);
436
- return provider?.idempotent ?? true;
437
- }
438
-
439
- private async runWave(
440
- nodeIds: string[],
441
- graph: ExecutionGraph,
442
- ctx: SchedulerContext,
443
- status: Map<string, NodeStatus>,
444
- completed: string[],
445
- failed: string[],
446
- blocked: string[]
447
- ): Promise<boolean> {
448
- const eligible: string[] = [];
449
- const depsNotMet: string[] = [];
450
-
451
- for (const id of nodeIds) {
452
- if (status.get(id) === 'completed') continue; // already done in recovery
453
- const node = graph.nodes.get(id)!;
454
- const depsMet = node.depends_on.every((dep) => status.get(dep) === 'completed');
455
- if (depsMet) {
456
- eligible.push(id);
457
- } else {
458
- depsNotMet.push(id);
459
- }
460
- }
461
-
462
- for (const id of depsNotMet) {
463
- status.set(id, 'blocked');
464
- blocked.push(id);
465
- this.emit(ctx, {
466
- type: 'WorkItemBlocked',
467
- work_item_id: id,
468
- payload: { reason: 'dependency_not_met' },
469
- });
470
- }
471
-
472
- for (const id of eligible) {
473
- const node = graph.nodes.get(id)!;
474
- if (node.mutation_scope.length === 0 && nodeMayMutate(node)) {
475
- this.emit(ctx, {
476
- type: 'PolicyWarning',
477
- work_item_id: id,
478
- payload: {
479
- reason: 'empty_mutation_scope',
480
- detail: 'node may write files but declares no mutation_scope; running serially and without scope checks',
481
- },
482
- });
483
- }
484
- }
485
-
486
- const readOnly = eligible.filter((id) => this.isConcurrentSafe(id, graph, ctx));
487
- const mutations = eligible.filter((id) => !readOnly.includes(id));
488
-
489
- if (readOnly.length > 0) {
490
- await Promise.all(
491
- readOnly.map((id) => this.runNode(id, graph, ctx, status, completed, failed, blocked))
492
- );
493
- }
494
-
495
- for (const id of mutations) {
496
- if (this.cancelled) break;
497
- await this.runNode(id, graph, ctx, status, completed, failed, blocked);
498
- }
499
-
500
- return failed.length > 0;
501
- }
502
-
503
- private async runNode(
504
- nodeId: string,
505
- graph: ExecutionGraph,
506
- ctx: SchedulerContext,
507
- status: Map<string, NodeStatus>,
508
- completed: string[],
509
- failed: string[],
510
- blocked: string[]
511
- ): Promise<void> {
512
- const node = graph.nodes.get(nodeId)!;
513
- status.set(nodeId, 'running');
514
- this.emit(ctx, {
515
- type: 'WorkItemReady',
516
- work_item_id: nodeId,
517
- payload: { title: node.title, wave: node.wave },
518
- });
519
-
520
- let lease: WorkspaceLease | null = null;
521
- // Dispose through the manager that allocated the lease (plugin provider or default).
522
- let leaseManager: WorkspaceManager | null = null;
523
- let lastResult: TaskResult | null = null;
524
- let lastError: string | null = null;
525
- // 1.20c: the same verify failure twice (normalized output) = suspect ruler or stuck executor: stop paying retries.
526
- let lastVerifySignature: string | null = null;
527
- let verifySuspect = false;
528
- const maxAttempts = node.policy.max_retries + 1;
529
- // 1.21.1 (OXB-047): work that arrives by another path never pays an agent and never becomes a human gate.
530
- // An explicit human gate (PLAN.json `gate`) still comes first: the attempt loop requests it as before.
531
- const humanGatePending = node.policy.requires_human_approval && !this.hasApprovedGate(node, ctx);
532
- if (!humanGatePending && (node.policy.verify_only || (node.policy.external_dependency?.length ?? 0) > 0)) {
533
- await this.runExternalNode(node, ctx, status, completed, failed, blocked);
534
- return;
535
- }
536
- const quotaBlocked = this.consumeQuotaForNode(ctx, node);
537
- if (quotaBlocked) {
538
- this.blockNode(nodeId, ctx, status, blocked, 'quota_exceeded', quotaBlocked);
539
- return;
540
- }
541
-
542
- for (let attempt = 1; attempt <= maxAttempts; attempt++) {
543
- const attemptId = `${nodeId}-a${attempt}`;
544
-
545
- this.emit(ctx, {
546
- type: 'AttemptStarted',
547
- work_item_id: nodeId,
548
- attempt_id: attemptId,
549
- payload: { attempt_number: attempt },
550
- });
551
-
552
- try {
553
- const policyDecision = this.evaluatePolicyForNode(node, ctx);
554
- if (policyDecision && !policyDecision.allowed) {
555
- this.emit(ctx, {
556
- type: 'PolicyEvaluated',
557
- work_item_id: nodeId,
558
- attempt_id: attemptId,
559
- payload: { ...policyDecision },
560
- });
561
- ctx.auditTrail?.record('policy_denied', ctx.policyActor ?? 'runtime', {
562
- runId: ctx.runId,
563
- workItemId: nodeId,
564
- detail: { reason: policyDecision.reason, rule_id: policyDecision.rule_id },
565
- });
566
- this.blockNode(nodeId, ctx, status, blocked, 'policy_denied', policyDecision.reason);
567
- return;
568
- }
569
-
570
- if (policyDecision) {
571
- this.emit(ctx, {
572
- type: 'PolicyEvaluated',
573
- work_item_id: nodeId,
574
- attempt_id: attemptId,
575
- payload: { ...policyDecision },
576
- });
577
- }
578
-
579
- if ((policyDecision?.gate_required || node.policy.requires_human_approval) && !this.hasApprovedGate(node, ctx)) {
580
- const gateId = await this.requestGateForNode(node, ctx, policyDecision);
581
- this.blockNode(nodeId, ctx, status, blocked, 'pending_gate', gateId);
582
- return;
583
- }
584
-
585
- // OXB-023: the run's turn/cost ceiling is checked before every attempt, never in the middle of one.
586
- const budgetReason = ctx.budget?.exhausted() ?? null;
587
- if (budgetReason) {
588
- this.emit(ctx, {
589
- type: 'BudgetExhausted',
590
- work_item_id: nodeId,
591
- attempt_id: attemptId,
592
- payload: { reason: budgetReason, attempt_number: attempt },
593
- });
594
- this.blockNode(nodeId, ctx, status, blocked, 'budget_exhausted', budgetReason);
595
- return;
596
- }
597
- const turnsLeft = ctx.budget?.remainingTurns() ?? null;
598
-
599
- const wsReq: WorkspaceRequest = {
600
- work_item_id: nodeId,
601
- attempt_number: attempt,
602
- strategy: node.workspace_strategy,
603
- mutation_scope: node.mutation_scope,
604
- };
605
- const workspaceManager = ctx.pluginRegistry?.workspaceProviderFor(node.workspace_strategy) ?? ctx.workspaceManager;
606
- leaseManager = workspaceManager;
607
- lease = await workspaceManager.allocate(wsReq);
608
- this.emit(ctx, {
609
- type: 'WorkspaceAllocated',
610
- work_item_id: nodeId,
611
- attempt_id: attemptId,
612
- payload: { workspace_id: lease.workspace_id, strategy: lease.strategy },
613
- });
614
-
615
- lastResult = await this.executeNode(node, lease, ctx, attempt, attemptId, {
616
- previousError: lastError,
617
- ...(turnsLeft != null ? { maxTurns: turnsLeft } : {}),
618
- });
619
-
620
- // OXB-026: the verify judges the work, not the end of the LLM conversation. An attempt that ran out of turns
621
- // after writing in its scope is verified before it is classified: green completes the task, red goes to the
622
- // informed retry. Discarding it unverified paid a whole second attempt for finished work.
623
- const turnLimitWithWork = !lastResult.success
624
- && lastResult.completed_by === 'turn_limit_exhausted'
625
- && Boolean(node.verify?.command)
626
- && (lastResult.evidence?.length ?? 0) > 0;
627
-
628
- if (lastResult.success || turnLimitWithWork) {
629
- const verifyResult = await this.verifyNode(node, lease, ctx, attemptId, attempt);
630
- if (verifyResult && verifyResult.status === 'failed') {
631
- // Informed retry: the next attempt sees the command, the reason and the output — not just "failed".
632
- lastResult = {
633
- success: false,
634
- failure_class: 'verify',
635
- evidence: lastResult.evidence,
636
- output: describeVerifyFailure(node.verify.command, verifyResult.check, verifyResult.gaps),
637
- };
638
- const signature = verifyFailureSignature(verifyResult.check);
639
- if (signature && signature === lastVerifySignature) {
640
- verifySuspect = true;
641
- this.emit(ctx, {
642
- type: 'VerifyCommandSuspect',
643
- work_item_id: nodeId,
644
- attempt_id: attemptId,
645
- payload: {
646
- attempt_number: attempt,
647
- command: node.verify.command,
648
- excerpt: tailLines(`${verifyResult.check?.error ?? ''}\n${verifyResult.check?.stderr ?? ''}\n${verifyResult.check?.stdout ?? ''}`, 12),
649
- reason: 'identical_verify_failure',
650
- },
651
- });
652
- break;
653
- }
654
- lastVerifySignature = signature;
655
- } else {
656
- this.emit(ctx, {
657
- type: 'WorkItemCompleted',
658
- work_item_id: nodeId,
659
- attempt_id: attemptId,
660
- payload: {
661
- attempt_number: attempt,
662
- evidence: lastResult.evidence,
663
- ...(turnLimitWithWork ? { completed_by: 'verify_after_turn_limit' } : {}),
664
- },
665
- });
666
- status.set(nodeId, 'completed');
667
- completed.push(nodeId);
668
- this.recordProgress();
669
- return;
670
- }
671
- }
672
-
673
- lastError = lastResult.output || (lastResult.failure_class ?? 'unknown error');
674
-
675
- if (lastResult.failure_class === 'policy') break;
676
-
677
- if (attempt < maxAttempts) {
678
- const retryBlocked = this.consumeRetryQuota(ctx);
679
- if (retryBlocked) {
680
- this.blockNode(nodeId, ctx, status, blocked, 'quota_exceeded', retryBlocked);
681
- return;
682
- }
683
- // Exponential backoff with jitter: 1s * 2^(attempt-1) + [0, 500ms], capped at 30s
684
- const backoffMs = Math.min(
685
- 1_000 * Math.pow(2, attempt - 1) + Math.random() * 500,
686
- 30_000
687
- );
688
- await new Promise<void>(resolve => setTimeout(resolve, backoffMs));
689
- this.emit(ctx, {
690
- type: 'RetryScheduled',
691
- work_item_id: nodeId,
692
- payload: { next_attempt: attempt + 1, reason: lastResult.failure_class, backoff_ms: backoffMs, output_tail: tailLines(lastResult.output || '', 60) },
693
- });
694
- }
695
- } catch (err: unknown) {
696
- // Error boundary: isolate task failure, emit structured event, do not crash scheduler
697
- const message = err instanceof Error ? err.message : String(err);
698
- const stack = err instanceof Error ? err.stack : undefined;
699
- this.emit(ctx, {
700
- type: 'TaskErrorBoundaryTripped',
701
- work_item_id: nodeId,
702
- payload: { message, stack, attempt },
703
- });
704
- lastResult = {
705
- success: false,
706
- failure_class: 'env',
707
- evidence: [],
708
- output: `[error_boundary] ${message}`,
709
- };
710
- lastError = lastResult.output;
711
- if (attempt < maxAttempts) {
712
- const backoffMs = Math.min(1_000 * Math.pow(2, attempt - 1) + Math.random() * 500, 30_000);
713
- await new Promise<void>(resolve => setTimeout(resolve, backoffMs));
714
- this.emit(ctx, {
715
- type: 'RetryScheduled',
716
- work_item_id: nodeId,
717
- payload: { next_attempt: attempt + 1, reason: 'env', backoff_ms: backoffMs, output_tail: tailLines(lastResult.output || '', 60) },
718
- });
719
- }
720
- } finally {
721
- if (lease) {
722
- await (leaseManager ?? ctx.workspaceManager).dispose(lease.workspace_id).catch((e: unknown) =>
723
- this.emit(ctx!, { type: 'WorkspaceDisposeFailed', payload: { workspace_id: lease?.workspace_id, error: String(e) } })
724
- );
725
- lease = null;
726
- leaseManager = null;
727
- }
728
- }
729
- }
730
-
731
- this.emit(ctx, {
732
- type: 'WorkItemBlocked',
733
- work_item_id: nodeId,
734
- payload: { failure_class: verifySuspect ? 'verify_suspect' : lastResult?.failure_class ?? 'env', max_attempts: maxAttempts, output_tail: tailLines(lastResult?.output || '', 60) },
735
- });
736
- status.set(nodeId, 'failed');
737
- failed.push(nodeId);
738
- }
739
-
740
- /** Abort keeps the progress made so far: an aborted run is recoverable, not a blank slate. */
741
- private abortRun(
742
- ctx: SchedulerContext,
743
- reason: string,
744
- completed: string[],
745
- failed: string[],
746
- blocked: string[]
747
- ): RunResult {
748
- this.emit(ctx, { type: 'RunAborted', payload: { reason, completed: completed.slice(), failed: failed.slice(), blocked: blocked.slice() } });
749
- if (this.journal) {
750
- this.journal.scheduler_state = 'aborted';
751
- this.journal.completed_work_items = completed.slice();
752
- this.journal.failed_work_items = failed.slice();
753
- this.journal.blocked_work_items = blocked.slice();
754
- this.journal.partial_result = { run_id: ctx.runId, completed, failed, blocked };
755
- saveJournal(ctx.projectRoot, ctx.runId, this.journal);
756
- }
757
- return { run_id: ctx.runId, status: 'aborted', completed, failed, blocked, reason };
758
- }
759
-
760
- pause(): void {
761
- this.paused = true;
762
- if (this.journal && this.ctx) {
763
- this.journal.scheduler_state = 'paused';
764
- this.journal.paused_at = new Date().toISOString();
765
- saveJournal(this.ctx.projectRoot, this.ctx.runId, this.journal);
766
- }
767
- }
768
-
769
- resume(): void {
770
- this.paused = false;
771
- if (this.journal && this.ctx) {
772
- this.journal.scheduler_state = 'running';
773
- this.journal.paused_at = null;
774
- saveJournal(this.ctx.projectRoot, this.ctx.runId, this.journal);
775
- }
776
- }
777
-
778
- cancel(): void {
779
- this.cancelled = true;
780
- if (this.journal && this.ctx) {
781
- this.journal.cancelled = true;
782
- this.journal.scheduler_state = 'cancelled';
783
- saveJournal(this.ctx.projectRoot, this.ctx.runId, this.journal);
784
- }
785
- }
786
-
787
- getJournal(): RunJournal | null {
788
- return this.journal;
789
- }
790
-
791
- static loadJournal(projectRoot: string, runId: string): RunJournal | null {
792
- return loadJournal(projectRoot, runId);
793
- }
794
-
795
- private async executeNode(
796
- node: GraphNode,
797
- lease: WorkspaceLease,
798
- ctx: SchedulerContext,
799
- attempt: number,
800
- attemptId: string,
801
- options: { previousError?: string | null; maxTurns?: number | null } = {},
802
- ): Promise<TaskResult> {
803
- const primaryAction = pickPrimaryAction(node, ctx.pluginRegistry);
804
- const provider = primaryAction ? ctx.pluginRegistry?.toolProviderFor(primaryAction.type) : null;
805
- if (!provider || !primaryAction) {
806
- return ctx.executor.execute(node, lease, ctx.runId, attempt, options);
807
- }
808
-
809
- ctx.auditTrail?.record('plugin_invoked', ctx.policyActor ?? 'runtime', {
810
- runId: ctx.runId,
811
- workItemId: node.id,
812
- resource: provider.name,
813
- detail: { action_type: primaryAction.type, attempt_id: attemptId },
814
- });
815
- this.emit(ctx, {
816
- type: 'ToolInvoked',
817
- work_item_id: node.id,
818
- attempt_id: attemptId,
819
- payload: { provider: provider.name, action_type: primaryAction.type },
820
- });
821
-
822
- const invocationInput = {
823
- action_type: primaryAction.type,
824
- work_item_id: node.id,
825
- run_id: ctx.runId,
826
- attempt_id: attemptId,
827
- params: {
828
- command: primaryAction.command ?? null,
829
- targets: primaryAction.targets ?? [],
830
- },
831
- workspace_root: lease.root_path,
832
- };
833
-
834
- if (provider.preInvoke) {
835
- const preCheck = await provider.preInvoke(invocationInput);
836
- if (!preCheck.allowed) {
837
- this.emit(ctx, {
838
- type: 'ToolFailed',
839
- work_item_id: node.id,
840
- attempt_id: attemptId,
841
- payload: { provider: provider.name, action_type: primaryAction.type, error: preCheck.reason ?? 'pre_invoke blocked', evidence_paths: [], side_effects_applied: [] },
842
- });
843
- return { success: false, failure_class: 'policy', evidence: [], output: preCheck.reason ?? 'pre_invoke blocked' };
844
- }
845
- }
846
-
847
- const result = await provider.invoke(invocationInput);
848
-
849
- if (provider.postInvoke) {
850
- await provider.postInvoke(invocationInput, result).catch(() => {});
851
- }
852
-
853
- this.emit(ctx, {
854
- type: result.success ? 'ToolCompleted' : 'ToolFailed',
855
- work_item_id: node.id,
856
- attempt_id: attemptId,
857
- payload: {
858
- provider: provider.name,
859
- action_type: primaryAction.type,
860
- evidence_paths: result.evidence_paths,
861
- side_effects_applied: result.side_effects_applied,
862
- error: result.error ?? null,
863
- },
864
- });
865
-
866
- return {
867
- success: result.success,
868
- failure_class: result.success ? null : provider.kind === 'external_operation' ? 'policy' : 'env',
869
- evidence: result.evidence_paths,
870
- output: result.output,
871
- };
872
- }
873
-
874
- private async verifyNode(
875
- node: GraphNode,
876
- lease: WorkspaceLease,
877
- ctx: SchedulerContext,
878
- attemptId: string,
879
- attempt: number,
880
- ): Promise<{ status: string; gaps?: string[]; check?: CheckResult } | null> {
881
- if (!node.verify?.command) return null;
882
- this.emit(ctx, {
883
- type: 'VerificationStarted',
884
- work_item_id: node.id,
885
- payload: { command: node.verify.command, attempt_number: attempt },
886
- });
887
- const suite: AcceptanceCheckSuite = {
888
- checks: [{
889
- id: `inline-${node.id}`,
890
- type: 'custom',
891
- command: node.verify.command,
892
- evidence_type_expected: 'stdout',
893
- acceptance_ref: null,
894
- description: `Verify ${node.id}`,
895
- }],
896
- compiled_at: new Date().toISOString(),
897
- spec_hash: '',
898
- plan_hash: '',
899
- };
900
- let result: { status: string; gaps?: string[]; check_results?: CheckResult[] };
901
- try {
902
- result = await verifyRun({
903
- suite,
904
- cwd: lease.root_path,
905
- timeoutMs: (ctx.options as Record<string, unknown>)?.verifyTimeoutMs as number ?? 60_000,
906
- runId: ctx.runId,
907
- workItemId: node.id,
908
- attemptNumber: attempt,
909
- projectRoot: ctx.projectRoot,
910
- pluginRegistry: ctx.pluginRegistry,
911
- });
912
- } catch (err) {
913
- this.emit(ctx, {
914
- type: 'VerificationCompleted',
915
- work_item_id: node.id,
916
- attempt_id: attemptId,
917
- payload: { status: 'error', error: String(err) },
918
- });
919
- return null;
920
- }
921
- this.emit(ctx, {
922
- type: 'VerificationCompleted',
923
- work_item_id: node.id,
924
- attempt_id: attemptId,
925
- payload: { status: result.status },
926
- });
927
- return { status: result.status, gaps: result.gaps, check: result.check_results?.[0] };
928
- }
929
-
930
- private evaluatePolicyForNode(node: GraphNode, ctx: SchedulerContext): PersistedPolicyDecision | null {
931
- if (!ctx.policyEngine) return null;
932
- const primaryAction = pickPrimaryAction(node, ctx.pluginRegistry);
933
- const decisionContext: PolicyContext = {
934
- tool: primaryAction?.type ?? 'custom',
935
- kind: node.workspace_strategy,
936
- mutation_scope: node.mutation_scope,
937
- affected_paths: node.mutation_scope,
938
- side_effect_class: inferSideEffectClass(node),
939
- mutation_count: node.mutation_scope.length,
940
- node_policy: {
941
- max_retries: node.policy.max_retries,
942
- },
943
- };
944
- const evaluated = ctx.policyEngine.evaluate(decisionContext);
945
- const persisted: PersistedPolicyDecision = {
946
- ...evaluated,
947
- run_id: ctx.runId,
948
- work_item_id: node.id,
949
- action: primaryAction?.type ?? 'custom',
950
- actor: ctx.policyActor ?? 'runtime',
951
- override: false,
952
- rationale: null,
953
- context: decisionContext,
954
- };
955
- savePolicyDecision(ctx.projectRoot, persisted);
956
- return persisted;
957
- }
958
-
959
- /** An approval already granted for this node in this run must not be requested again on re-execution. */
960
- private hasApprovedGate(node: GraphNode, ctx: SchedulerContext): boolean {
961
- if (!ctx.gateManager) return false;
962
- return ctx.gateManager
963
- .listResolved()
964
- .some((gate) => gate.work_item_id === node.id && gate.decision === 'approved' && (gate.run_id == null || gate.run_id === ctx.runId));
965
- }
966
-
967
- private async requestGateForNode(
968
- node: GraphNode,
969
- ctx: SchedulerContext,
970
- decision: PersistedPolicyDecision | null
971
- ): Promise<string> {
972
- if (!ctx.gateManager) {
973
- console.warn('[scheduler] ctx.gateManager not configured — gates will not be persisted');
974
- return 'gate-missing-manager';
975
- }
976
- const scope = inferGateScope(node);
977
- const primaryAction = pickPrimaryAction(node, ctx.pluginRegistry);
978
- const gate = await ctx.gateManager.request(scope, {
979
- run_id: ctx.runId,
980
- work_item_id: node.id,
981
- action: primaryAction?.type ?? 'custom',
982
- description: `Gate required before executing ${node.id}`,
983
- evidence_refs: [],
984
- risks: [decision?.reason ?? node.policy.gate_reason ?? 'human approval required'],
985
- rationale: decision?.reason ?? node.policy.gate_reason ?? 'node policy requires approval',
986
- policy_decision_id: decision?.decision_id ?? null,
987
- });
988
- if (this.journal && !this.journal.pending_gates.includes(gate.gate_id)) {
989
- this.journal.pending_gates.push(gate.gate_id);
990
- }
991
- ctx.auditTrail?.record('gate_requested', ctx.policyActor ?? 'runtime', {
992
- runId: ctx.runId,
993
- workItemId: node.id,
994
- detail: { gate_id: gate.gate_id, scope: gate.scope, action: gate.action },
995
- });
996
- return gate.gate_id;
997
- }
998
-
999
- /**
1000
- * A node delivered by another path (`verify_only`) or waiting on external work (`external_dependency`): no agent.
1001
- * verify_only runs only the node's verify — green completes it; red (or no verify) leaves it waiting. A node with an
1002
- * external dependency and no verify_only waits without a gate, so the rest of the run (and the next preflight) goes on.
1003
- */
1004
- private async runExternalNode(
1005
- node: GraphNode,
1006
- ctx: SchedulerContext,
1007
- status: Map<string, NodeStatus>,
1008
- completed: string[],
1009
- failed: string[],
1010
- blocked: string[]
1011
- ): Promise<void> {
1012
- const deps = node.policy.external_dependency ?? [];
1013
- if (node.policy.verify_only && node.verify?.command) {
1014
- const attemptId = `${node.id}-verify-only`;
1015
- const workspaceManager = ctx.pluginRegistry?.workspaceProviderFor(node.workspace_strategy) ?? ctx.workspaceManager;
1016
- const lease = await workspaceManager.allocate({ work_item_id: node.id, attempt_number: 1, strategy: node.workspace_strategy, mutation_scope: node.mutation_scope });
1017
- try {
1018
- const verdict = await this.verifyNode(node, lease, ctx, attemptId, 1);
1019
- if (verdict && verdict.status !== 'failed') {
1020
- this.emit(ctx, {
1021
- type: 'WorkItemCompleted',
1022
- work_item_id: node.id,
1023
- attempt_id: attemptId,
1024
- payload: { attempt_number: 1, evidence: [], completed_by: 'verify_only', external_dependency: deps },
1025
- });
1026
- status.set(node.id, 'completed');
1027
- completed.push(node.id);
1028
- this.recordProgress();
1029
- return;
1030
- }
1031
- } finally {
1032
- await workspaceManager.dispose(lease.workspace_id).catch(() => undefined);
1033
- }
1034
- }
1035
- this.blockNode(node.id, ctx, status, blocked, 'external_dependency', deps.length ? deps.join(', ') : 'verify_only: entrega externa ainda não verificada');
1036
- void failed;
1037
- }
1038
-
1039
- private blockNode(
1040
- nodeId: string,
1041
- ctx: SchedulerContext,
1042
- status: Map<string, NodeStatus>,
1043
- blocked: string[],
1044
- reason: string,
1045
- detail: string | QuotaViolation | null = null
1046
- ): void {
1047
- this.emit(ctx, {
1048
- type: 'WorkItemBlocked',
1049
- work_item_id: nodeId,
1050
- payload: { reason, detail },
1051
- });
1052
- status.set(nodeId, 'blocked');
1053
- if (!blocked.includes(nodeId)) blocked.push(nodeId);
1054
- }
1055
-
1056
- private consumeQuotaForNode(ctx: SchedulerContext, node: GraphNode): string | null {
1057
- if (!ctx.quota) return null;
1058
- let quota = consumeQuota(ctx.quota, 'work_items', 1);
1059
- if (node.mutation_scope.length > 0) {
1060
- quota = consumeQuota(quota, 'mutations', 1);
1061
- }
1062
- const violation = checkQuota(quota);
1063
- ctx.quota = quota;
1064
- return violation ? `${violation.quota_type}:${violation.consumed}/${violation.limit}` : null;
1065
- }
1066
-
1067
- private consumeRetryQuota(ctx: SchedulerContext): string | null {
1068
- if (!ctx.quota) return null;
1069
- ctx.quota = consumeQuota(ctx.quota, 'retries', 1);
1070
- const violation = checkQuota(ctx.quota);
1071
- return violation ? `${violation.quota_type}:${violation.consumed}/${violation.limit}` : null;
1072
- }
1073
-
1074
- private emit(
1075
- ctx: SchedulerContext,
1076
- input: EventInput
1077
- ): void {
1078
- const event = appendEvent(ctx.projectRoot, ctx.sessionId, {
1079
- run_id: ctx.runId,
1080
- ...input,
1081
- });
1082
- ctx.onEvent?.(event);
1083
- }
1084
- }
1085
-
1086
- const RECOVERABLE_JOURNAL_STATES = new Set<RunJournal['scheduler_state']>(['paused', 'interrupted', 'blocked', 'aborted', 'failed']);
1087
-
1088
- /** Nodes whose actions may write to the workspace (anything beyond reading and collecting evidence). */
1089
- function nodeMayMutate(node: GraphNode): boolean {
1090
- return node.actions.some((action) => action.type !== 'read_code' && action.type !== 'collect_evidence');
1091
- }
1092
-
1093
- function inferSideEffectClass(node: GraphNode): PolicyContext['side_effect_class'] {
1094
- if (node.mutation_scope.length > 0) return 'write_fs';
1095
- if (node.actions.some((action) => action.type === 'run_tests' || action.type === 'run_lint')) return 'spawn_process';
1096
- return 'read_fs';
1097
- }
1098
-
1099
- function pickPrimaryAction(node: GraphNode, pluginRegistry?: PluginRegistry): GraphNode['actions'][number] | undefined {
1100
- const candidateActions = node.actions.filter((action) => action.type !== 'collect_evidence');
1101
- const preferredMutation = candidateActions.find((action) => action.type === 'generate_patch')
1102
- || candidateActions.find((action) => action.type === 'run_tests')
1103
- || candidateActions[0];
1104
- if (!pluginRegistry) return preferredMutation;
1105
- return candidateActions.find((action) => pluginRegistry.toolProviderFor(action.type)) || preferredMutation;
1106
- }
1107
-
1108
- function inferGateScope(node: GraphNode): 'critical_mutation' | 'security' | 'plan_approval' {
1109
- if (node.mutation_scope.length > 0) return 'critical_mutation';
1110
- if (node.actions.some((action) => action.type === 'collect_evidence')) return 'security';
1111
- return 'plan_approval';
1112
- }
1113
-
1114
- /** Last `n` non-empty lines of a text. */
1115
- export function tailLines(text: string, n: number): string {
1116
- return String(text || '').split(/\r?\n/).map((l) => l.trimEnd()).filter((l) => l.trim()).slice(-n).join('\n');
1117
- }
1118
-
1119
- /** What the next attempt needs to know about a failed task verify (1.20c informed retry). */
1120
- export function describeVerifyFailure(command: string | null | undefined, check: CheckResult | undefined, gaps?: string[]): string {
1121
- const reason = check?.error || (check?.exit_code != null ? `exit code ${check.exit_code}` : (gaps || []).join('; ') || 'checks did not pass');
1122
- const output = tailLines(`${check?.stdout ?? ''}\n${check?.stderr ?? ''}`, 40);
1123
- return [
1124
- 'Verification failed after your previous attempt.',
1125
- `Command: ${command ?? '(none)'}`,
1126
- `Reason: ${reason}`,
1127
- output ? `Output (last lines):\n${output.slice(-4000)}` : 'Output: (empty)',
1128
- 'Fix the code so this exact command passes. If you are certain the command itself is wrong (not the code), stop and call finish_task explaining why — do not work around it.',
1129
- ].join('\n');
1130
- }
1131
-
1132
- /** Normalized failure fingerprint: timings, timestamps, hashes and temp paths removed. */
1133
- export function verifyFailureSignature(check: CheckResult | undefined): string | null {
1134
- if (!check) return null;
1135
- const raw = `${check.error ?? ''}\n${check.stderr ?? ''}\n${check.stdout ?? ''}`;
1136
- const normalized = raw
1137
- .replace(/\d{4}-\d{2}-\d{2}T[\d:.]+Z?/g, '<ts>')
1138
- .replace(/\b\d+(\.\d+)?\s?(ms|s)\b/g, '<t>')
1139
- .replace(/\b[0-9a-f]{7,64}\b/gi, '<hash>')
1140
- .replace(/[A-Za-z]:\\[^\s'"]*|\/tmp\/[^\s'"]*/g, '<path>')
1141
- .replace(/\s+/g, ' ')
1142
- .trim();
1143
- return normalized ? normalized.slice(-1200) : null;
1144
- }
1
+ import path from 'path';
2
+ import { PROVIDER_QUOTA_RE } from '../executor/quota-patterns';
3
+ import fs from 'fs';
4
+ import { appendEvent } from '../events/bus';
5
+ import type { OxeEvent } from '../events/envelope';
6
+ import type { EventInput } from '../events/bus';
7
+ import type { ExecutionGraph, GraphNode } from '../compiler/graph-compiler';
8
+ import type { WorkspaceManager, WorkspaceRequest } from '../workspace/workspace-manager';
9
+ import type { WorkspaceLease } from '../models/workspace';
10
+ import type { GateManager } from '../gate/gate-manager';
11
+ import type { PolicyEngine, PersistedPolicyDecision, PolicyContext } from '../policy/policy-engine';
12
+ import { savePolicyDecision } from '../policy/policy-engine';
13
+ import type { PluginRegistry } from '../plugins/plugin-registry';
14
+ import type { AuditTrail } from '../audit/audit-trail';
15
+ import type { RunQuota, QuotaViolation } from '../audit/audit-trail';
16
+ import { checkQuota, consumeQuota } from '../audit/audit-trail';
17
+ import {
18
+ saveJournal,
19
+ loadJournal,
20
+ deleteJournal,
21
+ createJournal,
22
+ } from './run-journal';
23
+ import type { RunJournal } from './run-journal';
24
+ import type { FailureClass } from '../models/failure';
25
+ import { listMemos } from '../decision/decision-memo';
26
+ import type { RollbackPlan } from '../decision/decision-memo';
27
+ import { runCapabilityAsync } from '../plugins/capability-adapter';
28
+ import { verifyRun } from '../verification/verification-compiler';
29
+ import type { AcceptanceCheckSuite, CheckResult } from '../verification/verification-compiler';
30
+
31
+ export interface TaskResult {
32
+ success: boolean;
33
+ failure_class: FailureClass;
34
+ evidence: string[];
35
+ output: string;
36
+ completed_by?: string;
37
+ /** OXB-185: turns used and the cap of the attempt, when it ended at the cap. */
38
+ turns_used?: number;
39
+ turns_cap?: number;
40
+ /** OXB-C28-1: a policy refusal whose trigger came from tool outputs of earlier turns (not from the pack). */
41
+ policy_trigger?: 'tool_output' | 'prompt';
42
+ /** Every verify segment's output with headers (1.21.2, OXB-066), for the attempt log. */
43
+ verify_log?: string;
44
+ }
45
+
46
+ export interface TaskExecutor {
47
+ execute(
48
+ node: GraphNode,
49
+ lease: WorkspaceLease,
50
+ runId: string,
51
+ attemptNumber: number,
52
+ options?: { previousError?: string | null; maxTurns?: number | null; model?: string | null }
53
+ ): Promise<TaskResult>;
54
+ }
55
+
56
+ /**
57
+ * Turn/cost ceiling of a run (1.21, OXB-023), kept by the caller from the executor's usage. The scheduler checks it
58
+ * between attempts — never killing one mid-way — and caps the next attempt to the turns that are left, so the run
59
+ * cannot go past the turn ceiling.
60
+ */
61
+ export interface RunBudget {
62
+ /** Why no further attempt may start, or null while there is budget. */
63
+ exhausted(): string | null;
64
+ /** Turns still allowed (the next attempt's cap), or null when turns are unlimited. */
65
+ remainingTurns(): number | null;
66
+ }
67
+
68
+ export interface SchedulerOptions {
69
+ /** OXB-155: per-segment timeout of the task verify (the caller passes config verify_timeout_ms; default 10 min). */
70
+ verifyTimeoutMs?: number;
71
+ /**
72
+ * OXB-171: per task, the files its frozen acceptance tests import/read that are outside its `files` (from the
73
+ * plan lint), and those tests. A verify failure that names one of the tests stops after attempt 1 as
74
+ * `scope_insufficient` instead of retrying a task that cannot pass.
75
+ */
76
+ outOfScopeRequirements?: Record<string, { files: string[]; tests: string[] }>;
77
+ /** OXB-120: project patterns (regex sources) added to the built-in environment / quota classifiers. */
78
+ failureClasses?: { environment?: string[]; quota?: string[] };
79
+ /**
80
+ * OxeSpace 15/11 (Celular F3 T9): a refusal by the model's usage policy is never retried automatically — but a
81
+ * classifier false positive passed on a plain retry before. With this (runtime execute --retry-policy-once, chosen by
82
+ * a person) each task gets ONE more attempt after a policy refusal, even past its max_retries.
83
+ */
84
+ retryPolicyOnce?: boolean;
85
+ /** OXB-C28-1: one automatic clean retry for a refusal triggered by tool outputs (default on; false = off). */
86
+ policyAutoRetry?: boolean;
87
+ /** Tasks this run already saw refused by policy (a later execute): their attempt 1 IS the one extra attempt. */
88
+ policyRefusedBefore?: string[];
89
+ /** Tasks whose one extra policy attempt was already spent in this run: blocked before any attempt (no model call). */
90
+ policyRetryExhausted?: string[];
91
+ /**
92
+ * OXB-138: a task that exhausts its attempts is DEFERRED and the run goes on with every task that does not depend on
93
+ * it (its dependents end `blocked_by_deferred`). false keeps the old stop-at-the-failed-wave behavior.
94
+ */
95
+ deferFailed?: boolean;
96
+ /**
97
+ * OXB-129: `stream` dispatches a task as soon as all its declared dependencies completed (not when its whole wave
98
+ * did), within the parallel limits; a task whose scope overlaps a running one (hot file) waits. `wave` (default)
99
+ * keeps the wave barrier. The wave becomes a reading grouping only in stream mode.
100
+ */
101
+ dispatch?: 'wave' | 'stream';
102
+ maxRunDurationMs?: number; // default: 30 min
103
+ staleProgressMs?: number; // default: 5 min without any task completing
104
+ /** OXB-204: max automatic wait (ms) on 429 / rate-limit reset before pausing as quota (default: 5 min). */
105
+ maxQuotaWaitMs?: number;
106
+ /** OXB-204: max consecutive automatic 429 waits per attempt before pausing as quota (default: 3). */
107
+ maxQuotaWaits?: number;
108
+ /** OXB-C1 (#6): run every top-level `&&` verify segment and report all red segments at once instead of stopping at the first failure. */
109
+ allSegments?: boolean;
110
+ /** Injectable sleep for deterministic tests. */
111
+ sleep?: (ms: number) => Promise<void>;
112
+ }
113
+
114
+ /** OXB-050: what integrating a worktree's work into the program checkout did. */
115
+ export interface ParallelIntegration {
116
+ ok: boolean;
117
+ /** In-scope files copied into the program checkout (relative paths). */
118
+ files: string[];
119
+ /** Files the attempt changed outside its mutation_scope (never copied). */
120
+ outside: string[];
121
+ error?: string;
122
+ }
123
+
124
+ /**
125
+ * OXB-050 (opt-in `--parallel-mutating`): the mutating nodes of a wave with disjoint `mutation_scope` run at the same
126
+ * time, each in its own isolated workspace (`manager`, a git worktree with prepared dependencies). A node whose verify
127
+ * passes there is integrated into the program checkout under a lock — in-scope files only — and verified again on the
128
+ * integrated tree before it completes. Concurrency is bounded by `maxParallel` and by free memory per agent.
129
+ */
130
+ export interface ParallelMutatingOptions {
131
+ maxParallel: number;
132
+ /** Free memory (MB) required to START another parallel node (one always runs). */
133
+ minFreeMb?: number;
134
+ freeMb?: () => number;
135
+ manager: WorkspaceManager;
136
+ integrate: (node: GraphNode, lease: WorkspaceLease) => ParallelIntegration | Promise<ParallelIntegration>;
137
+ /** Undo an integration whose verify on the integrated tree failed. */
138
+ discard: (files: string[]) => void | Promise<void>;
139
+ }
140
+
141
+ /** Two scopes may touch the same file: equal paths, one a directory prefix of the other, or a glob in either. */
142
+ export function scopesOverlap(a: string[], b: string[]): boolean {
143
+ if (!a.length || !b.length) return true;
144
+ const norm = (p: string) => String(p).replace(/\\/g, '/').replace(/\/+$/, '');
145
+ const base = (p: string) => norm(p).split(/[*?[{]/)[0].replace(/\/[^/]*$/, (m) => (/[*?[{]/.test(norm(p)) ? '' : m));
146
+ for (const x of a) {
147
+ for (const y of b) {
148
+ const nx = norm(x);
149
+ const ny = norm(y);
150
+ if (nx === ny) return true;
151
+ const gx = /[*?[{]/.test(nx);
152
+ const gy = /[*?[{]/.test(ny);
153
+ const px = gx ? base(nx) : nx;
154
+ const py = gy ? base(ny) : ny;
155
+ if (!px || !py) return true;
156
+ if (px === py || px.startsWith(`${py}/`) || py.startsWith(`${px}/`)) return true;
157
+ }
158
+ }
159
+ return false;
160
+ }
161
+
162
+ export interface SchedulerContext {
163
+ /**
164
+ * OXB-184: what the previous attempt of a task changed in the tree (paths, binary or not) and whether it is still
165
+ * there — appended to the informed retry, so the next attempt does not redo (or wrongly assume) work.
166
+ */
167
+ attemptChanges?: (nodeId: string) => { kept: string[]; gone: string[] } | null;
168
+ /** OXB-185: the turns of an attempt of this task (sized to it); the provider's maxTurns stays the upper bound. */
169
+ turnsFor?: (nodeId: string, attempt: number, lastFailureClass: string | null) => number | null;
170
+ /**
171
+ * OXB-131: the model of an attempt. Receives the attempt number and the previous attempt's failure class; the
172
+ * orchestrator applies override > tier escalation > the task's hint. Null keeps the executor's default.
173
+ */
174
+ modelFor?: (nodeId: string, attempt: number, lastFailureClass: string | null) => { model: string | null; tier: string | null; escalated?: boolean } | null;
175
+ /**
176
+ * OXB-130: the repair strategy before a retry. `retry` carries the adjustment (appended to the informed retry);
177
+ * any other strategy stops the attempts and blocks the node as `repair_<strategy>` (the orchestrator acts on it).
178
+ */
179
+ repairFor?: (nodeId: string, info: { attempt: number; maxAttempts: number; failureClass: string | null; output: string; verifySuspect: boolean }) => { strategy: string; reason: string; adjustment: string | null } | null;
180
+ projectRoot: string;
181
+ sessionId: string | null;
182
+ runId: string;
183
+ executor: TaskExecutor;
184
+ workspaceManager: WorkspaceManager;
185
+ gateManager?: GateManager;
186
+ policyEngine?: PolicyEngine;
187
+ pluginRegistry?: PluginRegistry;
188
+ auditTrail?: AuditTrail;
189
+ quota?: RunQuota;
190
+ budget?: RunBudget;
191
+ /**
192
+ * OxeSpace 14/11: a `runtime pause` from another process. Checked before every node starts: the task in progress
193
+ * finishes, the next one never starts. Returns the reason when a pause was requested, else null.
194
+ */
195
+ pauseRequested?: () => string | null;
196
+ policyActor?: string;
197
+ onEvent?: (event: OxeEvent) => void;
198
+ options?: SchedulerOptions;
199
+ parallel?: ParallelMutatingOptions;
200
+ }
201
+
202
+ export interface RunResult {
203
+ run_id: string;
204
+ status: 'completed' | 'failed' | 'blocked' | 'cancelled' | 'paused' | 'aborted';
205
+ completed: string[];
206
+ failed: string[];
207
+ blocked: string[];
208
+ pending_gates?: string[];
209
+ reason?: string;
210
+ }
211
+
212
+ type NodeStatus = 'pending' | 'ready' | 'running' | 'completed' | 'failed' | 'blocked';
213
+
214
+ export class Scheduler {
215
+ private cancelled = false;
216
+ private paused = false;
217
+ private journal: RunJournal | null = null;
218
+ private ctx: SchedulerContext | null = null;
219
+ private runStartMs = 0;
220
+ private lastProgressMs = 0;
221
+
222
+ private recordProgress(): void {
223
+ this.lastProgressMs = Date.now();
224
+ }
225
+
226
+ /** OXB-050: integrations into the program checkout happen one at a time (copy, verify, checkpoint). */
227
+ private integrationChain: Promise<unknown> = Promise.resolve();
228
+ private withIntegrationLock<T>(fn: () => Promise<T>): Promise<T> {
229
+ const run = this.integrationChain.then(fn, fn);
230
+ this.integrationChain = run.catch(() => undefined);
231
+ return run;
232
+ }
233
+
234
+ private async executeRollback(plan: RollbackPlan, ctx: SchedulerContext): Promise<void> {
235
+ try {
236
+ switch (plan.strategy) {
237
+ case 'revert_commit':
238
+ await runCapabilityAsync('git', ['revert', 'HEAD', '--no-edit'], {}, ctx.projectRoot, 30_000);
239
+ break;
240
+ case 'restore_workspace':
241
+ await runCapabilityAsync('git', ['checkout', '.'], {}, ctx.projectRoot, 30_000);
242
+ break;
243
+ case 'undo_patch':
244
+ for (const p of plan.steps) {
245
+ await runCapabilityAsync('git', ['checkout', 'HEAD', '--', p], {}, ctx.projectRoot, 10_000);
246
+ }
247
+ break;
248
+ case 'no_rollback':
249
+ default:
250
+ break;
251
+ }
252
+ this.emit(ctx, { type: 'RollbackExecuted', payload: { strategy: plan.strategy } });
253
+ } catch (err) {
254
+ this.emit(ctx, { type: 'RollbackFailed', payload: { strategy: plan.strategy, error: String(err) } });
255
+ }
256
+ }
257
+
258
+ async run(graph: ExecutionGraph, ctx: SchedulerContext): Promise<RunResult> {
259
+ this.cancelled = false;
260
+ this.paused = false;
261
+ this.ctx = ctx;
262
+ this.runStartMs = Date.now();
263
+ this.lastProgressMs = Date.now();
264
+
265
+ const status = new Map<string, NodeStatus>();
266
+ for (const id of graph.nodes.keys()) status.set(id, 'pending');
267
+
268
+ const completed: string[] = [];
269
+ const failed: string[] = [];
270
+ const blocked: string[] = [];
271
+
272
+ // Plan hash drift detection: abort if the graph was recompiled since ACTIVE-RUN was saved
273
+ const activeRunPath = ctx.sessionId
274
+ ? path.join(ctx.projectRoot, '.oxe', ctx.sessionId, 'execution', 'ACTIVE-RUN.json')
275
+ : path.join(ctx.projectRoot, '.oxe', 'ACTIVE-RUN.json');
276
+ if (fs.existsSync(activeRunPath)) {
277
+ try {
278
+ const activeRun = JSON.parse(fs.readFileSync(activeRunPath, 'utf8')) as Record<string, unknown>;
279
+ const savedHash = activeRun.plan_hash as string | undefined;
280
+ const currentHash = graph.metadata.plan_hash;
281
+ if (savedHash && savedHash !== currentHash) {
282
+ return {
283
+ run_id: ctx.runId,
284
+ status: 'aborted',
285
+ completed: [],
286
+ failed: [],
287
+ blocked: [],
288
+ reason: `plan_drift: graph recompiled (${savedHash} → ${currentHash}). Run /oxe-plan --replan to realign.`,
289
+ };
290
+ }
291
+ } catch {
292
+ // ACTIVE-RUN not parseable — continue without drift check
293
+ }
294
+ }
295
+
296
+ this.journal = createJournal(ctx.runId);
297
+ saveJournal(ctx.projectRoot, ctx.runId, this.journal);
298
+
299
+ this.emit(ctx, { type: 'RunStarted', payload: { run_id: ctx.runId } });
300
+ ctx.auditTrail?.record('run_started', ctx.policyActor ?? 'runtime', {
301
+ runId: ctx.runId,
302
+ detail: { session_id: ctx.sessionId ?? null },
303
+ });
304
+
305
+ const maxRunMs = ctx.options?.maxRunDurationMs ?? 30 * 60_000;
306
+ const staleMs = ctx.options?.staleProgressMs ?? 5 * 60_000;
307
+
308
+ // OXB-129: stream dispatch — no wave barrier.
309
+ if ((ctx.options as SchedulerOptions | undefined)?.dispatch === 'stream') {
310
+ await this.runStream(graph, ctx, status, completed, failed, blocked, maxRunMs);
311
+ }
312
+
313
+ for (const wave of (ctx.options as SchedulerOptions | undefined)?.dispatch === 'stream' ? [] : graph.waves) {
314
+ if (this.cancelled) break;
315
+
316
+ // Global run timeout
317
+ if (Date.now() - this.runStartMs > maxRunMs) {
318
+ return this.abortRun(ctx, 'global_timeout', completed, failed, blocked);
319
+ }
320
+
321
+ // Stale progress timeout (no task completed in staleMs)
322
+ if (Date.now() - this.lastProgressMs > staleMs) {
323
+ return this.abortRun(ctx, 'no_progress_timeout', completed, failed, blocked);
324
+ }
325
+
326
+ // Respect pause: persist journal and return paused result
327
+ if (this.paused) {
328
+ this.journal.scheduler_state = 'paused';
329
+ this.journal.paused_at = new Date().toISOString();
330
+ this.journal.completed_work_items = completed.slice();
331
+ this.journal.failed_work_items = failed.slice();
332
+ this.journal.blocked_work_items = blocked.slice();
333
+ this.journal.partial_result = { run_id: ctx.runId, completed, failed, blocked };
334
+ saveJournal(ctx.projectRoot, ctx.runId, this.journal);
335
+ ctx.auditTrail?.record('run_paused', ctx.policyActor ?? 'runtime', {
336
+ runId: ctx.runId,
337
+ detail: { completed, failed, blocked },
338
+ });
339
+ return { run_id: ctx.runId, status: 'paused', completed, failed, blocked, pending_gates: this.journal.pending_gates.slice() };
340
+ }
341
+
342
+ // OXB-138: a task depending (transitively) on a failed/deferred or blocked one does not run.
343
+ const deferMode = (ctx.options as SchedulerOptions | undefined)?.deferFailed === true;
344
+ let waveIds = wave.node_ids;
345
+ if (deferMode) {
346
+ waveIds = [];
347
+ for (const id of wave.node_ids) {
348
+ const n = graph.nodes.get(id);
349
+ const bad = (n?.depends_on ?? []).find((d) => status.get(d) === 'failed' || status.get(d) === 'blocked');
350
+ if (bad && status.get(id) === 'pending') this.blockNode(id, ctx, status, blocked, 'blocked_by_deferred', bad);
351
+ else waveIds.push(id);
352
+ }
353
+ }
354
+ const failedBefore = failed.length;
355
+ const waveFailed = await this.runWave(
356
+ waveIds,
357
+ graph,
358
+ ctx,
359
+ status,
360
+ completed,
361
+ failed,
362
+ blocked
363
+ );
364
+ if (deferMode) {
365
+ for (const id of failed.slice(failedBefore)) this.emit(ctx, { type: 'WorkItemDeferred', work_item_id: id, payload: { task: id } });
366
+ // OXB-C28-1: a deferred task is a decision of the run, not a stall — without this a wave whose only task was
367
+ // deferred after > staleProgressMs aborted the run (no_progress_timeout) and took the independent tasks along
368
+ if (failed.length > failedBefore || waveIds.some((id) => status.get(id) === 'blocked')) this.recordProgress();
369
+ }
370
+
371
+ // Sync journal after each wave
372
+ this.journal.completed_work_items = completed.slice();
373
+ this.journal.failed_work_items = failed.slice();
374
+ this.journal.blocked_work_items = blocked.slice();
375
+ saveJournal(ctx.projectRoot, ctx.runId, this.journal);
376
+
377
+ if (waveFailed && !deferMode) {
378
+ // Execute rollback plan if one was created for this run
379
+ const memos = listMemos(ctx.projectRoot, ctx.runId);
380
+ for (const memo of memos) {
381
+ if (memo.rollback_plan.strategy !== 'no_rollback') {
382
+ await this.executeRollback(memo.rollback_plan, ctx);
383
+ break; // apply at most one rollback plan per wave failure
384
+ }
385
+ }
386
+ break;
387
+ }
388
+ }
389
+
390
+ // Any remaining pending nodes become blocked — not on a pause: they are the work the resume picks up (OxeSpace
391
+ // 15/11, OxeCode F4: a requested pause after T17 marked T18 "upstream_wave_failed" and printed FAIL)
392
+ for (const [id, s] of status) {
393
+ if (s === 'pending' && !this.paused) {
394
+ status.set(id, 'blocked');
395
+ blocked.push(id);
396
+ this.emit(ctx, {
397
+ type: 'WorkItemBlocked',
398
+ work_item_id: id,
399
+ payload: { reason: 'upstream_wave_failed' },
400
+ });
401
+ }
402
+ }
403
+
404
+ const finalStatus: RunResult['status'] = this.cancelled
405
+ ? 'cancelled'
406
+ : this.paused // OXB-120: paused inside the last wave (environment / quota)
407
+ ? 'paused'
408
+ : failed.length > 0
409
+ ? 'failed'
410
+ : blocked.length > 0
411
+ ? 'blocked'
412
+ : 'completed';
413
+
414
+ this.emit(ctx, {
415
+ type: 'RunCompleted',
416
+ payload: { run_id: ctx.runId, status: finalStatus },
417
+ });
418
+ ctx.auditTrail?.record('run_completed', ctx.policyActor ?? 'runtime', {
419
+ runId: ctx.runId,
420
+ detail: {
421
+ status: finalStatus,
422
+ completed: completed.length,
423
+ failed: failed.length,
424
+ blocked: blocked.length,
425
+ pending_gates: this.journal.pending_gates.slice(),
426
+ },
427
+ });
428
+
429
+ this.journal.scheduler_state = this.cancelled
430
+ ? 'cancelled'
431
+ : finalStatus === 'blocked' || finalStatus === 'failed'
432
+ ? finalStatus
433
+ : 'completed';
434
+ this.journal.completed_work_items = completed.slice();
435
+ this.journal.failed_work_items = failed.slice();
436
+ this.journal.blocked_work_items = blocked.slice();
437
+ saveJournal(ctx.projectRoot, ctx.runId, this.journal);
438
+
439
+ return {
440
+ run_id: ctx.runId,
441
+ status: finalStatus,
442
+ completed,
443
+ failed,
444
+ blocked,
445
+ pending_gates: this.journal.pending_gates.slice(),
446
+ };
447
+ }
448
+
449
+ /**
450
+ * Recover a previously paused run by loading its journal and re-running
451
+ * only the work items that haven't completed yet.
452
+ */
453
+ async recover(runId: string, ctx: SchedulerContext, graph: ExecutionGraph): Promise<RunResult | null> {
454
+ const journal = loadJournal(ctx.projectRoot, runId);
455
+ // Paused, blocked (gates since approved), aborted (timeout) and failed runs can all be resumed;
456
+ // only completed/cancelled runs have nothing left to do.
457
+ if (!journal || !RECOVERABLE_JOURNAL_STATES.has(journal.scheduler_state)) return null;
458
+
459
+ // Restore state from journal
460
+ this.cancelled = false;
461
+ this.paused = false;
462
+ this.ctx = ctx;
463
+ this.journal = { ...journal, scheduler_state: 'running', paused_at: null };
464
+
465
+ const restoredCompleted = new Set(journal.completed_work_items);
466
+ const restoredFailed = new Set(journal.failed_work_items);
467
+ const restoredBlocked = new Set(journal.blocked_work_items);
468
+
469
+ const status = new Map<string, NodeStatus>();
470
+ for (const id of graph.nodes.keys()) {
471
+ if (restoredCompleted.has(id)) status.set(id, 'completed');
472
+ else if (restoredFailed.has(id)) status.set(id, 'failed');
473
+ else if (restoredBlocked.has(id)) status.set(id, 'blocked');
474
+ else status.set(id, 'pending');
475
+ }
476
+
477
+ const completed = [...restoredCompleted];
478
+ const failed = [...restoredFailed];
479
+ const blocked = [...restoredBlocked];
480
+
481
+ saveJournal(ctx.projectRoot, runId, this.journal);
482
+
483
+ this.emit(ctx, { type: 'RunStarted', payload: { run_id: ctx.runId, recovered: true } });
484
+
485
+ for (const wave of graph.waves) {
486
+ if (this.cancelled) break;
487
+ if (this.paused) {
488
+ this.journal.scheduler_state = 'paused';
489
+ this.journal.paused_at = new Date().toISOString();
490
+ this.journal.completed_work_items = completed.slice();
491
+ this.journal.failed_work_items = failed.slice();
492
+ this.journal.blocked_work_items = blocked.slice();
493
+ this.journal.partial_result = { run_id: ctx.runId, completed, failed, blocked };
494
+ saveJournal(ctx.projectRoot, ctx.runId, this.journal);
495
+ ctx.auditTrail?.record('run_paused', ctx.policyActor ?? 'runtime', {
496
+ runId: ctx.runId,
497
+ detail: { recovered: true, completed, failed, blocked },
498
+ });
499
+ return { run_id: ctx.runId, status: 'paused', completed, failed, blocked, pending_gates: this.journal.pending_gates.slice() };
500
+ }
501
+
502
+ // Skip waves fully completed
503
+ const allDone = wave.node_ids.every(
504
+ (id) => restoredCompleted.has(id) || restoredFailed.has(id) || restoredBlocked.has(id)
505
+ );
506
+ if (allDone) continue;
507
+
508
+ const waveFailed = await this.runWave(
509
+ wave.node_ids,
510
+ graph,
511
+ ctx,
512
+ status,
513
+ completed,
514
+ failed,
515
+ blocked
516
+ );
517
+
518
+ this.journal.completed_work_items = completed.slice();
519
+ this.journal.failed_work_items = failed.slice();
520
+ this.journal.blocked_work_items = blocked.slice();
521
+ saveJournal(ctx.projectRoot, ctx.runId, this.journal);
522
+
523
+ if (waveFailed) break;
524
+ }
525
+
526
+ for (const [id, s] of status) {
527
+ if (s === 'pending' && !this.paused) {
528
+ status.set(id, 'blocked');
529
+ blocked.push(id);
530
+ this.emit(ctx, {
531
+ type: 'WorkItemBlocked',
532
+ work_item_id: id,
533
+ payload: { reason: 'upstream_wave_failed' },
534
+ });
535
+ }
536
+ }
537
+
538
+ const finalStatus: RunResult['status'] = this.cancelled
539
+ ? 'cancelled'
540
+ : failed.length > 0
541
+ ? 'failed'
542
+ : blocked.length > 0
543
+ ? 'blocked'
544
+ : 'completed';
545
+
546
+ this.emit(ctx, {
547
+ type: 'RunCompleted',
548
+ payload: { run_id: ctx.runId, status: finalStatus, recovered: true },
549
+ });
550
+ ctx.auditTrail?.record('run_recovered', ctx.policyActor ?? 'runtime', {
551
+ runId: ctx.runId,
552
+ detail: {
553
+ status: finalStatus,
554
+ completed: completed.length,
555
+ failed: failed.length,
556
+ blocked: blocked.length,
557
+ pending_gates: this.journal.pending_gates.slice(),
558
+ },
559
+ });
560
+
561
+ this.journal.scheduler_state = this.cancelled
562
+ ? 'cancelled'
563
+ : finalStatus === 'blocked' || finalStatus === 'failed'
564
+ ? finalStatus
565
+ : 'completed';
566
+ this.journal.completed_work_items = completed.slice();
567
+ this.journal.failed_work_items = failed.slice();
568
+ this.journal.blocked_work_items = blocked.slice();
569
+ saveJournal(ctx.projectRoot, ctx.runId, this.journal);
570
+ deleteJournal(ctx.projectRoot, ctx.runId);
571
+
572
+ return {
573
+ run_id: ctx.runId,
574
+ status: finalStatus,
575
+ completed,
576
+ failed,
577
+ blocked,
578
+ pending_gates: this.journal.pending_gates.slice(),
579
+ };
580
+ }
581
+
582
+ private isConcurrentSafe(nodeId: string, graph: ExecutionGraph, ctx: SchedulerContext): boolean {
583
+ const node = graph.nodes.get(nodeId)!;
584
+ if (node.mutation_scope.length > 0) return false;
585
+ // A node that may write files but declares no scope is not provably safe to run in parallel
586
+ // (an empty scope used to mean "run everything in parallel, in place").
587
+ if (nodeMayMutate(node)) return false;
588
+ const primaryAction = pickPrimaryAction(node, ctx.pluginRegistry);
589
+ if (!primaryAction) return true;
590
+ const provider = ctx.pluginRegistry?.toolProviderFor(primaryAction.type);
591
+ return provider?.idempotent ?? true;
592
+ }
593
+
594
+ private async runWave(
595
+ nodeIds: string[],
596
+ graph: ExecutionGraph,
597
+ ctx: SchedulerContext,
598
+ status: Map<string, NodeStatus>,
599
+ completed: string[],
600
+ failed: string[],
601
+ blocked: string[]
602
+ ): Promise<boolean> {
603
+ // OXB-C19 (#2): re-evaluate intra-wave dependencies as nodes complete so a resumed/checkpointed task
604
+ // unblocks subsequent eligible tasks in the same wave instead of marking them blocked up-front.
605
+ const warnedEmptyScope = new Set<string>();
606
+ while (!this.cancelled && !this.paused) {
607
+ const eligible: string[] = [];
608
+ for (const id of nodeIds) {
609
+ if (status.get(id) !== 'pending') continue;
610
+ const node = graph.nodes.get(id)!;
611
+ const depsMet = node.depends_on.every((dep) => status.get(dep) === 'completed');
612
+ if (depsMet) eligible.push(id);
613
+ }
614
+ if (eligible.length === 0) break;
615
+
616
+ for (const id of eligible) {
617
+ if (warnedEmptyScope.has(id)) continue;
618
+ const node = graph.nodes.get(id)!;
619
+ // OXB-068: a verify_only / external-dependency node has an enforced empty scope (checked by the caller), not a
620
+ // "may write files" warning.
621
+ const externalNode = Boolean(node.policy.verify_only) || (node.policy.external_dependency?.length ?? 0) > 0;
622
+ if (node.mutation_scope.length === 0 && nodeMayMutate(node) && !externalNode) {
623
+ warnedEmptyScope.add(id);
624
+ this.emit(ctx, {
625
+ type: 'PolicyWarning',
626
+ work_item_id: id,
627
+ payload: {
628
+ reason: 'empty_mutation_scope',
629
+ detail: 'node may write files but declares no mutation_scope; running serially and without scope checks',
630
+ },
631
+ });
632
+ }
633
+ }
634
+
635
+ const readOnly = eligible.filter((id) => this.isConcurrentSafe(id, graph, ctx));
636
+ const mutations = eligible.filter((id) => !readOnly.includes(id));
637
+
638
+ if (readOnly.length > 0) {
639
+ await Promise.all(
640
+ readOnly.map((id) => this.runNode(id, graph, ctx, status, completed, failed, blocked))
641
+ );
642
+ }
643
+
644
+ if (ctx.parallel && mutations.length > 1) {
645
+ await this.runMutationsInParallel(mutations, graph, ctx, status, completed, failed, blocked);
646
+ } else {
647
+ for (const id of mutations) {
648
+ this.checkRequestedPause(ctx);
649
+ if (this.cancelled || this.paused) break;
650
+ await this.runNode(id, graph, ctx, status, completed, failed, blocked);
651
+ }
652
+ }
653
+ }
654
+
655
+ if (!this.cancelled && !this.paused) {
656
+ for (const id of nodeIds) {
657
+ if (status.get(id) !== 'pending') continue;
658
+ status.set(id, 'blocked');
659
+ blocked.push(id);
660
+ this.emit(ctx, {
661
+ type: 'WorkItemBlocked',
662
+ work_item_id: id,
663
+ payload: { reason: 'dependency_not_met' },
664
+ });
665
+ }
666
+ }
667
+
668
+ return failed.length > 0;
669
+ }
670
+
671
+ /**
672
+ * OXB-129: dispatch by dependency, not by wave. A node is ready when every dependency is completed; one with a failed
673
+ * or blocked dependency is blocked (only its dependents — the rest goes on). Ready nodes start in plan order, up to
674
+ * `parallel.maxParallel` (1 without --parallel-mutating), never two with overlapping scopes (a hot file serializes),
675
+ * and never past the free-memory floor. Every decision is a `DispatchState` event (ready / waiting with the reason).
676
+ */
677
+ private async runStream(
678
+ graph: ExecutionGraph,
679
+ ctx: SchedulerContext,
680
+ status: Map<string, NodeStatus>,
681
+ completed: string[],
682
+ failed: string[],
683
+ blocked: string[],
684
+ maxRunMs: number,
685
+ ): Promise<void> {
686
+ const order = graph.waves.flatMap((w) => w.node_ids);
687
+ const parallel = ctx.parallel;
688
+ const max = parallel ? Math.max(1, Math.floor(parallel.maxParallel || 1)) : 1;
689
+ const running = new Map<string, { scope: string[]; done: Promise<void> }>();
690
+ let lastSignature = '';
691
+ while (!this.cancelled && !this.paused) {
692
+ if (Date.now() - this.runStartMs > maxRunMs) break;
693
+ // a requested pause stops new starts; the nodes already running finish (awaited below)
694
+ this.checkRequestedPause(ctx);
695
+ if (this.paused) break;
696
+ const waiting: Array<{ id: string; reason: string }> = [];
697
+ const ready: string[] = [];
698
+ for (const id of order) {
699
+ if (status.get(id) !== 'pending' || running.has(id)) continue;
700
+ const node = graph.nodes.get(id)!;
701
+ const bad = node.depends_on.find((d) => status.get(d) === 'failed' || status.get(d) === 'blocked');
702
+ if (bad) { this.blockNode(id, ctx, status, blocked, 'dependency_not_met', bad); continue; }
703
+ const open = node.depends_on.filter((d) => status.get(d) !== 'completed');
704
+ if (open.length) { waiting.push({ id, reason: `depende de ${open.join(', ')}` }); continue; }
705
+ ready.push(id);
706
+ }
707
+ const started: string[] = [];
708
+ for (const id of ready) {
709
+ if (running.size >= max) { waiting.push({ id, reason: `limite de paralelismo (${max})` }); continue; }
710
+ const node = graph.nodes.get(id)!;
711
+ const hot = [...running.entries()].find(([, r]) => scopesOverlap(r.scope, node.mutation_scope) || (node.mutation_scope.length === 0 && nodeMayMutate(node)));
712
+ if (hot) { waiting.push({ id, reason: `arquivo quente: escopo em comum com ${hot[0]}` }); continue; }
713
+ if (running.size > 0 && parallel?.minFreeMb && parallel.freeMb && parallel.freeMb() < parallel.minFreeMb) { waiting.push({ id, reason: `memória livre abaixo de ${parallel.minFreeMb} MB` }); continue; }
714
+ const useParallel = Boolean(parallel) && max > 1;
715
+ const done = this.runNode(id, graph, ctx, status, completed, failed, blocked, useParallel ? { parallel: true } : {})
716
+ .catch(() => undefined)
717
+ .finally(() => { running.delete(id); });
718
+ running.set(id, { scope: node.mutation_scope, done });
719
+ started.push(id);
720
+ }
721
+ const signature = JSON.stringify([started, waiting]);
722
+ if (signature !== lastSignature && (started.length || waiting.length)) {
723
+ lastSignature = signature;
724
+ this.emit(ctx, { type: 'DispatchState', payload: { mode: 'stream', started, running: [...running.keys()], waiting } });
725
+ if (this.journal) this.journal.dispatch = { running: [...running.keys()], waiting };
726
+ }
727
+ if (running.size === 0) break;
728
+ await Promise.race([...running.values()].map((r) => r.done));
729
+ if (this.journal) {
730
+ this.journal.completed_work_items = completed.slice();
731
+ this.journal.failed_work_items = failed.slice();
732
+ this.journal.blocked_work_items = blocked.slice();
733
+ saveJournal(ctx.projectRoot, ctx.runId, this.journal);
734
+ }
735
+ }
736
+ if (running.size) await Promise.all([...running.values()].map((r) => r.done));
737
+ }
738
+
739
+ /** OXB-050: a pool over the wave's mutating nodes — disjoint scopes only, `maxParallel`, memory per agent. */
740
+ private async runMutationsInParallel(
741
+ mutations: string[],
742
+ graph: ExecutionGraph,
743
+ ctx: SchedulerContext,
744
+ status: Map<string, NodeStatus>,
745
+ completed: string[],
746
+ failed: string[],
747
+ blocked: string[]
748
+ ): Promise<void> {
749
+ const parallel = ctx.parallel!;
750
+ const max = Math.max(1, Math.floor(parallel.maxParallel || 1));
751
+ const pending = [...mutations];
752
+ const running = new Map<string, { scope: string[]; done: Promise<void> }>();
753
+ let memoryWarned = false;
754
+ while ((pending.length > 0 || running.size > 0) && !this.cancelled) {
755
+ // a requested pause: nothing new starts; what is running finishes
756
+ this.checkRequestedPause(ctx);
757
+ if (this.paused) {
758
+ if (running.size) await Promise.all([...running.values()].map((r) => r.done));
759
+ break;
760
+ }
761
+ for (const id of [...pending]) {
762
+ if (running.size >= max) break;
763
+ const scope = graph.nodes.get(id)!.mutation_scope;
764
+ if ([...running.values()].some((r) => scopesOverlap(r.scope, scope))) continue;
765
+ if (running.size > 0 && parallel.minFreeMb && parallel.freeMb && parallel.freeMb() < parallel.minFreeMb) {
766
+ if (!memoryWarned) {
767
+ memoryWarned = true;
768
+ this.emit(ctx, { type: 'PolicyWarning', work_item_id: id, payload: { reason: 'parallel_memory', detail: `memória livre abaixo de ${parallel.minFreeMb} MB: o próximo agente espera um terminar` } });
769
+ }
770
+ break;
771
+ }
772
+ pending.splice(pending.indexOf(id), 1);
773
+ const done = this.runNode(id, graph, ctx, status, completed, failed, blocked, { parallel: true })
774
+ .catch(() => undefined)
775
+ .finally(() => { running.delete(id); });
776
+ running.set(id, { scope, done });
777
+ }
778
+ if (running.size === 0) {
779
+ // Nothing could start (should not happen: one always runs) — fall back to the next one, alone.
780
+ const id = pending.shift();
781
+ if (id) await this.runNode(id, graph, ctx, status, completed, failed, blocked);
782
+ continue;
783
+ }
784
+ await Promise.race([...running.values()].map((r) => r.done));
785
+ }
786
+ }
787
+
788
+ private async runNode(
789
+ nodeId: string,
790
+ graph: ExecutionGraph,
791
+ ctx: SchedulerContext,
792
+ status: Map<string, NodeStatus>,
793
+ completed: string[],
794
+ failed: string[],
795
+ blocked: string[],
796
+ mode: { parallel?: boolean } = {}
797
+ ): Promise<void> {
798
+ const node = graph.nodes.get(nodeId)!;
799
+ const parallelNode = Boolean(mode.parallel && ctx.parallel);
800
+ status.set(nodeId, 'running');
801
+ this.emit(ctx, {
802
+ type: 'WorkItemReady',
803
+ work_item_id: nodeId,
804
+ payload: { title: node.title, wave: node.wave },
805
+ });
806
+
807
+ let lease: WorkspaceLease | null = null;
808
+ // Dispose through the manager that allocated the lease (plugin provider or default).
809
+ let leaseManager: WorkspaceManager | null = null;
810
+ let lastResult: TaskResult | null = null;
811
+ let lastError: string | null = null;
812
+ // 1.20c: the same verify failure twice (normalized output) = suspect ruler or stuck executor: stop paying retries.
813
+ let lastVerifySignature: string | null = null;
814
+ let verifySuspect = false;
815
+ let maxAttempts = node.policy.max_retries + 1;
816
+ let policyRetried = Boolean((ctx.options as SchedulerOptions | undefined)?.policyRefusedBefore?.includes(nodeId));
817
+ // 1.21.1 (OXB-047): work that arrives by another path never pays an agent and never becomes a human gate.
818
+ // An explicit human gate (PLAN.json `gate`) still comes first: the attempt loop requests it as before.
819
+ const humanGatePending = node.policy.requires_human_approval && !this.hasApprovedGate(node, ctx);
820
+ if (!humanGatePending && (node.policy.runtime_wait?.length ?? 0) > 0) {
821
+ const waits = node.policy.runtime_wait ?? [];
822
+ this.blockNode(nodeId, ctx, status, blocked, 'waiting_runtime_precondition', waits.join(', '));
823
+ return;
824
+ }
825
+ if (!humanGatePending && (node.policy.verify_only || (node.policy.external_dependency?.length ?? 0) > 0)) {
826
+ await this.runExternalNode(node, ctx, status, completed, failed, blocked);
827
+ return;
828
+ }
829
+ const quotaBlocked = this.consumeQuotaForNode(ctx, node);
830
+ if (quotaBlocked) {
831
+ this.blockNode(nodeId, ctx, status, blocked, 'quota_exceeded', quotaBlocked);
832
+ return;
833
+ }
834
+ // cross-review 15/11: --retry-policy-once in a 3rd execute of the same run would pay attempt 1 again for a task
835
+ // whose one extra policy attempt was already spent — blocked before any model call
836
+ if ((ctx.options as SchedulerOptions | undefined)?.retryPolicyOnce && (ctx.options as SchedulerOptions | undefined)?.policyRetryExhausted?.includes(nodeId)) {
837
+ this.blockNode(nodeId, ctx, status, blocked, 'policy_retry_exhausted', 'a tentativa extra de política desta tarefa já foi usada neste run: mude o prompt (oxe-cc runtime execute --task <id> --print-prompt) ou o escopo antes de tentar de novo');
838
+ return;
839
+ }
840
+
841
+ const maxQuotaWaitMs = (ctx.options as SchedulerOptions | undefined)?.maxQuotaWaitMs ?? 5 * 60_000;
842
+ const maxQuotaWaits = (ctx.options as SchedulerOptions | undefined)?.maxQuotaWaits ?? 3;
843
+ const sleepFn = (ctx.options as SchedulerOptions | undefined)?.sleep ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)));
844
+ let quotaWaits = 0;
845
+ // OxeSpace 15/11 (OxeChat F4 T9): a pause requested during an attempt holds the next one — the attempt boundary is a
846
+ // boundary too, not only the next node. The task stays PENDING (never blocked) for the execute after resume. Checked
847
+ // before the retry quota / RetryScheduled and after a rate-limit wait (cross-review R34).
848
+ const holdForPause = (next: number): boolean => {
849
+ this.checkRequestedPause(ctx);
850
+ if (!this.paused) return false;
851
+ this.emit(ctx, { type: 'PolicyWarning', work_item_id: nodeId, payload: { reason: 'paused_before_attempt', attempt: next, detail: `runtime pause: a tentativa ${next} não começa` } });
852
+ status.set(nodeId, 'pending');
853
+ return true;
854
+ };
855
+ let iteration = 0;
856
+
857
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
858
+ iteration += 1;
859
+ // a real iteration count: a rate-limit wait re-enters with the same attempt number (R34)
860
+ if (iteration > 1 && holdForPause(attempt)) return;
861
+ const attemptId = `${nodeId}-a${attempt}`;
862
+ const attemptModel = ctx.modelFor ? ctx.modelFor(nodeId, attempt, attempt > 1 ? (lastResult?.failure_class ?? null) : null) : null;
863
+
864
+ this.emit(ctx, {
865
+ type: 'AttemptStarted',
866
+ work_item_id: nodeId,
867
+ attempt_id: attemptId,
868
+ payload: { attempt_number: attempt, ...(attemptModel ? { model: attemptModel.model, tier: attemptModel.tier, escalated: Boolean(attemptModel.escalated) } : {}) },
869
+ });
870
+
871
+ try {
872
+ const policyDecision = this.evaluatePolicyForNode(node, ctx);
873
+ if (policyDecision && !policyDecision.allowed) {
874
+ this.emit(ctx, {
875
+ type: 'PolicyEvaluated',
876
+ work_item_id: nodeId,
877
+ attempt_id: attemptId,
878
+ payload: { ...policyDecision },
879
+ });
880
+ ctx.auditTrail?.record('policy_denied', ctx.policyActor ?? 'runtime', {
881
+ runId: ctx.runId,
882
+ workItemId: nodeId,
883
+ detail: { reason: policyDecision.reason, rule_id: policyDecision.rule_id },
884
+ });
885
+ this.blockNode(nodeId, ctx, status, blocked, 'policy_denied', policyDecision.reason);
886
+ return;
887
+ }
888
+
889
+ if (policyDecision) {
890
+ this.emit(ctx, {
891
+ type: 'PolicyEvaluated',
892
+ work_item_id: nodeId,
893
+ attempt_id: attemptId,
894
+ payload: { ...policyDecision },
895
+ });
896
+ }
897
+
898
+ if ((policyDecision?.gate_required || node.policy.requires_human_approval) && !this.hasApprovedGate(node, ctx)) {
899
+ const gateId = await this.requestGateForNode(node, ctx, policyDecision);
900
+ this.blockNode(nodeId, ctx, status, blocked, 'pending_gate', gateId);
901
+ return;
902
+ }
903
+
904
+ // OXB-023: the run's turn/cost ceiling is checked before every attempt, never in the middle of one.
905
+ const budgetReason = ctx.budget?.exhausted() ?? null;
906
+ if (budgetReason) {
907
+ this.emit(ctx, {
908
+ type: 'BudgetExhausted',
909
+ work_item_id: nodeId,
910
+ attempt_id: attemptId,
911
+ payload: { reason: budgetReason, attempt_number: attempt },
912
+ });
913
+ this.blockNode(nodeId, ctx, status, blocked, 'budget_exhausted', budgetReason);
914
+ return;
915
+ }
916
+ const budgetTurns = ctx.budget?.remainingTurns() ?? null;
917
+ const sizedTurns = ctx.turnsFor ? ctx.turnsFor(nodeId, attempt, attempt > 1 ? (lastResult?.failure_class ?? null) : null) : null;
918
+ const turnsLeft = budgetTurns != null && sizedTurns != null ? Math.min(budgetTurns, sizedTurns) : (budgetTurns ?? sizedTurns);
919
+
920
+ const wsReq: WorkspaceRequest = {
921
+ work_item_id: nodeId,
922
+ attempt_number: attempt,
923
+ strategy: node.workspace_strategy,
924
+ mutation_scope: node.mutation_scope,
925
+ };
926
+ const workspaceManager = parallelNode
927
+ ? ctx.parallel!.manager
928
+ : ctx.pluginRegistry?.workspaceProviderFor(node.workspace_strategy) ?? ctx.workspaceManager;
929
+ leaseManager = workspaceManager;
930
+ lease = await workspaceManager.allocate(wsReq);
931
+ this.emit(ctx, {
932
+ type: 'WorkspaceAllocated',
933
+ work_item_id: nodeId,
934
+ attempt_id: attemptId,
935
+ payload: { workspace_id: lease.workspace_id, strategy: lease.strategy },
936
+ });
937
+
938
+ lastResult = await this.executeNode(node, lease, ctx, attempt, attemptId, {
939
+ previousError: withAttemptChanges(lastError, attempt > 1 && ctx.attemptChanges ? ctx.attemptChanges(nodeId) : null),
940
+ ...(attemptModel && attemptModel.model ? { model: attemptModel.model } : {}),
941
+ ...(turnsLeft != null ? { maxTurns: turnsLeft } : {}),
942
+ });
943
+
944
+ // OXB-026: the verify judges the work, not the end of the LLM conversation. An attempt that ran out of turns
945
+ // after writing in its scope is verified before it is classified: green completes the task, red goes to the
946
+ // informed retry. Discarding it unverified paid a whole second attempt for finished work.
947
+ // a context-cap close (R44) is the same: work written, the verify decides before another paid attempt
948
+ const contextCap = lastResult.completed_by === 'context_cap';
949
+ const turnLimitWithWork = !lastResult.success
950
+ && (lastResult.completed_by === 'turn_limit_exhausted' || contextCap)
951
+ && Boolean(node.verify?.command)
952
+ && (lastResult.evidence?.length ?? 0) > 0;
953
+
954
+ // OXB-171: what the agent itself said (before a verify failure replaces the output).
955
+ const agentOutput = String(lastResult.output || '');
956
+ if (lastResult.success || turnLimitWithWork) {
957
+ const verifyResult = await this.verifyNode(node, lease, ctx, attemptId, attempt);
958
+ if (verifyResult && verifyResult.status === 'failed') {
959
+ // Informed retry: the next attempt sees the command, the reason and the output — not just "failed".
960
+ lastResult = {
961
+ success: false,
962
+ // OXB-185: out of turns, the red verify is a consequence — the class stays turns_exhausted.
963
+ failure_class: turnLimitWithWork ? (contextCap ? lastResult.failure_class : 'turns_exhausted') : 'verify',
964
+ evidence: lastResult.evidence,
965
+ output: `${turnLimitWithWork ? (contextCap ? `contexto cheio no turno ${lastResult.turns_used ?? '?'}; o verify do trabalho parcial:\n` : `turns_exhausted: ${lastResult.turns_used ?? '?'}/${lastResult.turns_cap ?? '?'} turnos usados sem finish_task; o verify do trabalho parcial:\n`) : ''}${describeVerifyFailure(node.verify.command, verifyResult.check, verifyResult.gaps, verifyResult.segment, verifyResult.segments)}`,
966
+ verify_log: buildVerifyLog(verifyResult.segments),
967
+ ...(turnLimitWithWork ? { turns_used: lastResult.turns_used, turns_cap: lastResult.turns_cap } : {}),
968
+ };
969
+ // OXB-120: a verify that failed for the environment (not the code) pauses the run — no attempt is spent.
970
+ const envClass = classifyFailureOutput(`${verifyResult.check?.error ?? ''}\n${verifyResult.check?.stderr ?? ''}\n${verifyResult.check?.stdout ?? ''}`, verifyResult.check?.exit_code ?? null, (ctx.options as SchedulerOptions | undefined)?.failureClasses, { builtinQuota: false });
971
+ if (envClass && envClass.kind === 'environment') {
972
+ this.pauseForFailure(ctx, nodeId, 'environment', envClass.diagnosis, null);
973
+ this.blockNode(nodeId, ctx, status, blocked, 'paused_environment', envClass.diagnosis);
974
+ return;
975
+ }
976
+ if (envClass && envClass.kind === 'quota') {
977
+ const rawQuotaOut = `${verifyResult.check?.error ?? ''}\n${verifyResult.check?.stderr ?? ''}\n${verifyResult.check?.stdout ?? ''}`;
978
+ const diag = envClass.diagnosis || tailLines(lastResult.output || '', 3);
979
+ const waitMs = parseRateLimitResetMs(rawQuotaOut);
980
+ if (waitMs != null && waitMs >= 0 && waitMs <= maxQuotaWaitMs && quotaWaits < maxQuotaWaits) {
981
+ quotaWaits += 1;
982
+ this.emit(ctx, {
983
+ type: 'RateLimitWait',
984
+ work_item_id: nodeId,
985
+ attempt_id: attemptId,
986
+ payload: { task: nodeId, attempt_number: attempt, wait_ms: waitMs, quota_wait: quotaWaits, diagnosis: diag },
987
+ });
988
+ await sleepFn(waitMs);
989
+ this.recordProgress();
990
+ attempt -= 1;
991
+ continue;
992
+ }
993
+ const resume = quotaResumeAt(rawQuotaOut);
994
+ this.pauseForFailure(ctx, nodeId, 'quota', diag, resume);
995
+ this.blockNode(nodeId, ctx, status, blocked, 'paused_quota', diag);
996
+ return;
997
+ }
998
+ // OXB-155: a verify that timed out did not fail — the clock did. It is never "identical_verify_failure".
999
+ const verifyTimedOut = Boolean((verifyResult.check as { timed_out?: boolean } | undefined)?.timed_out);
1000
+ const signature = verifyTimedOut || turnLimitWithWork ? null : verifyFailureSignature(verifyResult.check);
1001
+ if (signature && signature === lastVerifySignature) {
1002
+ verifySuspect = true;
1003
+ this.emit(ctx, {
1004
+ type: 'VerifyCommandSuspect',
1005
+ work_item_id: nodeId,
1006
+ attempt_id: attemptId,
1007
+ payload: {
1008
+ attempt_number: attempt,
1009
+ command: node.verify.command,
1010
+ excerpt: tailLines(`${verifyResult.check?.error ?? ''}\n${verifyResult.check?.stderr ?? ''}\n${verifyResult.check?.stdout ?? ''}`, 12),
1011
+ reason: 'identical_verify_failure',
1012
+ },
1013
+ });
1014
+ break;
1015
+ }
1016
+ lastVerifySignature = signature;
1017
+ // OXB-171: the frozen test needs a file outside the task's scope (plan lint) and it is THAT test failing, or
1018
+ // the agent said the change it needs is out of scope → stop now: a retry cannot pass.
1019
+ const scopeReason = turnLimitWithWork ? null : scopeInsufficientReason(nodeId, ctx, `${verifyResult.check?.stdout ?? ''}\n${verifyResult.check?.stderr ?? ''}`, agentOutput);
1020
+ if (scopeReason) {
1021
+ lastResult = { ...lastResult, failure_class: 'scope_insufficient' };
1022
+ this.emit(ctx, {
1023
+ type: 'ScopeInsufficient',
1024
+ work_item_id: nodeId,
1025
+ attempt_id: attemptId,
1026
+ payload: { task: nodeId, attempt_number: attempt, ...scopeReason, output_tail: tailLines(`${verifyResult.check?.stdout ?? ''}\n${verifyResult.check?.stderr ?? ''}`, 40) },
1027
+ });
1028
+ lastError = lastResult.output || 'scope_insufficient';
1029
+ break;
1030
+ }
1031
+ } else if (parallelNode) {
1032
+ // OXB-050: green in its worktree → integrate (in-scope files only) and verify again on the integrated tree,
1033
+ // under the integration lock; only then the task completes (and its checkpoint is committed).
1034
+ const attemptLease = lease;
1035
+ const outcome = await this.withIntegrationLock(async () => {
1036
+ const integration = await ctx.parallel!.integrate(node, attemptLease);
1037
+ if (integration.outside.length) {
1038
+ this.emit(ctx, {
1039
+ type: 'ScopeViolation',
1040
+ work_item_id: nodeId,
1041
+ attempt_id: attemptId,
1042
+ payload: { task: nodeId, paths: integration.outside, outcome: 'not_integrated', workspace: 'worktree' },
1043
+ });
1044
+ }
1045
+ if (!integration.ok) return { ok: false as const, output: `integration_failed: ${integration.error ?? 'unknown'}` };
1046
+ const integrated = await this.verifyNode(node, { ...attemptLease, root_path: ctx.projectRoot }, ctx, attemptId, attempt);
1047
+ if (integrated && integrated.status === 'failed') {
1048
+ await ctx.parallel!.discard(integration.files);
1049
+ return {
1050
+ ok: false as const,
1051
+ output: `Verify on the integrated tree failed (it passed in the task's worktree; another task's change may conflict).\n${describeVerifyFailure(node.verify.command, integrated.check, integrated.gaps, integrated.segment, integrated.segments)}`,
1052
+ };
1053
+ }
1054
+ this.emit(ctx, {
1055
+ type: 'WorkItemCompleted',
1056
+ work_item_id: nodeId,
1057
+ attempt_id: attemptId,
1058
+ payload: {
1059
+ attempt_number: attempt,
1060
+ evidence: lastResult!.evidence,
1061
+ workspace: 'worktree',
1062
+ integrated_files: integration.files,
1063
+ ...(turnLimitWithWork ? { completed_by: 'verify_after_turn_limit' } : {}),
1064
+ },
1065
+ });
1066
+ return { ok: true as const, output: '' };
1067
+ });
1068
+ if (outcome.ok) {
1069
+ status.set(nodeId, 'completed');
1070
+ completed.push(nodeId);
1071
+ this.recordProgress();
1072
+ return;
1073
+ }
1074
+ lastResult = { success: false, failure_class: 'verify', evidence: lastResult.evidence, output: outcome.output };
1075
+ } else {
1076
+ this.emit(ctx, {
1077
+ type: 'WorkItemCompleted',
1078
+ work_item_id: nodeId,
1079
+ attempt_id: attemptId,
1080
+ payload: {
1081
+ attempt_number: attempt,
1082
+ evidence: lastResult.evidence,
1083
+ ...(turnLimitWithWork ? { completed_by: 'verify_after_turn_limit' } : {}),
1084
+ },
1085
+ });
1086
+ status.set(nodeId, 'completed');
1087
+ completed.push(nodeId);
1088
+ this.recordProgress();
1089
+ return;
1090
+ }
1091
+ }
1092
+
1093
+ lastError = lastResult.output || (lastResult.failure_class ?? 'unknown error');
1094
+
1095
+ // OXB-171: the agent stopped saying the needed change is outside its files — a retry has the same files.
1096
+ if (!lastResult.success && lastResult.failure_class !== 'scope_insufficient' && lastResult.failure_class !== 'turns_exhausted' && OUT_OF_SCOPE_RE.test(agentOutput)) {
1097
+ lastResult = { ...lastResult, failure_class: 'scope_insufficient' };
1098
+ this.emit(ctx, {
1099
+ type: 'ScopeInsufficient',
1100
+ work_item_id: nodeId,
1101
+ attempt_id: attemptId,
1102
+ payload: { task: nodeId, attempt_number: attempt, reason: 'agent_reported_out_of_scope', output_tail: tailLines(agentOutput, 40) },
1103
+ });
1104
+ break;
1105
+ }
1106
+ if (lastResult.failure_class === 'scope_insufficient') break;
1107
+ // OXB-125: waiting for a person's answer — never a retry
1108
+ if (lastResult.failure_class === 'waiting_answer') {
1109
+ this.blockNode(nodeId, ctx, status, blocked, 'waiting_answer', tailLines(lastResult.output || '', 3));
1110
+ return;
1111
+ }
1112
+ if (lastResult.failure_class === 'policy') {
1113
+ // OXB-C28-1: a refusal triggered by tool outputs of earlier turns (not the pack) gets ONE automatic clean
1114
+ // retry — a fresh context (the pack and the tree) has none of those outputs. execute.policy_auto_retry: false
1115
+ // turns it off. A prompt-triggered refusal still needs --retry-policy-once.
1116
+ const autoPolicy = !policyRetried && lastResult.policy_trigger === 'tool_output'
1117
+ && (ctx.options as SchedulerOptions | undefined)?.policyAutoRetry !== false
1118
+ && !(ctx.options as SchedulerOptions | undefined)?.retryPolicyOnce;
1119
+ if (!autoPolicy && (!(ctx.options as SchedulerOptions | undefined)?.retryPolicyOnce || policyRetried)) break;
1120
+ policyRetried = true;
1121
+ if (holdForPause(attempt + 1)) return;
1122
+ // the run's retry quota counts this attempt too (cross-review 15/11)
1123
+ const policyRetryBlocked = this.consumeRetryQuota(ctx);
1124
+ if (policyRetryBlocked) {
1125
+ this.blockNode(nodeId, ctx, status, blocked, 'quota_exceeded', policyRetryBlocked);
1126
+ return;
1127
+ }
1128
+ if (attempt >= maxAttempts) maxAttempts = attempt + 1;
1129
+ this.emit(ctx, {
1130
+ type: 'RetryScheduled',
1131
+ work_item_id: nodeId,
1132
+ attempt_id: attemptId,
1133
+ // output_tail: the refused attempt keeps its log (attempts/<task>-<n>.log) with the trigger candidates
1134
+ payload: { task: nodeId, attempt_number: attempt, next_attempt: attempt + 1, reason: autoPolicy ? 'policy_auto_retry' : 'policy_retry_once', output_tail: tailLines(lastResult.output || '', 60) },
1135
+ });
1136
+ // a clean retry: the refusal text (and the CLI hint) never goes back into the model's prompt — it would feed
1137
+ // the classifier and instruct the model with a human command (cross-review 15/11)
1138
+ lastError = null;
1139
+ continue;
1140
+ }
1141
+ // The output of a red verify (or of an attempt that ran out of turns / made no progress) is the project's test
1142
+ // log: a test called "resets the form" or an error at line 429 is logic, not the provider.
1143
+ const executorLevelFailure = !lastResult.failure_class || ['env', 'llm', 'timeout', 'quota'].includes(String(lastResult.failure_class));
1144
+ const execClass = executorLevelFailure
1145
+ ? classifyFailureOutput(lastResult.output || '', null, (ctx.options as SchedulerOptions | undefined)?.failureClasses)
1146
+ : null;
1147
+ // OXB-120 / OXB-191 / OXB-204: short 429 rate-limit windows wait for the reported reset; long/unknown quotas pause.
1148
+ if (lastResult.failure_class === 'quota' || execClass?.kind === 'quota') {
1149
+ const rawQuotaOut = lastResult.output || '';
1150
+ const diag = (execClass?.kind === 'quota' ? execClass.diagnosis : null) || tailLines(rawQuotaOut, 3);
1151
+ const waitMs = parseRateLimitResetMs(rawQuotaOut);
1152
+ if (waitMs != null && waitMs >= 0 && waitMs <= maxQuotaWaitMs && quotaWaits < maxQuotaWaits) {
1153
+ quotaWaits += 1;
1154
+ this.emit(ctx, {
1155
+ type: 'RateLimitWait',
1156
+ work_item_id: nodeId,
1157
+ attempt_id: attemptId,
1158
+ payload: { task: nodeId, attempt_number: attempt, wait_ms: waitMs, quota_wait: quotaWaits, diagnosis: diag },
1159
+ });
1160
+ await sleepFn(waitMs);
1161
+ this.recordProgress();
1162
+ if (holdForPause(attempt)) return; // a pause during the wait: no paid call after it (R34)
1163
+ attempt -= 1;
1164
+ continue;
1165
+ }
1166
+ const resume = quotaResumeAt(rawQuotaOut);
1167
+ this.pauseForFailure(ctx, nodeId, 'quota', diag, resume);
1168
+ this.blockNode(nodeId, ctx, status, blocked, 'paused_quota', diag);
1169
+ return;
1170
+ }
1171
+ quotaWaits = 0;
1172
+ // cross-review 15/11: the http adapter reports a refused credential / missing endpoint (401/403/404) as
1173
+ // `environment` itself — configuration, not a reason to pay another attempt
1174
+ if (execClass?.kind === 'environment' || lastResult.failure_class === 'environment') {
1175
+ const diag = execClass?.kind === 'environment' ? execClass.diagnosis : tailLines(lastResult.output || '', 3);
1176
+ this.pauseForFailure(ctx, nodeId, 'environment', diag, null);
1177
+ this.blockNode(nodeId, ctx, status, blocked, 'paused_environment', diag);
1178
+ return;
1179
+ }
1180
+ // OXB-148: a prompt that does not fit fails the same way on a blind retry.
1181
+ if (lastResult.failure_class === 'context') break;
1182
+
1183
+ // OXB-130: decide the repair before paying another attempt.
1184
+ if (attempt < maxAttempts && ctx.repairFor) {
1185
+ const repair = ctx.repairFor(nodeId, { attempt, maxAttempts, failureClass: lastResult.failure_class ?? null, output: String(lastResult.output || ''), verifySuspect });
1186
+ if (repair) {
1187
+ this.emit(ctx, { type: 'RepairDecided', work_item_id: nodeId, attempt_id: attemptId, payload: { strategy: repair.strategy, reason: repair.reason, adjustment: repair.adjustment, attempt_number: attempt } });
1188
+ if (repair.strategy !== 'retry') {
1189
+ this.blockNode(nodeId, ctx, status, blocked, `repair_${repair.strategy}`, repair.reason);
1190
+ return;
1191
+ }
1192
+ if (repair.adjustment) lastError = `${lastError ?? ''}\n\n## Ajuste declarado para esta tentativa\n${repair.adjustment}`;
1193
+ }
1194
+ }
1195
+ if (attempt < maxAttempts) {
1196
+ // a pause: no retry quota spent, no RetryScheduled banner (R34)
1197
+ if (holdForPause(attempt + 1)) return;
1198
+ const retryBlocked = this.consumeRetryQuota(ctx);
1199
+ if (retryBlocked) {
1200
+ this.blockNode(nodeId, ctx, status, blocked, 'quota_exceeded', retryBlocked);
1201
+ return;
1202
+ }
1203
+ // Exponential backoff with jitter: 1s * 2^(attempt-1) + [0, 500ms], capped at 30s
1204
+ const backoffMs = Math.min(
1205
+ 1_000 * Math.pow(2, attempt - 1) + Math.random() * 500,
1206
+ 30_000
1207
+ );
1208
+ await new Promise<void>(resolve => setTimeout(resolve, backoffMs));
1209
+ this.emit(ctx, {
1210
+ type: 'RetryScheduled',
1211
+ work_item_id: nodeId,
1212
+ payload: { next_attempt: attempt + 1, reason: lastResult.failure_class, backoff_ms: backoffMs, output_tail: tailLines(lastResult.output || '', 60), ...(lastResult.verify_log ? { verify_log: lastResult.verify_log } : {}) },
1213
+ });
1214
+ }
1215
+ } catch (err: unknown) {
1216
+ // Error boundary: isolate task failure, emit structured event, do not crash scheduler
1217
+ const message = err instanceof Error ? err.message : String(err);
1218
+ const stack = err instanceof Error ? err.stack : undefined;
1219
+ this.emit(ctx, {
1220
+ type: 'TaskErrorBoundaryTripped',
1221
+ work_item_id: nodeId,
1222
+ payload: { message, stack, attempt },
1223
+ });
1224
+ lastResult = {
1225
+ success: false,
1226
+ failure_class: 'env',
1227
+ evidence: [],
1228
+ output: `[error_boundary] ${message}`,
1229
+ };
1230
+ lastError = lastResult.output;
1231
+ if (attempt < maxAttempts) {
1232
+ const backoffMs = Math.min(1_000 * Math.pow(2, attempt - 1) + Math.random() * 500, 30_000);
1233
+ await new Promise<void>(resolve => setTimeout(resolve, backoffMs));
1234
+ this.emit(ctx, {
1235
+ type: 'RetryScheduled',
1236
+ work_item_id: nodeId,
1237
+ payload: { next_attempt: attempt + 1, reason: 'env', backoff_ms: backoffMs, output_tail: tailLines(lastResult.output || '', 60) },
1238
+ });
1239
+ }
1240
+ } finally {
1241
+ if (lease) {
1242
+ await (leaseManager ?? ctx.workspaceManager).dispose(lease.workspace_id).catch((e: unknown) =>
1243
+ this.emit(ctx!, { type: 'WorkspaceDisposeFailed', payload: { workspace_id: lease?.workspace_id, error: String(e) } })
1244
+ );
1245
+ lease = null;
1246
+ leaseManager = null;
1247
+ }
1248
+ }
1249
+ }
1250
+
1251
+ this.emit(ctx, {
1252
+ type: 'WorkItemBlocked',
1253
+ work_item_id: nodeId,
1254
+ payload: { failure_class: verifySuspect ? 'verify_suspect' : lastResult?.failure_class ?? 'env', max_attempts: maxAttempts, output_tail: tailLines(lastResult?.output || '', 60), ...(lastResult?.verify_log ? { verify_log: lastResult.verify_log } : {}) },
1255
+ });
1256
+ status.set(nodeId, 'failed');
1257
+ failed.push(nodeId);
1258
+ }
1259
+
1260
+ /** Abort keeps the progress made so far: an aborted run is recoverable, not a blank slate. */
1261
+ private abortRun(
1262
+ ctx: SchedulerContext,
1263
+ reason: string,
1264
+ completed: string[],
1265
+ failed: string[],
1266
+ blocked: string[]
1267
+ ): RunResult {
1268
+ this.emit(ctx, { type: 'RunAborted', payload: { reason, completed: completed.slice(), failed: failed.slice(), blocked: blocked.slice() } });
1269
+ if (this.journal) {
1270
+ this.journal.scheduler_state = 'aborted';
1271
+ this.journal.completed_work_items = completed.slice();
1272
+ this.journal.failed_work_items = failed.slice();
1273
+ this.journal.blocked_work_items = blocked.slice();
1274
+ this.journal.partial_result = { run_id: ctx.runId, completed, failed, blocked };
1275
+ saveJournal(ctx.projectRoot, ctx.runId, this.journal);
1276
+ }
1277
+ return { run_id: ctx.runId, status: 'aborted', completed, failed, blocked, reason };
1278
+ }
1279
+
1280
+ /** A pause requested from outside (`runtime pause`) takes effect before the next node, never in the middle of one. */
1281
+ private checkRequestedPause(ctx: SchedulerContext): void {
1282
+ if (this.paused || !ctx.pauseRequested) return;
1283
+ let reason: string | null = null;
1284
+ try { reason = ctx.pauseRequested(); } catch { reason = null; }
1285
+ if (!reason) return;
1286
+ this.emit(ctx, { type: 'RunPaused', payload: { reason: 'requested', diagnosis: reason, resume_at: null } });
1287
+ this.pause();
1288
+ }
1289
+
1290
+ /** OXB-120: pause the run for a failure that is not the task's (environment / quota). */
1291
+ private pauseForFailure(ctx: SchedulerContext, nodeId: string, kind: 'environment' | 'quota', diagnosis: string, resumeAt: string | null): void {
1292
+ this.emit(ctx, { type: 'RunPaused', work_item_id: nodeId, payload: { reason: kind, diagnosis, resume_at: resumeAt, task: nodeId } });
1293
+ this.pause();
1294
+ }
1295
+
1296
+ pause(): void {
1297
+ this.paused = true;
1298
+ if (this.journal && this.ctx) {
1299
+ this.journal.scheduler_state = 'paused';
1300
+ this.journal.paused_at = new Date().toISOString();
1301
+ saveJournal(this.ctx.projectRoot, this.ctx.runId, this.journal);
1302
+ }
1303
+ }
1304
+
1305
+ resume(): void {
1306
+ this.paused = false;
1307
+ if (this.journal && this.ctx) {
1308
+ this.journal.scheduler_state = 'running';
1309
+ this.journal.paused_at = null;
1310
+ saveJournal(this.ctx.projectRoot, this.ctx.runId, this.journal);
1311
+ }
1312
+ }
1313
+
1314
+ cancel(): void {
1315
+ this.cancelled = true;
1316
+ if (this.journal && this.ctx) {
1317
+ this.journal.cancelled = true;
1318
+ this.journal.scheduler_state = 'cancelled';
1319
+ saveJournal(this.ctx.projectRoot, this.ctx.runId, this.journal);
1320
+ }
1321
+ }
1322
+
1323
+ getJournal(): RunJournal | null {
1324
+ return this.journal;
1325
+ }
1326
+
1327
+ static loadJournal(projectRoot: string, runId: string): RunJournal | null {
1328
+ return loadJournal(projectRoot, runId);
1329
+ }
1330
+
1331
+ private async executeNode(
1332
+ node: GraphNode,
1333
+ lease: WorkspaceLease,
1334
+ ctx: SchedulerContext,
1335
+ attempt: number,
1336
+ attemptId: string,
1337
+ options: { previousError?: string | null; maxTurns?: number | null; model?: string | null } = {},
1338
+ ): Promise<TaskResult> {
1339
+ const primaryAction = pickPrimaryAction(node, ctx.pluginRegistry);
1340
+ const provider = primaryAction ? ctx.pluginRegistry?.toolProviderFor(primaryAction.type) : null;
1341
+ if (!provider || !primaryAction) {
1342
+ return ctx.executor.execute(node, lease, ctx.runId, attempt, options);
1343
+ }
1344
+
1345
+ ctx.auditTrail?.record('plugin_invoked', ctx.policyActor ?? 'runtime', {
1346
+ runId: ctx.runId,
1347
+ workItemId: node.id,
1348
+ resource: provider.name,
1349
+ detail: { action_type: primaryAction.type, attempt_id: attemptId },
1350
+ });
1351
+ this.emit(ctx, {
1352
+ type: 'ToolInvoked',
1353
+ work_item_id: node.id,
1354
+ attempt_id: attemptId,
1355
+ payload: { provider: provider.name, action_type: primaryAction.type },
1356
+ });
1357
+
1358
+ const invocationInput = {
1359
+ action_type: primaryAction.type,
1360
+ work_item_id: node.id,
1361
+ run_id: ctx.runId,
1362
+ attempt_id: attemptId,
1363
+ params: {
1364
+ command: primaryAction.command ?? null,
1365
+ targets: primaryAction.targets ?? [],
1366
+ },
1367
+ workspace_root: lease.root_path,
1368
+ };
1369
+
1370
+ if (provider.preInvoke) {
1371
+ const preCheck = await provider.preInvoke(invocationInput);
1372
+ if (!preCheck.allowed) {
1373
+ this.emit(ctx, {
1374
+ type: 'ToolFailed',
1375
+ work_item_id: node.id,
1376
+ attempt_id: attemptId,
1377
+ payload: { provider: provider.name, action_type: primaryAction.type, error: preCheck.reason ?? 'pre_invoke blocked', evidence_paths: [], side_effects_applied: [] },
1378
+ });
1379
+ return { success: false, failure_class: 'policy', evidence: [], output: preCheck.reason ?? 'pre_invoke blocked' };
1380
+ }
1381
+ }
1382
+
1383
+ const result = await provider.invoke(invocationInput);
1384
+
1385
+ if (provider.postInvoke) {
1386
+ await provider.postInvoke(invocationInput, result).catch(() => {});
1387
+ }
1388
+
1389
+ this.emit(ctx, {
1390
+ type: result.success ? 'ToolCompleted' : 'ToolFailed',
1391
+ work_item_id: node.id,
1392
+ attempt_id: attemptId,
1393
+ payload: {
1394
+ provider: provider.name,
1395
+ action_type: primaryAction.type,
1396
+ evidence_paths: result.evidence_paths,
1397
+ side_effects_applied: result.side_effects_applied,
1398
+ error: result.error ?? null,
1399
+ },
1400
+ });
1401
+
1402
+ return {
1403
+ success: result.success,
1404
+ failure_class: result.success ? null : provider.kind === 'external_operation' ? 'policy' : 'env',
1405
+ evidence: result.evidence_paths,
1406
+ output: result.output,
1407
+ };
1408
+ }
1409
+
1410
+ private async verifyNode(
1411
+ node: GraphNode,
1412
+ lease: WorkspaceLease,
1413
+ ctx: SchedulerContext,
1414
+ attemptId: string,
1415
+ attempt: number,
1416
+ ): Promise<VerifyNodeResult | null> {
1417
+ if (!node.verify?.command) return null;
1418
+ this.emit(ctx, {
1419
+ type: 'VerificationStarted',
1420
+ work_item_id: node.id,
1421
+ payload: { command: node.verify.command, attempt_number: attempt },
1422
+ });
1423
+ // 1.21.2 (OXB-066): each top-level `&&` segment runs on its own, in order, stopping at the first failure. As one
1424
+ // command, `vitest … && tsc --noEmit` failed in tsc but the retry only carried the passing vitest output: the
1425
+ // executor never saw the type error (oxespace 1.5.0 T13: 4 attempts, US$ 4.54, 0 completed).
1426
+ const segments = splitVerifySegments(node.verify.command);
1427
+ // OXB-C28-2: consecutive remote segments run as one remote job (all_segments keeps one run per segment: it must
1428
+ // see every red segment, and one remote `&&` chain stops at the first)
1429
+ const units = (ctx.options as SchedulerOptions | undefined)?.allSegments
1430
+ ? segments.map((command, i) => ({ command, members: [i] }))
1431
+ : groupRemoteSegments(segments);
1432
+ const ran: VerifySegmentRun[] = [];
1433
+ const gaps: string[] = [];
1434
+ let status = 'passed';
1435
+ let failing: VerifySegmentRun | null = null;
1436
+ for (const unit of units) {
1437
+ const index = unit.members[0];
1438
+ const lastMember = unit.members[unit.members.length - 1];
1439
+ const merged = unit.members.length > 1;
1440
+ const command = unit.command;
1441
+ const label = merged ? `${index + 1}-${lastMember + 1}` : `${index + 1}`;
1442
+ const suite: AcceptanceCheckSuite = {
1443
+ checks: [{
1444
+ id: segments.length > 1 ? `inline-${node.id}-s${label}` : `inline-${node.id}`,
1445
+ type: 'custom',
1446
+ command,
1447
+ evidence_type_expected: 'stdout',
1448
+ acceptance_ref: null,
1449
+ description: `Verify ${node.id}${segments.length > 1 ? ` [${label}/${segments.length}]${merged ? ' (uma rodada remota)' : ''}` : ''}`,
1450
+ }],
1451
+ compiled_at: new Date().toISOString(),
1452
+ spec_hash: '',
1453
+ plan_hash: '',
1454
+ };
1455
+ let result: { status: string; gaps?: string[]; check_results?: CheckResult[] };
1456
+ try {
1457
+ result = await verifyRun({
1458
+ suite,
1459
+ cwd: lease.root_path,
1460
+ timeoutMs: (ctx.options as Record<string, unknown>)?.verifyTimeoutMs as number ?? 600_000,
1461
+ runId: ctx.runId,
1462
+ workItemId: node.id,
1463
+ attemptNumber: attempt,
1464
+ projectRoot: ctx.projectRoot,
1465
+ pluginRegistry: ctx.pluginRegistry,
1466
+ });
1467
+ } catch (err) {
1468
+ this.emit(ctx, {
1469
+ type: 'VerificationCompleted',
1470
+ work_item_id: node.id,
1471
+ attempt_id: attemptId,
1472
+ payload: { status: 'error', error: String(err), failed_segment: { index: index + 1, total: segments.length, command, exit_code: null } },
1473
+ });
1474
+ return null;
1475
+ }
1476
+ let segmentRun: VerifySegmentRun = { index: index + 1, total: segments.length, command, status: result.status, check: result.check_results?.[0] };
1477
+ if (merged) {
1478
+ const c0 = result.check_results?.[0];
1479
+ const at = result.status === 'passed' ? lastMember : remoteFailedMember(`${c0?.stdout ?? ''}\n${c0?.stderr ?? ''}`, unit.members);
1480
+ segmentRun = { ...segmentRun, index: at + 1, command: segments[at], merged: unit.members.map((m) => m + 1) };
1481
+ }
1482
+ // OXB-162: the same command, or test files an earlier segment of THIS attempt already passed, failing now is a
1483
+ // flaky suspect: rerun once; green → continue (marked), red → the task fails as before.
1484
+ if (result.status === 'failed') {
1485
+ const files = segmentTestFiles(command);
1486
+ const earlier = ran.find((r) => r.status === 'passed' && (r.command === command || (files.length > 0 && files.every((f) => segmentTestFiles(r.command).includes(f)))));
1487
+ if (earlier) {
1488
+ let rerun: { status: string; gaps?: string[]; check_results?: CheckResult[] } | null = null;
1489
+ try {
1490
+ rerun = await verifyRun({
1491
+ suite: { ...suite, checks: suite.checks.map((c) => ({ ...c, id: `${c.id}-rerun` })) },
1492
+ cwd: lease.root_path,
1493
+ timeoutMs: (ctx.options as Record<string, unknown>)?.verifyTimeoutMs as number ?? 600_000,
1494
+ runId: ctx.runId,
1495
+ workItemId: node.id,
1496
+ attemptNumber: attempt,
1497
+ projectRoot: ctx.projectRoot,
1498
+ pluginRegistry: ctx.pluginRegistry,
1499
+ });
1500
+ } catch { rerun = null; }
1501
+ const green = rerun?.status === 'passed';
1502
+ this.emit(ctx, {
1503
+ type: 'VerifyCommandSuspect',
1504
+ work_item_id: node.id,
1505
+ attempt_id: attemptId,
1506
+ payload: { attempt_number: attempt, command, reason: 'flaky_suspect', passed_before_in: earlier.index, rerun: green ? 'passed' : 'failed', excerpt: tailLines(`${segmentRun.check?.stdout ?? ''}\n${segmentRun.check?.stderr ?? ''}`, 12) },
1507
+ });
1508
+ if (green && rerun) {
1509
+ result = rerun;
1510
+ segmentRun = { ...segmentRun, status: 'passed', check: rerun.check_results?.[0], flaky_suspect: true };
1511
+ } else {
1512
+ segmentRun = { ...segmentRun, flaky_suspect: true };
1513
+ }
1514
+ }
1515
+ }
1516
+ ran.push(segmentRun);
1517
+ gaps.push(...(result.gaps ?? []));
1518
+ if (result.status === 'failed') {
1519
+ status = 'failed';
1520
+ if (!failing) failing = segmentRun;
1521
+ if (!(ctx.options as SchedulerOptions | undefined)?.allSegments) break;
1522
+ }
1523
+ if (result.status !== 'passed' && status === 'passed') status = result.status;
1524
+ }
1525
+ const failedRuns = ran.filter((r) => r.status === 'failed');
1526
+ // OXB-171: the failing segment's own output tail rides in the event (the cause was only found by rerunning by hand).
1527
+ const failedSegment = failing
1528
+ ? { index: failing.index, total: failing.total, command: failing.command, exit_code: failing.check?.exit_code ?? null, output_tail: tailLines(`${failing.check?.stdout ?? ''}\n${failing.check?.stderr ?? ''}\n${failing.check?.error ?? ''}`, 40) }
1529
+ : null;
1530
+ const failedSegments = failedRuns.map((f) => ({
1531
+ index: f.index,
1532
+ total: f.total,
1533
+ command: f.command,
1534
+ exit_code: f.check?.exit_code ?? null,
1535
+ output_tail: tailLines(`${f.check?.stdout ?? ''}\n${f.check?.stderr ?? ''}\n${f.check?.error ?? ''}`, 40),
1536
+ }));
1537
+ this.emit(ctx, {
1538
+ type: 'VerificationCompleted',
1539
+ work_item_id: node.id,
1540
+ attempt_id: attemptId,
1541
+ payload: {
1542
+ status,
1543
+ ...(failedSegment ? { failed_segment: failedSegment } : {}),
1544
+ ...(failedSegments.length > 1 ? { failed_segments: failedSegments } : {}),
1545
+ },
1546
+ });
1547
+ const last = ran[ran.length - 1];
1548
+ return {
1549
+ status,
1550
+ gaps,
1551
+ check: failing ? failing.check : last?.check,
1552
+ segment: failedSegment,
1553
+ segments: ran,
1554
+ };
1555
+ }
1556
+
1557
+ private evaluatePolicyForNode(node: GraphNode, ctx: SchedulerContext): PersistedPolicyDecision | null {
1558
+ if (!ctx.policyEngine) return null;
1559
+ const primaryAction = pickPrimaryAction(node, ctx.pluginRegistry);
1560
+ const decisionContext: PolicyContext = {
1561
+ tool: primaryAction?.type ?? 'custom',
1562
+ kind: node.workspace_strategy,
1563
+ mutation_scope: node.mutation_scope,
1564
+ affected_paths: node.mutation_scope,
1565
+ side_effect_class: inferSideEffectClass(node),
1566
+ mutation_count: node.mutation_scope.length,
1567
+ node_policy: {
1568
+ max_retries: node.policy.max_retries,
1569
+ },
1570
+ };
1571
+ const evaluated = ctx.policyEngine.evaluate(decisionContext);
1572
+ const persisted: PersistedPolicyDecision = {
1573
+ ...evaluated,
1574
+ run_id: ctx.runId,
1575
+ work_item_id: node.id,
1576
+ action: primaryAction?.type ?? 'custom',
1577
+ actor: ctx.policyActor ?? 'runtime',
1578
+ override: false,
1579
+ rationale: null,
1580
+ context: decisionContext,
1581
+ };
1582
+ savePolicyDecision(ctx.projectRoot, persisted);
1583
+ return persisted;
1584
+ }
1585
+
1586
+ /** An approval already granted for this node in this run must not be requested again on re-execution. */
1587
+ private hasApprovedGate(node: GraphNode, ctx: SchedulerContext): boolean {
1588
+ if (!ctx.gateManager) return false;
1589
+ return ctx.gateManager
1590
+ .listResolved()
1591
+ .some((gate) => gate.work_item_id === node.id && gate.decision === 'approved' && (gate.run_id == null || gate.run_id === ctx.runId));
1592
+ }
1593
+
1594
+ private async requestGateForNode(
1595
+ node: GraphNode,
1596
+ ctx: SchedulerContext,
1597
+ decision: PersistedPolicyDecision | null
1598
+ ): Promise<string> {
1599
+ if (!ctx.gateManager) {
1600
+ console.warn('[scheduler] ctx.gateManager not configured — gates will not be persisted');
1601
+ return 'gate-missing-manager';
1602
+ }
1603
+ const scope = inferGateScope(node);
1604
+ const primaryAction = pickPrimaryAction(node, ctx.pluginRegistry);
1605
+ const gate = await ctx.gateManager.request(scope, {
1606
+ run_id: ctx.runId,
1607
+ work_item_id: node.id,
1608
+ action: primaryAction?.type ?? 'custom',
1609
+ description: `Gate required before executing ${node.id}`,
1610
+ evidence_refs: [],
1611
+ risks: [decision?.reason ?? node.policy.gate_reason ?? 'human approval required'],
1612
+ rationale: decision?.reason ?? node.policy.gate_reason ?? 'node policy requires approval',
1613
+ policy_decision_id: decision?.decision_id ?? null,
1614
+ });
1615
+ if (this.journal && !this.journal.pending_gates.includes(gate.gate_id)) {
1616
+ this.journal.pending_gates.push(gate.gate_id);
1617
+ }
1618
+ ctx.auditTrail?.record('gate_requested', ctx.policyActor ?? 'runtime', {
1619
+ runId: ctx.runId,
1620
+ workItemId: node.id,
1621
+ detail: { gate_id: gate.gate_id, scope: gate.scope, action: gate.action },
1622
+ });
1623
+ return gate.gate_id;
1624
+ }
1625
+
1626
+ /**
1627
+ * A node delivered by another path (`verify_only`) or waiting on external work (`external_dependency`): no agent.
1628
+ * verify_only runs only the node's verify — green completes it; red (or no verify) leaves it waiting. A node with an
1629
+ * external dependency and no verify_only waits without a gate, so the rest of the run (and the next preflight) goes on.
1630
+ */
1631
+ private async runExternalNode(
1632
+ node: GraphNode,
1633
+ ctx: SchedulerContext,
1634
+ status: Map<string, NodeStatus>,
1635
+ completed: string[],
1636
+ failed: string[],
1637
+ blocked: string[]
1638
+ ): Promise<void> {
1639
+ const deps = node.policy.external_dependency ?? [];
1640
+ if (node.policy.verify_only && node.verify?.command) {
1641
+ const attemptId = `${node.id}-verify-only`;
1642
+ const workspaceManager = ctx.pluginRegistry?.workspaceProviderFor(node.workspace_strategy) ?? ctx.workspaceManager;
1643
+ const lease = await workspaceManager.allocate({ work_item_id: node.id, attempt_number: 1, strategy: node.workspace_strategy, mutation_scope: node.mutation_scope });
1644
+ try {
1645
+ const verdict = await this.verifyNode(node, lease, ctx, attemptId, 1);
1646
+ if (verdict && verdict.status !== 'failed') {
1647
+ this.emit(ctx, {
1648
+ type: 'WorkItemCompleted',
1649
+ work_item_id: node.id,
1650
+ attempt_id: attemptId,
1651
+ payload: { attempt_number: 1, evidence: [], completed_by: 'verify_only', external_dependency: deps },
1652
+ });
1653
+ status.set(node.id, 'completed');
1654
+ completed.push(node.id);
1655
+ this.recordProgress();
1656
+ return;
1657
+ }
1658
+ } finally {
1659
+ await workspaceManager.dispose(lease.workspace_id).catch(() => undefined);
1660
+ }
1661
+ }
1662
+ this.blockNode(node.id, ctx, status, blocked, 'external_dependency', deps.length ? deps.join(', ') : 'verify_only: entrega externa ainda não verificada');
1663
+ void failed;
1664
+ }
1665
+
1666
+ private blockNode(
1667
+ nodeId: string,
1668
+ ctx: SchedulerContext,
1669
+ status: Map<string, NodeStatus>,
1670
+ blocked: string[],
1671
+ reason: string,
1672
+ detail: string | QuotaViolation | null = null
1673
+ ): void {
1674
+ this.emit(ctx, {
1675
+ type: 'WorkItemBlocked',
1676
+ work_item_id: nodeId,
1677
+ payload: { reason, detail },
1678
+ });
1679
+ status.set(nodeId, 'blocked');
1680
+ if (!blocked.includes(nodeId)) blocked.push(nodeId);
1681
+ }
1682
+
1683
+ private consumeQuotaForNode(ctx: SchedulerContext, node: GraphNode): string | null {
1684
+ if (!ctx.quota) return null;
1685
+ let quota = consumeQuota(ctx.quota, 'work_items', 1);
1686
+ if (node.mutation_scope.length > 0) {
1687
+ quota = consumeQuota(quota, 'mutations', 1);
1688
+ }
1689
+ const violation = checkQuota(quota);
1690
+ ctx.quota = quota;
1691
+ return violation ? `${violation.quota_type}:${violation.consumed}/${violation.limit}` : null;
1692
+ }
1693
+
1694
+ private consumeRetryQuota(ctx: SchedulerContext): string | null {
1695
+ if (!ctx.quota) return null;
1696
+ ctx.quota = consumeQuota(ctx.quota, 'retries', 1);
1697
+ const violation = checkQuota(ctx.quota);
1698
+ return violation ? `${violation.quota_type}:${violation.consumed}/${violation.limit}` : null;
1699
+ }
1700
+
1701
+ private emit(
1702
+ ctx: SchedulerContext,
1703
+ input: EventInput
1704
+ ): void {
1705
+ const event = appendEvent(ctx.projectRoot, ctx.sessionId, {
1706
+ run_id: ctx.runId,
1707
+ ...input,
1708
+ });
1709
+ ctx.onEvent?.(event);
1710
+ }
1711
+ }
1712
+
1713
+ const RECOVERABLE_JOURNAL_STATES = new Set<RunJournal['scheduler_state']>(['paused', 'interrupted', 'blocked', 'aborted', 'failed']);
1714
+
1715
+ /** Nodes whose actions may write to the workspace (anything beyond reading and collecting evidence). */
1716
+ function nodeMayMutate(node: GraphNode): boolean {
1717
+ return node.actions.some((action) => action.type !== 'read_code' && action.type !== 'collect_evidence');
1718
+ }
1719
+
1720
+ function inferSideEffectClass(node: GraphNode): PolicyContext['side_effect_class'] {
1721
+ if (node.mutation_scope.length > 0) return 'write_fs';
1722
+ if (node.actions.some((action) => action.type === 'run_tests' || action.type === 'run_lint')) return 'spawn_process';
1723
+ return 'read_fs';
1724
+ }
1725
+
1726
+ function pickPrimaryAction(node: GraphNode, pluginRegistry?: PluginRegistry): GraphNode['actions'][number] | undefined {
1727
+ const candidateActions = node.actions.filter((action) => action.type !== 'collect_evidence');
1728
+ const preferredMutation = candidateActions.find((action) => action.type === 'generate_patch')
1729
+ || candidateActions.find((action) => action.type === 'run_tests')
1730
+ || candidateActions[0];
1731
+ if (!pluginRegistry) return preferredMutation;
1732
+ return candidateActions.find((action) => pluginRegistry.toolProviderFor(action.type)) || preferredMutation;
1733
+ }
1734
+
1735
+ function inferGateScope(node: GraphNode): 'critical_mutation' | 'security' | 'plan_approval' {
1736
+ if (node.mutation_scope.length > 0) return 'critical_mutation';
1737
+ if (node.actions.some((action) => action.type === 'collect_evidence')) return 'security';
1738
+ return 'plan_approval';
1739
+ }
1740
+
1741
+ /** Last `n` non-empty lines of a text. */
1742
+ /**
1743
+ * OXB-120: a failure that is not the task's logic must not cost an attempt. Environment (exit 126/127, a missing
1744
+ * executable, a build artifact not built, a native module for another Node, the network) and quota (a provider usage
1745
+ * limit) pause the run with a diagnosis; only `logic` failures consume attempts.
1746
+ */
1747
+ const ENVIRONMENT_RE = /command not found|is not recognized as an internal or external command|ENOENT[^\n]*\b(out|dist|build|\.next|lib)[\\/]|Cannot find module '(?!\.)[^']+'|was compiled against a different Node\.js version|NODE_MODULE_VERSION \d+|\bECONNREFUSED\b|\bENOTFOUND\b|\bEAI_AGAIN\b|getaddrinfo|\bECONNRESET\b|socket hang up|\bENOSPC\b|\bEMFILE\b|JavaScript heap out of memory/i;
1748
+ const QUOTA_RE = PROVIDER_QUOTA_RE;
1749
+ export function classifyFailureOutput(output: string, exitCode: number | null | undefined, extra?: { environment?: string[]; quota?: string[] }, opts?: { builtinQuota?: boolean }): { kind: 'environment' | 'quota'; diagnosis: string } | null {
1750
+ const text = String(output || '');
1751
+ if (exitCode === 0) return null;
1752
+ const lineOf = (re: RegExp) => (text.split(/\r?\n/).find((l) => re.test(l) && !/FileSystemFileChangedEvent/i.test(l)) || '').trim().slice(0, 240);
1753
+ const extraRe = (list?: string[]) => (list || []).map((p) => { try { return new RegExp(p, 'i'); } catch { return null; } }).filter(Boolean) as RegExp[];
1754
+ for (const re of extraRe(extra?.quota)) if (re.test(text)) return { kind: 'quota', diagnosis: lineOf(re) || 'quota exceeded' };
1755
+ for (const re of extraRe(extra?.environment)) if (re.test(text)) {
1756
+ const diag = lineOf(re);
1757
+ if (diag) return { kind: 'environment', diagnosis: diag };
1758
+ }
1759
+ if (opts?.builtinQuota !== false && QUOTA_RE.test(text)) return { kind: 'quota', diagnosis: lineOf(QUOTA_RE) || 'quota limit reached' };
1760
+ if (exitCode === 126 || exitCode === 127) return { kind: 'environment', diagnosis: lineOf(/./) || `exit ${exitCode}` };
1761
+ if (ENVIRONMENT_RE.test(text)) {
1762
+ const diag = lineOf(ENVIRONMENT_RE);
1763
+ if (diag) return { kind: 'environment', diagnosis: diag };
1764
+ }
1765
+ return null;
1766
+ }
1767
+ export function quotaResumeAt(text: string): string | null {
1768
+ const m = /resets? (?:at|in|on)?\s*([^\n.;·]{3,40})|try again (?:in|after) ([^\n.;·]{2,30})/i.exec(String(text || ''));
1769
+ return m ? (m[1] || m[2]).trim() : null;
1770
+ }
1771
+
1772
+ function unitMultiplierMs(unit: string | undefined, defaultMs = 1000): number {
1773
+ const u = String(unit || '').trim().toLowerCase();
1774
+ if (!u) return defaultMs;
1775
+ if (u === 'ms' || u.startsWith('millisecond')) return 1;
1776
+ if (u === 's' || u.startsWith('sec')) return 1000;
1777
+ if (u === 'm' || u.startsWith('min')) return 60_000;
1778
+ if (u === 'h' || u.startsWith('hr') || u.startsWith('hour')) return 3_600_000;
1779
+ return defaultMs;
1780
+ }
1781
+
1782
+ /**
1783
+ * OXB-204: extract explicit reset/retry duration in ms from 429 headers or provider error payloads.
1784
+ * Returns `null` when no machine-actionable duration is present (e.g. "resets Nov 14, 10am"), so multi-day
1785
+ * quotas still pause immediately instead of guessing.
1786
+ */
1787
+ export function parseRateLimitResetMs(
1788
+ text: string,
1789
+ nowMs = Date.now(),
1790
+ retryAfterHeader?: string | null,
1791
+ ): number | null {
1792
+ if (retryAfterHeader != null && String(retryAfterHeader).trim() !== '') {
1793
+ const rawHeader = String(retryAfterHeader).trim();
1794
+ if (/^\d+(?:\.\d+)?$/.test(rawHeader)) {
1795
+ const ms = Math.ceil(Number(rawHeader) * 1000);
1796
+ if (Number.isFinite(ms) && ms >= 0) return ms;
1797
+ } else {
1798
+ const parsedDate = Date.parse(rawHeader);
1799
+ if (Number.isFinite(parsedDate) && parsedDate >= nowMs) {
1800
+ return Math.ceil(parsedDate - nowMs);
1801
+ }
1802
+ }
1803
+ }
1804
+
1805
+ const raw = String(text || '');
1806
+ if (!raw) return null;
1807
+
1808
+ const retryDelayMatch = /"?retryDelay"?\s*[:=]\s*"?(\d+(?:\.\d+)?)\s*(ms|milliseconds?|s|secs?|seconds?|m|mins?|minutes?|h|hrs?|hours?)?"?/i.exec(raw);
1809
+ if (retryDelayMatch) {
1810
+ const ms = Math.ceil(Number(retryDelayMatch[1]) * unitMultiplierMs(retryDelayMatch[2], 1000));
1811
+ if (Number.isFinite(ms) && ms >= 0) return ms;
1812
+ }
1813
+
1814
+ const retryAfterField = /"?(retry[-_ ]after(?:[-_ ]ms)?)"?\s*[:=]\s*"?(\d+(?:\.\d+)?)\s*(ms|milliseconds?|s|secs?|seconds?|m|mins?|minutes?|h|hrs?|hours?)?"?/i.exec(raw);
1815
+ if (retryAfterField) {
1816
+ const defaultMs = /ms$/i.test(retryAfterField[1]) ? 1 : 1000;
1817
+ const ms = Math.ceil(Number(retryAfterField[2]) * unitMultiplierMs(retryAfterField[3], defaultMs));
1818
+ if (Number.isFinite(ms) && ms >= 0) return ms;
1819
+ }
1820
+
1821
+ const relMatch = /(?:please\s+)?(?:retry|try again|resets?|wait|backoff|available)\s+(?:in|after)\s+((?:\d+(?:\.\d+)?\s*(?:ms|milliseconds?|s|secs?|seconds?|m|mins?|minutes?|h|hrs?|hours?)(?:\s*,?\s*(?:and\s+)?)?)+)/i.exec(raw);
1822
+ if (relMatch) {
1823
+ let totalMs = 0;
1824
+ let matchedAny = false;
1825
+ const tokenRe = /(\d+(?:\.\d+)?)\s*(ms|milliseconds?|s|secs?|seconds?|m|mins?|minutes?|h|hrs?|hours?)/gi;
1826
+ let tok: RegExpExecArray | null;
1827
+ while ((tok = tokenRe.exec(relMatch[1])) !== null) {
1828
+ totalMs += Number(tok[1]) * unitMultiplierMs(tok[2], 1000);
1829
+ matchedAny = true;
1830
+ }
1831
+ if (matchedAny && Number.isFinite(totalMs) && totalMs >= 0) return Math.ceil(totalMs);
1832
+ }
1833
+
1834
+ const isoMatch = /resets?\s+(?:at\s+)?(\d{4}-\d{2}-\d{2}T[\d:.]+(?:Z|[+-]\d{2}:?\d{2}))/i.exec(raw);
1835
+ if (isoMatch) {
1836
+ const parsed = Date.parse(isoMatch[1]);
1837
+ if (Number.isFinite(parsed) && parsed >= nowMs) return Math.ceil(parsed - nowMs);
1838
+ }
1839
+
1840
+ return null;
1841
+ }
1842
+
1843
+ /** OXB-171: an agent that says the change it needs is outside its files (pt/en). */
1844
+ const OUT_OF_SCOPE_RE = /\b(out of (my |the task'?s? )?scope|outside (of )?(my |the task'?s? )?(scope|files)|not in (my |the task'?s? )?(files|scope)|fora do (meu |)escopo|fora dos arquivos( da tarefa)?|não está (no|nos) (escopo|arquivos)( da tarefa)?|scope_insufficient)\b/i;
1845
+
1846
+ /** OXB-C27-1: the output names this file (its path, or a non-generic basename such as sectionsApi.ts). */
1847
+ function mentionsFile(output: string, file: string): boolean {
1848
+ const f = String(file || '').replace(/\\/g, '/').replace(/^\.\//, '');
1849
+ if (!f) return false;
1850
+ if (output.includes(f)) return true;
1851
+ const base = f.split('/').pop() || '';
1852
+ if (!base || /^index\.[cm]?[jt]sx?$/i.test(base)) {
1853
+ const tail = f.split('/').slice(-2).join('/');
1854
+ return tail.includes('/') && output.includes(tail);
1855
+ }
1856
+ return new RegExp(`(^|[\\s/\\\\(\\['"\`])${base.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(:\\d+|[\\s)'"\`]|$)`, 'm').test(output);
1857
+ }
1858
+
1859
+ function scopeInsufficientReason(nodeId: string, ctx: SchedulerContext, verifyOutput: string, agentOutput: string): Record<string, unknown> | null {
1860
+ const req = (ctx.options as SchedulerOptions | undefined)?.outOfScopeRequirements?.[nodeId];
1861
+ if (req && req.files.length) {
1862
+ const out = String(verifyOutput || '').replace(/\\/g, '/');
1863
+ const named = req.tests.filter((t) => out.includes(t) || out.includes(t.split('/').pop() || t));
1864
+ // OXB-C27-1: an import is not a cause. Only when the failure passes through an out-of-scope file (the stack or
1865
+ // the diff names it) is it scope_insufficient; a fixture defect in the test (polish2 T6) is retried and, when it
1866
+ // repeats, becomes verify_suspect naming the test.
1867
+ const said = String(agentOutput || '').replace(/\\/g, '/');
1868
+ const touched = named.length ? req.files.filter((f) => mentionsFile(out, f) || mentionsFile(said, f)) : [];
1869
+ if (touched.length) return { reason: 'frozen_test_needs_out_of_scope_file', files: touched, tests: named };
1870
+ }
1871
+ if (OUT_OF_SCOPE_RE.test(agentOutput)) return { reason: 'agent_reported_out_of_scope' };
1872
+ // OXB-188: the agent left a stub it labels as blocked — the change it needs is outside the scope; never a retry.
1873
+ const blocked = /scope_insufficient: stub marcado como bloqueado[^\n]*/.exec(String(verifyOutput || ''));
1874
+ if (blocked) {
1875
+ const files = [...new Set([...blocked[0].matchAll(/precisa de ([^,(]+(?:, [^,(]+)*), fora do escopo/g)].flatMap((m) => m[1].split(', ').map((x) => x.trim())))];
1876
+ return { reason: 'blocked_stub', files, detail: blocked[0] };
1877
+ }
1878
+ // The pack names a symbol absent at the base that the attempt did not create (a name guessed from the file): a
1879
+ // plan defect, never fixed by a retry.
1880
+ const packDefect = /plan_defect: o pack nomeia um símbolo que não existe[^\n]*/.exec(String(verifyOutput || ''));
1881
+ if (packDefect) {
1882
+ const files = [...new Set([...packDefect[0].matchAll(/\b[\w$]+ em ([^,:]+?)(?=, |: )/g)].map((m) => m[1].trim()))];
1883
+ return { reason: 'pack_symbol_missing', files, detail: packDefect[0] };
1884
+ }
1885
+ return null;
1886
+ }
1887
+
1888
+ /** OXB-162: git's line-ending notices — they filled F4-T1's whole output tail and hid the failing test. */
1889
+ const GIT_EOL_NOTICE_RE = /^\s*warning: (in the working copy of .*(LF|CRLF) will be replaced|(LF|CRLF) will be replaced by (CRLF|LF))/i;
1890
+ /** A failing-test block start (vitest/jest/node:test/mocha/JUnit). */
1891
+ const FAIL_BLOCK_RE = /^\s*(FAIL\b|×|✗|✖|not ok\b|\d+\) |●\s)/;
1892
+ const FAIL_ERROR_RE = /AssertionError|Error: expect/;
1893
+
1894
+ export function tailLines(text: string, n: number): string {
1895
+ const lines = String(text || '').split(/\r?\n/).map((l) => l.trimEnd()).filter((l) => l.trim() && !GIT_EOL_NOTICE_RE.test(l));
1896
+ const tail = lines.slice(-n);
1897
+ // OXB-162: the last failing-test block, when the tail (summary lines, noise) does not reach it.
1898
+ let lastFail = -1;
1899
+ for (let i = lines.length - 1; i >= 0; i -= 1) if (FAIL_BLOCK_RE.test(lines[i])) { lastFail = i; break; }
1900
+ if (lastFail < 0) for (let i = lines.length - 1; i >= 0; i -= 1) if (FAIL_ERROR_RE.test(lines[i])) { lastFail = i; break; }
1901
+ if (lastFail >= 0 && lastFail < lines.length - n) {
1902
+ const block = lines.slice(lastFail, Math.min(lastFail + Math.max(10, Math.floor(n / 2)), lines.length - n));
1903
+ return [...block, '…', ...tail.slice(-Math.max(1, n - block.length - 1))].join('\n');
1904
+ }
1905
+ return tail.join('\n');
1906
+ }
1907
+
1908
+ /** OXB-162: the test files a segment names (`x.test.ts`, `y.spec.js`, JVM `--tests` excluded). */
1909
+ export function segmentTestFiles(command: string): string[] {
1910
+ return [...new Set((String(command).match(/[\w./\\-]+\.(?:test|spec)\.[cm]?[jt]sx?\b/g) || []).map((f) => f.replace(/\\/g, '/').replace(/^\.\//, '')))].sort();
1911
+ }
1912
+
1913
+ /** What the next attempt needs to know about a failed task verify (1.20c informed retry). */
1914
+ /** One `&&` segment of a task verify, as run (1.21.2, OXB-066). */
1915
+ export interface VerifySegmentRun {
1916
+ index: number;
1917
+ total: number;
1918
+ command: string;
1919
+ status: string;
1920
+ check?: CheckResult;
1921
+ /** OXB-162: failed after an earlier segment of the same attempt passed the same files; rerun once. */
1922
+ flaky_suspect?: boolean;
1923
+ /** OXB-C28-2: the segments (1-based) that ran in this one remote round trip; index is the failing (or last) one. */
1924
+ merged?: number[];
1925
+ }
1926
+
1927
+ const REMOTE_SEG_RE = /(?:^|[\s/\\"'])remote-verify(?:\.[cm]?js)?["']?(?:\s|$)/i;
1928
+ const REMOTE_MARK = (n: number) => `===OXE-SEG-${n}===`;
1929
+
1930
+ /** The `<prefix>` and `<inner command>` of a `<… remote-verify.mjs [opts]> -- <command>` segment, or null. */
1931
+ function remoteSegmentParts(segment: string): { prefix: string; inner: string } | null {
1932
+ const idx = segment.indexOf(' -- ');
1933
+ if (idx <= 0) return null;
1934
+ const prefix = segment.slice(0, idx).trim();
1935
+ // the prefix is the runner and its own options: the remote-verify script must be in it
1936
+ if (!REMOTE_SEG_RE.test(prefix)) return null;
1937
+ let inner = segment.slice(idx + 4).trim();
1938
+ const q = inner[0];
1939
+ if ((q === '"' || q === "'") && inner.endsWith(q) && inner.length > 1 && !inner.slice(1, -1).includes(q)) inner = inner.slice(1, -1).trim();
1940
+ // only text that survives inside one double-quoted shell argument on both sh and cmd; gradle152 has its own path
1941
+ if (!inner || /["`$\\%!]/.test(inner) || /gradle152\.mjs/i.test(inner)) return null;
1942
+ return { prefix, inner };
1943
+ }
1944
+
1945
+ /**
1946
+ * OXB-C28-2: consecutive `… remote-verify … -- <cmd>` segments with the same runner prefix run as ONE remote job
1947
+ * (`<prefix> -- "echo ===OXE-SEG-1=== && cmd1 && echo ===OXE-SEG-2=== && cmd2"`) — one push/queue/CI round trip
1948
+ * instead of one per segment (polish2 T3: 8 segments, 2–5 min each). The markers name the failing segment.
1949
+ * `members` are 0-based indexes into `segments`.
1950
+ */
1951
+ export function groupRemoteSegments(segments: string[]): Array<{ command: string; members: number[] }> {
1952
+ const out: Array<{ command: string; members: number[]; prefix?: string; inners?: string[] }> = [];
1953
+ segments.forEach((seg, i) => {
1954
+ const parts = remoteSegmentParts(seg);
1955
+ const prev = out[out.length - 1];
1956
+ if (parts && prev && prev.prefix === parts.prefix && prev.inners) {
1957
+ prev.members.push(i);
1958
+ prev.inners.push(parts.inner);
1959
+ return;
1960
+ }
1961
+ out.push(parts ? { command: seg, members: [i], prefix: parts.prefix, inners: [parts.inner] } : { command: seg, members: [i] });
1962
+ });
1963
+ return out.map((u) => (u.members.length > 1 && u.prefix && u.inners
1964
+ ? { command: `${u.prefix} -- "${u.inners.map((c, k) => `echo ${REMOTE_MARK(u.members[k] + 1)} && ${c}`).join(' && ')}"`, members: u.members }
1965
+ : { command: u.command, members: u.members }));
1966
+ }
1967
+
1968
+ /** OXB-C28-2: the 0-based segment of a merged remote run that failed — the last marker the remote log printed. */
1969
+ export function remoteFailedMember(output: string, members: number[]): number {
1970
+ let found = members[0];
1971
+ for (const m of members) if (String(output || '').includes(REMOTE_MARK(m + 1))) found = m;
1972
+ return found;
1973
+ }
1974
+
1975
+ export interface VerifyNodeResult {
1976
+ status: string;
1977
+ gaps?: string[];
1978
+ /** The failing segment's check (or the last one run). */
1979
+ check?: CheckResult;
1980
+ /** The segment that failed, when the verify has segments and one failed. */
1981
+ segment?: { index: number; total: number; command: string; exit_code: number | null } | null;
1982
+ segments?: VerifySegmentRun[];
1983
+ }
1984
+
1985
+ /**
1986
+ * Top-level `&&` segments of a verify command (quoted text is not split). Same rule as the dry-verify (OXB-018), so
1987
+ * what the planner checks before execution is what runs after.
1988
+ */
1989
+ export function splitVerifySegments(command: string): string[] {
1990
+ const out: string[] = [];
1991
+ let current = '';
1992
+ let quote: string | null = null;
1993
+ for (let i = 0; i < command.length; i += 1) {
1994
+ const ch = command[i];
1995
+ if (quote) {
1996
+ if (ch === quote) quote = null;
1997
+ } else if (ch === '"' || ch === "'") {
1998
+ quote = ch;
1999
+ } else if (ch === '&' && command[i + 1] === '&') {
2000
+ if (current.trim()) out.push(current.trim());
2001
+ current = '';
2002
+ i += 1;
2003
+ continue;
2004
+ }
2005
+ current += ch;
2006
+ }
2007
+ if (current.trim()) out.push(current.trim());
2008
+ return out.length ? out : [command];
2009
+ }
2010
+
2011
+ /** OXB-184: the retry text plus what the previous attempt left in the tree. */
2012
+ export function withAttemptChanges(previousError: string | null, changes: { kept: string[]; gone: string[] } | null): string | null {
2013
+ if (!changes || (!changes.kept.length && !changes.gone.length)) return previousError;
2014
+ const list = (xs: string[]) => xs.slice(0, 30).join(', ') + (xs.length > 30 ? ` (+${xs.length - 30})` : '');
2015
+ const lines = ['', '## O que a tentativa anterior deixou na árvore'];
2016
+ if (changes.kept.length) lines.push(`Mantidos (o verify desta tentativa os vê; não refaça sem motivo): ${list(changes.kept)}`);
2017
+ if (changes.gone.length) lines.push(`Escritos e NÃO mantidos (refaça se ainda forem necessários): ${list(changes.gone)}`);
2018
+ return `${previousError ?? ''}${lines.join('\n')}`;
2019
+ }
2020
+
2021
+ /** Every segment's output with a header per segment, for the attempt log (`attempts/<Tn>-<n>.log`). */
2022
+ export function buildVerifyLog(segments: VerifySegmentRun[] | undefined, maxLinesPerSegment = 120): string {
2023
+ return (segments ?? []).map((s) => {
2024
+ const check = s.check;
2025
+ const exit = check?.exit_code != null ? `exit ${check.exit_code}` : check?.error ? check.error : s.status;
2026
+ const body = tailLines(`${check?.stdout ?? ''}\n${check?.stderr ?? ''}`, maxLinesPerSegment);
2027
+ return `=== [${s.index}/${s.total}] ${s.command} — ${s.status} (${exit})${s.flaky_suspect ? ' · flaky_suspect (repetido: passou antes nesta tentativa)' : ''}${s.merged ? ` · uma rodada remota com os segmentos ${s.merged.join(', ')}` : ''} ===\n${body || '(sem saída)'}`;
2028
+ }).join('\n\n');
2029
+ }
2030
+
2031
+ export function describeVerifyFailure(
2032
+ command: string | null | undefined,
2033
+ check: CheckResult | undefined,
2034
+ gaps?: string[],
2035
+ segment?: { index: number; total: number; command: string } | null,
2036
+ segments?: VerifySegmentRun[],
2037
+ ): string {
2038
+ const failedList = (segments ?? []).filter((s) => s.status === 'failed');
2039
+ if (failedList.length > 1) {
2040
+ const blocks = failedList.map((f) => {
2041
+ const r = f.check?.error || (f.check?.exit_code != null ? `exit code ${f.check.exit_code}` : 'failed');
2042
+ const out = tailLines(`${f.check?.stdout ?? ''}\n${f.check?.stderr ?? ''}`, 30);
2043
+ return `Failing segment [${f.index}/${f.total}]: ${f.command} (${r})\n${out ? out.slice(-2500) : '(empty)'}`;
2044
+ });
2045
+ return [
2046
+ 'Verification failed after your previous attempt.',
2047
+ `Command: ${command ?? '(none)'}`,
2048
+ `${failedList.length} of ${failedList[0].total} verify segments failed:`,
2049
+ ...blocks,
2050
+ 'Fix the code so all failing segments pass. If you are certain a command itself is wrong (not the code), stop and call finish_task explaining why — do not work around it.',
2051
+ ].join('\n');
2052
+ }
2053
+ const reason = check?.error || (check?.exit_code != null ? `exit code ${check.exit_code}` : (gaps || []).join('; ') || 'checks did not pass');
2054
+ // Only the failing segment's output: the tail of a passing earlier segment never reaches the executor (OXB-066).
2055
+ const output = tailLines(`${check?.stdout ?? ''}\n${check?.stderr ?? ''}`, 40);
2056
+ const failingLine = segment && segment.total > 1
2057
+ ? [`Failing segment [${segment.index}/${segment.total}]: ${segment.command}`, `(segments before it passed; the output below is only from this segment)`]
2058
+ : [];
2059
+ return [
2060
+ 'Verification failed after your previous attempt.',
2061
+ `Command: ${command ?? '(none)'}`,
2062
+ ...failingLine,
2063
+ `Reason: ${reason}`,
2064
+ output ? `Output (last lines):\n${output.slice(-4000)}` : 'Output: (empty)',
2065
+ 'Fix the code so this exact command passes. If you are certain the command itself is wrong (not the code), stop and call finish_task explaining why — do not work around it.',
2066
+ ].join('\n');
2067
+ }
2068
+
2069
+ /** Normalized failure fingerprint: timings, timestamps, hashes and temp paths removed. */
2070
+ export function verifyFailureSignature(check: CheckResult | undefined): string | null {
2071
+ if (!check) return null;
2072
+ const raw = `${check.error ?? ''}\n${check.stderr ?? ''}\n${check.stdout ?? ''}`;
2073
+ const normalized = raw
2074
+ .replace(/\d{4}-\d{2}-\d{2}T[\d:.]+Z?/g, '<ts>')
2075
+ .replace(/\b\d+(\.\d+)?\s?(ms|s)\b/g, '<t>')
2076
+ .replace(/\b[0-9a-f]{7,64}\b/gi, '<hash>')
2077
+ .replace(/[A-Za-z]:\\[^\s'"]*|\/tmp\/[^\s'"]*/g, '<path>')
2078
+ .replace(/\s+/g, ' ')
2079
+ .trim();
2080
+ return normalized ? normalized.slice(-1200) : null;
2081
+ }