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
package/lib/sdk/index.cjs CHANGED
@@ -1,810 +1,815 @@
1
- 'use strict';
2
-
3
- /**
4
- * OXE SDK — API programática estável para integrações, CI e ferramentas.
5
- * Uso: `const oxe = require('oxe-cc')` ou `require('oxe-cc/lib/sdk/index.cjs')` conforme exports.
6
- */
7
-
8
- const fs = require('fs');
9
- const path = require('path');
10
- const health = require('../../bin/lib/oxe-project-health.cjs');
11
- const manifest = require('../../bin/lib/oxe-manifest.cjs');
12
- const workflows = require('../../bin/lib/oxe-workflows.cjs');
13
- const installResolve = require('../../bin/lib/oxe-install-resolve.cjs');
14
- const agentInstall = require('../../bin/lib/oxe-agent-install.cjs');
15
- const security = require('../../bin/lib/oxe-security.cjs');
16
- const plugins = require('../../bin/lib/oxe-plugins.cjs');
17
- const dashboard = require('../../bin/lib/oxe-dashboard.cjs');
18
- const operational = require('../../bin/lib/oxe-operational.cjs');
19
- const azure = require('../../bin/lib/oxe-azure.cjs');
20
- const context = require('../../bin/lib/oxe-context-engine.cjs');
21
- const runtimeSemantics = require('../../bin/lib/oxe-runtime-semantics.cjs');
22
- const release = require('../../bin/lib/oxe-release.cjs');
23
- const rationality = require('../../bin/lib/oxe-rationality.cjs');
24
- const artifactCatalog = require('../../bin/lib/oxe-artifact-catalog.cjs');
25
-
26
- const PACKAGE_ROOT = path.join(__dirname, '..', '..');
27
-
28
- /** @returns {{ version: string, name: string }} */
29
- function readPackageMeta(root = PACKAGE_ROOT) {
30
- try {
31
- const j = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'));
32
- return { version: String(j.version || '0.0.0'), name: String(j.name || 'oxe-cc') };
33
- } catch {
34
- return { version: '0.0.0', name: 'oxe-cc' };
35
- }
36
- }
37
-
38
- /** @param {string} packageRoot */
39
- function readMinNode(packageRoot) {
40
- try {
41
- const j = JSON.parse(fs.readFileSync(path.join(packageRoot, 'package.json'), 'utf8'));
42
- const eng = j.engines && j.engines.node;
43
- if (!eng || typeof eng !== 'string') return 18;
44
- const m = eng.match(/>=?\s*(\d+)/);
45
- return m ? parseInt(m[1], 10) : 18;
46
- } catch {
47
- return 18;
48
- }
49
- }
50
-
51
- /**
52
- * Faz parse de um PLAN.md e extrai tarefas estruturadas.
53
- *
54
- * @param {string} planMd - Conteúdo do PLAN.md (string).
55
- * @returns {{
56
- * tasks: Array<{
57
- * id: string,
58
- * title: string,
59
- * wave: number | null,
60
- * dependsOn: string[],
61
- * files: string[],
62
- * verifyCommand: string | null,
63
- * aceite: string[],
64
- * decisions: string[],
65
- * done: boolean,
66
- * meta: Record<string, unknown> | null,
67
- * }>,
68
- * waves: Record<number, string[]>,
69
- * totalTasks: number,
70
- * }}
71
- */
72
- function parsePlan(planMd) {
73
- const parts = planMd.split(/^###\s+(T\d+)\s*[—-]\s*/m);
74
- /** @type {ReturnType<typeof parsePlan>['tasks']} */
75
- const tasks = [];
76
- /** @type {Record<number, string[]>} */
77
- const waves = {};
78
-
79
- for (let i = 1; i < parts.length; i += 2) {
80
- const id = parts[i].trim();
81
- const rest = (parts[i + 1] || '').split(/^###\s+T\d+/m)[0];
82
- const titleMatch = rest.match(/^([^\n]+)/);
83
- const title = titleMatch ? titleMatch[1].trim() : '';
84
-
85
- const waveMatch = rest.match(/\*\*Onda:\*\*\s*(\d+)/i);
86
- const wave = waveMatch ? parseInt(waveMatch[1], 10) : null;
87
-
88
- const depsMatch = rest.match(/\*\*Depende\s+de:\*\*\s*([^\n]+)/i);
89
- const dependsOn = depsMatch
90
- ? depsMatch[1].split(/[,\s]+/).filter((s) => /^T\d+$/.test(s.trim()))
91
- : [];
92
-
93
- const filesMatch = rest.match(/\*\*Arquivos\s+prováveis:\*\*\s*([^\n]+)/i);
94
- const files = filesMatch
95
- ? filesMatch[1].match(/`([^`]+)`/g)?.map((s) => s.replace(/`/g, '')) || []
96
- : [];
97
-
98
- // Accept plain or bold-markdown form: "Verificação:", "**Verificação:**", "**Verify command:**", etc.
99
- // In "**Keyword:**" the asterisks come after the colon: keyword:\*{0,2}
100
- const verifyCmdMatch = rest.match(
101
- /\*{0,2}(?:Comando|Verify\s+command|Verificação|Verification):\*{0,2}\s*`([^`]+)`/is
102
- );
103
- const verifyCommand = verifyCmdMatch ? verifyCmdMatch[1].trim() : null;
104
-
105
- const aceiteMatch = rest.match(/\*\*Aceite\s+vinculado:\*\*\s*([^\n]+)/i);
106
- const aceite = aceiteMatch
107
- ? aceiteMatch[1].match(/A\d+/g) || []
108
- : [];
109
-
110
- const decisionsMatch = rest.match(/\*\*Decisão\s+vinculada:\*\*\s*([^\n]+)/i);
111
- const decisions = decisionsMatch
112
- ? decisionsMatch[1].match(/D-\d+/g) || []
113
- : [];
114
-
115
- // Parse do metadado JSON em comentário HTML <!-- oxe-task: {...} -->
116
- const metaMatch = rest.match(/<!--\s*oxe-task:\s*(\{[\s\S]*?\})\s*-->/);
117
- let meta = null;
118
- if (metaMatch) {
119
- try {
120
- meta = JSON.parse(metaMatch[1]);
121
- } catch {
122
- meta = null;
123
- }
124
- }
125
-
126
- const done = meta?.done === true;
127
-
128
- const task = { id, title, wave, dependsOn, files, verifyCommand, aceite, decisions, done, meta };
129
- tasks.push(task);
130
-
131
- if (wave != null) {
132
- if (!waves[wave]) waves[wave] = [];
133
- waves[wave].push(id);
134
- }
135
- }
136
-
137
- return { tasks, waves, totalTasks: tasks.length };
138
- }
139
-
140
- /**
141
- * Faz parse de um SPEC.md e extrai critérios de aceite.
142
- *
143
- * @param {string} specMd - Conteúdo do SPEC.md.
144
- * @returns {{
145
- * objective: string | null,
146
- * criteria: Array<{ id: string, criterion: string, howToVerify: string }>,
147
- * requiredSections: string[],
148
- * }}
149
- */
150
-
151
- /**
152
- * Parseia o arquivo lessons-metrics.json retornando o array de lições com métricas.
153
- * @param {string} metricsJson — conteúdo do arquivo lessons-metrics.json
154
- * @returns {Array<{ id: string, rule: string, type: string, applied_cycles: string[], outcomes: Array<{ cycle: string, verify_status: string, saved_hours?: number, failure_condition?: string }>, success_rate: number, status: string, deprecation_threshold: number }>}
155
- */
156
- function parseLessonsMetrics(metricsJson) {
157
- try {
158
- const data = JSON.parse(String(metricsJson || '{}'));
159
- return Array.isArray(data.lessons) ? data.lessons : [];
160
- } catch {
161
- return [];
162
- }
163
- }
164
-
165
- /**
166
- * Atualiza a métrica de uma lição com um novo outcome e recalcula success_rate.
167
- * @param {ReturnType<typeof parseLessonsMetrics>} metrics
168
- * @param {string} lessonId
169
- * @param {{ cycle: string, verify_status: string, saved_hours?: number, failure_condition?: string }} outcome
170
- * @returns {ReturnType<typeof parseLessonsMetrics>}
171
- */
172
- function updateLessonMetric(metrics, lessonId, outcome) {
173
- const arr = Array.isArray(metrics) ? metrics.slice() : [];
174
- const idx = arr.findIndex((l) => l.id === lessonId);
175
- if (idx === -1) return arr;
176
-
177
- const lesson = { ...arr[idx] };
178
- lesson.outcomes = [...(lesson.outcomes || []), outcome];
179
- if (!lesson.applied_cycles.includes(outcome.cycle)) {
180
- lesson.applied_cycles = [...lesson.applied_cycles, outcome.cycle];
181
- }
182
-
183
- const total = lesson.outcomes.length;
184
- const successes = lesson.outcomes.filter((o) => o.verify_status === 'complete').length;
185
- lesson.success_rate = total > 0 ? Math.round((successes / total) * 100) / 100 : 0;
186
-
187
- const threshold = typeof lesson.deprecation_threshold === 'number' ? lesson.deprecation_threshold : 0.5;
188
- if (lesson.success_rate < threshold && total >= 3) {
189
- lesson.status = 'deprecated';
190
- }
191
-
192
- arr[idx] = lesson;
193
- return arr;
194
- }
195
-
196
- /**
197
- * Marca como 'deprecated' todas as lições com success_rate abaixo do threshold e ≥ minObservations.
198
- * @param {ReturnType<typeof parseLessonsMetrics>} metrics
199
- * @param {number} [threshold=0.5]
200
- * @param {number} [minObservations=3]
201
- * @returns {ReturnType<typeof parseLessonsMetrics>}
202
- */
203
- function deprecateLowEffectiveness(metrics, threshold = 0.5, minObservations = 3) {
204
- return (Array.isArray(metrics) ? metrics : []).map((lesson) => {
205
- const observations = (lesson.outcomes || []).length;
206
- const rate = typeof lesson.success_rate === 'number' ? lesson.success_rate : 1;
207
- if (lesson.status !== 'deprecated' && observations >= minObservations && rate < threshold) {
208
- return { ...lesson, status: 'deprecated' };
209
- }
210
- return lesson;
211
- });
212
- }
213
-
214
- function parseSpec(specMd) {
215
- // Objetivo
216
- const objMatch = specMd.match(/##\s*Objetivo\s*\n+([\s\S]*?)(?=\n##\s|\n#[^\#]|$)/im);
217
- const objective = objMatch ? objMatch[1].trim().split('\n')[0].trim() : null;
218
-
219
- // Tabela de critérios
220
- /** @type {Array<{ id: string, criterion: string, howToVerify: string }>} */
221
- const criteria = [];
222
- const criteriaIdx = specMd.search(/##\s*Crit.rios.*?aceite/im);
223
- if (criteriaIdx !== -1) {
224
- const afterSection = specMd.slice(criteriaIdx);
225
- const nextHeadingMatch = afterSection.slice(3).match(/\n#{1,3} /);
226
- const sectionText = nextHeadingMatch
227
- ? afterSection.slice(0, nextHeadingMatch.index + 3 + 1)
228
- : afterSection;
229
- const rows = sectionText.split('\n').filter((l) => l.trimStart().startsWith('|'));
230
- for (const row of rows) {
231
- const cells = row.split('|').map((c) => c.trim()).filter(Boolean);
232
- if (cells.length >= 2 && /^A\d+$/i.test(cells[0])) {
233
- criteria.push({
234
- id: cells[0],
235
- criterion: cells[1] || '',
236
- howToVerify: cells[2] || '',
237
- });
238
- }
239
- }
240
- }
241
-
242
- // Seções presentes (para validação spec_required_sections)
243
- const headings = [];
244
- for (const m of specMd.matchAll(/^##\s+(.+)/gm)) {
245
- headings.push(`## ${m[1].trim()}`);
246
- }
247
-
248
- return { objective, criteria, requiredSections: headings };
249
- }
250
-
251
- /**
252
- * Faz parse do STATE.md e extrai fase, data do scan e próximo passo.
253
- *
254
- * @param {string} stateMd - Conteúdo do STATE.md.
255
- * @returns {{
256
- * phase: string | null,
257
- * lastScanDate: string | null,
258
- * nextStep: string | null,
259
- * decisions: string[],
260
- * activeWorkstreams: string[],
261
- * activeMilestone: string | null,
262
- * }}
263
- */
264
- function parseState(stateMd) {
265
- const phase = health.parseStatePhase(stateMd);
266
-
267
- const scanDate = health.parseLastScanDate(stateMd);
268
- const lastScanDate = scanDate ? scanDate.toISOString().split('T')[0] : null;
269
-
270
- const nextStepMatch = stateMd.match(/##\s*Próximo passo sugerido\s*\n+([\s\S]*?)(?=\n##\s|\n#[^\#]|$)/im);
271
- const nextStep = nextStepMatch ? nextStepMatch[1].trim().split('\n')[0].replace(/^[-*]\s*/, '').trim() : null;
272
-
273
- // Decisões persistentes (seção opcional)
274
- const decisionsMatch = stateMd.match(/##\s*Decisões persistentes\s*\n+([\s\S]*?)(?=\n##\s|\n#[^\#]|$)/im);
275
- const decisions = decisionsMatch
276
- ? decisionsMatch[1].match(/D-\d+[^)]*\)/g) || decisionsMatch[1].match(/D-\d+[^\n]*/g) || []
277
- : [];
278
-
279
- // Workstreams ativos (seção opcional)
280
- const wsMatch = stateMd.match(/##\s*Workstreams ativos\s*\n+([\s\S]*?)(?=\n##\s|\n#[^\#]|$)/im);
281
- const activeWorkstreams = wsMatch
282
- ? wsMatch[1].match(/`([^`]+)`/g)?.map((s) => s.replace(/`/g, '')) || []
283
- : [];
284
-
285
- // Milestone ativo
286
- const msMatch = stateMd.match(/##\s*Milestone ativo\s*\n+[^`]*`([^`]+)`/im);
287
- const activeMilestone = msMatch ? msMatch[1] : null;
288
-
289
- // Último retro
290
- const retroDate = health.parseLastRetroDate(stateMd);
291
- const lastRetroDate = retroDate ? retroDate.toISOString().split('T')[0] : null;
292
-
293
- // Blueprint de agentes (sessão)
294
- const runIdMatch = stateMd.match(/^\s*[-*]?\s*\*?\*?run_id:\*?\*?\s*(.+)/im);
295
- const runIdRaw = runIdMatch ? runIdMatch[1].trim().replace(/^[\(\-—]+|[\)\-—]+$/g, '').trim() : null;
296
- const runId = runIdRaw && runIdRaw !== '—' && runIdRaw !== '-' ? runIdRaw : null;
297
-
298
- const lifecycleMatch = stateMd.match(/^\s*[-*]?\s*\*?\*?lifecycle_status:\*?\*?\s*([^\s\n|`(]+)/im);
299
- const lifecycleStatusRaw = lifecycleMatch ? lifecycleMatch[1].trim() : null;
300
- const lifecycleStatus = lifecycleStatusRaw && lifecycleStatusRaw !== '—' && lifecycleStatusRaw !== '-' ? lifecycleStatusRaw : null;
301
-
302
- // Loop (sessão)
303
- const loopStatusMatch = stateMd.match(/^\s*[-*]?\s*\*?\*?loop_status:\*?\*?\s*([^\s\n|`(]+)/im);
304
- const loopStatusRaw = loopStatusMatch ? loopStatusMatch[1].trim() : null;
305
- const loopStatus = loopStatusRaw && loopStatusRaw !== '—' && loopStatusRaw !== '-' ? loopStatusRaw : null;
306
-
307
- return { phase, lastScanDate, lastRetroDate, nextStep, decisions, activeWorkstreams, activeMilestone, runId, lifecycleStatus, loopStatus };
308
- }
309
-
310
- /**
311
- * Valida fidelidade entre decisões do DISCUSS.md e tarefas do PLAN.md.
312
- * Retorna gaps onde decisões D-NN não têm tarefa vinculada.
313
- *
314
- * @param {string} discussMd - Conteúdo do DISCUSS.md.
315
- * @param {string} planMd - Conteúdo do PLAN.md.
316
- * @returns {{
317
- * ok: boolean,
318
- * gaps: Array<{ decisionId: string, decision: string }>,
319
- * covered: Array<{ decisionId: string, taskIds: string[] }>,
320
- * }}
321
- */
322
- function validateDecisionFidelity(discussMd, planMd) {
323
- // Extrair decisões da tabela D-NN
324
- const decisionRows = [];
325
- const decisoesIdx = discussMd.search(/##\s*Decis.es/im);
326
- if (decisoesIdx !== -1) {
327
- const afterSection = discussMd.slice(decisoesIdx);
328
- const nextHeadingMatch = afterSection.slice(3).match(/\n#{1,3} /);
329
- const sectionText = nextHeadingMatch
330
- ? afterSection.slice(0, nextHeadingMatch.index + 3 + 1)
331
- : afterSection;
332
- const rows = sectionText.split('\n').filter((l) => l.trimStart().startsWith('|'));
333
- for (const row of rows) {
334
- const cells = row.split('|').map((c) => c.trim()).filter(Boolean);
335
- if (cells.length >= 2 && /^D-\d+$/i.test(cells[0])) {
336
- decisionRows.push({ id: cells[0], text: cells[1] || '' });
337
- }
338
- }
339
- }
340
-
341
- if (!decisionRows.length) return { ok: true, gaps: [], covered: [] };
342
-
343
- const { tasks } = parsePlan(planMd);
344
-
345
- /** @type {ReturnType<typeof validateDecisionFidelity>['gaps']} */
346
- const gaps = [];
347
- /** @type {ReturnType<typeof validateDecisionFidelity>['covered']} */
348
- const covered = [];
349
-
350
- for (const dec of decisionRows) {
351
- // Ignorar decisões revertidas
352
- if (/revertida/i.test(dec.text)) continue;
353
-
354
- const tasksCovering = tasks.filter((t) => t.decisions.includes(dec.id));
355
- if (tasksCovering.length === 0) {
356
- gaps.push({ decisionId: dec.id, decision: dec.text });
357
- } else {
358
- covered.push({ decisionId: dec.id, taskIds: tasksCovering.map((t) => t.id) });
359
- }
360
- }
361
-
362
- return { ok: gaps.length === 0, gaps, covered };
363
- }
364
-
365
- /**
366
- * Verificações alinhadas ao `oxe-cc doctor`, com resultado estruturado (CI / gateways).
367
- *
368
- * @param {{
369
- * projectRoot: string,
370
- * packageRoot?: string,
371
- * nodeMajor?: number,
372
- * includeWorkflowLint?: boolean,
373
- * workflowLintOptions?: { maxBytesSoft?: number },
374
- * includeSecurity?: boolean,
375
- * }} args
376
- * @returns {{
377
- * ok: boolean,
378
- * errors: Array<{ code: string, message: string, detail?: unknown }>,
379
- * warnings: Array<{ code: string, message: string, detail?: unknown }>,
380
- * node: { currentMajor: number, minimumMajor: number, ok: boolean },
381
- * workflowDiff: ReturnType<typeof workflows.diffWorkflows> | null,
382
- * projectWorkflowsDir: string | null,
383
- * packageWorkflowsDir: string,
384
- * config: ReturnType<typeof health.loadOxeConfigMerged>,
385
- * validation: ReturnType<typeof health.validateConfigShape>,
386
- * healthReport: ReturnType<typeof health.buildHealthReport>,
387
- * workflowShape: ReturnType<typeof workflows.validateWorkflowShapes> | null,
388
- * securityReport: { secretFiles: string[], pluginsValid: boolean } | null,
389
- * }}
390
- */
391
- function runDoctorChecks(args) {
392
- const projectRoot = path.resolve(args.projectRoot);
393
- const packageRoot = path.resolve(args.packageRoot || PACKAGE_ROOT);
394
- const wfPkg = path.join(packageRoot, 'oxe', 'workflows');
395
-
396
- /** @type {Array<{ code: string, message: string, detail?: unknown }>} */
397
- const errors = [];
398
- /** @type {Array<{ code: string, message: string, detail?: unknown }>} */
399
- const warnings = [];
400
-
401
- const nodeMajor =
402
- args.nodeMajor != null
403
- ? args.nodeMajor
404
- : parseInt(String(process.versions.node).split('.')[0], 10);
405
- const minNode = readMinNode(packageRoot);
406
- const node = { currentMajor: nodeMajor, minimumMajor: minNode, ok: nodeMajor >= minNode };
407
- if (!node.ok) {
408
- errors.push({
409
- code: 'NODE_VERSION',
410
- message: `Node.js ${nodeMajor} abaixo do mínimo do pacote (${minNode})`,
411
- detail: { currentMajor: nodeMajor, minimumMajor: minNode },
412
- });
413
- }
414
-
415
- if (!fs.existsSync(wfPkg)) {
416
- errors.push({
417
- code: 'PACKAGE_WORKFLOWS_MISSING',
418
- message: `Pasta de workflows do pacote inexistente: ${wfPkg}`,
419
- });
420
- }
421
-
422
- const wfTgt = workflows.resolveWorkflowsDir(projectRoot);
423
- /** @type {ReturnType<typeof workflows.diffWorkflows> | null} */
424
- let workflowDiff = null;
425
-
426
- if (!wfTgt) {
427
- errors.push({
428
- code: 'PROJECT_WORKFLOWS_MISSING',
429
- message: 'Não existe .oxe/workflows nem oxe/workflows neste projeto',
430
- });
431
- } else if (fs.existsSync(wfPkg)) {
432
- workflowDiff = workflows.diffWorkflows(wfPkg, wfTgt);
433
- if (!workflowDiff.ok) {
434
- errors.push({
435
- code: 'WORKFLOW_DRIFT',
436
- message: `Faltam workflows em relação ao pacote: ${workflowDiff.missing.join(', ')}`,
437
- detail: { missing: workflowDiff.missing, extra: workflowDiff.extra },
438
- });
439
- } else if (workflowDiff.extra.length) {
440
- warnings.push({
441
- code: 'WORKFLOW_EXTRA',
442
- message: `Workflows extra no projeto (ok em forks): ${workflowDiff.extra.join(', ')}`,
443
- detail: { extra: workflowDiff.extra },
444
- });
445
- }
446
- }
447
-
448
- const config = health.loadOxeConfigMerged(projectRoot);
449
- const cfgPath = path.join(projectRoot, '.oxe', 'config.json');
450
- if (fs.existsSync(cfgPath)) {
451
- if (config.parseError) {
452
- errors.push({
453
- code: 'CONFIG_JSON_INVALID',
454
- message: `config.json inválido: ${config.parseError}`,
455
- detail: { path: cfgPath },
456
- });
457
- }
458
- }
459
-
460
- const validation = health.validateConfigShape(
461
- /** @type {Record<string, unknown>} */ (config.config)
462
- );
463
- for (const msg of validation.typeErrors) {
464
- warnings.push({ code: 'CONFIG_SHAPE', message: msg });
465
- }
466
- if (validation.unknownKeys.length) {
467
- warnings.push({
468
- code: 'CONFIG_UNKNOWN_KEYS',
469
- message: `Chaves desconhecidas: ${validation.unknownKeys.join(', ')}`,
470
- detail: { keys: validation.unknownKeys },
471
- });
472
- }
473
-
474
- const healthReport = health.buildHealthReport(projectRoot);
475
-
476
- /** @type {ReturnType<typeof workflows.validateWorkflowShapes> | null} */
477
- let workflowShape = null;
478
- const includeWorkflowLint = args.includeWorkflowLint !== false;
479
- if (includeWorkflowLint && wfTgt) {
480
- workflowShape = workflows.validateWorkflowShapes(wfTgt, args.workflowLintOptions || {});
481
- for (const w of workflowShape.warnings) {
482
- warnings.push(w);
483
- }
484
- }
485
-
486
- // Verificações de segurança (opcional, ativado por padrão)
487
- let securityReport = null;
488
- if (args.includeSecurity !== false) {
489
- const secretFiles = security.scanDirForSecretFiles(projectRoot, { maxDepth: 3 });
490
- if (secretFiles.length > 0) {
491
- warnings.push({
492
- code: 'SECURITY_SECRET_FILES',
493
- message: `Arquivos com nomes sensíveis detectados: ${secretFiles.join(', ')}`,
494
- detail: { files: secretFiles },
495
- });
496
- }
497
-
498
- // Verificar plugins se existirem
499
- const pluginsDir = path.join(projectRoot, '.oxe', 'plugins');
500
- let pluginsValid = true;
501
- if (fs.existsSync(pluginsDir)) {
502
- const pluginFiles = fs.readdirSync(pluginsDir).filter((f) => f.endsWith('.cjs'));
503
- for (const pf of pluginFiles) {
504
- const pluginPath = path.join(pluginsDir, pf);
505
- const safetyCheck = security.checkPathSafety(pluginPath, projectRoot);
506
- if (!safetyCheck.safe) {
507
- pluginsValid = false;
508
- warnings.push({
509
- code: 'SECURITY_PLUGIN_PATH',
510
- message: `Plugin com caminho inseguro: ${pf} — ${safetyCheck.reason}`,
511
- });
512
- }
513
- }
514
- }
515
-
516
- securityReport = { secretFiles, pluginsValid };
517
- }
518
-
519
- return {
520
- ok: errors.length === 0,
521
- errors,
522
- warnings,
523
- node,
524
- workflowDiff,
525
- projectWorkflowsDir: wfTgt,
526
- packageWorkflowsDir: wfPkg,
527
- config,
528
- validation,
529
- healthReport,
530
- workflowShape,
531
- securityReport,
532
- };
533
- }
534
-
535
- const meta = readPackageMeta();
536
-
537
- module.exports = {
538
- /** Versão do pacote `oxe-cc` (lida de package.json na raiz do pacote instalado). */
539
- version: meta.version,
540
- name: meta.name,
541
- PACKAGE_ROOT,
542
-
543
- /** Metadados e leitura de package.json (extensível para monorepos). */
544
- readPackageMeta,
545
- readMinNode,
546
-
547
- /** Parsing de artefatos OXE (PLAN, SPEC, STATE, hypotheses, confidence, lessons). */
548
- parsePlan,
549
- parseSpec,
550
- parseHypotheses: context.parseHypotheses,
551
- parseConfidenceVector: context.parseConfidenceVector,
552
- parseExecutionPlanTasks: rationality.parsePlanTasks,
553
- parseState,
554
- validateDecisionFidelity,
555
- parseLessonsMetrics,
556
- updateLessonMetric,
557
- deprecateLowEffectiveness,
558
-
559
- /** Estado do projeto, SPEC/PLAN, fase, config. */
560
- health: {
561
- loadOxeConfigMerged: health.loadOxeConfigMerged,
562
- validateConfigShape: health.validateConfigShape,
563
- buildHealthReport: health.buildHealthReport,
564
- buildStatusSummary: health.buildStatusSummary,
565
- agentSkillsReport: health.agentSkillsReport,
566
- detectWorkspaceMode: health.detectWorkspaceMode,
567
- shouldSuppressExecutionWorkspaceGates: health.shouldSuppressExecutionWorkspaceGates,
568
- suggestNextStep: health.suggestNextStep,
569
- oxePaths: health.oxePaths,
570
- parseStatePhase: health.parseStatePhase,
571
- parseLastScanDate: health.parseLastScanDate,
572
- parseLastCompactDate: health.parseLastCompactDate,
573
- parseLastRetroDate: health.parseLastRetroDate,
574
- isStaleScan: health.isStaleScan,
575
- isStaleLessons: health.isStaleLessons,
576
- copilotWorkspacePaths: health.copilotWorkspacePaths,
577
- copilotLegacyPaths: health.copilotLegacyPaths,
578
- copilotIntegrationReport: health.copilotIntegrationReport,
579
- planAgentsWarnings: health.planAgentsWarnings,
580
- phaseCoherenceWarnings: health.phaseCoherenceWarnings,
581
- specSectionWarnings: health.specSectionWarnings,
582
- planWaveWarningsFixed: health.planWaveWarningsFixed,
583
- planTaskAceiteWarnings: health.planTaskAceiteWarnings,
584
- buildExecutionRationality: health.buildExecutionRationality,
585
- executionRationalityWarningsFromSummary: health.executionRationalityWarningsFromSummary,
586
- verifyGapsWithoutSummaryWarning: health.verifyGapsWithoutSummaryWarning,
587
- expandExecutionProfile: health.expandExecutionProfile,
588
- ALLOWED_CONFIG_KEYS: health.ALLOWED_CONFIG_KEYS,
589
- EXECUTION_PROFILES: health.EXECUTION_PROFILES,
590
- VERIFICATION_DEPTHS: health.VERIFICATION_DEPTHS,
591
- INSTALL_PROFILES: health.INSTALL_PROFILES,
592
- INSTALL_REPO_LAYOUTS: health.INSTALL_REPO_LAYOUTS,
593
- INSTALL_OBJECT_KEYS: health.INSTALL_OBJECT_KEYS,
594
- EXPECTED_CODEBASE_MAPS: health.EXPECTED_CODEBASE_MAPS,
595
- },
596
-
597
- /** Workflows canónicos no disco. */
598
- workflows: {
599
- resolveWorkflowsDir: workflows.resolveWorkflowsDir,
600
- listWorkflowMdFiles: workflows.listWorkflowMdFiles,
601
- diffWorkflows: workflows.diffWorkflows,
602
- validateWorkflowShapes: workflows.validateWorkflowShapes,
603
- DEFAULT_MAX_BYTES_SOFT: workflows.DEFAULT_MAX_BYTES_SOFT,
604
- SUCCESS_CRITERIA_EXCEPTIONS: workflows.SUCCESS_CRITERIA_EXCEPTIONS,
605
- },
606
-
607
- /** Resolução de opções de instalação a partir de `.oxe/config.json`. */
608
- install: {
609
- resolveOptionsFromConfig: installResolve.resolveInstallOptionsFromConfig,
610
- },
611
-
612
- /** Manifesto de ficheiros instalados em `~` (integridade / backup). */
613
- manifest: {
614
- loadFileManifest: manifest.loadFileManifest,
615
- writeFileManifest: manifest.writeFileManifest,
616
- sha256File: manifest.sha256File,
617
- collectFilesRecursive: manifest.collectFilesRecursive,
618
- MANIFEST_DIR: manifest.MANIFEST_DIR,
619
- PATCHES_DIR: manifest.PATCHES_DIR,
620
- },
621
-
622
- /** Texto / multi-agente (rewrites de caminho, frontmatter). */
623
- agents: {
624
- adjustWorkflowPathsForNestedLayout: agentInstall.adjustWorkflowPathsForNestedLayout,
625
- parseCursorCommandFrontmatter: agentInstall.parseCursorCommandFrontmatter,
626
- },
627
-
628
- /** Segurança: validação de caminhos e detecção de segredos. */
629
- security: {
630
- checkPathSafety: security.checkPathSafety,
631
- scanFileForSecrets: security.scanFileForSecrets,
632
- scanDirForSecretFiles: security.scanDirForSecretFiles,
633
- validatePlanPaths: security.validatePlanPaths,
634
- checkFilePermission: security.checkFilePermission,
635
- checkPermissions: security.checkPermissions,
636
- globToRegex: security.globToRegex,
637
- DEFAULT_SECRET_PATTERNS: security.DEFAULT_SECRET_PATTERNS,
638
- DEFAULT_SECRET_CONTENT_PATTERNS: security.DEFAULT_SECRET_CONTENT_PATTERNS,
639
- DEFAULT_DENIED_PATH_PATTERNS: security.DEFAULT_DENIED_PATH_PATTERNS,
640
- },
641
-
642
- /** Plugin system — hooks de ciclo de vida em `.oxe/plugins/*.cjs`. */
643
- plugins: {
644
- loadPlugins: plugins.loadPlugins,
645
- runHook: plugins.runHook,
646
- validatePlugins: plugins.validatePlugins,
647
- initPluginsDir: plugins.initPluginsDir,
648
- resolvePluginSources: plugins.resolvePluginSources,
649
- installNpmPlugin: plugins.installNpmPlugin,
650
- },
651
-
652
- /** Dashboard local: contexto consolidado e persistência de revisão do plano. */
653
- dashboard: {
654
- loadDashboardContext: dashboard.loadDashboardContext,
655
- savePlanReviewStatus: dashboard.savePlanReviewStatus,
656
- addPlanReviewComment: dashboard.addPlanReviewComment,
657
- updatePlanReviewCommentStatus: dashboard.updatePlanReviewCommentStatus,
658
- },
659
-
660
- /** Release readiness: manifest, smoke matrix e checks de consistência antes de publicar. */
661
- release: {
662
- REQUIRED_RUNTIMES: release.REQUIRED_RUNTIMES,
663
- WRAPPER_TARGETS: release.WRAPPER_TARGETS,
664
- releasePaths: release.releasePaths,
665
- collectWrapperHashes: release.collectWrapperHashes,
666
- loadRuntimeSmokeReport: release.loadRuntimeSmokeReport,
667
- loadRecoveryFixtureReport: release.loadRecoveryFixtureReport,
668
- loadMultiAgentSoakReport: release.loadMultiAgentSoakReport,
669
- buildReleaseManifest: release.buildReleaseManifest,
670
- inspectCanonicalSource: release.inspectCanonicalSource,
671
- evaluateReleaseManifest: release.evaluateReleaseManifest,
672
- inspectReleaseReadiness: release.inspectReleaseReadiness,
673
- checkReleaseConsistency: release.checkReleaseConsistency,
674
- },
675
-
676
- /** Runtime operacional: tracing, active run, catálogo de capabilities e memória em camadas. */
677
- operational: {
678
- operationalPaths: operational.operationalPaths,
679
- appendEvent: operational.appendEvent,
680
- readEvents: operational.readEvents,
681
- summarizeEvents: operational.summarizeEvents,
682
- writeRunState: operational.writeRunState,
683
- readRunState: operational.readRunState,
684
- buildOperationalGraph: operational.buildOperationalGraph,
685
- serializeCanonicalState: operational.serializeCanonicalState,
686
- hydrateCanonicalState: operational.hydrateCanonicalState,
687
- reduceCanonicalRunState: operational.reduceCanonicalRunState,
688
- compileExecutionGraphFromArtifacts: operational.compileExecutionGraphFromArtifacts,
689
- compileVerificationSuiteFromArtifacts: operational.compileVerificationSuiteFromArtifacts,
690
- projectRuntimeArtifacts: operational.projectRuntimeArtifacts,
691
- runRuntimeCiChecks: operational.runRuntimeCiChecks,
692
- buildRuntimePluginRegistry: operational.buildRuntimePluginRegistry,
693
- readRuntimeGates: operational.readRuntimeGates,
694
- resolveRuntimeGate: operational.resolveRuntimeGate,
695
- runRuntimeVerify: operational.runRuntimeVerify,
696
- runRuntimePromotion: operational.runRuntimePromotion,
697
- recoverRuntimeState: operational.recoverRuntimeState,
698
- applyRuntimeAction: operational.applyRuntimeAction,
699
- parseCapabilityManifest: operational.parseCapabilityManifest,
700
- readCapabilityCatalog: operational.readCapabilityCatalog,
701
- buildMemoryLayers: operational.buildMemoryLayers,
702
- replayEvents: operational.replayEvents,
703
- replayRuntimeState: operational.replayRuntimeState,
704
- readRuntimeMultiAgentStatus: operational.readRuntimeMultiAgentStatus,
705
- multiAgentStatus: operational.readRuntimeMultiAgentStatus,
706
- },
707
-
708
- /** Context Engine V2: seleção, compressão e inspeção determinística de artefatos. */
709
- context: {
710
- contextPaths: context.contextPaths,
711
- resolveArtifactCandidates: context.resolveArtifactCandidates,
712
- buildProjectSummary: context.buildProjectSummary,
713
- buildSessionSummary: context.buildSessionSummary,
714
- buildPhaseSummary: context.buildPhaseSummary,
715
- buildContextIndex: context.buildContextIndex,
716
- buildContextPack: context.buildContextPack,
717
- inspectContextPack: context.inspectContextPack,
718
- buildAllContextPacks: context.buildAllContextPacks,
719
- computeContextQuality: context.computeContextQuality,
720
- computePackFreshness: context.computePackFreshness,
721
- resolvePackFile: context.resolvePackFile,
722
- summarizeText: context.summarizeText,
723
- extractSemanticFragment: context.extractSemanticFragment,
724
- parseHypotheses: context.parseHypotheses,
725
- parseConfidenceVector: context.parseConfidenceVector,
726
- },
727
-
728
- /** Semântica canónica multi-runtime para workflows, wrappers e prompts gerados. */
729
- runtimeSemantics: {
730
- CONTRACT_VERSION: runtimeSemantics.CONTRACT_VERSION,
731
- CONTRACTS_PATH: runtimeSemantics.CONTRACTS_PATH,
732
- CONTRACTS_REGISTRY: runtimeSemantics.CONTRACTS_REGISTRY,
733
- REQUIRED_CONTRACT_FIELDS: runtimeSemantics.REQUIRED_CONTRACT_FIELDS,
734
- RUNTIME_METADATA_KEYS: runtimeSemantics.RUNTIME_METADATA_KEYS,
735
- validateWorkflowContractsRegistry: runtimeSemantics.validateWorkflowContractsRegistry,
736
- getWorkflowContract: runtimeSemantics.getWorkflowContract,
737
- getAllWorkflowContracts: runtimeSemantics.getAllWorkflowContracts,
738
- computeSemanticsHash: runtimeSemantics.computeSemanticsHash,
739
- getRuntimeMetadataForSlug: runtimeSemantics.getRuntimeMetadataForSlug,
740
- renderRuntimeMetadataLines: runtimeSemantics.renderRuntimeMetadataLines,
741
- buildReasoningContractBlock: runtimeSemantics.buildReasoningContractBlock,
742
- pickRuntimeMetadata: runtimeSemantics.pickRuntimeMetadata,
743
- splitFrontmatter: runtimeSemantics.splitFrontmatter,
744
- parseFrontmatterMap: runtimeSemantics.parseFrontmatterMap,
745
- slugFromPromptFilename: runtimeSemantics.slugFromPromptFilename,
746
- slugFromCommandFilename: runtimeSemantics.slugFromCommandFilename,
747
- auditWrapperText: runtimeSemantics.auditWrapperText,
748
- auditRuntimeTargets: runtimeSemantics.auditRuntimeTargets,
749
- },
750
-
751
- /** Provider Azure nativo via Azure CLI. */
752
- azure: {
753
- MIN_AZURE_CLI_MAJOR: azure.MIN_AZURE_CLI_MAJOR,
754
- AZURE_CAPABILITY_IDS: azure.AZURE_CAPABILITY_IDS,
755
- RESOURCE_GRAPH_QUERY: azure.RESOURCE_GRAPH_QUERY,
756
- DEFAULT_AZURE_PROFILE: azure.DEFAULT_AZURE_PROFILE,
757
- azurePaths: azure.azurePaths,
758
- ensureAzureArtifacts: azure.ensureAzureArtifacts,
759
- isAzureContextEnabled: azure.isAzureContextEnabled,
760
- detectAzureCli: azure.detectAzureCli,
761
- loadAzureProfile: azure.loadAzureProfile,
762
- loadAzureAuthStatus: azure.loadAzureAuthStatus,
763
- loadAzureInventory: azure.loadAzureInventory,
764
- listAzureOperations: azure.listAzureOperations,
765
- summarizeInventory: azure.summarizeInventory,
766
- searchAzureInventory: azure.searchAzureInventory,
767
- diffInventory: azure.diffInventory,
768
- statusAzure: azure.statusAzure,
769
- ensureAzureCapabilities: azure.ensureAzureCapabilities,
770
- getAzureContext: azure.getAzureContext,
771
- loginAzure: azure.loginAzure,
772
- setAzureSubscription: azure.setAzureSubscription,
773
- syncAzureInventory: azure.syncAzureInventory,
774
- executeAzureRead: azure.executeAzureRead,
775
- planAzureOperation: azure.planAzureOperation,
776
- applyAzureOperation: azure.applyAzureOperation,
777
- azureDoctor: azure.azureDoctor,
778
- redactObject: azure.redactObject,
779
- },
780
-
781
- /**
782
- * Catálogo único de artefatos do `.oxe/` — fonte da verdade da legenda
783
- * (`.oxe/README.md`), do mapa vivo (`oxe-cc map`) e dos docs. Hosts podem
784
- * consumir `buildMapModel(target)` para projetar o estado real do diretório.
785
- */
786
- artifacts: {
787
- ARTIFACT_CATALOG: artifactCatalog.ARTIFACT_CATALOG,
788
- GROUPS: artifactCatalog.GROUPS,
789
- CORE_INSTALL_PATHS: artifactCatalog.CORE_INSTALL_PATHS,
790
- SOURCE_LABELS: artifactCatalog.SOURCE_LABELS,
791
- sourceLabel: artifactCatalog.sourceLabel,
792
- renderLegend: artifactCatalog.renderLegend,
793
- classifyEntry: artifactCatalog.classifyEntry,
794
- buildMapModel: artifactCatalog.buildMapModel,
795
- renderMap: artifactCatalog.renderMap,
796
- },
797
-
798
- /** Um único objeto com verificações tipo `doctor` + relatório de saúde. */
799
- runDoctorChecks,
800
- };
801
-
802
-
803
- // Re-exports from @oxe/runtime (R1 — Runtime Foundation)
804
- // The compiled runtime lives at lib/runtime/ alongside this file.
805
- try {
806
- const runtime = require('../runtime/index.js');
807
- Object.assign(module.exports, runtime);
808
- } catch {
809
- // Runtime not built yet — safe to skip during development
810
- }
1
+ 'use strict';
2
+
3
+ /**
4
+ * OXE SDK — API programática estável para integrações, CI e ferramentas.
5
+ * Uso: `const oxe = require('oxe-cc')` ou `require('oxe-cc/lib/sdk/index.cjs')` conforme exports.
6
+ */
7
+
8
+ const fs = require('fs');
9
+ const path = require('path');
10
+ const health = require('../../bin/lib/oxe-project-health.cjs');
11
+ const manifest = require('../../bin/lib/oxe-manifest.cjs');
12
+ const workflows = require('../../bin/lib/oxe-workflows.cjs');
13
+ const installResolve = require('../../bin/lib/oxe-install-resolve.cjs');
14
+ const agentInstall = require('../../bin/lib/oxe-agent-install.cjs');
15
+ const security = require('../../bin/lib/oxe-security.cjs');
16
+ const plugins = require('../../bin/lib/oxe-plugins.cjs');
17
+ const dashboard = require('../../bin/lib/oxe-dashboard.cjs');
18
+ const operational = require('../../bin/lib/oxe-operational.cjs');
19
+ const azure = require('../../bin/lib/oxe-azure.cjs');
20
+ const context = require('../../bin/lib/oxe-context-engine.cjs');
21
+ const runtimeSemantics = require('../../bin/lib/oxe-runtime-semantics.cjs');
22
+ const release = require('../../bin/lib/oxe-release.cjs');
23
+ const rationality = require('../../bin/lib/oxe-rationality.cjs');
24
+ const artifactCatalog = require('../../bin/lib/oxe-artifact-catalog.cjs');
25
+
26
+ const PACKAGE_ROOT = path.join(__dirname, '..', '..');
27
+
28
+ /** @returns {{ version: string, name: string }} */
29
+ function readPackageMeta(root = PACKAGE_ROOT) {
30
+ try {
31
+ const j = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'));
32
+ return { version: String(j.version || '0.0.0'), name: String(j.name || 'oxe-cc') };
33
+ } catch {
34
+ return { version: '0.0.0', name: 'oxe-cc' };
35
+ }
36
+ }
37
+
38
+ /** @param {string} packageRoot */
39
+ function readMinNode(packageRoot) {
40
+ try {
41
+ const j = JSON.parse(fs.readFileSync(path.join(packageRoot, 'package.json'), 'utf8'));
42
+ const eng = j.engines && j.engines.node;
43
+ if (!eng || typeof eng !== 'string') return 18;
44
+ const m = eng.match(/>=?\s*(\d+)/);
45
+ return m ? parseInt(m[1], 10) : 18;
46
+ } catch {
47
+ return 18;
48
+ }
49
+ }
50
+
51
+ /**
52
+ * Faz parse de um PLAN.md e extrai tarefas estruturadas.
53
+ *
54
+ * @param {string} planMd - Conteúdo do PLAN.md (string).
55
+ * @returns {{
56
+ * tasks: Array<{
57
+ * id: string,
58
+ * title: string,
59
+ * wave: number | null,
60
+ * dependsOn: string[],
61
+ * files: string[],
62
+ * verifyCommand: string | null,
63
+ * aceite: string[],
64
+ * decisions: string[],
65
+ * done: boolean,
66
+ * meta: Record<string, unknown> | null,
67
+ * }>,
68
+ * waves: Record<number, string[]>,
69
+ * totalTasks: number,
70
+ * }}
71
+ */
72
+ function parsePlan(planMd) {
73
+ const parts = planMd.split(/^###\s+(T\d+)\s*[—-]\s*/m);
74
+ /** @type {ReturnType<typeof parsePlan>['tasks']} */
75
+ const tasks = [];
76
+ /** @type {Record<number, string[]>} */
77
+ const waves = {};
78
+
79
+ for (let i = 1; i < parts.length; i += 2) {
80
+ const id = parts[i].trim();
81
+ const rest = (parts[i + 1] || '').split(/^###\s+T\d+/m)[0];
82
+ const titleMatch = rest.match(/^([^\n]+)/);
83
+ const title = titleMatch ? titleMatch[1].trim() : '';
84
+
85
+ const waveMatch = rest.match(/\*\*Onda:\*\*\s*(\d+)/i);
86
+ const wave = waveMatch ? parseInt(waveMatch[1], 10) : null;
87
+
88
+ const depsMatch = rest.match(/\*\*Depende\s+de:\*\*\s*([^\n]+)/i);
89
+ const dependsOn = depsMatch
90
+ ? depsMatch[1].split(/[,\s]+/).filter((s) => /^T\d+$/.test(s.trim()))
91
+ : [];
92
+
93
+ // Accept the template label ("Arquivos alvo"), the legacy one ("Arquivos prováveis") and plain "Arquivos"
94
+ const filesMatch = rest.match(/\*\*Arquivos(?:\s+(?:prov[aá]veis|alvo))?:\*\*\s*([^\n]+)/i);
95
+ // Only path-like spans become scope: `# linkly` (quoted content) or `mutation_scope: []` are prose.
96
+ const files = filesMatch
97
+ ? (filesMatch[1].match(/`([^`]+)`/g) || [])
98
+ .map((s) => s.replace(/`/g, '').trim())
99
+ .filter((s) => /^[^\s#:]+$/.test(s))
100
+ : [];
101
+
102
+ // Accept plain or bold-markdown form: "Verificação:", "**Verificação:**", "**Verify command:**", etc.
103
+ // In "**Keyword:**" the asterisks come after the colon: keyword:\*{0,2}
104
+ // Several "Comando:" lines are all kept (joined with &&); keeping only the first dropped checks.
105
+ const verifyCommands = [
106
+ ...rest.matchAll(/\*{0,2}(?:Comando|Verify\s+command|Verificação|Verification):\*{0,2}\s*`([^`]+)`/gi),
107
+ ].map((m) => m[1].trim()).filter(Boolean);
108
+ const verifyCommand = verifyCommands.length ? [...new Set(verifyCommands)].join(' && ') : null;
109
+
110
+ const aceiteMatch = rest.match(/\*\*Aceite\s+vinculado:\*\*\s*([^\n]+)/i);
111
+ const aceite = aceiteMatch
112
+ ? aceiteMatch[1].match(/A\d+/g) || []
113
+ : [];
114
+
115
+ const decisionsMatch = rest.match(/\*\*Decisão\s+vinculada:\*\*\s*([^\n]+)/i);
116
+ const decisions = decisionsMatch
117
+ ? decisionsMatch[1].match(/D-\d+/g) || []
118
+ : [];
119
+
120
+ // Parse do metadado JSON em comentário HTML <!-- oxe-task: {...} -->
121
+ const metaMatch = rest.match(/<!--\s*oxe-task:\s*(\{[\s\S]*?\})\s*-->/);
122
+ let meta = null;
123
+ if (metaMatch) {
124
+ try {
125
+ meta = JSON.parse(metaMatch[1]);
126
+ } catch {
127
+ meta = null;
128
+ }
129
+ }
130
+
131
+ const done = meta?.done === true;
132
+
133
+ const task = { id, title, wave, dependsOn, files, verifyCommand, aceite, decisions, done, meta };
134
+ tasks.push(task);
135
+
136
+ if (wave != null) {
137
+ if (!waves[wave]) waves[wave] = [];
138
+ waves[wave].push(id);
139
+ }
140
+ }
141
+
142
+ return { tasks, waves, totalTasks: tasks.length };
143
+ }
144
+
145
+ /**
146
+ * Faz parse de um SPEC.md e extrai critérios de aceite.
147
+ *
148
+ * @param {string} specMd - Conteúdo do SPEC.md.
149
+ * @returns {{
150
+ * objective: string | null,
151
+ * criteria: Array<{ id: string, criterion: string, howToVerify: string }>,
152
+ * requiredSections: string[],
153
+ * }}
154
+ */
155
+
156
+ /**
157
+ * Parseia o arquivo lessons-metrics.json retornando o array de lições com métricas.
158
+ * @param {string} metricsJson — conteúdo do arquivo lessons-metrics.json
159
+ * @returns {Array<{ id: string, rule: string, type: string, applied_cycles: string[], outcomes: Array<{ cycle: string, verify_status: string, saved_hours?: number, failure_condition?: string }>, success_rate: number, status: string, deprecation_threshold: number }>}
160
+ */
161
+ function parseLessonsMetrics(metricsJson) {
162
+ try {
163
+ const data = JSON.parse(String(metricsJson || '{}'));
164
+ return Array.isArray(data.lessons) ? data.lessons : [];
165
+ } catch {
166
+ return [];
167
+ }
168
+ }
169
+
170
+ /**
171
+ * Atualiza a métrica de uma lição com um novo outcome e recalcula success_rate.
172
+ * @param {ReturnType<typeof parseLessonsMetrics>} metrics
173
+ * @param {string} lessonId
174
+ * @param {{ cycle: string, verify_status: string, saved_hours?: number, failure_condition?: string }} outcome
175
+ * @returns {ReturnType<typeof parseLessonsMetrics>}
176
+ */
177
+ function updateLessonMetric(metrics, lessonId, outcome) {
178
+ const arr = Array.isArray(metrics) ? metrics.slice() : [];
179
+ const idx = arr.findIndex((l) => l.id === lessonId);
180
+ if (idx === -1) return arr;
181
+
182
+ const lesson = { ...arr[idx] };
183
+ lesson.outcomes = [...(lesson.outcomes || []), outcome];
184
+ if (!lesson.applied_cycles.includes(outcome.cycle)) {
185
+ lesson.applied_cycles = [...lesson.applied_cycles, outcome.cycle];
186
+ }
187
+
188
+ const total = lesson.outcomes.length;
189
+ const successes = lesson.outcomes.filter((o) => o.verify_status === 'complete').length;
190
+ lesson.success_rate = total > 0 ? Math.round((successes / total) * 100) / 100 : 0;
191
+
192
+ const threshold = typeof lesson.deprecation_threshold === 'number' ? lesson.deprecation_threshold : 0.5;
193
+ if (lesson.success_rate < threshold && total >= 3) {
194
+ lesson.status = 'deprecated';
195
+ }
196
+
197
+ arr[idx] = lesson;
198
+ return arr;
199
+ }
200
+
201
+ /**
202
+ * Marca como 'deprecated' todas as lições com success_rate abaixo do threshold e ≥ minObservations.
203
+ * @param {ReturnType<typeof parseLessonsMetrics>} metrics
204
+ * @param {number} [threshold=0.5]
205
+ * @param {number} [minObservations=3]
206
+ * @returns {ReturnType<typeof parseLessonsMetrics>}
207
+ */
208
+ function deprecateLowEffectiveness(metrics, threshold = 0.5, minObservations = 3) {
209
+ return (Array.isArray(metrics) ? metrics : []).map((lesson) => {
210
+ const observations = (lesson.outcomes || []).length;
211
+ const rate = typeof lesson.success_rate === 'number' ? lesson.success_rate : 1;
212
+ if (lesson.status !== 'deprecated' && observations >= minObservations && rate < threshold) {
213
+ return { ...lesson, status: 'deprecated' };
214
+ }
215
+ return lesson;
216
+ });
217
+ }
218
+
219
+ function parseSpec(specMd) {
220
+ // Objetivo
221
+ const objMatch = specMd.match(/##\s*Objetivo\s*\n+([\s\S]*?)(?=\n##\s|\n#[^\#]|$)/im);
222
+ const objective = objMatch ? objMatch[1].trim().split('\n')[0].trim() : null;
223
+
224
+ // Tabela de critérios
225
+ /** @type {Array<{ id: string, criterion: string, howToVerify: string }>} */
226
+ const criteria = [];
227
+ const criteriaIdx = specMd.search(/##\s*Crit.rios.*?aceite/im);
228
+ if (criteriaIdx !== -1) {
229
+ const afterSection = specMd.slice(criteriaIdx);
230
+ const nextHeadingMatch = afterSection.slice(3).match(/\n#{1,3} /);
231
+ const sectionText = nextHeadingMatch
232
+ ? afterSection.slice(0, nextHeadingMatch.index + 3 + 1)
233
+ : afterSection;
234
+ const rows = sectionText.split('\n').filter((l) => l.trimStart().startsWith('|'));
235
+ for (const row of rows) {
236
+ const cells = row.split('|').map((c) => c.trim()).filter(Boolean);
237
+ if (cells.length >= 2 && /^A\d+$/i.test(cells[0])) {
238
+ criteria.push({
239
+ id: cells[0],
240
+ criterion: cells[1] || '',
241
+ howToVerify: cells[2] || '',
242
+ });
243
+ }
244
+ }
245
+ }
246
+
247
+ // Seções presentes (para validação spec_required_sections)
248
+ const headings = [];
249
+ for (const m of specMd.matchAll(/^##\s+(.+)/gm)) {
250
+ headings.push(`## ${m[1].trim()}`);
251
+ }
252
+
253
+ return { objective, criteria, requiredSections: headings };
254
+ }
255
+
256
+ /**
257
+ * Faz parse do STATE.md e extrai fase, data do scan e próximo passo.
258
+ *
259
+ * @param {string} stateMd - Conteúdo do STATE.md.
260
+ * @returns {{
261
+ * phase: string | null,
262
+ * lastScanDate: string | null,
263
+ * nextStep: string | null,
264
+ * decisions: string[],
265
+ * activeWorkstreams: string[],
266
+ * activeMilestone: string | null,
267
+ * }}
268
+ */
269
+ function parseState(stateMd) {
270
+ const phase = health.parseStatePhase(stateMd);
271
+
272
+ const scanDate = health.parseLastScanDate(stateMd);
273
+ const lastScanDate = scanDate ? scanDate.toISOString().split('T')[0] : null;
274
+
275
+ const nextStepMatch = stateMd.match(/##\s*Próximo passo sugerido\s*\n+([\s\S]*?)(?=\n##\s|\n#[^\#]|$)/im);
276
+ const nextStep = nextStepMatch ? nextStepMatch[1].trim().split('\n')[0].replace(/^[-*]\s*/, '').trim() : null;
277
+
278
+ // Decisões persistentes (seção opcional)
279
+ const decisionsMatch = stateMd.match(/##\s*Decisões persistentes\s*\n+([\s\S]*?)(?=\n##\s|\n#[^\#]|$)/im);
280
+ const decisions = decisionsMatch
281
+ ? decisionsMatch[1].match(/D-\d+[^)]*\)/g) || decisionsMatch[1].match(/D-\d+[^\n]*/g) || []
282
+ : [];
283
+
284
+ // Workstreams ativos (seção opcional)
285
+ const wsMatch = stateMd.match(/##\s*Workstreams ativos\s*\n+([\s\S]*?)(?=\n##\s|\n#[^\#]|$)/im);
286
+ const activeWorkstreams = wsMatch
287
+ ? wsMatch[1].match(/`([^`]+)`/g)?.map((s) => s.replace(/`/g, '')) || []
288
+ : [];
289
+
290
+ // Milestone ativo
291
+ const msMatch = stateMd.match(/##\s*Milestone ativo\s*\n+[^`]*`([^`]+)`/im);
292
+ const activeMilestone = msMatch ? msMatch[1] : null;
293
+
294
+ // Último retro
295
+ const retroDate = health.parseLastRetroDate(stateMd);
296
+ const lastRetroDate = retroDate ? retroDate.toISOString().split('T')[0] : null;
297
+
298
+ // Blueprint de agentes (sessão)
299
+ const runIdMatch = stateMd.match(/^\s*[-*]?\s*\*?\*?run_id:\*?\*?\s*(.+)/im);
300
+ const runIdRaw = runIdMatch ? runIdMatch[1].trim().replace(/^[\(\-—]+|[\)\-—]+$/g, '').trim() : null;
301
+ const runId = runIdRaw && runIdRaw !== '—' && runIdRaw !== '-' ? runIdRaw : null;
302
+
303
+ const lifecycleMatch = stateMd.match(/^\s*[-*]?\s*\*?\*?lifecycle_status:\*?\*?\s*([^\s\n|`(]+)/im);
304
+ const lifecycleStatusRaw = lifecycleMatch ? lifecycleMatch[1].trim() : null;
305
+ const lifecycleStatus = lifecycleStatusRaw && lifecycleStatusRaw !== '—' && lifecycleStatusRaw !== '-' ? lifecycleStatusRaw : null;
306
+
307
+ // Loop (sessão)
308
+ const loopStatusMatch = stateMd.match(/^\s*[-*]?\s*\*?\*?loop_status:\*?\*?\s*([^\s\n|`(]+)/im);
309
+ const loopStatusRaw = loopStatusMatch ? loopStatusMatch[1].trim() : null;
310
+ const loopStatus = loopStatusRaw && loopStatusRaw !== '—' && loopStatusRaw !== '-' ? loopStatusRaw : null;
311
+
312
+ return { phase, lastScanDate, lastRetroDate, nextStep, decisions, activeWorkstreams, activeMilestone, runId, lifecycleStatus, loopStatus };
313
+ }
314
+
315
+ /**
316
+ * Valida fidelidade entre decisões do DISCUSS.md e tarefas do PLAN.md.
317
+ * Retorna gaps onde decisões D-NN não têm tarefa vinculada.
318
+ *
319
+ * @param {string} discussMd - Conteúdo do DISCUSS.md.
320
+ * @param {string} planMd - Conteúdo do PLAN.md.
321
+ * @returns {{
322
+ * ok: boolean,
323
+ * gaps: Array<{ decisionId: string, decision: string }>,
324
+ * covered: Array<{ decisionId: string, taskIds: string[] }>,
325
+ * }}
326
+ */
327
+ function validateDecisionFidelity(discussMd, planMd) {
328
+ // Extrair decisões da tabela D-NN
329
+ const decisionRows = [];
330
+ const decisoesIdx = discussMd.search(/##\s*Decis.es/im);
331
+ if (decisoesIdx !== -1) {
332
+ const afterSection = discussMd.slice(decisoesIdx);
333
+ const nextHeadingMatch = afterSection.slice(3).match(/\n#{1,3} /);
334
+ const sectionText = nextHeadingMatch
335
+ ? afterSection.slice(0, nextHeadingMatch.index + 3 + 1)
336
+ : afterSection;
337
+ const rows = sectionText.split('\n').filter((l) => l.trimStart().startsWith('|'));
338
+ for (const row of rows) {
339
+ const cells = row.split('|').map((c) => c.trim()).filter(Boolean);
340
+ if (cells.length >= 2 && /^D-\d+$/i.test(cells[0])) {
341
+ decisionRows.push({ id: cells[0], text: cells[1] || '' });
342
+ }
343
+ }
344
+ }
345
+
346
+ if (!decisionRows.length) return { ok: true, gaps: [], covered: [] };
347
+
348
+ const { tasks } = parsePlan(planMd);
349
+
350
+ /** @type {ReturnType<typeof validateDecisionFidelity>['gaps']} */
351
+ const gaps = [];
352
+ /** @type {ReturnType<typeof validateDecisionFidelity>['covered']} */
353
+ const covered = [];
354
+
355
+ for (const dec of decisionRows) {
356
+ // Ignorar decisões revertidas
357
+ if (/revertida/i.test(dec.text)) continue;
358
+
359
+ const tasksCovering = tasks.filter((t) => t.decisions.includes(dec.id));
360
+ if (tasksCovering.length === 0) {
361
+ gaps.push({ decisionId: dec.id, decision: dec.text });
362
+ } else {
363
+ covered.push({ decisionId: dec.id, taskIds: tasksCovering.map((t) => t.id) });
364
+ }
365
+ }
366
+
367
+ return { ok: gaps.length === 0, gaps, covered };
368
+ }
369
+
370
+ /**
371
+ * Verificações alinhadas ao `oxe-cc doctor`, com resultado estruturado (CI / gateways).
372
+ *
373
+ * @param {{
374
+ * projectRoot: string,
375
+ * packageRoot?: string,
376
+ * nodeMajor?: number,
377
+ * includeWorkflowLint?: boolean,
378
+ * workflowLintOptions?: { maxBytesSoft?: number },
379
+ * includeSecurity?: boolean,
380
+ * }} args
381
+ * @returns {{
382
+ * ok: boolean,
383
+ * errors: Array<{ code: string, message: string, detail?: unknown }>,
384
+ * warnings: Array<{ code: string, message: string, detail?: unknown }>,
385
+ * node: { currentMajor: number, minimumMajor: number, ok: boolean },
386
+ * workflowDiff: ReturnType<typeof workflows.diffWorkflows> | null,
387
+ * projectWorkflowsDir: string | null,
388
+ * packageWorkflowsDir: string,
389
+ * config: ReturnType<typeof health.loadOxeConfigMerged>,
390
+ * validation: ReturnType<typeof health.validateConfigShape>,
391
+ * healthReport: ReturnType<typeof health.buildHealthReport>,
392
+ * workflowShape: ReturnType<typeof workflows.validateWorkflowShapes> | null,
393
+ * securityReport: { secretFiles: string[], pluginsValid: boolean } | null,
394
+ * }}
395
+ */
396
+ function runDoctorChecks(args) {
397
+ const projectRoot = path.resolve(args.projectRoot);
398
+ const packageRoot = path.resolve(args.packageRoot || PACKAGE_ROOT);
399
+ const wfPkg = path.join(packageRoot, 'oxe', 'workflows');
400
+
401
+ /** @type {Array<{ code: string, message: string, detail?: unknown }>} */
402
+ const errors = [];
403
+ /** @type {Array<{ code: string, message: string, detail?: unknown }>} */
404
+ const warnings = [];
405
+
406
+ const nodeMajor =
407
+ args.nodeMajor != null
408
+ ? args.nodeMajor
409
+ : parseInt(String(process.versions.node).split('.')[0], 10);
410
+ const minNode = readMinNode(packageRoot);
411
+ const node = { currentMajor: nodeMajor, minimumMajor: minNode, ok: nodeMajor >= minNode };
412
+ if (!node.ok) {
413
+ errors.push({
414
+ code: 'NODE_VERSION',
415
+ message: `Node.js ${nodeMajor} abaixo do mínimo do pacote (${minNode})`,
416
+ detail: { currentMajor: nodeMajor, minimumMajor: minNode },
417
+ });
418
+ }
419
+
420
+ if (!fs.existsSync(wfPkg)) {
421
+ errors.push({
422
+ code: 'PACKAGE_WORKFLOWS_MISSING',
423
+ message: `Pasta de workflows do pacote inexistente: ${wfPkg}`,
424
+ });
425
+ }
426
+
427
+ const wfTgt = workflows.resolveWorkflowsDir(projectRoot);
428
+ /** @type {ReturnType<typeof workflows.diffWorkflows> | null} */
429
+ let workflowDiff = null;
430
+
431
+ if (!wfTgt) {
432
+ errors.push({
433
+ code: 'PROJECT_WORKFLOWS_MISSING',
434
+ message: 'Não existe .oxe/workflows nem oxe/workflows neste projeto',
435
+ });
436
+ } else if (fs.existsSync(wfPkg)) {
437
+ workflowDiff = workflows.diffWorkflows(wfPkg, wfTgt);
438
+ if (!workflowDiff.ok) {
439
+ errors.push({
440
+ code: 'WORKFLOW_DRIFT',
441
+ message: `Faltam workflows em relação ao pacote: ${workflowDiff.missing.join(', ')}`,
442
+ detail: { missing: workflowDiff.missing, extra: workflowDiff.extra },
443
+ });
444
+ } else if (workflowDiff.extra.length) {
445
+ warnings.push({
446
+ code: 'WORKFLOW_EXTRA',
447
+ message: `Workflows extra no projeto (ok em forks): ${workflowDiff.extra.join(', ')}`,
448
+ detail: { extra: workflowDiff.extra },
449
+ });
450
+ }
451
+ }
452
+
453
+ const config = health.loadOxeConfigMerged(projectRoot);
454
+ const cfgPath = path.join(projectRoot, '.oxe', 'config.json');
455
+ if (fs.existsSync(cfgPath)) {
456
+ if (config.parseError) {
457
+ errors.push({
458
+ code: 'CONFIG_JSON_INVALID',
459
+ message: `config.json inválido: ${config.parseError}`,
460
+ detail: { path: cfgPath },
461
+ });
462
+ }
463
+ }
464
+
465
+ const validation = health.validateConfigShape(
466
+ /** @type {Record<string, unknown>} */ (config.config)
467
+ );
468
+ for (const msg of validation.typeErrors) {
469
+ warnings.push({ code: 'CONFIG_SHAPE', message: msg });
470
+ }
471
+ if (validation.unknownKeys.length) {
472
+ warnings.push({
473
+ code: 'CONFIG_UNKNOWN_KEYS',
474
+ message: `Chaves desconhecidas: ${validation.unknownKeys.join(', ')}`,
475
+ detail: { keys: validation.unknownKeys },
476
+ });
477
+ }
478
+
479
+ const healthReport = health.buildHealthReport(projectRoot);
480
+
481
+ /** @type {ReturnType<typeof workflows.validateWorkflowShapes> | null} */
482
+ let workflowShape = null;
483
+ const includeWorkflowLint = args.includeWorkflowLint !== false;
484
+ if (includeWorkflowLint && wfTgt) {
485
+ workflowShape = workflows.validateWorkflowShapes(wfTgt, args.workflowLintOptions || {});
486
+ for (const w of workflowShape.warnings) {
487
+ warnings.push(w);
488
+ }
489
+ }
490
+
491
+ // Verificações de segurança (opcional, ativado por padrão)
492
+ let securityReport = null;
493
+ if (args.includeSecurity !== false) {
494
+ const secretFiles = security.scanDirForSecretFiles(projectRoot, { maxDepth: 3 });
495
+ if (secretFiles.length > 0) {
496
+ warnings.push({
497
+ code: 'SECURITY_SECRET_FILES',
498
+ message: `Arquivos com nomes sensíveis detectados: ${secretFiles.join(', ')}`,
499
+ detail: { files: secretFiles },
500
+ });
501
+ }
502
+
503
+ // Verificar plugins se existirem
504
+ const pluginsDir = path.join(projectRoot, '.oxe', 'plugins');
505
+ let pluginsValid = true;
506
+ if (fs.existsSync(pluginsDir)) {
507
+ const pluginFiles = fs.readdirSync(pluginsDir).filter((f) => f.endsWith('.cjs'));
508
+ for (const pf of pluginFiles) {
509
+ const pluginPath = path.join(pluginsDir, pf);
510
+ const safetyCheck = security.checkPathSafety(pluginPath, projectRoot);
511
+ if (!safetyCheck.safe) {
512
+ pluginsValid = false;
513
+ warnings.push({
514
+ code: 'SECURITY_PLUGIN_PATH',
515
+ message: `Plugin com caminho inseguro: ${pf} — ${safetyCheck.reason}`,
516
+ });
517
+ }
518
+ }
519
+ }
520
+
521
+ securityReport = { secretFiles, pluginsValid };
522
+ }
523
+
524
+ return {
525
+ ok: errors.length === 0,
526
+ errors,
527
+ warnings,
528
+ node,
529
+ workflowDiff,
530
+ projectWorkflowsDir: wfTgt,
531
+ packageWorkflowsDir: wfPkg,
532
+ config,
533
+ validation,
534
+ healthReport,
535
+ workflowShape,
536
+ securityReport,
537
+ };
538
+ }
539
+
540
+ const meta = readPackageMeta();
541
+
542
+ module.exports = {
543
+ /** Versão do pacote `oxe-cc` (lida de package.json na raiz do pacote instalado). */
544
+ version: meta.version,
545
+ name: meta.name,
546
+ PACKAGE_ROOT,
547
+
548
+ /** Metadados e leitura de package.json (extensível para monorepos). */
549
+ readPackageMeta,
550
+ readMinNode,
551
+
552
+ /** Parsing de artefatos OXE (PLAN, SPEC, STATE, hypotheses, confidence, lessons). */
553
+ parsePlan,
554
+ parseSpec,
555
+ parseHypotheses: context.parseHypotheses,
556
+ parseConfidenceVector: context.parseConfidenceVector,
557
+ parseExecutionPlanTasks: rationality.parsePlanTasks,
558
+ parseState,
559
+ validateDecisionFidelity,
560
+ parseLessonsMetrics,
561
+ updateLessonMetric,
562
+ deprecateLowEffectiveness,
563
+
564
+ /** Estado do projeto, SPEC/PLAN, fase, config. */
565
+ health: {
566
+ loadOxeConfigMerged: health.loadOxeConfigMerged,
567
+ validateConfigShape: health.validateConfigShape,
568
+ buildHealthReport: health.buildHealthReport,
569
+ buildStatusSummary: health.buildStatusSummary,
570
+ agentSkillsReport: health.agentSkillsReport,
571
+ detectWorkspaceMode: health.detectWorkspaceMode,
572
+ shouldSuppressExecutionWorkspaceGates: health.shouldSuppressExecutionWorkspaceGates,
573
+ suggestNextStep: health.suggestNextStep,
574
+ oxePaths: health.oxePaths,
575
+ parseStatePhase: health.parseStatePhase,
576
+ parseLastScanDate: health.parseLastScanDate,
577
+ parseLastCompactDate: health.parseLastCompactDate,
578
+ parseLastRetroDate: health.parseLastRetroDate,
579
+ isStaleScan: health.isStaleScan,
580
+ isStaleLessons: health.isStaleLessons,
581
+ copilotWorkspacePaths: health.copilotWorkspacePaths,
582
+ copilotLegacyPaths: health.copilotLegacyPaths,
583
+ copilotIntegrationReport: health.copilotIntegrationReport,
584
+ planAgentsWarnings: health.planAgentsWarnings,
585
+ phaseCoherenceWarnings: health.phaseCoherenceWarnings,
586
+ specSectionWarnings: health.specSectionWarnings,
587
+ planWaveWarningsFixed: health.planWaveWarningsFixed,
588
+ planTaskAceiteWarnings: health.planTaskAceiteWarnings,
589
+ buildExecutionRationality: health.buildExecutionRationality,
590
+ executionRationalityWarningsFromSummary: health.executionRationalityWarningsFromSummary,
591
+ verifyGapsWithoutSummaryWarning: health.verifyGapsWithoutSummaryWarning,
592
+ expandExecutionProfile: health.expandExecutionProfile,
593
+ ALLOWED_CONFIG_KEYS: health.ALLOWED_CONFIG_KEYS,
594
+ EXECUTION_PROFILES: health.EXECUTION_PROFILES,
595
+ VERIFICATION_DEPTHS: health.VERIFICATION_DEPTHS,
596
+ INSTALL_PROFILES: health.INSTALL_PROFILES,
597
+ INSTALL_REPO_LAYOUTS: health.INSTALL_REPO_LAYOUTS,
598
+ INSTALL_OBJECT_KEYS: health.INSTALL_OBJECT_KEYS,
599
+ EXPECTED_CODEBASE_MAPS: health.EXPECTED_CODEBASE_MAPS,
600
+ },
601
+
602
+ /** Workflows canónicos no disco. */
603
+ workflows: {
604
+ resolveWorkflowsDir: workflows.resolveWorkflowsDir,
605
+ listWorkflowMdFiles: workflows.listWorkflowMdFiles,
606
+ diffWorkflows: workflows.diffWorkflows,
607
+ validateWorkflowShapes: workflows.validateWorkflowShapes,
608
+ DEFAULT_MAX_BYTES_SOFT: workflows.DEFAULT_MAX_BYTES_SOFT,
609
+ SUCCESS_CRITERIA_EXCEPTIONS: workflows.SUCCESS_CRITERIA_EXCEPTIONS,
610
+ },
611
+
612
+ /** Resolução de opções de instalação a partir de `.oxe/config.json`. */
613
+ install: {
614
+ resolveOptionsFromConfig: installResolve.resolveInstallOptionsFromConfig,
615
+ },
616
+
617
+ /** Manifesto de ficheiros instalados em `~` (integridade / backup). */
618
+ manifest: {
619
+ loadFileManifest: manifest.loadFileManifest,
620
+ writeFileManifest: manifest.writeFileManifest,
621
+ sha256File: manifest.sha256File,
622
+ collectFilesRecursive: manifest.collectFilesRecursive,
623
+ MANIFEST_DIR: manifest.MANIFEST_DIR,
624
+ PATCHES_DIR: manifest.PATCHES_DIR,
625
+ },
626
+
627
+ /** Texto / multi-agente (rewrites de caminho, frontmatter). */
628
+ agents: {
629
+ adjustWorkflowPathsForNestedLayout: agentInstall.adjustWorkflowPathsForNestedLayout,
630
+ parseCursorCommandFrontmatter: agentInstall.parseCursorCommandFrontmatter,
631
+ },
632
+
633
+ /** Segurança: validação de caminhos e detecção de segredos. */
634
+ security: {
635
+ checkPathSafety: security.checkPathSafety,
636
+ scanFileForSecrets: security.scanFileForSecrets,
637
+ scanDirForSecretFiles: security.scanDirForSecretFiles,
638
+ validatePlanPaths: security.validatePlanPaths,
639
+ checkFilePermission: security.checkFilePermission,
640
+ checkPermissions: security.checkPermissions,
641
+ globToRegex: security.globToRegex,
642
+ DEFAULT_SECRET_PATTERNS: security.DEFAULT_SECRET_PATTERNS,
643
+ DEFAULT_SECRET_CONTENT_PATTERNS: security.DEFAULT_SECRET_CONTENT_PATTERNS,
644
+ DEFAULT_DENIED_PATH_PATTERNS: security.DEFAULT_DENIED_PATH_PATTERNS,
645
+ },
646
+
647
+ /** Plugin system — hooks de ciclo de vida em `.oxe/plugins/*.cjs`. */
648
+ plugins: {
649
+ loadPlugins: plugins.loadPlugins,
650
+ runHook: plugins.runHook,
651
+ validatePlugins: plugins.validatePlugins,
652
+ initPluginsDir: plugins.initPluginsDir,
653
+ resolvePluginSources: plugins.resolvePluginSources,
654
+ installNpmPlugin: plugins.installNpmPlugin,
655
+ },
656
+
657
+ /** Dashboard local: contexto consolidado e persistência de revisão do plano. */
658
+ dashboard: {
659
+ loadDashboardContext: dashboard.loadDashboardContext,
660
+ savePlanReviewStatus: dashboard.savePlanReviewStatus,
661
+ addPlanReviewComment: dashboard.addPlanReviewComment,
662
+ updatePlanReviewCommentStatus: dashboard.updatePlanReviewCommentStatus,
663
+ },
664
+
665
+ /** Release readiness: manifest, smoke matrix e checks de consistência antes de publicar. */
666
+ release: {
667
+ REQUIRED_RUNTIMES: release.REQUIRED_RUNTIMES,
668
+ WRAPPER_TARGETS: release.WRAPPER_TARGETS,
669
+ releasePaths: release.releasePaths,
670
+ collectWrapperHashes: release.collectWrapperHashes,
671
+ loadRuntimeSmokeReport: release.loadRuntimeSmokeReport,
672
+ loadRecoveryFixtureReport: release.loadRecoveryFixtureReport,
673
+ loadMultiAgentSoakReport: release.loadMultiAgentSoakReport,
674
+ buildReleaseManifest: release.buildReleaseManifest,
675
+ inspectCanonicalSource: release.inspectCanonicalSource,
676
+ evaluateReleaseManifest: release.evaluateReleaseManifest,
677
+ inspectReleaseReadiness: release.inspectReleaseReadiness,
678
+ checkReleaseConsistency: release.checkReleaseConsistency,
679
+ },
680
+
681
+ /** Runtime operacional: tracing, active run, catálogo de capabilities e memória em camadas. */
682
+ operational: {
683
+ operationalPaths: operational.operationalPaths,
684
+ appendEvent: operational.appendEvent,
685
+ readEvents: operational.readEvents,
686
+ summarizeEvents: operational.summarizeEvents,
687
+ writeRunState: operational.writeRunState,
688
+ readRunState: operational.readRunState,
689
+ buildOperationalGraph: operational.buildOperationalGraph,
690
+ serializeCanonicalState: operational.serializeCanonicalState,
691
+ hydrateCanonicalState: operational.hydrateCanonicalState,
692
+ reduceCanonicalRunState: operational.reduceCanonicalRunState,
693
+ compileExecutionGraphFromArtifacts: operational.compileExecutionGraphFromArtifacts,
694
+ compileVerificationSuiteFromArtifacts: operational.compileVerificationSuiteFromArtifacts,
695
+ projectRuntimeArtifacts: operational.projectRuntimeArtifacts,
696
+ runRuntimeCiChecks: operational.runRuntimeCiChecks,
697
+ buildRuntimePluginRegistry: operational.buildRuntimePluginRegistry,
698
+ readRuntimeGates: operational.readRuntimeGates,
699
+ resolveRuntimeGate: operational.resolveRuntimeGate,
700
+ runRuntimeVerify: operational.runRuntimeVerify,
701
+ runRuntimePromotion: operational.runRuntimePromotion,
702
+ recoverRuntimeState: operational.recoverRuntimeState,
703
+ applyRuntimeAction: operational.applyRuntimeAction,
704
+ parseCapabilityManifest: operational.parseCapabilityManifest,
705
+ readCapabilityCatalog: operational.readCapabilityCatalog,
706
+ buildMemoryLayers: operational.buildMemoryLayers,
707
+ replayEvents: operational.replayEvents,
708
+ replayRuntimeState: operational.replayRuntimeState,
709
+ readRuntimeMultiAgentStatus: operational.readRuntimeMultiAgentStatus,
710
+ multiAgentStatus: operational.readRuntimeMultiAgentStatus,
711
+ },
712
+
713
+ /** Context Engine V2: seleção, compressão e inspeção determinística de artefatos. */
714
+ context: {
715
+ contextPaths: context.contextPaths,
716
+ resolveArtifactCandidates: context.resolveArtifactCandidates,
717
+ buildProjectSummary: context.buildProjectSummary,
718
+ buildSessionSummary: context.buildSessionSummary,
719
+ buildPhaseSummary: context.buildPhaseSummary,
720
+ buildContextIndex: context.buildContextIndex,
721
+ buildContextPack: context.buildContextPack,
722
+ inspectContextPack: context.inspectContextPack,
723
+ buildAllContextPacks: context.buildAllContextPacks,
724
+ computeContextQuality: context.computeContextQuality,
725
+ computePackFreshness: context.computePackFreshness,
726
+ resolvePackFile: context.resolvePackFile,
727
+ summarizeText: context.summarizeText,
728
+ extractSemanticFragment: context.extractSemanticFragment,
729
+ parseHypotheses: context.parseHypotheses,
730
+ parseConfidenceVector: context.parseConfidenceVector,
731
+ },
732
+
733
+ /** Semântica canónica multi-runtime para workflows, wrappers e prompts gerados. */
734
+ runtimeSemantics: {
735
+ CONTRACT_VERSION: runtimeSemantics.CONTRACT_VERSION,
736
+ CONTRACTS_PATH: runtimeSemantics.CONTRACTS_PATH,
737
+ CONTRACTS_REGISTRY: runtimeSemantics.CONTRACTS_REGISTRY,
738
+ REQUIRED_CONTRACT_FIELDS: runtimeSemantics.REQUIRED_CONTRACT_FIELDS,
739
+ RUNTIME_METADATA_KEYS: runtimeSemantics.RUNTIME_METADATA_KEYS,
740
+ validateWorkflowContractsRegistry: runtimeSemantics.validateWorkflowContractsRegistry,
741
+ getWorkflowContract: runtimeSemantics.getWorkflowContract,
742
+ getAllWorkflowContracts: runtimeSemantics.getAllWorkflowContracts,
743
+ computeSemanticsHash: runtimeSemantics.computeSemanticsHash,
744
+ getRuntimeMetadataForSlug: runtimeSemantics.getRuntimeMetadataForSlug,
745
+ renderRuntimeMetadataLines: runtimeSemantics.renderRuntimeMetadataLines,
746
+ buildReasoningContractBlock: runtimeSemantics.buildReasoningContractBlock,
747
+ pickRuntimeMetadata: runtimeSemantics.pickRuntimeMetadata,
748
+ splitFrontmatter: runtimeSemantics.splitFrontmatter,
749
+ parseFrontmatterMap: runtimeSemantics.parseFrontmatterMap,
750
+ slugFromPromptFilename: runtimeSemantics.slugFromPromptFilename,
751
+ slugFromCommandFilename: runtimeSemantics.slugFromCommandFilename,
752
+ auditWrapperText: runtimeSemantics.auditWrapperText,
753
+ auditRuntimeTargets: runtimeSemantics.auditRuntimeTargets,
754
+ },
755
+
756
+ /** Provider Azure nativo via Azure CLI. */
757
+ azure: {
758
+ MIN_AZURE_CLI_MAJOR: azure.MIN_AZURE_CLI_MAJOR,
759
+ AZURE_CAPABILITY_IDS: azure.AZURE_CAPABILITY_IDS,
760
+ RESOURCE_GRAPH_QUERY: azure.RESOURCE_GRAPH_QUERY,
761
+ DEFAULT_AZURE_PROFILE: azure.DEFAULT_AZURE_PROFILE,
762
+ azurePaths: azure.azurePaths,
763
+ ensureAzureArtifacts: azure.ensureAzureArtifacts,
764
+ isAzureContextEnabled: azure.isAzureContextEnabled,
765
+ detectAzureCli: azure.detectAzureCli,
766
+ loadAzureProfile: azure.loadAzureProfile,
767
+ loadAzureAuthStatus: azure.loadAzureAuthStatus,
768
+ loadAzureInventory: azure.loadAzureInventory,
769
+ listAzureOperations: azure.listAzureOperations,
770
+ summarizeInventory: azure.summarizeInventory,
771
+ searchAzureInventory: azure.searchAzureInventory,
772
+ diffInventory: azure.diffInventory,
773
+ statusAzure: azure.statusAzure,
774
+ ensureAzureCapabilities: azure.ensureAzureCapabilities,
775
+ getAzureContext: azure.getAzureContext,
776
+ loginAzure: azure.loginAzure,
777
+ setAzureSubscription: azure.setAzureSubscription,
778
+ syncAzureInventory: azure.syncAzureInventory,
779
+ executeAzureRead: azure.executeAzureRead,
780
+ planAzureOperation: azure.planAzureOperation,
781
+ applyAzureOperation: azure.applyAzureOperation,
782
+ azureDoctor: azure.azureDoctor,
783
+ redactObject: azure.redactObject,
784
+ },
785
+
786
+ /**
787
+ * Catálogo único de artefatos do `.oxe/` — fonte da verdade da legenda
788
+ * (`.oxe/README.md`), do mapa vivo (`oxe-cc map`) e dos docs. Hosts podem
789
+ * consumir `buildMapModel(target)` para projetar o estado real do diretório.
790
+ */
791
+ artifacts: {
792
+ ARTIFACT_CATALOG: artifactCatalog.ARTIFACT_CATALOG,
793
+ GROUPS: artifactCatalog.GROUPS,
794
+ CORE_INSTALL_PATHS: artifactCatalog.CORE_INSTALL_PATHS,
795
+ SOURCE_LABELS: artifactCatalog.SOURCE_LABELS,
796
+ sourceLabel: artifactCatalog.sourceLabel,
797
+ renderLegend: artifactCatalog.renderLegend,
798
+ classifyEntry: artifactCatalog.classifyEntry,
799
+ buildMapModel: artifactCatalog.buildMapModel,
800
+ renderMap: artifactCatalog.renderMap,
801
+ },
802
+
803
+ /** Um único objeto com verificações tipo `doctor` + relatório de saúde. */
804
+ runDoctorChecks,
805
+ };
806
+
807
+
808
+ // Re-exports from @oxe/runtime (R1 — Runtime Foundation)
809
+ // The compiled runtime lives at lib/runtime/ alongside this file.
810
+ try {
811
+ const runtime = require('../runtime/index.js');
812
+ Object.assign(module.exports, runtime);
813
+ } catch {
814
+ // Runtime not built yet — safe to skip during development
815
+ }