oneie 2.0.2 → 2.0.5

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 (459) hide show
  1. package/AGENTS.md +245 -0
  2. package/CLAUDE.md +725 -0
  3. package/LICENSE.md +84 -0
  4. package/README.md +489 -931
  5. package/folders.yaml +78 -17
  6. package/one/.obsidian/app.json +1 -0
  7. package/one/.obsidian/appearance.json +1 -0
  8. package/one/.obsidian/core-plugins.json +33 -0
  9. package/one/.obsidian/workspace.json +211 -0
  10. package/one/connections/a2a.md +551 -0
  11. package/one/connections/acp.md +761 -0
  12. package/one/connections/acps.md +731 -0
  13. package/one/connections/agentkit.md +349 -0
  14. package/one/connections/agui.md +767 -0
  15. package/one/connections/any-backend.md +1702 -0
  16. package/one/connections/ap2.md +998 -0
  17. package/one/connections/api-docs.md +1891 -0
  18. package/one/connections/api.md +2190 -0
  19. package/one/connections/architecture-diagram.md +94 -0
  20. package/one/connections/communications.md +449 -0
  21. package/one/connections/connections.md +339 -0
  22. package/one/connections/copilotkit.md +1559 -0
  23. package/one/connections/cryptonetworks.md +781 -0
  24. package/one/connections/documentation.md +1120 -0
  25. package/one/connections/effect.md +279 -0
  26. package/one/connections/elizaos.md +1290 -0
  27. package/one/connections/inference.md +58 -0
  28. package/one/connections/kyc.md +632 -0
  29. package/one/connections/mcp.md +842 -0
  30. package/one/connections/membership.md +1152 -0
  31. package/one/connections/middleware.md +1067 -0
  32. package/one/connections/multitenant.md +1341 -0
  33. package/one/connections/n8n.md +1015 -0
  34. package/one/connections/patterns.md +89 -0
  35. package/one/connections/protocols.md +279 -0
  36. package/one/connections/relationships.md +107 -0
  37. package/one/connections/schema.md +587 -0
  38. package/one/connections/service-layer.md +550 -0
  39. package/one/connections/structure.md +0 -0
  40. package/one/connections/vectors.md +207 -0
  41. package/one/connections/wordpress.md +1302 -0
  42. package/one/connections/workflow-copy.md +905 -0
  43. package/one/connections/workflow-examples.md +741 -0
  44. package/one/connections/workflow.md +905 -0
  45. package/one/connections/workflows/delegation.md +885 -0
  46. package/one/connections/workflows/frontend.md +1037 -0
  47. package/one/connections/workflows/strategy.md +903 -0
  48. package/one/connections/workflows/tasks.md +698 -0
  49. package/one/connections/x402.md +1249 -0
  50. package/one/events/CASCADE-2-BACKEND-AGNOSTIC.md +412 -0
  51. package/one/events/FEATURE-2-4-COMPLETE.md +302 -0
  52. package/one/events/FEATURE_2_3_COMPLETE.md +575 -0
  53. package/one/events/GROUPS-MIGRATION.md +625 -0
  54. package/one/events/INSTALL-TESTS.md +293 -0
  55. package/one/events/INTEGRATION-ARCHITECTURE.md +561 -0
  56. package/one/events/INTEGRATION-CHECKLIST.md +1234 -0
  57. package/one/events/INTEGRATION-ORCHESTRATION.md +2623 -0
  58. package/one/events/INTEGRATION-SUMMARY.md +653 -0
  59. package/one/events/MIGRATION-REPORT.md +435 -0
  60. package/one/events/MIGRATION.md +69 -0
  61. package/one/events/README-archived.md +519 -0
  62. package/one/events/TEST-SUMMARY.md +393 -0
  63. package/one/events/TESTS-QUICK-REF.md +262 -0
  64. package/one/events/events.md +545 -0
  65. package/one/groups/groups.md +543 -0
  66. package/one/groups/one.md +599 -0
  67. package/one/groups/revenue.md +673 -0
  68. package/one/groups/strategy.md +869 -0
  69. package/one/groups/vision.md +98 -0
  70. package/one/knowledge/CLOUDFLARE_ENV_SETUP.md +49 -0
  71. package/one/knowledge/ai-platform.md +305 -0
  72. package/one/knowledge/architecture-any-backend.md +1366 -0
  73. package/one/knowledge/architecture-diagram.md +94 -0
  74. package/one/knowledge/architecture-frontend.md +930 -0
  75. package/one/knowledge/architecture.md +2077 -0
  76. package/one/knowledge/crypto.md +960 -0
  77. package/one/knowledge/docs/flow.md +0 -0
  78. package/one/knowledge/dsl.md +1660 -0
  79. package/one/knowledge/files.md +2471 -0
  80. package/one/knowledge/frontend.md +1038 -0
  81. package/one/knowledge/hono.md +2109 -0
  82. package/one/knowledge/implementation-examples.md +2536 -0
  83. package/one/knowledge/inference-score.md +159 -0
  84. package/one/knowledge/knowledge.md +642 -0
  85. package/one/knowledge/language.md +980 -0
  86. package/one/knowledge/lessons-learned.md +70 -0
  87. package/one/knowledge/ontology-6-dimensions.md +0 -0
  88. package/one/knowledge/ontology-documentation.md +356 -0
  89. package/one/knowledge/ontology-engineering-specification.md +1292 -0
  90. package/one/knowledge/ontology-engineering.md +1652 -0
  91. package/one/knowledge/ontology-frontend-copy-2.md +1492 -0
  92. package/one/knowledge/ontology-frontend-copy.md +753 -0
  93. package/one/knowledge/ontology-frontend-specifications.md +2188 -0
  94. package/one/knowledge/ontology-frontend.md +2427 -0
  95. package/one/knowledge/ontology-minimal.yaml +299 -0
  96. package/one/knowledge/ontology.md +2830 -0
  97. package/one/knowledge/ontology.md.backup +2822 -0
  98. package/one/knowledge/ontology.yaml +1165 -0
  99. package/one/knowledge/patterns/backend/convex-mutation-pattern.md +100 -0
  100. package/one/knowledge/patterns/backend/convex-query-pattern.md +88 -0
  101. package/one/knowledge/patterns/backend/mutation-template.md +231 -0
  102. package/one/knowledge/patterns/backend/query-template.md +267 -0
  103. package/one/knowledge/patterns/backend/service-template.md +237 -0
  104. package/one/knowledge/patterns/design/component-architecture.md +399 -0
  105. package/one/knowledge/patterns/design/test-driven-design-pattern.md +162 -0
  106. package/one/knowledge/patterns/design/wireframe-template.md +216 -0
  107. package/one/knowledge/patterns/frontend/component-template.md +195 -0
  108. package/one/knowledge/patterns/frontend/form-template.md +276 -0
  109. package/one/knowledge/patterns/frontend/page-template.md +178 -0
  110. package/one/knowledge/patterns/frontend/react-component-pattern.md +128 -0
  111. package/one/knowledge/patterns/test/acceptance-criteria-template.md +378 -0
  112. package/one/knowledge/patterns/test/technical-test-template.md +544 -0
  113. package/one/knowledge/patterns/test/test-driven-pattern.md +140 -0
  114. package/one/knowledge/patterns/test/user-flow-template.md +254 -0
  115. package/one/knowledge/provider-creation-guide.md +1064 -0
  116. package/one/knowledge/quality-loop.md +401 -0
  117. package/one/knowledge/readme.md +131 -0
  118. package/one/knowledge/rules.md +626 -0
  119. package/one/knowledge/score.md +67 -0
  120. package/one/knowledge/specifications.md +855 -0
  121. package/one/knowledge/tags.md +130 -0
  122. package/one/knowledge/todo.md +251 -0
  123. package/one/license.md +84 -0
  124. package/one/people/anthony-o-connell.md +440 -0
  125. package/one/people/people.md +567 -0
  126. package/one/things/CHECKLIST.md +356 -0
  127. package/one/things/ONE.md +510 -0
  128. package/one/things/agents/agent-backend.md +1401 -0
  129. package/one/things/agents/agent-builder.md +955 -0
  130. package/one/things/agents/agent-clean.md +709 -0
  131. package/one/things/agents/agent-clone.md +1341 -0
  132. package/one/things/agents/agent-designer.md +2177 -0
  133. package/one/things/agents/agent-director.md +1508 -0
  134. package/one/things/agents/agent-documenter.md +1049 -0
  135. package/one/things/agents/agent-frontend.md +1119 -0
  136. package/one/things/agents/agent-integrator.md +1192 -0
  137. package/one/things/agents/agent-problem-solver.md +1379 -0
  138. package/one/things/agents/agent-quality.md +1353 -0
  139. package/one/things/agents/agent-sales.md +986 -0
  140. package/one/things/cascade/cascade.yaml +464 -0
  141. package/one/things/cascade/docs/examples/1-1-agent-prompts/design.md +470 -0
  142. package/one/things/cascade/docs/examples/1-1-agent-prompts/tests.md +264 -0
  143. package/one/things/cascade/docs/examples/1-1-agent-prompts.md +486 -0
  144. package/one/things/cascade/docs/examples/1-2-yaml-orchestrator/design.md +497 -0
  145. package/one/things/cascade/docs/examples/1-2-yaml-orchestrator/tests.md +227 -0
  146. package/one/things/cascade/docs/examples/1-2-yaml-orchestrator.md +516 -0
  147. package/one/things/cascade/docs/examples/1-3-event-coordination/design.md +544 -0
  148. package/one/things/cascade/docs/examples/1-3-event-coordination/tests.md +223 -0
  149. package/one/things/cascade/docs/examples/1-3-event-coordination.md +508 -0
  150. package/one/things/cascade/docs/examples/1-4-knowledge-management/design.md +609 -0
  151. package/one/things/cascade/docs/examples/1-4-knowledge-management/tests.md +195 -0
  152. package/one/things/cascade/docs/examples/1-4-knowledge-management.md +577 -0
  153. package/one/things/cascade/docs/examples/1-5-quality-loops/design.md +797 -0
  154. package/one/things/cascade/docs/examples/1-5-quality-loops/tests.md +212 -0
  155. package/one/things/cascade/docs/examples/1-5-quality-loops.md +641 -0
  156. package/one/things/cascade/docs/examples/1-6-numbering-structure/design.md +610 -0
  157. package/one/things/cascade/docs/examples/1-6-numbering-structure/tests.md +213 -0
  158. package/one/things/cascade/docs/examples/1-6-numbering-structure.md +575 -0
  159. package/one/things/cascade/docs/examples/readme.md +222 -0
  160. package/one/things/cascade/docs/getting-started.md +515 -0
  161. package/one/things/cascade/docs/workflow.md +1372 -0
  162. package/one/things/cascade/readme.md +336 -0
  163. package/one/things/cascade/templates/feature-template.md +267 -0
  164. package/one/things/claude/agents/advocacy-activation-manager.md +685 -0
  165. package/one/things/claude/agents/advocacy-campaign-designer.md +663 -0
  166. package/one/things/claude/agents/analyst.md +483 -0
  167. package/one/things/claude/agents/architect.md +480 -0
  168. package/one/things/claude/agents/brand-identity-specialist.md +513 -0
  169. package/one/things/claude/agents/bstp-token-strategist.md +667 -0
  170. package/one/things/claude/agents/builder-repo.md +489 -0
  171. package/one/things/claude/agents/bullstamp-community-builder.md +574 -0
  172. package/one/things/claude/agents/bullstamp-marketing-orchestrator.md +506 -0
  173. package/one/things/claude/agents/bulltilt-platform-growth.md +567 -0
  174. package/one/things/claude/agents/company-bullstamp-character.md +587 -0
  175. package/one/things/claude/agents/company-bullstamp-community.md +292 -0
  176. package/one/things/claude/agents/company-bullstamp-marketing.md +292 -0
  177. package/one/things/claude/agents/company-bullstamp-token.md +292 -0
  178. package/one/things/claude/agents/company-bulltilt-growth.md +292 -0
  179. package/one/things/claude/agents/content-bibliography-formatter.md +381 -0
  180. package/one/things/claude/agents/content-calendar-planner.md +448 -0
  181. package/one/things/claude/agents/content-chapter-formatter.md +488 -0
  182. package/one/things/claude/agents/content-formatter.md +546 -0
  183. package/one/things/claude/agents/content-hook-specialist.md +462 -0
  184. package/one/things/claude/agents/content-image-formatter.md +535 -0
  185. package/one/things/claude/agents/content-introduction-formatter.md +485 -0
  186. package/one/things/claude/agents/content-multiplication-engine.md +556 -0
  187. package/one/things/claude/agents/content-playbook-writer.md +448 -0
  188. package/one/things/claude/agents/content-team-manager.md +622 -0
  189. package/one/things/claude/agents/content-toc-formatter.md +522 -0
  190. package/one/things/claude/agents/convex-backend-specialist.md +2561 -0
  191. package/one/things/claude/agents/core-manager.md +582 -0
  192. package/one/things/claude/agents/core-master.md +403 -0
  193. package/one/things/claude/agents/cross-functional-manager.md +471 -0
  194. package/one/things/claude/agents/crypto-airdrop-strategist.md +602 -0
  195. package/one/things/claude/agents/crypto-analytics-educator.md +553 -0
  196. package/one/things/claude/agents/crypto-architecture-specialist.md +466 -0
  197. package/one/things/claude/agents/crypto-community-analyst.md +298 -0
  198. package/one/things/claude/agents/crypto-community-psychologist.md +509 -0
  199. package/one/things/claude/agents/crypto-dex-optimization-expert.md +538 -0
  200. package/one/things/claude/agents/crypto-dex-optimizer.md +292 -0
  201. package/one/things/claude/agents/crypto-diamond-formation-specialist.md +513 -0
  202. package/one/things/claude/agents/crypto-diamond-hands.md +292 -0
  203. package/one/things/claude/agents/crypto-ecosystem-expansion-manager.md +554 -0
  204. package/one/things/claude/agents/crypto-engagement-specialist.md +540 -0
  205. package/one/things/claude/agents/crypto-market-researcher.md +292 -0
  206. package/one/things/claude/agents/crypto-marketing-orchestrator.md +523 -0
  207. package/one/things/claude/agents/crypto-network-effect-amplifier.md +569 -0
  208. package/one/things/claude/agents/crypto-optimization-analyst.md +554 -0
  209. package/one/things/claude/agents/crypto-strategic-synthesizer.md +517 -0
  210. package/one/things/claude/agents/crypto-team-manager.md +387 -0
  211. package/one/things/claude/agents/crypto-token-analyst.md +278 -0
  212. package/one/things/claude/agents/crypto-viral-content-creator.md +546 -0
  213. package/one/things/claude/agents/crypto-wallet-identification-expert.md +517 -0
  214. package/one/things/claude/agents/crypto-wallet-identifier.md +292 -0
  215. package/one/things/claude/agents/customer-journey-designer.md +481 -0
  216. package/one/things/claude/agents/customer-success-manager.md +581 -0
  217. package/one/things/claude/agents/dev.md +413 -0
  218. package/one/things/claude/agents/documenter.md +546 -0
  219. package/one/things/claude/agents/elevate-marketing-orchestrator.md +410 -0
  220. package/one/things/claude/agents/engagement-specialist.md +509 -0
  221. package/one/things/claude/agents/engineering-architect.md +387 -0
  222. package/one/things/claude/agents/engineering-business-analyst.md +537 -0
  223. package/one/things/claude/agents/engineering-developer.md +387 -0
  224. package/one/things/claude/agents/engineering-director.md +282 -0
  225. package/one/things/claude/agents/engineering-ingestor.md +649 -0
  226. package/one/things/claude/agents/engineering-product-manager.md +537 -0
  227. package/one/things/claude/agents/engineering-product-owner.md +537 -0
  228. package/one/things/claude/agents/engineering-project-coordinator.md +537 -0
  229. package/one/things/claude/agents/engineering-quality-assurance.md +393 -0
  230. package/one/things/claude/agents/engineering-team-manager.md +512 -0
  231. package/one/things/claude/agents/engineering-user-experience.md +387 -0
  232. package/one/things/claude/agents/framework-elevate-manager.md +294 -0
  233. package/one/things/claude/agents/improver.md +763 -0
  234. package/one/things/claude/agents/intelligence-team-manager.md +385 -0
  235. package/one/things/claude/agents/lead-capture-expert.md +466 -0
  236. package/one/things/claude/agents/lead-magnet-creator.md +453 -0
  237. package/one/things/claude/agents/market-research-analyst.md +412 -0
  238. package/one/things/claude/agents/marketing-brand-identity.md +314 -0
  239. package/one/things/claude/agents/marketing-content-hooks.md +450 -0
  240. package/one/things/claude/agents/marketing-content-multiplier.md +326 -0
  241. package/one/things/claude/agents/marketing-content-poster.md +361 -0
  242. package/one/things/claude/agents/marketing-customer-journey.md +326 -0
  243. package/one/things/claude/agents/marketing-director.md +397 -0
  244. package/one/things/claude/agents/marketing-engagement.md +326 -0
  245. package/one/things/claude/agents/marketing-lead-capture.md +326 -0
  246. package/one/things/claude/agents/marketing-lead-magnet.md +326 -0
  247. package/one/things/claude/agents/marketing-network-effects.md +326 -0
  248. package/one/things/claude/agents/marketing-nurture-campaigns.md +326 -0
  249. package/one/things/claude/agents/marketing-share-optimizer.md +326 -0
  250. package/one/things/claude/agents/marketing-team-manager.md +446 -0
  251. package/one/things/claude/agents/marketing-viral-growth.md +201 -0
  252. package/one/things/claude/agents/mission-commander.md +373 -0
  253. package/one/things/claude/agents/network-effect-analyst.md +587 -0
  254. package/one/things/claude/agents/nextjs-15-specialist.md +1547 -0
  255. package/one/things/claude/agents/npx.md +890 -0
  256. package/one/things/claude/agents/nurture-campaign-manager.md +531 -0
  257. package/one/things/claude/agents/one-master.md +355 -0
  258. package/one/things/claude/agents/one-orchestrator.md +315 -0
  259. package/one/things/claude/agents/one.md +601 -0
  260. package/one/things/claude/agents/playbook-generator.md +503 -0
  261. package/one/things/claude/agents/pm.md +326 -0
  262. package/one/things/claude/agents/po.md +345 -0
  263. package/one/things/claude/agents/qa.md +336 -0
  264. package/one/things/claude/agents/research-foundation-analyst.md +307 -0
  265. package/one/things/claude/agents/research-intelligence-gatherer.md +408 -0
  266. package/one/things/claude/agents/research-market-analyst.md +307 -0
  267. package/one/things/claude/agents/research-team-manager.md +482 -0
  268. package/one/things/claude/agents/sales-environment-optimizer.md +494 -0
  269. package/one/things/claude/agents/sales-team-manager.md +400 -0
  270. package/one/things/claude/agents/sales-upsell-strategist.md +307 -0
  271. package/one/things/claude/agents/service-advocacy-campaigns.md +307 -0
  272. package/one/things/claude/agents/service-advocacy-manager.md +307 -0
  273. package/one/things/claude/agents/service-success-manager.md +307 -0
  274. package/one/things/claude/agents/service-team-manager.md +400 -0
  275. package/one/things/claude/agents/shadcn-ui-design-system-specialist.md +2302 -0
  276. package/one/things/claude/agents/share-optimization-specialist.md +551 -0
  277. package/one/things/claude/agents/sm.md +327 -0
  278. package/one/things/claude/agents/story-teller.md +473 -0
  279. package/one/things/claude/agents/task-master.md +596 -0
  280. package/one/things/claude/agents/tauri-cross-platform-specialist.md +1827 -0
  281. package/one/things/claude/agents/tester.md +556 -0
  282. package/one/things/claude/agents/the-bull-character-manager.md +580 -0
  283. package/one/things/claude/agents/tools-playbook-generator.md +489 -0
  284. package/one/things/claude/agents/turbo-repo-builder.md +316 -0
  285. package/one/things/claude/agents/upsell-strategist.md +480 -0
  286. package/one/things/claude/agents/ux-expert.md +335 -0
  287. package/one/things/claude/agents/viral-growth-orchestrator.md +497 -0
  288. package/one/things/claude/claude-code-hooks-development.json +21 -0
  289. package/one/things/claude/claude-code-hooks-production.json +21 -0
  290. package/one/things/claude/claude-code-hooks.json +25 -0
  291. package/one/things/claude/commands/agent.md +104 -0
  292. package/one/things/claude/commands/cascade-status.md +128 -0
  293. package/one/things/claude/commands/ingest.md +290 -0
  294. package/one/things/claude/commands/ingestor.md +136 -0
  295. package/one/things/claude/commands/mission.md +83 -0
  296. package/one/things/claude/commands/npx.md +133 -0
  297. package/one/things/claude/commands/one.md +440 -0
  298. package/one/things/claude/commands/quality-check.md +204 -0
  299. package/one/things/claude/commands/smart-route.md +220 -0
  300. package/one/things/claude/commands/start.md +121 -0
  301. package/one/things/claude/commands/story.md +83 -0
  302. package/one/things/claude/commands/task.md +173 -0
  303. package/one/things/claude/hook-bypass.json +32 -0
  304. package/one/things/claude/hooks/agent-hook-config.json +427 -0
  305. package/one/things/claude/hooks/agent-hook-manager.js +525 -0
  306. package/one/things/claude/hooks/agent-load-balancer.js +271 -0
  307. package/one/things/claude/hooks/agent-request-interceptor.js +70 -0
  308. package/one/things/claude/hooks/build-hook.sh +156 -0
  309. package/one/things/claude/hooks/cascade-feedback.js +297 -0
  310. package/one/things/claude/hooks/cascade-integration-hooks.js +648 -0
  311. package/one/things/claude/hooks/cleanup-hook.sh +201 -0
  312. package/one/things/claude/hooks/continuous-improvement-monitor.js +510 -0
  313. package/one/things/claude/hooks/file-organization-engine.js +427 -0
  314. package/one/things/claude/hooks/file-organization-hook.sh +80 -0
  315. package/one/things/claude/hooks/file-organization-monitor.js +269 -0
  316. package/one/things/claude/hooks/format-hook.sh +43 -0
  317. package/one/things/claude/hooks/hook-bypass.sh +293 -0
  318. package/one/things/claude/hooks/hook-config-manager.js +202 -0
  319. package/one/things/claude/hooks/hook-debouncer.sh +62 -0
  320. package/one/things/claude/hooks/hook-logger.sh +89 -0
  321. package/one/things/claude/hooks/hook-orchestrator.js +662 -0
  322. package/one/things/claude/hooks/hook-performance-report.js +120 -0
  323. package/one/things/claude/hooks/lint-hook.sh +140 -0
  324. package/one/things/claude/hooks/mcp-cascade-integration.js +816 -0
  325. package/one/things/claude/hooks/memory-optimizer.js +510 -0
  326. package/one/things/claude/hooks/notification-hook.sh +204 -0
  327. package/one/things/claude/hooks/ontology-compliance.js +394 -0
  328. package/one/things/claude/hooks/ontology-hook-manager.js +316 -0
  329. package/one/things/claude/hooks/ontology-validation-engine.js +317 -0
  330. package/one/things/claude/hooks/ontology-validation-hook.sh +86 -0
  331. package/one/things/claude/hooks/performance-metrics.json +25 -0
  332. package/one/things/claude/hooks/performance-monitoring-hook.js +422 -0
  333. package/one/things/claude/hooks/quality-scoring-engine.js +834 -0
  334. package/one/things/claude/hooks/security-hook.sh +256 -0
  335. package/one/things/claude/hooks/simple-load-balancer.js +238 -0
  336. package/one/things/claude/hooks/startup-optimizer.js +625 -0
  337. package/one/things/claude/hooks/story-scoring-system.js +445 -0
  338. package/one/things/claude/hooks/story-validation-engine.js +473 -0
  339. package/one/things/claude/hooks/story-validation-hook-enhanced.sh +210 -0
  340. package/one/things/claude/hooks/story-validation-hook.sh +145 -0
  341. package/one/things/claude/hooks/structure-synchronizer.js +194 -0
  342. package/one/things/claude/hooks/sub-agent-output-validator.js +647 -0
  343. package/one/things/claude/hooks/sub-agent-validation-hook.js +343 -0
  344. package/one/things/claude/hooks/test-hook.sh +145 -0
  345. package/one/things/claude/hooks/test-story-validation.sh +170 -0
  346. package/one/things/claude/hooks/trinity-validation-system.js +392 -0
  347. package/one/things/claude/settings-local.json +86 -0
  348. package/one/things/cli/cli-code.md +652 -0
  349. package/one/things/cli/cli-compiler-code.md +652 -0
  350. package/one/things/cli/cli.md +1068 -0
  351. package/one/things/components/card-shadcn.md +929 -0
  352. package/one/things/components/card.md +1050 -0
  353. package/one/things/components.md +1669 -0
  354. package/one/things/componets.md +4 -0
  355. package/one/things/creator-diagram.md +166 -0
  356. package/one/things/examples/children/lemonade-stand.md +366 -0
  357. package/one/things/examples/enterprise/crm-saas.md +1429 -0
  358. package/one/things/features/1-1-agent-prompts/design.md +470 -0
  359. package/one/things/features/1-1-agent-prompts/tests.md +264 -0
  360. package/one/things/features/1-1-agent-prompts.md +486 -0
  361. package/one/things/features/1-2-yaml-orchestrator/design.md +497 -0
  362. package/one/things/features/1-2-yaml-orchestrator/tests.md +227 -0
  363. package/one/things/features/1-2-yaml-orchestrator.md +516 -0
  364. package/one/things/features/1-3-event-coordination/design.md +544 -0
  365. package/one/things/features/1-3-event-coordination/tests.md +223 -0
  366. package/one/things/features/1-3-event-coordination.md +508 -0
  367. package/one/things/features/1-4-knowledge-management/design.md +609 -0
  368. package/one/things/features/1-4-knowledge-management/tests.md +195 -0
  369. package/one/things/features/1-4-knowledge-management.md +577 -0
  370. package/one/things/features/1-5-quality-loops/design.md +797 -0
  371. package/one/things/features/1-5-quality-loops/tests.md +212 -0
  372. package/one/things/features/1-5-quality-loops.md +641 -0
  373. package/one/things/features/1-6-numbering-structure/design.md +610 -0
  374. package/one/things/features/1-6-numbering-structure/tests.md +213 -0
  375. package/one/things/features/1-6-numbering-structure.md +575 -0
  376. package/one/things/features/2-1-dataprovider-interface.md +2358 -0
  377. package/one/things/features/2-2-config-system.md +3075 -0
  378. package/one/things/features/2-3-effectts-services.md +1498 -0
  379. package/one/things/features/2-4-react-hooks.md +2120 -0
  380. package/one/things/features/2-5-auth-migration.md +2046 -0
  381. package/one/things/features/2-6-dashboard-migration.md +1985 -0
  382. package/one/things/features/2-7-alternative-providers.md +2505 -0
  383. package/one/things/features/2-7-implementation-report.md +680 -0
  384. package/one/things/features/2-cli.md +1235 -0
  385. package/one/things/features/2-design.md +1738 -0
  386. package/one/things/features/2-tests.md +520 -0
  387. package/one/things/features/AUTH_HOOKS_IMPLEMENTATION.md +521 -0
  388. package/one/things/features/DECOUPLING.md +272 -0
  389. package/one/things/features/DEPLOYMENT.md +452 -0
  390. package/one/things/features/IMPLEMENTATION_SUMMARY.md +316 -0
  391. package/one/things/features/dataprovider-interface/1-tests.md +1522 -0
  392. package/one/things/features/improve.md +843 -0
  393. package/one/things/features/remove-convex-deps.md +45 -0
  394. package/one/things/features/top-features.md +79 -0
  395. package/one/things/features/use-one-backend.md +1180 -0
  396. package/one/things/ideas/1-create-workflow.md +189 -0
  397. package/one/things/ideas/2-backend-agnostic-frontend.md +384 -0
  398. package/one/things/plans/1-create-workflow-status.md +555 -0
  399. package/one/things/plans/1-create-workflow.md +713 -0
  400. package/one/things/plans/2-backend-agnostic-frontend.md +543 -0
  401. package/one/things/plans/3-groups.md +502 -0
  402. package/one/things/plans/app.md +761 -0
  403. package/one/things/plans/backend-agnostic-frontend.md +323 -0
  404. package/one/things/plans/better-auth-any-backend-revised.md +1065 -0
  405. package/one/things/plans/better-auth-any-backend.md +1852 -0
  406. package/one/things/plans/better-auth-available-features.md +235 -0
  407. package/one/things/plans/big-plan.md +38 -0
  408. package/one/things/plans/convex-better-auth.md +1109 -0
  409. package/one/things/plans/convex-on-off.md +389 -0
  410. package/one/things/plans/deploy-to-cloudflare.md +581 -0
  411. package/one/things/plans/desktop.md +1121 -0
  412. package/one/things/plans/effect-components.md +1669 -0
  413. package/one/things/plans/effect.md +973 -0
  414. package/one/things/plans/email.md +953 -0
  415. package/one/things/plans/enhance-auth.md +1669 -0
  416. package/one/things/plans/install-components.md +198 -0
  417. package/one/things/plans/landing.md +728 -0
  418. package/one/things/plans/layout.md +205 -0
  419. package/one/things/plans/mail-backend.md +1308 -0
  420. package/one/things/plans/mail.md +2624 -0
  421. package/one/things/plans/next-features.md +83 -0
  422. package/one/things/plans/one.md +658 -0
  423. package/one/things/plans/ontology-6-dimensions.md +2216 -0
  424. package/one/things/plans/ontology-driven-strategy.md +866 -0
  425. package/one/things/plans/ontology-ui-approach.md +357 -0
  426. package/one/things/plans/open-agent.md +785 -0
  427. package/one/things/plans/organizations-to-groups.md +705 -0
  428. package/one/things/plans/performace.md +90 -0
  429. package/one/things/plans/release.md +432 -0
  430. package/one/things/plans/releases.md +809 -0
  431. package/one/things/plans/repos.md +76 -0
  432. package/one/things/plans/separate-copy-2.md +1293 -0
  433. package/one/things/plans/separate-copy-3.md +2458 -0
  434. package/one/things/plans/separate-copy.md +1293 -0
  435. package/one/things/plans/separate.md +1983 -0
  436. package/one/things/plans/shadcn-integration-summary.md +450 -0
  437. package/one/things/plans/sidebar.md +172 -0
  438. package/one/things/plans/small-fixes.md +5 -0
  439. package/one/things/plans/test-backend-connection.md +476 -0
  440. package/one/things/plans/workflow-files.md +1196 -0
  441. package/one/things/plans/workflow.md +1372 -0
  442. package/one/things/products/cascade-landing-page.md +737 -0
  443. package/one/things/products/cascade.md +1518 -0
  444. package/one/things/products/context-engineering.md +1427 -0
  445. package/one/things/products/onthology.md +0 -0
  446. package/one/things/products/ontology-ui-shadcn.md +1280 -0
  447. package/one/things/products/ontology-ui.md +1387 -0
  448. package/one/things/products/ontology.md +717 -0
  449. package/one/things/products/sdk.md +557 -0
  450. package/one/things/promptkit.md +903 -0
  451. package/one/things/service-providers-new.md +982 -0
  452. package/one/things/service-providers.md +1092 -0
  453. package/one/things/system.md +600 -0
  454. package/one/things/tests/2-1-dataprovider-interface.md +1144 -0
  455. package/one/things/tests/2-1-test-analysis.md +496 -0
  456. package/one/things/things.md +349 -0
  457. package/one/things/todo.md +1248 -0
  458. package/one/things/vision/elegant-interface.md +214 -0
  459. package/package.json +5 -2
@@ -0,0 +1,2536 @@
1
+
2
+ # ONE Platform - Implementation Examples
3
+
4
+ **Complete Reference**: Ontology, DSL, Schema, and Implementation Patterns
5
+
6
+ ---
7
+
8
+ ## Overview
9
+
10
+ The 6-dimension ontology architecture (things, connections, events, knowledge, people, protocols) provides unprecedented flexibility, while Convex + Effect.ts delivers production-grade reliability.
11
+
12
+ **Tech Stack**: Astro + React + shadcn/ui frontend, Convex backend with comprehensive components (@convex-dev/agent, workflow, rag, rate-limiter), Effect.ts service layer, Stripe Connect for payments.
13
+
14
+ ### Foundation Documents
15
+
16
+ This document integrates information from:
17
+
18
+ 1. **Ontology** (`Ontology.md`) - The 6-dimension data model that defines ALL things, connections, events, knowledge, people, and protocols
19
+ 2. **DSL** (`DSL.md`, `ONE DSL.md`, `ONE DSL English.md`) - Domain-specific language for feature definition
20
+ 3. **Schema** (`convex/schema.ts`) - Current authentication-focused schema and target ontology-based schema
21
+ 4. **Implementation Examples** - Real-world code patterns and feature implementations
22
+
23
+ ### Complete Architecture Stack
24
+
25
+ ```
26
+ ┌─────────────────────────────────────────────────────────────┐
27
+ │ Plain English DSL (Creator/CEO writes features) │
28
+ └─────────────────────────────────────────────────────────────┘
29
+ ↓
30
+ ┌─────────────────────────────────────────────────────────────┐
31
+ │ Technical DSL (JSON-like, validates against ontology) │
32
+ └─────────────────────────────────────────────────────────────┘
33
+ ↓
34
+ ┌─────────────────────────────────────────────────────────────┐
35
+ │ Ontology (6 dimensions: things, connections, events, knowledge, people, protocols) │
36
+ └─────────────────────────────────────────────────────────────┘
37
+ ↓
38
+ ┌─────────────────────────────────────────────────────────────┐
39
+ │ Schema Definition (Convex with validation) │
40
+ └─────────────────────────────────────────────────────────────┘
41
+ ↓
42
+ ┌─────────────────────────────────────────────────────────────┐
43
+ │ Generated Types (TypeScript strict mode) │
44
+ └─────────────────────────────────────────────────────────────┘
45
+ ↓
46
+ ┌─────────────────────────────────────────────────────────────┐
47
+ │ Provider Services (Effect.ts with dependency injection) │
48
+ └─────────────────────────────────────────────────────────────┘
49
+ ↓
50
+ ┌─────────────────────────────────────────────────────────────┐
51
+ │ Compiled TypeScript (Production code with tests) │
52
+ └─────────────────────────────────────────────────────────────┘
53
+ ↓
54
+ ┌─────────────────────────────────────────────────────────────┐
55
+ │ Deployed Feature (Live on ONE platform) │
56
+ └─────────────────────────────────────────────────────────────┘
57
+ ```
58
+
59
+ ### Why This Architecture Works
60
+
61
+ **Ontology-First Design:**
62
+ - Every feature maps to 6 dimensions (things, connections, events, knowledge, people, protocols)
63
+ - Simple test: "If you can't map it to these 6 dimensions, rethink it"
64
+ - AI agents can't generate invalid data models
65
+
66
+ **DSL Validation:**
67
+ - Plain English → Technical DSL → TypeScript
68
+ - Validates against ontology before compilation
69
+ - Generates type-safe code automatically
70
+ - Non-technical users can write features
71
+
72
+ **Schema Enforcement:**
73
+ - Convex schema validates all database operations
74
+ - Type-safe queries with full autocompletion
75
+ - Indexed for performance (< 100ms queries)
76
+ - Vector search for semantic operations
77
+
78
+ **Effect.ts Service Layer:**
79
+ - Typed error channels (no silent failures)
80
+ - Automatic dependency injection
81
+ - Testable with mocked services
82
+ - Composable business logic
83
+
84
+ ---
85
+
86
+ ## Ontology: The 6-Dimension Universe
87
+
88
+ **Purpose**: Complete data model for AI agents to understand how EVERYTHING in ONE platform is structured.
89
+
90
+ ### Core Concept
91
+
92
+ Every single thing in ONE platform exists in one of these 6 dimensions:
93
+
94
+ ```
95
+ ┌──────────────────────────────────────────────────────────────┐
96
+ │ ENTITIES TABLE │
97
+ │ Every "thing" - users, agents, content, tokens, courses │
98
+ └──────────────────────────────────────────────────────────────┘
99
+ ↓
100
+ ┌──────────────────────────────────────────────────────────────┐
101
+ │ CONNECTIONS TABLE │
102
+ │ Every relationship - owns, follows, taught_by, powers │
103
+ └──────────────────────────────────────────────────────────────┘
104
+ ↓
105
+ ┌──────────────────────────────────────────────────────────────┐
106
+ │ EVENTS TABLE │
107
+ │ Every action - purchased, created, viewed, completed │
108
+ └──────────────────────────────────────────────────────────────┘
109
+ ↓
110
+ ┌──────────────────────────────────────────────────────────────┐
111
+ │ TAGS TABLE │
112
+ │ Every category - industry:fitness, skill:video, etc. │
113
+ └──────────────────────────────────────────────────────────────┘
114
+ ```
115
+
116
+ **Golden Rule:** If you can't map your feature to these 6 dimensions, you're thinking about it wrong.
117
+
118
+ ### Entity Types
119
+
120
+ ```typescript
121
+ type EntityType =
122
+ // CORE
123
+ | "creator" // Human creator
124
+ | "ai_clone" // Digital twin of creator
125
+ | "audience_member" // Fan/user
126
+
127
+ // BUSINESS AGENTS (10 types)
128
+ | "strategy_agent" // Vision, planning, OKRs
129
+ | "research_agent" // Market, trends, competitors
130
+ | "marketing_agent" // Content strategy, SEO, distribution
131
+ | "sales_agent" // Funnels, conversion, follow-up
132
+ | "service_agent" // Support, onboarding, success
133
+ | "design_agent" // Brand, UI/UX, assets
134
+ | "engineering_agent" // Tech, integration, automation
135
+ | "finance_agent" // Revenue, costs, forecasting
136
+ | "legal_agent" // Compliance, contracts, IP
137
+ | "intelligence_agent" // Analytics, insights, predictions
138
+
139
+ // CONTENT
140
+ | "blog_post" // Written content
141
+ | "video" // Video content
142
+ | "podcast" // Audio content
143
+ | "social_post" // Social media post
144
+ | "email" // Email content
145
+ | "course" // Educational course
146
+ | "lesson" // Individual lesson
147
+
148
+ // PRODUCTS
149
+ | "digital_product" // Templates, tools, assets
150
+ | "membership" // Tiered membership
151
+ | "consultation" // 1-on-1 session
152
+ | "nft" // NFT collectible
153
+
154
+ // COMMUNITY
155
+ | "community" // Community space
156
+ | "conversation" // Thread/discussion
157
+ | "message" // Individual message
158
+
159
+ // TOKEN
160
+ | "token" // Actual token instance
161
+ | "token_contract" // Smart contract
162
+
163
+ // KNOWLEDGE
164
+ | "knowledge_item" // Piece of creator knowledge
165
+ | "embedding" // Vector embedding
166
+ ```
167
+
168
+ ### Connection Types (Optimized 24 Types)
169
+
170
+ **Design Philosophy**: Use metadata fields instead of proliferating connection types.
171
+
172
+ ```typescript
173
+ type ConnectionType =
174
+ // OWNERSHIP (3 types)
175
+ | "owns" // Creator owns token/content (metadata.revenueShare)
176
+ | "created_by" // Content created by creator
177
+ | "authored" // User authored content (vs. generated_by for AI)
178
+
179
+ // AI RELATIONSHIPS (3 types)
180
+ | "clone_of" // AI is clone of creator
181
+ | "trained_on" // Clone trained on content (metadata.trainingDataType)
182
+ | "powers" // Agent powers clone/feature (metadata.capability)
183
+
184
+ // CONTENT RELATIONSHIPS (4 types)
185
+ | "published_to" // Content published to platform (metadata.visibility)
186
+ | "part_of" // Lesson part of course (metadata.order, metadata.section)
187
+ | "references" // Content references entity (metadata.referenceType)
188
+ | "derived_from" // Content derived from original (metadata.derivationType)
189
+
190
+ // COMMUNITY RELATIONSHIPS (3 types)
191
+ | "member_of" // User member of community (metadata.role, metadata.joinedAt)
192
+ | "following" // User follows creator (metadata.notificationsEnabled)
193
+ | "engaged_with" // User engaged with content (metadata.engagementType: "liked", "commented", "shared")
194
+
195
+ // BUSINESS RELATIONSHIPS (3 types)
196
+ | "manages" // Agent manages function (metadata.permissions)
197
+ | "collaborates_with" // Entities collaborate (metadata.collaborationType, metadata.revenueShare)
198
+ | "assigned_to" // Task assigned to entity (metadata.priority, metadata.deadline)
199
+
200
+ // TRANSACTIONAL RELATIONSHIPS (4 types - consolidated from 7)
201
+ | "transacted" // Generic transaction (metadata.transactionType: "purchase", "subscription", "invoice")
202
+ | "holds" // User holds asset (metadata.assetType: "tokens", "nft", "stake", metadata.amount)
203
+ | "enrolled_in" // User enrolled in course (metadata.progress, metadata.startedAt)
204
+ | "completed" // User completed course/task (metadata.completedAt, metadata.certificateId)
205
+
206
+ // REFERRAL/GROWTH (2 types)
207
+ | "referred_by" // User referred by another (metadata.referralCode, metadata.conversionStatus)
208
+ | "converted_from" // User converted from lead (metadata.conversionType, metadata.source)
209
+
210
+ // MEDIA/ANALYTICS (2 types)
211
+ | "featured_in" // Entity featured in content (metadata.startTime, metadata.endTime)
212
+ | "analyzed_by" // Entity analyzed by intelligence (metadata.analysisType, metadata.confidence)
213
+ ```
214
+
215
+ **Key Improvements**:
216
+ - **Before**: 30+ connection types
217
+ - **After**: 24 optimized types
218
+ - **Strategy**: Use `metadata` for variants (e.g., "transacted" with metadata.transactionType instead of "paid_for", "subscribed_to", "invoiced_to")
219
+ - **Benefits**: Simpler schema, more flexible queries, easier to extend
220
+
221
+ ### Event Types (Optimized 38 Types)
222
+
223
+ **Design Philosophy**: Consolidate status variants into metadata fields.
224
+
225
+ ```typescript
226
+ type EventType =
227
+ // ENTITY LIFECYCLE (6 types)
228
+ | "entity_created" // Any entity created (metadata.entityType)
229
+ | "entity_updated" // Any entity updated (metadata.fields)
230
+ | "entity_deleted" // Soft delete (metadata.reason)
231
+ | "entity_restored" // Undelete (metadata.restoredBy)
232
+ | "entity_published" // Draft → Published (metadata.visibility)
233
+ | "entity_archived" // Active → Archived (metadata.archiveReason)
234
+
235
+ // AI/CLONE EVENTS (4 types)
236
+ | "clone_interaction" // Chat/interaction with clone (metadata.messageCount, metadata.duration)
237
+ | "clone_trained" // Training completed (metadata.dataPoints, metadata.model)
238
+ | "ai_generated" // AI generated content (metadata.contentType, metadata.prompt)
239
+ | "voice_cloned" // Voice clone created (metadata.provider, metadata.voiceId)
240
+
241
+ // AGENT EVENTS (3 types - consolidated from 4)
242
+ | "agent_executed" // Agent ran (metadata.status: "success", "failed", "partial")
243
+ | "workflow_started" // Workflow initiated (metadata.workflowType, metadata.steps)
244
+ | "workflow_completed" // Workflow finished (metadata.duration, metadata.status)
245
+
246
+ // CONTENT EVENTS (5 types)
247
+ | "content_viewed" // Content viewed (metadata.duration, metadata.completionRate)
248
+ | "content_interacted" // User interacted (metadata.interactionType: "liked", "shared", "commented")
249
+ | "content_downloaded" // Content downloaded (metadata.format)
250
+ | "content_embedded" // Embedding generated (metadata.model, metadata.dimensions)
251
+ | "content_moderated" // Moderation action (metadata.action, metadata.reason)
252
+
253
+ // LEARNING EVENTS (4 types - consolidated from 5)
254
+ | "course_enrolled" // User enrolled in course
255
+ | "progress_updated" // Progress on course/lesson (metadata.entityId, metadata.progress)
256
+ | "assessment_completed" // Test/quiz finished (metadata.score, metadata.passed)
257
+ | "certificate_earned" // Certificate issued (metadata.certificateId, metadata.skills)
258
+
259
+ // TOKEN/ASSET EVENTS (5 types - consolidated from 7)
260
+ | "token_deployed" // Contract deployed (metadata.contractAddress, metadata.chain)
261
+ | "token_transacted" // Token transaction (metadata.action: "purchased", "earned", "burned", metadata.amount)
262
+ | "token_staked" // Staking action (metadata.action: "staked", "unstaked", metadata.amount, metadata.duration)
263
+ | "governance_action" // Governance event (metadata.actionType: "vote", "proposal", "execution")
264
+ | "nft_minted" // NFT minted (metadata.tokenId, metadata.metadata)
265
+
266
+ // PAYMENT EVENTS (3 types - consolidated from 5)
267
+ | "payment_processed" // Payment event (metadata.status: "initiated", "completed", "failed", "refunded")
268
+ | "subscription_changed" // Subscription event (metadata.action: "started", "renewed", "cancelled", "upgraded")
269
+ | "invoice_generated" // Invoice created/sent (metadata.amount, metadata.dueDate, metadata.status)
270
+
271
+ // GROWTH/ENGAGEMENT (5 types)
272
+ | "referral_created" // Referral made (metadata.referralCode, metadata.channel)
273
+ | "referral_converted" // Referral converted (metadata.conversionValue)
274
+ | "achievement_unlocked" // Achievement earned (metadata.achievementId, metadata.points)
275
+ | "level_changed" // User level changed (metadata.oldLevel, metadata.newLevel, metadata.reason)
276
+ | "viral_shared" // Viral share occurred (metadata.platform, metadata.reach)
277
+
278
+ // ANALYTICS/INTELLIGENCE (3 types)
279
+ | "metric_calculated" // Metric computed (metadata.metricType, metadata.value)
280
+ | "insight_generated" // AI insight created (metadata.insightType, metadata.confidence)
281
+ | "report_generated" // Report created (metadata.reportType, metadata.period)
282
+ ```
283
+
284
+ **Key Improvements**:
285
+ - **Before**: 50+ event types with status variants
286
+ - **After**: 38 consolidated types
287
+ - **Strategy**: Use `metadata.status` or `metadata.action` for state variants
288
+ - **Example**: "payment_initiated", "payment_completed", "payment_failed" → "payment_processed" with metadata.status
289
+ - **Benefits**: Easier analytics queries, consistent event structure, simpler event handlers
290
+
291
+ **For complete ontology details, see:** `Ontology.md`
292
+
293
+ ---
294
+
295
+ ## ONE DSL: Domain-Specific Language
296
+
297
+ **Purpose**: Declarative language for defining features that compiles to Effect.ts and TypeScript.
298
+
299
+ ### DSL Architecture Stack
300
+
301
+ ```
302
+ Plain English (CEO writes)
303
+ ↓ [Parser]
304
+ Technical DSL (validated against ontology)
305
+ ↓ [Compiler]
306
+ TypeScript with Effect.ts (production code)
307
+ ↓ [Generated automatically]
308
+ Tests + Documentation
309
+ ↓
310
+ Deployed Feature
311
+ ```
312
+
313
+ ### Plain English DSL
314
+
315
+ **For creators and non-technical users** - Natural language that compiles to working code.
316
+
317
+ **Example:**
318
+ ```
319
+ FEATURE: Let fans chat with my AI clone
320
+
321
+ WHEN a fan sends a message
322
+ CHECK they own tokens
323
+ GET my AI personality
324
+ SEND message to AI with my personality
325
+ SAVE the conversation
326
+ GIVE fan 10 tokens as reward
327
+ SHOW AI response to fan
328
+ ```
329
+
330
+ **Core Commands:**
331
+ - `CHECK` - Validate something
332
+ - `CREATE` - Make something new
333
+ - `CONNECT` - Link two things
334
+ - `RECORD` - Log that something happened
335
+ - `CALL` - Use external service
336
+ - `GET` - Retrieve something
337
+ - `IF/THEN/ELSE` - Conditional logic
338
+ - `DO TOGETHER` - Atomic operations
339
+ - `WAIT` - Pause execution
340
+ - `FOR EACH` - Loop through items
341
+ - `GIVE` - Return result
342
+
343
+ ### Technical DSL
344
+
345
+ **For AI agents and developers** - JSON-like syntax that validates against ontology.
346
+
347
+ **Example:**
348
+ ```typescript
349
+ const createAICloneDSL = {
350
+ feature: "CreateAIClone",
351
+ input: {
352
+ creatorId: "Id<entities>",
353
+ videoUrls: "string[]",
354
+ },
355
+ output: {
356
+ cloneId: "Id<entities>",
357
+ voiceId: "string",
358
+ },
359
+ flow: [
360
+ {
361
+ validate: {
362
+ creatorId: { exists: true, type: "creator" },
363
+ videoUrls: { minLength: 3 },
364
+ },
365
+ onError: { return: { error: "InsufficientContent" } },
366
+ },
367
+ {
368
+ service: {
369
+ provider: "elevenlabs",
370
+ method: "cloneVoice",
371
+ params: { samples: "$audioSamples" },
372
+ output: "voiceId",
373
+ retry: { times: 3, delay: "5s" },
374
+ },
375
+ },
376
+ {
377
+ entity: {
378
+ type: "ai_clone",
379
+ name: "$creator.name + ' AI Clone'",
380
+ properties: {
381
+ voiceId: "$voiceId",
382
+ systemPrompt: "$personality.systemPrompt",
383
+ temperature: 0.7,
384
+ },
385
+ status: "active",
386
+ },
387
+ output: "cloneId",
388
+ },
389
+ {
390
+ connect: {
391
+ from: "$input.creatorId",
392
+ to: "$cloneId",
393
+ type: "owns",
394
+ },
395
+ },
396
+ {
397
+ event: {
398
+ entity: "$cloneId",
399
+ type: "clone_created",
400
+ actor: "$input.creatorId",
401
+ },
402
+ },
403
+ {
404
+ return: {
405
+ cloneId: "$cloneId",
406
+ voiceId: "$voiceId",
407
+ },
408
+ },
409
+ ],
410
+ };
411
+ ```
412
+
413
+ **DSL Primitives:**
414
+ - `entity` - Create entity in ontology
415
+ - `connect` - Create relationship between entities
416
+ - `event` - Log an event
417
+ - `query` - Retrieve entities/connections/events
418
+ - `flow` - Multi-step workflow with branching
419
+ - `service` - Call external provider (OpenAI, ElevenLabs, Stripe, etc.)
420
+ - `validate` - Check conditions
421
+ - `atomic` - Group operations with rollback support
422
+
423
+ ### DSL Validation & Compilation
424
+
425
+ **Validator** - Ensures DSL uses only valid ontology types:
426
+ ```typescript
427
+ class ONEValidator {
428
+ validate(dsl: any): { valid: boolean; errors: string[] } {
429
+ // Validates all entity types exist in ontology
430
+ // Validates all connection types exist in ontology
431
+ // Validates all event types exist in ontology
432
+ return { valid: true, errors: [] };
433
+ }
434
+ }
435
+ ```
436
+
437
+ **Compiler** - Generates type-safe TypeScript with Effect.ts:
438
+ ```typescript
439
+ class ONECompiler {
440
+ compile(dsl: any): string {
441
+ // Compiles DSL to TypeScript
442
+ // Generates Effect.ts service calls
443
+ // Adds proper error handling
444
+ // Creates fully typed code
445
+ return generatedCode;
446
+ }
447
+ }
448
+ ```
449
+
450
+ **Complete DSL examples and specifications in:** `DSL.md`, `ONE DSL.md`, `ONE DSL English.md`
451
+
452
+ ---
453
+
454
+ ## Schema Implementation
455
+
456
+ ### Current Schema (Authentication Focus)
457
+
458
+ **File**: `convex/schema.ts` (Current - Authentication focused)
459
+
460
+ ```typescript
461
+ import { defineSchema, defineTable } from "convex/server";
462
+ import { v } from "convex/values";
463
+
464
+ export default defineSchema({
465
+ users: defineTable({
466
+ email: v.string(),
467
+ passwordHash: v.string(),
468
+ name: v.optional(v.string()),
469
+ emailVerified: v.optional(v.boolean()),
470
+ createdAt: v.number(),
471
+ }).index("by_email", ["email"]),
472
+
473
+ sessions: defineTable({
474
+ userId: v.id("users"),
475
+ token: v.string(),
476
+ expiresAt: v.number(),
477
+ createdAt: v.number(),
478
+ }).index("by_token", ["token"])
479
+ .index("by_userId", ["userId"]),
480
+
481
+ passwordResets: defineTable({
482
+ userId: v.id("users"),
483
+ token: v.string(),
484
+ expiresAt: v.number(),
485
+ createdAt: v.number(),
486
+ used: v.boolean(),
487
+ }).index("by_token", ["token"])
488
+ .index("by_userId", ["userId"]),
489
+
490
+ emailVerifications: defineTable({
491
+ userId: v.id("users"),
492
+ email: v.string(),
493
+ token: v.string(),
494
+ expiresAt: v.number(),
495
+ createdAt: v.number(),
496
+ verified: v.boolean(),
497
+ }).index("by_token", ["token"])
498
+ .index("by_userId", ["userId"])
499
+ .index("by_email", ["email"]),
500
+
501
+ magicLinks: defineTable({
502
+ email: v.string(),
503
+ token: v.string(),
504
+ expiresAt: v.number(),
505
+ createdAt: v.number(),
506
+ used: v.boolean(),
507
+ }).index("by_token", ["token"])
508
+ .index("by_email", ["email"]),
509
+
510
+ twoFactorAuth: defineTable({
511
+ userId: v.id("users"),
512
+ secret: v.string(),
513
+ backupCodes: v.array(v.string()),
514
+ enabled: v.boolean(),
515
+ createdAt: v.number(),
516
+ }).index("by_userId", ["userId"]),
517
+ });
518
+ ```
519
+
520
+ ### Target Ontology-Based Schema (Plain Convex)
521
+
522
+ **Future implementation** - 6-dimension architecture with full ontology support:
523
+
524
+ ```typescript
525
+ import { defineSchema, defineTable } from "convex/server";
526
+ import { v } from "convex/values";
527
+
528
+ export default defineSchema({
529
+ // ENTITIES TABLE - All "things"
530
+ entities: defineTable({
531
+ type: v.union(
532
+ // Core
533
+ v.literal("creator"),
534
+ v.literal("ai_clone"),
535
+ v.literal("audience_member"),
536
+ // Business Agents
537
+ v.literal("strategy_agent"),
538
+ v.literal("research_agent"),
539
+ v.literal("marketing_agent"),
540
+ v.literal("sales_agent"),
541
+ v.literal("service_agent"),
542
+ v.literal("design_agent"),
543
+ v.literal("engineering_agent"),
544
+ v.literal("finance_agent"),
545
+ v.literal("legal_agent"),
546
+ v.literal("intelligence_agent"),
547
+ // Content
548
+ v.literal("blog_post"),
549
+ v.literal("video"),
550
+ v.literal("podcast"),
551
+ v.literal("social_post"),
552
+ v.literal("email"),
553
+ v.literal("course"),
554
+ v.literal("lesson"),
555
+ // Products
556
+ v.literal("digital_product"),
557
+ v.literal("membership"),
558
+ v.literal("consultation"),
559
+ v.literal("nft"),
560
+ // Community
561
+ v.literal("community"),
562
+ v.literal("conversation"),
563
+ v.literal("message"),
564
+ // Token
565
+ v.literal("token"),
566
+ v.literal("token_contract"),
567
+ // Knowledge
568
+ v.literal("knowledge_item"),
569
+ v.literal("embedding"),
570
+ // Platform
571
+ v.literal("website"),
572
+ v.literal("landing_page"),
573
+ v.literal("template"),
574
+ v.literal("livestream"),
575
+ v.literal("recording"),
576
+ v.literal("media_asset"),
577
+ // Business
578
+ v.literal("payment"),
579
+ v.literal("subscription"),
580
+ v.literal("invoice"),
581
+ v.literal("metric"),
582
+ v.literal("insight"),
583
+ v.literal("prediction"),
584
+ v.literal("report"),
585
+ // Marketing
586
+ v.literal("notification"),
587
+ v.literal("email_campaign"),
588
+ v.literal("announcement"),
589
+ v.literal("referral"),
590
+ v.literal("campaign"),
591
+ v.literal("lead")
592
+ ),
593
+ name: v.string(),
594
+ properties: v.any(), // Type-specific properties as JSON
595
+ status: v.optional(
596
+ v.union(
597
+ v.literal("active"),
598
+ v.literal("inactive"),
599
+ v.literal("draft"),
600
+ v.literal("published"),
601
+ v.literal("archived")
602
+ )
603
+ ),
604
+ createdAt: v.number(),
605
+ updatedAt: v.number(),
606
+ deletedAt: v.optional(v.number()),
607
+ })
608
+ .index("by_type", ["type"])
609
+ .index("by_status", ["status"])
610
+ .index("by_createdAt", ["createdAt"])
611
+ .index("by_type_status", ["type", "status"])
612
+ .searchIndex("search_entities", {
613
+ searchField: "name",
614
+ filterFields: ["type", "status"],
615
+ }),
616
+
617
+ // CONNECTIONS TABLE - All relationships
618
+ connections: defineTable({
619
+ fromEntityId: v.id("entities"),
620
+ toEntityId: v.id("entities"),
621
+ relationshipType: v.union(
622
+ // Ownership (3 types)
623
+ v.literal("owns"),
624
+ v.literal("created_by"),
625
+ v.literal("authored"),
626
+ // AI relationships (3 types)
627
+ v.literal("clone_of"),
628
+ v.literal("trained_on"),
629
+ v.literal("powers"),
630
+ // Content relationships (4 types)
631
+ v.literal("published_to"),
632
+ v.literal("part_of"),
633
+ v.literal("references"),
634
+ v.literal("derived_from"),
635
+ // Community relationships (3 types)
636
+ v.literal("member_of"),
637
+ v.literal("following"),
638
+ v.literal("engaged_with"),
639
+ // Business relationships (3 types)
640
+ v.literal("manages"),
641
+ v.literal("collaborates_with"),
642
+ v.literal("assigned_to"),
643
+ // Transactional relationships (4 types)
644
+ v.literal("transacted"),
645
+ v.literal("holds"),
646
+ v.literal("enrolled_in"),
647
+ v.literal("completed"),
648
+ // Referral/growth (2 types)
649
+ v.literal("referred_by"),
650
+ v.literal("converted_from"),
651
+ // Media/analytics (2 types)
652
+ v.literal("featured_in"),
653
+ v.literal("analyzed_by")
654
+ ),
655
+ metadata: v.optional(v.any()),
656
+ strength: v.optional(v.number()),
657
+ validFrom: v.optional(v.number()),
658
+ validTo: v.optional(v.number()),
659
+ createdAt: v.number(),
660
+ updatedAt: v.optional(v.number()),
661
+ })
662
+ .index("by_relationshipType", ["relationshipType"])
663
+ .index("by_fromEntity", ["fromEntityId"])
664
+ .index("by_toEntity", ["toEntityId"])
665
+ .index("by_from_type", ["fromEntityId", "relationshipType"])
666
+ .index("by_to_type", ["toEntityId", "relationshipType"])
667
+ .index("by_bidirectional", ["fromEntityId", "toEntityId"])
668
+ .index("by_type_from_to", ["relationshipType", "fromEntityId", "toEntityId"]),
669
+
670
+ // EVENTS TABLE - All actions
671
+ events: defineTable({
672
+ entityId: v.id("entities"),
673
+ eventType: v.union(
674
+ // Entity lifecycle (6 types)
675
+ v.literal("entity_created"),
676
+ v.literal("entity_updated"),
677
+ v.literal("entity_deleted"),
678
+ v.literal("entity_restored"),
679
+ v.literal("entity_published"),
680
+ v.literal("entity_archived"),
681
+ // AI/Clone events (4 types)
682
+ v.literal("clone_interaction"),
683
+ v.literal("clone_trained"),
684
+ v.literal("ai_generated"),
685
+ v.literal("voice_cloned"),
686
+ // Agent events (3 types)
687
+ v.literal("agent_executed"),
688
+ v.literal("workflow_started"),
689
+ v.literal("workflow_completed"),
690
+ // Content events (5 types)
691
+ v.literal("content_viewed"),
692
+ v.literal("content_interacted"),
693
+ v.literal("content_downloaded"),
694
+ v.literal("content_embedded"),
695
+ v.literal("content_moderated"),
696
+ // Learning events (4 types)
697
+ v.literal("course_enrolled"),
698
+ v.literal("progress_updated"),
699
+ v.literal("assessment_completed"),
700
+ v.literal("certificate_earned"),
701
+ // Token/asset events (5 types)
702
+ v.literal("token_deployed"),
703
+ v.literal("token_transacted"),
704
+ v.literal("token_staked"),
705
+ v.literal("governance_action"),
706
+ v.literal("nft_minted"),
707
+ // Payment events (3 types)
708
+ v.literal("payment_processed"),
709
+ v.literal("subscription_changed"),
710
+ v.literal("invoice_generated"),
711
+ // Growth/engagement (5 types)
712
+ v.literal("referral_created"),
713
+ v.literal("referral_converted"),
714
+ v.literal("achievement_unlocked"),
715
+ v.literal("level_changed"),
716
+ v.literal("viral_shared"),
717
+ // Analytics/intelligence (3 types)
718
+ v.literal("metric_calculated"),
719
+ v.literal("insight_generated"),
720
+ v.literal("report_generated")
721
+ ),
722
+ timestamp: v.number(),
723
+ metadata: v.optional(v.any()),
724
+ actorType: v.optional(
725
+ v.union(
726
+ v.literal("user"),
727
+ v.literal("ai_agent"),
728
+ v.literal("system"),
729
+ v.literal("api")
730
+ )
731
+ ),
732
+ actorId: v.optional(v.id("entities")),
733
+ source: v.optional(v.string()),
734
+ sessionId: v.optional(v.string()),
735
+ })
736
+ .index("by_entity", ["entityId"])
737
+ .index("by_timestamp", ["timestamp"])
738
+ .index("by_eventType", ["eventType"])
739
+ .index("by_entity_type", ["entityId", "eventType"])
740
+ .index("by_entity_type_time", ["entityId", "eventType", "timestamp"])
741
+ .index("by_type_time", ["eventType", "timestamp"])
742
+ .index("by_session", ["sessionId", "timestamp"])
743
+ .index("by_actor", ["actorId", "timestamp"]),
744
+
745
+ // TAGS TABLE - All categories
746
+ tags: defineTable({
747
+ name: v.string(),
748
+ category: v.optional(
749
+ v.union(
750
+ v.literal("skill"),
751
+ v.literal("industry"),
752
+ v.literal("topic"),
753
+ v.literal("format"),
754
+ v.literal("goal"),
755
+ v.literal("audience"),
756
+ v.literal("technology"),
757
+ v.literal("status")
758
+ )
759
+ ),
760
+ description: v.optional(v.string()),
761
+ color: v.optional(v.string()),
762
+ icon: v.optional(v.string()),
763
+ usageCount: v.number(),
764
+ createdAt: v.number(),
765
+ })
766
+ .index("by_name", ["name"])
767
+ .index("by_category", ["category"])
768
+ .index("by_usageCount", ["usageCount"]),
769
+
770
+ // ENTITY-TAG JUNCTION TABLE
771
+ entityTags: defineTable({
772
+ entityId: v.id("entities"),
773
+ tagId: v.id("tags"),
774
+ createdAt: v.number(),
775
+ })
776
+ .index("by_entity", ["entityId"])
777
+ .index("by_tag", ["tagId"])
778
+ .index("by_entity_tag", ["entityId", "tagId"]),
779
+
780
+ // EMBEDDINGS TABLE - Vector search
781
+ embeddings: defineTable({
782
+ entityId: v.id("entities"),
783
+ embedding: v.array(v.float64()),
784
+ model: v.string(),
785
+ createdAt: v.number(),
786
+ })
787
+ .index("by_entity", ["entityId"])
788
+ .vectorIndex("by_embedding", {
789
+ vectorField: "embedding",
790
+ dimensions: 1536,
791
+ filterFields: ["entityId", "model"],
792
+ }),
793
+ });
794
+ ```
795
+
796
+ **Migration Strategy**: Batched processing with dual-write pattern during transition period.
797
+
798
+ **Success Criteria**: ✅ Schema deploys without errors, ✅ All entity types creatable, ✅ Relationship queries work
799
+
800
+ ### Metadata-Based Query Patterns
801
+
802
+ **Purpose**: Show how to query consolidated types using metadata filters instead of proliferating specific types.
803
+
804
+ #### Example 1: Query Payments by Status
805
+
806
+ ```typescript
807
+ // OLD WAY: Multiple event types
808
+ // query("events").filter(q =>
809
+ // q.or(
810
+ // q.eq(q.field("eventType"), "payment_initiated"),
811
+ // q.eq(q.field("eventType"), "payment_completed"),
812
+ // q.eq(q.field("eventType"), "payment_failed")
813
+ // )
814
+ // )
815
+
816
+ // NEW WAY: Single event type with metadata filter
817
+ export const getPaymentsByStatus = query({
818
+ args: { status: v.union(v.literal("initiated"), v.literal("completed"), v.literal("failed"), v.literal("refunded")) },
819
+ handler: async (ctx, args) => {
820
+ const payments = await ctx.db
821
+ .query("events")
822
+ .withIndex("by_eventType", (q) => q.eq("eventType", "payment_processed"))
823
+ .filter((q) => q.eq(q.field("metadata.status"), args.status))
824
+ .order("desc")
825
+ .take(100);
826
+
827
+ return payments;
828
+ },
829
+ });
830
+ ```
831
+
832
+ #### Example 2: Query Connections by Transaction Type
833
+
834
+ ```typescript
835
+ // OLD WAY: Separate connection types for each transaction
836
+ // "paid_for", "subscribed_to", "invoiced_to"
837
+
838
+ // NEW WAY: Single "transacted" type with metadata
839
+ export const getTransactionsByType = query({
840
+ args: {
841
+ userId: v.id("entities"),
842
+ transactionType: v.union(v.literal("purchase"), v.literal("subscription"), v.literal("invoice"))
843
+ },
844
+ handler: async (ctx, args) => {
845
+ const transactions = await ctx.db
846
+ .query("connections")
847
+ .withIndex("by_from_type", (q) =>
848
+ q.eq("fromEntityId", args.userId).eq("relationshipType", "transacted")
849
+ )
850
+ .filter((q) => q.eq(q.field("metadata.transactionType"), args.transactionType))
851
+ .collect();
852
+
853
+ return transactions;
854
+ },
855
+ });
856
+ ```
857
+
858
+ #### Example 3: Query User Engagement by Interaction Type
859
+
860
+ ```typescript
861
+ // OLD WAY: Multiple connection types
862
+ // "content_liked", "content_shared", "content_commented"
863
+
864
+ // NEW WAY: Single "engaged_with" type with metadata
865
+ export const getUserEngagement = query({
866
+ args: {
867
+ contentId: v.id("entities"),
868
+ interactionType: v.optional(v.union(v.literal("liked"), v.literal("shared"), v.literal("commented")))
869
+ },
870
+ handler: async (ctx, args) => {
871
+ let engagements = ctx.db
872
+ .query("connections")
873
+ .withIndex("by_to_type", (q) =>
874
+ q.eq("toEntityId", args.contentId).eq("relationshipType", "engaged_with")
875
+ );
876
+
877
+ // Filter by interaction type if specified
878
+ if (args.interactionType) {
879
+ engagements = engagements.filter((q) =>
880
+ q.eq(q.field("metadata.engagementType"), args.interactionType)
881
+ );
882
+ }
883
+
884
+ return await engagements.collect();
885
+ },
886
+ });
887
+ ```
888
+
889
+ #### Example 4: Query Agent Executions by Status
890
+
891
+ ```typescript
892
+ // OLD WAY: Multiple event types
893
+ // "agent_executed", "agent_completed", "agent_failed"
894
+
895
+ // NEW WAY: Single event type with status in metadata
896
+ export const getAgentExecutions = query({
897
+ args: {
898
+ agentId: v.id("entities"),
899
+ status: v.optional(v.union(v.literal("success"), v.literal("failed"), v.literal("partial")))
900
+ },
901
+ handler: async (ctx, args) => {
902
+ let executions = ctx.db
903
+ .query("events")
904
+ .withIndex("by_entity_type", (q) =>
905
+ q.eq("entityId", args.agentId).eq("eventType", "agent_executed")
906
+ );
907
+
908
+ // Filter by status if specified
909
+ if (args.status) {
910
+ executions = executions.filter((q) =>
911
+ q.eq(q.field("metadata.status"), args.status)
912
+ );
913
+ }
914
+
915
+ return await executions.order("desc").take(50);
916
+ },
917
+ });
918
+ ```
919
+
920
+ #### Example 5: Analytics Query Across Consolidated Types
921
+
922
+ ```typescript
923
+ // Query all payment statuses for analytics
924
+ export const getPaymentAnalytics = query({
925
+ args: { startDate: v.number(), endDate: v.number() },
926
+ handler: async (ctx, args) => {
927
+ const payments = await ctx.db
928
+ .query("events")
929
+ .withIndex("by_type_time", (q) =>
930
+ q.eq("eventType", "payment_processed")
931
+ .gte("timestamp", args.startDate)
932
+ .lte("timestamp", args.endDate)
933
+ )
934
+ .collect();
935
+
936
+ // Aggregate by status
937
+ const analytics = {
938
+ initiated: 0,
939
+ completed: 0,
940
+ failed: 0,
941
+ refunded: 0,
942
+ totalAmount: 0,
943
+ };
944
+
945
+ payments.forEach((payment) => {
946
+ const status = payment.metadata?.status || "unknown";
947
+ if (status in analytics) {
948
+ analytics[status]++;
949
+ }
950
+ if (status === "completed") {
951
+ analytics.totalAmount += payment.metadata?.amount || 0;
952
+ }
953
+ });
954
+
955
+ return analytics;
956
+ },
957
+ });
958
+ ```
959
+
960
+ **Benefits of Metadata-Based Queries**:
961
+ - **Simpler schema**: 25 connection types vs. 30+, 35 event types vs. 50+
962
+ - **Easier analytics**: Single event type aggregation vs. multiple OR conditions
963
+ - **More flexible**: Add new statuses without schema migrations
964
+ - **Better performance**: Index on single eventType, filter on metadata
965
+ - **Clearer intent**: `metadata.status` explicitly shows state variants
966
+
967
+ ---
968
+
969
+ ## Quick Reference Guide
970
+
971
+ ### How to Build a Feature (Step-by-Step)
972
+
973
+ **1. Map to Ontology**
974
+ - What **entities** are involved? (creator, ai_clone, token, etc.)
975
+ - What **connections** link them? (owns, follows, enrolled_in, etc.)
976
+ - What **events** need logging? (clone_created, tokens_purchased, etc.)
977
+ - What **tags** categorize them? (industry:fitness, skill:video, etc.)
978
+
979
+ **2. Write in Plain English DSL**
980
+ ```
981
+ FEATURE: [What this does]
982
+
983
+ INPUT:
984
+ - [what you need]
985
+
986
+ OUTPUT:
987
+ - [what you get back]
988
+
989
+ FLOW:
990
+ CHECK [validations]
991
+ CALL [external services]
992
+ CREATE [entities]
993
+ CONNECT [relationships]
994
+ RECORD [events]
995
+ GIVE [results]
996
+ ```
997
+
998
+ **3. Validate Against Ontology**
999
+ ```typescript
1000
+ const validator = new ONEValidator(ontology);
1001
+ const validation = validator.validate(myFeatureDSL);
1002
+ if (!validation.valid) {
1003
+ console.error(validation.errors);
1004
+ }
1005
+ ```
1006
+
1007
+ **4. Compile to TypeScript**
1008
+ ```typescript
1009
+ const compiler = new ONECompiler();
1010
+ const code = compiler.compile(myFeatureDSL);
1011
+ // Generates type-safe Effect.ts code
1012
+ ```
1013
+
1014
+ **5. Deploy**
1015
+ ```bash
1016
+ # Code is automatically tested and deployed
1017
+ ```
1018
+
1019
+ ### Common Patterns
1020
+
1021
+ **Pattern: Create Thing with Ownership**
1022
+ ```typescript
1023
+ // DSL
1024
+ {
1025
+ thing: { type: "ai_clone", name: "My Clone", properties: {...} },
1026
+ output: "cloneId"
1027
+ }
1028
+ {
1029
+ connect: { from: "$creatorId", to: "$cloneId", type: "owns" }
1030
+ }
1031
+ {
1032
+ event: { thing: "$cloneId", type: "clone_created", actor: "$creatorId" }
1033
+ }
1034
+ ```
1035
+
1036
+ **Pattern: Token Purchase with Rollback**
1037
+ ```typescript
1038
+ // DSL
1039
+ {
1040
+ atomic: [
1041
+ { service: { provider: "stripe", method: "charge", ... } },
1042
+ { service: { provider: "blockchain", method: "mint", ... } }
1043
+ ],
1044
+ onError: {
1045
+ rollback: [
1046
+ { service: { provider: "stripe", method: "refund", ... } },
1047
+ { service: { provider: "blockchain", method: "burn", ... } }
1048
+ ]
1049
+ }
1050
+ }
1051
+ ```
1052
+
1053
+ **Pattern: Query with Relationships**
1054
+ ```typescript
1055
+ // Get creator's content
1056
+ {
1057
+ query: {
1058
+ from: "connections",
1059
+ where: [
1060
+ { field: "fromEntityId", operator: "eq", value: "$creatorId" },
1061
+ { field: "relationshipType", operator: "eq", value: "authored" }
1062
+ ]
1063
+ },
1064
+ output: "contentConnections"
1065
+ }
1066
+ ```
1067
+
1068
+ ### Validation Rules
1069
+
1070
+ **Thing Validation:**
1071
+ - ✅ Type must be valid ThingType from ontology
1072
+ - ✅ Name cannot be empty
1073
+ - ✅ Properties structure must match type
1074
+ - ✅ Status must be valid (active, inactive, draft, published, archived)
1075
+
1076
+ **Connection Validation:**
1077
+ - ✅ fromThingId and toThingId must exist
1078
+ - ✅ relationshipType must be valid ConnectionType
1079
+ - ✅ Cannot connect thing to itself (usually)
1080
+ - ✅ Relationship must make semantic sense
1081
+
1082
+ **Event Validation:**
1083
+ - ✅ thingId must exist
1084
+ - ✅ eventType must be valid EventType
1085
+ - ✅ timestamp required
1086
+ - ✅ actorId must exist if provided
1087
+
1088
+ **Knowledge Validation:**
1089
+ - ✅ label must be unique or properly scoped
1090
+ - ✅ category must be valid KnowledgeCategory
1091
+ - ✅ usageCount must be >= 0
1092
+
1093
+ ### Performance Guidelines
1094
+
1095
+ **Indexes:**
1096
+ - Use indexes for all filter fields
1097
+ - Compound indexes for multi-field queries
1098
+ - Vector indexes for semantic search
1099
+
1100
+ **Query Optimization:**
1101
+ - Always use indexes for filters
1102
+ - Limit results with `.take(n)`
1103
+ - Paginate large result sets
1104
+ - Prefer streaming over `.collect()` for large datasets
1105
+
1106
+ **Caching:**
1107
+ - Cache frequently accessed entities
1108
+ - Invalidate cache on entity updates
1109
+ - Use stale-while-revalidate pattern
1110
+
1111
+ ### Reference Files
1112
+
1113
+ - **Ontology Spec**: `Ontology.md` - Complete 6-dimension data model
1114
+ - **Technical DSL**: `DSL.md`, `ONE DSL.md` - JSON-like syntax and compiler
1115
+ - **Plain English DSL**: `ONE DSL English.md` - Natural language syntax
1116
+ - **Schema**: `convex/schema.ts` - Current and target schemas
1117
+ - **Examples**: This file - Real-world implementation patterns
1118
+
1119
+ ---
1120
+
1121
+ ### Week 2: Payment Infrastructure
1122
+
1123
+ **Stripe Connect Integration - Direct Revenue Enabler**
1124
+
1125
+ #### Implementation: Token Purchase with Revenue Splits
1126
+
1127
+ **File**: `convex/payments/tokenPurchase.ts`
1128
+
1129
+ ```typescript
1130
+ import { v } from "convex/values";
1131
+ import { mutation, query } from "./_generated/server";
1132
+ import { internal } from "./_generated/api";
1133
+
1134
+ // Query to get token ownership for revenue splits
1135
+ export const getTokenOwnership = query({
1136
+ args: { tokenId: v.id("entities") },
1137
+ handler: async (ctx, args) => {
1138
+ // Get token entity
1139
+ const token = await ctx.db.get(args.tokenId);
1140
+ if (!token || token.type !== "token") {
1141
+ throw new Error("Token not found");
1142
+ }
1143
+
1144
+ // Get ownership connections using plain Convex query with index
1145
+ const ownerships = await ctx.db
1146
+ .query("connections")
1147
+ .withIndex("by_to_type", (q) =>
1148
+ q.eq("toEntityId", args.tokenId).eq("relationshipType", "owns")
1149
+ )
1150
+ .collect();
1151
+
1152
+ // Return owners with revenue split metadata
1153
+ return Promise.all(
1154
+ ownerships.map(async (conn) => {
1155
+ const owner = await ctx.db.get(conn.fromEntityId);
1156
+ return {
1157
+ ownerId: conn.fromEntityId,
1158
+ ownerName: owner?.name,
1159
+ revenueShare: conn.metadata?.revenueShare || 0,
1160
+ stripeAccountId: owner?.properties?.stripeAccountId,
1161
+ };
1162
+ })
1163
+ );
1164
+ },
1165
+ });
1166
+
1167
+ // Mutation to process token purchase
1168
+ export const purchaseTokens = mutation({
1169
+ args: {
1170
+ userId: v.id("entities"),
1171
+ tokenId: v.id("entities"),
1172
+ amount: v.number(),
1173
+ usdAmount: v.number(),
1174
+ },
1175
+ handler: async (ctx, args) => {
1176
+ // Validate entities exist
1177
+ const user = await ctx.db.get(args.userId);
1178
+ const token = await ctx.db.get(args.tokenId);
1179
+
1180
+ if (!user || user.type !== "audience_member") {
1181
+ throw new Error("User not found");
1182
+ }
1183
+ if (!token || token.type !== "token") {
1184
+ throw new Error("Token not found");
1185
+ }
1186
+
1187
+ // Schedule payment processing (will be done in action)
1188
+ await ctx.scheduler.runAfter(0, internal.payments.processTokenPayment, {
1189
+ userId: args.userId,
1190
+ tokenId: args.tokenId,
1191
+ amount: args.amount,
1192
+ usdAmount: args.usdAmount,
1193
+ });
1194
+
1195
+ return { success: true, message: "Payment processing initiated" };
1196
+ },
1197
+ });
1198
+ ```
1199
+
1200
+ **File**: `convex/payments/processPayment.ts` (Action)
1201
+
1202
+ ```typescript
1203
+ "use node";
1204
+ import { v } from "convex/values";
1205
+ import { internalAction } from "./_generated/server";
1206
+ import { internal } from "./_generated/api";
1207
+ import Stripe from "stripe";
1208
+
1209
+ const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
1210
+
1211
+ export const processTokenPayment = internalAction({
1212
+ args: {
1213
+ userId: v.id("entities"),
1214
+ tokenId: v.id("entities"),
1215
+ amount: v.number(),
1216
+ usdAmount: v.number(),
1217
+ },
1218
+ handler: async (ctx, args) => {
1219
+ // Get ownership for revenue splits
1220
+ const ownership = await ctx.runQuery(internal.payments.getTokenOwnership, {
1221
+ tokenId: args.tokenId,
1222
+ });
1223
+
1224
+ const platformFee = Math.floor(args.usdAmount * 0.15 * 100); // 15% platform fee
1225
+
1226
+ // Create Stripe checkout with revenue splits
1227
+ const session = await stripe.checkout.sessions.create({
1228
+ line_items: [
1229
+ {
1230
+ price_data: {
1231
+ currency: "usd",
1232
+ unit_amount: args.usdAmount * 100,
1233
+ product_data: { name: `${args.amount} Tokens` },
1234
+ },
1235
+ quantity: 1,
1236
+ },
1237
+ ],
1238
+ mode: "payment",
1239
+ payment_intent_data: {
1240
+ application_fee_amount: platformFee,
1241
+ transfer_data: {
1242
+ destination: ownership[0].stripeAccountId, // Primary owner gets payment
1243
+ },
1244
+ },
1245
+ metadata: {
1246
+ userId: args.userId,
1247
+ tokenId: args.tokenId,
1248
+ amount: args.amount.toString(),
1249
+ },
1250
+ });
1251
+
1252
+ // Record payment event with metadata status
1253
+ await ctx.runMutation(internal.events.create, {
1254
+ entityId: args.tokenId,
1255
+ eventType: "payment_processed",
1256
+ actorType: "user",
1257
+ actorId: args.userId,
1258
+ metadata: {
1259
+ status: "initiated",
1260
+ paymentType: "token_purchase",
1261
+ amount: args.amount,
1262
+ usdAmount: args.usdAmount,
1263
+ sessionId: session.id,
1264
+ },
1265
+ });
1266
+
1267
+ return { sessionId: session.id, url: session.url };
1268
+ },
1269
+ });
1270
+ ```
1271
+
1272
+ **Seller Onboarding**: 2-minute Stripe Express flow with automatic account creation.
1273
+
1274
+ **Success Criteria**: ✅ Transactions process correctly, ✅ Revenue splits accurate, ✅ Webhooks handled
1275
+
1276
+ ---
1277
+
1278
+ ## Phase 2: Content & Product Economy (Weeks 3-4)
1279
+
1280
+ ### Week 3: Content Creation & Discovery
1281
+
1282
+ **Universal Content Creator - Multiple types following ontology (blog_post, video, podcast, social_post, course, digital_product)**
1283
+
1284
+ #### Content Creator Implementation
1285
+
1286
+ **File**: `convex/content/create.ts`
1287
+
1288
+ ```typescript
1289
+ import { v } from "convex/values";
1290
+ import { mutation } from "./_generated/server";
1291
+
1292
+ export const createContent = mutation({
1293
+ args: {
1294
+ creatorId: v.id("entities"),
1295
+ type: v.union(
1296
+ v.literal("blog_post"),
1297
+ v.literal("video"),
1298
+ v.literal("podcast"),
1299
+ v.literal("social_post"),
1300
+ v.literal("course"),
1301
+ v.literal("digital_product")
1302
+ ),
1303
+ name: v.string(),
1304
+ properties: v.any(), // Type-specific properties
1305
+ tags: v.optional(v.array(v.string())),
1306
+ collaborators: v.optional(
1307
+ v.array(
1308
+ v.object({
1309
+ entityId: v.id("entities"),
1310
+ revenueShare: v.number(), // 0.0 to 1.0
1311
+ })
1312
+ )
1313
+ ),
1314
+ },
1315
+ handler: async (ctx, args) => {
1316
+ // Validate creator exists
1317
+ const creator = await ctx.db.get(args.creatorId);
1318
+ if (!creator || creator.type !== "creator") {
1319
+ throw new Error("Creator not found");
1320
+ }
1321
+
1322
+ // Create content entity
1323
+ const contentId = await ctx.db.insert("entities", {
1324
+ type: args.type,
1325
+ name: args.name,
1326
+ properties: args.properties,
1327
+ status: "draft",
1328
+ createdAt: Date.now(),
1329
+ updatedAt: Date.now(),
1330
+ });
1331
+
1332
+ // Create ownership connection (creator owns content)
1333
+ await ctx.db.insert("connections", {
1334
+ fromEntityId: args.creatorId,
1335
+ toEntityId: contentId,
1336
+ relationshipType: "owns",
1337
+ metadata: { revenueShare: 1.0 }, // Creator gets 100% initially
1338
+ createdAt: Date.now(),
1339
+ });
1340
+
1341
+ // Create authored connection
1342
+ await ctx.db.insert("connections", {
1343
+ fromEntityId: args.creatorId,
1344
+ toEntityId: contentId,
1345
+ relationshipType: "authored",
1346
+ createdAt: Date.now(),
1347
+ });
1348
+
1349
+ // Add collaborators with revenue splits
1350
+ if (args.collaborators) {
1351
+ for (const collab of args.collaborators) {
1352
+ await ctx.db.insert("connections", {
1353
+ fromEntityId: collab.entityId,
1354
+ toEntityId: contentId,
1355
+ relationshipType: "owns",
1356
+ metadata: { revenueShare: collab.revenueShare },
1357
+ createdAt: Date.now(),
1358
+ });
1359
+ }
1360
+ }
1361
+
1362
+ // Add tags
1363
+ if (args.tags) {
1364
+ for (const tagName of args.tags) {
1365
+ // Get or create tag
1366
+ let tag = await ctx.db
1367
+ .query("tags")
1368
+ .withIndex("by_name", (q) => q.eq("name", tagName))
1369
+ .unique();
1370
+
1371
+ if (!tag) {
1372
+ const tagId = await ctx.db.insert("tags", {
1373
+ name: tagName,
1374
+ category: "topic",
1375
+ usageCount: 0,
1376
+ createdAt: Date.now(),
1377
+ });
1378
+ tag = await ctx.db.get(tagId);
1379
+ }
1380
+
1381
+ // Create entity-tag association
1382
+ await ctx.db.insert("entityTags", {
1383
+ entityId: contentId,
1384
+ tagId: tag!._id,
1385
+ createdAt: Date.now(),
1386
+ });
1387
+
1388
+ // Increment tag usage count
1389
+ await ctx.db.patch(tag!._id, {
1390
+ usageCount: tag!.usageCount + 1,
1391
+ });
1392
+ }
1393
+ }
1394
+
1395
+ // Log entity creation event with content-specific metadata
1396
+ await ctx.db.insert("events", {
1397
+ entityId: contentId,
1398
+ eventType: "entity_created",
1399
+ timestamp: Date.now(),
1400
+ actorType: "user",
1401
+ actorId: args.creatorId,
1402
+ metadata: {
1403
+ entityType: args.type,
1404
+ collaboratorCount: args.collaborators?.length || 0,
1405
+ tagCount: args.tags?.length || 0,
1406
+ },
1407
+ });
1408
+
1409
+ return { contentId, success: true };
1410
+ },
1411
+ });
1412
+ ```
1413
+
1414
+ **Frontend**: Multi-step wizard with file upload, collaborator management, tag selection, and license controls
1415
+
1416
+ ---
1417
+
1418
+ ### Week 4: Semantic Search Implementation
1419
+
1420
+ **Hybrid Search: Vector Similarity + Keyword Matching using ontology entities table**
1421
+
1422
+ #### Vector Embeddings
1423
+
1424
+ **File**: `convex/embeddings/generate.ts`
1425
+
1426
+ ```typescript
1427
+ "use node";
1428
+ import { v } from "convex/values";
1429
+ import { internalAction } from "./_generated/server";
1430
+ import { internal } from "./_generated/api";
1431
+ import OpenAI from "openai";
1432
+
1433
+ const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
1434
+
1435
+ export const generateEntityEmbedding = internalAction({
1436
+ args: { entityId: v.id("entities") },
1437
+ handler: async (ctx, args) => {
1438
+ // Get entity
1439
+ const entity = await ctx.runQuery(internal.entities.get, {
1440
+ id: args.entityId,
1441
+ });
1442
+
1443
+ if (!entity) {
1444
+ throw new Error("Entity not found");
1445
+ }
1446
+
1447
+ // Create searchable text from entity
1448
+ const text = `${entity.name}\n${entity.properties?.description || ""}\n${
1449
+ entity.properties?.content || ""
1450
+ }`;
1451
+
1452
+ // Generate embedding
1453
+ const response = await openai.embeddings.create({
1454
+ model: "text-embedding-3-small",
1455
+ input: text,
1456
+ dimensions: 1536,
1457
+ });
1458
+
1459
+ // Save embedding
1460
+ await ctx.runMutation(internal.embeddings.save, {
1461
+ entityId: args.entityId,
1462
+ embedding: response.data[0].embedding,
1463
+ model: "text-embedding-3-small",
1464
+ });
1465
+
1466
+ return { success: true };
1467
+ },
1468
+ });
1469
+ ```
1470
+
1471
+ **File**: `convex/embeddings/save.ts`
1472
+
1473
+ ```typescript
1474
+ import { v } from "convex/values";
1475
+ import { internalMutation } from "./_generated/server";
1476
+
1477
+ export const save = internalMutation({
1478
+ args: {
1479
+ entityId: v.id("entities"),
1480
+ embedding: v.array(v.float64()),
1481
+ model: v.string(),
1482
+ },
1483
+ handler: async (ctx, args) => {
1484
+ // Check if embedding exists
1485
+ const existing = await ctx.db
1486
+ .query("embeddings")
1487
+ .withIndex("by_entity", (q) => q.eq("entityId", args.entityId))
1488
+ .unique();
1489
+
1490
+ if (existing) {
1491
+ // Update existing
1492
+ await ctx.db.patch(existing._id, {
1493
+ embedding: args.embedding,
1494
+ model: args.model,
1495
+ createdAt: Date.now(),
1496
+ });
1497
+ } else {
1498
+ // Create new
1499
+ await ctx.db.insert("embeddings", {
1500
+ entityId: args.entityId,
1501
+ embedding: args.embedding,
1502
+ model: args.model,
1503
+ createdAt: Date.now(),
1504
+ });
1505
+ }
1506
+
1507
+ return { success: true };
1508
+ },
1509
+ });
1510
+ ```
1511
+
1512
+ #### Semantic Search Query
1513
+
1514
+ **File**: `convex/search/semantic.ts`
1515
+
1516
+ ```typescript
1517
+ "use node";
1518
+ import { v } from "convex/values";
1519
+ import { action } from "./_generated/server";
1520
+ import { internal } from "./_generated/api";
1521
+ import OpenAI from "openai";
1522
+
1523
+ const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
1524
+
1525
+ export const semanticSearch = action({
1526
+ args: {
1527
+ query: v.string(),
1528
+ entityTypes: v.optional(v.array(v.string())),
1529
+ limit: v.optional(v.number()),
1530
+ },
1531
+ handler: async (ctx, args) => {
1532
+ // Generate query embedding
1533
+ const response = await openai.embeddings.create({
1534
+ model: "text-embedding-3-small",
1535
+ input: args.query,
1536
+ dimensions: 1536,
1537
+ });
1538
+
1539
+ const queryEmbedding = response.data[0].embedding;
1540
+
1541
+ // Vector search on embeddings table
1542
+ const results = await ctx.vectorSearch("embeddings", "by_embedding", {
1543
+ vector: queryEmbedding,
1544
+ limit: args.limit || 20,
1545
+ });
1546
+
1547
+ // Hydrate entities and filter by type if specified
1548
+ const entities = await Promise.all(
1549
+ results.map(async (r) => {
1550
+ const entity = await ctx.runQuery(internal.entities.get, {
1551
+ id: r._id,
1552
+ });
1553
+ return { entity, score: r._score };
1554
+ })
1555
+ );
1556
+
1557
+ // Filter by entity type if specified
1558
+ const filtered = args.entityTypes
1559
+ ? entities.filter((e) => args.entityTypes!.includes(e.entity?.type || ""))
1560
+ : entities;
1561
+
1562
+ return filtered.map((e) => e.entity);
1563
+ },
1564
+ });
1565
+
1566
+ // Hybrid search combining vector similarity and keyword matching
1567
+ export const hybridSearch = action({
1568
+ args: {
1569
+ query: v.string(),
1570
+ entityTypes: v.optional(v.array(v.string())),
1571
+ limit: v.optional(v.number()),
1572
+ },
1573
+ handler: async (ctx, args) => {
1574
+ // Run semantic search
1575
+ const semanticResults = await ctx.runAction(internal.search.semanticSearch, {
1576
+ query: args.query,
1577
+ entityTypes: args.entityTypes,
1578
+ limit: args.limit,
1579
+ });
1580
+
1581
+ // Run keyword search using search index
1582
+ const keywordResults = await ctx.runQuery(internal.search.keywordSearch, {
1583
+ query: args.query,
1584
+ entityTypes: args.entityTypes,
1585
+ limit: args.limit,
1586
+ });
1587
+
1588
+ // Combine and deduplicate results
1589
+ const combined = new Map();
1590
+ semanticResults.forEach((entity) => combined.set(entity._id, entity));
1591
+ keywordResults.forEach((entity) => combined.set(entity._id, entity));
1592
+
1593
+ return Array.from(combined.values());
1594
+ },
1595
+ });
1596
+ ```
1597
+
1598
+ **Search UI**: Real-time results with filters (entity type, tags, status), debounced input, instant previews.
1599
+
1600
+ **Success Criteria**: ✅ Semantic search returns relevant results, ✅ Sub-300ms response time, ✅ Works for all entity types
1601
+
1602
+ ---
1603
+
1604
+ ## Phase 3: Viral Growth & ELEVATE (Weeks 5-6)
1605
+
1606
+ ### Week 5: ELEVATE Journey System
1607
+
1608
+ **9-Step Candy Crush-Style Progress System**
1609
+
1610
+ #### Journey Steps (ELEVATE Framework)
1611
+
1612
+ 1. **Hook** - Capture attention with free AI business analysis
1613
+ 2. **Gift** - Provide immediate value (insights report)
1614
+ 3. **Identify** - Payment gate ($100) - qualify serious users
1615
+ 4. **Engage** - Interactive workshops and tools
1616
+ 5. **Sell** - Core product/service delivery
1617
+ 6. **Nurture** - Ongoing support and resources
1618
+ 7. **Upsell** - Premium features and services
1619
+ 8. **Understand** - Analytics and optimization
1620
+ 9. **Share** - Referral rewards and viral loop
1621
+
1622
+ #### Workflow Implementation
1623
+
1624
+ **File**: `convex/elevate/journey.ts`
1625
+
1626
+ ```typescript
1627
+ import { WorkflowManager } from "@convex-dev/workflow";
1628
+
1629
+ const workflow = new WorkflowManager(components.workflow);
1630
+
1631
+ export const elevateJourney = workflow.define({
1632
+ defaultRetryBehavior: { maxAttempts: 3, initialBackoffMs: 1000 }
1633
+ }, async (ctx, { userId, journeyId }) => {
1634
+
1635
+ // Step 1: Hook - Generate AI analysis
1636
+ await ctx.step("hook", async () => {
1637
+ const analysis = await ctx.runAction(internal.ai.generateBusinessAnalysis, {
1638
+ userId,
1639
+ });
1640
+ await ctx.runMutation(internal.elevate.saveStep, {
1641
+ userId,
1642
+ stepId: "hook",
1643
+ status: "completed",
1644
+ output: analysis,
1645
+ });
1646
+ });
1647
+
1648
+ // Wait for user to review (24 hours)
1649
+ await ctx.wait(24 * 60 * 60 * 1000);
1650
+
1651
+ // Step 2: Gift - Deliver insights
1652
+ await ctx.step("gift", async () => {
1653
+ await ctx.runMutation(internal.notifications.sendInsightsReport, { userId });
1654
+ });
1655
+
1656
+ // Step 3: Identify - Payment gate
1657
+ await ctx.step("identify", async () => {
1658
+ const paid = await waitForPayment(ctx, userId, 100);
1659
+ if (!paid) {
1660
+ throw new Error("Payment not completed");
1661
+ }
1662
+ });
1663
+
1664
+ // Continue remaining steps...
1665
+
1666
+ return { completed: true };
1667
+ });
1668
+ ```
1669
+
1670
+ #### Visual Journey UI
1671
+
1672
+ **File**: `src/components/features/elevate/JourneyMap.tsx`
1673
+
1674
+ **Features**:
1675
+
1676
+ - SVG path visualization (Candy Crush style)
1677
+ - Step nodes with lock/unlock states
1678
+ - Star ratings (1-3 per step)
1679
+ - Progress percentage
1680
+ - Achievement badges
1681
+ - Animated transitions
1682
+
1683
+ **Pattern**:
1684
+
1685
+ ```typescript
1686
+ <svg viewBox="0 0 800 600">
1687
+ <path d="M 100,300 Q 200,100 400,300 T 700,300" />
1688
+ {steps.map((step, i) => (
1689
+ <g key={step.id}>
1690
+ <circle
1691
+ cx={positions[i].x}
1692
+ cy={positions[i].y}
1693
+ r="30"
1694
+ className={step.status === 'completed' ? 'fill-green' : 'fill-gray'}
1695
+ />
1696
+ <text>{step.name}</text>
1697
+ </g>
1698
+ ))}
1699
+ </svg>
1700
+ ```
1701
+
1702
+ **Payment Gate**: Integrated Stripe checkout modal at "Identify" step.
1703
+
1704
+ **Success Criteria**: ✅ All 9 steps functional, ✅ Payment gate works, ✅ Progress persists, ✅ Workflows resume after restart
1705
+
1706
+ ---
1707
+
1708
+ ### Week 6: Viral Invitation System
1709
+
1710
+ **Magic Links + Referral Tracking**
1711
+
1712
+ #### Magic Link Generation
1713
+
1714
+ **File**: `convex/invitations/magicLinks.ts`
1715
+
1716
+ ```typescript
1717
+ export const generateMagicLink = mutation({
1718
+ args: {
1719
+ email: v.string(),
1720
+ referralCode: v.string(),
1721
+ },
1722
+ handler: async (ctx, args) => {
1723
+ const token = crypto.randomBytes(32).toString("base64url");
1724
+
1725
+ await ctx.db.insert("events", {
1726
+ eventType: "invitation_created",
1727
+ timestamp: Date.now(),
1728
+ metadata: {
1729
+ email: args.email,
1730
+ token,
1731
+ referralCode: args.referralCode,
1732
+ expiresAt: Date.now() + (60 * 60 * 1000), // 1 hour
1733
+ },
1734
+ });
1735
+
1736
+ return `https://one.ie/invite/${token}`;
1737
+ },
1738
+ });
1739
+ ```
1740
+
1741
+ #### Auto-Registration Flow
1742
+
1743
+ **File**: `src/pages/invite/[token].astro`
1744
+
1745
+ ```typescript
1746
+ // Server-side validation
1747
+ const { token } = Astro.params;
1748
+ const invitation = await convex.query(api.invitations.verify, { token });
1749
+
1750
+ if (invitation.valid) {
1751
+ // Auto-register user
1752
+ const userId = await convex.mutation(api.auth.autoRegister, {
1753
+ email: invitation.email,
1754
+ referredBy: invitation.referralCode,
1755
+ });
1756
+
1757
+ // Create session and redirect
1758
+ return Astro.redirect("/dashboard");
1759
+ }
1760
+ ```
1761
+
1762
+ #### Referral Tracking
1763
+
1764
+ **Schema**: Track referrer → referred → conversion pipeline
1765
+
1766
+ **Commission Model**:
1767
+
1768
+ - 10% of referred user's first transaction
1769
+ - Tiered bonuses (5 referrals = $50 bonus, 25 = $500)
1770
+ - Lifetime tracking with attribution
1771
+
1772
+ **Bulk Invitations**: Queue-based processing for 100+ invitations with personalized messages.
1773
+
1774
+ **Success Criteria**: ✅ Magic links work reliably, ✅ Auto-registration smooth, ✅ Referral commissions accurate, ✅ K-factor > 1
1775
+
1776
+ ---
1777
+
1778
+ ## Phase 4: Scale & Production Readiness (Weeks 7-8)
1779
+
1780
+ ### Week 7: AI Agent Marketplace
1781
+
1782
+ **10 Business Agent Types from Ontology (strategy, research, marketing, sales, service, design, engineering, finance, legal, intelligence)**
1783
+
1784
+ #### Agent Registry
1785
+
1786
+ **File**: `convex/agents/register.ts`
1787
+
1788
+ ```typescript
1789
+ import { v } from "convex/values";
1790
+ import { mutation } from "./_generated/server";
1791
+
1792
+ export const registerAgent = mutation({
1793
+ args: {
1794
+ creatorId: v.id("entities"),
1795
+ agentType: v.union(
1796
+ v.literal("strategy_agent"),
1797
+ v.literal("research_agent"),
1798
+ v.literal("marketing_agent"),
1799
+ v.literal("sales_agent"),
1800
+ v.literal("service_agent"),
1801
+ v.literal("design_agent"),
1802
+ v.literal("engineering_agent"),
1803
+ v.literal("finance_agent"),
1804
+ v.literal("legal_agent"),
1805
+ v.literal("intelligence_agent")
1806
+ ),
1807
+ name: v.string(),
1808
+ description: v.string(),
1809
+ capabilities: v.array(v.string()),
1810
+ systemPrompt: v.string(),
1811
+ pricingModel: v.union(
1812
+ v.literal("per_request"),
1813
+ v.literal("token_based"),
1814
+ v.literal("subscription")
1815
+ ),
1816
+ basePrice: v.number(),
1817
+ tags: v.optional(v.array(v.string())),
1818
+ },
1819
+ handler: async (ctx, args) => {
1820
+ // Validate creator exists
1821
+ const creator = await ctx.db.get(args.creatorId);
1822
+ if (!creator || creator.type !== "creator") {
1823
+ throw new Error("Creator not found");
1824
+ }
1825
+
1826
+ // Create agent entity
1827
+ const agentId = await ctx.db.insert("entities", {
1828
+ type: args.agentType,
1829
+ name: args.name,
1830
+ properties: {
1831
+ description: args.description,
1832
+ capabilities: args.capabilities,
1833
+ systemPrompt: args.systemPrompt,
1834
+ model: "gpt-4-turbo",
1835
+ temperature: 0.7,
1836
+ pricingModel: args.pricingModel,
1837
+ basePrice: args.basePrice,
1838
+ totalExecutions: 0,
1839
+ successRate: 0,
1840
+ averageExecutionTime: 0,
1841
+ },
1842
+ status: "active",
1843
+ createdAt: Date.now(),
1844
+ updatedAt: Date.now(),
1845
+ });
1846
+
1847
+ // Create ownership connection
1848
+ await ctx.db.insert("connections", {
1849
+ fromEntityId: args.creatorId,
1850
+ toEntityId: agentId,
1851
+ relationshipType: "owns",
1852
+ metadata: { revenueShare: 1.0 },
1853
+ createdAt: Date.now(),
1854
+ });
1855
+
1856
+ // Add tags
1857
+ if (args.tags) {
1858
+ for (const tagName of args.tags) {
1859
+ let tag = await ctx.db
1860
+ .query("tags")
1861
+ .withIndex("by_name", (q) => q.eq("name", tagName))
1862
+ .unique();
1863
+
1864
+ if (!tag) {
1865
+ const tagId = await ctx.db.insert("tags", {
1866
+ name: tagName,
1867
+ category: "technology",
1868
+ usageCount: 0,
1869
+ createdAt: Date.now(),
1870
+ });
1871
+ tag = await ctx.db.get(tagId);
1872
+ }
1873
+
1874
+ await ctx.db.insert("entityTags", {
1875
+ entityId: agentId,
1876
+ tagId: tag!._id,
1877
+ createdAt: Date.now(),
1878
+ });
1879
+
1880
+ await ctx.db.patch(tag!._id, {
1881
+ usageCount: tag!.usageCount + 1,
1882
+ });
1883
+ }
1884
+ }
1885
+
1886
+ // Log entity creation event with agent-specific metadata
1887
+ await ctx.db.insert("events", {
1888
+ entityId: agentId,
1889
+ eventType: "entity_created",
1890
+ timestamp: Date.now(),
1891
+ actorType: "user",
1892
+ actorId: args.creatorId,
1893
+ metadata: {
1894
+ entityType: args.agentType,
1895
+ pricingModel: args.pricingModel,
1896
+ basePrice: args.basePrice,
1897
+ capabilities: args.capabilities,
1898
+ },
1899
+ });
1900
+
1901
+ return { agentId, success: true };
1902
+ },
1903
+ });
1904
+ ```
1905
+
1906
+ #### Agent Execution
1907
+
1908
+ **File**: `convex/agents/execute.ts`
1909
+
1910
+ ```typescript
1911
+ "use node";
1912
+ import { v } from "convex/values";
1913
+ import { action } from "./_generated/server";
1914
+ import { internal } from "./_generated/api";
1915
+ import OpenAI from "openai";
1916
+
1917
+ const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
1918
+
1919
+ export const invokeAgent = action({
1920
+ args: {
1921
+ agentId: v.id("entities"),
1922
+ userId: v.id("entities"),
1923
+ message: v.string(),
1924
+ },
1925
+ handler: async (ctx, args) => {
1926
+ const startTime = Date.now();
1927
+
1928
+ // Get agent configuration
1929
+ const agent = await ctx.runQuery(internal.agents.get, {
1930
+ id: args.agentId,
1931
+ });
1932
+
1933
+ if (!agent || !agent.type.endsWith("_agent")) {
1934
+ throw new Error("Agent not found");
1935
+ }
1936
+
1937
+ // Execute agent with OpenAI
1938
+ const response = await openai.chat.completions.create({
1939
+ model: agent.properties.model || "gpt-4-turbo",
1940
+ messages: [
1941
+ { role: "system", content: agent.properties.systemPrompt },
1942
+ { role: "user", content: args.message },
1943
+ ],
1944
+ temperature: agent.properties.temperature || 0.7,
1945
+ });
1946
+
1947
+ const executionTime = Date.now() - startTime;
1948
+ const aiResponse = response.choices[0].message.content || "";
1949
+
1950
+ // Track invocation (update metrics)
1951
+ await ctx.runMutation(internal.agents.trackInvocation, {
1952
+ agentId: args.agentId,
1953
+ executionTime,
1954
+ success: true,
1955
+ });
1956
+
1957
+ // Log agent execution event with success status in metadata
1958
+ await ctx.runMutation(internal.events.create, {
1959
+ entityId: args.agentId,
1960
+ eventType: "agent_executed",
1961
+ actorType: "user",
1962
+ actorId: args.userId,
1963
+ metadata: {
1964
+ status: "success",
1965
+ message: args.message,
1966
+ response: aiResponse,
1967
+ executionTime,
1968
+ tokensUsed: response.usage?.total_tokens || 0,
1969
+ },
1970
+ });
1971
+
1972
+ return {
1973
+ response: aiResponse,
1974
+ executionTime,
1975
+ tokensUsed: response.usage?.total_tokens || 0,
1976
+ };
1977
+ },
1978
+ });
1979
+ ```
1980
+
1981
+ **File**: `convex/agents/trackInvocation.ts`
1982
+
1983
+ ```typescript
1984
+ import { v } from "convex/values";
1985
+ import { internalMutation } from "./_generated/server";
1986
+
1987
+ export const trackInvocation = internalMutation({
1988
+ args: {
1989
+ agentId: v.id("entities"),
1990
+ executionTime: v.number(),
1991
+ success: v.boolean(),
1992
+ },
1993
+ handler: async (ctx, args) => {
1994
+ const agent = await ctx.db.get(args.agentId);
1995
+ if (!agent) return;
1996
+
1997
+ const totalExecutions = agent.properties.totalExecutions || 0;
1998
+ const successRate = agent.properties.successRate || 0;
1999
+ const avgExecTime = agent.properties.averageExecutionTime || 0;
2000
+
2001
+ // Update metrics
2002
+ const newTotalExecutions = totalExecutions + 1;
2003
+ const newSuccessRate =
2004
+ (successRate * totalExecutions + (args.success ? 1 : 0)) / newTotalExecutions;
2005
+ const newAvgExecTime =
2006
+ (avgExecTime * totalExecutions + args.executionTime) / newTotalExecutions;
2007
+
2008
+ await ctx.db.patch(args.agentId, {
2009
+ properties: {
2010
+ ...agent.properties,
2011
+ totalExecutions: newTotalExecutions,
2012
+ successRate: newSuccessRate,
2013
+ averageExecutionTime: newAvgExecTime,
2014
+ },
2015
+ updatedAt: Date.now(),
2016
+ });
2017
+ },
2018
+ });
2019
+ ```
2020
+
2021
+ #### Agent Marketplace UI
2022
+
2023
+ **File**: `src/components/features/agents/AgentMarketplace.tsx`
2024
+
2025
+ **Features**:
2026
+
2027
+ - Browse by category/capability
2028
+ - Try before you buy (free tier)
2029
+ - Usage-based billing
2030
+ - Rating and review system
2031
+ - Agent-to-agent delegation
2032
+
2033
+ **Success Criteria**: ✅ Agents execute reliably, ✅ Billing tracks usage accurately, ✅ UI responsive and intuitive
2034
+
2035
+ ---
2036
+
2037
+ ### Week 8: Analytics & Optimization
2038
+
2039
+ **Dashboard for Revenue, Engagement, and Performance Metrics**
2040
+
2041
+ #### Analytics Implementation
2042
+
2043
+ **File**: `convex/analytics/dashboards.ts`
2044
+
2045
+ ```typescript
2046
+ export const getRevenueMetrics = query({
2047
+ args: { timeRange: v.string() },
2048
+ handler: async (ctx, args) => {
2049
+ // Query consolidated payment events
2050
+ const payments = await ctx.db
2051
+ .query("events")
2052
+ .withIndex("by_type_time", (q) =>
2053
+ q.eq("eventType", "payment_processed")
2054
+ .gte("timestamp", getTimeRangeStart(args.timeRange))
2055
+ )
2056
+ .collect();
2057
+
2058
+ // Filter to completed payments only using metadata
2059
+ const completedPayments = payments.filter(
2060
+ (p) => p.metadata?.status === "completed"
2061
+ );
2062
+
2063
+ const totalRevenue = completedPayments.reduce(
2064
+ (sum, p) => sum + (p.metadata?.amount || 0),
2065
+ 0
2066
+ );
2067
+
2068
+ const platformFees = completedPayments.reduce(
2069
+ (sum, p) => sum + (p.metadata?.platformFee || 0),
2070
+ 0
2071
+ );
2072
+
2073
+ return {
2074
+ totalRevenue,
2075
+ platformFees,
2076
+ transactionCount: completedPayments.length,
2077
+ averageOrderValue: totalRevenue / completedPayments.length || 0,
2078
+ statusBreakdown: {
2079
+ initiated: payments.filter((p) => p.metadata?.status === "initiated").length,
2080
+ completed: completedPayments.length,
2081
+ failed: payments.filter((p) => p.metadata?.status === "failed").length,
2082
+ refunded: payments.filter((p) => p.metadata?.status === "refunded").length,
2083
+ },
2084
+ };
2085
+ },
2086
+ });
2087
+
2088
+ export const getElevateAnalytics = query({
2089
+ args: {},
2090
+ handler: async (ctx) => {
2091
+ // Query progress_updated events for journey tracking
2092
+ const progressEvents = await ctx.db
2093
+ .query("events")
2094
+ .withIndex("by_eventType", (q) => q.eq("eventType", "progress_updated"))
2095
+ .filter((q) => q.eq(q.field("metadata.journeyType"), "elevate"))
2096
+ .collect();
2097
+
2098
+ // Calculate step completion rates using metadata
2099
+ const stepCounts = {};
2100
+ progressEvents.forEach((event) => {
2101
+ const step = event.metadata?.stepId;
2102
+ if (step) {
2103
+ stepCounts[step] = (stepCounts[step] || 0) + 1;
2104
+ }
2105
+ });
2106
+
2107
+ return {
2108
+ totalJourneys: new Set(progressEvents.map((e) => e.actorId)).size,
2109
+ stepCompletionRates: stepCounts,
2110
+ conversionRate: (stepCounts["share"] || 0) / (stepCounts["hook"] || 1),
2111
+ };
2112
+ },
2113
+ });
2114
+ ```
2115
+
2116
+ #### Analytics Dashboard UI
2117
+
2118
+ **File**: `src/pages/analytics/index.astro`
2119
+
2120
+ **Charts**:
2121
+
2122
+ - Revenue over time (line chart)
2123
+ - Transaction volume (bar chart)
2124
+ - ELEVATE funnel (funnel chart)
2125
+ - Top-performing blocks (table)
2126
+ - User engagement heatmap
2127
+ - Real-time activity feed
2128
+
2129
+ **Libraries**: Recharts for React components, TailwindCSS for styling.
2130
+
2131
+ **Success Criteria**: ✅ All metrics accurate, ✅ Real-time updates, ✅ Export functionality, ✅ Sub-second load times
2132
+
2133
+ ---
2134
+
2135
+ ## Effect.ts Service Layer Integration
2136
+
2137
+ **Production-Grade Error Handling & Dependency Injection**
2138
+
2139
+ ### Typed Error Channels
2140
+
2141
+ **Purpose**: All errors are typed and explicit - no silent failures or generic error handling.
2142
+
2143
+ ```typescript
2144
+ import { Effect, Data } from "effect";
2145
+
2146
+ // Define typed error classes
2147
+ class ValidationError extends Data.TaggedError("ValidationError")<{
2148
+ field: string;
2149
+ message: string;
2150
+ }> {}
2151
+
2152
+ class DatabaseError extends Data.TaggedError("DatabaseError")<{
2153
+ operation: string;
2154
+ cause: unknown;
2155
+ }> {}
2156
+
2157
+ class ExternalServiceError extends Data.TaggedError("ExternalServiceError")<{
2158
+ service: string;
2159
+ statusCode?: number;
2160
+ message: string;
2161
+ }> {}
2162
+
2163
+ class NotFoundError extends Data.TaggedError("NotFoundError")<{
2164
+ entityType: string;
2165
+ entityId: string;
2166
+ }> {}
2167
+ ```
2168
+
2169
+ ### Service Layer Architecture
2170
+
2171
+ **File**: `convex/services/entities.ts`
2172
+
2173
+ ```typescript
2174
+ import { Effect, Layer, Context } from "effect";
2175
+ import { v } from "convex/values";
2176
+
2177
+ // Define service interface with typed errors
2178
+ class EntityService extends Context.Tag("EntityService")<
2179
+ EntityService,
2180
+ {
2181
+ create: (data: EntityCreateData) => Effect.Effect<
2182
+ string, // Success type: entity ID
2183
+ ValidationError | DatabaseError // Error types
2184
+ >;
2185
+ get: (id: string) => Effect.Effect<
2186
+ Entity,
2187
+ NotFoundError | DatabaseError
2188
+ >;
2189
+ update: (id: string, data: Partial<Entity>) => Effect.Effect<
2190
+ void,
2191
+ NotFoundError | ValidationError | DatabaseError
2192
+ >;
2193
+ search: (query: string) => Effect.Effect<
2194
+ Entity[],
2195
+ ExternalServiceError | DatabaseError
2196
+ >;
2197
+ }
2198
+ >() {}
2199
+
2200
+ // Implementation
2201
+ const EntityServiceLive = Layer.effect(
2202
+ EntityService,
2203
+ Effect.gen(function* () {
2204
+ const db = yield* DatabaseService;
2205
+ const embeddings = yield* EmbeddingService;
2206
+
2207
+ return {
2208
+ create: (data: EntityCreateData) =>
2209
+ Effect.gen(function* () {
2210
+ // Validation with typed error
2211
+ if (!data.name || data.name.trim().length === 0) {
2212
+ return yield* Effect.fail(
2213
+ new ValidationError({
2214
+ field: "name",
2215
+ message: "Name is required and cannot be empty",
2216
+ })
2217
+ );
2218
+ }
2219
+
2220
+ if (!data.type) {
2221
+ return yield* Effect.fail(
2222
+ new ValidationError({
2223
+ field: "type",
2224
+ message: "Entity type is required",
2225
+ })
2226
+ );
2227
+ }
2228
+
2229
+ // Create entity with error handling
2230
+ const entityId = yield* Effect.tryPromise({
2231
+ try: () =>
2232
+ db.insert("entities", {
2233
+ type: data.type,
2234
+ name: data.name,
2235
+ properties: data.properties || {},
2236
+ status: data.status || "active",
2237
+ createdAt: Date.now(),
2238
+ updatedAt: Date.now(),
2239
+ }),
2240
+ catch: (error) =>
2241
+ new DatabaseError({
2242
+ operation: "insert",
2243
+ cause: error,
2244
+ }),
2245
+ });
2246
+
2247
+ // Generate embedding asynchronously (errors logged but don't fail creation)
2248
+ yield* embeddings
2249
+ .generate(entityId)
2250
+ .pipe(
2251
+ Effect.catchAll((error) =>
2252
+ Effect.logWarning(`Failed to generate embedding: ${error}`)
2253
+ )
2254
+ );
2255
+
2256
+ return entityId;
2257
+ }),
2258
+
2259
+ get: (id: string) =>
2260
+ Effect.gen(function* () {
2261
+ const entity = yield* Effect.tryPromise({
2262
+ try: () => db.get(id),
2263
+ catch: (error) =>
2264
+ new DatabaseError({
2265
+ operation: "get",
2266
+ cause: error,
2267
+ }),
2268
+ });
2269
+
2270
+ if (!entity) {
2271
+ return yield* Effect.fail(
2272
+ new NotFoundError({
2273
+ entityType: "entity",
2274
+ entityId: id,
2275
+ })
2276
+ );
2277
+ }
2278
+
2279
+ return entity;
2280
+ }),
2281
+
2282
+ update: (id: string, data: Partial<Entity>) =>
2283
+ Effect.gen(function* () {
2284
+ // Check entity exists
2285
+ yield* Effect.get(id);
2286
+
2287
+ // Validation
2288
+ if (data.name !== undefined && data.name.trim().length === 0) {
2289
+ return yield* Effect.fail(
2290
+ new ValidationError({
2291
+ field: "name",
2292
+ message: "Name cannot be empty",
2293
+ })
2294
+ );
2295
+ }
2296
+
2297
+ // Update entity
2298
+ yield* Effect.tryPromise({
2299
+ try: () =>
2300
+ db.patch(id, {
2301
+ ...data,
2302
+ updatedAt: Date.now(),
2303
+ }),
2304
+ catch: (error) =>
2305
+ new DatabaseError({
2306
+ operation: "update",
2307
+ cause: error,
2308
+ }),
2309
+ });
2310
+ }),
2311
+
2312
+ search: (query: string) =>
2313
+ Effect.gen(function* () {
2314
+ // Generate query embedding
2315
+ const embedding = yield* embeddings
2316
+ .generateQuery(query)
2317
+ .pipe(
2318
+ Effect.mapError(
2319
+ (error) =>
2320
+ new ExternalServiceError({
2321
+ service: "OpenAI",
2322
+ message: `Failed to generate embedding: ${error}`,
2323
+ })
2324
+ )
2325
+ );
2326
+
2327
+ // Vector search
2328
+ const results = yield* Effect.tryPromise({
2329
+ try: () => db.vectorSearch("embeddings", { vector: embedding }),
2330
+ catch: (error) =>
2331
+ new DatabaseError({
2332
+ operation: "vectorSearch",
2333
+ cause: error,
2334
+ }),
2335
+ });
2336
+
2337
+ return results;
2338
+ }),
2339
+ };
2340
+ })
2341
+ );
2342
+ ```
2343
+
2344
+ ### Usage in Convex Functions
2345
+
2346
+ **File**: `convex/entities/create.ts`
2347
+
2348
+ ```typescript
2349
+ import { mutation } from "./_generated/server";
2350
+ import { v } from "convex/values";
2351
+ import { Effect } from "effect";
2352
+ import { EntityService, ValidationError, DatabaseError } from "../services/entities";
2353
+ import { MainLayer } from "../services/layers";
2354
+
2355
+ export const createEntity = mutation({
2356
+ args: {
2357
+ type: v.string(),
2358
+ name: v.string(),
2359
+ properties: v.optional(v.any()),
2360
+ },
2361
+ handler: async (ctx, args) => {
2362
+ const program = Effect.gen(function* () {
2363
+ const service = yield* EntityService;
2364
+ return yield* service.create({
2365
+ type: args.type,
2366
+ name: args.name,
2367
+ properties: args.properties,
2368
+ });
2369
+ });
2370
+
2371
+ // Run program with explicit error handling
2372
+ const result = await Effect.runPromise(
2373
+ program.pipe(
2374
+ Effect.provide(MainLayer),
2375
+ Effect.catchTags({
2376
+ ValidationError: (error) =>
2377
+ Effect.succeed({
2378
+ success: false,
2379
+ error: "validation",
2380
+ field: error.field,
2381
+ message: error.message,
2382
+ }),
2383
+ DatabaseError: (error) =>
2384
+ Effect.succeed({
2385
+ success: false,
2386
+ error: "database",
2387
+ message: "Failed to create entity",
2388
+ }),
2389
+ }),
2390
+ Effect.map((entityId) => ({
2391
+ success: true,
2392
+ entityId,
2393
+ }))
2394
+ )
2395
+ );
2396
+
2397
+ return result;
2398
+ },
2399
+ });
2400
+ ```
2401
+
2402
+ ### Testing with Mocked Services
2403
+
2404
+ **File**: `convex/services/entities.test.ts`
2405
+
2406
+ ```typescript
2407
+ import { Effect, Layer } from "effect";
2408
+ import { EntityService, ValidationError } from "./entities";
2409
+
2410
+ const MockEntityService = Layer.succeed(EntityService, {
2411
+ create: () => Effect.succeed("mock-entity-id"),
2412
+ get: () => Effect.succeed({ _id: "mock-id", name: "Mock Entity" }),
2413
+ update: () => Effect.succeed(undefined),
2414
+ search: () => Effect.succeed([]),
2415
+ });
2416
+
2417
+ describe("EntityService", () => {
2418
+ test("creates entity successfully", async () => {
2419
+ const program = Effect.gen(function* () {
2420
+ const service = yield* EntityService;
2421
+ return yield* service.create({
2422
+ type: "creator",
2423
+ name: "Test Creator",
2424
+ });
2425
+ });
2426
+
2427
+ const result = await Effect.runPromise(
2428
+ program.pipe(Effect.provide(MockEntityService))
2429
+ );
2430
+
2431
+ expect(result).toBe("mock-entity-id");
2432
+ });
2433
+
2434
+ test("validates required fields", async () => {
2435
+ const program = Effect.gen(function* () {
2436
+ const service = yield* EntityService;
2437
+ return yield* service.create({
2438
+ type: "creator",
2439
+ name: "", // Invalid
2440
+ });
2441
+ });
2442
+
2443
+ const result = await Effect.runPromiseExit(
2444
+ program.pipe(Effect.provide(MockEntityService))
2445
+ );
2446
+
2447
+ if (Effect.isFailure(result)) {
2448
+ expect(result.cause._tag).toBe("ValidationError");
2449
+ }
2450
+ });
2451
+ });
2452
+ ```
2453
+
2454
+ **Benefits of Effect.ts Pattern**:
2455
+
2456
+ - **Typed error channels**: Every error is explicit in the type signature
2457
+ - **No silent failures**: Impossible to ignore errors
2458
+ - **Automatic dependency injection**: Services compose cleanly
2459
+ - **Testable**: Mock any dependency with `Layer.succeed`
2460
+ - **Composable**: Chain operations with `Effect.gen`
2461
+ - **Full observability**: Built-in logging and tracing
2462
+ - **Retry logic**: Built-in retry with backoff
2463
+ - **Concurrent operations**: Safe parallel execution with `Effect.all`
2464
+
2465
+ ### Advanced Pattern: Atomic Operations with Rollback
2466
+
2467
+ ```typescript
2468
+ export const createContentWithOwnership = Effect.gen(function* () {
2469
+ const entities = yield* EntityService;
2470
+ const connections = yield* ConnectionService;
2471
+ const events = yield* EventService;
2472
+
2473
+ // All operations or none (atomic)
2474
+ const contentId = yield* entities.create({
2475
+ type: "blog_post",
2476
+ name: "My Post",
2477
+ });
2478
+
2479
+ yield* connections.create({
2480
+ fromEntityId: creatorId,
2481
+ toEntityId: contentId,
2482
+ relationshipType: "owns",
2483
+ });
2484
+
2485
+ yield* events.log({
2486
+ entityId: contentId,
2487
+ eventType: "entity_created",
2488
+ metadata: { entityType: "blog_post" },
2489
+ });
2490
+
2491
+ return contentId;
2492
+ }).pipe(
2493
+ Effect.catchAll((error) =>
2494
+ Effect.gen(function* () {
2495
+ // Rollback logic here
2496
+ yield* Effect.logError(`Transaction failed: ${error}`);
2497
+ return yield* Effect.fail(error);
2498
+ })
2499
+ )
2500
+ );
2501
+ ```
2502
+
2503
+ ---
2504
+
2505
+
2506
+
2507
+ ### Environment Setup
2508
+
2509
+ ```bash
2510
+ # Production
2511
+ CONVEX_DEPLOY_KEY=prod_xxx
2512
+ STRIPE_SECRET_KEY=sk_live_xxx
2513
+ STRIPE_WEBHOOK_SECRET=whsec_xxx
2514
+ CLERK_SECRET_KEY=sk_live_xxx
2515
+ OPENAI_API_KEY=sk-xxx
2516
+ SITE_URL=https://one.ie
2517
+
2518
+ # Monitoring
2519
+ AXIOM_API_KEY=xxx
2520
+ SENTRY_DSN=xxx
2521
+ ```
2522
+
2523
+ ---
2524
+
2525
+ ---
2526
+
2527
+ ## Risk Mitigation Matrix
2528
+
2529
+ |Risk|Likelihood|Impact|Mitigation|Owner|
2530
+ |---|---|---|---|---|
2531
+ |Payment failures|Medium|High|Stripe retry logic, clear error messages|Backend|
2532
+ |Migration data loss|Low|Critical|Batched processing, dual-write, backups|DevOps|
2533
+ |Performance degradation|Medium|High|Proper indexing, load testing, caching|Backend|
2534
+ |Security breach|Low|Critical|Security audit, penetration testing, bug bounty|Security|
2535
+ |Low user adoption|Medium|High|Beta testing, user interviews, onboarding optimization|Product|
2536
+ |Feature creep|High|Medium|Strict prioritization, MVP focus, iterative releases|PM|