oxe-cc 1.16.0 → 1.21.1

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 (284) hide show
  1. package/.github/copilot-instructions.md +177 -177
  2. package/.github/dependabot.yml +31 -31
  3. package/.github/workflows/ci.yml +159 -138
  4. package/.github/workflows/release.yml +107 -106
  5. package/AGENTS.md +97 -97
  6. package/CHANGELOG.md +1032 -856
  7. package/README.md +673 -600
  8. package/assets/readme-banner.svg +19 -19
  9. package/bin/banner.txt +13 -13
  10. package/bin/lib/oxe-agent-install.cjs +650 -650
  11. package/bin/lib/oxe-artifact-catalog.cjs +376 -376
  12. package/bin/lib/oxe-azure.cjs +1445 -1445
  13. package/bin/lib/oxe-budget.cjs +117 -0
  14. package/bin/lib/oxe-change.cjs +230 -0
  15. package/bin/lib/oxe-command-registry.cjs +31 -31
  16. package/bin/lib/oxe-commit-convention.cjs +85 -0
  17. package/bin/lib/oxe-context-engine.cjs +874 -874
  18. package/bin/lib/oxe-core-command-handlers.cjs +82 -82
  19. package/bin/lib/oxe-criterion-coverage.cjs +58 -0
  20. package/bin/lib/oxe-dashboard.cjs +737 -737
  21. package/bin/lib/oxe-dossier.cjs +281 -0
  22. package/bin/lib/oxe-install-resolve.cjs +134 -106
  23. package/bin/lib/oxe-manifest.cjs +124 -124
  24. package/bin/lib/oxe-npm-version.cjs +66 -66
  25. package/bin/lib/oxe-operational.cjs +4484 -2676
  26. package/bin/lib/oxe-phase-gates.cjs +280 -0
  27. package/bin/lib/oxe-plan-json.cjs +433 -0
  28. package/bin/lib/oxe-plugin-cli.cjs +95 -95
  29. package/bin/lib/oxe-plugins.cjs +432 -432
  30. package/bin/lib/oxe-process.cjs +56 -56
  31. package/bin/lib/oxe-program.cjs +205 -0
  32. package/bin/lib/oxe-project-env.cjs +178 -0
  33. package/bin/lib/oxe-project-health.cjs +2962 -2846
  34. package/bin/lib/oxe-rationality.cjs +73 -49
  35. package/bin/lib/oxe-release.cjs +42 -0
  36. package/bin/lib/oxe-repo-rules.cjs +108 -0
  37. package/bin/lib/oxe-runtime-semantics.cjs +514 -514
  38. package/bin/lib/oxe-scorecard.cjs +164 -0
  39. package/bin/lib/oxe-security.cjs +289 -289
  40. package/bin/lib/oxe-spike.cjs +98 -0
  41. package/bin/lib/oxe-verify-dryrun.cjs +152 -0
  42. package/bin/lib/oxe-workflows.cjs +145 -145
  43. package/bin/oxe-cc.js +6281 -5829
  44. package/docs/INTEGRATION.md +182 -182
  45. package/docs/QUALITY-GATES.md +46 -46
  46. package/docs/RELEASE-READINESS.md +87 -86
  47. package/docs/RUNTIME-SMOKE-MATRIX.md +137 -137
  48. package/docs/oxespace-1.5/BACKLOG.md +273 -0
  49. package/docs/oxevoice/BACKLOG.md +244 -0
  50. package/lib/runtime/compiler/graph-compiler.d.ts +13 -0
  51. package/lib/runtime/compiler/graph-compiler.js +40 -3
  52. package/lib/runtime/delivery/promotion-pipeline.js +6 -2
  53. package/lib/runtime/events/catalog.d.ts +1 -1
  54. package/lib/runtime/events/catalog.js +11 -0
  55. package/lib/runtime/executor/adapters/claude-cli.d.ts +63 -0
  56. package/lib/runtime/executor/adapters/claude-cli.js +250 -0
  57. package/lib/runtime/executor/adapters/http-openai.d.ts +9 -0
  58. package/lib/runtime/executor/adapters/http-openai.js +18 -0
  59. package/lib/runtime/executor/adapters/registry.d.ts +13 -0
  60. package/lib/runtime/executor/adapters/registry.js +29 -0
  61. package/lib/runtime/executor/adapters/types.d.ts +21 -0
  62. package/lib/runtime/executor/adapters/types.js +2 -0
  63. package/lib/runtime/executor/built-in-tools.d.ts +8 -0
  64. package/lib/runtime/executor/built-in-tools.js +40 -9
  65. package/lib/runtime/executor/index.d.ts +12 -2
  66. package/lib/runtime/executor/index.js +28 -1
  67. package/lib/runtime/executor/llm-task-executor.d.ts +35 -2
  68. package/lib/runtime/executor/llm-task-executor.js +97 -21
  69. package/lib/runtime/executor/node-context.d.ts +83 -0
  70. package/lib/runtime/executor/node-context.js +116 -0
  71. package/lib/runtime/executor/node-prompt-builder.d.ts +2 -0
  72. package/lib/runtime/executor/node-prompt-builder.js +2 -0
  73. package/lib/runtime/executor/shell-argv.d.ts +30 -0
  74. package/lib/runtime/executor/shell-argv.js +57 -0
  75. package/lib/runtime/executor/stream-completion.d.ts +11 -0
  76. package/lib/runtime/executor/stream-completion.js +10 -1
  77. package/lib/runtime/index.d.ts +5 -2
  78. package/lib/runtime/index.js +8 -1
  79. package/lib/runtime/program/index.d.ts +1 -0
  80. package/lib/runtime/program/index.js +17 -0
  81. package/lib/runtime/program/program-model.d.ts +74 -0
  82. package/lib/runtime/program/program-model.js +195 -0
  83. package/lib/runtime/projection/projection-engine.d.ts +10 -1
  84. package/lib/runtime/projection/projection-engine.js +25 -1
  85. package/lib/runtime/reducers/run-state-reducer.js +5 -0
  86. package/lib/runtime/scheduler/run-journal.d.ts +19 -1
  87. package/lib/runtime/scheduler/run-journal.js +40 -1
  88. package/lib/runtime/scheduler/scheduler.d.ts +30 -0
  89. package/lib/runtime/scheduler/scheduler.js +195 -19
  90. package/lib/runtime/verification/contract-exports.d.ts +24 -0
  91. package/lib/runtime/verification/contract-exports.js +201 -0
  92. package/lib/runtime/verification/index.d.ts +1 -0
  93. package/lib/runtime/verification/index.js +1 -0
  94. package/lib/runtime/verification/test-report-parsers.d.ts +37 -0
  95. package/lib/runtime/verification/test-report-parsers.js +180 -0
  96. package/lib/runtime/verification/verification-compiler.d.ts +67 -1
  97. package/lib/runtime/verification/verification-compiler.js +302 -25
  98. package/lib/runtime/verification/verification-manifest.d.ts +10 -0
  99. package/lib/runtime/verification/verification-manifest.js +18 -3
  100. package/lib/runtime/workspace/strategies/git-worktree.d.ts +9 -0
  101. package/lib/runtime/workspace/strategies/git-worktree.js +81 -0
  102. package/lib/sdk/README.md +61 -61
  103. package/lib/sdk/index.cjs +815 -810
  104. package/lib/sdk/index.d.ts +982 -982
  105. package/lib/sdk/index.types.ts +933 -933
  106. package/oxe/schemas/plan-agents.schema.json +122 -122
  107. package/oxe/schemas/plan.schema.json +85 -0
  108. package/oxe/templates/ACTIVE-RUN.template.json +32 -32
  109. package/oxe/templates/CAPABILITIES.template.md +7 -7
  110. package/oxe/templates/CAPABILITY.template.md +45 -45
  111. package/oxe/templates/CHECKPOINT.template.md +37 -37
  112. package/oxe/templates/CHECKPOINTS.template.md +7 -7
  113. package/oxe/templates/CODEBASE-DELTA.template.md +33 -33
  114. package/oxe/templates/CONFIG.md +105 -105
  115. package/oxe/templates/DISCUSS.template.md +44 -44
  116. package/oxe/templates/DOCS_BROWNFIELD_LAYOUT.md +55 -55
  117. package/oxe/templates/EXECUTION-RUNTIME.template.md +68 -68
  118. package/oxe/templates/FIXTURE-PACK.template.json +23 -23
  119. package/oxe/templates/FIXTURE-PACK.template.md +11 -11
  120. package/oxe/templates/GIT_HOOKS_OXE.md +52 -52
  121. package/oxe/templates/HYPOTHESES.template.md +33 -33
  122. package/oxe/templates/IMPLEMENTATION-PACK.template.json +42 -42
  123. package/oxe/templates/IMPLEMENTATION-PACK.template.md +16 -16
  124. package/oxe/templates/INVESTIGATION.template.md +38 -38
  125. package/oxe/templates/LESSONS-METRICS.template.json +13 -13
  126. package/oxe/templates/LESSONS.template.md +43 -43
  127. package/oxe/templates/MEMORY.template.md +49 -49
  128. package/oxe/templates/MILESTONES.template.md +17 -17
  129. package/oxe/templates/NOTES.template.md +16 -16
  130. package/oxe/templates/OBSERVATIONS.template.md +18 -18
  131. package/oxe/templates/PLAN-REVIEW.template.md +31 -31
  132. package/oxe/templates/PLAN.template.md +66 -66
  133. package/oxe/templates/PLUGINS.md +108 -108
  134. package/oxe/templates/REFERENCE-ANCHORS.template.md +9 -9
  135. package/oxe/templates/RESEARCH.template.md +57 -57
  136. package/oxe/templates/RESUME.template.md +49 -49
  137. package/oxe/templates/ROADMAP.template.md +44 -44
  138. package/oxe/templates/SECURITY.template.md +72 -72
  139. package/oxe/templates/SESSION.template.md +34 -34
  140. package/oxe/templates/SKILL.template.md +26 -26
  141. package/oxe/templates/SPEC.template.md +54 -54
  142. package/oxe/templates/STATE-REFERENCE.md +125 -125
  143. package/oxe/templates/STATE.md +30 -30
  144. package/oxe/templates/WORKFLOW_AUTHORING.md +93 -93
  145. package/oxe/templates/config.template.json +38 -38
  146. package/oxe/templates/plan-agent-messages-README.template.md +9 -9
  147. package/oxe/templates/plan-agents.template.json +30 -30
  148. package/oxe/templates/quick-agents.template.json +24 -24
  149. package/oxe/workflows/ask.md +96 -96
  150. package/oxe/workflows/capabilities.md +25 -25
  151. package/oxe/workflows/checkpoint.md +37 -37
  152. package/oxe/workflows/compact.md +44 -44
  153. package/oxe/workflows/dashboard.md +33 -33
  154. package/oxe/workflows/debug.md +34 -34
  155. package/oxe/workflows/discuss.md +86 -86
  156. package/oxe/workflows/execute.md +255 -255
  157. package/oxe/workflows/forensics.md +48 -48
  158. package/oxe/workflows/help.md +355 -355
  159. package/oxe/workflows/loop.md +67 -67
  160. package/oxe/workflows/milestone.md +95 -95
  161. package/oxe/workflows/next.md +45 -45
  162. package/oxe/workflows/obs.md +167 -167
  163. package/oxe/workflows/oxe.md +150 -149
  164. package/oxe/workflows/plan-agent.md +143 -143
  165. package/oxe/workflows/plan.md +525 -523
  166. package/oxe/workflows/project.md +55 -55
  167. package/oxe/workflows/quick.md +185 -185
  168. package/oxe/workflows/references/adaptive-discovery.md +27 -27
  169. package/oxe/workflows/references/flow-robustness-contract.md +80 -80
  170. package/oxe/workflows/references/legacy-brownfield.md +136 -136
  171. package/oxe/workflows/references/plan-agent-chat-protocol.md +99 -99
  172. package/oxe/workflows/references/plan-json-acceptance-program.md +143 -0
  173. package/oxe/workflows/references/reasoning-discovery.md +28 -28
  174. package/oxe/workflows/references/reasoning-execution.md +29 -29
  175. package/oxe/workflows/references/reasoning-planning.md +32 -32
  176. package/oxe/workflows/references/reasoning-review.md +29 -29
  177. package/oxe/workflows/references/reasoning-status.md +24 -24
  178. package/oxe/workflows/references/robustness-elevation.md +295 -295
  179. package/oxe/workflows/references/session-path-resolution.md +71 -71
  180. package/oxe/workflows/research.md +66 -66
  181. package/oxe/workflows/retro.md +117 -117
  182. package/oxe/workflows/review-pr.md +53 -53
  183. package/oxe/workflows/route.md +32 -32
  184. package/oxe/workflows/security.md +67 -67
  185. package/oxe/workflows/session.md +213 -213
  186. package/oxe/workflows/ship.md +142 -142
  187. package/oxe/workflows/skill.md +44 -44
  188. package/oxe/workflows/spec.md +569 -566
  189. package/oxe/workflows/ui-review.md +32 -32
  190. package/oxe/workflows/ui-spec.md +25 -25
  191. package/oxe/workflows/update.md +35 -35
  192. package/oxe/workflows/validate-gaps.md +45 -45
  193. package/oxe/workflows/verify-audit.md +73 -73
  194. package/oxe/workflows/verify.md +247 -244
  195. package/oxe/workflows/workflow-authoring.md +34 -34
  196. package/oxe/workflows/workstream.md +97 -97
  197. package/package.json +132 -129
  198. package/packages/runtime/package.json +18 -18
  199. package/packages/runtime/src/audit/audit-trail.ts +243 -243
  200. package/packages/runtime/src/audit/index.ts +2 -2
  201. package/packages/runtime/src/audit/policy-pack.ts +62 -62
  202. package/packages/runtime/src/compiler/graph-compiler.ts +336 -285
  203. package/packages/runtime/src/compiler/index.ts +1 -1
  204. package/packages/runtime/src/context/context-pack-builder.ts +339 -339
  205. package/packages/runtime/src/context/context-pack-store.ts +197 -197
  206. package/packages/runtime/src/context/context-profiles.ts +60 -60
  207. package/packages/runtime/src/context/index.ts +3 -3
  208. package/packages/runtime/src/decision/decision-engine.ts +174 -174
  209. package/packages/runtime/src/decision/decision-memo.ts +211 -211
  210. package/packages/runtime/src/decision/index.ts +2 -2
  211. package/packages/runtime/src/delivery/branch-manager.ts +91 -91
  212. package/packages/runtime/src/delivery/ci-checks.ts +285 -285
  213. package/packages/runtime/src/delivery/delivery-records.ts +75 -75
  214. package/packages/runtime/src/delivery/index.ts +5 -5
  215. package/packages/runtime/src/delivery/pr-manager.ts +112 -112
  216. package/packages/runtime/src/delivery/promotion-pipeline.ts +342 -334
  217. package/packages/runtime/src/events/bus.ts +92 -92
  218. package/packages/runtime/src/events/catalog.ts +45 -34
  219. package/packages/runtime/src/events/envelope.ts +14 -14
  220. package/packages/runtime/src/events/index.ts +3 -3
  221. package/packages/runtime/src/evidence/evidence-store.ts +130 -130
  222. package/packages/runtime/src/evidence/index.ts +1 -1
  223. package/packages/runtime/src/executor/adapters/claude-cli.ts +285 -0
  224. package/packages/runtime/src/executor/adapters/http-openai.ts +16 -0
  225. package/packages/runtime/src/executor/adapters/registry.ts +33 -0
  226. package/packages/runtime/src/executor/adapters/types.ts +24 -0
  227. package/packages/runtime/src/executor/built-in-tools.ts +36 -8
  228. package/packages/runtime/src/executor/index.ts +12 -2
  229. package/packages/runtime/src/executor/llm-task-executor.ts +125 -25
  230. package/packages/runtime/src/executor/node-context.ts +210 -0
  231. package/packages/runtime/src/executor/node-prompt-builder.ts +5 -0
  232. package/packages/runtime/src/executor/shell-argv.ts +66 -0
  233. package/packages/runtime/src/executor/stream-completion.ts +16 -1
  234. package/packages/runtime/src/gate/gate-manager.ts +289 -289
  235. package/packages/runtime/src/gate/index.ts +1 -1
  236. package/packages/runtime/src/index.ts +54 -44
  237. package/packages/runtime/src/models/attempt.ts +19 -19
  238. package/packages/runtime/src/models/evidence.ts +21 -21
  239. package/packages/runtime/src/models/gate-decision.ts +25 -25
  240. package/packages/runtime/src/models/index.ts +8 -8
  241. package/packages/runtime/src/models/run.ts +24 -24
  242. package/packages/runtime/src/models/session.ts +11 -11
  243. package/packages/runtime/src/models/verification-result.ts +10 -10
  244. package/packages/runtime/src/models/work-item.ts +25 -25
  245. package/packages/runtime/src/models/workspace.ts +31 -31
  246. package/packages/runtime/src/plugins/capability-adapter.ts +313 -313
  247. package/packages/runtime/src/plugins/capability-matrix.ts +126 -126
  248. package/packages/runtime/src/plugins/index.ts +5 -5
  249. package/packages/runtime/src/plugins/plugin-abi.ts +106 -106
  250. package/packages/runtime/src/plugins/plugin-manifest.ts +118 -118
  251. package/packages/runtime/src/plugins/plugin-registry.ts +241 -241
  252. package/packages/runtime/src/policy/index.ts +1 -1
  253. package/packages/runtime/src/policy/policy-engine.ts +330 -330
  254. package/packages/runtime/src/program/index.ts +1 -0
  255. package/packages/runtime/src/program/program-model.ts +233 -0
  256. package/packages/runtime/src/projection/index.ts +1 -1
  257. package/packages/runtime/src/projection/projection-engine.ts +361 -328
  258. package/packages/runtime/src/reducers/debug-reducer.ts +36 -36
  259. package/packages/runtime/src/reducers/index.ts +2 -2
  260. package/packages/runtime/src/reducers/run-state-reducer.ts +329 -326
  261. package/packages/runtime/src/scheduler/agent-registry.ts +132 -132
  262. package/packages/runtime/src/scheduler/agent-roles.ts +109 -109
  263. package/packages/runtime/src/scheduler/index.ts +4 -4
  264. package/packages/runtime/src/scheduler/multi-agent-coordinator.ts +1017 -1017
  265. package/packages/runtime/src/scheduler/run-journal.ts +105 -62
  266. package/packages/runtime/src/scheduler/scheduler.ts +1144 -938
  267. package/packages/runtime/src/verification/contract-exports.ts +203 -0
  268. package/packages/runtime/src/verification/index.ts +3 -2
  269. package/packages/runtime/src/verification/test-report-parsers.ts +198 -0
  270. package/packages/runtime/src/verification/verification-compiler.ts +766 -438
  271. package/packages/runtime/src/verification/verification-manifest.ts +281 -256
  272. package/packages/runtime/src/workspace/index.ts +5 -5
  273. package/packages/runtime/src/workspace/strategies/ephemeral-container.ts +126 -126
  274. package/packages/runtime/src/workspace/strategies/git-worktree.ts +150 -87
  275. package/packages/runtime/src/workspace/strategies/inplace.ts +38 -38
  276. package/packages/runtime/src/workspace/workspace-manager.ts +16 -16
  277. package/packages/runtime/tsconfig.json +23 -23
  278. package/vscode-extension/.vscodeignore +9 -9
  279. package/vscode-extension/package.json +193 -193
  280. package/vscode-extension/src/extension.js +320 -320
  281. package/vscode-extension/src/shared/contextLoader.js +137 -137
  282. package/vscode-extension/src/shared/contractBuilder.js +159 -159
  283. package/vscode-extension/src/shared/stateReader.js +101 -101
  284. package/docs/oxe-artifact-map.html +0 -1172
@@ -0,0 +1,433 @@
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
+ const ACCEPT_RE = /^A\d+$/;
18
+ const DECISION_RE = /^D-\d+$/;
19
+ const COMPLEXITY = new Set(['XS', 'S', 'M', 'L', 'XL']);
20
+
21
+ function planJsonPathFor(planMdPath) {
22
+ return planMdPath ? path.join(path.dirname(planMdPath), 'PLAN.json') : null;
23
+ }
24
+
25
+ function isStringArray(value, re) {
26
+ return Array.isArray(value) && value.every((v) => typeof v === 'string' && v.trim() && (!re || re.test(v)));
27
+ }
28
+
29
+ /** Erros de schema (lista vazia = válido). Mensagens com o caminho JSON do problema. */
30
+ function validatePlanJson(doc) {
31
+ const errors = [];
32
+ if (!doc || typeof doc !== 'object' || Array.isArray(doc)) return ['$: PLAN.json deve ser um objeto'];
33
+ if (doc.schema_version !== 1) errors.push('$.schema_version: deve ser 1');
34
+ if (doc.phase != null && !(typeof doc.phase === 'string' && /^F\d+$/.test(doc.phase))) errors.push('$.phase: deve ser "F<n>" ou null');
35
+ if (!Array.isArray(doc.tasks) || doc.tasks.length === 0) {
36
+ errors.push('$.tasks: deve ser uma lista com ao menos 1 tarefa');
37
+ return errors;
38
+ }
39
+ doc.tasks.forEach((task, i) => {
40
+ const at = `$.tasks[${i}]`;
41
+ if (!task || typeof task !== 'object') {
42
+ errors.push(`${at}: deve ser objeto`);
43
+ return;
44
+ }
45
+ if (typeof task.id !== 'string' || !TASK_ID_RE.test(task.id)) errors.push(`${at}.id: deve casar ^T\\d+$`);
46
+ if (typeof task.title !== 'string' || !task.title.trim()) errors.push(`${at}.title: obrigatório`);
47
+ if (!Number.isInteger(task.wave) || task.wave < 1) errors.push(`${at}.wave: inteiro ≥ 1`);
48
+ if (task.depends_on != null && !isStringArray(task.depends_on, TASK_ID_RE)) errors.push(`${at}.depends_on: lista de ids T<n>`);
49
+ if (task.files != null && !isStringArray(task.files)) errors.push(`${at}.files: lista de caminhos`);
50
+ if (task.acceptance != null && !isStringArray(task.acceptance, ACCEPT_RE)) errors.push(`${at}.acceptance: lista de A<n>`);
51
+ if (task.decisions != null && !isStringArray(task.decisions, DECISION_RE)) errors.push(`${at}.decisions: lista de D-<n>`);
52
+ if (task.complexity != null && !COMPLEXITY.has(task.complexity)) errors.push(`${at}.complexity: XS|S|M|L|XL`);
53
+ if (task.done != null && typeof task.done !== 'boolean') errors.push(`${at}.done: boolean`);
54
+ if (task.done_at != null && typeof task.done_at !== 'string') errors.push(`${at}.done_at: data ISO`);
55
+ if (task.done_commit != null && typeof task.done_commit !== 'string') errors.push(`${at}.done_commit: sha do checkpoint`);
56
+ if (task.reopened != null && !Array.isArray(task.reopened)) errors.push(`${at}.reopened: histórico de reaberturas`);
57
+ if (task.commit != null && (typeof task.commit !== 'string' || !task.commit.trim())) errors.push(`${at}.commit: mensagem do checkpoint`);
58
+ if (task.kind != null && !['code', 'spike', 'verify_only', 'external_delivery'].includes(task.kind)) errors.push(`${at}.kind: code | spike | verify_only | external_delivery`);
59
+ if (task.question != null && typeof task.question !== 'string') errors.push(`${at}.question: texto`);
60
+ if (task.gate != null && (typeof task.gate !== 'object' || Array.isArray(task.gate) || typeof task.gate.reason !== 'string')) errors.push(`${at}.gate: { kind?, reason }`);
61
+ if (task.blocked_by != null && !isStringArray(task.blocked_by)) errors.push(`${at}.blocked_by: lista de dependências externas`);
62
+ if (task.verify != null) {
63
+ if (typeof task.verify !== 'object' || Array.isArray(task.verify)) errors.push(`${at}.verify: objeto`);
64
+ else if (task.verify.commands != null && !isStringArray(task.verify.commands)) errors.push(`${at}.verify.commands: lista de comandos`);
65
+ }
66
+ });
67
+ if (doc.acceptance_tests != null) {
68
+ if (!Array.isArray(doc.acceptance_tests)) errors.push('$.acceptance_tests: lista');
69
+ else doc.acceptance_tests.forEach((entry, i) => {
70
+ const at = `$.acceptance_tests[${i}]`;
71
+ if (!entry || typeof entry !== 'object') return errors.push(`${at}: deve ser objeto`);
72
+ const hasId = typeof entry.id === 'string' && /^[A-Za-z][\w-]*$/.test(entry.id);
73
+ if (entry.id != null && !hasId) errors.push(`${at}.id: identificador (ex.: "CR-03" ou "lint-voice")`);
74
+ if (entry.criterion != null && (typeof entry.criterion !== 'string' || !ACCEPT_RE.test(entry.criterion))) errors.push(`${at}.criterion: A<n>`);
75
+ // Sem critério só para prova transversal (ex.: CR constraint): precisa de id próprio e resolves.
76
+ 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)`);
77
+ if (!isStringArray(entry.files) || entry.files.length === 0) errors.push(`${at}.files: lista com ao menos 1 caminho`);
78
+ if (typeof entry.command !== 'string' || !entry.command.trim()) errors.push(`${at}.command: obrigatório`);
79
+ if (entry.proves != null && !isStringArray(entry.proves)) errors.push(`${at}.proves: lista de nomes de teste`);
80
+ if (entry.resolves != null && !isStringArray(entry.resolves, /^CR-\d+$/)) errors.push(`${at}.resolves: lista de CR-NN`);
81
+ if (entry.version != null && !(Number.isInteger(entry.version) && entry.version >= 1)) errors.push(`${at}.version: inteiro ≥ 1`);
82
+ });
83
+ }
84
+ if (doc.budget != null) {
85
+ const b = doc.budget;
86
+ if (typeof b !== 'object' || Array.isArray(b)) errors.push('$.budget: { turns?, usd?, max_retries? }');
87
+ else {
88
+ if (b.turns != null && !(Number.isInteger(b.turns) && b.turns > 0)) errors.push('$.budget.turns: inteiro > 0');
89
+ if (b.usd != null && !(typeof b.usd === 'number' && b.usd > 0)) errors.push('$.budget.usd: número > 0');
90
+ if (b.max_retries != null && !(Number.isInteger(b.max_retries) && b.max_retries >= 0)) errors.push('$.budget.max_retries: inteiro ≥ 0');
91
+ }
92
+ }
93
+ if (doc.phase_gates != null) {
94
+ if (!Array.isArray(doc.phase_gates)) errors.push('$.phase_gates: lista');
95
+ else doc.phase_gates.forEach((gate, i) => {
96
+ const at = `$.phase_gates[${i}]`;
97
+ if (!gate || typeof gate !== 'object' || Array.isArray(gate)) return errors.push(`${at}: deve ser objeto`);
98
+ if (typeof gate.id !== 'string' || !/^[A-Za-z][\w-]*$/.test(gate.id)) errors.push(`${at}.id: identificador (ex.: "typecheck")`);
99
+ if (gate.kind != null && !['command', 'ci'].includes(gate.kind)) errors.push(`${at}.kind: command | ci`);
100
+ if (gate.kind !== 'ci' && (typeof gate.command !== 'string' || !gate.command.trim())) errors.push(`${at}.command: obrigatório (exceto kind: ci)`);
101
+ if (gate.when != null && !['phase_verify', 'program_close'].includes(gate.when)) errors.push(`${at}.when: phase_verify | program_close`);
102
+ if (gate.runner != null && (typeof gate.runner !== 'string' || !gate.runner.includes('{command}'))) errors.push(`${at}.runner: modelo com {command}`);
103
+ if (gate.timeout_ms != null && !(Number.isInteger(gate.timeout_ms) && gate.timeout_ms > 0)) errors.push(`${at}.timeout_ms: inteiro > 0`);
104
+ });
105
+ }
106
+ return errors;
107
+ }
108
+
109
+ /** PLAN.json → mesmo formato de `sdk.parsePlan` (o graph compiler e o verify não mudam). */
110
+ function planJsonToParsedPlan(doc) {
111
+ const spikeLib = require('./oxe-spike.cjs');
112
+ const tasks = doc.tasks.map((task) => {
113
+ const commands = task.verify && Array.isArray(task.verify.commands) ? task.verify.commands.map((c) => c.trim()).filter(Boolean) : [];
114
+ // OXB-007: a spike writes only its report and is verified by it (question, answer, evidence).
115
+ const spike = task.kind === 'spike';
116
+ if (spike) commands.push(spikeLib.spikeVerifyCommand(task.id));
117
+ const files = Array.isArray(task.files) && task.files.length ? [...task.files] : spike ? [spikeLib.spikeReportPath(task.id)] : [];
118
+ return {
119
+ id: task.id,
120
+ title: task.title,
121
+ wave: task.wave,
122
+ dependsOn: Array.isArray(task.depends_on) ? [...task.depends_on] : [],
123
+ files,
124
+ verifyCommand: commands.length ? [...new Set(commands)].join(' && ') : null,
125
+ aceite: Array.isArray(task.acceptance) ? [...task.acceptance] : [],
126
+ decisions: Array.isArray(task.decisions) ? [...task.decisions] : [],
127
+ done: task.done === true,
128
+ meta: {
129
+ source: 'PLAN.json',
130
+ complexity: task.complexity || null,
131
+ ...(typeof task.commit === 'string' && task.commit.trim() ? { commit: task.commit.trim() } : {}),
132
+ ...(task.done_commit ? { done_commit: task.done_commit } : {}),
133
+ ...(task.kind ? { kind: task.kind } : {}),
134
+ ...(typeof task.question === 'string' ? { question: task.question } : {}),
135
+ ...(task.gate ? { gate: task.gate } : {}),
136
+ ...(Array.isArray(task.blocked_by) && task.blocked_by.length ? { blocked_by: [...task.blocked_by] } : {}),
137
+ },
138
+ };
139
+ });
140
+ const waves = {};
141
+ for (const task of tasks) {
142
+ if (!waves[task.wave]) waves[task.wave] = [];
143
+ waves[task.wave].push(task.id);
144
+ }
145
+ // Testes de aceite do plano (1.19): escritos antes da execução, congelados por hash no compile.
146
+ const acceptanceTests = (Array.isArray(doc.acceptance_tests) ? doc.acceptance_tests : []).map((entry) => ({
147
+ id: typeof entry.id === 'string' ? entry.id : null,
148
+ criterion: typeof entry.criterion === 'string' ? entry.criterion : null,
149
+ files: [...new Set(entry.files.map((f) => String(f).trim()))],
150
+ command: entry.command.trim(),
151
+ proves: Array.isArray(entry.proves) ? entry.proves.map((name) => String(name).trim()).filter(Boolean) : [],
152
+ resolves: Array.isArray(entry.resolves) ? [...entry.resolves] : [],
153
+ version: Number.isInteger(entry.version) ? entry.version : 1,
154
+ }));
155
+ // Gates do projeto (1.21, OXB-020): rodam uma vez no verify da fase; normalizados por oxe-phase-gates.cjs.
156
+ const phaseGates = Array.isArray(doc.phase_gates) ? doc.phase_gates.map((gate) => ({ ...gate })) : [];
157
+ // Teto da execução (1.21, OXB-023): turnos/US$ por run e tentativas por tarefa.
158
+ const budget = doc.budget && typeof doc.budget === 'object' && !Array.isArray(doc.budget) ? { ...doc.budget } : null;
159
+ return { tasks, waves, totalTasks: tasks.length, source: 'PLAN.json', phase: doc.phase || null, acceptanceTests, phaseGates, budget };
160
+ }
161
+
162
+ /**
163
+ * Plano do runtime: PLAN.json válido ao lado do PLAN.md vence; inválido é erro (não cai em
164
+ * silêncio para o markdown); ausente → parser markdown com `source: 'PLAN.md'`.
165
+ */
166
+ function readPlanArtifact(planMdPath, planMdText, parseMarkdown) {
167
+ const jsonPath = planJsonPathFor(planMdPath);
168
+ if (jsonPath && fs.existsSync(jsonPath)) {
169
+ let doc;
170
+ try {
171
+ doc = JSON.parse(fs.readFileSync(jsonPath, 'utf8'));
172
+ } catch (err) {
173
+ throw new Error(`PLAN.json inválido (${jsonPath}): ${err.message}`);
174
+ }
175
+ const errors = validatePlanJson(doc);
176
+ if (errors.length) throw new Error(`PLAN.json não segue o schema (${jsonPath}):\n - ${errors.join('\n - ')}`);
177
+ return planJsonToParsedPlan(doc);
178
+ }
179
+ const parsed = parseMarkdown(planMdText || '');
180
+ return { ...parsed, source: 'PLAN.md' };
181
+ }
182
+
183
+ /**
184
+ * OXB-025: a task that finished (verify green) is marked `done` in PLAN.json with when and which checkpoint, so the
185
+ * next compile skips it instead of paying for it again. Atomic write; the rest of the document is kept as is.
186
+ * @returns {boolean} whether PLAN.json changed
187
+ */
188
+ function markPlanTaskDone(planMdPath, taskId, info = {}) {
189
+ const jsonPath = planJsonPathFor(planMdPath);
190
+ if (!jsonPath || !fs.existsSync(jsonPath)) return false;
191
+ let doc;
192
+ try {
193
+ doc = JSON.parse(fs.readFileSync(jsonPath, 'utf8'));
194
+ } catch {
195
+ return false;
196
+ }
197
+ const task = Array.isArray(doc.tasks) ? doc.tasks.find((t) => t && t.id === taskId) : null;
198
+ if (!task) return false;
199
+ if (task.done === true && (!info.commit || task.done_commit === info.commit)) return false;
200
+ task.done = true;
201
+ task.done_at = info.at || new Date().toISOString();
202
+ if (info.commit) task.done_commit = info.commit;
203
+ const tmp = `${jsonPath}.${process.pid}.tmp`;
204
+ fs.writeFileSync(tmp, `${JSON.stringify(doc, null, 2)}\n`, 'utf8');
205
+ fs.renameSync(tmp, jsonPath);
206
+ return true;
207
+ }
208
+
209
+ function hasCycle(tasks) {
210
+ const deps = new Map(tasks.map((t) => [t.id, t.dependsOn || []]));
211
+ const state = new Map();
212
+ const visit = (id) => {
213
+ if (state.get(id) === 1) return true;
214
+ if (state.get(id) === 2) return false;
215
+ state.set(id, 1);
216
+ for (const dep of deps.get(id) || []) if (deps.has(dep) && visit(dep)) return true;
217
+ state.set(id, 2);
218
+ return false;
219
+ };
220
+ return tasks.some((t) => visit(t.id));
221
+ }
222
+
223
+ /**
224
+ * Lint estrutural do plano: torna mecânicas as regras de quality gate de `oxe/workflows/plan.md`.
225
+ * @param {{ plan: any, spec?: any, pack?: any, phase?: any, maxTasksPerWave?: number }} input
226
+ * @returns {{ ok: boolean, errors: string[], warnings: string[] }}
227
+ */
228
+ function lintPlan(input) {
229
+ const errors = [];
230
+ const warnings = [];
231
+ const tasks = input.plan && Array.isArray(input.plan.tasks) ? input.plan.tasks : [];
232
+ if (tasks.length === 0) errors.push('plano sem tarefas');
233
+ const { lintSpikeTask } = require('./oxe-spike.cjs');
234
+ for (const task of tasks) if (!task.done) errors.push(...lintSpikeTask(task));
235
+ if (input.plan && input.plan.source === 'PLAN.md') {
236
+ warnings.push('PLAN.json ausente: o runtime usa o parser heurístico do PLAN.md (grave PLAN.json no /oxe-plan)');
237
+ }
238
+
239
+ const ids = new Map();
240
+ for (const task of tasks) ids.set(task.id, (ids.get(task.id) || 0) + 1);
241
+ for (const [id, count] of ids) if (count > 1) errors.push(`id duplicado: ${id} (${count}x)`);
242
+ const byId = new Map(tasks.map((t) => [t.id, t]));
243
+
244
+ for (const task of tasks) {
245
+ if (task.wave == null) errors.push(`${task.id}: sem onda`);
246
+ for (const dep of task.dependsOn || []) {
247
+ const target = byId.get(dep);
248
+ if (!target) errors.push(`${task.id}: depende de ${dep}, que não existe`);
249
+ else if (dep === task.id) errors.push(`${task.id}: depende de si mesma`);
250
+ else if (target.wave != null && task.wave != null && target.wave >= task.wave) {
251
+ errors.push(`${task.id} (onda ${task.wave}) depende de ${dep} (onda ${target.wave}): a dependência deve estar numa onda anterior`);
252
+ }
253
+ }
254
+ if (!task.verifyCommand && !task.done) warnings.push(`${task.id}: sem comando de verificação`);
255
+ }
256
+ if (tasks.length && hasCycle(tasks)) errors.push('dependência circular entre tarefas');
257
+
258
+ const waves = new Map();
259
+ for (const task of tasks) {
260
+ // Uma tarefa concluída não roda de novo: num replan ela não disputa escopo nem lugar na onda (OXB-015).
261
+ if (task.wave == null || task.done) continue;
262
+ if (!waves.has(task.wave)) waves.set(task.wave, []);
263
+ waves.get(task.wave).push(task);
264
+ }
265
+ const waveNumbers = [...waves.keys()].sort((a, b) => a - b);
266
+ waveNumbers.forEach((wave, i) => {
267
+ if (i > 0 && wave !== waveNumbers[i - 1] + 1) warnings.push(`onda ${waveNumbers[i - 1] + 1} vazia (ondas: ${waveNumbers.join(', ')})`);
268
+ });
269
+ for (const [wave, list] of waves) {
270
+ if (input.maxTasksPerWave && list.length > input.maxTasksPerWave) {
271
+ errors.push(`onda ${wave}: ${list.length} tarefas > plan_max_tasks_per_wave (${input.maxTasksPerWave})`);
272
+ }
273
+ const owner = new Map();
274
+ for (const task of list) {
275
+ for (const file of task.files || []) {
276
+ if (owner.has(file)) errors.push(`onda ${wave}: ${owner.get(file)} e ${task.id} escrevem ${file} (escopos devem ser disjuntos na mesma onda)`);
277
+ else owner.set(file, task.id);
278
+ }
279
+ }
280
+ }
281
+
282
+ const criteria = input.spec && Array.isArray(input.spec.criteria) ? input.spec.criteria.map((c) => c.id) : [];
283
+ const covered = new Set(tasks.flatMap((t) => t.aceite || []));
284
+ if (criteria.length) {
285
+ const known = new Set(criteria);
286
+ for (const task of tasks) {
287
+ for (const ref of task.aceite || []) if (!known.has(ref)) errors.push(`${task.id}: aceite ${ref} não existe na SPEC`);
288
+ }
289
+ }
290
+
291
+ const phase = input.phase || null;
292
+ if (phase && Array.isArray(phase.acceptance) && phase.acceptance.length) {
293
+ const allowed = new Set(phase.acceptance);
294
+ const outside = [...covered].filter((ref) => !allowed.has(ref));
295
+ if (outside.length) errors.push(`fase ${phase.id}: o plano usa A* de outras fases: ${outside.join(', ')}`);
296
+ const missing = phase.acceptance.filter((ref) => !covered.has(ref));
297
+ if (missing.length) errors.push(`fase ${phase.id}: A* da fase sem tarefa: ${missing.join(', ')}`);
298
+ if (input.plan && input.plan.phase && input.plan.phase !== phase.id) {
299
+ errors.push(`PLAN.json declara fase ${input.plan.phase}, mas a fase ativa é ${phase.id}`);
300
+ }
301
+ } else if (criteria.length) {
302
+ const missing = criteria.filter((ref) => !covered.has(ref));
303
+ if (missing.length) warnings.push(`A* da SPEC sem tarefa: ${missing.join(', ')}`);
304
+ }
305
+
306
+ // Aceite congelado: o teste que prova o A* é do plano, não do executor.
307
+ const acceptanceTests = input.plan && Array.isArray(input.plan.acceptanceTests) ? input.plan.acceptanceTests : [];
308
+ const testedCriteria = new Set(acceptanceTests.map((entry) => entry.criterion).filter(Boolean));
309
+ const ownedByTasks = new Map();
310
+ for (const task of tasks) for (const file of task.files || []) ownedByTasks.set(file, task.id);
311
+ for (const entry of acceptanceTests) {
312
+ if (entry.criterion && criteria.length && !criteria.includes(entry.criterion)) errors.push(`teste de aceite ${entry.criterion}: critério não existe na SPEC`);
313
+ for (const file of entry.files) {
314
+ if (input.projectRoot && !fs.existsSync(path.resolve(input.projectRoot, file))) {
315
+ errors.push(`teste de aceite ${entry.criterion}: ${file} não existe (escreva-o no /oxe-plan, antes da execução)`);
316
+ }
317
+ if (ownedByTasks.has(file)) {
318
+ errors.push(`teste de aceite ${entry.criterion}: ${file} está no escopo de ${ownedByTasks.get(file)} — o executor não pode escrever o próprio aceite`);
319
+ }
320
+ }
321
+ }
322
+ // Prova executada: o runner precisa listar os nomes dos testes que passaram.
323
+ for (const entry of acceptanceTests) {
324
+ if (!entry.proves || !entry.proves.length) continue;
325
+ const verbose = /--reporter[= ]verbose|--verbose|--test-reporter[= ](tap|spec)|node\s+--test|\s-v\b|junit/i.test(entry.command);
326
+ 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)`);
327
+ }
328
+ // Emenda de SPEC (CR spec_gap): teste de aceite de versão anterior está stale até ser reescrito.
329
+ const required = input.requiredVersions instanceof Map ? input.requiredVersions : new Map();
330
+ for (const [criterion, version] of required) {
331
+ const entry = acceptanceTests.find((a) => a.criterion === criterion);
332
+ if (!entry) errors.push(`${criterion}@v${version}: emenda sem teste de aceite (escreva-o com "version": ${version})`);
333
+ else if ((entry.version || 1) < version) errors.push(`${criterion}: teste de aceite v${entry.version || 1} está stale — a SPEC foi emendada para v${version}`);
334
+ }
335
+ const scopeAcceptance = phase && Array.isArray(phase.acceptance) && phase.acceptance.length ? phase.acceptance : [...covered];
336
+ const untested = scopeAcceptance.filter((ref) => !testedCriteria.has(ref));
337
+ if (untested.length) {
338
+ (input.requireAcceptanceTests ? errors : warnings).push(`A* sem teste de aceite congelado: ${untested.join(', ')}`);
339
+ }
340
+
341
+ const pack = input.pack && Array.isArray(input.pack.tasks) ? input.pack.tasks : null;
342
+ if (pack) {
343
+ const packIds = new Set(pack.map((t) => String((t && (t.id || t.task_id)) || '').trim()));
344
+ for (const task of tasks) {
345
+ if ((task.files || []).length && !task.done && !packIds.has(task.id)) {
346
+ errors.push(`${task.id}: tarefa mutável sem entrada no IMPLEMENTATION-PACK`);
347
+ }
348
+ }
349
+ // OXB-022: the very rules the execute preflight applies — nothing passes here and blocks there.
350
+ // (spikes declare a docs_only pack entry: they write only their report in .oxe/spikes/)
351
+ const { validatePackTask } = require('./oxe-rationality.cjs');
352
+ const pending = new Set(tasks.filter((task) => !task.done).map((task) => task.id));
353
+ for (const entry of pack) {
354
+ const id = String((entry && (entry.id || entry.task_id)) || '').trim();
355
+ if (id && !pending.has(id)) continue;
356
+ errors.push(...validatePackTask(entry).gaps);
357
+ }
358
+ }
359
+
360
+ return { ok: errors.length === 0, errors, warnings };
361
+ }
362
+
363
+ /**
364
+ * 1.21.1 (OXB-053/046): the task(s) that complete each criterion. A criterion's own verification (the SPEC
365
+ * "Como verificar" / its phase-wide acceptance test) can only pass after the LAST of its tasks: in the oxespace 1.5.0
366
+ * 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).
367
+ * The closer is the single task of the criterion that no other task of the same criterion depends on (transitively).
368
+ * With several such sinks the criterion is only checked at phase verify.
369
+ * @returns {Map<string, { closer: string|null, tasks: string[], sinks: string[] }>}
370
+ */
371
+ function criterionClosers(tasks) {
372
+ const list = Array.isArray(tasks) ? tasks : [];
373
+ const byId = new Map(list.map((t) => [t.id, t]));
374
+ const deps = (t) => (Array.isArray(t.dependsOn) ? t.dependsOn : Array.isArray(t.depends_on) ? t.depends_on : []);
375
+ const ancestors = new Map();
376
+ const ancestorsOf = (id, seen = new Set()) => {
377
+ if (ancestors.has(id)) return ancestors.get(id);
378
+ const out = new Set();
379
+ for (const d of deps(byId.get(id) || {})) {
380
+ if (seen.has(d)) continue;
381
+ seen.add(d);
382
+ out.add(d);
383
+ for (const a of ancestorsOf(d, seen)) out.add(a);
384
+ }
385
+ ancestors.set(id, out);
386
+ return out;
387
+ };
388
+ const result = new Map();
389
+ const criteria = new Set(list.flatMap((t) => (Array.isArray(t.aceite) ? t.aceite : Array.isArray(t.acceptance) ? t.acceptance : [])));
390
+ for (const criterion of criteria) {
391
+ const members = list.filter((t) => (t.aceite || t.acceptance || []).includes(criterion)).map((t) => t.id);
392
+ const sinks = members.filter((id) => !members.some((other) => other !== id && ancestorsOf(other).has(id)));
393
+ result.set(criterion, { closer: sinks.length === 1 ? sinks[0] : null, tasks: members, sinks });
394
+ }
395
+ return result;
396
+ }
397
+
398
+ /**
399
+ * 1.21.1: reopens a done task (rework after a CR or a failed phase verify). Since execute recompiles from the plan and
400
+ * skips done tasks, "run it again" means reopening it explicitly — never a stale graph re-running finished work.
401
+ * @returns {boolean} whether PLAN.json changed
402
+ */
403
+ function markPlanTaskOpen(planMdPath, taskId, info = {}) {
404
+ const jsonPath = planJsonPathFor(planMdPath);
405
+ if (!jsonPath || !fs.existsSync(jsonPath)) return false;
406
+ let doc;
407
+ try {
408
+ doc = JSON.parse(fs.readFileSync(jsonPath, 'utf8'));
409
+ } catch {
410
+ return false;
411
+ }
412
+ const task = Array.isArray(doc.tasks) ? doc.tasks.find((t) => t && t.id === taskId) : null;
413
+ if (!task || task.done !== true) return false;
414
+ task.done = false;
415
+ task.reopened = [...(Array.isArray(task.reopened) ? task.reopened : []), { at: new Date().toISOString(), by: info.by || null, previous_commit: task.done_commit || null }];
416
+ delete task.done_at;
417
+ delete task.done_commit;
418
+ const tmp = `${jsonPath}.${process.pid}.tmp`;
419
+ fs.writeFileSync(tmp, `${JSON.stringify(doc, null, 2)}\n`, 'utf8');
420
+ fs.renameSync(tmp, jsonPath);
421
+ return true;
422
+ }
423
+
424
+ module.exports = {
425
+ markPlanTaskOpen,
426
+ criterionClosers,
427
+ markPlanTaskDone,
428
+ planJsonPathFor,
429
+ validatePlanJson,
430
+ planJsonToParsedPlan,
431
+ readPlanArtifact,
432
+ lintPlan,
433
+ };
@@ -1,95 +1,95 @@
1
- 'use strict';
2
-
3
- const path = require('path');
4
- const oxePlugins = require('./oxe-plugins.cjs');
5
-
6
- const DEFAULT_COLORS = Object.freeze({
7
- green: '\x1b[32m',
8
- yellow: '\x1b[33m',
9
- dim: '\x1b[2m',
10
- red: '\x1b[31m',
11
- reset: '\x1b[0m',
12
- });
13
-
14
- function defaultUseAnsiColors() {
15
- if (process.env.NO_COLOR) return false;
16
- if (process.env.FORCE_COLOR === '0') return false;
17
- return process.stdout.isTTY === true;
18
- }
19
-
20
- /**
21
- * Executa o subcomando `plugins` sem acoplar parsing e rendering ao CLI principal.
22
- * @param {string[]} argv
23
- * @param {{
24
- * plugins?: typeof oxePlugins,
25
- * cwd?: string,
26
- * colors?: typeof DEFAULT_COLORS,
27
- * useAnsiColors?: () => boolean,
28
- * log?: (...args: unknown[]) => void,
29
- * error?: (...args: unknown[]) => void,
30
- * }} [options]
31
- * @returns {number} exit code
32
- */
33
- function runPluginCommand(argv, options = {}) {
34
- const plugins = options.plugins || oxePlugins;
35
- const colors = options.colors || DEFAULT_COLORS;
36
- const useAnsiColors = options.useAnsiColors || defaultUseAnsiColors;
37
- const log = options.log || console.log;
38
- const error = options.error || console.error;
39
-
40
- let pluginsDir = options.cwd || process.cwd();
41
- const pluginsArgv = argv.slice();
42
- for (let i = 0; i < pluginsArgv.length; i++) {
43
- if (pluginsArgv[i] === '--dir' && pluginsArgv[i + 1]) {
44
- pluginsDir = path.resolve(pluginsArgv[i + 1]);
45
- pluginsArgv.splice(i, 2);
46
- i--;
47
- }
48
- }
49
-
50
- const c = useAnsiColors();
51
- const subCmd = pluginsArgv[0] || 'list';
52
- const pluginTarget = pluginsArgv[1] || '';
53
-
54
- if (subCmd === 'list') {
55
- const result = plugins.loadPlugins(pluginsDir);
56
- log(`\n ${c ? colors.green : ''}Plugins carregados:${c ? colors.reset : ''} ${result.plugins.length}`);
57
- for (const plugin of result.plugins) {
58
- log(` • ${plugin.name}${plugin.version ? ` (${plugin.version})` : ''} — hooks: ${Object.keys(plugin.hooks).join(', ')}`);
59
- }
60
- if (result.errors.length) {
61
- log(`\n ${c ? colors.yellow : ''}Erros:${c ? colors.reset : ''}`);
62
- for (const pluginError of result.errors) {
63
- log(` ✗ ${pluginError.file}: ${pluginError.error}`);
64
- }
65
- }
66
- return 0;
67
- }
68
-
69
- if (subCmd === 'install' && pluginTarget) {
70
- const src = pluginTarget.startsWith('npm:') ? pluginTarget.slice(4) : pluginTarget;
71
- const version = pluginsArgv[2] || '';
72
- log(` Instalando plugin: ${src}${version ? `@${version}` : ''}...`);
73
- const result = plugins.installNpmPlugin(pluginsDir, src, version || undefined);
74
- if (result.ok) {
75
- log(` ${c ? colors.green : ''}✓${c ? colors.reset : ''} Instalado em: ${result.path}`);
76
- log(` ${c ? colors.dim : ''}Adicione ao .oxe/config.json: "plugins": [{ "source": "npm:${src}" }]${c ? colors.reset : ''}`);
77
- return 0;
78
- }
79
- error(` ${c ? colors.red : ''}✗ Falha:${c ? colors.reset : ''} ${result.error}`);
80
- return 1;
81
- }
82
-
83
- if (subCmd === 'remove' && pluginTarget) {
84
- log(` ${c ? colors.yellow : ''}Remove "${pluginTarget}" de .oxe/config.json → plugins[] manualmente.${c ? colors.reset : ''}`);
85
- log(` ${c ? colors.dim : ''}Arquivos npm: rm -rf .oxe/plugins/_npm/node_modules/${pluginTarget}${c ? colors.reset : ''}`);
86
- return 0;
87
- }
88
-
89
- log(` ${c ? colors.yellow : ''}Uso: oxe-cc plugins list | install <npm-package> [version] | remove <id>${c ? colors.reset : ''}`);
90
- return 0;
91
- }
92
-
93
- module.exports = {
94
- runPluginCommand,
95
- };
1
+ 'use strict';
2
+
3
+ const path = require('path');
4
+ const oxePlugins = require('./oxe-plugins.cjs');
5
+
6
+ const DEFAULT_COLORS = Object.freeze({
7
+ green: '\x1b[32m',
8
+ yellow: '\x1b[33m',
9
+ dim: '\x1b[2m',
10
+ red: '\x1b[31m',
11
+ reset: '\x1b[0m',
12
+ });
13
+
14
+ function defaultUseAnsiColors() {
15
+ if (process.env.NO_COLOR) return false;
16
+ if (process.env.FORCE_COLOR === '0') return false;
17
+ return process.stdout.isTTY === true;
18
+ }
19
+
20
+ /**
21
+ * Executa o subcomando `plugins` sem acoplar parsing e rendering ao CLI principal.
22
+ * @param {string[]} argv
23
+ * @param {{
24
+ * plugins?: typeof oxePlugins,
25
+ * cwd?: string,
26
+ * colors?: typeof DEFAULT_COLORS,
27
+ * useAnsiColors?: () => boolean,
28
+ * log?: (...args: unknown[]) => void,
29
+ * error?: (...args: unknown[]) => void,
30
+ * }} [options]
31
+ * @returns {number} exit code
32
+ */
33
+ function runPluginCommand(argv, options = {}) {
34
+ const plugins = options.plugins || oxePlugins;
35
+ const colors = options.colors || DEFAULT_COLORS;
36
+ const useAnsiColors = options.useAnsiColors || defaultUseAnsiColors;
37
+ const log = options.log || console.log;
38
+ const error = options.error || console.error;
39
+
40
+ let pluginsDir = options.cwd || process.cwd();
41
+ const pluginsArgv = argv.slice();
42
+ for (let i = 0; i < pluginsArgv.length; i++) {
43
+ if (pluginsArgv[i] === '--dir' && pluginsArgv[i + 1]) {
44
+ pluginsDir = path.resolve(pluginsArgv[i + 1]);
45
+ pluginsArgv.splice(i, 2);
46
+ i--;
47
+ }
48
+ }
49
+
50
+ const c = useAnsiColors();
51
+ const subCmd = pluginsArgv[0] || 'list';
52
+ const pluginTarget = pluginsArgv[1] || '';
53
+
54
+ if (subCmd === 'list') {
55
+ const result = plugins.loadPlugins(pluginsDir);
56
+ log(`\n ${c ? colors.green : ''}Plugins carregados:${c ? colors.reset : ''} ${result.plugins.length}`);
57
+ for (const plugin of result.plugins) {
58
+ log(` • ${plugin.name}${plugin.version ? ` (${plugin.version})` : ''} — hooks: ${Object.keys(plugin.hooks).join(', ')}`);
59
+ }
60
+ if (result.errors.length) {
61
+ log(`\n ${c ? colors.yellow : ''}Erros:${c ? colors.reset : ''}`);
62
+ for (const pluginError of result.errors) {
63
+ log(` ✗ ${pluginError.file}: ${pluginError.error}`);
64
+ }
65
+ }
66
+ return 0;
67
+ }
68
+
69
+ if (subCmd === 'install' && pluginTarget) {
70
+ const src = pluginTarget.startsWith('npm:') ? pluginTarget.slice(4) : pluginTarget;
71
+ const version = pluginsArgv[2] || '';
72
+ log(` Instalando plugin: ${src}${version ? `@${version}` : ''}...`);
73
+ const result = plugins.installNpmPlugin(pluginsDir, src, version || undefined);
74
+ if (result.ok) {
75
+ log(` ${c ? colors.green : ''}✓${c ? colors.reset : ''} Instalado em: ${result.path}`);
76
+ log(` ${c ? colors.dim : ''}Adicione ao .oxe/config.json: "plugins": [{ "source": "npm:${src}" }]${c ? colors.reset : ''}`);
77
+ return 0;
78
+ }
79
+ error(` ${c ? colors.red : ''}✗ Falha:${c ? colors.reset : ''} ${result.error}`);
80
+ return 1;
81
+ }
82
+
83
+ if (subCmd === 'remove' && pluginTarget) {
84
+ log(` ${c ? colors.yellow : ''}Remove "${pluginTarget}" de .oxe/config.json → plugins[] manualmente.${c ? colors.reset : ''}`);
85
+ log(` ${c ? colors.dim : ''}Arquivos npm: rm -rf .oxe/plugins/_npm/node_modules/${pluginTarget}${c ? colors.reset : ''}`);
86
+ return 0;
87
+ }
88
+
89
+ log(` ${c ? colors.yellow : ''}Uso: oxe-cc plugins list | install <npm-package> [version] | remove <id>${c ? colors.reset : ''}`);
90
+ return 0;
91
+ }
92
+
93
+ module.exports = {
94
+ runPluginCommand,
95
+ };