@egbe-ai/opencode 0.0.0-stage → 0.1.8

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 (479) hide show
  1. package/LICENSE +4 -0
  2. package/README.md +124 -2
  3. package/index.js +5 -0
  4. package/package.json +55 -4
  5. package/plugin.js +230 -0
  6. package/session-log.js +315 -0
  7. package/skills/.egbe-catalog/manifest.json +1 -0
  8. package/skills/egbe-os-analytics/SKILL.md +499 -0
  9. package/skills/egbe-os-analytics/canonical-events.v1.json +256 -0
  10. package/skills/egbe-os-analytics/references/session-funnel.md +130 -0
  11. package/skills/egbe-os-analytics/references/workflows/activation-tracking.md +147 -0
  12. package/skills/egbe-os-analytics/references/workflows/landing-click-tracking.md +209 -0
  13. package/skills/egbe-os-analytics/references/workflows/payment-lifecycle-tracking.md +122 -0
  14. package/skills/egbe-os-analytics/references/workflows/product-funnel-tracking.md +77 -0
  15. package/skills/egbe-os-analytics/references/workflows/signup-lifecycle-tracking.md +208 -0
  16. package/skills/egbe-os-analytics/scripts/umami_funnel.py +927 -0
  17. package/skills/egbe-os-apollo-lead-finder/SKILL.md +135 -0
  18. package/skills/egbe-os-apollo-lead-finder/references/operations.md +240 -0
  19. package/skills/egbe-os-apollo-lead-finder/scripts/enrich.js +6 -0
  20. package/skills/egbe-os-apollo-lead-finder/scripts/enrich.sh +4 -0
  21. package/skills/egbe-os-apollo-lead-finder/scripts/find-leads.js +6 -0
  22. package/skills/egbe-os-apollo-lead-finder/scripts/find-leads.sh +4 -0
  23. package/skills/egbe-os-apollo-lead-finder/scripts/lib/apollo-client.js +343 -0
  24. package/skills/egbe-os-apollo-lead-finder/scripts/lib/connection-identity.js +17 -0
  25. package/skills/egbe-os-apollo-lead-finder/scripts/lib/helpers.js +127 -0
  26. package/skills/egbe-os-apollo-lead-finder/scripts/lib/places-filters.js +217 -0
  27. package/skills/egbe-os-apollo-lead-finder/scripts/lib/sourcing.js +153 -0
  28. package/skills/egbe-os-apollo-lead-finder/scripts/places-leads.js +653 -0
  29. package/skills/egbe-os-apollo-lead-finder/scripts/places-leads.sh +4 -0
  30. package/skills/egbe-os-apollo-lead-finder/scripts/search.js +6 -0
  31. package/skills/egbe-os-apollo-lead-finder/scripts/search.sh +4 -0
  32. package/skills/egbe-os-campaign-landing-page/SKILL.md +95 -0
  33. package/skills/egbe-os-campaign-landing-page/agents/openai.yaml +4 -0
  34. package/skills/egbe-os-campaign-landing-page/references/leads-calendar-and-tracking.md +66 -0
  35. package/skills/egbe-os-campaign-landing-page/references/os-wiring.md +58 -0
  36. package/skills/egbe-os-campaign-landing-page/references/qa.md +40 -0
  37. package/skills/egbe-os-campaign-landing-page/references/routing.md +32 -0
  38. package/skills/egbe-os-db/SKILL.md +174 -0
  39. package/skills/egbe-os-deploy/SKILL.md +412 -0
  40. package/skills/egbe-os-design/SKILL.md +182 -0
  41. package/skills/egbe-os-design-landing-page/SKILL.md +117 -0
  42. package/skills/egbe-os-design-landing-page/agents/openai.yaml +4 -0
  43. package/skills/egbe-os-design-landing-page/assets/scaffold/.dockerignore +11 -0
  44. package/skills/egbe-os-design-landing-page/assets/scaffold/AGENTS.md +31 -0
  45. package/skills/egbe-os-design-landing-page/assets/scaffold/Dockerfile +21 -0
  46. package/skills/egbe-os-design-landing-page/assets/scaffold/eslint.config.mjs +18 -0
  47. package/skills/egbe-os-design-landing-page/assets/scaffold/next.config.ts +11 -0
  48. package/skills/egbe-os-design-landing-page/assets/scaffold/package.json +36 -0
  49. package/skills/egbe-os-design-landing-page/assets/scaffold/postcss.config.mjs +7 -0
  50. package/skills/egbe-os-design-landing-page/assets/scaffold/public/.gitkeep +1 -0
  51. package/skills/egbe-os-design-landing-page/assets/scaffold/sentry.edge.config.ts +13 -0
  52. package/skills/egbe-os-design-landing-page/assets/scaffold/sentry.server.config.ts +13 -0
  53. package/skills/egbe-os-design-landing-page/assets/scaffold/src/app/global-error.tsx +19 -0
  54. package/skills/egbe-os-design-landing-page/assets/scaffold/src/app/globals.css +22 -0
  55. package/skills/egbe-os-design-landing-page/assets/scaffold/src/app/layout.tsx +21 -0
  56. package/skills/egbe-os-design-landing-page/assets/scaffold/src/app/page.tsx +3 -0
  57. package/skills/egbe-os-design-landing-page/assets/scaffold/src/app/privacy/page.tsx +28 -0
  58. package/skills/egbe-os-design-landing-page/assets/scaffold/src/components/egbe-analytics.tsx +39 -0
  59. package/skills/egbe-os-design-landing-page/assets/scaffold/src/instrumentation-client.ts +15 -0
  60. package/skills/egbe-os-design-landing-page/assets/scaffold/src/instrumentation.ts +13 -0
  61. package/skills/egbe-os-design-landing-page/assets/scaffold/src/lib/egbe-observability.generated.ts +20 -0
  62. package/skills/egbe-os-design-landing-page/assets/scaffold/src/lib/utils.ts +6 -0
  63. package/skills/egbe-os-design-landing-page/assets/scaffold/tsconfig.json +34 -0
  64. package/skills/egbe-os-design-landing-page/references/application-preparation.md +44 -0
  65. package/skills/egbe-os-design-landing-page/references/page-inputs.md +22 -0
  66. package/skills/egbe-os-destination-readiness/SKILL.md +132 -0
  67. package/skills/egbe-os-destination-readiness/references/checks.md +130 -0
  68. package/skills/egbe-os-destination-readiness/references/network-requirements.md +34 -0
  69. package/skills/egbe-os-destination-readiness/references/report.md +116 -0
  70. package/skills/egbe-os-domains/SKILL.md +189 -0
  71. package/skills/egbe-os-errors/SKILL.md +259 -0
  72. package/skills/egbe-os-git/SKILL.md +275 -0
  73. package/skills/egbe-os-git/references/issues.md +33 -0
  74. package/skills/egbe-os-google-ads/SKILL.md +163 -0
  75. package/skills/egbe-os-google-ads/references/artifacts.md +133 -0
  76. package/skills/egbe-os-google-ads/references/campaigns.md +157 -0
  77. package/skills/egbe-os-google-ads/references/conversions.md +153 -0
  78. package/skills/egbe-os-google-ads/references/delivery.md +128 -0
  79. package/skills/egbe-os-google-ads/references/keyword-ideas.md +40 -0
  80. package/skills/egbe-os-google-ads/references/reporting.md +105 -0
  81. package/skills/egbe-os-google-ads/references/search-assets.md +219 -0
  82. package/skills/egbe-os-google-ads/references/server-conversions.md +119 -0
  83. package/skills/egbe-os-google-auth/SKILL.md +285 -0
  84. package/skills/egbe-os-google-auth/agents/openai.yaml +4 -0
  85. package/skills/egbe-os-gtm-knowledge/SKILL.md +151 -0
  86. package/skills/egbe-os-images/SKILL.md +163 -0
  87. package/skills/egbe-os-images/references/stock-images.md +21 -0
  88. package/skills/egbe-os-instantly-campaign-launcher/SKILL.md +127 -0
  89. package/skills/egbe-os-instantly-campaign-launcher/references/instantly-ops.md +260 -0
  90. package/skills/egbe-os-instantly-campaign-launcher/references/observation-and-scheduling.md +188 -0
  91. package/skills/egbe-os-instantly-campaign-launcher/references/reply-handling.md +116 -0
  92. package/skills/egbe-os-instantly-campaign-launcher/references/run-spec-template.json +65 -0
  93. package/skills/egbe-os-instantly-campaign-launcher/references/run-state.md +145 -0
  94. package/skills/egbe-os-instantly-campaign-launcher/scripts/conclude-campaign.js +158 -0
  95. package/skills/egbe-os-instantly-campaign-launcher/scripts/install-crons.js +956 -0
  96. package/skills/egbe-os-instantly-campaign-launcher/scripts/launch-campaign.js +2008 -0
  97. package/skills/egbe-os-instantly-campaign-launcher/scripts/lib/campaign-metrics.js +124 -0
  98. package/skills/egbe-os-instantly-campaign-launcher/scripts/lib/confirmed-opt-outs.js +208 -0
  99. package/skills/egbe-os-instantly-campaign-launcher/scripts/lib/connection-identity.js +17 -0
  100. package/skills/egbe-os-instantly-campaign-launcher/scripts/lib/create-once.js +23 -0
  101. package/skills/egbe-os-instantly-campaign-launcher/scripts/lib/gtm-identity.js +125 -0
  102. package/skills/egbe-os-instantly-campaign-launcher/scripts/lib/helpers.js +545 -0
  103. package/skills/egbe-os-instantly-campaign-launcher/scripts/lib/html-body.js +266 -0
  104. package/skills/egbe-os-instantly-campaign-launcher/scripts/lib/instantly-client.js +328 -0
  105. package/skills/egbe-os-instantly-campaign-launcher/scripts/lib/outreach-db.js +370 -0
  106. package/skills/egbe-os-instantly-campaign-launcher/scripts/lib/recipient-exclusion/index.js +86 -0
  107. package/skills/egbe-os-instantly-campaign-launcher/scripts/lib/replenish-test-harness.js +53 -0
  108. package/skills/egbe-os-instantly-campaign-launcher/scripts/lib/reply-queue.js +67 -0
  109. package/skills/egbe-os-instantly-campaign-launcher/scripts/lib/run-config.js +103 -0
  110. package/skills/egbe-os-instantly-campaign-launcher/scripts/lib/sender-selection.js +105 -0
  111. package/skills/egbe-os-instantly-campaign-launcher/scripts/monitor-campaign.js +607 -0
  112. package/skills/egbe-os-instantly-campaign-launcher/scripts/outreach-report.js +147 -0
  113. package/skills/egbe-os-instantly-campaign-launcher/scripts/replenish-leads.js +619 -0
  114. package/skills/egbe-os-instantly-campaign-launcher/scripts/reply-worker.js +258 -0
  115. package/skills/egbe-os-instantly-campaign-launcher/scripts/run-cron-job.js +32 -0
  116. package/skills/egbe-os-instantly-campaign-launcher/scripts/send-reply.js +260 -0
  117. package/skills/egbe-os-linkedin-ads/SKILL.md +114 -0
  118. package/skills/egbe-os-linkedin-ads/references/destination-requirements.md +30 -0
  119. package/skills/egbe-os-linkedin-ads/references/runtime/api-reference.md +154 -0
  120. package/skills/egbe-os-linkedin-ads/references/runtime/artifacts.md +63 -0
  121. package/skills/egbe-os-linkedin-ads/references/workflows/build-paused.md +44 -0
  122. package/skills/egbe-os-linkedin-ads/references/workflows/conversions.md +88 -0
  123. package/skills/egbe-os-linkedin-ads/references/workflows/launch-and-pause.md +49 -0
  124. package/skills/egbe-os-linkedin-ads/references/workflows/monitoring.md +35 -0
  125. package/skills/egbe-os-linkedin-ads/references/workflows/readiness.md +63 -0
  126. package/skills/egbe-os-linkedin-ads/references/workflows/targeting-and-creative.md +52 -0
  127. package/skills/egbe-os-llm/SKILL.md +160 -0
  128. package/skills/egbe-os-mail/SKILL.md +180 -0
  129. package/skills/egbe-os-me/SKILL.md +119 -0
  130. package/skills/egbe-os-meta-ads/SKILL.md +114 -0
  131. package/skills/egbe-os-meta-ads/references/creative/creative-specs.md +15 -0
  132. package/skills/egbe-os-meta-ads/references/creative/talking-head.md +35 -0
  133. package/skills/egbe-os-meta-ads/references/destination-requirements.md +30 -0
  134. package/skills/egbe-os-meta-ads/references/runtime/api-reference.md +436 -0
  135. package/skills/egbe-os-meta-ads/references/runtime/artifacts.md +51 -0
  136. package/skills/egbe-os-meta-ads/references/runtime/insights-reference.md +187 -0
  137. package/skills/egbe-os-meta-ads/references/runtime/pixel-install.md +196 -0
  138. package/skills/egbe-os-meta-ads/references/runtime/shared-analytics-attribution.md +16 -0
  139. package/skills/egbe-os-meta-ads/references/workflows/build-paused.md +36 -0
  140. package/skills/egbe-os-meta-ads/references/workflows/launch-ready.md +16 -0
  141. package/skills/egbe-os-meta-ads/references/workflows/launch.md +23 -0
  142. package/skills/egbe-os-meta-ads/references/workflows/monitoring.md +72 -0
  143. package/skills/egbe-os-meta-ads/references/workflows/pause.md +17 -0
  144. package/skills/egbe-os-meta-ads/references/workflows/recovery.md +23 -0
  145. package/skills/egbe-os-meta-ads/scripts/check-pixel.py +229 -0
  146. package/skills/egbe-os-meta-ads/scripts/validate-meta-artifacts.py +187 -0
  147. package/skills/egbe-os-notifications/SKILL.md +78 -0
  148. package/skills/egbe-os-openai-ads/SKILL.md +149 -0
  149. package/skills/egbe-os-openai-ads/references/creative/chat-card.md +51 -0
  150. package/skills/egbe-os-openai-ads/references/destination-requirements.md +29 -0
  151. package/skills/egbe-os-openai-ads/references/runtime/api-reference.md +219 -0
  152. package/skills/egbe-os-openai-ads/references/runtime/artifacts.md +169 -0
  153. package/skills/egbe-os-openai-ads/references/workflows/build-paused.md +40 -0
  154. package/skills/egbe-os-openai-ads/references/workflows/conversions.md +40 -0
  155. package/skills/egbe-os-openai-ads/references/workflows/creative-assembly.md +24 -0
  156. package/skills/egbe-os-openai-ads/references/workflows/launch.md +27 -0
  157. package/skills/egbe-os-openai-ads/references/workflows/monitoring.md +54 -0
  158. package/skills/egbe-os-openai-ads/references/workflows/pause.md +22 -0
  159. package/skills/egbe-os-openai-ads/references/workflows/readiness.md +37 -0
  160. package/skills/egbe-os-openai-ads/references/workflows/tracking.md +32 -0
  161. package/skills/egbe-os-openai-ads/scripts/validate-openai-artifacts.py +271 -0
  162. package/skills/egbe-os-organic-trend-watch/SKILL.md +139 -0
  163. package/skills/egbe-os-organic-trend-watch/agents/openai.yaml +4 -0
  164. package/skills/egbe-os-organic-trend-watch/references/analysis-and-adaptation.md +54 -0
  165. package/skills/egbe-os-organic-trend-watch/references/collection-and-analysis.md +117 -0
  166. package/skills/egbe-os-organic-trend-watch/references/output-contract.md +133 -0
  167. package/skills/egbe-os-organic-trend-watch/references/provider-contract.md +169 -0
  168. package/skills/egbe-os-organic-trend-watch/references/runtime-contract.md +204 -0
  169. package/skills/egbe-os-organic-trend-watch/references/visual-analysis-prompt.md +17 -0
  170. package/skills/egbe-os-organic-trend-watch/scripts/_analysis.py +612 -0
  171. package/skills/egbe-os-organic-trend-watch/scripts/_contract.py +1133 -0
  172. package/skills/egbe-os-organic-trend-watch/scripts/_provider_inputs.py +165 -0
  173. package/skills/egbe-os-organic-trend-watch/scripts/analyze-visual-evidence.py +315 -0
  174. package/skills/egbe-os-organic-trend-watch/scripts/build-provider-inputs.py +88 -0
  175. package/skills/egbe-os-organic-trend-watch/scripts/connection_identity.py +22 -0
  176. package/skills/egbe-os-organic-trend-watch/scripts/egbe_artifacts.py +24 -0
  177. package/skills/egbe-os-organic-trend-watch/scripts/finalize-receipt.py +106 -0
  178. package/skills/egbe-os-organic-trend-watch/scripts/normalize-videos.py +647 -0
  179. package/skills/egbe-os-organic-trend-watch/scripts/prepare-visual-evidence.py +324 -0
  180. package/skills/egbe-os-organic-trend-watch/scripts/render-result.py +30 -0
  181. package/skills/egbe-os-organic-trend-watch/scripts/run-apify.py +723 -0
  182. package/skills/egbe-os-organic-trend-watch/scripts/run-state.py +192 -0
  183. package/skills/egbe-os-organic-trend-watch/scripts/validate-context.py +27 -0
  184. package/skills/egbe-os-organic-trend-watch/scripts/validate-runtime.py +137 -0
  185. package/skills/egbe-os-payments/SKILL.md +215 -0
  186. package/skills/egbe-os-payments/agents/openai.yaml +4 -0
  187. package/skills/egbe-os-payments/assets/scaffolds/billing-nextjs-subscription/.egbe/scaffolds/billing-nextjs-subscription.v1.json +5 -0
  188. package/skills/egbe-os-payments/assets/scaffolds/billing-nextjs-subscription/AGENTS.append.md +13 -0
  189. package/skills/egbe-os-payments/assets/scaffolds/billing-nextjs-subscription/db/migrations/1000_egbe_billing.sql +66 -0
  190. package/skills/egbe-os-payments/assets/scaffolds/billing-nextjs-subscription/package.fragment.json +12 -0
  191. package/skills/egbe-os-payments/assets/scaffolds/billing-nextjs-subscription/scripts/billing-sync.mjs +162 -0
  192. package/skills/egbe-os-payments/assets/scaffolds/billing-nextjs-subscription/src/app/account/billing/error.tsx +11 -0
  193. package/skills/egbe-os-payments/assets/scaffolds/billing-nextjs-subscription/src/app/account/billing/loading.tsx +8 -0
  194. package/skills/egbe-os-payments/assets/scaffolds/billing-nextjs-subscription/src/app/account/billing/page.tsx +121 -0
  195. package/skills/egbe-os-payments/assets/scaffolds/billing-nextjs-subscription/src/app/api/billing/checkout/route.ts +102 -0
  196. package/skills/egbe-os-payments/assets/scaffolds/billing-nextjs-subscription/src/app/api/billing/portal/route.ts +54 -0
  197. package/skills/egbe-os-payments/assets/scaffolds/billing-nextjs-subscription/src/app/api/billing/status/route.ts +22 -0
  198. package/skills/egbe-os-payments/assets/scaffolds/billing-nextjs-subscription/src/app/api/payments/webhook/route.ts +65 -0
  199. package/skills/egbe-os-payments/assets/scaffolds/billing-nextjs-subscription/src/components/egbe-billing/plan-badge.tsx +16 -0
  200. package/skills/egbe-os-payments/assets/scaffolds/billing-nextjs-subscription/src/lib/egbe-billing/billing-sync.test.mjs +58 -0
  201. package/skills/egbe-os-payments/assets/scaffolds/billing-nextjs-subscription/src/lib/egbe-billing/catalog.ts +82 -0
  202. package/skills/egbe-os-payments/assets/scaffolds/billing-nextjs-subscription/src/lib/egbe-billing/checkout-payload.ts +47 -0
  203. package/skills/egbe-os-payments/assets/scaffolds/billing-nextjs-subscription/src/lib/egbe-billing/foundation-contract.test.mjs +59 -0
  204. package/skills/egbe-os-payments/assets/scaffolds/billing-nextjs-subscription/src/lib/egbe-billing/lifecycle.d.ts +16 -0
  205. package/skills/egbe-os-payments/assets/scaffolds/billing-nextjs-subscription/src/lib/egbe-billing/lifecycle.mjs +82 -0
  206. package/skills/egbe-os-payments/assets/scaffolds/billing-nextjs-subscription/src/lib/egbe-billing/lifecycle.test.mjs +94 -0
  207. package/skills/egbe-os-payments/assets/scaffolds/billing-nextjs-subscription/src/lib/egbe-billing/os-client.ts +96 -0
  208. package/skills/egbe-os-payments/assets/scaffolds/billing-nextjs-subscription/src/lib/egbe-billing/plans.json +17 -0
  209. package/skills/egbe-os-payments/assets/scaffolds/billing-nextjs-subscription/src/lib/egbe-billing/repository.ts +325 -0
  210. package/skills/egbe-os-payments/assets/scaffolds/billing-nextjs-subscription/src/lib/egbe-billing/signature.d.ts +6 -0
  211. package/skills/egbe-os-payments/assets/scaffolds/billing-nextjs-subscription/src/lib/egbe-billing/signature.mjs +22 -0
  212. package/skills/egbe-os-payments/references/contracts/plan-catalog.md +46 -0
  213. package/skills/egbe-os-payments/references/security/durable-verification.md +64 -0
  214. package/skills/egbe-os-payments/references/security/server-integration.md +26 -0
  215. package/skills/egbe-os-payments/references/security/webhook-and-entitlements.md +152 -0
  216. package/skills/egbe-os-payments/references/ux/billing-experience.md +47 -0
  217. package/skills/egbe-os-payments/references/workflows/account-billing.md +64 -0
  218. package/skills/egbe-os-payments/references/workflows/discounts-and-promotion-codes.md +265 -0
  219. package/skills/egbe-os-payments/references/workflows/one-time-purchase.md +75 -0
  220. package/skills/egbe-os-payments/references/workflows/product-checkout.md +355 -0
  221. package/skills/egbe-os-payments/references/workflows/subscription-lifecycle.md +55 -0
  222. package/skills/egbe-os-playbook/SKILL.md +79 -0
  223. package/skills/egbe-os-playbook/playbooks/market-and-acquisition/channels/email-outreach.md +91 -0
  224. package/skills/egbe-os-playbook/playbooks/market-and-acquisition/channels/google-search.md +40 -0
  225. package/skills/egbe-os-playbook/playbooks/market-and-acquisition/channels/linkedin.md +24 -0
  226. package/skills/egbe-os-playbook/playbooks/market-and-acquisition/channels/meta.md +23 -0
  227. package/skills/egbe-os-playbook/playbooks/market-and-acquisition/channels/openai.md +15 -0
  228. package/skills/egbe-os-playbook/playbooks/market-and-acquisition/channels/reddit.md +56 -0
  229. package/skills/egbe-os-playbook/playbooks/market-and-acquisition/choose-test.md +73 -0
  230. package/skills/egbe-os-playbook/playbooks/market-and-acquisition/evaluate.md +91 -0
  231. package/skills/egbe-os-playbook/playbooks/market-and-acquisition/market.md +96 -0
  232. package/skills/egbe-os-playbook/playbooks/market-and-acquisition/run-test.md +111 -0
  233. package/skills/egbe-os-playbook/playbooks/market-and-acquisition.md +56 -0
  234. package/skills/egbe-os-playbook/playbooks/product/business-loop.md +141 -0
  235. package/skills/egbe-os-playbook/playbooks/product/collaboration.md +26 -0
  236. package/skills/egbe-os-playbook/playbooks/product/deliver.md +75 -0
  237. package/skills/egbe-os-playbook/playbooks/product/diagnose.md +80 -0
  238. package/skills/egbe-os-playbook/playbooks/product/evaluate.md +67 -0
  239. package/skills/egbe-os-playbook/playbooks/product/experience.md +132 -0
  240. package/skills/egbe-os-playbook/playbooks/product/loop-examples.md +67 -0
  241. package/skills/egbe-os-playbook/playbooks/product/offer.md +65 -0
  242. package/skills/egbe-os-playbook/playbooks/product/value.md +91 -0
  243. package/skills/egbe-os-playbook/playbooks/product.md +67 -0
  244. package/skills/egbe-os-playbook/references/catalog.md +127 -0
  245. package/skills/egbe-os-playbook/references/changes.md +167 -0
  246. package/skills/egbe-os-playbook/scripts/playbook-changes.py +6 -0
  247. package/skills/egbe-os-playbook/scripts/playbook_changes/__init__.py +1 -0
  248. package/skills/egbe-os-playbook/scripts/playbook_changes/cli.py +57 -0
  249. package/skills/egbe-os-playbook/scripts/playbook_changes/operations.py +137 -0
  250. package/skills/egbe-os-playbook/scripts/playbook_changes/protocol.py +132 -0
  251. package/skills/egbe-os-playbook/scripts/playbook_changes/storage.py +180 -0
  252. package/skills/egbe-os-playbook/scripts/playbook_changes/transport.py +113 -0
  253. package/skills/egbe-os-product-auth/SKILL.md +151 -0
  254. package/skills/egbe-os-product-auth/agents/openai.yaml +4 -0
  255. package/skills/egbe-os-product-auth/assets/db/README.md +102 -0
  256. package/skills/egbe-os-product-auth/assets/db/create-validation-session.mjs +223 -0
  257. package/skills/egbe-os-product-auth/assets/db/migrate.mjs +64 -0
  258. package/skills/egbe-os-product-auth/assets/db/migrations/0001_auth.sql +33 -0
  259. package/skills/egbe-os-product-auth/assets/db/migrations/0002_auth_identities.sql +16 -0
  260. package/skills/egbe-os-product-auth/assets/scaffolds/product-auth-database/AGENTS.append.md +17 -0
  261. package/skills/egbe-os-product-auth/assets/scaffolds/product-auth-database/package.fragment.json +10 -0
  262. package/skills/egbe-os-product-auth/assets/scaffolds/product-nextjs-postgres/AGENTS.append.md +9 -0
  263. package/skills/egbe-os-product-auth/assets/scaffolds/product-nextjs-postgres/package.fragment.json +13 -0
  264. package/skills/egbe-os-product-auth/assets/scaffolds/product-nextjs-postgres/src/lib/egbe-product/db.ts +31 -0
  265. package/skills/egbe-os-product-auth/assets/scaffolds/product-nextjs-postgres/src/lib/egbe-product/identity.ts +94 -0
  266. package/skills/egbe-os-product-auth/assets/scaffolds/product-nextjs-postgres/src/lib/egbe-product/index.ts +3 -0
  267. package/skills/egbe-os-product-auth/assets/scaffolds/product-nextjs-postgres/src/lib/egbe-product/session.ts +91 -0
  268. package/skills/egbe-os-product-auth/references/contracts/live-auth-interface.md +108 -0
  269. package/skills/egbe-os-product-auth/references/frameworks/nextjs.md +34 -0
  270. package/skills/egbe-os-product-auth/references/security/session-and-credentials.md +73 -0
  271. package/skills/egbe-os-product-auth/references/ux/auth-experience.md +58 -0
  272. package/skills/egbe-os-product-auth/references/workflows/account-recovery.md +22 -0
  273. package/skills/egbe-os-product-auth/references/workflows/build-auth.md +212 -0
  274. package/skills/egbe-os-product-auth/references/workflows/google.md +34 -0
  275. package/skills/egbe-os-product-auth/references/workflows/passwordless-email.md +65 -0
  276. package/skills/egbe-os-product-build/SKILL.md +111 -0
  277. package/skills/egbe-os-product-build/agents/openai.yaml +4 -0
  278. package/skills/egbe-os-product-build/references/capabilities.md +25 -0
  279. package/skills/egbe-os-product-build/references/engineering.md +72 -0
  280. package/skills/egbe-os-product-build/references/execution.md +55 -0
  281. package/skills/egbe-os-product-build/references/foundations.md +93 -0
  282. package/skills/egbe-os-product-build/references/interface-quality.md +32 -0
  283. package/skills/egbe-os-product-build/references/workflows/private-review-handoff.md +86 -0
  284. package/skills/egbe-os-product-build/scripts/scaffold.py +296 -0
  285. package/skills/egbe-os-product-demo-video/SKILL.md +118 -0
  286. package/skills/egbe-os-product-demo-video/references/recording.md +32 -0
  287. package/skills/egbe-os-product-market-research/SKILL.md +159 -0
  288. package/skills/egbe-os-product-market-research/agents/openai.yaml +4 -0
  289. package/skills/egbe-os-product-market-research/references/catalog.v1.json +177 -0
  290. package/skills/egbe-os-product-market-research/references/config/channel-footprint-sources.v1.json +99 -0
  291. package/skills/egbe-os-product-market-research/references/config/creative-taxonomy.v1.json +367 -0
  292. package/skills/egbe-os-product-market-research/references/contracts/creative-video.md +75 -0
  293. package/skills/egbe-os-product-market-research/references/contracts/funnel-teardown.md +235 -0
  294. package/skills/egbe-os-product-market-research/references/contracts/geography-comparison.md +71 -0
  295. package/skills/egbe-os-product-market-research/references/contracts/lifecycle-capture.md +119 -0
  296. package/skills/egbe-os-product-market-research/references/contracts/research-artifacts.md +520 -0
  297. package/skills/egbe-os-product-market-research/references/contracts/walk-mechanics.v2.json +18 -0
  298. package/skills/egbe-os-product-market-research/references/prompts/acquisition-channels.md +137 -0
  299. package/skills/egbe-os-product-market-research/references/prompts/acquisition-channels.user.md +4 -0
  300. package/skills/egbe-os-product-market-research/references/prompts/competitive-landscape.md +118 -0
  301. package/skills/egbe-os-product-market-research/references/prompts/competitive-landscape.user.md +4 -0
  302. package/skills/egbe-os-product-market-research/references/prompts/demand-validation.md +154 -0
  303. package/skills/egbe-os-product-market-research/references/prompts/demand-validation.user.md +4 -0
  304. package/skills/egbe-os-product-market-research/references/prompts/market-size-and-dynamics.md +100 -0
  305. package/skills/egbe-os-product-market-research/references/prompts/market-size-and-dynamics.user.md +4 -0
  306. package/skills/egbe-os-product-market-research/references/prompts/pricing-and-monetization.md +126 -0
  307. package/skills/egbe-os-product-market-research/references/prompts/pricing-and-monetization.user.md +4 -0
  308. package/skills/egbe-os-product-market-research/references/prompts/target-audience.md +98 -0
  309. package/skills/egbe-os-product-market-research/references/prompts/target-audience.user.md +4 -0
  310. package/skills/egbe-os-product-market-research/references/prompts/unit-economics.md +217 -0
  311. package/skills/egbe-os-product-market-research/references/prompts/unit-economics.user.md +4 -0
  312. package/skills/egbe-os-product-market-research/references/prompts/value-proposition.md +113 -0
  313. package/skills/egbe-os-product-market-research/references/prompts/value-proposition.user.md +4 -0
  314. package/skills/egbe-os-product-market-research/references/workflows/acquisition-channels.md +27 -0
  315. package/skills/egbe-os-product-market-research/references/workflows/channel-footprint.md +163 -0
  316. package/skills/egbe-os-product-market-research/references/workflows/community-demand.md +100 -0
  317. package/skills/egbe-os-product-market-research/references/workflows/competitive-landscape.md +27 -0
  318. package/skills/egbe-os-product-market-research/references/workflows/competitor-ads.md +82 -0
  319. package/skills/egbe-os-product-market-research/references/workflows/competitor-set.md +300 -0
  320. package/skills/egbe-os-product-market-research/references/workflows/creative-patterns.md +228 -0
  321. package/skills/egbe-os-product-market-research/references/workflows/demand-validation.md +27 -0
  322. package/skills/egbe-os-product-market-research/references/workflows/fleet-prior.md +80 -0
  323. package/skills/egbe-os-product-market-research/references/workflows/funnel-teardown.md +184 -0
  324. package/skills/egbe-os-product-market-research/references/workflows/geography-comparison.md +84 -0
  325. package/skills/egbe-os-product-market-research/references/workflows/keyword-economics.md +122 -0
  326. package/skills/egbe-os-product-market-research/references/workflows/lifecycle-capture.md +218 -0
  327. package/skills/egbe-os-product-market-research/references/workflows/local-research.md +55 -0
  328. package/skills/egbe-os-product-market-research/references/workflows/market-size-and-dynamics.md +27 -0
  329. package/skills/egbe-os-product-market-research/references/workflows/preview.md +175 -0
  330. package/skills/egbe-os-product-market-research/references/workflows/pricing-and-monetization.md +27 -0
  331. package/skills/egbe-os-product-market-research/references/workflows/recommendations.md +35 -0
  332. package/skills/egbe-os-product-market-research/references/workflows/review-mining.md +76 -0
  333. package/skills/egbe-os-product-market-research/references/workflows/target-audience.md +27 -0
  334. package/skills/egbe-os-product-market-research/references/workflows/tiktok-reels-market-trends.md +46 -0
  335. package/skills/egbe-os-product-market-research/references/workflows/unit-economics.md +27 -0
  336. package/skills/egbe-os-product-market-research/references/workflows/value-proposition.md +27 -0
  337. package/skills/egbe-os-product-market-research/scripts/build-organic-trend-context.py +167 -0
  338. package/skills/egbe-os-product-market-research/scripts/build-preview-context.py +91 -0
  339. package/skills/egbe-os-product-market-research/scripts/build-research-query.py +225 -0
  340. package/skills/egbe-os-product-market-research/scripts/channel-footprint-model.py +294 -0
  341. package/skills/egbe-os-product-market-research/scripts/connection_identity.py +22 -0
  342. package/skills/egbe-os-product-market-research/scripts/creative-model.py +364 -0
  343. package/skills/egbe-os-product-market-research/scripts/creative-selection.py +113 -0
  344. package/skills/egbe-os-product-market-research/scripts/creative-semantics.py +365 -0
  345. package/skills/egbe-os-product-market-research/scripts/creative-video.py +542 -0
  346. package/skills/egbe-os-product-market-research/scripts/egbe_artifacts.py +24 -0
  347. package/skills/egbe-os-product-market-research/scripts/finalize-organic-trend-watch.py +304 -0
  348. package/skills/egbe-os-product-market-research/scripts/funnel-email-review.py +97 -0
  349. package/skills/egbe-os-product-market-research/scripts/funnel-model.py +966 -0
  350. package/skills/egbe-os-product-market-research/scripts/funnel_features.py +50 -0
  351. package/skills/egbe-os-product-market-research/scripts/geography-comparison-contract.py +172 -0
  352. package/skills/egbe-os-product-market-research/scripts/geography-comparison.py +169 -0
  353. package/skills/egbe-os-product-market-research/scripts/keyword-forecast.py +61 -0
  354. package/skills/egbe-os-product-market-research/scripts/keyword-locale-publication.py +136 -0
  355. package/skills/egbe-os-product-market-research/scripts/lifecycle-start.py +190 -0
  356. package/skills/egbe-os-product-market-research/scripts/persist-research-report.py +63 -0
  357. package/skills/egbe-os-product-market-research/scripts/research-artifact-io.py +281 -0
  358. package/skills/egbe-os-product-market-research/scripts/research-evidence.py +496 -0
  359. package/skills/egbe-os-product-market-research/scripts/research-policy.py +33 -0
  360. package/skills/egbe-os-product-market-research/scripts/research-section-runtime.py +343 -0
  361. package/skills/egbe-os-product-market-research/scripts/research-section-workflow.py +288 -0
  362. package/skills/egbe-os-product-market-research/scripts/research_integrity.py +122 -0
  363. package/skills/egbe-os-product-market-research/scripts/review-research-completion.py +306 -0
  364. package/skills/egbe-os-product-market-research/scripts/run-acquisition-channels.py +72 -0
  365. package/skills/egbe-os-product-market-research/scripts/run-channel-footprint.py +2258 -0
  366. package/skills/egbe-os-product-market-research/scripts/run-community-demand.py +1603 -0
  367. package/skills/egbe-os-product-market-research/scripts/run-competitive-landscape.py +66 -0
  368. package/skills/egbe-os-product-market-research/scripts/run-competitor-ads.py +1156 -0
  369. package/skills/egbe-os-product-market-research/scripts/run-competitor-set.py +2514 -0
  370. package/skills/egbe-os-product-market-research/scripts/run-creative-patterns.py +2042 -0
  371. package/skills/egbe-os-product-market-research/scripts/run-demand-validation.py +72 -0
  372. package/skills/egbe-os-product-market-research/scripts/run-fleet-prior.py +652 -0
  373. package/skills/egbe-os-product-market-research/scripts/run-funnel-teardown.py +493 -0
  374. package/skills/egbe-os-product-market-research/scripts/run-keyword-economics.py +1443 -0
  375. package/skills/egbe-os-product-market-research/scripts/run-lifecycle-capture.py +1543 -0
  376. package/skills/egbe-os-product-market-research/scripts/run-market-size-and-dynamics.py +66 -0
  377. package/skills/egbe-os-product-market-research/scripts/run-os-research.py +311 -0
  378. package/skills/egbe-os-product-market-research/scripts/run-pricing-and-monetization.py +71 -0
  379. package/skills/egbe-os-product-market-research/scripts/run-review-mining.py +1051 -0
  380. package/skills/egbe-os-product-market-research/scripts/run-target-audience.py +66 -0
  381. package/skills/egbe-os-product-market-research/scripts/run-unit-economics.py +71 -0
  382. package/skills/egbe-os-product-market-research/scripts/run-value-proposition.py +67 -0
  383. package/skills/egbe-os-product-market-research/scripts/upsert-markdown-section.py +156 -0
  384. package/skills/egbe-os-product-market-research/scripts/walk-funnels.py +249 -0
  385. package/skills/egbe-os-product-market-research/scripts/write-preview.py +710 -0
  386. package/skills/egbe-os-product-market-research/scripts/write-recommendations.py +272 -0
  387. package/skills/egbe-os-product-report/SKILL.md +150 -0
  388. package/skills/egbe-os-product-report/references/artifacts.md +84 -0
  389. package/skills/egbe-os-product-report/references/brief.md +34 -0
  390. package/skills/egbe-os-product-report/references/daily.md +76 -0
  391. package/skills/egbe-os-product-report/references/sources.md +68 -0
  392. package/skills/egbe-os-product-routines/SKILL.md +166 -0
  393. package/skills/egbe-os-product-routines/references/catalog.md +22 -0
  394. package/skills/egbe-os-product-routines/references/continuation-check.md +41 -0
  395. package/skills/egbe-os-product-routines/references/product-reporting.md +163 -0
  396. package/skills/egbe-os-product-routines/references/run-preset.md +32 -0
  397. package/skills/egbe-os-quickstart/scripts/egbe-curl.py +357 -0
  398. package/skills/egbe-os-quiz-funnel/SKILL.md +152 -0
  399. package/skills/egbe-os-quiz-funnel/agents/openai.yaml +4 -0
  400. package/skills/egbe-os-quiz-funnel/assets/engine/quiz-engine.d.mts +224 -0
  401. package/skills/egbe-os-quiz-funnel/assets/engine/quiz-engine.mjs +652 -0
  402. package/skills/egbe-os-quiz-funnel/assets/engine/quiz-engine.test.mjs +764 -0
  403. package/skills/egbe-os-quiz-funnel/assets/engine/quiz-history.d.mts +31 -0
  404. package/skills/egbe-os-quiz-funnel/assets/engine/quiz-history.mjs +87 -0
  405. package/skills/egbe-os-quiz-funnel/assets/engine/quiz-history.test.mjs +265 -0
  406. package/skills/egbe-os-quiz-funnel/assets/engine/quiz-reference.test.mjs +254 -0
  407. package/skills/egbe-os-quiz-funnel/assets/examples/egbe-docs/product/quizzes/books-checkup/QUIZ.md +195 -0
  408. package/skills/egbe-os-quiz-funnel/assets/examples/egbe-docs/product/quizzes/books-checkup/quiz.json +421 -0
  409. package/skills/egbe-os-quiz-funnel/assets/examples/egbe-docs/product/quizzes/books-checkup/quiz.public.json +369 -0
  410. package/skills/egbe-os-quiz-funnel/assets/examples/egbe-docs/product/quizzes/books-checkup/validation.json +21 -0
  411. package/skills/egbe-os-quiz-funnel/assets/reference/index.html +26 -0
  412. package/skills/egbe-os-quiz-funnel/assets/reference/quiz-bootstrap.js +31 -0
  413. package/skills/egbe-os-quiz-funnel/assets/reference/quiz-early-actions.mjs +11 -0
  414. package/skills/egbe-os-quiz-funnel/assets/reference/quiz-first-screen.mjs +32 -0
  415. package/skills/egbe-os-quiz-funnel/assets/reference/quiz-page.mjs +480 -0
  416. package/skills/egbe-os-quiz-funnel/assets/reference/quiz.css +264 -0
  417. package/skills/egbe-os-quiz-funnel/references/competitor-teardown.md +159 -0
  418. package/skills/egbe-os-quiz-funnel/references/conversion-handoff.md +156 -0
  419. package/skills/egbe-os-quiz-funnel/references/implementation.md +207 -0
  420. package/skills/egbe-os-quiz-funnel/references/inputs.md +37 -0
  421. package/skills/egbe-os-quiz-funnel/references/measurement.md +122 -0
  422. package/skills/egbe-os-quiz-funnel/references/spec-contract.md +335 -0
  423. package/skills/egbe-os-quiz-funnel/references/verification.md +101 -0
  424. package/skills/egbe-os-quiz-funnel/references/walk-mechanics.v2.json +18 -0
  425. package/skills/egbe-os-quiz-funnel/scripts/compile-quiz-spec.py +1869 -0
  426. package/skills/egbe-os-quiz-funnel/scripts/prepare-research-identity.py +66 -0
  427. package/skills/egbe-os-reddit-ads/SKILL.md +121 -0
  428. package/skills/egbe-os-reddit-ads/assets/static-banners/bold-statement/schema.json +41 -0
  429. package/skills/egbe-os-reddit-ads/assets/static-banners/bold-statement/template.html +106 -0
  430. package/skills/egbe-os-reddit-ads/assets/static-banners/data-proof/schema.json +61 -0
  431. package/skills/egbe-os-reddit-ads/assets/static-banners/data-proof/template.html +151 -0
  432. package/skills/egbe-os-reddit-ads/assets/static-banners/honest-breakdown/schema.json +91 -0
  433. package/skills/egbe-os-reddit-ads/assets/static-banners/honest-breakdown/template.html +185 -0
  434. package/skills/egbe-os-reddit-ads/assets/static-banners/question-hook/schema.json +51 -0
  435. package/skills/egbe-os-reddit-ads/assets/static-banners/question-hook/template.html +121 -0
  436. package/skills/egbe-os-reddit-ads/assets/static-banners/reddit-post-style/schema.json +87 -0
  437. package/skills/egbe-os-reddit-ads/assets/static-banners/reddit-post-style/template.html +212 -0
  438. package/skills/egbe-os-reddit-ads/references/creative/html-to-png-pipeline.md +123 -0
  439. package/skills/egbe-os-reddit-ads/references/creative/static-banner-qa.md +12 -0
  440. package/skills/egbe-os-reddit-ads/references/creative/static-banner-system.md +16 -0
  441. package/skills/egbe-os-reddit-ads/references/destination-requirements.md +36 -0
  442. package/skills/egbe-os-reddit-ads/references/runtime/api-reference.md +435 -0
  443. package/skills/egbe-os-reddit-ads/references/runtime/artifacts.md +57 -0
  444. package/skills/egbe-os-reddit-ads/references/runtime/monitoring.md +64 -0
  445. package/skills/egbe-os-reddit-ads/references/runtime/pixel-and-tracking.md +49 -0
  446. package/skills/egbe-os-reddit-ads/references/runtime/policies.md +19 -0
  447. package/skills/egbe-os-reddit-ads/references/runtime/shared-analytics-attribution.md +14 -0
  448. package/skills/egbe-os-reddit-ads/references/workflows/build-paused.md +35 -0
  449. package/skills/egbe-os-reddit-ads/references/workflows/launch-ready.md +19 -0
  450. package/skills/egbe-os-reddit-ads/references/workflows/launch.md +32 -0
  451. package/skills/egbe-os-reddit-ads/references/workflows/readiness.md +9 -0
  452. package/skills/egbe-os-reddit-ads/scripts/capture-ad.sh +178 -0
  453. package/skills/egbe-os-reddit-ads/scripts/validate-reddit-artifacts.py +187 -0
  454. package/skills/egbe-os-report-ui/SKILL.md +133 -0
  455. package/skills/egbe-os-report-ui/assets/egbe-wordmark.svg +9 -0
  456. package/skills/egbe-os-report-ui/assets/examples/components.html +417 -0
  457. package/skills/egbe-os-report-ui/assets/examples/editorial.html +209 -0
  458. package/skills/egbe-os-report-ui/assets/scaffold.html +179 -0
  459. package/skills/egbe-os-report-ui/references/components.md +209 -0
  460. package/skills/egbe-os-research/SKILL.md +125 -0
  461. package/skills/egbe-os-saas-unit-economics/SKILL.md +188 -0
  462. package/skills/egbe-os-scrape/SKILL.md +160 -0
  463. package/skills/egbe-os-search/SKILL.md +182 -0
  464. package/skills/egbe-os-search/references/google-places.md +81 -0
  465. package/skills/egbe-os-support/SKILL.md +149 -0
  466. package/skills/egbe-os-telemetry/SKILL.md +344 -0
  467. package/skills/egbe-os-telemetry/references/harnesses/claude-code.md +97 -0
  468. package/skills/egbe-os-telemetry/references/harnesses/codex.md +22 -0
  469. package/skills/egbe-os-telemetry/references/harnesses/hermes.md +39 -0
  470. package/skills/egbe-os-telemetry/references/harnesses/openclaw.md +139 -0
  471. package/skills/egbe-os-telemetry/references/harnesses/opencode.md +28 -0
  472. package/skills/egbe-os-tools/SKILL.md +180 -0
  473. package/skills/egbe-os-tools/references/theona.md +26 -0
  474. package/skills/egbe-os-wallet/SKILL.md +181 -0
  475. package/skills/egbe-setup/EGBE.md +484 -0
  476. package/skills/egbe-setup/SKILL.md +116 -0
  477. package/skills/egbe-setup/references/project.md +80 -0
  478. package/state.js +37 -0
  479. package/update.js +361 -0
@@ -0,0 +1,1869 @@
1
+ #!/usr/bin/env python3
2
+ """Validate a quiz funnel specification and render its derived artifacts.
3
+
4
+ Reads `egbe-docs/product/quizzes/<quiz-slug>/quiz.json` below the workspace
5
+ root, checks its executable contract, and writes `QUIZ.md`,
6
+ `quiz.public.json`, and `validation.json` next to them.
7
+
8
+ The compiler checks structure and consistency. It cannot check that a claim is
9
+ true; that remains the author's responsibility.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import argparse
15
+ import hashlib
16
+ import itertools
17
+ import json
18
+ import os
19
+ import re
20
+ import sys
21
+ import tempfile
22
+ import unicodedata
23
+ from datetime import date, datetime, timezone
24
+ from pathlib import Path
25
+ from typing import Any
26
+ from urllib.parse import parse_qsl, urlsplit
27
+
28
+
29
+ SPEC_CONTRACT = "quiz-funnel-spec-v1"
30
+ PUBLIC_CONTRACT = "quiz-funnel-public-v1"
31
+ REPORT_CONTRACT = "quiz-funnel-validation-v1"
32
+ PAGE_FILES = ("QUIZ.md", "quiz.public.json")
33
+
34
+ SLUG_PATTERN = re.compile(r"^[a-z0-9][a-z0-9-]{0,62}$")
35
+ ID_PATTERN = re.compile(r"^[a-z][a-z0-9_-]{0,39}$")
36
+ PARAM_PATTERN = re.compile(r"^[a-z][a-z0-9_]{0,39}$")
37
+ LANGUAGE_PATTERN = re.compile(r"^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$")
38
+ COUNTRY_PATTERN = re.compile(r"^[A-Z]{2}$")
39
+ ROUTE_PATTERN = re.compile(r"^/[a-z0-9_-]+(?:/[a-z0-9_-]+)*$")
40
+ TOKEN_PATTERN = re.compile(r"\{\{(.*?)\}\}")
41
+ ANSWER_TOKEN_PATTERN = re.compile(r"^answer:([a-z][a-z0-9_-]{0,39})$")
42
+
43
+ # First path segments that belong to other surfaces of a product.
44
+ RESERVED_SEGMENTS = {
45
+ "account",
46
+ "admin",
47
+ "api",
48
+ "auth",
49
+ "checkout",
50
+ "dashboard",
51
+ "login",
52
+ "logout",
53
+ "pricing",
54
+ "privacy",
55
+ "register",
56
+ "signup",
57
+ "terms",
58
+ }
59
+ # Geographies where tracking beyond what is strictly necessary needs consent:
60
+ # the European Economic Area, the United Kingdom, and Switzerland.
61
+ CONSENT_GEOGRAPHIES = frozenset(
62
+ "AT BE BG HR CY CZ DK EE FI FR DE GR HU IE IT LV LT LU MT NL PL PT RO SK SI ES SE "
63
+ "IS LI NO GB CH".split()
64
+ )
65
+ PERSONAL_PARAMS = {"email", "mail", "name", "phone", "tel"}
66
+ DESTINATION_KINDS = ("booking_url", "lead_form", "signup", "checkout")
67
+ GOAL_DESTINATIONS = {
68
+ "call": {"booking_url", "lead_form"},
69
+ "signup": {"signup"},
70
+ "payment": {"checkout"},
71
+ }
72
+ LEAD_FIELDS = ("name", "email", "phone", "company")
73
+ PROOF_KINDS = {"count", "fact", "logo", "statistic", "testimonial"}
74
+ QUESTION_PURPOSES = {"build_case", "personalize", "qualify"}
75
+ INTERSTITIAL_KINDS = {"encouragement", "proof", "teach"}
76
+ RESULT_FITS = {"fit", "partial", "not_fit"}
77
+
78
+ MAX_RULE_COMBINATIONS = 200_000
79
+
80
+
81
+ class SpecError(ValueError):
82
+ """The executable specification violates the contract."""
83
+
84
+
85
+ def _canonical_json(value: Any) -> str:
86
+ return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
87
+
88
+
89
+ def _sha256(text: str) -> str:
90
+ return hashlib.sha256(text.encode("utf-8")).hexdigest()
91
+
92
+
93
+ def _is_text(value: Any) -> bool:
94
+ return isinstance(value, str) and bool(value.strip())
95
+
96
+
97
+ def _is_choice(value: Any, choices: Any) -> bool:
98
+ return isinstance(value, str) and value in choices
99
+
100
+
101
+ def _plain(value: str) -> str:
102
+ """A text without case and accents, for finding a phrase in another text."""
103
+ decomposed = unicodedata.normalize("NFKD", value.casefold())
104
+ return "".join(
105
+ character for character in decomposed if not unicodedata.combining(character)
106
+ )
107
+
108
+
109
+ def _has_control_characters(value: str) -> bool:
110
+ return any(character.isspace() or ord(character) < 32 for character in value)
111
+
112
+
113
+ def _named(path: str, item: Any) -> str:
114
+ """`screens[1]` becomes `screens[1] (behind)` when the item has a usable id."""
115
+ identifier = item.get("id") if isinstance(item, dict) else None
116
+ if isinstance(identifier, str) and ID_PATTERN.fullmatch(identifier):
117
+ return f"{path} ({identifier})"
118
+ return path
119
+
120
+
121
+ class Tokens:
122
+ """Which `{{answer:...}}` tokens one visitor-facing text may contain."""
123
+
124
+ def __init__(
125
+ self, questions: dict[str, dict[str, Any]], *, sentence: bool, place: str
126
+ ) -> None:
127
+ self.questions = questions
128
+ self.sentence = sentence
129
+ self.place = place
130
+
131
+ def as_points(self) -> "Tokens":
132
+ return Tokens(self.questions, sentence=False, place=self.place)
133
+
134
+
135
+ class Validation:
136
+ """Collect executable contract errors and nonblocking diagnostics."""
137
+
138
+ def __init__(self) -> None:
139
+ self.errors: list[str] = []
140
+ self.warnings: list[dict[str, str]] = []
141
+ self.reachability = "not_checked"
142
+ # Questions whose answer a rule or a token uses.
143
+ self.referenced: set[str] = set()
144
+ # Every text the visitor reads.
145
+ self.read: list[tuple[str, str]] = []
146
+
147
+ def error(self, message: str) -> None:
148
+ self.errors.append(message)
149
+
150
+ def warn(self, rule: str, target: str, message: str) -> None:
151
+ self.warnings.append({"rule": rule, "target": target, "message": message})
152
+
153
+ def text(self, value: Any, path: str) -> bool:
154
+ """An internal text: any non-empty string."""
155
+ if _is_text(value):
156
+ return True
157
+ self.error(f"{path} must be a non-empty string")
158
+ return False
159
+
160
+ def copy(
161
+ self,
162
+ value: Any,
163
+ path: str,
164
+ *,
165
+ tokens: Tokens | None = None,
166
+ ) -> bool:
167
+ """A text the visitor reads: one plain line, with safe answer tokens."""
168
+ if not self.text(value, path):
169
+ return False
170
+ if value != value.strip() or "\n" in value or "\r" in value:
171
+ self.error(
172
+ f"{path} must be one line of plain text without line breaks or "
173
+ "surrounding spaces"
174
+ )
175
+ self._check_tokens(value, path, tokens)
176
+ self.read.append((path, value))
177
+ return True
178
+
179
+ def _check_tokens(
180
+ self, value: str, path: str, tokens: Tokens | None
181
+ ) -> None:
182
+ if tokens is None:
183
+ if "{{" in value or "}}" in value:
184
+ self.error(
185
+ f"{path} must not contain a token; tokens work only in the "
186
+ "headline, body, and points of interstitial screens and results"
187
+ )
188
+ return
189
+ leftover = TOKEN_PATTERN.sub("", value)
190
+ if "{{" in leftover or "}}" in leftover:
191
+ self.error(f"{path} contains an unfinished token")
192
+ for raw in TOKEN_PATTERN.findall(value):
193
+ match = ANSWER_TOKEN_PATTERN.fullmatch(raw.strip())
194
+ if match is None:
195
+ self.error(
196
+ f"{path} contains the unknown token '{{{{{raw}}}}}'; only "
197
+ "{{answer:<question id>}} is supported"
198
+ )
199
+ continue
200
+ question_id = match.group(1)
201
+ question = tokens.questions.get(question_id)
202
+ if question is None:
203
+ self.error(
204
+ f"{path} token names '{question_id}', which is not a question "
205
+ f"the visitor has answered before {tokens.place}"
206
+ )
207
+ continue
208
+ self.referenced.add(question_id)
209
+ if question["sensitive"]:
210
+ self.error(
211
+ f"{path} token names the sensitive question '{question_id}'; "
212
+ "answer text must not appear on unmasked screens or results"
213
+ )
214
+ continue
215
+ if not tokens.sentence:
216
+ continue
217
+ if question["select"] != "single":
218
+ self.error(
219
+ f"{path} token names '{question_id}', which is not a "
220
+ "single-select question; quote it in `points` instead"
221
+ )
222
+ if question["has_escape"]:
223
+ self.error(
224
+ f"{path} token names '{question_id}', which has an escape "
225
+ "option; a declined answer cannot be quoted in a sentence, "
226
+ "quote it in `points` instead"
227
+ )
228
+
229
+ def text_list(self, value: Any, path: str, *, nonempty: bool) -> list[str]:
230
+ if not isinstance(value, list):
231
+ self.error(f"{path} must be an array")
232
+ return []
233
+ if nonempty and not value:
234
+ self.error(f"{path} must not be empty")
235
+ items = []
236
+ for index, item in enumerate(value):
237
+ if self.text(item, f"{path}[{index}]"):
238
+ items.append(item)
239
+ return items
240
+
241
+ def mapping(
242
+ self,
243
+ value: Any,
244
+ path: str,
245
+ *,
246
+ required: tuple[str, ...],
247
+ optional: tuple[str, ...] = (),
248
+ ) -> dict[str, Any] | None:
249
+ if not isinstance(value, dict):
250
+ self.error(f"{path} must be an object")
251
+ return None
252
+ for key in required:
253
+ if key not in value:
254
+ self.error(f"{path}.{key} is required")
255
+ allowed = set(required) | set(optional)
256
+ for key in sorted(str(key) for key in value if key not in allowed):
257
+ self.error(f"{path}.{key} is not part of the contract")
258
+ return value
259
+
260
+ def identifier(self, value: Any, path: str) -> bool:
261
+ if isinstance(value, str) and ID_PATTERN.fullmatch(value):
262
+ return True
263
+ self.error(
264
+ f"{path} must start with a lowercase letter and contain only "
265
+ "lowercase letters, digits, '-' or '_' (40 characters at most)"
266
+ )
267
+ return False
268
+
269
+ def flag(self, value: Any, path: str) -> bool:
270
+ if isinstance(value, bool):
271
+ return value
272
+ self.error(f"{path} must be true or false")
273
+ return False
274
+
275
+
276
+ def _is_same_origin_path(value: Any) -> bool:
277
+ return (
278
+ isinstance(value, str)
279
+ and value.startswith("/")
280
+ and not value.startswith("//")
281
+ and "\\" not in value
282
+ and "#" not in value
283
+ and not _has_control_characters(value)
284
+ )
285
+
286
+
287
+ def _query_keys(query: str) -> set[str]:
288
+ return {key.lower() for key, _ in parse_qsl(query, keep_blank_values=True)}
289
+
290
+
291
+ def _validate_https_url(check: Validation, value: Any, path: str) -> bool:
292
+ message = f"{path} must be an absolute https URL"
293
+ if not _is_text(value) or _has_control_characters(value):
294
+ check.error(message)
295
+ return False
296
+ try:
297
+ parts = urlsplit(value)
298
+ hostname = parts.hostname
299
+ credentials = parts.username or parts.password
300
+ _ = parts.port # Reading the port validates it.
301
+ except ValueError:
302
+ check.error(message)
303
+ return False
304
+ if parts.scheme != "https" or not hostname or "." not in hostname:
305
+ check.error(message)
306
+ return False
307
+ valid = True
308
+ if credentials:
309
+ check.error(f"{path} must not contain credentials")
310
+ valid = False
311
+ if parts.fragment:
312
+ check.error(f"{path} must not contain a fragment")
313
+ valid = False
314
+ personal = sorted(_query_keys(parts.query) & PERSONAL_PARAMS)
315
+ if personal:
316
+ check.error(
317
+ f"{path} must not carry personal data in its query ({', '.join(personal)})"
318
+ )
319
+ valid = False
320
+ return valid
321
+
322
+
323
+ def _location(value: str) -> str:
324
+ """The part of an address that identifies the page, without its query."""
325
+ if value.startswith("/"):
326
+ return value.split("?", 1)[0].rstrip("/") or "/"
327
+ parts = urlsplit(value)
328
+ return f"https://{(parts.hostname or '').lower()}{parts.path.rstrip('/')}"
329
+
330
+
331
+ def _validate_path(check: Validation, value: Any, path: str) -> str | None:
332
+ if not _is_same_origin_path(value):
333
+ check.error(
334
+ f"{path} must be a same-origin path that starts with '/' and has no "
335
+ "fragment or spaces"
336
+ )
337
+ return None
338
+ personal = sorted(_query_keys(urlsplit(value).query) & PERSONAL_PARAMS)
339
+ if personal:
340
+ check.error(
341
+ f"{path} must not carry personal data in its query ({', '.join(personal)})"
342
+ )
343
+ return None
344
+ return _location(value)
345
+
346
+
347
+ def _validate_inputs(check: Validation, inputs: Any) -> dict[str, Any]:
348
+ facts: dict[str, Any] = {
349
+ "not_for": [],
350
+ "geographies": [],
351
+ "claims": [],
352
+ }
353
+ inputs = check.mapping(
354
+ inputs,
355
+ "inputs",
356
+ required=("product", "application", "segment", "offer", "traffic", "sources"),
357
+ )
358
+ if inputs is None:
359
+ return facts
360
+ check.text(inputs.get("product"), "inputs.product")
361
+
362
+ application = check.mapping(
363
+ inputs.get("application"), "inputs.application", required=("repository", "url")
364
+ )
365
+ if application is not None:
366
+ check.text(application.get("repository"), "inputs.application.repository")
367
+ _validate_https_url(check, application.get("url"), "inputs.application.url")
368
+
369
+ segment = check.mapping(
370
+ inputs.get("segment"),
371
+ "inputs.segment",
372
+ required=("name", "situation", "problem"),
373
+ )
374
+ if segment is not None:
375
+ for key in ("name", "situation", "problem"):
376
+ check.text(segment.get(key), f"inputs.segment.{key}")
377
+
378
+ offer = check.mapping(
379
+ inputs.get("offer"),
380
+ "inputs.offer",
381
+ required=("promise", "mechanism", "terms", "claims_to_avoid", "not_for"),
382
+ )
383
+ if offer is not None:
384
+ for key in ("promise", "mechanism", "terms"):
385
+ check.text(offer.get(key), f"inputs.offer.{key}")
386
+ facts["claims"] = check.text_list(
387
+ offer.get("claims_to_avoid"), "inputs.offer.claims_to_avoid", nonempty=False
388
+ )
389
+ facts["not_for"] = check.text_list(
390
+ offer.get("not_for"), "inputs.offer.not_for", nonempty=False
391
+ )
392
+
393
+ traffic = check.mapping(
394
+ inputs.get("traffic"),
395
+ "inputs.traffic",
396
+ required=("channels", "geographies"),
397
+ optional=("promise",),
398
+ )
399
+ if traffic is not None:
400
+ check.text_list(traffic.get("channels"), "inputs.traffic.channels", nonempty=True)
401
+ geographies = check.text_list(
402
+ traffic.get("geographies"), "inputs.traffic.geographies", nonempty=True
403
+ )
404
+ for index, code in enumerate(geographies):
405
+ if not COUNTRY_PATTERN.fullmatch(code):
406
+ check.error(
407
+ f"inputs.traffic.geographies[{index}] must be a two-letter "
408
+ "country code such as US, GB, or ES"
409
+ )
410
+ facts["geographies"] = geographies
411
+ if "promise" in traffic:
412
+ check.text(traffic["promise"], "inputs.traffic.promise")
413
+
414
+ sources = inputs.get("sources")
415
+ if not isinstance(sources, list) or not sources:
416
+ check.error("inputs.sources must be a non-empty array")
417
+ return facts
418
+ for index, source in enumerate(sources):
419
+ source = check.mapping(
420
+ source, f"inputs.sources[{index}]", required=("label", "ref")
421
+ )
422
+ if source is not None:
423
+ check.text(source.get("label"), f"inputs.sources[{index}].label")
424
+ check.text(source.get("ref"), f"inputs.sources[{index}].ref")
425
+ return facts
426
+
427
+
428
+ def _validate_link(check: Validation, link: Any, path: str) -> str | None:
429
+ """A `link` destination carries exactly one of a same-origin path or a URL."""
430
+ if not isinstance(link, dict):
431
+ check.error(f"{path} must be an object")
432
+ return None
433
+ for key in sorted(str(key) for key in link if key not in {"kind", "path", "url"}):
434
+ check.error(f"{path}.{key} is not part of the contract")
435
+ if link.get("kind") != "link":
436
+ check.error(f"{path}.kind must be 'link'")
437
+ has_path, has_url = "path" in link, "url" in link
438
+ if has_path == has_url:
439
+ check.error(f"{path} must contain exactly one of 'path' or 'url'")
440
+ return None
441
+ if has_path:
442
+ return _validate_path(check, link["path"], f"{path}.path")
443
+ if _validate_https_url(check, link["url"], f"{path}.url"):
444
+ return _location(link["url"])
445
+ return None
446
+
447
+
448
+ def _validate_booking(check: Validation, destination: dict[str, Any]) -> str | None:
449
+ check.mapping(
450
+ destination,
451
+ "goal.destination",
452
+ required=("kind", "url"),
453
+ optional=("fallback_params", "result_param"),
454
+ )
455
+ valid_url = _validate_https_url(check, destination.get("url"), "goal.destination.url")
456
+ carried = _query_keys(urlsplit(destination["url"]).query) if valid_url else set()
457
+
458
+ params = destination.get("fallback_params", {})
459
+ if not isinstance(params, dict):
460
+ check.error("goal.destination.fallback_params must be an object")
461
+ else:
462
+ for key, value in params.items():
463
+ if not isinstance(key, str) or not PARAM_PATTERN.fullmatch(key):
464
+ check.error(
465
+ f"goal.destination.fallback_params.{key} is not a valid "
466
+ "query parameter name"
467
+ )
468
+ elif key in PERSONAL_PARAMS:
469
+ check.error(
470
+ f"goal.destination.fallback_params.{key} would carry personal data"
471
+ )
472
+ check.text(value, f"goal.destination.fallback_params.{key}")
473
+ if "result_param" in destination:
474
+ result_param = destination["result_param"]
475
+ if not isinstance(result_param, str) or not PARAM_PATTERN.fullmatch(result_param):
476
+ check.error(
477
+ "goal.destination.result_param is not a valid query parameter name"
478
+ )
479
+ elif result_param in PERSONAL_PARAMS:
480
+ check.error("goal.destination.result_param would carry personal data")
481
+ elif result_param in carried:
482
+ check.error(
483
+ f"goal.destination.url already carries '{result_param}', so the "
484
+ "result could never be added; remove it from the address or "
485
+ "choose another result_param"
486
+ )
487
+ return _location(destination["url"]) if valid_url else None
488
+
489
+
490
+ def _validate_lead_form(check: Validation, destination: dict[str, Any]) -> str | None:
491
+ check.mapping(
492
+ destination,
493
+ "goal.destination",
494
+ required=(
495
+ "kind",
496
+ "action",
497
+ "fields",
498
+ "field_labels",
499
+ "submit_label",
500
+ "error",
501
+ "success",
502
+ ),
503
+ optional=("consent_note",),
504
+ )
505
+ fields = check.text_list(
506
+ destination.get("fields"), "goal.destination.fields", nonempty=True
507
+ )
508
+ for field in fields:
509
+ if field not in LEAD_FIELDS:
510
+ check.error(
511
+ f"goal.destination.fields contains '{field}'; allowed fields are "
512
+ f"{', '.join(LEAD_FIELDS)}"
513
+ )
514
+ if len(set(fields)) != len(fields):
515
+ check.error("goal.destination.fields must not repeat a field")
516
+ if fields and not {"email", "phone"} & set(fields):
517
+ check.error("goal.destination.fields must include email or phone")
518
+ labels = destination.get("field_labels")
519
+ if not isinstance(labels, dict):
520
+ check.error("goal.destination.field_labels must be an object")
521
+ else:
522
+ for field in fields:
523
+ check.copy(labels.get(field), f"goal.destination.field_labels.{field}")
524
+ for key in sorted(str(key) for key in labels if key not in fields):
525
+ check.error(f"goal.destination.field_labels.{key} has no matching field")
526
+ check.copy(
527
+ destination.get("submit_label"),
528
+ "goal.destination.submit_label",
529
+ )
530
+ check.copy(destination.get("error"), "goal.destination.error")
531
+ if "consent_note" in destination:
532
+ check.copy(
533
+ destination["consent_note"],
534
+ "goal.destination.consent_note",
535
+ )
536
+ success = check.mapping(
537
+ destination.get("success"),
538
+ "goal.destination.success",
539
+ required=("headline", "body"),
540
+ )
541
+ if success is not None:
542
+ for key in ("headline", "body"):
543
+ check.copy(
544
+ success.get(key),
545
+ f"goal.destination.success.{key}",
546
+ )
547
+ return _validate_path(check, destination.get("action"), "goal.destination.action")
548
+
549
+
550
+ def _validate_checkout(check: Validation, destination: dict[str, Any]) -> str | None:
551
+ check.mapping(
552
+ destination,
553
+ "goal.destination",
554
+ required=("kind", "path", "plan_key", "price"),
555
+ optional=("plan_param",),
556
+ )
557
+ check.text(destination.get("plan_key"), "goal.destination.plan_key")
558
+ if "price" in destination:
559
+ check.copy(destination["price"], "goal.destination.price")
560
+ location = _validate_path(check, destination.get("path"), "goal.destination.path")
561
+ plan_param = destination.get("plan_param", "plan")
562
+ if (
563
+ not isinstance(plan_param, str)
564
+ or not PARAM_PATTERN.fullmatch(plan_param)
565
+ or plan_param in PERSONAL_PARAMS
566
+ ):
567
+ check.error("goal.destination.plan_param is not a valid query parameter name")
568
+ elif location is not None and plan_param in _query_keys(
569
+ urlsplit(destination["path"]).query
570
+ ):
571
+ check.error(
572
+ f"goal.destination.path must not already carry '{plan_param}'; "
573
+ "the selected plan is appended from plan_key"
574
+ )
575
+ return location
576
+
577
+
578
+ def _validate_goal(check: Validation, goal: Any) -> dict[str, Any]:
579
+ """Validate the goal; return where it leads and the price it must show."""
580
+ facts: dict[str, Any] = {"location": None, "price": None}
581
+ goal = check.mapping(
582
+ goal, "goal", required=("type", "destination"), optional=("statement",)
583
+ )
584
+ if goal is None:
585
+ return facts
586
+ goal_type = goal.get("type")
587
+ if not _is_choice(goal_type, GOAL_DESTINATIONS):
588
+ check.error("goal.type must be one of call, signup, payment")
589
+ goal_type = None
590
+ if "statement" in goal:
591
+ check.text(goal["statement"], "goal.statement")
592
+
593
+ destination = goal.get("destination")
594
+ if not isinstance(destination, dict):
595
+ check.error("goal.destination must be an object")
596
+ return facts
597
+ kind = destination.get("kind")
598
+ if not _is_choice(kind, DESTINATION_KINDS):
599
+ check.error(
600
+ f"goal.destination.kind must be one of {', '.join(DESTINATION_KINDS)}"
601
+ )
602
+ return facts
603
+ if goal_type is not None and kind not in GOAL_DESTINATIONS[goal_type]:
604
+ check.error(
605
+ f"goal.destination.kind '{kind}' does not serve goal '{goal_type}'; "
606
+ f"use one of {', '.join(sorted(GOAL_DESTINATIONS[goal_type]))}"
607
+ )
608
+ if kind == "booking_url":
609
+ facts["location"] = _validate_booking(check, destination)
610
+ elif kind == "lead_form":
611
+ facts["location"] = _validate_lead_form(check, destination)
612
+ elif kind == "checkout":
613
+ facts["location"] = _validate_checkout(check, destination)
614
+ if _is_text(destination.get("price")):
615
+ facts["price"] = destination["price"].strip()
616
+ else:
617
+ check.mapping(destination, "goal.destination", required=("kind", "path"))
618
+ facts["location"] = _validate_path(
619
+ check, destination.get("path"), "goal.destination.path"
620
+ )
621
+ return facts
622
+
623
+
624
+ def _validate_proof(check: Validation, proof: Any) -> dict[str, dict[str, Any]]:
625
+ entries: dict[str, dict[str, Any]] = {}
626
+ if not isinstance(proof, list):
627
+ check.error("proof must be an array (it may be empty)")
628
+ return entries
629
+ for index, item in enumerate(proof):
630
+ path = _named(f"proof[{index}]", item)
631
+ item = check.mapping(
632
+ item,
633
+ path,
634
+ required=("id", "kind", "text", "source"),
635
+ optional=("author", "citation"),
636
+ )
637
+ if item is None:
638
+ continue
639
+ if check.identifier(item.get("id"), f"{path}.id"):
640
+ if item["id"] in entries:
641
+ check.error(f"{path}.id is already used")
642
+ entries[item["id"]] = item
643
+ kind = item.get("kind")
644
+ if not _is_choice(kind, PROOF_KINDS):
645
+ check.error(f"{path}.kind must be one of {', '.join(sorted(PROOF_KINDS))}")
646
+ check.copy(item.get("text"), f"{path}.text")
647
+ if not _is_text(item.get("source")):
648
+ check.error(
649
+ f"{path}.source is required: record where this proof can be "
650
+ "checked, or remove the proof"
651
+ )
652
+ if kind == "testimonial" and "author" not in item:
653
+ check.error(f"{path}.author is required for a testimonial")
654
+ if kind == "statistic" and "citation" not in item:
655
+ check.error(
656
+ f"{path}.citation is required for a third-party statistic; it is "
657
+ "shown to the visitor next to the number"
658
+ )
659
+ for key in ("author", "citation"):
660
+ if key in item:
661
+ check.copy(item[key], f"{path}.{key}")
662
+ return entries
663
+
664
+
665
+ def _validate_proof_refs(
666
+ check: Validation,
667
+ value: Any,
668
+ path: str,
669
+ proof: dict[str, dict[str, Any]],
670
+ used: set[str],
671
+ ) -> tuple[str, ...]:
672
+ refs = check.text_list(value, path, nonempty=False)
673
+ for ref in refs:
674
+ if ref not in proof:
675
+ check.error(f"{path} references unknown proof '{ref}'")
676
+ else:
677
+ used.add(ref)
678
+ if len(set(refs)) != len(refs):
679
+ check.error(f"{path} must not repeat a proof id")
680
+ return tuple(ref for ref in refs if ref in proof)
681
+
682
+
683
+ def _validate_media(check: Validation, media: Any, path: str) -> None:
684
+ media = check.mapping(media, path, required=("src", "alt", "source"))
685
+ if media is None:
686
+ return
687
+ src = media.get("src")
688
+ if isinstance(src, str) and src.startswith("/"):
689
+ _validate_path(check, src, f"{path}.src")
690
+ else:
691
+ _validate_https_url(check, src, f"{path}.src")
692
+ check.copy(media.get("alt"), f"{path}.alt")
693
+ if not _is_text(media.get("source")):
694
+ check.error(
695
+ f"{path}.source is required: record what the image shows and where "
696
+ "it comes from"
697
+ )
698
+
699
+
700
+ def _validate_texts(
701
+ check: Validation,
702
+ item: dict[str, Any],
703
+ path: str,
704
+ tokens: Tokens,
705
+ ) -> None:
706
+ """The headline, body, and points of an interstitial screen, variant, or result."""
707
+ options = {
708
+ "tokens": tokens,
709
+ }
710
+ if "headline" in item:
711
+ check.copy(item["headline"], f"{path}.headline", **options)
712
+ if "body" in item:
713
+ check.copy(item["body"], f"{path}.body", **options)
714
+ if "media" in item:
715
+ _validate_media(check, item["media"], f"{path}.media")
716
+ if "points" not in item:
717
+ return
718
+ points = item["points"]
719
+ if not isinstance(points, list) or not points:
720
+ check.error(f"{path}.points must be a non-empty array when present")
721
+ return
722
+ options["tokens"] = tokens.as_points()
723
+ for index, point in enumerate(points):
724
+ check.copy(point, f"{path}.points[{index}]", **options)
725
+
726
+
727
+ def _validate_when(
728
+ check: Validation,
729
+ when: Any,
730
+ path: str,
731
+ questions: dict[str, dict[str, Any]],
732
+ place: str,
733
+ *,
734
+ in_results: bool,
735
+ ) -> bool:
736
+ if not isinstance(when, dict) or len(when) != 1 or not set(when) <= {"all", "any"}:
737
+ check.error(f"{path} must contain exactly one of 'all' or 'any'")
738
+ return False
739
+ mode = next(iter(when))
740
+ conditions = when[mode]
741
+ if not isinstance(conditions, list) or not conditions:
742
+ check.error(f"{path}.{mode} must be a non-empty array")
743
+ return False
744
+ valid = True
745
+ for index, condition in enumerate(conditions):
746
+ condition_path = f"{path}.{mode}[{index}]"
747
+ if not isinstance(condition, dict):
748
+ check.error(f"{condition_path} must be an object")
749
+ valid = False
750
+ continue
751
+ for key in sorted(
752
+ str(key) for key in condition if key not in {"screen", "any_of", "none_of"}
753
+ ):
754
+ check.error(f"{condition_path}.{key} is not part of the contract")
755
+ valid = False
756
+ operators = [key for key in ("any_of", "none_of") if key in condition]
757
+ if len(operators) != 1:
758
+ check.error(
759
+ f"{condition_path} must contain exactly one of 'any_of' or 'none_of'"
760
+ )
761
+ valid = False
762
+ continue
763
+ screen_id = condition.get("screen")
764
+ question = questions.get(screen_id) if isinstance(screen_id, str) else None
765
+ if question is None:
766
+ check.error(
767
+ f"{condition_path}.screen must name a question the visitor has "
768
+ f"answered before {place}"
769
+ )
770
+ valid = False
771
+ else:
772
+ check.referenced.add(screen_id)
773
+ if in_results:
774
+ if question["sensitive"]:
775
+ check.error(
776
+ f"{condition_path}.screen names the sensitive question "
777
+ f"'{screen_id}'; the answer to a sensitive question must "
778
+ "not choose the result, because the result is reported"
779
+ )
780
+ valid = False
781
+ values = condition[operators[0]]
782
+ if (
783
+ not isinstance(values, list)
784
+ or not values
785
+ or not all(isinstance(value, str) for value in values)
786
+ ):
787
+ check.error(
788
+ f"{condition_path}.{operators[0]} must be a non-empty array of option ids"
789
+ )
790
+ valid = False
791
+ continue
792
+ if len(set(values)) != len(values):
793
+ check.error(f"{condition_path}.{operators[0]} must not repeat an option")
794
+ valid = False
795
+ if question is not None:
796
+ for value in values:
797
+ if value not in question["options"]:
798
+ check.error(
799
+ f"{condition_path}.{operators[0]} names unknown option "
800
+ f"'{value}' of screen '{screen_id}'"
801
+ )
802
+ valid = False
803
+ return valid
804
+
805
+
806
+ def _validate_question(
807
+ check: Validation, screen: dict[str, Any], path: str, index: int
808
+ ) -> dict[str, Any] | None:
809
+ select = screen.get("select")
810
+ required = ["id", "type", "select", "headline", "options"]
811
+ if select == "multi":
812
+ required.append("button")
813
+ # `button` and `lead` get their own, more helpful messages below.
814
+ check.mapping(
815
+ screen,
816
+ path,
817
+ required=tuple(required),
818
+ optional=("button", "hint", "lead", "sensitive", "purpose"),
819
+ )
820
+ target = screen["id"] if isinstance(screen.get("id"), str) else f"#{index + 1}"
821
+
822
+ if select not in ("single", "multi"):
823
+ check.error(f"{path}.select must be 'single' or 'multi'")
824
+ if select == "single" and "button" in screen:
825
+ check.error(
826
+ f"{path}.button is not allowed: a single-select question advances "
827
+ "as soon as an option is chosen"
828
+ )
829
+ if select == "multi" and "button" in screen:
830
+ check.copy(screen["button"], f"{path}.button")
831
+ if "lead" in screen:
832
+ check.copy(screen["lead"], f"{path}.lead")
833
+ if "hint" in screen:
834
+ check.copy(screen["hint"], f"{path}.hint")
835
+ check.copy(
836
+ screen.get("headline"),
837
+ f"{path}.headline",
838
+ )
839
+ purpose = screen.get("purpose")
840
+ if purpose is not None and not _is_choice(purpose, QUESTION_PURPOSES):
841
+ check.error(
842
+ f"{path}.purpose must be one of {', '.join(sorted(QUESTION_PURPOSES))}"
843
+ )
844
+ sensitive = "sensitive" in screen and check.flag(
845
+ screen["sensitive"], f"{path}.sensitive"
846
+ )
847
+
848
+ options = screen.get("options")
849
+ if not isinstance(options, list):
850
+ check.error(f"{path}.options must be an array")
851
+ return None
852
+ if not options:
853
+ check.error(f"{path}.options must not be empty")
854
+
855
+ known: dict[str, dict[str, Any]] = {}
856
+ escapes = 0
857
+ for option_index, option in enumerate(options):
858
+ option_path = _named(f"{path}.options[{option_index}]", option)
859
+ option = check.mapping(
860
+ option,
861
+ option_path,
862
+ required=("id", "label"),
863
+ optional=("escape", "phrase"),
864
+ )
865
+ if option is None:
866
+ continue
867
+ if check.identifier(option.get("id"), f"{option_path}.id"):
868
+ if option["id"] in known:
869
+ check.error(f"{option_path}.id is already used on this screen")
870
+ known[option["id"]] = option
871
+ check.copy(option.get("label"), f"{option_path}.label")
872
+ if "phrase" in option:
873
+ check.copy(option["phrase"], f"{option_path}.phrase")
874
+ if "escape" in option and check.flag(option["escape"], f"{option_path}.escape"):
875
+ escapes += 1
876
+ if escapes > 1:
877
+ check.error(f"{path}.options must not contain more than one escape option")
878
+ if options and escapes == len(options):
879
+ check.error(f"{path}.options must offer an answer besides the escape option")
880
+ if sensitive and escapes == 0:
881
+ check.error(
882
+ f"{path} is sensitive and needs an escape option such as "
883
+ "'Prefer not to say' (set escape to true on it)"
884
+ )
885
+ if select == "multi" and escapes == 0:
886
+ check.warn(
887
+ "multi_select_escape",
888
+ target,
889
+ f"{path} is a multi-select question without an escape option; a "
890
+ "visitor to whom no option applies cannot continue",
891
+ )
892
+ return {
893
+ "select": select if select in ("single", "multi") else "single",
894
+ "purpose": purpose,
895
+ "options": known,
896
+ "has_escape": escapes > 0,
897
+ "sensitive": sensitive,
898
+ }
899
+
900
+
901
+ def _validate_interstitial(
902
+ check: Validation,
903
+ screen: dict[str, Any],
904
+ path: str,
905
+ index: int,
906
+ questions: dict[str, dict[str, Any]],
907
+ proof: dict[str, dict[str, Any]],
908
+ used_proof: set[str],
909
+ ) -> list[Any]:
910
+ """Validate one interstitial screen and return its variant conditions."""
911
+ check.mapping(
912
+ screen,
913
+ path,
914
+ required=("id", "type", "kind", "headline", "button"),
915
+ optional=("body", "media", "points", "proof_ids", "variants"),
916
+ )
917
+ target = screen["id"] if isinstance(screen.get("id"), str) else f"#{index + 1}"
918
+ place = f"screen '{target}'"
919
+ tokens = Tokens(questions, sentence=True, place=place)
920
+ kind = screen.get("kind")
921
+ if not _is_choice(kind, INTERSTITIAL_KINDS):
922
+ check.error(f"{path}.kind must be one of {', '.join(sorted(INTERSTITIAL_KINDS))}")
923
+ refs = _validate_proof_refs(
924
+ check, screen.get("proof_ids", []), f"{path}.proof_ids", proof, used_proof
925
+ )
926
+ if kind == "proof" and not refs:
927
+ check.error(f"{path} is a proof screen and must reference at least one proof")
928
+ _validate_texts(check, screen, path, tokens)
929
+ check.copy(screen.get("button"), f"{path}.button")
930
+
931
+ conditions: list[Any] = []
932
+ if "variants" not in screen:
933
+ return conditions
934
+ variants = screen["variants"]
935
+ if not isinstance(variants, list) or not variants:
936
+ check.error(f"{path}.variants must be a non-empty array when present")
937
+ return conditions
938
+ for variant_index, variant in enumerate(variants):
939
+ variant_path = f"{path}.variants[{variant_index}]"
940
+ variant = check.mapping(
941
+ variant,
942
+ variant_path,
943
+ required=("when",),
944
+ optional=("headline", "body", "media", "points", "proof_ids"),
945
+ )
946
+ if variant is None:
947
+ conditions.append(None)
948
+ continue
949
+ if not set(variant) & {"headline", "body", "media", "points", "proof_ids"}:
950
+ check.error(
951
+ f"{variant_path} must change at least one text, the image, or the proof"
952
+ )
953
+ valid = _validate_when(
954
+ check,
955
+ variant.get("when"),
956
+ f"{variant_path}.when",
957
+ questions,
958
+ place,
959
+ in_results=False,
960
+ )
961
+ conditions.append(variant.get("when") if valid else None)
962
+ variant_refs = refs
963
+ if "proof_ids" in variant:
964
+ variant_refs = _validate_proof_refs(
965
+ check,
966
+ variant["proof_ids"],
967
+ f"{variant_path}.proof_ids",
968
+ proof,
969
+ used_proof,
970
+ )
971
+ if kind == "proof" and not variant_refs:
972
+ check.error(
973
+ f"{variant_path} belongs to a proof screen and must reference "
974
+ "at least one proof"
975
+ )
976
+ _validate_texts(check, variant, variant_path, tokens)
977
+ return conditions
978
+
979
+
980
+ def _validate_screens(
981
+ check: Validation,
982
+ screens: Any,
983
+ proof: dict[str, dict[str, Any]],
984
+ used_proof: set[str],
985
+ ) -> tuple[dict[str, dict[str, Any]], list[tuple[str, list[Any]]], set[str]]:
986
+ questions: dict[str, dict[str, Any]] = {}
987
+ rule_sets: list[tuple[str, list[Any]]] = []
988
+ seen: set[str] = set()
989
+ if not isinstance(screens, list) or not screens:
990
+ check.error("screens must be a non-empty array")
991
+ return questions, rule_sets, seen
992
+
993
+ for index, screen in enumerate(screens):
994
+ path = _named(f"screens[{index}]", screen)
995
+ if not isinstance(screen, dict):
996
+ check.error(f"{path} must be an object")
997
+ continue
998
+ screen_id = screen.get("id")
999
+ if check.identifier(screen_id, f"{path}.id"):
1000
+ if screen_id in seen:
1001
+ check.error(f"{path}.id is already used")
1002
+ seen.add(screen_id)
1003
+ else:
1004
+ screen_id = None
1005
+ kind = screen.get("type")
1006
+ if kind == "question":
1007
+ question = _validate_question(check, screen, path, index)
1008
+ if question is not None and screen_id is not None:
1009
+ questions[screen_id] = question
1010
+ elif kind == "interstitial":
1011
+ conditions = _validate_interstitial(
1012
+ check, screen, path, index, dict(questions), proof, used_proof
1013
+ )
1014
+ if conditions:
1015
+ rule_sets.append((path, [*conditions, None]))
1016
+ else:
1017
+ check.error(f"{path}.type must be 'question' or 'interstitial'")
1018
+
1019
+ return questions, rule_sets, seen
1020
+
1021
+
1022
+ def _can_be_left_out(point: str, questions: dict[str, dict[str, Any]]) -> bool:
1023
+ """True when the page leaves the point out for some visitors.
1024
+
1025
+ A point is left out when the visitor chose the escape option of a question
1026
+ that the point quotes.
1027
+ """
1028
+ for raw in TOKEN_PATTERN.findall(point):
1029
+ match = ANSWER_TOKEN_PATTERN.fullmatch(raw.strip())
1030
+ question = questions.get(match.group(1)) if match else None
1031
+ if question is None or question["has_escape"]:
1032
+ return True
1033
+ return False
1034
+
1035
+
1036
+ def _validate_price_is_shown(
1037
+ check: Validation,
1038
+ result: dict[str, Any],
1039
+ cta: dict[str, Any],
1040
+ path: str,
1041
+ price: str,
1042
+ questions: dict[str, dict[str, Any]],
1043
+ ) -> None:
1044
+ """Every visitor of a result that leads to the checkout reads the price."""
1045
+ always = [result.get("headline"), result.get("body"), cta.get("label"), cta.get("note")]
1046
+ sometimes = []
1047
+ points = result.get("points")
1048
+ for point in points if isinstance(points, list) else []:
1049
+ if isinstance(point, str):
1050
+ (sometimes if _can_be_left_out(point, questions) else always).append(point)
1051
+ if any(isinstance(text, str) and price in text for text in always):
1052
+ return
1053
+ if any(price in point for point in sometimes):
1054
+ check.error(
1055
+ f"{path} shows the price '{price}' only in a point that is left out "
1056
+ "when the visitor declines a question it quotes; state the price in "
1057
+ "a text that every visitor of this result reads"
1058
+ )
1059
+ else:
1060
+ check.error(
1061
+ f"{path} leads to the checkout and must show the price "
1062
+ f"'{price}' exactly as goal.destination.price states it"
1063
+ )
1064
+
1065
+
1066
+ def _validate_results(
1067
+ check: Validation,
1068
+ results: Any,
1069
+ questions: dict[str, dict[str, Any]],
1070
+ proof: dict[str, dict[str, Any]],
1071
+ used_proof: set[str],
1072
+ goal: dict[str, Any],
1073
+ not_for: list[str],
1074
+ screen_ids: set[str],
1075
+ ) -> list[Any]:
1076
+ """Validate the results and return their conditions in order."""
1077
+ conditions: list[Any] = []
1078
+ if not isinstance(results, list) or not results:
1079
+ check.error("results must be a non-empty array")
1080
+ return conditions
1081
+ place = "the result"
1082
+ tokens = Tokens(questions, sentence=True, place=place)
1083
+ seen: set[str] = set()
1084
+ converting = 0
1085
+ for index, result in enumerate(results):
1086
+ path = _named(f"results[{index}]", result)
1087
+ result = check.mapping(
1088
+ result,
1089
+ path,
1090
+ required=("id", "fit", "headline", "body", "cta"),
1091
+ optional=("when", "media", "points", "proof_ids"),
1092
+ )
1093
+ if result is None:
1094
+ conditions.append(None)
1095
+ continue
1096
+ result_id = result.get("id")
1097
+ if check.identifier(result_id, f"{path}.id"):
1098
+ if result_id in seen:
1099
+ check.error(f"{path}.id is already used")
1100
+ elif result_id in screen_ids:
1101
+ check.error(f"{path}.id is already used by a screen")
1102
+ seen.add(result_id)
1103
+
1104
+ is_last = index == len(results) - 1
1105
+ if "when" in result:
1106
+ if is_last:
1107
+ check.error(
1108
+ f"{path} is the last result and must be the default: remove 'when'"
1109
+ )
1110
+ valid = _validate_when(
1111
+ check, result["when"], f"{path}.when", questions, place, in_results=True
1112
+ )
1113
+ conditions.append(result["when"] if valid and not is_last else None)
1114
+ else:
1115
+ if not is_last:
1116
+ check.error(
1117
+ f"{path} has no 'when'; only the last result may be the default"
1118
+ )
1119
+ conditions.append(None)
1120
+
1121
+ fit = result.get("fit")
1122
+ if not _is_choice(fit, RESULT_FITS):
1123
+ check.error(f"{path}.fit must be one of fit, partial, not_fit")
1124
+ fit = None
1125
+ elif fit == "not_fit" and not not_for:
1126
+ check.error(
1127
+ f"{path} is not_fit, but inputs.offer.not_for names nobody the "
1128
+ "offer is not for; do not invent a disqualification"
1129
+ )
1130
+ refs = _validate_proof_refs(
1131
+ check, result.get("proof_ids", []), f"{path}.proof_ids", proof, used_proof
1132
+ )
1133
+ _validate_texts(check, result, path, tokens)
1134
+
1135
+ if "cta" not in result:
1136
+ continue
1137
+ cta = result["cta"]
1138
+ if cta is None:
1139
+ if fit != "not_fit":
1140
+ check.error(f"{path}.cta may be null only for a not_fit result")
1141
+ continue
1142
+ cta = check.mapping(
1143
+ cta, f"{path}.cta", required=("label",), optional=("destination", "note")
1144
+ )
1145
+ if cta is None:
1146
+ continue
1147
+ if "note" in cta:
1148
+ check.copy(
1149
+ cta["note"],
1150
+ f"{path}.cta.note",
1151
+ )
1152
+ check.copy(
1153
+ cta.get("label"),
1154
+ f"{path}.cta.label",
1155
+ )
1156
+ if "destination" in cta:
1157
+ location = _validate_link(check, cta["destination"], f"{path}.cta.destination")
1158
+ if location is not None and location == goal["location"]:
1159
+ check.error(
1160
+ f"{path}.cta.destination leads to the destination of the goal; "
1161
+ "remove it to use the goal, or lead somewhere else"
1162
+ )
1163
+ elif fit == "not_fit":
1164
+ check.error(
1165
+ f"{path} is not_fit and must not send the visitor to the goal "
1166
+ "destination: give it its own link destination or set cta to null"
1167
+ )
1168
+ elif fit in ("fit", "partial"):
1169
+ converting += 1
1170
+ if goal["price"]:
1171
+ _validate_price_is_shown(
1172
+ check, result, cta, path, goal["price"], questions
1173
+ )
1174
+
1175
+ if converting == 0:
1176
+ check.error(
1177
+ "no fit or partial result leads to the goal destination; the quiz "
1178
+ "cannot convert"
1179
+ )
1180
+ return conditions
1181
+
1182
+
1183
+ def _answer_classes(
1184
+ question: dict[str, Any], option_sets: list[frozenset[str]],
1185
+ budget: int = MAX_RULE_COMBINATIONS,
1186
+ ) -> set[tuple[bool, ...]] | None:
1187
+ """Distinct ways one question's answer can satisfy the option sets that rules test."""
1188
+ regular = [key for key, option in question["options"].items() if not option.get("escape")]
1189
+ escapes = [key for key, option in question["options"].items() if option.get("escape")]
1190
+
1191
+ def signature(option_id: str) -> tuple[bool, ...]:
1192
+ return tuple(option_id in options for options in option_sets)
1193
+
1194
+ classes = {signature(option_id) for option_id in escapes}
1195
+ singles = {signature(option_id) for option_id in regular}
1196
+ if question["select"] == "single":
1197
+ return classes | singles if len(classes | singles) <= budget else None
1198
+ # A multi-select answer is any non-empty set of regular options, or the
1199
+ # escape option alone. Its class is the union of the classes of its options.
1200
+ # Bound the work BEFORE combinations are enumerated. Large option lists are
1201
+ # valid input; a skipped exhaustive check is not proof of reachability.
1202
+ if len(singles) >= budget.bit_length() or (1 << len(singles)) - 1 + len(classes) > budget:
1203
+ return None
1204
+ for size in range(1, len(singles) + 1):
1205
+ for group in itertools.combinations(sorted(singles), size):
1206
+ classes.add(tuple(any(column) for column in zip(*group)))
1207
+ return classes
1208
+
1209
+
1210
+ def _unreachable(
1211
+ rules: list[Any], questions: dict[str, dict[str, Any]]
1212
+ ) -> list[int] | None:
1213
+ """Indexes of rules no answer can select; None when the space is too large.
1214
+
1215
+ `rules` holds `when` objects in order; None stands for a rule that always
1216
+ matches, such as the default result.
1217
+ """
1218
+ tested: dict[str, list[frozenset[str]]] = {}
1219
+ for when in rules:
1220
+ if when is None:
1221
+ continue
1222
+ for condition in next(iter(when.values())):
1223
+ options = frozenset(condition.get("any_of") or condition.get("none_of"))
1224
+ known = tested.setdefault(condition["screen"], [])
1225
+ if options not in known:
1226
+ known.append(options)
1227
+
1228
+ names = sorted(tested)
1229
+ spaces = []
1230
+ total = 1
1231
+ for name in names:
1232
+ classes = _answer_classes(questions[name], tested[name], MAX_RULE_COMBINATIONS // total)
1233
+ if classes is None:
1234
+ return None
1235
+ space = sorted(classes)
1236
+ spaces.append(space)
1237
+ total *= max(len(space), 1)
1238
+ if total > MAX_RULE_COMBINATIONS:
1239
+ return None
1240
+
1241
+ def matches(when: Any, answer: dict[str, tuple[bool, ...]]) -> bool:
1242
+ if when is None:
1243
+ return True
1244
+ mode, conditions = next(iter(when.items()))
1245
+ outcomes = []
1246
+ for condition in conditions:
1247
+ operator = "any_of" if "any_of" in condition else "none_of"
1248
+ column = tested[condition["screen"]].index(frozenset(condition[operator]))
1249
+ hit = answer[condition["screen"]][column]
1250
+ outcomes.append(hit if operator == "any_of" else not hit)
1251
+ return all(outcomes) if mode == "all" else any(outcomes)
1252
+
1253
+ reached: set[int] = set()
1254
+ for combination in itertools.product(*spaces):
1255
+ answer = dict(zip(names, combination))
1256
+ for index, when in enumerate(rules):
1257
+ if matches(when, answer):
1258
+ reached.add(index)
1259
+ break
1260
+ return [index for index in range(len(rules)) if index not in reached]
1261
+
1262
+
1263
+ def _validate_reachability(
1264
+ check: Validation,
1265
+ results: list[Any],
1266
+ rule_sets: list[tuple[str, list[Any]]],
1267
+ result_rules: list[Any],
1268
+ questions: dict[str, dict[str, Any]],
1269
+ ) -> None:
1270
+ check.reachability = "checked"
1271
+
1272
+ def unreachable(rules: list[Any], target: str) -> list[int]:
1273
+ found = _unreachable(rules, questions)
1274
+ if found is None:
1275
+ check.reachability = "not_checked"
1276
+ check.warn(
1277
+ "reachability_not_checked", target,
1278
+ "Exhaustive reachability exceeds the bounded analysis budget; "
1279
+ "not verified. Check these paths separately before release.",
1280
+ )
1281
+ return []
1282
+ return found
1283
+
1284
+ for index in unreachable(result_rules, "results"):
1285
+ check.error(
1286
+ f"{_named(f'results[{index}]', results[index])} can never be shown: "
1287
+ "its conditions cannot be met, or earlier results catch every answer "
1288
+ "that meets them"
1289
+ )
1290
+ for path, rules in rule_sets:
1291
+ for index in unreachable(rules, path):
1292
+ if index == len(rules) - 1:
1293
+ check.error(
1294
+ f"{path} never shows its own texts because its variants catch "
1295
+ "every answer; move the texts of one variant onto the screen"
1296
+ )
1297
+ else:
1298
+ check.error(
1299
+ f"{path}.variants[{index}] can never be shown: its conditions "
1300
+ "cannot be met, or earlier variants catch every answer that "
1301
+ "meets them"
1302
+ )
1303
+
1304
+
1305
+ def _validate_claims(
1306
+ check: Validation,
1307
+ inputs: dict[str, Any],
1308
+ ) -> None:
1309
+ """Check configured prohibited claims; word matching cannot prove truth."""
1310
+ claims = [(claim.strip(), _plain(claim.strip())) for claim in inputs["claims"]]
1311
+ for path, text in check.read:
1312
+ plain = _plain(text)
1313
+ for claim, plain_claim in claims:
1314
+ if plain_claim and plain_claim in plain:
1315
+ check.error(
1316
+ f"{path} states a claim to avoid: '{claim}' "
1317
+ "(inputs.offer.claims_to_avoid)"
1318
+ )
1319
+
1320
+
1321
+ def validate_spec(
1322
+ spec: Any,
1323
+ ) -> tuple[list[str], list[dict[str, str]], dict[str, Any]]:
1324
+ """Return executable contract errors, diagnostics, and derived facts."""
1325
+ check = Validation()
1326
+ facts: dict[str, Any] = {"consent_geographies": []}
1327
+ root = check.mapping(
1328
+ spec,
1329
+ "spec",
1330
+ required=(
1331
+ "contract",
1332
+ "quiz_slug",
1333
+ "product_slug",
1334
+ "route",
1335
+ "language",
1336
+ "title",
1337
+ "ui",
1338
+ "inputs",
1339
+ "goal",
1340
+ "proof",
1341
+ "screens",
1342
+ "results",
1343
+ ),
1344
+ )
1345
+ if root is None:
1346
+ return check.errors, [], facts
1347
+
1348
+ if root.get("contract") != SPEC_CONTRACT:
1349
+ check.error(f"contract must be '{SPEC_CONTRACT}'")
1350
+ for key in ("quiz_slug", "product_slug"):
1351
+ value = root.get(key)
1352
+ if not isinstance(value, str) or not SLUG_PATTERN.fullmatch(value):
1353
+ check.error(
1354
+ f"{key} must be a slug of lowercase letters, digits and '-' "
1355
+ "(63 characters at most)"
1356
+ )
1357
+ route = root.get("route")
1358
+ if not isinstance(route, str) or not ROUTE_PATTERN.fullmatch(route):
1359
+ check.error(
1360
+ "route must be a lowercase path such as /quiz/<quiz-slug> without a "
1361
+ "query, fragment, or trailing slash"
1362
+ )
1363
+ elif route.split("/")[1] in RESERVED_SEGMENTS:
1364
+ check.error(
1365
+ f"route '{route}' starts with '/{route.split('/')[1]}', which belongs "
1366
+ "to another surface of the product"
1367
+ )
1368
+ language = root.get("language")
1369
+ if not isinstance(language, str) or not LANGUAGE_PATTERN.fullmatch(language):
1370
+ check.error("language must be a language tag such as en, es, or pt-BR")
1371
+ check.copy(root.get("title"), "title")
1372
+
1373
+ ui = check.mapping(root.get("ui"), "ui", required=("back", "progress"))
1374
+ if ui is not None:
1375
+ check.copy(ui.get("back"), "ui.back")
1376
+ if check.copy(ui.get("progress"), "ui.progress"):
1377
+ for placeholder in ("{current}", "{total}"):
1378
+ if placeholder not in ui["progress"]:
1379
+ check.error(f"ui.progress must contain the placeholder {placeholder}")
1380
+
1381
+ inputs = _validate_inputs(check, root.get("inputs"))
1382
+ facts["consent_geographies"] = sorted(
1383
+ {code for code in inputs["geographies"] if code in CONSENT_GEOGRAPHIES}
1384
+ )
1385
+ goal = _validate_goal(check, root.get("goal"))
1386
+ proof = _validate_proof(check, root.get("proof"))
1387
+ used_proof: set[str] = set()
1388
+ questions, rule_sets, screen_ids = _validate_screens(
1389
+ check, root.get("screens"), proof, used_proof
1390
+ )
1391
+ result_rules = _validate_results(
1392
+ check,
1393
+ root.get("results"),
1394
+ questions,
1395
+ proof,
1396
+ used_proof,
1397
+ goal,
1398
+ inputs["not_for"],
1399
+ screen_ids,
1400
+ )
1401
+ for proof_id in sorted(set(proof) - used_proof):
1402
+ check.error(f"proof '{proof_id}' is not shown on any screen or result")
1403
+ for screen_id, question in questions.items():
1404
+ if question["purpose"] in ("personalize", "qualify") and screen_id not in check.referenced:
1405
+ check.warn(
1406
+ "unused_answer",
1407
+ screen_id,
1408
+ f"question '{screen_id}' has the purpose '{question['purpose']}' "
1409
+ "but no rule or token uses its answer",
1410
+ )
1411
+ if not check.errors:
1412
+ # Rules and claims are only comparable once every reference is known to be valid.
1413
+ _validate_reachability(check, root["results"], rule_sets, result_rules, questions)
1414
+ _validate_claims(check, inputs)
1415
+
1416
+ facts["reachability"] = check.reachability
1417
+ return check.errors, check.warnings, facts
1418
+
1419
+
1420
+ def _used_proof_ids(spec: dict[str, Any]) -> list[str]:
1421
+ ordered: list[str] = []
1422
+ holders: list[dict[str, Any]] = []
1423
+ for screen in spec["screens"]:
1424
+ holders.append(screen)
1425
+ holders.extend(screen.get("variants", []))
1426
+ holders.extend(spec["results"])
1427
+ for holder in holders:
1428
+ for proof_id in holder.get("proof_ids", []):
1429
+ if proof_id not in ordered:
1430
+ ordered.append(proof_id)
1431
+ return ordered
1432
+
1433
+
1434
+ def public_spec(spec: dict[str, Any], digest: str) -> dict[str, Any]:
1435
+ """Project the part of a valid specification that the page renders."""
1436
+ proof_by_id = {item["id"]: item for item in spec["proof"]}
1437
+ proof = {}
1438
+ for proof_id in _used_proof_ids(spec):
1439
+ item = proof_by_id[proof_id]
1440
+ proof[proof_id] = {
1441
+ key: item[key] for key in ("kind", "text", "author", "citation") if key in item
1442
+ }
1443
+ def shown(item: dict[str, Any]) -> dict[str, Any]:
1444
+ # `purpose` explains the design and the `source` of an image is a note
1445
+ # for the owner; the page needs neither. `sensitive` stays: the page
1446
+ # keeps the chosen option of such a question private.
1447
+ public_item = {key: value for key, value in item.items() if key != "purpose"}
1448
+ if "media" in item:
1449
+ public_item["media"] = {key: item["media"][key] for key in ("src", "alt")}
1450
+ if "variants" in item:
1451
+ public_item["variants"] = [shown(variant) for variant in item["variants"]]
1452
+ return public_item
1453
+
1454
+ screens = [shown(screen) for screen in spec["screens"]]
1455
+ public = {
1456
+ "contract": PUBLIC_CONTRACT,
1457
+ "quiz_slug": spec["quiz_slug"],
1458
+ "product_slug": spec["product_slug"],
1459
+ "route": spec["route"],
1460
+ "language": spec["language"],
1461
+ "title": spec["title"],
1462
+ "ui": spec["ui"],
1463
+ "goal": {
1464
+ "type": spec["goal"]["type"],
1465
+ "destination": spec["goal"]["destination"],
1466
+ },
1467
+ "proof": proof,
1468
+ "screens": screens,
1469
+ "results": [shown(result) for result in spec["results"]],
1470
+ }
1471
+ # `spec_sha256` names the specification this was compiled from.
1472
+ # `public_sha256` changes only when the page itself changes; saved progress
1473
+ # of a visitor is valid for one value of it.
1474
+ return {
1475
+ "contract": PUBLIC_CONTRACT,
1476
+ "spec_sha256": digest,
1477
+ "public_sha256": _sha256(_canonical_json(public)),
1478
+ **{key: value for key, value in public.items() if key != "contract"},
1479
+ }
1480
+
1481
+
1482
+ def _cell(value: Any) -> str:
1483
+ return str(value).replace("|", "\\|").replace("\n", " ").strip()
1484
+
1485
+
1486
+ def _option_label(questions: dict[str, dict[str, Any]], screen_id: str, option_id: str) -> str:
1487
+ for option in questions[screen_id]["options"]:
1488
+ if option["id"] == option_id:
1489
+ return option["label"]
1490
+ return option_id
1491
+
1492
+
1493
+ def _describe_when(
1494
+ when: dict[str, Any] | None, questions: dict[str, dict[str, Any]], default: str
1495
+ ) -> str:
1496
+ if when is None:
1497
+ return default
1498
+ mode = next(iter(when))
1499
+ parts = []
1500
+ for condition in when[mode]:
1501
+ operator = "any_of" if "any_of" in condition else "none_of"
1502
+ option_ids = condition[operator]
1503
+ labels = ", ".join(
1504
+ f"\"{_option_label(questions, condition['screen'], option_id)}\""
1505
+ for option_id in option_ids
1506
+ )
1507
+ if len(option_ids) == 1:
1508
+ verb = "is" if operator == "any_of" else "is not"
1509
+ else:
1510
+ verb = "is one of" if operator == "any_of" else "is none of"
1511
+ parts.append(f"`{condition['screen']}` {verb} {labels}")
1512
+ joiner = " and " if mode == "all" else " or "
1513
+ return "Shown when " + joiner.join(parts) + "."
1514
+
1515
+
1516
+ def _describe_destination(destination: dict[str, Any]) -> str:
1517
+ kind = destination["kind"]
1518
+ if kind == "booking_url":
1519
+ return f"booking page {destination['url']}"
1520
+ if kind == "lead_form":
1521
+ fields = ", ".join(destination["fields"])
1522
+ return f"request form ({fields}) posting to `{destination['action']}`"
1523
+ if kind == "signup":
1524
+ return f"signup at `{destination['path']}`"
1525
+ if kind == "checkout":
1526
+ return (
1527
+ f"checkout at `{destination['path']}` for the plan "
1528
+ f"`{destination['plan_key']}` at {destination['price']}"
1529
+ )
1530
+ return destination.get("path") or destination.get("url", "")
1531
+
1532
+
1533
+ def _render_texts(lines: list[str], item: dict[str, Any]) -> None:
1534
+ if "headline" in item:
1535
+ lines.extend([f"**{item['headline']}**", ""])
1536
+ if "body" in item:
1537
+ lines.extend([item["body"], ""])
1538
+ if "points" in item:
1539
+ lines.extend(f"- {point}" for point in item["points"])
1540
+ lines.append("")
1541
+ if "media" in item:
1542
+ media = item["media"]
1543
+ lines.extend(
1544
+ [f"Image: `{media['src']}` — {media['alt']} (source: {media['source']})", ""]
1545
+ )
1546
+ if item.get("proof_ids"):
1547
+ refs = ", ".join(f"`{proof_id}`" for proof_id in item["proof_ids"])
1548
+ lines.extend([f"Proof: {refs}", ""])
1549
+
1550
+
1551
+ def render_markdown(
1552
+ spec: dict[str, Any], facts: dict[str, Any]
1553
+ ) -> str:
1554
+ inputs = spec["inputs"]
1555
+ goal = spec["goal"]
1556
+ offer = inputs["offer"]
1557
+ traffic = inputs["traffic"]
1558
+ questions = {
1559
+ screen["id"]: screen for screen in spec["screens"] if screen["type"] == "question"
1560
+ }
1561
+ consent = facts["consent_geographies"]
1562
+ lines = [
1563
+ f"# {spec['title']}",
1564
+ "",
1565
+ "Rendered from `quiz.json`. Edit the specification and compile it again; "
1566
+ "do not edit this file.",
1567
+ "",
1568
+ "## Summary",
1569
+ "",
1570
+ f"- **Product:** {inputs['product']}",
1571
+ f"- **Application:** {inputs['application']['url']} "
1572
+ f"(repository `{inputs['application']['repository']}`)",
1573
+ f"- **Segment:** {inputs['segment']['name']} — {inputs['segment']['situation']} "
1574
+ f"Problem: {inputs['segment']['problem']}",
1575
+ f"- **Offer:** {offer['promise']} Mechanism: {offer['mechanism']} "
1576
+ f"Terms: {offer['terms']}",
1577
+ f"- **Goal:** {goal['type']} — {_describe_destination(goal['destination'])}",
1578
+ f"- **Route:** `{spec['route']}`",
1579
+ f"- **Language:** {spec['language']}",
1580
+ f"- **Traffic:** {', '.join(traffic['channels'])} in "
1581
+ f"{', '.join(traffic['geographies'])}"
1582
+ + (f"; arriving promise: {traffic['promise']}" if "promise" in traffic else ""),
1583
+ "- **Consent:** "
1584
+ + (
1585
+ f"required in {', '.join(consent)} before tracking beyond what is "
1586
+ "strictly necessary"
1587
+ if consent
1588
+ else "no planned geography is on the consent list"
1589
+ ),
1590
+ f"- **Length:** {len(questions)} questions, "
1591
+ f"{len(spec['screens']) - len(questions)} interstitial screens, "
1592
+ f"{len(spec['results'])} results",
1593
+ "",
1594
+ ]
1595
+ for title, items in (
1596
+ ("The offer is not for:", offer["not_for"]),
1597
+ ("Claims to avoid:", offer["claims_to_avoid"]),
1598
+ ):
1599
+ if items:
1600
+ lines.extend([title, ""])
1601
+ lines.extend(f"- {item}" for item in items)
1602
+ lines.append("")
1603
+
1604
+ lines.extend(["## Proof", ""])
1605
+ if spec["proof"]:
1606
+ lines.extend(["| Id | Kind | Shown text | Source |", "|---|---|---|---|"])
1607
+ for item in spec["proof"]:
1608
+ shown = item["text"]
1609
+ if "author" in item:
1610
+ shown += f" — {item['author']}"
1611
+ if "citation" in item:
1612
+ shown += f" ({item['citation']})"
1613
+ lines.append(
1614
+ f"| `{item['id']}` | {item['kind']} | {_cell(shown)} | "
1615
+ f"{_cell(item['source'])} |"
1616
+ )
1617
+ else:
1618
+ lines.append("No proof is shown.")
1619
+ lines.append("")
1620
+
1621
+ lines.extend(["## Flow", ""])
1622
+ for index, screen in enumerate(spec["screens"], start=1):
1623
+ if screen["type"] == "question":
1624
+ traits = [f"{screen['select']}-select"]
1625
+ if screen.get("purpose"):
1626
+ traits.append(screen["purpose"])
1627
+ if screen.get("sensitive"):
1628
+ traits.append("sensitive")
1629
+ lines.append(f"### {index}. `{screen['id']}` — question ({', '.join(traits)})")
1630
+ lines.append("")
1631
+ if "lead" in screen:
1632
+ lines.extend([f"Lead: {screen['lead']}", ""])
1633
+ lines.extend([f"**{screen['headline']}**", ""])
1634
+ if "hint" in screen:
1635
+ lines.extend([f"Hint: {screen['hint']}", ""])
1636
+ for option in screen["options"]:
1637
+ notes = []
1638
+ if "phrase" in option:
1639
+ notes.append(f"in a sentence: \"{option['phrase']}\"")
1640
+ if option.get("escape"):
1641
+ notes.append("escape")
1642
+ suffix = f" _({'; '.join(notes)})_" if notes else ""
1643
+ lines.append(f"- `{option['id']}` {option['label']}{suffix}")
1644
+ lines.append("")
1645
+ if screen["select"] == "multi":
1646
+ lines.extend([f"Button: {screen['button']}", ""])
1647
+ continue
1648
+ lines.append(f"### {index}. `{screen['id']}` — interstitial ({screen['kind']})")
1649
+ lines.append("")
1650
+ _render_texts(lines, screen)
1651
+ lines.extend([f"Button: {screen['button']}", ""])
1652
+ for variant in screen.get("variants", []):
1653
+ lines.extend(
1654
+ [
1655
+ "Variant. "
1656
+ + _describe_when(variant["when"], questions, "")
1657
+ + " It replaces:",
1658
+ "",
1659
+ ]
1660
+ )
1661
+ _render_texts(lines, variant)
1662
+
1663
+ lines.extend(["## Results", ""])
1664
+ for result in spec["results"]:
1665
+ lines.extend(
1666
+ [
1667
+ f"### `{result['id']}` — {result['fit']}",
1668
+ "",
1669
+ _describe_when(
1670
+ result.get("when"),
1671
+ questions,
1672
+ "Default: shown when no earlier result matches.",
1673
+ ),
1674
+ "",
1675
+ ]
1676
+ )
1677
+ if result["fit"] == "not_fit":
1678
+ lines.extend(
1679
+ [
1680
+ "Appears as soon as the answers decide it: the questions after "
1681
+ "the deciding one are skipped.",
1682
+ "",
1683
+ ]
1684
+ )
1685
+ _render_texts(lines, result)
1686
+ cta = result["cta"]
1687
+ if cta is None:
1688
+ lines.append("No call to action.")
1689
+ elif "destination" in cta:
1690
+ lines.append(
1691
+ f"Call to action: {cta['label']} → "
1692
+ f"{_describe_destination(cta['destination'])}"
1693
+ )
1694
+ else:
1695
+ lines.append(f"Call to action: {cta['label']} → goal destination")
1696
+ if cta and "note" in cta:
1697
+ lines.extend(["", f"Note under the button: {cta['note']}"])
1698
+ lines.append("")
1699
+
1700
+ return "\n".join(lines)
1701
+
1702
+
1703
+ def _atomic_write(path: Path, content: str) -> None:
1704
+ path.parent.mkdir(parents=True, exist_ok=True)
1705
+ descriptor, temporary_name = tempfile.mkstemp(
1706
+ prefix=f".{path.name}.", dir=str(path.parent), text=True
1707
+ )
1708
+ try:
1709
+ with os.fdopen(descriptor, "w", encoding="utf-8") as handle:
1710
+ handle.write(content)
1711
+ # mkstemp creates owner-only files; artifacts are ordinary documents.
1712
+ os.chmod(temporary_name, 0o644)
1713
+ os.replace(temporary_name, path)
1714
+ except BaseException:
1715
+ try:
1716
+ os.unlink(temporary_name)
1717
+ except FileNotFoundError:
1718
+ pass
1719
+ raise
1720
+
1721
+
1722
+ def _format_problems(errors: list[str], warnings: list[dict[str, str]]) -> str:
1723
+ lines = ["Quiz specification is not ready:"]
1724
+ lines.extend(f"- {message}" for message in errors)
1725
+ for item in warnings:
1726
+ lines.append(f"- [{item['rule']} @ {item['target']}] {item['message']}")
1727
+ return "\n".join(lines)
1728
+
1729
+
1730
+ def _load(folder: Path) -> Any:
1731
+ spec_path = folder / "quiz.json"
1732
+ try:
1733
+ spec = json.loads(spec_path.read_text(encoding="utf-8"))
1734
+ except FileNotFoundError as exc:
1735
+ raise SpecError(f"specification does not exist: {spec_path}") from exc
1736
+ except (json.JSONDecodeError, UnicodeDecodeError, RecursionError) as exc:
1737
+ raise SpecError(f"specification is not valid JSON: {exc}") from exc
1738
+ return spec
1739
+
1740
+
1741
+ def failure_receipt(quiz_slug: str, today: date, problem: SpecError) -> str:
1742
+ """The `validation.json` text that records why a compile was not ready."""
1743
+ receipt = {
1744
+ "contract": REPORT_CONTRACT,
1745
+ "status": "not_ready",
1746
+ "validated_on": today.isoformat(),
1747
+ "quiz_slug": quiz_slug,
1748
+ "problems": str(problem).splitlines()[1:] or [str(problem)],
1749
+ }
1750
+ return json.dumps(receipt, indent=2, ensure_ascii=False) + "\n"
1751
+
1752
+
1753
+ def compile_spec(
1754
+ spec: Any, quiz_slug: str, today: date
1755
+ ) -> tuple[dict[str, Any], dict[str, str]]:
1756
+ """Compile a parsed specification without touching the filesystem.
1757
+
1758
+ Returns the validation report and the exact text of each artifact keyed by
1759
+ file name. Raises SpecError when the specification is not ready.
1760
+ """
1761
+ try:
1762
+ errors, warnings, facts = validate_spec(spec)
1763
+ except RecursionError as exc:
1764
+ raise SpecError("specification is nested too deeply") from exc
1765
+ if isinstance(spec, dict) and spec.get("quiz_slug") not in (None, quiz_slug):
1766
+ errors.append(
1767
+ f"quiz_slug '{spec.get('quiz_slug')}' does not match its folder "
1768
+ f"'{quiz_slug}'"
1769
+ )
1770
+ if errors:
1771
+ raise SpecError(_format_problems(errors, warnings))
1772
+
1773
+ digest = _sha256(_canonical_json(spec))
1774
+ public = public_spec(spec, digest)
1775
+ questions = [screen for screen in spec["screens"] if screen["type"] == "question"]
1776
+ report = {
1777
+ "contract": REPORT_CONTRACT,
1778
+ "status": "ready",
1779
+ "validated_on": today.isoformat(),
1780
+ "quiz_slug": spec["quiz_slug"],
1781
+ "route": spec["route"],
1782
+ "goal": spec["goal"]["type"],
1783
+ "destination": spec["goal"]["destination"]["kind"],
1784
+ "spec_sha256": digest,
1785
+ "public_sha256": public["public_sha256"],
1786
+ "counts": {
1787
+ "screens": len(spec["screens"]),
1788
+ "questions": len(questions),
1789
+ "interstitials": len(spec["screens"]) - len(questions),
1790
+ "results": len(spec["results"]),
1791
+ "proof": len(spec["proof"]),
1792
+ },
1793
+ "consent_geographies": facts["consent_geographies"],
1794
+ "reachability": facts["reachability"],
1795
+ "warnings": warnings,
1796
+ }
1797
+ files = {
1798
+ "QUIZ.md": render_markdown(spec, facts),
1799
+ "quiz.public.json": json.dumps(public, indent=2, ensure_ascii=False) + "\n",
1800
+ "validation.json": json.dumps(report, indent=2, ensure_ascii=False) + "\n",
1801
+ }
1802
+ return report, files
1803
+
1804
+
1805
+ def compile_quiz(
1806
+ workspace: Path, quiz_slug: str, today: date, *, check_only: bool = False
1807
+ ) -> dict[str, Any]:
1808
+ if not SLUG_PATTERN.fullmatch(quiz_slug):
1809
+ raise SpecError("--quiz-slug must be a slug of lowercase letters, digits and '-'")
1810
+ folder = workspace / 'egbe-docs/product/quizzes' / quiz_slug
1811
+ try:
1812
+ report, files = compile_spec(_load(folder), quiz_slug, today)
1813
+ except SpecError as problem:
1814
+ if not check_only and folder.is_dir():
1815
+ # What an earlier version compiled must not outlive a failed compile.
1816
+ for name in PAGE_FILES:
1817
+ (folder / name).unlink(missing_ok=True)
1818
+ _atomic_write(folder / "validation.json", failure_receipt(quiz_slug, today, problem))
1819
+ raise
1820
+
1821
+ if not check_only:
1822
+ for name, content in files.items():
1823
+ _atomic_write(folder / name, content)
1824
+ return report
1825
+
1826
+
1827
+ def main() -> int:
1828
+ parser = argparse.ArgumentParser(
1829
+ description="Validate a quiz funnel specification and render its artifacts."
1830
+ )
1831
+ parser.add_argument(
1832
+ "--workspace",
1833
+ required=True,
1834
+ type=Path,
1835
+ help="Root that contains egbe-docs/product/quizzes/<quiz-slug>/",
1836
+ )
1837
+ parser.add_argument("--quiz-slug", required=True, help="Folder name of the quiz")
1838
+ parser.add_argument(
1839
+ "--today",
1840
+ type=date.fromisoformat,
1841
+ default=None,
1842
+ help="Reference date for reproducible tests (default: current UTC date)",
1843
+ )
1844
+ parser.add_argument(
1845
+ "--check",
1846
+ action="store_true",
1847
+ help="Validate only; write and remove nothing",
1848
+ )
1849
+ args = parser.parse_args()
1850
+ today = args.today or datetime.now(timezone.utc).date()
1851
+
1852
+ try:
1853
+ report = compile_quiz(
1854
+ args.workspace, args.quiz_slug, today, check_only=args.check
1855
+ )
1856
+ except (OSError, SpecError) as exc:
1857
+ print(str(exc), file=sys.stderr)
1858
+ return 2
1859
+ counts = report["counts"]
1860
+ print(
1861
+ f"Quiz specification ready: goal={report['goal']} "
1862
+ f"questions={counts['questions']} results={counts['results']} "
1863
+ f"sha256={report['spec_sha256']}"
1864
+ )
1865
+ return 0
1866
+
1867
+
1868
+ if __name__ == "__main__":
1869
+ raise SystemExit(main())