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
@@ -0,0 +1,1107 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * OXE 1.19 — PLAN.json canônico + `plan lint`.
5
+ *
6
+ * O PLAN.md parseado por heurística foi a origem da maioria das correções dos benchmarks
7
+ * (escopo `# linkly`, `Comando:` múltiplo, `Arquivos alvo`). Com o PLAN.json ao lado do PLAN.md,
8
+ * o runtime lê dados estruturados; o markdown vira fallback com aviso.
9
+ *
10
+ * Validação sem dependência nova, seguindo `oxe/schemas/plan.schema.json`.
11
+ */
12
+
13
+ const fs = require('fs');
14
+ const path = require('path');
15
+
16
+ const TASK_ID_RE = /^T\d+$/;
17
+ // 1.21.2 (OXB-037): A<n>, subcriteria A<n>.<m> and global criteria G<n>.
18
+ const ACCEPT_RE = require('./oxe-criteria-ids.cjs').CRITERION_ID_RE;
19
+ // OXB-112: D-<n>, D-<fase>-<n> (D-F2-3) and D-SPIKE-<Tn>
20
+ const DECISION_RE = require('./oxe-decisions.cjs').DECISION_ID_RE;
21
+ const COMPLEXITY = new Set(['XS', 'S', 'M', 'L', 'XL']);
22
+
23
+
24
+ /** OXB-085: preconditions a task waits on before starting (PLAN.json `blocked_by` objects). */
25
+ const PRECONDITION_KINDS = { pr: ['merged', 'closed'], commit: ['on_branch'], file: ['exists'] };
26
+
27
+ function preconditionProblem(entry) {
28
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) return 'texto ("owner/repo#123") ou { kind: "pr"|"commit"|"file", ref, until? }';
29
+ if (!PRECONDITION_KINDS[entry.kind]) return `kind "${entry.kind}" desconhecido — use pr, commit ou file`;
30
+ if (typeof entry.ref !== 'string' || !entry.ref.trim()) return `${entry.kind}: ref obrigatório (ex.: ${entry.kind === 'pr' ? '"#686"' : entry.kind === 'commit' ? '"a1b2c3d"' : '"src/x.ts"'})`;
31
+ if (entry.until != null && !PRECONDITION_KINDS[entry.kind].includes(entry.until)) return `${entry.kind}: until "${entry.until}" inválido — use ${PRECONDITION_KINDS[entry.kind].join(' | ')}`;
32
+ if (entry.branch != null && (entry.kind !== 'commit' || typeof entry.branch !== 'string')) return 'branch só vale para kind "commit" (texto)';
33
+ return null;
34
+ }
35
+
36
+ function preconditionLabel(p) {
37
+ if (p.kind === 'pr') return `${p.ref} (${p.until === 'closed' ? 'PR fechado' : 'PR mergeado'})`;
38
+ if (p.kind === 'commit') return `commit ${p.ref.slice(0, 12)} em ${p.branch || 'origin/main'}`;
39
+ return `arquivo ${p.ref}`;
40
+ }
41
+
42
+ /** String entries of `blocked_by`: work delivered by another path (the task is externally delivered). */
43
+ function externalRefs(task) {
44
+ return (Array.isArray(task && task.blocked_by) ? task.blocked_by : []).filter((e) => typeof e === 'string' && e.trim()).map((e) => e.trim());
45
+ }
46
+
47
+ /** Object entries of `blocked_by`, normalized, with a label for the status ("aguardando #686 (PR mergeado)"). */
48
+ function taskPreconditions(task) {
49
+ return (Array.isArray(task && task.blocked_by) ? task.blocked_by : [])
50
+ .filter((e) => e && typeof e === 'object' && !Array.isArray(e) && !preconditionProblem(e))
51
+ .map((e) => {
52
+ const p = { kind: e.kind, ref: e.ref.trim(), until: e.until || PRECONDITION_KINDS[e.kind][0], ...(e.branch ? { branch: e.branch } : {}) };
53
+ return { ...p, label: preconditionLabel(p) };
54
+ });
55
+ }
56
+
57
+ function planJsonPathFor(planMdPath) {
58
+ return planMdPath ? path.join(path.dirname(planMdPath), 'PLAN.json') : null;
59
+ }
60
+
61
+ function isStringArray(value, re) {
62
+ return Array.isArray(value) && value.every((v) => typeof v === 'string' && v.trim() && (!re || re.test(v)));
63
+ }
64
+
65
+ /** Erros de schema (lista vazia = válido). Mensagens com o caminho JSON do problema. */
66
+ function validatePlanJson(doc) {
67
+ const errors = [];
68
+ if (!doc || typeof doc !== 'object' || Array.isArray(doc)) return ['$: PLAN.json deve ser um objeto'];
69
+ if (doc.schema_version !== 1) errors.push('$.schema_version: deve ser 1');
70
+ if (doc.phase != null && !(typeof doc.phase === 'string' && /^F\d+$/.test(doc.phase))) errors.push('$.phase: deve ser "F<n>" ou null');
71
+ if (!Array.isArray(doc.tasks) || doc.tasks.length === 0) {
72
+ errors.push('$.tasks: deve ser uma lista com ao menos 1 tarefa');
73
+ return errors;
74
+ }
75
+ doc.tasks.forEach((task, i) => {
76
+ const at = `$.tasks[${i}]`;
77
+ if (!task || typeof task !== 'object') {
78
+ errors.push(`${at}: deve ser objeto`);
79
+ return;
80
+ }
81
+ if (typeof task.id !== 'string' || !TASK_ID_RE.test(task.id)) errors.push(`${at}.id: deve casar ^T\\d+$`);
82
+ if (typeof task.title !== 'string' || !task.title.trim()) errors.push(`${at}.title: obrigatório`);
83
+ if (!Number.isInteger(task.wave) || task.wave < 1) errors.push(`${at}.wave: inteiro ≥ 1`);
84
+ if (task.depends_on != null && !isStringArray(task.depends_on, TASK_ID_RE)) errors.push(`${at}.depends_on: lista de ids T<n>`);
85
+ if (task.files != null && !isStringArray(task.files)) errors.push(`${at}.files: lista de caminhos`);
86
+ if (task.edited_paths != null && !isStringArray(task.edited_paths)) errors.push(`${at}.edited_paths: lista de caminhos`);
87
+ if (task.gates != null && !isStringArray(task.gates)) errors.push(`${at}.gates: lista de comandos de gate`);
88
+ // OXB-086: name the offending value — FRONTEND's prose criteria failed with only "lista de A<n>".
89
+ if (task.acceptance != null) {
90
+ if (!Array.isArray(task.acceptance)) errors.push(`${at}.acceptance: lista de ids A<n> (ex.: ["A12"]), não ${typeof task.acceptance === 'string' ? `o texto "${task.acceptance.slice(0, 60)}"` : typeof task.acceptance}`);
91
+ else {
92
+ const bad = task.acceptance.filter((v) => typeof v !== 'string' || !ACCEPT_RE.test(v));
93
+ if (bad.length) errors.push(`${at}.acceptance: ${bad.map((v) => JSON.stringify(typeof v === 'string' ? v.slice(0, 60) : v)).join(', ')} não ${bad.length > 1 ? 'são ids' : 'é id'} A<n> — critérios são ids A da SPEC; a prosa vai em "notes"`);
94
+ }
95
+ }
96
+ if (task.decisions != null && !isStringArray(task.decisions, DECISION_RE)) errors.push(`${at}.decisions: lista de D-<n> / D-<fase>-<n>`);
97
+ if (task.complexity != null && !COMPLEXITY.has(task.complexity)) errors.push(`${at}.complexity: XS|S|M|L|XL`);
98
+ if (task.done != null && typeof task.done !== 'boolean') errors.push(`${at}.done: boolean`);
99
+ if (task.status != null && !['pending', 'in_progress', 'done', 'blocked'].includes(task.status)) errors.push(`${at}.status: pending | in_progress | done | blocked`);
100
+ if (task.started_at != null && typeof task.started_at !== 'string') errors.push(`${at}.started_at: data ISO`);
101
+ if (task.base_sha != null && typeof task.base_sha !== 'string') errors.push(`${at}.base_sha: sha git`);
102
+ if (task.executor != null && typeof task.executor !== 'string') errors.push(`${at}.executor: texto`);
103
+ if (task.done_at != null && typeof task.done_at !== 'string') errors.push(`${at}.done_at: data ISO`);
104
+ if (task.done_commit != null && typeof task.done_commit !== 'string') errors.push(`${at}.done_commit: sha do checkpoint`);
105
+ if (task.reopened != null && !Array.isArray(task.reopened)) errors.push(`${at}.reopened: histórico de reaberturas`);
106
+ if (task.commit != null && (typeof task.commit !== 'string' || !task.commit.trim())) errors.push(`${at}.commit: mensagem do checkpoint`);
107
+ // OXB-106: add | remove | move | test-only | config-only are declarative code kinds with their own pack rule.
108
+ if (task.kind != null && !['code', 'spike', 'verify_only', 'external_delivery', 'add', 'remove', 'move', 'test-only', 'config-only'].includes(task.kind)) errors.push(`${at}.kind: code | spike | verify_only | external_delivery | add | remove | move | test-only | config-only`);
109
+ if (task.question != null && typeof task.question !== 'string') errors.push(`${at}.question: texto`);
110
+ if (task.gate != null && (typeof task.gate !== 'object' || Array.isArray(task.gate) || typeof task.gate.reason !== 'string')) errors.push(`${at}.gate: { kind?, reason }`);
111
+ // OXB-085: an entry is a string (work delivered by another path, e.g. "owner/repo#594") or a precondition object
112
+ // { kind: "pr"|"commit"|"file", ref, until? } the task waits on before it starts (it is still this plan's work).
113
+ if (task.blocked_by != null) {
114
+ if (!Array.isArray(task.blocked_by)) errors.push(`${at}.blocked_by: lista de dependências externas`);
115
+ else task.blocked_by.forEach((entry, k) => {
116
+ if (typeof entry === 'string') { if (!entry.trim()) errors.push(`${at}.blocked_by[${k}]: texto vazio`); return; }
117
+ const problem = preconditionProblem(entry);
118
+ if (problem) errors.push(`${at}.blocked_by[${k}]: ${problem}`);
119
+ });
120
+ }
121
+ if (task.verify != null) {
122
+ if (typeof task.verify !== 'object' || Array.isArray(task.verify)) errors.push(`${at}.verify: objeto`);
123
+ else if (task.verify.commands != null && !isStringArray(task.verify.commands)) errors.push(`${at}.verify.commands: lista de comandos`);
124
+ }
125
+ });
126
+ if (doc.acceptance_tests != null) {
127
+ if (!Array.isArray(doc.acceptance_tests)) errors.push('$.acceptance_tests: lista');
128
+ else doc.acceptance_tests.forEach((entry, i) => {
129
+ const at = `$.acceptance_tests[${i}]`;
130
+ if (!entry || typeof entry !== 'object') return errors.push(`${at}: deve ser objeto`);
131
+ const hasId = typeof entry.id === 'string' && /^[A-Za-z][\w-]*$/.test(entry.id);
132
+ if (entry.id != null && !hasId) errors.push(`${at}.id: identificador (ex.: "CR-03" ou "lint-voice")`);
133
+ if (entry.criterion != null && (typeof entry.criterion !== 'string' || !ACCEPT_RE.test(entry.criterion))) errors.push(`${at}.criterion: A<n>`);
134
+ // Sem critério só para prova transversal (ex.: CR constraint): precisa de id próprio e resolves.
135
+ if (entry.criterion == null && !(hasId && Array.isArray(entry.resolves) && entry.resolves.length)) errors.push(`${at}.criterion: A<n> (ou "id" + "resolves" para uma prova transversal)`);
136
+ if (!isStringArray(entry.files) || entry.files.length === 0) errors.push(`${at}.files: lista com ao menos 1 caminho`);
137
+ if (typeof entry.command !== 'string' || !entry.command.trim()) errors.push(`${at}.command: obrigatório`);
138
+ if (entry.proves != null && !isStringArray(entry.proves)) errors.push(`${at}.proves: lista de nomes de teste${entry.proves && typeof entry.proves === 'object' && !Array.isArray(entry.proves) ? ' — o formato { arquivo: [títulos] } é de plano por papel: junte com oxe-cc plan merge' : ''}`);
139
+ if (entry.rigor != null && entry.rigor !== 'source-assertion') errors.push(`${at}.rigor: só "source-assertion"`);
140
+ if (entry.rigor === 'source-assertion' && !(typeof entry.rigor_reason === 'string' && entry.rigor_reason.trim().length >= 8)) errors.push(`${at}.rigor_reason: diga por que este teste afirma sobre o texto do código`);
141
+ if (entry.resolves != null && !isStringArray(entry.resolves, require('./oxe-criteria-ids.cjs').CR_ID_RE)) errors.push(`${at}.resolves: lista de CR-NN (ou CR-<fase>-N)`);
142
+ if (entry.version != null && !(Number.isInteger(entry.version) && entry.version >= 1)) errors.push(`${at}.version: inteiro ≥ 1`);
143
+ if (entry.sha256 != null && (typeof entry.sha256 !== 'string' || !/^[0-9a-f]{64}$/i.test(entry.sha256))) errors.push(`${at}.sha256: sha256 hex (64 chars)`);
144
+ if (entry.hashes != null) {
145
+ if (typeof entry.hashes !== 'object' || Array.isArray(entry.hashes)) errors.push(`${at}.hashes: objeto { [path]: sha256 }`);
146
+ else {
147
+ for (const [hp, hv] of Object.entries(entry.hashes)) {
148
+ if (typeof hv !== 'string' || !/^[0-9a-f]{64}$/i.test(hv)) errors.push(`${at}.hashes[${JSON.stringify(hp)}]: sha256 hex (64 chars)`);
149
+ }
150
+ }
151
+ }
152
+ if (entry.amended != null && !Array.isArray(entry.amended)) errors.push(`${at}.amended: histórico de emendas`);
153
+ });
154
+ }
155
+ if (doc.budget != null) {
156
+ const b = doc.budget;
157
+ if (typeof b !== 'object' || Array.isArray(b)) errors.push('$.budget: { turns?, usd?, max_retries? }');
158
+ else {
159
+ if (b.turns != null && !(Number.isInteger(b.turns) && b.turns > 0)) errors.push('$.budget.turns: inteiro > 0');
160
+ if (b.usd != null && !(typeof b.usd === 'number' && b.usd > 0)) errors.push('$.budget.usd: número > 0');
161
+ if (b.max_retries != null && !(Number.isInteger(b.max_retries) && b.max_retries >= 0)) errors.push('$.budget.max_retries: inteiro ≥ 0');
162
+ }
163
+ }
164
+ if (doc.phase_gates != null) {
165
+ if (!Array.isArray(doc.phase_gates)) errors.push('$.phase_gates: lista');
166
+ else doc.phase_gates.forEach((gate, i) => {
167
+ const at = `$.phase_gates[${i}]`;
168
+ if (!gate || typeof gate !== 'object' || Array.isArray(gate)) return errors.push(`${at}: deve ser objeto`);
169
+ if (typeof gate.id !== 'string' || !/^[A-Za-z][\w-]*$/.test(gate.id)) errors.push(`${at}.id: identificador (ex.: "typecheck")`);
170
+ if (gate.kind != null && !['command', 'ci'].includes(gate.kind)) errors.push(`${at}.kind: command | ci`);
171
+ if (gate.kind !== 'ci' && (typeof gate.command !== 'string' || !gate.command.trim())) errors.push(`${at}.command: obrigatório (exceto kind: ci)`);
172
+ if (gate.when != null && !['phase_verify', 'program_close'].includes(gate.when)) errors.push(`${at}.when: phase_verify | program_close`);
173
+ if (gate.runner != null && (typeof gate.runner !== 'string' || !gate.runner.includes('{command}'))) errors.push(`${at}.runner: modelo com {command}`);
174
+ if (gate.timeout_ms != null && !(Number.isInteger(gate.timeout_ms) && gate.timeout_ms > 0)) errors.push(`${at}.timeout_ms: inteiro > 0`);
175
+ });
176
+ }
177
+ return errors;
178
+ }
179
+
180
+ /**
181
+ * OXB-073: test titles a JS/TS test file declares (`it`/`test` with a literal title, any `.only/.skip/.each` chain).
182
+ * Template literals with `${…}` are skipped (their title is only known at run time).
183
+ */
184
+ /**
185
+ * OXB-150: JUnit tests in Kotlin/Java are methods, not string literals: `@Test fun name()`, `@Test fun \`spaced name\`()`,
186
+ * `@Test void name()` (any modifiers, other annotations in between), with `@DisplayName("…")` when present. F10's
187
+ * AttnUsageTest.kt was read as ONE test named "Notice" (a string literal in the body).
188
+ */
189
+ function blankCodeComments(text) {
190
+ const s = String(text || '');
191
+ let out = '';
192
+ for (let i = 0; i < s.length; i += 1) {
193
+ const ch = s[i];
194
+ if (ch === '"' || ch === "'" || ch === '`') {
195
+ let j = i + 1;
196
+ for (; j < s.length && s[j] !== ch; j += 1) if (s[j] === '\\') j += 1;
197
+ out += s.slice(i, j + 1);
198
+ i = j;
199
+ } else if (ch === '/' && s[i + 1] === '/') {
200
+ let j = s.indexOf('\n', i);
201
+ if (j < 0) j = s.length;
202
+ out += ' '.repeat(j - i);
203
+ i = j - 1;
204
+ } else if (ch === '/' && s[i + 1] === '*') {
205
+ let j = s.indexOf('*/', i + 2);
206
+ j = j < 0 ? s.length : j + 2;
207
+ out += s.slice(i, j).replace(/[^\n]/g, ' ');
208
+ i = j - 1;
209
+ } else out += ch;
210
+ }
211
+ return out;
212
+ }
213
+
214
+ function declaredJvmTestTitles(text) {
215
+ const out = [];
216
+ const src = blankCodeComments(text);
217
+ const re = /@(?:Test|ParameterizedTest|RepeatedTest|TestFactory)\b(?:\([^)]*\))?((?:\s*@[\w.]+(?:\((?:[^()"]|"(?:\\.|[^"\\])*")*\))?)*)\s*(?:(?:public|private|protected|internal|open|override|final|suspend|static)\s+)*(?:fun\s+(?:`([^`]+)`|([A-Za-z_$][\w$]*))|(?:[\w<>[\],.?]+\s+)?([A-Za-z_$][\w$]*)\s*\()/g;
218
+ for (const m of src.matchAll(re)) {
219
+ const name = m[2] || m[3] || m[4];
220
+ if (name) out.push(name);
221
+ const display = /@DisplayName\(\s*"((?:\\.|[^"\\])*)"\s*\)/.exec(m[1] || '');
222
+ if (display) out.push(display[1].replace(/\\(.)/g, '$1'));
223
+ }
224
+ // @DisplayName written before @Test
225
+ for (const m of src.matchAll(/@DisplayName\(\s*"((?:\\.|[^"\\])*)"\s*\)\s*@(?:Test|ParameterizedTest)\b/g)) out.push(m[1].replace(/\\(.)/g, '$1'));
226
+ return [...new Set(out)];
227
+ }
228
+
229
+ /**
230
+ * OXB-190: `test.each(table)('title %s', …)` / `it.each` / `describe.each` (and the tagged-template form). Each yields
231
+ * the template, its literal part (placeholders %s %d %i %j %o %p %# and $var removed, so a prove can name "the title"
232
+ * without the case), and — when the table is a literal array of strings/numbers — every expanded name.
233
+ */
234
+ function eachTestTitles(text) {
235
+ return eachTestGroups(text).flatMap((g) => g.titles);
236
+ }
237
+
238
+ /** OXB-C28-3: each it/test/describe.each call with its position and kind (a full test name needs the describe chain). */
239
+ function eachTestGroups(text) {
240
+ const groups = [];
241
+ const src = blankCodeComments(text);
242
+ const re = /\b(it|test|describe)(?:\.(?:only|skip|concurrent))?\.each\s*/g;
243
+ let m;
244
+ while ((m = re.exec(src))) {
245
+ const out = [];
246
+ groups.push({ at: m.index, kind: m[1], titles: out });
247
+ let i = m.index + m[0].length;
248
+ let table = null;
249
+ if (src[i] === '(') {
250
+ let depth = 0;
251
+ let j = i;
252
+ let quote = null;
253
+ for (; j < src.length; j += 1) {
254
+ const c = src[j];
255
+ if (quote) { if (c === '\\') { j += 1; continue; } if (c === quote) quote = null; continue; }
256
+ if (c === '"' || c === "'" || c === '`') { quote = c; continue; }
257
+ if (c === '(' || c === '[' || c === '{') depth += 1;
258
+ else if (c === ')' || c === ']' || c === '}') { depth -= 1; if (depth === 0) break; }
259
+ }
260
+ table = src.slice(i + 1, j);
261
+ i = j + 1;
262
+ } else if (src[i] === '`') {
263
+ const end = src.indexOf('`', i + 1);
264
+ if (end < 0) continue;
265
+ i = end + 1;
266
+ } else continue;
267
+ const t = /^\s*\(\s*(['"`])((?:\\.|(?!\1)[^\\])*)\1/.exec(src.slice(i));
268
+ if (!t) continue;
269
+ const template = t[2].replace(/\\(['"`\\])/g, '$1');
270
+ out.push(template);
271
+ const literal = template.replace(/%[sdifjop#%]|\$[A-Za-z_][\w.]*/g, ' ').replace(/\(\s*\)|\[\s*\]/g, ' ').replace(/\s+/g, ' ').trim();
272
+ if (literal && literal !== template) out.push(literal);
273
+ // a literal table: [['en'], ['pt-BR']] or ['en', 'pt-BR'] → the expanded names
274
+ let rows = null;
275
+ try { rows = JSON.parse(String(table || '').trim().replace(/'((?:\\.|[^'\\])*)'/g, (_, s) => JSON.stringify(s.replace(/\\'/g, "'")))); } catch { rows = null; }
276
+ if (Array.isArray(rows)) {
277
+ for (const row of rows.slice(0, 50)) {
278
+ const args = Array.isArray(row) ? row : [row];
279
+ if (!args.every((a) => ['string', 'number', 'boolean'].includes(typeof a))) continue;
280
+ let k = 0;
281
+ out.push(template.replace(/%[sdifjop]/g, () => String(args[k++])).replace(/%#/g, String(rows.indexOf(row))));
282
+ }
283
+ }
284
+ }
285
+ return groups.filter((g) => g.titles.length);
286
+ }
287
+
288
+ function declaredTestTitles(text, file, opts = {}) {
289
+ if (file && /\.(kt|kts|java|groovy|scala)$/i.test(String(file))) return declaredJvmTestTitles(text);
290
+ const src = blankCodeComments(text);
291
+ const out = eachTestTitles(src);
292
+ const re = /\b(?:it|test)(?!\.(?:describe|suite|step|beforeEach|afterEach|beforeAll|afterAll|before|after|use|info|expect|extend|setTimeout|configure)\b)(?:\.\w+)*\s*\(\s*(['"`])((?:\\.|(?!\1)[^\\])*)\1/g;
293
+ for (const m of src.matchAll(re)) {
294
+ if (m[1] === '`' && m[2].includes('${')) continue;
295
+ out.push(m[2].replace(/\\(['"`\\])/g, '$1'));
296
+ }
297
+ // OXB-C21 #3: `plan lint` proves may name a describe()/suite() title (aligned with `alm refine lint`), but only when
298
+ // asked: spec freeze builds `proves` from the it/test titles alone (a suite title is not a test that runs).
299
+ if (!opts.includeSuites) return out;
300
+ const suiteRe = /\b(?:(?:it|test)\.)?(?:describe|suite)(?:\.(?:only|skip|concurrent|sequential|serial|parallel))*\s*\(\s*(['"`])((?:\\.|(?!\1)[^\\])*)\1/g;
301
+ for (const m of src.matchAll(suiteRe)) {
302
+ if (m[1] === '`' && m[2].includes('${')) continue;
303
+ out.push(m[2].replace(/\\(['"`\\])/g, '$1'));
304
+ }
305
+ return out;
306
+ }
307
+
308
+ /**
309
+ * OxeSpace 15/11 (R34): the criteria only `plan task supersede` tasks held (their `superseded.acceptance`), that no other
310
+ * task of the plan covers — exempt from coverage in plan lint, verify and trace, like a standing criterion.
311
+ */
312
+ function supersededCriteria(doc) {
313
+ const tasks = (doc && Array.isArray(doc.tasks) ? doc.tasks : []).filter(Boolean);
314
+ const held = new Set(tasks.filter((t) => !t.superseded).flatMap((t) => [...(t.acceptance || []), ...(t.aceite || [])]));
315
+ return [...new Set(tasks.filter((t) => t.superseded).flatMap((t) => (t.superseded.acceptance || [])))].filter((a) => !held.has(a));
316
+ }
317
+
318
+ /** PLAN.json → mesmo formato de `sdk.parsePlan` (o graph compiler e o verify não mudam). */
319
+ function planJsonToParsedPlan(doc) {
320
+ const spikeLib = require('./oxe-spike.cjs');
321
+ // OxeSpace 15/11 (Celular F4): T14's checkpoint failed (its work stayed uncommitted in the tree); T15, independent in
322
+ // the plan but sharing PairingFlow.kt, ran on top of it and the hunks became inseparable. A pending task whose files
323
+ // overlap a task with UNCOMMITTED work (checkpoint_failed, not done) waits for that commit — no paid attempt.
324
+ const normF = (f) => String(typeof f === 'string' ? f : (f && f.path) || '').replace(/\\/g, '/').replace(/^\.\//, '');
325
+ // an empty_checkpoint that left nothing in the tree (no leftover) holds no edits to wait on (cross-review 15/11)
326
+ const uncommitted = (doc.tasks || []).filter((t) => t && t.done !== true && t.status !== 'done' && t.checkpoint_failed
327
+ && !(t.checkpoint_failed.kind === 'empty_checkpoint' && !(Array.isArray(t.checkpoint_failed.leftover) && t.checkpoint_failed.leftover.length)));
328
+ // a directory in either scope covers the files under it (`app/pairing` × `app/pairing/PairingFlow.kt`)
329
+ const under = (a, b) => a === b || b.startsWith(`${a.replace(/\/+$/, '')}/`);
330
+ const sharedWait = (task) => {
331
+ if (!task || task.done === true || task.checkpoint_failed) return [];
332
+ const mine = [...new Set((task.files || []).map(normF).filter((f) => f && !f.includes('*')))];
333
+ const out = [];
334
+ for (const u of uncommitted) {
335
+ if (u.id === task.id) continue;
336
+ const shared = (u.files || []).map(normF).filter((f) => f && !f.includes('*') && mine.some((m) => under(m, f) || under(f, m)));
337
+ if (shared.length) out.push(`waiting_shared_files: ${u.id} (${shared.slice(0, 3).join(', ')}${shared.length > 3 ? ', …' : ''}) — commit ${u.id} first (runtime commit-task ${u.id}, or --together)`);
338
+ }
339
+ return out;
340
+ };
341
+ const scopeInsufficientFor = (task) => {
342
+ if (!task || !task.checkpoint_failed || task.checkpoint_failed.kind !== 'scope_insufficient') return [];
343
+ const reds = Array.isArray(task.checkpoint_failed.related_red) ? task.checkpoint_failed.related_red.map(normF).filter(Boolean) : [];
344
+ if (!reds.length) return ['scope_insufficient: (verifique o escopo)'];
345
+ const mine = (task.files || []).map(normF).filter(Boolean);
346
+ const unresolved = reds.filter((r) => !mine.some((m) => under(m, r)));
347
+ return unresolved.length ? [`scope_insufficient: ${unresolved.join(', ')}`] : [];
348
+ };
349
+ const tasks = doc.tasks.map((task) => {
350
+ const commands = task.verify && Array.isArray(task.verify.commands) ? task.verify.commands.map((c) => c.trim()).filter(Boolean) : [];
351
+ // OXB-007: a spike writes only its report and is verified by it (question, answer, evidence).
352
+ const spike = task.kind === 'spike';
353
+ if (spike) commands.push(spikeLib.spikeVerifyCommand(task.id));
354
+ const files = Array.isArray(task.files) && task.files.length ? [...task.files] : spike ? [spikeLib.spikeReportPath(task.id)] : [];
355
+ const scopeWaits = scopeInsufficientFor(task);
356
+ const blockedByList = [...externalRefs(task), ...scopeWaits, ...sharedWait(task)];
357
+ return {
358
+ id: task.id,
359
+ title: task.title,
360
+ wave: task.wave,
361
+ dependsOn: Array.isArray(task.depends_on) ? [...task.depends_on] : [],
362
+ files,
363
+ verifyCommand: commands.length ? [...new Set(commands)].join(' && ') : null,
364
+ aceite: Array.isArray(task.acceptance) ? [...task.acceptance] : [],
365
+ decisions: Array.isArray(task.decisions) ? [...task.decisions] : [],
366
+ done: task.done === true || task.status === 'done',
367
+ meta: {
368
+ source: 'PLAN.json',
369
+ complexity: task.complexity || null,
370
+ ...(task.status ? { status: task.status } : {}),
371
+ ...(task.started_at ? { started_at: task.started_at } : {}),
372
+ ...(task.base_sha ? { base_sha: task.base_sha } : {}),
373
+ ...(task.executor ? { executor: task.executor } : {}),
374
+ ...(typeof task.commit === 'string' && task.commit.trim() ? { commit: task.commit.trim() } : {}),
375
+ ...(task.done_commit ? { done_commit: task.done_commit } : {}),
376
+ ...(task.kind ? { kind: task.kind } : {}),
377
+ ...(typeof task.question === 'string' ? { question: task.question } : {}),
378
+ ...(task.gate ? { gate: task.gate } : {}),
379
+ // OXB-172: a task whose related tests went red OUTSIDE its scope waits (a CR / a plan edit), never re-runs blind.
380
+ ...(blockedByList.length ? { blocked_by: blockedByList } : {}),
381
+ ...(taskPreconditions(task).length ? { waits_on: taskPreconditions(task) } : {}),
382
+ },
383
+ };
384
+ });
385
+ const waves = {};
386
+ for (const task of tasks) {
387
+ if (!waves[task.wave]) waves[task.wave] = [];
388
+ waves[task.wave].push(task.id);
389
+ }
390
+ // Testes de aceite do plano (1.19): escritos antes da execução, congelados por hash no compile.
391
+ const acceptanceTests = (Array.isArray(doc.acceptance_tests) ? doc.acceptance_tests : []).map((entry) => ({
392
+ id: typeof entry.id === 'string' ? entry.id : null,
393
+ criterion: typeof entry.criterion === 'string' ? entry.criterion : null,
394
+ files: [...new Set(entry.files.map((f) => String(f).trim()))],
395
+ command: entry.command.trim(),
396
+ proves: Array.isArray(entry.proves) ? entry.proves.map((name) => String(name).trim()).filter(Boolean) : [],
397
+ resolves: Array.isArray(entry.resolves) ? [...entry.resolves] : [],
398
+ // the task the test belongs to (bound by task; without it, by criterion) — kept, so the binding reaches the
399
+ // dry-verify and the executor (OxeSpace 14/11: a CR test bound by task was dropped here)
400
+ ...(typeof entry.task === 'string' && entry.task.trim() ? { task: entry.task.trim().toUpperCase() } : {}),
401
+ version: Number.isInteger(entry.version) ? entry.version : 1,
402
+ // OXB-072: own timeout for a slow suite (e.g. Electron).
403
+ ...(Number.isInteger(entry.timeout_ms) && entry.timeout_ms > 0 ? { timeout_ms: entry.timeout_ms } : {}),
404
+ ...(typeof entry.sha256 === 'string' && entry.sha256 ? { sha256: entry.sha256 } : {}),
405
+ ...(entry.hashes && typeof entry.hashes === 'object' && !Array.isArray(entry.hashes) ? { hashes: { ...entry.hashes } } : {}),
406
+ ...(Array.isArray(entry.amended) ? { amended: [...entry.amended] } : {}),
407
+ }));
408
+ // Gates do projeto (1.21, OXB-020): rodam uma vez no verify da fase; normalizados por oxe-phase-gates.cjs.
409
+ const phaseGates = Array.isArray(doc.phase_gates) ? doc.phase_gates.map((gate) => ({ ...gate })) : [];
410
+ // Teto da execução (1.21, OXB-023): turnos/US$ por run e tentativas por tarefa.
411
+ const budget = doc.budget && typeof doc.budget === 'object' && !Array.isArray(doc.budget) ? { ...doc.budget } : null;
412
+ return { tasks, waves, totalTasks: tasks.length, source: 'PLAN.json', phase: doc.phase || null, acceptanceTests, phaseGates, budget, supersededCriteria: supersededCriteria(doc) };
413
+ }
414
+
415
+ /**
416
+ * Plano do runtime: PLAN.json válido ao lado do PLAN.md vence; inválido é erro (não cai em
417
+ * silêncio para o markdown); ausente → parser markdown com `source: 'PLAN.md'`.
418
+ */
419
+ function readPlanArtifact(planMdPath, planMdText, parseMarkdown) {
420
+ const jsonPath = planJsonPathFor(planMdPath);
421
+ if (jsonPath && fs.existsSync(jsonPath)) {
422
+ let doc;
423
+ try {
424
+ doc = JSON.parse(fs.readFileSync(jsonPath, 'utf8'));
425
+ } catch (err) {
426
+ throw new Error(`PLAN.json inválido (${jsonPath}): ${err.message}`);
427
+ }
428
+ const errors = validatePlanJson(doc);
429
+ if (errors.length) throw new Error(`PLAN.json não segue o schema (${jsonPath}):\n - ${errors.join('\n - ')}`);
430
+ return planJsonToParsedPlan(doc);
431
+ }
432
+ const parsed = parseMarkdown(planMdText || '');
433
+ return { ...parsed, source: 'PLAN.md' };
434
+ }
435
+
436
+ /**
437
+ * OXB-025: a task that finished (verify green) is marked `done` in PLAN.json with when and which checkpoint, so the
438
+ * next compile skips it instead of paying for it again. Atomic write; the rest of the document is kept as is.
439
+ * @returns {boolean} whether PLAN.json changed
440
+ */
441
+ /**
442
+ * OXB-087: PLAN.json is written by the running execute (done) and by `plan append` (new tasks) at the same time; both
443
+ * read-modify-write under this lock file so neither drops the other's change. A lock older than 30 s is stale.
444
+ */
445
+ function withPlanLock(jsonPath, fn) {
446
+ const lock = `${jsonPath}.lock`;
447
+ const deadline = Date.now() + 10_000;
448
+ let fd = null;
449
+ while (fd === null) {
450
+ try {
451
+ fd = fs.openSync(lock, 'wx');
452
+ } catch (err) {
453
+ if (err.code !== 'EEXIST') throw err;
454
+ try { if (Date.now() - fs.statSync(lock).mtimeMs > 30_000) { fs.rmSync(lock, { force: true }); continue; } } catch { continue; }
455
+ if (Date.now() > deadline) throw new Error(`PLAN.json ocupado (${lock}) — tente de novo`);
456
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 25);
457
+ }
458
+ }
459
+ try {
460
+ return fn();
461
+ } finally {
462
+ try { fs.closeSync(fd); } catch { /* */ }
463
+ fs.rmSync(lock, { force: true });
464
+ }
465
+ }
466
+
467
+ function markPlanTaskDone(planMdPath, taskId, info = {}) {
468
+ const jsonPath = planJsonPathFor(planMdPath);
469
+ if (!jsonPath || !fs.existsSync(jsonPath)) return false;
470
+ return withPlanLock(jsonPath, () => markPlanTaskDoneUnlocked(jsonPath, taskId, info));
471
+ }
472
+
473
+ function markPlanTaskDoneUnlocked(jsonPath, taskId, info) {
474
+ let doc;
475
+ try {
476
+ doc = JSON.parse(fs.readFileSync(jsonPath, 'utf8'));
477
+ } catch {
478
+ return false;
479
+ }
480
+ const task = Array.isArray(doc.tasks) ? doc.tasks.find((t) => t && t.id === taskId) : null;
481
+ if (!task) return false;
482
+ if (task.done === true && task.status !== 'in_progress' && (!info.commit || task.done_commit === info.commit)) return false;
483
+ task.done = true;
484
+ if (task.status != null || info.setStatus === true) task.status = 'done';
485
+ task.done_at = info.at || new Date().toISOString();
486
+ if (info.commit) task.done_commit = info.commit;
487
+ delete task.started_at;
488
+ delete task.base_sha;
489
+ delete task.executor;
490
+ delete task.checkpoint_failed;
491
+ const tmp = `${jsonPath}.${process.pid}.tmp`;
492
+ fs.writeFileSync(tmp, `${JSON.stringify(doc, null, 2)}\n`, 'utf8');
493
+ fs.renameSync(tmp, jsonPath);
494
+ return true;
495
+ }
496
+
497
+ /** OXB-204: mark a task as `in_progress` with executor + base SHA when execution starts. */
498
+ function markPlanTaskStarted(planMdPath, taskId, info = {}) {
499
+ const jsonPath = planJsonPathFor(planMdPath);
500
+ if (!jsonPath || !fs.existsSync(jsonPath)) return false;
501
+ return withPlanLock(jsonPath, () => {
502
+ let doc;
503
+ try { doc = JSON.parse(fs.readFileSync(jsonPath, 'utf8')); } catch { return false; }
504
+ const task = Array.isArray(doc.tasks) ? doc.tasks.find((t) => t && t.id === taskId) : null;
505
+ if (!task || task.done === true) return false;
506
+ task.status = 'in_progress';
507
+ task.started_at = info.at || new Date().toISOString();
508
+ if (info.executor) task.executor = String(info.executor);
509
+ if (info.base_sha) task.base_sha = String(info.base_sha);
510
+ const tmp = `${jsonPath}.${process.pid}.tmp`;
511
+ fs.writeFileSync(tmp, `${JSON.stringify(doc, null, 2)}\n`, 'utf8');
512
+ fs.renameSync(tmp, jsonPath);
513
+ return true;
514
+ });
515
+ }
516
+
517
+ /** OXB-204: clear `in_progress` state (e.g. after `runtime resume --reset-task`). */
518
+ function clearPlanTaskInProgress(planMdPath, taskId) {
519
+ const jsonPath = planJsonPathFor(planMdPath);
520
+ if (!jsonPath || !fs.existsSync(jsonPath)) return false;
521
+ return withPlanLock(jsonPath, () => {
522
+ let doc;
523
+ try { doc = JSON.parse(fs.readFileSync(jsonPath, 'utf8')); } catch { return false; }
524
+ const task = Array.isArray(doc.tasks) ? doc.tasks.find((t) => t && t.id === taskId) : null;
525
+ if (!task) return false;
526
+ const had = task.status === 'in_progress' || task.started_at != null || task.base_sha != null || task.executor != null;
527
+ if (!had) return false;
528
+ if (task.status === 'in_progress') delete task.status;
529
+ delete task.started_at;
530
+ delete task.base_sha;
531
+ delete task.executor;
532
+ const tmp = `${jsonPath}.${process.pid}.tmp`;
533
+ fs.writeFileSync(tmp, `${JSON.stringify(doc, null, 2)}\n`, 'utf8');
534
+ fs.renameSync(tmp, jsonPath);
535
+ return true;
536
+ });
537
+ }
538
+
539
+ /**
540
+ * OXB-205: surgical amendment of a frozen acceptance test's sha256 in PLAN.json, preserving all task `done` / `status`
541
+ * fields untouched.
542
+ */
543
+ function amendFrozenTestInPlanJson(planMdPath, relPath, newSha, info = {}) {
544
+ const jsonPath = planJsonPathFor(planMdPath);
545
+ if (!jsonPath || !fs.existsSync(jsonPath)) return { ok: false, error: 'PLAN.json não encontrado' };
546
+ const normTarget = String(relPath || '').replace(/\\/g, '/').replace(/^\.\//, '');
547
+ return withPlanLock(jsonPath, () => {
548
+ let doc;
549
+ try { doc = JSON.parse(fs.readFileSync(jsonPath, 'utf8')); } catch (err) { return { ok: false, error: `PLAN.json inválido: ${err.message}` }; }
550
+ if (!Array.isArray(doc.acceptance_tests) || !doc.acceptance_tests.length) {
551
+ return { ok: false, error: 'PLAN.json não declara acceptance_tests' };
552
+ }
553
+ const matched = [];
554
+ const crRe = require('./oxe-criteria-ids.cjs').CR_ID_RE;
555
+ const at = info.at || new Date().toISOString();
556
+ const by = info.by || 'tech-lead';
557
+ const reason = String(info.reason || '').trim();
558
+ for (const entry of doc.acceptance_tests) {
559
+ if (!entry || !Array.isArray(entry.files)) continue;
560
+ const idx = entry.files.findIndex((f) => String(f || '').replace(/\\/g, '/').replace(/^\.\//, '') === normTarget);
561
+ if (idx < 0) continue;
562
+ const canonicalFile = String(entry.files[idx]).replace(/\\/g, '/').replace(/^\.\//, '');
563
+ const planStoredSha = (entry.hashes && entry.hashes[canonicalFile])
564
+ || (entry.files.length === 1 && typeof entry.sha256 === 'string' ? entry.sha256 : null)
565
+ || null;
566
+ // OXB-C21 #2: when PLAN.json already holds newSha while the run lock held the prior hash (e.g. after acceptance_tampered),
567
+ // prefer info.previous_sha256 so before/after logs show the real lock hash vs new disk hash instead of identical hashes.
568
+ const prevSha = (planStoredSha && planStoredSha !== newSha)
569
+ ? planStoredSha
570
+ : (info.previous_sha256 && info.previous_sha256 !== newSha ? info.previous_sha256 : (planStoredSha || info.previous_sha256 || null));
571
+ if (entry.files.length === 1) {
572
+ entry.sha256 = newSha;
573
+ }
574
+ entry.hashes = {
575
+ ...(entry.hashes && typeof entry.hashes === 'object' && !Array.isArray(entry.hashes) ? entry.hashes : {}),
576
+ [canonicalFile]: newSha,
577
+ };
578
+ if (reason && crRe.test(reason)) {
579
+ const resolves = Array.isArray(entry.resolves) ? [...entry.resolves] : [];
580
+ if (!resolves.includes(reason)) resolves.push(reason);
581
+ entry.resolves = resolves;
582
+ const req = info.amendments instanceof Map && entry.criterion ? info.amendments.get(entry.criterion) : null;
583
+ const reqVer = req && Number(req.required) > 1 ? Number(req.required) : 2;
584
+ entry.version = Math.max(reqVer, (Number.isInteger(entry.version) ? entry.version : 1) + 1);
585
+ }
586
+ entry.amended = [
587
+ ...(Array.isArray(entry.amended) ? entry.amended : []),
588
+ { file: canonicalFile, previous_sha256: prevSha, sha256: newSha, reason, by, at },
589
+ ];
590
+ matched.push({ criterion: entry.criterion || entry.id || null, previous_sha256: prevSha });
591
+ }
592
+ if (!matched.length) {
593
+ return { ok: false, error: `${normTarget} não está declarado em acceptance_tests de PLAN.json` };
594
+ }
595
+ const tmp = `${jsonPath}.${process.pid}.tmp`;
596
+ fs.writeFileSync(tmp, `${JSON.stringify(doc, null, 2)}\n`, 'utf8');
597
+ fs.renameSync(tmp, jsonPath);
598
+ return { ok: true, matched, previous_sha256: matched[0].previous_sha256 || null };
599
+ });
600
+ }
601
+
602
+ /** OXB-167: the task passed its verify but its checkpoint commit failed — not done; the next execute retries the commit. */
603
+ function markPlanTaskCheckpointFailed(planMdPath, taskId, info = {}) {
604
+ const jsonPath = planJsonPathFor(planMdPath);
605
+ if (!jsonPath || !fs.existsSync(jsonPath)) return false;
606
+ return withPlanLock(jsonPath, () => {
607
+ let doc;
608
+ try { doc = JSON.parse(fs.readFileSync(jsonPath, 'utf8')); } catch { return false; }
609
+ const task = Array.isArray(doc.tasks) ? doc.tasks.find((t) => t && t.id === taskId) : null;
610
+ if (!task) return false;
611
+ task.done = false;
612
+ delete task.done_at;
613
+ delete task.done_commit;
614
+ task.checkpoint_failed = { at: new Date().toISOString(), reason: String(info.reason || '').slice(0, 800), ...(info.commit ? { commit: info.commit } : {}), ...(info.leftover ? { leftover: info.leftover.slice(0, 50) } : {}), ...(info.run_id ? { run_id: info.run_id } : {}), ...(info.snapshot ? { snapshot: info.snapshot } : {}), ...(info.kind ? { kind: info.kind } : {}), ...(info.related_red ? { related_red: info.related_red } : {}), ...(info.real_regressions ? { real_regressions: info.real_regressions } : {}), ...(info.later_owned_reds && info.later_owned_reds.length ? { later_owned_reds: info.later_owned_reds } : {}), ...(info.preexisting_reds && info.preexisting_reds.length ? { preexisting_reds: info.preexisting_reds } : {}), ...(info.title ? { title: info.title } : {}) };
615
+ const tmp = `${jsonPath}.${process.pid}.tmp`;
616
+ fs.writeFileSync(tmp, `${JSON.stringify(doc, null, 2)}\n`, 'utf8');
617
+ fs.renameSync(tmp, jsonPath);
618
+ return true;
619
+ });
620
+ }
621
+
622
+ function hasCycle(tasks) {
623
+ const deps = new Map(tasks.map((t) => [t.id, t.dependsOn || []]));
624
+ const state = new Map();
625
+ const visit = (id) => {
626
+ if (state.get(id) === 1) return true;
627
+ if (state.get(id) === 2) return false;
628
+ state.set(id, 1);
629
+ for (const dep of deps.get(id) || []) if (deps.has(dep) && visit(dep)) return true;
630
+ state.set(id, 2);
631
+ return false;
632
+ };
633
+ return tasks.some((t) => visit(t.id));
634
+ }
635
+
636
+ /**
637
+ * Lint estrutural do plano: torna mecânicas as regras de quality gate de `oxe/workflows/plan.md`.
638
+ * @param {{ plan: any, spec?: any, pack?: any, phase?: any, maxTasksPerWave?: number }} input
639
+ * @returns {{ ok: boolean, errors: string[], warnings: string[] }}
640
+ */
641
+ function lintPlan(input) {
642
+ const errors = [];
643
+ const warnings = [];
644
+ const tasks = input.plan && Array.isArray(input.plan.tasks) ? input.plan.tasks : [];
645
+ if (tasks.length === 0) errors.push('plano sem tarefas');
646
+ const { lintSpikeTask } = require('./oxe-spike.cjs');
647
+ for (const task of tasks) if (!task.done) errors.push(...lintSpikeTask(task));
648
+ if (input.plan && input.plan.source === 'PLAN.md') {
649
+ warnings.push('PLAN.json ausente: o runtime usa o parser heurístico do PLAN.md (grave PLAN.json no /oxe-plan)');
650
+ }
651
+
652
+ const ids = new Map();
653
+ for (const task of tasks) ids.set(task.id, (ids.get(task.id) || 0) + 1);
654
+ for (const [id, count] of ids) if (count > 1) errors.push(`id duplicado: ${id} (${count}x)`);
655
+ const byId = new Map(tasks.map((t) => [t.id, t]));
656
+
657
+ for (const task of tasks) {
658
+ if (task.wave == null) errors.push(`${task.id}: sem onda`);
659
+ for (const dep of task.dependsOn || []) {
660
+ const target = byId.get(dep);
661
+ if (!target) errors.push(`${task.id}: depende de ${dep}, que não existe`);
662
+ else if (dep === task.id) errors.push(`${task.id}: depende de si mesma`);
663
+ else if (target.wave != null && task.wave != null && target.wave >= task.wave) {
664
+ errors.push(`${task.id} (onda ${task.wave}) depende de ${dep} (onda ${target.wave}): a dependência deve estar numa onda anterior`);
665
+ }
666
+ }
667
+ if (!task.verifyCommand && !task.done) warnings.push(`${task.id}: sem comando de verificação`);
668
+ }
669
+
670
+ // OXB-193: helper to check scope containment
671
+ const isPathInScope = (filePath, scope) => {
672
+ const f = String(filePath || '').replace(/\\/g, '/');
673
+ for (const raw of scope || []) {
674
+ const s = String(raw || '').replace(/\\/g, '/').replace(/^\.\//, '');
675
+ if (!s) continue;
676
+ if (/[*?[{]/.test(s)) {
677
+ const re = new RegExp(`^${s.replace(/[.+^$()|\\]/g, '\\$&').replace(/\*\*\/?/g, '\u0000').replace(/\*/g, '[^/]*').replace(/\?/g, '[^/]').replace(/\u0000/g, '.*')}$`);
678
+ if (re.test(f)) return true;
679
+ } else {
680
+ const clean = s.replace(/\/+$/, '');
681
+ if (f === clean || f.startsWith(`${clean}/`)) return true;
682
+ }
683
+ }
684
+ return false;
685
+ };
686
+
687
+ // OXB-193: warn if files contains an unexpanded directory
688
+ for (const task of tasks) {
689
+ for (const file of task.files || []) {
690
+ const s = String(file || '').trim();
691
+ const isDirPattern = s.endsWith('/') || s.endsWith('/**');
692
+ let isDiskDir = false;
693
+ if (input.projectRoot) {
694
+ try {
695
+ const abs = path.resolve(input.projectRoot, s.replace(/(\/\*\*|\/)+$/, ''));
696
+ isDiskDir = fs.existsSync(abs) && fs.statSync(abs).isDirectory();
697
+ } catch { /* ignore */ }
698
+ }
699
+ if (isDirPattern || isDiskDir) {
700
+ const hasChild = (task.files || []).some((f) => f !== s && isPathInScope(f, [s]));
701
+ if (!hasChild) {
702
+ warnings.push(`${task.id}: diretório não expandido em files ("${s}") — use oxe-cc plan build para expandir os arquivos`);
703
+ }
704
+ }
705
+ }
706
+ }
707
+
708
+ // OXB-194: error if verify references a file removed by the task or a dependency
709
+ const packTasks = input.pack && Array.isArray(input.pack.tasks) ? input.pack.tasks : [];
710
+ const packTaskById = new Map(packTasks.map((t) => [String(t.id || t.task_id || '').trim(), t]));
711
+ for (const task of tasks) {
712
+ const transitiveRemoved = new Set();
713
+ const visited = new Set();
714
+ const q = [task.id];
715
+ while (q.length) {
716
+ const curId = q.shift();
717
+ if (visited.has(curId)) continue;
718
+ visited.add(curId);
719
+ const curTask = byId.get(curId);
720
+ const curPack = packTaskById.get(curId);
721
+ if (curTask && Array.isArray(curTask.removed_paths)) for (const p of curTask.removed_paths) transitiveRemoved.add(String(p).replace(/\\/g, '/'));
722
+ if (curPack && Array.isArray(curPack.removed_paths)) for (const p of curPack.removed_paths) transitiveRemoved.add(String(p).replace(/\\/g, '/'));
723
+ const deps = curTask ? (curTask.dependsOn || curTask.depends_on || []) : [];
724
+ for (const d of deps) q.push(d);
725
+ }
726
+ if (transitiveRemoved.size > 0) {
727
+ const verifyCmds = [];
728
+ if (task.verifyCommand) verifyCmds.push(task.verifyCommand);
729
+ if (task.verify && Array.isArray(task.verify.commands)) verifyCmds.push(...task.verify.commands);
730
+ for (const cmd of verifyCmds) {
731
+ for (const rem of transitiveRemoved) {
732
+ if (cmd.includes(rem)) {
733
+ errors.push(`${task.id}: verify cita arquivo removido por ela ou dependência ("${rem}")`);
734
+ }
735
+ }
736
+ }
737
+ }
738
+ }
739
+
740
+ // OXB-195 / OXB-207: coupled_scope check (including built-in offer-audit rule + MENU_EFFECTS lint note)
741
+ let coupledRules = [];
742
+ try {
743
+ coupledRules = require('./oxe-plan-build.cjs').loadCoupledScope(input.projectRoot || null, {
744
+ coupledScope: input.config && Array.isArray(input.config.coupled_scope) ? input.config.coupled_scope : undefined,
745
+ builtinCoupledScope: input.config && input.config.builtin_coupled_scope === false ? false : undefined,
746
+ });
747
+ } catch { /* ignore */ }
748
+ if (coupledRules.length) {
749
+ for (const task of tasks) {
750
+ if (task.done === true) continue;
751
+ const taskFiles = (task.files || []).map((f) => String(f).replace(/\\/g, '/'));
752
+ const editedPaths = (task.edited_paths || []).map((f) => String(f).replace(/\\/g, '/'));
753
+ const removedPaths = (task.removed_paths || []).map((f) => String(f).replace(/\\/g, '/'));
754
+ for (const rule of coupledRules) {
755
+ const when = rule.when ? (Array.isArray(rule.when) ? rule.when : [rule.when]) : [];
756
+ const whenDeleted = rule.when_deleted ? (Array.isArray(rule.when_deleted) ? rule.when_deleted : [rule.when_deleted]) : [];
757
+ const whenEdited = rule.when_edited ? (Array.isArray(rule.when_edited) ? rule.when_edited : [rule.when_edited]) : [];
758
+ const matchWhen = when.some((w) => taskFiles.some((f) => isPathInScope(f, [w])));
759
+ const matchDeleted = whenDeleted.some((w) => removedPaths.some((f) => isPathInScope(f, [w])));
760
+ const matchEdited = whenEdited.some((w) => editedPaths.some((f) => isPathInScope(f, [w])));
761
+ if (matchWhen || matchDeleted || matchEdited) {
762
+ const inc = (Array.isArray(rule.include) ? rule.include : (rule.include ? [rule.include] : [])).map((f) => String(f).replace(/\\/g, '/'));
763
+ const missing = inc.filter((f) => !taskFiles.includes(f));
764
+ if (missing.length) {
765
+ warnings.push(`${task.id}: escopo acoplado recomendado não incluído em files (${missing.join(', ')})${rule.note ? ` — ${rule.note}` : ''}`);
766
+ } else if (rule.note) {
767
+ warnings.push(`${task.id}: ${rule.note}`);
768
+ }
769
+ }
770
+ }
771
+ }
772
+ }
773
+
774
+ // 1.21.2 shift-left generated_files: warn before execute if a task includes a generated file without its source
775
+ // in files or in an ancestor dependency (at checkpoint that deterministically blocks as scope_insufficient).
776
+ let genRules = input.config && Array.isArray(input.config.generated_files) ? input.config.generated_files : null;
777
+ if (!genRules && input.projectRoot) {
778
+ try {
779
+ const cfgPath = path.join(input.projectRoot, '.oxe', 'config.json');
780
+ if (fs.existsSync(cfgPath)) {
781
+ const cfg = JSON.parse(fs.readFileSync(cfgPath, 'utf8'));
782
+ if (Array.isArray(cfg.generated_files)) genRules = cfg.generated_files;
783
+ }
784
+ } catch { /* ignore */ }
785
+ }
786
+ if (Array.isArray(genRules) && genRules.length) {
787
+ const dh = require('./oxe-dom-hooks.cjs');
788
+ const scopeCoversSource = (scope, s) => scope.some((p) => p === s || dh.globRe(s).test(p) || dh.globRe(p).test(String(s).replace(/\*.*$/, 'x')) || String(s).startsWith(`${p.replace(/\/+$/, '')}/`));
789
+ const acceptanceByCrit = new Map();
790
+ for (const entry of input.plan && Array.isArray(input.plan.acceptanceTests) ? input.plan.acceptanceTests : []) {
791
+ if (entry && entry.criterion) acceptanceByCrit.set(entry.criterion, [...(acceptanceByCrit.get(entry.criterion) || []), entry]);
792
+ }
793
+ for (const task of tasks) {
794
+ if (task.done === true) continue;
795
+ const taskFiles = (task.files || []).map((f) => String(f || '').replace(/\\/g, '/').replace(/^\.\//, '')).filter(Boolean);
796
+ if (!taskFiles.length) continue;
797
+ const ancestorFiles = [];
798
+ const seenDeps = new Set([task.id]);
799
+ const depQueue = [...(task.dependsOn || task.depends_on || [])];
800
+ while (depQueue.length) {
801
+ const depId = depQueue.shift();
802
+ if (!depId || seenDeps.has(depId)) continue;
803
+ seenDeps.add(depId);
804
+ const depTask = byId.get(depId);
805
+ if (!depTask) continue;
806
+ for (const f of depTask.files || []) {
807
+ const norm = String(f || '').replace(/\\/g, '/').replace(/^\.\//, '');
808
+ if (norm) ancestorFiles.push(norm);
809
+ }
810
+ for (const d of depTask.dependsOn || depTask.depends_on || []) depQueue.push(d);
811
+ }
812
+ const combinedScope = [...taskFiles, ...ancestorFiles];
813
+ for (const rule of genRules) {
814
+ if (!rule || !rule.file || !rule.source) continue;
815
+ const filePatterns = (Array.isArray(rule.file) ? rule.file : [rule.file]).map((g) => String(g).replace(/\\/g, '/'));
816
+ const fileRes = filePatterns.map(dh.globRe);
817
+ const edited = taskFiles.filter((p) => filePatterns.includes(p) || fileRes.some((re) => re.test(p)));
818
+ if (!edited.length) continue;
819
+ const sources = (Array.isArray(rule.source) ? rule.source : [rule.source]).map((s) => String(s).replace(/\\/g, '/'));
820
+ if (!sources.some((s) => scopeCoversSource(combinedScope, s))) {
821
+ warnings.push(`${task.id}: files inclui arquivo gerado (${edited.join(', ')}) sem a fonte (${sources.join(', ')}) em files nem nas dependências — no checkpoint isso bloqueia como scope_insufficient`);
822
+ }
823
+ if (rule.test) {
824
+ const normTest = String(rule.test).replace(/\\/g, '/').replace(/^\.\//, '');
825
+ const critEntries = (task.aceite || []).flatMap((c) => acceptanceByCrit.get(c) || []);
826
+ const verifyTexts = [
827
+ task.verifyCommand || '',
828
+ ...((task.verify && Array.isArray(task.verify.commands)) ? task.verify.commands : []),
829
+ ...(Array.isArray(task.affected_suites) ? task.affected_suites : []),
830
+ ...taskFiles,
831
+ ...critEntries.flatMap((e) => [e.command || '', ...(e.files || [])]),
832
+ ].map((v) => String(v || '').replace(/\\/g, '/'));
833
+ if (!verifyTexts.some((v) => v.includes(normTest))) {
834
+ warnings.push(`${task.id}: files inclui arquivo gerado (${edited.join(', ')}) sem o teste do gerador (${normTest}) em verify`);
835
+ }
836
+ }
837
+ }
838
+ }
839
+ }
840
+ if (tasks.length && hasCycle(tasks)) errors.push('dependência circular entre tarefas');
841
+
842
+ const waves = new Map();
843
+ for (const task of tasks) {
844
+ // Uma tarefa concluída não roda de novo: num replan ela não disputa escopo nem lugar na onda (OXB-015).
845
+ if (task.wave == null || task.done) continue;
846
+ if (!waves.has(task.wave)) waves.set(task.wave, []);
847
+ waves.get(task.wave).push(task);
848
+ }
849
+ const waveNumbers = [...waves.keys()].sort((a, b) => a - b);
850
+ waveNumbers.forEach((wave, i) => {
851
+ if (i > 0 && wave !== waveNumbers[i - 1] + 1) warnings.push(`onda ${waveNumbers[i - 1] + 1} vazia (ondas: ${waveNumbers.join(', ')})`);
852
+ });
853
+ for (const [wave, list] of waves) {
854
+ if (input.maxTasksPerWave && list.length > input.maxTasksPerWave) {
855
+ errors.push(`onda ${wave}: ${list.length} tarefas > plan_max_tasks_per_wave (${input.maxTasksPerWave})`);
856
+ }
857
+ const owner = new Map();
858
+ for (const task of list) {
859
+ for (const file of task.files || []) {
860
+ if (owner.has(file)) errors.push(`onda ${wave}: ${owner.get(file)} e ${task.id} escrevem ${file} (escopos devem ser disjuntos na mesma onda)`);
861
+ else owner.set(file, task.id);
862
+ }
863
+ }
864
+ }
865
+
866
+ const criteria = input.spec && Array.isArray(input.spec.criteria) ? input.spec.criteria.map((c) => c.id) : [];
867
+ const covered = new Set(tasks.flatMap((t) => t.aceite || []));
868
+ if (criteria.length) {
869
+ const known = new Set(criteria);
870
+ for (const task of tasks) {
871
+ for (const ref of task.aceite || []) if (!known.has(ref)) errors.push(`${task.id}: aceite ${ref} não existe na SPEC`);
872
+ }
873
+ }
874
+
875
+ const phase = input.phase || null;
876
+ const critIds = require('./oxe-criteria-ids.cjs');
877
+ // OXB-037: global criteria G* hold for every UI task of the phase — each must be covered by some UI task.
878
+ const globals = criteria.filter(critIds.isGlobal);
879
+ const uiTasks = tasks.filter((t) => critIds.isUiTask(t) && !t.done);
880
+ if (globals.length && uiTasks.length) {
881
+ const uiCovered = new Set(uiTasks.flatMap((t) => t.aceite || []));
882
+ const missingG = globals.filter((g) => !uiCovered.has(g));
883
+ if (missingG.length) warnings.push(`critérios globais sem tarefa de UI que os cubra: ${missingG.join(', ')} (o plano tem ${uiTasks.length} tarefa(s) de UI: ${uiTasks.map((t) => t.id).join(', ')})`);
884
+ }
885
+ if (phase && Array.isArray(phase.acceptance) && phase.acceptance.length) {
886
+ const allowed = new Set(phase.acceptance);
887
+ // A subcriterion belongs to its parent's phase; a G* is global.
888
+ const standing = new Set([...(input.standing || []), ...((input.plan && input.plan.supersededCriteria) || [])]);
889
+ const outside = [...covered].filter((ref) => !critIds.inPhase(ref, allowed) && !standing.has(ref));
890
+ if (outside.length) errors.push(`fase ${phase.id}: o plano usa A* de outras fases: ${outside.join(', ')}`);
891
+ // A parent with subcriteria declared in the SPEC is covered when each subcriterion is (OXB-037).
892
+ const missing = critIds.uncovered(phase.acceptance.filter((ref) => !critIds.isGlobal(ref) && !standing.has(ref)), covered, criteria);
893
+ if (missing.length) errors.push(`fase ${phase.id}: A* da fase sem tarefa: ${missing.join(', ')}`);
894
+ if (input.plan && input.plan.phase && input.plan.phase !== phase.id) {
895
+ errors.push(`PLAN.json declara fase ${input.plan.phase}, mas a fase ativa é ${phase.id}`);
896
+ }
897
+ } else if (criteria.length) {
898
+ const superseded = new Set((input.plan && input.plan.supersededCriteria) || []);
899
+ const missing = critIds.uncovered(criteria.filter((ref) => !critIds.isGlobal(ref) && !critIds.isSub(ref) && !superseded.has(ref)), covered, criteria);
900
+ if (missing.length) warnings.push(`A* da SPEC sem tarefa: ${missing.join(', ')}`);
901
+ }
902
+
903
+ // Aceite congelado: o teste que prova o A* é do plano, não do executor.
904
+ const acceptanceTests = input.plan && Array.isArray(input.plan.acceptanceTests) ? input.plan.acceptanceTests : [];
905
+ const testedCriteria = new Set(acceptanceTests.map((entry) => entry.criterion).filter(Boolean));
906
+ const ownedByTasks = new Map();
907
+ for (const task of tasks) for (const file of task.files || []) ownedByTasks.set(file, task.id);
908
+ for (const entry of acceptanceTests) {
909
+ if (entry.criterion && criteria.length && !criteria.includes(entry.criterion)) errors.push(`teste de aceite ${entry.criterion}: critério não existe na SPEC`);
910
+ for (const file of entry.files) {
911
+ // bench B52: a wall-clock assertion (p95, elapsed ms under a limit) frozen as acceptance is flaky under load —
912
+ // the criterion belongs in .oxe/program/nfr.json (OXB-144: samples, median, phase gate)
913
+ if (input.projectRoot) {
914
+ let text = '';
915
+ try { text = fs.readFileSync(path.resolve(input.projectRoot, file), 'utf8'); } catch { text = ''; }
916
+ const timing = /performance\.now\(\)|process\.hrtime|Date\.now\(\)\s*-|\bp9[059]\b|percentile/i.test(text);
917
+ const bound = /toBeLessThan(?:OrEqual)?\(|assert\.ok\([^)\n]*<=?\s*\d|expect\([^)\n]*\)\s*\.\s*to\.be\.below|<=?\s*\d{2,}\s*\)/.test(text);
918
+ if (timing && bound) warnings.push(`teste de aceite ${entry.criterion}: ${file} afirma um limite de tempo de parede (p95/ms) — instável sob carga; declare o NFR em .oxe/program/nfr.json (runtime nfr measure, amostras + mediana) e deixe no teste só o comportamento [bench B52]`);
919
+ }
920
+ if (input.projectRoot && !fs.existsSync(path.resolve(input.projectRoot, file))) {
921
+ errors.push(`teste de aceite ${entry.criterion}: ${file} não existe (escreva-o no /oxe-plan, antes da execução)`);
922
+ }
923
+ if (ownedByTasks.has(file)) {
924
+ const badOwner = ownedByTasks.get(file);
925
+ errors.push(`teste de aceite ${entry.criterion}: ${file} está no escopo de ${badOwner} — o executor não pode escrever o próprio aceite (remova de files com: oxe-cc plan task edit ${badOwner} --remove-paths ${file} --by <papel> --reason "remover teste congelado de files")`);
926
+ }
927
+ }
928
+ }
929
+ // Prova executada: o runner precisa listar os nomes dos testes que passaram.
930
+ for (const entry of acceptanceTests) {
931
+ if (!entry.proves || !entry.proves.length) continue;
932
+ // gradle / maven: the test names come from testLogging lines (`Class > method PASSED`) or the JUnit XML reports
933
+ const verbose = /--reporter[= ]verbose|--verbose|--test-reporter[= ](tap|spec)|node\s+--test|\s-v\b|junit|\b(gradlew|gradle|mvnw?)/i.test(entry.command);
934
+ if (!verbose) warnings.push(`teste de aceite ${entry.criterion}: 'proves' exige saída com nomes de teste — use um reporter verbose (ex.: vitest --reporter=verbose)`);
935
+ // OXB-073: each `proves` must name a test the files DECLARE. Paraphrased proves ("ratchet (LIMIT_SELECTED) stays at
936
+ // 22 or lower, never raised" for the test "ratchet stays at 22 or lower (never raised)") can never be found among
937
+ // the passed tests: the verify said proof_not_executed although every test passed.
938
+ if (input.projectRoot) {
939
+ const declared = [];
940
+ for (const file of entry.files || []) {
941
+ let text = '';
942
+ try { text = fs.readFileSync(path.resolve(input.projectRoot, file), 'utf8'); } catch { continue; }
943
+ declared.push(...declaredTestTitles(text, file, { includeSuites: true }));
944
+ }
945
+ if (declared.length) {
946
+ const norm = (s) => String(s).toLowerCase().replace(/[›>]/g, ' ').replace(/\s+/g, ' ').trim();
947
+ const haystack = declared.map(norm);
948
+ for (const proof of entry.proves) {
949
+ const wanted = norm(String(proof).includes('›') ? String(proof).split('›').slice(1).join('›') : proof);
950
+ if (!haystack.some((name) => name.includes(wanted))) {
951
+ errors.push(`teste de aceite ${entry.id || entry.criterion}: proves "${proof}" não é o nome de nenhum teste declarado em ${entry.files.join(', ')} — use o nome exato (ou um trecho dele). Testes declarados: ${declared.slice(0, 8).map((n) => `"${n}"`).join('; ')}`);
952
+ }
953
+ }
954
+ }
955
+ }
956
+ }
957
+ // Emenda de SPEC (CR spec_gap): teste de aceite de versão anterior está stale até ser reescrito.
958
+ // OXB-062: `amendments` tells an additive amendment (earlier tests stay valid, one new test carries the version)
959
+ // from a changing one (every earlier test is stale). Plain `requiredVersions` means changing.
960
+ const amendments = input.amendments instanceof Map
961
+ ? input.amendments
962
+ : new Map([...(input.requiredVersions instanceof Map ? input.requiredVersions : new Map())].map(([c, v]) => [c, { required: v, staleBelow: v }]));
963
+ const supersededForAmend = new Set((input.plan && input.plan.supersededCriteria) || []);
964
+ for (const [criterion, req] of amendments) {
965
+ if (supersededForAmend.has(criterion)) continue; // superseded (plan task supersede): proven by the phase that replaces it
966
+ const entries = acceptanceTests.filter((a) => a.criterion === criterion);
967
+ if (!entries.some((e) => (e.version || 1) >= req.required)) {
968
+ errors.push(entries.length && req.staleBelow < req.required
969
+ ? `${criterion}@v${req.required}: emenda aditiva sem teste novo (adicione um teste com "version": ${req.required}; os anteriores continuam valendo)`
970
+ : entries.length
971
+ ? `${criterion}: teste de aceite v${Math.max(...entries.map((e) => e.version || 1))} está stale — a SPEC foi emendada para v${req.required}`
972
+ : `${criterion}@v${req.required}: emenda sem teste de aceite (escreva-o com "version": ${req.required})`);
973
+ }
974
+ for (const e of entries) {
975
+ const v = e.version || 1;
976
+ if (v < req.staleBelow && entries.some((o) => (o.version || 1) >= req.required)) {
977
+ errors.push(`${criterion}: teste de aceite v${v}${e.files && e.files[0] ? ` (${e.files[0]})` : ''} está stale — a SPEC foi emendada para v${req.staleBelow}`);
978
+ }
979
+ }
980
+ }
981
+ const scopeAcceptance = phase && Array.isArray(phase.acceptance) && phase.acceptance.length ? phase.acceptance : [...covered];
982
+ // OXB-091: a standing criterion is proven by the phase sign-off + evidence, not by a frozen test.
983
+ const standingSet = new Set([...(input.standing || []), ...((input.plan && input.plan.supersededCriteria) || [])]);
984
+ const untested = scopeAcceptance.filter((ref) => !testedCriteria.has(ref) && !standingSet.has(ref));
985
+ if (untested.length) {
986
+ (input.requireAcceptanceTests ? errors : warnings).push(`A* sem teste de aceite congelado: ${untested.join(', ')}`);
987
+ }
988
+
989
+ const pack = input.pack && Array.isArray(input.pack.tasks) ? input.pack.tasks : null;
990
+ if (pack) {
991
+ const packIds = new Set(pack.map((t) => String((t && (t.id || t.task_id)) || '').trim()));
992
+ // OXB-088: a pack of another phase (F1's stale pack under F2's plan: T1–T13 passed only because ids matched).
993
+ const packPhase = input.pack && typeof input.pack.phase === 'string' ? input.pack.phase : null;
994
+ const planPhase = (input.plan && input.plan.phase) || (phase && phase.id) || null;
995
+ const otherPhase = packPhase && planPhase && packPhase !== planPhase ? packPhase : null;
996
+ if (otherPhase) warnings.push(`IMPLEMENTATION-PACK é da fase ${otherPhase}, e o plano é da ${planPhase} — gere o pack desta fase`);
997
+ for (const task of tasks) {
998
+ if ((task.files || []).length && !task.done && !packIds.has(task.id)) {
999
+ errors.push(`${task.id}: tarefa mutável sem entrada no IMPLEMENTATION-PACK${otherPhase ? ` (o pack é da fase ${otherPhase})` : ''}`);
1000
+ }
1001
+ }
1002
+ // OXB-022: the very rules the execute preflight applies — nothing passes here and blocks there.
1003
+ // (spikes declare a docs_only pack entry: they write only their report in .oxe/spikes/)
1004
+ const { validatePackTask } = require('./oxe-rationality.cjs');
1005
+ const pending = new Set(tasks.filter((task) => !task.done).map((task) => task.id));
1006
+ for (const entry of pack) {
1007
+ const id = String((entry && (entry.id || entry.task_id)) || '').trim();
1008
+ if (id && !pending.has(id)) continue;
1009
+ errors.push(...validatePackTask(entry).gaps);
1010
+ }
1011
+ }
1012
+
1013
+ return { ok: errors.length === 0, errors, warnings };
1014
+ }
1015
+
1016
+ /**
1017
+ * 1.21.1 (OXB-053/046): the task(s) that complete each criterion. A criterion's own verification (the SPEC
1018
+ * "Como verificar" / its phase-wide acceptance test) can only pass after the LAST of its tasks: in the oxespace 1.5.0
1019
+ * F1 the A4 test checked every dialog in src/ and ran in the verify of T8 and T9 too, failing 12 times (US$ 37.52).
1020
+ * The closer is the single task of the criterion that no other task of the same criterion depends on (transitively).
1021
+ * With several such sinks the criterion is only checked at phase verify.
1022
+ * @returns {Map<string, { closer: string|null, tasks: string[], sinks: string[] }>}
1023
+ */
1024
+ function criterionClosers(tasks) {
1025
+ const list = Array.isArray(tasks) ? tasks : [];
1026
+ const byId = new Map(list.map((t) => [t.id, t]));
1027
+ const deps = (t) => (Array.isArray(t.dependsOn) ? t.dependsOn : Array.isArray(t.depends_on) ? t.depends_on : []);
1028
+ const ancestors = new Map();
1029
+ const ancestorsOf = (id, seen = new Set()) => {
1030
+ if (ancestors.has(id)) return ancestors.get(id);
1031
+ const out = new Set();
1032
+ for (const d of deps(byId.get(id) || {})) {
1033
+ if (seen.has(d)) continue;
1034
+ seen.add(d);
1035
+ out.add(d);
1036
+ for (const a of ancestorsOf(d, seen)) out.add(a);
1037
+ }
1038
+ ancestors.set(id, out);
1039
+ return out;
1040
+ };
1041
+ const result = new Map();
1042
+ const criteria = new Set(list.flatMap((t) => (Array.isArray(t.aceite) ? t.aceite : Array.isArray(t.acceptance) ? t.acceptance : [])));
1043
+ for (const criterion of criteria) {
1044
+ const members = list.filter((t) => (t.aceite || t.acceptance || []).includes(criterion)).map((t) => t.id);
1045
+ const sinks = members.filter((id) => !members.some((other) => other !== id && ancestorsOf(other).has(id)));
1046
+ result.set(criterion, { closer: sinks.length === 1 ? sinks[0] : null, tasks: members, sinks });
1047
+ }
1048
+ return result;
1049
+ }
1050
+
1051
+ /**
1052
+ * 1.21.1: reopens a done task (rework after a CR or a failed phase verify). Since execute recompiles from the plan and
1053
+ * skips done tasks, "run it again" means reopening it explicitly — never a stale graph re-running finished work.
1054
+ * @returns {boolean} whether PLAN.json changed
1055
+ */
1056
+ function markPlanTaskOpen(planMdPath, taskId, info = {}) {
1057
+ const jsonPath = planJsonPathFor(planMdPath);
1058
+ if (!jsonPath || !fs.existsSync(jsonPath)) return false;
1059
+ let doc;
1060
+ try {
1061
+ doc = JSON.parse(fs.readFileSync(jsonPath, 'utf8'));
1062
+ } catch {
1063
+ return false;
1064
+ }
1065
+ const task = Array.isArray(doc.tasks) ? doc.tasks.find((t) => t && t.id === taskId) : null;
1066
+ if (!task || (task.done !== true && !task.checkpoint_failed && task.status !== 'done' && task.status !== 'in_progress')) return false;
1067
+ // a task folded into another (plan task fold) never comes back: its scope now belongs to the target
1068
+ if (task.merged_into) throw new Error(`${taskId} foi fundida em ${task.merged_into} (plan task fold): reabra ${task.merged_into}, não ${taskId}`);
1069
+ if (task.superseded) throw new Error(`${taskId} foi substituída por ${task.superseded.by_phase} (plan task supersede): não volta a este plano`);
1070
+ delete task.checkpoint_failed; // OXB-172: reopen also clears a failed checkpoint (scope fixed by a plan edit / CR)
1071
+ task.done = false;
1072
+ if (task.status != null) delete task.status;
1073
+ delete task.started_at;
1074
+ delete task.base_sha;
1075
+ delete task.executor;
1076
+ task.reopened = [...(Array.isArray(task.reopened) ? task.reopened : []), { at: new Date().toISOString(), by: info.by || null, previous_commit: task.done_commit || null }];
1077
+ delete task.done_at;
1078
+ delete task.done_commit;
1079
+ const tmp = `${jsonPath}.${process.pid}.tmp`;
1080
+ fs.writeFileSync(tmp, `${JSON.stringify(doc, null, 2)}\n`, 'utf8');
1081
+ fs.renameSync(tmp, jsonPath);
1082
+ return true;
1083
+ }
1084
+
1085
+ module.exports = {
1086
+ supersededCriteria,
1087
+ eachTestTitles,
1088
+ eachTestGroups,
1089
+ markPlanTaskCheckpointFailed,
1090
+ markPlanTaskStarted,
1091
+ clearPlanTaskInProgress,
1092
+ amendFrozenTestInPlanJson,
1093
+ withPlanLock,
1094
+ ACCEPT_RE,
1095
+ externalRefs,
1096
+ taskPreconditions,
1097
+ preconditionProblem,
1098
+ declaredTestTitles,
1099
+ markPlanTaskOpen,
1100
+ criterionClosers,
1101
+ markPlanTaskDone,
1102
+ planJsonPathFor,
1103
+ validatePlanJson,
1104
+ planJsonToParsedPlan,
1105
+ readPlanArtifact,
1106
+ lintPlan,
1107
+ };