oxe-cc 1.21.1 → 1.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (498) hide show
  1. package/.cursor/commands/oxe-alm.md +47 -0
  2. package/.cursor/commands/oxe-ask.md +1 -1
  3. package/.cursor/commands/oxe-capabilities.md +1 -1
  4. package/.cursor/commands/oxe-checkpoint.md +1 -1
  5. package/.cursor/commands/oxe-compact.md +1 -1
  6. package/.cursor/commands/oxe-dashboard.md +1 -1
  7. package/.cursor/commands/oxe-debug.md +1 -1
  8. package/.cursor/commands/oxe-discuss.md +45 -45
  9. package/.cursor/commands/oxe-execute.md +52 -50
  10. package/.cursor/commands/oxe-forensics.md +1 -1
  11. package/.cursor/commands/oxe-help.md +44 -44
  12. package/.cursor/commands/oxe-loop.md +1 -1
  13. package/.cursor/commands/oxe-milestone.md +1 -1
  14. package/.cursor/commands/oxe-next.md +44 -44
  15. package/.cursor/commands/oxe-obs.md +1 -1
  16. package/.cursor/commands/oxe-plan-agent.md +1 -1
  17. package/.cursor/commands/oxe-plan.md +49 -47
  18. package/.cursor/commands/oxe-project.md +1 -1
  19. package/.cursor/commands/oxe-quick.md +49 -47
  20. package/.cursor/commands/oxe-research.md +1 -1
  21. package/.cursor/commands/oxe-retro.md +1 -1
  22. package/.cursor/commands/oxe-review-pr.md +47 -47
  23. package/.cursor/commands/oxe-route.md +1 -1
  24. package/.cursor/commands/oxe-scan.md +47 -47
  25. package/.cursor/commands/oxe-security.md +1 -1
  26. package/.cursor/commands/oxe-session.md +1 -1
  27. package/.cursor/commands/oxe-ship.md +47 -47
  28. package/.cursor/commands/oxe-skill.md +1 -1
  29. package/.cursor/commands/oxe-spec.md +49 -47
  30. package/.cursor/commands/oxe-ui-review.md +1 -1
  31. package/.cursor/commands/oxe-ui-spec.md +1 -1
  32. package/.cursor/commands/oxe-update.md +1 -1
  33. package/.cursor/commands/oxe-validate-gaps.md +1 -1
  34. package/.cursor/commands/oxe-verify-audit.md +1 -1
  35. package/.cursor/commands/oxe-verify.md +50 -50
  36. package/.cursor/commands/oxe-workflow-authoring.md +1 -1
  37. package/.cursor/commands/oxe-workstream.md +1 -1
  38. package/.cursor/commands/oxe.md +51 -49
  39. package/.github/copilot-instructions.md +177 -177
  40. package/.github/dependabot.yml +31 -31
  41. package/.github/prompts/oxe-alm.prompt.md +47 -0
  42. package/.github/prompts/oxe-ask.prompt.md +47 -47
  43. package/.github/prompts/oxe-capabilities.prompt.md +47 -47
  44. package/.github/prompts/oxe-checkpoint.prompt.md +47 -47
  45. package/.github/prompts/oxe-compact.prompt.md +46 -46
  46. package/.github/prompts/oxe-dashboard.prompt.md +47 -47
  47. package/.github/prompts/oxe-debug.prompt.md +47 -47
  48. package/.github/prompts/oxe-discuss.prompt.md +47 -47
  49. package/.github/prompts/oxe-execute.prompt.md +52 -50
  50. package/.github/prompts/oxe-forensics.prompt.md +47 -47
  51. package/.github/prompts/oxe-help.prompt.md +46 -46
  52. package/.github/prompts/oxe-loop.prompt.md +47 -47
  53. package/.github/prompts/oxe-milestone.prompt.md +47 -47
  54. package/.github/prompts/oxe-next.prompt.md +46 -46
  55. package/.github/prompts/oxe-obs.prompt.md +47 -47
  56. package/.github/prompts/oxe-plan-agent.prompt.md +46 -46
  57. package/.github/prompts/oxe-plan.prompt.md +49 -47
  58. package/.github/prompts/oxe-project.prompt.md +47 -47
  59. package/.github/prompts/oxe-quick.prompt.md +49 -47
  60. package/.github/prompts/oxe-research.prompt.md +47 -47
  61. package/.github/prompts/oxe-retro.prompt.md +47 -47
  62. package/.github/prompts/oxe-review-pr.prompt.md +47 -47
  63. package/.github/prompts/oxe-route.prompt.md +47 -47
  64. package/.github/prompts/oxe-scan.prompt.md +47 -47
  65. package/.github/prompts/oxe-security.prompt.md +47 -47
  66. package/.github/prompts/oxe-session.prompt.md +47 -47
  67. package/.github/prompts/oxe-ship.prompt.md +47 -47
  68. package/.github/prompts/oxe-skill.prompt.md +47 -47
  69. package/.github/prompts/oxe-spec.prompt.md +49 -47
  70. package/.github/prompts/oxe-ui-review.prompt.md +47 -47
  71. package/.github/prompts/oxe-ui-spec.prompt.md +47 -47
  72. package/.github/prompts/oxe-update.prompt.md +46 -46
  73. package/.github/prompts/oxe-validate-gaps.prompt.md +47 -47
  74. package/.github/prompts/oxe-verify-audit.prompt.md +1 -1
  75. package/.github/prompts/oxe-verify.prompt.md +50 -50
  76. package/.github/prompts/oxe-workflow-authoring.prompt.md +1 -1
  77. package/.github/prompts/oxe-workstream.prompt.md +47 -47
  78. package/.github/prompts/oxe.prompt.md +51 -49
  79. package/.github/workflows/ci.yml +163 -163
  80. package/.github/workflows/release.yml +120 -120
  81. package/AGENTS.md +108 -102
  82. package/CHANGELOG.md +1883 -1042
  83. package/LICENSE +21 -21
  84. package/QUICKSTART.md +99 -99
  85. package/README.md +703 -673
  86. package/bin/banner.txt +18 -18
  87. package/bin/lib/oxe-acceptance-audit.cjs +195 -0
  88. package/bin/lib/oxe-adr.cjs +145 -0
  89. package/bin/lib/oxe-agent-install.cjs +679 -677
  90. package/bin/lib/oxe-alm-admin.cjs +215 -0
  91. package/bin/lib/oxe-alm-metrics.cjs +143 -0
  92. package/bin/lib/oxe-alm-prs.cjs +274 -0
  93. package/bin/lib/oxe-alm-refine.cjs +1003 -0
  94. package/bin/lib/oxe-alm.cjs +1289 -0
  95. package/bin/lib/oxe-anchor-copy.cjs +218 -0
  96. package/bin/lib/oxe-api-surface.cjs +96 -0
  97. package/bin/lib/oxe-artifact-catalog.cjs +376 -376
  98. package/bin/lib/oxe-artifact-refs.cjs +72 -0
  99. package/bin/lib/oxe-attention.cjs +97 -0
  100. package/bin/lib/oxe-autoresume.cjs +448 -0
  101. package/bin/lib/oxe-budget.cjs +154 -117
  102. package/bin/lib/oxe-change-folder.cjs +130 -0
  103. package/bin/lib/oxe-change.cjs +389 -230
  104. package/bin/lib/oxe-channels.cjs +82 -0
  105. package/bin/lib/oxe-cited-paths.cjs +180 -0
  106. package/bin/lib/oxe-cli-errors.cjs +76 -0
  107. package/bin/lib/oxe-cli-output.cjs +111 -0
  108. package/bin/lib/oxe-command-registry.cjs +31 -31
  109. package/bin/lib/oxe-commit-convention.cjs +104 -85
  110. package/bin/lib/oxe-complexity.cjs +106 -0
  111. package/bin/lib/oxe-console-decode.cjs +23 -0
  112. package/bin/lib/oxe-context-engine.cjs +874 -874
  113. package/bin/lib/oxe-coordinator-queue.cjs +67 -0
  114. package/bin/lib/oxe-core-command-handlers.cjs +84 -82
  115. package/bin/lib/oxe-criteria-ids.cjs +87 -0
  116. package/bin/lib/oxe-criterion-coverage.cjs +93 -58
  117. package/bin/lib/oxe-cross-card-conflicts.cjs +639 -0
  118. package/bin/lib/oxe-customize.cjs +146 -0
  119. package/bin/lib/oxe-dashboard.cjs +737 -737
  120. package/bin/lib/oxe-decisions.cjs +211 -0
  121. package/bin/lib/oxe-deferred.cjs +80 -0
  122. package/bin/lib/oxe-deps-audit.cjs +136 -0
  123. package/bin/lib/oxe-diff-reviewer.cjs +105 -0
  124. package/bin/lib/oxe-dir-info.cjs +138 -0
  125. package/bin/lib/oxe-docs-check.cjs +124 -0
  126. package/bin/lib/oxe-docs-publish.cjs +81 -0
  127. package/bin/lib/oxe-dom-hooks.cjs +902 -0
  128. package/bin/lib/oxe-dossier.cjs +355 -281
  129. package/bin/lib/oxe-e2e-ready.cjs +360 -0
  130. package/bin/lib/oxe-env-sanitize.cjs +155 -0
  131. package/bin/lib/oxe-event-bus.cjs +118 -118
  132. package/bin/lib/oxe-failure-cost.cjs +144 -0
  133. package/bin/lib/oxe-file-size-guard.cjs +849 -0
  134. package/bin/lib/oxe-findings.cjs +86 -0
  135. package/bin/lib/oxe-grill-cases.cjs +148 -0
  136. package/bin/lib/oxe-grill.cjs +444 -0
  137. package/bin/lib/oxe-grooming.cjs +115 -0
  138. package/bin/lib/oxe-guard.cjs +180 -0
  139. package/bin/lib/oxe-handoff.cjs +97 -0
  140. package/bin/lib/oxe-install-resolve.cjs +134 -134
  141. package/bin/lib/oxe-integration-checks.cjs +285 -0
  142. package/bin/lib/oxe-intent-context.cjs +101 -0
  143. package/bin/lib/oxe-journey.cjs +403 -0
  144. package/bin/lib/oxe-known-failures.cjs +138 -0
  145. package/bin/lib/oxe-local-config.cjs +77 -0
  146. package/bin/lib/oxe-manifest.cjs +124 -124
  147. package/bin/lib/oxe-memory-kernel.cjs +190 -188
  148. package/bin/lib/oxe-merge-train.cjs +277 -0
  149. package/bin/lib/oxe-model-resolve.cjs +74 -0
  150. package/bin/lib/oxe-model-tiers.cjs +65 -0
  151. package/bin/lib/oxe-nfr.cjs +125 -0
  152. package/bin/lib/oxe-npm-version.cjs +66 -66
  153. package/bin/lib/oxe-open-defects.cjs +121 -0
  154. package/bin/lib/oxe-operational.cjs +15949 -4484
  155. package/bin/lib/oxe-origin-guard.cjs +102 -0
  156. package/bin/lib/oxe-origin.cjs +377 -0
  157. package/bin/lib/oxe-pack-removed.cjs +208 -0
  158. package/bin/lib/oxe-parallel-run.cjs +81 -0
  159. package/bin/lib/oxe-parallel.cjs +234 -0
  160. package/bin/lib/oxe-phase-extras.cjs +185 -0
  161. package/bin/lib/oxe-phase-gates.cjs +551 -280
  162. package/bin/lib/oxe-plan-build.cjs +1520 -0
  163. package/bin/lib/oxe-plan-json.cjs +1107 -433
  164. package/bin/lib/oxe-plan-merge.cjs +253 -0
  165. package/bin/lib/oxe-plan-mutate.cjs +214 -0
  166. package/bin/lib/oxe-plan-repair.cjs +479 -0
  167. package/bin/lib/oxe-plan-review.cjs +256 -0
  168. package/bin/lib/oxe-plan-skeleton.cjs +494 -0
  169. package/bin/lib/oxe-plan-staleness.cjs +125 -0
  170. package/bin/lib/oxe-plugin-cli.cjs +97 -95
  171. package/bin/lib/oxe-plugins.cjs +432 -432
  172. package/bin/lib/oxe-policy-rules.cjs +144 -0
  173. package/bin/lib/oxe-prd.cjs +129 -0
  174. package/bin/lib/oxe-preflight.cjs +378 -0
  175. package/bin/lib/oxe-process.cjs +67 -67
  176. package/bin/lib/oxe-program-members.cjs +97 -0
  177. package/bin/lib/oxe-program.cjs +245 -205
  178. package/bin/lib/oxe-progress-run.cjs +80 -0
  179. package/bin/lib/oxe-project-env.cjs +273 -178
  180. package/bin/lib/oxe-project-health.cjs +3424 -2962
  181. package/bin/lib/oxe-promote-helpers.cjs +1561 -0
  182. package/bin/lib/oxe-provider-antigravity.cjs +114 -0
  183. package/bin/lib/oxe-provider-grok.cjs +48 -0
  184. package/bin/lib/oxe-questions.cjs +115 -0
  185. package/bin/lib/oxe-quick.cjs +537 -0
  186. package/bin/lib/oxe-ratchets.cjs +132 -0
  187. package/bin/lib/oxe-rationality.cjs +587 -556
  188. package/bin/lib/oxe-real-regression.cjs +97 -0
  189. package/bin/lib/oxe-recovery.cjs +160 -0
  190. package/bin/lib/oxe-release-ops.cjs +325 -0
  191. package/bin/lib/oxe-release.cjs +622 -593
  192. package/bin/lib/oxe-repair.cjs +153 -0
  193. package/bin/lib/oxe-repo-map.cjs +136 -0
  194. package/bin/lib/oxe-repo-rules.cjs +121 -108
  195. package/bin/lib/oxe-research-provenance.cjs +96 -0
  196. package/bin/lib/oxe-resume.cjs +406 -0
  197. package/bin/lib/oxe-review.cjs +403 -0
  198. package/bin/lib/oxe-rfc.cjs +192 -0
  199. package/bin/lib/oxe-risk-decision.cjs +141 -0
  200. package/bin/lib/oxe-runtime-semantics.cjs +521 -514
  201. package/bin/lib/oxe-scorecard.cjs +234 -164
  202. package/bin/lib/oxe-scratch.cjs +81 -0
  203. package/bin/lib/oxe-seams.cjs +159 -0
  204. package/bin/lib/oxe-semver.cjs +83 -0
  205. package/bin/lib/oxe-ship-pr.cjs +204 -0
  206. package/bin/lib/oxe-signal.cjs +173 -0
  207. package/bin/lib/oxe-skill-loader.cjs +131 -131
  208. package/bin/lib/oxe-spec-check.cjs +217 -0
  209. package/bin/lib/oxe-spec-ears.cjs +98 -0
  210. package/bin/lib/oxe-spec-edit.cjs +411 -0
  211. package/bin/lib/oxe-spec-freeze.cjs +378 -0
  212. package/bin/lib/oxe-spec-probe.cjs +146 -0
  213. package/bin/lib/oxe-spec-stress.cjs +146 -0
  214. package/bin/lib/oxe-spike.cjs +98 -98
  215. package/bin/lib/oxe-state.cjs +87 -0
  216. package/bin/lib/oxe-stub-check.cjs +355 -0
  217. package/bin/lib/oxe-suite-impact.cjs +1145 -0
  218. package/bin/lib/oxe-sync.cjs +250 -0
  219. package/bin/lib/oxe-system-design.cjs +138 -0
  220. package/bin/lib/oxe-task-gates.cjs +139 -0
  221. package/bin/lib/oxe-telemetry.cjs +201 -0
  222. package/bin/lib/oxe-test-precheck.cjs +508 -0
  223. package/bin/lib/oxe-test-rigor.cjs +663 -0
  224. package/bin/lib/oxe-test-scope.cjs +883 -0
  225. package/bin/lib/oxe-trace.cjs +168 -0
  226. package/bin/lib/oxe-turns.cjs +64 -0
  227. package/bin/lib/oxe-ui-evidence.cjs +187 -0
  228. package/bin/lib/oxe-ui-verify.cjs +55 -0
  229. package/bin/lib/oxe-unsafe-commands.cjs +94 -0
  230. package/bin/lib/oxe-verdicts.cjs +131 -0
  231. package/bin/lib/oxe-verify-dryrun.cjs +541 -152
  232. package/bin/lib/oxe-verify-remote.cjs +208 -0
  233. package/bin/lib/oxe-vitest-batch.cjs +142 -0
  234. package/bin/lib/oxe-workflow-budget.cjs +99 -0
  235. package/bin/lib/oxe-workflow-eval.cjs +118 -0
  236. package/bin/lib/oxe-workflows.cjs +147 -145
  237. package/bin/lib/oxe-worktree-deps.cjs +241 -0
  238. package/bin/lib/oxe-worktree-gc.cjs +170 -0
  239. package/bin/oxe-cc.js +10669 -6281
  240. package/commands/oxe/alm.md +54 -0
  241. package/commands/oxe/ask.md +55 -55
  242. package/commands/oxe/capabilities.md +50 -50
  243. package/commands/oxe/checkpoint.md +53 -53
  244. package/commands/oxe/compact.md +47 -47
  245. package/commands/oxe/dashboard.md +51 -51
  246. package/commands/oxe/debug.md +58 -58
  247. package/commands/oxe/discuss.md +58 -58
  248. package/commands/oxe/execute.md +63 -61
  249. package/commands/oxe/forensics.md +53 -53
  250. package/commands/oxe/help.md +48 -48
  251. package/commands/oxe/loop.md +54 -54
  252. package/commands/oxe/milestone.md +53 -53
  253. package/commands/oxe/next.md +49 -49
  254. package/commands/oxe/obs.md +53 -53
  255. package/commands/oxe/oxe.md +55 -53
  256. package/commands/oxe/plan-agent.md +57 -57
  257. package/commands/oxe/plan.md +59 -57
  258. package/commands/oxe/project.md +53 -53
  259. package/commands/oxe/quick.md +53 -53
  260. package/commands/oxe/research.md +53 -53
  261. package/commands/oxe/retro.md +53 -53
  262. package/commands/oxe/review-pr.md +53 -53
  263. package/commands/oxe/route.md +48 -48
  264. package/commands/oxe/scan.md +58 -58
  265. package/commands/oxe/security.md +53 -53
  266. package/commands/oxe/session.md +53 -53
  267. package/commands/oxe/ship.md +53 -53
  268. package/commands/oxe/skill.md +53 -53
  269. package/commands/oxe/spec.md +59 -56
  270. package/commands/oxe/ui-review.md +53 -53
  271. package/commands/oxe/ui-spec.md +53 -53
  272. package/commands/oxe/update.md +53 -53
  273. package/commands/oxe/validate-gaps.md +53 -53
  274. package/commands/oxe/verify-audit.md +50 -50
  275. package/commands/oxe/verify.md +60 -60
  276. package/commands/oxe/workflow-authoring.md +50 -50
  277. package/commands/oxe/workstream.md +53 -53
  278. package/docs/ADLC-COVERAGE.md +55 -0
  279. package/docs/CONTENT-MIGRATION-AUDIT.md +49 -49
  280. package/docs/HAPPY-PATH.md +106 -0
  281. package/docs/INCIDENT-PLAYBOOK.md +181 -181
  282. package/docs/INTEGRATION.md +182 -182
  283. package/docs/QUALITY-GATES.md +46 -46
  284. package/docs/RELEASE-READINESS.md +87 -87
  285. package/docs/ROLES.md +129 -129
  286. package/docs/RUNTIME-SMOKE-MATRIX.md +137 -137
  287. package/docs/TEAM-ADOPTION.md +153 -153
  288. package/docs/WALKTHROUGH.md +241 -241
  289. package/docs/adr/D-1-isolamento-read-only-e-sanitizacao-centralizada-de-env-vars.md +29 -0
  290. package/docs/adr/D-2-junction-segura-de-node-modules-condicionada-a-sha-256-de-pa.md +29 -0
  291. package/docs/adr/D-3-preflight-local-5s-impacto-estatico-e2e-e-leitura-explicita.md +29 -0
  292. package/docs/adr/D-4-governanca-de-release-unificada-retomada-idempotente-pos-rei.md +29 -0
  293. package/docs/adr/README.md +15 -0
  294. package/docs/cli-errors.md +20 -0
  295. package/docs/oxespace-1.5/BACKLOG.md +2056 -273
  296. package/docs/oxespace-1.5/HANDOFF-1.21.2.md +140 -0
  297. package/docs/oxevoice/BACKLOG.md +244 -244
  298. package/lib/runtime/compiler/graph-compiler.d.ts +2 -0
  299. package/lib/runtime/compiler/graph-compiler.js +11 -2
  300. package/lib/runtime/delivery/promotion-pipeline.d.ts +1 -0
  301. package/lib/runtime/delivery/promotion-pipeline.js +53 -0
  302. package/lib/runtime/events/catalog.d.ts +1 -1
  303. package/lib/runtime/events/catalog.js +18 -0
  304. package/lib/runtime/executor/action-tool-map.d.ts +3 -1
  305. package/lib/runtime/executor/action-tool-map.js +4 -1
  306. package/lib/runtime/executor/adapters/antigravity-cli.d.ts +103 -0
  307. package/lib/runtime/executor/adapters/antigravity-cli.js +530 -0
  308. package/lib/runtime/executor/adapters/claude-cli.d.ts +29 -0
  309. package/lib/runtime/executor/adapters/claude-cli.js +92 -14
  310. package/lib/runtime/executor/adapters/grok-cli.d.ts +89 -0
  311. package/lib/runtime/executor/adapters/grok-cli.js +351 -0
  312. package/lib/runtime/executor/adapters/registry.d.ts +6 -1
  313. package/lib/runtime/executor/adapters/registry.js +22 -2
  314. package/lib/runtime/executor/adapters/types.d.ts +1 -1
  315. package/lib/runtime/executor/built-in-tools.d.ts +56 -0
  316. package/lib/runtime/executor/built-in-tools.js +219 -17
  317. package/lib/runtime/executor/index.d.ts +9 -2
  318. package/lib/runtime/executor/index.js +23 -1
  319. package/lib/runtime/executor/llm-task-executor.d.ts +76 -3
  320. package/lib/runtime/executor/llm-task-executor.js +514 -31
  321. package/lib/runtime/executor/node-context.d.ts +11 -0
  322. package/lib/runtime/executor/node-context.js +10 -0
  323. package/lib/runtime/executor/node-prompt-builder.js +2 -0
  324. package/lib/runtime/executor/quota-patterns.d.ts +7 -0
  325. package/lib/runtime/executor/quota-patterns.js +39 -0
  326. package/lib/runtime/executor/shell-argv.d.ts +11 -0
  327. package/lib/runtime/executor/shell-argv.js +89 -2
  328. package/lib/runtime/executor/stream-completion.d.ts +16 -0
  329. package/lib/runtime/executor/stream-completion.js +72 -4
  330. package/lib/runtime/index.d.ts +1 -1
  331. package/lib/runtime/index.js +3 -1
  332. package/lib/runtime/models/failure.d.ts +1 -1
  333. package/lib/runtime/models/run.d.ts +1 -1
  334. package/lib/runtime/program/program-model.d.ts +20 -2
  335. package/lib/runtime/program/program-model.js +73 -6
  336. package/lib/runtime/projection/projection-engine.d.ts +6 -0
  337. package/lib/runtime/projection/projection-engine.js +30 -2
  338. package/lib/runtime/reducers/run-state-reducer.js +43 -5
  339. package/lib/runtime/scheduler/run-journal.d.ts +8 -0
  340. package/lib/runtime/scheduler/scheduler.d.ts +211 -2
  341. package/lib/runtime/scheduler/scheduler.js +982 -98
  342. package/lib/runtime/verification/runner-timeout.d.ts +7 -0
  343. package/lib/runtime/verification/runner-timeout.js +17 -0
  344. package/lib/runtime/verification/test-report-parsers.d.ts +2 -1
  345. package/lib/runtime/verification/test-report-parsers.js +9 -1
  346. package/lib/runtime/verification/verification-compiler.d.ts +34 -1
  347. package/lib/runtime/verification/verification-compiler.js +206 -74
  348. package/lib/runtime/verification/verification-manifest.d.ts +2 -0
  349. package/lib/runtime/verification/verification-manifest.js +15 -1
  350. package/lib/runtime/workspace/index.d.ts +2 -1
  351. package/lib/runtime/workspace/index.js +3 -1
  352. package/lib/runtime/workspace/strategies/ephemeral-container.d.ts +9 -0
  353. package/lib/runtime/workspace/strategies/ephemeral-container.js +37 -10
  354. package/lib/runtime/workspace/strategies/git-worktree.d.ts +15 -1
  355. package/lib/runtime/workspace/strategies/git-worktree.js +53 -1
  356. package/lib/sdk/README.md +82 -82
  357. package/lib/sdk/index.cjs +828 -815
  358. package/lib/sdk/index.d.ts +982 -982
  359. package/lib/sdk/index.types.ts +933 -933
  360. package/oxe/agents/oxe-assumptions-analyzer.md +136 -136
  361. package/oxe/agents/oxe-codebase-mapper.md +142 -142
  362. package/oxe/agents/oxe-debugger.md +145 -145
  363. package/oxe/agents/oxe-executor.md +139 -139
  364. package/oxe/agents/oxe-integration-checker.md +142 -142
  365. package/oxe/agents/oxe-plan-checker.md +143 -143
  366. package/oxe/agents/oxe-planner.md +151 -151
  367. package/oxe/agents/oxe-research-synthesizer.md +146 -146
  368. package/oxe/agents/oxe-researcher.md +163 -163
  369. package/oxe/agents/oxe-ui-auditor.md +151 -151
  370. package/oxe/agents/oxe-ui-checker.md +157 -157
  371. package/oxe/agents/oxe-ui-researcher.md +179 -179
  372. package/oxe/agents/oxe-validation-auditor.md +154 -154
  373. package/oxe/agents/oxe-verifier.md +132 -132
  374. package/oxe/migrations/config-migrations.json +15 -0
  375. package/oxe/personas/README.md +91 -91
  376. package/oxe/personas/architect.md +149 -149
  377. package/oxe/personas/db-specialist.md +149 -149
  378. package/oxe/personas/debugger.md +155 -155
  379. package/oxe/personas/executor.md +164 -164
  380. package/oxe/personas/planner.md +165 -165
  381. package/oxe/personas/researcher.md +148 -148
  382. package/oxe/personas/ui-specialist.md +164 -164
  383. package/oxe/personas/verifier.md +174 -174
  384. package/oxe/schemas/plan.schema.json +101 -85
  385. package/oxe/schemas/role-plan.schema.json +50 -0
  386. package/oxe/schemas/swarm-run.schema.json +130 -130
  387. package/oxe/templates/CONFIG.md +277 -105
  388. package/oxe/templates/DISCUSS.template.md +45 -44
  389. package/oxe/templates/EXECUTION-RUNTIME.template.md +68 -68
  390. package/oxe/templates/FIXTURE-PACK.template.json +41 -41
  391. package/oxe/templates/FIXTURE-PACK.template.md +30 -30
  392. package/oxe/templates/GLOSSARY.template.md +9 -0
  393. package/oxe/templates/IMPLEMENTATION-PACK.template.json +68 -68
  394. package/oxe/templates/IMPLEMENTATION-PACK.template.md +48 -48
  395. package/oxe/templates/PLAN.template.md +151 -151
  396. package/oxe/templates/PLUGINS.md +108 -108
  397. package/oxe/templates/PRD.template.md +53 -0
  398. package/oxe/templates/REFERENCE-ANCHORS.template.md +39 -35
  399. package/oxe/templates/RESEARCH.template.md +65 -57
  400. package/oxe/templates/RFC.template.md +43 -0
  401. package/oxe/templates/SPEC.template.md +119 -119
  402. package/oxe/templates/STATE-REFERENCE.md +125 -125
  403. package/oxe/templates/STATE.md +30 -30
  404. package/oxe/templates/SUMMARY.template.md +50 -50
  405. package/oxe/templates/VISUAL-INPUTS.template.json +27 -27
  406. package/oxe/templates/VISUAL-INPUTS.template.md +36 -36
  407. package/oxe/templates/config.template.json +38 -38
  408. package/oxe/templates/finding-rules.json +22 -0
  409. package/oxe/templates/stress-methods.md +33 -0
  410. package/oxe/workflows/agent-mode.md +150 -150
  411. package/oxe/workflows/alm.md +50 -0
  412. package/oxe/workflows/compact/plan.md +149 -0
  413. package/oxe/workflows/compact/spec.md +114 -0
  414. package/oxe/workflows/compact.md +45 -44
  415. package/oxe/workflows/conduct.md +149 -149
  416. package/oxe/workflows/debug.md +43 -43
  417. package/oxe/workflows/discuss.md +98 -86
  418. package/oxe/workflows/distill.md +164 -164
  419. package/oxe/workflows/execute.md +273 -269
  420. package/oxe/workflows/forensics.md +53 -53
  421. package/oxe/workflows/help.md +361 -355
  422. package/oxe/workflows/lean/execute.md +42 -0
  423. package/oxe/workflows/lean/plan.md +60 -0
  424. package/oxe/workflows/lean/spec.md +61 -0
  425. package/oxe/workflows/memory.md +163 -163
  426. package/oxe/workflows/next.md +47 -45
  427. package/oxe/workflows/oxe.md +168 -150
  428. package/oxe/workflows/plan.md +563 -556
  429. package/oxe/workflows/quick.md +199 -185
  430. package/oxe/workflows/references/alm-refine.md +55 -0
  431. package/oxe/workflows/references/azure-in-plan.md +5 -0
  432. package/oxe/workflows/references/change-management.md +48 -0
  433. package/oxe/workflows/references/flow-robustness-contract.md +80 -80
  434. package/oxe/workflows/references/grill.md +74 -0
  435. package/oxe/workflows/references/next-step-footer.md +33 -0
  436. package/oxe/workflows/references/plan-json-acceptance-program.md +174 -143
  437. package/oxe/workflows/references/product-docs-alm.md +51 -0
  438. package/oxe/workflows/references/workflow-runtime-contracts.json +1167 -1151
  439. package/oxe/workflows/research.md +67 -66
  440. package/oxe/workflows/route.md +32 -32
  441. package/oxe/workflows/scan.md +356 -355
  442. package/oxe/workflows/ship.md +91 -142
  443. package/oxe/workflows/size-budget.json +62 -0
  444. package/oxe/workflows/spec.md +615 -619
  445. package/oxe/workflows/swarm/board.md +119 -119
  446. package/oxe/workflows/swarm/scout.md +170 -170
  447. package/oxe/workflows/swarm-mode.md +280 -280
  448. package/oxe/workflows/ui-review.md +37 -37
  449. package/oxe/workflows/ui-spec.md +32 -32
  450. package/oxe/workflows/verify.md +273 -255
  451. package/package.json +134 -132
  452. package/packages/runtime/package.json +18 -18
  453. package/packages/runtime/src/compiler/graph-compiler.ts +349 -336
  454. package/packages/runtime/src/context/context-pack-builder.ts +339 -339
  455. package/packages/runtime/src/delivery/promotion-pipeline.ts +397 -342
  456. package/packages/runtime/src/events/catalog.ts +63 -45
  457. package/packages/runtime/src/executor/action-tool-map.ts +52 -50
  458. package/packages/runtime/src/executor/adapters/antigravity-cli.ts +619 -0
  459. package/packages/runtime/src/executor/adapters/claude-cli.ts +367 -285
  460. package/packages/runtime/src/executor/adapters/grok-cli.ts +392 -0
  461. package/packages/runtime/src/executor/adapters/http-openai.ts +16 -16
  462. package/packages/runtime/src/executor/adapters/registry.ts +53 -33
  463. package/packages/runtime/src/executor/adapters/types.ts +24 -24
  464. package/packages/runtime/src/executor/built-in-tools.ts +525 -333
  465. package/packages/runtime/src/executor/index.ts +23 -16
  466. package/packages/runtime/src/executor/llm-task-executor.ts +854 -336
  467. package/packages/runtime/src/executor/node-context.ts +226 -210
  468. package/packages/runtime/src/executor/node-prompt-builder.ts +69 -67
  469. package/packages/runtime/src/executor/quota-patterns.ts +41 -0
  470. package/packages/runtime/src/executor/shell-argv.ts +144 -66
  471. package/packages/runtime/src/executor/stream-completion.ts +230 -160
  472. package/packages/runtime/src/index.ts +56 -54
  473. package/packages/runtime/src/models/failure.ts +22 -13
  474. package/packages/runtime/src/models/run.ts +25 -24
  475. package/packages/runtime/src/plugins/capability-adapter.ts +313 -313
  476. package/packages/runtime/src/plugins/plugin-abi.ts +106 -106
  477. package/packages/runtime/src/plugins/plugin-registry.ts +241 -241
  478. package/packages/runtime/src/program/index.ts +1 -1
  479. package/packages/runtime/src/program/program-model.ts +293 -233
  480. package/packages/runtime/src/projection/projection-engine.ts +386 -361
  481. package/packages/runtime/src/reducers/run-state-reducer.ts +365 -329
  482. package/packages/runtime/src/scheduler/multi-agent-coordinator.ts +1017 -1017
  483. package/packages/runtime/src/scheduler/run-journal.ts +107 -105
  484. package/packages/runtime/src/scheduler/scheduler.ts +2081 -1144
  485. package/packages/runtime/src/verification/contract-exports.ts +203 -203
  486. package/packages/runtime/src/verification/index.ts +3 -3
  487. package/packages/runtime/src/verification/runner-timeout.ts +17 -0
  488. package/packages/runtime/src/verification/test-report-parsers.ts +204 -198
  489. package/packages/runtime/src/verification/verification-compiler.ts +906 -766
  490. package/packages/runtime/src/verification/verification-manifest.ts +296 -281
  491. package/packages/runtime/src/workspace/index.ts +6 -5
  492. package/packages/runtime/src/workspace/strategies/ephemeral-container.ts +159 -126
  493. package/packages/runtime/src/workspace/strategies/git-worktree.ts +190 -150
  494. package/packages/runtime/tsconfig.json +23 -23
  495. package/vscode-extension/.vscodeignore +9 -9
  496. package/vscode-extension/LICENSE +21 -21
  497. package/vscode-extension/package.json +193 -193
  498. package/vscode-extension/src/extension.js +320 -320
@@ -1,737 +1,737 @@
1
- 'use strict';
2
-
3
- const fs = require('fs');
4
- const path = require('path');
5
- const http = require('http');
6
- const { URL } = require('url');
7
- const health = require('./oxe-project-health.cjs');
8
- const operational = require('./oxe-operational.cjs');
9
- const azure = require('./oxe-azure.cjs');
10
- const contextEngine = require('./oxe-context-engine.cjs');
11
-
12
- function readTextIfExists(p) {
13
- try { return fs.existsSync(p) ? fs.readFileSync(p, 'utf8') : null; } catch { return null; }
14
- }
15
-
16
- function readJsonArrayIfExists(p) {
17
- try {
18
- if (!fs.existsSync(p)) return [];
19
- const raw = JSON.parse(fs.readFileSync(p, 'utf8'));
20
- return Array.isArray(raw) ? raw : [];
21
- } catch { return []; }
22
- }
23
-
24
- function ensureDirForFile(p) { fs.mkdirSync(path.dirname(p), { recursive: true }); }
25
- function firstMatch(text, regex) { const m = String(text || '').match(regex); return m ? m[1].trim() : null; }
26
- function escapeRegex(v) { return v.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); }
27
- function summarizeText(text, max = 500) { const clean = String(text || '').replace(/\r\n/g, '\n').trim(); return !clean ? '' : clean.length > max ? `${clean.slice(0, max - 1)}…` : clean; }
28
- function normalizeCell(v) { return String(v || '').replace(/<br\s*\/?>/gi, ' ').replace(/`/g, '').replace(/\s+/g, ' ').trim(); }
29
- function splitTableRow(line) { return line.trim().replace(/^\|/, '').replace(/\|$/, '').split('|').map((c) => normalizeCell(c)); }
30
-
31
- function parseMarkdownTables(text) {
32
- const lines = String(text || '').replace(/\r\n/g, '\n').split('\n');
33
- const tables = [];
34
- for (let i = 0; i < lines.length - 1; i += 1) {
35
- if (!lines[i].trim().startsWith('|')) continue;
36
- if (!/^\s*\|?[\-:\s|]+\|?\s*$/.test(lines[i + 1] || '')) continue;
37
- const headers = splitTableRow(lines[i]);
38
- const rows = [];
39
- let j = i + 2;
40
- while (j < lines.length && lines[j].trim().startsWith('|')) {
41
- const cells = splitTableRow(lines[j]);
42
- const row = {};
43
- for (let k = 0; k < headers.length; k += 1) row[headers[k]] = normalizeCell(cells[k] || '');
44
- rows.push(row);
45
- j += 1;
46
- }
47
- tables.push({ headers, rows });
48
- i = j - 1;
49
- }
50
- return tables;
51
- }
52
-
53
- function findTableByHeaders(text, expected) {
54
- const wants = expected.map((x) => x.toLowerCase());
55
- return parseMarkdownTables(text).find((table) => wants.every((w) => table.headers.some((h) => h.toLowerCase() === w)));
56
- }
57
-
58
- function listSectionItems(text, heading) {
59
- const match = String(text || '').match(new RegExp(`##\\s*${escapeRegex(heading)}\\s*\\n+([\\s\\S]*?)(?=\\n##\\s|$)`, 'i'));
60
- if (!match) return [];
61
- return match[1].split('\n').map((l) => l.trim()).filter((l) => /^-\s+/.test(l)).map((l) => l.replace(/^-\s+/, '').trim()).filter(Boolean);
62
- }
63
-
64
- function parsePlan(planMd) {
65
- const parts = planMd.split(/^###\s+(T\d+)\s*[—-]\s*/m);
66
- const tasks = [];
67
- const waves = {};
68
- for (let i = 1; i < parts.length; i += 2) {
69
- const id = parts[i].trim();
70
- const rest = (parts[i + 1] || '').split(/^###\s+T\d+/m)[0];
71
- const title = ((rest.match(/^([^\n]+)/) || [null, ''])[1] || '').trim();
72
- const wave = Number((rest.match(/\*\*Onda:\*\*\s*(\d+)/i) || [null, ''])[1]) || null;
73
- const dependsOn = (((rest.match(/\*\*Depende\s+de:\*\*\s*([^\n]+)/i) || [null, ''])[1]) || '').split(/[,\s]+/).filter((s) => /^T\d+$/.test(s.trim()));
74
- const verifyCommand = (rest.match(/Comando:\s*`([^`]+)`/i) || [null, null])[1];
75
- const aceite = ((((rest.match(/\*\*Aceite\s+vinculado:\*\*\s*([^\n]+)/i) || [null, ''])[1]) || '').match(/A\d+/g) || []);
76
- const decisions = ((((rest.match(/\*\*Decisão\s+vinculada:\*\*\s*([^\n]+)/i) || [null, ''])[1]) || '').match(/D-\d+/g) || []);
77
- const task = { id, title, wave, dependsOn, verifyCommand, aceite, decisions };
78
- tasks.push(task);
79
- if (wave != null) (waves[wave] ||= []).push(id);
80
- }
81
- return {
82
- tasks,
83
- totalTasks: tasks.length,
84
- waves: Object.keys(waves).map((k) => ({ wave: Number(k), taskIds: waves[k], tasks: waves[k].map((id) => tasks.find((t) => t.id === id)).filter(Boolean) })).sort((a, b) => a.wave - b.wave),
85
- };
86
- }
87
-
88
- function parseSpec(specMd) {
89
- const objective = (((specMd.match(/##\s*Objetivo\s*\n+([\s\S]*?)(?=\n##\s|\n#[^\#]|$)/im) || [null, ''])[1]) || '').trim().split('\n')[0].trim() || null;
90
- const criteria = [];
91
- const m = specMd.match(/##\s*Critérios.*?aceite[\s\S]*?(\|[\s\S]*?)(?=\n##\s|\n#[^\#]|$)/im);
92
- if (m) {
93
- for (const row of m[1].split('\n').filter((l) => l.startsWith('|'))) {
94
- const cells = row.split('|').map((c) => c.trim()).filter(Boolean);
95
- if (cells.length >= 2 && /^A\d+$/i.test(cells[0])) criteria.push({ id: cells[0].toUpperCase(), criterion: cells[1] || '', howToVerify: cells[2] || '' });
96
- }
97
- }
98
- return { objective, criteria };
99
- }
100
-
101
- function parseRuntime(runtimeMd) {
102
- const agentTable = findTableByHeaders(runtimeMd, ['ID', 'Papel', 'Tarefas', 'Estado']);
103
- const checkpointTable = findTableByHeaders(runtimeMd, ['ID', 'Tipo', 'Escopo', 'Estado']);
104
- return {
105
- currentWave: Number(firstMatch(runtimeMd, /\*\*Onda:\*\*\s*([^\n]+)/i)) || firstMatch(runtimeMd, /\*\*Onda:\*\*\s*([^\n]+)/i),
106
- status: firstMatch(runtimeMd, /\*\*Estado:\*\*\s*([^\n]+)/i),
107
- activeTasks: ((firstMatch(runtimeMd, /\*\*Tarefas ativas:\*\*\s*([^\n]+)/i) || '').split(',').map((x) => x.trim()).filter(Boolean)),
108
- nextAction: firstMatch(runtimeMd, /\*\*Ação:\*\*\s*([^\n]+)/i),
109
- nextReason: firstMatch(runtimeMd, /\*\*Motivo:\*\*\s*([^\n]+)/i),
110
- agents: (agentTable?.rows || []).map((row) => ({ id: row.ID || row.Id || '—', role: row.Papel || row.Role || '—', tasks: (row.Tarefas || row.Tasks || '').split(',').map((x) => x.trim()).filter(Boolean), status: row.Estado || row.Status || '—' })),
111
- checkpoints: (checkpointTable?.rows || []).map((row) => ({ id: row.ID || row.Id || '—', type: row.Tipo || row.Type || '—', scope: row.Escopo || row.Scope || '—', status: row.Estado || row.Status || '—', decision: row.Decisão || row.Decisao || row.Decision || '—' })),
112
- evidence: listSectionItems(runtimeMd, 'Evidências produzidas'),
113
- blockages: listSectionItems(runtimeMd, 'Bloqueios').filter((x) => !/^(\(nenhum\)|nenhum)$/i.test(x)),
114
- };
115
- }
116
-
117
- function parseCheckpointsIndex(md) {
118
- const table = findTableByHeaders(md, ['ID', 'Tipo', 'Fase', 'Escopo', 'Estado']);
119
- return (table?.rows || []).map((row) => ({ id: row.ID || row.Id || '—', type: row.Tipo || row.Type || '—', phase: row.Fase || row.Phase || '—', scope: row.Escopo || row.Scope || '—', status: row.Estado || row.Status || '—', notes: row.Notas || row.Notes || '—' }));
120
- }
121
-
122
- function parseSessionsIndex(md) {
123
- const table = parseMarkdownTables(md).find((t) => {
124
- const h = t.headers.map((x) => x.toLowerCase());
125
- return h.includes('id') && h.includes('nome') && h.includes('status') && h.includes('path');
126
- });
127
- return (table?.rows || []).map((row) => ({ id: row.ID || row.Id || '—', name: row.Nome || row.Name || '—', status: row.Status || '—', createdAt: row.Criada || row.Created || '—', lastActivity: row['Última atividade'] || row['Ultima atividade'] || row['Last activity'] || '—', summary: row.Resumo || row.Summary || '—', path: (row.Path || row.Caminho || '—').replace(/`/g, '') }));
128
- }
129
-
130
- function parseSessionDetail(md) {
131
- return { id: firstMatch(md, /\*\*ID:\*\*\s*([^\n]+)/i), name: firstMatch(md, /\*\*Nome:\*\*\s*([^\n]+)/i), status: firstMatch(md, /\*\*Status:\*\*\s*([^\n]+)/i), createdAt: firstMatch(md, /\*\*Criada:\*\*\s*([^\n]+)/i), lastActivity: firstMatch(md, /\*\*(?:Última|Ultima) atividade:\*\*\s*([^\n]+)/i), summary: firstMatch(md, /\*\*Resumo:\*\*\s*([^\n]+)/i), tags: listSectionItems(md, 'Tags'), history: (findTableByHeaders(md, ['Data', 'Evento'])?.rows || []).map((row) => ({ date: row.Data || row.Date || '—', event: row.Evento || row.Event || '—' })) };
132
- }
133
-
134
- function normalizeEvidenceStatus(raw) {
135
- const v = String(raw || '').toLowerCase();
136
- if (!v) return 'mentioned';
137
- if (/(ok|pass|aprov|sim|true|done|conclu)/.test(v)) return 'passed';
138
- if (/(fail|falh|reprov|não|nao|false|blocked)/.test(v)) return 'failed';
139
- return 'mentioned';
140
- }
141
-
142
- function parseVerify(md) {
143
- const criteria = [];
144
- for (const table of parseMarkdownTables(md)) {
145
- for (const row of table.rows) {
146
- const idCandidate = row.ID || row.Id || row['Critério'] || row['Criterio'] || '';
147
- const match = String(idCandidate).match(/A\d+/i);
148
- if (!match) continue;
149
- criteria.push({ id: match[0].toUpperCase(), status: normalizeEvidenceStatus(row.Status || row.Resultado || row.Result || row.Veredito || row['Passou?'] || ''), summary: row.Evidência || row.Evidencia || row.Resumo || row.Notas || '' });
150
- }
151
- }
152
- return { criteria, mentionedCriteria: Array.from(new Set((md.match(/\bA\d+\b/g) || []).map((x) => x.toUpperCase()))), failed: /\b(verify_failed|falhou|falha|reprovad)\b/i.test(md), passed: /\b(verify_complete|aprovad|passou|sucesso)\b/i.test(md) };
153
- }
154
-
155
- function confidenceBand(confidence, threshold) {
156
- const normalizedThreshold = health.normalizePlanConfidenceThreshold(threshold);
157
- if (confidence == null) return 'unknown';
158
- if (health.isExecutablePlanConfidence(confidence, normalizedThreshold)) return 'ready';
159
- if (confidence >= Math.max(80, normalizedThreshold - 10)) return 'rational_but_not_ready';
160
- if (confidence >= 50) return 'needs_refinement';
161
- return 'do_not_execute';
162
- }
163
-
164
- function computeReadiness(ctx, threshold) {
165
- if (ctx.workspaceMode === 'product_package' && ctx.releaseReadiness) {
166
- const blockers = Array.isArray(ctx.releaseReadiness.blockers) ? ctx.releaseReadiness.blockers.slice() : [];
167
- const warnings = Array.isArray(ctx.releaseReadiness.warnings) ? ctx.releaseReadiness.warnings.slice() : [];
168
- return {
169
- go: Boolean(ctx.releaseReadiness.ok),
170
- decision: ctx.releaseReadiness.ok ? 'go' : 'no-go',
171
- threshold: health.normalizePlanConfidenceThreshold(threshold),
172
- confidence: ctx.plan && ctx.plan.selfEvaluation ? ctx.plan.selfEvaluation.confidence : null,
173
- confidenceBand: confidenceBand(ctx.plan && ctx.plan.selfEvaluation ? ctx.plan.selfEvaluation.confidence : null, threshold),
174
- checkpointPending: false,
175
- blockers,
176
- warnings,
177
- };
178
- }
179
- const normalizedThreshold = health.normalizePlanConfidenceThreshold(threshold);
180
- const blockers = [];
181
- const warnings = [...ctx.diagnostics.reviewWarnings, ...ctx.diagnostics.runtimeWarnings, ...ctx.diagnostics.planWarnings];
182
- if (!ctx.plan.selfEvaluation || !ctx.plan.selfEvaluation.hasSection) blockers.push('self_evaluation:missing');
183
- if (ctx.plan.selfEvaluation && Array.isArray(ctx.plan.selfEvaluation.warnings) && ctx.plan.selfEvaluation.warnings.length) {
184
- blockers.push(`self_evaluation:warnings:${ctx.plan.selfEvaluation.warnings.length}`);
185
- }
186
- if (ctx.planReviewStatus !== 'approved') blockers.push(`review_status:${ctx.planReviewStatus || 'draft'}`);
187
- if (ctx.plan.selfEvaluation.bestPlan === 'não') blockers.push('best_plan:no');
188
- if (ctx.plan.selfEvaluation.confidence == null) blockers.push('confidence:missing');
189
- else if (!health.isExecutablePlanConfidence(ctx.plan.selfEvaluation.confidence, normalizedThreshold)) {
190
- blockers.push(`confidence:${ctx.plan.selfEvaluation.confidence}%<=${normalizedThreshold}%`);
191
- }
192
- if (!ctx.executionRationality || !ctx.executionRationality.implementationPackReady) {
193
- blockers.push('implementation_pack:not_ready');
194
- }
195
- if (!ctx.executionRationality || !ctx.executionRationality.referenceAnchorsReady) {
196
- blockers.push('reference_anchors:not_ready');
197
- }
198
- if (!ctx.executionRationality || !ctx.executionRationality.fixturePackReady) {
199
- blockers.push('fixture_pack:not_ready');
200
- }
201
- if (ctx.checkpoints.parsed.some((x) => /pending_approval/i.test(x.status))) blockers.push('checkpoint:pending_approval');
202
- if (ctx.runtime.parsed.status === 'blocked') blockers.push('runtime:blocked');
203
- if (ctx.spec.uncoveredCriteria.length) warnings.push(`${ctx.spec.uncoveredCriteria.length} critérios sem cobertura no plano`);
204
- if (ctx.executionRationality && Array.isArray(ctx.executionRationality.criticalExecutionGaps)) {
205
- warnings.push(...ctx.executionRationality.criticalExecutionGaps);
206
- }
207
- return {
208
- go: blockers.length === 0,
209
- decision: blockers.length === 0 ? 'go' : 'no-go',
210
- threshold: normalizedThreshold,
211
- confidence: ctx.plan.selfEvaluation.confidence,
212
- confidenceBand: confidenceBand(ctx.plan.selfEvaluation.confidence, normalizedThreshold),
213
- checkpointPending: blockers.includes('checkpoint:pending_approval'),
214
- blockers,
215
- warnings,
216
- };
217
- }
218
-
219
- function buildCoverageMatrix(spec, plan, verify) {
220
- const taskMap = new Map();
221
- for (const task of plan.tasks) {
222
- for (const criterion of task.aceite || []) {
223
- if (!taskMap.has(criterion)) taskMap.set(criterion, []);
224
- taskMap.get(criterion).push(task.id);
225
- }
226
- }
227
- const verifyMap = new Map((verify.criteria || []).map((x) => [x.id, x]));
228
- return spec.criteria.map((c) => ({
229
- id: c.id,
230
- criterion: c.criterion,
231
- verifyHow: c.howToVerify,
232
- tasks: taskMap.get(c.id) || [],
233
- planCovered: taskMap.has(c.id),
234
- verifyStatus: verifyMap.has(c.id) ? verifyMap.get(c.id).status : (verify.mentionedCriteria || []).includes(c.id) ? 'mentioned' : 'missing',
235
- verifySummary: verifyMap.has(c.id) ? verifyMap.get(c.id).summary : '',
236
- }));
237
- }
238
-
239
- function computeCalibration(phase, confidence, verify, threshold) {
240
- const normalizedThreshold = health.normalizePlanConfidenceThreshold(threshold);
241
- if (confidence == null) return { status: 'pending', summary: 'Calibração indisponível antes do verify.' };
242
- const low = String(phase || '').toLowerCase();
243
- const completed = low === 'verify_complete' || verify.passed;
244
- const failed = low === 'verify_failed' || verify.failed;
245
- if (!completed && !failed) return { status: 'pending', summary: 'Calibração só fecha após verify.' };
246
- if (health.isExecutablePlanConfidence(confidence, normalizedThreshold) && failed) {
247
- return { status: 'overconfident', summary: `Confiança ${confidence}% acima do gate executável, mas o verify falhou.` };
248
- }
249
- if (!health.isExecutablePlanConfidence(confidence, normalizedThreshold) && failed) {
250
- return { status: 'calibrated-risk', summary: `O plano já sinalizava risco (${confidence}%) abaixo do gate executável e o verify confirmou a fragilidade.` };
251
- }
252
- if (!health.isExecutablePlanConfidence(confidence, normalizedThreshold) && completed) {
253
- return { status: 'underconfident', summary: `O resultado final foi melhor que a confiança inicial (${confidence}%), mas o plano ainda não superava o gate executável.` };
254
- }
255
- if (health.isExecutablePlanConfidence(confidence, normalizedThreshold) && completed) {
256
- return { status: 'well-calibrated', summary: `Alta confiança executável (${confidence}%) e verify coerente com a expectativa.` };
257
- }
258
- return { status: 'acceptable', summary: `Confiança ${confidence}% e verify dentro da faixa esperada.` };
259
- }
260
-
261
- function readRepositoryContext(codebaseDir) {
262
- const names = ['OVERVIEW.md', 'STACK.md', 'STRUCTURE.md', 'TESTING.md', 'CONCERNS.md', 'INTEGRATIONS.md'];
263
- const out = {};
264
- for (const name of names) out[name.replace('.md', '').toLowerCase()] = { path: path.join(codebaseDir, name), summary: summarizeText(readTextIfExists(path.join(codebaseDir, name)) || '', 420) };
265
- return out;
266
- }
267
-
268
- function ensureStateSection(stateText, sectionTitle) {
269
- return new RegExp(`##\\s*${escapeRegex(sectionTitle)}`, 'i').test(stateText) ? stateText : `${stateText.trimEnd()}\n\n## ${sectionTitle}\n\n`;
270
- }
271
-
272
- function upsertBulletInSection(body, label, value) {
273
- const line = `- **${label}:** ${value}`;
274
- const re = new RegExp(`^- \\*\\*${escapeRegex(label)}:\\*\\*.*$`, 'im');
275
- if (re.test(body)) return body.replace(re, line);
276
- const trimmed = body.trimEnd();
277
- return !trimmed ? `${line}\n` : `${trimmed}\n${line}\n`;
278
- }
279
-
280
- function upsertStateBullet(stateText, sectionTitle, label, value) {
281
- const ensured = ensureStateSection(stateText, sectionTitle);
282
- const re = new RegExp(`(##\\s*${escapeRegex(sectionTitle)}\\s*\\n+)([\\s\\S]*?)(?=\\n##\\s|$)`, 'i');
283
- return ensured.replace(re, (m, head, body) => `${head}${upsertBulletInSection(body, label, value)}`);
284
- }
285
-
286
- function reviewPaths(projectRoot, activeSession) {
287
- const p = health.scopedOxePaths(projectRoot, activeSession);
288
- return { ...p, state: health.oxePaths(projectRoot).state, reviewJson: p.planReviewComments };
289
- }
290
-
291
- function readScopedText(primaryPath, fallbackPath) {
292
- const primary = readTextIfExists(primaryPath);
293
- if (primary) return primary;
294
- return fallbackPath && fallbackPath !== primaryPath ? readTextIfExists(fallbackPath) || '' : '';
295
- }
296
-
297
- function savePlanReviewStatus(projectRoot, input = {}) {
298
- const globalStatePath = health.oxePaths(projectRoot).state;
299
- const stateText = readTextIfExists(globalStatePath) || '# OXE — Estado\n';
300
- const activeSession = input.activeSession === undefined ? health.parseActiveSession(stateText) : input.activeSession;
301
- const p = reviewPaths(projectRoot, activeSession || null);
302
- const nowIso = new Date().toISOString();
303
- const status = String(input.status || 'draft');
304
- const note = String(input.note || '—');
305
- const author = String(input.author || 'dashboard');
306
- const reviewRef = path.relative(path.join(projectRoot, '.oxe'), p.planReview).replace(/\\/g, '/');
307
- let nextState = stateText;
308
- nextState = upsertStateBullet(nextState, 'Revisão do plano (opcional — dashboard / aprovação)', 'plan_review_status', `\`${status}\``);
309
- nextState = upsertStateBullet(nextState, 'Revisão do plano (opcional — dashboard / aprovação)', 'plan_review_updated', `\`${nowIso}\``);
310
- nextState = upsertStateBullet(nextState, 'Revisão do plano (opcional — dashboard / aprovação)', 'plan_review_ref', `\`${reviewRef}\``);
311
- nextState = upsertStateBullet(nextState, 'Revisão do plano (opcional — dashboard / aprovação)', 'Notas', note);
312
- ensureDirForFile(globalStatePath);
313
- fs.writeFileSync(globalStatePath, nextState, 'utf8');
314
- const comments = readJsonArrayIfExists(p.reviewJson);
315
- const format = (c) => `- **${c.target || 'plan'}** [${c.type || 'note'} | ${c.status || 'open'}] ${c.text || ''}`;
316
- const reviewMd =
317
- `---\noxe_doc: plan_review\nstatus: ${status}\nupdated: ${nowIso.slice(0, 10)}\nplan_ref: ${path.basename(p.plan)}\n---\n\n# OXE — Revisão do Plano\n\n## Estado\n\n- **Status:** ${status}\n- **Atualizado em:** ${nowIso}\n- **Origem:** dashboard local\n- **Autor:** ${author}\n\n## Decisão\n\n- **Resultado:** ${status}\n- **Justificativa:** ${note}\n\n## Comentários abertos\n\n${comments.filter((x) => x.status !== 'resolved').map(format).join('\n') || '- Nenhum'}\n\n## Comentários resolvidos\n\n${comments.filter((x) => x.status === 'resolved').map(format).join('\n') || '- Nenhum'}\n\n## Próxima ação recomendada\n\n${status === 'approved' ? '- `/oxe-execute` ou `oxe-cc status` para seguir a trilha.' : '- `/oxe-plan --replan` ou ajuste do plano antes de executar.'}\n`;
318
- ensureDirForFile(p.planReview);
319
- fs.writeFileSync(p.planReview, reviewMd, 'utf8');
320
- operational.appendEvent(projectRoot, activeSession || null, {
321
- type: 'plan_review_status_changed',
322
- payload: { status, note, author, review_ref: reviewRef },
323
- });
324
- return { status, updatedAt: nowIso, ref: p.planReview, note, author, activeSession: activeSession || null };
325
- }
326
-
327
- function addPlanReviewComment(projectRoot, input = {}) {
328
- const stateText = readTextIfExists(health.oxePaths(projectRoot).state) || '# OXE — Estado\n';
329
- const activeSession = input.activeSession === undefined ? health.parseActiveSession(stateText) : input.activeSession;
330
- const p = reviewPaths(projectRoot, activeSession || null);
331
- const comments = readJsonArrayIfExists(p.reviewJson);
332
- const next = { id: `c-${Date.now().toString(36)}`, target: String(input.target || 'plan'), type: String(input.type || 'note'), status: 'open', author: String(input.author || 'dashboard'), created_at: new Date().toISOString(), text: String(input.text || '').trim() };
333
- comments.push(next);
334
- ensureDirForFile(p.reviewJson);
335
- fs.writeFileSync(p.reviewJson, JSON.stringify(comments, null, 2), 'utf8');
336
- operational.appendEvent(projectRoot, activeSession || null, {
337
- type: 'plan_review_comment_added',
338
- payload: { comment_id: next.id, target: next.target, comment_type: next.type },
339
- });
340
- savePlanReviewStatus(projectRoot, { activeSession, status: health.parsePlanReviewStatus(stateText) || 'in_review', note: 'Há comentários de revisão em aberto', author: String(input.author || 'dashboard') });
341
- return next;
342
- }
343
-
344
- function updatePlanReviewCommentStatus(projectRoot, input = {}) {
345
- const stateText = readTextIfExists(health.oxePaths(projectRoot).state) || '# OXE — Estado\n';
346
- const activeSession = input.activeSession === undefined ? health.parseActiveSession(stateText) : input.activeSession;
347
- const p = reviewPaths(projectRoot, activeSession || null);
348
- const comments = readJsonArrayIfExists(p.reviewJson);
349
- const idx = comments.findIndex((x) => x.id === input.commentId);
350
- if (idx === -1) return null;
351
- comments[idx] = { ...comments[idx], status: String(input.status || 'resolved'), updated_at: new Date().toISOString() };
352
- fs.writeFileSync(p.reviewJson, JSON.stringify(comments, null, 2), 'utf8');
353
- operational.appendEvent(projectRoot, activeSession || null, {
354
- type: 'plan_review_comment_updated',
355
- payload: { comment_id: comments[idx].id, status: comments[idx].status },
356
- });
357
- return comments[idx];
358
- }
359
-
360
- function loadDashboardContext(projectRoot, opts = {}) {
361
- const globalPaths = health.oxePaths(projectRoot);
362
- const stateText = readTextIfExists(globalPaths.state) || '';
363
- const activeSession = opts.activeSession === undefined ? health.parseActiveSession(stateText) : opts.activeSession;
364
- const p = reviewPaths(projectRoot, activeSession || null);
365
- const rootScoped = reviewPaths(projectRoot, null);
366
- const report = health.buildHealthReport(projectRoot);
367
- const specText = readScopedText(p.spec, rootScoped.spec);
368
- const planText = readScopedText(p.plan, rootScoped.plan);
369
- const verifyText = readScopedText(p.verify, rootScoped.verify);
370
- const runtimeText = readScopedText(p.runtime, rootScoped.runtime);
371
- const checkpointsText = readScopedText(p.checkpoints, rootScoped.checkpoints);
372
- const spec = parseSpec(specText);
373
- const plan = parsePlan(planText);
374
- const runtime = parseRuntime(runtimeText);
375
- const checkpoints = parseCheckpointsIndex(checkpointsText);
376
- const verify = parseVerify(verifyText);
377
- const activeRunState = operational.readRunState(projectRoot, activeSession || null);
378
- const traceEvents = operational.readEvents(projectRoot, activeSession || null);
379
- const traceSummary = operational.summarizeEvents(traceEvents);
380
- const memoryLayers = operational.buildMemoryLayers(projectRoot, activeSession || null);
381
- const capabilityCatalog = operational.readCapabilityCatalog(projectRoot);
382
- const azurePaths = azure.azurePaths(projectRoot);
383
- const dashboardPack = report.contextPacks && report.contextPacks.dashboard
384
- ? report.contextPacks.dashboard
385
- : contextEngine.inspectContextPack(projectRoot, { workflow: 'dashboard', activeSession: activeSession || null });
386
- const sessionsRaw = readTextIfExists(globalPaths.sessionsIndex) || '';
387
- const sessions = parseSessionsIndex(sessionsRaw);
388
- const sessionPath = activeSession ? path.join(projectRoot, '.oxe', activeSession, 'SESSION.md') : null;
389
- const sessionRaw = sessionPath ? readTextIfExists(sessionPath) || '' : '';
390
- const ctx = {
391
- projectRoot: path.resolve(projectRoot),
392
- workspaceMode: report.workspaceMode || 'oxe_project',
393
- releaseReadiness: report.releaseReadiness || null,
394
- activeSession: activeSession || null,
395
- phase: report.phase || health.parseStatePhase(stateText),
396
- healthStatus: report.healthStatus,
397
- nextStep: report.next,
398
- planReviewStatus: report.planReviewStatus || 'draft',
399
- state: { path: globalPaths.state, raw: stateText, parsed: { phase: health.parseStatePhase(stateText), activeSession, runtimeStatus: firstMatch(stateText, /\*\*runtime_status:\*\*\s*([^\n]+)/i) } },
400
- spec: { path: p.spec, raw: specText, objective: spec.objective, criteria: spec.criteria, uncoveredCriteria: spec.criteria.filter((c) => !plan.tasks.some((t) => (t.aceite || []).includes(c.id))) },
401
- plan: { path: p.plan, raw: planText, tasks: plan.tasks, waves: plan.waves, totalTasks: plan.totalTasks, selfEvaluation: report.planSelfEvaluation },
402
- executionRationality: report.executionRationality || null,
403
- runtime: { path: p.runtime, raw: runtimeText, summary: summarizeText(runtimeText, 800), parsed: runtime },
404
- activeRun: activeRunState,
405
- runtimeCanonical: activeRunState && activeRunState.canonical_state ? activeRunState.canonical_state : null,
406
- compiledGraph: activeRunState && activeRunState.compiled_graph ? activeRunState.compiled_graph : null,
407
- enterprise: {
408
- runtimeMode: report.runtimeMode || null,
409
- fallbackMode: report.fallbackMode || null,
410
- verificationSummary: report.verificationSummary || null,
411
- residualRiskSummary: report.residualRiskSummary || null,
412
- evidenceCoverage: report.evidenceCoverage || null,
413
- pendingGates: report.pendingGates || null,
414
- gateQueue: report.gateQueue || null,
415
- policyDecisionSummary: report.policyDecisionSummary || null,
416
- policyCoverage: report.policyCoverage || null,
417
- quotaSummary: report.quotaSummary || null,
418
- auditSummary: report.auditSummary || null,
419
- promotionSummary: report.promotionSummary || null,
420
- promotionReadiness: report.promotionReadiness || null,
421
- recoveryState: report.recoveryState || null,
422
- multiAgent: report.multiAgent || null,
423
- providerCatalog: report.providerCatalog || null,
424
- implementationPackReady: report.implementationPackReady,
425
- referenceAnchorsReady: report.referenceAnchorsReady,
426
- fixturePackReady: report.fixturePackReady,
427
- executionRationalityReady: report.executionRationalityReady,
428
- criticalExecutionGaps: report.criticalExecutionGaps || [],
429
- warnings: report.enterpriseWarn || [],
430
- },
431
- tracing: { path: operational.operationalPaths(projectRoot, activeSession || null).events, events: traceEvents, summary: traceSummary },
432
- checkpoints: { path: p.checkpoints, raw: checkpointsText, parsed: checkpoints },
433
- verify: { path: p.verify, raw: verifyText, summary: summarizeText(verifyText, 800), parsed: verify },
434
- review: { markdownPath: p.planReview, commentsPath: p.reviewJson, comments: readJsonArrayIfExists(p.reviewJson) },
435
- sessions: { indexPath: globalPaths.sessionsIndex, raw: sessionsRaw, items: sessions, currentPath: sessionPath, current: sessionRaw ? parseSessionDetail(sessionRaw) : null },
436
- support: { capabilitiesSummary: summarizeText(readTextIfExists(p.capabilitiesIndex) || '', 420), investigationsSummary: summarizeText(readTextIfExists(p.investigationsIndex) || '', 420) },
437
- capabilities: capabilityCatalog,
438
- memoryLayers,
439
- context: {
440
- pack: dashboardPack,
441
- packs: report.contextPacks || {},
442
- quality: report.contextQuality || null,
443
- freshness: report.packFreshness || {},
444
- summaries: report.activeSummaryRefs || {},
445
- semantics: report.semanticsDrift || null,
446
- },
447
- azure: report.azureActive && report.azure
448
- ? {
449
- ...report.azure,
450
- profilePath: azurePaths.profile,
451
- authStatusPath: azurePaths.authStatus,
452
- inventoryMarkdownPath: azurePaths.inventoryMd,
453
- serviceBusPath: azurePaths.serviceBusMd,
454
- eventGridPath: azurePaths.eventGridMd,
455
- sqlPath: azurePaths.sqlMd,
456
- }
457
- : null,
458
- diagnostics: {
459
- reviewWarnings: report.reviewWarn,
460
- runtimeWarnings: report.runtimeWarn,
461
- enterpriseWarnings: report.enterpriseWarn || [],
462
- planWarnings: report.planWarn,
463
- sessionWarnings: report.sessionWarn,
464
- capabilityWarnings: report.capabilityWarn,
465
- investigationWarnings: report.investigationWarn,
466
- },
467
- repositoryContext: readRepositoryContext(rootScoped.codebase),
468
- };
469
- if (ctx.azure) {
470
- const inventorySummary = ctx.azure.inventorySummary || { total: 0, servicebus: 0, eventgrid: 0, sql: 0 };
471
- ctx.repositoryContext.azure = {
472
- path: ctx.azure.inventoryMarkdownPath,
473
- summary: `login=${ctx.azure.authStatus && ctx.azure.authStatus.login_active ? 'ativo' : 'ausente'} · subscription=${ctx.azure.profile && (ctx.azure.profile.subscription_name || ctx.azure.profile.subscription_id) || '—'} · total=${inventorySummary.total} · sb=${inventorySummary.servicebus || 0} · eg=${inventorySummary.eventgrid || 0} · sql=${inventorySummary.sql || 0}`,
474
- };
475
- }
476
- ctx.readiness = computeReadiness(ctx, report.planConfidenceThreshold || 90);
477
- ctx.coverage = buildCoverageMatrix(ctx.spec, ctx.plan, verify);
478
- ctx.calibration = computeCalibration(ctx.phase, ctx.plan.selfEvaluation.confidence, verify, ctx.readiness.threshold);
479
- ctx.visual = {
480
- flow: { nodes: [{ label: 'STATE', status: 'done' }, { label: 'SPEC', status: ctx.spec.raw ? 'done' : 'pending' }, { label: 'PLAN', status: ctx.plan.raw ? 'done' : 'pending' }, { label: 'REVIEW', status: ctx.planReviewStatus === 'approved' ? 'done' : /(rejected|needs_revision)/i.test(ctx.planReviewStatus) ? 'blocked' : 'active' }, { label: 'EXECUTE', status: ctx.runtime.parsed.status === 'running' ? 'active' : ctx.runtime.raw ? 'done' : 'pending' }, { label: 'CHECKPOINTS', status: ctx.readiness.checkpointPending ? 'active' : ctx.checkpoints.parsed.length ? 'done' : 'pending' }, { label: 'VERIFY', status: ctx.verify.raw ? 'done' : 'pending' }, { label: 'LESSONS', status: 'pending' }] },
481
- artifactGraph: [
482
- { id: 'state', label: 'STATE', path: ctx.state.path, detail: ctx.phase || 'índice global', status: 'done' },
483
- { id: 'spec', label: 'SPEC', path: ctx.spec.path, detail: ctx.spec.objective || 'contrato', status: ctx.spec.raw ? 'done' : 'pending' },
484
- { id: 'plan', label: 'PLAN', path: ctx.plan.path, detail: `${ctx.plan.totalTasks} tarefas`, status: ctx.plan.raw ? 'done' : 'pending' },
485
- {
486
- id: 'implementation-pack',
487
- label: 'IMPLEMENTATION PACK',
488
- path: ctx.executionRationality && ctx.executionRationality.implementationPack ? ctx.executionRationality.implementationPack.path : '—',
489
- detail: ctx.executionRationality && ctx.executionRationality.implementationPack ? `${ctx.executionRationality.implementationPack.taskCount || 0} contratos` : 'sem contrato',
490
- status: ctx.executionRationality && ctx.executionRationality.implementationPackReady ? 'done' : 'blocked',
491
- },
492
- {
493
- id: 'reference-anchors',
494
- label: 'REFERENCE ANCHORS',
495
- path: ctx.executionRationality && ctx.executionRationality.referenceAnchors ? ctx.executionRationality.referenceAnchors.path : '—',
496
- detail: ctx.executionRationality && ctx.executionRationality.referenceAnchors ? `${ctx.executionRationality.referenceAnchors.anchors ? ctx.executionRationality.referenceAnchors.anchors.length : 0} âncoras` : 'sem âncoras',
497
- status: ctx.executionRationality && ctx.executionRationality.referenceAnchorsReady ? 'done' : 'blocked',
498
- },
499
- {
500
- id: 'fixture-pack',
501
- label: 'FIXTURE PACK',
502
- path: ctx.executionRationality && ctx.executionRationality.fixturePack ? ctx.executionRationality.fixturePack.path : '—',
503
- detail: ctx.executionRationality && ctx.executionRationality.fixturePack ? `${ctx.executionRationality.fixturePack.fixtureCount || 0} fixtures` : 'sem fixtures',
504
- status: ctx.executionRationality && ctx.executionRationality.fixturePackReady ? 'done' : 'blocked',
505
- },
506
- { id: 'review', label: 'PLAN REVIEW', path: ctx.review.markdownPath, detail: ctx.planReviewStatus, status: ctx.planReviewStatus === 'approved' ? 'done' : 'active' },
507
- { id: 'runtime', label: 'RUNTIME', path: ctx.runtime.path, detail: ctx.runtime.parsed.status || 'sem status', status: ctx.runtime.raw ? 'active' : 'pending' },
508
- { id: 'active-run', label: 'ACTIVE RUN', path: operational.operationalPaths(projectRoot, activeSession || null).activeRun, detail: ctx.activeRun && ctx.activeRun.run_id ? `${ctx.activeRun.run_id} · ${ctx.activeRun.status}` : 'sem run ativo', status: ctx.activeRun ? 'active' : 'pending' },
509
- { id: 'events', label: 'TRACE', path: operational.operationalPaths(projectRoot, activeSession || null).events, detail: `${ctx.tracing.summary.total} evento(s)`, status: ctx.tracing.summary.total ? 'done' : 'pending' },
510
- { id: 'checkpoints', label: 'CHECKPOINTS', path: ctx.checkpoints.path, detail: `${ctx.checkpoints.parsed.length} gates`, status: ctx.readiness.checkpointPending ? 'active' : 'pending' },
511
- { id: 'verify', label: 'VERIFY', path: ctx.verify.path, detail: ctx.calibration.status, status: ctx.verify.raw ? 'done' : 'pending' },
512
- ],
513
- };
514
- if (ctx.azure) {
515
- ctx.visual.artifactGraph.push(
516
- {
517
- id: 'azure-profile',
518
- label: 'AZURE PROFILE',
519
- path: ctx.azure.profilePath,
520
- detail: ctx.azure.profile && (ctx.azure.profile.subscription_name || ctx.azure.profile.subscription_id) || 'sem subscription',
521
- status: ctx.azure.authStatus && ctx.azure.authStatus.login_active ? 'done' : 'blocked',
522
- },
523
- {
524
- id: 'azure-inventory',
525
- label: 'AZURE INVENTORY',
526
- path: ctx.azure.inventoryMarkdownPath,
527
- detail: ctx.azure.inventorySummary ? `${ctx.azure.inventorySummary.total} recurso(s)` : 'inventário ausente',
528
- status: ctx.azure.inventorySyncedAt ? (ctx.azure.inventoryStale && ctx.azure.inventoryStale.stale ? 'warning' : 'done') : 'pending',
529
- }
530
- );
531
- }
532
- ctx.operationalGraph = ctx.activeRun ? operational.buildOperationalGraph(ctx.activeRun) : { nodes: [], edges: [] };
533
- ctx.dashboard = { readOnly: false };
534
- return ctx;
535
- }
536
-
537
- function dashboardHtml() {
538
- return `<!doctype html><html lang="pt-BR"><head><meta charset="utf-8"/><meta name="viewport" content="width=device-width,initial-scale=1"/><title>OXE Dashboard</title><style>
539
- :root{--bg:#f4efe6;--bg2:#edf4ed;--panel:#fff;--ink:#1d2f3e;--muted:#617787;--line:#dbe3e8;--brand:#173f58;--ok:#1f7a52;--warn:#9d6b12;--bad:#a53e3e;--info:#235f84;--okbg:#e4f3eb;--warnbg:#fbf0da;--badbg:#f8e8e8;--infobg:#e5eff7;--shadow:0 16px 40px rgba(17,32,44,.08);--radius:18px}*{box-sizing:border-box}body{margin:0;background:linear-gradient(180deg,var(--bg),var(--bg2));font-family:"Segoe UI",Arial,sans-serif;color:var(--ink)}.page{max-width:1560px;margin:0 auto;padding:24px}.hero,.stats,.tabs,.grid2,.grid3,.layout{display:grid;gap:16px}.hero{grid-template-columns:1.2fr .8fr}.stats{grid-template-columns:repeat(5,minmax(0,1fr));margin:0 0 16px}.layout{grid-template-columns:1.45fr .95fr}.grid2{grid-template-columns:repeat(2,minmax(0,1fr))}.grid3{grid-template-columns:repeat(3,minmax(0,1fr))}.panel,.metric,.mini,.item,.entry{background:var(--panel);border:1px solid var(--line);border-radius:var(--radius);box-shadow:var(--shadow)}.panel{padding:18px}.metric,.mini,.item,.entry{padding:14px}.stack,.list,.rail{display:grid;gap:14px}.rail{grid-template-columns:repeat(8,minmax(100px,1fr))}.tabs{grid-template-columns:repeat(7,max-content)}.tab{padding:10px 14px;border:1px solid var(--line);border-radius:999px;background:#fff;cursor:pointer;font-weight:700}.tab.active{background:var(--brand);color:#fff;border-color:var(--brand)}.view{display:none}.view.active{display:block}.label{font-size:11px;letter-spacing:.08em;text-transform:uppercase;color:var(--muted)}.value{font-size:24px;font-weight:800;margin-top:6px}.muted{color:var(--muted)}.small{font-size:13px}.badge{display:inline-flex;align-items:center;justify-content:center;border-radius:999px;padding:6px 10px;font-size:11px;text-transform:uppercase;font-weight:800}.done{background:var(--okbg);color:var(--ok)}.active{background:var(--infobg);color:var(--info)}.warning{background:var(--warnbg);color:var(--warn)}.blocked{background:var(--badbg);color:var(--bad)}.pending{background:#edf1f4;color:#567181}.head{display:flex;justify-content:space-between;gap:10px;align-items:flex-start;margin-bottom:12px}.actions{display:flex;gap:10px;flex-wrap:wrap;margin-top:12px}button{border:0;border-radius:12px;padding:10px 12px;font-weight:700;cursor:pointer}.primary{background:var(--brand);color:#fff}.secondary{background:#edf2f5;color:var(--ink)}.warnbtn{background:#f2e3c5;color:#81540a}.danger{background:#f5dada;color:#8d3030}input,select,textarea{width:100%;border:1px solid var(--line);border-radius:12px;padding:10px;font:inherit}.form{display:grid;gap:10px}.raw{white-space:pre-wrap;background:#f8faf9;border:1px solid var(--line);border-radius:12px;padding:12px;max-height:220px;overflow:auto}.chip{display:inline-flex;border-radius:999px;padding:4px 8px;background:#eef3f6;color:#355267;font-size:12px;margin:4px 6px 0 0}.node{padding:12px;border:1px solid var(--line);border-radius:16px;background:#fff}.go{background:linear-gradient(180deg,#f2fbf5,#ebf7ef)}.nogo{background:linear-gradient(180deg,#fff5f5,#faeded)}@media (max-width:1200px){.hero,.layout{grid-template-columns:1fr}.rail{grid-template-columns:repeat(4,minmax(100px,1fr))}}@media (max-width:860px){.stats,.grid2,.grid3,.tabs,.rail{grid-template-columns:1fr}.page{padding:16px}}</style></head><body><div class="page"><div class="hero"><div class="panel"><h1 style="margin:0;font-size:42px">OXE Decision Control Room</h1><div class="muted" style="margin-top:10px">Control room para decisões reais de Go / No-Go, sem duplicar a fonte de verdade textual do OXE.</div></div><div class="grid2"><div class="mini"><div class="label">Projeto</div><div class="small" id="hero-project">—</div></div><div class="mini"><div class="label">Sessão</div><div class="value" id="hero-session">—</div></div><div class="mini"><div class="label">Próximo passo</div><div class="small" id="hero-next">—</div></div><div class="mini"><div class="label">Confiança</div><div class="value" id="hero-confidence">—</div></div></div></div><div id="app">Carregando…</div></div><script>
540
- const app=document.getElementById('app');let ctx=null;let tab='decision';let session=null;
541
- const esc=(s)=>String(s??'').replace(/[&<>"]/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c])); const cls=(s)=>{const v=String(s||'').toLowerCase();if(/(healthy|approved|done|go|well-calibrated|passed|ready|completed)/.test(v))return'done';if(/(running|in_review|active|mentioned|acceptable|controlled|replaying)/.test(v))return'active';if(/(rejected|needs_revision|blocked|failed|no-go|overconfident|do_not_execute|aborted|waiting_approval)/.test(v))return'blocked';if(/(risk|warning|underconfident|needs_refinement|paused)/.test(v))return'warning';return'pending';}; const badge=(s,l)=>'<span class="badge '+cls(s)+'">'+esc(l||s||'pending')+'</span>'; const list=(items,empty)=>items&&items.length?'<div class="list">'+items.join('')+'</div>':'<div class="entry small">'+esc(empty)+'</div>'; const runtimeDisabled=()=>ctx&&ctx.dashboard&&ctx.dashboard.readOnly;
542
- async function api(url,opts={}){const res=await fetch(url,{headers:{'Content-Type':'application/json'},...opts});if(!res.ok)throw new Error(await res.text());return res.json();} async function refresh(){ctx=await api('/api/context'+(session?'?session='+encodeURIComponent(session):''));render();}
543
- function render(){document.getElementById('hero-project').textContent=ctx.projectRoot||'—';document.getElementById('hero-session').textContent=ctx.activeSession||'modo legado';document.getElementById('hero-next').textContent=(ctx.nextStep.step||'—')+' · '+(ctx.nextStep.reason||'—');document.getElementById('hero-confidence').textContent=ctx.readiness.confidence!=null?ctx.readiness.confidence+'%':'—';
544
- const flow=(ctx.visual.flow.nodes||[]).map((n)=>'<div class="node"><div class="label">Etapa</div><div style="font-weight:800;font-size:18px;margin-top:6px">'+esc(n.label)+'</div><div style="margin-top:10px">'+badge(n.status)+'</div></div>');
545
- const graph=(ctx.visual.artifactGraph||[]).map((n)=>'<div class="item"><div class="head"><strong>'+esc(n.label)+'</strong>'+badge(n.status)+'</div><div class="small">'+esc(n.detail||'—')+'</div><div class="small muted" style="margin-top:8px">'+esc(n.path||'—')+'</div></div>');
546
- const waves=(ctx.plan.waves||[]).map((w)=>'<div class="panel"><div class="head"><div><strong>Onda '+esc(w.wave)+'</strong><div class="small muted">'+esc(w.taskIds.length)+' tarefas</div></div>'+badge(String(ctx.runtime.parsed.currentWave)===String(w.wave)?'running':'planned')+'</div>'+w.tasks.map((t)=>'<div class="entry"><div style="font-weight:800">'+esc(t.id)+' — '+esc(t.title)+'</div><div class="small muted" style="margin-top:6px">Depende de: '+esc(t.dependsOn.length?t.dependsOn.join(', '):'—')+'</div><div class="small muted">Verificação: '+esc(t.verifyCommand||'—')+'</div><div class="small" style="margin-top:6px">'+(t.aceite||[]).map((x)=>'<span class="chip">'+esc(x)+'</span>').join('')+(t.decisions||[]).map((x)=>'<span class="chip">'+esc(x)+'</span>').join('')+'</div></div>').join('')+'</div>');
547
- const coverage=(ctx.coverage||[]).map((c)=>'<div class="item"><div class="head"><strong>'+esc(c.id)+'</strong>'+badge(c.verifyStatus,c.verifyStatus)+'</div><div class="small">'+esc(c.criterion)+'</div><div class="small muted" style="margin-top:8px">Plano: '+esc(c.tasks.length?c.tasks.join(', '):'sem cobertura')+'</div><div class="small muted">Verify: '+esc(c.verifySummary||c.verifyHow||'sem evidência explícita')+'</div></div>');
548
- const checkpoints=(ctx.checkpoints.parsed||[]).map((c)=>'<div class="item"><div class="head"><strong>'+esc(c.id)+'</strong>'+badge(c.status)+'</div><div class="small muted">Tipo: '+esc(c.type)+' · Fase: '+esc(c.phase||'—')+' · Escopo: '+esc(c.scope||'—')+'</div><div class="small" style="margin-top:8px">'+esc(c.notes||'—')+'</div></div>');
549
- const agents=((ctx.runtime.parsed.agents&&ctx.runtime.parsed.agents.length)?ctx.runtime.parsed.agents:(ctx.blueprint&&ctx.blueprint.agents)||[]).map((a)=>'<div class="item"><div class="head"><strong>'+esc(a.id||a.name||'agent')+'</strong>'+badge(a.status||a.model_hint||'planned')+'</div><div class="small muted">'+esc(a.role||a.persona||'—')+'</div><div class="small">Tarefas: '+esc((a.tasks||[]).join(', ')||a.scope||'—')+'</div></div>');
550
- const comments=(ctx.review.comments||[]).map((c)=>'<div class="item"><div class="small muted">'+esc(c.target)+' · '+esc(c.type)+' · '+esc(c.status)+' · '+esc(c.author)+'</div><div style="margin-top:6px">'+esc(c.text)+'</div>'+(c.status!=='resolved'?'<div class="actions"><button class="secondary" onclick="resolveComment(\\''+esc(c.id)+'\\')">Resolver</button></div>':'')+'</div>');
551
- const sessions=(ctx.sessions.items||[]).map((s)=>'<div class="item"><div class="head"><div><strong>'+esc(s.id)+' · '+esc(s.name)+'</strong><div class="small muted">Criada: '+esc(s.createdAt)+' · Última atividade: '+esc(s.lastActivity)+'</div></div>'+badge(s.status)+'</div><div class="small">'+esc(s.summary||'—')+'</div><div class="small muted" style="margin-top:8px">'+esc(s.path||'—')+'</div><div class="actions"><button class="secondary" onclick="openSession(\\''+esc(s.path)+'\\')">Abrir sessão</button></div></div>');
552
- const repo=Object.entries(ctx.repositoryContext||{}).map(([k,v])=>'<div class="item"><strong>'+esc(k.toUpperCase())+'</strong><div class="small" style="margin-top:8px">'+esc(v.summary||'Sem resumo disponível.')+'</div><div class="small muted" style="margin-top:8px">'+esc(v.path||'—')+'</div></div>');
553
- const contextSelected=((ctx.context&&ctx.context.pack&&ctx.context.pack.selected_artifacts)||[]).map((artifact)=>'<div class="item"><div class="head"><strong>'+esc(artifact.alias)+'</strong>'+badge(artifact.exists?(artifact.using_fallback?'fallback':'selected'):'missing',artifact.exists?(artifact.using_fallback?'fallback':'selected'):'missing')+'</div><div class="small">'+esc(artifact.summary||'—')+'</div><div class="small muted" style="margin-top:8px">'+esc(artifact.path||'—')+'</div></div>');
554
- const contextGaps=((ctx.context&&ctx.context.pack&&ctx.context.pack.gaps)||[]).map((gap)=>'<div class="entry small">['+esc(gap.severity)+'] '+esc(gap.alias)+': '+esc(gap.reason)+'</div>');
555
- const contextConflicts=((ctx.context&&ctx.context.pack&&ctx.context.pack.conflicts)||[]).map((conflict)=>'<div class="entry small">'+esc(conflict.alias)+': '+esc(conflict.reason)+'</div>');
556
- const semanticsWarnings=((ctx.context&&ctx.context.semantics&&ctx.context.semantics.audit&&ctx.context.semantics.audit.warnings)||[]).map((warning)=>'<div class="entry small">'+esc(warning)+'</div>');
557
- const blockers=(ctx.readiness.blockers||[]).map((x)=>'<div class="entry small">'+esc(x)+'</div>'); const warnings=(ctx.readiness.warnings||[]).concat((ctx.diagnostics.enterpriseWarnings||[])).slice(0,10).map((x)=>'<div class="entry small">'+esc(x)+'</div>'); const evidence=(ctx.runtime.parsed.evidence||[]).map((x)=>'<div class="entry small">'+esc(x)+'</div>'); const blockages=(ctx.runtime.parsed.blockages||[]).map((x)=>'<div class="entry small">'+esc(x)+'</div>'); const history=((ctx.sessions.current&&ctx.sessions.current.history)||[]).map((x)=>'<div class="entry small">'+esc(x.date)+' · '+esc(x.event)+'</div>');
558
- const enterpriseGates=((ctx.enterprise&&ctx.enterprise.pendingGates&&ctx.enterprise.pendingGates.pending)||[]).map((gate)=>'<div class="entry small">'+esc(gate.gate_id)+' · '+esc(gate.scope)+' · '+esc(gate.work_item_id||'run')+'</div>');
559
- app.innerHTML='<div class="stats"><div class="metric"><div class="label">Saúde lógica</div><div class="value">'+badge(ctx.healthStatus)+'</div></div><div class="metric"><div class="label">Go / No-Go</div><div class="value">'+badge(ctx.readiness.decision,ctx.readiness.decision)+'</div></div><div class="metric"><div class="label">Review</div><div class="value">'+badge(ctx.planReviewStatus)+'</div></div><div class="metric"><div class="label">Checkpoints</div><div class="value">'+badge(ctx.readiness.checkpointPending?'pending_approval':'clear',ctx.readiness.checkpointPending?'pendente':'ok')+'</div></div><div class="metric"><div class="label">Runtime</div><div class="value">'+badge(ctx.runtime.parsed.status||ctx.state.parsed.runtimeStatus||'pending')+'</div></div></div>'
560
- +'<div class="tabs">'+['decision','plan','execution','evidence','sessions','context','repository'].map((t)=>'<button class="tab'+(tab===t?' active':'')+'" onclick="setTab(\\''+t+'\\')">'+(t==='repository'?'repository context':t)+'</button>').join('')+'</div>'
561
- +'<div class="view'+(tab==='decision'?' active':'')+'"><div class="layout"><div class="stack"><div class="panel"><div class="head"><div><h2 style="margin:0">Decision Control</h2><div class="muted">A pergunta principal: podemos executar agora?</div></div></div><div class="'+(ctx.readiness.go?'panel go':'panel nogo')+'" style="padding:18px"><div class="label">Decisão operacional</div><div style="font-size:38px;font-weight:900;margin-top:8px">'+(ctx.readiness.go?'GO':'NO-GO')+'</div><div class="small muted" style="margin-top:8px">'+esc(ctx.nextStep.reason||'—')+'</div><div class="actions">'+badge(ctx.planReviewStatus,'review:'+ctx.planReviewStatus)+badge(ctx.readiness.confidenceBand,'confiança:'+ctx.readiness.confidenceBand)+(ctx.readiness.checkpointPending?badge('pending_approval','checkpoint pendente'):'')+'</div></div></div><div class="panel"><div class="head"><div><h2 style="margin:0">Decision Rail</h2><div class="muted">Spec → Plan → Review → Execute → Verify → Lessons.</div></div></div><div class="rail">'+flow.join('')+'</div></div><div class="panel"><div class="head"><div><h2 style="margin:0">Readiness Map</h2><div class="muted">Bloqueios e sinais ativos antes do execute.</div></div></div><div class="grid2"><div><h3>Bloqueios</h3>'+list(blockers,'Sem bloqueios formais para executar.')+'</div><div><h3>Warnings</h3>'+list(warnings,'Sem warnings relevantes.')+'</div></div></div><div class="panel"><div class="head"><div><h2 style="margin:0">Review e aprovação</h2><div class="muted">Persistida em STATE.md, PLAN-REVIEW.md e comentários.</div></div></div><div class="grid2"><div><div class="actions"><button class="primary" onclick="changeReview(\\'approved\\')">Aprovar</button><button class="warnbtn" onclick="changeReview(\\'needs_revision\\')">Pedir revisão</button><button class="secondary" onclick="changeReview(\\'in_review\\')">Marcar em revisão</button><button class="danger" onclick="changeReview(\\'rejected\\')">Rejeitar</button></div><div class="form"><input id="comment-target" placeholder="target ex.: wave:1, T2, checkpoint:CP-01"/><select id="comment-type"><option value="note">note</option><option value="risk">risk</option><option value="question">question</option><option value="approval">approval</option></select><textarea id="comment-text" rows="6" placeholder="Comentário de revisão"></textarea><button class="primary" onclick="addComment()">Adicionar comentário</button></div></div><div><h3>Comentários</h3>'+list(comments,'Nenhum comentário de revisão.')+'</div></div></div></div><div class="stack"><div class="panel"><div class="head"><div><h2 style="margin:0">Mapa de artefatos</h2><div class="muted">Fonte de verdade visual do ciclo atual.</div></div></div><div class="grid3">'+graph.join('')+'</div></div><div class="panel"><div class="head"><div><h2 style="margin:0">Calibração do plano</h2><div class="muted">Confiança prevista versus resultado real.</div></div>'+badge(ctx.calibration.status)+'</div><div class="small">'+esc(ctx.calibration.summary)+'</div></div></div></div></div>'
562
- +'<div class="view'+(tab==='plan'?' active':'')+'"><div class="layout"><div class="stack"><div class="panel"><div class="head"><div><h2 style="margin:0">Trilha do plano</h2><div class="muted">Ondas, dependências e vínculos com aceite e decisões.</div></div>'+badge(ctx.planReviewStatus)+'</div>'+list(waves,'PLAN.md ausente ou sem tarefas estruturadas.')+'</div><div class="panel"><div class="head"><div><h2 style="margin:0">Matriz de cobertura</h2><div class="muted">SPEC → PLAN → VERIFY em um único quadro.</div></div></div><div class="grid2">'+coverage.join('')+'</div></div></div><div class="stack"><div class="panel"><div class="head"><div><h2 style="margin:0">Autoavaliação do plano</h2><div class="muted">Melhor plano atual e faixa de confiança.</div></div></div><div class="grid3"><div class="item"><strong>Melhor plano atual</strong><div class="small muted" style="margin-top:8px">'+esc((ctx.plan.selfEvaluation&&ctx.plan.selfEvaluation.bestPlan)||'—')+'</div></div><div class="item"><strong>Confiança</strong><div class="small muted" style="margin-top:8px">'+esc(ctx.readiness.confidence!=null?ctx.readiness.confidence+'%':'—')+'</div></div><div class="item"><strong>Faixa</strong><div class="small muted" style="margin-top:8px">'+esc(ctx.readiness.confidenceBand)+'</div></div></div></div><div class="panel"><div class="head"><div><h2 style="margin:0">Lacunas da SPEC</h2><div class="muted">Critérios sem cobertura explícita no plano.</div></div></div>'+list((ctx.spec.uncoveredCriteria||[]).map((c)=>'<div class="entry small">'+esc(c.id)+' · '+esc(c.criterion)+'</div>'),'Sem lacunas detectadas.')+'</div></div></div></div>'
563
- +'<div class="view'+(tab==='execution'?' active':'')+'"><div class="layout"><div class="stack"><div class="panel"><div class="head"><div><h2 style="margin:0">Runtime operacional</h2><div class="muted">Estado tático da execução.</div></div>'+badge(ctx.runtime.parsed.status||'pending')+'</div><div class="grid3"><div class="item"><strong>Onda atual</strong><div class="small muted" style="margin-top:8px">'+esc(ctx.runtime.parsed.currentWave||'—')+'</div></div><div class="item"><strong>Tarefas ativas</strong><div class="small muted" style="margin-top:8px">'+esc((ctx.runtime.parsed.activeTasks||[]).join(', ')||'—')+'</div></div><div class="item"><strong>Próxima ação</strong><div class="small muted" style="margin-top:8px">'+esc(ctx.runtime.parsed.nextAction||'—')+'</div></div><div class="item"><strong>Motivo</strong><div class="small muted" style="margin-top:8px">'+esc(ctx.runtime.parsed.nextReason||'—')+'</div></div><div class="item"><strong>Modo runtime</strong><div class="small muted" style="margin-top:8px">'+esc((ctx.enterprise&&ctx.enterprise.runtimeMode&&ctx.enterprise.runtimeMode.runtime_mode)||'—')+'</div></div><div class="item"><strong>Fallback</strong><div class="small muted" style="margin-top:8px">'+esc((ctx.enterprise&&ctx.enterprise.fallbackMode)||'—')+'</div></div></div></div><div class="panel"><div class="head"><div><h2 style="margin:0">Checkpoints</h2><div class="muted">Gates humanos formais.</div></div></div>'+list(checkpoints,'CHECKPOINTS.md ausente ou sem gates formais.')+'</div><div class="panel"><div class="head"><div><h2 style="margin:0">Gates pendentes</h2><div class="muted">Fila operacional persistida por run/work item.</div></div></div>'+list(enterpriseGates,'Sem gates pendentes no runtime.')+'</div><div class="panel"><div class="head"><div><h2 style="margin:0">Agentes</h2><div class="muted">Blueprint e runtime multiagente.</div></div></div>'+list(agents,'Sem blueprint de agentes ou runtime multiagente ativo.')+'</div></div><div class="stack"><div class="panel"><div class="head"><div><h2 style="margin:0">Evidências</h2><div class="muted">Artefatos e sinais da execução atual.</div></div></div>'+list(evidence,'Sem evidência operacional registrada.')+'</div><div class="panel"><div class="head"><div><h2 style="margin:0">Enterprise verify</h2><div class="muted">Manifest, risco residual, governança e promoção.</div></div></div><div class="grid3">'+kvItem('Checks',(ctx.enterprise&&ctx.enterprise.verificationSummary&&ctx.enterprise.verificationSummary.total)||'—')+kvItem('Fail',(ctx.enterprise&&ctx.enterprise.verificationSummary&&ctx.enterprise.verificationSummary.fail)||0)+kvItem('Coverage',(ctx.enterprise&&ctx.enterprise.evidenceCoverage&&String(ctx.enterprise.evidenceCoverage.coverage_percent)+'%')||'—')+kvItem('Residual risks',(ctx.enterprise&&ctx.enterprise.residualRiskSummary&&ctx.enterprise.residualRiskSummary.total)||0)+kvItem('High/Critical',(ctx.enterprise&&ctx.enterprise.residualRiskSummary&&ctx.enterprise.residualRiskSummary.highOrCritical)||0)+kvItem('Policy decisions',(ctx.enterprise&&ctx.enterprise.policyDecisionSummary&&ctx.enterprise.policyDecisionSummary.total)||0)+kvItem('Policy coverage',(ctx.enterprise&&ctx.enterprise.policyCoverage&&String(ctx.enterprise.policyCoverage.coveragePercent)+'%')||'—')+kvItem('Quota retries',(ctx.enterprise&&ctx.enterprise.quotaSummary&&ctx.enterprise.quotaSummary.consumed&&String(ctx.enterprise.quotaSummary.consumed.retries)+'/'+((ctx.enterprise.quotaSummary.limits&&ctx.enterprise.quotaSummary.limits.maxRetriesPerRun)!=null?ctx.enterprise.quotaSummary.limits.maxRetriesPerRun:'∞'))||'—')+kvItem('Audit critical',(ctx.enterprise&&ctx.enterprise.auditSummary&&ctx.enterprise.auditSummary.critical)||0)+kvItem('Promotion',(ctx.enterprise&&ctx.enterprise.promotionSummary&&ctx.enterprise.promotionSummary.status)||'—')+kvItem('Promotion readiness',(ctx.enterprise&&ctx.enterprise.promotionReadiness&&ctx.enterprise.promotionReadiness.status)||'—')+kvItem('Recovery',(ctx.enterprise&&ctx.enterprise.recoveryState&&ctx.enterprise.recoveryState.status)||'—')+kvItem('Providers',((ctx.enterprise&&ctx.enterprise.providerCatalog&&ctx.enterprise.providerCatalog.summary&&((ctx.enterprise.providerCatalog.summary.pluginsCount!=null?ctx.enterprise.providerCatalog.summary.pluginsCount:ctx.enterprise.providerCatalog.summary.total_plugins)!=null?(ctx.enterprise.providerCatalog.summary.pluginsCount!=null?ctx.enterprise.providerCatalog.summary.pluginsCount:ctx.enterprise.providerCatalog.summary.total_plugins):Array.isArray(ctx.enterprise.providerCatalog.summary.plugins)?ctx.enterprise.providerCatalog.summary.plugins.length:0)))||0)+'</div></div><div class="panel"><div class="head"><div><h2 style="margin:0">Bloqueios</h2><div class="muted">O que impede avanço agora.</div></div></div>'+list(blockages,'Sem bloqueios explícitos.')+'</div><div class="panel"><div class="head"><div><h2 style="margin:0">Runtime bruto</h2><div class="muted">Leitura direta do artefato operacional.</div></div></div><div class="raw">'+esc(ctx.runtime.summary||'EXECUTION-RUNTIME.md ausente.')+'</div></div></div></div></div>'
564
- +'<div class="view'+(tab==='evidence'?' active':'')+'"><div class="layout"><div class="stack"><div class="panel"><div class="head"><div><h2 style="margin:0">Verify</h2><div class="muted">Evidência final e validação.</div></div>'+badge(ctx.calibration.status)+'</div><div class="raw">'+esc(ctx.verify.summary||'VERIFY.md ausente.')+'</div></div><div class="panel"><div class="head"><div><h2 style="margin:0">Critérios no verify</h2><div class="muted">Evidências detectadas por critério A*.</div></div></div><div class="grid2">'+coverage.join('')+'</div></div></div><div class="stack"><div class="panel"><div class="head"><div><h2 style="margin:0">Investigações</h2><div class="muted">Base de evidência antes do plano.</div></div></div><div class="raw">'+esc(ctx.support.investigationsSummary||'INVESTIGATIONS.md ausente.')+'</div></div><div class="panel"><div class="head"><div><h2 style="margin:0">Capabilities</h2><div class="muted">Recursos nativos do projeto.</div></div></div><div class="raw">'+esc(ctx.support.capabilitiesSummary||'CAPABILITIES.md ausente.')+'</div></div></div></div></div>'
565
- +'<div class="view'+(tab==='sessions'?' active':'')+'"><div class="layout"><div class="stack"><div class="panel"><div class="head"><div><h2 style="margin:0">Sessão ativa</h2><div class="muted">Contexto atual resolvido pelo STATE global.</div></div></div><div class="grid2"><div class="item"><strong>ID</strong><div class="small muted" style="margin-top:8px">'+esc((ctx.sessions.current&&ctx.sessions.current.id)||'—')+'</div></div><div class="item"><strong>Nome</strong><div class="small muted" style="margin-top:8px">'+esc((ctx.sessions.current&&ctx.sessions.current.name)||ctx.activeSession||'—')+'</div></div><div class="item"><strong>Status</strong><div class="small muted" style="margin-top:8px">'+esc((ctx.sessions.current&&ctx.sessions.current.status)||'—')+'</div></div><div class="item"><strong>Última atividade</strong><div class="small muted" style="margin-top:8px">'+esc((ctx.sessions.current&&ctx.sessions.current.lastActivity)||'—')+'</div></div></div><div class="item" style="margin-top:14px"><strong>Resumo</strong><div class="small muted" style="margin-top:8px">'+esc((ctx.sessions.current&&ctx.sessions.current.summary)||'Sem SESSION.md ativo ou modo legado.')+'</div><div class="small muted" style="margin-top:8px">'+esc(ctx.sessions.currentPath||'—')+'</div></div><div class="item" style="margin-top:14px"><strong>Tags</strong><div class="small" style="margin-top:8px">'+((ctx.sessions.current&&ctx.sessions.current.tags)||[]).map((x)=>'<span class="chip">'+esc(x)+'</span>').join('')+'</div></div><h3>Histórico</h3>'+list(history,'Sem histórico de sessão disponível.')+'</div></div><div class="stack"><div class="panel"><div class="head"><div><h2 style="margin:0">Lista de sessões</h2><div class="muted">Índice real lido de .oxe/SESSIONS.md.</div></div></div>'+list(sessions,'SESSIONS.md ausente ou sem sessões registradas.')+'</div><div class="panel"><div class="head"><div><h2 style="margin:0">Índice bruto</h2><div class="muted">Leitura direta do artefato global.</div></div></div><div class="raw">'+esc(ctx.sessions.raw||'SESSIONS.md ausente.')+'</div></div></div></div></div>'
566
- +'<div class="view'+(tab==='context'?' active':'')+'"><div class="layout"><div class="stack"><div class="panel"><div class="head"><div><h2 style="margin:0">Context Pack</h2><div class="muted">Seleção determinística de artefatos para este estado do OXE.</div></div>'+badge((ctx.context&&ctx.context.quality&&ctx.context.quality.primaryStatus)||((ctx.context&&ctx.context.pack&&ctx.context.pack.context_quality&&ctx.context.pack.context_quality.status)||'pending'))+'</div><div class="grid3"><div class="item"><strong>Workflow primário</strong><div class="small muted" style="margin-top:8px">'+esc((ctx.context&&ctx.context.quality&&ctx.context.quality.primaryWorkflow)||'dashboard')+'</div></div><div class="item"><strong>Score</strong><div class="small muted" style="margin-top:8px">'+esc((ctx.context&&ctx.context.quality&&ctx.context.quality.primaryScore)!=null?String(ctx.context.quality.primaryScore):'—')+'</div></div><div class="item"><strong>Freshness</strong><div class="small muted" style="margin-top:8px">'+esc((ctx.context&&ctx.context.pack&&ctx.context.pack.freshness&&ctx.context.pack.freshness.reason)||'—')+'</div></div></div><div class="small muted" style="margin-top:12px">Pack: '+esc((ctx.context&&ctx.context.pack&&ctx.context.pack.path)||'—')+' · semantics hash: '+esc((ctx.context&&ctx.context.pack&&ctx.context.pack.semantics_hash)||'—')+'</div></div><div class="panel"><div class="head"><div><h2 style="margin:0">Artefatos selecionados</h2><div class="muted">Contexto efetivamente priorizado pelo pack.</div></div></div><div class="grid2">'+contextSelected.join('')+'</div></div></div><div class="stack"><div class="panel"><div class="head"><div><h2 style="margin:0">Gaps e conflitos</h2><div class="muted">Lacunas e divergências entre raiz e sessão.</div></div></div><h3>Gaps</h3>'+list(contextGaps,'Sem gaps no pack atual.')+'<h3>Conflitos</h3>'+list(contextConflicts,'Sem conflitos detectados.')+'</div><div class="panel"><div class="head"><div><h2 style="margin:0">Summaries ativos</h2><div class="muted">Referências persistidas para compressão de contexto.</div></div></div><div class="grid2">'+kvItem('Project summary',(ctx.context&&ctx.context.summaries&&ctx.context.summaries.project)||'—')+kvItem('Session summary',(ctx.context&&ctx.context.summaries&&ctx.context.summaries.session)||'—')+kvItem('Phase summary',(ctx.context&&ctx.context.summaries&&ctx.context.summaries.phase)||'—')+'</div></div><div class="panel"><div class="head"><div><h2 style="margin:0">Semântica multi-runtime</h2><div class="muted">Drift auditável entre workflow, wrapper e prompt renderizado.</div></div>'+badge(ctx.context&&ctx.context.semantics&&ctx.context.semantics.ok?'healthy':'warning',ctx.context&&ctx.context.semantics&&ctx.context.semantics.ok?'ok':'drift')+'</div><div class="small muted">Manifest: '+esc((ctx.context&&ctx.context.semantics&&ctx.context.semantics.manifestPath)||'—')+' · mismatch count: '+esc((ctx.context&&ctx.context.semantics&&ctx.context.semantics.audit&&ctx.context.semantics.audit.mismatchCount)||0)+'</div>'+list(semanticsWarnings,'Sem warnings semânticos ativos.')+'</div></div></div></div>'
567
- +'<div class="view'+(tab==='repository'?' active':'')+'"><div class="panel"><div class="head"><div><h2 style="margin:0">Repository Context</h2><div class="muted">Contexto de repositório como suporte de decisão.</div></div></div><div class="grid3">'+repo.join('')+'</div></div></div>'; enhanceExecutionView();}
568
- function executionViewElement(){return Array.from(app.querySelectorAll('.view')).find((view)=>view.textContent.includes('Runtime operacional'));}
569
- function panel(title,body){return '<div class="panel"><div class="head"><div><h2 style="margin:0">'+esc(title)+'</h2></div></div>'+body+'</div>';}
570
- function kvItem(label,value){return '<div class="item"><strong>'+esc(label)+'</strong><div class="small muted" style="margin-top:8px">'+esc(value)+'</div></div>';}
571
- function actionButton(label,action,klass){return '<button class="'+klass+'" '+(runtimeDisabled()?'disabled':'')+' onclick="runtimeAction(\\''+action+'\\')">'+label+'</button>';}
572
- function enhanceExecutionView(){
573
- const view=executionViewElement();
574
- if(!view||!ctx)return;
575
- const stacks=view.querySelectorAll('.stack');
576
- if(stacks.length<2)return;
577
- const activeRun=ctx.activeRun||{};
578
- const graph=ctx.operationalGraph||{nodes:[],edges:[]};
579
- const trace=((ctx.tracing&&ctx.tracing.events)||[]).slice(-8).reverse().map((event)=>'<div class="entry"><div class="head"><strong>'+esc(event.type)+'</strong>'+badge(event.timestamp?event.timestamp.slice(11,19):'—',event.timestamp?event.timestamp.slice(11,19):'—')+'</div><div class="small muted">run='+esc(event.run_id||'—')+' · wave='+esc(event.wave_id||'—')+' · task='+esc(event.task_id||'—')+'</div><div class="small" style="margin-top:8px">'+esc(JSON.stringify(event.payload||{}))+'</div></div>').join('')||'<div class="entry small">Sem eventos registrados.</div>';
580
- const nodes=(graph.nodes||[]).map((node)=>'<div class="item"><div class="head"><strong>'+esc(node.label||node.id)+'</strong>'+badge(node.status||'pending')+'</div><div class="small muted">'+esc(node.kind||'node')+'</div><div class="small" style="margin-top:8px">'+esc(node.detail||'—')+'</div></div>').join('')||'<div class="entry small">Sem nós operacionais.</div>';
581
- const edges=(graph.edges||[]).map((edge)=>'<div class="entry"><div class="small"><strong>'+esc(edge.from)+'</strong> → <strong>'+esc(edge.to)+'</strong></div><div class="small muted" style="margin-top:6px">'+esc(edge.type||'link')+' · '+esc(edge.status||'—')+'</div><div class="small" style="margin-top:6px">'+esc(edge.reason||edge.label||'—')+'</div></div>').join('')||'<div class="entry small">Sem handoffs ou dependências registradas.</div>';
582
- const memory=Object.entries(ctx.memoryLayers||{}).filter(([key])=>key!=='readOrder').map(([key,val])=>kvItem(key,Array.isArray(val.source)?val.source.join(' | '):val.source||'—')).join('')||'<div class="entry small">Sem contrato de memória disponível.</div>';
583
- const enterprise=ctx.enterprise||{};
584
- const gateQueue=enterprise.gateQueue||{pending:[],stalePending:[],resolvedRecent:[],gateSlaHours:24};
585
- const pendingGates=(gateQueue.pending||[]).map((gate)=>'<div class="entry"><div class="head"><strong>'+esc(gate.gate_id)+'</strong>'+badge(gate.status||'pending')+'</div><div class="small muted">scope='+esc(gate.scope||'—')+' · task='+esc(gate.work_item_id||'—')+' · actor='+(gate.actor?esc(gate.actor):'—')+'</div><div class="small" style="margin-top:8px">'+esc((gate.context&&gate.context.description)||gate.action||'Sem descrição')+'</div><div class="actions" style="margin-top:12px"><button class="primary" '+(runtimeDisabled()?'disabled':'')+' onclick="runtimeGateResolve(\\''+esc(gate.gate_id)+'\\',\\'approve\\')">Approve</button><button class="warnbtn" '+(runtimeDisabled()?'disabled':'')+' onclick="runtimeGateResolve(\\''+esc(gate.gate_id)+'\\',\\'waive\\')">Waive</button><button class="danger" '+(runtimeDisabled()?'disabled':'')+' onclick="runtimeGateResolve(\\''+esc(gate.gate_id)+'\\',\\'reject\\')">Reject</button></div></div>').join('')||'<div class="entry small">Sem gates pendentes.</div>';
586
- const staleGates=(gateQueue.stalePending||[]).map((gate)=>'<div class="entry"><div class="head"><strong>'+esc(gate.gate_id)+'</strong>'+badge('stale','warning')+'</div><div class="small muted">requested_at='+esc(gate.requested_at||'—')+' · scope='+esc(gate.scope||'—')+'</div></div>').join('')||'<div class="entry small">Sem gates stale.</div>';
587
- const recentResolved=(gateQueue.resolvedRecent||[]).map((gate)=>'<div class="entry"><div class="head"><strong>'+esc(gate.gate_id)+'</strong>'+badge(gate.decision||'resolved','ok')+'</div><div class="small muted">actor='+esc(gate.actor||'—')+' · reason='+esc(gate.reason||'—')+'</div></div>').join('')||'<div class="entry small">Sem resoluções recentes.</div>';
588
- const gatePanel=panel('Runtime gates','<div class="grid3">'+kvItem('Pending',String((gateQueue.pending||[]).length))+kvItem('Stale',String(gateQueue.staleCount||0))+kvItem('SLA (h)',String(gateQueue.gateSlaHours||24))+'</div><h3>Pendentes</h3>'+pendingGates+'<h3>Stale</h3>'+staleGates+'<h3>Resolvidos nas últimas 24h</h3>'+recentResolved);
589
- const multiAgent=enterprise.multiAgent||null;
590
- const multiAgentPanel=multiAgent&&multiAgent.enabled?panel('Multi-agent','<div class="grid3">'+kvItem('Mode',multiAgent.mode||'—')+kvItem('Isolation',multiAgent.workspaceIsolationEnforced?'isolated':'shared')+kvItem('Agents',String((multiAgent.agents||[]).length))+'</div><h3>Ownership</h3>'+((multiAgent.ownership||[]).map((item)=>'<div class="entry"><div class="head"><strong>'+esc(item.work_item_id||'—')+'</strong>'+badge(item.owner_agent_id||'unassigned')+'</div></div>').join('')||'<div class="entry small">Sem ownership ativo.</div>')+'<h3>Handoffs</h3>'+((multiAgent.handoffs||[]).map((handoff)=>'<div class="entry"><div class="small"><strong>'+esc(handoff.from_agent_id||'—')+'</strong> → <strong>'+esc(handoff.to_agent_id||'—')+'</strong></div><div class="small muted" style="margin-top:6px">'+esc(handoff.work_item_id||'—')+'</div></div>').join('')||'<div class="entry small">Sem handoffs registrados.</div>')):'';
591
- const recovery=enterprise.recoveryState||null;
592
- const recoveryPanel=recovery?panel('Recovery','<div class="grid3">'+kvItem('Status',recovery.status||'—')+kvItem('Last recovery',recovery.lastRecoveredAt||'—')+kvItem('Issues',String((recovery.issues||[]).length))+'</div><h3>Issues</h3>'+((recovery.issues||[]).map((issue)=>'<div class="entry"><div class="small"><strong>'+esc(issue.code||'issue')+'</strong></div><div class="small muted" style="margin-top:6px">'+esc(issue.message||issue.reason||'—')+'</div></div>').join('')||'<div class="entry small">Sem inconsistências abertas.</div>')):'';
593
- const promotion=enterprise.promotionReadiness||null;
594
- const promotionPanel=promotion?panel('Promotion readiness','<div class="grid3">'+kvItem('Status',promotion.status||'—')+kvItem('Coverage',String(promotion.coveragePercent==null?'—':promotion.coveragePercent+'%'))+kvItem('Policy',String(promotion.policyCoveragePercent==null?'—':promotion.policyCoveragePercent+'%'))+'</div><h3>Blockers</h3>'+((promotion.reasons||promotion.blockers||[]).map((reason)=>'<div class="entry small">'+esc(reason)+'</div>').join('')||'<div class="entry small">Sem blockers ativos.</div>')):'';
595
- const azure=ctx.azure||null;
596
- const azureInventory=azure&&azure.inventorySummary?azure.inventorySummary:{total:0,servicebus:0,eventgrid:0,sql:0,other:0};
597
- const azurePanel=azure?panel('Azure context operacional','<div class="grid3">'+kvItem('Login',azure.authStatus&&azure.authStatus.login_active?'ativo':'ausente')+kvItem('Subscription',azure.profile&&(azure.profile.subscription_name||azure.profile.subscription_id)||'—')+kvItem('Último sync',azure.inventorySyncedAt||'—')+kvItem('Service Bus',String(azureInventory.servicebus||0))+kvItem('Event Grid',String(azureInventory.eventgrid||0))+kvItem('Azure SQL',String(azureInventory.sql||0))+'</div><div class="small muted" style="margin-top:12px">Inventário: total '+esc(azureInventory.total||0)+' · pending operations: '+esc(azure.pendingOperations||0)+' · '+esc(azure.inventoryStale&&azure.inventoryStale.stale?'stale':'fresh')+'</div>'+(azure.lastOperation?'<div class="entry" style="margin-top:12px"><div class="head"><strong>Última operação</strong>'+badge(azure.lastOperation.phase||'pending')+'</div><div class="small">'+esc(azure.lastOperation.summary||azure.lastOperation.operation_id||'—')+'</div><div class="small muted" style="margin-top:8px">'+esc(azure.lastOperation.operation_id||'—')+'</div></div>':'')):'';
598
- stacks[0].insertAdjacentHTML('afterbegin',panel('Run control','<div class="grid3">'+kvItem('Run ID',activeRun.run_id||'—')+kvItem('Status',activeRun.status||'pending')+kvItem('Cursor',(activeRun.cursor&&((activeRun.cursor.wave!=null?'wave '+activeRun.cursor.wave:'')+(activeRun.cursor.task?' · '+activeRun.cursor.task:'')+(activeRun.cursor.mode?' · '+activeRun.cursor.mode:'')))||'—')+'</div><div class="actions">'+actionButton('Start','start','primary')+actionButton('Pause','pause','warnbtn')+actionButton('Resume','resume','secondary')+actionButton('Replay','replay','danger')+'</div><div class="small muted" style="margin-top:12px">Transitions: '+esc((activeRun.metrics&&activeRun.metrics.transitions)||0)+' · pause_count: '+esc((activeRun.metrics&&activeRun.metrics.pause_count)||0)+' · replay_count: '+esc((activeRun.metrics&&activeRun.metrics.replay_count)||0)+'</div>'));
599
- stacks[0].insertAdjacentHTML('beforeend',panel('Mapa operacional','<div class="grid3">'+nodes+'</div><h3>Handoffs e dependências</h3>'+edges)+(gatePanel||'')+(multiAgentPanel||'')+(azurePanel||''));
600
- stacks[1].insertAdjacentHTML('afterbegin',panel('Trace operacional','<div class="small muted" style="margin-bottom:12px">Arquivo: '+esc((ctx.tracing&&ctx.tracing.path)||'—')+' · total: '+esc((ctx.tracing&&ctx.tracing.summary&&ctx.tracing.summary.total)||0)+' evento(s)</div>'+trace));
601
- stacks[1].insertAdjacentHTML('beforeend',panel('Camadas de memória','<div class="small muted" style="margin-bottom:12px">'+esc(((ctx.memoryLayers&&ctx.memoryLayers.readOrder)||[]).join(' → ')||'—')+'</div><div class="grid2">'+memory+'</div>')+(recoveryPanel||'')+(promotionPanel||''));
602
- }
603
- function setTab(next){tab=next;render();}
604
- async function openSession(path){session=path||null;await refresh();tab='sessions';render();}
605
- async function changeReview(status){const note=prompt('Justificativa curta para o novo estado do plano:',status==='approved'?'Plano aprovado para execução.':'');if(note==null)return;await api('/api/review/status',{method:'POST',body:JSON.stringify({status,note,author:'user',activeSession:session})});await refresh();}
606
- async function addComment(){const target=document.getElementById('comment-target').value||'plan';const type=document.getElementById('comment-type').value||'note';const text=document.getElementById('comment-text').value.trim();if(!text)return alert('Escreva um comentário.');await api('/api/review/comment',{method:'POST',body:JSON.stringify({target,type,text,author:'user',activeSession:session})});document.getElementById('comment-text').value='';await refresh();}
607
- async function resolveComment(id){await api('/api/review/comment-status',{method:'POST',body:JSON.stringify({commentId:id,status:'resolved',activeSession:session})});await refresh();}
608
- async function runtimeAction(action){if(runtimeDisabled())return;const reason=prompt('Motivo da transição de runtime:',action==='start'?'iniciar execução':'');if(reason==null)return;const wave=prompt('Onda atual (opcional):',ctx.activeRun&&ctx.activeRun.current_wave!=null?String(ctx.activeRun.current_wave):'');if(wave===null)return;const task=prompt('Tarefa atual (opcional):',ctx.activeRun&&ctx.activeRun.cursor&&ctx.activeRun.cursor.task?String(ctx.activeRun.cursor.task):'');if(task===null)return;await api('/api/runtime/action',{method:'POST',body:JSON.stringify({action,reason,activeSession:session,wave:wave?Number(wave):null,task:task||null})});await refresh();}
609
- async function runtimeGateResolve(gateId,decision){if(runtimeDisabled())return;const needsReason=decision==='reject'||decision==='waive';const reason=needsReason?prompt('Justificativa obrigatória para '+decision+':',''):'';if(needsReason&&(!reason||!reason.trim()))return alert('Justificativa é obrigatória para '+decision+'.');await api('/api/runtime/gates/resolve',{method:'POST',body:JSON.stringify({gateId,decision,actor:'dashboard',reason:reason&&reason.trim()?reason.trim():undefined,activeSession:session})});await refresh();}
610
- window.setTab=setTab;window.openSession=openSession;window.changeReview=changeReview;window.addComment=addComment;window.resolveComment=resolveComment;window.runtimeAction=runtimeAction;window.runtimeGateResolve=runtimeGateResolve;refresh().catch((err)=>{app.innerHTML='<div class="panel"><h2>Erro</h2><div class="muted">'+esc(err.message)+'</div></div>';});
611
- </script></body></html>`;
612
- }
613
-
614
- function readJsonBody(req) {
615
- return new Promise((resolve, reject) => {
616
- let raw = '';
617
- req.on('data', (chunk) => {
618
- raw += chunk;
619
- if (raw.length > 1024 * 1024) {
620
- reject(new Error('Payload demasiado grande.'));
621
- req.destroy();
622
- }
623
- });
624
- req.on('end', () => {
625
- if (!raw.trim()) return resolve({});
626
- try {
627
- resolve(JSON.parse(raw));
628
- } catch (err) {
629
- reject(new Error('JSON inválido.'));
630
- }
631
- });
632
- req.on('error', reject);
633
- });
634
- }
635
-
636
- function sendJson(res, status, body) {
637
- const payload = JSON.stringify(body, null, 2);
638
- res.writeHead(status, {
639
- 'Content-Type': 'application/json; charset=utf-8',
640
- 'Content-Length': Buffer.byteLength(payload),
641
- 'Cache-Control': 'no-store',
642
- });
643
- res.end(payload);
644
- }
645
-
646
- function createDashboardServer(projectRoot, opts = {}) {
647
- const root = path.resolve(projectRoot);
648
- const server = http.createServer(async (req, res) => {
649
- try {
650
- const reqUrl = new URL(req.url || '/', 'http://127.0.0.1');
651
- if (req.method === 'GET' && reqUrl.pathname === '/') {
652
- const html = dashboardHtml();
653
- res.writeHead(200, {
654
- 'Content-Type': 'text/html; charset=utf-8',
655
- 'Content-Length': Buffer.byteLength(html),
656
- 'Cache-Control': 'no-store',
657
- });
658
- res.end(html);
659
- return;
660
- }
661
-
662
- if (req.method === 'GET' && reqUrl.pathname === '/api/context') {
663
- const activeSession = reqUrl.searchParams.get('session') || opts.activeSession || null;
664
- sendJson(res, 200, { ...loadDashboardContext(root, { activeSession }), dashboard: { readOnly: Boolean(opts.readOnly) } });
665
- return;
666
- }
667
-
668
- if (opts.readOnly && req.method === 'POST' && (reqUrl.pathname.startsWith('/api/review/') || reqUrl.pathname.startsWith('/api/runtime/'))) {
669
- sendJson(res, 403, { error: 'Dashboard em modo read-only.' });
670
- return;
671
- }
672
-
673
- if (req.method === 'POST' && reqUrl.pathname === '/api/review/status') {
674
- const body = await readJsonBody(req);
675
- const result = savePlanReviewStatus(root, body || {});
676
- sendJson(res, 200, result);
677
- return;
678
- }
679
-
680
- if (req.method === 'POST' && reqUrl.pathname === '/api/review/comment') {
681
- const body = await readJsonBody(req);
682
- const result = addPlanReviewComment(root, body || {});
683
- sendJson(res, 200, result);
684
- return;
685
- }
686
-
687
- if (req.method === 'POST' && reqUrl.pathname === '/api/review/comment-status') {
688
- const body = await readJsonBody(req);
689
- const result = updatePlanReviewCommentStatus(root, body || {});
690
- if (!result) {
691
- sendJson(res, 404, { error: 'Comentário não encontrado.' });
692
- return;
693
- }
694
- const stateText = readTextIfExists(health.oxePaths(root).state) || '';
695
- savePlanReviewStatus(root, {
696
- activeSession: body.activeSession,
697
- status: health.parsePlanReviewStatus(stateText) || 'in_review',
698
- note: 'Estado de comentários de revisão atualizado',
699
- author: body.author || 'dashboard',
700
- });
701
- sendJson(res, 200, result);
702
- return;
703
- }
704
-
705
- if (req.method === 'POST' && reqUrl.pathname === '/api/runtime/action') {
706
- const body = await readJsonBody(req);
707
- const result = operational.applyRuntimeAction(root, body.activeSession || opts.activeSession || null, body || {});
708
- sendJson(res, 200, result);
709
- return;
710
- }
711
-
712
- if (req.method === 'POST' && reqUrl.pathname === '/api/runtime/gates/resolve') {
713
- const body = await readJsonBody(req);
714
- const result = await operational.resolveRuntimeGate(root, body.activeSession || opts.activeSession || null, body || {});
715
- sendJson(res, 200, result);
716
- return;
717
- }
718
-
719
- sendJson(res, 404, { error: 'Rota não encontrada.' });
720
- } catch (err) {
721
- sendJson(res, 500, { error: err && err.message ? err.message : 'Erro interno.' });
722
- }
723
- });
724
- return server;
725
- }
726
-
727
- module.exports = {
728
- loadDashboardContext,
729
- savePlanReviewStatus,
730
- addPlanReviewComment,
731
- updatePlanReviewCommentStatus,
732
- createDashboardServer,
733
- parsePlan,
734
- parseSpec,
735
- parseVerify,
736
- buildCoverageMatrix,
737
- };
1
+ 'use strict';
2
+
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+ const http = require('http');
6
+ const { URL } = require('url');
7
+ const health = require('./oxe-project-health.cjs');
8
+ const operational = require('./oxe-operational.cjs');
9
+ const azure = require('./oxe-azure.cjs');
10
+ const contextEngine = require('./oxe-context-engine.cjs');
11
+
12
+ function readTextIfExists(p) {
13
+ try { return fs.existsSync(p) ? fs.readFileSync(p, 'utf8') : null; } catch { return null; }
14
+ }
15
+
16
+ function readJsonArrayIfExists(p) {
17
+ try {
18
+ if (!fs.existsSync(p)) return [];
19
+ const raw = JSON.parse(fs.readFileSync(p, 'utf8'));
20
+ return Array.isArray(raw) ? raw : [];
21
+ } catch { return []; }
22
+ }
23
+
24
+ function ensureDirForFile(p) { fs.mkdirSync(path.dirname(p), { recursive: true }); }
25
+ function firstMatch(text, regex) { const m = String(text || '').match(regex); return m ? m[1].trim() : null; }
26
+ function escapeRegex(v) { return v.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); }
27
+ function summarizeText(text, max = 500) { const clean = String(text || '').replace(/\r\n/g, '\n').trim(); return !clean ? '' : clean.length > max ? `${clean.slice(0, max - 1)}…` : clean; }
28
+ function normalizeCell(v) { return String(v || '').replace(/<br\s*\/?>/gi, ' ').replace(/`/g, '').replace(/\s+/g, ' ').trim(); }
29
+ function splitTableRow(line) { return line.trim().replace(/^\|/, '').replace(/\|$/, '').split('|').map((c) => normalizeCell(c)); }
30
+
31
+ function parseMarkdownTables(text) {
32
+ const lines = String(text || '').replace(/\r\n/g, '\n').split('\n');
33
+ const tables = [];
34
+ for (let i = 0; i < lines.length - 1; i += 1) {
35
+ if (!lines[i].trim().startsWith('|')) continue;
36
+ if (!/^\s*\|?[\-:\s|]+\|?\s*$/.test(lines[i + 1] || '')) continue;
37
+ const headers = splitTableRow(lines[i]);
38
+ const rows = [];
39
+ let j = i + 2;
40
+ while (j < lines.length && lines[j].trim().startsWith('|')) {
41
+ const cells = splitTableRow(lines[j]);
42
+ const row = {};
43
+ for (let k = 0; k < headers.length; k += 1) row[headers[k]] = normalizeCell(cells[k] || '');
44
+ rows.push(row);
45
+ j += 1;
46
+ }
47
+ tables.push({ headers, rows });
48
+ i = j - 1;
49
+ }
50
+ return tables;
51
+ }
52
+
53
+ function findTableByHeaders(text, expected) {
54
+ const wants = expected.map((x) => x.toLowerCase());
55
+ return parseMarkdownTables(text).find((table) => wants.every((w) => table.headers.some((h) => h.toLowerCase() === w)));
56
+ }
57
+
58
+ function listSectionItems(text, heading) {
59
+ const match = String(text || '').match(new RegExp(`##\\s*${escapeRegex(heading)}\\s*\\n+([\\s\\S]*?)(?=\\n##\\s|$)`, 'i'));
60
+ if (!match) return [];
61
+ return match[1].split('\n').map((l) => l.trim()).filter((l) => /^-\s+/.test(l)).map((l) => l.replace(/^-\s+/, '').trim()).filter(Boolean);
62
+ }
63
+
64
+ function parsePlan(planMd) {
65
+ const parts = planMd.split(/^###\s+(T\d+)\s*[—-]\s*/m);
66
+ const tasks = [];
67
+ const waves = {};
68
+ for (let i = 1; i < parts.length; i += 2) {
69
+ const id = parts[i].trim();
70
+ const rest = (parts[i + 1] || '').split(/^###\s+T\d+/m)[0];
71
+ const title = ((rest.match(/^([^\n]+)/) || [null, ''])[1] || '').trim();
72
+ const wave = Number((rest.match(/\*\*Onda:\*\*\s*(\d+)/i) || [null, ''])[1]) || null;
73
+ const dependsOn = (((rest.match(/\*\*Depende\s+de:\*\*\s*([^\n]+)/i) || [null, ''])[1]) || '').split(/[,\s]+/).filter((s) => /^T\d+$/.test(s.trim()));
74
+ const verifyCommand = (rest.match(/Comando:\s*`([^`]+)`/i) || [null, null])[1];
75
+ const aceite = ((((rest.match(/\*\*Aceite\s+vinculado:\*\*\s*([^\n]+)/i) || [null, ''])[1]) || '').match(/A\d+/g) || []);
76
+ const decisions = ((((rest.match(/\*\*Decisão\s+vinculada:\*\*\s*([^\n]+)/i) || [null, ''])[1]) || '').match(/D-\d+/g) || []);
77
+ const task = { id, title, wave, dependsOn, verifyCommand, aceite, decisions };
78
+ tasks.push(task);
79
+ if (wave != null) (waves[wave] ||= []).push(id);
80
+ }
81
+ return {
82
+ tasks,
83
+ totalTasks: tasks.length,
84
+ waves: Object.keys(waves).map((k) => ({ wave: Number(k), taskIds: waves[k], tasks: waves[k].map((id) => tasks.find((t) => t.id === id)).filter(Boolean) })).sort((a, b) => a.wave - b.wave),
85
+ };
86
+ }
87
+
88
+ function parseSpec(specMd) {
89
+ const objective = (((specMd.match(/##\s*Objetivo\s*\n+([\s\S]*?)(?=\n##\s|\n#[^\#]|$)/im) || [null, ''])[1]) || '').trim().split('\n')[0].trim() || null;
90
+ const criteria = [];
91
+ const m = specMd.match(/##\s*Critérios.*?aceite[\s\S]*?(\|[\s\S]*?)(?=\n##\s|\n#[^\#]|$)/im);
92
+ if (m) {
93
+ for (const row of m[1].split('\n').filter((l) => l.startsWith('|'))) {
94
+ const cells = row.split('|').map((c) => c.trim()).filter(Boolean);
95
+ if (cells.length >= 2 && /^(?:A\d+(?:\.\d+)?|G\d+)$/i.test(cells[0])) criteria.push({ id: cells[0].toUpperCase(), criterion: cells[1] || '', howToVerify: cells[2] || '' });
96
+ }
97
+ }
98
+ return { objective, criteria };
99
+ }
100
+
101
+ function parseRuntime(runtimeMd) {
102
+ const agentTable = findTableByHeaders(runtimeMd, ['ID', 'Papel', 'Tarefas', 'Estado']);
103
+ const checkpointTable = findTableByHeaders(runtimeMd, ['ID', 'Tipo', 'Escopo', 'Estado']);
104
+ return {
105
+ currentWave: Number(firstMatch(runtimeMd, /\*\*Onda:\*\*\s*([^\n]+)/i)) || firstMatch(runtimeMd, /\*\*Onda:\*\*\s*([^\n]+)/i),
106
+ status: firstMatch(runtimeMd, /\*\*Estado:\*\*\s*([^\n]+)/i),
107
+ activeTasks: ((firstMatch(runtimeMd, /\*\*Tarefas ativas:\*\*\s*([^\n]+)/i) || '').split(',').map((x) => x.trim()).filter(Boolean)),
108
+ nextAction: firstMatch(runtimeMd, /\*\*Ação:\*\*\s*([^\n]+)/i),
109
+ nextReason: firstMatch(runtimeMd, /\*\*Motivo:\*\*\s*([^\n]+)/i),
110
+ agents: (agentTable?.rows || []).map((row) => ({ id: row.ID || row.Id || '—', role: row.Papel || row.Role || '—', tasks: (row.Tarefas || row.Tasks || '').split(',').map((x) => x.trim()).filter(Boolean), status: row.Estado || row.Status || '—' })),
111
+ checkpoints: (checkpointTable?.rows || []).map((row) => ({ id: row.ID || row.Id || '—', type: row.Tipo || row.Type || '—', scope: row.Escopo || row.Scope || '—', status: row.Estado || row.Status || '—', decision: row.Decisão || row.Decisao || row.Decision || '—' })),
112
+ evidence: listSectionItems(runtimeMd, 'Evidências produzidas'),
113
+ blockages: listSectionItems(runtimeMd, 'Bloqueios').filter((x) => !/^(\(nenhum\)|nenhum)$/i.test(x)),
114
+ };
115
+ }
116
+
117
+ function parseCheckpointsIndex(md) {
118
+ const table = findTableByHeaders(md, ['ID', 'Tipo', 'Fase', 'Escopo', 'Estado']);
119
+ return (table?.rows || []).map((row) => ({ id: row.ID || row.Id || '—', type: row.Tipo || row.Type || '—', phase: row.Fase || row.Phase || '—', scope: row.Escopo || row.Scope || '—', status: row.Estado || row.Status || '—', notes: row.Notas || row.Notes || '—' }));
120
+ }
121
+
122
+ function parseSessionsIndex(md) {
123
+ const table = parseMarkdownTables(md).find((t) => {
124
+ const h = t.headers.map((x) => x.toLowerCase());
125
+ return h.includes('id') && h.includes('nome') && h.includes('status') && h.includes('path');
126
+ });
127
+ return (table?.rows || []).map((row) => ({ id: row.ID || row.Id || '—', name: row.Nome || row.Name || '—', status: row.Status || '—', createdAt: row.Criada || row.Created || '—', lastActivity: row['Última atividade'] || row['Ultima atividade'] || row['Last activity'] || '—', summary: row.Resumo || row.Summary || '—', path: (row.Path || row.Caminho || '—').replace(/`/g, '') }));
128
+ }
129
+
130
+ function parseSessionDetail(md) {
131
+ return { id: firstMatch(md, /\*\*ID:\*\*\s*([^\n]+)/i), name: firstMatch(md, /\*\*Nome:\*\*\s*([^\n]+)/i), status: firstMatch(md, /\*\*Status:\*\*\s*([^\n]+)/i), createdAt: firstMatch(md, /\*\*Criada:\*\*\s*([^\n]+)/i), lastActivity: firstMatch(md, /\*\*(?:Última|Ultima) atividade:\*\*\s*([^\n]+)/i), summary: firstMatch(md, /\*\*Resumo:\*\*\s*([^\n]+)/i), tags: listSectionItems(md, 'Tags'), history: (findTableByHeaders(md, ['Data', 'Evento'])?.rows || []).map((row) => ({ date: row.Data || row.Date || '—', event: row.Evento || row.Event || '—' })) };
132
+ }
133
+
134
+ function normalizeEvidenceStatus(raw) {
135
+ const v = String(raw || '').toLowerCase();
136
+ if (!v) return 'mentioned';
137
+ if (/(ok|pass|aprov|sim|true|done|conclu)/.test(v)) return 'passed';
138
+ if (/(fail|falh|reprov|não|nao|false|blocked)/.test(v)) return 'failed';
139
+ return 'mentioned';
140
+ }
141
+
142
+ function parseVerify(md) {
143
+ const criteria = [];
144
+ for (const table of parseMarkdownTables(md)) {
145
+ for (const row of table.rows) {
146
+ const idCandidate = row.ID || row.Id || row['Critério'] || row['Criterio'] || '';
147
+ const match = String(idCandidate).match(/A\d+/i);
148
+ if (!match) continue;
149
+ criteria.push({ id: match[0].toUpperCase(), status: normalizeEvidenceStatus(row.Status || row.Resultado || row.Result || row.Veredito || row['Passou?'] || ''), summary: row.Evidência || row.Evidencia || row.Resumo || row.Notas || '' });
150
+ }
151
+ }
152
+ return { criteria, mentionedCriteria: Array.from(new Set((md.match(/\bA\d+\b/g) || []).map((x) => x.toUpperCase()))), failed: /\b(verify_failed|falhou|falha|reprovad)\b/i.test(md), passed: /\b(verify_complete|aprovad|passou|sucesso)\b/i.test(md) };
153
+ }
154
+
155
+ function confidenceBand(confidence, threshold) {
156
+ const normalizedThreshold = health.normalizePlanConfidenceThreshold(threshold);
157
+ if (confidence == null) return 'unknown';
158
+ if (health.isExecutablePlanConfidence(confidence, normalizedThreshold)) return 'ready';
159
+ if (confidence >= Math.max(80, normalizedThreshold - 10)) return 'rational_but_not_ready';
160
+ if (confidence >= 50) return 'needs_refinement';
161
+ return 'do_not_execute';
162
+ }
163
+
164
+ function computeReadiness(ctx, threshold) {
165
+ if (ctx.workspaceMode === 'product_package' && ctx.releaseReadiness) {
166
+ const blockers = Array.isArray(ctx.releaseReadiness.blockers) ? ctx.releaseReadiness.blockers.slice() : [];
167
+ const warnings = Array.isArray(ctx.releaseReadiness.warnings) ? ctx.releaseReadiness.warnings.slice() : [];
168
+ return {
169
+ go: Boolean(ctx.releaseReadiness.ok),
170
+ decision: ctx.releaseReadiness.ok ? 'go' : 'no-go',
171
+ threshold: health.normalizePlanConfidenceThreshold(threshold),
172
+ confidence: ctx.plan && ctx.plan.selfEvaluation ? ctx.plan.selfEvaluation.confidence : null,
173
+ confidenceBand: confidenceBand(ctx.plan && ctx.plan.selfEvaluation ? ctx.plan.selfEvaluation.confidence : null, threshold),
174
+ checkpointPending: false,
175
+ blockers,
176
+ warnings,
177
+ };
178
+ }
179
+ const normalizedThreshold = health.normalizePlanConfidenceThreshold(threshold);
180
+ const blockers = [];
181
+ const warnings = [...ctx.diagnostics.reviewWarnings, ...ctx.diagnostics.runtimeWarnings, ...ctx.diagnostics.planWarnings];
182
+ if (!ctx.plan.selfEvaluation || !ctx.plan.selfEvaluation.hasSection) blockers.push('self_evaluation:missing');
183
+ if (ctx.plan.selfEvaluation && Array.isArray(ctx.plan.selfEvaluation.warnings) && ctx.plan.selfEvaluation.warnings.length) {
184
+ blockers.push(`self_evaluation:warnings:${ctx.plan.selfEvaluation.warnings.length}`);
185
+ }
186
+ if (ctx.planReviewStatus !== 'approved') blockers.push(`review_status:${ctx.planReviewStatus || 'draft'}`);
187
+ if (ctx.plan.selfEvaluation.bestPlan === 'não') blockers.push('best_plan:no');
188
+ if (ctx.plan.selfEvaluation.confidence == null) blockers.push('confidence:missing');
189
+ else if (!health.isExecutablePlanConfidence(ctx.plan.selfEvaluation.confidence, normalizedThreshold)) {
190
+ blockers.push(`confidence:${ctx.plan.selfEvaluation.confidence}%<=${normalizedThreshold}%`);
191
+ }
192
+ if (!ctx.executionRationality || !ctx.executionRationality.implementationPackReady) {
193
+ blockers.push('implementation_pack:not_ready');
194
+ }
195
+ if (!ctx.executionRationality || !ctx.executionRationality.referenceAnchorsReady) {
196
+ blockers.push('reference_anchors:not_ready');
197
+ }
198
+ if (!ctx.executionRationality || !ctx.executionRationality.fixturePackReady) {
199
+ blockers.push('fixture_pack:not_ready');
200
+ }
201
+ if (ctx.checkpoints.parsed.some((x) => /pending_approval/i.test(x.status))) blockers.push('checkpoint:pending_approval');
202
+ if (ctx.runtime.parsed.status === 'blocked') blockers.push('runtime:blocked');
203
+ if (ctx.spec.uncoveredCriteria.length) warnings.push(`${ctx.spec.uncoveredCriteria.length} critérios sem cobertura no plano`);
204
+ if (ctx.executionRationality && Array.isArray(ctx.executionRationality.criticalExecutionGaps)) {
205
+ warnings.push(...ctx.executionRationality.criticalExecutionGaps);
206
+ }
207
+ return {
208
+ go: blockers.length === 0,
209
+ decision: blockers.length === 0 ? 'go' : 'no-go',
210
+ threshold: normalizedThreshold,
211
+ confidence: ctx.plan.selfEvaluation.confidence,
212
+ confidenceBand: confidenceBand(ctx.plan.selfEvaluation.confidence, normalizedThreshold),
213
+ checkpointPending: blockers.includes('checkpoint:pending_approval'),
214
+ blockers,
215
+ warnings,
216
+ };
217
+ }
218
+
219
+ function buildCoverageMatrix(spec, plan, verify) {
220
+ const taskMap = new Map();
221
+ for (const task of plan.tasks) {
222
+ for (const criterion of task.aceite || []) {
223
+ if (!taskMap.has(criterion)) taskMap.set(criterion, []);
224
+ taskMap.get(criterion).push(task.id);
225
+ }
226
+ }
227
+ const verifyMap = new Map((verify.criteria || []).map((x) => [x.id, x]));
228
+ return spec.criteria.map((c) => ({
229
+ id: c.id,
230
+ criterion: c.criterion,
231
+ verifyHow: c.howToVerify,
232
+ tasks: taskMap.get(c.id) || [],
233
+ planCovered: taskMap.has(c.id),
234
+ verifyStatus: verifyMap.has(c.id) ? verifyMap.get(c.id).status : (verify.mentionedCriteria || []).includes(c.id) ? 'mentioned' : 'missing',
235
+ verifySummary: verifyMap.has(c.id) ? verifyMap.get(c.id).summary : '',
236
+ }));
237
+ }
238
+
239
+ function computeCalibration(phase, confidence, verify, threshold) {
240
+ const normalizedThreshold = health.normalizePlanConfidenceThreshold(threshold);
241
+ if (confidence == null) return { status: 'pending', summary: 'Calibração indisponível antes do verify.' };
242
+ const low = String(phase || '').toLowerCase();
243
+ const completed = low === 'verify_complete' || verify.passed;
244
+ const failed = low === 'verify_failed' || verify.failed;
245
+ if (!completed && !failed) return { status: 'pending', summary: 'Calibração só fecha após verify.' };
246
+ if (health.isExecutablePlanConfidence(confidence, normalizedThreshold) && failed) {
247
+ return { status: 'overconfident', summary: `Confiança ${confidence}% acima do gate executável, mas o verify falhou.` };
248
+ }
249
+ if (!health.isExecutablePlanConfidence(confidence, normalizedThreshold) && failed) {
250
+ return { status: 'calibrated-risk', summary: `O plano já sinalizava risco (${confidence}%) abaixo do gate executável e o verify confirmou a fragilidade.` };
251
+ }
252
+ if (!health.isExecutablePlanConfidence(confidence, normalizedThreshold) && completed) {
253
+ return { status: 'underconfident', summary: `O resultado final foi melhor que a confiança inicial (${confidence}%), mas o plano ainda não superava o gate executável.` };
254
+ }
255
+ if (health.isExecutablePlanConfidence(confidence, normalizedThreshold) && completed) {
256
+ return { status: 'well-calibrated', summary: `Alta confiança executável (${confidence}%) e verify coerente com a expectativa.` };
257
+ }
258
+ return { status: 'acceptable', summary: `Confiança ${confidence}% e verify dentro da faixa esperada.` };
259
+ }
260
+
261
+ function readRepositoryContext(codebaseDir) {
262
+ const names = ['OVERVIEW.md', 'STACK.md', 'STRUCTURE.md', 'TESTING.md', 'CONCERNS.md', 'INTEGRATIONS.md'];
263
+ const out = {};
264
+ for (const name of names) out[name.replace('.md', '').toLowerCase()] = { path: path.join(codebaseDir, name), summary: summarizeText(readTextIfExists(path.join(codebaseDir, name)) || '', 420) };
265
+ return out;
266
+ }
267
+
268
+ function ensureStateSection(stateText, sectionTitle) {
269
+ return new RegExp(`##\\s*${escapeRegex(sectionTitle)}`, 'i').test(stateText) ? stateText : `${stateText.trimEnd()}\n\n## ${sectionTitle}\n\n`;
270
+ }
271
+
272
+ function upsertBulletInSection(body, label, value) {
273
+ const line = `- **${label}:** ${value}`;
274
+ const re = new RegExp(`^- \\*\\*${escapeRegex(label)}:\\*\\*.*$`, 'im');
275
+ if (re.test(body)) return body.replace(re, line);
276
+ const trimmed = body.trimEnd();
277
+ return !trimmed ? `${line}\n` : `${trimmed}\n${line}\n`;
278
+ }
279
+
280
+ function upsertStateBullet(stateText, sectionTitle, label, value) {
281
+ const ensured = ensureStateSection(stateText, sectionTitle);
282
+ const re = new RegExp(`(##\\s*${escapeRegex(sectionTitle)}\\s*\\n+)([\\s\\S]*?)(?=\\n##\\s|$)`, 'i');
283
+ return ensured.replace(re, (m, head, body) => `${head}${upsertBulletInSection(body, label, value)}`);
284
+ }
285
+
286
+ function reviewPaths(projectRoot, activeSession) {
287
+ const p = health.scopedOxePaths(projectRoot, activeSession);
288
+ return { ...p, state: health.oxePaths(projectRoot).state, reviewJson: p.planReviewComments };
289
+ }
290
+
291
+ function readScopedText(primaryPath, fallbackPath) {
292
+ const primary = readTextIfExists(primaryPath);
293
+ if (primary) return primary;
294
+ return fallbackPath && fallbackPath !== primaryPath ? readTextIfExists(fallbackPath) || '' : '';
295
+ }
296
+
297
+ function savePlanReviewStatus(projectRoot, input = {}) {
298
+ const globalStatePath = health.oxePaths(projectRoot).state;
299
+ const stateText = readTextIfExists(globalStatePath) || '# OXE — Estado\n';
300
+ const activeSession = input.activeSession === undefined ? health.parseActiveSession(stateText) : input.activeSession;
301
+ const p = reviewPaths(projectRoot, activeSession || null);
302
+ const nowIso = new Date().toISOString();
303
+ const status = String(input.status || 'draft');
304
+ const note = String(input.note || '—');
305
+ const author = String(input.author || 'dashboard');
306
+ const reviewRef = path.relative(path.join(projectRoot, '.oxe'), p.planReview).replace(/\\/g, '/');
307
+ let nextState = stateText;
308
+ nextState = upsertStateBullet(nextState, 'Revisão do plano (opcional — dashboard / aprovação)', 'plan_review_status', `\`${status}\``);
309
+ nextState = upsertStateBullet(nextState, 'Revisão do plano (opcional — dashboard / aprovação)', 'plan_review_updated', `\`${nowIso}\``);
310
+ nextState = upsertStateBullet(nextState, 'Revisão do plano (opcional — dashboard / aprovação)', 'plan_review_ref', `\`${reviewRef}\``);
311
+ nextState = upsertStateBullet(nextState, 'Revisão do plano (opcional — dashboard / aprovação)', 'Notas', note);
312
+ ensureDirForFile(globalStatePath);
313
+ fs.writeFileSync(globalStatePath, nextState, 'utf8');
314
+ const comments = readJsonArrayIfExists(p.reviewJson);
315
+ const format = (c) => `- **${c.target || 'plan'}** [${c.type || 'note'} | ${c.status || 'open'}] ${c.text || ''}`;
316
+ const reviewMd =
317
+ `---\noxe_doc: plan_review\nstatus: ${status}\nupdated: ${nowIso.slice(0, 10)}\nplan_ref: ${path.basename(p.plan)}\n---\n\n# OXE — Revisão do Plano\n\n## Estado\n\n- **Status:** ${status}\n- **Atualizado em:** ${nowIso}\n- **Origem:** dashboard local\n- **Autor:** ${author}\n\n## Decisão\n\n- **Resultado:** ${status}\n- **Justificativa:** ${note}\n\n## Comentários abertos\n\n${comments.filter((x) => x.status !== 'resolved').map(format).join('\n') || '- Nenhum'}\n\n## Comentários resolvidos\n\n${comments.filter((x) => x.status === 'resolved').map(format).join('\n') || '- Nenhum'}\n\n## Próxima ação recomendada\n\n${status === 'approved' ? '- `/oxe-execute` ou `oxe-cc status` para seguir a trilha.' : '- `/oxe-plan --replan` ou ajuste do plano antes de executar.'}\n`;
318
+ ensureDirForFile(p.planReview);
319
+ fs.writeFileSync(p.planReview, reviewMd, 'utf8');
320
+ operational.appendEvent(projectRoot, activeSession || null, {
321
+ type: 'plan_review_status_changed',
322
+ payload: { status, note, author, review_ref: reviewRef },
323
+ });
324
+ return { status, updatedAt: nowIso, ref: p.planReview, note, author, activeSession: activeSession || null };
325
+ }
326
+
327
+ function addPlanReviewComment(projectRoot, input = {}) {
328
+ const stateText = readTextIfExists(health.oxePaths(projectRoot).state) || '# OXE — Estado\n';
329
+ const activeSession = input.activeSession === undefined ? health.parseActiveSession(stateText) : input.activeSession;
330
+ const p = reviewPaths(projectRoot, activeSession || null);
331
+ const comments = readJsonArrayIfExists(p.reviewJson);
332
+ const next = { id: `c-${Date.now().toString(36)}`, target: String(input.target || 'plan'), type: String(input.type || 'note'), status: 'open', author: String(input.author || 'dashboard'), created_at: new Date().toISOString(), text: String(input.text || '').trim() };
333
+ comments.push(next);
334
+ ensureDirForFile(p.reviewJson);
335
+ fs.writeFileSync(p.reviewJson, JSON.stringify(comments, null, 2), 'utf8');
336
+ operational.appendEvent(projectRoot, activeSession || null, {
337
+ type: 'plan_review_comment_added',
338
+ payload: { comment_id: next.id, target: next.target, comment_type: next.type },
339
+ });
340
+ savePlanReviewStatus(projectRoot, { activeSession, status: health.parsePlanReviewStatus(stateText) || 'in_review', note: 'Há comentários de revisão em aberto', author: String(input.author || 'dashboard') });
341
+ return next;
342
+ }
343
+
344
+ function updatePlanReviewCommentStatus(projectRoot, input = {}) {
345
+ const stateText = readTextIfExists(health.oxePaths(projectRoot).state) || '# OXE — Estado\n';
346
+ const activeSession = input.activeSession === undefined ? health.parseActiveSession(stateText) : input.activeSession;
347
+ const p = reviewPaths(projectRoot, activeSession || null);
348
+ const comments = readJsonArrayIfExists(p.reviewJson);
349
+ const idx = comments.findIndex((x) => x.id === input.commentId);
350
+ if (idx === -1) return null;
351
+ comments[idx] = { ...comments[idx], status: String(input.status || 'resolved'), updated_at: new Date().toISOString() };
352
+ fs.writeFileSync(p.reviewJson, JSON.stringify(comments, null, 2), 'utf8');
353
+ operational.appendEvent(projectRoot, activeSession || null, {
354
+ type: 'plan_review_comment_updated',
355
+ payload: { comment_id: comments[idx].id, status: comments[idx].status },
356
+ });
357
+ return comments[idx];
358
+ }
359
+
360
+ function loadDashboardContext(projectRoot, opts = {}) {
361
+ const globalPaths = health.oxePaths(projectRoot);
362
+ const stateText = readTextIfExists(globalPaths.state) || '';
363
+ const activeSession = opts.activeSession === undefined ? health.parseActiveSession(stateText) : opts.activeSession;
364
+ const p = reviewPaths(projectRoot, activeSession || null);
365
+ const rootScoped = reviewPaths(projectRoot, null);
366
+ const report = health.buildHealthReport(projectRoot);
367
+ const specText = readScopedText(p.spec, rootScoped.spec);
368
+ const planText = readScopedText(p.plan, rootScoped.plan);
369
+ const verifyText = readScopedText(p.verify, rootScoped.verify);
370
+ const runtimeText = readScopedText(p.runtime, rootScoped.runtime);
371
+ const checkpointsText = readScopedText(p.checkpoints, rootScoped.checkpoints);
372
+ const spec = parseSpec(specText);
373
+ const plan = parsePlan(planText);
374
+ const runtime = parseRuntime(runtimeText);
375
+ const checkpoints = parseCheckpointsIndex(checkpointsText);
376
+ const verify = parseVerify(verifyText);
377
+ const activeRunState = operational.readRunState(projectRoot, activeSession || null);
378
+ const traceEvents = operational.readEvents(projectRoot, activeSession || null);
379
+ const traceSummary = operational.summarizeEvents(traceEvents);
380
+ const memoryLayers = operational.buildMemoryLayers(projectRoot, activeSession || null);
381
+ const capabilityCatalog = operational.readCapabilityCatalog(projectRoot);
382
+ const azurePaths = azure.azurePaths(projectRoot);
383
+ const dashboardPack = report.contextPacks && report.contextPacks.dashboard
384
+ ? report.contextPacks.dashboard
385
+ : contextEngine.inspectContextPack(projectRoot, { workflow: 'dashboard', activeSession: activeSession || null });
386
+ const sessionsRaw = readTextIfExists(globalPaths.sessionsIndex) || '';
387
+ const sessions = parseSessionsIndex(sessionsRaw);
388
+ const sessionPath = activeSession ? path.join(projectRoot, '.oxe', activeSession, 'SESSION.md') : null;
389
+ const sessionRaw = sessionPath ? readTextIfExists(sessionPath) || '' : '';
390
+ const ctx = {
391
+ projectRoot: path.resolve(projectRoot),
392
+ workspaceMode: report.workspaceMode || 'oxe_project',
393
+ releaseReadiness: report.releaseReadiness || null,
394
+ activeSession: activeSession || null,
395
+ phase: report.phase || health.parseStatePhase(stateText),
396
+ healthStatus: report.healthStatus,
397
+ nextStep: report.next,
398
+ planReviewStatus: report.planReviewStatus || 'draft',
399
+ state: { path: globalPaths.state, raw: stateText, parsed: { phase: health.parseStatePhase(stateText), activeSession, runtimeStatus: firstMatch(stateText, /\*\*runtime_status:\*\*\s*([^\n]+)/i) } },
400
+ spec: { path: p.spec, raw: specText, objective: spec.objective, criteria: spec.criteria, uncoveredCriteria: spec.criteria.filter((c) => !plan.tasks.some((t) => (t.aceite || []).includes(c.id))) },
401
+ plan: { path: p.plan, raw: planText, tasks: plan.tasks, waves: plan.waves, totalTasks: plan.totalTasks, selfEvaluation: report.planSelfEvaluation },
402
+ executionRationality: report.executionRationality || null,
403
+ runtime: { path: p.runtime, raw: runtimeText, summary: summarizeText(runtimeText, 800), parsed: runtime },
404
+ activeRun: activeRunState,
405
+ runtimeCanonical: activeRunState && activeRunState.canonical_state ? activeRunState.canonical_state : null,
406
+ compiledGraph: activeRunState && activeRunState.compiled_graph ? activeRunState.compiled_graph : null,
407
+ enterprise: {
408
+ runtimeMode: report.runtimeMode || null,
409
+ fallbackMode: report.fallbackMode || null,
410
+ verificationSummary: report.verificationSummary || null,
411
+ residualRiskSummary: report.residualRiskSummary || null,
412
+ evidenceCoverage: report.evidenceCoverage || null,
413
+ pendingGates: report.pendingGates || null,
414
+ gateQueue: report.gateQueue || null,
415
+ policyDecisionSummary: report.policyDecisionSummary || null,
416
+ policyCoverage: report.policyCoverage || null,
417
+ quotaSummary: report.quotaSummary || null,
418
+ auditSummary: report.auditSummary || null,
419
+ promotionSummary: report.promotionSummary || null,
420
+ promotionReadiness: report.promotionReadiness || null,
421
+ recoveryState: report.recoveryState || null,
422
+ multiAgent: report.multiAgent || null,
423
+ providerCatalog: report.providerCatalog || null,
424
+ implementationPackReady: report.implementationPackReady,
425
+ referenceAnchorsReady: report.referenceAnchorsReady,
426
+ fixturePackReady: report.fixturePackReady,
427
+ executionRationalityReady: report.executionRationalityReady,
428
+ criticalExecutionGaps: report.criticalExecutionGaps || [],
429
+ warnings: report.enterpriseWarn || [],
430
+ },
431
+ tracing: { path: operational.operationalPaths(projectRoot, activeSession || null).events, events: traceEvents, summary: traceSummary },
432
+ checkpoints: { path: p.checkpoints, raw: checkpointsText, parsed: checkpoints },
433
+ verify: { path: p.verify, raw: verifyText, summary: summarizeText(verifyText, 800), parsed: verify },
434
+ review: { markdownPath: p.planReview, commentsPath: p.reviewJson, comments: readJsonArrayIfExists(p.reviewJson) },
435
+ sessions: { indexPath: globalPaths.sessionsIndex, raw: sessionsRaw, items: sessions, currentPath: sessionPath, current: sessionRaw ? parseSessionDetail(sessionRaw) : null },
436
+ support: { capabilitiesSummary: summarizeText(readTextIfExists(p.capabilitiesIndex) || '', 420), investigationsSummary: summarizeText(readTextIfExists(p.investigationsIndex) || '', 420) },
437
+ capabilities: capabilityCatalog,
438
+ memoryLayers,
439
+ context: {
440
+ pack: dashboardPack,
441
+ packs: report.contextPacks || {},
442
+ quality: report.contextQuality || null,
443
+ freshness: report.packFreshness || {},
444
+ summaries: report.activeSummaryRefs || {},
445
+ semantics: report.semanticsDrift || null,
446
+ },
447
+ azure: report.azureActive && report.azure
448
+ ? {
449
+ ...report.azure,
450
+ profilePath: azurePaths.profile,
451
+ authStatusPath: azurePaths.authStatus,
452
+ inventoryMarkdownPath: azurePaths.inventoryMd,
453
+ serviceBusPath: azurePaths.serviceBusMd,
454
+ eventGridPath: azurePaths.eventGridMd,
455
+ sqlPath: azurePaths.sqlMd,
456
+ }
457
+ : null,
458
+ diagnostics: {
459
+ reviewWarnings: report.reviewWarn,
460
+ runtimeWarnings: report.runtimeWarn,
461
+ enterpriseWarnings: report.enterpriseWarn || [],
462
+ planWarnings: report.planWarn,
463
+ sessionWarnings: report.sessionWarn,
464
+ capabilityWarnings: report.capabilityWarn,
465
+ investigationWarnings: report.investigationWarn,
466
+ },
467
+ repositoryContext: readRepositoryContext(rootScoped.codebase),
468
+ };
469
+ if (ctx.azure) {
470
+ const inventorySummary = ctx.azure.inventorySummary || { total: 0, servicebus: 0, eventgrid: 0, sql: 0 };
471
+ ctx.repositoryContext.azure = {
472
+ path: ctx.azure.inventoryMarkdownPath,
473
+ summary: `login=${ctx.azure.authStatus && ctx.azure.authStatus.login_active ? 'ativo' : 'ausente'} · subscription=${ctx.azure.profile && (ctx.azure.profile.subscription_name || ctx.azure.profile.subscription_id) || '—'} · total=${inventorySummary.total} · sb=${inventorySummary.servicebus || 0} · eg=${inventorySummary.eventgrid || 0} · sql=${inventorySummary.sql || 0}`,
474
+ };
475
+ }
476
+ ctx.readiness = computeReadiness(ctx, report.planConfidenceThreshold || 90);
477
+ ctx.coverage = buildCoverageMatrix(ctx.spec, ctx.plan, verify);
478
+ ctx.calibration = computeCalibration(ctx.phase, ctx.plan.selfEvaluation.confidence, verify, ctx.readiness.threshold);
479
+ ctx.visual = {
480
+ flow: { nodes: [{ label: 'STATE', status: 'done' }, { label: 'SPEC', status: ctx.spec.raw ? 'done' : 'pending' }, { label: 'PLAN', status: ctx.plan.raw ? 'done' : 'pending' }, { label: 'REVIEW', status: ctx.planReviewStatus === 'approved' ? 'done' : /(rejected|needs_revision)/i.test(ctx.planReviewStatus) ? 'blocked' : 'active' }, { label: 'EXECUTE', status: ctx.runtime.parsed.status === 'running' ? 'active' : ctx.runtime.raw ? 'done' : 'pending' }, { label: 'CHECKPOINTS', status: ctx.readiness.checkpointPending ? 'active' : ctx.checkpoints.parsed.length ? 'done' : 'pending' }, { label: 'VERIFY', status: ctx.verify.raw ? 'done' : 'pending' }, { label: 'LESSONS', status: 'pending' }] },
481
+ artifactGraph: [
482
+ { id: 'state', label: 'STATE', path: ctx.state.path, detail: ctx.phase || 'índice global', status: 'done' },
483
+ { id: 'spec', label: 'SPEC', path: ctx.spec.path, detail: ctx.spec.objective || 'contrato', status: ctx.spec.raw ? 'done' : 'pending' },
484
+ { id: 'plan', label: 'PLAN', path: ctx.plan.path, detail: `${ctx.plan.totalTasks} tarefas`, status: ctx.plan.raw ? 'done' : 'pending' },
485
+ {
486
+ id: 'implementation-pack',
487
+ label: 'IMPLEMENTATION PACK',
488
+ path: ctx.executionRationality && ctx.executionRationality.implementationPack ? ctx.executionRationality.implementationPack.path : '—',
489
+ detail: ctx.executionRationality && ctx.executionRationality.implementationPack ? `${ctx.executionRationality.implementationPack.taskCount || 0} contratos` : 'sem contrato',
490
+ status: ctx.executionRationality && ctx.executionRationality.implementationPackReady ? 'done' : 'blocked',
491
+ },
492
+ {
493
+ id: 'reference-anchors',
494
+ label: 'REFERENCE ANCHORS',
495
+ path: ctx.executionRationality && ctx.executionRationality.referenceAnchors ? ctx.executionRationality.referenceAnchors.path : '—',
496
+ detail: ctx.executionRationality && ctx.executionRationality.referenceAnchors ? `${ctx.executionRationality.referenceAnchors.anchors ? ctx.executionRationality.referenceAnchors.anchors.length : 0} âncoras` : 'sem âncoras',
497
+ status: ctx.executionRationality && ctx.executionRationality.referenceAnchorsReady ? 'done' : 'blocked',
498
+ },
499
+ {
500
+ id: 'fixture-pack',
501
+ label: 'FIXTURE PACK',
502
+ path: ctx.executionRationality && ctx.executionRationality.fixturePack ? ctx.executionRationality.fixturePack.path : '—',
503
+ detail: ctx.executionRationality && ctx.executionRationality.fixturePack ? `${ctx.executionRationality.fixturePack.fixtureCount || 0} fixtures` : 'sem fixtures',
504
+ status: ctx.executionRationality && ctx.executionRationality.fixturePackReady ? 'done' : 'blocked',
505
+ },
506
+ { id: 'review', label: 'PLAN REVIEW', path: ctx.review.markdownPath, detail: ctx.planReviewStatus, status: ctx.planReviewStatus === 'approved' ? 'done' : 'active' },
507
+ { id: 'runtime', label: 'RUNTIME', path: ctx.runtime.path, detail: ctx.runtime.parsed.status || 'sem status', status: ctx.runtime.raw ? 'active' : 'pending' },
508
+ { id: 'active-run', label: 'ACTIVE RUN', path: operational.operationalPaths(projectRoot, activeSession || null).activeRun, detail: ctx.activeRun && ctx.activeRun.run_id ? `${ctx.activeRun.run_id} · ${ctx.activeRun.status}` : 'sem run ativo', status: ctx.activeRun ? 'active' : 'pending' },
509
+ { id: 'events', label: 'TRACE', path: operational.operationalPaths(projectRoot, activeSession || null).events, detail: `${ctx.tracing.summary.total} evento(s)`, status: ctx.tracing.summary.total ? 'done' : 'pending' },
510
+ { id: 'checkpoints', label: 'CHECKPOINTS', path: ctx.checkpoints.path, detail: `${ctx.checkpoints.parsed.length} gates`, status: ctx.readiness.checkpointPending ? 'active' : 'pending' },
511
+ { id: 'verify', label: 'VERIFY', path: ctx.verify.path, detail: ctx.calibration.status, status: ctx.verify.raw ? 'done' : 'pending' },
512
+ ],
513
+ };
514
+ if (ctx.azure) {
515
+ ctx.visual.artifactGraph.push(
516
+ {
517
+ id: 'azure-profile',
518
+ label: 'AZURE PROFILE',
519
+ path: ctx.azure.profilePath,
520
+ detail: ctx.azure.profile && (ctx.azure.profile.subscription_name || ctx.azure.profile.subscription_id) || 'sem subscription',
521
+ status: ctx.azure.authStatus && ctx.azure.authStatus.login_active ? 'done' : 'blocked',
522
+ },
523
+ {
524
+ id: 'azure-inventory',
525
+ label: 'AZURE INVENTORY',
526
+ path: ctx.azure.inventoryMarkdownPath,
527
+ detail: ctx.azure.inventorySummary ? `${ctx.azure.inventorySummary.total} recurso(s)` : 'inventário ausente',
528
+ status: ctx.azure.inventorySyncedAt ? (ctx.azure.inventoryStale && ctx.azure.inventoryStale.stale ? 'warning' : 'done') : 'pending',
529
+ }
530
+ );
531
+ }
532
+ ctx.operationalGraph = ctx.activeRun ? operational.buildOperationalGraph(ctx.activeRun) : { nodes: [], edges: [] };
533
+ ctx.dashboard = { readOnly: false };
534
+ return ctx;
535
+ }
536
+
537
+ function dashboardHtml() {
538
+ return `<!doctype html><html lang="pt-BR"><head><meta charset="utf-8"/><meta name="viewport" content="width=device-width,initial-scale=1"/><title>OXE Dashboard</title><style>
539
+ :root{--bg:#f4efe6;--bg2:#edf4ed;--panel:#fff;--ink:#1d2f3e;--muted:#617787;--line:#dbe3e8;--brand:#173f58;--ok:#1f7a52;--warn:#9d6b12;--bad:#a53e3e;--info:#235f84;--okbg:#e4f3eb;--warnbg:#fbf0da;--badbg:#f8e8e8;--infobg:#e5eff7;--shadow:0 16px 40px rgba(17,32,44,.08);--radius:18px}*{box-sizing:border-box}body{margin:0;background:linear-gradient(180deg,var(--bg),var(--bg2));font-family:"Segoe UI",Arial,sans-serif;color:var(--ink)}.page{max-width:1560px;margin:0 auto;padding:24px}.hero,.stats,.tabs,.grid2,.grid3,.layout{display:grid;gap:16px}.hero{grid-template-columns:1.2fr .8fr}.stats{grid-template-columns:repeat(5,minmax(0,1fr));margin:0 0 16px}.layout{grid-template-columns:1.45fr .95fr}.grid2{grid-template-columns:repeat(2,minmax(0,1fr))}.grid3{grid-template-columns:repeat(3,minmax(0,1fr))}.panel,.metric,.mini,.item,.entry{background:var(--panel);border:1px solid var(--line);border-radius:var(--radius);box-shadow:var(--shadow)}.panel{padding:18px}.metric,.mini,.item,.entry{padding:14px}.stack,.list,.rail{display:grid;gap:14px}.rail{grid-template-columns:repeat(8,minmax(100px,1fr))}.tabs{grid-template-columns:repeat(7,max-content)}.tab{padding:10px 14px;border:1px solid var(--line);border-radius:999px;background:#fff;cursor:pointer;font-weight:700}.tab.active{background:var(--brand);color:#fff;border-color:var(--brand)}.view{display:none}.view.active{display:block}.label{font-size:11px;letter-spacing:.08em;text-transform:uppercase;color:var(--muted)}.value{font-size:24px;font-weight:800;margin-top:6px}.muted{color:var(--muted)}.small{font-size:13px}.badge{display:inline-flex;align-items:center;justify-content:center;border-radius:999px;padding:6px 10px;font-size:11px;text-transform:uppercase;font-weight:800}.done{background:var(--okbg);color:var(--ok)}.active{background:var(--infobg);color:var(--info)}.warning{background:var(--warnbg);color:var(--warn)}.blocked{background:var(--badbg);color:var(--bad)}.pending{background:#edf1f4;color:#567181}.head{display:flex;justify-content:space-between;gap:10px;align-items:flex-start;margin-bottom:12px}.actions{display:flex;gap:10px;flex-wrap:wrap;margin-top:12px}button{border:0;border-radius:12px;padding:10px 12px;font-weight:700;cursor:pointer}.primary{background:var(--brand);color:#fff}.secondary{background:#edf2f5;color:var(--ink)}.warnbtn{background:#f2e3c5;color:#81540a}.danger{background:#f5dada;color:#8d3030}input,select,textarea{width:100%;border:1px solid var(--line);border-radius:12px;padding:10px;font:inherit}.form{display:grid;gap:10px}.raw{white-space:pre-wrap;background:#f8faf9;border:1px solid var(--line);border-radius:12px;padding:12px;max-height:220px;overflow:auto}.chip{display:inline-flex;border-radius:999px;padding:4px 8px;background:#eef3f6;color:#355267;font-size:12px;margin:4px 6px 0 0}.node{padding:12px;border:1px solid var(--line);border-radius:16px;background:#fff}.go{background:linear-gradient(180deg,#f2fbf5,#ebf7ef)}.nogo{background:linear-gradient(180deg,#fff5f5,#faeded)}@media (max-width:1200px){.hero,.layout{grid-template-columns:1fr}.rail{grid-template-columns:repeat(4,minmax(100px,1fr))}}@media (max-width:860px){.stats,.grid2,.grid3,.tabs,.rail{grid-template-columns:1fr}.page{padding:16px}}</style></head><body><div class="page"><div class="hero"><div class="panel"><h1 style="margin:0;font-size:42px">OXE Decision Control Room</h1><div class="muted" style="margin-top:10px">Control room para decisões reais de Go / No-Go, sem duplicar a fonte de verdade textual do OXE.</div></div><div class="grid2"><div class="mini"><div class="label">Projeto</div><div class="small" id="hero-project">—</div></div><div class="mini"><div class="label">Sessão</div><div class="value" id="hero-session">—</div></div><div class="mini"><div class="label">Próximo passo</div><div class="small" id="hero-next">—</div></div><div class="mini"><div class="label">Confiança</div><div class="value" id="hero-confidence">—</div></div></div></div><div id="app">Carregando…</div></div><script>
540
+ const app=document.getElementById('app');let ctx=null;let tab='decision';let session=null;
541
+ const esc=(s)=>String(s??'').replace(/[&<>"]/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c])); const cls=(s)=>{const v=String(s||'').toLowerCase();if(/(healthy|approved|done|go|well-calibrated|passed|ready|completed)/.test(v))return'done';if(/(running|in_review|active|mentioned|acceptable|controlled|replaying)/.test(v))return'active';if(/(rejected|needs_revision|blocked|failed|no-go|overconfident|do_not_execute|aborted|waiting_approval)/.test(v))return'blocked';if(/(risk|warning|underconfident|needs_refinement|paused)/.test(v))return'warning';return'pending';}; const badge=(s,l)=>'<span class="badge '+cls(s)+'">'+esc(l||s||'pending')+'</span>'; const list=(items,empty)=>items&&items.length?'<div class="list">'+items.join('')+'</div>':'<div class="entry small">'+esc(empty)+'</div>'; const runtimeDisabled=()=>ctx&&ctx.dashboard&&ctx.dashboard.readOnly;
542
+ async function api(url,opts={}){const res=await fetch(url,{headers:{'Content-Type':'application/json'},...opts});if(!res.ok)throw new Error(await res.text());return res.json();} async function refresh(){ctx=await api('/api/context'+(session?'?session='+encodeURIComponent(session):''));render();}
543
+ function render(){document.getElementById('hero-project').textContent=ctx.projectRoot||'—';document.getElementById('hero-session').textContent=ctx.activeSession||'modo legado';document.getElementById('hero-next').textContent=(ctx.nextStep.step||'—')+' · '+(ctx.nextStep.reason||'—');document.getElementById('hero-confidence').textContent=ctx.readiness.confidence!=null?ctx.readiness.confidence+'%':'—';
544
+ const flow=(ctx.visual.flow.nodes||[]).map((n)=>'<div class="node"><div class="label">Etapa</div><div style="font-weight:800;font-size:18px;margin-top:6px">'+esc(n.label)+'</div><div style="margin-top:10px">'+badge(n.status)+'</div></div>');
545
+ const graph=(ctx.visual.artifactGraph||[]).map((n)=>'<div class="item"><div class="head"><strong>'+esc(n.label)+'</strong>'+badge(n.status)+'</div><div class="small">'+esc(n.detail||'—')+'</div><div class="small muted" style="margin-top:8px">'+esc(n.path||'—')+'</div></div>');
546
+ const waves=(ctx.plan.waves||[]).map((w)=>'<div class="panel"><div class="head"><div><strong>Onda '+esc(w.wave)+'</strong><div class="small muted">'+esc(w.taskIds.length)+' tarefas</div></div>'+badge(String(ctx.runtime.parsed.currentWave)===String(w.wave)?'running':'planned')+'</div>'+w.tasks.map((t)=>'<div class="entry"><div style="font-weight:800">'+esc(t.id)+' — '+esc(t.title)+'</div><div class="small muted" style="margin-top:6px">Depende de: '+esc(t.dependsOn.length?t.dependsOn.join(', '):'—')+'</div><div class="small muted">Verificação: '+esc(t.verifyCommand||'—')+'</div><div class="small" style="margin-top:6px">'+(t.aceite||[]).map((x)=>'<span class="chip">'+esc(x)+'</span>').join('')+(t.decisions||[]).map((x)=>'<span class="chip">'+esc(x)+'</span>').join('')+'</div></div>').join('')+'</div>');
547
+ const coverage=(ctx.coverage||[]).map((c)=>'<div class="item"><div class="head"><strong>'+esc(c.id)+'</strong>'+badge(c.verifyStatus,c.verifyStatus)+'</div><div class="small">'+esc(c.criterion)+'</div><div class="small muted" style="margin-top:8px">Plano: '+esc(c.tasks.length?c.tasks.join(', '):'sem cobertura')+'</div><div class="small muted">Verify: '+esc(c.verifySummary||c.verifyHow||'sem evidência explícita')+'</div></div>');
548
+ const checkpoints=(ctx.checkpoints.parsed||[]).map((c)=>'<div class="item"><div class="head"><strong>'+esc(c.id)+'</strong>'+badge(c.status)+'</div><div class="small muted">Tipo: '+esc(c.type)+' · Fase: '+esc(c.phase||'—')+' · Escopo: '+esc(c.scope||'—')+'</div><div class="small" style="margin-top:8px">'+esc(c.notes||'—')+'</div></div>');
549
+ const agents=((ctx.runtime.parsed.agents&&ctx.runtime.parsed.agents.length)?ctx.runtime.parsed.agents:(ctx.blueprint&&ctx.blueprint.agents)||[]).map((a)=>'<div class="item"><div class="head"><strong>'+esc(a.id||a.name||'agent')+'</strong>'+badge(a.status||a.model_hint||'planned')+'</div><div class="small muted">'+esc(a.role||a.persona||'—')+'</div><div class="small">Tarefas: '+esc((a.tasks||[]).join(', ')||a.scope||'—')+'</div></div>');
550
+ const comments=(ctx.review.comments||[]).map((c)=>'<div class="item"><div class="small muted">'+esc(c.target)+' · '+esc(c.type)+' · '+esc(c.status)+' · '+esc(c.author)+'</div><div style="margin-top:6px">'+esc(c.text)+'</div>'+(c.status!=='resolved'?'<div class="actions"><button class="secondary" onclick="resolveComment(\\''+esc(c.id)+'\\')">Resolver</button></div>':'')+'</div>');
551
+ const sessions=(ctx.sessions.items||[]).map((s)=>'<div class="item"><div class="head"><div><strong>'+esc(s.id)+' · '+esc(s.name)+'</strong><div class="small muted">Criada: '+esc(s.createdAt)+' · Última atividade: '+esc(s.lastActivity)+'</div></div>'+badge(s.status)+'</div><div class="small">'+esc(s.summary||'—')+'</div><div class="small muted" style="margin-top:8px">'+esc(s.path||'—')+'</div><div class="actions"><button class="secondary" onclick="openSession(\\''+esc(s.path)+'\\')">Abrir sessão</button></div></div>');
552
+ const repo=Object.entries(ctx.repositoryContext||{}).map(([k,v])=>'<div class="item"><strong>'+esc(k.toUpperCase())+'</strong><div class="small" style="margin-top:8px">'+esc(v.summary||'Sem resumo disponível.')+'</div><div class="small muted" style="margin-top:8px">'+esc(v.path||'—')+'</div></div>');
553
+ const contextSelected=((ctx.context&&ctx.context.pack&&ctx.context.pack.selected_artifacts)||[]).map((artifact)=>'<div class="item"><div class="head"><strong>'+esc(artifact.alias)+'</strong>'+badge(artifact.exists?(artifact.using_fallback?'fallback':'selected'):'missing',artifact.exists?(artifact.using_fallback?'fallback':'selected'):'missing')+'</div><div class="small">'+esc(artifact.summary||'—')+'</div><div class="small muted" style="margin-top:8px">'+esc(artifact.path||'—')+'</div></div>');
554
+ const contextGaps=((ctx.context&&ctx.context.pack&&ctx.context.pack.gaps)||[]).map((gap)=>'<div class="entry small">['+esc(gap.severity)+'] '+esc(gap.alias)+': '+esc(gap.reason)+'</div>');
555
+ const contextConflicts=((ctx.context&&ctx.context.pack&&ctx.context.pack.conflicts)||[]).map((conflict)=>'<div class="entry small">'+esc(conflict.alias)+': '+esc(conflict.reason)+'</div>');
556
+ const semanticsWarnings=((ctx.context&&ctx.context.semantics&&ctx.context.semantics.audit&&ctx.context.semantics.audit.warnings)||[]).map((warning)=>'<div class="entry small">'+esc(warning)+'</div>');
557
+ const blockers=(ctx.readiness.blockers||[]).map((x)=>'<div class="entry small">'+esc(x)+'</div>'); const warnings=(ctx.readiness.warnings||[]).concat((ctx.diagnostics.enterpriseWarnings||[])).slice(0,10).map((x)=>'<div class="entry small">'+esc(x)+'</div>'); const evidence=(ctx.runtime.parsed.evidence||[]).map((x)=>'<div class="entry small">'+esc(x)+'</div>'); const blockages=(ctx.runtime.parsed.blockages||[]).map((x)=>'<div class="entry small">'+esc(x)+'</div>'); const history=((ctx.sessions.current&&ctx.sessions.current.history)||[]).map((x)=>'<div class="entry small">'+esc(x.date)+' · '+esc(x.event)+'</div>');
558
+ const enterpriseGates=((ctx.enterprise&&ctx.enterprise.pendingGates&&ctx.enterprise.pendingGates.pending)||[]).map((gate)=>'<div class="entry small">'+esc(gate.gate_id)+' · '+esc(gate.scope)+' · '+esc(gate.work_item_id||'run')+'</div>');
559
+ app.innerHTML='<div class="stats"><div class="metric"><div class="label">Saúde lógica</div><div class="value">'+badge(ctx.healthStatus)+'</div></div><div class="metric"><div class="label">Go / No-Go</div><div class="value">'+badge(ctx.readiness.decision,ctx.readiness.decision)+'</div></div><div class="metric"><div class="label">Review</div><div class="value">'+badge(ctx.planReviewStatus)+'</div></div><div class="metric"><div class="label">Checkpoints</div><div class="value">'+badge(ctx.readiness.checkpointPending?'pending_approval':'clear',ctx.readiness.checkpointPending?'pendente':'ok')+'</div></div><div class="metric"><div class="label">Runtime</div><div class="value">'+badge(ctx.runtime.parsed.status||ctx.state.parsed.runtimeStatus||'pending')+'</div></div></div>'
560
+ +'<div class="tabs">'+['decision','plan','execution','evidence','sessions','context','repository'].map((t)=>'<button class="tab'+(tab===t?' active':'')+'" onclick="setTab(\\''+t+'\\')">'+(t==='repository'?'repository context':t)+'</button>').join('')+'</div>'
561
+ +'<div class="view'+(tab==='decision'?' active':'')+'"><div class="layout"><div class="stack"><div class="panel"><div class="head"><div><h2 style="margin:0">Decision Control</h2><div class="muted">A pergunta principal: podemos executar agora?</div></div></div><div class="'+(ctx.readiness.go?'panel go':'panel nogo')+'" style="padding:18px"><div class="label">Decisão operacional</div><div style="font-size:38px;font-weight:900;margin-top:8px">'+(ctx.readiness.go?'GO':'NO-GO')+'</div><div class="small muted" style="margin-top:8px">'+esc(ctx.nextStep.reason||'—')+'</div><div class="actions">'+badge(ctx.planReviewStatus,'review:'+ctx.planReviewStatus)+badge(ctx.readiness.confidenceBand,'confiança:'+ctx.readiness.confidenceBand)+(ctx.readiness.checkpointPending?badge('pending_approval','checkpoint pendente'):'')+'</div></div></div><div class="panel"><div class="head"><div><h2 style="margin:0">Decision Rail</h2><div class="muted">Spec → Plan → Review → Execute → Verify → Lessons.</div></div></div><div class="rail">'+flow.join('')+'</div></div><div class="panel"><div class="head"><div><h2 style="margin:0">Readiness Map</h2><div class="muted">Bloqueios e sinais ativos antes do execute.</div></div></div><div class="grid2"><div><h3>Bloqueios</h3>'+list(blockers,'Sem bloqueios formais para executar.')+'</div><div><h3>Warnings</h3>'+list(warnings,'Sem warnings relevantes.')+'</div></div></div><div class="panel"><div class="head"><div><h2 style="margin:0">Review e aprovação</h2><div class="muted">Persistida em STATE.md, PLAN-REVIEW.md e comentários.</div></div></div><div class="grid2"><div><div class="actions"><button class="primary" onclick="changeReview(\\'approved\\')">Aprovar</button><button class="warnbtn" onclick="changeReview(\\'needs_revision\\')">Pedir revisão</button><button class="secondary" onclick="changeReview(\\'in_review\\')">Marcar em revisão</button><button class="danger" onclick="changeReview(\\'rejected\\')">Rejeitar</button></div><div class="form"><input id="comment-target" placeholder="target ex.: wave:1, T2, checkpoint:CP-01"/><select id="comment-type"><option value="note">note</option><option value="risk">risk</option><option value="question">question</option><option value="approval">approval</option></select><textarea id="comment-text" rows="6" placeholder="Comentário de revisão"></textarea><button class="primary" onclick="addComment()">Adicionar comentário</button></div></div><div><h3>Comentários</h3>'+list(comments,'Nenhum comentário de revisão.')+'</div></div></div></div><div class="stack"><div class="panel"><div class="head"><div><h2 style="margin:0">Mapa de artefatos</h2><div class="muted">Fonte de verdade visual do ciclo atual.</div></div></div><div class="grid3">'+graph.join('')+'</div></div><div class="panel"><div class="head"><div><h2 style="margin:0">Calibração do plano</h2><div class="muted">Confiança prevista versus resultado real.</div></div>'+badge(ctx.calibration.status)+'</div><div class="small">'+esc(ctx.calibration.summary)+'</div></div></div></div></div>'
562
+ +'<div class="view'+(tab==='plan'?' active':'')+'"><div class="layout"><div class="stack"><div class="panel"><div class="head"><div><h2 style="margin:0">Trilha do plano</h2><div class="muted">Ondas, dependências e vínculos com aceite e decisões.</div></div>'+badge(ctx.planReviewStatus)+'</div>'+list(waves,'PLAN.md ausente ou sem tarefas estruturadas.')+'</div><div class="panel"><div class="head"><div><h2 style="margin:0">Matriz de cobertura</h2><div class="muted">SPEC → PLAN → VERIFY em um único quadro.</div></div></div><div class="grid2">'+coverage.join('')+'</div></div></div><div class="stack"><div class="panel"><div class="head"><div><h2 style="margin:0">Autoavaliação do plano</h2><div class="muted">Melhor plano atual e faixa de confiança.</div></div></div><div class="grid3"><div class="item"><strong>Melhor plano atual</strong><div class="small muted" style="margin-top:8px">'+esc((ctx.plan.selfEvaluation&&ctx.plan.selfEvaluation.bestPlan)||'—')+'</div></div><div class="item"><strong>Confiança</strong><div class="small muted" style="margin-top:8px">'+esc(ctx.readiness.confidence!=null?ctx.readiness.confidence+'%':'—')+'</div></div><div class="item"><strong>Faixa</strong><div class="small muted" style="margin-top:8px">'+esc(ctx.readiness.confidenceBand)+'</div></div></div></div><div class="panel"><div class="head"><div><h2 style="margin:0">Lacunas da SPEC</h2><div class="muted">Critérios sem cobertura explícita no plano.</div></div></div>'+list((ctx.spec.uncoveredCriteria||[]).map((c)=>'<div class="entry small">'+esc(c.id)+' · '+esc(c.criterion)+'</div>'),'Sem lacunas detectadas.')+'</div></div></div></div>'
563
+ +'<div class="view'+(tab==='execution'?' active':'')+'"><div class="layout"><div class="stack"><div class="panel"><div class="head"><div><h2 style="margin:0">Runtime operacional</h2><div class="muted">Estado tático da execução.</div></div>'+badge(ctx.runtime.parsed.status||'pending')+'</div><div class="grid3"><div class="item"><strong>Onda atual</strong><div class="small muted" style="margin-top:8px">'+esc(ctx.runtime.parsed.currentWave||'—')+'</div></div><div class="item"><strong>Tarefas ativas</strong><div class="small muted" style="margin-top:8px">'+esc((ctx.runtime.parsed.activeTasks||[]).join(', ')||'—')+'</div></div><div class="item"><strong>Próxima ação</strong><div class="small muted" style="margin-top:8px">'+esc(ctx.runtime.parsed.nextAction||'—')+'</div></div><div class="item"><strong>Motivo</strong><div class="small muted" style="margin-top:8px">'+esc(ctx.runtime.parsed.nextReason||'—')+'</div></div><div class="item"><strong>Modo runtime</strong><div class="small muted" style="margin-top:8px">'+esc((ctx.enterprise&&ctx.enterprise.runtimeMode&&ctx.enterprise.runtimeMode.runtime_mode)||'—')+'</div></div><div class="item"><strong>Fallback</strong><div class="small muted" style="margin-top:8px">'+esc((ctx.enterprise&&ctx.enterprise.fallbackMode)||'—')+'</div></div></div></div><div class="panel"><div class="head"><div><h2 style="margin:0">Checkpoints</h2><div class="muted">Gates humanos formais.</div></div></div>'+list(checkpoints,'CHECKPOINTS.md ausente ou sem gates formais.')+'</div><div class="panel"><div class="head"><div><h2 style="margin:0">Gates pendentes</h2><div class="muted">Fila operacional persistida por run/work item.</div></div></div>'+list(enterpriseGates,'Sem gates pendentes no runtime.')+'</div><div class="panel"><div class="head"><div><h2 style="margin:0">Agentes</h2><div class="muted">Blueprint e runtime multiagente.</div></div></div>'+list(agents,'Sem blueprint de agentes ou runtime multiagente ativo.')+'</div></div><div class="stack"><div class="panel"><div class="head"><div><h2 style="margin:0">Evidências</h2><div class="muted">Artefatos e sinais da execução atual.</div></div></div>'+list(evidence,'Sem evidência operacional registrada.')+'</div><div class="panel"><div class="head"><div><h2 style="margin:0">Enterprise verify</h2><div class="muted">Manifest, risco residual, governança e promoção.</div></div></div><div class="grid3">'+kvItem('Checks',(ctx.enterprise&&ctx.enterprise.verificationSummary&&ctx.enterprise.verificationSummary.total)||'—')+kvItem('Fail',(ctx.enterprise&&ctx.enterprise.verificationSummary&&ctx.enterprise.verificationSummary.fail)||0)+kvItem('Coverage',(ctx.enterprise&&ctx.enterprise.evidenceCoverage&&String(ctx.enterprise.evidenceCoverage.coverage_percent)+'%')||'—')+kvItem('Residual risks',(ctx.enterprise&&ctx.enterprise.residualRiskSummary&&ctx.enterprise.residualRiskSummary.total)||0)+kvItem('High/Critical',(ctx.enterprise&&ctx.enterprise.residualRiskSummary&&ctx.enterprise.residualRiskSummary.highOrCritical)||0)+kvItem('Policy decisions',(ctx.enterprise&&ctx.enterprise.policyDecisionSummary&&ctx.enterprise.policyDecisionSummary.total)||0)+kvItem('Policy coverage',(ctx.enterprise&&ctx.enterprise.policyCoverage&&String(ctx.enterprise.policyCoverage.coveragePercent)+'%')||'—')+kvItem('Quota retries',(ctx.enterprise&&ctx.enterprise.quotaSummary&&ctx.enterprise.quotaSummary.consumed&&String(ctx.enterprise.quotaSummary.consumed.retries)+'/'+((ctx.enterprise.quotaSummary.limits&&ctx.enterprise.quotaSummary.limits.maxRetriesPerRun)!=null?ctx.enterprise.quotaSummary.limits.maxRetriesPerRun:'∞'))||'—')+kvItem('Audit critical',(ctx.enterprise&&ctx.enterprise.auditSummary&&ctx.enterprise.auditSummary.critical)||0)+kvItem('Promotion',(ctx.enterprise&&ctx.enterprise.promotionSummary&&ctx.enterprise.promotionSummary.status)||'—')+kvItem('Promotion readiness',(ctx.enterprise&&ctx.enterprise.promotionReadiness&&ctx.enterprise.promotionReadiness.status)||'—')+kvItem('Recovery',(ctx.enterprise&&ctx.enterprise.recoveryState&&ctx.enterprise.recoveryState.status)||'—')+kvItem('Providers',((ctx.enterprise&&ctx.enterprise.providerCatalog&&ctx.enterprise.providerCatalog.summary&&((ctx.enterprise.providerCatalog.summary.pluginsCount!=null?ctx.enterprise.providerCatalog.summary.pluginsCount:ctx.enterprise.providerCatalog.summary.total_plugins)!=null?(ctx.enterprise.providerCatalog.summary.pluginsCount!=null?ctx.enterprise.providerCatalog.summary.pluginsCount:ctx.enterprise.providerCatalog.summary.total_plugins):Array.isArray(ctx.enterprise.providerCatalog.summary.plugins)?ctx.enterprise.providerCatalog.summary.plugins.length:0)))||0)+'</div></div><div class="panel"><div class="head"><div><h2 style="margin:0">Bloqueios</h2><div class="muted">O que impede avanço agora.</div></div></div>'+list(blockages,'Sem bloqueios explícitos.')+'</div><div class="panel"><div class="head"><div><h2 style="margin:0">Runtime bruto</h2><div class="muted">Leitura direta do artefato operacional.</div></div></div><div class="raw">'+esc(ctx.runtime.summary||'EXECUTION-RUNTIME.md ausente.')+'</div></div></div></div></div>'
564
+ +'<div class="view'+(tab==='evidence'?' active':'')+'"><div class="layout"><div class="stack"><div class="panel"><div class="head"><div><h2 style="margin:0">Verify</h2><div class="muted">Evidência final e validação.</div></div>'+badge(ctx.calibration.status)+'</div><div class="raw">'+esc(ctx.verify.summary||'VERIFY.md ausente.')+'</div></div><div class="panel"><div class="head"><div><h2 style="margin:0">Critérios no verify</h2><div class="muted">Evidências detectadas por critério A*.</div></div></div><div class="grid2">'+coverage.join('')+'</div></div></div><div class="stack"><div class="panel"><div class="head"><div><h2 style="margin:0">Investigações</h2><div class="muted">Base de evidência antes do plano.</div></div></div><div class="raw">'+esc(ctx.support.investigationsSummary||'INVESTIGATIONS.md ausente.')+'</div></div><div class="panel"><div class="head"><div><h2 style="margin:0">Capabilities</h2><div class="muted">Recursos nativos do projeto.</div></div></div><div class="raw">'+esc(ctx.support.capabilitiesSummary||'CAPABILITIES.md ausente.')+'</div></div></div></div></div>'
565
+ +'<div class="view'+(tab==='sessions'?' active':'')+'"><div class="layout"><div class="stack"><div class="panel"><div class="head"><div><h2 style="margin:0">Sessão ativa</h2><div class="muted">Contexto atual resolvido pelo STATE global.</div></div></div><div class="grid2"><div class="item"><strong>ID</strong><div class="small muted" style="margin-top:8px">'+esc((ctx.sessions.current&&ctx.sessions.current.id)||'—')+'</div></div><div class="item"><strong>Nome</strong><div class="small muted" style="margin-top:8px">'+esc((ctx.sessions.current&&ctx.sessions.current.name)||ctx.activeSession||'—')+'</div></div><div class="item"><strong>Status</strong><div class="small muted" style="margin-top:8px">'+esc((ctx.sessions.current&&ctx.sessions.current.status)||'—')+'</div></div><div class="item"><strong>Última atividade</strong><div class="small muted" style="margin-top:8px">'+esc((ctx.sessions.current&&ctx.sessions.current.lastActivity)||'—')+'</div></div></div><div class="item" style="margin-top:14px"><strong>Resumo</strong><div class="small muted" style="margin-top:8px">'+esc((ctx.sessions.current&&ctx.sessions.current.summary)||'Sem SESSION.md ativo ou modo legado.')+'</div><div class="small muted" style="margin-top:8px">'+esc(ctx.sessions.currentPath||'—')+'</div></div><div class="item" style="margin-top:14px"><strong>Tags</strong><div class="small" style="margin-top:8px">'+((ctx.sessions.current&&ctx.sessions.current.tags)||[]).map((x)=>'<span class="chip">'+esc(x)+'</span>').join('')+'</div></div><h3>Histórico</h3>'+list(history,'Sem histórico de sessão disponível.')+'</div></div><div class="stack"><div class="panel"><div class="head"><div><h2 style="margin:0">Lista de sessões</h2><div class="muted">Índice real lido de .oxe/SESSIONS.md.</div></div></div>'+list(sessions,'SESSIONS.md ausente ou sem sessões registradas.')+'</div><div class="panel"><div class="head"><div><h2 style="margin:0">Índice bruto</h2><div class="muted">Leitura direta do artefato global.</div></div></div><div class="raw">'+esc(ctx.sessions.raw||'SESSIONS.md ausente.')+'</div></div></div></div></div>'
566
+ +'<div class="view'+(tab==='context'?' active':'')+'"><div class="layout"><div class="stack"><div class="panel"><div class="head"><div><h2 style="margin:0">Context Pack</h2><div class="muted">Seleção determinística de artefatos para este estado do OXE.</div></div>'+badge((ctx.context&&ctx.context.quality&&ctx.context.quality.primaryStatus)||((ctx.context&&ctx.context.pack&&ctx.context.pack.context_quality&&ctx.context.pack.context_quality.status)||'pending'))+'</div><div class="grid3"><div class="item"><strong>Workflow primário</strong><div class="small muted" style="margin-top:8px">'+esc((ctx.context&&ctx.context.quality&&ctx.context.quality.primaryWorkflow)||'dashboard')+'</div></div><div class="item"><strong>Score</strong><div class="small muted" style="margin-top:8px">'+esc((ctx.context&&ctx.context.quality&&ctx.context.quality.primaryScore)!=null?String(ctx.context.quality.primaryScore):'—')+'</div></div><div class="item"><strong>Freshness</strong><div class="small muted" style="margin-top:8px">'+esc((ctx.context&&ctx.context.pack&&ctx.context.pack.freshness&&ctx.context.pack.freshness.reason)||'—')+'</div></div></div><div class="small muted" style="margin-top:12px">Pack: '+esc((ctx.context&&ctx.context.pack&&ctx.context.pack.path)||'—')+' · semantics hash: '+esc((ctx.context&&ctx.context.pack&&ctx.context.pack.semantics_hash)||'—')+'</div></div><div class="panel"><div class="head"><div><h2 style="margin:0">Artefatos selecionados</h2><div class="muted">Contexto efetivamente priorizado pelo pack.</div></div></div><div class="grid2">'+contextSelected.join('')+'</div></div></div><div class="stack"><div class="panel"><div class="head"><div><h2 style="margin:0">Gaps e conflitos</h2><div class="muted">Lacunas e divergências entre raiz e sessão.</div></div></div><h3>Gaps</h3>'+list(contextGaps,'Sem gaps no pack atual.')+'<h3>Conflitos</h3>'+list(contextConflicts,'Sem conflitos detectados.')+'</div><div class="panel"><div class="head"><div><h2 style="margin:0">Summaries ativos</h2><div class="muted">Referências persistidas para compressão de contexto.</div></div></div><div class="grid2">'+kvItem('Project summary',(ctx.context&&ctx.context.summaries&&ctx.context.summaries.project)||'—')+kvItem('Session summary',(ctx.context&&ctx.context.summaries&&ctx.context.summaries.session)||'—')+kvItem('Phase summary',(ctx.context&&ctx.context.summaries&&ctx.context.summaries.phase)||'—')+'</div></div><div class="panel"><div class="head"><div><h2 style="margin:0">Semântica multi-runtime</h2><div class="muted">Drift auditável entre workflow, wrapper e prompt renderizado.</div></div>'+badge(ctx.context&&ctx.context.semantics&&ctx.context.semantics.ok?'healthy':'warning',ctx.context&&ctx.context.semantics&&ctx.context.semantics.ok?'ok':'drift')+'</div><div class="small muted">Manifest: '+esc((ctx.context&&ctx.context.semantics&&ctx.context.semantics.manifestPath)||'—')+' · mismatch count: '+esc((ctx.context&&ctx.context.semantics&&ctx.context.semantics.audit&&ctx.context.semantics.audit.mismatchCount)||0)+'</div>'+list(semanticsWarnings,'Sem warnings semânticos ativos.')+'</div></div></div></div>'
567
+ +'<div class="view'+(tab==='repository'?' active':'')+'"><div class="panel"><div class="head"><div><h2 style="margin:0">Repository Context</h2><div class="muted">Contexto de repositório como suporte de decisão.</div></div></div><div class="grid3">'+repo.join('')+'</div></div></div>'; enhanceExecutionView();}
568
+ function executionViewElement(){return Array.from(app.querySelectorAll('.view')).find((view)=>view.textContent.includes('Runtime operacional'));}
569
+ function panel(title,body){return '<div class="panel"><div class="head"><div><h2 style="margin:0">'+esc(title)+'</h2></div></div>'+body+'</div>';}
570
+ function kvItem(label,value){return '<div class="item"><strong>'+esc(label)+'</strong><div class="small muted" style="margin-top:8px">'+esc(value)+'</div></div>';}
571
+ function actionButton(label,action,klass){return '<button class="'+klass+'" '+(runtimeDisabled()?'disabled':'')+' onclick="runtimeAction(\\''+action+'\\')">'+label+'</button>';}
572
+ function enhanceExecutionView(){
573
+ const view=executionViewElement();
574
+ if(!view||!ctx)return;
575
+ const stacks=view.querySelectorAll('.stack');
576
+ if(stacks.length<2)return;
577
+ const activeRun=ctx.activeRun||{};
578
+ const graph=ctx.operationalGraph||{nodes:[],edges:[]};
579
+ const trace=((ctx.tracing&&ctx.tracing.events)||[]).slice(-8).reverse().map((event)=>'<div class="entry"><div class="head"><strong>'+esc(event.type)+'</strong>'+badge(event.timestamp?event.timestamp.slice(11,19):'—',event.timestamp?event.timestamp.slice(11,19):'—')+'</div><div class="small muted">run='+esc(event.run_id||'—')+' · wave='+esc(event.wave_id||'—')+' · task='+esc(event.task_id||'—')+'</div><div class="small" style="margin-top:8px">'+esc(JSON.stringify(event.payload||{}))+'</div></div>').join('')||'<div class="entry small">Sem eventos registrados.</div>';
580
+ const nodes=(graph.nodes||[]).map((node)=>'<div class="item"><div class="head"><strong>'+esc(node.label||node.id)+'</strong>'+badge(node.status||'pending')+'</div><div class="small muted">'+esc(node.kind||'node')+'</div><div class="small" style="margin-top:8px">'+esc(node.detail||'—')+'</div></div>').join('')||'<div class="entry small">Sem nós operacionais.</div>';
581
+ const edges=(graph.edges||[]).map((edge)=>'<div class="entry"><div class="small"><strong>'+esc(edge.from)+'</strong> → <strong>'+esc(edge.to)+'</strong></div><div class="small muted" style="margin-top:6px">'+esc(edge.type||'link')+' · '+esc(edge.status||'—')+'</div><div class="small" style="margin-top:6px">'+esc(edge.reason||edge.label||'—')+'</div></div>').join('')||'<div class="entry small">Sem handoffs ou dependências registradas.</div>';
582
+ const memory=Object.entries(ctx.memoryLayers||{}).filter(([key])=>key!=='readOrder').map(([key,val])=>kvItem(key,Array.isArray(val.source)?val.source.join(' | '):val.source||'—')).join('')||'<div class="entry small">Sem contrato de memória disponível.</div>';
583
+ const enterprise=ctx.enterprise||{};
584
+ const gateQueue=enterprise.gateQueue||{pending:[],stalePending:[],resolvedRecent:[],gateSlaHours:24};
585
+ const pendingGates=(gateQueue.pending||[]).map((gate)=>'<div class="entry"><div class="head"><strong>'+esc(gate.gate_id)+'</strong>'+badge(gate.status||'pending')+'</div><div class="small muted">scope='+esc(gate.scope||'—')+' · task='+esc(gate.work_item_id||'—')+' · actor='+(gate.actor?esc(gate.actor):'—')+'</div><div class="small" style="margin-top:8px">'+esc((gate.context&&gate.context.description)||gate.action||'Sem descrição')+'</div><div class="actions" style="margin-top:12px"><button class="primary" '+(runtimeDisabled()?'disabled':'')+' onclick="runtimeGateResolve(\\''+esc(gate.gate_id)+'\\',\\'approve\\')">Approve</button><button class="warnbtn" '+(runtimeDisabled()?'disabled':'')+' onclick="runtimeGateResolve(\\''+esc(gate.gate_id)+'\\',\\'waive\\')">Waive</button><button class="danger" '+(runtimeDisabled()?'disabled':'')+' onclick="runtimeGateResolve(\\''+esc(gate.gate_id)+'\\',\\'reject\\')">Reject</button></div></div>').join('')||'<div class="entry small">Sem gates pendentes.</div>';
586
+ const staleGates=(gateQueue.stalePending||[]).map((gate)=>'<div class="entry"><div class="head"><strong>'+esc(gate.gate_id)+'</strong>'+badge('stale','warning')+'</div><div class="small muted">requested_at='+esc(gate.requested_at||'—')+' · scope='+esc(gate.scope||'—')+'</div></div>').join('')||'<div class="entry small">Sem gates stale.</div>';
587
+ const recentResolved=(gateQueue.resolvedRecent||[]).map((gate)=>'<div class="entry"><div class="head"><strong>'+esc(gate.gate_id)+'</strong>'+badge(gate.decision||'resolved','ok')+'</div><div class="small muted">actor='+esc(gate.actor||'—')+' · reason='+esc(gate.reason||'—')+'</div></div>').join('')||'<div class="entry small">Sem resoluções recentes.</div>';
588
+ const gatePanel=panel('Runtime gates','<div class="grid3">'+kvItem('Pending',String((gateQueue.pending||[]).length))+kvItem('Stale',String(gateQueue.staleCount||0))+kvItem('SLA (h)',String(gateQueue.gateSlaHours||24))+'</div><h3>Pendentes</h3>'+pendingGates+'<h3>Stale</h3>'+staleGates+'<h3>Resolvidos nas últimas 24h</h3>'+recentResolved);
589
+ const multiAgent=enterprise.multiAgent||null;
590
+ const multiAgentPanel=multiAgent&&multiAgent.enabled?panel('Multi-agent','<div class="grid3">'+kvItem('Mode',multiAgent.mode||'—')+kvItem('Isolation',multiAgent.workspaceIsolationEnforced?'isolated':'shared')+kvItem('Agents',String((multiAgent.agents||[]).length))+'</div><h3>Ownership</h3>'+((multiAgent.ownership||[]).map((item)=>'<div class="entry"><div class="head"><strong>'+esc(item.work_item_id||'—')+'</strong>'+badge(item.owner_agent_id||'unassigned')+'</div></div>').join('')||'<div class="entry small">Sem ownership ativo.</div>')+'<h3>Handoffs</h3>'+((multiAgent.handoffs||[]).map((handoff)=>'<div class="entry"><div class="small"><strong>'+esc(handoff.from_agent_id||'—')+'</strong> → <strong>'+esc(handoff.to_agent_id||'—')+'</strong></div><div class="small muted" style="margin-top:6px">'+esc(handoff.work_item_id||'—')+'</div></div>').join('')||'<div class="entry small">Sem handoffs registrados.</div>')):'';
591
+ const recovery=enterprise.recoveryState||null;
592
+ const recoveryPanel=recovery?panel('Recovery','<div class="grid3">'+kvItem('Status',recovery.status||'—')+kvItem('Last recovery',recovery.lastRecoveredAt||'—')+kvItem('Issues',String((recovery.issues||[]).length))+'</div><h3>Issues</h3>'+((recovery.issues||[]).map((issue)=>'<div class="entry"><div class="small"><strong>'+esc(issue.code||'issue')+'</strong></div><div class="small muted" style="margin-top:6px">'+esc(issue.message||issue.reason||'—')+'</div></div>').join('')||'<div class="entry small">Sem inconsistências abertas.</div>')):'';
593
+ const promotion=enterprise.promotionReadiness||null;
594
+ const promotionPanel=promotion?panel('Promotion readiness','<div class="grid3">'+kvItem('Status',promotion.status||'—')+kvItem('Coverage',String(promotion.coveragePercent==null?'—':promotion.coveragePercent+'%'))+kvItem('Policy',String(promotion.policyCoveragePercent==null?'—':promotion.policyCoveragePercent+'%'))+'</div><h3>Blockers</h3>'+((promotion.reasons||promotion.blockers||[]).map((reason)=>'<div class="entry small">'+esc(reason)+'</div>').join('')||'<div class="entry small">Sem blockers ativos.</div>')):'';
595
+ const azure=ctx.azure||null;
596
+ const azureInventory=azure&&azure.inventorySummary?azure.inventorySummary:{total:0,servicebus:0,eventgrid:0,sql:0,other:0};
597
+ const azurePanel=azure?panel('Azure context operacional','<div class="grid3">'+kvItem('Login',azure.authStatus&&azure.authStatus.login_active?'ativo':'ausente')+kvItem('Subscription',azure.profile&&(azure.profile.subscription_name||azure.profile.subscription_id)||'—')+kvItem('Último sync',azure.inventorySyncedAt||'—')+kvItem('Service Bus',String(azureInventory.servicebus||0))+kvItem('Event Grid',String(azureInventory.eventgrid||0))+kvItem('Azure SQL',String(azureInventory.sql||0))+'</div><div class="small muted" style="margin-top:12px">Inventário: total '+esc(azureInventory.total||0)+' · pending operations: '+esc(azure.pendingOperations||0)+' · '+esc(azure.inventoryStale&&azure.inventoryStale.stale?'stale':'fresh')+'</div>'+(azure.lastOperation?'<div class="entry" style="margin-top:12px"><div class="head"><strong>Última operação</strong>'+badge(azure.lastOperation.phase||'pending')+'</div><div class="small">'+esc(azure.lastOperation.summary||azure.lastOperation.operation_id||'—')+'</div><div class="small muted" style="margin-top:8px">'+esc(azure.lastOperation.operation_id||'—')+'</div></div>':'')):'';
598
+ stacks[0].insertAdjacentHTML('afterbegin',panel('Run control','<div class="grid3">'+kvItem('Run ID',activeRun.run_id||'—')+kvItem('Status',activeRun.status||'pending')+kvItem('Cursor',(activeRun.cursor&&((activeRun.cursor.wave!=null?'wave '+activeRun.cursor.wave:'')+(activeRun.cursor.task?' · '+activeRun.cursor.task:'')+(activeRun.cursor.mode?' · '+activeRun.cursor.mode:'')))||'—')+'</div><div class="actions">'+actionButton('Start','start','primary')+actionButton('Pause','pause','warnbtn')+actionButton('Resume','resume','secondary')+actionButton('Replay','replay','danger')+'</div><div class="small muted" style="margin-top:12px">Transitions: '+esc((activeRun.metrics&&activeRun.metrics.transitions)||0)+' · pause_count: '+esc((activeRun.metrics&&activeRun.metrics.pause_count)||0)+' · replay_count: '+esc((activeRun.metrics&&activeRun.metrics.replay_count)||0)+'</div>'));
599
+ stacks[0].insertAdjacentHTML('beforeend',panel('Mapa operacional','<div class="grid3">'+nodes+'</div><h3>Handoffs e dependências</h3>'+edges)+(gatePanel||'')+(multiAgentPanel||'')+(azurePanel||''));
600
+ stacks[1].insertAdjacentHTML('afterbegin',panel('Trace operacional','<div class="small muted" style="margin-bottom:12px">Arquivo: '+esc((ctx.tracing&&ctx.tracing.path)||'—')+' · total: '+esc((ctx.tracing&&ctx.tracing.summary&&ctx.tracing.summary.total)||0)+' evento(s)</div>'+trace));
601
+ stacks[1].insertAdjacentHTML('beforeend',panel('Camadas de memória','<div class="small muted" style="margin-bottom:12px">'+esc(((ctx.memoryLayers&&ctx.memoryLayers.readOrder)||[]).join(' → ')||'—')+'</div><div class="grid2">'+memory+'</div>')+(recoveryPanel||'')+(promotionPanel||''));
602
+ }
603
+ function setTab(next){tab=next;render();}
604
+ async function openSession(path){session=path||null;await refresh();tab='sessions';render();}
605
+ async function changeReview(status){const note=prompt('Justificativa curta para o novo estado do plano:',status==='approved'?'Plano aprovado para execução.':'');if(note==null)return;await api('/api/review/status',{method:'POST',body:JSON.stringify({status,note,author:'user',activeSession:session})});await refresh();}
606
+ async function addComment(){const target=document.getElementById('comment-target').value||'plan';const type=document.getElementById('comment-type').value||'note';const text=document.getElementById('comment-text').value.trim();if(!text)return alert('Escreva um comentário.');await api('/api/review/comment',{method:'POST',body:JSON.stringify({target,type,text,author:'user',activeSession:session})});document.getElementById('comment-text').value='';await refresh();}
607
+ async function resolveComment(id){await api('/api/review/comment-status',{method:'POST',body:JSON.stringify({commentId:id,status:'resolved',activeSession:session})});await refresh();}
608
+ async function runtimeAction(action){if(runtimeDisabled())return;const reason=prompt('Motivo da transição de runtime:',action==='start'?'iniciar execução':'');if(reason==null)return;const wave=prompt('Onda atual (opcional):',ctx.activeRun&&ctx.activeRun.current_wave!=null?String(ctx.activeRun.current_wave):'');if(wave===null)return;const task=prompt('Tarefa atual (opcional):',ctx.activeRun&&ctx.activeRun.cursor&&ctx.activeRun.cursor.task?String(ctx.activeRun.cursor.task):'');if(task===null)return;await api('/api/runtime/action',{method:'POST',body:JSON.stringify({action,reason,activeSession:session,wave:wave?Number(wave):null,task:task||null})});await refresh();}
609
+ async function runtimeGateResolve(gateId,decision){if(runtimeDisabled())return;const needsReason=decision==='reject'||decision==='waive';const reason=needsReason?prompt('Justificativa obrigatória para '+decision+':',''):'';if(needsReason&&(!reason||!reason.trim()))return alert('Justificativa é obrigatória para '+decision+'.');await api('/api/runtime/gates/resolve',{method:'POST',body:JSON.stringify({gateId,decision,actor:'dashboard',reason:reason&&reason.trim()?reason.trim():undefined,activeSession:session})});await refresh();}
610
+ window.setTab=setTab;window.openSession=openSession;window.changeReview=changeReview;window.addComment=addComment;window.resolveComment=resolveComment;window.runtimeAction=runtimeAction;window.runtimeGateResolve=runtimeGateResolve;refresh().catch((err)=>{app.innerHTML='<div class="panel"><h2>Erro</h2><div class="muted">'+esc(err.message)+'</div></div>';});
611
+ </script></body></html>`;
612
+ }
613
+
614
+ function readJsonBody(req) {
615
+ return new Promise((resolve, reject) => {
616
+ let raw = '';
617
+ req.on('data', (chunk) => {
618
+ raw += chunk;
619
+ if (raw.length > 1024 * 1024) {
620
+ reject(new Error('Payload demasiado grande.'));
621
+ req.destroy();
622
+ }
623
+ });
624
+ req.on('end', () => {
625
+ if (!raw.trim()) return resolve({});
626
+ try {
627
+ resolve(JSON.parse(raw));
628
+ } catch (err) {
629
+ reject(new Error('JSON inválido.'));
630
+ }
631
+ });
632
+ req.on('error', reject);
633
+ });
634
+ }
635
+
636
+ function sendJson(res, status, body) {
637
+ const payload = JSON.stringify(body, null, 2);
638
+ res.writeHead(status, {
639
+ 'Content-Type': 'application/json; charset=utf-8',
640
+ 'Content-Length': Buffer.byteLength(payload),
641
+ 'Cache-Control': 'no-store',
642
+ });
643
+ res.end(payload);
644
+ }
645
+
646
+ function createDashboardServer(projectRoot, opts = {}) {
647
+ const root = path.resolve(projectRoot);
648
+ const server = http.createServer(async (req, res) => {
649
+ try {
650
+ const reqUrl = new URL(req.url || '/', 'http://127.0.0.1');
651
+ if (req.method === 'GET' && reqUrl.pathname === '/') {
652
+ const html = dashboardHtml();
653
+ res.writeHead(200, {
654
+ 'Content-Type': 'text/html; charset=utf-8',
655
+ 'Content-Length': Buffer.byteLength(html),
656
+ 'Cache-Control': 'no-store',
657
+ });
658
+ res.end(html);
659
+ return;
660
+ }
661
+
662
+ if (req.method === 'GET' && reqUrl.pathname === '/api/context') {
663
+ const activeSession = reqUrl.searchParams.get('session') || opts.activeSession || null;
664
+ sendJson(res, 200, { ...loadDashboardContext(root, { activeSession }), dashboard: { readOnly: Boolean(opts.readOnly) } });
665
+ return;
666
+ }
667
+
668
+ if (opts.readOnly && req.method === 'POST' && (reqUrl.pathname.startsWith('/api/review/') || reqUrl.pathname.startsWith('/api/runtime/'))) {
669
+ sendJson(res, 403, { error: 'Dashboard em modo read-only.' });
670
+ return;
671
+ }
672
+
673
+ if (req.method === 'POST' && reqUrl.pathname === '/api/review/status') {
674
+ const body = await readJsonBody(req);
675
+ const result = savePlanReviewStatus(root, body || {});
676
+ sendJson(res, 200, result);
677
+ return;
678
+ }
679
+
680
+ if (req.method === 'POST' && reqUrl.pathname === '/api/review/comment') {
681
+ const body = await readJsonBody(req);
682
+ const result = addPlanReviewComment(root, body || {});
683
+ sendJson(res, 200, result);
684
+ return;
685
+ }
686
+
687
+ if (req.method === 'POST' && reqUrl.pathname === '/api/review/comment-status') {
688
+ const body = await readJsonBody(req);
689
+ const result = updatePlanReviewCommentStatus(root, body || {});
690
+ if (!result) {
691
+ sendJson(res, 404, { error: 'Comentário não encontrado.' });
692
+ return;
693
+ }
694
+ const stateText = readTextIfExists(health.oxePaths(root).state) || '';
695
+ savePlanReviewStatus(root, {
696
+ activeSession: body.activeSession,
697
+ status: health.parsePlanReviewStatus(stateText) || 'in_review',
698
+ note: 'Estado de comentários de revisão atualizado',
699
+ author: body.author || 'dashboard',
700
+ });
701
+ sendJson(res, 200, result);
702
+ return;
703
+ }
704
+
705
+ if (req.method === 'POST' && reqUrl.pathname === '/api/runtime/action') {
706
+ const body = await readJsonBody(req);
707
+ const result = operational.applyRuntimeAction(root, body.activeSession || opts.activeSession || null, body || {});
708
+ sendJson(res, 200, result);
709
+ return;
710
+ }
711
+
712
+ if (req.method === 'POST' && reqUrl.pathname === '/api/runtime/gates/resolve') {
713
+ const body = await readJsonBody(req);
714
+ const result = await operational.resolveRuntimeGate(root, body.activeSession || opts.activeSession || null, body || {});
715
+ sendJson(res, 200, result);
716
+ return;
717
+ }
718
+
719
+ sendJson(res, 404, { error: 'Rota não encontrada.' });
720
+ } catch (err) {
721
+ sendJson(res, 500, { error: err && err.message ? err.message : 'Erro interno.' });
722
+ }
723
+ });
724
+ return server;
725
+ }
726
+
727
+ module.exports = {
728
+ loadDashboardContext,
729
+ savePlanReviewStatus,
730
+ addPlanReviewComment,
731
+ updatePlanReviewCommentStatus,
732
+ createDashboardServer,
733
+ parsePlan,
734
+ parseSpec,
735
+ parseVerify,
736
+ buildCoverageMatrix,
737
+ };