create-ailk 0.1.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (284) hide show
  1. package/component-catalog.md +210 -52
  2. package/dist/cli.js +0 -0
  3. package/dist/lib/apply-module-patches.d.ts +47 -0
  4. package/dist/lib/apply-module-patches.js +370 -0
  5. package/dist/lib/extract-module-bundle.d.ts +12 -3
  6. package/dist/lib/extract-module-bundle.js +236 -24
  7. package/dist/lib/fetch-module.d.ts +3 -38
  8. package/dist/lib/fetch-module.js +26 -8
  9. package/dist/lib/module-license-gate.d.ts +2 -0
  10. package/dist/lib/module-license-gate.js +1 -0
  11. package/dist/lib/paid-paths.d.ts +16 -0
  12. package/dist/lib/paid-paths.js +90 -0
  13. package/dist/module-architecture.d.ts +139 -23
  14. package/dist/module-architecture.js +668 -25
  15. package/dist/parse-args.d.ts +2 -2
  16. package/dist/parse-args.js +3 -1
  17. package/dist/programmatic.d.ts +2 -1
  18. package/dist/programmatic.js +15 -4
  19. package/dist/surfaces.d.ts +12 -36
  20. package/dist/surfaces.js +35 -5
  21. package/dist/sync-routes.js +31 -1
  22. package/package.json +14 -15
  23. package/templates/.claude/agents/web.md +2 -3
  24. package/templates/.claude/rules/architecture.md +5 -5
  25. package/templates/.claude/skills/README.md +2 -1
  26. package/templates/.env.example +21 -9
  27. package/templates/CONVENTIONS.md +6 -7
  28. package/templates/apps/api/.env.example +9 -0
  29. package/templates/apps/api/CLAUDE.md +35 -4
  30. package/templates/apps/api/package.json +0 -1
  31. package/templates/apps/api/src/__tests__/cors.test.ts +195 -0
  32. package/templates/apps/api/src/__tests__/module-exclusion.test.ts +60 -2
  33. package/templates/apps/api/src/__tests__/vercel-handler.test.ts +159 -0
  34. package/templates/apps/api/src/config/__tests__/modules.test.ts +76 -0
  35. package/templates/apps/api/src/config/index.ts +19 -0
  36. package/templates/apps/api/src/config/modules.ts +12 -14
  37. package/templates/apps/api/src/lib/__mocks__/prisma.ts +13 -0
  38. package/templates/apps/api/src/lib/__tests__/slice-load.test.ts +89 -0
  39. package/templates/apps/api/src/lib/slice-load.ts +90 -0
  40. package/templates/apps/api/src/openapi/__tests__/openapi.test.ts +52 -32
  41. package/templates/apps/api/src/openapi/__tests__/spec-identity.test.ts +182 -0
  42. package/templates/apps/api/src/openapi/__tests__/surface-drift.test.ts +293 -0
  43. package/templates/apps/api/src/openapi/index.ts +9 -3
  44. package/templates/apps/api/src/openapi/spec.ts +505 -65
  45. package/templates/apps/api/src/openapi/surface-drift.ts +195 -0
  46. package/templates/apps/api/src/routes/content/__tests__/create.test.ts +14 -0
  47. package/templates/apps/api/src/routes/content/__tests__/delete.test.ts +14 -0
  48. package/templates/apps/api/src/routes/content/__tests__/update.test.ts +14 -0
  49. package/templates/apps/api/src/routes/content/index.ts +38 -11
  50. package/templates/apps/api/src/routes/project-listings/__tests__/configured-application.test.ts +28 -0
  51. package/templates/apps/api/src/routes/project-listings/__tests__/drafts.test.ts +144 -0
  52. package/templates/apps/api/src/routes/project-listings/__tests__/founder-identity.test.ts +796 -0
  53. package/templates/apps/api/src/routes/project-listings/__tests__/me.test.ts +478 -0
  54. package/templates/apps/api/src/routes/project-listings/__tests__/public.test.ts +38 -0
  55. package/templates/apps/api/src/routes/project-listings/__tests__/resume-email.test.ts +814 -0
  56. package/templates/apps/api/src/routes/project-listings/__tests__/site-answers.test.ts +717 -0
  57. package/templates/apps/api/src/routes/project-listings/__tests__/site-key.test.ts +35 -0
  58. package/templates/apps/api/src/routes/project-listings/__tests__/structured-address.test.ts +484 -0
  59. package/templates/apps/api/src/routes/project-listings/index.ts +52 -10
  60. package/templates/apps/api/src/routes/project-listings/me.ts +86 -0
  61. package/templates/apps/api/src/routes/project-listings/patch-draft.ts +5 -0
  62. package/templates/apps/api/src/routes/project-listings/public.ts +5 -0
  63. package/templates/apps/api/src/routes/project-listings/respond.ts +11 -0
  64. package/templates/apps/api/src/routes/project-listings/resume-token.ts +5 -0
  65. package/templates/apps/api/src/routes/project-listings/start.ts +38 -0
  66. package/templates/apps/api/src/routes/project-listings/submit.ts +5 -0
  67. package/templates/apps/api/src/routes/project-listings/verify-email.ts +150 -0
  68. package/templates/apps/api/src/server.ts +471 -133
  69. package/templates/apps/api/src/services/__tests__/consent-migration.test.ts +65 -0
  70. package/templates/apps/api/src/services/__tests__/consent.test.ts +282 -0
  71. package/templates/apps/api/src/services/consent.ts +236 -0
  72. package/templates/apps/api/src/services/deliverable-fulfillment.ts +10 -0
  73. package/templates/apps/api/src/services/listing-config.ts +58 -0
  74. package/templates/apps/api/src/services/project-listing-resume-email.ts +326 -0
  75. package/templates/apps/api/src/services/project-listings.ts +602 -29
  76. package/templates/apps/api/src/vercel-handler.ts +60 -26
  77. package/templates/apps/mcp/.env.example +8 -0
  78. package/templates/apps/mcp/CLAUDE.md +2 -2
  79. package/templates/apps/mcp/__tests__/catalog-drift.test.ts +21 -0
  80. package/templates/apps/mcp/__tests__/config/modules.test.ts +78 -0
  81. package/templates/apps/mcp/__tests__/module-exclusion.test.ts +1 -1
  82. package/templates/apps/mcp/src/config/modules.ts +14 -13
  83. package/templates/apps/mcp/src/server.ts +8 -4
  84. package/templates/apps/mcp/src/tools/index.ts +7 -22
  85. package/templates/apps/web/.env.example +15 -0
  86. package/templates/apps/web/app/[locale]/(authed)/{waitlist/__tests__ → __tests__}/gate.test.tsx +4 -4
  87. package/templates/apps/web/app/[locale]/flows/[slug]/FlowStepperClient.tsx +2 -1
  88. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/FlowStepperClient.permalink.test.tsx +2 -1
  89. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/FlowStepperClient.test.tsx +2 -1
  90. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/flow.actions.test.ts +1 -0
  91. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/two-route-tool.test.tsx +1 -0
  92. package/templates/apps/web/app/[locale]/flows/[slug]/flow.actions.ts +2 -1
  93. package/templates/apps/web/app/[locale]/flows/[slug]/page.tsx +1 -0
  94. package/templates/apps/web/app/[locale]/flows/[slug]/start/page.tsx +1 -0
  95. package/templates/apps/web/app/[locale]/layout.tsx +13 -1
  96. package/templates/apps/web/app/llms.txt/route.ts +12 -9
  97. package/templates/apps/web/jest.config.cjs +20 -13
  98. package/templates/apps/web/lib/__tests__/site-theme.test.ts +112 -0
  99. package/templates/apps/web/lib/site-brand.tsx +4 -1
  100. package/templates/apps/web/lib/site-theme.ts +74 -0
  101. package/templates/apps/web/next.config.mjs +1 -3
  102. package/templates/apps/web/package.json +1 -6
  103. package/templates/apps/web/public/android-chrome-192x192.png +0 -0
  104. package/templates/apps/web/public/android-chrome-512x512.png +0 -0
  105. package/templates/apps/web/public/apple-touch-icon.png +0 -0
  106. package/templates/apps/web/public/favicon-16x16.png +0 -0
  107. package/templates/apps/web/public/favicon-32x32.png +0 -0
  108. package/templates/apps/web/public/favicon.ico +0 -0
  109. package/templates/apps/web/public/favicon.svg +6 -3
  110. package/templates/apps/web/public/lockup-horizontal.svg +4 -0
  111. package/templates/apps/web/public/logomark.svg +4 -0
  112. package/templates/apps/web/public/site.webmanifest +2 -2
  113. package/templates/apps/web/public/wordmark.svg +4 -0
  114. package/templates/content/_site.mdx +12 -0
  115. package/templates/database/CHANGELOG.md +94 -0
  116. package/templates/database/inbox/schema.prisma +165 -0
  117. package/templates/database/migrations/20260911140000_listing_structured_address/migration.sql +32 -0
  118. package/templates/database/migrations/20260911180000_consent_grants/migration.sql +71 -0
  119. package/templates/database/migrations/20260911200000_listing_site_answers/migration.sql +30 -0
  120. package/templates/database/migrations/20260912120000_listing_owner_link/migration.sql +49 -0
  121. package/templates/database/migrations/20260914120000_listing_founder_identity/migration.sql +123 -0
  122. package/templates/database/package.json +1 -1
  123. package/templates/database/scripts/db-generate-locked.sh +0 -0
  124. package/templates/package.json +1 -1
  125. package/templates/.claude/skills/scaffold-commerce/SKILL.md +0 -807
  126. package/templates/.claude/skills/scaffold-commerce/references/lookup-keys-template.md +0 -71
  127. package/templates/.claude/skills/scaffold-commerce/references/marketplace-brand-pages.md +0 -83
  128. package/templates/.claude/skills/scaffold-commerce/templates/checkout-route.template.ts +0 -370
  129. package/templates/.claude/skills/scaffold-commerce/templates/invoice-route.template.ts +0 -376
  130. package/templates/.claude/skills/scaffold-commerce/templates/marketplace-cta-route.tsx.tmpl +0 -72
  131. package/templates/.claude/skills/scaffold-commerce/templates/payment-link-route.template.ts +0 -471
  132. package/templates/.claude/skills/scaffold-commerce/templates/portal-route.template.ts +0 -365
  133. package/templates/.claude/skills/scaffold-commerce/templates/stripe-config.template.ts +0 -60
  134. package/templates/.claude/skills/scaffold-commerce/templates/subscription-route.template.ts +0 -446
  135. package/templates/apps/api/src/__tests__/server.test.ts +0 -253
  136. package/templates/apps/api/src/bin/deliverable-resend.ts +0 -144
  137. package/templates/apps/api/src/bin/deliverable-upload.ts +0 -114
  138. package/templates/apps/api/src/bin/followup-sweep.ts +0 -44
  139. package/templates/apps/api/src/bin/listing-csv-sweep.ts +0 -46
  140. package/templates/apps/api/src/bin/seed-presets.ts +0 -58
  141. package/templates/apps/api/src/bin/seed-waitlist-experiments.ts +0 -104
  142. package/templates/apps/api/src/bin/session-retention-sweep.ts +0 -46
  143. package/templates/apps/api/src/lib/__tests__/stripe.test.ts +0 -74
  144. package/templates/apps/api/src/lib/stripe.ts +0 -52
  145. package/templates/apps/api/src/lib/tenant-db.ts +0 -225
  146. package/templates/apps/api/src/lib/ws-token.ts +0 -91
  147. package/templates/apps/api/src/middleware/tenant.ts +0 -99
  148. package/templates/apps/api/src/routes/billing/__tests__/portal.test.ts +0 -450
  149. package/templates/apps/api/src/routes/billing/__tests__/read.test.ts +0 -262
  150. package/templates/apps/api/src/routes/billing/__tests__/usage.test.ts +0 -436
  151. package/templates/apps/api/src/routes/billing/index.ts +0 -36
  152. package/templates/apps/api/src/routes/billing/portal.ts +0 -182
  153. package/templates/apps/api/src/routes/billing/read.ts +0 -75
  154. package/templates/apps/api/src/routes/billing/usage.ts +0 -153
  155. package/templates/apps/api/src/routes/checkout/__tests__/sessions.test.ts +0 -687
  156. package/templates/apps/api/src/routes/checkout/index.ts +0 -13
  157. package/templates/apps/api/src/routes/checkout/sessions.ts +0 -197
  158. package/templates/apps/api/src/routes/deliverables/__tests__/index.test.ts +0 -393
  159. package/templates/apps/api/src/routes/deliverables/index.ts +0 -200
  160. package/templates/apps/api/src/routes/flow-checkouts/__tests__/index.test.ts +0 -443
  161. package/templates/apps/api/src/routes/flow-checkouts/index.ts +0 -82
  162. package/templates/apps/api/src/routes/flows/README.md +0 -147
  163. package/templates/apps/api/src/routes/flows/__tests__/index.test.ts +0 -752
  164. package/templates/apps/api/src/routes/flows/__tests__/recommender.test.ts +0 -671
  165. package/templates/apps/api/src/routes/flows/index.ts +0 -202
  166. package/templates/apps/api/src/routes/flows/recommender.ts +0 -443
  167. package/templates/apps/api/src/routes/project-listings/__tests__/copy-edit.test.ts +0 -815
  168. package/templates/apps/api/src/routes/project-listings/__tests__/tenant-isolation.test.ts +0 -566
  169. package/templates/apps/api/src/routes/project-listings/get.ts +0 -70
  170. package/templates/apps/api/src/routes/project-listings/list.ts +0 -47
  171. package/templates/apps/api/src/routes/project-listings/patch.ts +0 -136
  172. package/templates/apps/api/src/routes/schedule/__tests__/index.test.ts +0 -490
  173. package/templates/apps/api/src/routes/schedule/index.ts +0 -249
  174. package/templates/apps/api/src/routes/slack/__tests__/actions.test.ts +0 -385
  175. package/templates/apps/api/src/routes/slack/actions.ts +0 -177
  176. package/templates/apps/api/src/routes/slack/index.ts +0 -38
  177. package/templates/apps/api/src/routes/waitlist-experiments/__tests__/tenant-isolation.test.ts +0 -577
  178. package/templates/apps/api/src/routes/waitlist-experiments/comparison.ts +0 -78
  179. package/templates/apps/api/src/routes/waitlist-experiments/index.ts +0 -41
  180. package/templates/apps/api/src/routes/waitlist-experiments/list.ts +0 -64
  181. package/templates/apps/api/src/routes/waitlist-experiments/respond.ts +0 -42
  182. package/templates/apps/api/src/routes/waitlist-experiments/signup.ts +0 -84
  183. package/templates/apps/api/src/routes/waitlist-experiments/signups.ts +0 -119
  184. package/templates/apps/api/src/routes/waitlist-signups/__tests__/index.test.ts +0 -238
  185. package/templates/apps/api/src/routes/waitlist-signups/index.ts +0 -101
  186. package/templates/apps/api/src/routes/webhooks/README.md +0 -80
  187. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-flow-checkout.test.ts +0 -315
  188. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-idempotency.test.ts +0 -247
  189. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-org-billing.test.ts +0 -270
  190. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-rate-limit.test.ts +0 -198
  191. package/templates/apps/api/src/routes/webhooks/__tests__/stripe.test.ts +0 -633
  192. package/templates/apps/api/src/routes/webhooks/index.ts +0 -41
  193. package/templates/apps/api/src/routes/webhooks/stripe.ts +0 -481
  194. package/templates/apps/api/src/routes/workspaces/__tests__/config-tenant-isolation.test.ts +0 -356
  195. package/templates/apps/api/src/routes/workspaces/__tests__/tenant-isolation.test.ts +0 -671
  196. package/templates/apps/api/src/routes/workspaces/config.ts +0 -125
  197. package/templates/apps/api/src/routes/workspaces/index.ts +0 -194
  198. package/templates/apps/api/src/routes/workspaces/sessions.ts +0 -218
  199. package/templates/apps/api/src/services/__tests__/flow-aggregate.test.ts +0 -425
  200. package/templates/apps/api/src/services/__tests__/flow-engine.test.ts +0 -2840
  201. package/templates/apps/api/src/services/__tests__/lead-promotion.test.ts +0 -393
  202. package/templates/apps/api/src/services/__tests__/listing-csv-sweep.test.ts +0 -560
  203. package/templates/apps/api/src/services/__tests__/playbook-compile.test.ts +0 -406
  204. package/templates/apps/api/src/services/__tests__/playbook-render.test.ts +0 -290
  205. package/templates/apps/api/src/services/__tests__/project-listing-decision.test.ts +0 -736
  206. package/templates/apps/api/src/services/__tests__/project-listing-flow.test.ts +0 -475
  207. package/templates/apps/api/src/services/__tests__/project-listing-issue.test.ts +0 -340
  208. package/templates/apps/api/src/services/__tests__/recommender-capture.test.ts +0 -983
  209. package/templates/apps/api/src/services/__tests__/tenant-context-cascade.test.ts +0 -71
  210. package/templates/apps/api/src/services/__tests__/tenant-context.test.ts +0 -379
  211. package/templates/apps/api/src/services/__tests__/usage-metering.test.ts +0 -768
  212. package/templates/apps/api/src/services/__tests__/waitlist-dashboard.test.ts +0 -1314
  213. package/templates/apps/api/src/services/__tests__/waitlist-experiments.test.ts +0 -341
  214. package/templates/apps/api/src/services/__tests__/waitlist-followup.test.ts +0 -567
  215. package/templates/apps/api/src/services/__tests__/waitlist-scoring.test.ts +0 -474
  216. package/templates/apps/api/src/services/__tests__/waitlist-signups.test.ts +0 -354
  217. package/templates/apps/api/src/services/flow-aggregate.ts +0 -232
  218. package/templates/apps/api/src/services/flow-checkouts.ts +0 -123
  219. package/templates/apps/api/src/services/flow-engine.ts +0 -1278
  220. package/templates/apps/api/src/services/lead-promotion.ts +0 -176
  221. package/templates/apps/api/src/services/listing-csv-sweep.ts +0 -455
  222. package/templates/apps/api/src/services/playbook-compile.ts +0 -398
  223. package/templates/apps/api/src/services/playbook-render.ts +0 -263
  224. package/templates/apps/api/src/services/project-listing-decision.ts +0 -490
  225. package/templates/apps/api/src/services/project-listing-flow.ts +0 -426
  226. package/templates/apps/api/src/services/project-listing-issue.ts +0 -251
  227. package/templates/apps/api/src/services/recommender-capture.ts +0 -835
  228. package/templates/apps/api/src/services/scheduling/cal-provider.ts +0 -392
  229. package/templates/apps/api/src/services/scheduling/index.ts +0 -63
  230. package/templates/apps/api/src/services/scheduling/types.ts +0 -88
  231. package/templates/apps/api/src/services/tenant-context.ts +0 -451
  232. package/templates/apps/api/src/services/usage-metering.ts +0 -699
  233. package/templates/apps/api/src/services/waitlist-dashboard.ts +0 -947
  234. package/templates/apps/api/src/services/waitlist-experiments.ts +0 -213
  235. package/templates/apps/api/src/services/waitlist-followup.ts +0 -486
  236. package/templates/apps/api/src/services/waitlist-scoring.ts +0 -166
  237. package/templates/apps/api/src/services/waitlist-signups.ts +0 -165
  238. package/templates/apps/mcp/__tests__/schedule_tools.test.ts +0 -242
  239. package/templates/apps/mcp/src/tools/create_booking.ts +0 -58
  240. package/templates/apps/mcp/src/tools/get_event_meta.ts +0 -55
  241. package/templates/apps/mcp/src/tools/get_flow.ts +0 -61
  242. package/templates/apps/mcp/src/tools/list_availability.ts +0 -67
  243. package/templates/apps/mcp/src/tools/submit_flow_step.ts +0 -83
  244. package/templates/apps/web/app/[locale]/(authed)/waitlist/[experimentId]/page.tsx +0 -309
  245. package/templates/apps/web/app/[locale]/(authed)/waitlist/[experimentId]/signups/[leadId]/page.tsx +0 -149
  246. package/templates/apps/web/app/[locale]/(authed)/waitlist/__tests__/comparison.test.tsx +0 -273
  247. package/templates/apps/web/app/[locale]/(authed)/waitlist/__tests__/list.test.tsx +0 -171
  248. package/templates/apps/web/app/[locale]/(authed)/waitlist/__tests__/signup.test.tsx +0 -179
  249. package/templates/apps/web/app/[locale]/(authed)/waitlist/components/ExperimentsTable.tsx +0 -116
  250. package/templates/apps/web/app/[locale]/(authed)/waitlist/components/OfferFunnelTable.tsx +0 -66
  251. package/templates/apps/web/app/[locale]/(authed)/waitlist/components/RollupTicker.tsx +0 -61
  252. package/templates/apps/web/app/[locale]/(authed)/waitlist/components/ScoreTrace.tsx +0 -114
  253. package/templates/apps/web/app/[locale]/(authed)/waitlist/components/SignupsTable.tsx +0 -139
  254. package/templates/apps/web/app/[locale]/(authed)/waitlist/components/WaitlistComparisonTabs.tsx +0 -85
  255. package/templates/apps/web/app/[locale]/(authed)/waitlist/components/status-badges.tsx +0 -67
  256. package/templates/apps/web/app/[locale]/(authed)/waitlist/page.tsx +0 -179
  257. package/templates/apps/web/app/[locale]/blog/[[...slug]]/page.tsx +0 -178
  258. package/templates/apps/web/app/[locale]/dev/purchase/__tests__/actions.test.ts +0 -160
  259. package/templates/apps/web/app/[locale]/dev/purchase/error.tsx +0 -25
  260. package/templates/apps/web/app/[locale]/dev/purchase/page.tsx +0 -117
  261. package/templates/apps/web/app/[locale]/dev/purchase/purchase.actions.ts +0 -58
  262. package/templates/apps/web/app/[locale]/docs/[[...slug]]/page.tsx +0 -119
  263. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/checkout.actions.test.ts +0 -287
  264. package/templates/apps/web/app/[locale]/flows/[slug]/checkout.actions.ts +0 -254
  265. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/ResultsClient.tsx +0 -532
  266. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/ResultsEmailStep.tsx +0 -121
  267. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/__tests__/ResultsClient.checkout.test.tsx +0 -457
  268. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/__tests__/page.test.tsx +0 -396
  269. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/page.tsx +0 -114
  270. package/templates/apps/web/app/[locale]/projects/apply/ListingApplicationClient.tsx +0 -110
  271. package/templates/apps/web/app/[locale]/projects/apply/__tests__/ListingApplicationClient.test.tsx +0 -96
  272. package/templates/apps/web/app/[locale]/schedule/__tests__/page.test.tsx +0 -117
  273. package/templates/apps/web/app/[locale]/schedule/confirmed/__tests__/page.test.tsx +0 -96
  274. package/templates/apps/web/app/[locale]/schedule/confirmed/page.tsx +0 -92
  275. package/templates/apps/web/app/[locale]/schedule/page.tsx +0 -82
  276. package/templates/apps/web/content/en/blog/README.txt +0 -25
  277. package/templates/apps/web/content/en/docs/index.mdx +0 -28
  278. package/templates/apps/web/lib/__mocks__/source-server.js +0 -31
  279. package/templates/apps/web/lib/blog-list-data.ts +0 -95
  280. package/templates/apps/web/lib/blog-post-data.ts +0 -79
  281. package/templates/apps/web/lib/source.ts +0 -34
  282. package/templates/apps/web/public/logomark-dark.svg +0 -4
  283. package/templates/apps/web/public/logomark-light.svg +0 -4
  284. package/templates/apps/web/source.config.ts +0 -78
@@ -1,406 +0,0 @@
1
- // oss: false
2
- /**
3
- * @file playbook-compile.test.ts
4
- * @description Golden tests for FEAT-074 U4a's compile (#4715).
5
- *
6
- * Every golden's `source` is run through the VENDORED
7
- * `check-playbook.py --self-test`-verified checker (`vendor/playbook-method/`)
8
- * against the REAL vendored play library — AC-1/AC-6. `check-playbook.py`
9
- * takes `--playbook PATH` (a markdown FILE carrying the
10
- * `<!-- playbook-source: {...} -->` block), not a bare object, so each
11
- * assertion writes `result.markdown` (which already contains that exact
12
- * block — `compilePlaybook` renders it) to a temp file and runs the checker
13
- * against it.
14
- *
15
- * `compileAndStorePlaybook`'s own suite mocks `@working-theory/database`
16
- * (via `__mocks__/prisma.ts`, mirroring waitlist-scoring.test.ts) and
17
- * `@working-theory/observability`'s logger, so its Prisma write shape,
18
- * append-only behavior, and fail-soft catch are directly assertable without
19
- * a live database.
20
- */
21
- // eslint-disable-next-line no-restricted-syntax -- prisma is a DB boundary; __mocks__/prisma.ts activates the auto-mock (Jest requires explicit call for local files)
22
- jest.mock("../../lib/prisma.js");
23
-
24
- const mockLoggerError = jest.fn();
25
- jest.mock("@working-theory/observability", () => ({
26
- logger: {
27
- info: jest.fn(),
28
- warn: jest.fn(),
29
- error: (...args: unknown[]) => mockLoggerError(...args),
30
- debug: jest.fn(),
31
- },
32
- }));
33
-
34
- import { createHash } from "node:crypto";
35
- import { execFileSync } from "node:child_process";
36
- import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
37
- import { tmpdir } from "node:os";
38
- import { dirname, join } from "node:path";
39
-
40
- import { prisma } from "../../lib/prisma.js";
41
- import {
42
- compileAndStorePlaybook,
43
- compilePlaybook,
44
- loadVendoredPlayLibrary,
45
- PlaybookCompileError,
46
- resolveVendoredLibraryPath,
47
- type PlayLibrary,
48
- } from "../playbook-compile.js";
49
-
50
- // Never `import.meta.url` here (see playbook-compile.ts's header — ts-jest
51
- // compiles this file to CommonJS, which cannot execute `import.meta`).
52
- // `resolveVendoredLibraryPath` already does the cwd-relative probing this
53
- // test needs; the vendor directory is that resolved file's own dirname.
54
- const VENDOR_DIR = dirname(resolveVendoredLibraryPath());
55
- const CHECKER_PATH = join(VENDOR_DIR, "check-playbook.py");
56
- const SCHEMA_PATH = join(VENDOR_DIR, "playbook-source.schema.json");
57
- const PLAYS_PATH = join(VENDOR_DIR, "targeting-maturity.plays.json");
58
-
59
- const LIBRARY: PlayLibrary = loadVendoredPlayLibrary();
60
-
61
- /** Runs the vendored checker against one golden's rendered markdown. Throws
62
- * (failing the test) on a non-zero exit — `execFileSync` throws on exit != 0. */
63
- function runCheckerOnMarkdown(markdown: string): void {
64
- const dir = mkdtempSync(join(tmpdir(), "playbook-checker-"));
65
- const playbookPath = join(dir, "PLAYBOOK-golden.md");
66
- try {
67
- writeFileSync(playbookPath, markdown, "utf8");
68
- execFileSync(
69
- "python3",
70
- [CHECKER_PATH, "--playbook", playbookPath, "--plays", PLAYS_PATH, "--schema", SCHEMA_PATH],
71
- { stdio: "pipe" },
72
- );
73
- } finally {
74
- rmSync(dir, { recursive: true, force: true });
75
- }
76
- }
77
-
78
- /** A `predicate`-kind ruleTrace entry, the shape `evaluateWaitlistScoring`
79
- * produces (`RuleTraceEntry`, `@working-theory/validation`) — hand-built
80
- * here (not run through the real evaluator) since only the `tier`/`path`/
81
- * `result` fields matter to `compilePlaybook`'s loop-back detection. */
82
- function predicateEntry(tier: string, refName: string, result: boolean) {
83
- return {
84
- kind: "predicate" as const,
85
- tier,
86
- path: `allOf[0].ref(level1_only).allOf[0].ref(level1_signal).anyOf[0].ref(${refName}).eq`,
87
- node: {},
88
- result,
89
- detail: `${refName} = ${result}`,
90
- };
91
- }
92
-
93
- describe("compilePlaybook (D1) — goldens", () => {
94
- it("Level 0 (the Gate) compiles, unlocks_next = Level 1's ids, passes the vendored checker (AC-1, AC-6)", () => {
95
- const { source, markdown } = compilePlaybook({
96
- score: { id: "wlscore_gate", tier: "level_0", ruleTrace: [] },
97
- plays: LIBRARY,
98
- leadId: "lead_gate",
99
- });
100
-
101
- expect(source).toMatchObject({
102
- artifact_type: "playbook",
103
- scope: "person",
104
- scope_ref: "lead_gate",
105
- method: "targeting-maturity",
106
- level: 0,
107
- compiled_from: "wlscore_gate",
108
- });
109
- expect(source.plays).toEqual(["tm-0.1", "tm-0.2"]);
110
- expect(source.unlocks_next).toEqual(["tm-1.1", "tm-1.2", "tm-1.3", "tm-1.4", "tm-1.5", "tm-1.6"]);
111
- expect(markdown).toContain('"level":0');
112
-
113
- runCheckerOnMarkdown(markdown);
114
- });
115
-
116
- it("Level 1 via paying customers compiles, unlocks_next = Level 2's ids, no loop-back framing, passes the checker (AC-1)", () => {
117
- const { source, markdown } = compilePlaybook({
118
- score: {
119
- id: "wlscore_l1_customers",
120
- tier: "level_1",
121
- ruleTrace: [predicateEntry("level_1", "has_customers", true)],
122
- },
123
- plays: LIBRARY,
124
- leadId: "lead_l1_customers",
125
- });
126
-
127
- expect(source.level).toBe(1);
128
- expect(source.plays).toEqual(["tm-1.1", "tm-1.2", "tm-1.3", "tm-1.4", "tm-1.5", "tm-1.6"]);
129
- expect(source.unlocks_next).toEqual(["tm-2.1", "tm-2.2", "tm-2.3"]);
130
- expect(markdown).not.toContain("loop-back");
131
-
132
- runCheckerOnMarkdown(markdown);
133
- });
134
-
135
- it("Level 1 via a confirmed-Fit cohort renders the Level-6 loop-back framing, source otherwise identical (AC-1)", () => {
136
- const { source, markdown } = compilePlaybook({
137
- score: {
138
- id: "wlscore_l1_cohort",
139
- tier: "level_1",
140
- ruleTrace: [predicateEntry("level_1", "has_confirmed_fit_cohort", true)],
141
- },
142
- plays: LIBRARY,
143
- leadId: "lead_l1_cohort",
144
- });
145
-
146
- expect(source.level).toBe(1);
147
- expect(source.plays).toEqual(["tm-1.1", "tm-1.2", "tm-1.3", "tm-1.4", "tm-1.5", "tm-1.6"]);
148
- expect(source.unlocks_next).toEqual(["tm-2.1", "tm-2.2", "tm-2.3"]);
149
- expect(markdown).toContain("loop-back");
150
-
151
- runCheckerOnMarkdown(markdown);
152
- });
153
-
154
- it("Level 5 compiles, unlocks_next = Level 7's ids (never 6, which the method has no such Level for) (AC-1)", () => {
155
- const { source, markdown } = compilePlaybook({
156
- score: { id: "wlscore_l5", tier: "level_5", ruleTrace: [] },
157
- plays: LIBRARY,
158
- leadId: "lead_l5",
159
- });
160
-
161
- expect(source.level).toBe(5);
162
- expect(source.plays).toEqual(["tm-5.1", "tm-5.2", "tm-5.3", "tm-5.4", "tm-5.5", "tm-5.6"]);
163
- expect(source.unlocks_next).toEqual([
164
- "tm-7.1",
165
- "tm-7.2",
166
- "tm-7.3",
167
- "tm-7.4",
168
- "tm-7.5",
169
- "tm-7.6",
170
- ]);
171
-
172
- runCheckerOnMarkdown(markdown);
173
- });
174
-
175
- it("Level 8 compiles, unlocks_next = Level 7's ids — library-declared, never level + 1 = 9 (AC-1)", () => {
176
- const { source, markdown } = compilePlaybook({
177
- score: { id: "wlscore_l8", tier: "level_8", ruleTrace: [] },
178
- plays: LIBRARY,
179
- leadId: "lead_l8",
180
- });
181
-
182
- expect(source.level).toBe(8);
183
- expect(source.plays).toEqual(["tm-8.1", "tm-8.2", "tm-8.3", "tm-8.4"]);
184
- expect(source.unlocks_next).toEqual([
185
- "tm-7.1",
186
- "tm-7.2",
187
- "tm-7.3",
188
- "tm-7.4",
189
- "tm-7.5",
190
- "tm-7.6",
191
- ]);
192
-
193
- runCheckerOnMarkdown(markdown);
194
- });
195
- });
196
-
197
- describe("compilePlaybook — determinism (AC-2)", () => {
198
- it("compiling the same score twice yields byte-identical markdown and deep-equal source", () => {
199
- const input = {
200
- score: {
201
- id: "wlscore_det",
202
- tier: "level_7",
203
- ruleTrace: [predicateEntry("level_7", "validated_icp", true)],
204
- },
205
- plays: LIBRARY,
206
- leadId: "lead_det",
207
- };
208
-
209
- const first = compilePlaybook(input);
210
- const second = compilePlaybook(input);
211
-
212
- expect(second.markdown).toBe(first.markdown);
213
- expect(second.source).toEqual(first.source);
214
- });
215
- });
216
-
217
- describe("compilePlaybook — fail-soft compile errors (AC-4, spec §5.3)", () => {
218
- it("throws PlaybookCompileError for an unrecognized tier", () => {
219
- expect(() =>
220
- compilePlaybook({
221
- score: { id: "wlscore_bad", tier: "level_unresolved", ruleTrace: [] },
222
- plays: LIBRARY,
223
- leadId: "lead_bad",
224
- }),
225
- ).toThrow(PlaybookCompileError);
226
- });
227
-
228
- it("throws PlaybookCompileError when the library declares no plays for the tier's Level", () => {
229
- const emptyLibrary: PlayLibrary = { version: "1.0.0", method: "targeting-maturity", levels: [] };
230
- expect(() =>
231
- compilePlaybook({
232
- score: { id: "wlscore_empty", tier: "level_3", ruleTrace: [] },
233
- plays: emptyLibrary,
234
- leadId: "lead_empty",
235
- }),
236
- ).toThrow(PlaybookCompileError);
237
- });
238
- });
239
-
240
- describe("compileAndStorePlaybook (D4) — the Prisma-touching wrapper", () => {
241
- beforeEach(() => {
242
- jest.clearAllMocks();
243
- });
244
-
245
- it("creates exactly one PlaybookInstance row carrying the compiled source + markdown (AC-3)", async () => {
246
- (prisma.playbookInstance.create as jest.Mock).mockResolvedValue({ id: "pbk_1" });
247
-
248
- await compileAndStorePlaybook({
249
- siteId: "site-abc",
250
- leadId: "lead-1",
251
- experimentKey: "targeting-maturity",
252
- scoreId: "wlscore_1",
253
- tier: "level_1",
254
- ruleTrace: [],
255
- });
256
-
257
- expect(prisma.playbookInstance.create).toHaveBeenCalledTimes(1);
258
- const [call] = (prisma.playbookInstance.create as jest.Mock).mock.calls[0]!;
259
- expect(call.data).toMatchObject({
260
- siteId: "site-abc",
261
- leadId: "lead-1",
262
- experimentKey: "targeting-maturity",
263
- scoreId: "wlscore_1",
264
- tier: "level_1",
265
- level: 1,
266
- });
267
- expect(call.data.source).toMatchObject({ level: 1, compiled_from: "wlscore_1", scope_ref: "lead-1" });
268
- expect(typeof call.data.markdown).toBe("string");
269
- expect(call.data.markdown).toContain("playbook-source");
270
- });
271
-
272
- it("append-only: a second call for the same lead creates a SECOND row, never an update/upsert (AC-3)", async () => {
273
- (prisma.playbookInstance.create as jest.Mock)
274
- .mockResolvedValueOnce({ id: "pbk_1" })
275
- .mockResolvedValueOnce({ id: "pbk_2" });
276
-
277
- await compileAndStorePlaybook({
278
- siteId: "site-abc",
279
- leadId: "lead-1",
280
- experimentKey: "targeting-maturity",
281
- scoreId: "wlscore_1",
282
- tier: "level_1",
283
- ruleTrace: [],
284
- });
285
- await compileAndStorePlaybook({
286
- siteId: "site-abc",
287
- leadId: "lead-1",
288
- experimentKey: "targeting-maturity",
289
- scoreId: "wlscore_2",
290
- tier: "level_2",
291
- ruleTrace: [],
292
- });
293
-
294
- // Two calls -> two creates, distinct rows (the second scoreId), never a
295
- // single row mutated in place — the append-only contract (D2).
296
- expect(prisma.playbookInstance.create).toHaveBeenCalledTimes(2);
297
- const [firstCall] = (prisma.playbookInstance.create as jest.Mock).mock.calls[0]!;
298
- const [secondCall] = (prisma.playbookInstance.create as jest.Mock).mock.calls[1]!;
299
- expect(firstCall.data.scoreId).toBe("wlscore_1");
300
- expect(secondCall.data.scoreId).toBe("wlscore_2");
301
- });
302
-
303
- it("a compile failure (an unrecognized tier) is logged and never throws — the score is unaffected (AC-4)", async () => {
304
- await expect(
305
- compileAndStorePlaybook({
306
- siteId: "site-abc",
307
- leadId: "lead-1",
308
- experimentKey: "targeting-maturity",
309
- scoreId: "wlscore_1",
310
- tier: "level_unresolved",
311
- ruleTrace: [],
312
- }),
313
- ).resolves.toBeUndefined();
314
-
315
- expect(prisma.playbookInstance.create).not.toHaveBeenCalled();
316
- expect(mockLoggerError).toHaveBeenCalledWith(
317
- expect.objectContaining({
318
- siteId: "site-abc",
319
- experimentKey: "targeting-maturity",
320
- leadId: "lead-1",
321
- kind: "playbook_compile_failed",
322
- }),
323
- expect.any(String),
324
- );
325
- });
326
-
327
- it("a Prisma write failure is logged and never throws (AC-4)", async () => {
328
- (prisma.playbookInstance.create as jest.Mock).mockRejectedValue(new Error("db down"));
329
-
330
- await expect(
331
- compileAndStorePlaybook({
332
- siteId: "site-abc",
333
- leadId: "lead-1",
334
- experimentKey: "targeting-maturity",
335
- scoreId: "wlscore_1",
336
- tier: "level_1",
337
- ruleTrace: [],
338
- }),
339
- ).resolves.toBeUndefined();
340
-
341
- expect(mockLoggerError).toHaveBeenCalledWith(
342
- expect.objectContaining({ kind: "playbook_compile_failed" }),
343
- expect.any(String),
344
- );
345
- });
346
-
347
- it("a missing vendored library file degrades like any other compile failure — never throws at import or at call time (security review M1, AC-4)", async () => {
348
- // A fresh module instance (its own memoization cache) with process.cwd()
349
- // pointed at a path with no vendor/ tree above it, so every candidate in
350
- // resolveVendoredLibraryPath's probe misses and the fallback readFileSync
351
- // throws ENOENT — exactly M1's failure mode, exercised WITHOUT mocking
352
- // node:fs (a real missing-file read, not a simulated one).
353
- let freshCompileAndStorePlaybook!: typeof compileAndStorePlaybook;
354
- jest.isolateModules(() => {
355
- freshCompileAndStorePlaybook = require("../playbook-compile.js").compileAndStorePlaybook;
356
- });
357
-
358
- // The load is LAZY (M1) — it happens on the CALL below, not at the
359
- // require() above — so the cwd mock must still be active here, and is
360
- // restored only after the call that exercises it.
361
- const cwdSpy = jest.spyOn(process, "cwd").mockReturnValue("/nonexistent-root-for-m1-test");
362
- let result: unknown;
363
- try {
364
- result = await freshCompileAndStorePlaybook({
365
- siteId: "site-abc",
366
- leadId: "lead-1",
367
- experimentKey: "targeting-maturity",
368
- scoreId: "wlscore_missing_lib",
369
- tier: "level_1",
370
- ruleTrace: [],
371
- });
372
- } finally {
373
- cwdSpy.mockRestore();
374
- }
375
- expect(result).toBeUndefined();
376
-
377
- expect(prisma.playbookInstance.create).not.toHaveBeenCalled();
378
- expect(mockLoggerError).toHaveBeenCalledWith(
379
- expect.objectContaining({
380
- siteId: "site-abc",
381
- experimentKey: "targeting-maturity",
382
- leadId: "lead-1",
383
- kind: "playbook_compile_failed",
384
- }),
385
- expect.any(String),
386
- );
387
- });
388
- });
389
-
390
- describe("vendored checker self-test + provenance (AC-6)", () => {
391
- it("check-playbook.py --self-test exits 0", () => {
392
- expect(() => execFileSync("python3", [CHECKER_PATH, "--self-test"], { stdio: "pipe" })).not.toThrow();
393
- });
394
-
395
- it("each vendored file's sha256 equals the hash recorded in PROVENANCE.md", () => {
396
- const provenance = readFileSync(join(VENDOR_DIR, "PROVENANCE.md"), "utf8");
397
- for (const file of [
398
- "check-playbook.py",
399
- "playbook-source.schema.json",
400
- "targeting-maturity.plays.json",
401
- ]) {
402
- const actual = createHash("sha256").update(readFileSync(join(VENDOR_DIR, file))).digest("hex");
403
- expect(provenance).toContain(actual);
404
- }
405
- });
406
- });
@@ -1,290 +0,0 @@
1
- /**
2
- * @file playbook-render.test.ts
3
- * @description Golden tests for FEAT-074 U4b's renderer (#4718, AC-1/AC-2/AC-6).
4
- *
5
- * Reuses `compilePlaybook` (U4a) to produce a real `{source, markdown}` pair
6
- * from the vendored play library for each golden — the SAME goldens
7
- * `playbook-compile.test.ts` exercises (Level 0, Level 1 via paying
8
- * customers, Level 1 via the confirmed-Fit cohort loop-back, Level 5, Level
9
- * 8), so the render is proven against the real compile output, not a
10
- * hand-rolled `source`/`markdown` pair.
11
- *
12
- * PDF page count is read via `pdf-lib` itself (`PDFDocument.load`, already a
13
- * production dependency — no ESM friction under Jest). PDF TEXT is read by
14
- * shelling out to a standalone Node ESM script that drives `pdfjs-dist`'s
15
- * legacy Node build: `pdfjs-dist/legacy/build/pdf.mjs` uses `import.meta.url`
16
- * internally, which Jest's CommonJS-compiled test runner cannot load via a
17
- * dynamic `import()` (verified: `SyntaxError: Cannot use 'import.meta'
18
- * outside a module`) — mirrors `playbook-compile.test.ts`'s own
19
- * `execFileSync`-a-real-separate-process pattern (there, `check-playbook.py`;
20
- * here, a small Node ESM extractor script written to a temp file per call).
21
- */
22
- import { execFileSync } from "node:child_process";
23
- import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
24
- import { tmpdir } from "node:os";
25
- import { join } from "node:path";
26
-
27
- import { PDFDocument } from "pdf-lib";
28
-
29
- import {
30
- compilePlaybook,
31
- loadVendoredPlayLibrary,
32
- type PlayLibrary,
33
- } from "../playbook-compile.js";
34
- import { PlaybookRenderError, renderPlaybookPdf } from "../playbook-render.js";
35
-
36
- const LIBRARY: PlayLibrary = loadVendoredPlayLibrary();
37
-
38
- /** A `predicate`-kind ruleTrace entry (mirrors playbook-compile.test.ts's
39
- * own `predicateEntry` helper — only `tier`/`path`/`result` matter to
40
- * `compilePlaybook`'s loop-back detection). */
41
- function predicateEntry(tier: string, refName: string, result: boolean) {
42
- return {
43
- kind: "predicate" as const,
44
- tier,
45
- path: `allOf[0].ref(level1_only).allOf[0].ref(level1_signal).anyOf[0].ref(${refName}).eq`,
46
- node: {},
47
- result,
48
- detail: `${refName} = ${result}`,
49
- };
50
- }
51
-
52
- // ─── Extraction helper — a standalone Node ESM child process ──────────────
53
-
54
- const EXTRACT_SCRIPT = `
55
- import { readFileSync } from "node:fs";
56
- import { pathToFileURL } from "node:url";
57
- // pdfjs-dist's legacy Node build (getDocument) calls Promise.withResolvers(),
58
- // a Node 22 API. CI pins Node 20.19 (no Promise.withResolvers), so guard it
59
- // here -- before the pdfjs dynamic import below -- with a spec-compliant
60
- // polyfill (https://tc39.es/proposal-promise-with-resolvers/).
61
- if (typeof Promise.withResolvers !== "function") {
62
- Promise.withResolvers = function () {
63
- let resolve, reject;
64
- const promise = new Promise((res, rej) => {
65
- resolve = res;
66
- reject = rej;
67
- });
68
- return { promise, resolve, reject };
69
- };
70
- }
71
- const bytes = new Uint8Array(readFileSync(process.argv[2]));
72
- const pdfjs = await import(pathToFileURL(process.argv[3]).href);
73
- const doc = await pdfjs.getDocument({
74
- data: bytes,
75
- useWorkerFetch: false,
76
- isEvalSupported: false,
77
- useSystemFonts: true,
78
- }).promise;
79
- const pageTexts = [];
80
- for (let i = 1; i <= doc.numPages; i++) {
81
- const page = await doc.getPage(i);
82
- const textContent = await page.getTextContent();
83
- pageTexts.push(textContent.items.map((it) => it.str).join(" "));
84
- }
85
- process.stdout.write(JSON.stringify({ text: pageTexts.join("\\n") }));
86
- `;
87
-
88
- /**
89
- * Absolute path to pdfjs-dist's legacy Node entry, resolved from THIS
90
- * (CommonJS-compiled, per ts-jest's `module: 'commonjs'` preset — see the
91
- * file header) test module's own `require`. Passed to the child process by
92
- * absolute path — never a bare `"pdfjs-dist/..."` specifier — because the
93
- * extractor script is written to a temp directory outside this workspace's
94
- * `node_modules` resolution chain, where a bare specifier cannot resolve.
95
- */
96
- const PDFJS_LEGACY_ENTRY = require.resolve("pdfjs-dist/legacy/build/pdf.mjs");
97
-
98
- /** Extracts the concatenated text of every page of a PDF's bytes. */
99
- function extractPdfText(bytes: Uint8Array): string {
100
- const dir = mkdtempSync(join(tmpdir(), "playbook-pdf-extract-"));
101
- try {
102
- const scriptPath = join(dir, "extract.mjs");
103
- const pdfPath = join(dir, "playbook.pdf");
104
- writeFileSync(scriptPath, EXTRACT_SCRIPT, "utf8");
105
- writeFileSync(pdfPath, bytes);
106
- const out = execFileSync(
107
- "node",
108
- [scriptPath, pdfPath, PDFJS_LEGACY_ENTRY],
109
- { encoding: "utf8" },
110
- );
111
- return (JSON.parse(out) as { text: string }).text;
112
- } finally {
113
- rmSync(dir, { recursive: true, force: true });
114
- }
115
- }
116
-
117
- async function pageCount(bytes: Uint8Array): Promise<number> {
118
- const doc = await PDFDocument.load(bytes);
119
- return doc.getPageCount();
120
- }
121
-
122
- /** Renders and asserts the AC-6 <= 2s bound on EVERY golden call site, not
123
- * only one -- a per-golden bound, since the PDF renders per-request inside
124
- * the download route and the largest golden (Level 5, 6 own plays + 6
125
- * unlock plays) is exactly the case the bound exists to guard. */
126
- async function renderTimed(
127
- input: Parameters<typeof renderPlaybookPdf>[0],
128
- ): Promise<Uint8Array> {
129
- const start = Date.now();
130
- const bytes = await renderPlaybookPdf(input);
131
- expect(Date.now() - start).toBeLessThanOrEqual(2000);
132
- return bytes;
133
- }
134
-
135
- /** Every play title the library declares for `level` — used to assert the
136
- * rendered PDF's extracted text contains all of them (never hand-duplicated
137
- * as a literal string list, so this test can't drift from the library). */
138
- function titlesForLevel(level: number): string[] {
139
- const entry = LIBRARY.levels.find((l) => l.level === level);
140
- if (!entry) throw new Error(`no fixture level ${level} in the vendored library`);
141
- return entry.plays.map((p) => p.title);
142
- }
143
-
144
- /** The play ids the library declares for `level` — used to assert
145
- * `compilePlaybook`'s `source.unlocks_next` matches the library exactly
146
- * (mirrors playbook-compile.test.ts's own equivalent assertions). */
147
- function idsForLevel(level: number): string[] {
148
- const entry = LIBRARY.levels.find((l) => l.level === level);
149
- if (!entry) throw new Error(`no fixture level ${level} in the vendored library`);
150
- return entry.plays.map((p) => p.id);
151
- }
152
-
153
- // ─── The forbidden-token matcher (spec §2.1/AC-2) ──────────────────────────
154
-
155
- const WHOLE_WORD_FORBIDDEN = /\b(tier|cell|coefficient|stage)\b/;
156
- const SUBSTRING_FORBIDDEN = "level_";
157
-
158
- function assertNoForbiddenTokens(text: string): void {
159
- const lower = text.toLowerCase();
160
- expect(WHOLE_WORD_FORBIDDEN.test(lower)).toBe(false);
161
- expect(lower).not.toContain(SUBSTRING_FORBIDDEN);
162
- }
163
-
164
- // ─── Goldens — Level 0, 1 (both routes), 5, 8 — mirrors playbook-compile.test.ts ──
165
-
166
- describe("renderPlaybookPdf — goldens (AC-1, AC-2, AC-6)", () => {
167
- it("Level 0 (the Gate): labelled 'Gate', never 'Level 0'; every Level-0 play title present; no forbidden tokens; <= 6 pages; <= 2s", async () => {
168
- const { source, markdown } = compilePlaybook({
169
- score: { id: "wlscore_gate", tier: "level_0", ruleTrace: [] },
170
- plays: LIBRARY,
171
- leadId: "lead_gate",
172
- });
173
-
174
- const bytes = await renderTimed({ source, markdown, locale: "en" });
175
-
176
- expect(await pageCount(bytes)).toBeLessThanOrEqual(6);
177
-
178
- const text = extractPdfText(bytes);
179
- expect(text).toContain("Gate");
180
- expect(text).not.toContain("Level 0");
181
- for (const title of titlesForLevel(0)) {
182
- expect(text).toContain(title);
183
- }
184
- assertNoForbiddenTokens(text);
185
- });
186
-
187
- it("Level 1 via paying customers: labelled 'Level 1'; every Level-1 play title present; no forbidden tokens; <= 2s", async () => {
188
- const { source, markdown } = compilePlaybook({
189
- score: {
190
- id: "wlscore_l1_customers",
191
- tier: "level_1",
192
- ruleTrace: [predicateEntry("level_1", "has_customers", true)],
193
- },
194
- plays: LIBRARY,
195
- leadId: "lead_l1_customers",
196
- });
197
-
198
- const bytes = await renderTimed({ source, markdown, locale: "en" });
199
- expect(await pageCount(bytes)).toBeLessThanOrEqual(6);
200
-
201
- const text = extractPdfText(bytes);
202
- expect(text).toContain("Level 1");
203
- for (const title of titlesForLevel(1)) {
204
- expect(text).toContain(title);
205
- }
206
- assertNoForbiddenTokens(text);
207
- });
208
-
209
- it("Level 1 via the confirmed-Fit cohort loop-back: same Level-1 render contract as the paying-customers golden; <= 2s", async () => {
210
- const { source, markdown } = compilePlaybook({
211
- score: {
212
- id: "wlscore_l1_cohort",
213
- tier: "level_1",
214
- ruleTrace: [predicateEntry("level_1", "has_confirmed_fit_cohort", true)],
215
- },
216
- plays: LIBRARY,
217
- leadId: "lead_l1_cohort",
218
- });
219
-
220
- const bytes = await renderTimed({ source, markdown, locale: "en" });
221
- expect(await pageCount(bytes)).toBeLessThanOrEqual(6);
222
-
223
- const text = extractPdfText(bytes);
224
- expect(text).toContain("Level 1");
225
- for (const title of titlesForLevel(1)) {
226
- expect(text).toContain(title);
227
- }
228
- assertNoForbiddenTokens(text);
229
- });
230
-
231
- it("Level 5 (unlocks Level 7 -- never 6, the largest golden: 6 own plays + 6 unlock plays): every title present in both sections, no forbidden tokens, <= 6 pages, <= 2s", async () => {
232
- const { source, markdown } = compilePlaybook({
233
- score: { id: "wlscore_l5", tier: "level_5", ruleTrace: [] },
234
- plays: LIBRARY,
235
- leadId: "lead_l5",
236
- });
237
- expect(source.unlocks_next).toEqual(idsForLevel(7));
238
-
239
- const bytes = await renderTimed({ source, markdown, locale: "en" });
240
- expect(await pageCount(bytes)).toBeLessThanOrEqual(6);
241
-
242
- const text = extractPdfText(bytes);
243
- expect(text).toContain("Level 5");
244
- expect(text).toContain("Level 7");
245
- for (const title of [...titlesForLevel(5), ...titlesForLevel(7)]) {
246
- expect(text).toContain(title);
247
- }
248
- assertNoForbiddenTokens(text);
249
- });
250
-
251
- it("Level 8 (unlocks Level 7, never 9 -- library-declared, non-monotonic): every title present, no forbidden tokens; <= 2s", async () => {
252
- const { source, markdown } = compilePlaybook({
253
- score: { id: "wlscore_l8", tier: "level_8", ruleTrace: [] },
254
- plays: LIBRARY,
255
- leadId: "lead_l8",
256
- });
257
- expect(source.unlocks_next).toEqual(idsForLevel(7));
258
-
259
- const bytes = await renderTimed({ source, markdown, locale: "en" });
260
- expect(await pageCount(bytes)).toBeLessThanOrEqual(6);
261
-
262
- const text = extractPdfText(bytes);
263
- expect(text).toContain("Level 8");
264
- expect(text).toContain("Level 7");
265
- for (const title of [...titlesForLevel(8), ...titlesForLevel(7)]) {
266
- expect(text).toContain(title);
267
- }
268
- assertNoForbiddenTokens(text);
269
- });
270
- });
271
-
272
- // ─── A play id the current library no longer declares — a library defect ──
273
-
274
- describe("renderPlaybookPdf — library-defect posture (mirrors PlaybookCompileError)", () => {
275
- it("throws PlaybookRenderError when source names a play id the current library does not declare", async () => {
276
- const source = {
277
- artifact_type: "playbook" as const,
278
- scope: "person" as const,
279
- scope_ref: "lead_defect",
280
- method: "targeting-maturity",
281
- level: 0,
282
- plays: ["tm-0.1", "tm-999.999"],
283
- compiled_from: "wlscore_defect",
284
- };
285
-
286
- await expect(
287
- renderPlaybookPdf({ source, markdown: "", locale: "en" }),
288
- ).rejects.toThrow(PlaybookRenderError);
289
- });
290
- });