oxe-cc 1.16.0 → 1.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (590) hide show
  1. package/.cursor/commands/oxe-alm.md +47 -0
  2. package/.cursor/commands/oxe-ask.md +1 -1
  3. package/.cursor/commands/oxe-capabilities.md +1 -1
  4. package/.cursor/commands/oxe-checkpoint.md +1 -1
  5. package/.cursor/commands/oxe-compact.md +1 -1
  6. package/.cursor/commands/oxe-dashboard.md +1 -1
  7. package/.cursor/commands/oxe-debug.md +1 -1
  8. package/.cursor/commands/oxe-discuss.md +45 -45
  9. package/.cursor/commands/oxe-execute.md +52 -50
  10. package/.cursor/commands/oxe-forensics.md +1 -1
  11. package/.cursor/commands/oxe-help.md +44 -44
  12. package/.cursor/commands/oxe-loop.md +1 -1
  13. package/.cursor/commands/oxe-milestone.md +1 -1
  14. package/.cursor/commands/oxe-next.md +44 -44
  15. package/.cursor/commands/oxe-obs.md +1 -1
  16. package/.cursor/commands/oxe-plan-agent.md +1 -1
  17. package/.cursor/commands/oxe-plan.md +49 -47
  18. package/.cursor/commands/oxe-project.md +1 -1
  19. package/.cursor/commands/oxe-quick.md +49 -47
  20. package/.cursor/commands/oxe-research.md +1 -1
  21. package/.cursor/commands/oxe-retro.md +1 -1
  22. package/.cursor/commands/oxe-review-pr.md +47 -47
  23. package/.cursor/commands/oxe-route.md +1 -1
  24. package/.cursor/commands/oxe-scan.md +47 -47
  25. package/.cursor/commands/oxe-security.md +1 -1
  26. package/.cursor/commands/oxe-session.md +1 -1
  27. package/.cursor/commands/oxe-ship.md +47 -47
  28. package/.cursor/commands/oxe-skill.md +1 -1
  29. package/.cursor/commands/oxe-spec.md +49 -47
  30. package/.cursor/commands/oxe-ui-review.md +1 -1
  31. package/.cursor/commands/oxe-ui-spec.md +1 -1
  32. package/.cursor/commands/oxe-update.md +1 -1
  33. package/.cursor/commands/oxe-validate-gaps.md +1 -1
  34. package/.cursor/commands/oxe-verify-audit.md +1 -1
  35. package/.cursor/commands/oxe-verify.md +50 -50
  36. package/.cursor/commands/oxe-workflow-authoring.md +1 -1
  37. package/.cursor/commands/oxe-workstream.md +1 -1
  38. package/.cursor/commands/oxe.md +51 -49
  39. package/.github/copilot-instructions.md +3 -3
  40. package/.github/prompts/oxe-alm.prompt.md +47 -0
  41. package/.github/prompts/oxe-ask.prompt.md +47 -47
  42. package/.github/prompts/oxe-capabilities.prompt.md +47 -47
  43. package/.github/prompts/oxe-checkpoint.prompt.md +47 -47
  44. package/.github/prompts/oxe-compact.prompt.md +46 -46
  45. package/.github/prompts/oxe-dashboard.prompt.md +47 -47
  46. package/.github/prompts/oxe-debug.prompt.md +47 -47
  47. package/.github/prompts/oxe-discuss.prompt.md +47 -47
  48. package/.github/prompts/oxe-execute.prompt.md +52 -50
  49. package/.github/prompts/oxe-forensics.prompt.md +47 -47
  50. package/.github/prompts/oxe-help.prompt.md +46 -46
  51. package/.github/prompts/oxe-loop.prompt.md +47 -47
  52. package/.github/prompts/oxe-milestone.prompt.md +47 -47
  53. package/.github/prompts/oxe-next.prompt.md +46 -46
  54. package/.github/prompts/oxe-obs.prompt.md +47 -47
  55. package/.github/prompts/oxe-plan-agent.prompt.md +46 -46
  56. package/.github/prompts/oxe-plan.prompt.md +49 -47
  57. package/.github/prompts/oxe-project.prompt.md +47 -47
  58. package/.github/prompts/oxe-quick.prompt.md +49 -47
  59. package/.github/prompts/oxe-research.prompt.md +47 -47
  60. package/.github/prompts/oxe-retro.prompt.md +47 -47
  61. package/.github/prompts/oxe-review-pr.prompt.md +47 -47
  62. package/.github/prompts/oxe-route.prompt.md +47 -47
  63. package/.github/prompts/oxe-scan.prompt.md +47 -47
  64. package/.github/prompts/oxe-security.prompt.md +47 -47
  65. package/.github/prompts/oxe-session.prompt.md +47 -47
  66. package/.github/prompts/oxe-ship.prompt.md +47 -47
  67. package/.github/prompts/oxe-skill.prompt.md +47 -47
  68. package/.github/prompts/oxe-spec.prompt.md +49 -47
  69. package/.github/prompts/oxe-ui-review.prompt.md +47 -47
  70. package/.github/prompts/oxe-ui-spec.prompt.md +47 -47
  71. package/.github/prompts/oxe-update.prompt.md +46 -46
  72. package/.github/prompts/oxe-validate-gaps.prompt.md +47 -47
  73. package/.github/prompts/oxe-verify-audit.prompt.md +1 -1
  74. package/.github/prompts/oxe-verify.prompt.md +50 -50
  75. package/.github/prompts/oxe-workflow-authoring.prompt.md +1 -1
  76. package/.github/prompts/oxe-workstream.prompt.md +47 -47
  77. package/.github/prompts/oxe.prompt.md +51 -49
  78. package/.github/workflows/ci.yml +26 -5
  79. package/.github/workflows/release.yml +15 -14
  80. package/AGENTS.md +15 -9
  81. package/CHANGELOG.md +1027 -10
  82. package/LICENSE +21 -21
  83. package/QUICKSTART.md +99 -99
  84. package/README.md +120 -17
  85. package/assets/readme-banner.svg +19 -19
  86. package/bin/banner.txt +5 -5
  87. package/bin/lib/oxe-acceptance-audit.cjs +195 -0
  88. package/bin/lib/oxe-adr.cjs +145 -0
  89. package/bin/lib/oxe-agent-install.cjs +31 -29
  90. package/bin/lib/oxe-alm-admin.cjs +215 -0
  91. package/bin/lib/oxe-alm-metrics.cjs +143 -0
  92. package/bin/lib/oxe-alm-prs.cjs +274 -0
  93. package/bin/lib/oxe-alm-refine.cjs +1003 -0
  94. package/bin/lib/oxe-alm.cjs +1289 -0
  95. package/bin/lib/oxe-anchor-copy.cjs +218 -0
  96. package/bin/lib/oxe-api-surface.cjs +96 -0
  97. package/bin/lib/oxe-artifact-refs.cjs +72 -0
  98. package/bin/lib/oxe-attention.cjs +97 -0
  99. package/bin/lib/oxe-autoresume.cjs +448 -0
  100. package/bin/lib/oxe-azure.cjs +1445 -1445
  101. package/bin/lib/oxe-budget.cjs +154 -0
  102. package/bin/lib/oxe-change-folder.cjs +130 -0
  103. package/bin/lib/oxe-change.cjs +389 -0
  104. package/bin/lib/oxe-channels.cjs +82 -0
  105. package/bin/lib/oxe-cited-paths.cjs +180 -0
  106. package/bin/lib/oxe-cli-errors.cjs +76 -0
  107. package/bin/lib/oxe-cli-output.cjs +111 -0
  108. package/bin/lib/oxe-commit-convention.cjs +104 -0
  109. package/bin/lib/oxe-complexity.cjs +106 -0
  110. package/bin/lib/oxe-console-decode.cjs +23 -0
  111. package/bin/lib/oxe-coordinator-queue.cjs +67 -0
  112. package/bin/lib/oxe-core-command-handlers.cjs +10 -8
  113. package/bin/lib/oxe-criteria-ids.cjs +87 -0
  114. package/bin/lib/oxe-criterion-coverage.cjs +93 -0
  115. package/bin/lib/oxe-cross-card-conflicts.cjs +639 -0
  116. package/bin/lib/oxe-customize.cjs +146 -0
  117. package/bin/lib/oxe-dashboard.cjs +1 -1
  118. package/bin/lib/oxe-decisions.cjs +211 -0
  119. package/bin/lib/oxe-deferred.cjs +80 -0
  120. package/bin/lib/oxe-deps-audit.cjs +136 -0
  121. package/bin/lib/oxe-diff-reviewer.cjs +105 -0
  122. package/bin/lib/oxe-dir-info.cjs +138 -0
  123. package/bin/lib/oxe-docs-check.cjs +124 -0
  124. package/bin/lib/oxe-docs-publish.cjs +81 -0
  125. package/bin/lib/oxe-dom-hooks.cjs +902 -0
  126. package/bin/lib/oxe-dossier.cjs +355 -0
  127. package/bin/lib/oxe-e2e-ready.cjs +360 -0
  128. package/bin/lib/oxe-env-sanitize.cjs +155 -0
  129. package/bin/lib/oxe-event-bus.cjs +118 -118
  130. package/bin/lib/oxe-failure-cost.cjs +144 -0
  131. package/bin/lib/oxe-file-size-guard.cjs +849 -0
  132. package/bin/lib/oxe-findings.cjs +86 -0
  133. package/bin/lib/oxe-grill-cases.cjs +148 -0
  134. package/bin/lib/oxe-grill.cjs +444 -0
  135. package/bin/lib/oxe-grooming.cjs +115 -0
  136. package/bin/lib/oxe-guard.cjs +180 -0
  137. package/bin/lib/oxe-handoff.cjs +97 -0
  138. package/bin/lib/oxe-install-resolve.cjs +28 -0
  139. package/bin/lib/oxe-integration-checks.cjs +285 -0
  140. package/bin/lib/oxe-intent-context.cjs +101 -0
  141. package/bin/lib/oxe-journey.cjs +403 -0
  142. package/bin/lib/oxe-known-failures.cjs +138 -0
  143. package/bin/lib/oxe-local-config.cjs +77 -0
  144. package/bin/lib/oxe-memory-kernel.cjs +190 -188
  145. package/bin/lib/oxe-merge-train.cjs +277 -0
  146. package/bin/lib/oxe-model-resolve.cjs +74 -0
  147. package/bin/lib/oxe-model-tiers.cjs +65 -0
  148. package/bin/lib/oxe-nfr.cjs +125 -0
  149. package/bin/lib/oxe-npm-version.cjs +1 -1
  150. package/bin/lib/oxe-open-defects.cjs +121 -0
  151. package/bin/lib/oxe-operational.cjs +14339 -1066
  152. package/bin/lib/oxe-origin-guard.cjs +102 -0
  153. package/bin/lib/oxe-origin.cjs +377 -0
  154. package/bin/lib/oxe-pack-removed.cjs +208 -0
  155. package/bin/lib/oxe-parallel-run.cjs +81 -0
  156. package/bin/lib/oxe-parallel.cjs +234 -0
  157. package/bin/lib/oxe-phase-extras.cjs +185 -0
  158. package/bin/lib/oxe-phase-gates.cjs +551 -0
  159. package/bin/lib/oxe-plan-build.cjs +1520 -0
  160. package/bin/lib/oxe-plan-json.cjs +1107 -0
  161. package/bin/lib/oxe-plan-merge.cjs +253 -0
  162. package/bin/lib/oxe-plan-mutate.cjs +214 -0
  163. package/bin/lib/oxe-plan-repair.cjs +479 -0
  164. package/bin/lib/oxe-plan-review.cjs +256 -0
  165. package/bin/lib/oxe-plan-skeleton.cjs +494 -0
  166. package/bin/lib/oxe-plan-staleness.cjs +125 -0
  167. package/bin/lib/oxe-plugin-cli.cjs +3 -1
  168. package/bin/lib/oxe-policy-rules.cjs +144 -0
  169. package/bin/lib/oxe-prd.cjs +129 -0
  170. package/bin/lib/oxe-preflight.cjs +378 -0
  171. package/bin/lib/oxe-process.cjs +11 -11
  172. package/bin/lib/oxe-program-members.cjs +97 -0
  173. package/bin/lib/oxe-program.cjs +245 -0
  174. package/bin/lib/oxe-progress-run.cjs +80 -0
  175. package/bin/lib/oxe-project-env.cjs +273 -0
  176. package/bin/lib/oxe-project-health.cjs +619 -41
  177. package/bin/lib/oxe-promote-helpers.cjs +1561 -0
  178. package/bin/lib/oxe-provider-antigravity.cjs +114 -0
  179. package/bin/lib/oxe-provider-grok.cjs +48 -0
  180. package/bin/lib/oxe-questions.cjs +115 -0
  181. package/bin/lib/oxe-quick.cjs +537 -0
  182. package/bin/lib/oxe-ratchets.cjs +132 -0
  183. package/bin/lib/oxe-rationality.cjs +587 -532
  184. package/bin/lib/oxe-real-regression.cjs +97 -0
  185. package/bin/lib/oxe-recovery.cjs +160 -0
  186. package/bin/lib/oxe-release-ops.cjs +325 -0
  187. package/bin/lib/oxe-release.cjs +622 -551
  188. package/bin/lib/oxe-repair.cjs +153 -0
  189. package/bin/lib/oxe-repo-map.cjs +136 -0
  190. package/bin/lib/oxe-repo-rules.cjs +121 -0
  191. package/bin/lib/oxe-research-provenance.cjs +96 -0
  192. package/bin/lib/oxe-resume.cjs +406 -0
  193. package/bin/lib/oxe-review.cjs +403 -0
  194. package/bin/lib/oxe-rfc.cjs +192 -0
  195. package/bin/lib/oxe-risk-decision.cjs +141 -0
  196. package/bin/lib/oxe-runtime-semantics.cjs +8 -1
  197. package/bin/lib/oxe-scorecard.cjs +234 -0
  198. package/bin/lib/oxe-scratch.cjs +81 -0
  199. package/bin/lib/oxe-seams.cjs +159 -0
  200. package/bin/lib/oxe-security.cjs +289 -289
  201. package/bin/lib/oxe-semver.cjs +83 -0
  202. package/bin/lib/oxe-ship-pr.cjs +204 -0
  203. package/bin/lib/oxe-signal.cjs +173 -0
  204. package/bin/lib/oxe-skill-loader.cjs +131 -131
  205. package/bin/lib/oxe-spec-check.cjs +217 -0
  206. package/bin/lib/oxe-spec-ears.cjs +98 -0
  207. package/bin/lib/oxe-spec-edit.cjs +411 -0
  208. package/bin/lib/oxe-spec-freeze.cjs +378 -0
  209. package/bin/lib/oxe-spec-probe.cjs +146 -0
  210. package/bin/lib/oxe-spec-stress.cjs +146 -0
  211. package/bin/lib/oxe-spike.cjs +98 -0
  212. package/bin/lib/oxe-state.cjs +87 -0
  213. package/bin/lib/oxe-stub-check.cjs +355 -0
  214. package/bin/lib/oxe-suite-impact.cjs +1145 -0
  215. package/bin/lib/oxe-sync.cjs +250 -0
  216. package/bin/lib/oxe-system-design.cjs +138 -0
  217. package/bin/lib/oxe-task-gates.cjs +139 -0
  218. package/bin/lib/oxe-telemetry.cjs +201 -0
  219. package/bin/lib/oxe-test-precheck.cjs +508 -0
  220. package/bin/lib/oxe-test-rigor.cjs +663 -0
  221. package/bin/lib/oxe-test-scope.cjs +883 -0
  222. package/bin/lib/oxe-trace.cjs +168 -0
  223. package/bin/lib/oxe-turns.cjs +64 -0
  224. package/bin/lib/oxe-ui-evidence.cjs +187 -0
  225. package/bin/lib/oxe-ui-verify.cjs +55 -0
  226. package/bin/lib/oxe-unsafe-commands.cjs +94 -0
  227. package/bin/lib/oxe-verdicts.cjs +131 -0
  228. package/bin/lib/oxe-verify-dryrun.cjs +541 -0
  229. package/bin/lib/oxe-verify-remote.cjs +208 -0
  230. package/bin/lib/oxe-vitest-batch.cjs +142 -0
  231. package/bin/lib/oxe-workflow-budget.cjs +99 -0
  232. package/bin/lib/oxe-workflow-eval.cjs +118 -0
  233. package/bin/lib/oxe-workflows.cjs +3 -1
  234. package/bin/lib/oxe-worktree-deps.cjs +241 -0
  235. package/bin/lib/oxe-worktree-gc.cjs +170 -0
  236. package/bin/oxe-cc.js +4934 -94
  237. package/commands/oxe/alm.md +54 -0
  238. package/commands/oxe/ask.md +55 -55
  239. package/commands/oxe/capabilities.md +50 -50
  240. package/commands/oxe/checkpoint.md +53 -53
  241. package/commands/oxe/compact.md +47 -47
  242. package/commands/oxe/dashboard.md +51 -51
  243. package/commands/oxe/debug.md +58 -58
  244. package/commands/oxe/discuss.md +58 -58
  245. package/commands/oxe/execute.md +63 -61
  246. package/commands/oxe/forensics.md +53 -53
  247. package/commands/oxe/help.md +48 -48
  248. package/commands/oxe/loop.md +54 -54
  249. package/commands/oxe/milestone.md +53 -53
  250. package/commands/oxe/next.md +49 -49
  251. package/commands/oxe/obs.md +53 -53
  252. package/commands/oxe/oxe.md +55 -53
  253. package/commands/oxe/plan-agent.md +57 -57
  254. package/commands/oxe/plan.md +59 -57
  255. package/commands/oxe/project.md +53 -53
  256. package/commands/oxe/quick.md +53 -53
  257. package/commands/oxe/research.md +53 -53
  258. package/commands/oxe/retro.md +53 -53
  259. package/commands/oxe/review-pr.md +53 -53
  260. package/commands/oxe/route.md +48 -48
  261. package/commands/oxe/scan.md +58 -58
  262. package/commands/oxe/security.md +53 -53
  263. package/commands/oxe/session.md +53 -53
  264. package/commands/oxe/ship.md +53 -53
  265. package/commands/oxe/skill.md +53 -53
  266. package/commands/oxe/spec.md +59 -56
  267. package/commands/oxe/ui-review.md +53 -53
  268. package/commands/oxe/ui-spec.md +53 -53
  269. package/commands/oxe/update.md +53 -53
  270. package/commands/oxe/validate-gaps.md +53 -53
  271. package/commands/oxe/verify-audit.md +50 -50
  272. package/commands/oxe/verify.md +60 -60
  273. package/commands/oxe/workflow-authoring.md +50 -50
  274. package/commands/oxe/workstream.md +53 -53
  275. package/docs/ADLC-COVERAGE.md +55 -0
  276. package/docs/CONTENT-MIGRATION-AUDIT.md +49 -49
  277. package/docs/HAPPY-PATH.md +106 -0
  278. package/docs/INCIDENT-PLAYBOOK.md +181 -181
  279. package/docs/RELEASE-READINESS.md +1 -0
  280. package/docs/ROLES.md +129 -129
  281. package/docs/TEAM-ADOPTION.md +153 -153
  282. package/docs/WALKTHROUGH.md +241 -241
  283. package/docs/adr/D-1-isolamento-read-only-e-sanitizacao-centralizada-de-env-vars.md +29 -0
  284. package/docs/adr/D-2-junction-segura-de-node-modules-condicionada-a-sha-256-de-pa.md +29 -0
  285. package/docs/adr/D-3-preflight-local-5s-impacto-estatico-e2e-e-leitura-explicita.md +29 -0
  286. package/docs/adr/D-4-governanca-de-release-unificada-retomada-idempotente-pos-rei.md +29 -0
  287. package/docs/adr/README.md +15 -0
  288. package/docs/cli-errors.md +20 -0
  289. package/docs/oxespace-1.5/BACKLOG.md +2056 -0
  290. package/docs/oxespace-1.5/HANDOFF-1.21.2.md +140 -0
  291. package/docs/oxevoice/BACKLOG.md +244 -0
  292. package/lib/runtime/compiler/graph-compiler.d.ts +15 -0
  293. package/lib/runtime/compiler/graph-compiler.js +49 -3
  294. package/lib/runtime/delivery/promotion-pipeline.d.ts +1 -0
  295. package/lib/runtime/delivery/promotion-pipeline.js +59 -2
  296. package/lib/runtime/events/catalog.d.ts +1 -1
  297. package/lib/runtime/events/catalog.js +29 -0
  298. package/lib/runtime/executor/action-tool-map.d.ts +3 -1
  299. package/lib/runtime/executor/action-tool-map.js +4 -1
  300. package/lib/runtime/executor/adapters/antigravity-cli.d.ts +103 -0
  301. package/lib/runtime/executor/adapters/antigravity-cli.js +530 -0
  302. package/lib/runtime/executor/adapters/claude-cli.d.ts +92 -0
  303. package/lib/runtime/executor/adapters/claude-cli.js +328 -0
  304. package/lib/runtime/executor/adapters/grok-cli.d.ts +89 -0
  305. package/lib/runtime/executor/adapters/grok-cli.js +351 -0
  306. package/lib/runtime/executor/adapters/http-openai.d.ts +9 -0
  307. package/lib/runtime/executor/adapters/http-openai.js +18 -0
  308. package/lib/runtime/executor/adapters/registry.d.ts +18 -0
  309. package/lib/runtime/executor/adapters/registry.js +49 -0
  310. package/lib/runtime/executor/adapters/types.d.ts +21 -0
  311. package/lib/runtime/executor/adapters/types.js +2 -0
  312. package/lib/runtime/executor/built-in-tools.d.ts +64 -0
  313. package/lib/runtime/executor/built-in-tools.js +257 -24
  314. package/lib/runtime/executor/index.d.ts +19 -2
  315. package/lib/runtime/executor/index.js +50 -1
  316. package/lib/runtime/executor/llm-task-executor.d.ts +108 -2
  317. package/lib/runtime/executor/llm-task-executor.js +598 -39
  318. package/lib/runtime/executor/node-context.d.ts +94 -0
  319. package/lib/runtime/executor/node-context.js +126 -0
  320. package/lib/runtime/executor/node-prompt-builder.d.ts +2 -0
  321. package/lib/runtime/executor/node-prompt-builder.js +4 -0
  322. package/lib/runtime/executor/quota-patterns.d.ts +7 -0
  323. package/lib/runtime/executor/quota-patterns.js +39 -0
  324. package/lib/runtime/executor/shell-argv.d.ts +41 -0
  325. package/lib/runtime/executor/shell-argv.js +144 -0
  326. package/lib/runtime/executor/stream-completion.d.ts +27 -0
  327. package/lib/runtime/executor/stream-completion.js +82 -5
  328. package/lib/runtime/index.d.ts +5 -2
  329. package/lib/runtime/index.js +10 -1
  330. package/lib/runtime/models/failure.d.ts +1 -1
  331. package/lib/runtime/models/run.d.ts +1 -1
  332. package/lib/runtime/program/index.d.ts +1 -0
  333. package/lib/runtime/program/index.js +17 -0
  334. package/lib/runtime/program/program-model.d.ts +92 -0
  335. package/lib/runtime/program/program-model.js +262 -0
  336. package/lib/runtime/projection/projection-engine.d.ts +16 -1
  337. package/lib/runtime/projection/projection-engine.js +55 -3
  338. package/lib/runtime/reducers/run-state-reducer.js +48 -5
  339. package/lib/runtime/scheduler/run-journal.d.ts +27 -1
  340. package/lib/runtime/scheduler/run-journal.js +40 -1
  341. package/lib/runtime/scheduler/scheduler.d.ts +239 -0
  342. package/lib/runtime/scheduler/scheduler.js +1157 -97
  343. package/lib/runtime/verification/contract-exports.d.ts +24 -0
  344. package/lib/runtime/verification/contract-exports.js +201 -0
  345. package/lib/runtime/verification/index.d.ts +1 -0
  346. package/lib/runtime/verification/index.js +1 -0
  347. package/lib/runtime/verification/runner-timeout.d.ts +7 -0
  348. package/lib/runtime/verification/runner-timeout.js +17 -0
  349. package/lib/runtime/verification/test-report-parsers.d.ts +38 -0
  350. package/lib/runtime/verification/test-report-parsers.js +188 -0
  351. package/lib/runtime/verification/verification-compiler.d.ts +101 -2
  352. package/lib/runtime/verification/verification-compiler.js +491 -82
  353. package/lib/runtime/verification/verification-manifest.d.ts +12 -0
  354. package/lib/runtime/verification/verification-manifest.js +33 -4
  355. package/lib/runtime/workspace/index.d.ts +2 -1
  356. package/lib/runtime/workspace/index.js +3 -1
  357. package/lib/runtime/workspace/strategies/ephemeral-container.d.ts +9 -0
  358. package/lib/runtime/workspace/strategies/ephemeral-container.js +37 -10
  359. package/lib/runtime/workspace/strategies/git-worktree.d.ts +24 -1
  360. package/lib/runtime/workspace/strategies/git-worktree.js +134 -1
  361. package/lib/sdk/README.md +21 -21
  362. package/lib/sdk/index.cjs +27 -9
  363. package/oxe/agents/oxe-assumptions-analyzer.md +136 -136
  364. package/oxe/agents/oxe-codebase-mapper.md +142 -142
  365. package/oxe/agents/oxe-debugger.md +145 -145
  366. package/oxe/agents/oxe-executor.md +139 -139
  367. package/oxe/agents/oxe-integration-checker.md +142 -142
  368. package/oxe/agents/oxe-plan-checker.md +143 -143
  369. package/oxe/agents/oxe-planner.md +151 -151
  370. package/oxe/agents/oxe-research-synthesizer.md +146 -146
  371. package/oxe/agents/oxe-researcher.md +163 -163
  372. package/oxe/agents/oxe-ui-auditor.md +151 -151
  373. package/oxe/agents/oxe-ui-checker.md +157 -157
  374. package/oxe/agents/oxe-ui-researcher.md +179 -179
  375. package/oxe/agents/oxe-validation-auditor.md +154 -154
  376. package/oxe/agents/oxe-verifier.md +132 -132
  377. package/oxe/migrations/config-migrations.json +15 -0
  378. package/oxe/personas/README.md +91 -91
  379. package/oxe/personas/architect.md +149 -149
  380. package/oxe/personas/db-specialist.md +149 -149
  381. package/oxe/personas/debugger.md +155 -155
  382. package/oxe/personas/executor.md +164 -164
  383. package/oxe/personas/planner.md +165 -165
  384. package/oxe/personas/researcher.md +148 -148
  385. package/oxe/personas/ui-specialist.md +164 -164
  386. package/oxe/personas/verifier.md +174 -174
  387. package/oxe/schemas/plan-agents.schema.json +122 -122
  388. package/oxe/schemas/plan.schema.json +101 -0
  389. package/oxe/schemas/role-plan.schema.json +50 -0
  390. package/oxe/schemas/swarm-run.schema.json +130 -130
  391. package/oxe/templates/ACTIVE-RUN.template.json +32 -32
  392. package/oxe/templates/CAPABILITIES.template.md +7 -7
  393. package/oxe/templates/CAPABILITY.template.md +45 -45
  394. package/oxe/templates/CHECKPOINT.template.md +37 -37
  395. package/oxe/templates/CHECKPOINTS.template.md +7 -7
  396. package/oxe/templates/CODEBASE-DELTA.template.md +33 -33
  397. package/oxe/templates/CONFIG.md +172 -0
  398. package/oxe/templates/DISCUSS.template.md +1 -0
  399. package/oxe/templates/DOCS_BROWNFIELD_LAYOUT.md +55 -55
  400. package/oxe/templates/FIXTURE-PACK.template.json +18 -18
  401. package/oxe/templates/FIXTURE-PACK.template.md +19 -19
  402. package/oxe/templates/GIT_HOOKS_OXE.md +52 -52
  403. package/oxe/templates/GLOSSARY.template.md +9 -0
  404. package/oxe/templates/HYPOTHESES.template.md +33 -33
  405. package/oxe/templates/IMPLEMENTATION-PACK.template.json +26 -26
  406. package/oxe/templates/IMPLEMENTATION-PACK.template.md +32 -32
  407. package/oxe/templates/INVESTIGATION.template.md +38 -38
  408. package/oxe/templates/LESSONS-METRICS.template.json +13 -13
  409. package/oxe/templates/LESSONS.template.md +43 -43
  410. package/oxe/templates/MEMORY.template.md +49 -49
  411. package/oxe/templates/MILESTONES.template.md +17 -17
  412. package/oxe/templates/NOTES.template.md +16 -16
  413. package/oxe/templates/OBSERVATIONS.template.md +18 -18
  414. package/oxe/templates/PLAN-REVIEW.template.md +31 -31
  415. package/oxe/templates/PLAN.template.md +87 -87
  416. package/oxe/templates/PRD.template.md +53 -0
  417. package/oxe/templates/REFERENCE-ANCHORS.template.md +30 -26
  418. package/oxe/templates/RESEARCH.template.md +8 -0
  419. package/oxe/templates/RESUME.template.md +49 -49
  420. package/oxe/templates/RFC.template.md +43 -0
  421. package/oxe/templates/ROADMAP.template.md +44 -44
  422. package/oxe/templates/SECURITY.template.md +72 -72
  423. package/oxe/templates/SESSION.template.md +34 -34
  424. package/oxe/templates/SKILL.template.md +26 -26
  425. package/oxe/templates/SPEC.template.md +65 -65
  426. package/oxe/templates/SUMMARY.template.md +50 -50
  427. package/oxe/templates/VISUAL-INPUTS.template.json +27 -27
  428. package/oxe/templates/VISUAL-INPUTS.template.md +36 -36
  429. package/oxe/templates/WORKFLOW_AUTHORING.md +93 -93
  430. package/oxe/templates/finding-rules.json +22 -0
  431. package/oxe/templates/plan-agent-messages-README.template.md +9 -9
  432. package/oxe/templates/plan-agents.template.json +30 -30
  433. package/oxe/templates/quick-agents.template.json +24 -24
  434. package/oxe/templates/stress-methods.md +33 -0
  435. package/oxe/workflows/agent-mode.md +150 -150
  436. package/oxe/workflows/alm.md +50 -0
  437. package/oxe/workflows/ask.md +96 -96
  438. package/oxe/workflows/capabilities.md +25 -25
  439. package/oxe/workflows/checkpoint.md +37 -37
  440. package/oxe/workflows/compact/plan.md +149 -0
  441. package/oxe/workflows/compact/spec.md +114 -0
  442. package/oxe/workflows/compact.md +1 -0
  443. package/oxe/workflows/conduct.md +149 -149
  444. package/oxe/workflows/dashboard.md +33 -33
  445. package/oxe/workflows/debug.md +9 -9
  446. package/oxe/workflows/discuss.md +15 -3
  447. package/oxe/workflows/distill.md +164 -164
  448. package/oxe/workflows/execute.md +30 -26
  449. package/oxe/workflows/forensics.md +5 -5
  450. package/oxe/workflows/help.md +10 -4
  451. package/oxe/workflows/lean/execute.md +42 -0
  452. package/oxe/workflows/lean/plan.md +60 -0
  453. package/oxe/workflows/lean/spec.md +61 -0
  454. package/oxe/workflows/loop.md +67 -67
  455. package/oxe/workflows/memory.md +163 -163
  456. package/oxe/workflows/milestone.md +95 -95
  457. package/oxe/workflows/next.md +10 -8
  458. package/oxe/workflows/obs.md +167 -167
  459. package/oxe/workflows/oxe.md +33 -14
  460. package/oxe/workflows/plan-agent.md +143 -143
  461. package/oxe/workflows/plan.md +49 -40
  462. package/oxe/workflows/project.md +55 -55
  463. package/oxe/workflows/quick.md +19 -5
  464. package/oxe/workflows/references/adaptive-discovery.md +27 -27
  465. package/oxe/workflows/references/alm-refine.md +55 -0
  466. package/oxe/workflows/references/azure-in-plan.md +5 -0
  467. package/oxe/workflows/references/change-management.md +48 -0
  468. package/oxe/workflows/references/grill.md +74 -0
  469. package/oxe/workflows/references/legacy-brownfield.md +136 -136
  470. package/oxe/workflows/references/next-step-footer.md +33 -0
  471. package/oxe/workflows/references/plan-agent-chat-protocol.md +99 -99
  472. package/oxe/workflows/references/plan-json-acceptance-program.md +174 -0
  473. package/oxe/workflows/references/product-docs-alm.md +51 -0
  474. package/oxe/workflows/references/reasoning-discovery.md +28 -28
  475. package/oxe/workflows/references/reasoning-execution.md +29 -29
  476. package/oxe/workflows/references/reasoning-planning.md +32 -32
  477. package/oxe/workflows/references/reasoning-review.md +29 -29
  478. package/oxe/workflows/references/reasoning-status.md +24 -24
  479. package/oxe/workflows/references/robustness-elevation.md +295 -295
  480. package/oxe/workflows/references/session-path-resolution.md +71 -71
  481. package/oxe/workflows/references/workflow-runtime-contracts.json +1167 -1151
  482. package/oxe/workflows/research.md +1 -0
  483. package/oxe/workflows/retro.md +117 -117
  484. package/oxe/workflows/review-pr.md +53 -53
  485. package/oxe/workflows/route.md +1 -1
  486. package/oxe/workflows/scan.md +356 -355
  487. package/oxe/workflows/security.md +67 -67
  488. package/oxe/workflows/session.md +213 -213
  489. package/oxe/workflows/ship.md +74 -125
  490. package/oxe/workflows/size-budget.json +62 -0
  491. package/oxe/workflows/skill.md +44 -44
  492. package/oxe/workflows/spec.md +92 -93
  493. package/oxe/workflows/swarm/board.md +119 -119
  494. package/oxe/workflows/swarm/scout.md +170 -170
  495. package/oxe/workflows/swarm-mode.md +280 -280
  496. package/oxe/workflows/ui-review.md +5 -5
  497. package/oxe/workflows/ui-spec.md +7 -7
  498. package/oxe/workflows/update.md +35 -35
  499. package/oxe/workflows/validate-gaps.md +45 -45
  500. package/oxe/workflows/verify-audit.md +73 -73
  501. package/oxe/workflows/verify.md +35 -14
  502. package/oxe/workflows/workflow-authoring.md +34 -34
  503. package/oxe/workflows/workstream.md +97 -97
  504. package/package.json +8 -3
  505. package/packages/runtime/package.json +1 -1
  506. package/packages/runtime/src/audit/audit-trail.ts +243 -243
  507. package/packages/runtime/src/audit/index.ts +2 -2
  508. package/packages/runtime/src/audit/policy-pack.ts +62 -62
  509. package/packages/runtime/src/compiler/graph-compiler.ts +67 -3
  510. package/packages/runtime/src/compiler/index.ts +1 -1
  511. package/packages/runtime/src/context/context-pack-store.ts +197 -197
  512. package/packages/runtime/src/context/context-profiles.ts +60 -60
  513. package/packages/runtime/src/context/index.ts +3 -3
  514. package/packages/runtime/src/decision/decision-engine.ts +174 -174
  515. package/packages/runtime/src/decision/decision-memo.ts +211 -211
  516. package/packages/runtime/src/decision/index.ts +2 -2
  517. package/packages/runtime/src/delivery/branch-manager.ts +91 -91
  518. package/packages/runtime/src/delivery/ci-checks.ts +285 -285
  519. package/packages/runtime/src/delivery/delivery-records.ts +75 -75
  520. package/packages/runtime/src/delivery/index.ts +5 -5
  521. package/packages/runtime/src/delivery/pr-manager.ts +112 -112
  522. package/packages/runtime/src/delivery/promotion-pipeline.ts +65 -2
  523. package/packages/runtime/src/events/bus.ts +92 -92
  524. package/packages/runtime/src/events/catalog.ts +29 -0
  525. package/packages/runtime/src/events/envelope.ts +14 -14
  526. package/packages/runtime/src/events/index.ts +3 -3
  527. package/packages/runtime/src/evidence/evidence-store.ts +130 -130
  528. package/packages/runtime/src/evidence/index.ts +1 -1
  529. package/packages/runtime/src/executor/action-tool-map.ts +52 -50
  530. package/packages/runtime/src/executor/adapters/antigravity-cli.ts +619 -0
  531. package/packages/runtime/src/executor/adapters/claude-cli.ts +367 -0
  532. package/packages/runtime/src/executor/adapters/grok-cli.ts +392 -0
  533. package/packages/runtime/src/executor/adapters/http-openai.ts +16 -0
  534. package/packages/runtime/src/executor/adapters/registry.ts +53 -0
  535. package/packages/runtime/src/executor/adapters/types.ts +24 -0
  536. package/packages/runtime/src/executor/built-in-tools.ts +525 -305
  537. package/packages/runtime/src/executor/index.ts +23 -6
  538. package/packages/runtime/src/executor/llm-task-executor.ts +854 -236
  539. package/packages/runtime/src/executor/node-context.ts +226 -0
  540. package/packages/runtime/src/executor/node-prompt-builder.ts +69 -62
  541. package/packages/runtime/src/executor/quota-patterns.ts +41 -0
  542. package/packages/runtime/src/executor/shell-argv.ts +144 -0
  543. package/packages/runtime/src/executor/stream-completion.ts +230 -145
  544. package/packages/runtime/src/gate/gate-manager.ts +289 -289
  545. package/packages/runtime/src/gate/index.ts +1 -1
  546. package/packages/runtime/src/index.ts +12 -0
  547. package/packages/runtime/src/models/attempt.ts +19 -19
  548. package/packages/runtime/src/models/evidence.ts +21 -21
  549. package/packages/runtime/src/models/failure.ts +22 -13
  550. package/packages/runtime/src/models/gate-decision.ts +25 -25
  551. package/packages/runtime/src/models/index.ts +8 -8
  552. package/packages/runtime/src/models/run.ts +1 -0
  553. package/packages/runtime/src/models/session.ts +11 -11
  554. package/packages/runtime/src/models/verification-result.ts +10 -10
  555. package/packages/runtime/src/models/work-item.ts +25 -25
  556. package/packages/runtime/src/models/workspace.ts +31 -31
  557. package/packages/runtime/src/plugins/capability-matrix.ts +126 -126
  558. package/packages/runtime/src/plugins/index.ts +5 -5
  559. package/packages/runtime/src/plugins/plugin-manifest.ts +118 -118
  560. package/packages/runtime/src/policy/index.ts +1 -1
  561. package/packages/runtime/src/policy/policy-engine.ts +330 -330
  562. package/packages/runtime/src/program/index.ts +1 -0
  563. package/packages/runtime/src/program/program-model.ts +293 -0
  564. package/packages/runtime/src/projection/index.ts +1 -1
  565. package/packages/runtime/src/projection/projection-engine.ts +61 -3
  566. package/packages/runtime/src/reducers/debug-reducer.ts +36 -36
  567. package/packages/runtime/src/reducers/index.ts +2 -2
  568. package/packages/runtime/src/reducers/run-state-reducer.ts +44 -5
  569. package/packages/runtime/src/scheduler/agent-registry.ts +132 -132
  570. package/packages/runtime/src/scheduler/agent-roles.ts +109 -109
  571. package/packages/runtime/src/scheduler/index.ts +4 -4
  572. package/packages/runtime/src/scheduler/run-journal.ts +47 -2
  573. package/packages/runtime/src/scheduler/scheduler.ts +1242 -99
  574. package/packages/runtime/src/verification/contract-exports.ts +203 -0
  575. package/packages/runtime/src/verification/index.ts +1 -0
  576. package/packages/runtime/src/verification/runner-timeout.ts +17 -0
  577. package/packages/runtime/src/verification/test-report-parsers.ts +204 -0
  578. package/packages/runtime/src/verification/verification-compiler.ts +508 -40
  579. package/packages/runtime/src/verification/verification-manifest.ts +44 -4
  580. package/packages/runtime/src/workspace/index.ts +2 -1
  581. package/packages/runtime/src/workspace/strategies/ephemeral-container.ts +44 -11
  582. package/packages/runtime/src/workspace/strategies/git-worktree.ts +104 -1
  583. package/packages/runtime/src/workspace/strategies/inplace.ts +38 -38
  584. package/packages/runtime/src/workspace/workspace-manager.ts +16 -16
  585. package/vscode-extension/LICENSE +21 -21
  586. package/vscode-extension/package.json +1 -1
  587. package/vscode-extension/src/shared/contextLoader.js +137 -137
  588. package/vscode-extension/src/shared/contractBuilder.js +159 -159
  589. package/vscode-extension/src/shared/stateReader.js +101 -101
  590. package/docs/oxe-artifact-map.html +0 -1172
@@ -4,7 +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;
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;
18
+ exports.describeVerifyFailure = describeVerifyFailure;
19
+ exports.verifyFailureSignature = verifyFailureSignature;
7
20
  const path_1 = __importDefault(require("path"));
21
+ const quota_patterns_1 = require("../executor/quota-patterns");
8
22
  const fs_1 = __importDefault(require("fs"));
9
23
  const bus_1 = require("../events/bus");
10
24
  const policy_engine_1 = require("../policy/policy-engine");
@@ -13,6 +27,30 @@ const run_journal_1 = require("./run-journal");
13
27
  const decision_memo_1 = require("../decision/decision-memo");
14
28
  const capability_adapter_1 = require("../plugins/capability-adapter");
15
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
+ }
16
54
  class Scheduler {
17
55
  constructor() {
18
56
  this.cancelled = false;
@@ -21,10 +59,17 @@ class Scheduler {
21
59
  this.ctx = null;
22
60
  this.runStartMs = 0;
23
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();
24
64
  }
25
65
  recordProgress() {
26
66
  this.lastProgressMs = Date.now();
27
67
  }
68
+ withIntegrationLock(fn) {
69
+ const run = this.integrationChain.then(fn, fn);
70
+ this.integrationChain = run.catch(() => undefined);
71
+ return run;
72
+ }
28
73
  async executeRollback(plan, ctx) {
29
74
  try {
30
75
  switch (plan.strategy) {
@@ -94,18 +139,20 @@ class Scheduler {
94
139
  });
95
140
  const maxRunMs = ctx.options?.maxRunDurationMs ?? 30 * 60000;
96
141
  const staleMs = ctx.options?.staleProgressMs ?? 5 * 60000;
97
- 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) {
98
147
  if (this.cancelled)
99
148
  break;
100
149
  // Global run timeout
101
150
  if (Date.now() - this.runStartMs > maxRunMs) {
102
- this.emit(ctx, { type: 'RunAborted', payload: { reason: 'global_timeout' } });
103
- return { run_id: ctx.runId, status: 'aborted', completed: [], failed: [], blocked: [], reason: 'global_timeout' };
151
+ return this.abortRun(ctx, 'global_timeout', completed, failed, blocked);
104
152
  }
105
153
  // Stale progress timeout (no task completed in staleMs)
106
154
  if (Date.now() - this.lastProgressMs > staleMs) {
107
- this.emit(ctx, { type: 'RunAborted', payload: { reason: 'no_progress_timeout' } });
108
- return { run_id: ctx.runId, status: 'aborted', completed: [], failed: [], blocked: [], reason: 'no_progress_timeout' };
155
+ return this.abortRun(ctx, 'no_progress_timeout', completed, failed, blocked);
109
156
  }
110
157
  // Respect pause: persist journal and return paused result
111
158
  if (this.paused) {
@@ -122,13 +169,36 @@ class Scheduler {
122
169
  });
123
170
  return { run_id: ctx.runId, status: 'paused', completed, failed, blocked, pending_gates: this.journal.pending_gates.slice() };
124
171
  }
125
- 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
+ }
126
196
  // Sync journal after each wave
127
197
  this.journal.completed_work_items = completed.slice();
128
198
  this.journal.failed_work_items = failed.slice();
129
199
  this.journal.blocked_work_items = blocked.slice();
130
200
  (0, run_journal_1.saveJournal)(ctx.projectRoot, ctx.runId, this.journal);
131
- if (waveFailed) {
201
+ if (waveFailed && !deferMode) {
132
202
  // Execute rollback plan if one was created for this run
133
203
  const memos = (0, decision_memo_1.listMemos)(ctx.projectRoot, ctx.runId);
134
204
  for (const memo of memos) {
@@ -140,9 +210,10 @@ class Scheduler {
140
210
  break;
141
211
  }
142
212
  }
143
- // 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)
144
215
  for (const [id, s] of status) {
145
- if (s === 'pending') {
216
+ if (s === 'pending' && !this.paused) {
146
217
  status.set(id, 'blocked');
147
218
  blocked.push(id);
148
219
  this.emit(ctx, {
@@ -154,11 +225,13 @@ class Scheduler {
154
225
  }
155
226
  const finalStatus = this.cancelled
156
227
  ? 'cancelled'
157
- : failed.length > 0
158
- ? 'failed'
159
- : blocked.length > 0
160
- ? 'blocked'
161
- : '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';
162
235
  this.emit(ctx, {
163
236
  type: 'RunCompleted',
164
237
  payload: { run_id: ctx.runId, status: finalStatus },
@@ -173,7 +246,11 @@ class Scheduler {
173
246
  pending_gates: this.journal.pending_gates.slice(),
174
247
  },
175
248
  });
176
- this.journal.scheduler_state = this.cancelled ? 'cancelled' : finalStatus === 'blocked' ? 'blocked' : 'completed';
249
+ this.journal.scheduler_state = this.cancelled
250
+ ? 'cancelled'
251
+ : finalStatus === 'blocked' || finalStatus === 'failed'
252
+ ? finalStatus
253
+ : 'completed';
177
254
  this.journal.completed_work_items = completed.slice();
178
255
  this.journal.failed_work_items = failed.slice();
179
256
  this.journal.blocked_work_items = blocked.slice();
@@ -193,7 +270,9 @@ class Scheduler {
193
270
  */
194
271
  async recover(runId, ctx, graph) {
195
272
  const journal = (0, run_journal_1.loadJournal)(ctx.projectRoot, runId);
196
- if (!journal || journal.scheduler_state !== 'paused')
273
+ // Paused, blocked (gates since approved), aborted (timeout) and failed runs can all be resumed;
274
+ // only completed/cancelled runs have nothing left to do.
275
+ if (!journal || !RECOVERABLE_JOURNAL_STATES.has(journal.scheduler_state))
197
276
  return null;
198
277
  // Restore state from journal
199
278
  this.cancelled = false;
@@ -249,7 +328,7 @@ class Scheduler {
249
328
  break;
250
329
  }
251
330
  for (const [id, s] of status) {
252
- if (s === 'pending') {
331
+ if (s === 'pending' && !this.paused) {
253
332
  status.set(id, 'blocked');
254
333
  blocked.push(id);
255
334
  this.emit(ctx, {
@@ -280,7 +359,11 @@ class Scheduler {
280
359
  pending_gates: this.journal.pending_gates.slice(),
281
360
  },
282
361
  });
283
- this.journal.scheduler_state = this.cancelled ? 'cancelled' : finalStatus === 'blocked' ? 'blocked' : 'completed';
362
+ this.journal.scheduler_state = this.cancelled
363
+ ? 'cancelled'
364
+ : finalStatus === 'blocked' || finalStatus === 'failed'
365
+ ? finalStatus
366
+ : 'completed';
284
367
  this.journal.completed_work_items = completed.slice();
285
368
  this.journal.failed_work_items = failed.slice();
286
369
  this.journal.blocked_work_items = blocked.slice();
@@ -299,6 +382,10 @@ class Scheduler {
299
382
  const node = graph.nodes.get(nodeId);
300
383
  if (node.mutation_scope.length > 0)
301
384
  return false;
385
+ // A node that may write files but declares no scope is not provably safe to run in parallel
386
+ // (an empty scope used to mean "run everything in parallel, in place").
387
+ if (nodeMayMutate(node))
388
+ return false;
302
389
  const primaryAction = pickPrimaryAction(node, ctx.pluginRegistry);
303
390
  if (!primaryAction)
304
391
  return true;
@@ -306,43 +393,199 @@ class Scheduler {
306
393
  return provider?.idempotent ?? true;
307
394
  }
308
395
  async runWave(nodeIds, graph, ctx, status, completed, failed, blocked) {
309
- const eligible = [];
310
- const depsNotMet = [];
311
- for (const id of nodeIds) {
312
- if (status.get(id) === 'completed')
313
- continue; // already done in recovery
314
- const node = graph.nodes.get(id);
315
- const depsMet = node.depends_on.every((dep) => status.get(dep) === 'completed');
316
- if (depsMet) {
317
- 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);
318
437
  }
319
438
  else {
320
- 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
+ }
321
445
  }
322
446
  }
323
- for (const id of depsNotMet) {
324
- status.set(id, 'blocked');
325
- blocked.push(id);
326
- this.emit(ctx, {
327
- type: 'WorkItemBlocked',
328
- work_item_id: id,
329
- payload: { reason: 'dependency_not_met' },
330
- });
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);
453
+ this.emit(ctx, {
454
+ type: 'WorkItemBlocked',
455
+ work_item_id: id,
456
+ payload: { reason: 'dependency_not_met' },
457
+ });
458
+ }
331
459
  }
332
- const readOnly = eligible.filter((id) => this.isConcurrentSafe(id, graph, ctx));
333
- const mutations = eligible.filter((id) => !readOnly.includes(id));
334
- if (readOnly.length > 0) {
335
- 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
+ }
336
538
  }
337
- for (const id of mutations) {
338
- 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));
339
555
  break;
340
- 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));
341
584
  }
342
- return failed.length > 0;
343
585
  }
344
- async runNode(nodeId, graph, ctx, status, completed, failed, blocked) {
586
+ async runNode(nodeId, graph, ctx, status, completed, failed, blocked, mode = {}) {
345
587
  const node = graph.nodes.get(nodeId);
588
+ const parallelNode = Boolean(mode.parallel && ctx.parallel);
346
589
  status.set(nodeId, 'running');
347
590
  this.emit(ctx, {
348
591
  type: 'WorkItemReady',
@@ -350,21 +593,66 @@ class Scheduler {
350
593
  payload: { title: node.title, wave: node.wave },
351
594
  });
352
595
  let lease = null;
596
+ // Dispose through the manager that allocated the lease (plugin provider or default).
597
+ let leaseManager = null;
353
598
  let lastResult = null;
354
599
  let lastError = null;
355
- const maxAttempts = node.policy.max_retries + 1;
600
+ // 1.20c: the same verify failure twice (normalized output) = suspect ruler or stuck executor: stop paying retries.
601
+ let lastVerifySignature = null;
602
+ let verifySuspect = false;
603
+ let maxAttempts = node.policy.max_retries + 1;
604
+ let policyRetried = Boolean(ctx.options?.policyRefusedBefore?.includes(nodeId));
605
+ // 1.21.1 (OXB-047): work that arrives by another path never pays an agent and never becomes a human gate.
606
+ // An explicit human gate (PLAN.json `gate`) still comes first: the attempt loop requests it as before.
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
+ }
613
+ if (!humanGatePending && (node.policy.verify_only || (node.policy.external_dependency?.length ?? 0) > 0)) {
614
+ await this.runExternalNode(node, ctx, status, completed, failed, blocked);
615
+ return;
616
+ }
356
617
  const quotaBlocked = this.consumeQuotaForNode(ctx, node);
357
618
  if (quotaBlocked) {
358
619
  this.blockNode(nodeId, ctx, status, blocked, 'quota_exceeded', quotaBlocked);
359
620
  return;
360
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;
361
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;
362
649
  const attemptId = `${nodeId}-a${attempt}`;
650
+ const attemptModel = ctx.modelFor ? ctx.modelFor(nodeId, attempt, attempt > 1 ? (lastResult?.failure_class ?? null) : null) : null;
363
651
  this.emit(ctx, {
364
652
  type: 'AttemptStarted',
365
653
  work_item_id: nodeId,
366
654
  attempt_id: attemptId,
367
- payload: { attempt_number: attempt },
655
+ payload: { attempt_number: attempt, ...(attemptModel ? { model: attemptModel.model, tier: attemptModel.tier, escalated: Boolean(attemptModel.escalated) } : {}) },
368
656
  });
369
657
  try {
370
658
  const policyDecision = this.evaluatePolicyForNode(node, ctx);
@@ -391,18 +679,36 @@ class Scheduler {
391
679
  payload: { ...policyDecision },
392
680
  });
393
681
  }
394
- if (policyDecision?.gate_required || node.policy.requires_human_approval) {
682
+ if ((policyDecision?.gate_required || node.policy.requires_human_approval) && !this.hasApprovedGate(node, ctx)) {
395
683
  const gateId = await this.requestGateForNode(node, ctx, policyDecision);
396
684
  this.blockNode(nodeId, ctx, status, blocked, 'pending_gate', gateId);
397
685
  return;
398
686
  }
687
+ // OXB-023: the run's turn/cost ceiling is checked before every attempt, never in the middle of one.
688
+ const budgetReason = ctx.budget?.exhausted() ?? null;
689
+ if (budgetReason) {
690
+ this.emit(ctx, {
691
+ type: 'BudgetExhausted',
692
+ work_item_id: nodeId,
693
+ attempt_id: attemptId,
694
+ payload: { reason: budgetReason, attempt_number: attempt },
695
+ });
696
+ this.blockNode(nodeId, ctx, status, blocked, 'budget_exhausted', budgetReason);
697
+ return;
698
+ }
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);
399
702
  const wsReq = {
400
703
  work_item_id: nodeId,
401
704
  attempt_number: attempt,
402
705
  strategy: node.workspace_strategy,
403
706
  mutation_scope: node.mutation_scope,
404
707
  };
405
- 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;
711
+ leaseManager = workspaceManager;
406
712
  lease = await workspaceManager.allocate(wsReq);
407
713
  this.emit(ctx, {
408
714
  type: 'WorkspaceAllocated',
@@ -410,23 +716,154 @@ class Scheduler {
410
716
  attempt_id: attemptId,
411
717
  payload: { workspace_id: lease.workspace_id, strategy: lease.strategy },
412
718
  });
413
- lastResult = await this.executeNode(node, lease, ctx, attempt, attemptId, { previousError: lastError });
414
- if (lastResult.success) {
719
+ lastResult = await this.executeNode(node, lease, ctx, attempt, attemptId, {
720
+ previousError: withAttemptChanges(lastError, attempt > 1 && ctx.attemptChanges ? ctx.attemptChanges(nodeId) : null),
721
+ ...(attemptModel && attemptModel.model ? { model: attemptModel.model } : {}),
722
+ ...(turnsLeft != null ? { maxTurns: turnsLeft } : {}),
723
+ });
724
+ // OXB-026: the verify judges the work, not the end of the LLM conversation. An attempt that ran out of turns
725
+ // after writing in its scope is verified before it is classified: green completes the task, red goes to the
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';
729
+ const turnLimitWithWork = !lastResult.success
730
+ && (lastResult.completed_by === 'turn_limit_exhausted' || contextCap)
731
+ && Boolean(node.verify?.command)
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 || '');
735
+ if (lastResult.success || turnLimitWithWork) {
415
736
  const verifyResult = await this.verifyNode(node, lease, ctx, attemptId, attempt);
416
737
  if (verifyResult && verifyResult.status === 'failed') {
738
+ // Informed retry: the next attempt sees the command, the reason and the output — not just "failed".
417
739
  lastResult = {
418
740
  success: false,
419
- 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',
420
743
  evidence: lastResult.evidence,
421
- output: `Verification failed: ${(verifyResult.gaps || []).join('; ') || 'checks did not pass'}`,
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 } : {}),
422
747
  };
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);
780
+ if (signature && signature === lastVerifySignature) {
781
+ verifySuspect = true;
782
+ this.emit(ctx, {
783
+ type: 'VerifyCommandSuspect',
784
+ work_item_id: nodeId,
785
+ attempt_id: attemptId,
786
+ payload: {
787
+ attempt_number: attempt,
788
+ command: node.verify.command,
789
+ excerpt: tailLines(`${verifyResult.check?.error ?? ''}\n${verifyResult.check?.stderr ?? ''}\n${verifyResult.check?.stdout ?? ''}`, 12),
790
+ reason: 'identical_verify_failure',
791
+ },
792
+ });
793
+ break;
794
+ }
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 };
423
856
  }
424
857
  else {
425
858
  this.emit(ctx, {
426
859
  type: 'WorkItemCompleted',
427
860
  work_item_id: nodeId,
428
861
  attempt_id: attemptId,
429
- payload: { attempt_number: attempt, evidence: lastResult.evidence },
862
+ payload: {
863
+ attempt_number: attempt,
864
+ evidence: lastResult.evidence,
865
+ ...(turnLimitWithWork ? { completed_by: 'verify_after_turn_limit' } : {}),
866
+ },
430
867
  });
431
868
  status.set(nodeId, 'completed');
432
869
  completed.push(nodeId);
@@ -435,9 +872,116 @@ class Scheduler {
435
872
  }
436
873
  }
437
874
  lastError = lastResult.output || (lastResult.failure_class ?? 'unknown error');
438
- 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')
439
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
+ }
440
981
  if (attempt < maxAttempts) {
982
+ // a pause: no retry quota spent, no RetryScheduled banner (R34)
983
+ if (holdForPause(attempt + 1))
984
+ return;
441
985
  const retryBlocked = this.consumeRetryQuota(ctx);
442
986
  if (retryBlocked) {
443
987
  this.blockNode(nodeId, ctx, status, blocked, 'quota_exceeded', retryBlocked);
@@ -449,7 +993,7 @@ class Scheduler {
449
993
  this.emit(ctx, {
450
994
  type: 'RetryScheduled',
451
995
  work_item_id: nodeId,
452
- payload: { next_attempt: attempt + 1, reason: lastResult.failure_class, backoff_ms: backoffMs },
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 } : {}) },
453
997
  });
454
998
  }
455
999
  }
@@ -475,25 +1019,60 @@ class Scheduler {
475
1019
  this.emit(ctx, {
476
1020
  type: 'RetryScheduled',
477
1021
  work_item_id: nodeId,
478
- payload: { next_attempt: attempt + 1, reason: 'env', backoff_ms: backoffMs },
1022
+ payload: { next_attempt: attempt + 1, reason: 'env', backoff_ms: backoffMs, output_tail: tailLines(lastResult.output || '', 60) },
479
1023
  });
480
1024
  }
481
1025
  }
482
1026
  finally {
483
1027
  if (lease) {
484
- await ctx.workspaceManager.dispose(lease.workspace_id).catch((e) => this.emit(ctx, { type: 'WorkspaceDisposeFailed', payload: { workspace_id: lease?.workspace_id, error: String(e) } }));
1028
+ await (leaseManager ?? ctx.workspaceManager).dispose(lease.workspace_id).catch((e) => this.emit(ctx, { type: 'WorkspaceDisposeFailed', payload: { workspace_id: lease?.workspace_id, error: String(e) } }));
485
1029
  lease = null;
1030
+ leaseManager = null;
486
1031
  }
487
1032
  }
488
1033
  }
489
1034
  this.emit(ctx, {
490
1035
  type: 'WorkItemBlocked',
491
1036
  work_item_id: nodeId,
492
- payload: { failure_class: lastResult?.failure_class ?? 'env', max_attempts: maxAttempts },
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 } : {}) },
493
1038
  });
494
1039
  status.set(nodeId, 'failed');
495
1040
  failed.push(nodeId);
496
1041
  }
1042
+ /** Abort keeps the progress made so far: an aborted run is recoverable, not a blank slate. */
1043
+ abortRun(ctx, reason, completed, failed, blocked) {
1044
+ this.emit(ctx, { type: 'RunAborted', payload: { reason, completed: completed.slice(), failed: failed.slice(), blocked: blocked.slice() } });
1045
+ if (this.journal) {
1046
+ this.journal.scheduler_state = 'aborted';
1047
+ this.journal.completed_work_items = completed.slice();
1048
+ this.journal.failed_work_items = failed.slice();
1049
+ this.journal.blocked_work_items = blocked.slice();
1050
+ this.journal.partial_result = { run_id: ctx.runId, completed, failed, blocked };
1051
+ (0, run_journal_1.saveJournal)(ctx.projectRoot, ctx.runId, this.journal);
1052
+ }
1053
+ return { run_id: ctx.runId, status: 'aborted', completed, failed, blocked, reason };
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
+ }
497
1076
  pause() {
498
1077
  this.paused = true;
499
1078
  if (this.journal && this.ctx) {
@@ -596,48 +1175,146 @@ class Scheduler {
596
1175
  work_item_id: node.id,
597
1176
  payload: { command: node.verify.command, attempt_number: attempt },
598
1177
  });
599
- const suite = {
600
- checks: [{
601
- id: `inline-${node.id}`,
602
- type: 'custom',
603
- command: node.verify.command,
604
- evidence_type_expected: 'stdout',
605
- acceptance_ref: null,
606
- description: `Verify ${node.id}`,
607
- }],
608
- compiled_at: new Date().toISOString(),
609
- spec_hash: '',
610
- plan_hash: '',
611
- };
612
- let result;
613
- try {
614
- result = await (0, verification_compiler_1.verifyRun)({
615
- suite,
616
- cwd: lease.root_path,
617
- timeoutMs: ctx.options?.verifyTimeoutMs ?? 60000,
618
- runId: ctx.runId,
619
- workItemId: node.id,
620
- attemptNumber: attempt,
621
- projectRoot: ctx.projectRoot,
622
- pluginRegistry: ctx.pluginRegistry,
623
- });
624
- }
625
- catch (err) {
626
- this.emit(ctx, {
627
- type: 'VerificationCompleted',
628
- work_item_id: node.id,
629
- attempt_id: attemptId,
630
- payload: { status: 'error', error: String(err) },
631
- });
632
- 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;
633
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
+ }));
634
1300
  this.emit(ctx, {
635
1301
  type: 'VerificationCompleted',
636
1302
  work_item_id: node.id,
637
1303
  attempt_id: attemptId,
638
- payload: { status: result.status },
1304
+ payload: {
1305
+ status,
1306
+ ...(failedSegment ? { failed_segment: failedSegment } : {}),
1307
+ ...(failedSegments.length > 1 ? { failed_segments: failedSegments } : {}),
1308
+ },
639
1309
  });
640
- return result;
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
+ };
641
1318
  }
642
1319
  evaluatePolicyForNode(node, ctx) {
643
1320
  if (!ctx.policyEngine)
@@ -668,6 +1345,14 @@ class Scheduler {
668
1345
  (0, policy_engine_1.savePolicyDecision)(ctx.projectRoot, persisted);
669
1346
  return persisted;
670
1347
  }
1348
+ /** An approval already granted for this node in this run must not be requested again on re-execution. */
1349
+ hasApprovedGate(node, ctx) {
1350
+ if (!ctx.gateManager)
1351
+ return false;
1352
+ return ctx.gateManager
1353
+ .listResolved()
1354
+ .some((gate) => gate.work_item_id === node.id && gate.decision === 'approved' && (gate.run_id == null || gate.run_id === ctx.runId));
1355
+ }
671
1356
  async requestGateForNode(node, ctx, decision) {
672
1357
  if (!ctx.gateManager) {
673
1358
  console.warn('[scheduler] ctx.gateManager not configured — gates will not be persisted');
@@ -681,8 +1366,8 @@ class Scheduler {
681
1366
  action: primaryAction?.type ?? 'custom',
682
1367
  description: `Gate required before executing ${node.id}`,
683
1368
  evidence_refs: [],
684
- risks: [decision?.reason ?? 'human approval required'],
685
- rationale: decision?.reason ?? 'node policy requires approval',
1369
+ risks: [decision?.reason ?? node.policy.gate_reason ?? 'human approval required'],
1370
+ rationale: decision?.reason ?? node.policy.gate_reason ?? 'node policy requires approval',
686
1371
  policy_decision_id: decision?.decision_id ?? null,
687
1372
  });
688
1373
  if (this.journal && !this.journal.pending_gates.includes(gate.gate_id)) {
@@ -695,6 +1380,39 @@ class Scheduler {
695
1380
  });
696
1381
  return gate.gate_id;
697
1382
  }
1383
+ /**
1384
+ * A node delivered by another path (`verify_only`) or waiting on external work (`external_dependency`): no agent.
1385
+ * verify_only runs only the node's verify — green completes it; red (or no verify) leaves it waiting. A node with an
1386
+ * external dependency and no verify_only waits without a gate, so the rest of the run (and the next preflight) goes on.
1387
+ */
1388
+ async runExternalNode(node, ctx, status, completed, failed, blocked) {
1389
+ const deps = node.policy.external_dependency ?? [];
1390
+ if (node.policy.verify_only && node.verify?.command) {
1391
+ const attemptId = `${node.id}-verify-only`;
1392
+ const workspaceManager = ctx.pluginRegistry?.workspaceProviderFor(node.workspace_strategy) ?? ctx.workspaceManager;
1393
+ const lease = await workspaceManager.allocate({ work_item_id: node.id, attempt_number: 1, strategy: node.workspace_strategy, mutation_scope: node.mutation_scope });
1394
+ try {
1395
+ const verdict = await this.verifyNode(node, lease, ctx, attemptId, 1);
1396
+ if (verdict && verdict.status !== 'failed') {
1397
+ this.emit(ctx, {
1398
+ type: 'WorkItemCompleted',
1399
+ work_item_id: node.id,
1400
+ attempt_id: attemptId,
1401
+ payload: { attempt_number: 1, evidence: [], completed_by: 'verify_only', external_dependency: deps },
1402
+ });
1403
+ status.set(node.id, 'completed');
1404
+ completed.push(node.id);
1405
+ this.recordProgress();
1406
+ return;
1407
+ }
1408
+ }
1409
+ finally {
1410
+ await workspaceManager.dispose(lease.workspace_id).catch(() => undefined);
1411
+ }
1412
+ }
1413
+ this.blockNode(node.id, ctx, status, blocked, 'external_dependency', deps.length ? deps.join(', ') : 'verify_only: entrega externa ainda não verificada');
1414
+ void failed;
1415
+ }
698
1416
  blockNode(nodeId, ctx, status, blocked, reason, detail = null) {
699
1417
  this.emit(ctx, {
700
1418
  type: 'WorkItemBlocked',
@@ -732,6 +1450,11 @@ class Scheduler {
732
1450
  }
733
1451
  }
734
1452
  exports.Scheduler = Scheduler;
1453
+ const RECOVERABLE_JOURNAL_STATES = new Set(['paused', 'interrupted', 'blocked', 'aborted', 'failed']);
1454
+ /** Nodes whose actions may write to the workspace (anything beyond reading and collecting evidence). */
1455
+ function nodeMayMutate(node) {
1456
+ return node.actions.some((action) => action.type !== 'read_code' && action.type !== 'collect_evidence');
1457
+ }
735
1458
  function inferSideEffectClass(node) {
736
1459
  if (node.mutation_scope.length > 0)
737
1460
  return 'write_fs';
@@ -755,3 +1478,340 @@ function inferGateScope(node) {
755
1478
  return 'security';
756
1479
  return 'plan_approval';
757
1480
  }
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/;
1646
+ function tailLines(text, 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 };
1691
+ }
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
+ }
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).
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
+ : [];
1795
+ return [
1796
+ 'Verification failed after your previous attempt.',
1797
+ `Command: ${command ?? '(none)'}`,
1798
+ ...failingLine,
1799
+ `Reason: ${reason}`,
1800
+ output ? `Output (last lines):\n${output.slice(-4000)}` : 'Output: (empty)',
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.',
1802
+ ].join('\n');
1803
+ }
1804
+ /** Normalized failure fingerprint: timings, timestamps, hashes and temp paths removed. */
1805
+ function verifyFailureSignature(check) {
1806
+ if (!check)
1807
+ return null;
1808
+ const raw = `${check.error ?? ''}\n${check.stderr ?? ''}\n${check.stdout ?? ''}`;
1809
+ const normalized = raw
1810
+ .replace(/\d{4}-\d{2}-\d{2}T[\d:.]+Z?/g, '<ts>')
1811
+ .replace(/\b\d+(\.\d+)?\s?(ms|s)\b/g, '<t>')
1812
+ .replace(/\b[0-9a-f]{7,64}\b/gi, '<hash>')
1813
+ .replace(/[A-Za-z]:\\[^\s'"]*|\/tmp\/[^\s'"]*/g, '<path>')
1814
+ .replace(/\s+/g, ' ')
1815
+ .trim();
1816
+ return normalized ? normalized.slice(-1200) : null;
1817
+ }