create-ailk 0.23.0 → 0.25.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (604) hide show
  1. package/README.md +68 -33
  2. package/component-catalog.json +3 -3
  3. package/component-catalog.md +3 -3
  4. package/dist/add-module.js +10 -3
  5. package/dist/add-route.d.ts +12 -1
  6. package/dist/add-route.js +38 -4
  7. package/dist/cli.js +12 -7
  8. package/dist/derive-architecture.d.ts +3 -4
  9. package/dist/derive-architecture.js +75 -22
  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 +1 -1
  14. package/dist/lib/fetch-template-snapshot.js +7 -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 +34 -12
  19. package/dist/lib/scaffold-render-sweep.d.ts +33 -0
  20. package/dist/lib/scaffold-render-sweep.js +45 -0
  21. package/dist/module-architecture.d.ts +20 -3
  22. package/dist/module-architecture.js +122 -538
  23. package/dist/paid-sections.d.ts +25 -1
  24. package/dist/paid-sections.js +88 -3
  25. package/dist/surfaces.js +10 -2
  26. package/dist/sync-routes.d.ts +30 -4
  27. package/dist/sync-routes.js +271 -18
  28. package/dist/template-record.d.ts +14 -4
  29. package/dist/template-record.js +23 -5
  30. package/dist/topology.d.ts +16 -3
  31. package/dist/topology.js +31 -19
  32. package/dist/update.d.ts +10 -1
  33. package/dist/update.js +540 -16
  34. package/package.json +3 -3
  35. package/release-scope.json +1 -1
  36. package/templates/.claude/cloudparity-repo-hooks.json +5 -0
  37. package/templates/.claude/hooks/template-guard.sh +137 -0
  38. package/templates/.claude/rules/extending.md +106 -0
  39. package/templates/.claude/rules/loop-contract.md +2 -2
  40. package/templates/.claude/settings.json +11 -0
  41. package/templates/.env.example +9 -5
  42. package/templates/.github/workflows/ci.yml +7 -4
  43. package/templates/CLAUDE.md +15 -3
  44. package/templates/CONVENTIONS.md +8 -10
  45. package/templates/README.md +14 -13
  46. package/templates/apps/api/.env.example +9 -2
  47. package/templates/apps/api/CLAUDE.md +122 -82
  48. package/templates/apps/api/jest.config.cjs +15 -5
  49. package/templates/apps/api/package.json +16 -20
  50. package/templates/apps/api/src/__tests__/trusted-origins.server.test.ts +2 -2
  51. package/templates/apps/api/src/__tests__/vercel-handler.test.ts +4 -4
  52. package/templates/apps/api/src/index.ts +1 -1
  53. package/templates/apps/api/src/lib/__mocks__/prisma.ts +7 -4
  54. package/templates/apps/api/src/modules/commerce.ts +10 -0
  55. package/templates/apps/api/src/modules/content-write.ts +10 -0
  56. package/templates/apps/api/src/modules/multi-tenant.ts +10 -0
  57. package/templates/apps/api/src/modules/scheduling.ts +10 -0
  58. package/templates/apps/api/src/modules/signal-collectors.ts +10 -0
  59. package/templates/apps/api/src/modules/workspace.ts +10 -0
  60. package/templates/apps/api/src/server.ts +117 -1857
  61. package/templates/apps/api/vercel.json +2 -2
  62. package/templates/apps/mcp/CLAUDE.md +77 -24
  63. package/templates/apps/mcp/__tests__/app-entry.test.ts +4 -254
  64. package/templates/apps/mcp/__tests__/boot-file.test.ts +92 -0
  65. package/templates/apps/mcp/jest.config.cjs +6 -1
  66. package/templates/apps/mcp/package.json +5 -12
  67. package/templates/apps/mcp/src/app.ts +8 -7
  68. package/templates/apps/mcp/src/index.ts +6 -34
  69. package/templates/apps/mcp/src/lib/paid-tools.generated.ts +10 -0
  70. package/templates/apps/mcp/src/lib/topology.generated.ts +2 -2
  71. package/templates/apps/mcp/src/site.ts +12 -0
  72. package/templates/apps/web/.env.example +1 -1
  73. package/templates/apps/web/CLAUDE.md +21 -5
  74. package/templates/apps/web/app/.well-known/mcp.json/route.ts +9 -3
  75. package/templates/apps/web/app/[locale]/contact/__tests__/ConversationalIntakeWrapper.test.tsx +1 -1
  76. package/templates/apps/web/app/[locale]/contact/contact.actions.ts +14 -4
  77. package/templates/apps/web/app/[locale]/contact/intake-analytics.ts +1 -1
  78. package/templates/apps/web/app/[locale]/contact/intake-script.ts +1 -1
  79. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/magnet-page.test.tsx +22 -1
  80. package/templates/apps/web/app/[locale]/flows/[slug]/magnet-page.tsx +28 -7
  81. package/templates/apps/web/app/[locale]/pricing/__tests__/unconnected.test.tsx +43 -0
  82. package/templates/apps/web/app/[locale]/pricing/page.tsx +7 -3
  83. package/templates/apps/web/app/api/offerings/checkout/[lookupKey]/__tests__/route.test.ts +222 -0
  84. package/templates/apps/web/app/api/offerings/checkout/[lookupKey]/route.ts +10 -3
  85. package/templates/apps/web/app/api/revalidate/route.ts +3 -3
  86. package/templates/apps/web/auth.ts +2 -2
  87. package/templates/apps/web/jest.config.cjs +1 -0
  88. package/templates/apps/web/lib/__tests__/magnet-routes.test.ts +7 -0
  89. package/templates/apps/web/lib/auth-email.ts +1 -1
  90. package/templates/apps/web/lib/magnet-routes.ts +3 -1
  91. package/templates/apps/web/lib/newsletter.actions.ts +9 -6
  92. package/templates/apps/web/lib/relay.ts +2 -2
  93. package/templates/apps/web/lib/release-scope.ts +47 -0
  94. package/templates/apps/web/lib/server-api.ts +1 -1
  95. package/templates/apps/web/src/lib/commerce-claim.ts +1 -1
  96. package/templates/customizations.yaml +37 -0
  97. package/templates/database/prisma.config.ts +10 -14
  98. package/templates/database/seed-test.ts +2 -2
  99. package/templates/database/seed.ts +32 -5
  100. package/templates/package.json +12 -6
  101. package/templates/pnpm-workspace.yaml +0 -1
  102. package/templates/project.yaml +16 -8
  103. package/templates/tools/jest/reporters.cjs +65 -0
  104. package/templates/tools/lint-architecture.ts +757 -7
  105. package/templates/tsconfig.json +1 -2
  106. package/versions.json +48 -35
  107. package/templates/apps/api/src/__tests__/commerce-claim-registration.test.ts +0 -409
  108. package/templates/apps/api/src/__tests__/factories/agent-caller.ts +0 -102
  109. package/templates/apps/api/src/__tests__/factories/content-fixture.ts +0 -138
  110. package/templates/apps/api/src/__tests__/factories/in-memory-prisma.ts +0 -441
  111. package/templates/apps/api/src/__tests__/factories/index.ts +0 -70
  112. package/templates/apps/api/src/__tests__/factories/lead-fixture.ts +0 -82
  113. package/templates/apps/api/src/__tests__/leads-forwarded-rate-limit.test.ts +0 -135
  114. package/templates/apps/api/src/__tests__/services/enrichment-shim.test.ts +0 -126
  115. package/templates/apps/api/src/__tests__/stripe-boot.test.ts +0 -132
  116. package/templates/apps/api/src/__tests__/support/hub-sign-in-fake-db.ts +0 -362
  117. package/templates/apps/api/src/bin/__tests__/rate-limit-probe.test.ts +0 -184
  118. package/templates/apps/api/src/bin/abandon-sweep.ts +0 -42
  119. package/templates/apps/api/src/bin/rate-limit-probe.ts +0 -53
  120. package/templates/apps/api/src/bin/spokes.ts +0 -198
  121. package/templates/apps/api/src/bin/stripe-connections-rekey.ts +0 -45
  122. package/templates/apps/api/src/config/__tests__/hub-require-spoke-key.test.ts +0 -196
  123. package/templates/apps/api/src/config/__tests__/index.test.ts +0 -233
  124. package/templates/apps/api/src/config/__tests__/modules.test.ts +0 -76
  125. package/templates/apps/api/src/config/__tests__/stripe-connection-key.test.ts +0 -185
  126. package/templates/apps/api/src/config/__tests__/trusted-origins.test.ts +0 -238
  127. package/templates/apps/api/src/config/index.ts +0 -596
  128. package/templates/apps/api/src/config/modules.ts +0 -83
  129. package/templates/apps/api/src/lib/__tests__/agent-store.test.ts +0 -581
  130. package/templates/apps/api/src/lib/__tests__/auth-email-budget.test.ts +0 -143
  131. package/templates/apps/api/src/lib/__tests__/consent-ledger-double.ts +0 -237
  132. package/templates/apps/api/src/lib/__tests__/consent-store.test.ts +0 -353
  133. package/templates/apps/api/src/lib/__tests__/content-adapter.test.ts +0 -201
  134. package/templates/apps/api/src/lib/__tests__/deliverable-asset-store.test.ts +0 -224
  135. package/templates/apps/api/src/lib/__tests__/error-serializer.test.ts +0 -120
  136. package/templates/apps/api/src/lib/__tests__/errors.test.ts +0 -94
  137. package/templates/apps/api/src/lib/__tests__/file-fallback.test.ts +0 -144
  138. package/templates/apps/api/src/lib/__tests__/fixtures/HomePage/home.mdx +0 -8
  139. package/templates/apps/api/src/lib/__tests__/flow-completion-store.test.ts +0 -149
  140. package/templates/apps/api/src/lib/__tests__/flow-rename-race.db.test.ts +0 -116
  141. package/templates/apps/api/src/lib/__tests__/hub-sign-in-store.test.ts +0 -209
  142. package/templates/apps/api/src/lib/__tests__/lead-capture-store.test.ts +0 -257
  143. package/templates/apps/api/src/lib/__tests__/lead-delivery.test.ts +0 -96
  144. package/templates/apps/api/src/lib/__tests__/outbound-http.test.ts +0 -125
  145. package/templates/apps/api/src/lib/__tests__/prisma.test.ts +0 -165
  146. package/templates/apps/api/src/lib/__tests__/require-commerce-claim.test.ts +0 -317
  147. package/templates/apps/api/src/lib/__tests__/require-paid-tier.test.ts +0 -129
  148. package/templates/apps/api/src/lib/__tests__/site.test.ts +0 -292
  149. package/templates/apps/api/src/lib/__tests__/slice-load.test.ts +0 -89
  150. package/templates/apps/api/src/lib/__tests__/spoke-store.test.ts +0 -202
  151. package/templates/apps/api/src/lib/__tests__/stripe-admission.test.ts +0 -217
  152. package/templates/apps/api/src/lib/__tests__/stripe.test.ts +0 -82
  153. package/templates/apps/api/src/lib/agent-store.ts +0 -613
  154. package/templates/apps/api/src/lib/auth-email-budget.ts +0 -161
  155. package/templates/apps/api/src/lib/consent-store.ts +0 -363
  156. package/templates/apps/api/src/lib/content-adapter.ts +0 -112
  157. package/templates/apps/api/src/lib/deliverable-asset-store.ts +0 -96
  158. package/templates/apps/api/src/lib/error-serializer.ts +0 -164
  159. package/templates/apps/api/src/lib/errors.ts +0 -95
  160. package/templates/apps/api/src/lib/file-fallback.ts +0 -87
  161. package/templates/apps/api/src/lib/flow-completion-store.ts +0 -136
  162. package/templates/apps/api/src/lib/hub-sign-in-store.ts +0 -455
  163. package/templates/apps/api/src/lib/lead-capture-store.ts +0 -122
  164. package/templates/apps/api/src/lib/lead-delivery.ts +0 -52
  165. package/templates/apps/api/src/lib/license-key-store.ts +0 -45
  166. package/templates/apps/api/src/lib/locales.ts +0 -201
  167. package/templates/apps/api/src/lib/outbound-http.ts +0 -127
  168. package/templates/apps/api/src/lib/prisma.ts +0 -21
  169. package/templates/apps/api/src/lib/proposal-paid-store.ts +0 -66
  170. package/templates/apps/api/src/lib/rate-limit-probe.ts +0 -165
  171. package/templates/apps/api/src/lib/rate-limit-store.ts +0 -142
  172. package/templates/apps/api/src/lib/require-commerce-claim.ts +0 -250
  173. package/templates/apps/api/src/lib/require-paid-tier.ts +0 -53
  174. package/templates/apps/api/src/lib/site.ts +0 -254
  175. package/templates/apps/api/src/lib/slice-load.ts +0 -90
  176. package/templates/apps/api/src/lib/spoke-store.ts +0 -180
  177. package/templates/apps/api/src/lib/stripe.ts +0 -318
  178. package/templates/apps/api/src/lib/webhook-idempotency.ts +0 -156
  179. package/templates/apps/api/src/middleware/__tests__/adversarial/bearer-token-format.test.ts +0 -111
  180. package/templates/apps/api/src/middleware/__tests__/adversarial/cookie-or-bearer-precedence.test.ts +0 -172
  181. package/templates/apps/api/src/middleware/__tests__/adversarial/csrf-bearer-skip.test.ts +0 -119
  182. package/templates/apps/api/src/middleware/__tests__/adversarial/csrf-cookie-path.test.ts +0 -138
  183. package/templates/apps/api/src/middleware/__tests__/adversarial/csrf-trusted-origins.test.ts +0 -142
  184. package/templates/apps/api/src/middleware/__tests__/adversarial/session-fixation.test.ts +0 -155
  185. package/templates/apps/api/src/middleware/__tests__/adversarial/session-timeout.test.ts +0 -139
  186. package/templates/apps/api/src/middleware/__tests__/auth.bearer-path.test.ts +0 -562
  187. package/templates/apps/api/src/middleware/__tests__/auth.both-present-precedence.test.ts +0 -76
  188. package/templates/apps/api/src/middleware/__tests__/auth.cookie-path.test.ts +0 -220
  189. package/templates/apps/api/src/middleware/__tests__/auth.database-not-configured.test.ts +0 -97
  190. package/templates/apps/api/src/middleware/__tests__/auth.hub-session-path.test.ts +0 -557
  191. package/templates/apps/api/src/middleware/__tests__/auth.neither-present.test.ts +0 -72
  192. package/templates/apps/api/src/middleware/__tests__/auth.optional-cookie.test.ts +0 -140
  193. package/templates/apps/api/src/middleware/__tests__/default-tenant.test.ts +0 -721
  194. package/templates/apps/api/src/middleware/__tests__/rate-limit-cross-isolate.db.test.ts +0 -220
  195. package/templates/apps/api/src/middleware/__tests__/rate-limit-store.test.ts +0 -430
  196. package/templates/apps/api/src/middleware/__tests__/rate-limit.test.ts +0 -1409
  197. package/templates/apps/api/src/middleware/__tests__/write-budget.test.ts +0 -174
  198. package/templates/apps/api/src/middleware/auth.ts +0 -864
  199. package/templates/apps/api/src/middleware/default-tenant.ts +0 -166
  200. package/templates/apps/api/src/middleware/rate-limit.ts +0 -983
  201. package/templates/apps/api/src/openapi/__tests__/openapi.test.ts +0 -264
  202. package/templates/apps/api/src/openapi/__tests__/spec-identity.test.ts +0 -182
  203. package/templates/apps/api/src/openapi/index.ts +0 -18
  204. package/templates/apps/api/src/openapi/spec.ts +0 -1815
  205. package/templates/apps/api/src/openapi/surface-drift.ts +0 -195
  206. package/templates/apps/api/src/routes/aeo/__tests__/index.test.ts +0 -175
  207. package/templates/apps/api/src/routes/aeo/index.ts +0 -107
  208. package/templates/apps/api/src/routes/auth/__tests__/auth-tokens.functional.test.ts +0 -196
  209. package/templates/apps/api/src/routes/auth/__tests__/auth-user.functional.test.ts +0 -249
  210. package/templates/apps/api/src/routes/auth/__tests__/hub-sign-in.test.ts +0 -532
  211. package/templates/apps/api/src/routes/auth/__tests__/tokens.test.ts +0 -313
  212. package/templates/apps/api/src/routes/auth/__tests__/transactional-email.test.ts +0 -413
  213. package/templates/apps/api/src/routes/auth/__tests__/user.test.ts +0 -609
  214. package/templates/apps/api/src/routes/auth/hub-sign-in.ts +0 -242
  215. package/templates/apps/api/src/routes/auth/tokens.ts +0 -211
  216. package/templates/apps/api/src/routes/auth/transactional-email.ts +0 -301
  217. package/templates/apps/api/src/routes/auth/user.ts +0 -305
  218. package/templates/apps/api/src/routes/billing/plan-checkout.ts +0 -325
  219. package/templates/apps/api/src/routes/checkout/__tests__/live-key.test.ts +0 -178
  220. package/templates/apps/api/src/routes/checkout/__tests__/offerings-authorization.test.ts +0 -1300
  221. package/templates/apps/api/src/routes/checkout/__tests__/session.test.ts +0 -448
  222. package/templates/apps/api/src/routes/checkout/__tests__/sessions.test.ts +0 -1742
  223. package/templates/apps/api/src/routes/checkout/index.ts +0 -34
  224. package/templates/apps/api/src/routes/checkout/session.ts +0 -171
  225. package/templates/apps/api/src/routes/checkout/sessions.ts +0 -540
  226. package/templates/apps/api/src/routes/consent/__tests__/account.test.ts +0 -386
  227. package/templates/apps/api/src/routes/consent/__tests__/sign-up-rate-limit.test.ts +0 -160
  228. package/templates/apps/api/src/routes/consent/account.ts +0 -268
  229. package/templates/apps/api/src/routes/consent/cookie.ts +0 -90
  230. package/templates/apps/api/src/routes/consent/index.ts +0 -26
  231. package/templates/apps/api/src/routes/consent/unsubscribe.ts +0 -127
  232. package/templates/apps/api/src/routes/content/__tests__/get-page.test.ts +0 -853
  233. package/templates/apps/api/src/routes/content/__tests__/list-pages.test.ts +0 -230
  234. package/templates/apps/api/src/routes/content/__tests__/list-types.test.ts +0 -44
  235. package/templates/apps/api/src/routes/content/__tests__/locale.test.ts +0 -118
  236. package/templates/apps/api/src/routes/content/__tests__/offerings.test.ts +0 -731
  237. package/templates/apps/api/src/routes/content/__tests__/pricing.test.ts +0 -753
  238. package/templates/apps/api/src/routes/content/__tests__/rate-limit.test.ts +0 -51
  239. package/templates/apps/api/src/routes/content/__tests__/search.test.ts +0 -450
  240. package/templates/apps/api/src/routes/content/__tests__/shown-offerings.test.ts +0 -762
  241. package/templates/apps/api/src/routes/content/get-page.ts +0 -268
  242. package/templates/apps/api/src/routes/content/index.ts +0 -49
  243. package/templates/apps/api/src/routes/content/list-pages.ts +0 -95
  244. package/templates/apps/api/src/routes/content/list-types.ts +0 -19
  245. package/templates/apps/api/src/routes/content/offerings.ts +0 -184
  246. package/templates/apps/api/src/routes/content/pricing.ts +0 -176
  247. package/templates/apps/api/src/routes/content/rate-limit.ts +0 -22
  248. package/templates/apps/api/src/routes/content/search.ts +0 -129
  249. package/templates/apps/api/src/routes/content/shown-offerings.ts +0 -229
  250. package/templates/apps/api/src/routes/content/slug.ts +0 -9
  251. package/templates/apps/api/src/routes/leads/__tests__/capture.test.ts +0 -88
  252. package/templates/apps/api/src/routes/leads/__tests__/list.test.ts +0 -171
  253. package/templates/apps/api/src/routes/leads/__tests__/magnet-completion.test.ts +0 -515
  254. package/templates/apps/api/src/routes/leads/__tests__/spoke.test.ts +0 -392
  255. package/templates/apps/api/src/routes/leads/__tests__/track.test.ts +0 -165
  256. package/templates/apps/api/src/routes/leads/index.ts +0 -573
  257. package/templates/apps/api/src/routes/leads/list.ts +0 -104
  258. package/templates/apps/api/src/routes/project-listings/__tests__/configured-application.test.ts +0 -626
  259. package/templates/apps/api/src/routes/project-listings/__tests__/drafts.test.ts +0 -1268
  260. package/templates/apps/api/src/routes/project-listings/__tests__/founder-identity.test.ts +0 -847
  261. package/templates/apps/api/src/routes/project-listings/__tests__/me.test.ts +0 -480
  262. package/templates/apps/api/src/routes/project-listings/__tests__/public.test.ts +0 -465
  263. package/templates/apps/api/src/routes/project-listings/__tests__/resume-email.test.ts +0 -872
  264. package/templates/apps/api/src/routes/project-listings/__tests__/site-answers.test.ts +0 -1022
  265. package/templates/apps/api/src/routes/project-listings/__tests__/site-key.test.ts +0 -484
  266. package/templates/apps/api/src/routes/project-listings/__tests__/structured-address.test.ts +0 -535
  267. package/templates/apps/api/src/routes/project-listings/index.ts +0 -164
  268. package/templates/apps/api/src/routes/project-listings/me.ts +0 -87
  269. package/templates/apps/api/src/routes/project-listings/patch-copy.ts +0 -224
  270. package/templates/apps/api/src/routes/project-listings/patch-draft.ts +0 -102
  271. package/templates/apps/api/src/routes/project-listings/public.ts +0 -98
  272. package/templates/apps/api/src/routes/project-listings/respond.ts +0 -48
  273. package/templates/apps/api/src/routes/project-listings/resume-token.ts +0 -27
  274. package/templates/apps/api/src/routes/project-listings/start.ts +0 -140
  275. package/templates/apps/api/src/routes/project-listings/submit.ts +0 -130
  276. package/templates/apps/api/src/routes/project-listings/verify-email.ts +0 -150
  277. package/templates/apps/api/src/routes/requests/__tests__/confirm.test.ts +0 -686
  278. package/templates/apps/api/src/routes/requests/confirm.ts +0 -601
  279. package/templates/apps/api/src/routes/requests/index.ts +0 -54
  280. package/templates/apps/api/src/routes/test/auth/__tests__/session.test.ts +0 -306
  281. package/templates/apps/api/src/routes/test/auth/session.ts +0 -143
  282. package/templates/apps/api/src/routes/webhooks/README.md +0 -398
  283. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-checkout-consent.test.ts +0 -649
  284. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-dunning.test.ts +0 -749
  285. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-flow-checkout.test.ts +0 -448
  286. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-idempotency.test.ts +0 -264
  287. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-livemode-live.test.ts +0 -159
  288. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-livemode.test.ts +0 -158
  289. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-offerings.test.ts +0 -814
  290. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-org-billing.test.ts +0 -301
  291. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-proposal-paid.test.ts +0 -369
  292. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-rate-limit.test.ts +0 -215
  293. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-request-paid.test.ts +0 -301
  294. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-site-filter.test.ts +0 -808
  295. package/templates/apps/api/src/routes/webhooks/__tests__/stripe.test.ts +0 -1155
  296. package/templates/apps/api/src/routes/webhooks/index.ts +0 -141
  297. package/templates/apps/api/src/routes/webhooks/stripe-offerings.ts +0 -384
  298. package/templates/apps/api/src/routes/webhooks/stripe.ts +0 -2026
  299. package/templates/apps/api/src/services/__tests__/abandon-email.test.ts +0 -528
  300. package/templates/apps/api/src/services/__tests__/answer-distributions.test.ts +0 -132
  301. package/templates/apps/api/src/services/__tests__/audit-log.test.ts +0 -1028
  302. package/templates/apps/api/src/services/__tests__/checkout-plan.test.ts +0 -313
  303. package/templates/apps/api/src/services/__tests__/consent-ledger.test.ts +0 -503
  304. package/templates/apps/api/src/services/__tests__/consent-migration.test.ts +0 -65
  305. package/templates/apps/api/src/services/__tests__/consent.test.ts +0 -299
  306. package/templates/apps/api/src/services/__tests__/default-tenant.test.ts +0 -147
  307. package/templates/apps/api/src/services/__tests__/deliverable-fulfillment.test.ts +0 -867
  308. package/templates/apps/api/src/services/__tests__/deliverable-resend.test.ts +0 -379
  309. package/templates/apps/api/src/services/__tests__/dunning-policy.test.ts +0 -368
  310. package/templates/apps/api/src/services/__tests__/entitlements.test.ts +0 -142
  311. package/templates/apps/api/src/services/__tests__/hub-sign-in.test.ts +0 -854
  312. package/templates/apps/api/src/services/__tests__/keyless-workspace-predicate.test.ts +0 -234
  313. package/templates/apps/api/src/services/__tests__/lead-accept-user.test.ts +0 -251
  314. package/templates/apps/api/src/services/__tests__/lead-routing.test.ts +0 -2660
  315. package/templates/apps/api/src/services/__tests__/listing-config.test.ts +0 -166
  316. package/templates/apps/api/src/services/__tests__/magnet-completion.test.ts +0 -389
  317. package/templates/apps/api/src/services/__tests__/person.test.ts +0 -1176
  318. package/templates/apps/api/src/services/__tests__/plan-offerings.test.ts +0 -444
  319. package/templates/apps/api/src/services/__tests__/project-listings.fence.test.ts +0 -154
  320. package/templates/apps/api/src/services/__tests__/public-site-resolver.test.ts +0 -137
  321. package/templates/apps/api/src/services/__tests__/request-confirm.test.ts +0 -531
  322. package/templates/apps/api/src/services/__tests__/revalidation.test.ts +0 -372
  323. package/templates/apps/api/src/services/__tests__/slack-notify.test.ts +0 -348
  324. package/templates/apps/api/src/services/__tests__/spoke-resolution.test.ts +0 -660
  325. package/templates/apps/api/src/services/__tests__/usage-aggregation.test.ts +0 -941
  326. package/templates/apps/api/src/services/__tests__/usage-credits.test.ts +0 -588
  327. package/templates/apps/api/src/services/__tests__/verified-email.test.ts +0 -78
  328. package/templates/apps/api/src/services/abandon-email.ts +0 -313
  329. package/templates/apps/api/src/services/aeo-score.ts +0 -325
  330. package/templates/apps/api/src/services/answer-distributions.ts +0 -138
  331. package/templates/apps/api/src/services/audit-log.ts +0 -961
  332. package/templates/apps/api/src/services/checkout-buyer.ts +0 -168
  333. package/templates/apps/api/src/services/consent.ts +0 -834
  334. package/templates/apps/api/src/services/default-tenant.ts +0 -416
  335. package/templates/apps/api/src/services/deliverable-fulfillment.ts +0 -755
  336. package/templates/apps/api/src/services/dunning-policy.ts +0 -294
  337. package/templates/apps/api/src/services/enrichment-shim.ts +0 -53
  338. package/templates/apps/api/src/services/entitlements.ts +0 -338
  339. package/templates/apps/api/src/services/hub-sign-in.ts +0 -472
  340. package/templates/apps/api/src/services/lead-accept-user.ts +0 -126
  341. package/templates/apps/api/src/services/lead-promotion.ts +0 -160
  342. package/templates/apps/api/src/services/lead-routing.ts +0 -1372
  343. package/templates/apps/api/src/services/leads-inbox.ts +0 -312
  344. package/templates/apps/api/src/services/listing-config.ts +0 -178
  345. package/templates/apps/api/src/services/magnet-completion.ts +0 -242
  346. package/templates/apps/api/src/services/offerings/__tests__/catalog.test.ts +0 -295
  347. package/templates/apps/api/src/services/offerings/__tests__/checkout-session-record.test.ts +0 -268
  348. package/templates/apps/api/src/services/offerings/__tests__/connection.test.ts +0 -868
  349. package/templates/apps/api/src/services/offerings/__tests__/fixtures.ts +0 -416
  350. package/templates/apps/api/src/services/offerings/__tests__/org-products.test.ts +0 -396
  351. package/templates/apps/api/src/services/offerings/__tests__/readers.test.ts +0 -681
  352. package/templates/apps/api/src/services/offerings/__tests__/source.test.ts +0 -231
  353. package/templates/apps/api/src/services/offerings/catalog.ts +0 -308
  354. package/templates/apps/api/src/services/offerings/checkout-authorization.ts +0 -385
  355. package/templates/apps/api/src/services/offerings/checkout-session-record.ts +0 -192
  356. package/templates/apps/api/src/services/offerings/connection.ts +0 -1003
  357. package/templates/apps/api/src/services/offerings/index.ts +0 -614
  358. package/templates/apps/api/src/services/offerings/source.ts +0 -140
  359. package/templates/apps/api/src/services/offerings/store.ts +0 -150
  360. package/templates/apps/api/src/services/owner-workspaces.ts +0 -132
  361. package/templates/apps/api/src/services/person.ts +0 -1188
  362. package/templates/apps/api/src/services/plan-offerings.ts +0 -125
  363. package/templates/apps/api/src/services/project-listing-resume-email.ts +0 -326
  364. package/templates/apps/api/src/services/project-listings.ts +0 -2073
  365. package/templates/apps/api/src/services/public-site-resolver.ts +0 -396
  366. package/templates/apps/api/src/services/request-confirm.ts +0 -698
  367. package/templates/apps/api/src/services/revalidation.ts +0 -235
  368. package/templates/apps/api/src/services/slack-notify.ts +0 -291
  369. package/templates/apps/api/src/services/usage-aggregation.ts +0 -516
  370. package/templates/apps/api/src/services/usage-credits.ts +0 -340
  371. package/templates/apps/api/src/services/verified-email.ts +0 -71
  372. package/templates/apps/mcp/__tests__/abuse/daily-cap.test.ts +0 -52
  373. package/templates/apps/mcp/__tests__/abuse/email-validator.test.ts +0 -46
  374. package/templates/apps/mcp/__tests__/abuse/guard.test.ts +0 -198
  375. package/templates/apps/mcp/__tests__/abuse/honeypot.test.ts +0 -36
  376. package/templates/apps/mcp/__tests__/abuse/user-agent-deny.test.ts +0 -54
  377. package/templates/apps/mcp/__tests__/aeo-cli-parity.test.ts +0 -116
  378. package/templates/apps/mcp/__tests__/audit-single-page.test.ts +0 -299
  379. package/templates/apps/mcp/__tests__/boot.test.ts +0 -280
  380. package/templates/apps/mcp/__tests__/catalog-drift.test.ts +0 -359
  381. package/templates/apps/mcp/__tests__/config/modules.test.ts +0 -78
  382. package/templates/apps/mcp/__tests__/get_business_hours.test.ts +0 -82
  383. package/templates/apps/mcp/__tests__/get_faq.test.ts +0 -80
  384. package/templates/apps/mcp/__tests__/get_locations.test.ts +0 -65
  385. package/templates/apps/mcp/__tests__/get_offerings.test.ts +0 -557
  386. package/templates/apps/mcp/__tests__/get_pricing.test.ts +0 -524
  387. package/templates/apps/mcp/__tests__/get_site_info.test.ts +0 -81
  388. package/templates/apps/mcp/__tests__/http-transport.test.ts +0 -1151
  389. package/templates/apps/mcp/__tests__/index.test.ts +0 -195
  390. package/templates/apps/mcp/__tests__/lib/audit-single-page-readiness-scan.test.ts +0 -191
  391. package/templates/apps/mcp/__tests__/lib/commerce-claim.test.ts +0 -531
  392. package/templates/apps/mcp/__tests__/lib/content-adapter-parity.test.ts +0 -65
  393. package/templates/apps/mcp/__tests__/lib/content-adapter.test.ts +0 -187
  394. package/templates/apps/mcp/__tests__/lib/content-root.test.ts +0 -93
  395. package/templates/apps/mcp/__tests__/lib/errors.test.ts +0 -75
  396. package/templates/apps/mcp/__tests__/lib/fail-closed-tools.test.ts +0 -165
  397. package/templates/apps/mcp/__tests__/lib/public-workspace.test.ts +0 -124
  398. package/templates/apps/mcp/__tests__/list_pages.test.ts +0 -228
  399. package/templates/apps/mcp/__tests__/locale.test.ts +0 -135
  400. package/templates/apps/mcp/__tests__/module-exclusion.test.ts +0 -175
  401. package/templates/apps/mcp/__tests__/purchase-disabled.test.ts +0 -101
  402. package/templates/apps/mcp/__tests__/read_content.test.ts +0 -474
  403. package/templates/apps/mcp/__tests__/request_callback.test.ts +0 -225
  404. package/templates/apps/mcp/__tests__/search_content.test.ts +0 -256
  405. package/templates/apps/mcp/__tests__/server.test.ts +0 -388
  406. package/templates/apps/mcp/__tests__/start_purchase.test.ts +0 -448
  407. package/templates/apps/mcp/__tests__/submit_lead.test.ts +0 -307
  408. package/templates/apps/mcp/__tests__/subscribe_newsletter.test.ts +0 -223
  409. package/templates/apps/mcp/__tests__/tools/create_project.test.ts +0 -243
  410. package/templates/apps/mcp/__tests__/tools/purchase.test.ts +0 -451
  411. package/templates/apps/mcp/src/abuse/daily-cap.ts +0 -47
  412. package/templates/apps/mcp/src/abuse/email-validator.ts +0 -25
  413. package/templates/apps/mcp/src/abuse/honeypot.ts +0 -21
  414. package/templates/apps/mcp/src/abuse/index.ts +0 -342
  415. package/templates/apps/mcp/src/abuse/user-agent-deny.ts +0 -58
  416. package/templates/apps/mcp/src/boot.ts +0 -167
  417. package/templates/apps/mcp/src/config/modules.ts +0 -43
  418. package/templates/apps/mcp/src/http-transport.ts +0 -526
  419. package/templates/apps/mcp/src/lib/audit-single-page.ts +0 -308
  420. package/templates/apps/mcp/src/lib/commerce-claim.ts +0 -263
  421. package/templates/apps/mcp/src/lib/content-adapter.ts +0 -142
  422. package/templates/apps/mcp/src/lib/empty-content-adapter.ts +0 -139
  423. package/templates/apps/mcp/src/lib/errors.ts +0 -61
  424. package/templates/apps/mcp/src/lib/license-key-store.ts +0 -45
  425. package/templates/apps/mcp/src/lib/locales.ts +0 -171
  426. package/templates/apps/mcp/src/lib/prisma.ts +0 -39
  427. package/templates/apps/mcp/src/lib/public-workspace.ts +0 -133
  428. package/templates/apps/mcp/src/lib/resolve-locale.ts +0 -30
  429. package/templates/apps/mcp/src/lib/shown-offerings.ts +0 -105
  430. package/templates/apps/mcp/src/lib/stripe-tax-signal.ts +0 -59
  431. package/templates/apps/mcp/src/request-context.ts +0 -52
  432. package/templates/apps/mcp/src/server.ts +0 -343
  433. package/templates/apps/mcp/src/serverless-app.ts +0 -88
  434. package/templates/apps/mcp/src/tools/audit.ts +0 -127
  435. package/templates/apps/mcp/src/tools/capture_lead.ts +0 -64
  436. package/templates/apps/mcp/src/tools/create_project.ts +0 -134
  437. package/templates/apps/mcp/src/tools/get_business_hours.ts +0 -68
  438. package/templates/apps/mcp/src/tools/get_faq.ts +0 -71
  439. package/templates/apps/mcp/src/tools/get_locations.ts +0 -88
  440. package/templates/apps/mcp/src/tools/get_offerings.ts +0 -96
  441. package/templates/apps/mcp/src/tools/get_pricing.ts +0 -94
  442. package/templates/apps/mcp/src/tools/get_site_info.ts +0 -86
  443. package/templates/apps/mcp/src/tools/index.ts +0 -137
  444. package/templates/apps/mcp/src/tools/list_pages.ts +0 -74
  445. package/templates/apps/mcp/src/tools/person_notes.ts +0 -25
  446. package/templates/apps/mcp/src/tools/proposals.ts +0 -27
  447. package/templates/apps/mcp/src/tools/purchase.ts +0 -205
  448. package/templates/apps/mcp/src/tools/read_content.ts +0 -75
  449. package/templates/apps/mcp/src/tools/request_callback.ts +0 -59
  450. package/templates/apps/mcp/src/tools/search_content.ts +0 -67
  451. package/templates/apps/mcp/src/tools/subscribe_newsletter.ts +0 -57
  452. package/templates/apps/mcp/src/workspace-server.ts +0 -224
  453. package/templates/database/CHANGELOG.md +0 -961
  454. package/templates/database/LICENSE +0 -202
  455. package/templates/database/NOTICE +0 -2
  456. package/templates/database/README.md +0 -243
  457. package/templates/database/__tests__/agents.db.test.ts +0 -320
  458. package/templates/database/__tests__/appointment.db.test.ts +0 -106
  459. package/templates/database/__tests__/artifact-content-store.db.test.ts +0 -316
  460. package/templates/database/__tests__/composite-fence.db.test.ts +0 -206
  461. package/templates/database/__tests__/consent-ledger.db.test.ts +0 -345
  462. package/templates/database/__tests__/consent-source-checkout-migration.test.ts +0 -79
  463. package/templates/database/__tests__/fence-fan-out.db.test.ts +0 -715
  464. package/templates/database/__tests__/fixtures/appointment-create-probe.ts +0 -79
  465. package/templates/database/__tests__/fixtures/person-backfill.json +0 -264
  466. package/templates/database/__tests__/fixtures/person-contact-backfill.json +0 -182
  467. package/templates/database/__tests__/fixtures/project-listing-consent-probe.ts +0 -100
  468. package/templates/database/__tests__/flow-completion-migration.test.ts +0 -115
  469. package/templates/database/__tests__/flow-completion.db.test.ts +0 -136
  470. package/templates/database/__tests__/flow-workspace-key.db.test.ts +0 -263
  471. package/templates/database/__tests__/flows-listing-diagnostic.test.ts +0 -392
  472. package/templates/database/__tests__/flows-presets.test.ts +0 -173
  473. package/templates/database/__tests__/in-page-magnets-migration.test.ts +0 -161
  474. package/templates/database/__tests__/lead-idempotency-key.db.test.ts +0 -92
  475. package/templates/database/__tests__/member-area.db.test.ts +0 -257
  476. package/templates/database/__tests__/member-contract-migration.test.ts +0 -85
  477. package/templates/database/__tests__/member-contract.db.test.ts +0 -413
  478. package/templates/database/__tests__/offerings-checkout-session.db.test.ts +0 -270
  479. package/templates/database/__tests__/offerings-migration.test.ts +0 -197
  480. package/templates/database/__tests__/offerings-shown-price-ids-migration.test.ts +0 -86
  481. package/templates/database/__tests__/offerings.db.test.ts +0 -303
  482. package/templates/database/__tests__/outbound-message-action.db.test.ts +0 -80
  483. package/templates/database/__tests__/person-contact.db.test.ts +0 -563
  484. package/templates/database/__tests__/person-notes.db.test.ts +0 -249
  485. package/templates/database/__tests__/person.db.test.ts +0 -586
  486. package/templates/database/__tests__/piece-kind-migration.test.ts +0 -67
  487. package/templates/database/__tests__/piece-kind.db.test.ts +0 -208
  488. package/templates/database/__tests__/prefixed-ids.db.test.ts +0 -222
  489. package/templates/database/__tests__/project-listing-consent-at.db.test.ts +0 -111
  490. package/templates/database/__tests__/seed.test.ts +0 -240
  491. package/templates/database/__tests__/spoke-registry.db.test.ts +0 -191
  492. package/templates/database/__tests__/tenancy.test.ts +0 -141
  493. package/templates/database/__tests__/user-cascade.test.ts +0 -140
  494. package/templates/database/_gitignore +0 -8
  495. package/templates/database/auth/.gitkeep +0 -0
  496. package/templates/database/auth/schema.prisma +0 -641
  497. package/templates/database/config/.gitkeep +0 -0
  498. package/templates/database/config/schema.prisma +0 -441
  499. package/templates/database/content/.gitkeep +0 -0
  500. package/templates/database/content/schema.prisma +0 -339
  501. package/templates/database/eslint.config.mjs +0 -69
  502. package/templates/database/flows/listing-diagnostic.ts +0 -182
  503. package/templates/database/flows/presets.ts +0 -315
  504. package/templates/database/inbox/.gitkeep +0 -0
  505. package/templates/database/inbox/README.md +0 -3
  506. package/templates/database/inbox/__tests__/schema.test.ts +0 -44
  507. package/templates/database/inbox/schema.prisma +0 -1447
  508. package/templates/database/jest.config.cjs +0 -36
  509. package/templates/database/migrations/20260508000000_add_inbox_namespace/migration.sql +0 -328
  510. package/templates/database/migrations/20260513000000_better_auth_migration/migration.sql +0 -100
  511. package/templates/database/migrations/20260515000000_add_user_billing_fields/migration.sql +0 -28
  512. package/templates/database/migrations/20260516000000_add_user_tier_care_plan_seat/migration.sql +0 -25
  513. package/templates/database/migrations/20260518000000_add_telemetry_records/migration.sql +0 -42
  514. package/templates/database/migrations/20260525000000_theme_wiring/migration.sql +0 -67
  515. package/templates/database/migrations/20260710000000_retire_commercial_tier/migration.sql +0 -21
  516. package/templates/database/migrations/20260712215647_add_multi_tenant_tenancy/migration.sql +0 -201
  517. package/templates/database/migrations/20260713143320_reanchor_site_config_to_workspace/migration.sql +0 -67
  518. package/templates/database/migrations/20260713174000_add_audit_logs/migration.sql +0 -46
  519. package/templates/database/migrations/20260713190000_drop_telemetry_records/migration.sql +0 -25
  520. package/templates/database/migrations/20260713192000_add_uuidv7_function/migration.sql +0 -49
  521. package/templates/database/migrations/20260713192429_prefixed_uuid_entity_ids/migration.sql +0 -197
  522. package/templates/database/migrations/20260713200000_add_org_billing/migration.sql +0 -32
  523. package/templates/database/migrations/20260714000000_add_lead_promotion_fields/migration.sql +0 -22
  524. package/templates/database/migrations/20260714010000_add_usage_billing_content_models/migration.sql +0 -151
  525. package/templates/database/migrations/20260714020000_add_usage_billing_auth_config_models/migration.sql +0 -223
  526. package/templates/database/migrations/20260714030000_credit_balance_non_negative/migration.sql +0 -22
  527. package/templates/database/migrations/20260714030000_widen_usage_billing_report_aggregates/migration.sql +0 -32
  528. package/templates/database/migrations/20260810233516_add_flow_engine_models/migration.sql +0 -40
  529. package/templates/database/migrations/20260811020000_add_flow_session_abandon_email_columns/migration.sql +0 -4
  530. package/templates/database/migrations/20260811030000_add_flow_session_abandon_email_index/migration.sql +0 -2
  531. package/templates/database/migrations/20260811040000_add_flow_session_segment/migration.sql +0 -2
  532. package/templates/database/migrations/20260811050000_add_deliverable_models/migration.sql +0 -29
  533. package/templates/database/migrations/20260812000000_add_deliverable_grant_send_columns/migration.sql +0 -6
  534. package/templates/database/migrations/20260902222948_add_waitlist_experiment_models/migration.sql +0 -39
  535. package/templates/database/migrations/20260902224500_add_waitlist_id_format_checks/migration.sql +0 -24
  536. package/templates/database/migrations/20260903004112_add_flow_session_flags_aeo_score/migration.sql +0 -3
  537. package/templates/database/migrations/20260903010000_add_playbook_instance/migration.sql +0 -33
  538. package/templates/database/migrations/20260904000000_add_waitlist_followup_send/migration.sql +0 -30
  539. package/templates/database/migrations/20260905230000_add_flow_checkout/migration.sql +0 -47
  540. package/templates/database/migrations/20260906000000_add_flow_checkout_idempotency/migration.sql +0 -16
  541. package/templates/database/migrations/20260907120000_add_project_listing/migration.sql +0 -47
  542. package/templates/database/migrations/20260907130000_add_project_listing_slack_columns/migration.sql +0 -10
  543. package/templates/database/migrations/20260907180000_add_listing_csv_send/migration.sql +0 -26
  544. package/templates/database/migrations/20260909120000_project_listings_platform/migration.sql +0 -90
  545. package/templates/database/migrations/20260909180000_listing_draft_and_fields/migration.sql +0 -174
  546. package/templates/database/migrations/20260910120000_listing_public_site_key/migration.sql +0 -14
  547. package/templates/database/migrations/20260911120000_listing_copy_edit_audit/migration.sql +0 -25
  548. package/templates/database/migrations/20260911140000_listing_structured_address/migration.sql +0 -32
  549. package/templates/database/migrations/20260911180000_consent_grants/migration.sql +0 -71
  550. package/templates/database/migrations/20260911200000_listing_site_answers/migration.sql +0 -30
  551. package/templates/database/migrations/20260912120000_listing_owner_link/migration.sql +0 -49
  552. package/templates/database/migrations/20260914120000_listing_founder_identity/migration.sql +0 -123
  553. package/templates/database/migrations/20260915120000_project_listing_solution/migration.sql +0 -15
  554. package/templates/database/migrations/20260916120000_artifact_content_store/migration.sql +0 -158
  555. package/templates/database/migrations/20260917120000_callback_request_confirm/migration.sql +0 -40
  556. package/templates/database/migrations/20260918120000_add_appointment/migration.sql +0 -67
  557. package/templates/database/migrations/20260918120000_asset_metadata_columns/migration.sql +0 -70
  558. package/templates/database/migrations/20260919120000_flow_workspace_key/migration.sql +0 -181
  559. package/templates/database/migrations/20260919130000_flow_definition_admin_columns/migration.sql +0 -172
  560. package/templates/database/migrations/20260919130000_workspace_meetings/migration.sql +0 -41
  561. package/templates/database/migrations/20260919140000_inbox_workspace_key/migration.sql +0 -185
  562. package/templates/database/migrations/20260920120000_lead_handled_at/migration.sql +0 -70
  563. package/templates/database/migrations/20260920130000_lead_workspace_source_index/migration.sql +0 -57
  564. package/templates/database/migrations/20260921120000_deliverable_grant_workspace_key/migration.sql +0 -68
  565. package/templates/database/migrations/20260922120000_tenancy_fence/migration.sql +0 -1067
  566. package/templates/database/migrations/20260923120000_listing_capturing_magnet/migration.sql +0 -210
  567. package/templates/database/migrations/20261003120000_spoke_registry/migration.sql +0 -80
  568. package/templates/database/migrations/20261003130000_scheduling_connection/migration.sql +0 -49
  569. package/templates/database/migrations/20261005120000_agents/migration.sql +0 -84
  570. package/templates/database/migrations/20261008120000_user_last_workspace/migration.sql +0 -35
  571. package/templates/database/migrations/20261008130000_lead_idempotency_key/migration.sql +0 -20
  572. package/templates/database/migrations/20261009120000_agent_grants/migration.sql +0 -33
  573. package/templates/database/migrations/20261010120000_person/migration.sql +0 -106
  574. package/templates/database/migrations/20261010121000_person_backfill/migration.sql +0 -132
  575. package/templates/database/migrations/20261010130000_agent_grants_people_read/migration.sql +0 -20
  576. package/templates/database/migrations/20261011120000_member_area/migration.sql +0 -158
  577. package/templates/database/migrations/20261011130000_agent_grants_member_pieces_manage/migration.sql +0 -21
  578. package/templates/database/migrations/20261012120000_member_contract/migration.sql +0 -192
  579. package/templates/database/migrations/20261013120000_lead_spoke_checkout/migration.sql +0 -20
  580. package/templates/database/migrations/20261014120000_consent_ledger/migration.sql +0 -122
  581. package/templates/database/migrations/20261014120000_person_contact/migration.sql +0 -231
  582. package/templates/database/migrations/20261015120000_person_notes/migration.sql +0 -77
  583. package/templates/database/migrations/20261015120000_rate_limit_counters/migration.sql +0 -43
  584. package/templates/database/migrations/20261016120000_piece_kind/migration.sql +0 -95
  585. package/templates/database/migrations/20261017120000_outbound_message_action/migration.sql +0 -30
  586. package/templates/database/migrations/20261018120000_flow_completion/migration.sql +0 -52
  587. package/templates/database/migrations/20261019120000_consent_source_checkout/migration.sql +0 -27
  588. package/templates/database/migrations/20261020120000_offerings_data_model/migration.sql +0 -146
  589. package/templates/database/migrations/20261021120000_offerings_checkout_session/migration.sql +0 -77
  590. package/templates/database/migrations/20261022120000_in_page_magnets/migration.sql +0 -45
  591. package/templates/database/migrations/20261023120000_offerings_shown_price_ids/migration.sql +0 -47
  592. package/templates/database/migrations/20261024120000_organization_plan_checkout_session/migration.sql +0 -16
  593. package/templates/database/migrations/migration_lock.toml +0 -3
  594. package/templates/database/ops/.gitkeep +0 -0
  595. package/templates/database/ops/schema.prisma +0 -43
  596. package/templates/database/package.json +0 -89
  597. package/templates/database/schema.prisma +0 -71
  598. package/templates/database/scripts/db-generate-locked.sh +0 -80
  599. package/templates/database/scripts/person-backfill.sql +0 -132
  600. package/templates/database/tenancy.ts +0 -183
  601. package/templates/database/tsconfig.build.json +0 -16
  602. package/templates/database/tsconfig.flows.json +0 -15
  603. package/templates/database/tsconfig.json +0 -16
  604. 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
- });