oxe-cc 1.21.1 → 1.22.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (514) hide show
  1. package/.cursor/commands/oxe-alm.md +47 -0
  2. package/.cursor/commands/oxe-ask.md +1 -1
  3. package/.cursor/commands/oxe-capabilities.md +1 -1
  4. package/.cursor/commands/oxe-checkpoint.md +1 -1
  5. package/.cursor/commands/oxe-compact.md +1 -1
  6. package/.cursor/commands/oxe-dashboard.md +1 -1
  7. package/.cursor/commands/oxe-debug.md +1 -1
  8. package/.cursor/commands/oxe-discuss.md +1 -1
  9. package/.cursor/commands/oxe-execute.md +3 -1
  10. package/.cursor/commands/oxe-forensics.md +1 -1
  11. package/.cursor/commands/oxe-help.md +1 -1
  12. package/.cursor/commands/oxe-loop.md +1 -1
  13. package/.cursor/commands/oxe-milestone.md +1 -1
  14. package/.cursor/commands/oxe-next.md +1 -1
  15. package/.cursor/commands/oxe-obs.md +1 -1
  16. package/.cursor/commands/oxe-plan-agent.md +1 -1
  17. package/.cursor/commands/oxe-plan.md +3 -1
  18. package/.cursor/commands/oxe-project.md +1 -1
  19. package/.cursor/commands/oxe-quick.md +6 -4
  20. package/.cursor/commands/oxe-research.md +1 -1
  21. package/.cursor/commands/oxe-retro.md +1 -1
  22. package/.cursor/commands/oxe-review-pr.md +1 -1
  23. package/.cursor/commands/oxe-route.md +1 -1
  24. package/.cursor/commands/oxe-scan.md +1 -1
  25. package/.cursor/commands/oxe-security.md +1 -1
  26. package/.cursor/commands/oxe-session.md +1 -1
  27. package/.cursor/commands/oxe-ship.md +8 -8
  28. package/.cursor/commands/oxe-skill.md +1 -1
  29. package/.cursor/commands/oxe-spec.md +5 -3
  30. package/.cursor/commands/oxe-ui-review.md +1 -1
  31. package/.cursor/commands/oxe-ui-spec.md +1 -1
  32. package/.cursor/commands/oxe-update.md +1 -1
  33. package/.cursor/commands/oxe-validate-gaps.md +1 -1
  34. package/.cursor/commands/oxe-verify-audit.md +1 -1
  35. package/.cursor/commands/oxe-verify.md +1 -1
  36. package/.cursor/commands/oxe-workflow-authoring.md +1 -1
  37. package/.cursor/commands/oxe-workstream.md +1 -1
  38. package/.cursor/commands/oxe.md +4 -2
  39. package/.github/copilot-instructions.md +177 -177
  40. package/.github/dependabot.yml +31 -31
  41. package/.github/prompts/oxe-alm.prompt.md +47 -0
  42. package/.github/prompts/oxe-ask.prompt.md +1 -1
  43. package/.github/prompts/oxe-capabilities.prompt.md +1 -1
  44. package/.github/prompts/oxe-checkpoint.prompt.md +1 -1
  45. package/.github/prompts/oxe-compact.prompt.md +1 -1
  46. package/.github/prompts/oxe-dashboard.prompt.md +1 -1
  47. package/.github/prompts/oxe-debug.prompt.md +1 -1
  48. package/.github/prompts/oxe-discuss.prompt.md +1 -1
  49. package/.github/prompts/oxe-execute.prompt.md +3 -1
  50. package/.github/prompts/oxe-forensics.prompt.md +1 -1
  51. package/.github/prompts/oxe-help.prompt.md +1 -1
  52. package/.github/prompts/oxe-loop.prompt.md +1 -1
  53. package/.github/prompts/oxe-milestone.prompt.md +1 -1
  54. package/.github/prompts/oxe-next.prompt.md +1 -1
  55. package/.github/prompts/oxe-obs.prompt.md +1 -1
  56. package/.github/prompts/oxe-plan-agent.prompt.md +1 -1
  57. package/.github/prompts/oxe-plan.prompt.md +3 -1
  58. package/.github/prompts/oxe-project.prompt.md +1 -1
  59. package/.github/prompts/oxe-quick.prompt.md +6 -4
  60. package/.github/prompts/oxe-research.prompt.md +1 -1
  61. package/.github/prompts/oxe-retro.prompt.md +1 -1
  62. package/.github/prompts/oxe-review-pr.prompt.md +1 -1
  63. package/.github/prompts/oxe-route.prompt.md +1 -1
  64. package/.github/prompts/oxe-scan.prompt.md +1 -1
  65. package/.github/prompts/oxe-security.prompt.md +1 -1
  66. package/.github/prompts/oxe-session.prompt.md +1 -1
  67. package/.github/prompts/oxe-ship.prompt.md +7 -7
  68. package/.github/prompts/oxe-skill.prompt.md +1 -1
  69. package/.github/prompts/oxe-spec.prompt.md +4 -2
  70. package/.github/prompts/oxe-ui-review.prompt.md +1 -1
  71. package/.github/prompts/oxe-ui-spec.prompt.md +1 -1
  72. package/.github/prompts/oxe-update.prompt.md +1 -1
  73. package/.github/prompts/oxe-validate-gaps.prompt.md +1 -1
  74. package/.github/prompts/oxe-verify-audit.prompt.md +1 -1
  75. package/.github/prompts/oxe-verify.prompt.md +1 -1
  76. package/.github/prompts/oxe-workflow-authoring.prompt.md +1 -1
  77. package/.github/prompts/oxe-workstream.prompt.md +1 -1
  78. package/.github/prompts/oxe.prompt.md +4 -2
  79. package/.github/workflows/ci.yml +163 -163
  80. package/.github/workflows/release.yml +151 -120
  81. package/AGENTS.md +108 -102
  82. package/CHANGELOG.md +1971 -1042
  83. package/LICENSE +21 -21
  84. package/QUICKSTART.md +99 -99
  85. package/README.md +703 -673
  86. package/bin/banner.txt +18 -18
  87. package/bin/lib/commands/ops-commands.cjs +751 -0
  88. package/bin/lib/commands/spec-program-commands.cjs +337 -0
  89. package/bin/lib/operational/alm-refine-runtime.cjs +791 -0
  90. package/bin/lib/operational/child-env.cjs +52 -0
  91. package/bin/lib/operational/promote-runtime.cjs +1187 -0
  92. package/bin/lib/oxe-acceptance-audit.cjs +195 -0
  93. package/bin/lib/oxe-adr.cjs +145 -0
  94. package/bin/lib/oxe-agent-coord.cjs +246 -0
  95. package/bin/lib/oxe-agent-install.cjs +679 -677
  96. package/bin/lib/oxe-alm-admin.cjs +215 -0
  97. package/bin/lib/oxe-alm-metrics.cjs +143 -0
  98. package/bin/lib/oxe-alm-prs.cjs +274 -0
  99. package/bin/lib/oxe-alm-refine.cjs +1099 -0
  100. package/bin/lib/oxe-alm.cjs +1289 -0
  101. package/bin/lib/oxe-anchor-copy.cjs +218 -0
  102. package/bin/lib/oxe-api-surface.cjs +96 -0
  103. package/bin/lib/oxe-artifact-catalog.cjs +376 -376
  104. package/bin/lib/oxe-artifact-refs.cjs +72 -0
  105. package/bin/lib/oxe-attention.cjs +97 -0
  106. package/bin/lib/oxe-autoresume.cjs +448 -0
  107. package/bin/lib/oxe-budget.cjs +154 -117
  108. package/bin/lib/oxe-change-folder.cjs +130 -0
  109. package/bin/lib/oxe-change.cjs +389 -230
  110. package/bin/lib/oxe-channels.cjs +82 -0
  111. package/bin/lib/oxe-ci-adapter.cjs +304 -0
  112. package/bin/lib/oxe-cited-paths.cjs +180 -0
  113. package/bin/lib/oxe-cli-errors.cjs +76 -0
  114. package/bin/lib/oxe-cli-output.cjs +111 -0
  115. package/bin/lib/oxe-command-registry.cjs +31 -31
  116. package/bin/lib/oxe-commit-convention.cjs +104 -85
  117. package/bin/lib/oxe-complexity.cjs +106 -0
  118. package/bin/lib/oxe-console-decode.cjs +23 -0
  119. package/bin/lib/oxe-context-engine.cjs +874 -874
  120. package/bin/lib/oxe-coordinator-queue.cjs +67 -0
  121. package/bin/lib/oxe-core-command-handlers.cjs +84 -82
  122. package/bin/lib/oxe-criteria-ids.cjs +87 -0
  123. package/bin/lib/oxe-criterion-coverage.cjs +93 -58
  124. package/bin/lib/oxe-cross-card-conflicts.cjs +639 -0
  125. package/bin/lib/oxe-customize.cjs +146 -0
  126. package/bin/lib/oxe-dashboard.cjs +737 -737
  127. package/bin/lib/oxe-decisions.cjs +217 -0
  128. package/bin/lib/oxe-deferred.cjs +80 -0
  129. package/bin/lib/oxe-deps-audit.cjs +136 -0
  130. package/bin/lib/oxe-diff-reviewer.cjs +105 -0
  131. package/bin/lib/oxe-dir-info.cjs +157 -0
  132. package/bin/lib/oxe-docs-check.cjs +124 -0
  133. package/bin/lib/oxe-docs-publish.cjs +81 -0
  134. package/bin/lib/oxe-dom-hooks.cjs +902 -0
  135. package/bin/lib/oxe-dossier.cjs +355 -281
  136. package/bin/lib/oxe-e2e-ready.cjs +360 -0
  137. package/bin/lib/oxe-env-sanitize.cjs +160 -0
  138. package/bin/lib/oxe-event-bus.cjs +118 -118
  139. package/bin/lib/oxe-failure-cost.cjs +144 -0
  140. package/bin/lib/oxe-file-size-guard.cjs +849 -0
  141. package/bin/lib/oxe-findings.cjs +86 -0
  142. package/bin/lib/oxe-git-root.cjs +97 -0
  143. package/bin/lib/oxe-grill-cases.cjs +148 -0
  144. package/bin/lib/oxe-grill.cjs +533 -0
  145. package/bin/lib/oxe-grooming.cjs +115 -0
  146. package/bin/lib/oxe-guard.cjs +180 -0
  147. package/bin/lib/oxe-handoff.cjs +97 -0
  148. package/bin/lib/oxe-install-resolve.cjs +134 -134
  149. package/bin/lib/oxe-integration-checks.cjs +285 -0
  150. package/bin/lib/oxe-intent-context.cjs +101 -0
  151. package/bin/lib/oxe-journey.cjs +403 -0
  152. package/bin/lib/oxe-known-failures.cjs +138 -0
  153. package/bin/lib/oxe-local-config.cjs +77 -0
  154. package/bin/lib/oxe-manifest.cjs +124 -124
  155. package/bin/lib/oxe-memory-kernel.cjs +190 -188
  156. package/bin/lib/oxe-merge-train.cjs +277 -0
  157. package/bin/lib/oxe-model-resolve.cjs +74 -0
  158. package/bin/lib/oxe-model-tiers.cjs +65 -0
  159. package/bin/lib/oxe-nfr.cjs +125 -0
  160. package/bin/lib/oxe-npm-version.cjs +66 -66
  161. package/bin/lib/oxe-onboard.cjs +640 -0
  162. package/bin/lib/oxe-open-defects.cjs +121 -0
  163. package/bin/lib/oxe-operational.cjs +12112 -2115
  164. package/bin/lib/oxe-origin-guard.cjs +102 -0
  165. package/bin/lib/oxe-origin.cjs +380 -0
  166. package/bin/lib/oxe-pack-removed.cjs +208 -0
  167. package/bin/lib/oxe-parallel-run.cjs +81 -0
  168. package/bin/lib/oxe-parallel.cjs +234 -0
  169. package/bin/lib/oxe-phase-extras.cjs +185 -0
  170. package/bin/lib/oxe-phase-gates.cjs +688 -280
  171. package/bin/lib/oxe-plan-build.cjs +1580 -0
  172. package/bin/lib/oxe-plan-json.cjs +1107 -433
  173. package/bin/lib/oxe-plan-merge.cjs +253 -0
  174. package/bin/lib/oxe-plan-mutate.cjs +320 -0
  175. package/bin/lib/oxe-plan-repair.cjs +479 -0
  176. package/bin/lib/oxe-plan-review.cjs +256 -0
  177. package/bin/lib/oxe-plan-skeleton.cjs +494 -0
  178. package/bin/lib/oxe-plan-staleness.cjs +125 -0
  179. package/bin/lib/oxe-plugin-cli.cjs +97 -95
  180. package/bin/lib/oxe-plugins.cjs +432 -432
  181. package/bin/lib/oxe-policy-rules.cjs +144 -0
  182. package/bin/lib/oxe-prd.cjs +129 -0
  183. package/bin/lib/oxe-preflight.cjs +384 -0
  184. package/bin/lib/oxe-presets.cjs +216 -0
  185. package/bin/lib/oxe-process.cjs +67 -67
  186. package/bin/lib/oxe-program-members.cjs +97 -0
  187. package/bin/lib/oxe-program.cjs +245 -205
  188. package/bin/lib/oxe-progress-run.cjs +80 -0
  189. package/bin/lib/oxe-project-env.cjs +352 -178
  190. package/bin/lib/oxe-project-health.cjs +3426 -2962
  191. package/bin/lib/oxe-promote-helpers.cjs +1561 -0
  192. package/bin/lib/oxe-provider-antigravity.cjs +114 -0
  193. package/bin/lib/oxe-provider-grok.cjs +48 -0
  194. package/bin/lib/oxe-questions.cjs +115 -0
  195. package/bin/lib/oxe-quick.cjs +537 -0
  196. package/bin/lib/oxe-ratchets.cjs +132 -0
  197. package/bin/lib/oxe-rationality.cjs +587 -556
  198. package/bin/lib/oxe-real-regression.cjs +97 -0
  199. package/bin/lib/oxe-recovery.cjs +160 -0
  200. package/bin/lib/oxe-reevaluate.cjs +198 -0
  201. package/bin/lib/oxe-release-ops.cjs +361 -0
  202. package/bin/lib/oxe-release.cjs +622 -593
  203. package/bin/lib/oxe-repair.cjs +153 -0
  204. package/bin/lib/oxe-repo-map.cjs +136 -0
  205. package/bin/lib/oxe-repo-rules.cjs +121 -108
  206. package/bin/lib/oxe-research-provenance.cjs +96 -0
  207. package/bin/lib/oxe-resume.cjs +406 -0
  208. package/bin/lib/oxe-review.cjs +403 -0
  209. package/bin/lib/oxe-rfc.cjs +192 -0
  210. package/bin/lib/oxe-risk-decision.cjs +141 -0
  211. package/bin/lib/oxe-runtime-semantics.cjs +521 -514
  212. package/bin/lib/oxe-scorecard.cjs +627 -164
  213. package/bin/lib/oxe-scratch.cjs +81 -0
  214. package/bin/lib/oxe-seams.cjs +159 -0
  215. package/bin/lib/oxe-semver.cjs +83 -0
  216. package/bin/lib/oxe-ship-pr.cjs +272 -0
  217. package/bin/lib/oxe-signal.cjs +173 -0
  218. package/bin/lib/oxe-skill-loader.cjs +131 -131
  219. package/bin/lib/oxe-spec-check.cjs +249 -0
  220. package/bin/lib/oxe-spec-ears.cjs +98 -0
  221. package/bin/lib/oxe-spec-edit.cjs +411 -0
  222. package/bin/lib/oxe-spec-freeze.cjs +378 -0
  223. package/bin/lib/oxe-spec-probe.cjs +146 -0
  224. package/bin/lib/oxe-spec-stress.cjs +146 -0
  225. package/bin/lib/oxe-spike.cjs +98 -98
  226. package/bin/lib/oxe-state.cjs +87 -0
  227. package/bin/lib/oxe-stub-check.cjs +355 -0
  228. package/bin/lib/oxe-suite-impact.cjs +1160 -0
  229. package/bin/lib/oxe-sync.cjs +347 -0
  230. package/bin/lib/oxe-system-design.cjs +138 -0
  231. package/bin/lib/oxe-task-gates.cjs +139 -0
  232. package/bin/lib/oxe-telemetry.cjs +201 -0
  233. package/bin/lib/oxe-test-precheck.cjs +508 -0
  234. package/bin/lib/oxe-test-rigor.cjs +663 -0
  235. package/bin/lib/oxe-test-scope.cjs +883 -0
  236. package/bin/lib/oxe-trace.cjs +168 -0
  237. package/bin/lib/oxe-turns.cjs +64 -0
  238. package/bin/lib/oxe-ui-evidence.cjs +187 -0
  239. package/bin/lib/oxe-ui-verify.cjs +55 -0
  240. package/bin/lib/oxe-unsafe-commands.cjs +94 -0
  241. package/bin/lib/oxe-verdicts.cjs +131 -0
  242. package/bin/lib/oxe-verify-cache.cjs +132 -0
  243. package/bin/lib/oxe-verify-dryrun.cjs +541 -152
  244. package/bin/lib/oxe-verify-remote.cjs +208 -0
  245. package/bin/lib/oxe-vitest-batch.cjs +149 -0
  246. package/bin/lib/oxe-workflow-budget.cjs +99 -0
  247. package/bin/lib/oxe-workflow-eval.cjs +118 -0
  248. package/bin/lib/oxe-workflows.cjs +147 -145
  249. package/bin/lib/oxe-worktree-deps.cjs +241 -0
  250. package/bin/lib/oxe-worktree-gc.cjs +655 -0
  251. package/bin/oxe-cc.js +3861 -100
  252. package/commands/oxe/alm.md +54 -0
  253. package/commands/oxe/ask.md +1 -1
  254. package/commands/oxe/capabilities.md +1 -1
  255. package/commands/oxe/checkpoint.md +1 -1
  256. package/commands/oxe/compact.md +1 -1
  257. package/commands/oxe/dashboard.md +1 -1
  258. package/commands/oxe/debug.md +1 -1
  259. package/commands/oxe/discuss.md +1 -1
  260. package/commands/oxe/execute.md +3 -1
  261. package/commands/oxe/forensics.md +1 -1
  262. package/commands/oxe/help.md +1 -1
  263. package/commands/oxe/loop.md +1 -1
  264. package/commands/oxe/milestone.md +1 -1
  265. package/commands/oxe/next.md +1 -1
  266. package/commands/oxe/obs.md +1 -1
  267. package/commands/oxe/oxe.md +3 -1
  268. package/commands/oxe/plan-agent.md +1 -1
  269. package/commands/oxe/plan.md +3 -1
  270. package/commands/oxe/project.md +1 -1
  271. package/commands/oxe/quick.md +4 -4
  272. package/commands/oxe/research.md +1 -1
  273. package/commands/oxe/retro.md +1 -1
  274. package/commands/oxe/review-pr.md +1 -1
  275. package/commands/oxe/route.md +1 -1
  276. package/commands/oxe/scan.md +1 -1
  277. package/commands/oxe/security.md +1 -1
  278. package/commands/oxe/session.md +1 -1
  279. package/commands/oxe/ship.md +6 -6
  280. package/commands/oxe/skill.md +1 -1
  281. package/commands/oxe/spec.md +6 -3
  282. package/commands/oxe/ui-review.md +1 -1
  283. package/commands/oxe/ui-spec.md +1 -1
  284. package/commands/oxe/update.md +1 -1
  285. package/commands/oxe/validate-gaps.md +1 -1
  286. package/commands/oxe/verify-audit.md +1 -1
  287. package/commands/oxe/verify.md +1 -1
  288. package/commands/oxe/workflow-authoring.md +1 -1
  289. package/commands/oxe/workstream.md +1 -1
  290. package/docs/ADLC-COVERAGE.md +55 -0
  291. package/docs/CONTENT-MIGRATION-AUDIT.md +49 -49
  292. package/docs/HAPPY-PATH.md +106 -0
  293. package/docs/INCIDENT-PLAYBOOK.md +181 -181
  294. package/docs/INTEGRATION.md +182 -182
  295. package/docs/QUALITY-GATES.md +46 -46
  296. package/docs/RELEASE-READINESS.md +93 -87
  297. package/docs/ROLES.md +129 -129
  298. package/docs/RUNTIME-SMOKE-MATRIX.md +137 -137
  299. package/docs/TEAM-ADOPTION.md +153 -153
  300. package/docs/WALKTHROUGH.md +241 -241
  301. package/docs/adr/D-1-isolamento-read-only-e-sanitizacao-centralizada-de-env-vars.md +29 -0
  302. package/docs/adr/D-2-junction-segura-de-node-modules-condicionada-a-sha-256-de-pa.md +29 -0
  303. package/docs/adr/D-3-preflight-local-5s-impacto-estatico-e2e-e-leitura-explicita.md +29 -0
  304. package/docs/adr/D-4-governanca-de-release-unificada-retomada-idempotente-pos-rei.md +29 -0
  305. package/docs/adr/D-5-core-agnostico-vs-presets-declarativos-de-dominio.md +29 -0
  306. package/docs/adr/D-6-decomposicao-strangler-fig-de-oxe-cc-e-oxe-operational.md +29 -0
  307. package/docs/adr/D-7-paridade-pre-push-com-phase-gates-path-aware-json-compacto-e.md +28 -0
  308. package/docs/adr/D-F1F4-1-paridade-pre-push-compactacao-json-sync-version-pins-e-quali.md +44 -0
  309. package/docs/adr/README.md +19 -0
  310. package/docs/cli-errors.md +20 -0
  311. package/docs/oxespace-1.5/BACKLOG.md +2056 -273
  312. package/docs/oxespace-1.5/HANDOFF-1.21.2.md +140 -0
  313. package/docs/oxevoice/BACKLOG.md +244 -244
  314. package/lib/runtime/compiler/graph-compiler.d.ts +2 -0
  315. package/lib/runtime/compiler/graph-compiler.js +11 -2
  316. package/lib/runtime/delivery/promotion-pipeline.d.ts +1 -0
  317. package/lib/runtime/delivery/promotion-pipeline.js +53 -0
  318. package/lib/runtime/events/catalog.d.ts +1 -1
  319. package/lib/runtime/events/catalog.js +18 -0
  320. package/lib/runtime/executor/action-tool-map.d.ts +3 -1
  321. package/lib/runtime/executor/action-tool-map.js +4 -1
  322. package/lib/runtime/executor/adapters/antigravity-cli.d.ts +103 -0
  323. package/lib/runtime/executor/adapters/antigravity-cli.js +530 -0
  324. package/lib/runtime/executor/adapters/claude-cli.d.ts +29 -0
  325. package/lib/runtime/executor/adapters/claude-cli.js +92 -14
  326. package/lib/runtime/executor/adapters/grok-cli.d.ts +89 -0
  327. package/lib/runtime/executor/adapters/grok-cli.js +351 -0
  328. package/lib/runtime/executor/adapters/registry.d.ts +6 -1
  329. package/lib/runtime/executor/adapters/registry.js +22 -2
  330. package/lib/runtime/executor/adapters/types.d.ts +1 -1
  331. package/lib/runtime/executor/built-in-tools.d.ts +56 -0
  332. package/lib/runtime/executor/built-in-tools.js +219 -17
  333. package/lib/runtime/executor/index.d.ts +9 -2
  334. package/lib/runtime/executor/index.js +23 -1
  335. package/lib/runtime/executor/llm-task-executor.d.ts +76 -3
  336. package/lib/runtime/executor/llm-task-executor.js +514 -31
  337. package/lib/runtime/executor/node-context.d.ts +11 -0
  338. package/lib/runtime/executor/node-context.js +10 -0
  339. package/lib/runtime/executor/node-prompt-builder.js +2 -0
  340. package/lib/runtime/executor/quota-patterns.d.ts +7 -0
  341. package/lib/runtime/executor/quota-patterns.js +39 -0
  342. package/lib/runtime/executor/shell-argv.d.ts +11 -0
  343. package/lib/runtime/executor/shell-argv.js +89 -2
  344. package/lib/runtime/executor/stream-completion.d.ts +16 -0
  345. package/lib/runtime/executor/stream-completion.js +72 -4
  346. package/lib/runtime/index.d.ts +1 -1
  347. package/lib/runtime/index.js +3 -1
  348. package/lib/runtime/models/failure.d.ts +1 -1
  349. package/lib/runtime/models/run.d.ts +1 -1
  350. package/lib/runtime/program/program-model.d.ts +20 -2
  351. package/lib/runtime/program/program-model.js +73 -6
  352. package/lib/runtime/projection/projection-engine.d.ts +6 -0
  353. package/lib/runtime/projection/projection-engine.js +30 -2
  354. package/lib/runtime/reducers/run-state-reducer.js +43 -5
  355. package/lib/runtime/scheduler/run-journal.d.ts +8 -0
  356. package/lib/runtime/scheduler/scheduler.d.ts +211 -2
  357. package/lib/runtime/scheduler/scheduler.js +982 -98
  358. package/lib/runtime/verification/runner-timeout.d.ts +7 -0
  359. package/lib/runtime/verification/runner-timeout.js +17 -0
  360. package/lib/runtime/verification/test-report-parsers.d.ts +2 -1
  361. package/lib/runtime/verification/test-report-parsers.js +9 -1
  362. package/lib/runtime/verification/verification-compiler.d.ts +46 -2
  363. package/lib/runtime/verification/verification-compiler.js +335 -33
  364. package/lib/runtime/verification/verification-manifest.d.ts +2 -0
  365. package/lib/runtime/verification/verification-manifest.js +15 -1
  366. package/lib/runtime/workspace/index.d.ts +2 -1
  367. package/lib/runtime/workspace/index.js +3 -1
  368. package/lib/runtime/workspace/strategies/ephemeral-container.d.ts +9 -0
  369. package/lib/runtime/workspace/strategies/ephemeral-container.js +37 -10
  370. package/lib/runtime/workspace/strategies/git-worktree.d.ts +15 -1
  371. package/lib/runtime/workspace/strategies/git-worktree.js +53 -1
  372. package/lib/sdk/README.md +82 -82
  373. package/lib/sdk/index.cjs +828 -815
  374. package/lib/sdk/index.d.ts +982 -982
  375. package/lib/sdk/index.types.ts +933 -933
  376. package/oxe/agents/oxe-assumptions-analyzer.md +136 -136
  377. package/oxe/agents/oxe-codebase-mapper.md +142 -142
  378. package/oxe/agents/oxe-debugger.md +145 -145
  379. package/oxe/agents/oxe-executor.md +139 -139
  380. package/oxe/agents/oxe-integration-checker.md +142 -142
  381. package/oxe/agents/oxe-plan-checker.md +143 -143
  382. package/oxe/agents/oxe-planner.md +151 -151
  383. package/oxe/agents/oxe-research-synthesizer.md +146 -146
  384. package/oxe/agents/oxe-researcher.md +163 -163
  385. package/oxe/agents/oxe-ui-auditor.md +151 -151
  386. package/oxe/agents/oxe-ui-checker.md +157 -157
  387. package/oxe/agents/oxe-ui-researcher.md +179 -179
  388. package/oxe/agents/oxe-validation-auditor.md +154 -154
  389. package/oxe/agents/oxe-verifier.md +132 -132
  390. package/oxe/migrations/config-migrations.json +15 -0
  391. package/oxe/personas/README.md +91 -91
  392. package/oxe/personas/architect.md +149 -149
  393. package/oxe/personas/db-specialist.md +149 -149
  394. package/oxe/personas/debugger.md +155 -155
  395. package/oxe/personas/executor.md +164 -164
  396. package/oxe/personas/planner.md +165 -165
  397. package/oxe/personas/researcher.md +148 -148
  398. package/oxe/personas/ui-specialist.md +164 -164
  399. package/oxe/personas/verifier.md +174 -174
  400. package/oxe/schemas/plan.schema.json +101 -85
  401. package/oxe/schemas/role-plan.schema.json +50 -0
  402. package/oxe/schemas/swarm-run.schema.json +130 -130
  403. package/oxe/templates/CONFIG.md +290 -105
  404. package/oxe/templates/DISCUSS.template.md +45 -44
  405. package/oxe/templates/EXECUTION-RUNTIME.template.md +68 -68
  406. package/oxe/templates/FIXTURE-PACK.template.json +41 -41
  407. package/oxe/templates/FIXTURE-PACK.template.md +30 -30
  408. package/oxe/templates/GLOSSARY.template.md +9 -0
  409. package/oxe/templates/IMPLEMENTATION-PACK.template.json +68 -68
  410. package/oxe/templates/IMPLEMENTATION-PACK.template.md +48 -48
  411. package/oxe/templates/PLAN.template.md +151 -151
  412. package/oxe/templates/PLUGINS.md +108 -108
  413. package/oxe/templates/PRD.template.md +53 -0
  414. package/oxe/templates/REFERENCE-ANCHORS.template.md +39 -35
  415. package/oxe/templates/RESEARCH.template.md +65 -57
  416. package/oxe/templates/RFC.template.md +43 -0
  417. package/oxe/templates/SPEC.template.md +119 -119
  418. package/oxe/templates/STATE-REFERENCE.md +125 -125
  419. package/oxe/templates/STATE.md +30 -30
  420. package/oxe/templates/SUMMARY.template.md +50 -50
  421. package/oxe/templates/VISUAL-INPUTS.template.json +27 -27
  422. package/oxe/templates/VISUAL-INPUTS.template.md +36 -36
  423. package/oxe/templates/config.template.json +38 -38
  424. package/oxe/templates/finding-rules.json +22 -0
  425. package/oxe/templates/stress-methods.md +33 -0
  426. package/oxe/workflows/agent-mode.md +150 -150
  427. package/oxe/workflows/alm.md +50 -0
  428. package/oxe/workflows/compact/plan.md +149 -0
  429. package/oxe/workflows/compact/spec.md +114 -0
  430. package/oxe/workflows/compact.md +45 -44
  431. package/oxe/workflows/conduct.md +149 -149
  432. package/oxe/workflows/debug.md +43 -43
  433. package/oxe/workflows/discuss.md +98 -86
  434. package/oxe/workflows/distill.md +164 -164
  435. package/oxe/workflows/execute.md +273 -269
  436. package/oxe/workflows/forensics.md +53 -53
  437. package/oxe/workflows/help.md +364 -355
  438. package/oxe/workflows/lean/execute.md +43 -0
  439. package/oxe/workflows/lean/plan.md +60 -0
  440. package/oxe/workflows/lean/spec.md +61 -0
  441. package/oxe/workflows/memory.md +163 -163
  442. package/oxe/workflows/next.md +47 -45
  443. package/oxe/workflows/oxe.md +168 -150
  444. package/oxe/workflows/plan.md +563 -556
  445. package/oxe/workflows/quick.md +199 -185
  446. package/oxe/workflows/references/alm-refine.md +55 -0
  447. package/oxe/workflows/references/azure-in-plan.md +5 -0
  448. package/oxe/workflows/references/change-management.md +48 -0
  449. package/oxe/workflows/references/flow-robustness-contract.md +80 -80
  450. package/oxe/workflows/references/grill.md +74 -0
  451. package/oxe/workflows/references/next-step-footer.md +33 -0
  452. package/oxe/workflows/references/plan-json-acceptance-program.md +174 -143
  453. package/oxe/workflows/references/product-docs-alm.md +51 -0
  454. package/oxe/workflows/references/workflow-runtime-contracts.json +1167 -1151
  455. package/oxe/workflows/research.md +67 -66
  456. package/oxe/workflows/route.md +32 -32
  457. package/oxe/workflows/scan.md +356 -355
  458. package/oxe/workflows/ship.md +93 -142
  459. package/oxe/workflows/size-budget.json +62 -0
  460. package/oxe/workflows/spec.md +615 -619
  461. package/oxe/workflows/swarm/board.md +119 -119
  462. package/oxe/workflows/swarm/scout.md +170 -170
  463. package/oxe/workflows/swarm-mode.md +280 -280
  464. package/oxe/workflows/ui-review.md +37 -37
  465. package/oxe/workflows/ui-spec.md +32 -32
  466. package/oxe/workflows/verify.md +273 -255
  467. package/package.json +134 -132
  468. package/packages/runtime/package.json +18 -18
  469. package/packages/runtime/src/compiler/graph-compiler.ts +349 -336
  470. package/packages/runtime/src/context/context-pack-builder.ts +339 -339
  471. package/packages/runtime/src/delivery/promotion-pipeline.ts +397 -342
  472. package/packages/runtime/src/events/catalog.ts +63 -45
  473. package/packages/runtime/src/executor/action-tool-map.ts +52 -50
  474. package/packages/runtime/src/executor/adapters/antigravity-cli.ts +619 -0
  475. package/packages/runtime/src/executor/adapters/claude-cli.ts +367 -285
  476. package/packages/runtime/src/executor/adapters/grok-cli.ts +392 -0
  477. package/packages/runtime/src/executor/adapters/http-openai.ts +16 -16
  478. package/packages/runtime/src/executor/adapters/registry.ts +53 -33
  479. package/packages/runtime/src/executor/adapters/types.ts +24 -24
  480. package/packages/runtime/src/executor/built-in-tools.ts +525 -333
  481. package/packages/runtime/src/executor/index.ts +23 -16
  482. package/packages/runtime/src/executor/llm-task-executor.ts +854 -336
  483. package/packages/runtime/src/executor/node-context.ts +226 -210
  484. package/packages/runtime/src/executor/node-prompt-builder.ts +69 -67
  485. package/packages/runtime/src/executor/quota-patterns.ts +41 -0
  486. package/packages/runtime/src/executor/shell-argv.ts +144 -66
  487. package/packages/runtime/src/executor/stream-completion.ts +230 -160
  488. package/packages/runtime/src/index.ts +56 -54
  489. package/packages/runtime/src/models/failure.ts +22 -13
  490. package/packages/runtime/src/models/run.ts +25 -24
  491. package/packages/runtime/src/plugins/capability-adapter.ts +313 -313
  492. package/packages/runtime/src/plugins/plugin-abi.ts +106 -106
  493. package/packages/runtime/src/plugins/plugin-registry.ts +241 -241
  494. package/packages/runtime/src/program/index.ts +1 -1
  495. package/packages/runtime/src/program/program-model.ts +293 -233
  496. package/packages/runtime/src/projection/projection-engine.ts +386 -361
  497. package/packages/runtime/src/reducers/run-state-reducer.ts +365 -329
  498. package/packages/runtime/src/scheduler/multi-agent-coordinator.ts +1017 -1017
  499. package/packages/runtime/src/scheduler/run-journal.ts +107 -105
  500. package/packages/runtime/src/scheduler/scheduler.ts +2081 -1144
  501. package/packages/runtime/src/verification/contract-exports.ts +203 -203
  502. package/packages/runtime/src/verification/index.ts +3 -3
  503. package/packages/runtime/src/verification/runner-timeout.ts +17 -0
  504. package/packages/runtime/src/verification/test-report-parsers.ts +204 -198
  505. package/packages/runtime/src/verification/verification-compiler.ts +1074 -766
  506. package/packages/runtime/src/verification/verification-manifest.ts +296 -281
  507. package/packages/runtime/src/workspace/index.ts +6 -5
  508. package/packages/runtime/src/workspace/strategies/ephemeral-container.ts +159 -126
  509. package/packages/runtime/src/workspace/strategies/git-worktree.ts +190 -150
  510. package/packages/runtime/tsconfig.json +24 -23
  511. package/vscode-extension/.vscodeignore +9 -9
  512. package/vscode-extension/LICENSE +21 -21
  513. package/vscode-extension/package.json +193 -193
  514. package/vscode-extension/src/extension.js +320 -320
@@ -4,10 +4,21 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.Scheduler = void 0;
7
+ exports.scopesOverlap = scopesOverlap;
8
+ exports.classifyFailureOutput = classifyFailureOutput;
9
+ exports.quotaResumeAt = quotaResumeAt;
10
+ exports.parseRateLimitResetMs = parseRateLimitResetMs;
7
11
  exports.tailLines = tailLines;
12
+ exports.segmentTestFiles = segmentTestFiles;
13
+ exports.groupRemoteSegments = groupRemoteSegments;
14
+ exports.remoteFailedMember = remoteFailedMember;
15
+ exports.splitVerifySegments = splitVerifySegments;
16
+ exports.withAttemptChanges = withAttemptChanges;
17
+ exports.buildVerifyLog = buildVerifyLog;
8
18
  exports.describeVerifyFailure = describeVerifyFailure;
9
19
  exports.verifyFailureSignature = verifyFailureSignature;
10
20
  const path_1 = __importDefault(require("path"));
21
+ const quota_patterns_1 = require("../executor/quota-patterns");
11
22
  const fs_1 = __importDefault(require("fs"));
12
23
  const bus_1 = require("../events/bus");
13
24
  const policy_engine_1 = require("../policy/policy-engine");
@@ -16,6 +27,30 @@ const run_journal_1 = require("./run-journal");
16
27
  const decision_memo_1 = require("../decision/decision-memo");
17
28
  const capability_adapter_1 = require("../plugins/capability-adapter");
18
29
  const verification_compiler_1 = require("../verification/verification-compiler");
30
+ /** Two scopes may touch the same file: equal paths, one a directory prefix of the other, or a glob in either. */
31
+ function scopesOverlap(a, b) {
32
+ if (!a.length || !b.length)
33
+ return true;
34
+ const norm = (p) => String(p).replace(/\\/g, '/').replace(/\/+$/, '');
35
+ const base = (p) => norm(p).split(/[*?[{]/)[0].replace(/\/[^/]*$/, (m) => (/[*?[{]/.test(norm(p)) ? '' : m));
36
+ for (const x of a) {
37
+ for (const y of b) {
38
+ const nx = norm(x);
39
+ const ny = norm(y);
40
+ if (nx === ny)
41
+ return true;
42
+ const gx = /[*?[{]/.test(nx);
43
+ const gy = /[*?[{]/.test(ny);
44
+ const px = gx ? base(nx) : nx;
45
+ const py = gy ? base(ny) : ny;
46
+ if (!px || !py)
47
+ return true;
48
+ if (px === py || px.startsWith(`${py}/`) || py.startsWith(`${px}/`))
49
+ return true;
50
+ }
51
+ }
52
+ return false;
53
+ }
19
54
  class Scheduler {
20
55
  constructor() {
21
56
  this.cancelled = false;
@@ -24,10 +59,17 @@ class Scheduler {
24
59
  this.ctx = null;
25
60
  this.runStartMs = 0;
26
61
  this.lastProgressMs = 0;
62
+ /** OXB-050: integrations into the program checkout happen one at a time (copy, verify, checkpoint). */
63
+ this.integrationChain = Promise.resolve();
27
64
  }
28
65
  recordProgress() {
29
66
  this.lastProgressMs = Date.now();
30
67
  }
68
+ withIntegrationLock(fn) {
69
+ const run = this.integrationChain.then(fn, fn);
70
+ this.integrationChain = run.catch(() => undefined);
71
+ return run;
72
+ }
31
73
  async executeRollback(plan, ctx) {
32
74
  try {
33
75
  switch (plan.strategy) {
@@ -97,7 +139,11 @@ class Scheduler {
97
139
  });
98
140
  const maxRunMs = ctx.options?.maxRunDurationMs ?? 30 * 60000;
99
141
  const staleMs = ctx.options?.staleProgressMs ?? 5 * 60000;
100
- for (const wave of graph.waves) {
142
+ // OXB-129: stream dispatch — no wave barrier.
143
+ if (ctx.options?.dispatch === 'stream') {
144
+ await this.runStream(graph, ctx, status, completed, failed, blocked, maxRunMs);
145
+ }
146
+ for (const wave of ctx.options?.dispatch === 'stream' ? [] : graph.waves) {
101
147
  if (this.cancelled)
102
148
  break;
103
149
  // Global run timeout
@@ -123,13 +169,36 @@ class Scheduler {
123
169
  });
124
170
  return { run_id: ctx.runId, status: 'paused', completed, failed, blocked, pending_gates: this.journal.pending_gates.slice() };
125
171
  }
126
- const waveFailed = await this.runWave(wave.node_ids, graph, ctx, status, completed, failed, blocked);
172
+ // OXB-138: a task depending (transitively) on a failed/deferred or blocked one does not run.
173
+ const deferMode = ctx.options?.deferFailed === true;
174
+ let waveIds = wave.node_ids;
175
+ if (deferMode) {
176
+ waveIds = [];
177
+ for (const id of wave.node_ids) {
178
+ const n = graph.nodes.get(id);
179
+ const bad = (n?.depends_on ?? []).find((d) => status.get(d) === 'failed' || status.get(d) === 'blocked');
180
+ if (bad && status.get(id) === 'pending')
181
+ this.blockNode(id, ctx, status, blocked, 'blocked_by_deferred', bad);
182
+ else
183
+ waveIds.push(id);
184
+ }
185
+ }
186
+ const failedBefore = failed.length;
187
+ const waveFailed = await this.runWave(waveIds, graph, ctx, status, completed, failed, blocked);
188
+ if (deferMode) {
189
+ for (const id of failed.slice(failedBefore))
190
+ this.emit(ctx, { type: 'WorkItemDeferred', work_item_id: id, payload: { task: id } });
191
+ // OXB-C28-1: a deferred task is a decision of the run, not a stall — without this a wave whose only task was
192
+ // deferred after > staleProgressMs aborted the run (no_progress_timeout) and took the independent tasks along
193
+ if (failed.length > failedBefore || waveIds.some((id) => status.get(id) === 'blocked'))
194
+ this.recordProgress();
195
+ }
127
196
  // Sync journal after each wave
128
197
  this.journal.completed_work_items = completed.slice();
129
198
  this.journal.failed_work_items = failed.slice();
130
199
  this.journal.blocked_work_items = blocked.slice();
131
200
  (0, run_journal_1.saveJournal)(ctx.projectRoot, ctx.runId, this.journal);
132
- if (waveFailed) {
201
+ if (waveFailed && !deferMode) {
133
202
  // Execute rollback plan if one was created for this run
134
203
  const memos = (0, decision_memo_1.listMemos)(ctx.projectRoot, ctx.runId);
135
204
  for (const memo of memos) {
@@ -141,9 +210,10 @@ class Scheduler {
141
210
  break;
142
211
  }
143
212
  }
144
- // Any remaining pending nodes become blocked
213
+ // Any remaining pending nodes become blocked — not on a pause: they are the work the resume picks up (OxeSpace
214
+ // 15/11, OxeCode F4: a requested pause after T17 marked T18 "upstream_wave_failed" and printed FAIL)
145
215
  for (const [id, s] of status) {
146
- if (s === 'pending') {
216
+ if (s === 'pending' && !this.paused) {
147
217
  status.set(id, 'blocked');
148
218
  blocked.push(id);
149
219
  this.emit(ctx, {
@@ -155,11 +225,13 @@ class Scheduler {
155
225
  }
156
226
  const finalStatus = this.cancelled
157
227
  ? 'cancelled'
158
- : failed.length > 0
159
- ? 'failed'
160
- : blocked.length > 0
161
- ? 'blocked'
162
- : 'completed';
228
+ : this.paused // OXB-120: paused inside the last wave (environment / quota)
229
+ ? 'paused'
230
+ : failed.length > 0
231
+ ? 'failed'
232
+ : blocked.length > 0
233
+ ? 'blocked'
234
+ : 'completed';
163
235
  this.emit(ctx, {
164
236
  type: 'RunCompleted',
165
237
  payload: { run_id: ctx.runId, status: finalStatus },
@@ -256,7 +328,7 @@ class Scheduler {
256
328
  break;
257
329
  }
258
330
  for (const [id, s] of status) {
259
- if (s === 'pending') {
331
+ if (s === 'pending' && !this.paused) {
260
332
  status.set(id, 'blocked');
261
333
  blocked.push(id);
262
334
  this.emit(ctx, {
@@ -321,56 +393,199 @@ class Scheduler {
321
393
  return provider?.idempotent ?? true;
322
394
  }
323
395
  async runWave(nodeIds, graph, ctx, status, completed, failed, blocked) {
324
- const eligible = [];
325
- const depsNotMet = [];
326
- for (const id of nodeIds) {
327
- if (status.get(id) === 'completed')
328
- continue; // already done in recovery
329
- const node = graph.nodes.get(id);
330
- const depsMet = node.depends_on.every((dep) => status.get(dep) === 'completed');
331
- if (depsMet) {
332
- eligible.push(id);
396
+ // OXB-C19 (#2): re-evaluate intra-wave dependencies as nodes complete so a resumed/checkpointed task
397
+ // unblocks subsequent eligible tasks in the same wave instead of marking them blocked up-front.
398
+ const warnedEmptyScope = new Set();
399
+ while (!this.cancelled && !this.paused) {
400
+ const eligible = [];
401
+ for (const id of nodeIds) {
402
+ if (status.get(id) !== 'pending')
403
+ continue;
404
+ const node = graph.nodes.get(id);
405
+ const depsMet = node.depends_on.every((dep) => status.get(dep) === 'completed');
406
+ if (depsMet)
407
+ eligible.push(id);
408
+ }
409
+ if (eligible.length === 0)
410
+ break;
411
+ for (const id of eligible) {
412
+ if (warnedEmptyScope.has(id))
413
+ continue;
414
+ const node = graph.nodes.get(id);
415
+ // OXB-068: a verify_only / external-dependency node has an enforced empty scope (checked by the caller), not a
416
+ // "may write files" warning.
417
+ const externalNode = Boolean(node.policy.verify_only) || (node.policy.external_dependency?.length ?? 0) > 0;
418
+ if (node.mutation_scope.length === 0 && nodeMayMutate(node) && !externalNode) {
419
+ warnedEmptyScope.add(id);
420
+ this.emit(ctx, {
421
+ type: 'PolicyWarning',
422
+ work_item_id: id,
423
+ payload: {
424
+ reason: 'empty_mutation_scope',
425
+ detail: 'node may write files but declares no mutation_scope; running serially and without scope checks',
426
+ },
427
+ });
428
+ }
429
+ }
430
+ const readOnly = eligible.filter((id) => this.isConcurrentSafe(id, graph, ctx));
431
+ const mutations = eligible.filter((id) => !readOnly.includes(id));
432
+ if (readOnly.length > 0) {
433
+ await Promise.all(readOnly.map((id) => this.runNode(id, graph, ctx, status, completed, failed, blocked)));
434
+ }
435
+ if (ctx.parallel && mutations.length > 1) {
436
+ await this.runMutationsInParallel(mutations, graph, ctx, status, completed, failed, blocked);
333
437
  }
334
438
  else {
335
- depsNotMet.push(id);
439
+ for (const id of mutations) {
440
+ this.checkRequestedPause(ctx);
441
+ if (this.cancelled || this.paused)
442
+ break;
443
+ await this.runNode(id, graph, ctx, status, completed, failed, blocked);
444
+ }
336
445
  }
337
446
  }
338
- for (const id of depsNotMet) {
339
- status.set(id, 'blocked');
340
- blocked.push(id);
341
- this.emit(ctx, {
342
- type: 'WorkItemBlocked',
343
- work_item_id: id,
344
- payload: { reason: 'dependency_not_met' },
345
- });
346
- }
347
- for (const id of eligible) {
348
- const node = graph.nodes.get(id);
349
- if (node.mutation_scope.length === 0 && nodeMayMutate(node)) {
447
+ if (!this.cancelled && !this.paused) {
448
+ for (const id of nodeIds) {
449
+ if (status.get(id) !== 'pending')
450
+ continue;
451
+ status.set(id, 'blocked');
452
+ blocked.push(id);
350
453
  this.emit(ctx, {
351
- type: 'PolicyWarning',
454
+ type: 'WorkItemBlocked',
352
455
  work_item_id: id,
353
- payload: {
354
- reason: 'empty_mutation_scope',
355
- detail: 'node may write files but declares no mutation_scope; running serially and without scope checks',
356
- },
456
+ payload: { reason: 'dependency_not_met' },
357
457
  });
358
458
  }
359
459
  }
360
- const readOnly = eligible.filter((id) => this.isConcurrentSafe(id, graph, ctx));
361
- const mutations = eligible.filter((id) => !readOnly.includes(id));
362
- if (readOnly.length > 0) {
363
- await Promise.all(readOnly.map((id) => this.runNode(id, graph, ctx, status, completed, failed, blocked)));
460
+ return failed.length > 0;
461
+ }
462
+ /**
463
+ * OXB-129: dispatch by dependency, not by wave. A node is ready when every dependency is completed; one with a failed
464
+ * or blocked dependency is blocked (only its dependents — the rest goes on). Ready nodes start in plan order, up to
465
+ * `parallel.maxParallel` (1 without --parallel-mutating), never two with overlapping scopes (a hot file serializes),
466
+ * and never past the free-memory floor. Every decision is a `DispatchState` event (ready / waiting with the reason).
467
+ */
468
+ async runStream(graph, ctx, status, completed, failed, blocked, maxRunMs) {
469
+ const order = graph.waves.flatMap((w) => w.node_ids);
470
+ const parallel = ctx.parallel;
471
+ const max = parallel ? Math.max(1, Math.floor(parallel.maxParallel || 1)) : 1;
472
+ const running = new Map();
473
+ let lastSignature = '';
474
+ while (!this.cancelled && !this.paused) {
475
+ if (Date.now() - this.runStartMs > maxRunMs)
476
+ break;
477
+ // a requested pause stops new starts; the nodes already running finish (awaited below)
478
+ this.checkRequestedPause(ctx);
479
+ if (this.paused)
480
+ break;
481
+ const waiting = [];
482
+ const ready = [];
483
+ for (const id of order) {
484
+ if (status.get(id) !== 'pending' || running.has(id))
485
+ continue;
486
+ const node = graph.nodes.get(id);
487
+ const bad = node.depends_on.find((d) => status.get(d) === 'failed' || status.get(d) === 'blocked');
488
+ if (bad) {
489
+ this.blockNode(id, ctx, status, blocked, 'dependency_not_met', bad);
490
+ continue;
491
+ }
492
+ const open = node.depends_on.filter((d) => status.get(d) !== 'completed');
493
+ if (open.length) {
494
+ waiting.push({ id, reason: `depende de ${open.join(', ')}` });
495
+ continue;
496
+ }
497
+ ready.push(id);
498
+ }
499
+ const started = [];
500
+ for (const id of ready) {
501
+ if (running.size >= max) {
502
+ waiting.push({ id, reason: `limite de paralelismo (${max})` });
503
+ continue;
504
+ }
505
+ const node = graph.nodes.get(id);
506
+ const hot = [...running.entries()].find(([, r]) => scopesOverlap(r.scope, node.mutation_scope) || (node.mutation_scope.length === 0 && nodeMayMutate(node)));
507
+ if (hot) {
508
+ waiting.push({ id, reason: `arquivo quente: escopo em comum com ${hot[0]}` });
509
+ continue;
510
+ }
511
+ if (running.size > 0 && parallel?.minFreeMb && parallel.freeMb && parallel.freeMb() < parallel.minFreeMb) {
512
+ waiting.push({ id, reason: `memória livre abaixo de ${parallel.minFreeMb} MB` });
513
+ continue;
514
+ }
515
+ const useParallel = Boolean(parallel) && max > 1;
516
+ const done = this.runNode(id, graph, ctx, status, completed, failed, blocked, useParallel ? { parallel: true } : {})
517
+ .catch(() => undefined)
518
+ .finally(() => { running.delete(id); });
519
+ running.set(id, { scope: node.mutation_scope, done });
520
+ started.push(id);
521
+ }
522
+ const signature = JSON.stringify([started, waiting]);
523
+ if (signature !== lastSignature && (started.length || waiting.length)) {
524
+ lastSignature = signature;
525
+ this.emit(ctx, { type: 'DispatchState', payload: { mode: 'stream', started, running: [...running.keys()], waiting } });
526
+ if (this.journal)
527
+ this.journal.dispatch = { running: [...running.keys()], waiting };
528
+ }
529
+ if (running.size === 0)
530
+ break;
531
+ await Promise.race([...running.values()].map((r) => r.done));
532
+ if (this.journal) {
533
+ this.journal.completed_work_items = completed.slice();
534
+ this.journal.failed_work_items = failed.slice();
535
+ this.journal.blocked_work_items = blocked.slice();
536
+ (0, run_journal_1.saveJournal)(ctx.projectRoot, ctx.runId, this.journal);
537
+ }
364
538
  }
365
- for (const id of mutations) {
366
- if (this.cancelled)
539
+ if (running.size)
540
+ await Promise.all([...running.values()].map((r) => r.done));
541
+ }
542
+ /** OXB-050: a pool over the wave's mutating nodes — disjoint scopes only, `maxParallel`, memory per agent. */
543
+ async runMutationsInParallel(mutations, graph, ctx, status, completed, failed, blocked) {
544
+ const parallel = ctx.parallel;
545
+ const max = Math.max(1, Math.floor(parallel.maxParallel || 1));
546
+ const pending = [...mutations];
547
+ const running = new Map();
548
+ let memoryWarned = false;
549
+ while ((pending.length > 0 || running.size > 0) && !this.cancelled) {
550
+ // a requested pause: nothing new starts; what is running finishes
551
+ this.checkRequestedPause(ctx);
552
+ if (this.paused) {
553
+ if (running.size)
554
+ await Promise.all([...running.values()].map((r) => r.done));
367
555
  break;
368
- await this.runNode(id, graph, ctx, status, completed, failed, blocked);
556
+ }
557
+ for (const id of [...pending]) {
558
+ if (running.size >= max)
559
+ break;
560
+ const scope = graph.nodes.get(id).mutation_scope;
561
+ if ([...running.values()].some((r) => scopesOverlap(r.scope, scope)))
562
+ continue;
563
+ if (running.size > 0 && parallel.minFreeMb && parallel.freeMb && parallel.freeMb() < parallel.minFreeMb) {
564
+ if (!memoryWarned) {
565
+ memoryWarned = true;
566
+ 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` } });
567
+ }
568
+ break;
569
+ }
570
+ pending.splice(pending.indexOf(id), 1);
571
+ const done = this.runNode(id, graph, ctx, status, completed, failed, blocked, { parallel: true })
572
+ .catch(() => undefined)
573
+ .finally(() => { running.delete(id); });
574
+ running.set(id, { scope, done });
575
+ }
576
+ if (running.size === 0) {
577
+ // Nothing could start (should not happen: one always runs) — fall back to the next one, alone.
578
+ const id = pending.shift();
579
+ if (id)
580
+ await this.runNode(id, graph, ctx, status, completed, failed, blocked);
581
+ continue;
582
+ }
583
+ await Promise.race([...running.values()].map((r) => r.done));
369
584
  }
370
- return failed.length > 0;
371
585
  }
372
- async runNode(nodeId, graph, ctx, status, completed, failed, blocked) {
586
+ async runNode(nodeId, graph, ctx, status, completed, failed, blocked, mode = {}) {
373
587
  const node = graph.nodes.get(nodeId);
588
+ const parallelNode = Boolean(mode.parallel && ctx.parallel);
374
589
  status.set(nodeId, 'running');
375
590
  this.emit(ctx, {
376
591
  type: 'WorkItemReady',
@@ -385,10 +600,16 @@ class Scheduler {
385
600
  // 1.20c: the same verify failure twice (normalized output) = suspect ruler or stuck executor: stop paying retries.
386
601
  let lastVerifySignature = null;
387
602
  let verifySuspect = false;
388
- const maxAttempts = node.policy.max_retries + 1;
603
+ let maxAttempts = node.policy.max_retries + 1;
604
+ let policyRetried = Boolean(ctx.options?.policyRefusedBefore?.includes(nodeId));
389
605
  // 1.21.1 (OXB-047): work that arrives by another path never pays an agent and never becomes a human gate.
390
606
  // An explicit human gate (PLAN.json `gate`) still comes first: the attempt loop requests it as before.
391
607
  const humanGatePending = node.policy.requires_human_approval && !this.hasApprovedGate(node, ctx);
608
+ if (!humanGatePending && (node.policy.runtime_wait?.length ?? 0) > 0) {
609
+ const waits = node.policy.runtime_wait ?? [];
610
+ this.blockNode(nodeId, ctx, status, blocked, 'waiting_runtime_precondition', waits.join(', '));
611
+ return;
612
+ }
392
613
  if (!humanGatePending && (node.policy.verify_only || (node.policy.external_dependency?.length ?? 0) > 0)) {
393
614
  await this.runExternalNode(node, ctx, status, completed, failed, blocked);
394
615
  return;
@@ -398,13 +619,40 @@ class Scheduler {
398
619
  this.blockNode(nodeId, ctx, status, blocked, 'quota_exceeded', quotaBlocked);
399
620
  return;
400
621
  }
622
+ // cross-review 15/11: --retry-policy-once in a 3rd execute of the same run would pay attempt 1 again for a task
623
+ // whose one extra policy attempt was already spent — blocked before any model call
624
+ if (ctx.options?.retryPolicyOnce && ctx.options?.policyRetryExhausted?.includes(nodeId)) {
625
+ 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');
626
+ return;
627
+ }
628
+ const maxQuotaWaitMs = ctx.options?.maxQuotaWaitMs ?? 5 * 60000;
629
+ const maxQuotaWaits = ctx.options?.maxQuotaWaits ?? 3;
630
+ const sleepFn = ctx.options?.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
631
+ let quotaWaits = 0;
632
+ // OxeSpace 15/11 (OxeChat F4 T9): a pause requested during an attempt holds the next one — the attempt boundary is a
633
+ // boundary too, not only the next node. The task stays PENDING (never blocked) for the execute after resume. Checked
634
+ // before the retry quota / RetryScheduled and after a rate-limit wait (cross-review R34).
635
+ const holdForPause = (next) => {
636
+ this.checkRequestedPause(ctx);
637
+ if (!this.paused)
638
+ return false;
639
+ 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` } });
640
+ status.set(nodeId, 'pending');
641
+ return true;
642
+ };
643
+ let iteration = 0;
401
644
  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
645
+ iteration += 1;
646
+ // a real iteration count: a rate-limit wait re-enters with the same attempt number (R34)
647
+ if (iteration > 1 && holdForPause(attempt))
648
+ return;
402
649
  const attemptId = `${nodeId}-a${attempt}`;
650
+ const attemptModel = ctx.modelFor ? ctx.modelFor(nodeId, attempt, attempt > 1 ? (lastResult?.failure_class ?? null) : null) : null;
403
651
  this.emit(ctx, {
404
652
  type: 'AttemptStarted',
405
653
  work_item_id: nodeId,
406
654
  attempt_id: attemptId,
407
- payload: { attempt_number: attempt },
655
+ payload: { attempt_number: attempt, ...(attemptModel ? { model: attemptModel.model, tier: attemptModel.tier, escalated: Boolean(attemptModel.escalated) } : {}) },
408
656
  });
409
657
  try {
410
658
  const policyDecision = this.evaluatePolicyForNode(node, ctx);
@@ -448,14 +696,18 @@ class Scheduler {
448
696
  this.blockNode(nodeId, ctx, status, blocked, 'budget_exhausted', budgetReason);
449
697
  return;
450
698
  }
451
- const turnsLeft = ctx.budget?.remainingTurns() ?? null;
699
+ const budgetTurns = ctx.budget?.remainingTurns() ?? null;
700
+ const sizedTurns = ctx.turnsFor ? ctx.turnsFor(nodeId, attempt, attempt > 1 ? (lastResult?.failure_class ?? null) : null) : null;
701
+ const turnsLeft = budgetTurns != null && sizedTurns != null ? Math.min(budgetTurns, sizedTurns) : (budgetTurns ?? sizedTurns);
452
702
  const wsReq = {
453
703
  work_item_id: nodeId,
454
704
  attempt_number: attempt,
455
705
  strategy: node.workspace_strategy,
456
706
  mutation_scope: node.mutation_scope,
457
707
  };
458
- const workspaceManager = ctx.pluginRegistry?.workspaceProviderFor(node.workspace_strategy) ?? ctx.workspaceManager;
708
+ const workspaceManager = parallelNode
709
+ ? ctx.parallel.manager
710
+ : ctx.pluginRegistry?.workspaceProviderFor(node.workspace_strategy) ?? ctx.workspaceManager;
459
711
  leaseManager = workspaceManager;
460
712
  lease = await workspaceManager.allocate(wsReq);
461
713
  this.emit(ctx, {
@@ -465,27 +717,66 @@ class Scheduler {
465
717
  payload: { workspace_id: lease.workspace_id, strategy: lease.strategy },
466
718
  });
467
719
  lastResult = await this.executeNode(node, lease, ctx, attempt, attemptId, {
468
- previousError: lastError,
720
+ previousError: withAttemptChanges(lastError, attempt > 1 && ctx.attemptChanges ? ctx.attemptChanges(nodeId) : null),
721
+ ...(attemptModel && attemptModel.model ? { model: attemptModel.model } : {}),
469
722
  ...(turnsLeft != null ? { maxTurns: turnsLeft } : {}),
470
723
  });
471
724
  // OXB-026: the verify judges the work, not the end of the LLM conversation. An attempt that ran out of turns
472
725
  // after writing in its scope is verified before it is classified: green completes the task, red goes to the
473
726
  // informed retry. Discarding it unverified paid a whole second attempt for finished work.
727
+ // a context-cap close (R44) is the same: work written, the verify decides before another paid attempt
728
+ const contextCap = lastResult.completed_by === 'context_cap';
474
729
  const turnLimitWithWork = !lastResult.success
475
- && lastResult.completed_by === 'turn_limit_exhausted'
730
+ && (lastResult.completed_by === 'turn_limit_exhausted' || contextCap)
476
731
  && Boolean(node.verify?.command)
477
732
  && (lastResult.evidence?.length ?? 0) > 0;
733
+ // OXB-171: what the agent itself said (before a verify failure replaces the output).
734
+ const agentOutput = String(lastResult.output || '');
478
735
  if (lastResult.success || turnLimitWithWork) {
479
736
  const verifyResult = await this.verifyNode(node, lease, ctx, attemptId, attempt);
480
737
  if (verifyResult && verifyResult.status === 'failed') {
481
738
  // Informed retry: the next attempt sees the command, the reason and the output — not just "failed".
482
739
  lastResult = {
483
740
  success: false,
484
- failure_class: 'verify',
741
+ // OXB-185: out of turns, the red verify is a consequence — the class stays turns_exhausted.
742
+ failure_class: turnLimitWithWork ? (contextCap ? lastResult.failure_class : 'turns_exhausted') : 'verify',
485
743
  evidence: lastResult.evidence,
486
- output: describeVerifyFailure(node.verify.command, verifyResult.check, verifyResult.gaps),
744
+ 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)}`,
745
+ verify_log: buildVerifyLog(verifyResult.segments),
746
+ ...(turnLimitWithWork ? { turns_used: lastResult.turns_used, turns_cap: lastResult.turns_cap } : {}),
487
747
  };
488
- const signature = verifyFailureSignature(verifyResult.check);
748
+ // OXB-120: a verify that failed for the environment (not the code) pauses the run — no attempt is spent.
749
+ const envClass = classifyFailureOutput(`${verifyResult.check?.error ?? ''}\n${verifyResult.check?.stderr ?? ''}\n${verifyResult.check?.stdout ?? ''}`, verifyResult.check?.exit_code ?? null, ctx.options?.failureClasses, { builtinQuota: false });
750
+ if (envClass && envClass.kind === 'environment') {
751
+ this.pauseForFailure(ctx, nodeId, 'environment', envClass.diagnosis, null);
752
+ this.blockNode(nodeId, ctx, status, blocked, 'paused_environment', envClass.diagnosis);
753
+ return;
754
+ }
755
+ if (envClass && envClass.kind === 'quota') {
756
+ const rawQuotaOut = `${verifyResult.check?.error ?? ''}\n${verifyResult.check?.stderr ?? ''}\n${verifyResult.check?.stdout ?? ''}`;
757
+ const diag = envClass.diagnosis || tailLines(lastResult.output || '', 3);
758
+ const waitMs = parseRateLimitResetMs(rawQuotaOut);
759
+ if (waitMs != null && waitMs >= 0 && waitMs <= maxQuotaWaitMs && quotaWaits < maxQuotaWaits) {
760
+ quotaWaits += 1;
761
+ this.emit(ctx, {
762
+ type: 'RateLimitWait',
763
+ work_item_id: nodeId,
764
+ attempt_id: attemptId,
765
+ payload: { task: nodeId, attempt_number: attempt, wait_ms: waitMs, quota_wait: quotaWaits, diagnosis: diag },
766
+ });
767
+ await sleepFn(waitMs);
768
+ this.recordProgress();
769
+ attempt -= 1;
770
+ continue;
771
+ }
772
+ const resume = quotaResumeAt(rawQuotaOut);
773
+ this.pauseForFailure(ctx, nodeId, 'quota', diag, resume);
774
+ this.blockNode(nodeId, ctx, status, blocked, 'paused_quota', diag);
775
+ return;
776
+ }
777
+ // OXB-155: a verify that timed out did not fail — the clock did. It is never "identical_verify_failure".
778
+ const verifyTimedOut = Boolean(verifyResult.check?.timed_out);
779
+ const signature = verifyTimedOut || turnLimitWithWork ? null : verifyFailureSignature(verifyResult.check);
489
780
  if (signature && signature === lastVerifySignature) {
490
781
  verifySuspect = true;
491
782
  this.emit(ctx, {
@@ -502,6 +793,66 @@ class Scheduler {
502
793
  break;
503
794
  }
504
795
  lastVerifySignature = signature;
796
+ // OXB-171: the frozen test needs a file outside the task's scope (plan lint) and it is THAT test failing, or
797
+ // the agent said the change it needs is out of scope → stop now: a retry cannot pass.
798
+ const scopeReason = turnLimitWithWork ? null : scopeInsufficientReason(nodeId, ctx, `${verifyResult.check?.stdout ?? ''}\n${verifyResult.check?.stderr ?? ''}`, agentOutput);
799
+ if (scopeReason) {
800
+ lastResult = { ...lastResult, failure_class: 'scope_insufficient' };
801
+ this.emit(ctx, {
802
+ type: 'ScopeInsufficient',
803
+ work_item_id: nodeId,
804
+ attempt_id: attemptId,
805
+ payload: { task: nodeId, attempt_number: attempt, ...scopeReason, output_tail: tailLines(`${verifyResult.check?.stdout ?? ''}\n${verifyResult.check?.stderr ?? ''}`, 40) },
806
+ });
807
+ lastError = lastResult.output || 'scope_insufficient';
808
+ break;
809
+ }
810
+ }
811
+ else if (parallelNode) {
812
+ // OXB-050: green in its worktree → integrate (in-scope files only) and verify again on the integrated tree,
813
+ // under the integration lock; only then the task completes (and its checkpoint is committed).
814
+ const attemptLease = lease;
815
+ const outcome = await this.withIntegrationLock(async () => {
816
+ const integration = await ctx.parallel.integrate(node, attemptLease);
817
+ if (integration.outside.length) {
818
+ this.emit(ctx, {
819
+ type: 'ScopeViolation',
820
+ work_item_id: nodeId,
821
+ attempt_id: attemptId,
822
+ payload: { task: nodeId, paths: integration.outside, outcome: 'not_integrated', workspace: 'worktree' },
823
+ });
824
+ }
825
+ if (!integration.ok)
826
+ return { ok: false, output: `integration_failed: ${integration.error ?? 'unknown'}` };
827
+ const integrated = await this.verifyNode(node, { ...attemptLease, root_path: ctx.projectRoot }, ctx, attemptId, attempt);
828
+ if (integrated && integrated.status === 'failed') {
829
+ await ctx.parallel.discard(integration.files);
830
+ return {
831
+ ok: false,
832
+ 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)}`,
833
+ };
834
+ }
835
+ this.emit(ctx, {
836
+ type: 'WorkItemCompleted',
837
+ work_item_id: nodeId,
838
+ attempt_id: attemptId,
839
+ payload: {
840
+ attempt_number: attempt,
841
+ evidence: lastResult.evidence,
842
+ workspace: 'worktree',
843
+ integrated_files: integration.files,
844
+ ...(turnLimitWithWork ? { completed_by: 'verify_after_turn_limit' } : {}),
845
+ },
846
+ });
847
+ return { ok: true, output: '' };
848
+ });
849
+ if (outcome.ok) {
850
+ status.set(nodeId, 'completed');
851
+ completed.push(nodeId);
852
+ this.recordProgress();
853
+ return;
854
+ }
855
+ lastResult = { success: false, failure_class: 'verify', evidence: lastResult.evidence, output: outcome.output };
505
856
  }
506
857
  else {
507
858
  this.emit(ctx, {
@@ -521,9 +872,116 @@ class Scheduler {
521
872
  }
522
873
  }
523
874
  lastError = lastResult.output || (lastResult.failure_class ?? 'unknown error');
524
- if (lastResult.failure_class === 'policy')
875
+ // OXB-171: the agent stopped saying the needed change is outside its files — a retry has the same files.
876
+ if (!lastResult.success && lastResult.failure_class !== 'scope_insufficient' && lastResult.failure_class !== 'turns_exhausted' && OUT_OF_SCOPE_RE.test(agentOutput)) {
877
+ lastResult = { ...lastResult, failure_class: 'scope_insufficient' };
878
+ this.emit(ctx, {
879
+ type: 'ScopeInsufficient',
880
+ work_item_id: nodeId,
881
+ attempt_id: attemptId,
882
+ payload: { task: nodeId, attempt_number: attempt, reason: 'agent_reported_out_of_scope', output_tail: tailLines(agentOutput, 40) },
883
+ });
884
+ break;
885
+ }
886
+ if (lastResult.failure_class === 'scope_insufficient')
887
+ break;
888
+ // OXB-125: waiting for a person's answer — never a retry
889
+ if (lastResult.failure_class === 'waiting_answer') {
890
+ this.blockNode(nodeId, ctx, status, blocked, 'waiting_answer', tailLines(lastResult.output || '', 3));
891
+ return;
892
+ }
893
+ if (lastResult.failure_class === 'policy') {
894
+ // OXB-C28-1: a refusal triggered by tool outputs of earlier turns (not the pack) gets ONE automatic clean
895
+ // retry — a fresh context (the pack and the tree) has none of those outputs. execute.policy_auto_retry: false
896
+ // turns it off. A prompt-triggered refusal still needs --retry-policy-once.
897
+ const autoPolicy = !policyRetried && lastResult.policy_trigger === 'tool_output'
898
+ && ctx.options?.policyAutoRetry !== false
899
+ && !ctx.options?.retryPolicyOnce;
900
+ if (!autoPolicy && (!ctx.options?.retryPolicyOnce || policyRetried))
901
+ break;
902
+ policyRetried = true;
903
+ if (holdForPause(attempt + 1))
904
+ return;
905
+ // the run's retry quota counts this attempt too (cross-review 15/11)
906
+ const policyRetryBlocked = this.consumeRetryQuota(ctx);
907
+ if (policyRetryBlocked) {
908
+ this.blockNode(nodeId, ctx, status, blocked, 'quota_exceeded', policyRetryBlocked);
909
+ return;
910
+ }
911
+ if (attempt >= maxAttempts)
912
+ maxAttempts = attempt + 1;
913
+ this.emit(ctx, {
914
+ type: 'RetryScheduled',
915
+ work_item_id: nodeId,
916
+ attempt_id: attemptId,
917
+ // output_tail: the refused attempt keeps its log (attempts/<task>-<n>.log) with the trigger candidates
918
+ payload: { task: nodeId, attempt_number: attempt, next_attempt: attempt + 1, reason: autoPolicy ? 'policy_auto_retry' : 'policy_retry_once', output_tail: tailLines(lastResult.output || '', 60) },
919
+ });
920
+ // a clean retry: the refusal text (and the CLI hint) never goes back into the model's prompt — it would feed
921
+ // the classifier and instruct the model with a human command (cross-review 15/11)
922
+ lastError = null;
923
+ continue;
924
+ }
925
+ // The output of a red verify (or of an attempt that ran out of turns / made no progress) is the project's test
926
+ // log: a test called "resets the form" or an error at line 429 is logic, not the provider.
927
+ const executorLevelFailure = !lastResult.failure_class || ['env', 'llm', 'timeout', 'quota'].includes(String(lastResult.failure_class));
928
+ const execClass = executorLevelFailure
929
+ ? classifyFailureOutput(lastResult.output || '', null, ctx.options?.failureClasses)
930
+ : null;
931
+ // OXB-120 / OXB-191 / OXB-204: short 429 rate-limit windows wait for the reported reset; long/unknown quotas pause.
932
+ if (lastResult.failure_class === 'quota' || execClass?.kind === 'quota') {
933
+ const rawQuotaOut = lastResult.output || '';
934
+ const diag = (execClass?.kind === 'quota' ? execClass.diagnosis : null) || tailLines(rawQuotaOut, 3);
935
+ const waitMs = parseRateLimitResetMs(rawQuotaOut);
936
+ if (waitMs != null && waitMs >= 0 && waitMs <= maxQuotaWaitMs && quotaWaits < maxQuotaWaits) {
937
+ quotaWaits += 1;
938
+ this.emit(ctx, {
939
+ type: 'RateLimitWait',
940
+ work_item_id: nodeId,
941
+ attempt_id: attemptId,
942
+ payload: { task: nodeId, attempt_number: attempt, wait_ms: waitMs, quota_wait: quotaWaits, diagnosis: diag },
943
+ });
944
+ await sleepFn(waitMs);
945
+ this.recordProgress();
946
+ if (holdForPause(attempt))
947
+ return; // a pause during the wait: no paid call after it (R34)
948
+ attempt -= 1;
949
+ continue;
950
+ }
951
+ const resume = quotaResumeAt(rawQuotaOut);
952
+ this.pauseForFailure(ctx, nodeId, 'quota', diag, resume);
953
+ this.blockNode(nodeId, ctx, status, blocked, 'paused_quota', diag);
954
+ return;
955
+ }
956
+ quotaWaits = 0;
957
+ // cross-review 15/11: the http adapter reports a refused credential / missing endpoint (401/403/404) as
958
+ // `environment` itself — configuration, not a reason to pay another attempt
959
+ if (execClass?.kind === 'environment' || lastResult.failure_class === 'environment') {
960
+ const diag = execClass?.kind === 'environment' ? execClass.diagnosis : tailLines(lastResult.output || '', 3);
961
+ this.pauseForFailure(ctx, nodeId, 'environment', diag, null);
962
+ this.blockNode(nodeId, ctx, status, blocked, 'paused_environment', diag);
963
+ return;
964
+ }
965
+ // OXB-148: a prompt that does not fit fails the same way on a blind retry.
966
+ if (lastResult.failure_class === 'context')
525
967
  break;
968
+ // OXB-130: decide the repair before paying another attempt.
969
+ if (attempt < maxAttempts && ctx.repairFor) {
970
+ const repair = ctx.repairFor(nodeId, { attempt, maxAttempts, failureClass: lastResult.failure_class ?? null, output: String(lastResult.output || ''), verifySuspect });
971
+ if (repair) {
972
+ 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 } });
973
+ if (repair.strategy !== 'retry') {
974
+ this.blockNode(nodeId, ctx, status, blocked, `repair_${repair.strategy}`, repair.reason);
975
+ return;
976
+ }
977
+ if (repair.adjustment)
978
+ lastError = `${lastError ?? ''}\n\n## Ajuste declarado para esta tentativa\n${repair.adjustment}`;
979
+ }
980
+ }
526
981
  if (attempt < maxAttempts) {
982
+ // a pause: no retry quota spent, no RetryScheduled banner (R34)
983
+ if (holdForPause(attempt + 1))
984
+ return;
527
985
  const retryBlocked = this.consumeRetryQuota(ctx);
528
986
  if (retryBlocked) {
529
987
  this.blockNode(nodeId, ctx, status, blocked, 'quota_exceeded', retryBlocked);
@@ -535,7 +993,7 @@ class Scheduler {
535
993
  this.emit(ctx, {
536
994
  type: 'RetryScheduled',
537
995
  work_item_id: nodeId,
538
- payload: { next_attempt: attempt + 1, reason: lastResult.failure_class, backoff_ms: backoffMs, output_tail: tailLines(lastResult.output || '', 60) },
996
+ 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 } : {}) },
539
997
  });
540
998
  }
541
999
  }
@@ -576,7 +1034,7 @@ class Scheduler {
576
1034
  this.emit(ctx, {
577
1035
  type: 'WorkItemBlocked',
578
1036
  work_item_id: nodeId,
579
- payload: { failure_class: verifySuspect ? 'verify_suspect' : lastResult?.failure_class ?? 'env', max_attempts: maxAttempts, output_tail: tailLines(lastResult?.output || '', 60) },
1037
+ 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 } : {}) },
580
1038
  });
581
1039
  status.set(nodeId, 'failed');
582
1040
  failed.push(nodeId);
@@ -594,6 +1052,27 @@ class Scheduler {
594
1052
  }
595
1053
  return { run_id: ctx.runId, status: 'aborted', completed, failed, blocked, reason };
596
1054
  }
1055
+ /** A pause requested from outside (`runtime pause`) takes effect before the next node, never in the middle of one. */
1056
+ checkRequestedPause(ctx) {
1057
+ if (this.paused || !ctx.pauseRequested)
1058
+ return;
1059
+ let reason = null;
1060
+ try {
1061
+ reason = ctx.pauseRequested();
1062
+ }
1063
+ catch {
1064
+ reason = null;
1065
+ }
1066
+ if (!reason)
1067
+ return;
1068
+ this.emit(ctx, { type: 'RunPaused', payload: { reason: 'requested', diagnosis: reason, resume_at: null } });
1069
+ this.pause();
1070
+ }
1071
+ /** OXB-120: pause the run for a failure that is not the task's (environment / quota). */
1072
+ pauseForFailure(ctx, nodeId, kind, diagnosis, resumeAt) {
1073
+ this.emit(ctx, { type: 'RunPaused', work_item_id: nodeId, payload: { reason: kind, diagnosis, resume_at: resumeAt, task: nodeId } });
1074
+ this.pause();
1075
+ }
597
1076
  pause() {
598
1077
  this.paused = true;
599
1078
  if (this.journal && this.ctx) {
@@ -696,48 +1175,146 @@ class Scheduler {
696
1175
  work_item_id: node.id,
697
1176
  payload: { command: node.verify.command, attempt_number: attempt },
698
1177
  });
699
- const suite = {
700
- checks: [{
701
- id: `inline-${node.id}`,
702
- type: 'custom',
703
- command: node.verify.command,
704
- evidence_type_expected: 'stdout',
705
- acceptance_ref: null,
706
- description: `Verify ${node.id}`,
707
- }],
708
- compiled_at: new Date().toISOString(),
709
- spec_hash: '',
710
- plan_hash: '',
711
- };
712
- let result;
713
- try {
714
- result = await (0, verification_compiler_1.verifyRun)({
715
- suite,
716
- cwd: lease.root_path,
717
- timeoutMs: ctx.options?.verifyTimeoutMs ?? 60000,
718
- runId: ctx.runId,
719
- workItemId: node.id,
720
- attemptNumber: attempt,
721
- projectRoot: ctx.projectRoot,
722
- pluginRegistry: ctx.pluginRegistry,
723
- });
724
- }
725
- catch (err) {
726
- this.emit(ctx, {
727
- type: 'VerificationCompleted',
728
- work_item_id: node.id,
729
- attempt_id: attemptId,
730
- payload: { status: 'error', error: String(err) },
731
- });
732
- return null;
1178
+ // 1.21.2 (OXB-066): each top-level `&&` segment runs on its own, in order, stopping at the first failure. As one
1179
+ // command, `vitest … && tsc --noEmit` failed in tsc but the retry only carried the passing vitest output: the
1180
+ // executor never saw the type error (oxespace 1.5.0 T13: 4 attempts, US$ 4.54, 0 completed).
1181
+ const segments = splitVerifySegments(node.verify.command);
1182
+ // OXB-C28-2: consecutive remote segments run as one remote job (all_segments keeps one run per segment: it must
1183
+ // see every red segment, and one remote `&&` chain stops at the first)
1184
+ const units = ctx.options?.allSegments
1185
+ ? segments.map((command, i) => ({ command, members: [i] }))
1186
+ : groupRemoteSegments(segments);
1187
+ const ran = [];
1188
+ const gaps = [];
1189
+ let status = 'passed';
1190
+ let failing = null;
1191
+ for (const unit of units) {
1192
+ const index = unit.members[0];
1193
+ const lastMember = unit.members[unit.members.length - 1];
1194
+ const merged = unit.members.length > 1;
1195
+ const command = unit.command;
1196
+ const label = merged ? `${index + 1}-${lastMember + 1}` : `${index + 1}`;
1197
+ const suite = {
1198
+ checks: [{
1199
+ id: segments.length > 1 ? `inline-${node.id}-s${label}` : `inline-${node.id}`,
1200
+ type: 'custom',
1201
+ command,
1202
+ evidence_type_expected: 'stdout',
1203
+ acceptance_ref: null,
1204
+ description: `Verify ${node.id}${segments.length > 1 ? ` [${label}/${segments.length}]${merged ? ' (uma rodada remota)' : ''}` : ''}`,
1205
+ }],
1206
+ compiled_at: new Date().toISOString(),
1207
+ spec_hash: '',
1208
+ plan_hash: '',
1209
+ };
1210
+ let result;
1211
+ try {
1212
+ result = await (0, verification_compiler_1.verifyRun)({
1213
+ suite,
1214
+ cwd: lease.root_path,
1215
+ timeoutMs: ctx.options?.verifyTimeoutMs ?? 600000,
1216
+ runId: ctx.runId,
1217
+ workItemId: node.id,
1218
+ attemptNumber: attempt,
1219
+ projectRoot: ctx.projectRoot,
1220
+ pluginRegistry: ctx.pluginRegistry,
1221
+ });
1222
+ }
1223
+ catch (err) {
1224
+ this.emit(ctx, {
1225
+ type: 'VerificationCompleted',
1226
+ work_item_id: node.id,
1227
+ attempt_id: attemptId,
1228
+ payload: { status: 'error', error: String(err), failed_segment: { index: index + 1, total: segments.length, command, exit_code: null } },
1229
+ });
1230
+ return null;
1231
+ }
1232
+ let segmentRun = { index: index + 1, total: segments.length, command, status: result.status, check: result.check_results?.[0] };
1233
+ if (merged) {
1234
+ const c0 = result.check_results?.[0];
1235
+ const at = result.status === 'passed' ? lastMember : remoteFailedMember(`${c0?.stdout ?? ''}\n${c0?.stderr ?? ''}`, unit.members);
1236
+ segmentRun = { ...segmentRun, index: at + 1, command: segments[at], merged: unit.members.map((m) => m + 1) };
1237
+ }
1238
+ // OXB-162: the same command, or test files an earlier segment of THIS attempt already passed, failing now is a
1239
+ // flaky suspect: rerun once; green → continue (marked), red → the task fails as before.
1240
+ if (result.status === 'failed') {
1241
+ const files = segmentTestFiles(command);
1242
+ const earlier = ran.find((r) => r.status === 'passed' && (r.command === command || (files.length > 0 && files.every((f) => segmentTestFiles(r.command).includes(f)))));
1243
+ if (earlier) {
1244
+ let rerun = null;
1245
+ try {
1246
+ rerun = await (0, verification_compiler_1.verifyRun)({
1247
+ suite: { ...suite, checks: suite.checks.map((c) => ({ ...c, id: `${c.id}-rerun` })) },
1248
+ cwd: lease.root_path,
1249
+ timeoutMs: ctx.options?.verifyTimeoutMs ?? 600000,
1250
+ runId: ctx.runId,
1251
+ workItemId: node.id,
1252
+ attemptNumber: attempt,
1253
+ projectRoot: ctx.projectRoot,
1254
+ pluginRegistry: ctx.pluginRegistry,
1255
+ });
1256
+ }
1257
+ catch {
1258
+ rerun = null;
1259
+ }
1260
+ const green = rerun?.status === 'passed';
1261
+ this.emit(ctx, {
1262
+ type: 'VerifyCommandSuspect',
1263
+ work_item_id: node.id,
1264
+ attempt_id: attemptId,
1265
+ 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) },
1266
+ });
1267
+ if (green && rerun) {
1268
+ result = rerun;
1269
+ segmentRun = { ...segmentRun, status: 'passed', check: rerun.check_results?.[0], flaky_suspect: true };
1270
+ }
1271
+ else {
1272
+ segmentRun = { ...segmentRun, flaky_suspect: true };
1273
+ }
1274
+ }
1275
+ }
1276
+ ran.push(segmentRun);
1277
+ gaps.push(...(result.gaps ?? []));
1278
+ if (result.status === 'failed') {
1279
+ status = 'failed';
1280
+ if (!failing)
1281
+ failing = segmentRun;
1282
+ if (!ctx.options?.allSegments)
1283
+ break;
1284
+ }
1285
+ if (result.status !== 'passed' && status === 'passed')
1286
+ status = result.status;
733
1287
  }
1288
+ const failedRuns = ran.filter((r) => r.status === 'failed');
1289
+ // OXB-171: the failing segment's own output tail rides in the event (the cause was only found by rerunning by hand).
1290
+ const failedSegment = failing
1291
+ ? { 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) }
1292
+ : null;
1293
+ const failedSegments = failedRuns.map((f) => ({
1294
+ index: f.index,
1295
+ total: f.total,
1296
+ command: f.command,
1297
+ exit_code: f.check?.exit_code ?? null,
1298
+ output_tail: tailLines(`${f.check?.stdout ?? ''}\n${f.check?.stderr ?? ''}\n${f.check?.error ?? ''}`, 40),
1299
+ }));
734
1300
  this.emit(ctx, {
735
1301
  type: 'VerificationCompleted',
736
1302
  work_item_id: node.id,
737
1303
  attempt_id: attemptId,
738
- payload: { status: result.status },
1304
+ payload: {
1305
+ status,
1306
+ ...(failedSegment ? { failed_segment: failedSegment } : {}),
1307
+ ...(failedSegments.length > 1 ? { failed_segments: failedSegments } : {}),
1308
+ },
739
1309
  });
740
- return { status: result.status, gaps: result.gaps, check: result.check_results?.[0] };
1310
+ const last = ran[ran.length - 1];
1311
+ return {
1312
+ status,
1313
+ gaps,
1314
+ check: failing ? failing.check : last?.check,
1315
+ segment: failedSegment,
1316
+ segments: ran,
1317
+ };
741
1318
  }
742
1319
  evaluatePolicyForNode(node, ctx) {
743
1320
  if (!ctx.policyEngine)
@@ -902,16 +1479,323 @@ function inferGateScope(node) {
902
1479
  return 'plan_approval';
903
1480
  }
904
1481
  /** Last `n` non-empty lines of a text. */
1482
+ /**
1483
+ * OXB-120: a failure that is not the task's logic must not cost an attempt. Environment (exit 126/127, a missing
1484
+ * executable, a build artifact not built, a native module for another Node, the network) and quota (a provider usage
1485
+ * limit) pause the run with a diagnosis; only `logic` failures consume attempts.
1486
+ */
1487
+ 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;
1488
+ const QUOTA_RE = quota_patterns_1.PROVIDER_QUOTA_RE;
1489
+ function classifyFailureOutput(output, exitCode, extra, opts) {
1490
+ const text = String(output || '');
1491
+ if (exitCode === 0)
1492
+ return null;
1493
+ const lineOf = (re) => (text.split(/\r?\n/).find((l) => re.test(l) && !/FileSystemFileChangedEvent/i.test(l)) || '').trim().slice(0, 240);
1494
+ const extraRe = (list) => (list || []).map((p) => { try {
1495
+ return new RegExp(p, 'i');
1496
+ }
1497
+ catch {
1498
+ return null;
1499
+ } }).filter(Boolean);
1500
+ for (const re of extraRe(extra?.quota))
1501
+ if (re.test(text))
1502
+ return { kind: 'quota', diagnosis: lineOf(re) || 'quota exceeded' };
1503
+ for (const re of extraRe(extra?.environment))
1504
+ if (re.test(text)) {
1505
+ const diag = lineOf(re);
1506
+ if (diag)
1507
+ return { kind: 'environment', diagnosis: diag };
1508
+ }
1509
+ if (opts?.builtinQuota !== false && QUOTA_RE.test(text))
1510
+ return { kind: 'quota', diagnosis: lineOf(QUOTA_RE) || 'quota limit reached' };
1511
+ if (exitCode === 126 || exitCode === 127)
1512
+ return { kind: 'environment', diagnosis: lineOf(/./) || `exit ${exitCode}` };
1513
+ if (ENVIRONMENT_RE.test(text)) {
1514
+ const diag = lineOf(ENVIRONMENT_RE);
1515
+ if (diag)
1516
+ return { kind: 'environment', diagnosis: diag };
1517
+ }
1518
+ return null;
1519
+ }
1520
+ function quotaResumeAt(text) {
1521
+ const m = /resets? (?:at|in|on)?\s*([^\n.;·]{3,40})|try again (?:in|after) ([^\n.;·]{2,30})/i.exec(String(text || ''));
1522
+ return m ? (m[1] || m[2]).trim() : null;
1523
+ }
1524
+ function unitMultiplierMs(unit, defaultMs = 1000) {
1525
+ const u = String(unit || '').trim().toLowerCase();
1526
+ if (!u)
1527
+ return defaultMs;
1528
+ if (u === 'ms' || u.startsWith('millisecond'))
1529
+ return 1;
1530
+ if (u === 's' || u.startsWith('sec'))
1531
+ return 1000;
1532
+ if (u === 'm' || u.startsWith('min'))
1533
+ return 60000;
1534
+ if (u === 'h' || u.startsWith('hr') || u.startsWith('hour'))
1535
+ return 3600000;
1536
+ return defaultMs;
1537
+ }
1538
+ /**
1539
+ * OXB-204: extract explicit reset/retry duration in ms from 429 headers or provider error payloads.
1540
+ * Returns `null` when no machine-actionable duration is present (e.g. "resets Nov 14, 10am"), so multi-day
1541
+ * quotas still pause immediately instead of guessing.
1542
+ */
1543
+ function parseRateLimitResetMs(text, nowMs = Date.now(), retryAfterHeader) {
1544
+ if (retryAfterHeader != null && String(retryAfterHeader).trim() !== '') {
1545
+ const rawHeader = String(retryAfterHeader).trim();
1546
+ if (/^\d+(?:\.\d+)?$/.test(rawHeader)) {
1547
+ const ms = Math.ceil(Number(rawHeader) * 1000);
1548
+ if (Number.isFinite(ms) && ms >= 0)
1549
+ return ms;
1550
+ }
1551
+ else {
1552
+ const parsedDate = Date.parse(rawHeader);
1553
+ if (Number.isFinite(parsedDate) && parsedDate >= nowMs) {
1554
+ return Math.ceil(parsedDate - nowMs);
1555
+ }
1556
+ }
1557
+ }
1558
+ const raw = String(text || '');
1559
+ if (!raw)
1560
+ return null;
1561
+ const retryDelayMatch = /"?retryDelay"?\s*[:=]\s*"?(\d+(?:\.\d+)?)\s*(ms|milliseconds?|s|secs?|seconds?|m|mins?|minutes?|h|hrs?|hours?)?"?/i.exec(raw);
1562
+ if (retryDelayMatch) {
1563
+ const ms = Math.ceil(Number(retryDelayMatch[1]) * unitMultiplierMs(retryDelayMatch[2], 1000));
1564
+ if (Number.isFinite(ms) && ms >= 0)
1565
+ return ms;
1566
+ }
1567
+ const retryAfterField = /"?(retry[-_ ]after(?:[-_ ]ms)?)"?\s*[:=]\s*"?(\d+(?:\.\d+)?)\s*(ms|milliseconds?|s|secs?|seconds?|m|mins?|minutes?|h|hrs?|hours?)?"?/i.exec(raw);
1568
+ if (retryAfterField) {
1569
+ const defaultMs = /ms$/i.test(retryAfterField[1]) ? 1 : 1000;
1570
+ const ms = Math.ceil(Number(retryAfterField[2]) * unitMultiplierMs(retryAfterField[3], defaultMs));
1571
+ if (Number.isFinite(ms) && ms >= 0)
1572
+ return ms;
1573
+ }
1574
+ 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);
1575
+ if (relMatch) {
1576
+ let totalMs = 0;
1577
+ let matchedAny = false;
1578
+ const tokenRe = /(\d+(?:\.\d+)?)\s*(ms|milliseconds?|s|secs?|seconds?|m|mins?|minutes?|h|hrs?|hours?)/gi;
1579
+ let tok;
1580
+ while ((tok = tokenRe.exec(relMatch[1])) !== null) {
1581
+ totalMs += Number(tok[1]) * unitMultiplierMs(tok[2], 1000);
1582
+ matchedAny = true;
1583
+ }
1584
+ if (matchedAny && Number.isFinite(totalMs) && totalMs >= 0)
1585
+ return Math.ceil(totalMs);
1586
+ }
1587
+ const isoMatch = /resets?\s+(?:at\s+)?(\d{4}-\d{2}-\d{2}T[\d:.]+(?:Z|[+-]\d{2}:?\d{2}))/i.exec(raw);
1588
+ if (isoMatch) {
1589
+ const parsed = Date.parse(isoMatch[1]);
1590
+ if (Number.isFinite(parsed) && parsed >= nowMs)
1591
+ return Math.ceil(parsed - nowMs);
1592
+ }
1593
+ return null;
1594
+ }
1595
+ /** OXB-171: an agent that says the change it needs is outside its files (pt/en). */
1596
+ 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;
1597
+ /** OXB-C27-1: the output names this file (its path, or a non-generic basename such as sectionsApi.ts). */
1598
+ function mentionsFile(output, file) {
1599
+ const f = String(file || '').replace(/\\/g, '/').replace(/^\.\//, '');
1600
+ if (!f)
1601
+ return false;
1602
+ if (output.includes(f))
1603
+ return true;
1604
+ const base = f.split('/').pop() || '';
1605
+ if (!base || /^index\.[cm]?[jt]sx?$/i.test(base)) {
1606
+ const tail = f.split('/').slice(-2).join('/');
1607
+ return tail.includes('/') && output.includes(tail);
1608
+ }
1609
+ return new RegExp(`(^|[\\s/\\\\(\\['"\`])${base.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(:\\d+|[\\s)'"\`]|$)`, 'm').test(output);
1610
+ }
1611
+ function scopeInsufficientReason(nodeId, ctx, verifyOutput, agentOutput) {
1612
+ const req = ctx.options?.outOfScopeRequirements?.[nodeId];
1613
+ if (req && req.files.length) {
1614
+ const out = String(verifyOutput || '').replace(/\\/g, '/');
1615
+ const named = req.tests.filter((t) => out.includes(t) || out.includes(t.split('/').pop() || t));
1616
+ // OXB-C27-1: an import is not a cause. Only when the failure passes through an out-of-scope file (the stack or
1617
+ // the diff names it) is it scope_insufficient; a fixture defect in the test (polish2 T6) is retried and, when it
1618
+ // repeats, becomes verify_suspect naming the test.
1619
+ const said = String(agentOutput || '').replace(/\\/g, '/');
1620
+ const touched = named.length ? req.files.filter((f) => mentionsFile(out, f) || mentionsFile(said, f)) : [];
1621
+ if (touched.length)
1622
+ return { reason: 'frozen_test_needs_out_of_scope_file', files: touched, tests: named };
1623
+ }
1624
+ if (OUT_OF_SCOPE_RE.test(agentOutput))
1625
+ return { reason: 'agent_reported_out_of_scope' };
1626
+ // OXB-188: the agent left a stub it labels as blocked — the change it needs is outside the scope; never a retry.
1627
+ const blocked = /scope_insufficient: stub marcado como bloqueado[^\n]*/.exec(String(verifyOutput || ''));
1628
+ if (blocked) {
1629
+ const files = [...new Set([...blocked[0].matchAll(/precisa de ([^,(]+(?:, [^,(]+)*), fora do escopo/g)].flatMap((m) => m[1].split(', ').map((x) => x.trim())))];
1630
+ return { reason: 'blocked_stub', files, detail: blocked[0] };
1631
+ }
1632
+ // The pack names a symbol absent at the base that the attempt did not create (a name guessed from the file): a
1633
+ // plan defect, never fixed by a retry.
1634
+ const packDefect = /plan_defect: o pack nomeia um símbolo que não existe[^\n]*/.exec(String(verifyOutput || ''));
1635
+ if (packDefect) {
1636
+ const files = [...new Set([...packDefect[0].matchAll(/\b[\w$]+ em ([^,:]+?)(?=, |: )/g)].map((m) => m[1].trim()))];
1637
+ return { reason: 'pack_symbol_missing', files, detail: packDefect[0] };
1638
+ }
1639
+ return null;
1640
+ }
1641
+ /** OXB-162: git's line-ending notices — they filled F4-T1's whole output tail and hid the failing test. */
1642
+ 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;
1643
+ /** A failing-test block start (vitest/jest/node:test/mocha/JUnit). */
1644
+ const FAIL_BLOCK_RE = /^\s*(FAIL\b|×|✗|✖|not ok\b|\d+\) |●\s)/;
1645
+ const FAIL_ERROR_RE = /AssertionError|Error: expect/;
905
1646
  function tailLines(text, n) {
906
- return String(text || '').split(/\r?\n/).map((l) => l.trimEnd()).filter((l) => l.trim()).slice(-n).join('\n');
1647
+ const lines = String(text || '').split(/\r?\n/).map((l) => l.trimEnd()).filter((l) => l.trim() && !GIT_EOL_NOTICE_RE.test(l));
1648
+ const tail = lines.slice(-n);
1649
+ // OXB-162: the last failing-test block, when the tail (summary lines, noise) does not reach it.
1650
+ let lastFail = -1;
1651
+ for (let i = lines.length - 1; i >= 0; i -= 1)
1652
+ if (FAIL_BLOCK_RE.test(lines[i])) {
1653
+ lastFail = i;
1654
+ break;
1655
+ }
1656
+ if (lastFail < 0)
1657
+ for (let i = lines.length - 1; i >= 0; i -= 1)
1658
+ if (FAIL_ERROR_RE.test(lines[i])) {
1659
+ lastFail = i;
1660
+ break;
1661
+ }
1662
+ if (lastFail >= 0 && lastFail < lines.length - n) {
1663
+ const block = lines.slice(lastFail, Math.min(lastFail + Math.max(10, Math.floor(n / 2)), lines.length - n));
1664
+ return [...block, '…', ...tail.slice(-Math.max(1, n - block.length - 1))].join('\n');
1665
+ }
1666
+ return tail.join('\n');
1667
+ }
1668
+ /** OXB-162: the test files a segment names (`x.test.ts`, `y.spec.js`, JVM `--tests` excluded). */
1669
+ function segmentTestFiles(command) {
1670
+ return [...new Set((String(command).match(/[\w./\\-]+\.(?:test|spec)\.[cm]?[jt]sx?\b/g) || []).map((f) => f.replace(/\\/g, '/').replace(/^\.\//, '')))].sort();
1671
+ }
1672
+ const REMOTE_SEG_RE = /(?:^|[\s/\\"'])remote-verify(?:\.[cm]?js)?["']?(?:\s|$)/i;
1673
+ const REMOTE_MARK = (n) => `===OXE-SEG-${n}===`;
1674
+ /** The `<prefix>` and `<inner command>` of a `<… remote-verify.mjs [opts]> -- <command>` segment, or null. */
1675
+ function remoteSegmentParts(segment) {
1676
+ const idx = segment.indexOf(' -- ');
1677
+ if (idx <= 0)
1678
+ return null;
1679
+ const prefix = segment.slice(0, idx).trim();
1680
+ // the prefix is the runner and its own options: the remote-verify script must be in it
1681
+ if (!REMOTE_SEG_RE.test(prefix))
1682
+ return null;
1683
+ let inner = segment.slice(idx + 4).trim();
1684
+ const q = inner[0];
1685
+ if ((q === '"' || q === "'") && inner.endsWith(q) && inner.length > 1 && !inner.slice(1, -1).includes(q))
1686
+ inner = inner.slice(1, -1).trim();
1687
+ // only text that survives inside one double-quoted shell argument on both sh and cmd; gradle152 has its own path
1688
+ if (!inner || /["`$\\%!]/.test(inner) || /gradle152\.mjs/i.test(inner))
1689
+ return null;
1690
+ return { prefix, inner };
907
1691
  }
908
- /** What the next attempt needs to know about a failed task verify (1.20c informed retry). */
909
- function describeVerifyFailure(command, check, gaps) {
1692
+ /**
1693
+ * OXB-C28-2: consecutive `… remote-verify … -- <cmd>` segments with the same runner prefix run as ONE remote job
1694
+ * (`<prefix> -- "echo ===OXE-SEG-1=== && cmd1 && echo ===OXE-SEG-2=== && cmd2"`) — one push/queue/CI round trip
1695
+ * instead of one per segment (polish2 T3: 8 segments, 2–5 min each). The markers name the failing segment.
1696
+ * `members` are 0-based indexes into `segments`.
1697
+ */
1698
+ function groupRemoteSegments(segments) {
1699
+ const out = [];
1700
+ segments.forEach((seg, i) => {
1701
+ const parts = remoteSegmentParts(seg);
1702
+ const prev = out[out.length - 1];
1703
+ if (parts && prev && prev.prefix === parts.prefix && prev.inners) {
1704
+ prev.members.push(i);
1705
+ prev.inners.push(parts.inner);
1706
+ return;
1707
+ }
1708
+ out.push(parts ? { command: seg, members: [i], prefix: parts.prefix, inners: [parts.inner] } : { command: seg, members: [i] });
1709
+ });
1710
+ return out.map((u) => (u.members.length > 1 && u.prefix && u.inners
1711
+ ? { command: `${u.prefix} -- "${u.inners.map((c, k) => `echo ${REMOTE_MARK(u.members[k] + 1)} && ${c}`).join(' && ')}"`, members: u.members }
1712
+ : { command: u.command, members: u.members }));
1713
+ }
1714
+ /** OXB-C28-2: the 0-based segment of a merged remote run that failed — the last marker the remote log printed. */
1715
+ function remoteFailedMember(output, members) {
1716
+ let found = members[0];
1717
+ for (const m of members)
1718
+ if (String(output || '').includes(REMOTE_MARK(m + 1)))
1719
+ found = m;
1720
+ return found;
1721
+ }
1722
+ /**
1723
+ * Top-level `&&` segments of a verify command (quoted text is not split). Same rule as the dry-verify (OXB-018), so
1724
+ * what the planner checks before execution is what runs after.
1725
+ */
1726
+ function splitVerifySegments(command) {
1727
+ const out = [];
1728
+ let current = '';
1729
+ let quote = null;
1730
+ for (let i = 0; i < command.length; i += 1) {
1731
+ const ch = command[i];
1732
+ if (quote) {
1733
+ if (ch === quote)
1734
+ quote = null;
1735
+ }
1736
+ else if (ch === '"' || ch === "'") {
1737
+ quote = ch;
1738
+ }
1739
+ else if (ch === '&' && command[i + 1] === '&') {
1740
+ if (current.trim())
1741
+ out.push(current.trim());
1742
+ current = '';
1743
+ i += 1;
1744
+ continue;
1745
+ }
1746
+ current += ch;
1747
+ }
1748
+ if (current.trim())
1749
+ out.push(current.trim());
1750
+ return out.length ? out : [command];
1751
+ }
1752
+ /** OXB-184: the retry text plus what the previous attempt left in the tree. */
1753
+ function withAttemptChanges(previousError, changes) {
1754
+ if (!changes || (!changes.kept.length && !changes.gone.length))
1755
+ return previousError;
1756
+ const list = (xs) => xs.slice(0, 30).join(', ') + (xs.length > 30 ? ` (+${xs.length - 30})` : '');
1757
+ const lines = ['', '## O que a tentativa anterior deixou na árvore'];
1758
+ if (changes.kept.length)
1759
+ lines.push(`Mantidos (o verify desta tentativa os vê; não refaça sem motivo): ${list(changes.kept)}`);
1760
+ if (changes.gone.length)
1761
+ lines.push(`Escritos e NÃO mantidos (refaça se ainda forem necessários): ${list(changes.gone)}`);
1762
+ return `${previousError ?? ''}${lines.join('\n')}`;
1763
+ }
1764
+ /** Every segment's output with a header per segment, for the attempt log (`attempts/<Tn>-<n>.log`). */
1765
+ function buildVerifyLog(segments, maxLinesPerSegment = 120) {
1766
+ return (segments ?? []).map((s) => {
1767
+ const check = s.check;
1768
+ const exit = check?.exit_code != null ? `exit ${check.exit_code}` : check?.error ? check.error : s.status;
1769
+ const body = tailLines(`${check?.stdout ?? ''}\n${check?.stderr ?? ''}`, maxLinesPerSegment);
1770
+ 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)'}`;
1771
+ }).join('\n\n');
1772
+ }
1773
+ function describeVerifyFailure(command, check, gaps, segment, segments) {
1774
+ const failedList = (segments ?? []).filter((s) => s.status === 'failed');
1775
+ if (failedList.length > 1) {
1776
+ const blocks = failedList.map((f) => {
1777
+ const r = f.check?.error || (f.check?.exit_code != null ? `exit code ${f.check.exit_code}` : 'failed');
1778
+ const out = tailLines(`${f.check?.stdout ?? ''}\n${f.check?.stderr ?? ''}`, 30);
1779
+ return `Failing segment [${f.index}/${f.total}]: ${f.command} (${r})\n${out ? out.slice(-2500) : '(empty)'}`;
1780
+ });
1781
+ return [
1782
+ 'Verification failed after your previous attempt.',
1783
+ `Command: ${command ?? '(none)'}`,
1784
+ `${failedList.length} of ${failedList[0].total} verify segments failed:`,
1785
+ ...blocks,
1786
+ '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.',
1787
+ ].join('\n');
1788
+ }
910
1789
  const reason = check?.error || (check?.exit_code != null ? `exit code ${check.exit_code}` : (gaps || []).join('; ') || 'checks did not pass');
1790
+ // Only the failing segment's output: the tail of a passing earlier segment never reaches the executor (OXB-066).
911
1791
  const output = tailLines(`${check?.stdout ?? ''}\n${check?.stderr ?? ''}`, 40);
1792
+ const failingLine = segment && segment.total > 1
1793
+ ? [`Failing segment [${segment.index}/${segment.total}]: ${segment.command}`, `(segments before it passed; the output below is only from this segment)`]
1794
+ : [];
912
1795
  return [
913
1796
  'Verification failed after your previous attempt.',
914
1797
  `Command: ${command ?? '(none)'}`,
1798
+ ...failingLine,
915
1799
  `Reason: ${reason}`,
916
1800
  output ? `Output (last lines):\n${output.slice(-4000)}` : 'Output: (empty)',
917
1801
  '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.',