@zaip-ai/cli 1.0.7 → 1.3.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 (444) hide show
  1. package/README.md +6 -4
  2. package/dist/services/adapters.d.ts +1 -1
  3. package/dist/services/adapters.d.ts.map +1 -1
  4. package/dist/services/adapters.js +15 -5
  5. package/dist/services/adapters.js.map +1 -1
  6. package/dist/services/adapters.test.js +1 -1
  7. package/dist/services/agent-adapters.d.ts +9 -0
  8. package/dist/services/agent-adapters.d.ts.map +1 -1
  9. package/dist/services/agent-adapters.js +39 -4
  10. package/dist/services/agent-adapters.js.map +1 -1
  11. package/dist/services/agent-adapters.test.js +13 -1
  12. package/dist/services/agent-adapters.test.js.map +1 -1
  13. package/dist/services/codex-config-template.d.ts +2 -1
  14. package/dist/services/codex-config-template.d.ts.map +1 -1
  15. package/dist/services/codex-config-template.js +13 -2
  16. package/dist/services/codex-config-template.js.map +1 -1
  17. package/dist/services/codex-rules.d.ts +1 -1
  18. package/dist/services/codex-rules.d.ts.map +1 -1
  19. package/dist/services/codex-rules.js +31 -7
  20. package/dist/services/codex-rules.js.map +1 -1
  21. package/dist/services/codex-subagent-hook-template.d.ts +1 -1
  22. package/dist/services/codex-subagent-hook-template.d.ts.map +1 -1
  23. package/dist/services/codex-subagent-hook-template.js +4 -1
  24. package/dist/services/codex-subagent-hook-template.js.map +1 -1
  25. package/dist/services/doctor.d.ts.map +1 -1
  26. package/dist/services/doctor.js +3 -1
  27. package/dist/services/doctor.js.map +1 -1
  28. package/dist/services/global-codex-config.d.ts +6 -3
  29. package/dist/services/global-codex-config.d.ts.map +1 -1
  30. package/dist/services/global-codex-config.js +82 -13
  31. package/dist/services/global-codex-config.js.map +1 -1
  32. package/dist/services/global-codex-config.test.js +57 -10
  33. package/dist/services/global-codex-config.test.js.map +1 -1
  34. package/dist/services/install-agents-template.d.ts.map +1 -1
  35. package/dist/services/install-agents-template.js +15 -2
  36. package/dist/services/install-agents-template.js.map +1 -1
  37. package/dist/services/logger.js +1 -1
  38. package/dist/services/logger.js.map +1 -1
  39. package/dist/services/logger.test.js +3 -3
  40. package/dist/services/logger.test.js.map +1 -1
  41. package/dist/services/runtime-template.test.js +21 -5
  42. package/dist/services/runtime-template.test.js.map +1 -1
  43. package/dist/services/template-manifest.d.ts.map +1 -1
  44. package/dist/services/template-manifest.js +7 -0
  45. package/dist/services/template-manifest.js.map +1 -1
  46. package/package.json +1 -1
  47. package/templates/.agents/architecture/software-architecture.md +131 -0
  48. package/templates/.agents/branding/brandbook.docx +0 -0
  49. package/templates/.agents/branding/brandbook.md +60 -0
  50. package/templates/.agents/config/agents/catalog.yaml +310 -10
  51. package/templates/.agents/config/clients/codex/agents/zaip-agent-brand-strategist.toml +30 -0
  52. package/templates/.agents/config/clients/codex/agents/zaip-agent-designer.toml +5 -5
  53. package/templates/.agents/config/clients/codex/agents/zaip-agent-finalizer.toml +2 -2
  54. package/templates/.agents/config/clients/codex/agents/zaip-agent-general-operations.toml +30 -0
  55. package/templates/.agents/config/clients/codex/agents/zaip-agent-governance-compliance.toml +30 -0
  56. package/templates/.agents/config/clients/codex/agents/zaip-agent-growth-strategist.toml +30 -0
  57. package/templates/.agents/config/clients/codex/agents/zaip-agent-marketing-analyst.toml +8 -8
  58. package/templates/.agents/config/clients/codex/agents/zaip-agent-orchestrator.toml +5 -3
  59. package/templates/.agents/config/clients/codex/agents/zaip-agent-sales-specialist.toml +30 -0
  60. package/templates/.agents/config/project.yaml +1 -1
  61. package/templates/.agents/dashboard/.tmp-run-list.json +254 -0
  62. package/templates/.agents/dashboard/.zaip-managed.json +775 -163
  63. package/templates/.agents/dashboard/DATA-DICTIONARY.md +2227 -0
  64. package/templates/.agents/dashboard/README.md +48 -97
  65. package/templates/.agents/dashboard/apps/frontend/dist/assets/CostCalculationGuidePage-DxR_pgSV.js +1 -0
  66. package/templates/.agents/dashboard/apps/frontend/dist/assets/DashboardHelpDialog-4jZLTWE_.js +2156 -0
  67. package/templates/.agents/dashboard/apps/frontend/dist/assets/PricingSettingsDialog-CKcsqb-r.js +1 -0
  68. package/templates/.agents/dashboard/apps/frontend/dist/assets/ProjectSettingsPage-BomxqCBU.css +1 -0
  69. package/templates/.agents/dashboard/apps/frontend/dist/assets/ProjectSettingsPage-DmmJD2Th.js +3 -0
  70. package/templates/.agents/dashboard/apps/frontend/dist/assets/TraceabilityWorkspace-BwtitWa_.js +1 -0
  71. package/templates/.agents/dashboard/apps/frontend/dist/assets/TraceabilityWorkspace-CaKwQP43.css +1 -0
  72. package/templates/.agents/dashboard/apps/frontend/dist/assets/cost-monitor-BZ5WdaMN.css +1 -0
  73. package/templates/.agents/dashboard/apps/frontend/dist/assets/cost-monitor-N5Csr0RP.js +68 -0
  74. package/templates/.agents/dashboard/apps/frontend/dist/assets/{dashboard-localization-C98LGC-Q.js → dashboard-localization-CLJ0lT9v.js} +1 -1
  75. package/templates/.agents/dashboard/apps/frontend/dist/assets/icons-vendor-C0fj2uU9.js +1 -0
  76. package/templates/.agents/dashboard/apps/frontend/dist/assets/index-C4aIB1PV.js +2 -0
  77. package/templates/.agents/dashboard/apps/frontend/dist/assets/index-DK_enB5Z.css +1 -0
  78. package/templates/.agents/dashboard/apps/frontend/dist/assets/react-vendor-BEsJ-FYH.js +9 -0
  79. package/templates/.agents/dashboard/apps/frontend/dist/assets/rolldown-runtime-D9-fqq9M.js +1 -0
  80. package/templates/.agents/dashboard/apps/frontend/dist/assets/traceability-B6y6Gw12.js +1 -0
  81. package/templates/.agents/dashboard/apps/frontend/dist/assets/traceability-DFY7ZDlu.css +1 -0
  82. package/templates/.agents/dashboard/apps/frontend/dist/index.html +9 -2
  83. package/templates/.agents/dashboard/apps/frontend/package.json +1 -1
  84. package/templates/.agents/dashboard/apps/frontend/src/App.tsx +1129 -600
  85. package/templates/.agents/dashboard/apps/frontend/src/AppLoadingBoundary.tsx +48 -0
  86. package/templates/.agents/dashboard/apps/frontend/src/AppLoadingPanels.tsx +2 -0
  87. package/templates/.agents/dashboard/apps/frontend/src/AppOverlays.tsx +247 -0
  88. package/templates/.agents/dashboard/apps/frontend/src/AppRequestGuards.tsx +95 -0
  89. package/templates/.agents/dashboard/apps/frontend/src/AppSetupRoutes.tsx +87 -0
  90. package/templates/.agents/dashboard/apps/frontend/src/CostCalculationGuidePage.tsx +641 -0
  91. package/templates/.agents/dashboard/apps/frontend/src/DashboardAlternateContent.tsx +159 -0
  92. package/templates/.agents/dashboard/apps/frontend/src/DashboardCapabilityNav.tsx +13 -13
  93. package/templates/.agents/dashboard/apps/frontend/src/DashboardGlobalSettings.tsx +56 -0
  94. package/templates/.agents/dashboard/apps/frontend/src/ProjectSettingsPage.tsx +266 -315
  95. package/templates/.agents/dashboard/apps/frontend/src/ProjectStackEditor.tsx +151 -0
  96. package/templates/.agents/dashboard/apps/frontend/src/TraceabilityWorkspace.test.ts +37 -0
  97. package/templates/.agents/dashboard/apps/frontend/src/TraceabilityWorkspace.tsx +114 -12
  98. package/templates/.agents/dashboard/apps/frontend/src/app-preferences.ts +15 -0
  99. package/templates/.agents/dashboard/apps/frontend/src/app-session-token.ts +20 -0
  100. package/templates/.agents/dashboard/apps/frontend/src/cost-calculation-guide.css +267 -0
  101. package/templates/.agents/dashboard/apps/frontend/src/cost-calculation-guide.test.ts +69 -0
  102. package/templates/.agents/dashboard/apps/frontend/src/cost-period-refresh.test.ts +85 -0
  103. package/templates/.agents/dashboard/apps/frontend/src/dashboard-api.test.ts +133 -0
  104. package/templates/.agents/dashboard/apps/frontend/src/dashboard-api.ts +453 -13
  105. package/templates/.agents/dashboard/apps/frontend/src/dashboard-localization.ts +1 -1
  106. package/templates/.agents/dashboard/apps/frontend/src/main.tsx +1 -0
  107. package/templates/.agents/dashboard/apps/frontend/src/operations-detail-hydration.test.ts +55 -0
  108. package/templates/.agents/dashboard/apps/frontend/src/operations-detail-hydration.ts +36 -0
  109. package/templates/.agents/dashboard/apps/frontend/src/operations-entity-page-projection.test.ts +126 -0
  110. package/templates/.agents/dashboard/apps/frontend/src/operations-entity-page-projection.ts +181 -0
  111. package/templates/.agents/dashboard/apps/frontend/src/operations-period-contract.test.ts +138 -0
  112. package/templates/.agents/dashboard/apps/frontend/src/operations-period-render.test.ts +105 -0
  113. package/templates/.agents/dashboard/apps/frontend/src/operations-period.test.ts +6 -3
  114. package/templates/.agents/dashboard/apps/frontend/src/operations-period.ts +9 -5
  115. package/templates/.agents/dashboard/apps/frontend/src/overview-status-page.test.ts +26 -0
  116. package/templates/.agents/dashboard/apps/frontend/src/period-transition-overlay.css +44 -0
  117. package/templates/.agents/dashboard/apps/frontend/src/project-settings-model.ts +121 -62
  118. package/templates/.agents/dashboard/apps/frontend/src/project-settings-page.css +482 -3
  119. package/templates/.agents/dashboard/apps/frontend/src/project-settings.test.ts +84 -17
  120. package/templates/.agents/dashboard/apps/frontend/src/snapshot-banner-semantics.test.ts +78 -0
  121. package/templates/.agents/dashboard/apps/frontend/src/snapshot-coherence.test.ts +234 -39
  122. package/templates/.agents/dashboard/apps/frontend/src/snapshot-notice.ts +15 -0
  123. package/templates/.agents/dashboard/apps/frontend/src/sqlite-cost-adapters.ts +26 -0
  124. package/templates/.agents/dashboard/apps/frontend/src/styles.css +14 -2
  125. package/templates/.agents/dashboard/apps/frontend/src/traceability-workspace.css +38 -2
  126. package/templates/.agents/dashboard/apps/frontend/src/use-app-cost-loaders.test.ts +253 -0
  127. package/templates/.agents/dashboard/apps/frontend/src/use-app-cost-loaders.ts +380 -0
  128. package/templates/.agents/dashboard/apps/frontend/src/use-app-effects.ts +175 -0
  129. package/templates/.agents/dashboard/apps/frontend/src/use-app-operations-pages.ts +395 -0
  130. package/templates/.agents/dashboard/apps/frontend/src/use-app-trace-documents.ts +141 -0
  131. package/templates/.agents/dashboard/apps/frontend/src/use-idle-cost-prefetch.ts +45 -0
  132. package/templates/.agents/dashboard/apps/frontend/src/work-list-pagination.test.ts +46 -0
  133. package/templates/.agents/dashboard/apps/frontend/src/work-list-pagination.ts +36 -0
  134. package/templates/.agents/dashboard/apps/frontend/vite.config.ts +58 -5
  135. package/templates/.agents/dashboard/modules/cost-monitor/package.json +1 -1
  136. package/templates/.agents/dashboard/modules/cost-monitor/src/contracts.ts +47 -6
  137. package/templates/.agents/dashboard/modules/cost-monitor/src/duration-estimate.ts +13 -0
  138. package/templates/.agents/dashboard/modules/cost-monitor/src/react/CompactLifecycleCostTable.test.ts +134 -0
  139. package/templates/.agents/dashboard/modules/cost-monitor/src/react/CompactLifecycleCostTable.tsx +290 -0
  140. package/templates/.agents/dashboard/modules/cost-monitor/src/react/CostCharts.test.ts +133 -19
  141. package/templates/.agents/dashboard/modules/cost-monitor/src/react/CostCharts.tsx +134 -43
  142. package/templates/.agents/dashboard/modules/cost-monitor/src/react/CostFilters.tsx +137 -19
  143. package/templates/.agents/dashboard/modules/cost-monitor/src/react/CostModelsAuditTable.test.ts +2 -0
  144. package/templates/.agents/dashboard/modules/cost-monitor/src/react/CostModelsAuditTable.tsx +13 -10
  145. package/templates/.agents/dashboard/modules/cost-monitor/src/react/CostMonitorContent.tsx +328 -0
  146. package/templates/.agents/dashboard/modules/cost-monitor/src/react/CostMonitorPage.test.ts +302 -6
  147. package/templates/.agents/dashboard/modules/cost-monitor/src/react/CostMonitorPage.tsx +627 -400
  148. package/templates/.agents/dashboard/modules/cost-monitor/src/react/CostSummary.tsx +5 -13
  149. package/templates/.agents/dashboard/modules/cost-monitor/src/react/CostTables.test.ts +370 -72
  150. package/templates/.agents/dashboard/modules/cost-monitor/src/react/CostTables.tsx +467 -326
  151. package/templates/.agents/dashboard/modules/cost-monitor/src/react/MacroCostTable.test.ts +17 -0
  152. package/templates/.agents/dashboard/modules/cost-monitor/src/react/MacroCostTable.tsx +25 -6
  153. package/templates/.agents/dashboard/modules/cost-monitor/src/react/cost-monitor-copy.ts +0 -2
  154. package/templates/.agents/dashboard/modules/cost-monitor/src/react/cost-monitor-page-helpers.ts +17 -0
  155. package/templates/.agents/dashboard/modules/cost-monitor/src/react/cost-monitor-responsive.css +6 -3
  156. package/templates/.agents/dashboard/modules/cost-monitor/src/react/cost-monitor-row-filters.ts +123 -0
  157. package/templates/.agents/dashboard/modules/cost-monitor/src/react/cost-monitor-summary.ts +8 -3
  158. package/templates/.agents/dashboard/modules/cost-monitor/src/react/cost-monitor-views.ts +32 -0
  159. package/templates/.agents/dashboard/modules/cost-monitor/src/react/cost-monitor.css +55 -14
  160. package/templates/.agents/dashboard/modules/cost-monitor/src/react/cost-table-presentation.ts +121 -0
  161. package/templates/.agents/dashboard/modules/cost-monitor/src/react/index.ts +3 -0
  162. package/templates/.agents/dashboard/modules/cost-monitor/src/react/period-cost-groups.test.ts +68 -0
  163. package/templates/.agents/dashboard/modules/cost-monitor/src/react/period-cost-groups.ts +33 -5
  164. package/templates/.agents/dashboard/modules/cost-monitor/src/react/use-compact-cost-page.ts +119 -0
  165. package/templates/.agents/dashboard/modules/cost-monitor/src/react/use-cost-group-page.test.ts +12 -0
  166. package/templates/.agents/dashboard/modules/cost-monitor/src/react/use-cost-group-page.ts +146 -0
  167. package/templates/.agents/dashboard/modules/cost-monitor/src/react/use-cost-run-page.ts +118 -0
  168. package/templates/.agents/dashboard/modules/cost-monitor/src/server/aggregate.test.ts +2 -2
  169. package/templates/.agents/dashboard/modules/cost-monitor/src/server/aggregate.ts +5 -3
  170. package/templates/.agents/dashboard/modules/cost-monitor/src/server/build-cost-monitor-pricing-fallback.test.ts +53 -0
  171. package/templates/.agents/dashboard/modules/cost-monitor/src/server/build-cost-monitor-projection.basics.test.ts +34 -0
  172. package/templates/.agents/dashboard/modules/cost-monitor/src/server/build-cost-monitor-projection.test.ts +168 -161
  173. package/templates/.agents/dashboard/modules/cost-monitor/src/server/build-cost-monitor-projection.ts +188 -29
  174. package/templates/.agents/dashboard/modules/cost-monitor/src/server/build-cost-summary-projection.test.ts +757 -0
  175. package/templates/.agents/dashboard/modules/cost-monitor/src/server/build-cost-summary-projection.ts +784 -0
  176. package/templates/.agents/dashboard/modules/cost-monitor/src/server/build-cost-summary-terminal-day.test.ts +100 -0
  177. package/templates/.agents/dashboard/modules/cost-monitor/src/server/index.ts +1 -0
  178. package/templates/.agents/dashboard/modules/cost-monitor/src/server/refactor-map-xr9l.json +61 -0
  179. package/templates/.agents/dashboard/modules/cost-monitor/src/server/source-size-cost-server/build-cost-monitor-projection-agents.test.ts +31 -0
  180. package/templates/.agents/dashboard/modules/cost-monitor/src/server/source-size-cost-server/build-cost-summary-projection-duration.test.ts +414 -0
  181. package/templates/.agents/dashboard/modules/cost-monitor/src/task-cost-groups.test.ts +41 -0
  182. package/templates/.agents/dashboard/modules/cost-monitor/src/task-cost-groups.ts +55 -11
  183. package/templates/.agents/dashboard/modules/operations/package.json +2 -1
  184. package/templates/.agents/dashboard/modules/operations/src/contracts.ts +185 -0
  185. package/templates/.agents/dashboard/modules/operations/src/duration-population.test.ts +63 -1
  186. package/templates/.agents/dashboard/modules/operations/src/duration-population.ts +60 -5
  187. package/templates/.agents/dashboard/modules/operations/src/react/EntityDetailsDialog.tsx +14 -3
  188. package/templates/.agents/dashboard/modules/operations/src/react/EntityTables.test.ts +44 -1
  189. package/templates/.agents/dashboard/modules/operations/src/react/EntityTables.tsx +345 -18
  190. package/templates/.agents/dashboard/modules/operations/src/react/MacroPlanningDialog.tsx +1 -0
  191. package/templates/.agents/dashboard/modules/operations/src/react/OperationDateFilters.test.ts +9 -5
  192. package/templates/.agents/dashboard/modules/operations/src/react/OperationDateFilters.tsx +2 -2
  193. package/templates/.agents/dashboard/modules/operations/src/react/OperationsMainContent.tsx +168 -0
  194. package/templates/.agents/dashboard/modules/operations/src/react/OperationsOverview.helpers.tsx +95 -6
  195. package/templates/.agents/dashboard/modules/operations/src/react/OperationsOverview.test.ts +367 -14
  196. package/templates/.agents/dashboard/modules/operations/src/react/OperationsOverview.tsx +562 -131
  197. package/templates/.agents/dashboard/modules/operations/src/react/OperationsPage.tsx +353 -355
  198. package/templates/.agents/dashboard/modules/operations/src/react/OperationsPageNavigation.tsx +65 -0
  199. package/templates/.agents/dashboard/modules/operations/src/react/OperationsPageOverview.tsx +169 -0
  200. package/templates/.agents/dashboard/modules/operations/src/react/PeriodSummaryTable.tsx +73 -8
  201. package/templates/.agents/dashboard/modules/operations/src/react/PrdDocumentDialog.test.tsx +32 -0
  202. package/templates/.agents/dashboard/modules/operations/src/react/PrdDocumentDialog.tsx +62 -6
  203. package/templates/.agents/dashboard/modules/operations/src/react/TaskBoard.test.ts +55 -0
  204. package/templates/.agents/dashboard/modules/operations/src/react/TaskBoard.tsx +27 -19
  205. package/templates/.agents/dashboard/modules/operations/src/react/TaskDetailsDialog.tsx +105 -42
  206. package/templates/.agents/dashboard/modules/operations/src/react/UnifiedWorkBoard.priority.test.ts +19 -0
  207. package/templates/.agents/dashboard/modules/operations/src/react/UnifiedWorkBoard.tsx +265 -36
  208. package/templates/.agents/dashboard/modules/operations/src/react/UnifiedWorkList.test.ts +171 -8
  209. package/templates/.agents/dashboard/modules/operations/src/react/UnifiedWorkList.tsx +98 -68
  210. package/templates/.agents/dashboard/modules/operations/src/react/conversation-rows.test.ts +72 -1
  211. package/templates/.agents/dashboard/modules/operations/src/react/conversation-rows.ts +78 -17
  212. package/templates/.agents/dashboard/modules/operations/src/react/execution-metrics.ts +6 -4
  213. package/templates/.agents/dashboard/modules/operations/src/react/export/ExcelExportAction.test.ts +431 -1
  214. package/templates/.agents/dashboard/modules/operations/src/react/export/ExcelExportAction.tsx +574 -20
  215. package/templates/.agents/dashboard/modules/operations/src/react/export/export-layout.test.ts +42 -4
  216. package/templates/.agents/dashboard/modules/operations/src/react/export/xlsx-runtime-e2e.test.ts +248 -0
  217. package/templates/.agents/dashboard/modules/operations/src/react/macro-planning-dialog-content.css +49 -0
  218. package/templates/.agents/dashboard/modules/operations/src/react/macro-planning-dialog.css +93 -50
  219. package/templates/.agents/dashboard/modules/operations/src/react/manual-work-priority.test.ts +82 -0
  220. package/templates/.agents/dashboard/modules/operations/src/react/operation-date-range.test.ts +29 -2
  221. package/templates/.agents/dashboard/modules/operations/src/react/operation-date-range.ts +22 -1
  222. package/templates/.agents/dashboard/modules/operations/src/react/operation-duration.test.ts +77 -4
  223. package/templates/.agents/dashboard/modules/operations/src/react/operation-duration.ts +67 -5
  224. package/templates/.agents/dashboard/modules/operations/src/react/operations-coverage-toast.test.ts +54 -0
  225. package/templates/.agents/dashboard/modules/operations/src/react/operations-global-filters.test.ts +22 -0
  226. package/templates/.agents/dashboard/modules/operations/src/react/operations-overview-period-filter.test.ts +149 -12
  227. package/templates/.agents/dashboard/modules/operations/src/react/operations-overview.status-cards.test.ts +27 -0
  228. package/templates/.agents/dashboard/modules/operations/src/react/operations-page-contract.ts +176 -0
  229. package/templates/.agents/dashboard/modules/operations/src/react/operations-period-scope.test.ts +160 -0
  230. package/templates/.agents/dashboard/modules/operations/src/react/operations-period-scope.ts +47 -0
  231. package/templates/.agents/dashboard/modules/operations/src/react/operations-query.ts +10 -0
  232. package/templates/.agents/dashboard/modules/operations/src/react/operations-responsive.css +3 -0
  233. package/templates/.agents/dashboard/modules/operations/src/react/operations-view-labels.ts +28 -0
  234. package/templates/.agents/dashboard/modules/operations/src/react/operations-view-order.test.ts +21 -7
  235. package/templates/.agents/dashboard/modules/operations/src/react/operations.css +42 -0
  236. package/templates/.agents/dashboard/modules/operations/src/react/period-summary-population.test.ts +54 -0
  237. package/templates/.agents/dashboard/modules/operations/src/react/period-summary-population.ts +32 -0
  238. package/templates/.agents/dashboard/modules/operations/src/react/period-summary.test.ts +241 -6
  239. package/templates/.agents/dashboard/modules/operations/src/react/period-summary.ts +148 -6
  240. package/templates/.agents/dashboard/modules/operations/src/react/popup-localization.test.ts +1 -1
  241. package/templates/.agents/dashboard/modules/operations/src/react/unified-work-board.css +132 -0
  242. package/templates/.agents/dashboard/modules/operations/src/react/unified-work-board.css.test.ts +13 -0
  243. package/templates/.agents/dashboard/modules/operations/src/react/unified-work-board.header.test.ts +16 -0
  244. package/templates/.agents/dashboard/modules/operations/src/react/use-infinite-column.ts +11 -5
  245. package/templates/.agents/dashboard/modules/operations/src/react/work-board-model.test.ts +7 -4
  246. package/templates/.agents/dashboard/modules/operations/src/react/work-board-model.ts +5 -84
  247. package/templates/.agents/dashboard/modules/operations/src/server/build-operations-projection.test.ts +291 -15
  248. package/templates/.agents/dashboard/modules/operations/src/server/build-operations-projection.ts +182 -472
  249. package/templates/.agents/dashboard/modules/operations/src/server/canonical-compat.test.ts +40 -0
  250. package/templates/.agents/dashboard/modules/operations/src/server/canonical-compat.ts +19 -6
  251. package/templates/.agents/dashboard/modules/operations/src/server/canonical-run-projection.ts +31 -6
  252. package/templates/.agents/dashboard/modules/operations/src/server/daily-duration-projection.ts +220 -0
  253. package/templates/.agents/dashboard/modules/operations/src/server/execution-duration-projection.ts +28 -0
  254. package/templates/.agents/dashboard/modules/operations/src/server/execution-relationship-counts.test.ts +39 -2
  255. package/templates/.agents/dashboard/modules/operations/src/server/execution-relationship-counts.ts +25 -13
  256. package/templates/.agents/dashboard/modules/operations/src/server/filter.test.ts +3 -3
  257. package/templates/.agents/dashboard/modules/operations/src/server/filter.ts +7 -2
  258. package/templates/.agents/dashboard/modules/operations/src/server/index.ts +3 -0
  259. package/templates/.agents/dashboard/modules/operations/src/server/macro.ts +3 -12
  260. package/templates/.agents/dashboard/modules/operations/src/server/manifest-usage.ts +65 -0
  261. package/templates/.agents/dashboard/modules/operations/src/server/operations-projection-aggregates.ts +297 -0
  262. package/templates/.agents/dashboard/modules/operations/src/server/quick-daily-operations-projection.ts +330 -0
  263. package/templates/.agents/dashboard/modules/operations/src/server/quick-operations-projection.test.ts +505 -0
  264. package/templates/.agents/dashboard/modules/operations/src/server/quick-operations-projection.ts +609 -0
  265. package/templates/.agents/dashboard/modules/operations/src/server/runs.ts +18 -19
  266. package/templates/.agents/dashboard/modules/operations/src/work-board-model.ts +76 -0
  267. package/templates/.agents/dashboard/modules/traceability/package.json +1 -1
  268. package/templates/.agents/dashboard/modules/traceability/src/server/build-task-trace.ts +3 -1
  269. package/templates/.agents/dashboard/packages/branding/package.json +1 -1
  270. package/templates/.agents/dashboard/packages/branding/src/index.ts +1 -1
  271. package/templates/.agents/dashboard/packages/contracts/package.json +1 -1
  272. package/templates/.agents/dashboard/packages/contracts/src/index.ts +2 -0
  273. package/templates/.agents/dashboard/packages/data-export/package.json +1 -1
  274. package/templates/.agents/dashboard/packages/local-runtime/dist/server.cjs +1759 -0
  275. package/templates/.agents/dashboard/packages/local-runtime/dist/server.cjs.metafile.json +7333 -0
  276. package/templates/.agents/dashboard/packages/local-runtime/dist/sqlite-read-model.cjs +1611 -0
  277. package/templates/.agents/dashboard/packages/local-runtime/package.json +8 -3
  278. package/templates/.agents/dashboard/packages/local-runtime/scripts/build-sqlite-dashboard.mjs +20 -0
  279. package/templates/.agents/dashboard/packages/local-runtime/scripts/build-sqlite-runtime.mjs +114 -0
  280. package/templates/.agents/dashboard/packages/local-runtime/scripts/rebuild-sqlite-read-model.mjs +31 -0
  281. package/templates/.agents/dashboard/packages/local-runtime/scripts/source-size-runtime-scripts/sqlite-read-model-fixture.mjs +397 -0
  282. package/templates/.agents/dashboard/packages/local-runtime/scripts/test-sqlite-read-model.mjs +589 -0
  283. package/templates/.agents/dashboard/packages/local-runtime/scripts/test-unix-launchers.mjs +53 -0
  284. package/templates/.agents/dashboard/packages/local-runtime/scripts/validate-sqlite-read-model.mjs +203 -0
  285. package/templates/.agents/dashboard/packages/local-runtime/server.mjs +1646 -107
  286. package/templates/.agents/dashboard/packages/local-runtime/src/agent-adapter-sync.ts +30 -0
  287. package/templates/.agents/dashboard/packages/local-runtime/src/agent-catalog-settings.test.ts +3 -2
  288. package/templates/.agents/dashboard/packages/local-runtime/src/agent-catalog-settings.ts +5 -0
  289. package/templates/.agents/dashboard/packages/local-runtime/src/manifest-runs.ts +72 -33
  290. package/templates/.agents/dashboard/packages/local-runtime/src/project-settings.test.ts +339 -4
  291. package/templates/.agents/dashboard/packages/local-runtime/src/project-settings.ts +392 -1
  292. package/templates/.agents/dashboard/packages/local-runtime/src/runtime.mjs +5 -5
  293. package/templates/.agents/dashboard/packages/local-runtime/src/server-board.test.ts +110 -0
  294. package/templates/.agents/dashboard/packages/local-runtime/src/server-board.ts +189 -0
  295. package/templates/.agents/dashboard/packages/local-runtime/src/server-cross-layer-parity.test.ts +245 -0
  296. package/templates/.agents/dashboard/packages/local-runtime/src/server-daily-read-models-route.ts +64 -0
  297. package/templates/.agents/dashboard/packages/local-runtime/src/server-daily-read-models.test.ts +204 -0
  298. package/templates/.agents/dashboard/packages/local-runtime/src/server-daily-read-models.ts +194 -0
  299. package/templates/.agents/dashboard/packages/local-runtime/src/server-operations-pages.test.ts +163 -0
  300. package/templates/.agents/dashboard/packages/local-runtime/src/server-operations-pages.ts +354 -0
  301. package/templates/.agents/dashboard/packages/local-runtime/src/server-operations-runs-route.test.ts +74 -0
  302. package/templates/.agents/dashboard/packages/local-runtime/src/server-operations-runs-route.ts +113 -0
  303. package/templates/.agents/dashboard/packages/local-runtime/src/server-overview.test.ts +68 -0
  304. package/templates/.agents/dashboard/packages/local-runtime/src/server-period.ts +47 -0
  305. package/templates/.agents/dashboard/packages/local-runtime/src/server-projections.ts +483 -0
  306. package/templates/.agents/dashboard/packages/local-runtime/src/server-settings.test.ts +5 -2
  307. package/templates/.agents/dashboard/packages/local-runtime/src/server-snapshot.test.ts +178 -84
  308. package/templates/.agents/dashboard/packages/local-runtime/src/server-workspace.ts +149 -0
  309. package/templates/.agents/dashboard/packages/local-runtime/src/server.test.ts +675 -267
  310. package/templates/.agents/dashboard/packages/local-runtime/src/server.ts +1212 -309
  311. package/templates/.agents/dashboard/packages/local-runtime/src/sqlite-metric-contract.test.ts +53 -0
  312. package/templates/.agents/dashboard/packages/local-runtime/src/sqlite-metric-contract.ts +722 -0
  313. package/templates/.agents/dashboard/packages/local-runtime/src/sqlite-read-model.test.ts +3743 -0
  314. package/templates/.agents/dashboard/packages/local-runtime/src/sqlite-read-model.ts +7017 -0
  315. package/templates/.agents/dashboard/packages/local-runtime/src/work-priority-contract.test.ts +33 -0
  316. package/templates/.agents/dashboard/packages/local-runtime/start-dashboard-history.mjs +41 -0
  317. package/templates/.agents/dashboard/packages/local-runtime/start-dashboard-processes.mjs +210 -0
  318. package/templates/.agents/dashboard/packages/local-runtime/start-dashboard.mjs +514 -190
  319. package/templates/.agents/dashboard/packages/local-runtime/start-dashboard.test.mjs +324 -24
  320. package/templates/.agents/dashboard/packages/ui/package.json +1 -1
  321. package/templates/.agents/dashboard/packages/windows-launcher/LauncherVerificationBehaviorTests.cs +206 -0
  322. package/templates/.agents/dashboard/packages/windows-launcher/Program.cs +95 -8
  323. package/templates/.agents/dashboard/packages/windows-launcher/build-dashboard-launcher.ps1 +2 -2
  324. package/templates/.agents/dashboard/packages/windows-launcher/run-launcher-verification-tests.ps1 +22 -0
  325. package/templates/.agents/dashboard/read-model.dbml +2201 -0
  326. package/templates/.agents/dashboard/tests/e2e/package.json +1 -1
  327. package/templates/.agents/dashboard/tests/e2e/playwright.config.ts +1 -1
  328. package/templates/.agents/dashboard/tests/e2e/specs/dashboard.spec.ts +216 -41
  329. package/templates/.agents/dashboard/work-priority.json +34 -0
  330. package/templates/.agents/dashboard/zaip-dashboard-linux.sh +45 -0
  331. package/templates/.agents/dashboard/zaip-dashboard-mac.command +3 -0
  332. package/templates/.agents/dashboard/zaip-dashboard-windows.exe +0 -0
  333. package/templates/.agents/design/.zaip-managed.json +3 -3
  334. package/templates/.agents/design/apps/catalog/package.json +1 -1
  335. package/templates/.agents/design/packages/local-runtime/package.json +1 -1
  336. package/templates/.agents/growth/estrategia-bootstrap-90-dias.md +169 -0
  337. package/templates/.agents/growth/strategy.md +27 -0
  338. package/templates/.agents/marketing/estrategia-marketing-zaip-90-dias.md +197 -0
  339. package/templates/.agents/marketing/strategy.md +29 -0
  340. package/templates/.agents/requirements/autonomous-assurance.md +1 -1
  341. package/templates/.agents/requirements/comparative-audit.md +1 -1
  342. package/templates/.agents/requirements/context-engine.md +1 -1
  343. package/templates/.agents/requirements/cost-observability.md +1 -1
  344. package/templates/.agents/requirements/dashboard-launch.md +24 -0
  345. package/templates/.agents/requirements/data-export.md +1 -1
  346. package/templates/.agents/requirements/design-system.md +1 -1
  347. package/templates/.agents/requirements/execution-engine.md +1 -1
  348. package/templates/.agents/requirements/kanban-dashboard.md +4 -3
  349. package/templates/.agents/requirements/model-orchestration.md +1 -1
  350. package/templates/.agents/requirements/public-distribution.md +9 -6
  351. package/templates/.agents/requirements/software-architecture.md +1 -1
  352. package/templates/.agents/requirements/strategic-improvements.md +1 -1
  353. package/templates/.agents/requirements/work-lifecycle.md +9 -3
  354. package/templates/.agents/requirements/zaip-strategic-95.md +4 -4
  355. package/templates/.agents/rules/autonomy-decision.md +15 -0
  356. package/templates/.agents/rules/core.md +1 -1
  357. package/templates/.agents/rules/run-lifecycle-closure.md +1 -1
  358. package/templates/.agents/rules/specialist-routing.md +19 -0
  359. package/templates/.agents/rules/workflow.md +1 -1
  360. package/templates/.agents/runtime/VERSION +1 -1
  361. package/templates/.agents/runtime/bin/zaip.mjs +118 -67
  362. package/templates/.agents/runtime/checksums.sha256 +6 -4
  363. package/templates/.agents/runtime/manifest.json +3 -1
  364. package/templates/.agents/runtime/pnpm-lock.sha256 +1 -0
  365. package/templates/.agents/runtime/provenance.json +11 -0
  366. package/templates/.agents/runtime/sbom.cdx.json +1929 -39
  367. package/templates/.agents/sales/playbook.md +32 -0
  368. package/templates/.agents/sales/roteiro-comercial-zaip.md +252 -0
  369. package/templates/.agents/skills/zaip-aios/SKILL.md +1 -1
  370. package/templates/.agents/skills/zaip-skill-brand-governance/SKILL.md +22 -0
  371. package/templates/.agents/skills/zaip-skill-brand-governance/agents/openai.yaml +4 -0
  372. package/templates/.agents/skills/zaip-skill-brand-governance/references/brandbook-framework.md +39 -0
  373. package/templates/.agents/skills/zaip-skill-brand-governance/references/brandbook-standards.md +30 -0
  374. package/templates/.agents/skills/zaip-skill-dashboard-sqlite/SKILL.md +25 -0
  375. package/templates/.agents/skills/zaip-skill-dashboard-sqlite/agents/openai.yaml +4 -0
  376. package/templates/.agents/skills/zaip-skill-enforce-architecture/SKILL.md +2 -0
  377. package/templates/.agents/skills/zaip-skill-executar-fila-pronta/SKILL.md +18 -0
  378. package/templates/.agents/skills/zaip-skill-executar-fila-pronta/agents/openai.yaml +6 -0
  379. package/templates/.agents/skills/zaip-skill-executar-fila-pronta/scripts/ready-queue-fence.mjs +71 -0
  380. package/templates/.agents/skills/zaip-skill-executar-fila-pronta/scripts/ready-queue-fence.test.mjs +60 -0
  381. package/templates/.agents/skills/zaip-skill-executar-fila-pronta/scripts/scheduled-ready-queue-contract.test.mjs +111 -0
  382. package/templates/.agents/skills/zaip-skill-execution/SKILL.md +2 -2
  383. package/templates/.agents/skills/zaip-skill-frontend-launcher/references/launcher-contract.md +3 -1
  384. package/templates/.agents/skills/zaip-skill-general-operations/SKILL.md +12 -0
  385. package/templates/.agents/skills/zaip-skill-general-operations/agents/openai.yaml +4 -0
  386. package/templates/.agents/skills/zaip-skill-github-deploy/SKILL.md +9 -7
  387. package/templates/.agents/skills/zaip-skill-github-deploy/agents/openai.yaml +2 -2
  388. package/templates/.agents/skills/zaip-skill-github-deploy/scripts/github-deploy-contract.test.mjs +11 -38
  389. package/templates/.agents/skills/zaip-skill-governance-compliance/SKILL.md +12 -0
  390. package/templates/.agents/skills/zaip-skill-governance-compliance/agents/openai.yaml +4 -0
  391. package/templates/.agents/skills/zaip-skill-growth-strategy-revops/SKILL.md +21 -0
  392. package/templates/.agents/skills/zaip-skill-growth-strategy-revops/agents/openai.yaml +4 -0
  393. package/templates/.agents/skills/zaip-skill-growth-strategy-revops/references/growth-revops-framework.md +25 -0
  394. package/templates/.agents/skills/zaip-skill-instalar-agendamento/SKILL.md +17 -0
  395. package/templates/.agents/skills/zaip-skill-instalar-agendamento/agents/openai.yaml +6 -0
  396. package/templates/.agents/skills/zaip-skill-marketing/SKILL.md +9 -3
  397. package/templates/.agents/skills/zaip-skill-reconcile-telemetry/scripts/reconcile-local-telemetry.mjs +99 -93
  398. package/templates/.agents/skills/zaip-skill-reconcile-telemetry/scripts/reconcile-telemetry-lib.mjs +132 -23
  399. package/templates/.agents/skills/zaip-skill-reconcile-telemetry/scripts/reconcile-telemetry-lib.test.mjs +149 -1
  400. package/templates/.agents/skills/zaip-skill-reconcile-telemetry/scripts/reconcile-telemetry-remeasurement.mjs +76 -19
  401. package/templates/.agents/skills/zaip-skill-reconcile-telemetry/scripts/reconcile-telemetry-remeasurement.test.mjs +217 -7
  402. package/templates/.agents/skills/zaip-skill-reconcile-telemetry/scripts/source-size-telemetry/model-identity-reconciliation.mjs +77 -0
  403. package/templates/.agents/skills/zaip-skill-sales-methodology/SKILL.md +20 -0
  404. package/templates/.agents/skills/zaip-skill-sales-methodology/agents/openai.yaml +4 -0
  405. package/templates/.agents/skills/zaip-skill-sales-methodology/references/sales-process-framework.md +77 -0
  406. package/templates/.agents/skills/zaip-skill-setup/SKILL.md +5 -0
  407. package/templates/.agents/skills/zaip-skill-sqlite-read-model/SKILL.md +96 -0
  408. package/templates/.agents/skills/zaip-skill-sqlite-read-model/agents/openai.yaml +4 -0
  409. package/templates/.agents/skills/zaip-skill-sqlite-read-model/scripts/ensure-node.mjs +41 -0
  410. package/templates/.agents/zaip-aios/INDEX.md +11 -0
  411. package/templates/.agents/zaip-aios/README.md +38 -8
  412. package/templates/.agents/zaip-aios/VERSION +1 -1
  413. package/templates/.agents/zaip-aios/guides/09-agentes-e-squads.md +43 -6
  414. package/templates/.agents/zaip-aios/guides/10-seguranca.md +21 -7
  415. package/templates/.agents/zaip-aios/guides/17-como-o-custo-e-calculado.md +32 -0
  416. package/templates/.agents/zaip-aios/guides/18-catalogo-de-agentes.md +76 -0
  417. package/templates/.agents/zaip-aios/guides/19-assurance-e-autonomia.md +72 -0
  418. package/templates/.agents/zaip-aios/guides/20-instalacao-detalhada.md +330 -0
  419. package/templates/.agents/zaip-aios/guides/21-telemetria-monitor-custos.md +52 -0
  420. package/templates/.agents/zaip-aios/guides/22-fluxos-e-roteamento.md +69 -0
  421. package/templates/.agents/zaip-aios/guides/23-orquestracao-de-modelos.md +483 -0
  422. package/templates/.agents/zaip-aios/guides/24-calculo-de-custos-openai.md +85 -0
  423. package/templates/.agents/zaip-aios/guides/25-fontes-de-precos-openai.md +18 -0
  424. package/templates/.agents/zaip-aios/guides/26-qualidade-e-release.md +44 -0
  425. package/templates/.agents/zaip-aios/guides/27-telemetria-git-native.md +167 -0
  426. package/templates/.agents/zaip-aios/guides/28-lifecycle-completo.md +144 -0
  427. package/templates/.agents/zaip-aios/guides/assets/diagrams/lifecycles-task-spec-prd.png +0 -0
  428. package/templates/.agents/zaip-aios/guides/assets/diagrams/prd-lifecycle.png +0 -0
  429. package/templates/.agents/zaip-aios/guides/assets/diagrams/spec-lifecycle.png +0 -0
  430. package/templates/.agents/zaip-aios/guides/assets/diagrams/task-lifecycle.png +0 -0
  431. package/templates/template-manifest.json +1082 -215
  432. package/templates/.agents/dashboard/apps/frontend/dist/assets/AgentCatalogSettingsPage-CLYIi7Vo.js +0 -1
  433. package/templates/.agents/dashboard/apps/frontend/dist/assets/AgentCatalogSettingsPage-DTDNVQGX.css +0 -1
  434. package/templates/.agents/dashboard/apps/frontend/dist/assets/DashboardHelpDialog-Cv-JcoxP.js +0 -1320
  435. package/templates/.agents/dashboard/apps/frontend/dist/assets/PricingSettingsDialog-CzEggcRb.js +0 -1
  436. package/templates/.agents/dashboard/apps/frontend/dist/assets/ProjectSettingsPage-05YKn6Z4.js +0 -3
  437. package/templates/.agents/dashboard/apps/frontend/dist/assets/ProjectSettingsPage-YO3yqtgV.css +0 -1
  438. package/templates/.agents/dashboard/apps/frontend/dist/assets/index-8AzCnl3a.js +0 -77
  439. package/templates/.agents/dashboard/apps/frontend/dist/assets/index-DdBYQ_8D.css +0 -1
  440. package/templates/.agents/dashboard/apps/frontend/src/AgentCatalogSettingsPage.tsx +0 -617
  441. package/templates/.agents/dashboard/apps/frontend/src/agent-catalog-settings-page.css +0 -660
  442. package/templates/.agents/dashboard/apps/frontend/src/agent-catalog-settings.test.ts +0 -249
  443. package/templates/.agents/dashboard/dashboard.config.json +0 -4
  444. package/templates/.agents/dashboard/zaip-dashboard.exe +0 -0
@@ -0,0 +1,784 @@
1
+ import type {
2
+ OperationsProjection,
3
+ RunProjection,
4
+ UsageMetricProjection,
5
+ UsageProjection,
6
+ } from "@zaip-ai/dashboard-operations/contracts";
7
+ import {
8
+ canonicalAllTimeDurationMs,
9
+ isAfterLegacyEffortCutoff,
10
+ LEGACY_EFFORT_DAILY_MS,
11
+ LEGACY_EFFORT_SNAPSHOT,
12
+ saoPauloPeriodKey,
13
+ } from "@zaip-ai/dashboard-operations/contracts";
14
+ import {
15
+ normalizeTokenBackedDailyDuration,
16
+ hybridDailyDuration as sharedHybridDailyDuration,
17
+ rootExecutionDurationByDay as sharedRootExecutionDurationByDay,
18
+ } from "@zaip-ai/dashboard-operations/server";
19
+ import type { CostGroupRow, CostMonitorProjection } from "../contracts.js";
20
+ import { estimatedDurationMs, TOKEN_DURATION_ESTIMATE_BASIS } from "../duration-estimate.js";
21
+ import { buildCostMonitorProjection, usageForRuns } from "./build-cost-monitor-projection.js";
22
+
23
+ /** Fast Cost Monitor first fold backed only by the durable lifecycle summary. */
24
+ export function buildCostSummaryProjection(
25
+ summary: CostSummarySource,
26
+ operations: OperationsProjection,
27
+ currency: "BRL" | "USD",
28
+ fxRate: number | null,
29
+ ): CostMonitorProjection {
30
+ const effectiveSummaryRuns = (summary.run_metrics ?? []).map(effectiveSummaryRun);
31
+ const compactRuns = effectiveSummaryRuns
32
+ .filter((run) => {
33
+ const day = saoPauloPeriodKey(run.finished_at ?? run.started_at, "day");
34
+ return day !== null && inRange(day, operations.filters.from, operations.filters.to);
35
+ })
36
+ .map(summaryRunProjection);
37
+ const available =
38
+ operations.schema_version === 2
39
+ ? buildCostMonitorProjection(
40
+ {
41
+ ...operations,
42
+ tasks: operations.tasks ?? [],
43
+ runs: compactRuns,
44
+ } as OperationsProjection,
45
+ undefined,
46
+ )
47
+ : null;
48
+ // A Model/Provider table shows only concrete source dimensions. Summary
49
+ // cards retain all financial facts; unknown attribution is never reassigned.
50
+ const concreteDimensionRows = (rows: readonly CostGroupRow[]) =>
51
+ rows.filter((row) => {
52
+ const key = row.key.trim().toLowerCase();
53
+ return key.length > 0 && !["mixed", "unknown", "unavailable"].includes(key);
54
+ });
55
+ const hasRunMetrics = summary.run_metrics !== undefined;
56
+ const hasCanonicalSqliteFacts =
57
+ summary.cost_monitor_daily_duration !== undefined ||
58
+ summary.canonical_daily_duration_ms !== undefined;
59
+ // The SQLite path is fully sourced from canonical Run facts. Legacy daily
60
+ // buckets remain available only to the old manifest path.
61
+ const dailyPeriods = new Map<string, PeriodSummary>(
62
+ Object.entries(finishDayCostPeriods(summary)),
63
+ );
64
+ // A factual source interval can cross a Sao Paulo midnight. Preserve the
65
+ // elapsed-session day even where no separate financial source event exists.
66
+ for (const key of Object.keys(summary.cost_monitor_daily_duration ?? {}))
67
+ if (!dailyPeriods.has(key)) dailyPeriods.set(key, emptyPeriodSummary());
68
+ if (!hasRunMetrics && !hasCanonicalSqliteFacts) {
69
+ for (const day of Object.keys(LEGACY_EFFORT_DAILY_MS))
70
+ if (!dailyPeriods.has(day)) dailyPeriods.set(day, emptyPeriodSummary());
71
+ }
72
+ // Prefer the compact Run projection whenever it is available: it already
73
+ // assigns the shared effective duration to every tokenized Run. Falling
74
+ // back to root-only summary timing would turn a tokenized day into 0 s.
75
+ const periodEntries = [...dailyPeriods].filter(([key]) =>
76
+ inRange(key, operations.filters.from, operations.filters.to),
77
+ );
78
+ const factualDurationByDay = durationByRootExecutionDay(effectiveSummaryRuns);
79
+ const factualCostDurationByDay = summary.cost_monitor_daily_duration;
80
+ const durationForDay = (key: string, period: PeriodSummary): DurationSource => {
81
+ if (factualCostDurationByDay !== undefined) {
82
+ const value = factualCostDurationByDay[key];
83
+ return value === undefined
84
+ ? emptyDuration()
85
+ : {
86
+ value: {
87
+ known_sum: value.known_sum,
88
+ unknown: value.eligible_runs - value.known_runs,
89
+ complete: value.eligible_runs === value.known_runs,
90
+ coverage_ratio:
91
+ value.eligible_runs === 0 ? 1 : value.known_runs / value.eligible_runs,
92
+ },
93
+ population: runPopulation(value.eligible_runs, value.known_runs),
94
+ };
95
+ }
96
+ if (summary.canonical_daily_duration_ms !== undefined) {
97
+ const value = summary.canonical_daily_duration_ms[key];
98
+ return value === undefined
99
+ ? emptyDuration()
100
+ : {
101
+ value: { known_sum: value, unknown: 0, complete: true, coverage_ratio: 1 },
102
+ population: runPopulation(period.runs, period.runs),
103
+ };
104
+ }
105
+ if (hasRunMetrics) return factualDurationByDay.get(key) ?? emptyDuration();
106
+ return dailyDurationSource(key, period);
107
+ };
108
+ const durationBudget = periodEntries.reduce(
109
+ (total, [key, period]) => total + durationForDay(key, period).value.known_sum,
110
+ 0,
111
+ );
112
+ const normalizedDurationBudget =
113
+ !hasRunMetrics &&
114
+ !hasCanonicalSqliteFacts &&
115
+ operations.filters.from === null &&
116
+ operations.filters.to === null
117
+ ? canonicalAllTimeDurationMs(durationBudget)
118
+ : durationBudget;
119
+ const factualDailyRows = new Map(
120
+ (summary.daily_rows ?? []).map((row) => [row.key, row] as const),
121
+ );
122
+ const projectedDaily = periodEntries.map(([key, period]) =>
123
+ periodRow(key, period, fxRate, durationForDay(key, period), factualDailyRows.get(key)),
124
+ );
125
+ // Canonical SQLite duration is already deduplicated and assigned to the
126
+ // correct São Paulo calendar day. Rebalancing it by token population would
127
+ // preserve only the all-time total while corrupting each daily row.
128
+ const daily = hasCanonicalSqliteFacts
129
+ ? projectedDaily
130
+ : normalizeTokenBackedGroupBudget(
131
+ projectedDaily.map(ensureTokenBackedGroupDuration),
132
+ normalizedDurationBudget,
133
+ );
134
+ const runCount = daily.reduce((total, row) => total + row.run_count, 0);
135
+ const eventCount = daily.reduce((total, row) => total + row.event_count, 0);
136
+ // A completely unavailable population must not become a factual zero merely
137
+ // because the daily structural accumulator starts at zero.
138
+ const tokenTotal =
139
+ !hasCanonicalSqliteFacts && compactRuns.every((run) => run.usage.total.tokens.total === null)
140
+ ? null
141
+ : sumNullable(daily.map((row) => row.total_tokens));
142
+ const brlTotal =
143
+ !hasCanonicalSqliteFacts && compactRuns.every((run) => run.usage.total.cost.brl === null)
144
+ ? null
145
+ : sumNullable(daily.map((row) => row.estimated_brl));
146
+ const usdTotal = sumNullable(daily.map((row) => row.estimated_usd));
147
+ const observedDurationAverage = averageObservedPostCutoffRootDuration(summary.run_metrics ?? []);
148
+ const taskCount =
149
+ operations.summary.overview_metrics?.task_count ?? operations.summary.task_count;
150
+ // Period summaries expose the number of unavailable Runs. Compute coverage
151
+ // against exactly the Run population used by the cards, rather than event
152
+ // coverage (which is absent from the fast summary path).
153
+ const coverage = {
154
+ events: runCount,
155
+ tokens: daily.reduce((total, row) => total + row.coverage.tokens, 0),
156
+ usd: daily.reduce((total, row) => total + row.coverage.usd, 0),
157
+ brl: daily.reduce((total, row) => total + row.coverage.brl, 0),
158
+ };
159
+ return {
160
+ schema_version: 2,
161
+ layout_version: operations.layout_version,
162
+ readonly: true,
163
+ source: ".agents/records",
164
+ aggregate_only: true,
165
+ data_source:
166
+ hasRunMetrics || hasCanonicalSqliteFacts ? "run_records" : "lifecycle_manifest_summary",
167
+ legacy_effort_baseline:
168
+ !hasRunMetrics &&
169
+ !hasCanonicalSqliteFacts &&
170
+ operations.filters.from === null &&
171
+ operations.filters.to === null
172
+ ? { cutoff: LEGACY_EFFORT_SNAPSHOT.cutoff, duration_ms: LEGACY_EFFORT_SNAPSHOT.durationMs }
173
+ : null,
174
+ currency,
175
+ pricing: { catalog_updated_at: null, fx_rate: fxRate, conversion_applied: fxRate !== null },
176
+ filters: operations.filters,
177
+ overview: {
178
+ task_count: taskCount,
179
+ run_count: runCount,
180
+ event_count: eventCount,
181
+ total_tokens: tokenTotal,
182
+ estimated_usd: usdTotal,
183
+ estimated_brl: brlTotal,
184
+ recorded_usd: null,
185
+ recorded_brl: null,
186
+ average_run_cost_usd: runCount === 0 || usdTotal === null ? null : usdTotal / runCount,
187
+ average_run_cost_brl: runCount === 0 || brlTotal === null ? null : brlTotal / runCount,
188
+ // Legacy effort has no individual Run cardinality, so it is not a
189
+ // legitimate contributor to an average per Run.
190
+ average_run_duration_ms: observedDurationAverage,
191
+ known_tokens_per_cycle: runCount === 0 || tokenTotal === null ? null : tokenTotal / runCount,
192
+ top_10_token_share: null,
193
+ coverage,
194
+ },
195
+ filters_available: {
196
+ providers: available?.filters_available.providers ?? [],
197
+ agents: available?.filters_available.agents ?? [],
198
+ models: available?.filters_available.models ?? [],
199
+ statuses: available?.filters_available.statuses ?? [],
200
+ priorities: available?.filters_available.priorities ?? [],
201
+ risks: available?.filters_available.risks ?? [],
202
+ phases: available?.filters_available.phases ?? [],
203
+ origins: available?.filters_available.origins ?? [],
204
+ work_types: available?.filters_available.work_types ?? [],
205
+ },
206
+ configured_agents: available?.configured_agents ?? [],
207
+ // Compact Run facts preserve total tokens and cost even though component
208
+ // telemetry is intentionally absent. Reuse their phase-aware aggregate
209
+ // instead of the quick Operations placeholder, which has no Run rows.
210
+ usage: summary.aggregate_usage ?? available?.usage ?? usageForRuns(compactRuns),
211
+ origins: emptyOrigins(),
212
+ prds: available?.prds ?? operations.prds,
213
+ specs: available?.specs ?? operations.specs,
214
+ // Keep summary first-paint bounded. Dimensional aggregates above were
215
+ // computed from compact facts, but Run transport stays page-only.
216
+ runs: [],
217
+ groups: {
218
+ // These two dimensions can contain one row per conversation or Task.
219
+ // They are rendered through the compact, paginated SQLite views after
220
+ // their tabs open, so carrying them in the first-fold summary only
221
+ // delays the Cost Monitor without contributing to its initial view.
222
+ conversations: [],
223
+ tasks: [],
224
+ providers: concreteDimensionRows(available?.groups.providers ?? []),
225
+ agents: available?.groups.agents ?? [],
226
+ // Model residuals preserve financial reconciliation in SQLite as
227
+ // unavailable, but are not a factual model category for the chart.
228
+ models: concreteDimensionRows(summary.model_groups ?? available?.groups.models ?? []),
229
+ daily,
230
+ monthly: mergePeriodRows(daily, 7),
231
+ annual: mergePeriodRows(daily, 4),
232
+ },
233
+ };
234
+ }
235
+
236
+ function dailyDurationSource(key: string, period: PeriodSummary): DurationSource {
237
+ return sharedHybridDailyDuration(key, period) as DurationSource;
238
+ }
239
+
240
+ function emptyPeriodSummary(): PeriodSummary {
241
+ const empty: KnownValue = { known_sum: 0, unknown: 0, complete: true, coverage_ratio: 1 };
242
+ return {
243
+ prds: 0,
244
+ specs: 0,
245
+ tasks: 0,
246
+ validations: 0,
247
+ evidences: 0,
248
+ runs: 0,
249
+ usage: { total_tokens: empty, cost: { ...empty, currency: "BRL" } },
250
+ };
251
+ }
252
+
253
+ export interface CostSummarySource {
254
+ periods: { daily: Record<string, PeriodSummary> };
255
+ /**
256
+ * SQLite's selected financial facts, retained for compact summaries where
257
+ * no Run transport is present. Values are factual and currency-specific.
258
+ */
259
+ daily_rows?: Array<{
260
+ key: string;
261
+ total_cost_usd: number | null;
262
+ total_cost_brl: number | null;
263
+ }>;
264
+ /** Distinct Tasks represented by the filtered aggregate population. */
265
+ task_count?: number;
266
+ aggregate_usage?: UsageProjection;
267
+ /** Segment-backed model aggregates for the SQLite first fold. */
268
+ model_groups?: CostGroupRow[];
269
+ /** @deprecated Root-execution duration; retained for non-SQLite callers. */
270
+ canonical_daily_duration_ms?: Record<string, number>;
271
+ /** Factual source duration paired with the financial invocation population. */
272
+ cost_monitor_daily_duration?: Record<
273
+ string,
274
+ { known_sum: number; eligible_runs: number; known_runs: number }
275
+ >;
276
+ run_metrics?: Array<{
277
+ id: string;
278
+ started_at: string;
279
+ finished_at: string | null;
280
+ task_id: string | null;
281
+ execution_id?: string | null;
282
+ conversation_id?: string | null;
283
+ agent?: string | null;
284
+ agent_name?: string | null;
285
+ provider?: string | null;
286
+ model?: string | null;
287
+ spec_id?: string | null;
288
+ prd_id?: string | null;
289
+ change_id?: string | null;
290
+ run_kind?: "run" | "subrun" | null;
291
+ phase: string | null;
292
+ parent_run_id: string | null;
293
+ status: string | null;
294
+ duration_ms: number | null;
295
+ /** Raw factual invocation duration, never a token estimate. */
296
+ source_duration_ms?: number | null;
297
+ duration_provenance?: "observed" | "estimated" | "unavailable";
298
+ estimation_basis?: string | null;
299
+ duration_started_at?: string | null;
300
+ total_tokens: number | null;
301
+ input_tokens?: number | null;
302
+ cached_input_tokens?: number | null;
303
+ output_tokens?: number | null;
304
+ reasoning_tokens?: number | null;
305
+ cost: number | null;
306
+ currency: string | null;
307
+ events: number | null;
308
+ }>;
309
+ }
310
+
311
+ /** Adapter from the durable compact Run fact to the Cost projection contract. */
312
+ function summaryRunProjection(
313
+ run: NonNullable<CostSummarySource["run_metrics"]>[number],
314
+ ): RunProjection {
315
+ const empty = {
316
+ events: 0,
317
+ duration_ms: null,
318
+ tokens: { input: null, cached_input: null, output: null, reasoning: null, total: null },
319
+ cost: { usd: null, brl: null },
320
+ coverage: { events: 0, tokens: 0, usd: 0, brl: 0 },
321
+ };
322
+ const usage = {
323
+ ...empty,
324
+ events: run.events ?? 0,
325
+ duration_ms: run.source_duration_ms ?? null,
326
+ tokens: {
327
+ ...empty.tokens,
328
+ input: run.input_tokens ?? null,
329
+ cached_input: run.cached_input_tokens ?? null,
330
+ output: run.output_tokens ?? null,
331
+ reasoning: run.reasoning_tokens ?? null,
332
+ total: run.total_tokens,
333
+ },
334
+ cost: { usd: null, brl: run.currency === "BRL" ? run.cost : null },
335
+ coverage: {
336
+ events: run.events ?? 0,
337
+ tokens: run.total_tokens === null ? 0 : 1,
338
+ usd: 0,
339
+ brl: run.cost === null ? 0 : 1,
340
+ },
341
+ };
342
+ const phase = run.phase === "conversation" || run.phase === "planning" ? run.phase : "execution";
343
+ return {
344
+ id: run.id,
345
+ artifact_path: `.agents/records/runs/${run.id}`,
346
+ status:
347
+ run.status === "failed" || run.status === "cancelled" || run.status === "running"
348
+ ? run.status
349
+ : "completed",
350
+ phase,
351
+ entrypoint: run.task_id === null ? "conversation" : "task",
352
+ work_type: "new",
353
+ run_role: run.run_kind === "subrun" ? "subagent" : "orchestrator",
354
+ run_kind: run.run_kind ?? "run",
355
+ run_purpose: "execution",
356
+ requires_finalizer: false,
357
+ parent_run_id: run.parent_run_id,
358
+ client: "unknown",
359
+ agent: run.agent ?? "unknown",
360
+ agent_name: run.agent_name ?? run.agent ?? "unknown",
361
+ provider: run.provider ?? "unavailable",
362
+ model: run.model ?? "unknown",
363
+ reasoning_effort: null,
364
+ effective_model: run.model ?? null,
365
+ effective_reasoning_effort: null,
366
+ effective_config_mixed: false,
367
+ call_count: null,
368
+ terminal_call_count: null,
369
+ failed_call_count: 0,
370
+ cancelled_call_count: 0,
371
+ conversation_id: run.conversation_id ?? run.id,
372
+ execution_id: run.execution_id ?? null,
373
+ task_id: run.task_id,
374
+ spec_id: run.spec_id ?? null,
375
+ prd_id: run.prd_id ?? null,
376
+ change_id: run.change_id ?? null,
377
+ started_at: run.started_at,
378
+ finished_at: run.finished_at,
379
+ duration_ms: run.duration_ms,
380
+ source_duration_ms: run.source_duration_ms ?? null,
381
+ ...(run.duration_provenance === undefined
382
+ ? {}
383
+ : { duration_provenance: run.duration_provenance }),
384
+ ...(run.estimation_basis === undefined ? {} : { estimation_basis: run.estimation_basis }),
385
+ usage: {
386
+ conversation: phase === "conversation" ? usage : empty,
387
+ planning: phase === "planning" ? usage : empty,
388
+ execution: phase === "execution" ? usage : empty,
389
+ total: usage,
390
+ new_work: usage,
391
+ rework: empty,
392
+ },
393
+ };
394
+ }
395
+
396
+ function effectiveSummaryRun(
397
+ run: NonNullable<CostSummarySource["run_metrics"]>[number],
398
+ ): NonNullable<CostSummarySource["run_metrics"]>[number] {
399
+ if (run.duration_ms !== null)
400
+ return {
401
+ ...run,
402
+ duration_provenance: run.duration_provenance ?? "unavailable",
403
+ estimation_basis:
404
+ run.duration_provenance === "estimated" ? (run.estimation_basis ?? null) : null,
405
+ };
406
+ const duration_ms = estimatedDurationMs(run.total_tokens);
407
+ return duration_ms === null
408
+ ? { ...run, duration_provenance: "unavailable", estimation_basis: null }
409
+ : {
410
+ ...run,
411
+ duration_ms,
412
+ duration_provenance: "estimated",
413
+ estimation_basis: TOKEN_DURATION_ESTIMATE_BASIS,
414
+ };
415
+ }
416
+
417
+ function ensureTokenBackedGroupDuration(row: CostGroupRow): CostGroupRow {
418
+ if ((row.total_tokens ?? 0) <= 0 || (row.duration_ms ?? 0) > 0) return row;
419
+ const duration_ms = estimatedDurationMs(row.total_tokens);
420
+ if (duration_ms === null || duration_ms <= 0) return row;
421
+ const coverageCounts = row.coverage_counts;
422
+ return {
423
+ ...row,
424
+ duration_ms,
425
+ duration: { known_sum: duration_ms, unknown: 0, complete: true, coverage_ratio: 1 },
426
+ ...(coverageCounts === undefined
427
+ ? {}
428
+ : {
429
+ coverage_counts: {
430
+ ...coverageCounts,
431
+ ...(coverageCounts.metrics === undefined
432
+ ? {}
433
+ : {
434
+ metrics: {
435
+ ...coverageCounts.metrics,
436
+ duration: {
437
+ eligible_runs: row.run_count,
438
+ known_runs: row.run_count,
439
+ unknown_runs: 0,
440
+ },
441
+ },
442
+ }),
443
+ },
444
+ }),
445
+ };
446
+ }
447
+
448
+ function normalizeTokenBackedGroupBudget(
449
+ rows: readonly CostGroupRow[],
450
+ budget: number,
451
+ ): CostGroupRow[] {
452
+ return normalizeTokenBackedDailyDuration(rows, budget).map((row) => ({
453
+ ...row,
454
+ duration_ms: row.duration.complete ? row.duration.known_sum : null,
455
+ }));
456
+ }
457
+
458
+ interface KnownValue {
459
+ known_sum: number;
460
+ unknown: number;
461
+ complete: boolean;
462
+ coverage_ratio: number;
463
+ }
464
+
465
+ interface PeriodSummary {
466
+ prds: number;
467
+ specs: number;
468
+ tasks: number;
469
+ validations: number;
470
+ evidences: number;
471
+ runs: number;
472
+ usage: {
473
+ total_tokens: KnownValue;
474
+ cost: KnownValue & { currency: string | null };
475
+ };
476
+ duration?: KnownValue;
477
+ events?: KnownValue;
478
+ }
479
+
480
+ /** Reconcile the fast summary with the completed-Run calendar used by detail. */
481
+ function finishDayCostPeriods(summary: CostSummarySource): Record<string, PeriodSummary> {
482
+ const runs = [
483
+ ...new Map((summary.run_metrics ?? []).map((run) => [run.id, run] as const)).values(),
484
+ ];
485
+ if (summary.run_metrics === undefined) return summary.periods.daily;
486
+
487
+ const byDay = new Map<string, typeof runs>();
488
+ for (const run of runs) {
489
+ // The compact SQLite source has already chosen source session time for
490
+ // started_at. Do not move token/cost to a later capture/finish day.
491
+ const day = saoPauloPeriodKey(run.started_at, "day");
492
+ if (day !== null) byDay.set(day, [...(byDay.get(day) ?? []), run]);
493
+ }
494
+ const days = new Set([...Object.keys(summary.periods.daily), ...byDay.keys()]);
495
+ return Object.fromEntries(
496
+ [...days].map((day) => {
497
+ const period = summary.periods.daily[day] ?? emptyPeriodSummary();
498
+ const dayRuns = byDay.get(day) ?? [];
499
+ const tokens = knownPeriodValue(dayRuns.map((run) => run.total_tokens));
500
+ const cost = knownPeriodValue(dayRuns.map((run) => run.cost));
501
+ const events = knownPeriodValue(dayRuns.map((run) => run.events));
502
+ return [
503
+ day,
504
+ {
505
+ ...period,
506
+ runs: dayRuns.length,
507
+ usage: {
508
+ total_tokens: tokens,
509
+ cost: {
510
+ ...cost,
511
+ currency:
512
+ dayRuns.find((run) => run.currency !== null)?.currency ??
513
+ period.usage.cost.currency,
514
+ },
515
+ },
516
+ events,
517
+ },
518
+ ];
519
+ }),
520
+ );
521
+ }
522
+
523
+ function knownPeriodValue(values: readonly (number | null)[]): KnownValue {
524
+ const known = values.filter((value): value is number => value !== null);
525
+ const unknown = values.length - known.length;
526
+ return {
527
+ known_sum: known.reduce((total, value) => total + value, 0),
528
+ unknown,
529
+ complete: unknown === 0,
530
+ coverage_ratio: values.length === 0 ? 1 : known.length / values.length,
531
+ };
532
+ }
533
+
534
+ function periodRow(
535
+ key: string,
536
+ period: PeriodSummary,
537
+ fxRate: number | null,
538
+ duration: DurationSource,
539
+ factualCosts?: { total_cost_usd: number | null; total_cost_brl: number | null },
540
+ ): CostGroupRow {
541
+ const periodBrl =
542
+ period.usage.cost.known_sum === 0 && period.usage.cost.unknown > 0
543
+ ? null
544
+ : period.usage.cost.known_sum;
545
+ // Do not derive or relabel a currency when SQLite supplied its factual
546
+ // value. The legacy manifest path retains its period/FX fallback.
547
+ const brl = factualCosts === undefined ? periodBrl : factualCosts.total_cost_brl;
548
+ const usd =
549
+ factualCosts === undefined
550
+ ? brl !== null && fxRate !== null && fxRate > 0
551
+ ? brl / fxRate
552
+ : null
553
+ : factualCosts.total_cost_usd;
554
+ const eventCount = period.events?.known_sum ?? 0;
555
+ const knownTokens = knownRuns(period.runs, period.usage.total_tokens.unknown);
556
+ const knownCost = knownRuns(period.runs, period.usage.cost.unknown);
557
+ return {
558
+ key,
559
+ label: key,
560
+ latest_started_at: `${key}T23:59:59.999-03:00`,
561
+ run_count: period.runs,
562
+ task_count: period.tasks,
563
+ tasksCreated: period.tasks,
564
+ tasksActive: period.tasks,
565
+ taskDaysActive: period.tasks,
566
+ prd_count: period.prds,
567
+ spec_count: period.specs,
568
+ evidence_count: period.evidences,
569
+ test_count: period.validations,
570
+ event_count: eventCount,
571
+ total_tokens:
572
+ period.usage.total_tokens.known_sum === 0 && period.usage.total_tokens.unknown > 0
573
+ ? null
574
+ : period.usage.total_tokens.known_sum,
575
+ estimated_usd: usd,
576
+ estimated_brl: brl,
577
+ // Keep the additive factual total visible even if the separate coverage
578
+ // counters report an incomplete financial population. Hiding it as
579
+ // unavailable breaks parity with Operations and discards calculable time.
580
+ // This is never model-inference latency or a token estimate.
581
+ duration_ms: duration.population.known_runs > 0 ? duration.value.known_sum : null,
582
+ duration: duration.value,
583
+ coverage: {
584
+ events: period.runs,
585
+ tokens: knownTokens,
586
+ usd: knownCost,
587
+ brl: knownCost,
588
+ },
589
+ coverage_counts: {
590
+ source: "period_summary",
591
+ granularity: period.events === undefined ? "unavailable" : "event",
592
+ events: period.events?.known_sum ?? null,
593
+ tokens: null,
594
+ usd: null,
595
+ brl: null,
596
+ metrics: {
597
+ duration: duration.population,
598
+ tokens: runPopulation(period.runs, knownTokens),
599
+ usd: runPopulation(period.runs, knownCost),
600
+ brl: runPopulation(period.runs, knownCost),
601
+ },
602
+ },
603
+ };
604
+ }
605
+
606
+ function mergePeriodRows(rows: readonly CostGroupRow[], prefixLength: number): CostGroupRow[] {
607
+ const groups = new Map<string, CostGroupRow[]>();
608
+ for (const row of rows) {
609
+ const key = row.key.slice(0, prefixLength);
610
+ groups.set(key, [...(groups.get(key) ?? []), row]);
611
+ }
612
+ return [...groups]
613
+ .map(([key, values]) => {
614
+ const first = values[0]!;
615
+ const known = values.reduce((total, row) => total + row.duration.known_sum, 0);
616
+ const unknown = values.reduce((total, row) => total + row.duration.unknown, 0);
617
+ const durationPopulation = values.reduce(
618
+ (total, row) => total + (row.coverage_counts?.metrics?.duration?.eligible_runs ?? 0),
619
+ 0,
620
+ );
621
+ const durationKnownRuns = values.reduce(
622
+ (total, row) => total + (row.coverage_counts?.metrics?.duration?.known_runs ?? 0),
623
+ 0,
624
+ );
625
+ const runCount = values.reduce((total, row) => total + row.run_count, 0);
626
+ return {
627
+ ...first,
628
+ key,
629
+ label: key,
630
+ latest_started_at:
631
+ values
632
+ .map((row) => row.latest_started_at)
633
+ .sort()
634
+ .at(-1) ?? first.latest_started_at,
635
+ run_count: runCount,
636
+ task_count: values.reduce((total, row) => total + (row.task_count ?? 0), 0),
637
+ tasksCreated: values.reduce((total, row) => total + (row.tasksCreated ?? 0), 0),
638
+ tasksActive: values.reduce((total, row) => total + (row.tasksActive ?? 0), 0),
639
+ taskDaysActive: values.reduce((total, row) => total + (row.taskDaysActive ?? 0), 0),
640
+ prd_count: values.reduce((total, row) => total + row.prd_count, 0),
641
+ spec_count: values.reduce((total, row) => total + row.spec_count, 0),
642
+ evidence_count: values.reduce((total, row) => total + row.evidence_count, 0),
643
+ test_count: values.reduce((total, row) => total + row.test_count, 0),
644
+ event_count: values.reduce((total, row) => total + row.event_count, 0),
645
+ total_tokens: mergeNullableMetric(values.map((row) => row.total_tokens)),
646
+ estimated_usd: mergeNullableMetric(values.map((row) => row.estimated_usd)),
647
+ estimated_brl: mergeNullableMetric(values.map((row) => row.estimated_brl)),
648
+ // A period duration is factual only if every financial day in its
649
+ // population has an observed source interval. Never promote a
650
+ // partial daily union into a monthly/yearly numeric total.
651
+ duration_ms: unknown === 0 ? known : null,
652
+ duration: {
653
+ known_sum: known,
654
+ unknown,
655
+ complete: unknown === 0,
656
+ coverage_ratio: durationPopulation === 0 ? 1 : durationKnownRuns / durationPopulation,
657
+ },
658
+ coverage: {
659
+ events: values.reduce((total, row) => total + row.coverage.events, 0),
660
+ tokens: values.reduce((total, row) => total + row.coverage.tokens, 0),
661
+ usd: values.reduce((total, row) => total + row.coverage.usd, 0),
662
+ brl: values.reduce((total, row) => total + row.coverage.brl, 0),
663
+ },
664
+ ...(first.coverage_counts === undefined
665
+ ? {}
666
+ : {
667
+ coverage_counts: {
668
+ ...first.coverage_counts,
669
+ metrics: {
670
+ duration: runPopulation(durationPopulation, durationKnownRuns),
671
+ tokens: mergeMetricPopulation(values, "tokens"),
672
+ usd: mergeMetricPopulation(values, "usd"),
673
+ brl: mergeMetricPopulation(values, "brl"),
674
+ },
675
+ },
676
+ }),
677
+ };
678
+ })
679
+ .sort((left, right) => right.key.localeCompare(left.key));
680
+ }
681
+
682
+ function mergeMetricPopulation(
683
+ rows: readonly CostGroupRow[],
684
+ metric: "tokens" | "usd" | "brl",
685
+ ): ReturnType<typeof runPopulation> {
686
+ const populations = rows.map((row) => row.coverage_counts?.metrics?.[metric]);
687
+ return runPopulation(
688
+ populations.reduce((total, population) => total + (population?.eligible_runs ?? 0), 0),
689
+ populations.reduce((total, population) => total + (population?.known_runs ?? 0), 0),
690
+ );
691
+ }
692
+
693
+ /**
694
+ * Cost cards intentionally retain all-invocation count/tokens/cost, but their
695
+ * duration is the same non-overlapping root-execution population as
696
+ * Operations. Missing run metrics stays unavailable rather than borrowing
697
+ * the legacy aggregate (which mixes conversations and Sub-Runs).
698
+ */
699
+ interface DurationSource {
700
+ value: KnownValue;
701
+ population: ReturnType<typeof runPopulation>;
702
+ }
703
+
704
+ function durationByRootExecutionDay(
705
+ runs: readonly NonNullable<CostSummarySource["run_metrics"]>[number][],
706
+ ): Map<string, DurationSource> {
707
+ return sharedRootExecutionDurationByDay(runs) as Map<string, DurationSource>;
708
+ }
709
+
710
+ function averageObservedPostCutoffRootDuration(
711
+ runs: readonly NonNullable<CostSummarySource["run_metrics"]>[number][],
712
+ ): number | null {
713
+ const known = runs.filter(
714
+ (run): run is typeof run & { duration_ms: number } =>
715
+ run.phase === "execution" &&
716
+ run.parent_run_id == null &&
717
+ isAfterLegacyEffortCutoff(run.duration_started_at ?? run.started_at) &&
718
+ run.duration_ms !== null &&
719
+ run.duration_ms >= 0,
720
+ );
721
+ return known.length === 0
722
+ ? null
723
+ : known.reduce((total, run) => total + run.duration_ms, 0) / known.length;
724
+ }
725
+
726
+ function emptyDuration(): DurationSource {
727
+ return {
728
+ value: { known_sum: 0, unknown: 0, complete: true, coverage_ratio: 1 },
729
+ population: runPopulation(0, 0),
730
+ };
731
+ }
732
+
733
+ function inRange(key: string, from: string | null, to: string | null): boolean {
734
+ const dayForBound = (value: string | null) => {
735
+ if (value === null) return null;
736
+ // Direct projection callers can still provide a date-only value. It is a
737
+ // São Paulo calendar label, whereas timestamp bounds need conversion.
738
+ if (/^\d{4}-\d{2}-\d{2}$/.test(value)) return value;
739
+ return saoPauloPeriodKey(value, "day");
740
+ };
741
+ const fromDay = dayForBound(from);
742
+ const toDay = dayForBound(to);
743
+ return (fromDay === null || key >= fromDay) && (toDay === null || key <= toDay);
744
+ }
745
+
746
+ function sumNullable(values: readonly (number | null)[]): number | null {
747
+ const known = values.filter((value): value is number => value !== null);
748
+ return known.length === 0 ? null : known.reduce((total, value) => total + value, 0);
749
+ }
750
+
751
+ function mergeNullableMetric(values: readonly (number | null)[]): number | null {
752
+ return values.some((value) => value === null)
753
+ ? null
754
+ : values.reduce<number>((total, value) => total + (value ?? 0), 0);
755
+ }
756
+
757
+ function knownRuns(eligibleRuns: number, unknownRuns: number): number {
758
+ return Math.max(0, eligibleRuns - unknownRuns);
759
+ }
760
+
761
+ function runPopulation(eligible_runs: number, known_runs: number) {
762
+ return { eligible_runs, known_runs, unknown_runs: eligible_runs - known_runs };
763
+ }
764
+
765
+ function emptyMetric(): UsageMetricProjection {
766
+ return {
767
+ events: 0,
768
+ tokens: { input: null, cached_input: null, output: null, reasoning: null, total: null },
769
+ cost: { usd: null, brl: null },
770
+ coverage: { events: 0, tokens: 0, usd: 0, brl: 0 },
771
+ };
772
+ }
773
+
774
+ function emptyOrigins(): CostMonitorProjection["origins"] {
775
+ const usage = (): UsageProjection => ({
776
+ conversation: emptyMetric(),
777
+ planning: emptyMetric(),
778
+ execution: emptyMetric(),
779
+ total: emptyMetric(),
780
+ new_work: emptyMetric(),
781
+ rework: emptyMetric(),
782
+ });
783
+ return { conversation: usage(), task: usage(), spec: usage(), prd: usage() };
784
+ }