create-ailk 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (299) hide show
  1. package/README.md +55 -8
  2. package/component-catalog.json +336 -27
  3. package/component-catalog.md +25 -12
  4. package/dist/lib/api-boot-assertion.d.ts +46 -0
  5. package/dist/lib/api-boot-assertion.js +70 -0
  6. package/dist/lib/import-graph.d.ts +29 -0
  7. package/dist/lib/import-graph.js +140 -0
  8. package/dist/module-architecture.d.ts +1 -0
  9. package/dist/module-architecture.js +253 -127
  10. package/dist/surfaces.js +105 -7
  11. package/dist/template-manifest.d.ts +33 -0
  12. package/dist/template-manifest.js +99 -16
  13. package/dist/template-names.d.ts +1 -1
  14. package/dist/template-names.js +1 -0
  15. package/package.json +3 -2
  16. package/site-templates/marketing-site/TEMPLATE-MANIFEST.json +22 -2
  17. package/site-templates/marketing-site/TEMPLATE-MANIFEST.md +9 -2
  18. package/site-templates/marketing-site/ailk-template.json +1 -1
  19. package/site-templates/marketing-site-free/TEMPLATE-MANIFEST.json +2 -2
  20. package/site-templates/marketing-site-free/TEMPLATE-MANIFEST.md +1 -0
  21. package/site-templates/minimalism-site/TEMPLATE-MANIFEST.json +10 -2
  22. package/site-templates/minimalism-site/TEMPLATE-MANIFEST.md +47 -35
  23. package/site-templates/minimalism-site/ailk-template.json +2 -1
  24. package/site-templates/minimalism-site/assets/wordmark-placeholder.svg +28 -0
  25. package/site-templates/minimalism-site/content/en/HomePage/home.mdx +49 -19
  26. package/site-templates/simple-service/TEMPLATE-MANIFEST.json +240 -0
  27. package/site-templates/simple-service/TEMPLATE-MANIFEST.md +278 -0
  28. package/site-templates/simple-service/ailk-template.json +10 -0
  29. package/site-templates/simple-service/content/en/AboutPage/about.mdx +38 -0
  30. package/site-templates/simple-service/content/en/ContactPage/contact.mdx +67 -0
  31. package/site-templates/simple-service/content/en/FAQPage/faq.mdx +56 -0
  32. package/site-templates/simple-service/content/en/HomePage/home.mdx +85 -0
  33. package/site-templates/simple-service/content/en/Service/landscape-design.mdx +40 -0
  34. package/site-templates/simple-service/content/en/Service/lawn-maintenance.mdx +40 -0
  35. package/site-templates/simple-service/content/en/Service/seasonal-cleanup.mdx +40 -0
  36. package/site-templates/simple-service/content/en/ServicesList/services.mdx +72 -0
  37. package/site-templates/simple-service/provenance.json +4 -0
  38. package/templates/.env.example +72 -7
  39. package/templates/apps/api/.ailk/inbox/2026-09-20T14-57-31.552Z-fallback-1789916251590-037e9005.json +8 -0
  40. package/templates/apps/api/.ailk/inbox/2026-09-20T14-57-33.840Z-fallback-1789916253842-b52659e9.json +12 -0
  41. package/templates/apps/api/.ailk/inbox/2026-09-20T14-57-33.844Z-fallback-1789916253845-6b266f8c.json +12 -0
  42. package/templates/apps/api/.env.example +13 -0
  43. package/templates/apps/api/CLAUDE.md +26 -2
  44. package/templates/apps/api/jest.config.cjs +3 -0
  45. package/templates/apps/api/package.json +1 -0
  46. package/templates/apps/api/src/__tests__/commerce-claim-registration.test.ts +407 -0
  47. package/templates/apps/api/src/__tests__/module-exclusion.test.ts +83 -7
  48. package/templates/apps/api/src/__tests__/server.test.ts +471 -0
  49. package/templates/apps/api/src/__tests__/vercel-handler.test.ts +45 -0
  50. package/templates/apps/api/src/__tests__/workspace-module-registration.test.ts +2 -0
  51. package/templates/apps/api/src/config/index.ts +62 -0
  52. package/templates/apps/api/src/config/modules.ts +7 -3
  53. package/templates/apps/api/src/lib/__mocks__/prisma.ts +238 -2
  54. package/templates/apps/api/src/lib/__tests__/auth-email-budget.test.ts +143 -0
  55. package/templates/apps/api/src/lib/__tests__/content-adapter.test.ts +23 -0
  56. package/templates/apps/api/src/lib/__tests__/deliverable-asset-store.test.ts +125 -0
  57. package/templates/apps/api/src/lib/__tests__/error-serializer.test.ts +20 -0
  58. package/templates/apps/api/src/lib/__tests__/require-commerce-claim.test.ts +317 -0
  59. package/templates/apps/api/src/lib/__tests__/site.test.ts +238 -0
  60. package/templates/apps/api/src/lib/__tests__/stripe.test.ts +75 -0
  61. package/templates/apps/api/src/lib/auth-email-budget.ts +160 -0
  62. package/templates/apps/api/src/lib/content-adapter.ts +57 -31
  63. package/templates/apps/api/src/lib/deliverable-asset-store.ts +76 -0
  64. package/templates/apps/api/src/lib/error-serializer.ts +23 -3
  65. package/templates/apps/api/src/lib/outbound-http.ts +7 -2
  66. package/templates/apps/api/src/lib/require-commerce-claim.ts +250 -0
  67. package/templates/apps/api/src/lib/site.ts +208 -9
  68. package/templates/apps/api/src/lib/stripe.ts +66 -0
  69. package/templates/apps/api/src/middleware/__tests__/default-tenant.test.ts +182 -0
  70. package/templates/apps/api/src/middleware/__tests__/rate-limit.test.ts +42 -0
  71. package/templates/apps/api/src/middleware/rate-limit.ts +7 -1
  72. package/templates/apps/api/src/openapi/spec.ts +543 -2
  73. package/templates/apps/api/src/routes/auth/__tests__/auth-user.functional.test.ts +48 -0
  74. package/templates/apps/api/src/routes/auth/__tests__/transactional-email.test.ts +309 -0
  75. package/templates/apps/api/src/routes/auth/__tests__/user.test.ts +123 -0
  76. package/templates/apps/api/src/routes/auth/transactional-email.ts +273 -0
  77. package/templates/apps/api/src/routes/auth/user.ts +61 -0
  78. package/templates/apps/api/src/routes/checkout/__tests__/session.test.ts +434 -0
  79. package/templates/apps/api/src/routes/checkout/__tests__/sessions.test.ts +888 -0
  80. package/templates/apps/api/src/routes/checkout/index.ts +34 -0
  81. package/templates/apps/api/src/routes/checkout/session.ts +139 -0
  82. package/templates/apps/api/src/routes/checkout/sessions.ts +197 -0
  83. package/templates/apps/api/src/routes/content/__tests__/get-page.test.ts +554 -0
  84. package/templates/apps/api/src/routes/content/__tests__/list-pages.test.ts +108 -0
  85. package/templates/apps/api/src/routes/content/__tests__/search.test.ts +450 -0
  86. package/templates/apps/api/src/routes/content/get-page.ts +94 -12
  87. package/templates/apps/api/src/routes/content/index.ts +13 -73
  88. package/templates/apps/api/src/routes/content/list-pages.ts +15 -3
  89. package/templates/apps/api/src/routes/content/rate-limit.ts +15 -6
  90. package/templates/apps/api/src/routes/content/search.ts +129 -0
  91. package/templates/apps/api/src/routes/leads/__tests__/index.test.ts +447 -31
  92. package/templates/apps/api/src/routes/leads/index.ts +100 -13
  93. package/templates/apps/api/src/routes/project-listings/__tests__/configured-application.test.ts +51 -0
  94. package/templates/apps/api/src/routes/project-listings/__tests__/drafts.test.ts +351 -0
  95. package/templates/apps/api/src/routes/project-listings/__tests__/founder-identity.test.ts +51 -0
  96. package/templates/apps/api/src/routes/project-listings/__tests__/me.test.ts +5 -2
  97. package/templates/apps/api/src/routes/project-listings/__tests__/public.test.ts +4 -1
  98. package/templates/apps/api/src/routes/project-listings/__tests__/resume-email.test.ts +58 -0
  99. package/templates/apps/api/src/routes/project-listings/__tests__/site-answers.test.ts +107 -6
  100. package/templates/apps/api/src/routes/project-listings/__tests__/site-key.test.ts +87 -2
  101. package/templates/apps/api/src/routes/project-listings/__tests__/structured-address.test.ts +51 -0
  102. package/templates/apps/api/src/routes/project-listings/start.ts +5 -1
  103. package/templates/apps/api/src/routes/requests/__tests__/confirm.test.ts +686 -0
  104. package/templates/apps/api/src/routes/requests/confirm.ts +601 -0
  105. package/templates/apps/api/src/routes/requests/index.ts +54 -0
  106. package/templates/apps/api/src/routes/webhooks/README.md +265 -0
  107. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-dunning.test.ts +749 -0
  108. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-flow-checkout.test.ts +330 -0
  109. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-idempotency.test.ts +262 -0
  110. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-org-billing.test.ts +285 -0
  111. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-rate-limit.test.ts +213 -0
  112. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-request-paid.test.ts +301 -0
  113. package/templates/apps/api/src/routes/webhooks/__tests__/stripe.test.ts +648 -0
  114. package/templates/apps/api/src/routes/webhooks/index.ts +89 -0
  115. package/templates/apps/api/src/routes/webhooks/stripe.ts +1399 -0
  116. package/templates/apps/api/src/server.ts +439 -49
  117. package/templates/apps/api/src/services/__tests__/abandon-email.test.ts +39 -0
  118. package/templates/apps/api/src/services/__tests__/aeo-score.test.ts +217 -40
  119. package/templates/apps/api/src/services/__tests__/audit-log.test.ts +620 -0
  120. package/templates/apps/api/src/services/__tests__/consent.test.ts +2 -0
  121. package/templates/apps/api/src/services/__tests__/deliverable-fulfillment.test.ts +300 -5
  122. package/templates/apps/api/src/services/__tests__/deliverable-resend.test.ts +20 -0
  123. package/templates/apps/api/src/services/__tests__/dunning-policy.test.ts +368 -0
  124. package/templates/apps/api/src/services/__tests__/lead-routing.test.ts +160 -0
  125. package/templates/apps/api/src/services/__tests__/listing-config.test.ts +166 -0
  126. package/templates/apps/api/src/services/__tests__/project-listings.fence.test.ts +154 -0
  127. package/templates/apps/api/src/services/__tests__/public-site-resolver.test.ts +137 -0
  128. package/templates/apps/api/src/services/__tests__/request-confirm.test.ts +444 -0
  129. package/templates/apps/api/src/services/__tests__/revalidation.test.ts +238 -0
  130. package/templates/apps/api/src/services/__tests__/verified-email.test.ts +78 -0
  131. package/templates/apps/api/src/services/abandon-email.ts +8 -2
  132. package/templates/apps/api/src/services/aeo-score.ts +49 -12
  133. package/templates/apps/api/src/services/audit-log.ts +668 -0
  134. package/templates/apps/api/src/services/consent.ts +18 -0
  135. package/templates/apps/api/src/services/default-tenant.ts +70 -31
  136. package/templates/apps/api/src/services/deliverable-fulfillment.ts +141 -13
  137. package/templates/apps/api/src/services/dunning-policy.ts +294 -0
  138. package/templates/apps/api/src/services/entitlements.ts +80 -0
  139. package/templates/apps/api/src/services/lead-promotion.ts +13 -14
  140. package/templates/apps/api/src/services/lead-routing.ts +161 -2
  141. package/templates/apps/api/src/services/leads-inbox.ts +23 -2
  142. package/templates/apps/api/src/services/listing-config.ts +27 -9
  143. package/templates/apps/api/src/services/project-listings.ts +201 -6
  144. package/templates/apps/api/src/services/public-site-resolver.ts +106 -0
  145. package/templates/apps/api/src/services/request-confirm.ts +646 -0
  146. package/templates/apps/api/src/services/revalidation.ts +173 -0
  147. package/templates/apps/api/src/services/verified-email.ts +71 -0
  148. package/templates/apps/api/src/vercel-handler.ts +75 -35
  149. package/templates/apps/mcp/.env.example +17 -0
  150. package/templates/apps/mcp/CLAUDE.md +57 -24
  151. package/templates/apps/mcp/__tests__/aeo-cli-parity.test.ts +6 -0
  152. package/templates/apps/mcp/__tests__/audit.test.ts +137 -8
  153. package/templates/apps/mcp/__tests__/catalog-drift.test.ts +79 -36
  154. package/templates/apps/mcp/__tests__/get_offerings.test.ts +111 -2
  155. package/templates/apps/mcp/__tests__/get_pricing.test.ts +82 -2
  156. package/templates/apps/mcp/__tests__/http-transport.test.ts +541 -2
  157. package/templates/apps/mcp/__tests__/index.test.ts +39 -0
  158. package/templates/apps/mcp/__tests__/lib/audit-single-page-readiness-scan.test.ts +143 -0
  159. package/templates/apps/mcp/__tests__/lib/commerce-claim.test.ts +111 -0
  160. package/templates/apps/mcp/__tests__/lib/content-adapter-parity.test.ts +65 -0
  161. package/templates/apps/mcp/__tests__/lib/content-adapter.test.ts +188 -0
  162. package/templates/apps/mcp/__tests__/lib/fail-closed-tools.test.ts +165 -0
  163. package/templates/apps/mcp/__tests__/lib/public-workspace.test.ts +124 -0
  164. package/templates/apps/mcp/__tests__/list_pages.test.ts +116 -0
  165. package/templates/apps/mcp/__tests__/module-exclusion.test.ts +7 -1
  166. package/templates/apps/mcp/__tests__/parity.test.ts +10 -7
  167. package/templates/apps/mcp/__tests__/purchase-disabled.test.ts +89 -22
  168. package/templates/apps/mcp/__tests__/read_content.test.ts +322 -1
  169. package/templates/apps/mcp/__tests__/search_content.test.ts +105 -2
  170. package/templates/apps/mcp/__tests__/server.test.ts +67 -14
  171. package/templates/apps/mcp/__tests__/start_purchase.test.ts +252 -0
  172. package/templates/apps/mcp/__tests__/tools/purchase.test.ts +300 -123
  173. package/templates/apps/mcp/jest.config.cjs +13 -0
  174. package/templates/apps/mcp/package.json +2 -0
  175. package/templates/apps/mcp/src/abuse/index.ts +159 -24
  176. package/templates/apps/mcp/src/config/modules.ts +10 -5
  177. package/templates/apps/mcp/src/http-transport.ts +102 -29
  178. package/templates/apps/mcp/src/index.ts +73 -11
  179. package/templates/apps/mcp/src/lib/audit-single-page.ts +90 -3
  180. package/templates/apps/mcp/src/lib/commerce-claim.ts +94 -0
  181. package/templates/apps/mcp/src/lib/content-adapter.ts +113 -0
  182. package/templates/apps/mcp/src/lib/empty-content-adapter.ts +139 -0
  183. package/templates/apps/mcp/src/lib/prisma.ts +39 -0
  184. package/templates/apps/mcp/src/lib/public-workspace.ts +133 -0
  185. package/templates/apps/mcp/src/lib/stripe-tax-signal.ts +59 -0
  186. package/templates/apps/mcp/src/server.ts +59 -35
  187. package/templates/apps/mcp/src/tools/audit.ts +26 -2
  188. package/templates/apps/mcp/src/tools/get_business_hours.ts +4 -3
  189. package/templates/apps/mcp/src/tools/get_faq.ts +4 -3
  190. package/templates/apps/mcp/src/tools/get_locations.ts +5 -3
  191. package/templates/apps/mcp/src/tools/get_offerings.ts +16 -4
  192. package/templates/apps/mcp/src/tools/get_pricing.ts +25 -6
  193. package/templates/apps/mcp/src/tools/get_site_info.ts +4 -3
  194. package/templates/apps/mcp/src/tools/index.ts +6 -4
  195. package/templates/apps/mcp/src/tools/list_pages.ts +4 -3
  196. package/templates/apps/mcp/src/tools/purchase.ts +128 -45
  197. package/templates/apps/mcp/src/tools/read_content.ts +20 -6
  198. package/templates/apps/mcp/src/tools/search_content.ts +11 -4
  199. package/templates/apps/web/.env.example +71 -5
  200. package/templates/apps/web/CLAUDE.md +44 -0
  201. package/templates/apps/web/app/.well-known/mcp.json/build-manifest.ts +18 -2
  202. package/templates/apps/web/app/.well-known/mcp.json/route.ts +11 -3
  203. package/templates/apps/web/app/[locale]/(auth)/__tests__/auth-pages.test.tsx +282 -0
  204. package/templates/apps/web/app/[locale]/(auth)/__tests__/password-reset.test.tsx +515 -0
  205. package/templates/apps/web/app/[locale]/(auth)/forgot-password/forgot-password-card.tsx +89 -0
  206. package/templates/apps/web/app/[locale]/(auth)/forgot-password/page.tsx +109 -0
  207. package/templates/apps/web/app/[locale]/(auth)/layout.tsx +92 -0
  208. package/templates/apps/web/app/[locale]/(auth)/reset-password/page.tsx +135 -0
  209. package/templates/apps/web/app/[locale]/(auth)/reset-password/reset-password-card.tsx +109 -0
  210. package/templates/apps/web/app/[locale]/{sign-in → (auth)/sign-in}/__tests__/page.test.tsx +48 -2
  211. package/templates/apps/web/app/[locale]/{sign-in → (auth)/sign-in}/page.tsx +20 -6
  212. package/templates/apps/web/app/[locale]/(auth)/sign-in/sign-in-card.tsx +125 -0
  213. package/templates/apps/web/app/[locale]/(auth)/sign-up/page.tsx +96 -0
  214. package/templates/apps/web/app/[locale]/(auth)/sign-up/sign-up-card.tsx +101 -0
  215. package/templates/apps/web/app/[locale]/(auth)/use-auth-card-flow.ts +102 -0
  216. package/templates/apps/web/app/[locale]/(auth)/verify-email/page.tsx +87 -0
  217. package/templates/apps/web/app/[locale]/(authed)/__tests__/gate.test.tsx +20 -10
  218. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/page.test.tsx +84 -0
  219. package/templates/apps/web/app/[locale]/(authed)/account/actions.ts +58 -0
  220. package/templates/apps/web/app/[locale]/(authed)/account/page.tsx +63 -8
  221. package/templates/apps/web/app/[locale]/(authed)/layout.tsx +18 -1
  222. package/templates/apps/web/app/[locale]/cancellation/page.tsx +44 -0
  223. package/templates/apps/web/app/[locale]/layout.tsx +133 -87
  224. package/templates/apps/web/app/[locale]/purchase/__tests__/cancel.test.tsx +162 -0
  225. package/templates/apps/web/app/[locale]/purchase/__tests__/module-scope.test.ts +68 -0
  226. package/templates/apps/web/app/[locale]/purchase/__tests__/success.test.tsx +361 -0
  227. package/templates/apps/web/app/[locale]/purchase/cancel/page.tsx +115 -0
  228. package/templates/apps/web/app/[locale]/purchase/success/page.tsx +307 -0
  229. package/templates/apps/web/app/[locale]/returns/page.tsx +44 -0
  230. package/templates/apps/web/app/[locale]/shipping/page.tsx +44 -0
  231. package/templates/apps/web/app/api/revalidate/__tests__/route.test.ts +670 -0
  232. package/templates/apps/web/app/api/revalidate/route.ts +194 -0
  233. package/templates/apps/web/auth.ts +407 -8
  234. package/templates/apps/web/jest.config.cjs +8 -4
  235. package/templates/apps/web/lib/__tests__/auth-email.test.ts +214 -0
  236. package/templates/apps/web/lib/__tests__/auth-routes.test.ts +74 -0
  237. package/templates/apps/web/lib/__tests__/meeting-slugs.test.ts +72 -0
  238. package/templates/apps/web/lib/__tests__/structured-data.test.tsx +18 -1
  239. package/templates/apps/web/lib/auth-email.ts +318 -0
  240. package/templates/apps/web/lib/auth-env.ts +85 -0
  241. package/templates/apps/web/lib/auth-routes.ts +55 -0
  242. package/templates/apps/web/lib/meeting-slugs.ts +53 -0
  243. package/templates/apps/web/lib/telemetry-scrub.ts +5 -1
  244. package/templates/apps/web/messages/en.json +187 -0
  245. package/templates/apps/web/package.json +2 -1
  246. package/templates/apps/web/src/lib/commerce-claim.ts +33 -0
  247. package/templates/apps/web/src/lib/commerce-sections.ts +61 -0
  248. package/templates/content/en/CancellationPolicyPage/cancellation.mdx +108 -0
  249. package/templates/content/en/ReturnsPolicyPage/returns.mdx +108 -0
  250. package/templates/content/en/ShippingPolicyPage/shipping.mdx +108 -0
  251. package/templates/database/CHANGELOG.md +142 -0
  252. package/templates/database/README.md +10 -3
  253. package/templates/database/__tests__/appointment.db.test.ts +106 -0
  254. package/templates/database/__tests__/artifact-content-store.db.test.ts +316 -0
  255. package/templates/database/__tests__/composite-fence.db.test.ts +206 -0
  256. package/templates/database/__tests__/fence-fan-out.db.test.ts +711 -0
  257. package/templates/database/__tests__/fixtures/appointment-create-probe.ts +79 -0
  258. package/templates/database/__tests__/fixtures/project-listing-consent-probe.ts +100 -0
  259. package/templates/database/__tests__/flow-workspace-key.db.test.ts +263 -0
  260. package/templates/database/__tests__/prefixed-ids.db.test.ts +85 -9
  261. package/templates/database/__tests__/project-listing-consent-at.db.test.ts +111 -0
  262. package/templates/database/__tests__/tenancy.test.ts +141 -0
  263. package/templates/database/config/schema.prisma +79 -2
  264. package/templates/database/content/schema.prisma +87 -11
  265. package/templates/database/inbox/schema.prisma +452 -9
  266. package/templates/database/jest.config.cjs +5 -3
  267. package/templates/database/migrations/20260915120000_project_listing_solution/migration.sql +15 -0
  268. package/templates/database/migrations/20260916120000_artifact_content_store/migration.sql +158 -0
  269. package/templates/database/migrations/20260917120000_callback_request_confirm/migration.sql +40 -0
  270. package/templates/database/migrations/20260918120000_add_appointment/migration.sql +67 -0
  271. package/templates/database/migrations/20260918120000_asset_metadata_columns/migration.sql +70 -0
  272. package/templates/database/migrations/20260919120000_flow_workspace_key/migration.sql +181 -0
  273. package/templates/database/migrations/20260919130000_flow_definition_admin_columns/migration.sql +172 -0
  274. package/templates/database/migrations/20260919130000_workspace_meetings/migration.sql +41 -0
  275. package/templates/database/migrations/20260919140000_inbox_workspace_key/migration.sql +185 -0
  276. package/templates/database/migrations/20260920120000_lead_handled_at/migration.sql +70 -0
  277. package/templates/database/migrations/20260920130000_lead_workspace_source_index/migration.sql +57 -0
  278. package/templates/database/migrations/20260921120000_deliverable_grant_workspace_key/migration.sql +68 -0
  279. package/templates/database/migrations/20260922120000_tenancy_fence/migration.sql +1067 -0
  280. package/templates/database/migrations/20260923120000_listing_capturing_magnet/migration.sql +210 -0
  281. package/templates/database/package.json +1 -1
  282. package/templates/database/tenancy.ts +86 -1
  283. package/templates/database/tsconfig.json +1 -0
  284. package/versions.json +34 -34
  285. package/templates/apps/api/src/routes/content/__tests__/create.test.ts +0 -253
  286. package/templates/apps/api/src/routes/content/__tests__/delete.test.ts +0 -215
  287. package/templates/apps/api/src/routes/content/__tests__/update.test.ts +0 -266
  288. package/templates/apps/api/src/routes/content/create.ts +0 -115
  289. package/templates/apps/api/src/routes/content/delete.ts +0 -82
  290. package/templates/apps/api/src/routes/content/update.ts +0 -112
  291. package/templates/apps/mcp/__tests__/create_page.test.ts +0 -202
  292. package/templates/apps/mcp/__tests__/delete_page.test.ts +0 -177
  293. package/templates/apps/mcp/__tests__/update_page.test.ts +0 -196
  294. package/templates/apps/mcp/src/tools/create_page.ts +0 -96
  295. package/templates/apps/mcp/src/tools/delete_page.ts +0 -74
  296. package/templates/apps/mcp/src/tools/update_page.ts +0 -92
  297. package/templates/apps/web/app/[locale]/sign-in/sign-in-card.tsx +0 -123
  298. /package/templates/apps/web/app/[locale]/{sign-in → (auth)/sign-in}/__tests__/next-path.test.ts +0 -0
  299. /package/templates/apps/web/app/[locale]/{sign-in → (auth)/sign-in}/next-path.ts +0 -0
@@ -0,0 +1,620 @@
1
+ /**
2
+ * @file audit-log.test.ts
3
+ * @description Unit tests for the agent-action audit writer (#6040,
4
+ * REL-017 row 5 / FEAT-084 SUB-096), scored against docs/specs/6040-one-auditlog-row-per-agent-spec.md §5.1.
5
+ *
6
+ * External dependency boundaries mocked:
7
+ * - apps/api/src/lib/prisma — the repo-standard `__mocks__/prisma.ts`
8
+ * manual mock (`jest.mock("../../lib/prisma.js")`). Not read directly by
9
+ * any case below — `recordAgentAction`'s injectable `AuditWriteClient`
10
+ * (D1) means every case supplies its own stub delegate — this mock is
11
+ * kept only so importing `audit-log.ts` never constructs a real
12
+ * `PrismaPg` adapter (the repo-standard reason every sibling service
13
+ * test carries this line regardless of whether it touches `prisma`
14
+ * directly).
15
+ * - @working-theory/observability `logger` — a partial mock (`...actual`
16
+ * plus an overridden `logger`) so `redactHighEntropy` and `sanitizePII`
17
+ * still run for real (AC-2 case 5 pins the real `sanitizePII`'s
18
+ * behaviour) while `logger.error` / `logger.warn` are observable.
19
+ */
20
+
21
+ // 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.
22
+ jest.mock("../../lib/prisma.js");
23
+
24
+ const mockLoggerError = jest.fn();
25
+ const mockLoggerWarn = jest.fn();
26
+ jest.mock("@working-theory/observability", () => {
27
+ const actual = jest.requireActual("@working-theory/observability");
28
+ return {
29
+ ...actual,
30
+ logger: {
31
+ info: jest.fn(),
32
+ debug: jest.fn(),
33
+ warn: (...args: unknown[]) => mockLoggerWarn(...args),
34
+ error: (...args: unknown[]) => mockLoggerError(...args),
35
+ },
36
+ };
37
+ });
38
+
39
+ import { readFileSync } from "node:fs";
40
+ import { join } from "node:path";
41
+
42
+ import { zAuditLogId, zWorkspaceId, type Id } from "@working-theory/ids";
43
+ import { sanitizePII } from "@working-theory/observability";
44
+
45
+ import type { TenantContext } from "../default-tenant.js";
46
+ import {
47
+ deriveAuditRowId,
48
+ recordAgentAction,
49
+ redactPersonalData,
50
+ type AuditRowDigestInput,
51
+ type AuditWriteClient,
52
+ type RecordAgentActionInput,
53
+ } from "../audit-log.js";
54
+
55
+ // ─── Fixtures ───────────────────────────────────────────────────────────────
56
+
57
+ // v7-shaped, RFC-4122-variant uuids — each satisfies the same
58
+ // `[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}` CHECK
59
+ // grammar `zWorkspaceId` / `zAuditLogId` enforce.
60
+ const WORKSPACE_ID = "wksp_0190f3a2-7c1d-7e4a-9b2c-000000000001";
61
+ const ORG_ID = "org_0190f3a2-7c1d-7e4a-9b2c-000000000002";
62
+ const USER_ID = "user_0190f3a2-7c1d-7e4a-9b2c-000000000003";
63
+
64
+ const TENANT: TenantContext = {
65
+ userId: USER_ID as Id<"user">,
66
+ organizationId: ORG_ID as Id<"organization">,
67
+ workspaceId: WORKSPACE_ID as Id<"workspace">,
68
+ role: "owner",
69
+ };
70
+
71
+ const BASE_INPUT: RecordAgentActionInput = {
72
+ tenant: TENANT,
73
+ actorId: "agent_abc123",
74
+ tool: "refund",
75
+ outcome: "succeeded",
76
+ idempotencyKey: "req_abc123",
77
+ };
78
+
79
+ /** A resolved row's `data` argument, as `AuditWriteClient.auditLog.create`
80
+ * would have received it — loosely typed here since the test asserts on
81
+ * individual fields rather than importing the module-private row shape. */
82
+ interface WrittenRow {
83
+ id: string;
84
+ workspaceId: string;
85
+ actorId: string;
86
+ actorType: string;
87
+ action: string;
88
+ targetType?: string;
89
+ targetId?: string;
90
+ metadata: Record<string, unknown>;
91
+ }
92
+
93
+ function stubDb(
94
+ create: jest.Mock = jest.fn().mockResolvedValue({ id: "ignored" }),
95
+ ): {
96
+ db: AuditWriteClient;
97
+ create: jest.Mock;
98
+ } {
99
+ return { db: { auditLog: { create } }, create };
100
+ }
101
+
102
+ function firstWrittenRow(create: jest.Mock): WrittenRow {
103
+ return (create.mock.calls[0]![0] as { data: WrittenRow }).data;
104
+ }
105
+
106
+ beforeEach(() => {
107
+ mockLoggerError.mockClear();
108
+ mockLoggerWarn.mockClear();
109
+ });
110
+
111
+ // ─── AC-1 — exactly one row, carrying the five facts ───────────────────────
112
+
113
+ describe("AC-1 — exactly one row, carrying the five facts", () => {
114
+ it("calls create exactly once for one recordAgentAction call", async () => {
115
+ const { db, create } = stubDb();
116
+ await recordAgentAction(BASE_INPUT, db);
117
+ expect(create).toHaveBeenCalledTimes(1);
118
+ });
119
+
120
+ it("writes workspaceId from the resolved tenant, satisfying zWorkspaceId", async () => {
121
+ const { db, create } = stubDb();
122
+ await recordAgentAction(BASE_INPUT, db);
123
+ const row = firstWrittenRow(create);
124
+ expect(row.workspaceId).toBe(TENANT.workspaceId);
125
+ expect(zWorkspaceId.safeParse(row.workspaceId).success).toBe(true);
126
+ });
127
+
128
+ it("writes actorType 'agent' unconditionally — a regression guard, not caller-influenced", async () => {
129
+ const { db, create } = stubDb();
130
+ await recordAgentAction({ ...BASE_INPUT, outcome: "refused" }, db);
131
+ const row = firstWrittenRow(create);
132
+ expect(row.actorType).toBe("agent");
133
+ });
134
+
135
+ it("writes actorId verbatim", async () => {
136
+ const { db, create } = stubDb();
137
+ await recordAgentAction(BASE_INPUT, db);
138
+ const row = firstWrittenRow(create);
139
+ expect(row.actorId).toBe(BASE_INPUT.actorId);
140
+ });
141
+
142
+ it("writes action as 'agent.commerce.' + tool — the tool name in the column, not only metadata", async () => {
143
+ const { db, create } = stubDb();
144
+ await recordAgentAction({ ...BASE_INPUT, tool: "start_purchase" }, db);
145
+ const row = firstWrittenRow(create);
146
+ expect(row.action).toBe("agent.commerce.start_purchase");
147
+ });
148
+
149
+ it.each([
150
+ "succeeded",
151
+ "failed",
152
+ "refused",
153
+ "awaiting_approval",
154
+ ] satisfies RecordAgentActionInput["outcome"][])(
155
+ "writes metadata.outcome = %s for every AgentActionOutcome member",
156
+ async (outcome) => {
157
+ const { db, create } = stubDb();
158
+ await recordAgentAction({ ...BASE_INPUT, outcome }, db);
159
+ const row = firstWrittenRow(create);
160
+ expect(row.metadata.outcome).toBe(outcome);
161
+ },
162
+ );
163
+
164
+ it("omits createdAt so the database clock supplies it — an agent cannot backdate its own row", async () => {
165
+ const { db, create } = stubDb();
166
+ await recordAgentAction(BASE_INPUT, db);
167
+ const row = firstWrittenRow(create) as WrittenRow & { createdAt?: unknown };
168
+ expect(row.createdAt).toBeUndefined();
169
+ });
170
+
171
+ it("writes an id satisfying zAuditLogId and the migration's literal CHECK regex", async () => {
172
+ const { db, create } = stubDb();
173
+ await recordAgentAction(BASE_INPUT, db);
174
+ const row = firstWrittenRow(create);
175
+ // database/migrations/20260713192429_prefixed_uuid_entity_ids/migration.sql:158
176
+ expect(row.id).toMatch(
177
+ /^audit_[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,
178
+ );
179
+ expect(zAuditLogId.safeParse(row.id).success).toBe(true);
180
+ });
181
+ });
182
+
183
+ // ─── AC-2 — personal data never reaches the stored row in clear form ───────
184
+
185
+ describe("AC-2 — personal data never reaches the stored row in clear form", () => {
186
+ it("redacts an email and phone number from summary/failureReason on the serialized row", async () => {
187
+ const { db, create } = stubDb();
188
+ await recordAgentAction(
189
+ {
190
+ ...BASE_INPUT,
191
+ outcome: "failed",
192
+ summary: "refunded buyer jane.doe@example.com, phone +1 415 555 0134",
193
+ failureReason: "declined for jane.doe@example.com",
194
+ },
195
+ db,
196
+ );
197
+ const row = firstWrittenRow(create);
198
+ const serialized = JSON.stringify(row);
199
+ expect(serialized).not.toContain("jane.doe@example.com");
200
+ expect(serialized).not.toContain("555 0134");
201
+ expect(serialized).toContain("[REDACTED:email]");
202
+ });
203
+
204
+ it("folds a full-width @ via NFKC so an email survives a unicode homoglyph domain", async () => {
205
+ const { db, create } = stubDb();
206
+ const fullWidthAt = "@";
207
+ const cyrillicA = "а"; // homoglyph for latin "a" — NOT folded by NFKC
208
+ const summary = `contact jane.doe${fullWidthAt}ex${cyrillicA}mple.com`;
209
+ await recordAgentAction({ ...BASE_INPUT, summary }, db);
210
+ const row = firstWrittenRow(create);
211
+ const serialized = JSON.stringify(row);
212
+ expect(serialized).not.toContain(summary);
213
+ expect(serialized).toContain("[REDACTED:email]");
214
+ });
215
+
216
+ it.each([
217
+ ["tool", { tool: "refund_jane.doe@example.com" }],
218
+ ["targetType", { targetType: "jane@example.com" }],
219
+ ["targetId", { targetId: "jane@example.com" }],
220
+ ["actorId", { actorId: "agent jane@example.com" }],
221
+ ] as [string, Partial<RecordAgentActionInput>][])(
222
+ "refuses a personal-data-shaped %s rather than writing it verbatim",
223
+ async (_name, override) => {
224
+ const { db, create } = stubDb();
225
+ const result = await recordAgentAction(
226
+ { ...BASE_INPUT, ...override },
227
+ db,
228
+ );
229
+ expect(result).toEqual({
230
+ ok: false,
231
+ error: {
232
+ kind: "invalid_input",
233
+ message: expect.any(String),
234
+ persisted: false,
235
+ },
236
+ });
237
+ expect(create).not.toHaveBeenCalled();
238
+ },
239
+ );
240
+
241
+ it.each([
242
+ ["summary", { summary: "a".repeat(2001) }],
243
+ ["failureReason", { failureReason: "a".repeat(2001) }],
244
+ ] as [string, Partial<RecordAgentActionInput>][])(
245
+ "refuses a %s over the 2000-character cap rather than truncating it",
246
+ async (_name, override) => {
247
+ const { db, create } = stubDb();
248
+ const result = await recordAgentAction(
249
+ { ...BASE_INPUT, ...override },
250
+ db,
251
+ );
252
+ expect(result.ok).toBe(false);
253
+ if (!result.ok) expect(result.error.kind).toBe("invalid_input");
254
+ expect(create).not.toHaveBeenCalled();
255
+ },
256
+ );
257
+
258
+ it("refuses an idempotencyKey outside the required identifier grammar (a space)", async () => {
259
+ const { db, create } = stubDb();
260
+ const result = await recordAgentAction(
261
+ { ...BASE_INPUT, idempotencyKey: "req 1" },
262
+ db,
263
+ );
264
+ expect(result.ok).toBe(false);
265
+ expect(create).not.toHaveBeenCalled();
266
+ });
267
+
268
+ it.each([
269
+ ["actorId", { actorId: "4155550134" }],
270
+ ["idempotencyKey", { idempotencyKey: "4155550134" }],
271
+ ] as [string, Partial<RecordAgentActionInput>][])(
272
+ "refuses a charset-valid but personal-data-shaped %s (a bare digit run) rather than silently rewriting an identifier",
273
+ async (_name, override) => {
274
+ const { db, create } = stubDb();
275
+ const result = await recordAgentAction(
276
+ { ...BASE_INPUT, ...override },
277
+ db,
278
+ );
279
+ expect(result.ok).toBe(false);
280
+ expect(create).not.toHaveBeenCalled();
281
+ },
282
+ );
283
+
284
+ it.each([
285
+ ["tool", { tool: "refund" }],
286
+ ["summary", { summary: "notehere" }],
287
+ ] as [string, Partial<RecordAgentActionInput>][])(
288
+ "refuses a %s containing a NUL character — a reliable audit-disable switch if it reached Postgres",
289
+ async (_name, override) => {
290
+ const { db, create } = stubDb();
291
+ const result = await recordAgentAction(
292
+ { ...BASE_INPUT, ...override },
293
+ db,
294
+ );
295
+ expect(result.ok).toBe(false);
296
+ expect(create).not.toHaveBeenCalled();
297
+ },
298
+ );
299
+
300
+ it("never stores a hash or pseudonym of the redacted value", async () => {
301
+ const { db, create } = stubDb();
302
+ await recordAgentAction(
303
+ { ...BASE_INPUT, summary: "contact jane.doe@example.com" },
304
+ db,
305
+ );
306
+ const row = firstWrittenRow(create);
307
+ expect(JSON.stringify(row)).not.toMatch(/[0-9a-f]{32,}/);
308
+ });
309
+
310
+ it("writes exactly the allow-listed metadata keys on the success path", async () => {
311
+ const { db, create } = stubDb();
312
+ await recordAgentAction({ ...BASE_INPUT, summary: "ok" }, db);
313
+ const row = firstWrittenRow(create);
314
+ expect(Object.keys(row.metadata).sort()).toEqual(
315
+ ["idempotencyKey", "outcome", "summary", "tool", "v"].sort(),
316
+ );
317
+ });
318
+
319
+ it("adds failureReason to the allow-listed metadata keys on the failure path", async () => {
320
+ const { db, create } = stubDb();
321
+ await recordAgentAction(
322
+ { ...BASE_INPUT, outcome: "failed", failureReason: "declined" },
323
+ db,
324
+ );
325
+ const row = firstWrittenRow(create);
326
+ expect(Object.keys(row.metadata).sort()).toEqual(
327
+ ["failureReason", "idempotencyKey", "outcome", "tool", "v"].sort(),
328
+ );
329
+ });
330
+
331
+ it("declares no member whose purpose is a buyer's identity", () => {
332
+ void recordAgentAction({
333
+ ...BASE_INPUT,
334
+ // @ts-expect-error — `buyerEmail` is not a declared member of
335
+ // RecordAgentActionInput (D5(a), D11). This proves the member is
336
+ // UNDECLARED, not that no declared member can carry personal data —
337
+ // `summary` can (D5 concedes this; § 9 SEC-12).
338
+ buyerEmail: "buyer@example.com",
339
+ });
340
+ });
341
+
342
+ it("pins the tree's sanitizePII helper NOT redacting an email — a canary on a module this writer does not use", () => {
343
+ expect(sanitizePII({ email: "jane@example.com" }).email).toBe(
344
+ "jane@example.com",
345
+ );
346
+ });
347
+ });
348
+
349
+ // ─── AC-3 — a write failure is surfaced, and the block decision is explicit ─
350
+
351
+ describe("AC-3 — a write failure is surfaced, and the block decision is explicit in the code", () => {
352
+ it("resolves with ok:false rather than throwing on a write failure", async () => {
353
+ const { db } = stubDb(jest.fn().mockRejectedValue(new Error("boom")));
354
+ const result = await recordAgentAction(BASE_INPUT, db);
355
+ expect(result).toEqual({
356
+ ok: false,
357
+ error: {
358
+ kind: "write_failed",
359
+ message: expect.any(String),
360
+ persisted: false,
361
+ },
362
+ });
363
+ });
364
+
365
+ it("never returns or logs the raw error message — Prisma's data argument IS the audit row", async () => {
366
+ const sentinel = "SENTINEL-jane.doe@example.com";
367
+ const { db } = stubDb(jest.fn().mockRejectedValue(new Error(sentinel)));
368
+ const result = await recordAgentAction(BASE_INPUT, db);
369
+ expect(result.ok).toBe(false);
370
+ if (!result.ok) expect(result.error.message).not.toContain(sentinel);
371
+ expect(JSON.stringify(mockLoggerError.mock.calls[0])).not.toContain(
372
+ sentinel,
373
+ );
374
+ });
375
+
376
+ it("logs exactly once at error, with a code but no personal data", async () => {
377
+ const { db } = stubDb(jest.fn().mockRejectedValue({ code: "P2025" }));
378
+ await recordAgentAction(
379
+ { ...BASE_INPUT, summary: "contact jane.doe@example.com" },
380
+ db,
381
+ );
382
+ expect(mockLoggerError).toHaveBeenCalledTimes(1);
383
+ const fields = mockLoggerError.mock.calls[0]![0] as Record<string, unknown>;
384
+ expect(fields.errorCode).toBe("P2025");
385
+ expect(JSON.stringify(fields)).not.toContain("jane.doe@example.com");
386
+ });
387
+
388
+ it("states the no-block decision as source text under a named docblock heading", () => {
389
+ const source = readFileSync(join(__dirname, "../audit-log.ts"), "utf8");
390
+ expect(source).toContain("AUDIT FAILURE DOES NOT BLOCK THE AUDITED ACTION");
391
+ expect(source).toContain("never aborts the caller's action");
392
+ });
393
+ });
394
+
395
+ // ─── AC-4 — a replay produces no duplicate row ─────────────────────────────
396
+
397
+ describe("AC-4 — a replay produces no duplicate row", () => {
398
+ const DIGEST_BASE: AuditRowDigestInput = {
399
+ workspaceId: TENANT.workspaceId,
400
+ actorId: "agent_abc123",
401
+ actorType: "agent",
402
+ action: "agent.commerce.refund",
403
+ targetType: "lead",
404
+ targetId: "lead_xyz",
405
+ outcome: "succeeded",
406
+ summary: "ok",
407
+ failureReason: "n-a",
408
+ idempotencyKey: "req_1",
409
+ };
410
+
411
+ it("is deterministic for identical whole-row input", () => {
412
+ expect(deriveAuditRowId(DIGEST_BASE)).toBe(
413
+ deriveAuditRowId({ ...DIGEST_BASE }),
414
+ );
415
+ });
416
+
417
+ it.each(Object.keys(DIGEST_BASE))(
418
+ "changes the id when %s changes, holding every other field fixed",
419
+ (field) => {
420
+ const before = deriveAuditRowId(DIGEST_BASE);
421
+ // eslint-disable-next-line no-restricted-syntax -- generic field-flip over every AuditRowDigestInput key (incl. the AuditActorType/AgentActionOutcome unions), read purely as a string for the mutation; the digest function itself only ever sees valid AuditRowDigestInput values in production.
422
+ const baseAsStrings = DIGEST_BASE as unknown as Record<string, string>;
423
+ const changed = {
424
+ ...DIGEST_BASE,
425
+ [field]: `${baseAsStrings[field]}-x`,
426
+ } as AuditRowDigestInput;
427
+ expect(deriveAuditRowId(changed)).not.toBe(before);
428
+ },
429
+ );
430
+
431
+ it("resists boundary forgery from the length-prefixed encoding (§9 SEC-10)", () => {
432
+ // Shifting content across the action/idempotencyKey boundary must not
433
+ // collide — a separator-concatenation implementation would produce the
434
+ // same byte string ("a.b" + "k" === "a" + ".b.k"-shaped) for both.
435
+ const a = deriveAuditRowId({
436
+ ...DIGEST_BASE,
437
+ action: "a.b",
438
+ idempotencyKey: "k",
439
+ });
440
+ const b = deriveAuditRowId({
441
+ ...DIGEST_BASE,
442
+ action: "a",
443
+ idempotencyKey: "b.k",
444
+ });
445
+ expect(a).not.toBe(b);
446
+ });
447
+
448
+ it("does not let a byte-identical decoy suppress the real action's record (the suppression attack, §9 SEC-01)", async () => {
449
+ const { db, create } = stubDb();
450
+ const shared = {
451
+ ...BASE_INPUT,
452
+ tool: "refund",
453
+ idempotencyKey: "req_shared",
454
+ };
455
+ const first = await recordAgentAction(
456
+ { ...shared, outcome: "refused", summary: "decoy" },
457
+ db,
458
+ );
459
+ const second = await recordAgentAction(
460
+ { ...shared, outcome: "succeeded", summary: "real refund" },
461
+ db,
462
+ );
463
+ expect(create).toHaveBeenCalledTimes(2);
464
+ expect(first).toEqual({
465
+ ok: true,
466
+ outcome: "recorded",
467
+ id: expect.any(String),
468
+ });
469
+ expect(second).toEqual({
470
+ ok: true,
471
+ outcome: "recorded",
472
+ id: expect.any(String),
473
+ });
474
+ if (first.ok && second.ok) {
475
+ expect(first.id).not.toBe(second.id);
476
+ }
477
+ });
478
+
479
+ it("reports a replay as duplicate — ok:true, and NOT 'recorded'", async () => {
480
+ const create = jest
481
+ .fn()
482
+ .mockResolvedValueOnce({ id: "ignored" })
483
+ .mockRejectedValueOnce({ code: "P2002" });
484
+ const { db } = stubDb(create);
485
+ const first = await recordAgentAction(BASE_INPUT, db);
486
+ const second = await recordAgentAction(BASE_INPUT, db);
487
+ expect(first).toEqual({
488
+ ok: true,
489
+ outcome: "recorded",
490
+ id: expect.any(String),
491
+ });
492
+ expect(second).toEqual({
493
+ ok: true,
494
+ outcome: "duplicate",
495
+ id: expect.any(String),
496
+ });
497
+ expect(mockLoggerWarn).toHaveBeenCalledTimes(1);
498
+ });
499
+
500
+ it("refuses a digit-heavy dashed uuid as an idempotencyKey — the personal-data scan reads it as a phone number, so a caller must re-spell its entropy (#6231)", async () => {
501
+ const { db, create } = stubDb();
502
+ const result = await recordAgentAction(
503
+ { ...BASE_INPUT, idempotencyKey: "01234567-8901-4234-8567-890123456789" },
504
+ db,
505
+ );
506
+ expect(result).toEqual({
507
+ ok: false,
508
+ error: {
509
+ kind: "invalid_input",
510
+ message: expect.stringContaining("personal data"),
511
+ persisted: false,
512
+ },
513
+ });
514
+ // A refusal writes NO row — an unaudited action, the failure mode the
515
+ // magnet routes' `_`-grouped key exists to avoid.
516
+ expect(create).not.toHaveBeenCalled();
517
+ });
518
+
519
+ it("logs the duplicate outcome at warn, naming the colliding row — a collision is never silent regardless of caller (#6231)", async () => {
520
+ const { db } = stubDb(jest.fn().mockRejectedValue({ code: "P2002" }));
521
+ const result = await recordAgentAction(BASE_INPUT, db);
522
+ expect(result).toEqual({
523
+ ok: true,
524
+ outcome: "duplicate",
525
+ id: expect.any(String),
526
+ });
527
+ const collidingId = result.ok ? result.id : undefined;
528
+ expect(mockLoggerError).not.toHaveBeenCalled();
529
+ expect(mockLoggerWarn).toHaveBeenCalledTimes(1);
530
+ const [payload, message] = mockLoggerWarn.mock.calls[0] as [
531
+ Record<string, unknown>,
532
+ string,
533
+ ];
534
+ expect(payload).toMatchObject({
535
+ workspaceId: WORKSPACE_ID,
536
+ auditLogId: collidingId,
537
+ });
538
+ expect(message).toMatch(/duplicate/i);
539
+ });
540
+
541
+ it("never reads before writing — no find*/update/delete on the delegate (a narrow claim; §6.2's manual psql insert is the real evidence)", () => {
542
+ const source = readFileSync(join(__dirname, "../audit-log.ts"), "utf8");
543
+ expect(source).not.toMatch(/auditLog\.(find|update|delete|count)/);
544
+ });
545
+
546
+ it("classifies a non-P2002 rejection as write_failed, never as duplicate", async () => {
547
+ const { db } = stubDb(jest.fn().mockRejectedValue({ code: "P2025" }));
548
+ const result = await recordAgentAction(BASE_INPUT, db);
549
+ expect(result).toEqual({
550
+ ok: false,
551
+ error: {
552
+ kind: "write_failed",
553
+ message: expect.any(String),
554
+ persisted: false,
555
+ },
556
+ });
557
+ });
558
+ });
559
+
560
+ // ─── Supplementary — targetType/targetId pass-through (§3 D3, D5(a2)) ──────
561
+
562
+ describe("targetType/targetId pass-through", () => {
563
+ it("validates targetId against its named entity's own id grammar when targetType names a registered entity", async () => {
564
+ const { db, create } = stubDb();
565
+ const result = await recordAgentAction(
566
+ { ...BASE_INPUT, targetType: "workspace", targetId: TENANT.workspaceId },
567
+ db,
568
+ );
569
+ expect(result.ok).toBe(true);
570
+ const row = firstWrittenRow(create);
571
+ expect(row.targetType).toBe("workspace");
572
+ expect(row.targetId).toBe(TENANT.workspaceId);
573
+ });
574
+
575
+ it("refuses a targetId that does not match its named entity's id grammar", async () => {
576
+ const { db, create } = stubDb();
577
+ const result = await recordAgentAction(
578
+ {
579
+ ...BASE_INPUT,
580
+ targetType: "workspace",
581
+ targetId: "not-a-workspace-id",
582
+ },
583
+ db,
584
+ );
585
+ expect(result.ok).toBe(false);
586
+ expect(create).not.toHaveBeenCalled();
587
+ });
588
+
589
+ it("refuses a malformed tenant.workspaceId", async () => {
590
+ const { db, create } = stubDb();
591
+ const result = await recordAgentAction(
592
+ {
593
+ ...BASE_INPUT,
594
+ tenant: {
595
+ ...TENANT,
596
+ workspaceId: "not-a-workspace-id" as Id<"workspace">,
597
+ },
598
+ },
599
+ db,
600
+ );
601
+ expect(result.ok).toBe(false);
602
+ expect(create).not.toHaveBeenCalled();
603
+ });
604
+ });
605
+
606
+ // ─── redactPersonalData — the exported pure helper, directly ───────────────
607
+
608
+ describe("redactPersonalData (exported pure helper)", () => {
609
+ it("returns the input unchanged when it carries no personal-data-shaped substring", () => {
610
+ expect(redactPersonalData("nothing to see here")).toBe(
611
+ "nothing to see here",
612
+ );
613
+ });
614
+
615
+ it("redacts a long digit run (account/card-shaped) not caught by the phone pattern", () => {
616
+ expect(redactPersonalData("card 411111111111111")).toContain(
617
+ "[REDACTED:number]",
618
+ );
619
+ });
620
+ });
@@ -212,6 +212,8 @@ describe("recordLegacyConsent (#5275 D11)", () => {
212
212
  expect(rows).toHaveLength(1);
213
213
  expect(rows[0]).toEqual({
214
214
  siteId: SITE_ID,
215
+ // #6374 — the fence's isolation key, equal to `siteId` by construction.
216
+ workspaceId: SITE_ID,
215
217
  ...SUBJECT,
216
218
  purposeId: DEFAULT_CONSENT_PURPOSE_ID,
217
219
  granted: true,