oxe-cc 1.16.0 → 1.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (590) 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 +45 -45
  9. package/.cursor/commands/oxe-execute.md +52 -50
  10. package/.cursor/commands/oxe-forensics.md +1 -1
  11. package/.cursor/commands/oxe-help.md +44 -44
  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 +44 -44
  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 +49 -47
  18. package/.cursor/commands/oxe-project.md +1 -1
  19. package/.cursor/commands/oxe-quick.md +49 -47
  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 +47 -47
  23. package/.cursor/commands/oxe-route.md +1 -1
  24. package/.cursor/commands/oxe-scan.md +47 -47
  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 +47 -47
  28. package/.cursor/commands/oxe-skill.md +1 -1
  29. package/.cursor/commands/oxe-spec.md +49 -47
  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 +50 -50
  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 +51 -49
  39. package/.github/copilot-instructions.md +3 -3
  40. package/.github/prompts/oxe-alm.prompt.md +47 -0
  41. package/.github/prompts/oxe-ask.prompt.md +47 -47
  42. package/.github/prompts/oxe-capabilities.prompt.md +47 -47
  43. package/.github/prompts/oxe-checkpoint.prompt.md +47 -47
  44. package/.github/prompts/oxe-compact.prompt.md +46 -46
  45. package/.github/prompts/oxe-dashboard.prompt.md +47 -47
  46. package/.github/prompts/oxe-debug.prompt.md +47 -47
  47. package/.github/prompts/oxe-discuss.prompt.md +47 -47
  48. package/.github/prompts/oxe-execute.prompt.md +52 -50
  49. package/.github/prompts/oxe-forensics.prompt.md +47 -47
  50. package/.github/prompts/oxe-help.prompt.md +46 -46
  51. package/.github/prompts/oxe-loop.prompt.md +47 -47
  52. package/.github/prompts/oxe-milestone.prompt.md +47 -47
  53. package/.github/prompts/oxe-next.prompt.md +46 -46
  54. package/.github/prompts/oxe-obs.prompt.md +47 -47
  55. package/.github/prompts/oxe-plan-agent.prompt.md +46 -46
  56. package/.github/prompts/oxe-plan.prompt.md +49 -47
  57. package/.github/prompts/oxe-project.prompt.md +47 -47
  58. package/.github/prompts/oxe-quick.prompt.md +49 -47
  59. package/.github/prompts/oxe-research.prompt.md +47 -47
  60. package/.github/prompts/oxe-retro.prompt.md +47 -47
  61. package/.github/prompts/oxe-review-pr.prompt.md +47 -47
  62. package/.github/prompts/oxe-route.prompt.md +47 -47
  63. package/.github/prompts/oxe-scan.prompt.md +47 -47
  64. package/.github/prompts/oxe-security.prompt.md +47 -47
  65. package/.github/prompts/oxe-session.prompt.md +47 -47
  66. package/.github/prompts/oxe-ship.prompt.md +47 -47
  67. package/.github/prompts/oxe-skill.prompt.md +47 -47
  68. package/.github/prompts/oxe-spec.prompt.md +49 -47
  69. package/.github/prompts/oxe-ui-review.prompt.md +47 -47
  70. package/.github/prompts/oxe-ui-spec.prompt.md +47 -47
  71. package/.github/prompts/oxe-update.prompt.md +46 -46
  72. package/.github/prompts/oxe-validate-gaps.prompt.md +47 -47
  73. package/.github/prompts/oxe-verify-audit.prompt.md +1 -1
  74. package/.github/prompts/oxe-verify.prompt.md +50 -50
  75. package/.github/prompts/oxe-workflow-authoring.prompt.md +1 -1
  76. package/.github/prompts/oxe-workstream.prompt.md +47 -47
  77. package/.github/prompts/oxe.prompt.md +51 -49
  78. package/.github/workflows/ci.yml +26 -5
  79. package/.github/workflows/release.yml +15 -14
  80. package/AGENTS.md +15 -9
  81. package/CHANGELOG.md +1027 -10
  82. package/LICENSE +21 -21
  83. package/QUICKSTART.md +99 -99
  84. package/README.md +120 -17
  85. package/assets/readme-banner.svg +19 -19
  86. package/bin/banner.txt +5 -5
  87. package/bin/lib/oxe-acceptance-audit.cjs +195 -0
  88. package/bin/lib/oxe-adr.cjs +145 -0
  89. package/bin/lib/oxe-agent-install.cjs +31 -29
  90. package/bin/lib/oxe-alm-admin.cjs +215 -0
  91. package/bin/lib/oxe-alm-metrics.cjs +143 -0
  92. package/bin/lib/oxe-alm-prs.cjs +274 -0
  93. package/bin/lib/oxe-alm-refine.cjs +1003 -0
  94. package/bin/lib/oxe-alm.cjs +1289 -0
  95. package/bin/lib/oxe-anchor-copy.cjs +218 -0
  96. package/bin/lib/oxe-api-surface.cjs +96 -0
  97. package/bin/lib/oxe-artifact-refs.cjs +72 -0
  98. package/bin/lib/oxe-attention.cjs +97 -0
  99. package/bin/lib/oxe-autoresume.cjs +448 -0
  100. package/bin/lib/oxe-azure.cjs +1445 -1445
  101. package/bin/lib/oxe-budget.cjs +154 -0
  102. package/bin/lib/oxe-change-folder.cjs +130 -0
  103. package/bin/lib/oxe-change.cjs +389 -0
  104. package/bin/lib/oxe-channels.cjs +82 -0
  105. package/bin/lib/oxe-cited-paths.cjs +180 -0
  106. package/bin/lib/oxe-cli-errors.cjs +76 -0
  107. package/bin/lib/oxe-cli-output.cjs +111 -0
  108. package/bin/lib/oxe-commit-convention.cjs +104 -0
  109. package/bin/lib/oxe-complexity.cjs +106 -0
  110. package/bin/lib/oxe-console-decode.cjs +23 -0
  111. package/bin/lib/oxe-coordinator-queue.cjs +67 -0
  112. package/bin/lib/oxe-core-command-handlers.cjs +10 -8
  113. package/bin/lib/oxe-criteria-ids.cjs +87 -0
  114. package/bin/lib/oxe-criterion-coverage.cjs +93 -0
  115. package/bin/lib/oxe-cross-card-conflicts.cjs +639 -0
  116. package/bin/lib/oxe-customize.cjs +146 -0
  117. package/bin/lib/oxe-dashboard.cjs +1 -1
  118. package/bin/lib/oxe-decisions.cjs +211 -0
  119. package/bin/lib/oxe-deferred.cjs +80 -0
  120. package/bin/lib/oxe-deps-audit.cjs +136 -0
  121. package/bin/lib/oxe-diff-reviewer.cjs +105 -0
  122. package/bin/lib/oxe-dir-info.cjs +138 -0
  123. package/bin/lib/oxe-docs-check.cjs +124 -0
  124. package/bin/lib/oxe-docs-publish.cjs +81 -0
  125. package/bin/lib/oxe-dom-hooks.cjs +902 -0
  126. package/bin/lib/oxe-dossier.cjs +355 -0
  127. package/bin/lib/oxe-e2e-ready.cjs +360 -0
  128. package/bin/lib/oxe-env-sanitize.cjs +155 -0
  129. package/bin/lib/oxe-event-bus.cjs +118 -118
  130. package/bin/lib/oxe-failure-cost.cjs +144 -0
  131. package/bin/lib/oxe-file-size-guard.cjs +849 -0
  132. package/bin/lib/oxe-findings.cjs +86 -0
  133. package/bin/lib/oxe-grill-cases.cjs +148 -0
  134. package/bin/lib/oxe-grill.cjs +444 -0
  135. package/bin/lib/oxe-grooming.cjs +115 -0
  136. package/bin/lib/oxe-guard.cjs +180 -0
  137. package/bin/lib/oxe-handoff.cjs +97 -0
  138. package/bin/lib/oxe-install-resolve.cjs +28 -0
  139. package/bin/lib/oxe-integration-checks.cjs +285 -0
  140. package/bin/lib/oxe-intent-context.cjs +101 -0
  141. package/bin/lib/oxe-journey.cjs +403 -0
  142. package/bin/lib/oxe-known-failures.cjs +138 -0
  143. package/bin/lib/oxe-local-config.cjs +77 -0
  144. package/bin/lib/oxe-memory-kernel.cjs +190 -188
  145. package/bin/lib/oxe-merge-train.cjs +277 -0
  146. package/bin/lib/oxe-model-resolve.cjs +74 -0
  147. package/bin/lib/oxe-model-tiers.cjs +65 -0
  148. package/bin/lib/oxe-nfr.cjs +125 -0
  149. package/bin/lib/oxe-npm-version.cjs +1 -1
  150. package/bin/lib/oxe-open-defects.cjs +121 -0
  151. package/bin/lib/oxe-operational.cjs +14339 -1066
  152. package/bin/lib/oxe-origin-guard.cjs +102 -0
  153. package/bin/lib/oxe-origin.cjs +377 -0
  154. package/bin/lib/oxe-pack-removed.cjs +208 -0
  155. package/bin/lib/oxe-parallel-run.cjs +81 -0
  156. package/bin/lib/oxe-parallel.cjs +234 -0
  157. package/bin/lib/oxe-phase-extras.cjs +185 -0
  158. package/bin/lib/oxe-phase-gates.cjs +551 -0
  159. package/bin/lib/oxe-plan-build.cjs +1520 -0
  160. package/bin/lib/oxe-plan-json.cjs +1107 -0
  161. package/bin/lib/oxe-plan-merge.cjs +253 -0
  162. package/bin/lib/oxe-plan-mutate.cjs +214 -0
  163. package/bin/lib/oxe-plan-repair.cjs +479 -0
  164. package/bin/lib/oxe-plan-review.cjs +256 -0
  165. package/bin/lib/oxe-plan-skeleton.cjs +494 -0
  166. package/bin/lib/oxe-plan-staleness.cjs +125 -0
  167. package/bin/lib/oxe-plugin-cli.cjs +3 -1
  168. package/bin/lib/oxe-policy-rules.cjs +144 -0
  169. package/bin/lib/oxe-prd.cjs +129 -0
  170. package/bin/lib/oxe-preflight.cjs +378 -0
  171. package/bin/lib/oxe-process.cjs +11 -11
  172. package/bin/lib/oxe-program-members.cjs +97 -0
  173. package/bin/lib/oxe-program.cjs +245 -0
  174. package/bin/lib/oxe-progress-run.cjs +80 -0
  175. package/bin/lib/oxe-project-env.cjs +273 -0
  176. package/bin/lib/oxe-project-health.cjs +619 -41
  177. package/bin/lib/oxe-promote-helpers.cjs +1561 -0
  178. package/bin/lib/oxe-provider-antigravity.cjs +114 -0
  179. package/bin/lib/oxe-provider-grok.cjs +48 -0
  180. package/bin/lib/oxe-questions.cjs +115 -0
  181. package/bin/lib/oxe-quick.cjs +537 -0
  182. package/bin/lib/oxe-ratchets.cjs +132 -0
  183. package/bin/lib/oxe-rationality.cjs +587 -532
  184. package/bin/lib/oxe-real-regression.cjs +97 -0
  185. package/bin/lib/oxe-recovery.cjs +160 -0
  186. package/bin/lib/oxe-release-ops.cjs +325 -0
  187. package/bin/lib/oxe-release.cjs +622 -551
  188. package/bin/lib/oxe-repair.cjs +153 -0
  189. package/bin/lib/oxe-repo-map.cjs +136 -0
  190. package/bin/lib/oxe-repo-rules.cjs +121 -0
  191. package/bin/lib/oxe-research-provenance.cjs +96 -0
  192. package/bin/lib/oxe-resume.cjs +406 -0
  193. package/bin/lib/oxe-review.cjs +403 -0
  194. package/bin/lib/oxe-rfc.cjs +192 -0
  195. package/bin/lib/oxe-risk-decision.cjs +141 -0
  196. package/bin/lib/oxe-runtime-semantics.cjs +8 -1
  197. package/bin/lib/oxe-scorecard.cjs +234 -0
  198. package/bin/lib/oxe-scratch.cjs +81 -0
  199. package/bin/lib/oxe-seams.cjs +159 -0
  200. package/bin/lib/oxe-security.cjs +289 -289
  201. package/bin/lib/oxe-semver.cjs +83 -0
  202. package/bin/lib/oxe-ship-pr.cjs +204 -0
  203. package/bin/lib/oxe-signal.cjs +173 -0
  204. package/bin/lib/oxe-skill-loader.cjs +131 -131
  205. package/bin/lib/oxe-spec-check.cjs +217 -0
  206. package/bin/lib/oxe-spec-ears.cjs +98 -0
  207. package/bin/lib/oxe-spec-edit.cjs +411 -0
  208. package/bin/lib/oxe-spec-freeze.cjs +378 -0
  209. package/bin/lib/oxe-spec-probe.cjs +146 -0
  210. package/bin/lib/oxe-spec-stress.cjs +146 -0
  211. package/bin/lib/oxe-spike.cjs +98 -0
  212. package/bin/lib/oxe-state.cjs +87 -0
  213. package/bin/lib/oxe-stub-check.cjs +355 -0
  214. package/bin/lib/oxe-suite-impact.cjs +1145 -0
  215. package/bin/lib/oxe-sync.cjs +250 -0
  216. package/bin/lib/oxe-system-design.cjs +138 -0
  217. package/bin/lib/oxe-task-gates.cjs +139 -0
  218. package/bin/lib/oxe-telemetry.cjs +201 -0
  219. package/bin/lib/oxe-test-precheck.cjs +508 -0
  220. package/bin/lib/oxe-test-rigor.cjs +663 -0
  221. package/bin/lib/oxe-test-scope.cjs +883 -0
  222. package/bin/lib/oxe-trace.cjs +168 -0
  223. package/bin/lib/oxe-turns.cjs +64 -0
  224. package/bin/lib/oxe-ui-evidence.cjs +187 -0
  225. package/bin/lib/oxe-ui-verify.cjs +55 -0
  226. package/bin/lib/oxe-unsafe-commands.cjs +94 -0
  227. package/bin/lib/oxe-verdicts.cjs +131 -0
  228. package/bin/lib/oxe-verify-dryrun.cjs +541 -0
  229. package/bin/lib/oxe-verify-remote.cjs +208 -0
  230. package/bin/lib/oxe-vitest-batch.cjs +142 -0
  231. package/bin/lib/oxe-workflow-budget.cjs +99 -0
  232. package/bin/lib/oxe-workflow-eval.cjs +118 -0
  233. package/bin/lib/oxe-workflows.cjs +3 -1
  234. package/bin/lib/oxe-worktree-deps.cjs +241 -0
  235. package/bin/lib/oxe-worktree-gc.cjs +170 -0
  236. package/bin/oxe-cc.js +4934 -94
  237. package/commands/oxe/alm.md +54 -0
  238. package/commands/oxe/ask.md +55 -55
  239. package/commands/oxe/capabilities.md +50 -50
  240. package/commands/oxe/checkpoint.md +53 -53
  241. package/commands/oxe/compact.md +47 -47
  242. package/commands/oxe/dashboard.md +51 -51
  243. package/commands/oxe/debug.md +58 -58
  244. package/commands/oxe/discuss.md +58 -58
  245. package/commands/oxe/execute.md +63 -61
  246. package/commands/oxe/forensics.md +53 -53
  247. package/commands/oxe/help.md +48 -48
  248. package/commands/oxe/loop.md +54 -54
  249. package/commands/oxe/milestone.md +53 -53
  250. package/commands/oxe/next.md +49 -49
  251. package/commands/oxe/obs.md +53 -53
  252. package/commands/oxe/oxe.md +55 -53
  253. package/commands/oxe/plan-agent.md +57 -57
  254. package/commands/oxe/plan.md +59 -57
  255. package/commands/oxe/project.md +53 -53
  256. package/commands/oxe/quick.md +53 -53
  257. package/commands/oxe/research.md +53 -53
  258. package/commands/oxe/retro.md +53 -53
  259. package/commands/oxe/review-pr.md +53 -53
  260. package/commands/oxe/route.md +48 -48
  261. package/commands/oxe/scan.md +58 -58
  262. package/commands/oxe/security.md +53 -53
  263. package/commands/oxe/session.md +53 -53
  264. package/commands/oxe/ship.md +53 -53
  265. package/commands/oxe/skill.md +53 -53
  266. package/commands/oxe/spec.md +59 -56
  267. package/commands/oxe/ui-review.md +53 -53
  268. package/commands/oxe/ui-spec.md +53 -53
  269. package/commands/oxe/update.md +53 -53
  270. package/commands/oxe/validate-gaps.md +53 -53
  271. package/commands/oxe/verify-audit.md +50 -50
  272. package/commands/oxe/verify.md +60 -60
  273. package/commands/oxe/workflow-authoring.md +50 -50
  274. package/commands/oxe/workstream.md +53 -53
  275. package/docs/ADLC-COVERAGE.md +55 -0
  276. package/docs/CONTENT-MIGRATION-AUDIT.md +49 -49
  277. package/docs/HAPPY-PATH.md +106 -0
  278. package/docs/INCIDENT-PLAYBOOK.md +181 -181
  279. package/docs/RELEASE-READINESS.md +1 -0
  280. package/docs/ROLES.md +129 -129
  281. package/docs/TEAM-ADOPTION.md +153 -153
  282. package/docs/WALKTHROUGH.md +241 -241
  283. package/docs/adr/D-1-isolamento-read-only-e-sanitizacao-centralizada-de-env-vars.md +29 -0
  284. package/docs/adr/D-2-junction-segura-de-node-modules-condicionada-a-sha-256-de-pa.md +29 -0
  285. package/docs/adr/D-3-preflight-local-5s-impacto-estatico-e2e-e-leitura-explicita.md +29 -0
  286. package/docs/adr/D-4-governanca-de-release-unificada-retomada-idempotente-pos-rei.md +29 -0
  287. package/docs/adr/README.md +15 -0
  288. package/docs/cli-errors.md +20 -0
  289. package/docs/oxespace-1.5/BACKLOG.md +2056 -0
  290. package/docs/oxespace-1.5/HANDOFF-1.21.2.md +140 -0
  291. package/docs/oxevoice/BACKLOG.md +244 -0
  292. package/lib/runtime/compiler/graph-compiler.d.ts +15 -0
  293. package/lib/runtime/compiler/graph-compiler.js +49 -3
  294. package/lib/runtime/delivery/promotion-pipeline.d.ts +1 -0
  295. package/lib/runtime/delivery/promotion-pipeline.js +59 -2
  296. package/lib/runtime/events/catalog.d.ts +1 -1
  297. package/lib/runtime/events/catalog.js +29 -0
  298. package/lib/runtime/executor/action-tool-map.d.ts +3 -1
  299. package/lib/runtime/executor/action-tool-map.js +4 -1
  300. package/lib/runtime/executor/adapters/antigravity-cli.d.ts +103 -0
  301. package/lib/runtime/executor/adapters/antigravity-cli.js +530 -0
  302. package/lib/runtime/executor/adapters/claude-cli.d.ts +92 -0
  303. package/lib/runtime/executor/adapters/claude-cli.js +328 -0
  304. package/lib/runtime/executor/adapters/grok-cli.d.ts +89 -0
  305. package/lib/runtime/executor/adapters/grok-cli.js +351 -0
  306. package/lib/runtime/executor/adapters/http-openai.d.ts +9 -0
  307. package/lib/runtime/executor/adapters/http-openai.js +18 -0
  308. package/lib/runtime/executor/adapters/registry.d.ts +18 -0
  309. package/lib/runtime/executor/adapters/registry.js +49 -0
  310. package/lib/runtime/executor/adapters/types.d.ts +21 -0
  311. package/lib/runtime/executor/adapters/types.js +2 -0
  312. package/lib/runtime/executor/built-in-tools.d.ts +64 -0
  313. package/lib/runtime/executor/built-in-tools.js +257 -24
  314. package/lib/runtime/executor/index.d.ts +19 -2
  315. package/lib/runtime/executor/index.js +50 -1
  316. package/lib/runtime/executor/llm-task-executor.d.ts +108 -2
  317. package/lib/runtime/executor/llm-task-executor.js +598 -39
  318. package/lib/runtime/executor/node-context.d.ts +94 -0
  319. package/lib/runtime/executor/node-context.js +126 -0
  320. package/lib/runtime/executor/node-prompt-builder.d.ts +2 -0
  321. package/lib/runtime/executor/node-prompt-builder.js +4 -0
  322. package/lib/runtime/executor/quota-patterns.d.ts +7 -0
  323. package/lib/runtime/executor/quota-patterns.js +39 -0
  324. package/lib/runtime/executor/shell-argv.d.ts +41 -0
  325. package/lib/runtime/executor/shell-argv.js +144 -0
  326. package/lib/runtime/executor/stream-completion.d.ts +27 -0
  327. package/lib/runtime/executor/stream-completion.js +82 -5
  328. package/lib/runtime/index.d.ts +5 -2
  329. package/lib/runtime/index.js +10 -1
  330. package/lib/runtime/models/failure.d.ts +1 -1
  331. package/lib/runtime/models/run.d.ts +1 -1
  332. package/lib/runtime/program/index.d.ts +1 -0
  333. package/lib/runtime/program/index.js +17 -0
  334. package/lib/runtime/program/program-model.d.ts +92 -0
  335. package/lib/runtime/program/program-model.js +262 -0
  336. package/lib/runtime/projection/projection-engine.d.ts +16 -1
  337. package/lib/runtime/projection/projection-engine.js +55 -3
  338. package/lib/runtime/reducers/run-state-reducer.js +48 -5
  339. package/lib/runtime/scheduler/run-journal.d.ts +27 -1
  340. package/lib/runtime/scheduler/run-journal.js +40 -1
  341. package/lib/runtime/scheduler/scheduler.d.ts +239 -0
  342. package/lib/runtime/scheduler/scheduler.js +1157 -97
  343. package/lib/runtime/verification/contract-exports.d.ts +24 -0
  344. package/lib/runtime/verification/contract-exports.js +201 -0
  345. package/lib/runtime/verification/index.d.ts +1 -0
  346. package/lib/runtime/verification/index.js +1 -0
  347. package/lib/runtime/verification/runner-timeout.d.ts +7 -0
  348. package/lib/runtime/verification/runner-timeout.js +17 -0
  349. package/lib/runtime/verification/test-report-parsers.d.ts +38 -0
  350. package/lib/runtime/verification/test-report-parsers.js +188 -0
  351. package/lib/runtime/verification/verification-compiler.d.ts +101 -2
  352. package/lib/runtime/verification/verification-compiler.js +491 -82
  353. package/lib/runtime/verification/verification-manifest.d.ts +12 -0
  354. package/lib/runtime/verification/verification-manifest.js +33 -4
  355. package/lib/runtime/workspace/index.d.ts +2 -1
  356. package/lib/runtime/workspace/index.js +3 -1
  357. package/lib/runtime/workspace/strategies/ephemeral-container.d.ts +9 -0
  358. package/lib/runtime/workspace/strategies/ephemeral-container.js +37 -10
  359. package/lib/runtime/workspace/strategies/git-worktree.d.ts +24 -1
  360. package/lib/runtime/workspace/strategies/git-worktree.js +134 -1
  361. package/lib/sdk/README.md +21 -21
  362. package/lib/sdk/index.cjs +27 -9
  363. package/oxe/agents/oxe-assumptions-analyzer.md +136 -136
  364. package/oxe/agents/oxe-codebase-mapper.md +142 -142
  365. package/oxe/agents/oxe-debugger.md +145 -145
  366. package/oxe/agents/oxe-executor.md +139 -139
  367. package/oxe/agents/oxe-integration-checker.md +142 -142
  368. package/oxe/agents/oxe-plan-checker.md +143 -143
  369. package/oxe/agents/oxe-planner.md +151 -151
  370. package/oxe/agents/oxe-research-synthesizer.md +146 -146
  371. package/oxe/agents/oxe-researcher.md +163 -163
  372. package/oxe/agents/oxe-ui-auditor.md +151 -151
  373. package/oxe/agents/oxe-ui-checker.md +157 -157
  374. package/oxe/agents/oxe-ui-researcher.md +179 -179
  375. package/oxe/agents/oxe-validation-auditor.md +154 -154
  376. package/oxe/agents/oxe-verifier.md +132 -132
  377. package/oxe/migrations/config-migrations.json +15 -0
  378. package/oxe/personas/README.md +91 -91
  379. package/oxe/personas/architect.md +149 -149
  380. package/oxe/personas/db-specialist.md +149 -149
  381. package/oxe/personas/debugger.md +155 -155
  382. package/oxe/personas/executor.md +164 -164
  383. package/oxe/personas/planner.md +165 -165
  384. package/oxe/personas/researcher.md +148 -148
  385. package/oxe/personas/ui-specialist.md +164 -164
  386. package/oxe/personas/verifier.md +174 -174
  387. package/oxe/schemas/plan-agents.schema.json +122 -122
  388. package/oxe/schemas/plan.schema.json +101 -0
  389. package/oxe/schemas/role-plan.schema.json +50 -0
  390. package/oxe/schemas/swarm-run.schema.json +130 -130
  391. package/oxe/templates/ACTIVE-RUN.template.json +32 -32
  392. package/oxe/templates/CAPABILITIES.template.md +7 -7
  393. package/oxe/templates/CAPABILITY.template.md +45 -45
  394. package/oxe/templates/CHECKPOINT.template.md +37 -37
  395. package/oxe/templates/CHECKPOINTS.template.md +7 -7
  396. package/oxe/templates/CODEBASE-DELTA.template.md +33 -33
  397. package/oxe/templates/CONFIG.md +172 -0
  398. package/oxe/templates/DISCUSS.template.md +1 -0
  399. package/oxe/templates/DOCS_BROWNFIELD_LAYOUT.md +55 -55
  400. package/oxe/templates/FIXTURE-PACK.template.json +18 -18
  401. package/oxe/templates/FIXTURE-PACK.template.md +19 -19
  402. package/oxe/templates/GIT_HOOKS_OXE.md +52 -52
  403. package/oxe/templates/GLOSSARY.template.md +9 -0
  404. package/oxe/templates/HYPOTHESES.template.md +33 -33
  405. package/oxe/templates/IMPLEMENTATION-PACK.template.json +26 -26
  406. package/oxe/templates/IMPLEMENTATION-PACK.template.md +32 -32
  407. package/oxe/templates/INVESTIGATION.template.md +38 -38
  408. package/oxe/templates/LESSONS-METRICS.template.json +13 -13
  409. package/oxe/templates/LESSONS.template.md +43 -43
  410. package/oxe/templates/MEMORY.template.md +49 -49
  411. package/oxe/templates/MILESTONES.template.md +17 -17
  412. package/oxe/templates/NOTES.template.md +16 -16
  413. package/oxe/templates/OBSERVATIONS.template.md +18 -18
  414. package/oxe/templates/PLAN-REVIEW.template.md +31 -31
  415. package/oxe/templates/PLAN.template.md +87 -87
  416. package/oxe/templates/PRD.template.md +53 -0
  417. package/oxe/templates/REFERENCE-ANCHORS.template.md +30 -26
  418. package/oxe/templates/RESEARCH.template.md +8 -0
  419. package/oxe/templates/RESUME.template.md +49 -49
  420. package/oxe/templates/RFC.template.md +43 -0
  421. package/oxe/templates/ROADMAP.template.md +44 -44
  422. package/oxe/templates/SECURITY.template.md +72 -72
  423. package/oxe/templates/SESSION.template.md +34 -34
  424. package/oxe/templates/SKILL.template.md +26 -26
  425. package/oxe/templates/SPEC.template.md +65 -65
  426. package/oxe/templates/SUMMARY.template.md +50 -50
  427. package/oxe/templates/VISUAL-INPUTS.template.json +27 -27
  428. package/oxe/templates/VISUAL-INPUTS.template.md +36 -36
  429. package/oxe/templates/WORKFLOW_AUTHORING.md +93 -93
  430. package/oxe/templates/finding-rules.json +22 -0
  431. package/oxe/templates/plan-agent-messages-README.template.md +9 -9
  432. package/oxe/templates/plan-agents.template.json +30 -30
  433. package/oxe/templates/quick-agents.template.json +24 -24
  434. package/oxe/templates/stress-methods.md +33 -0
  435. package/oxe/workflows/agent-mode.md +150 -150
  436. package/oxe/workflows/alm.md +50 -0
  437. package/oxe/workflows/ask.md +96 -96
  438. package/oxe/workflows/capabilities.md +25 -25
  439. package/oxe/workflows/checkpoint.md +37 -37
  440. package/oxe/workflows/compact/plan.md +149 -0
  441. package/oxe/workflows/compact/spec.md +114 -0
  442. package/oxe/workflows/compact.md +1 -0
  443. package/oxe/workflows/conduct.md +149 -149
  444. package/oxe/workflows/dashboard.md +33 -33
  445. package/oxe/workflows/debug.md +9 -9
  446. package/oxe/workflows/discuss.md +15 -3
  447. package/oxe/workflows/distill.md +164 -164
  448. package/oxe/workflows/execute.md +30 -26
  449. package/oxe/workflows/forensics.md +5 -5
  450. package/oxe/workflows/help.md +10 -4
  451. package/oxe/workflows/lean/execute.md +42 -0
  452. package/oxe/workflows/lean/plan.md +60 -0
  453. package/oxe/workflows/lean/spec.md +61 -0
  454. package/oxe/workflows/loop.md +67 -67
  455. package/oxe/workflows/memory.md +163 -163
  456. package/oxe/workflows/milestone.md +95 -95
  457. package/oxe/workflows/next.md +10 -8
  458. package/oxe/workflows/obs.md +167 -167
  459. package/oxe/workflows/oxe.md +33 -14
  460. package/oxe/workflows/plan-agent.md +143 -143
  461. package/oxe/workflows/plan.md +49 -40
  462. package/oxe/workflows/project.md +55 -55
  463. package/oxe/workflows/quick.md +19 -5
  464. package/oxe/workflows/references/adaptive-discovery.md +27 -27
  465. package/oxe/workflows/references/alm-refine.md +55 -0
  466. package/oxe/workflows/references/azure-in-plan.md +5 -0
  467. package/oxe/workflows/references/change-management.md +48 -0
  468. package/oxe/workflows/references/grill.md +74 -0
  469. package/oxe/workflows/references/legacy-brownfield.md +136 -136
  470. package/oxe/workflows/references/next-step-footer.md +33 -0
  471. package/oxe/workflows/references/plan-agent-chat-protocol.md +99 -99
  472. package/oxe/workflows/references/plan-json-acceptance-program.md +174 -0
  473. package/oxe/workflows/references/product-docs-alm.md +51 -0
  474. package/oxe/workflows/references/reasoning-discovery.md +28 -28
  475. package/oxe/workflows/references/reasoning-execution.md +29 -29
  476. package/oxe/workflows/references/reasoning-planning.md +32 -32
  477. package/oxe/workflows/references/reasoning-review.md +29 -29
  478. package/oxe/workflows/references/reasoning-status.md +24 -24
  479. package/oxe/workflows/references/robustness-elevation.md +295 -295
  480. package/oxe/workflows/references/session-path-resolution.md +71 -71
  481. package/oxe/workflows/references/workflow-runtime-contracts.json +1167 -1151
  482. package/oxe/workflows/research.md +1 -0
  483. package/oxe/workflows/retro.md +117 -117
  484. package/oxe/workflows/review-pr.md +53 -53
  485. package/oxe/workflows/route.md +1 -1
  486. package/oxe/workflows/scan.md +356 -355
  487. package/oxe/workflows/security.md +67 -67
  488. package/oxe/workflows/session.md +213 -213
  489. package/oxe/workflows/ship.md +74 -125
  490. package/oxe/workflows/size-budget.json +62 -0
  491. package/oxe/workflows/skill.md +44 -44
  492. package/oxe/workflows/spec.md +92 -93
  493. package/oxe/workflows/swarm/board.md +119 -119
  494. package/oxe/workflows/swarm/scout.md +170 -170
  495. package/oxe/workflows/swarm-mode.md +280 -280
  496. package/oxe/workflows/ui-review.md +5 -5
  497. package/oxe/workflows/ui-spec.md +7 -7
  498. package/oxe/workflows/update.md +35 -35
  499. package/oxe/workflows/validate-gaps.md +45 -45
  500. package/oxe/workflows/verify-audit.md +73 -73
  501. package/oxe/workflows/verify.md +35 -14
  502. package/oxe/workflows/workflow-authoring.md +34 -34
  503. package/oxe/workflows/workstream.md +97 -97
  504. package/package.json +8 -3
  505. package/packages/runtime/package.json +1 -1
  506. package/packages/runtime/src/audit/audit-trail.ts +243 -243
  507. package/packages/runtime/src/audit/index.ts +2 -2
  508. package/packages/runtime/src/audit/policy-pack.ts +62 -62
  509. package/packages/runtime/src/compiler/graph-compiler.ts +67 -3
  510. package/packages/runtime/src/compiler/index.ts +1 -1
  511. package/packages/runtime/src/context/context-pack-store.ts +197 -197
  512. package/packages/runtime/src/context/context-profiles.ts +60 -60
  513. package/packages/runtime/src/context/index.ts +3 -3
  514. package/packages/runtime/src/decision/decision-engine.ts +174 -174
  515. package/packages/runtime/src/decision/decision-memo.ts +211 -211
  516. package/packages/runtime/src/decision/index.ts +2 -2
  517. package/packages/runtime/src/delivery/branch-manager.ts +91 -91
  518. package/packages/runtime/src/delivery/ci-checks.ts +285 -285
  519. package/packages/runtime/src/delivery/delivery-records.ts +75 -75
  520. package/packages/runtime/src/delivery/index.ts +5 -5
  521. package/packages/runtime/src/delivery/pr-manager.ts +112 -112
  522. package/packages/runtime/src/delivery/promotion-pipeline.ts +65 -2
  523. package/packages/runtime/src/events/bus.ts +92 -92
  524. package/packages/runtime/src/events/catalog.ts +29 -0
  525. package/packages/runtime/src/events/envelope.ts +14 -14
  526. package/packages/runtime/src/events/index.ts +3 -3
  527. package/packages/runtime/src/evidence/evidence-store.ts +130 -130
  528. package/packages/runtime/src/evidence/index.ts +1 -1
  529. package/packages/runtime/src/executor/action-tool-map.ts +52 -50
  530. package/packages/runtime/src/executor/adapters/antigravity-cli.ts +619 -0
  531. package/packages/runtime/src/executor/adapters/claude-cli.ts +367 -0
  532. package/packages/runtime/src/executor/adapters/grok-cli.ts +392 -0
  533. package/packages/runtime/src/executor/adapters/http-openai.ts +16 -0
  534. package/packages/runtime/src/executor/adapters/registry.ts +53 -0
  535. package/packages/runtime/src/executor/adapters/types.ts +24 -0
  536. package/packages/runtime/src/executor/built-in-tools.ts +525 -305
  537. package/packages/runtime/src/executor/index.ts +23 -6
  538. package/packages/runtime/src/executor/llm-task-executor.ts +854 -236
  539. package/packages/runtime/src/executor/node-context.ts +226 -0
  540. package/packages/runtime/src/executor/node-prompt-builder.ts +69 -62
  541. package/packages/runtime/src/executor/quota-patterns.ts +41 -0
  542. package/packages/runtime/src/executor/shell-argv.ts +144 -0
  543. package/packages/runtime/src/executor/stream-completion.ts +230 -145
  544. package/packages/runtime/src/gate/gate-manager.ts +289 -289
  545. package/packages/runtime/src/gate/index.ts +1 -1
  546. package/packages/runtime/src/index.ts +12 -0
  547. package/packages/runtime/src/models/attempt.ts +19 -19
  548. package/packages/runtime/src/models/evidence.ts +21 -21
  549. package/packages/runtime/src/models/failure.ts +22 -13
  550. package/packages/runtime/src/models/gate-decision.ts +25 -25
  551. package/packages/runtime/src/models/index.ts +8 -8
  552. package/packages/runtime/src/models/run.ts +1 -0
  553. package/packages/runtime/src/models/session.ts +11 -11
  554. package/packages/runtime/src/models/verification-result.ts +10 -10
  555. package/packages/runtime/src/models/work-item.ts +25 -25
  556. package/packages/runtime/src/models/workspace.ts +31 -31
  557. package/packages/runtime/src/plugins/capability-matrix.ts +126 -126
  558. package/packages/runtime/src/plugins/index.ts +5 -5
  559. package/packages/runtime/src/plugins/plugin-manifest.ts +118 -118
  560. package/packages/runtime/src/policy/index.ts +1 -1
  561. package/packages/runtime/src/policy/policy-engine.ts +330 -330
  562. package/packages/runtime/src/program/index.ts +1 -0
  563. package/packages/runtime/src/program/program-model.ts +293 -0
  564. package/packages/runtime/src/projection/index.ts +1 -1
  565. package/packages/runtime/src/projection/projection-engine.ts +61 -3
  566. package/packages/runtime/src/reducers/debug-reducer.ts +36 -36
  567. package/packages/runtime/src/reducers/index.ts +2 -2
  568. package/packages/runtime/src/reducers/run-state-reducer.ts +44 -5
  569. package/packages/runtime/src/scheduler/agent-registry.ts +132 -132
  570. package/packages/runtime/src/scheduler/agent-roles.ts +109 -109
  571. package/packages/runtime/src/scheduler/index.ts +4 -4
  572. package/packages/runtime/src/scheduler/run-journal.ts +47 -2
  573. package/packages/runtime/src/scheduler/scheduler.ts +1242 -99
  574. package/packages/runtime/src/verification/contract-exports.ts +203 -0
  575. package/packages/runtime/src/verification/index.ts +1 -0
  576. package/packages/runtime/src/verification/runner-timeout.ts +17 -0
  577. package/packages/runtime/src/verification/test-report-parsers.ts +204 -0
  578. package/packages/runtime/src/verification/verification-compiler.ts +508 -40
  579. package/packages/runtime/src/verification/verification-manifest.ts +44 -4
  580. package/packages/runtime/src/workspace/index.ts +2 -1
  581. package/packages/runtime/src/workspace/strategies/ephemeral-container.ts +44 -11
  582. package/packages/runtime/src/workspace/strategies/git-worktree.ts +104 -1
  583. package/packages/runtime/src/workspace/strategies/inplace.ts +38 -38
  584. package/packages/runtime/src/workspace/workspace-manager.ts +16 -16
  585. package/vscode-extension/LICENSE +21 -21
  586. package/vscode-extension/package.json +1 -1
  587. package/vscode-extension/src/shared/contextLoader.js +137 -137
  588. package/vscode-extension/src/shared/contractBuilder.js +159 -159
  589. package/vscode-extension/src/shared/stateReader.js +101 -101
  590. package/docs/oxe-artifact-map.html +0 -1172
@@ -1,4 +1,5 @@
1
1
  import path from 'path';
2
+ import { PROVIDER_QUOTA_RE } from '../executor/quota-patterns';
2
3
  import fs from 'fs';
3
4
  import { appendEvent } from '../events/bus';
4
5
  import type { OxeEvent } from '../events/envelope';
@@ -25,7 +26,7 @@ import { listMemos } from '../decision/decision-memo';
25
26
  import type { RollbackPlan } from '../decision/decision-memo';
26
27
  import { runCapabilityAsync } from '../plugins/capability-adapter';
27
28
  import { verifyRun } from '../verification/verification-compiler';
28
- import type { AcceptanceCheckSuite } from '../verification/verification-compiler';
29
+ import type { AcceptanceCheckSuite, CheckResult } from '../verification/verification-compiler';
29
30
 
30
31
  export interface TaskResult {
31
32
  success: boolean;
@@ -33,6 +34,13 @@ export interface TaskResult {
33
34
  evidence: string[];
34
35
  output: string;
35
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;
36
44
  }
37
45
 
38
46
  export interface TaskExecutor {
@@ -41,16 +49,134 @@ export interface TaskExecutor {
41
49
  lease: WorkspaceLease,
42
50
  runId: string,
43
51
  attemptNumber: number,
44
- options?: { previousError?: string | null }
52
+ options?: { previousError?: string | null; maxTurns?: number | null; model?: string | null }
45
53
  ): Promise<TaskResult>;
46
54
  }
47
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
+
48
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';
49
102
  maxRunDurationMs?: number; // default: 30 min
50
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;
51
160
  }
52
161
 
53
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;
54
180
  projectRoot: string;
55
181
  sessionId: string | null;
56
182
  runId: string;
@@ -61,9 +187,16 @@ export interface SchedulerContext {
61
187
  pluginRegistry?: PluginRegistry;
62
188
  auditTrail?: AuditTrail;
63
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;
64
196
  policyActor?: string;
65
197
  onEvent?: (event: OxeEvent) => void;
66
198
  options?: SchedulerOptions;
199
+ parallel?: ParallelMutatingOptions;
67
200
  }
68
201
 
69
202
  export interface RunResult {
@@ -90,6 +223,14 @@ export class Scheduler {
90
223
  this.lastProgressMs = Date.now();
91
224
  }
92
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
+
93
234
  private async executeRollback(plan: RollbackPlan, ctx: SchedulerContext): Promise<void> {
94
235
  try {
95
236
  switch (plan.strategy) {
@@ -164,19 +305,22 @@ export class Scheduler {
164
305
  const maxRunMs = ctx.options?.maxRunDurationMs ?? 30 * 60_000;
165
306
  const staleMs = ctx.options?.staleProgressMs ?? 5 * 60_000;
166
307
 
167
- for (const wave of graph.waves) {
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) {
168
314
  if (this.cancelled) break;
169
315
 
170
316
  // Global run timeout
171
317
  if (Date.now() - this.runStartMs > maxRunMs) {
172
- this.emit(ctx, { type: 'RunAborted', payload: { reason: 'global_timeout' } });
173
- return { run_id: ctx.runId, status: 'aborted', completed: [], failed: [], blocked: [], reason: 'global_timeout' };
318
+ return this.abortRun(ctx, 'global_timeout', completed, failed, blocked);
174
319
  }
175
320
 
176
321
  // Stale progress timeout (no task completed in staleMs)
177
322
  if (Date.now() - this.lastProgressMs > staleMs) {
178
- this.emit(ctx, { type: 'RunAborted', payload: { reason: 'no_progress_timeout' } });
179
- return { run_id: ctx.runId, status: 'aborted', completed: [], failed: [], blocked: [], reason: 'no_progress_timeout' };
323
+ return this.abortRun(ctx, 'no_progress_timeout', completed, failed, blocked);
180
324
  }
181
325
 
182
326
  // Respect pause: persist journal and return paused result
@@ -195,8 +339,21 @@ export class Scheduler {
195
339
  return { run_id: ctx.runId, status: 'paused', completed, failed, blocked, pending_gates: this.journal.pending_gates.slice() };
196
340
  }
197
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;
198
355
  const waveFailed = await this.runWave(
199
- wave.node_ids,
356
+ waveIds,
200
357
  graph,
201
358
  ctx,
202
359
  status,
@@ -204,6 +361,12 @@ export class Scheduler {
204
361
  failed,
205
362
  blocked
206
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
+ }
207
370
 
208
371
  // Sync journal after each wave
209
372
  this.journal.completed_work_items = completed.slice();
@@ -211,7 +374,7 @@ export class Scheduler {
211
374
  this.journal.blocked_work_items = blocked.slice();
212
375
  saveJournal(ctx.projectRoot, ctx.runId, this.journal);
213
376
 
214
- if (waveFailed) {
377
+ if (waveFailed && !deferMode) {
215
378
  // Execute rollback plan if one was created for this run
216
379
  const memos = listMemos(ctx.projectRoot, ctx.runId);
217
380
  for (const memo of memos) {
@@ -224,9 +387,10 @@ export class Scheduler {
224
387
  }
225
388
  }
226
389
 
227
- // Any remaining pending nodes become blocked
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)
228
392
  for (const [id, s] of status) {
229
- if (s === 'pending') {
393
+ if (s === 'pending' && !this.paused) {
230
394
  status.set(id, 'blocked');
231
395
  blocked.push(id);
232
396
  this.emit(ctx, {
@@ -239,6 +403,8 @@ export class Scheduler {
239
403
 
240
404
  const finalStatus: RunResult['status'] = this.cancelled
241
405
  ? 'cancelled'
406
+ : this.paused // OXB-120: paused inside the last wave (environment / quota)
407
+ ? 'paused'
242
408
  : failed.length > 0
243
409
  ? 'failed'
244
410
  : blocked.length > 0
@@ -260,7 +426,11 @@ export class Scheduler {
260
426
  },
261
427
  });
262
428
 
263
- this.journal.scheduler_state = this.cancelled ? 'cancelled' : finalStatus === 'blocked' ? 'blocked' : 'completed';
429
+ this.journal.scheduler_state = this.cancelled
430
+ ? 'cancelled'
431
+ : finalStatus === 'blocked' || finalStatus === 'failed'
432
+ ? finalStatus
433
+ : 'completed';
264
434
  this.journal.completed_work_items = completed.slice();
265
435
  this.journal.failed_work_items = failed.slice();
266
436
  this.journal.blocked_work_items = blocked.slice();
@@ -282,7 +452,9 @@ export class Scheduler {
282
452
  */
283
453
  async recover(runId: string, ctx: SchedulerContext, graph: ExecutionGraph): Promise<RunResult | null> {
284
454
  const journal = loadJournal(ctx.projectRoot, runId);
285
- if (!journal || journal.scheduler_state !== 'paused') return null;
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;
286
458
 
287
459
  // Restore state from journal
288
460
  this.cancelled = false;
@@ -352,7 +524,7 @@ export class Scheduler {
352
524
  }
353
525
 
354
526
  for (const [id, s] of status) {
355
- if (s === 'pending') {
527
+ if (s === 'pending' && !this.paused) {
356
528
  status.set(id, 'blocked');
357
529
  blocked.push(id);
358
530
  this.emit(ctx, {
@@ -386,7 +558,11 @@ export class Scheduler {
386
558
  },
387
559
  });
388
560
 
389
- this.journal.scheduler_state = this.cancelled ? 'cancelled' : finalStatus === 'blocked' ? 'blocked' : 'completed';
561
+ this.journal.scheduler_state = this.cancelled
562
+ ? 'cancelled'
563
+ : finalStatus === 'blocked' || finalStatus === 'failed'
564
+ ? finalStatus
565
+ : 'completed';
390
566
  this.journal.completed_work_items = completed.slice();
391
567
  this.journal.failed_work_items = failed.slice();
392
568
  this.journal.blocked_work_items = blocked.slice();
@@ -406,6 +582,9 @@ export class Scheduler {
406
582
  private isConcurrentSafe(nodeId: string, graph: ExecutionGraph, ctx: SchedulerContext): boolean {
407
583
  const node = graph.nodes.get(nodeId)!;
408
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;
409
588
  const primaryAction = pickPrimaryAction(node, ctx.pluginRegistry);
410
589
  if (!primaryAction) return true;
411
590
  const provider = ctx.pluginRegistry?.toolProviderFor(primaryAction.type);
@@ -421,45 +600,189 @@ export class Scheduler {
421
600
  failed: string[],
422
601
  blocked: string[]
423
602
  ): Promise<boolean> {
424
- const eligible: string[] = [];
425
- const depsNotMet: string[] = [];
426
-
427
- for (const id of nodeIds) {
428
- if (status.get(id) === 'completed') continue; // already done in recovery
429
- const node = graph.nodes.get(id)!;
430
- const depsMet = node.depends_on.every((dep) => status.get(dep) === 'completed');
431
- if (depsMet) {
432
- eligible.push(id);
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);
433
646
  } else {
434
- depsNotMet.push(id);
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
+ }
435
652
  }
436
653
  }
437
654
 
438
- for (const id of depsNotMet) {
439
- status.set(id, 'blocked');
440
- blocked.push(id);
441
- this.emit(ctx, {
442
- type: 'WorkItemBlocked',
443
- work_item_id: id,
444
- payload: { reason: 'dependency_not_met' },
445
- });
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
+ }
446
666
  }
447
667
 
448
- const readOnly = eligible.filter((id) => this.isConcurrentSafe(id, graph, ctx));
449
- const mutations = eligible.filter((id) => !readOnly.includes(id));
668
+ return failed.length > 0;
669
+ }
450
670
 
451
- if (readOnly.length > 0) {
452
- await Promise.all(
453
- readOnly.map((id) => this.runNode(id, graph, ctx, status, completed, failed, blocked))
454
- );
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
+ }
455
735
  }
736
+ if (running.size) await Promise.all([...running.values()].map((r) => r.done));
737
+ }
456
738
 
457
- for (const id of mutations) {
458
- if (this.cancelled) break;
459
- await this.runNode(id, graph, ctx, status, completed, failed, blocked);
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));
460
785
  }
461
-
462
- return failed.length > 0;
463
786
  }
464
787
 
465
788
  private async runNode(
@@ -469,9 +792,11 @@ export class Scheduler {
469
792
  status: Map<string, NodeStatus>,
470
793
  completed: string[],
471
794
  failed: string[],
472
- blocked: string[]
795
+ blocked: string[],
796
+ mode: { parallel?: boolean } = {}
473
797
  ): Promise<void> {
474
798
  const node = graph.nodes.get(nodeId)!;
799
+ const parallelNode = Boolean(mode.parallel && ctx.parallel);
475
800
  status.set(nodeId, 'running');
476
801
  this.emit(ctx, {
477
802
  type: 'WorkItemReady',
@@ -480,23 +805,67 @@ export class Scheduler {
480
805
  });
481
806
 
482
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;
483
810
  let lastResult: TaskResult | null = null;
484
811
  let lastError: string | null = null;
485
- const maxAttempts = node.policy.max_retries + 1;
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
+ }
486
829
  const quotaBlocked = this.consumeQuotaForNode(ctx, node);
487
830
  if (quotaBlocked) {
488
831
  this.blockNode(nodeId, ctx, status, blocked, 'quota_exceeded', quotaBlocked);
489
832
  return;
490
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;
491
856
 
492
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;
493
861
  const attemptId = `${nodeId}-a${attempt}`;
862
+ const attemptModel = ctx.modelFor ? ctx.modelFor(nodeId, attempt, attempt > 1 ? (lastResult?.failure_class ?? null) : null) : null;
494
863
 
495
864
  this.emit(ctx, {
496
865
  type: 'AttemptStarted',
497
866
  work_item_id: nodeId,
498
867
  attempt_id: attemptId,
499
- payload: { attempt_number: attempt },
868
+ payload: { attempt_number: attempt, ...(attemptModel ? { model: attemptModel.model, tier: attemptModel.tier, escalated: Boolean(attemptModel.escalated) } : {}) },
500
869
  });
501
870
 
502
871
  try {
@@ -526,19 +895,38 @@ export class Scheduler {
526
895
  });
527
896
  }
528
897
 
529
- if (policyDecision?.gate_required || node.policy.requires_human_approval) {
898
+ if ((policyDecision?.gate_required || node.policy.requires_human_approval) && !this.hasApprovedGate(node, ctx)) {
530
899
  const gateId = await this.requestGateForNode(node, ctx, policyDecision);
531
900
  this.blockNode(nodeId, ctx, status, blocked, 'pending_gate', gateId);
532
901
  return;
533
902
  }
534
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
+
535
920
  const wsReq: WorkspaceRequest = {
536
921
  work_item_id: nodeId,
537
922
  attempt_number: attempt,
538
923
  strategy: node.workspace_strategy,
539
924
  mutation_scope: node.mutation_scope,
540
925
  };
541
- const workspaceManager = ctx.pluginRegistry?.workspaceProviderFor(node.workspace_strategy) ?? ctx.workspaceManager;
926
+ const workspaceManager = parallelNode
927
+ ? ctx.parallel!.manager
928
+ : ctx.pluginRegistry?.workspaceProviderFor(node.workspace_strategy) ?? ctx.workspaceManager;
929
+ leaseManager = workspaceManager;
542
930
  lease = await workspaceManager.allocate(wsReq);
543
931
  this.emit(ctx, {
544
932
  type: 'WorkspaceAllocated',
@@ -547,23 +935,153 @@ export class Scheduler {
547
935
  payload: { workspace_id: lease.workspace_id, strategy: lease.strategy },
548
936
  });
549
937
 
550
- lastResult = await this.executeNode(node, lease, ctx, attempt, attemptId, { previousError: lastError });
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
+ });
551
943
 
552
- if (lastResult.success) {
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) {
553
957
  const verifyResult = await this.verifyNode(node, lease, ctx, attemptId, attempt);
554
958
  if (verifyResult && verifyResult.status === 'failed') {
959
+ // Informed retry: the next attempt sees the command, the reason and the output — not just "failed".
555
960
  lastResult = {
556
961
  success: false,
557
- failure_class: 'verify',
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',
558
964
  evidence: lastResult.evidence,
559
- output: `Verification failed: ${(verifyResult.gaps || []).join('; ') || 'checks did not pass'}`,
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 } : {}),
560
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 };
561
1075
  } else {
562
1076
  this.emit(ctx, {
563
1077
  type: 'WorkItemCompleted',
564
1078
  work_item_id: nodeId,
565
1079
  attempt_id: attemptId,
566
- payload: { attempt_number: attempt, evidence: lastResult.evidence },
1080
+ payload: {
1081
+ attempt_number: attempt,
1082
+ evidence: lastResult.evidence,
1083
+ ...(turnLimitWithWork ? { completed_by: 'verify_after_turn_limit' } : {}),
1084
+ },
567
1085
  });
568
1086
  status.set(nodeId, 'completed');
569
1087
  completed.push(nodeId);
@@ -574,9 +1092,109 @@ export class Scheduler {
574
1092
 
575
1093
  lastError = lastResult.output || (lastResult.failure_class ?? 'unknown error');
576
1094
 
577
- if (lastResult.failure_class === 'policy') break;
578
-
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
+ }
579
1195
  if (attempt < maxAttempts) {
1196
+ // a pause: no retry quota spent, no RetryScheduled banner (R34)
1197
+ if (holdForPause(attempt + 1)) return;
580
1198
  const retryBlocked = this.consumeRetryQuota(ctx);
581
1199
  if (retryBlocked) {
582
1200
  this.blockNode(nodeId, ctx, status, blocked, 'quota_exceeded', retryBlocked);
@@ -591,7 +1209,7 @@ export class Scheduler {
591
1209
  this.emit(ctx, {
592
1210
  type: 'RetryScheduled',
593
1211
  work_item_id: nodeId,
594
- payload: { next_attempt: attempt + 1, reason: lastResult.failure_class, backoff_ms: backoffMs },
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 } : {}) },
595
1213
  });
596
1214
  }
597
1215
  } catch (err: unknown) {
@@ -616,15 +1234,16 @@ export class Scheduler {
616
1234
  this.emit(ctx, {
617
1235
  type: 'RetryScheduled',
618
1236
  work_item_id: nodeId,
619
- payload: { next_attempt: attempt + 1, reason: 'env', backoff_ms: backoffMs },
1237
+ payload: { next_attempt: attempt + 1, reason: 'env', backoff_ms: backoffMs, output_tail: tailLines(lastResult.output || '', 60) },
620
1238
  });
621
1239
  }
622
1240
  } finally {
623
1241
  if (lease) {
624
- await ctx.workspaceManager.dispose(lease.workspace_id).catch((e: unknown) =>
1242
+ await (leaseManager ?? ctx.workspaceManager).dispose(lease.workspace_id).catch((e: unknown) =>
625
1243
  this.emit(ctx!, { type: 'WorkspaceDisposeFailed', payload: { workspace_id: lease?.workspace_id, error: String(e) } })
626
1244
  );
627
1245
  lease = null;
1246
+ leaseManager = null;
628
1247
  }
629
1248
  }
630
1249
  }
@@ -632,12 +1251,48 @@ export class Scheduler {
632
1251
  this.emit(ctx, {
633
1252
  type: 'WorkItemBlocked',
634
1253
  work_item_id: nodeId,
635
- payload: { failure_class: lastResult?.failure_class ?? 'env', max_attempts: maxAttempts },
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 } : {}) },
636
1255
  });
637
1256
  status.set(nodeId, 'failed');
638
1257
  failed.push(nodeId);
639
1258
  }
640
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
+
641
1296
  pause(): void {
642
1297
  this.paused = true;
643
1298
  if (this.journal && this.ctx) {
@@ -679,7 +1334,7 @@ export class Scheduler {
679
1334
  ctx: SchedulerContext,
680
1335
  attempt: number,
681
1336
  attemptId: string,
682
- options: { previousError?: string | null } = {},
1337
+ options: { previousError?: string | null; maxTurns?: number | null; model?: string | null } = {},
683
1338
  ): Promise<TaskResult> {
684
1339
  const primaryAction = pickPrimaryAction(node, ctx.pluginRegistry);
685
1340
  const provider = primaryAction ? ctx.pluginRegistry?.toolProviderFor(primaryAction.type) : null;
@@ -758,54 +1413,145 @@ export class Scheduler {
758
1413
  ctx: SchedulerContext,
759
1414
  attemptId: string,
760
1415
  attempt: number,
761
- ): Promise<{ status: string; gaps?: string[] } | null> {
1416
+ ): Promise<VerifyNodeResult | null> {
762
1417
  if (!node.verify?.command) return null;
763
1418
  this.emit(ctx, {
764
1419
  type: 'VerificationStarted',
765
1420
  work_item_id: node.id,
766
1421
  payload: { command: node.verify.command, attempt_number: attempt },
767
1422
  });
768
- const suite: AcceptanceCheckSuite = {
769
- checks: [{
770
- id: `inline-${node.id}`,
771
- type: 'custom',
772
- command: node.verify.command,
773
- evidence_type_expected: 'stdout',
774
- acceptance_ref: null,
775
- description: `Verify ${node.id}`,
776
- }],
777
- compiled_at: new Date().toISOString(),
778
- spec_hash: '',
779
- plan_hash: '',
780
- };
781
- let result: { status: string; gaps?: string[] };
782
- try {
783
- result = await verifyRun({
784
- suite,
785
- cwd: lease.root_path,
786
- timeoutMs: (ctx.options as Record<string, unknown>)?.verifyTimeoutMs as number ?? 60_000,
787
- runId: ctx.runId,
788
- workItemId: node.id,
789
- attemptNumber: attempt,
790
- projectRoot: ctx.projectRoot,
791
- pluginRegistry: ctx.pluginRegistry,
792
- });
793
- } catch (err) {
794
- this.emit(ctx, {
795
- type: 'VerificationCompleted',
796
- work_item_id: node.id,
797
- attempt_id: attemptId,
798
- payload: { status: 'error', error: String(err) },
799
- });
800
- return null;
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;
801
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
+ }));
802
1537
  this.emit(ctx, {
803
1538
  type: 'VerificationCompleted',
804
1539
  work_item_id: node.id,
805
1540
  attempt_id: attemptId,
806
- payload: { status: result.status },
1541
+ payload: {
1542
+ status,
1543
+ ...(failedSegment ? { failed_segment: failedSegment } : {}),
1544
+ ...(failedSegments.length > 1 ? { failed_segments: failedSegments } : {}),
1545
+ },
807
1546
  });
808
- return result;
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
+ };
809
1555
  }
810
1556
 
811
1557
  private evaluatePolicyForNode(node: GraphNode, ctx: SchedulerContext): PersistedPolicyDecision | null {
@@ -837,6 +1583,14 @@ export class Scheduler {
837
1583
  return persisted;
838
1584
  }
839
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
+
840
1594
  private async requestGateForNode(
841
1595
  node: GraphNode,
842
1596
  ctx: SchedulerContext,
@@ -854,8 +1608,8 @@ export class Scheduler {
854
1608
  action: primaryAction?.type ?? 'custom',
855
1609
  description: `Gate required before executing ${node.id}`,
856
1610
  evidence_refs: [],
857
- risks: [decision?.reason ?? 'human approval required'],
858
- rationale: decision?.reason ?? 'node policy requires approval',
1611
+ risks: [decision?.reason ?? node.policy.gate_reason ?? 'human approval required'],
1612
+ rationale: decision?.reason ?? node.policy.gate_reason ?? 'node policy requires approval',
859
1613
  policy_decision_id: decision?.decision_id ?? null,
860
1614
  });
861
1615
  if (this.journal && !this.journal.pending_gates.includes(gate.gate_id)) {
@@ -869,6 +1623,46 @@ export class Scheduler {
869
1623
  return gate.gate_id;
870
1624
  }
871
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
+
872
1666
  private blockNode(
873
1667
  nodeId: string,
874
1668
  ctx: SchedulerContext,
@@ -916,6 +1710,13 @@ export class Scheduler {
916
1710
  }
917
1711
  }
918
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
+
919
1720
  function inferSideEffectClass(node: GraphNode): PolicyContext['side_effect_class'] {
920
1721
  if (node.mutation_scope.length > 0) return 'write_fs';
921
1722
  if (node.actions.some((action) => action.type === 'run_tests' || action.type === 'run_lint')) return 'spawn_process';
@@ -936,3 +1737,345 @@ function inferGateScope(node: GraphNode): 'critical_mutation' | 'security' | 'pl
936
1737
  if (node.actions.some((action) => action.type === 'collect_evidence')) return 'security';
937
1738
  return 'plan_approval';
938
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
+ }