@zaip-ai/cli 2.0.0 → 2.6.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 (460) hide show
  1. package/README.md +33 -14
  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 +30 -25
  5. package/dist/services/adapters.js.map +1 -1
  6. package/dist/services/agent-adapters.js +45 -15
  7. package/dist/services/agent-adapters.js.map +1 -1
  8. package/dist/services/agent-adapters.test.js +13 -7
  9. package/dist/services/agent-adapters.test.js.map +1 -1
  10. package/dist/services/agent-discovery.d.ts +27 -0
  11. package/dist/services/agent-discovery.d.ts.map +1 -0
  12. package/dist/services/agent-discovery.js +73 -0
  13. package/dist/services/agent-discovery.js.map +1 -0
  14. package/dist/services/codex-conversation-lifecycle-hook.d.ts.map +1 -1
  15. package/dist/services/codex-conversation-lifecycle-hook.js +153 -24
  16. package/dist/services/codex-conversation-lifecycle-hook.js.map +1 -1
  17. package/dist/services/codex-pre-tool-hook-template.d.ts.map +1 -1
  18. package/dist/services/codex-pre-tool-hook-template.js +146 -72
  19. package/dist/services/codex-pre-tool-hook-template.js.map +1 -1
  20. package/dist/services/codex-rules.d.ts +1 -1
  21. package/dist/services/codex-rules.d.ts.map +1 -1
  22. package/dist/services/codex-rules.js +3 -3
  23. package/dist/services/codex-subagent-hook-template.d.ts +1 -1
  24. package/dist/services/codex-subagent-hook-template.d.ts.map +1 -1
  25. package/dist/services/codex-subagent-hook-template.js +117 -66
  26. package/dist/services/codex-subagent-hook-template.js.map +1 -1
  27. package/dist/services/install-agents-template.d.ts.map +1 -1
  28. package/dist/services/install-agents-template.js +56 -6
  29. package/dist/services/install-agents-template.js.map +1 -1
  30. package/dist/services/logger.js +1 -1
  31. package/dist/services/logger.js.map +1 -1
  32. package/dist/services/logger.test.js +24 -3
  33. package/dist/services/logger.test.js.map +1 -1
  34. package/dist/services/runtime-template.test.js +138 -1
  35. package/dist/services/runtime-template.test.js.map +1 -1
  36. package/package.json +1 -1
  37. package/templates/.agents/.env.example +9 -3
  38. package/templates/.agents/README-ENG.md +47 -5
  39. package/templates/.agents/README.md +38 -9
  40. package/templates/.agents/architecture/software-architecture.md +1 -59
  41. package/templates/.agents/branding/brandbook.md +3 -0
  42. package/templates/.agents/config/agents/catalog.yaml +40 -28
  43. package/templates/.agents/config/agents/discovery.json +319 -0
  44. package/templates/.agents/config/clients/codex/agents/zaip-agent-analyst.toml +3 -6
  45. package/templates/.agents/config/clients/codex/agents/zaip-agent-auditor.toml +3 -6
  46. package/templates/.agents/config/clients/codex/agents/zaip-agent-backend.toml +4 -7
  47. package/templates/.agents/config/clients/codex/agents/zaip-agent-brand-strategist.toml +6 -8
  48. package/templates/.agents/config/clients/codex/agents/zaip-agent-builder.toml +4 -7
  49. package/templates/.agents/config/clients/codex/agents/zaip-agent-cloud-engineer.toml +13 -13
  50. package/templates/.agents/config/clients/codex/agents/zaip-agent-data-analyst.toml +5 -7
  51. package/templates/.agents/config/clients/codex/agents/zaip-agent-designer.toml +4 -7
  52. package/templates/.agents/config/clients/codex/agents/zaip-agent-finalizer.toml +3 -6
  53. package/templates/.agents/config/clients/codex/agents/zaip-agent-frontend.toml +4 -7
  54. package/templates/.agents/config/clients/codex/agents/zaip-agent-general-operations.toml +6 -8
  55. package/templates/.agents/config/clients/codex/agents/zaip-agent-governance-compliance.toml +3 -6
  56. package/templates/.agents/config/clients/codex/agents/zaip-agent-growth-strategist.toml +6 -8
  57. package/templates/.agents/config/clients/codex/agents/zaip-agent-integrator.toml +3 -6
  58. package/templates/.agents/config/clients/codex/agents/zaip-agent-marketing-analyst.toml +6 -8
  59. package/templates/.agents/config/clients/codex/agents/zaip-agent-orchestrator.toml +4 -5
  60. package/templates/.agents/config/clients/codex/agents/zaip-agent-refactoring-specialist.toml +3 -6
  61. package/templates/.agents/config/clients/codex/agents/zaip-agent-reviewer.toml +3 -6
  62. package/templates/.agents/config/clients/codex/agents/zaip-agent-sales-specialist.toml +6 -8
  63. package/templates/.agents/config/clients/codex/agents/zaip-agent-security-auditor.toml +3 -6
  64. package/templates/.agents/config/clients/codex/agents/zaip-agent-task-executor.toml +4 -7
  65. package/templates/.agents/config/clients/codex/agents/zaip-agent-website-developer.toml +4 -7
  66. package/templates/.agents/config/clients/codex/agents/zaip-agent-writer.toml +3 -6
  67. package/templates/.agents/config/pricing/models.json +57 -33
  68. package/templates/.agents/config/project.yaml +12 -1
  69. package/templates/.agents/dashboard/.zaip-managed.json +378 -98
  70. package/templates/.agents/dashboard/apps/frontend/dist/assets/CostCalculationGuidePage-CGxeQak4.js +1 -0
  71. package/templates/.agents/dashboard/apps/frontend/dist/assets/{DashboardHelpDialog-CYfpYsTr.js → DashboardHelpDialog-tzS7YxYB.js} +173 -47
  72. package/templates/.agents/dashboard/apps/frontend/dist/assets/PricingSettingsDialog-DEbCi1gP.js +1 -0
  73. package/templates/.agents/dashboard/apps/frontend/dist/assets/ProjectSettingsPage-1L7Qw-Gq.js +3 -0
  74. package/templates/.agents/dashboard/apps/frontend/dist/assets/ProjectSettingsPage-EInWr641.css +1 -0
  75. package/templates/.agents/dashboard/apps/frontend/dist/assets/TraceabilityWorkspace-t1Om0Abw.js +1 -0
  76. package/templates/.agents/dashboard/apps/frontend/dist/assets/cost-monitor-B6aZfo5f.js +68 -0
  77. package/templates/.agents/dashboard/apps/frontend/dist/assets/{icons-vendor-TPUT2IUt.js → icons-vendor-DiGC-dsJ.js} +1 -1
  78. package/templates/.agents/dashboard/apps/frontend/dist/assets/index-DgTmNHN5.js +2 -0
  79. package/templates/.agents/dashboard/apps/frontend/dist/assets/{react-vendor-Ct48XHGL.js → react-vendor-kPO6yNed.js} +1 -1
  80. package/templates/.agents/dashboard/apps/frontend/dist/assets/rolldown-runtime-Bh1tDfsg.js +1 -0
  81. package/templates/.agents/dashboard/apps/frontend/dist/assets/traceability-DQpKX9c1.js +1 -0
  82. package/templates/.agents/dashboard/apps/frontend/dist/index.html +6 -6
  83. package/templates/.agents/dashboard/apps/frontend/package.json +1 -1
  84. package/templates/.agents/dashboard/apps/frontend/src/App.tsx +3 -1264
  85. package/templates/.agents/dashboard/apps/frontend/src/AppDashboardContent.tsx +363 -0
  86. package/templates/.agents/dashboard/apps/frontend/src/ProjectSettingsPage.dom.test.ts +99 -0
  87. package/templates/.agents/dashboard/apps/frontend/src/ProjectSettingsPage.tsx +62 -6
  88. package/templates/.agents/dashboard/apps/frontend/src/ProjectStackEditor.tsx +3 -1
  89. package/templates/.agents/dashboard/apps/frontend/src/__tests__/app-composition-support.ts +7 -0
  90. package/templates/.agents/dashboard/apps/frontend/src/cost-period-refresh.test.ts +9 -7
  91. package/templates/.agents/dashboard/apps/frontend/src/dashboard-api-settings.ts +151 -0
  92. package/templates/.agents/dashboard/apps/frontend/src/dashboard-api.ts +28 -153
  93. package/templates/.agents/dashboard/apps/frontend/src/dashboard-app-shell.tsx +33 -0
  94. package/templates/.agents/dashboard/apps/frontend/src/dashboard-cost-facts.ts +30 -0
  95. package/templates/.agents/dashboard/apps/frontend/src/dashboard-project-overview.ts +7 -1
  96. package/templates/.agents/dashboard/apps/frontend/src/dashboard-retry.ts +17 -0
  97. package/templates/.agents/dashboard/apps/frontend/src/dashboard-setup-route.ts +29 -0
  98. package/templates/.agents/dashboard/apps/frontend/src/dashboard-view-actions.ts +66 -0
  99. package/templates/.agents/dashboard/apps/frontend/src/operations-period-render.test.ts +3 -2
  100. package/templates/.agents/dashboard/apps/frontend/src/overview-status-page.test.ts +2 -2
  101. package/templates/.agents/dashboard/apps/frontend/src/project-installation-status.test.ts +48 -0
  102. package/templates/.agents/dashboard/apps/frontend/src/project-installation-status.ts +29 -0
  103. package/templates/.agents/dashboard/apps/frontend/src/project-settings-page.css +68 -0
  104. package/templates/.agents/dashboard/apps/frontend/src/project-settings.test.ts +2 -2
  105. package/templates/.agents/dashboard/apps/frontend/src/sao-paulo-day-rollover.test.ts +36 -0
  106. package/templates/.agents/dashboard/apps/frontend/src/sao-paulo-day-rollover.ts +30 -0
  107. package/templates/.agents/dashboard/apps/frontend/src/snapshot-banner-semantics.test.ts +2 -5
  108. package/templates/.agents/dashboard/apps/frontend/src/snapshot-coherence.test.ts +30 -19
  109. package/templates/.agents/dashboard/apps/frontend/src/use-app-effects.ts +9 -1
  110. package/templates/.agents/dashboard/apps/frontend/src/use-app-trace-task-pagination.ts +77 -0
  111. package/templates/.agents/dashboard/apps/frontend/src/use-app-work-board.ts +397 -0
  112. package/templates/.agents/dashboard/apps/frontend/src/use-dashboard-app-model.tsx +782 -0
  113. package/templates/.agents/dashboard/apps/frontend/src/use-snapshot-notice.tsx +49 -0
  114. package/templates/.agents/dashboard/modules/cost-monitor/package.json +1 -1
  115. package/templates/.agents/dashboard/modules/cost-monitor/src/react/CostDeveloperPanelSlot.tsx +16 -0
  116. package/templates/.agents/dashboard/modules/cost-monitor/src/react/CostGroupsTable.tsx +459 -0
  117. package/templates/.agents/dashboard/modules/cost-monitor/src/react/CostMonitorPage.test.ts +27 -17
  118. package/templates/.agents/dashboard/modules/cost-monitor/src/react/CostMonitorPage.tsx +62 -186
  119. package/templates/.agents/dashboard/modules/cost-monitor/src/react/CostMonitorRunDialog.tsx +20 -0
  120. package/templates/.agents/dashboard/modules/cost-monitor/src/react/CostTables-hides-calls-that-have-no-collected.test.ts +80 -0
  121. package/templates/.agents/dashboard/modules/cost-monitor/src/react/CostTables-keeps-legacy-codex-identity-fields-blank.test.ts +455 -0
  122. package/templates/.agents/dashboard/modules/cost-monitor/src/react/CostTables.test.ts +18 -525
  123. package/templates/.agents/dashboard/modules/cost-monitor/src/react/CostTables.tsx +32 -508
  124. package/templates/.agents/dashboard/modules/cost-monitor/src/react/cost-monitor-export-sources.ts +74 -0
  125. package/templates/.agents/dashboard/modules/cost-monitor/src/react/cost-monitor-page-actions.ts +19 -0
  126. package/templates/.agents/dashboard/modules/cost-monitor/src/react/cost-monitor-page-selectors.ts +49 -0
  127. package/templates/.agents/dashboard/modules/cost-monitor/src/react/cost-table-formatters.ts +115 -0
  128. package/templates/.agents/dashboard/modules/cost-monitor/src/server/build-cost-monitor-projection.test-fixtures.ts +2 -0
  129. package/templates/.agents/dashboard/modules/operations/package.json +1 -1
  130. package/templates/.agents/dashboard/modules/operations/src/contracts.ts +4 -0
  131. package/templates/.agents/dashboard/modules/operations/src/react/EntityTableBadges.tsx +34 -0
  132. package/templates/.agents/dashboard/modules/operations/src/react/EntityTables.tsx +8 -38
  133. package/templates/.agents/dashboard/modules/operations/src/react/OperationsOverview-keeps-structure-classes-mutually-exclusive.test.ts +243 -0
  134. package/templates/.agents/dashboard/modules/operations/src/react/OperationsOverview.test.ts +27 -275
  135. package/templates/.agents/dashboard/modules/operations/src/react/OperationsOverview.tsx +70 -247
  136. package/templates/.agents/dashboard/modules/operations/src/react/OperationsOverviewCharts.tsx +171 -0
  137. package/templates/.agents/dashboard/modules/operations/src/react/OperationsOverviewPanels.tsx +64 -0
  138. package/templates/.agents/dashboard/modules/operations/src/react/OperationsPage.tsx +4 -3
  139. package/templates/.agents/dashboard/modules/operations/src/react/PrdDocumentDialog.test.tsx +2 -1
  140. package/templates/.agents/dashboard/modules/operations/src/react/manual-work-priority.test.ts +2 -1
  141. package/templates/.agents/dashboard/modules/operations/src/react/operations-coverage-toast.test.ts +6 -2
  142. package/templates/.agents/dashboard/modules/operations/src/react/operations-overview-period-filter.test.ts +6 -14
  143. package/templates/.agents/dashboard/modules/operations/src/react/operations-overview.status-cards.test.ts +3 -1
  144. package/templates/.agents/dashboard/modules/operations/src/react/operations-page-contract.ts +2 -0
  145. package/templates/.agents/dashboard/modules/operations/src/react/overview-metric-format.ts +32 -0
  146. package/templates/.agents/dashboard/modules/traceability/package.json +1 -1
  147. package/templates/.agents/dashboard/packages/branding/package.json +1 -1
  148. package/templates/.agents/dashboard/packages/branding/src/index.ts +1 -1
  149. package/templates/.agents/dashboard/packages/contracts/package.json +1 -1
  150. package/templates/.agents/dashboard/packages/data-export/package.json +1 -1
  151. package/templates/.agents/dashboard/packages/local-runtime/dist/server.cjs +1458 -1458
  152. package/templates/.agents/dashboard/packages/local-runtime/dist/sqlite-read-model.cjs +1425 -1425
  153. package/templates/.agents/dashboard/packages/local-runtime/package.json +2 -1
  154. package/templates/.agents/dashboard/packages/local-runtime/scripts/build-sqlite-runtime.mjs +7 -3
  155. package/templates/.agents/dashboard/packages/local-runtime/server.mjs +1458 -1459
  156. package/templates/.agents/dashboard/packages/local-runtime/src/active-codex-telemetry.ts +25 -0
  157. package/templates/.agents/dashboard/packages/local-runtime/src/agent-catalog-settings.test.ts +1 -1
  158. package/templates/.agents/dashboard/packages/local-runtime/src/project-settings.test.ts +53 -8
  159. package/templates/.agents/dashboard/packages/local-runtime/src/project-settings.ts +79 -24
  160. package/templates/.agents/dashboard/packages/local-runtime/src/projection-refresh-diagnostics.ts +35 -0
  161. package/templates/.agents/dashboard/packages/local-runtime/src/server-costs-routes.ts +168 -0
  162. package/templates/.agents/dashboard/packages/local-runtime/src/server-dual-reads-manifest-summaries-without-losing.test.ts +344 -0
  163. package/templates/.agents/dashboard/packages/local-runtime/src/server-http-contracts.ts +31 -0
  164. package/templates/.agents/dashboard/packages/local-runtime/src/server-operations-routes.ts +345 -0
  165. package/templates/.agents/dashboard/packages/local-runtime/src/server-read-projections.ts +461 -0
  166. package/templates/.agents/dashboard/packages/local-runtime/src/server-reconciliation-refresh.test.ts +78 -0
  167. package/templates/.agents/dashboard/packages/local-runtime/src/server-route-context.ts +13 -0
  168. package/templates/.agents/dashboard/packages/local-runtime/src/server-snapshot-synchronization.test.ts +18 -0
  169. package/templates/.agents/dashboard/packages/local-runtime/src/server-snapshot-synchronization.ts +19 -3
  170. package/templates/.agents/dashboard/packages/local-runtime/src/server-snapshot.test.ts +22 -21
  171. package/templates/.agents/dashboard/packages/local-runtime/src/server-sqlite-task-trace.ts +1 -1
  172. package/templates/.agents/dashboard/packages/local-runtime/src/server-sqlite-view-allowlist.test.ts +25 -0
  173. package/templates/.agents/dashboard/packages/local-runtime/src/server-trace-routes.ts +64 -0
  174. package/templates/.agents/dashboard/packages/local-runtime/src/server-work-reconciliation.test.ts +2 -30
  175. package/templates/.agents/dashboard/packages/local-runtime/src/server-work-reconciliation.ts +6 -23
  176. package/templates/.agents/dashboard/packages/local-runtime/src/server.test-fixtures.ts +1 -1
  177. package/templates/.agents/dashboard/packages/local-runtime/src/server.test.ts +2 -330
  178. package/templates/.agents/dashboard/packages/local-runtime/src/server.ts +73 -1060
  179. package/templates/.agents/dashboard/packages/local-runtime/src/sqlite-materialize-first-fold.ts +78 -0
  180. package/templates/.agents/dashboard/packages/local-runtime/src/sqlite-materialize-projections.ts +561 -0
  181. package/templates/.agents/dashboard/packages/local-runtime/src/sqlite-materialize-runs.ts +600 -0
  182. package/templates/.agents/dashboard/packages/local-runtime/src/sqlite-metric-contract.test.ts +1 -1
  183. package/templates/.agents/dashboard/packages/local-runtime/src/sqlite-query-agent-dimension.ts +269 -0
  184. package/templates/.agents/dashboard/packages/local-runtime/src/sqlite-query-context.ts +32 -0
  185. package/templates/.agents/dashboard/packages/local-runtime/src/sqlite-query-entity-group.ts +244 -0
  186. package/templates/.agents/dashboard/packages/local-runtime/src/sqlite-query-filtered-dimension.ts +292 -0
  187. package/templates/.agents/dashboard/packages/local-runtime/src/sqlite-query-financial.ts +547 -0
  188. package/templates/.agents/dashboard/packages/local-runtime/src/sqlite-query-model-dimension.ts +360 -0
  189. package/templates/.agents/dashboard/packages/local-runtime/src/sqlite-query-provider-dimension.ts +169 -0
  190. package/templates/.agents/dashboard/packages/local-runtime/src/sqlite-query-summary.ts +475 -0
  191. package/templates/.agents/dashboard/packages/local-runtime/src/sqlite-query-temporal-dimension.ts +132 -0
  192. package/templates/.agents/dashboard/packages/local-runtime/src/sqlite-query-timing.ts +299 -0
  193. package/templates/.agents/dashboard/packages/local-runtime/src/sqlite-query-view-page.ts +692 -0
  194. package/templates/.agents/dashboard/packages/local-runtime/src/sqlite-read-model-counts-every-root-execution-day-returns.test.ts +739 -0
  195. package/templates/.agents/dashboard/packages/local-runtime/src/sqlite-read-model-does-not-convert-delayed-historical-finalizer.test.ts +706 -0
  196. package/templates/.agents/dashboard/packages/local-runtime/src/sqlite-read-model-filesystem.ts +748 -0
  197. package/templates/.agents/dashboard/packages/local-runtime/src/sqlite-read-model-first-fold-types.ts +1 -1
  198. package/templates/.agents/dashboard/packages/local-runtime/src/sqlite-read-model-keeps-orphan-telemetry-out-kanban-without.test.ts +710 -0
  199. package/templates/.agents/dashboard/packages/local-runtime/src/sqlite-read-model-marks-token-cost-telemetry-unavailable-when.test.ts +618 -0
  200. package/templates/.agents/dashboard/packages/local-runtime/src/sqlite-read-model-rebuild.ts +755 -0
  201. package/templates/.agents/dashboard/packages/local-runtime/src/sqlite-read-model-rebuilds-disposable-snapshot-serves-zaip-records.test.ts +276 -0
  202. package/templates/.agents/dashboard/packages/local-runtime/src/sqlite-read-model-schema.ts +193 -0
  203. package/templates/.agents/dashboard/packages/local-runtime/src/sqlite-read-model-types.ts +123 -0
  204. package/templates/.agents/dashboard/packages/local-runtime/src/sqlite-read-model.test.ts +1 -2805
  205. package/templates/.agents/dashboard/packages/local-runtime/src/sqlite-read-model.ts +17 -6930
  206. package/templates/.agents/dashboard/packages/local-runtime/src/sqlite-schema-base-views.ts +385 -0
  207. package/templates/.agents/dashboard/packages/local-runtime/src/sqlite-schema-dashboard-views.ts +412 -0
  208. package/templates/.agents/dashboard/packages/local-runtime/src/work-priority-contract.test.ts +4 -3
  209. package/templates/.agents/dashboard/packages/local-runtime/start-dashboard-build.mjs +195 -0
  210. package/templates/.agents/dashboard/packages/local-runtime/start-dashboard-lifecycle.test.mjs +2 -7
  211. package/templates/.agents/dashboard/packages/local-runtime/start-dashboard-logging.mjs +35 -0
  212. package/templates/.agents/dashboard/packages/local-runtime/start-dashboard-navigation.mjs +114 -0
  213. package/templates/.agents/dashboard/packages/local-runtime/start-dashboard-paths.mjs +90 -0
  214. package/templates/.agents/dashboard/packages/local-runtime/start-dashboard.mjs +89 -418
  215. package/templates/.agents/dashboard/packages/local-runtime/start-dashboard.test.mjs +22 -12
  216. package/templates/.agents/dashboard/packages/ui/package.json +1 -1
  217. package/templates/.agents/dashboard/tests/e2e/package.json +1 -1
  218. package/templates/.agents/dashboard/tests/e2e/playwright.config.ts +4 -1
  219. package/templates/.agents/design/.zaip-managed.json +5 -5
  220. package/templates/.agents/design/DESIGN.md +2 -186
  221. package/templates/.agents/design/README.md +12 -2
  222. package/templates/.agents/design/apps/catalog/package.json +1 -1
  223. package/templates/.agents/design/packages/local-runtime/package.json +1 -1
  224. package/templates/.agents/growth/strategy.md +3 -0
  225. package/templates/.agents/marketing/strategy.md +3 -0
  226. package/templates/.agents/requirements/autonomous-assurance.md +2 -1
  227. package/templates/.agents/requirements/cloud-hostinger-autonomy.md +1 -1
  228. package/templates/.agents/requirements/comparative-audit.md +1 -1
  229. package/templates/.agents/requirements/context-engine.md +1 -1
  230. package/templates/.agents/requirements/cost-observability.md +1 -1
  231. package/templates/.agents/requirements/dashboard-launch.md +1 -1
  232. package/templates/.agents/requirements/data-export.md +1 -1
  233. package/templates/.agents/requirements/design-system.md +13 -4
  234. package/templates/.agents/requirements/execution-engine.md +1 -1
  235. package/templates/.agents/requirements/kanban-dashboard.md +1 -1
  236. package/templates/.agents/requirements/model-orchestration.md +15 -5
  237. package/templates/.agents/requirements/public-distribution.md +5 -3
  238. package/templates/.agents/requirements/software-architecture.md +1 -1
  239. package/templates/.agents/requirements/strategic-improvements.md +1 -1
  240. package/templates/.agents/requirements/work-lifecycle.md +3 -3
  241. package/templates/.agents/requirements/zaip-strategic-95.md +1 -1
  242. package/templates/.agents/rules/architecture.md +2 -0
  243. package/templates/.agents/rules/astra-diagnostic.md +20 -0
  244. package/templates/.agents/rules/autonomy-decision.md +3 -1
  245. package/templates/.agents/rules/cloud-hostinger-autonomy.md +2 -0
  246. package/templates/.agents/rules/context.md +2 -1
  247. package/templates/.agents/rules/core.md +9 -14
  248. package/templates/.agents/rules/design-system-central-contract.md +17 -0
  249. package/templates/.agents/rules/evolution.md +3 -1
  250. package/templates/.agents/rules/frontend-lite.md +3 -1
  251. package/templates/.agents/rules/local-sqlite-storage.md +2 -2
  252. package/templates/.agents/rules/meta-mcp.md +4 -1
  253. package/templates/.agents/rules/model-orchestration.md +1 -1
  254. package/templates/.agents/rules/run-lifecycle-closure.md +7 -5
  255. package/templates/.agents/rules/security.md +3 -1
  256. package/templates/.agents/rules/specialist-routing.md +6 -2
  257. package/templates/.agents/rules/text-writing-utf8.md +1 -1
  258. package/templates/.agents/rules/workflow.md +7 -5
  259. package/templates/.agents/runtime/VERSION +1 -1
  260. package/templates/.agents/runtime/bin/zaip.mjs +534 -266
  261. package/templates/.agents/runtime/checksums.sha256 +6 -6
  262. package/templates/.agents/runtime/manifest.json +1 -1
  263. package/templates/.agents/runtime/pnpm-lock.sha256 +1 -1
  264. package/templates/.agents/runtime/provenance.json +5 -5
  265. package/templates/.agents/runtime/sbom.cdx.json +1 -1
  266. package/templates/.agents/sales/playbook.md +3 -0
  267. package/templates/.agents/skills/zaip-aios/SKILL.md +5 -3
  268. package/templates/.agents/skills/zaip-skill-adapt-stack/SKILL.md +1 -0
  269. package/templates/.agents/skills/zaip-skill-api-contracts/SKILL.md +14 -0
  270. package/templates/.agents/skills/zaip-skill-api-contracts/agents/openai.yaml +4 -0
  271. package/templates/.agents/skills/zaip-skill-application-observability/SKILL.md +15 -0
  272. package/templates/.agents/skills/zaip-skill-application-observability/agents/openai.yaml +4 -0
  273. package/templates/.agents/skills/zaip-skill-application-observability/references/signal-design.md +3 -0
  274. package/templates/.agents/skills/zaip-skill-application-readiness/SKILL.md +15 -0
  275. package/templates/.agents/skills/zaip-skill-application-readiness/agents/openai.yaml +4 -0
  276. package/templates/.agents/skills/zaip-skill-application-readiness/references/evidence-matrix.md +3 -0
  277. package/templates/.agents/skills/zaip-skill-architecture-design/SKILL.md +14 -0
  278. package/templates/.agents/skills/zaip-skill-architecture-design/agents/openai.yaml +4 -0
  279. package/templates/.agents/skills/zaip-skill-async-jobs/SKILL.md +14 -0
  280. package/templates/.agents/skills/zaip-skill-async-jobs/agents/openai.yaml +4 -0
  281. package/templates/.agents/skills/zaip-skill-auth-tenancy/SKILL.md +15 -0
  282. package/templates/.agents/skills/zaip-skill-auth-tenancy/agents/openai.yaml +4 -0
  283. package/templates/.agents/skills/zaip-skill-auth-tenancy/references/data-access-paths.md +9 -0
  284. package/templates/.agents/skills/zaip-skill-auth-tenancy/references/worker-scenario.md +5 -0
  285. package/templates/.agents/skills/zaip-skill-auth-tenancy/scripts/worker-contract.test.mjs +27 -0
  286. package/templates/.agents/skills/zaip-skill-author-skills/SKILL.md +2 -0
  287. package/templates/.agents/skills/zaip-skill-author-skills/references/engineering-skill-index.md +9 -0
  288. package/templates/.agents/skills/zaip-skill-author-skills/scripts/audit-skill-catalog.mjs +5 -3
  289. package/templates/.agents/skills/zaip-skill-author-skills/scripts/author-skill-scripts.test.mjs +27 -0
  290. package/templates/.agents/skills/zaip-skill-backend/SKILL.md +4 -0
  291. package/templates/.agents/skills/zaip-skill-backend/references/deployment-environments.md +75 -0
  292. package/templates/.agents/skills/zaip-skill-backend/references/supabase-migration-contract.md +23 -0
  293. package/templates/.agents/skills/zaip-skill-brand-governance/SKILL.md +2 -0
  294. package/templates/.agents/skills/zaip-skill-cache-strategy/SKILL.md +14 -0
  295. package/templates/.agents/skills/zaip-skill-cache-strategy/agents/openai.yaml +4 -0
  296. package/templates/.agents/skills/zaip-skill-change/SKILL.md +1 -1
  297. package/templates/.agents/skills/zaip-skill-cloud-engineering/SKILL.md +7 -0
  298. package/templates/.agents/skills/zaip-skill-cloudflare-github-deploy/SKILL.md +37 -0
  299. package/templates/.agents/skills/zaip-skill-cloudflare-github-deploy/agents/openai.yaml +6 -0
  300. package/templates/.agents/skills/zaip-skill-cloudflare-github-deploy/references/workers-static-assets.md +26 -0
  301. package/templates/.agents/skills/zaip-skill-cloudflare-github-deploy/references/workflow-templates.md +71 -0
  302. package/templates/.agents/skills/zaip-skill-cloudflare-github-deploy/scripts/cloudflare-github-deploy-contract.test.mjs +77 -0
  303. package/templates/.agents/skills/zaip-skill-config/SKILL.md +21 -11
  304. package/templates/.agents/skills/zaip-skill-config/agents/openai.yaml +2 -2
  305. package/templates/.agents/skills/zaip-skill-container-runtime/SKILL.md +14 -0
  306. package/templates/.agents/skills/zaip-skill-container-runtime/agents/openai.yaml +4 -0
  307. package/templates/.agents/skills/zaip-skill-context/SKILL.md +6 -1
  308. package/templates/.agents/skills/zaip-skill-context/references/prd-spec-task-handoff.md +10 -0
  309. package/templates/.agents/skills/zaip-skill-context/references/rule-selection.md +20 -0
  310. package/templates/.agents/skills/zaip-skill-cqrs/SKILL.md +1 -0
  311. package/templates/.agents/skills/zaip-skill-cybersecurity/SKILL.md +18 -0
  312. package/templates/.agents/skills/zaip-skill-cybersecurity/agents/openai.yaml +4 -0
  313. package/templates/.agents/skills/zaip-skill-cybersecurity/references/audit-contract.md +94 -0
  314. package/templates/.agents/skills/zaip-skill-cybersecurity/scripts/score-audit.mjs +185 -0
  315. package/templates/.agents/skills/zaip-skill-cybersecurity/scripts/score-audit.test.mjs +101 -0
  316. package/templates/.agents/skills/zaip-skill-data-modeling/SKILL.md +14 -0
  317. package/templates/.agents/skills/zaip-skill-data-modeling/agents/openai.yaml +4 -0
  318. package/templates/.agents/skills/zaip-skill-database-migrations/SKILL.md +20 -0
  319. package/templates/.agents/skills/zaip-skill-database-migrations/agents/openai.yaml +4 -0
  320. package/templates/.agents/skills/zaip-skill-database-migrations/references/manual-mode.md +15 -0
  321. package/templates/.agents/skills/zaip-skill-database-migrations/references/promotion-example.md +5 -0
  322. package/templates/.agents/skills/zaip-skill-database-migrations/scripts/export-manual-sql.mjs +145 -0
  323. package/templates/.agents/skills/zaip-skill-database-migrations/scripts/export-manual-sql.test.mjs +178 -0
  324. package/templates/.agents/skills/zaip-skill-dependency-upgrade/SKILL.md +14 -0
  325. package/templates/.agents/skills/zaip-skill-dependency-upgrade/agents/openai.yaml +4 -0
  326. package/templates/.agents/skills/zaip-skill-deployment-pipeline/SKILL.md +15 -0
  327. package/templates/.agents/skills/zaip-skill-deployment-pipeline/agents/openai.yaml +4 -0
  328. package/templates/.agents/skills/zaip-skill-deployment-pipeline/references/runtime-shapes.md +3 -0
  329. package/templates/.agents/skills/zaip-skill-design-system/SKILL.md +20 -9
  330. package/templates/.agents/skills/zaip-skill-dev-environment/SKILL.md +14 -0
  331. package/templates/.agents/skills/zaip-skill-dev-environment/agents/openai.yaml +4 -0
  332. package/templates/.agents/skills/zaip-skill-dev-environment/references/inventory-contract.md +7 -0
  333. package/templates/.agents/skills/zaip-skill-dev-environment/scripts/inventory.mjs +77 -0
  334. package/templates/.agents/skills/zaip-skill-disaster-recovery/SKILL.md +15 -0
  335. package/templates/.agents/skills/zaip-skill-disaster-recovery/agents/openai.yaml +4 -0
  336. package/templates/.agents/skills/zaip-skill-disaster-recovery/references/recovery-scope.md +3 -0
  337. package/templates/.agents/skills/zaip-skill-execution/SKILL.md +5 -3
  338. package/templates/.agents/skills/zaip-skill-execution/references/correction-cycle.md +7 -0
  339. package/templates/.agents/skills/zaip-skill-execution/references/runtime-governance.md +13 -0
  340. package/templates/.agents/skills/zaip-skill-external-integrations/SKILL.md +14 -0
  341. package/templates/.agents/skills/zaip-skill-external-integrations/agents/openai.yaml +4 -0
  342. package/templates/.agents/skills/zaip-skill-frontend/SKILL.md +4 -0
  343. package/templates/.agents/skills/zaip-skill-frontend-componentization/SKILL.md +44 -0
  344. package/templates/.agents/skills/zaip-skill-frontend-componentization/agents/openai.yaml +4 -0
  345. package/templates/.agents/skills/zaip-skill-frontend-data-flows/SKILL.md +14 -0
  346. package/templates/.agents/skills/zaip-skill-frontend-data-flows/agents/openai.yaml +4 -0
  347. package/templates/.agents/skills/zaip-skill-general-operations/SKILL.md +8 -7
  348. package/templates/.agents/skills/zaip-skill-general-operations/references/extended-workflow.md +7 -0
  349. package/templates/.agents/skills/zaip-skill-github-actions-setup/SKILL.md +36 -0
  350. package/templates/.agents/skills/zaip-skill-github-actions-setup/agents/openai.yaml +4 -0
  351. package/templates/.agents/skills/zaip-skill-github-actions-setup/references/cloudflare-pages.md +33 -0
  352. package/templates/.agents/skills/zaip-skill-github-actions-setup/references/github.md +63 -0
  353. package/templates/.agents/skills/zaip-skill-github-actions-setup/references/hostinger-vps.md +55 -0
  354. package/templates/.agents/skills/zaip-skill-github-actions-setup/references/npm.md +30 -0
  355. package/templates/.agents/skills/zaip-skill-github-actions-setup/scripts/check-skill.mjs +55 -0
  356. package/templates/.agents/skills/zaip-skill-github-actions-setup/scripts/verify-cloudflare.mjs +61 -0
  357. package/templates/.agents/skills/zaip-skill-github-actions-setup/scripts/verify-cloudflare.test.mjs +128 -0
  358. package/templates/.agents/skills/zaip-skill-github-actions-setup/scripts/verify-ssh.integration.test.mjs +106 -0
  359. package/templates/.agents/skills/zaip-skill-github-deploy/SKILL.md +43 -76
  360. package/templates/.agents/skills/zaip-skill-github-deploy/references/deployment-workflow.md +131 -0
  361. package/templates/.agents/skills/zaip-skill-github-deploy/references/github-release-workflow-template.md +31 -0
  362. package/templates/.agents/skills/zaip-skill-github-deploy/references/release-gate-matrix.md +24 -0
  363. package/templates/.agents/skills/zaip-skill-github-deploy/references/release-identity.md +44 -0
  364. package/templates/.agents/skills/zaip-skill-github-deploy/references/release-notes.md +134 -0
  365. package/templates/.agents/skills/zaip-skill-github-deploy/scripts/consumer-release-preparation.mjs +389 -0
  366. package/templates/.agents/skills/zaip-skill-github-deploy/scripts/consumer-release-preparation.test.mjs +134 -0
  367. package/templates/.agents/skills/zaip-skill-github-deploy/scripts/github-deploy-contract.test.mjs +25 -2
  368. package/templates/.agents/skills/zaip-skill-github-deploy/scripts/github-readiness-api.test.mjs +134 -0
  369. package/templates/.agents/skills/zaip-skill-github-deploy/scripts/github-readiness.mjs +98 -0
  370. package/templates/.agents/skills/zaip-skill-github-deploy/scripts/github-readiness.test.mjs +25 -0
  371. package/templates/.agents/skills/zaip-skill-github-deploy/scripts/install-github-readiness-workflow.mjs +159 -0
  372. package/templates/.agents/skills/zaip-skill-github-deploy/scripts/install-github-readiness-workflow.test.mjs +160 -0
  373. package/templates/.agents/skills/zaip-skill-github-deploy/scripts/preflight.mjs +149 -12
  374. package/templates/.agents/skills/zaip-skill-github-deploy/scripts/preflight.test.mjs +64 -5
  375. package/templates/.agents/skills/zaip-skill-github-deploy/scripts/release-notes-coverage.test.mjs +126 -0
  376. package/templates/.agents/skills/zaip-skill-github-deploy/scripts/resolve-release-identity.mjs +78 -0
  377. package/templates/.agents/skills/zaip-skill-github-deploy/scripts/resolve-release-identity.test.mjs +51 -0
  378. package/templates/.agents/skills/zaip-skill-github-deploy/scripts/validate-release-notes.mjs +184 -0
  379. package/templates/.agents/skills/zaip-skill-github-deploy/scripts/validate-release-notes.test.mjs +109 -0
  380. package/templates/.agents/skills/zaip-skill-github-setup/SKILL.md +5 -0
  381. package/templates/.agents/skills/zaip-skill-github-setup-ssh-folder/SKILL.md +54 -0
  382. package/templates/.agents/skills/zaip-skill-github-setup-ssh-folder/agents/openai.yaml +4 -0
  383. package/templates/.agents/skills/zaip-skill-github-setup-ssh-folder/assets/.env.example +9 -0
  384. package/templates/.agents/skills/zaip-skill-github-setup-ssh-folder/references/operational-procedure.md +137 -0
  385. package/templates/.agents/skills/zaip-skill-growth-strategy-revops/SKILL.md +8 -18
  386. package/templates/.agents/skills/zaip-skill-growth-strategy-revops/references/extended-workflow.md +21 -0
  387. package/templates/.agents/skills/zaip-skill-hostinger-cloudflare-terraform/SKILL.md +18 -10
  388. package/templates/.agents/skills/zaip-skill-hostinger-cloudflare-terraform/agents/openai.yaml +3 -4
  389. package/templates/.agents/skills/zaip-skill-hostinger-cloudflare-terraform/references/aws-cli-terraform.md +62 -0
  390. package/templates/.agents/skills/zaip-skill-hostinger-cloudflare-terraform/references/guia-iniciante-hostinger-vps.md +183 -0
  391. package/templates/.agents/skills/zaip-skill-marketing/SKILL.md +8 -13
  392. package/templates/.agents/skills/zaip-skill-marketing/references/extended-workflow.md +16 -0
  393. package/templates/.agents/skills/zaip-skill-meta-ads-setup/SKILL.md +2 -0
  394. package/templates/.agents/skills/zaip-skill-meta-token-onboarding/SKILL.md +17 -0
  395. package/templates/.agents/skills/zaip-skill-meta-token-onboarding/agents/openai.yaml +4 -0
  396. package/templates/.agents/skills/zaip-skill-meta-token-onboarding/references/onboarding-manual.md +96 -0
  397. package/templates/.agents/skills/zaip-skill-module-scaffold/SKILL.md +14 -0
  398. package/templates/.agents/skills/zaip-skill-module-scaffold/agents/openai.yaml +4 -0
  399. package/templates/.agents/skills/zaip-skill-module-scaffold/references/scaffold-contract.md +9 -0
  400. package/templates/.agents/skills/zaip-skill-module-scaffold/scripts/helpers.test.mjs +121 -0
  401. package/templates/.agents/skills/zaip-skill-module-scaffold/scripts/scaffold.mjs +169 -0
  402. package/templates/.agents/skills/zaip-skill-move-prd/SKILL.md +1 -1
  403. package/templates/.agents/skills/zaip-skill-move-spec/SKILL.md +1 -1
  404. package/templates/.agents/skills/zaip-skill-performance-engineering/SKILL.md +14 -0
  405. package/templates/.agents/skills/zaip-skill-performance-engineering/agents/openai.yaml +4 -0
  406. package/templates/.agents/skills/zaip-skill-prd/SKILL.md +1 -1
  407. package/templates/.agents/skills/zaip-skill-reconcile-telemetry/scripts/reconcile-local-telemetry.mjs +1 -0
  408. package/templates/.agents/skills/zaip-skill-reconcile-telemetry/scripts/reconcile-telemetry-lib.mjs +26 -9
  409. package/templates/.agents/skills/zaip-skill-reconcile-telemetry/scripts/reconcile-telemetry-lib.test.mjs +39 -13
  410. package/templates/.agents/skills/zaip-skill-reconcile-telemetry/scripts/reconcile-telemetry-remeasurement.mjs +1 -0
  411. package/templates/.agents/skills/zaip-skill-refactor-landing-page/SKILL.md +66 -0
  412. package/templates/.agents/skills/zaip-skill-refactor-landing-page/agents/openai.yaml +4 -0
  413. package/templates/.agents/skills/zaip-skill-refactor-landing-page/references/behavioral-dry-run.md +23 -0
  414. package/templates/.agents/skills/zaip-skill-release-qualification/SKILL.md +44 -1
  415. package/templates/.agents/skills/zaip-skill-release-qualification/references/local-preparation.md +98 -0
  416. package/templates/.agents/skills/zaip-skill-review/SKILL.md +1 -0
  417. package/templates/.agents/skills/zaip-skill-rules/SKILL.md +3 -3
  418. package/templates/.agents/skills/zaip-skill-sales-methodology/SKILL.md +9 -17
  419. package/templates/.agents/skills/zaip-skill-sales-methodology/references/extended-workflow.md +20 -0
  420. package/templates/.agents/skills/zaip-skill-setup/SKILL.md +22 -21
  421. package/templates/.agents/skills/zaip-skill-setup/agents/openai.yaml +2 -2
  422. package/templates/.agents/skills/zaip-skill-spec/SKILL.md +3 -2
  423. package/templates/.agents/skills/zaip-skill-storage-uploads/SKILL.md +14 -0
  424. package/templates/.agents/skills/zaip-skill-storage-uploads/agents/openai.yaml +4 -0
  425. package/templates/.agents/skills/zaip-skill-systematic-debugging/SKILL.md +14 -0
  426. package/templates/.agents/skills/zaip-skill-systematic-debugging/agents/openai.yaml +4 -0
  427. package/templates/.agents/skills/zaip-skill-task/SKILL.md +16 -7
  428. package/templates/.agents/skills/zaip-skill-task/references/commit-policy.md +25 -0
  429. package/templates/.agents/skills/zaip-skill-test-data/SKILL.md +14 -0
  430. package/templates/.agents/skills/zaip-skill-test-data/agents/openai.yaml +4 -0
  431. package/templates/.agents/skills/zaip-skill-test-data/scripts/generate.mjs +72 -0
  432. package/templates/.agents/skills/zaip-skill-testing-strategy/SKILL.md +15 -0
  433. package/templates/.agents/skills/zaip-skill-testing-strategy/agents/openai.yaml +4 -0
  434. package/templates/.agents/skills/zaip-skill-testing-strategy/references/example-map.md +3 -0
  435. package/templates/.agents/skills/zaip-skill-text-encoding/SKILL.md +1 -1
  436. package/templates/.agents/skills/zaip-skill-website-readiness/SKILL.md +8 -0
  437. package/templates/.agents/zaip-aios/INDEX.md +1 -1
  438. package/templates/.agents/zaip-aios/README.md +6 -0
  439. package/templates/.agents/zaip-aios/VERSION +1 -1
  440. package/templates/.agents/zaip-aios/guides/08-contexto-e-tokens.md +19 -3
  441. package/templates/.agents/zaip-aios/guides/10-seguranca.md +2 -1
  442. package/templates/.agents/zaip-aios/guides/12-instalacao-e-upgrade.md +37 -7
  443. package/templates/.agents/zaip-aios/guides/20-instalacao-detalhada.md +19 -4
  444. package/templates/.agents/zaip-aios/guides/23-orquestracao-de-modelos.md +32 -3
  445. package/templates/.agents/zaip-aios/guides/26-qualidade-e-release.md +21 -0
  446. package/templates/scripts/validate-cloud-hostinger-contract.mjs +34 -0
  447. package/templates/template-manifest.json +1031 -235
  448. package/templates/.agents/branding/.gitkeep +0 -0
  449. package/templates/.agents/dashboard/apps/frontend/dist/assets/CostCalculationGuidePage-snUCQYTC.js +0 -1
  450. package/templates/.agents/dashboard/apps/frontend/dist/assets/PricingSettingsDialog-BPtVUGgs.js +0 -1
  451. package/templates/.agents/dashboard/apps/frontend/dist/assets/ProjectSettingsPage-3Awyaovx.js +0 -3
  452. package/templates/.agents/dashboard/apps/frontend/dist/assets/ProjectSettingsPage-GgzpZ_PY.css +0 -1
  453. package/templates/.agents/dashboard/apps/frontend/dist/assets/TraceabilityWorkspace-DHDrd5rE.js +0 -1
  454. package/templates/.agents/dashboard/apps/frontend/dist/assets/cost-monitor-DbaLbU2q.js +0 -68
  455. package/templates/.agents/dashboard/apps/frontend/dist/assets/index-BYbpmqmM.js +0 -2
  456. package/templates/.agents/dashboard/apps/frontend/dist/assets/rolldown-runtime-D9-fqq9M.js +0 -1
  457. package/templates/.agents/dashboard/apps/frontend/dist/assets/traceability-BDe4_Ubl.js +0 -1
  458. package/templates/.agents/growth/.gitkeep +0 -0
  459. package/templates/.agents/marketing/.gitkeep +0 -0
  460. package/templates/.agents/sales/.gitkeep +0 -0
@@ -0,0 +1,78 @@
1
+ import type { DatabaseSync } from "node:sqlite";
2
+ import { persistFirstFoldPayloadsInDatabase } from "./sqlite-first-fold-persistence.js";
3
+ import { measureFirstFold } from "./sqlite-first-fold-timing.js";
4
+ import { operationsWorkRowsInRange } from "./sqlite-operations-work-list.js";
5
+ import { saoPauloCurrentMonth } from "./sqlite-read-model-canonical.js";
6
+ import { SqliteReadModelFileSystem } from "./sqlite-read-model-filesystem.js";
7
+ import type { SqliteFirstFoldMonthlyQuick } from "./sqlite-read-model-first-fold-types.js";
8
+ import { reportSqliteReadModelLaunchProgress } from "./sqlite-read-model-launch-progress.js";
9
+ export function refreshFirstFoldPayloads(workspaceRoot: string, database: DatabaseSync): void {
10
+ const reportLaunchProgress = reportSqliteReadModelLaunchProgress;
11
+ const timed = <T>(phase: string, action: () => T) =>
12
+ measureFirstFold(
13
+ process.env.ZAIP_DASHBOARD_LAUNCH_PROGRESS === "1",
14
+ reportLaunchProgress,
15
+ phase,
16
+ action,
17
+ );
18
+ // This reader shares the writer connection, therefore it sees the
19
+ // uncommitted canonical facts and projections. Its payloads join the
20
+ // same BEGIN IMMEDIATE transaction below.
21
+ const firstFoldFilesystem = new SqliteReadModelFileSystem(workspaceRoot, database);
22
+ const firstFoldViewport = timed("first_fold_viewport", () =>
23
+ firstFoldFilesystem.firstFoldViewportAllTime(),
24
+ );
25
+ const firstFoldAllTime = timed("first_fold_all_time", () =>
26
+ firstFoldFilesystem.firstFoldAllTime(),
27
+ );
28
+ const firstFoldAllTimeBoard = timed("first_fold_board", () =>
29
+ firstFoldFilesystem.firstFoldBoardAllTime(),
30
+ );
31
+ const costMonitorSummaryAllTime = timed("first_fold_cost_summary", () =>
32
+ firstFoldFilesystem.costMonitorSummaryAggregate({ from: null, to: null }),
33
+ );
34
+ const quickMonth = saoPauloCurrentMonth();
35
+ const costMonitorSummaryCurrentMonth = timed("first_fold_cost_summary_month", () =>
36
+ firstFoldFilesystem.costMonitorSummaryAggregate(quickMonth),
37
+ );
38
+ const firstFoldMonthlyQuick: SqliteFirstFoldMonthlyQuick = {
39
+ from_day: quickMonth.from,
40
+ to_day: quickMonth.to,
41
+ source_latest_day: timed("first_fold_latest_day", () =>
42
+ firstFoldFilesystem.firstFoldRelevantLatestDay(),
43
+ ),
44
+ aggregate: timed("first_fold_month_aggregate", () =>
45
+ firstFoldFilesystem.firstFoldAggregate(quickMonth),
46
+ ),
47
+ pages: {
48
+ task: operationsWorkRowsInRange(
49
+ firstFoldAllTimeBoard.pages.task,
50
+ quickMonth.from,
51
+ quickMonth.to,
52
+ ),
53
+ spec: operationsWorkRowsInRange(
54
+ firstFoldAllTimeBoard.pages.spec,
55
+ quickMonth.from,
56
+ quickMonth.to,
57
+ ),
58
+ prd: operationsWorkRowsInRange(
59
+ firstFoldAllTimeBoard.pages.prd,
60
+ quickMonth.from,
61
+ quickMonth.to,
62
+ ),
63
+ },
64
+ top_tasks: timed("first_fold_month_top_tasks", () => firstFoldFilesystem.topTasks(quickMonth)),
65
+ };
66
+ firstFoldFilesystem.close();
67
+ persistFirstFoldPayloadsInDatabase(database, {
68
+ first_fold_viewport_cache: JSON.stringify(firstFoldViewport),
69
+ first_fold_all_time_cache: JSON.stringify(firstFoldAllTime),
70
+ first_fold_all_time_board_cache: JSON.stringify(firstFoldAllTimeBoard),
71
+ cost_monitor_summary_cache: JSON.stringify(costMonitorSummaryAllTime),
72
+ cost_monitor_summary_month_cache: JSON.stringify({
73
+ ...quickMonth,
74
+ aggregate: costMonitorSummaryCurrentMonth,
75
+ }),
76
+ first_fold_monthly_quick_cache: JSON.stringify(firstFoldMonthlyQuick),
77
+ });
78
+ }
@@ -0,0 +1,561 @@
1
+ import { createHash } from "node:crypto";
2
+ import type { DatabaseSync } from "node:sqlite";
3
+ import { allocateSharedCreationValue } from "@zaip-ai/lifecycle-manifests";
4
+ import { buildCostDimensionAggregates } from "./sqlite-cost-aggregates.js";
5
+ import { rebuildCostInvocationDimensionFactsSql } from "./sqlite-cost-dimension-facts.js";
6
+ import { materializeCostGroupDailyProjection } from "./sqlite-cost-group-projection.js";
7
+ import { readCostInvocationProjection } from "./sqlite-cost-invocation-projection.js";
8
+ import { synchronizePayloadRows } from "./sqlite-incremental-cache.js";
9
+ import type { materializeCanonicalRuns } from "./sqlite-materialize-runs.js";
10
+ import { materializeOperationsWorkProjection } from "./sqlite-operations-projection.js";
11
+ import {
12
+ aggregateCost,
13
+ type CanonicalEntity,
14
+ consolidatedValue,
15
+ knownSum,
16
+ saoPauloDay,
17
+ } from "./sqlite-read-model-canonical.js";
18
+ import { readModelSchemaVersion } from "./sqlite-read-model-schema.js";
19
+ import { baseViewSql } from "./sqlite-schema-base-views.js";
20
+ import { dashboardViewSql } from "./sqlite-schema-dashboard-views.js";
21
+
22
+ type ProjectionInput = ReturnType<typeof materializeCanonicalRuns> & {
23
+ database: DatabaseSync;
24
+ canonicalEntities: Map<string, CanonicalEntity>;
25
+ changedCreationRunIds: Set<string>;
26
+ hasPersistentSchema: boolean;
27
+ files: number;
28
+ skipped: number;
29
+ fingerprint: string;
30
+ };
31
+ export function materializeDashboardProjections(input: ProjectionInput) {
32
+ const {
33
+ database,
34
+ canonicalEntities,
35
+ changedCreationRunIds,
36
+ hasPersistentSchema,
37
+ files,
38
+ skipped,
39
+ fingerprint,
40
+ temporalRuns,
41
+ getFold,
42
+ pricingCatalog,
43
+ fxRate,
44
+ rootRunId,
45
+ catalogHash,
46
+ columns,
47
+ canonicalInsertActivity,
48
+ excludedUnknownTokenRunCount,
49
+ unassistedActivityCount,
50
+ agentProfiles,
51
+ } = input;
52
+ const creationSpecsByRun = new Map<string, CanonicalEntity[]>();
53
+ for (const entity of canonicalEntities.values()) {
54
+ if (entity.kind !== "spec" || entity.creationRunId === null) continue;
55
+ creationSpecsByRun.set(entity.creationRunId, [
56
+ ...(creationSpecsByRun.get(entity.creationRunId) ?? []),
57
+ entity,
58
+ ]);
59
+ }
60
+ for (const row of database
61
+ .prepare(
62
+ "SELECT DISTINCT run_id FROM zaip_aios_activities WHERE payload_type='shared_creation_allocation'",
63
+ )
64
+ .all() as Array<{ run_id: string }>)
65
+ if (changedCreationRunIds.has(row.run_id) || temporalRuns.has(row.run_id))
66
+ database
67
+ .prepare(
68
+ "DELETE FROM zaip_aios_activities WHERE payload_type='shared_creation_allocation' AND run_id=?",
69
+ )
70
+ .run(row.run_id);
71
+ const materializeSharedCreationAllocations = () => {
72
+ for (const [runId, recipients] of creationSpecsByRun) {
73
+ if (recipients.length === 0) continue;
74
+ if (hasPersistentSchema && !changedCreationRunIds.has(runId) && !temporalRuns.has(runId))
75
+ continue;
76
+ const source = getFold(runId);
77
+ if (source === undefined) continue;
78
+ const { fold, row } = source;
79
+ const started = fold.run;
80
+ const usage = fold.effective_usage_records;
81
+ const canonicalActivity = database
82
+ .prepare(
83
+ "SELECT duration_ms, duration_provenance, source_started_at, source_finished_at FROM zaip_aios_activities WHERE run_id=? AND payload_type IS NULL LIMIT 1",
84
+ )
85
+ .get(runId) as
86
+ | {
87
+ duration_ms: number | null;
88
+ duration_provenance: string | null;
89
+ source_started_at: string | null;
90
+ source_finished_at: string | null;
91
+ }
92
+ | undefined;
93
+ const cost = aggregateCost(usage, fold, pricingCatalog, fxRate);
94
+ const recipientIds = recipients.map((recipient) => recipient.id);
95
+ // The allocator owns the only partition. Read the already-materialized
96
+ // canonical activity fact after attributed-token-active reconciliation;
97
+ // never use the wider JSONL session span or a pre-divided value.
98
+ const sharedCreationDuration = canonicalActivity?.duration_ms ?? null;
99
+ const allocations = {
100
+ source_duration_ms: allocateSharedCreationValue(sharedCreationDuration, recipientIds),
101
+ // Shared creation attribution uses only the observed source interval;
102
+ // never propagate an effective/legacy aggregate that can include
103
+ // more than the creation segment.
104
+ duration_ms: allocateSharedCreationValue(sharedCreationDuration, recipientIds),
105
+ input_tokens: allocateSharedCreationValue(knownSum(usage, "input"), recipientIds),
106
+ cached_input_tokens: allocateSharedCreationValue(
107
+ knownSum(usage, "cached_input"),
108
+ recipientIds,
109
+ ),
110
+ output_tokens: allocateSharedCreationValue(knownSum(usage, "output"), recipientIds),
111
+ reasoning_tokens: allocateSharedCreationValue(knownSum(usage, "reasoning"), recipientIds),
112
+ total_tokens: allocateSharedCreationValue(knownSum(usage, "total"), recipientIds),
113
+ cost_usd: allocateSharedCreationValue(cost.usd, recipientIds),
114
+ cost_brl: allocateSharedCreationValue(cost.brl, recipientIds),
115
+ };
116
+ for (const recipient of recipients) {
117
+ const attributed =
118
+ usage.find((record) => record.attributed_spec_id === recipient.id) ?? null;
119
+ const attributedDuration =
120
+ attributed?.source_started_at && attributed?.source_finished_at
121
+ ? Math.max(
122
+ 0,
123
+ Date.parse(attributed.source_finished_at) -
124
+ Date.parse(attributed.source_started_at),
125
+ )
126
+ : null;
127
+ const activityRowId = `ACTV-${createHash("sha256")
128
+ .update(`shared-creation:${runId}:${recipient.id}`)
129
+ .digest("hex")
130
+ .slice(0, 24)}`;
131
+ const lastRecord = fold.records.at(-1);
132
+ const allocation = {
133
+ activity_row_id: activityRowId,
134
+ activity_source_kind: "shared_creation_allocation",
135
+ activity_key: `shared-creation:${runId}:${recipient.id}`,
136
+ source_path: row.path,
137
+ source_hash: row.content_sha256,
138
+ source_occurred_at: started.occurred_at,
139
+ recorded_at: lastRecord?.occurred_at ?? started.occurred_at,
140
+ version_activity_id: null,
141
+ source_last_event_id: lastRecord?.event_id ?? null,
142
+ source_last_sequence: lastRecord?.sequence ?? null,
143
+ work_item_kind: "spec",
144
+ title: recipient.title,
145
+ work_item_status: recipient.status,
146
+ work_stage: recipient.stage,
147
+ risk: recipient.risk,
148
+ run_role: "shared_creation_allocation",
149
+ root_run_id: rootRunId(fold),
150
+ parent_run_id: started.parent_run_id,
151
+ agent_run_id: null,
152
+ root_agent_run_id: null,
153
+ parent_agent_run_id: null,
154
+ agent_run_role: null,
155
+ delegation_depth: started.delegation_depth ?? null,
156
+ agent_invocation_id: null,
157
+ root_agent_invocation_id: null,
158
+ parent_agent_invocation_id: null,
159
+ invocation_kind: null,
160
+ execution_id: started.execution_id,
161
+ task_id: null,
162
+ spec_id: recipient.id,
163
+ prd_id: null,
164
+ change_id: null,
165
+ conversation_id: started.conversation_id,
166
+ run_id: started.run_id,
167
+ occurred_at: started.occurred_at,
168
+ occurred_day_sp: saoPauloDay(started.occurred_at),
169
+ execution_kind: started.execution_kind ?? null,
170
+ entrypoint: started.entrypoint,
171
+ work_type: started.work_type,
172
+ phase: started.phase,
173
+ purpose: started.run_purpose ?? null,
174
+ status: fold.status,
175
+ activity_kind: "planning",
176
+ zaip_agent: started.agent_name ?? started.agent,
177
+ zaip_agent_persona: null,
178
+ zaip_agent_job: null,
179
+ zaip_agent_role: null,
180
+ agent_catalog_id: null,
181
+ agent_catalog_hash: catalogHash,
182
+ client: started.client,
183
+ provider: null,
184
+ model: null,
185
+ service_tier: null,
186
+ reasoning_effort: started.reasoning_effort ?? null,
187
+ developer_account_id: null,
188
+ developer_login: null,
189
+ developer_attribution_source: null,
190
+ source_duration_ms:
191
+ attributedDuration ?? allocations.source_duration_ms.get(recipient.id) ?? null,
192
+ source_started_at:
193
+ attributed?.source_started_at ?? canonicalActivity?.source_started_at ?? null,
194
+ source_finished_at:
195
+ attributed?.source_finished_at ?? canonicalActivity?.source_finished_at ?? null,
196
+ duration_ms: attributedDuration ?? allocations.duration_ms.get(recipient.id) ?? null,
197
+ duration_provenance: attributed
198
+ ? "explicit_spec_turn_recovery"
199
+ : "shared_creation_allocation",
200
+ input_tokens:
201
+ attributed?.tokens.input ?? allocations.input_tokens.get(recipient.id) ?? null,
202
+ cached_input_tokens:
203
+ attributed?.tokens.cached_input ??
204
+ allocations.cached_input_tokens.get(recipient.id) ??
205
+ null,
206
+ output_tokens:
207
+ attributed?.tokens.output ?? allocations.output_tokens.get(recipient.id) ?? null,
208
+ reasoning_tokens:
209
+ attributed?.tokens.reasoning ?? allocations.reasoning_tokens.get(recipient.id) ?? null,
210
+ total_tokens:
211
+ attributed?.tokens.total ?? allocations.total_tokens.get(recipient.id) ?? null,
212
+ token_source: consolidatedValue(usage.map((record) => record.tokens.source)),
213
+ usage_event_count: usage.length,
214
+ llm_call_count: null,
215
+ cost_usd: attributed?.cost.usd ?? allocations.cost_usd.get(recipient.id) ?? null,
216
+ cost_brl: attributed?.cost.brl ?? allocations.cost_brl.get(recipient.id) ?? null,
217
+ cost_method: cost.method,
218
+ pricing_model: cost.pricingModel,
219
+ pricing_source: cost.pricingSource,
220
+ fx_rate: cost.fxRate,
221
+ source_event_count: fold.records.length,
222
+ root_run_duration: null,
223
+ sub_run_duration: null,
224
+ payload_type: "shared_creation_allocation",
225
+ payload_json: JSON.stringify({
226
+ provenance: attributed ? "explicit_spec_turn_recovery" : "shared_creation_allocation",
227
+ base_duration_provenance: canonicalActivity?.duration_provenance ?? null,
228
+ creation_run_id: runId,
229
+ spec_id: recipient.id,
230
+ }),
231
+ } satisfies Record<(typeof columns)[number], string | number | null>;
232
+ canonicalInsertActivity.run(...columns.map((column) => allocation[column] ?? null));
233
+ }
234
+ }
235
+ };
236
+ materializeSharedCreationAllocations();
237
+ const canonicalRunCount = Number(
238
+ (
239
+ database
240
+ .prepare("SELECT COUNT(*) count FROM zaip_aios_activities WHERE payload_type IS NULL")
241
+ .get() as { count: number }
242
+ ).count,
243
+ );
244
+ const invocationCount = (
245
+ database
246
+ .prepare(
247
+ "SELECT COUNT(*) AS count FROM zaip_aios_activities WHERE agent_invocation_id IS NOT NULL",
248
+ )
249
+ .get() as { count: number }
250
+ ).count;
251
+ database
252
+ .prepare("INSERT INTO read_model_metadata(key, value) VALUES (?, ?)")
253
+ .run("source_file_count", String(files));
254
+ database
255
+ .prepare("INSERT INTO read_model_metadata(key, value) VALUES (?, ?)")
256
+ .run("excluded_source_count", String(skipped));
257
+ const dayCount = (
258
+ database
259
+ .prepare(
260
+ "SELECT COUNT(DISTINCT occurred_day_sp) AS count FROM zaip_aios_activities WHERE occurred_day_sp IS NOT NULL",
261
+ )
262
+ .get() as { count: number }
263
+ ).count;
264
+ const activityCount = (
265
+ database
266
+ .prepare(
267
+ "SELECT COUNT(*) AS count FROM zaip_aios_activities WHERE payload_type IS NULL OR payload_type='shared_creation_allocation'",
268
+ )
269
+ .get() as {
270
+ count: number;
271
+ }
272
+ ).count;
273
+ const agentRunCount = (
274
+ database
275
+ .prepare(
276
+ "SELECT COUNT(*) AS count FROM zaip_aios_activities WHERE activity_source_kind = 'agent_run'",
277
+ )
278
+ .get() as { count: number }
279
+ ).count;
280
+ // The header is a telemetry freshness signal, not an indication that the
281
+ // SQLite file was rebuilt. Restrict it to Runs that produced canonical
282
+ // activities in this same transaction so a parsed-but-not-materialized
283
+ // record cannot advance the displayed value.
284
+ let latestTokenCollectedAt: { occurredAt: string; instant: number } | null = null;
285
+ for (const runId of new Set(
286
+ (
287
+ database
288
+ .prepare("SELECT DISTINCT run_id FROM zaip_aios_activities WHERE payload_type IS NULL")
289
+ .all() as Array<{ run_id: string }>
290
+ ).map((row) => row.run_id),
291
+ )) {
292
+ const usage = getFold(runId)?.fold.effective_usage_records ?? [];
293
+ for (const record of usage) {
294
+ if (typeof record.tokens.total !== "number" || record.tokens.total <= 0) continue;
295
+ const instant = Date.parse(record.occurred_at);
296
+ if (!Number.isFinite(instant)) continue;
297
+ if (latestTokenCollectedAt === null || instant > latestTokenCollectedAt.instant)
298
+ latestTokenCollectedAt = { occurredAt: record.occurred_at, instant };
299
+ }
300
+ }
301
+ database
302
+ .prepare("INSERT INTO read_model_metadata(key, value) VALUES (?, ?)")
303
+ .run("daily_aggregate_count", String(dayCount));
304
+ database
305
+ .prepare("INSERT INTO read_model_metadata(key, value) VALUES (?, ?)")
306
+ .run("activity_count", String(activityCount));
307
+ database
308
+ .prepare("INSERT INTO read_model_metadata(key, value) VALUES (?, ?)")
309
+ .run("canonical_run_count", String(canonicalRunCount));
310
+ database
311
+ .prepare("INSERT INTO read_model_metadata(key, value) VALUES (?, ?)")
312
+ .run("excluded_unknown_token_run_count", String(excludedUnknownTokenRunCount));
313
+ database
314
+ .prepare("INSERT INTO read_model_metadata(key, value) VALUES (?, ?)")
315
+ .run("agent_run_count", String(agentRunCount));
316
+ database
317
+ .prepare("INSERT INTO read_model_metadata(key, value) VALUES (?, ?)")
318
+ .run("telemetry_summary_count", "0");
319
+ database
320
+ .prepare("INSERT INTO read_model_metadata(key, value) VALUES (?, ?)")
321
+ .run("unassisted_activity_count", String(unassistedActivityCount));
322
+ database
323
+ .prepare("INSERT INTO read_model_metadata(key, value) VALUES (?, ?)")
324
+ .run("unassisted_turn_count", String(unassistedActivityCount));
325
+ database
326
+ .prepare("INSERT INTO read_model_metadata(key, value) VALUES (?, ?)")
327
+ .run("agent_invocation_count", String(invocationCount));
328
+ database
329
+ .prepare("INSERT INTO read_model_metadata(key, value) VALUES (?, ?)")
330
+ .run("schema_version", readModelSchemaVersion);
331
+ database
332
+ .prepare("INSERT INTO read_model_metadata(key, value) VALUES (?, ?)")
333
+ .run("source_fingerprint", fingerprint);
334
+ database
335
+ .prepare("INSERT INTO read_model_metadata(key, value) VALUES (?, ?)")
336
+ .run("snapshot_updated_at", new Date().toISOString());
337
+ database
338
+ .prepare("INSERT INTO read_model_metadata(key, value) VALUES (?, ?)")
339
+ .run("latest_token_collected_at", latestTokenCollectedAt?.occurredAt ?? "");
340
+ // Seed the selectable Model/Provider dimensions and take the compact
341
+ // aggregate snapshot while the fact still contains only canonical
342
+ // activities. The following technical payload serialization can add
343
+ // millions of rows and must never be scanned by this calculation.
344
+ const insertConfiguredModel = database.prepare(
345
+ "INSERT OR IGNORE INTO zaip_dim_llm_model(model) VALUES (?)",
346
+ );
347
+ const insertConfiguredProvider = database.prepare(
348
+ "INSERT OR IGNORE INTO zaip_dim_provider(provider) VALUES (?)",
349
+ );
350
+ for (const configuredModel of pricingCatalog.models) {
351
+ insertConfiguredModel.run(configuredModel.id);
352
+ insertConfiguredProvider.run(configuredModel.provider);
353
+ }
354
+ const costDimensionAggregates = buildCostDimensionAggregates(database, agentProfiles);
355
+ // The rebuild scratch tables above are intentionally TEMP only. Persist
356
+ // their technical inputs as typed payload activities so the on-disk
357
+ // model has one fact plus its three declared dimensions, never hidden
358
+ // canonical/index/cache tables.
359
+ const persistPayload = (
360
+ payloadType: string,
361
+ selectSql: string,
362
+ _preserveExistingSource = false,
363
+ ) => synchronizePayloadRows(database, payloadType, selectSql);
364
+ persistPayload(
365
+ "metadata",
366
+ "SELECT key AS row_key, json_object('key', key, 'value', value) AS payload_json FROM read_model_metadata",
367
+ );
368
+ persistPayload(
369
+ "source_state",
370
+ "SELECT source_path AS row_key, json_object('source_path', source_path, 'source_hash', source_hash, 'mtime_ms', mtime_ms, 'ctime_ms', ctime_ms, 'size_bytes', size_bytes, 'file_identity', file_identity, 'source_kind', source_kind, 'last_processed_at', last_processed_at) AS payload_json FROM read_model_source_state",
371
+ true,
372
+ );
373
+ persistPayload(
374
+ "file",
375
+ "SELECT path AS row_key, json_object('path', path, 'content', content, 'mtime_ms', mtime_ms, 'size_bytes', size_bytes, 'content_sha256', content_sha256, 'artifact_kind', artifact_kind, 'artifact_id', artifact_id, 'artifact_occurred_at', artifact_occurred_at, 'artifact_occurred_day_sp', artifact_occurred_day_sp, 'artifact_task_id', artifact_task_id, 'artifact_change_id', artifact_change_id, 'artifact_run_id', artifact_run_id) AS payload_json FROM files",
376
+ true,
377
+ );
378
+ persistPayload(
379
+ "work_item",
380
+ "SELECT entity_kind || ':' || id AS row_key, json_object('entity_kind', entity_kind, 'id', id, 'title', title, 'status', status, 'stage', stage, 'risk', risk, 'spec_id', spec_id, 'change_id', change_id, 'creation_run_id', creation_run_id, 'completed_run_id', completed_run_id, 'occurred_at', occurred_at, 'occurred_day_sp', occurred_day_sp) AS payload_json FROM canonical_work_items",
381
+ );
382
+ persistPayload(
383
+ "execution",
384
+ "SELECT id AS row_key, json_object('id', id, 'status', status, 'kind', kind, 'origin_type', origin_type, 'origin_id', origin_id, 'created_at', created_at, 'occurred_day_sp', occurred_day_sp, 'finished_at', finished_at, 'source_path', source_path) AS payload_json FROM canonical_executions",
385
+ );
386
+ persistPayload(
387
+ "change",
388
+ "SELECT id AS row_key, json_object('id', id, 'title', title, 'status', status, 'risk', risk, 'source_type', source_type, 'source_id', source_id, 'source_spec_id', source_spec_id, 'source_prd_id', source_prd_id, 'requirement_ids_json', requirement_ids_json, 'acceptance_ids_json', acceptance_ids_json, 'task_ids_json', task_ids_json, 'result', result, 'created_at', created_at, 'occurred_day_sp', occurred_day_sp, 'source_path', source_path) AS payload_json FROM canonical_changes",
389
+ );
390
+ persistPayload(
391
+ "decision",
392
+ "SELECT id AS row_key, json_object('id', id, 'title', title, 'origin', origin, 'scope_type', scope_type, 'scope_id', scope_id, 'created_at', created_at, 'occurred_day_sp', occurred_day_sp, 'source_path', source_path) AS payload_json FROM canonical_decisions",
393
+ );
394
+ persistPayload(
395
+ "run_index",
396
+ "SELECT run_id AS row_key, json_object('run_id', run_id, 'occurred_at', occurred_at, 'occurred_day_sp', occurred_day_sp, 'task_id', task_id, 'phase', phase, 'run_role', run_role, 'duration_ms', duration_ms, 'source_event_count', source_event_count, 'zaip_agent', zaip_agent, 'provider', provider, 'model', model, 'status', status) AS payload_json FROM canonical_run_index",
397
+ );
398
+ persistPayload(
399
+ "usage_segment",
400
+ "SELECT agent_invocation_id || ':' || ROW_NUMBER() OVER(PARTITION BY agent_invocation_id ORDER BY rowid) AS row_key, json_object('agent_invocation_id', agent_invocation_id, 'provider', provider, 'model', model, 'service_tier', service_tier, 'reasoning_effort', reasoning_effort, 'input_tokens', input_tokens, 'cached_input_tokens', cached_input_tokens, 'uncached_input_tokens', uncached_input_tokens, 'output_tokens', output_tokens, 'reasoning_tokens', reasoning_tokens, 'visible_output_tokens', visible_output_tokens, 'total_tokens', total_tokens, 'input_rate_usd_per_million', input_rate_usd_per_million, 'cached_input_rate_usd_per_million', cached_input_rate_usd_per_million, 'output_rate_usd_per_million', output_rate_usd_per_million, 'reasoning_rate_usd_per_million', reasoning_rate_usd_per_million, 'context_input_multiplier', context_input_multiplier, 'context_output_multiplier', context_output_multiplier, 'speed_cost_multiplier', speed_cost_multiplier, 'pricing_scenario', pricing_scenario, 'standard_cost_usd', standard_cost_usd, 'speed_uplift_usd', speed_uplift_usd, 'input_cost_usd', input_cost_usd, 'cached_input_cost_usd', cached_input_cost_usd, 'output_cost_usd', output_cost_usd, 'reasoning_cost_usd', reasoning_cost_usd, 'calculated_cost_usd', calculated_cost_usd, 'recorded_cost_usd', recorded_cost_usd, 'cost_variance_usd', cost_variance_usd, 'cost_usd', cost_usd, 'cost_brl', cost_brl, 'cost_method', cost_method, 'pricing_model', pricing_model, 'pricing_source', pricing_source, 'fx_rate', fx_rate) AS payload_json FROM invocation_usage_segments",
401
+ );
402
+ persistPayload(
403
+ "duration_allocation",
404
+ "SELECT activity_row_id || ':' || occurred_day_sp AS row_key, json_object('activity_row_id', activity_row_id, 'occurred_day_sp', occurred_day_sp, 'attributed_token_active_ms', attributed_token_active_ms) AS payload_json FROM attributed_token_active_facts",
405
+ );
406
+ // Configuration-backed dimensions contain the current selectable
407
+ // catalog even when no activity has used an option yet. Historical
408
+ // values remain faithfully recorded in the fact without becoming
409
+ // current filter options after their catalog entry is removed.
410
+ const insertConfiguredAgent = database.prepare(
411
+ "INSERT OR IGNORE INTO zaip_dim_zaip_agent(zaip_agent, catalog_id, persona, job, role, catalog_hash) VALUES (?, ?, ?, ?, ?, ?)",
412
+ );
413
+ for (const [agent, profile] of agentProfiles)
414
+ insertConfiguredAgent.run(
415
+ agent,
416
+ profile.catalogId,
417
+ profile.persona,
418
+ profile.job,
419
+ profile.role,
420
+ catalogHash,
421
+ );
422
+ const dimensionPayloads: Array<{ row_key: string; payload_json: string }> = [];
423
+ for (const dimension of ["model", "provider"] as const)
424
+ for (const row of costDimensionAggregates[dimension])
425
+ dimensionPayloads.push({
426
+ row_key: `${dimension}:${row.key}`,
427
+ payload_json: JSON.stringify({ schema_version: 1, dimension, ...row }),
428
+ });
429
+ for (const [dimension, projection] of Object.entries(costDimensionAggregates.remote)) {
430
+ for (const row of projection.rows)
431
+ dimensionPayloads.push({
432
+ row_key: `${dimension}:${row.key}`,
433
+ payload_json: JSON.stringify({ schema_version: 1, dimension, row_kind: "row", ...row }),
434
+ });
435
+ dimensionPayloads.push({
436
+ row_key: `${dimension}:__totals__`,
437
+ payload_json: JSON.stringify({
438
+ schema_version: 1,
439
+ dimension,
440
+ row_kind: "totals",
441
+ ...projection.totals,
442
+ }),
443
+ });
444
+ }
445
+ synchronizePayloadRows(database, "cost_dimension_aggregate_v1", dimensionPayloads);
446
+ // Keep canonical TEMP references outside the public-view name rewriter.
447
+ database.exec(
448
+ hasPersistentSchema
449
+ ? rebuildCostInvocationDimensionFactsSql
450
+ .replace(
451
+ "CREATE TABLE cost_invocation_dimension_facts AS",
452
+ "DELETE FROM cost_invocation_dimension_facts; INSERT INTO cost_invocation_dimension_facts",
453
+ )
454
+ .replace(/CREATE INDEX cost_dimension_facts_[A-Za-z_]+ ON [^;]+;/g, "")
455
+ : rebuildCostInvocationDimensionFactsSql,
456
+ );
457
+ const viewSql = baseViewSql + dashboardViewSql;
458
+ // Every SQLite view has a single discoverable namespace. References in
459
+ // the view definitions are rewritten from their concise source aliases
460
+ // at build time, so DBeaver and direct SQL never expose unprefixed views.
461
+ const viewNames = [...viewSql.matchAll(/\bCREATE VIEW ([A-Za-z_][A-Za-z0-9_]*)/g)]
462
+ .map((match) => match[1])
463
+ .filter((name): name is string => name !== undefined);
464
+ const normalizedViewSql = viewNames.reduce((sql, name) => {
465
+ const conciseName = name.startsWith("vw_") ? name.slice("vw_".length) : name;
466
+ return sql.replace(new RegExp(`\\b${name}\\b`, "g"), `zaip_vw_${conciseName}`);
467
+ }, viewSql);
468
+ // Some historical vw_* objects were aliases of an already-declared
469
+ // concise view. After normalization they have the same public name;
470
+ // retain the first definition and discard only the redundant wrapper.
471
+ const persistedViews = new Set<string>();
472
+ const deduplicatedViewSql = normalizedViewSql.replace(
473
+ /\bCREATE VIEW ([A-Za-z_][A-Za-z0-9_]*)[\s\S]*?;/g,
474
+ (statement, name: string) => {
475
+ if (persistedViews.has(name)) return "";
476
+ persistedViews.add(name);
477
+ return statement;
478
+ },
479
+ );
480
+ if (!hasPersistentSchema) database.exec(deduplicatedViewSql);
481
+ // One row per stable GitHub account. Costs are summed from the single
482
+ // canonical Run fact, while delivery is joined exclusively through the
483
+ // Task's completed_run_id (never inferred from a branch or latest Run).
484
+ const developerProjectionSql = `
485
+ CREATE TABLE developer_cost_projection AS
486
+ WITH completed AS (
487
+ SELECT a.developer_account_id, COUNT(DISTINCT w.id) AS completed_task_count
488
+ FROM zaip_vw_canonical_work_items w
489
+ JOIN zaip_vw_activities a ON a.run_id=w.completed_run_id
490
+ WHERE w.entity_kind='task' AND w.status='completed'
491
+ AND a.developer_account_id IS NOT NULL
492
+ GROUP BY a.developer_account_id
493
+ )
494
+ SELECT a.developer_account_id AS account_id,
495
+ MAX(a.developer_login) AS login_snapshot,
496
+ CASE WHEN COUNT(DISTINCT a.developer_attribution_source)=1 THEN MAX(a.developer_attribution_source) ELSE 'mixed' END AS attribution_source,
497
+ COUNT(*) AS run_count,
498
+ SUM(a.source_event_count) AS source_event_count,
499
+ SUM(a.total_tokens) AS total_tokens,
500
+ SUM(a.cost_usd) AS total_cost_usd,
501
+ SUM(a.cost_brl) AS total_cost_brl,
502
+ COUNT(a.total_tokens) AS token_covered_runs,
503
+ COUNT(a.cost_usd) AS usd_covered_runs,
504
+ COUNT(a.cost_brl) AS brl_covered_runs,
505
+ COALESCE(completed.completed_task_count, 0) AS completed_task_count
506
+ FROM zaip_vw_activities a LEFT JOIN completed USING(developer_account_id)
507
+ WHERE a.developer_account_id IS NOT NULL
508
+ GROUP BY a.developer_account_id
509
+ ORDER BY total_cost_brl DESC, account_id;
510
+ CREATE INDEX developer_cost_projection_lookup ON developer_cost_projection(account_id);
511
+ `;
512
+ database.exec(
513
+ hasPersistentSchema
514
+ ? developerProjectionSql
515
+ .replace(
516
+ "CREATE TABLE developer_cost_projection AS",
517
+ "DELETE FROM developer_cost_projection; INSERT INTO developer_cost_projection",
518
+ )
519
+ .replace(
520
+ "CREATE INDEX developer_cost_projection_lookup ON developer_cost_projection(account_id);",
521
+ "",
522
+ )
523
+ : developerProjectionSql,
524
+ );
525
+ materializeCostGroupDailyProjection(database);
526
+ materializeOperationsWorkProjection(database);
527
+ // Persist the complete unfiltered invocation projection while the seed
528
+ // still owns the compact canonical facts. Runtime pages can then slice
529
+ // 10/100 rows without expanding the pricing view for every request.
530
+ const costAgentInvocationProjection = readCostInvocationProjection(database);
531
+ synchronizePayloadRows(
532
+ database,
533
+ "cost_agent_invocation_projection_v1",
534
+ costAgentInvocationProjection.flatMap((row) => {
535
+ const invocationId = String(row.agent_invocation_id ?? "");
536
+ return invocationId
537
+ ? [
538
+ {
539
+ row_key: invocationId,
540
+ payload_json: JSON.stringify(row),
541
+ occurred_day_sp: typeof row.occurred_day_sp === "string" ? row.occurred_day_sp : null,
542
+ },
543
+ ]
544
+ : [];
545
+ }),
546
+ );
547
+ // Source staging tables are no longer needed after the projections are
548
+ // materialized. Release their TEMP names before installing the public
549
+ // view aliases on this same connection.
550
+ database.exec(`
551
+ DROP TABLE IF EXISTS files;
552
+ DROP TABLE IF EXISTS read_model_source_state;
553
+ DROP TABLE IF EXISTS read_model_metadata;
554
+ DROP TABLE IF EXISTS canonical_work_items;
555
+ DROP TABLE IF EXISTS canonical_executions;
556
+ DROP TABLE IF EXISTS canonical_changes;
557
+ DROP TABLE IF EXISTS canonical_decisions;
558
+ DROP TABLE IF EXISTS canonical_run_index;
559
+ DROP TABLE IF EXISTS invocation_usage_segments;
560
+ `);
561
+ }