create-ailk 0.24.0 → 0.26.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 (638) hide show
  1. package/README.md +53 -22
  2. package/component-catalog.json +3 -3
  3. package/component-catalog.md +3 -3
  4. package/dist/add-module.js +4 -2
  5. package/dist/add-route.d.ts +12 -1
  6. package/dist/add-route.js +31 -3
  7. package/dist/cli.js +12 -7
  8. package/dist/derive-architecture.d.ts +3 -4
  9. package/dist/derive-architecture.js +65 -29
  10. package/dist/lib/design-checks.d.ts +9 -4
  11. package/dist/lib/design-checks.js +13 -7
  12. package/dist/lib/extract-module-bundle.js +29 -2
  13. package/dist/lib/fetch-template-snapshot.d.ts +2 -1
  14. package/dist/lib/fetch-template-snapshot.js +8 -3
  15. package/dist/lib/import-graph.d.ts +1 -1
  16. package/dist/lib/import-graph.js +4 -4
  17. package/dist/lib/module-license-gate.d.ts +12 -1
  18. package/dist/lib/module-license-gate.js +36 -15
  19. package/dist/lib/module-tier.d.ts +2 -8
  20. package/dist/lib/module-tier.js +13 -12
  21. package/dist/module-architecture.d.ts +20 -3
  22. package/dist/module-architecture.js +129 -552
  23. package/dist/paid-sections.d.ts +25 -1
  24. package/dist/paid-sections.js +88 -3
  25. package/dist/starter-grid.d.ts +6 -6
  26. package/dist/starter-grid.js +12 -5
  27. package/dist/surfaces.js +39 -2
  28. package/dist/template-record.d.ts +21 -3
  29. package/dist/template-record.js +38 -7
  30. package/dist/topology.d.ts +16 -3
  31. package/dist/topology.js +54 -23
  32. package/dist/update.d.ts +10 -1
  33. package/dist/update.js +715 -21
  34. package/package.json +3 -3
  35. package/release-scope.json +2 -2
  36. package/site-templates/marketing-site/TEMPLATE-MANIFEST.json +8 -2
  37. package/site-templates/marketing-site/TEMPLATE-MANIFEST.md +2 -2
  38. package/site-templates/marketing-site/ailk-template.json +7 -1
  39. package/site-templates/marketing-site/provenance.json +7 -1
  40. package/site-templates/saas-product/ailk-template.json +2 -1
  41. package/site-templates/saas-product/provenance.json +1 -0
  42. package/templates/.claude/cloudparity-repo-hooks.json +5 -0
  43. package/templates/.claude/hooks/template-guard.sh +137 -0
  44. package/templates/.claude/rules/extending.md +106 -0
  45. package/templates/.claude/rules/loop-contract.md +2 -2
  46. package/templates/.claude/settings.json +11 -0
  47. package/templates/.env.example +20 -5
  48. package/templates/.github/workflows/ci.yml +7 -4
  49. package/templates/CLAUDE.md +11 -1
  50. package/templates/CONVENTIONS.md +8 -10
  51. package/templates/README.md +14 -13
  52. package/templates/apps/api/.env.example +23 -2
  53. package/templates/apps/api/CLAUDE.md +119 -83
  54. package/templates/apps/api/jest.config.cjs +15 -5
  55. package/templates/apps/api/package.json +16 -20
  56. package/templates/apps/api/src/__tests__/trusted-origins.server.test.ts +2 -2
  57. package/templates/apps/api/src/__tests__/vercel-handler.test.ts +4 -4
  58. package/templates/apps/api/src/index.ts +1 -1
  59. package/templates/apps/api/src/lib/__mocks__/prisma-client.js +16 -0
  60. package/templates/apps/api/src/lib/__mocks__/prisma.ts +3 -3
  61. package/templates/apps/api/src/modules/commerce.ts +10 -0
  62. package/templates/apps/api/src/modules/content-write.ts +10 -0
  63. package/templates/apps/api/src/modules/multi-tenant.ts +10 -0
  64. package/templates/apps/api/src/modules/scheduling.ts +10 -0
  65. package/templates/apps/api/src/modules/signal-collectors.ts +10 -0
  66. package/templates/apps/api/src/modules/workspace.ts +10 -0
  67. package/templates/apps/api/src/server.ts +117 -1882
  68. package/templates/apps/api/vercel.json +2 -2
  69. package/templates/apps/mcp/CLAUDE.md +90 -26
  70. package/templates/apps/mcp/__tests__/app-entry.test.ts +4 -254
  71. package/templates/apps/mcp/__tests__/boot-file.test.ts +92 -0
  72. package/templates/apps/mcp/jest.config.cjs +6 -1
  73. package/templates/apps/mcp/package.json +5 -13
  74. package/templates/apps/mcp/src/app.ts +8 -7
  75. package/templates/apps/mcp/src/index.ts +6 -34
  76. package/templates/apps/mcp/src/lib/paid-tools.generated.ts +10 -0
  77. package/templates/apps/mcp/src/lib/topology.generated.ts +2 -2
  78. package/templates/apps/mcp/src/site.ts +12 -0
  79. package/templates/apps/web/.env.example +1 -1
  80. package/templates/apps/web/CLAUDE.md +31 -3
  81. package/templates/apps/web/app/.well-known/mcp.json/route.ts +9 -3
  82. package/templates/apps/web/app/[locale]/(auth)/__tests__/auth-pages.test.tsx +43 -4
  83. package/templates/apps/web/app/[locale]/(auth)/legal-footnote.tsx +35 -0
  84. package/templates/apps/web/app/[locale]/(auth)/sign-in/__tests__/page.test.tsx +117 -8
  85. package/templates/apps/web/app/[locale]/(auth)/sign-in/page.tsx +14 -37
  86. package/templates/apps/web/app/[locale]/(auth)/sign-in/sign-in-card.tsx +6 -6
  87. package/templates/apps/web/app/[locale]/(auth)/sign-in/sign-in-text.ts +20 -35
  88. package/templates/apps/web/app/[locale]/(auth)/sign-up/__tests__/page.test.tsx +108 -0
  89. package/templates/apps/web/app/[locale]/(auth)/sign-up/__tests__/sign-up-card.test.tsx +111 -5
  90. package/templates/apps/web/app/[locale]/(auth)/sign-up/page.tsx +78 -16
  91. package/templates/apps/web/app/[locale]/(auth)/sign-up/sign-up-card.tsx +132 -12
  92. package/templates/apps/web/app/[locale]/(authed)/__tests__/gate.test.tsx +53 -1
  93. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/billing.test.tsx +38 -0
  94. package/templates/apps/web/app/[locale]/(authed)/account/billing/page.tsx +4 -2
  95. package/templates/apps/web/app/[locale]/(authed)/sign-in-gate.tsx +47 -24
  96. package/templates/apps/web/app/[locale]/(authed)/signed-out-gate.generated.tsx +23 -4
  97. package/templates/apps/web/app/[locale]/contact/intake-analytics.ts +1 -1
  98. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/magnet-page.test.tsx +22 -1
  99. package/templates/apps/web/app/[locale]/flows/[slug]/magnet-page.tsx +7 -3
  100. package/templates/apps/web/app/[locale]/layout.tsx +33 -13
  101. package/templates/apps/web/app/[locale]/meet/confirmed/BookingHandOff.tsx +128 -0
  102. package/templates/apps/web/app/[locale]/meet/confirmed/__tests__/BookingHandOff.test.tsx +126 -0
  103. package/templates/apps/web/app/[locale]/pricing/__tests__/unconnected.test.tsx +43 -0
  104. package/templates/apps/web/app/[locale]/pricing/page.tsx +7 -3
  105. package/templates/apps/web/app/api/offerings/checkout/[lookupKey]/__tests__/route.test.ts +222 -0
  106. package/templates/apps/web/app/api/offerings/checkout/[lookupKey]/route.ts +10 -3
  107. package/templates/apps/web/app/api/revalidate/route.ts +3 -3
  108. package/templates/apps/web/auth.ts +10 -6
  109. package/templates/apps/web/i18n/request.ts +49 -1
  110. package/templates/apps/web/jest.config.cjs +1 -0
  111. package/templates/apps/web/lib/__tests__/account-config.test.ts +7 -0
  112. package/templates/apps/web/lib/__tests__/auth-email.test.ts +276 -0
  113. package/templates/apps/web/lib/auth-email.ts +103 -21
  114. package/templates/apps/web/lib/hub-session/__tests__/sign-in-gate.test.tsx +72 -23
  115. package/templates/apps/web/lib/hub-session/sign-in-gate.tsx +94 -70
  116. package/templates/apps/web/lib/prisma-for-auth.ts +5 -2
  117. package/templates/apps/web/lib/relay.ts +2 -2
  118. package/templates/apps/web/lib/release-scope.ts +47 -0
  119. package/templates/apps/web/lib/server-api.ts +1 -1
  120. package/templates/apps/web/lib/sign-up-agreements.ts +291 -28
  121. package/templates/apps/web/lib/site-contributions.ts +18 -0
  122. package/templates/apps/web/messages/en.json +186 -20
  123. package/templates/apps/web/messages/site/en.json +1 -0
  124. package/templates/apps/web/src/lib/commerce-claim.ts +1 -1
  125. package/templates/customizations.yaml +37 -0
  126. package/templates/database/prisma.config.ts +10 -14
  127. package/templates/database/seed-test.ts +2 -2
  128. package/templates/database/seed.ts +5 -5
  129. package/templates/package.json +12 -6
  130. package/templates/pnpm-workspace.yaml +0 -1
  131. package/templates/project.yaml +16 -8
  132. package/templates/tools/jest/reporters.cjs +65 -0
  133. package/templates/tools/lint-architecture.ts +553 -7
  134. package/templates/tsconfig.json +1 -2
  135. package/versions.json +49 -36
  136. package/templates/apps/api/src/__tests__/commerce-claim-registration.test.ts +0 -409
  137. package/templates/apps/api/src/__tests__/factories/agent-caller.ts +0 -102
  138. package/templates/apps/api/src/__tests__/factories/content-fixture.ts +0 -138
  139. package/templates/apps/api/src/__tests__/factories/in-memory-prisma.ts +0 -441
  140. package/templates/apps/api/src/__tests__/factories/index.ts +0 -70
  141. package/templates/apps/api/src/__tests__/factories/lead-fixture.ts +0 -82
  142. package/templates/apps/api/src/__tests__/leads-forwarded-rate-limit.test.ts +0 -135
  143. package/templates/apps/api/src/__tests__/services/enrichment-shim.test.ts +0 -126
  144. package/templates/apps/api/src/__tests__/stripe-boot.test.ts +0 -132
  145. package/templates/apps/api/src/__tests__/support/hub-sign-in-fake-db.ts +0 -362
  146. package/templates/apps/api/src/bin/__tests__/rate-limit-probe.test.ts +0 -184
  147. package/templates/apps/api/src/bin/abandon-sweep.ts +0 -42
  148. package/templates/apps/api/src/bin/rate-limit-probe.ts +0 -53
  149. package/templates/apps/api/src/bin/spokes.ts +0 -198
  150. package/templates/apps/api/src/bin/stripe-connections-rekey.ts +0 -45
  151. package/templates/apps/api/src/config/__tests__/hub-require-spoke-key.test.ts +0 -196
  152. package/templates/apps/api/src/config/__tests__/index.test.ts +0 -233
  153. package/templates/apps/api/src/config/__tests__/modules.test.ts +0 -76
  154. package/templates/apps/api/src/config/__tests__/stripe-connection-key.test.ts +0 -185
  155. package/templates/apps/api/src/config/__tests__/trusted-origins.test.ts +0 -238
  156. package/templates/apps/api/src/config/index.ts +0 -596
  157. package/templates/apps/api/src/config/modules.ts +0 -83
  158. package/templates/apps/api/src/lib/__tests__/agent-store.test.ts +0 -581
  159. package/templates/apps/api/src/lib/__tests__/auth-email-budget.test.ts +0 -143
  160. package/templates/apps/api/src/lib/__tests__/consent-ledger-double.ts +0 -237
  161. package/templates/apps/api/src/lib/__tests__/consent-store.test.ts +0 -353
  162. package/templates/apps/api/src/lib/__tests__/content-adapter.test.ts +0 -201
  163. package/templates/apps/api/src/lib/__tests__/deliverable-asset-store.test.ts +0 -224
  164. package/templates/apps/api/src/lib/__tests__/error-serializer.test.ts +0 -120
  165. package/templates/apps/api/src/lib/__tests__/errors.test.ts +0 -94
  166. package/templates/apps/api/src/lib/__tests__/file-fallback.test.ts +0 -144
  167. package/templates/apps/api/src/lib/__tests__/fixtures/HomePage/home.mdx +0 -8
  168. package/templates/apps/api/src/lib/__tests__/flow-completion-store.test.ts +0 -149
  169. package/templates/apps/api/src/lib/__tests__/flow-rename-race.db.test.ts +0 -116
  170. package/templates/apps/api/src/lib/__tests__/hub-sign-in-store.test.ts +0 -209
  171. package/templates/apps/api/src/lib/__tests__/lead-capture-store.test.ts +0 -257
  172. package/templates/apps/api/src/lib/__tests__/lead-delivery.test.ts +0 -96
  173. package/templates/apps/api/src/lib/__tests__/outbound-http.test.ts +0 -125
  174. package/templates/apps/api/src/lib/__tests__/prisma.test.ts +0 -165
  175. package/templates/apps/api/src/lib/__tests__/require-commerce-claim.test.ts +0 -317
  176. package/templates/apps/api/src/lib/__tests__/require-paid-tier.test.ts +0 -129
  177. package/templates/apps/api/src/lib/__tests__/site.test.ts +0 -308
  178. package/templates/apps/api/src/lib/__tests__/slice-load.test.ts +0 -89
  179. package/templates/apps/api/src/lib/__tests__/spoke-store.test.ts +0 -202
  180. package/templates/apps/api/src/lib/__tests__/stripe-admission.test.ts +0 -217
  181. package/templates/apps/api/src/lib/__tests__/stripe.test.ts +0 -82
  182. package/templates/apps/api/src/lib/agent-store.ts +0 -613
  183. package/templates/apps/api/src/lib/auth-email-budget.ts +0 -161
  184. package/templates/apps/api/src/lib/consent-store.ts +0 -363
  185. package/templates/apps/api/src/lib/content-adapter.ts +0 -112
  186. package/templates/apps/api/src/lib/deliverable-asset-store.ts +0 -96
  187. package/templates/apps/api/src/lib/error-serializer.ts +0 -164
  188. package/templates/apps/api/src/lib/errors.ts +0 -95
  189. package/templates/apps/api/src/lib/file-fallback.ts +0 -87
  190. package/templates/apps/api/src/lib/flow-completion-store.ts +0 -136
  191. package/templates/apps/api/src/lib/hub-sign-in-store.ts +0 -455
  192. package/templates/apps/api/src/lib/lead-capture-store.ts +0 -122
  193. package/templates/apps/api/src/lib/lead-delivery.ts +0 -52
  194. package/templates/apps/api/src/lib/license-key-store.ts +0 -45
  195. package/templates/apps/api/src/lib/locales.ts +0 -201
  196. package/templates/apps/api/src/lib/outbound-http.ts +0 -127
  197. package/templates/apps/api/src/lib/prisma.ts +0 -21
  198. package/templates/apps/api/src/lib/proposal-paid-store.ts +0 -66
  199. package/templates/apps/api/src/lib/rate-limit-probe.ts +0 -165
  200. package/templates/apps/api/src/lib/rate-limit-store.ts +0 -142
  201. package/templates/apps/api/src/lib/require-commerce-claim.ts +0 -250
  202. package/templates/apps/api/src/lib/require-paid-tier.ts +0 -53
  203. package/templates/apps/api/src/lib/site.ts +0 -257
  204. package/templates/apps/api/src/lib/slice-load.ts +0 -90
  205. package/templates/apps/api/src/lib/spoke-store.ts +0 -180
  206. package/templates/apps/api/src/lib/stripe.ts +0 -321
  207. package/templates/apps/api/src/lib/webhook-idempotency.ts +0 -156
  208. package/templates/apps/api/src/middleware/__tests__/adversarial/bearer-token-format.test.ts +0 -111
  209. package/templates/apps/api/src/middleware/__tests__/adversarial/cookie-or-bearer-precedence.test.ts +0 -172
  210. package/templates/apps/api/src/middleware/__tests__/adversarial/csrf-bearer-skip.test.ts +0 -119
  211. package/templates/apps/api/src/middleware/__tests__/adversarial/csrf-cookie-path.test.ts +0 -138
  212. package/templates/apps/api/src/middleware/__tests__/adversarial/csrf-trusted-origins.test.ts +0 -142
  213. package/templates/apps/api/src/middleware/__tests__/adversarial/session-fixation.test.ts +0 -155
  214. package/templates/apps/api/src/middleware/__tests__/adversarial/session-timeout.test.ts +0 -139
  215. package/templates/apps/api/src/middleware/__tests__/auth.bearer-path.test.ts +0 -562
  216. package/templates/apps/api/src/middleware/__tests__/auth.both-present-precedence.test.ts +0 -76
  217. package/templates/apps/api/src/middleware/__tests__/auth.cookie-path.test.ts +0 -220
  218. package/templates/apps/api/src/middleware/__tests__/auth.database-not-configured.test.ts +0 -97
  219. package/templates/apps/api/src/middleware/__tests__/auth.hub-session-path.test.ts +0 -557
  220. package/templates/apps/api/src/middleware/__tests__/auth.neither-present.test.ts +0 -72
  221. package/templates/apps/api/src/middleware/__tests__/auth.optional-cookie.test.ts +0 -140
  222. package/templates/apps/api/src/middleware/__tests__/default-tenant.test.ts +0 -721
  223. package/templates/apps/api/src/middleware/__tests__/rate-limit-cross-isolate.db.test.ts +0 -220
  224. package/templates/apps/api/src/middleware/__tests__/rate-limit-store.test.ts +0 -430
  225. package/templates/apps/api/src/middleware/__tests__/rate-limit.test.ts +0 -1409
  226. package/templates/apps/api/src/middleware/__tests__/write-budget.test.ts +0 -174
  227. package/templates/apps/api/src/middleware/auth.ts +0 -864
  228. package/templates/apps/api/src/middleware/default-tenant.ts +0 -166
  229. package/templates/apps/api/src/middleware/rate-limit.ts +0 -983
  230. package/templates/apps/api/src/openapi/__tests__/openapi.test.ts +0 -391
  231. package/templates/apps/api/src/openapi/__tests__/spec-identity.test.ts +0 -182
  232. package/templates/apps/api/src/openapi/index.ts +0 -18
  233. package/templates/apps/api/src/openapi/spec.ts +0 -2148
  234. package/templates/apps/api/src/openapi/surface-drift.ts +0 -195
  235. package/templates/apps/api/src/routes/aeo/__tests__/index.test.ts +0 -175
  236. package/templates/apps/api/src/routes/aeo/index.ts +0 -107
  237. package/templates/apps/api/src/routes/auth/__tests__/auth-tokens.functional.test.ts +0 -196
  238. package/templates/apps/api/src/routes/auth/__tests__/auth-user.functional.test.ts +0 -249
  239. package/templates/apps/api/src/routes/auth/__tests__/hub-sign-in.test.ts +0 -532
  240. package/templates/apps/api/src/routes/auth/__tests__/tokens.test.ts +0 -313
  241. package/templates/apps/api/src/routes/auth/__tests__/transactional-email.test.ts +0 -413
  242. package/templates/apps/api/src/routes/auth/__tests__/user.test.ts +0 -609
  243. package/templates/apps/api/src/routes/auth/hub-sign-in.ts +0 -242
  244. package/templates/apps/api/src/routes/auth/tokens.ts +0 -211
  245. package/templates/apps/api/src/routes/auth/transactional-email.ts +0 -301
  246. package/templates/apps/api/src/routes/auth/user.ts +0 -305
  247. package/templates/apps/api/src/routes/billing/plan-checkout.ts +0 -332
  248. package/templates/apps/api/src/routes/checkout/__tests__/live-key.test.ts +0 -178
  249. package/templates/apps/api/src/routes/checkout/__tests__/offerings-authorization.test.ts +0 -1426
  250. package/templates/apps/api/src/routes/checkout/__tests__/session.test.ts +0 -448
  251. package/templates/apps/api/src/routes/checkout/__tests__/sessions.test.ts +0 -1742
  252. package/templates/apps/api/src/routes/checkout/index.ts +0 -34
  253. package/templates/apps/api/src/routes/checkout/session.ts +0 -171
  254. package/templates/apps/api/src/routes/checkout/sessions.ts +0 -540
  255. package/templates/apps/api/src/routes/consent/__tests__/account.test.ts +0 -386
  256. package/templates/apps/api/src/routes/consent/__tests__/sign-up-rate-limit.test.ts +0 -160
  257. package/templates/apps/api/src/routes/consent/account.ts +0 -268
  258. package/templates/apps/api/src/routes/consent/cookie.ts +0 -90
  259. package/templates/apps/api/src/routes/consent/index.ts +0 -26
  260. package/templates/apps/api/src/routes/consent/unsubscribe.ts +0 -127
  261. package/templates/apps/api/src/routes/content/__tests__/get-page.test.ts +0 -853
  262. package/templates/apps/api/src/routes/content/__tests__/list-pages.test.ts +0 -230
  263. package/templates/apps/api/src/routes/content/__tests__/list-types.test.ts +0 -44
  264. package/templates/apps/api/src/routes/content/__tests__/locale.test.ts +0 -118
  265. package/templates/apps/api/src/routes/content/__tests__/offerings.test.ts +0 -731
  266. package/templates/apps/api/src/routes/content/__tests__/pricing.test.ts +0 -753
  267. package/templates/apps/api/src/routes/content/__tests__/rate-limit.test.ts +0 -51
  268. package/templates/apps/api/src/routes/content/__tests__/search.test.ts +0 -450
  269. package/templates/apps/api/src/routes/content/__tests__/shown-offerings.test.ts +0 -762
  270. package/templates/apps/api/src/routes/content/get-page.ts +0 -183
  271. package/templates/apps/api/src/routes/content/index.ts +0 -49
  272. package/templates/apps/api/src/routes/content/list-pages.ts +0 -74
  273. package/templates/apps/api/src/routes/content/list-types.ts +0 -19
  274. package/templates/apps/api/src/routes/content/offerings.ts +0 -184
  275. package/templates/apps/api/src/routes/content/pricing.ts +0 -176
  276. package/templates/apps/api/src/routes/content/rate-limit.ts +0 -22
  277. package/templates/apps/api/src/routes/content/search.ts +0 -100
  278. package/templates/apps/api/src/routes/content/shown-offerings.ts +0 -229
  279. package/templates/apps/api/src/routes/leads/__tests__/capture.test.ts +0 -88
  280. package/templates/apps/api/src/routes/leads/__tests__/list.test.ts +0 -171
  281. package/templates/apps/api/src/routes/leads/__tests__/magnet-completion.test.ts +0 -515
  282. package/templates/apps/api/src/routes/leads/__tests__/spoke.test.ts +0 -392
  283. package/templates/apps/api/src/routes/leads/__tests__/track.test.ts +0 -165
  284. package/templates/apps/api/src/routes/leads/index.ts +0 -639
  285. package/templates/apps/api/src/routes/leads/list.ts +0 -104
  286. package/templates/apps/api/src/routes/project-listings/__tests__/configured-application.test.ts +0 -626
  287. package/templates/apps/api/src/routes/project-listings/__tests__/drafts.test.ts +0 -1268
  288. package/templates/apps/api/src/routes/project-listings/__tests__/founder-identity.test.ts +0 -847
  289. package/templates/apps/api/src/routes/project-listings/__tests__/me.test.ts +0 -491
  290. package/templates/apps/api/src/routes/project-listings/__tests__/public.test.ts +0 -476
  291. package/templates/apps/api/src/routes/project-listings/__tests__/resume-email.test.ts +0 -872
  292. package/templates/apps/api/src/routes/project-listings/__tests__/site-answers.test.ts +0 -1022
  293. package/templates/apps/api/src/routes/project-listings/__tests__/site-key.test.ts +0 -484
  294. package/templates/apps/api/src/routes/project-listings/__tests__/structured-address.test.ts +0 -535
  295. package/templates/apps/api/src/routes/project-listings/index.ts +0 -164
  296. package/templates/apps/api/src/routes/project-listings/me.ts +0 -87
  297. package/templates/apps/api/src/routes/project-listings/patch-copy.ts +0 -224
  298. package/templates/apps/api/src/routes/project-listings/patch-draft.ts +0 -102
  299. package/templates/apps/api/src/routes/project-listings/public.ts +0 -98
  300. package/templates/apps/api/src/routes/project-listings/respond.ts +0 -48
  301. package/templates/apps/api/src/routes/project-listings/resume-token.ts +0 -27
  302. package/templates/apps/api/src/routes/project-listings/start.ts +0 -140
  303. package/templates/apps/api/src/routes/project-listings/submit.ts +0 -130
  304. package/templates/apps/api/src/routes/project-listings/verify-email.ts +0 -150
  305. package/templates/apps/api/src/routes/requests/__tests__/confirm.test.ts +0 -686
  306. package/templates/apps/api/src/routes/requests/confirm.ts +0 -601
  307. package/templates/apps/api/src/routes/requests/index.ts +0 -54
  308. package/templates/apps/api/src/routes/test/auth/__tests__/session.test.ts +0 -306
  309. package/templates/apps/api/src/routes/test/auth/session.ts +0 -143
  310. package/templates/apps/api/src/routes/webhooks/README.md +0 -398
  311. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-checkout-consent.test.ts +0 -649
  312. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-dunning.test.ts +0 -749
  313. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-flow-checkout.test.ts +0 -449
  314. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-idempotency.test.ts +0 -264
  315. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-livemode-live.test.ts +0 -159
  316. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-livemode.test.ts +0 -158
  317. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-offerings.test.ts +0 -814
  318. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-org-billing.test.ts +0 -301
  319. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-proposal-paid.test.ts +0 -369
  320. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-rate-limit.test.ts +0 -215
  321. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-request-paid.test.ts +0 -301
  322. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-site-filter.test.ts +0 -809
  323. package/templates/apps/api/src/routes/webhooks/__tests__/stripe.test.ts +0 -1155
  324. package/templates/apps/api/src/routes/webhooks/index.ts +0 -141
  325. package/templates/apps/api/src/routes/webhooks/stripe-offerings.ts +0 -384
  326. package/templates/apps/api/src/routes/webhooks/stripe.ts +0 -2028
  327. package/templates/apps/api/src/services/__tests__/abandon-email.test.ts +0 -645
  328. package/templates/apps/api/src/services/__tests__/answer-distributions.test.ts +0 -132
  329. package/templates/apps/api/src/services/__tests__/audit-log.test.ts +0 -1028
  330. package/templates/apps/api/src/services/__tests__/checkout-plan.test.ts +0 -313
  331. package/templates/apps/api/src/services/__tests__/consent-ledger.test.ts +0 -503
  332. package/templates/apps/api/src/services/__tests__/consent-migration.test.ts +0 -65
  333. package/templates/apps/api/src/services/__tests__/consent.test.ts +0 -299
  334. package/templates/apps/api/src/services/__tests__/default-tenant.test.ts +0 -147
  335. package/templates/apps/api/src/services/__tests__/deliverable-fulfillment.test.ts +0 -877
  336. package/templates/apps/api/src/services/__tests__/deliverable-resend.test.ts +0 -379
  337. package/templates/apps/api/src/services/__tests__/dunning-policy.test.ts +0 -368
  338. package/templates/apps/api/src/services/__tests__/entitlements.test.ts +0 -142
  339. package/templates/apps/api/src/services/__tests__/hub-sign-in.test.ts +0 -854
  340. package/templates/apps/api/src/services/__tests__/keyless-workspace-predicate.test.ts +0 -234
  341. package/templates/apps/api/src/services/__tests__/lead-accept-user.test.ts +0 -251
  342. package/templates/apps/api/src/services/__tests__/lead-routing.test.ts +0 -2660
  343. package/templates/apps/api/src/services/__tests__/listing-config.test.ts +0 -166
  344. package/templates/apps/api/src/services/__tests__/magnet-completion.test.ts +0 -389
  345. package/templates/apps/api/src/services/__tests__/person.test.ts +0 -1204
  346. package/templates/apps/api/src/services/__tests__/plan-offerings.test.ts +0 -450
  347. package/templates/apps/api/src/services/__tests__/project-listings.counts.test.ts +0 -202
  348. package/templates/apps/api/src/services/__tests__/project-listings.fence.test.ts +0 -151
  349. package/templates/apps/api/src/services/__tests__/public-site-resolver.test.ts +0 -137
  350. package/templates/apps/api/src/services/__tests__/request-confirm.test.ts +0 -531
  351. package/templates/apps/api/src/services/__tests__/revalidation.test.ts +0 -372
  352. package/templates/apps/api/src/services/__tests__/slack-notify.test.ts +0 -348
  353. package/templates/apps/api/src/services/__tests__/spoke-resolution.test.ts +0 -660
  354. package/templates/apps/api/src/services/__tests__/usage-aggregation.test.ts +0 -941
  355. package/templates/apps/api/src/services/__tests__/usage-credits.test.ts +0 -588
  356. package/templates/apps/api/src/services/__tests__/verified-email.test.ts +0 -78
  357. package/templates/apps/api/src/services/abandon-email.ts +0 -336
  358. package/templates/apps/api/src/services/aeo-score.ts +0 -325
  359. package/templates/apps/api/src/services/answer-distributions.ts +0 -138
  360. package/templates/apps/api/src/services/audit-log.ts +0 -961
  361. package/templates/apps/api/src/services/checkout-buyer.ts +0 -168
  362. package/templates/apps/api/src/services/consent.ts +0 -834
  363. package/templates/apps/api/src/services/default-tenant.ts +0 -416
  364. package/templates/apps/api/src/services/deliverable-fulfillment.ts +0 -750
  365. package/templates/apps/api/src/services/dunning-policy.ts +0 -294
  366. package/templates/apps/api/src/services/enrichment-shim.ts +0 -53
  367. package/templates/apps/api/src/services/entitlements.ts +0 -338
  368. package/templates/apps/api/src/services/hub-sign-in.ts +0 -472
  369. package/templates/apps/api/src/services/lead-accept-user.ts +0 -126
  370. package/templates/apps/api/src/services/lead-promotion.ts +0 -160
  371. package/templates/apps/api/src/services/lead-routing.ts +0 -1372
  372. package/templates/apps/api/src/services/leads-inbox.ts +0 -312
  373. package/templates/apps/api/src/services/listing-config.ts +0 -178
  374. package/templates/apps/api/src/services/magnet-completion.ts +0 -242
  375. package/templates/apps/api/src/services/offerings/__tests__/catalog.test.ts +0 -348
  376. package/templates/apps/api/src/services/offerings/__tests__/checkout-session-record.test.ts +0 -268
  377. package/templates/apps/api/src/services/offerings/__tests__/connection.test.ts +0 -975
  378. package/templates/apps/api/src/services/offerings/__tests__/fixtures.ts +0 -416
  379. package/templates/apps/api/src/services/offerings/__tests__/org-products.test.ts +0 -400
  380. package/templates/apps/api/src/services/offerings/__tests__/readers.test.ts +0 -685
  381. package/templates/apps/api/src/services/offerings/__tests__/source.test.ts +0 -231
  382. package/templates/apps/api/src/services/offerings/catalog.ts +0 -318
  383. package/templates/apps/api/src/services/offerings/checkout-authorization.ts +0 -403
  384. package/templates/apps/api/src/services/offerings/checkout-session-record.ts +0 -192
  385. package/templates/apps/api/src/services/offerings/connection.ts +0 -1083
  386. package/templates/apps/api/src/services/offerings/index.ts +0 -614
  387. package/templates/apps/api/src/services/offerings/source.ts +0 -140
  388. package/templates/apps/api/src/services/offerings/store.ts +0 -150
  389. package/templates/apps/api/src/services/owner-workspaces.ts +0 -132
  390. package/templates/apps/api/src/services/person.ts +0 -1211
  391. package/templates/apps/api/src/services/plan-offerings.ts +0 -125
  392. package/templates/apps/api/src/services/project-listing-resume-email.ts +0 -326
  393. package/templates/apps/api/src/services/project-listings.ts +0 -2085
  394. package/templates/apps/api/src/services/public-site-resolver.ts +0 -396
  395. package/templates/apps/api/src/services/request-confirm.ts +0 -698
  396. package/templates/apps/api/src/services/revalidation.ts +0 -235
  397. package/templates/apps/api/src/services/slack-notify.ts +0 -291
  398. package/templates/apps/api/src/services/usage-aggregation.ts +0 -516
  399. package/templates/apps/api/src/services/usage-credits.ts +0 -340
  400. package/templates/apps/api/src/services/verified-email.ts +0 -71
  401. package/templates/apps/mcp/__tests__/abuse/daily-cap.test.ts +0 -52
  402. package/templates/apps/mcp/__tests__/abuse/email-validator.test.ts +0 -46
  403. package/templates/apps/mcp/__tests__/abuse/guard.test.ts +0 -198
  404. package/templates/apps/mcp/__tests__/abuse/honeypot.test.ts +0 -36
  405. package/templates/apps/mcp/__tests__/abuse/user-agent-deny.test.ts +0 -54
  406. package/templates/apps/mcp/__tests__/aeo-cli-parity.test.ts +0 -116
  407. package/templates/apps/mcp/__tests__/audit-single-page.test.ts +0 -299
  408. package/templates/apps/mcp/__tests__/boot.test.ts +0 -280
  409. package/templates/apps/mcp/__tests__/catalog-drift.test.ts +0 -359
  410. package/templates/apps/mcp/__tests__/config/modules.test.ts +0 -78
  411. package/templates/apps/mcp/__tests__/get_business_hours.test.ts +0 -82
  412. package/templates/apps/mcp/__tests__/get_faq.test.ts +0 -80
  413. package/templates/apps/mcp/__tests__/get_locations.test.ts +0 -65
  414. package/templates/apps/mcp/__tests__/get_offerings.test.ts +0 -557
  415. package/templates/apps/mcp/__tests__/get_pricing.test.ts +0 -524
  416. package/templates/apps/mcp/__tests__/get_site_info.test.ts +0 -81
  417. package/templates/apps/mcp/__tests__/http-transport.test.ts +0 -1232
  418. package/templates/apps/mcp/__tests__/index.test.ts +0 -195
  419. package/templates/apps/mcp/__tests__/lib/audit-single-page-readiness-scan.test.ts +0 -191
  420. package/templates/apps/mcp/__tests__/lib/commerce-claim.test.ts +0 -531
  421. package/templates/apps/mcp/__tests__/lib/content-adapter-parity.test.ts +0 -70
  422. package/templates/apps/mcp/__tests__/lib/content-adapter.test.ts +0 -162
  423. package/templates/apps/mcp/__tests__/lib/content-root.test.ts +0 -93
  424. package/templates/apps/mcp/__tests__/lib/errors.test.ts +0 -75
  425. package/templates/apps/mcp/__tests__/lib/fail-closed-tools.test.ts +0 -180
  426. package/templates/apps/mcp/__tests__/lib/public-workspace.test.ts +0 -124
  427. package/templates/apps/mcp/__tests__/list_pages.test.ts +0 -268
  428. package/templates/apps/mcp/__tests__/locale.test.ts +0 -120
  429. package/templates/apps/mcp/__tests__/module-exclusion.test.ts +0 -175
  430. package/templates/apps/mcp/__tests__/purchase-disabled.test.ts +0 -101
  431. package/templates/apps/mcp/__tests__/rate-limit-write.test.ts +0 -189
  432. package/templates/apps/mcp/__tests__/read_content.test.ts +0 -511
  433. package/templates/apps/mcp/__tests__/request_callback.test.ts +0 -160
  434. package/templates/apps/mcp/__tests__/search_content.test.ts +0 -271
  435. package/templates/apps/mcp/__tests__/server.test.ts +0 -388
  436. package/templates/apps/mcp/__tests__/start_purchase.test.ts +0 -448
  437. package/templates/apps/mcp/__tests__/submit_lead.test.ts +0 -222
  438. package/templates/apps/mcp/__tests__/subscribe_newsletter.test.ts +0 -152
  439. package/templates/apps/mcp/__tests__/tools/create_project.test.ts +0 -243
  440. package/templates/apps/mcp/__tests__/tools/purchase.test.ts +0 -451
  441. package/templates/apps/mcp/src/abuse/daily-cap.ts +0 -47
  442. package/templates/apps/mcp/src/abuse/email-validator.ts +0 -25
  443. package/templates/apps/mcp/src/abuse/honeypot.ts +0 -21
  444. package/templates/apps/mcp/src/abuse/index.ts +0 -349
  445. package/templates/apps/mcp/src/abuse/user-agent-deny.ts +0 -58
  446. package/templates/apps/mcp/src/boot.ts +0 -167
  447. package/templates/apps/mcp/src/config/modules.ts +0 -43
  448. package/templates/apps/mcp/src/http-transport.ts +0 -564
  449. package/templates/apps/mcp/src/lib/audit-single-page.ts +0 -308
  450. package/templates/apps/mcp/src/lib/commerce-claim.ts +0 -263
  451. package/templates/apps/mcp/src/lib/content-adapter.ts +0 -116
  452. package/templates/apps/mcp/src/lib/empty-content-adapter.ts +0 -140
  453. package/templates/apps/mcp/src/lib/errors.ts +0 -61
  454. package/templates/apps/mcp/src/lib/license-key-store.ts +0 -45
  455. package/templates/apps/mcp/src/lib/locales.ts +0 -171
  456. package/templates/apps/mcp/src/lib/prisma.ts +0 -39
  457. package/templates/apps/mcp/src/lib/public-workspace.ts +0 -133
  458. package/templates/apps/mcp/src/lib/resolve-locale.ts +0 -30
  459. package/templates/apps/mcp/src/lib/shown-offerings.ts +0 -105
  460. package/templates/apps/mcp/src/lib/site-config.ts +0 -53
  461. package/templates/apps/mcp/src/lib/stripe-tax-signal.ts +0 -59
  462. package/templates/apps/mcp/src/request-context.ts +0 -52
  463. package/templates/apps/mcp/src/server.ts +0 -343
  464. package/templates/apps/mcp/src/serverless-app.ts +0 -88
  465. package/templates/apps/mcp/src/tools/audit.ts +0 -127
  466. package/templates/apps/mcp/src/tools/capture_lead.ts +0 -66
  467. package/templates/apps/mcp/src/tools/create_project.ts +0 -134
  468. package/templates/apps/mcp/src/tools/get_business_hours.ts +0 -68
  469. package/templates/apps/mcp/src/tools/get_faq.ts +0 -71
  470. package/templates/apps/mcp/src/tools/get_locations.ts +0 -88
  471. package/templates/apps/mcp/src/tools/get_offerings.ts +0 -96
  472. package/templates/apps/mcp/src/tools/get_pricing.ts +0 -94
  473. package/templates/apps/mcp/src/tools/get_site_info.ts +0 -86
  474. package/templates/apps/mcp/src/tools/index.ts +0 -138
  475. package/templates/apps/mcp/src/tools/list_pages.ts +0 -68
  476. package/templates/apps/mcp/src/tools/person_notes.ts +0 -25
  477. package/templates/apps/mcp/src/tools/proposals.ts +0 -27
  478. package/templates/apps/mcp/src/tools/purchase.ts +0 -205
  479. package/templates/apps/mcp/src/tools/read_content.ts +0 -81
  480. package/templates/apps/mcp/src/tools/request_callback.ts +0 -52
  481. package/templates/apps/mcp/src/tools/search_content.ts +0 -63
  482. package/templates/apps/mcp/src/tools/subscribe_newsletter.ts +0 -54
  483. package/templates/apps/mcp/src/workspace-server.ts +0 -224
  484. package/templates/database/CHANGELOG.md +0 -981
  485. package/templates/database/LICENSE +0 -202
  486. package/templates/database/NOTICE +0 -2
  487. package/templates/database/README.md +0 -243
  488. package/templates/database/__tests__/agents.db.test.ts +0 -320
  489. package/templates/database/__tests__/appointment.db.test.ts +0 -106
  490. package/templates/database/__tests__/artifact-content-store.db.test.ts +0 -316
  491. package/templates/database/__tests__/composite-fence.db.test.ts +0 -206
  492. package/templates/database/__tests__/consent-ledger.db.test.ts +0 -345
  493. package/templates/database/__tests__/consent-source-checkout-migration.test.ts +0 -79
  494. package/templates/database/__tests__/fence-fan-out.db.test.ts +0 -715
  495. package/templates/database/__tests__/fixtures/appointment-create-probe.ts +0 -79
  496. package/templates/database/__tests__/fixtures/person-backfill.json +0 -264
  497. package/templates/database/__tests__/fixtures/person-contact-backfill.json +0 -182
  498. package/templates/database/__tests__/fixtures/project-listing-consent-probe.ts +0 -100
  499. package/templates/database/__tests__/flow-completion-migration.test.ts +0 -115
  500. package/templates/database/__tests__/flow-completion.db.test.ts +0 -136
  501. package/templates/database/__tests__/flow-workspace-key.db.test.ts +0 -263
  502. package/templates/database/__tests__/flows-listing-diagnostic.test.ts +0 -392
  503. package/templates/database/__tests__/flows-presets.test.ts +0 -173
  504. package/templates/database/__tests__/in-page-magnets-migration.test.ts +0 -161
  505. package/templates/database/__tests__/lead-idempotency-key.db.test.ts +0 -92
  506. package/templates/database/__tests__/member-area.db.test.ts +0 -257
  507. package/templates/database/__tests__/member-contract-migration.test.ts +0 -85
  508. package/templates/database/__tests__/member-contract.db.test.ts +0 -413
  509. package/templates/database/__tests__/offerings-checkout-session.db.test.ts +0 -270
  510. package/templates/database/__tests__/offerings-migration.test.ts +0 -197
  511. package/templates/database/__tests__/offerings-shown-price-ids-migration.test.ts +0 -86
  512. package/templates/database/__tests__/offerings.db.test.ts +0 -303
  513. package/templates/database/__tests__/outbound-message-action.db.test.ts +0 -80
  514. package/templates/database/__tests__/person-contact.db.test.ts +0 -563
  515. package/templates/database/__tests__/person-notes.db.test.ts +0 -249
  516. package/templates/database/__tests__/person.db.test.ts +0 -586
  517. package/templates/database/__tests__/piece-kind-migration.test.ts +0 -67
  518. package/templates/database/__tests__/piece-kind.db.test.ts +0 -208
  519. package/templates/database/__tests__/prefixed-ids.db.test.ts +0 -222
  520. package/templates/database/__tests__/project-listing-consent-at.db.test.ts +0 -111
  521. package/templates/database/__tests__/seed.test.ts +0 -272
  522. package/templates/database/__tests__/spoke-registry.db.test.ts +0 -191
  523. package/templates/database/__tests__/tenancy.test.ts +0 -141
  524. package/templates/database/__tests__/trial-magnet-migration.test.ts +0 -186
  525. package/templates/database/__tests__/user-cascade.test.ts +0 -140
  526. package/templates/database/_gitignore +0 -8
  527. package/templates/database/auth/.gitkeep +0 -0
  528. package/templates/database/auth/schema.prisma +0 -641
  529. package/templates/database/config/.gitkeep +0 -0
  530. package/templates/database/config/schema.prisma +0 -441
  531. package/templates/database/content/.gitkeep +0 -0
  532. package/templates/database/content/schema.prisma +0 -339
  533. package/templates/database/eslint.config.mjs +0 -69
  534. package/templates/database/flows/listing-diagnostic.ts +0 -182
  535. package/templates/database/flows/presets.ts +0 -315
  536. package/templates/database/inbox/.gitkeep +0 -0
  537. package/templates/database/inbox/README.md +0 -3
  538. package/templates/database/inbox/__tests__/schema.test.ts +0 -44
  539. package/templates/database/inbox/schema.prisma +0 -1447
  540. package/templates/database/jest.config.cjs +0 -36
  541. package/templates/database/migrations/20260508000000_add_inbox_namespace/migration.sql +0 -328
  542. package/templates/database/migrations/20260513000000_better_auth_migration/migration.sql +0 -100
  543. package/templates/database/migrations/20260515000000_add_user_billing_fields/migration.sql +0 -28
  544. package/templates/database/migrations/20260516000000_add_user_tier_care_plan_seat/migration.sql +0 -25
  545. package/templates/database/migrations/20260518000000_add_telemetry_records/migration.sql +0 -42
  546. package/templates/database/migrations/20260525000000_theme_wiring/migration.sql +0 -67
  547. package/templates/database/migrations/20260710000000_retire_commercial_tier/migration.sql +0 -21
  548. package/templates/database/migrations/20260712215647_add_multi_tenant_tenancy/migration.sql +0 -201
  549. package/templates/database/migrations/20260713143320_reanchor_site_config_to_workspace/migration.sql +0 -67
  550. package/templates/database/migrations/20260713174000_add_audit_logs/migration.sql +0 -46
  551. package/templates/database/migrations/20260713190000_drop_telemetry_records/migration.sql +0 -25
  552. package/templates/database/migrations/20260713192000_add_uuidv7_function/migration.sql +0 -49
  553. package/templates/database/migrations/20260713192429_prefixed_uuid_entity_ids/migration.sql +0 -197
  554. package/templates/database/migrations/20260713200000_add_org_billing/migration.sql +0 -32
  555. package/templates/database/migrations/20260714000000_add_lead_promotion_fields/migration.sql +0 -22
  556. package/templates/database/migrations/20260714010000_add_usage_billing_content_models/migration.sql +0 -151
  557. package/templates/database/migrations/20260714020000_add_usage_billing_auth_config_models/migration.sql +0 -223
  558. package/templates/database/migrations/20260714030000_credit_balance_non_negative/migration.sql +0 -22
  559. package/templates/database/migrations/20260714030000_widen_usage_billing_report_aggregates/migration.sql +0 -32
  560. package/templates/database/migrations/20260810233516_add_flow_engine_models/migration.sql +0 -40
  561. package/templates/database/migrations/20260811020000_add_flow_session_abandon_email_columns/migration.sql +0 -4
  562. package/templates/database/migrations/20260811030000_add_flow_session_abandon_email_index/migration.sql +0 -2
  563. package/templates/database/migrations/20260811040000_add_flow_session_segment/migration.sql +0 -2
  564. package/templates/database/migrations/20260811050000_add_deliverable_models/migration.sql +0 -29
  565. package/templates/database/migrations/20260812000000_add_deliverable_grant_send_columns/migration.sql +0 -6
  566. package/templates/database/migrations/20260902222948_add_waitlist_experiment_models/migration.sql +0 -39
  567. package/templates/database/migrations/20260902224500_add_waitlist_id_format_checks/migration.sql +0 -24
  568. package/templates/database/migrations/20260903004112_add_flow_session_flags_aeo_score/migration.sql +0 -3
  569. package/templates/database/migrations/20260903010000_add_playbook_instance/migration.sql +0 -33
  570. package/templates/database/migrations/20260904000000_add_waitlist_followup_send/migration.sql +0 -30
  571. package/templates/database/migrations/20260905230000_add_flow_checkout/migration.sql +0 -47
  572. package/templates/database/migrations/20260906000000_add_flow_checkout_idempotency/migration.sql +0 -16
  573. package/templates/database/migrations/20260907120000_add_project_listing/migration.sql +0 -47
  574. package/templates/database/migrations/20260907130000_add_project_listing_slack_columns/migration.sql +0 -10
  575. package/templates/database/migrations/20260907180000_add_listing_csv_send/migration.sql +0 -26
  576. package/templates/database/migrations/20260909120000_project_listings_platform/migration.sql +0 -90
  577. package/templates/database/migrations/20260909180000_listing_draft_and_fields/migration.sql +0 -174
  578. package/templates/database/migrations/20260910120000_listing_public_site_key/migration.sql +0 -14
  579. package/templates/database/migrations/20260911120000_listing_copy_edit_audit/migration.sql +0 -25
  580. package/templates/database/migrations/20260911140000_listing_structured_address/migration.sql +0 -32
  581. package/templates/database/migrations/20260911180000_consent_grants/migration.sql +0 -71
  582. package/templates/database/migrations/20260911200000_listing_site_answers/migration.sql +0 -30
  583. package/templates/database/migrations/20260912120000_listing_owner_link/migration.sql +0 -49
  584. package/templates/database/migrations/20260914120000_listing_founder_identity/migration.sql +0 -123
  585. package/templates/database/migrations/20260915120000_project_listing_solution/migration.sql +0 -15
  586. package/templates/database/migrations/20260916120000_artifact_content_store/migration.sql +0 -158
  587. package/templates/database/migrations/20260917120000_callback_request_confirm/migration.sql +0 -40
  588. package/templates/database/migrations/20260918120000_add_appointment/migration.sql +0 -67
  589. package/templates/database/migrations/20260918120000_asset_metadata_columns/migration.sql +0 -70
  590. package/templates/database/migrations/20260919120000_flow_workspace_key/migration.sql +0 -181
  591. package/templates/database/migrations/20260919130000_flow_definition_admin_columns/migration.sql +0 -172
  592. package/templates/database/migrations/20260919130000_workspace_meetings/migration.sql +0 -41
  593. package/templates/database/migrations/20260919140000_inbox_workspace_key/migration.sql +0 -185
  594. package/templates/database/migrations/20260920120000_lead_handled_at/migration.sql +0 -70
  595. package/templates/database/migrations/20260920130000_lead_workspace_source_index/migration.sql +0 -57
  596. package/templates/database/migrations/20260921120000_deliverable_grant_workspace_key/migration.sql +0 -68
  597. package/templates/database/migrations/20260922120000_tenancy_fence/migration.sql +0 -1067
  598. package/templates/database/migrations/20260923120000_listing_capturing_magnet/migration.sql +0 -210
  599. package/templates/database/migrations/20261003120000_spoke_registry/migration.sql +0 -80
  600. package/templates/database/migrations/20261003130000_scheduling_connection/migration.sql +0 -49
  601. package/templates/database/migrations/20261005120000_agents/migration.sql +0 -84
  602. package/templates/database/migrations/20261008120000_user_last_workspace/migration.sql +0 -35
  603. package/templates/database/migrations/20261008130000_lead_idempotency_key/migration.sql +0 -20
  604. package/templates/database/migrations/20261009120000_agent_grants/migration.sql +0 -33
  605. package/templates/database/migrations/20261010120000_person/migration.sql +0 -106
  606. package/templates/database/migrations/20261010121000_person_backfill/migration.sql +0 -132
  607. package/templates/database/migrations/20261010130000_agent_grants_people_read/migration.sql +0 -20
  608. package/templates/database/migrations/20261011120000_member_area/migration.sql +0 -158
  609. package/templates/database/migrations/20261011130000_agent_grants_member_pieces_manage/migration.sql +0 -21
  610. package/templates/database/migrations/20261012120000_member_contract/migration.sql +0 -192
  611. package/templates/database/migrations/20261013120000_lead_spoke_checkout/migration.sql +0 -20
  612. package/templates/database/migrations/20261014120000_consent_ledger/migration.sql +0 -122
  613. package/templates/database/migrations/20261014120000_person_contact/migration.sql +0 -231
  614. package/templates/database/migrations/20261015120000_person_notes/migration.sql +0 -77
  615. package/templates/database/migrations/20261015120000_rate_limit_counters/migration.sql +0 -43
  616. package/templates/database/migrations/20261016120000_piece_kind/migration.sql +0 -95
  617. package/templates/database/migrations/20261017120000_outbound_message_action/migration.sql +0 -30
  618. package/templates/database/migrations/20261018120000_flow_completion/migration.sql +0 -52
  619. package/templates/database/migrations/20261019120000_consent_source_checkout/migration.sql +0 -27
  620. package/templates/database/migrations/20261020120000_offerings_data_model/migration.sql +0 -146
  621. package/templates/database/migrations/20261021120000_offerings_checkout_session/migration.sql +0 -77
  622. package/templates/database/migrations/20261022120000_in_page_magnets/migration.sql +0 -45
  623. package/templates/database/migrations/20261023120000_offerings_shown_price_ids/migration.sql +0 -47
  624. package/templates/database/migrations/20261024120000_organization_plan_checkout_session/migration.sql +0 -16
  625. package/templates/database/migrations/20261025120000_trial_magnet/migration.sql +0 -28
  626. package/templates/database/migrations/20261026120000_trial_magnet_proof_line/migration.sql +0 -23
  627. package/templates/database/migrations/migration_lock.toml +0 -3
  628. package/templates/database/ops/.gitkeep +0 -0
  629. package/templates/database/ops/schema.prisma +0 -43
  630. package/templates/database/package.json +0 -89
  631. package/templates/database/schema.prisma +0 -71
  632. package/templates/database/scripts/db-generate-locked.sh +0 -80
  633. package/templates/database/scripts/person-backfill.sql +0 -132
  634. package/templates/database/tenancy.ts +0 -183
  635. package/templates/database/tsconfig.build.json +0 -16
  636. package/templates/database/tsconfig.flows.json +0 -15
  637. package/templates/database/tsconfig.json +0 -16
  638. package/templates/database/tsconfig.tenancy.json +0 -14
@@ -1,941 +0,0 @@
1
- /**
2
- * @file usage-aggregation.test.ts
3
- * @description Unit tests for the usage-aggregation service (ADR 0009 D3
4
- * service-layer pattern; spec
5
- * docs/specs/3705-s2-usage-aggregation-service-spec.md §5).
6
- *
7
- * External dependency boundary mocked:
8
- * - apps/api/src/lib/prisma — the repo-standard `__mocks__/prisma.ts`
9
- * manual mock (`jest.mock("../../lib/prisma.js")`), extended with
10
- * `usageEvent.aggregate` + `usageBillingReport.upsert` (#3714, FEAT-047
11
- * P2.S2 — not yet in the generated Prisma client this package compiles
12
- * against; `aggregate` since #3739 M2, was `findMany`). `usage-aggregation.ts`
13
- * casts `prisma` to a local structural delegate type
14
- * (`UsageAggregationPrismaDelegates`); this test does the same so the
15
- * mock's `jest.fn()` methods type-check the same way the service's calls
16
- * do.
17
- *
18
- * `usageEvent.aggregate` is given a REALISTIC `_sum`/`_count` implementation
19
- * over an in-memory fixture "table" (mirroring `usage-metering.test.ts`'s
20
- * `seedMarkupTable` pattern) so the org-isolation (AC-4/AC-UB-10) and
21
- * period-window tests exercise the actual query-boundary filtering the
22
- * service relies on, not just a static per-call stub — the fixture applies
23
- * the SAME `where` filter a real Postgres aggregate would, then sums the
24
- * matching rows itself (standing in for the DB's SUM).
25
- *
26
- * `usageBillingReport.upsert` is given REALISTIC upsert semantics over an
27
- * in-memory table keyed by the compound `(organizationId, periodStart,
28
- * periodEnd)` unique constraint, so the idempotency test (AC-2) proves no
29
- * duplicate row is ever created on re-run — not merely that `upsert` was
30
- * called twice.
31
- *
32
- * COLUMN-WIDTH ENFORCEMENT (#3738 H2 — load-bearing). The upsert fixture parses
33
- * the REAL `database/content/schema.prisma` at test time, derives each persisted
34
- * column's representable range from its declared type (`@db.Decimal(p,s)` /
35
- * `Int` / `BigInt`), and THROWS the same errors Postgres would on overflow
36
- * (`numeric field overflow`, `integer out of range`).
37
- *
38
- * This is what makes the $10k-month / 2.15B-token tests real rather than
39
- * decorative. With a plain `jest.fn()` upsert an overflow is INVISIBLE — the
40
- * mock happily accepts any JS number — so the H2 defect (aggregate columns
41
- * sized for a single event: `Decimal(10,6)` = max $9,999.999999, `Int` = max
42
- * 2.15B tokens) would sail through a mocked suite untouched, which is exactly
43
- * how it reached `main`. By grounding the fixture in the actual schema file,
44
- * the overflow tests FAIL against the pre-fix columns and pass only once the
45
- * migration widens them — and they can never drift from the schema, because
46
- * they read it.
47
- */
48
-
49
- // eslint-disable-next-line no-restricted-syntax -- lib/prisma.ts wraps the external DB boundary (PrismaClient requires a live connection); __mocks__/prisma.ts is the repo-standard test double for this boundary.
50
- jest.mock("../../lib/prisma.js");
51
-
52
- import { readFileSync } from "node:fs";
53
- import { resolve } from "node:path";
54
-
55
- import { prisma } from "../../lib/prisma.js";
56
- import {
57
- aggregateUsagePeriod,
58
- type AggregateResult,
59
- type UsageAggregationPrismaDelegates,
60
- } from "../usage-aggregation";
61
-
62
- // The generated Prisma client doesn't carry the FEAT-047 P1 models yet
63
- // (#3709/#3710) — see the file docblock. Same structural cast the service
64
- // source uses.
65
- // eslint-disable-next-line no-restricted-syntax -- prisma's TS type resolves to the real (not-yet-augmented) PrismaClient; the FEAT-047 content-namespace delegates (usageEvent/usageBillingReport, #3709) don't exist on it yet, so the intermediate `unknown` widening is required, not gratuitous — mirrors the identical cast in usage-aggregation.ts.
66
- const db = prisma as unknown as UsageAggregationPrismaDelegates;
67
-
68
- /** The delegate methods are typed as plain functions; the mock behind them is a jest.Mock. */
69
- const mockOf = (fn: unknown): jest.Mock => fn as jest.Mock;
70
-
71
- const ORG_A = "org_00000000-0000-7000-8000-0000000000a1";
72
- const ORG_B = "org_00000000-0000-7000-8000-0000000000b2";
73
-
74
- /** March 2026 (UTC) — the test period. */
75
- const PERIOD_START = new Date(Date.UTC(2026, 2, 1));
76
- const PERIOD_END = new Date(Date.UTC(2026, 3, 1)); // April 1, UTC — exclusive upper bound
77
- /** Any timestamp within the period; the service normalizes to the month start. */
78
- const MID_PERIOD_DATE = new Date(Date.UTC(2026, 2, 1));
79
-
80
- // ── Schema-grounded column limits (#3738 H2) ─────────────────────────────────
81
- // Parsed from the REAL schema so the fixture's overflow behaviour can never
82
- // drift from the migration. See the file docblock for why this is load-bearing.
83
-
84
- const SCHEMA_PATH = resolve(
85
- __dirname,
86
- "../../../../../database/content/schema.prisma",
87
- );
88
-
89
- /** The `UsageBillingReport` model block, verbatim from database/content/schema.prisma. */
90
- function readReportModelBlock(): string {
91
- const schema = readFileSync(SCHEMA_PATH, "utf8");
92
- const match = schema.match(/model\s+UsageBillingReport\s*\{([\s\S]*?)\n\}/);
93
- if (!match?.[1]) {
94
- throw new Error(
95
- `Could not locate the UsageBillingReport model in ${SCHEMA_PATH}`,
96
- );
97
- }
98
- return match[1];
99
- }
100
-
101
- /** Max value a Postgres `numeric(p, s)` column can hold: 10^(p-s) - 10^-s. */
102
- function decimalMax(precision: number, scale: number): number {
103
- return 10 ** (precision - scale) - 10 ** -scale;
104
- }
105
-
106
- const INT4_MAX = 2_147_483_647;
107
- const INT8_MAX = 9_223_372_036_854_775_807n;
108
-
109
- type ColumnLimit =
110
- | { kind: "decimal"; max: number }
111
- | { kind: "int4"; max: number }
112
- | { kind: "int8"; max: bigint };
113
-
114
- /**
115
- * Derives the representable range of a `UsageBillingReport` field from the
116
- * live schema — `@db.Decimal(p,s)` -> numeric bounds; bare `Int` -> int4;
117
- * `BigInt` -> int8.
118
- */
119
- function columnLimit(field: string): ColumnLimit {
120
- const block = readReportModelBlock();
121
- const line = block
122
- .split("\n")
123
- .find((l) => new RegExp(`^\\s*${field}\\s+\\w`).test(l));
124
- if (!line) {
125
- throw new Error(`Field ${field} not found on UsageBillingReport`);
126
- }
127
-
128
- const dec = line.match(/@db\.Decimal\((\d+)\s*,\s*(\d+)\)/);
129
- if (dec) {
130
- return { kind: "decimal", max: decimalMax(Number(dec[1]), Number(dec[2])) };
131
- }
132
- if (/^\s*\w+\s+BigInt\b/.test(line)) return { kind: "int8", max: INT8_MAX };
133
- if (/^\s*\w+\s+Int\b/.test(line)) return { kind: "int4", max: INT4_MAX };
134
- throw new Error(`Unrecognised column type for ${field}: ${line.trim()}`);
135
- }
136
-
137
- /** The persisted columns the service writes, with their schema-derived limits. */
138
- const PERSISTED_COLUMNS = [
139
- "totalProviderCost",
140
- "totalMarkupAmount",
141
- "totalBilledAmount",
142
- "totalTokens",
143
- "eventCount",
144
- ] as const;
145
-
146
- /**
147
- * Throws exactly as Postgres would when a written value exceeds its column.
148
- * This is the check a `jest.fn()` upsert silently skips — and the reason the
149
- * H2 overflow reached `main`.
150
- */
151
- function assertFitsColumns(data: Record<string, unknown>): void {
152
- for (const field of PERSISTED_COLUMNS) {
153
- if (!(field in data)) continue;
154
- const raw = data[field];
155
- if (raw === undefined || raw === null) continue;
156
-
157
- const limit = columnLimit(field);
158
- const value = typeof raw === "bigint" ? raw : Number(raw);
159
-
160
- if (limit.kind === "decimal") {
161
- if (Math.abs(Number(value)) > limit.max) {
162
- throw new Error(
163
- `numeric field overflow: a field with precision limit ${limit.max} ` +
164
- `cannot hold ${String(value)} (column ${field})`,
165
- );
166
- }
167
- } else if (limit.kind === "int4") {
168
- if (Math.abs(Number(value)) > limit.max) {
169
- throw new Error(`integer out of range (column ${field})`);
170
- }
171
- } else {
172
- const asBig =
173
- typeof value === "bigint" ? value : BigInt(Math.trunc(Number(value)));
174
- if (asBig > limit.max || asBig < -limit.max) {
175
- throw new Error(`bigint out of range (column ${field})`);
176
- }
177
- }
178
- }
179
- }
180
-
181
- type FixtureEvent = {
182
- organizationId: string;
183
- completionStatus: string;
184
- createdAt: Date;
185
- providerCostUsd: unknown;
186
- billedCostUsd: unknown;
187
- totalTokens: unknown;
188
- };
189
-
190
- /** The in-memory "usage_events" fixture table `aggregate` sums over. */
191
- let eventTable: FixtureEvent[];
192
- /** The in-memory "usage_billing_reports" table, keyed by the compound unique constraint. */
193
- let reportTable: Map<string, Record<string, unknown> & { id: string }>;
194
- let reportIdCounter: number;
195
-
196
- function reportKey(organizationId: string, periodStart: Date, periodEnd: Date): string {
197
- return `${organizationId}|${periodStart.toISOString()}|${periodEnd.toISOString()}`;
198
- }
199
-
200
- /**
201
- * Coerces a fixture row's value the same way a real Postgres NOT NULL
202
- * Decimal/Int column would have to (the fixture's inputs are already
203
- * numeric or Decimal-shaped by construction — `seedEvent`'s type only
204
- * accepts those) — mirrors the service's own `toNumber` for Decimal-like
205
- * `{ toNumber() }` fixture rows (#3738 M1's coercion tests).
206
- */
207
- function fixtureToNumber(value: unknown): number {
208
- if (typeof value === "number") return value;
209
- if (
210
- value !== null &&
211
- typeof value === "object" &&
212
- "toNumber" in value &&
213
- typeof (value as { toNumber: unknown }).toNumber === "function"
214
- ) {
215
- return (value as { toNumber(): number }).toNumber();
216
- }
217
- return Number.NaN;
218
- }
219
-
220
- /** Installs realistic aggregate() _sum/_count filtering + realistic upsert (insert-or-update, no duplicates). */
221
- function installFixtureDb() {
222
- // #3739 M2 — stands in for Postgres's SUM: filters the in-memory table by
223
- // the same `where` clause a real aggregate query would apply, then sums
224
- // the matching rows' three columns and reports the count. Returns `null`
225
- // per `_sum` field when zero rows match (Prisma's own convention), so
226
- // callers exercise the same null-coalescing path production hits.
227
- mockOf(db.usageEvent.aggregate).mockImplementation(
228
- async (args: {
229
- where: {
230
- organizationId: string;
231
- completionStatus: string;
232
- createdAt: { gte: Date; lt: Date };
233
- };
234
- }) => {
235
- const { organizationId, completionStatus, createdAt } = args.where;
236
- const matching = eventTable.filter(
237
- (e) =>
238
- e.organizationId === organizationId &&
239
- e.completionStatus === completionStatus &&
240
- e.createdAt.getTime() >= createdAt.gte.getTime() &&
241
- e.createdAt.getTime() < createdAt.lt.getTime(),
242
- );
243
- if (matching.length === 0) {
244
- return {
245
- _sum: { providerCostUsd: null, billedCostUsd: null, totalTokens: null },
246
- _count: 0,
247
- };
248
- }
249
- let providerCostUsd = 0;
250
- let billedCostUsd = 0;
251
- let totalTokens = 0;
252
- for (const row of matching) {
253
- providerCostUsd += fixtureToNumber(row.providerCostUsd);
254
- billedCostUsd += fixtureToNumber(row.billedCostUsd);
255
- totalTokens += fixtureToNumber(row.totalTokens);
256
- }
257
- return {
258
- _sum: { providerCostUsd, billedCostUsd, totalTokens },
259
- _count: matching.length,
260
- };
261
- },
262
- );
263
-
264
- mockOf(db.usageBillingReport.upsert).mockImplementation(
265
- async (args: {
266
- where: {
267
- organizationId_periodStart_periodEnd: {
268
- organizationId: string;
269
- periodStart: Date;
270
- periodEnd: Date;
271
- };
272
- };
273
- create: Record<string, unknown>;
274
- update: Record<string, unknown>;
275
- }) => {
276
- const { organizationId, periodStart, periodEnd } =
277
- args.where.organizationId_periodStart_periodEnd;
278
- const key = reportKey(organizationId, periodStart, periodEnd);
279
- const existing = reportTable.get(key);
280
- if (existing) {
281
- // Postgres validates the written values against the column types —
282
- // so does this fixture (#3738 H2).
283
- assertFitsColumns(args.update);
284
- const updated = { ...existing, ...args.update };
285
- reportTable.set(key, updated);
286
- return { id: existing.id };
287
- }
288
- assertFitsColumns(args.create);
289
- reportIdCounter += 1;
290
- const id = `rpt_${reportIdCounter}`;
291
- const created = { id, ...args.create };
292
- reportTable.set(key, created);
293
- return { id };
294
- },
295
- );
296
- }
297
-
298
- /** The system-default markup usage-metering falls back to (20%). */
299
- const DEFAULT_MARKUP = 1.2;
300
-
301
- /**
302
- * Seeds one UsageEvent. When `billedCostUsd` is not pinned explicitly it is
303
- * DERIVED from `providerCostUsd` at the default markup, so the fixture always
304
- * produces a COHERENT event (billed >= provider), exactly as `recordUsageEvent`
305
- * writes it.
306
- *
307
- * Previously the default was a flat `billedCostUsd: 1.2`, which — paired with
308
- * an explicit `providerCostUsd: 3` / `999` — silently produced INVERTED events
309
- * (billed < provider: billing below cost). Those are impossible in production
310
- * and are now correctly rejected by the money invariants (#3738 M1), so the
311
- * fixture must model a real event rather than an impossible one. A test that
312
- * WANTS an inverted row still pins `billedCostUsd` explicitly.
313
- */
314
- function seedEvent(overrides: Partial<FixtureEvent>): void {
315
- const merged = {
316
- organizationId: ORG_A,
317
- completionStatus: "success",
318
- createdAt: MID_PERIOD_DATE,
319
- providerCostUsd: 1,
320
- totalTokens: 1_000,
321
- ...overrides,
322
- };
323
-
324
- const billedCostUsd =
325
- "billedCostUsd" in overrides
326
- ? overrides.billedCostUsd
327
- : typeof merged.providerCostUsd === "number"
328
- ? merged.providerCostUsd * DEFAULT_MARKUP
329
- : DEFAULT_MARKUP;
330
-
331
- eventTable.push({ ...merged, billedCostUsd });
332
- }
333
-
334
- function expectInvalidInput(result: AggregateResult) {
335
- expect(result.ok).toBe(false);
336
- const err = result as Extract<AggregateResult, { ok: false }>;
337
- expect(err.error.kind).toBe("invalid_input");
338
- }
339
-
340
- describe("aggregateUsagePeriod", () => {
341
- beforeEach(() => {
342
- jest.clearAllMocks();
343
- jest.spyOn(console, "warn").mockImplementation(() => undefined);
344
- jest.spyOn(console, "error").mockImplementation(() => undefined);
345
- eventTable = [];
346
- reportTable = new Map();
347
- reportIdCounter = 0;
348
- installFixtureDb();
349
- });
350
-
351
- afterEach(() => {
352
- jest.restoreAllMocks();
353
- });
354
-
355
- // ── AC-1: SUM successful UsageEvents into the totals ──────────────────────
356
- it("AC-1: SUMs successful UsageEvents into provider/markup/billed/tokens/eventCount", async () => {
357
- seedEvent({ providerCostUsd: 3, billedCostUsd: 3.6, totalTokens: 1_000_000 });
358
- seedEvent({ providerCostUsd: 2, billedCostUsd: 2.4, totalTokens: 500_000 });
359
-
360
- const result = await aggregateUsagePeriod(ORG_A, PERIOD_START);
361
-
362
- expect(result.ok).toBe(true);
363
- const ok = result as Extract<AggregateResult, { ok: true }>;
364
- expect(ok.totals).toEqual({
365
- totalProviderCost: 5,
366
- totalMarkupAmount: 1,
367
- totalBilledAmount: 6,
368
- totalTokens: 1_500_000,
369
- eventCount: 2,
370
- includedCents: 0,
371
- creditBalanceCents: 0,
372
- onDemandCents: 0,
373
- });
374
- });
375
-
376
- it("AC-1: filters out non-success completionStatus (D2) — an error/pricing_missing event is excluded", async () => {
377
- seedEvent({ providerCostUsd: 3, billedCostUsd: 3.6, totalTokens: 1_000 });
378
- seedEvent({
379
- completionStatus: "error",
380
- providerCostUsd: 100,
381
- billedCostUsd: 120,
382
- totalTokens: 999_999,
383
- });
384
- seedEvent({
385
- completionStatus: "pricing_missing:success",
386
- providerCostUsd: 0,
387
- billedCostUsd: 0,
388
- totalTokens: 999_999,
389
- });
390
-
391
- const result = (await aggregateUsagePeriod(ORG_A, PERIOD_START)) as Extract<
392
- AggregateResult,
393
- { ok: true }
394
- >;
395
-
396
- expect(result.totals.eventCount).toBe(1);
397
- expect(result.totals.totalProviderCost).toBe(3);
398
- expect(result.totals.totalTokens).toBe(1_000);
399
- });
400
-
401
- it("AC-1: excludes events outside the period window (before periodStart / at-or-after periodEnd)", async () => {
402
- seedEvent({
403
- createdAt: new Date(PERIOD_START.getTime() - 1),
404
- providerCostUsd: 10,
405
- }); // just before the window
406
- seedEvent({ createdAt: PERIOD_START, providerCostUsd: 1 }); // inclusive lower bound
407
- seedEvent({ createdAt: PERIOD_END, providerCostUsd: 10 }); // exclusive upper bound — excluded
408
- seedEvent({
409
- createdAt: new Date(PERIOD_END.getTime() - 1),
410
- providerCostUsd: 1,
411
- }); // just inside the window
412
-
413
- const result = (await aggregateUsagePeriod(ORG_A, PERIOD_START)) as Extract<
414
- AggregateResult,
415
- { ok: true }
416
- >;
417
-
418
- expect(result.totals.eventCount).toBe(2);
419
- expect(result.totals.totalProviderCost).toBe(2);
420
- });
421
-
422
- it("a periodStart mid-month normalizes to the calendar-month window", async () => {
423
- seedEvent({ createdAt: MID_PERIOD_DATE, providerCostUsd: 5 });
424
-
425
- const midMonth = new Date(Date.UTC(2026, 2, 17, 8, 30));
426
- const result = (await aggregateUsagePeriod(ORG_A, midMonth)) as Extract<
427
- AggregateResult,
428
- { ok: true }
429
- >;
430
-
431
- expect(result.totals.eventCount).toBe(1);
432
- expect(result.totals.totalProviderCost).toBe(5);
433
- });
434
-
435
- // ── AC-2: idempotent getOrCreateReport ─────────────────────────────────────
436
- describe("AC-2: idempotency", () => {
437
- it("a second invocation for the same (org, period) UPDATES the same report — no duplicate", async () => {
438
- seedEvent({ providerCostUsd: 1, billedCostUsd: 1.2, totalTokens: 100 });
439
-
440
- const first = (await aggregateUsagePeriod(ORG_A, PERIOD_START)) as Extract<
441
- AggregateResult,
442
- { ok: true }
443
- >;
444
-
445
- // A second event lands before the re-run — the re-run must reflect it.
446
- seedEvent({ providerCostUsd: 2, billedCostUsd: 2.4, totalTokens: 200 });
447
- const second = (await aggregateUsagePeriod(ORG_A, PERIOD_START)) as Extract<
448
- AggregateResult,
449
- { ok: true }
450
- >;
451
-
452
- expect(second.reportId).toBe(first.reportId);
453
- expect(reportTable.size).toBe(1); // no duplicate row
454
- expect(second.totals.eventCount).toBe(2);
455
- expect(second.totals.totalProviderCost).toBe(3);
456
- expect(db.usageBillingReport.upsert).toHaveBeenCalledTimes(2);
457
- });
458
-
459
- it("status stays PENDING across a re-run (P2 never advances it)", async () => {
460
- seedEvent({ providerCostUsd: 1, billedCostUsd: 1.2, totalTokens: 100 });
461
- await aggregateUsagePeriod(ORG_A, PERIOD_START);
462
- await aggregateUsagePeriod(ORG_A, PERIOD_START);
463
-
464
- const [record] = Array.from(reportTable.values());
465
- // The service never writes `status` — the DB default (PENDING) stands,
466
- // and a re-run's `update` payload must not carry the key either.
467
- const updateCall = mockOf(db.usageBillingReport.upsert).mock.calls[1]?.[0] as {
468
- update: Record<string, unknown>;
469
- };
470
- expect(updateCall.update).not.toHaveProperty("status");
471
- expect(record).not.toHaveProperty("status");
472
- });
473
-
474
- it("a re-run does not clobber attribution cents a later phase (P3/P4) may have set", async () => {
475
- seedEvent({ providerCostUsd: 1, billedCostUsd: 1.2, totalTokens: 100 });
476
- await aggregateUsagePeriod(ORG_A, PERIOD_START);
477
-
478
- // Simulate P3/P4 having since applied attribution to the persisted row.
479
- const [key] = Array.from(reportTable.keys());
480
- const existing = reportTable.get(key!)!;
481
- reportTable.set(key!, { ...existing, includedCents: 500 });
482
-
483
- await aggregateUsagePeriod(ORG_A, PERIOD_START);
484
-
485
- const updated = reportTable.get(key!)!;
486
- expect(updated.includedCents).toBe(500);
487
- });
488
- });
489
-
490
- // ── AC-3 (AC-UB-03a): reconciliation over a full test period ───────────────
491
- describe("AC-3: reconciliation (AC-UB-03a)", () => {
492
- it("report totals equal the SUM of source events, and totalBilled == totalProvider * (1 + markup) within tolerance", async () => {
493
- const MARKUP = 0.2; // 20% — matches the system-default markup usage-metering falls back to
494
- const events = [
495
- { providerCostUsd: 3, tokens: 1_000_000 },
496
- { providerCostUsd: 2, tokens: 500_000 },
497
- { providerCostUsd: 7.5, tokens: 2_250_000 },
498
- { providerCostUsd: 0.333333, tokens: 10_000 },
499
- ];
500
- let expectedProvider = 0;
501
- let expectedBilled = 0;
502
- let expectedTokens = 0;
503
- for (const e of events) {
504
- const billed = e.providerCostUsd * (1 + MARKUP);
505
- seedEvent({
506
- providerCostUsd: e.providerCostUsd,
507
- billedCostUsd: billed,
508
- totalTokens: e.tokens,
509
- });
510
- expectedProvider += e.providerCostUsd;
511
- expectedBilled += billed;
512
- expectedTokens += e.tokens;
513
- }
514
-
515
- const result = (await aggregateUsagePeriod(ORG_A, PERIOD_START)) as Extract<
516
- AggregateResult,
517
- { ok: true }
518
- >;
519
-
520
- expect(result.totals.totalProviderCost).toBeCloseTo(expectedProvider, 6);
521
- expect(result.totals.totalBilledAmount).toBeCloseTo(expectedBilled, 6);
522
- expect(result.totals.totalTokens).toBe(expectedTokens);
523
- expect(result.totals.eventCount).toBe(events.length);
524
-
525
- // AC-UB-03a — the reconciliation identity, within tolerance.
526
- expect(result.totals.totalBilledAmount).toBeCloseTo(
527
- result.totals.totalProviderCost * (1 + MARKUP),
528
- 6,
529
- );
530
- // totalBilled == totalProvider + totalMarkup holds exactly by construction.
531
- expect(
532
- result.totals.totalProviderCost + result.totals.totalMarkupAmount,
533
- ).toBeCloseTo(result.totals.totalBilledAmount, 10);
534
- });
535
-
536
- it("an empty period reconciles to all-zero totals, not a missing/undefined report", async () => {
537
- const result = (await aggregateUsagePeriod(ORG_A, PERIOD_START)) as Extract<
538
- AggregateResult,
539
- { ok: true }
540
- >;
541
-
542
- expect(result.totals).toEqual({
543
- totalProviderCost: 0,
544
- totalMarkupAmount: 0,
545
- totalBilledAmount: 0,
546
- totalTokens: 0,
547
- eventCount: 0,
548
- includedCents: 0,
549
- creditBalanceCents: 0,
550
- onDemandCents: 0,
551
- });
552
- });
553
- });
554
-
555
- // ── AC-4 (AC-UB-10): org isolation ─────────────────────────────────────────
556
- describe("AC-4: org isolation (AC-UB-10)", () => {
557
- it("org A's aggregation never includes org B's events", async () => {
558
- seedEvent({ organizationId: ORG_A, providerCostUsd: 3, totalTokens: 100 });
559
- seedEvent({ organizationId: ORG_B, providerCostUsd: 999, totalTokens: 999_999 });
560
-
561
- const resultA = (await aggregateUsagePeriod(ORG_A, PERIOD_START)) as Extract<
562
- AggregateResult,
563
- { ok: true }
564
- >;
565
-
566
- expect(resultA.totals.eventCount).toBe(1);
567
- expect(resultA.totals.totalProviderCost).toBe(3);
568
- expect(resultA.totals.totalTokens).toBe(100);
569
- });
570
-
571
- it("the query is organizationId-scoped at the boundary, not filtered client-side", async () => {
572
- seedEvent({ organizationId: ORG_A });
573
-
574
- await aggregateUsagePeriod(ORG_A, PERIOD_START);
575
-
576
- expect(db.usageEvent.aggregate).toHaveBeenCalledWith(
577
- expect.objectContaining({
578
- where: expect.objectContaining({ organizationId: ORG_A }),
579
- }),
580
- );
581
- });
582
-
583
- it("org A and org B get separate reports for the same period", async () => {
584
- seedEvent({ organizationId: ORG_A, providerCostUsd: 1 });
585
- seedEvent({ organizationId: ORG_B, providerCostUsd: 2 });
586
-
587
- const resultA = (await aggregateUsagePeriod(ORG_A, PERIOD_START)) as Extract<
588
- AggregateResult,
589
- { ok: true }
590
- >;
591
- const resultB = (await aggregateUsagePeriod(ORG_B, PERIOD_START)) as Extract<
592
- AggregateResult,
593
- { ok: true }
594
- >;
595
-
596
- expect(resultA.reportId).not.toBe(resultB.reportId);
597
- expect(reportTable.size).toBe(2);
598
- });
599
- });
600
-
601
- // ── AC-5: discriminated result, PII-safe logging, invalid-input handling ──
602
- describe("AC-5: boundary validation + result shape", () => {
603
- it("rejects a malformed organizationId", async () => {
604
- const result = await aggregateUsagePeriod("not-an-org-id", PERIOD_START);
605
-
606
- expectInvalidInput(result);
607
- expect(db.usageEvent.aggregate).not.toHaveBeenCalled();
608
- expect(db.usageBillingReport.upsert).not.toHaveBeenCalled();
609
- });
610
-
611
- it("rejects an invalid Date", async () => {
612
- const result = await aggregateUsagePeriod(ORG_A, new Date(NaN));
613
-
614
- expectInvalidInput(result);
615
- expect(db.usageEvent.aggregate).not.toHaveBeenCalled();
616
- });
617
-
618
- it("the error names the offending field", async () => {
619
- const result = await aggregateUsagePeriod("not-an-org-id", PERIOD_START);
620
-
621
- const err = result as Extract<AggregateResult, { ok: false }>;
622
- expect(err.error.message).toContain("organizationId");
623
- });
624
-
625
- it("PII/content non-leak — the ok result carries only ids/counts/computed totals", async () => {
626
- seedEvent({});
627
-
628
- const result = await aggregateUsagePeriod(ORG_A, PERIOD_START);
629
-
630
- expect(Object.keys(result)).toEqual(
631
- expect.arrayContaining(["ok", "reportId", "totals"]),
632
- );
633
- const ok = result as Extract<AggregateResult, { ok: true }>;
634
- expect(Object.keys(ok.totals).sort()).toEqual(
635
- [
636
- "creditBalanceCents",
637
- "eventCount",
638
- "includedCents",
639
- "onDemandCents",
640
- "totalBilledAmount",
641
- "totalMarkupAmount",
642
- "totalProviderCost",
643
- "totalTokens",
644
- ].sort(),
645
- );
646
- });
647
- });
648
-
649
- // ── Non-finite guard — a corrupt row must never poison the persisted report ─
650
- describe("non-finite guard (fails closed, never persists a poisoned total)", () => {
651
- it("a NaN-valued stored event fails the aggregation rather than writing NaN", async () => {
652
- seedEvent({ providerCostUsd: Number.NaN, billedCostUsd: 1, totalTokens: 1 });
653
-
654
- const result = await aggregateUsagePeriod(ORG_A, PERIOD_START);
655
-
656
- expect(result.ok).toBe(false);
657
- const err = result as Extract<AggregateResult, { ok: false }>;
658
- expect(err.error.kind).toBe("aggregation_failed");
659
- expect(db.usageBillingReport.upsert).not.toHaveBeenCalled();
660
- });
661
-
662
- it("a corrupt Decimal-shaped row (unparseable) fails the aggregation, never persists", async () => {
663
- seedEvent({ providerCostUsd: "not-a-number", billedCostUsd: 1, totalTokens: 1 });
664
-
665
- const result = await aggregateUsagePeriod(ORG_A, PERIOD_START);
666
-
667
- expect(result.ok).toBe(false);
668
- const err = result as Extract<AggregateResult, { ok: false }>;
669
- expect(err.error.kind).toBe("aggregation_failed");
670
- expect(db.usageBillingReport.upsert).not.toHaveBeenCalled();
671
- });
672
-
673
- it("a Prisma-Decimal-like row (object with toNumber()) coerces correctly on the happy path", async () => {
674
- seedEvent({
675
- providerCostUsd: { toNumber: () => 4 },
676
- billedCostUsd: { toNumber: () => 4.8 },
677
- totalTokens: 1_000,
678
- });
679
-
680
- const result = (await aggregateUsagePeriod(ORG_A, PERIOD_START)) as Extract<
681
- AggregateResult,
682
- { ok: true }
683
- >;
684
-
685
- expect(result.ok).toBe(true);
686
- expect(result.totals.totalProviderCost).toBe(4);
687
- expect(result.totals.totalBilledAmount).toBe(4.8);
688
- });
689
- });
690
-
691
- // ── write_failed — the report write itself throws ─────────────────────────
692
- describe("write_failed", () => {
693
- it("a report-write failure returns write_failed and does not leak the raw error", async () => {
694
- seedEvent({ providerCostUsd: 1, billedCostUsd: 1.2, totalTokens: 1 });
695
- const leaky = new Error(
696
- `Invalid \`prisma.usageBillingReport.upsert()\` invocation: { organizationId: "${ORG_A}" }`,
697
- );
698
- mockOf(db.usageBillingReport.upsert).mockRejectedValueOnce(leaky);
699
-
700
- const result = await aggregateUsagePeriod(ORG_A, PERIOD_START);
701
-
702
- expect(result.ok).toBe(false);
703
- const err = result as Extract<AggregateResult, { ok: false }>;
704
- expect(err.error.kind).toBe("write_failed");
705
- expect(err.error.message).not.toContain(ORG_A);
706
- expect(err.error.message).not.toContain("prisma");
707
- expect(console.error).toHaveBeenCalled();
708
- });
709
- });
710
-
711
- // ── H1 (#3738): the READ path is inside the error guard ───────────────────
712
- // Before the fix, the read (findMany, then aggregate since #3739 M2) sat
713
- // OUTSIDE the try/catch, so a DB read error rejected the promise instead of
714
- // returning the discriminated union the docblock promises ("Never
715
- // throws"). #3717's route will trust that union.
716
- describe("H1: read-path error guard (the union contract holds on a read failure)", () => {
717
- it("a DB read failure returns a discriminated result rather than throwing", async () => {
718
- mockOf(db.usageEvent.aggregate).mockRejectedValueOnce(
719
- new Error("connection pool timeout"),
720
- );
721
-
722
- const result = await aggregateUsagePeriod(ORG_A, PERIOD_START);
723
-
724
- expect(result.ok).toBe(false);
725
- const err = result as Extract<AggregateResult, { ok: false }>;
726
- expect(err.error.kind).toBe("read_failed");
727
- // Fails closed — a failed read must never write a (zeroed) report.
728
- expect(db.usageBillingReport.upsert).not.toHaveBeenCalled();
729
- });
730
-
731
- it("a read failure does not leak the tenant id or the raw Prisma error", async () => {
732
- // Prisma read errors embed the `where` clause — which carries the org id.
733
- const leaky = new Error(
734
- `Invalid \`prisma.usageEvent.aggregate()\` invocation: { where: { organizationId: "${ORG_A}" } }`,
735
- );
736
- mockOf(db.usageEvent.aggregate).mockRejectedValueOnce(leaky);
737
-
738
- const result = await aggregateUsagePeriod(ORG_A, PERIOD_START);
739
-
740
- const err = result as Extract<AggregateResult, { ok: false }>;
741
- expect(err.error.message).not.toContain(ORG_A);
742
- expect(err.error.message).not.toContain("prisma");
743
- // The detail is logged server-side only.
744
- expect(console.error).toHaveBeenCalled();
745
- });
746
- });
747
-
748
- // ── H2a (#3738): the aggregate columns can represent a real month ─────────
749
- // These are the load-bearing tests. The upsert fixture enforces the REAL
750
- // schema's column widths (see the file docblock), so both cases FAIL against
751
- // the pre-fix `Decimal(10,6)` / `Int` columns — the exact defect that stalls
752
- // billing forever for the largest tenants.
753
- describe("H2a: aggregate columns hold a large month (schema-grounded)", () => {
754
- it("a $10,000+ provider-cost month aggregates and persists", async () => {
755
- // 3 × $4,000 = $12,000 provider — past the old Decimal(10,6) ceiling
756
- // ($9,999.999999), which made the upsert throw and permanently stall the
757
- // report for this org.
758
- for (let i = 0; i < 3; i += 1) {
759
- seedEvent({
760
- providerCostUsd: 4_000,
761
- billedCostUsd: 4_800,
762
- totalTokens: 1_000,
763
- });
764
- }
765
-
766
- const result = await aggregateUsagePeriod(ORG_A, PERIOD_START);
767
-
768
- expect(result.ok).toBe(true);
769
- const ok = result as Extract<AggregateResult, { ok: true }>;
770
- expect(ok.totals.totalProviderCost).toBe(12_000);
771
- expect(ok.totals.totalBilledAmount).toBe(14_400);
772
- expect(ok.totals.totalMarkupAmount).toBe(2_400);
773
- // The report row actually exists — billing did not stall.
774
- expect(reportTable.size).toBe(1);
775
- });
776
-
777
- it("a >2.15B-token month aggregates and persists", async () => {
778
- // 3 × 800M = 2.4B tokens — past the old int4 ceiling (2,147,483,647).
779
- // ~700k requests at 3k tokens: one busy tenant.
780
- for (let i = 0; i < 3; i += 1) {
781
- seedEvent({
782
- providerCostUsd: 1,
783
- billedCostUsd: 1.2,
784
- totalTokens: 800_000_000,
785
- });
786
- }
787
-
788
- const result = await aggregateUsagePeriod(ORG_A, PERIOD_START);
789
-
790
- expect(result.ok).toBe(true);
791
- const ok = result as Extract<AggregateResult, { ok: true }>;
792
- expect(ok.totals.totalTokens).toBe(2_400_000_000);
793
- expect(reportTable.size).toBe(1);
794
- });
795
-
796
- it("totalTokens is written as a BigInt (the widened int8 column)", async () => {
797
- seedEvent({ totalTokens: 3_000_000_000 });
798
-
799
- await aggregateUsagePeriod(ORG_A, PERIOD_START);
800
-
801
- const createCall = mockOf(db.usageBillingReport.upsert).mock
802
- .calls[0]?.[0] as { create: Record<string, unknown> };
803
- expect(typeof createCall.create.totalTokens).toBe("bigint");
804
- expect(createCall.create.totalTokens).toBe(3_000_000_000n);
805
- });
806
-
807
- it("the schema itself declares aggregate-sized columns (guards against a schema regression)", () => {
808
- // Asserted directly against database/content/schema.prisma so a future
809
- // narrowing of these columns fails here, not in production billing.
810
- const provider = columnLimit("totalProviderCost");
811
- const billed = columnLimit("totalBilledAmount");
812
- const markup = columnLimit("totalMarkupAmount");
813
- const tokens = columnLimit("totalTokens");
814
-
815
- // Must comfortably clear a $10k month (the old ceiling).
816
- for (const usd of [provider, billed, markup]) {
817
- expect(usd.kind).toBe("decimal");
818
- expect(usd.max as number).toBeGreaterThan(1_000_000);
819
- }
820
- // Must be int8 — int4 tops out at 2.15B tokens.
821
- expect(tokens.kind).toBe("int8");
822
- });
823
- });
824
-
825
- // ── H2b (#3738): a pre-write bounds assertion, LOUD and alertable ─────────
826
- // Fail-closed is right, but the failure must be DISTINGUISHABLE — a generic
827
- // `write_failed` + a bare console.error is how silent, permanent,
828
- // largest-customer revenue loss goes unnoticed.
829
- describe("H2b: bounds assertion fails closed with a distinct, alertable kind", () => {
830
- it("a total beyond the representable range returns aggregate_overflow, not write_failed", async () => {
831
- // Past the service's own MAX_TOTAL_USD cap. Reached here via two large
832
- // rows; in production, via a corrupt row or an org past the cap. Either
833
- // way the guard protects the TOTAL, however it is arrived at.
834
- seedEvent({ providerCostUsd: 6e8, billedCostUsd: 7e8, totalTokens: 1 });
835
- seedEvent({ providerCostUsd: 6e8, billedCostUsd: 7e8, totalTokens: 1 });
836
-
837
- const result = await aggregateUsagePeriod(ORG_A, PERIOD_START);
838
-
839
- expect(result.ok).toBe(false);
840
- const err = result as Extract<AggregateResult, { ok: false }>;
841
- expect(err.error.kind).toBe("aggregate_overflow");
842
- // Distinct from the generic write failure — this is the alertable signal.
843
- expect(err.error.kind).not.toBe("write_failed");
844
- // Never persists a truncated/overflowed total.
845
- expect(db.usageBillingReport.upsert).not.toHaveBeenCalled();
846
- });
847
-
848
- it("a token total beyond MAX_SAFE_INTEGER returns aggregate_overflow", async () => {
849
- seedEvent({ totalTokens: 9e15 });
850
- seedEvent({ totalTokens: 9e15 });
851
-
852
- const result = await aggregateUsagePeriod(ORG_A, PERIOD_START);
853
-
854
- const err = result as Extract<AggregateResult, { ok: false }>;
855
- expect(err.error.kind).toBe("aggregate_overflow");
856
- expect(db.usageBillingReport.upsert).not.toHaveBeenCalled();
857
- });
858
-
859
- it("the overflow is logged as an alertable event, not a bare generic error", async () => {
860
- seedEvent({ providerCostUsd: 6e8, billedCostUsd: 7e8 });
861
- seedEvent({ providerCostUsd: 6e8, billedCostUsd: 7e8 });
862
-
863
- await aggregateUsagePeriod(ORG_A, PERIOD_START);
864
-
865
- // The log line must name the overflow so it can be alerted on.
866
- const logged = mockOf(console.error).mock.calls.flat().map(String).join(" ");
867
- expect(logged).toMatch(/overflow/i);
868
- });
869
-
870
- it("the assertion fires BEFORE the column limit, so Postgres never overflows", async () => {
871
- // The service's cap ($1B) sits far below the column capacity
872
- // (Decimal(20,6) ≈ $1e14), so the loud assertion is always the gate —
873
- // the DB's silent numeric overflow is unreachable.
874
- const cap = columnLimit("totalProviderCost");
875
- expect(cap.kind).toBe("decimal");
876
- expect(cap.max as number).toBeGreaterThan(1e9);
877
- });
878
- });
879
-
880
- // ── M1 (#3738): the money guard checks non-negative, not just finite ──────
881
- // A negative total is FINITE — it sails through a finite-only guard and
882
- // persists as a credit. This is the class that produced the sibling's bug.
883
- describe("M1: non-negative + reconciliation guard", () => {
884
- it("a negative provider cost fails closed rather than persisting a credit", async () => {
885
- seedEvent({ providerCostUsd: -5, billedCostUsd: 1, totalTokens: 1 });
886
-
887
- const result = await aggregateUsagePeriod(ORG_A, PERIOD_START);
888
-
889
- expect(result.ok).toBe(false);
890
- const err = result as Extract<AggregateResult, { ok: false }>;
891
- expect(err.error.kind).toBe("aggregation_failed");
892
- expect(db.usageBillingReport.upsert).not.toHaveBeenCalled();
893
- });
894
-
895
- it("a billed total below the provider total (negative markup) fails closed", async () => {
896
- seedEvent({ providerCostUsd: 10, billedCostUsd: 5, totalTokens: 1 });
897
-
898
- const result = await aggregateUsagePeriod(ORG_A, PERIOD_START);
899
-
900
- expect(result.ok).toBe(false);
901
- const err = result as Extract<AggregateResult, { ok: false }>;
902
- expect(err.error.kind).toBe("aggregation_failed");
903
- expect(db.usageBillingReport.upsert).not.toHaveBeenCalled();
904
- });
905
-
906
- it("a negative token count fails closed", async () => {
907
- seedEvent({ totalTokens: -100 });
908
-
909
- const result = await aggregateUsagePeriod(ORG_A, PERIOD_START);
910
-
911
- expect(result.ok).toBe(false);
912
- expect(db.usageBillingReport.upsert).not.toHaveBeenCalled();
913
- });
914
- });
915
-
916
- // ── L1 (#3738): toNumber must not coerce an unusable value to a silent 0 ──
917
- describe("L1: unusable column values fail closed, never coerce to a silent zero", () => {
918
- it("a null money column fails the aggregation rather than underbilling as 0", async () => {
919
- // `Number(null) === 0` — the old coercion silently DROPPED the row's cost
920
- // (an underbill) instead of the NaN the docblock claimed it produced.
921
- seedEvent({ providerCostUsd: null, billedCostUsd: 1, totalTokens: 1 });
922
-
923
- const result = await aggregateUsagePeriod(ORG_A, PERIOD_START);
924
-
925
- expect(result.ok).toBe(false);
926
- const err = result as Extract<AggregateResult, { ok: false }>;
927
- expect(err.error.kind).toBe("aggregation_failed");
928
- expect(db.usageBillingReport.upsert).not.toHaveBeenCalled();
929
- });
930
-
931
- it("an empty-string money column fails the aggregation (Number('') === 0)", async () => {
932
- seedEvent({ providerCostUsd: "", billedCostUsd: 1, totalTokens: 1 });
933
-
934
- const result = await aggregateUsagePeriod(ORG_A, PERIOD_START);
935
-
936
- const err = result as Extract<AggregateResult, { ok: false }>;
937
- expect(err.error.kind).toBe("aggregation_failed");
938
- expect(db.usageBillingReport.upsert).not.toHaveBeenCalled();
939
- });
940
- });
941
- });