oneie 2.0.2 → 2.0.3

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 (405) hide show
  1. package/AGENTS.md +245 -0
  2. package/CLAUDE.md +534 -0
  3. package/one/.obsidian/app.json +1 -0
  4. package/one/.obsidian/appearance.json +1 -0
  5. package/one/.obsidian/core-plugins.json +33 -0
  6. package/one/.obsidian/workspace.json +211 -0
  7. package/one/connections/a2a.md +551 -0
  8. package/one/connections/acp.md +761 -0
  9. package/one/connections/acps.md +731 -0
  10. package/one/connections/agui.md +767 -0
  11. package/one/connections/any-backend.md +1702 -0
  12. package/one/connections/ap2.md +998 -0
  13. package/one/connections/api-docs.md +1891 -0
  14. package/one/connections/api.md +2190 -0
  15. package/one/connections/architecture-diagram.md +94 -0
  16. package/one/connections/communications.md +449 -0
  17. package/one/connections/connections.md +339 -0
  18. package/one/connections/cryptonetworks.md +781 -0
  19. package/one/connections/documentation.md +1120 -0
  20. package/one/connections/effect.md +279 -0
  21. package/one/connections/elizaos.md +1290 -0
  22. package/one/connections/inference.md +58 -0
  23. package/one/connections/kyc.md +632 -0
  24. package/one/connections/mcp.md +842 -0
  25. package/one/connections/membership.md +1152 -0
  26. package/one/connections/middleware.md +1067 -0
  27. package/one/connections/multitenant.md +1341 -0
  28. package/one/connections/n8n.md +1015 -0
  29. package/one/connections/patterns.md +89 -0
  30. package/one/connections/protocols.md +279 -0
  31. package/one/connections/relationships.md +107 -0
  32. package/one/connections/schema.md +587 -0
  33. package/one/connections/service-layer.md +550 -0
  34. package/one/connections/structure.md +0 -0
  35. package/one/connections/vectors.md +207 -0
  36. package/one/connections/wordpress.md +1302 -0
  37. package/one/connections/workflow-copy.md +905 -0
  38. package/one/connections/workflow-examples.md +741 -0
  39. package/one/connections/workflow.md +905 -0
  40. package/one/connections/workflows/delegation.md +885 -0
  41. package/one/connections/workflows/frontend.md +1037 -0
  42. package/one/connections/workflows/strategy.md +903 -0
  43. package/one/connections/workflows/tasks.md +698 -0
  44. package/one/connections/x402.md +1249 -0
  45. package/one/events/events.md +545 -0
  46. package/one/knowledge/ai-platform.md +305 -0
  47. package/one/knowledge/architecture-diagram.md +94 -0
  48. package/one/knowledge/architecture-frontend.md +930 -0
  49. package/one/knowledge/architecture.md +2077 -0
  50. package/one/knowledge/crypto.md +960 -0
  51. package/one/knowledge/dsl.md +1660 -0
  52. package/one/knowledge/files.md +2471 -0
  53. package/one/knowledge/frontend.md +1038 -0
  54. package/one/knowledge/hono.md +2109 -0
  55. package/one/knowledge/implementation-examples.md +2536 -0
  56. package/one/knowledge/inference-score.md +159 -0
  57. package/one/knowledge/knowledge.md +642 -0
  58. package/one/knowledge/language.md +980 -0
  59. package/one/knowledge/lessons-learned.md +70 -0
  60. package/one/knowledge/ontology-6-dimensions.md +0 -0
  61. package/one/knowledge/ontology-documentation.md +356 -0
  62. package/one/knowledge/ontology-engineering-specification.md +1292 -0
  63. package/one/knowledge/ontology-engineering.md +1652 -0
  64. package/one/knowledge/ontology-frontend-copy-2.md +1492 -0
  65. package/one/knowledge/ontology-frontend-copy.md +753 -0
  66. package/one/knowledge/ontology-frontend-specifications.md +2188 -0
  67. package/one/knowledge/ontology-frontend.md +2427 -0
  68. package/one/knowledge/ontology-minimal.yaml +299 -0
  69. package/one/knowledge/ontology.md +2819 -0
  70. package/one/knowledge/ontology.yaml +1165 -0
  71. package/one/knowledge/patterns/backend/convex-mutation-pattern.md +100 -0
  72. package/one/knowledge/patterns/backend/convex-query-pattern.md +88 -0
  73. package/one/knowledge/patterns/backend/mutation-template.md +231 -0
  74. package/one/knowledge/patterns/backend/query-template.md +267 -0
  75. package/one/knowledge/patterns/backend/service-template.md +237 -0
  76. package/one/knowledge/patterns/design/component-architecture.md +399 -0
  77. package/one/knowledge/patterns/design/test-driven-design-pattern.md +162 -0
  78. package/one/knowledge/patterns/design/wireframe-template.md +216 -0
  79. package/one/knowledge/patterns/frontend/component-template.md +195 -0
  80. package/one/knowledge/patterns/frontend/form-template.md +276 -0
  81. package/one/knowledge/patterns/frontend/page-template.md +178 -0
  82. package/one/knowledge/patterns/frontend/react-component-pattern.md +128 -0
  83. package/one/knowledge/patterns/test/acceptance-criteria-template.md +378 -0
  84. package/one/knowledge/patterns/test/technical-test-template.md +544 -0
  85. package/one/knowledge/patterns/test/test-driven-pattern.md +140 -0
  86. package/one/knowledge/patterns/test/user-flow-template.md +254 -0
  87. package/one/knowledge/quality-loop.md +401 -0
  88. package/one/knowledge/readme.md +131 -0
  89. package/one/knowledge/rules.md +626 -0
  90. package/one/knowledge/score.md +67 -0
  91. package/one/knowledge/specifications.md +855 -0
  92. package/one/knowledge/tags.md +130 -0
  93. package/one/organisation/one.md +599 -0
  94. package/one/organisation/organisation.md +438 -0
  95. package/one/organisation/revenue.md +673 -0
  96. package/one/organisation/strategy.md +869 -0
  97. package/one/organisation/vision.md +98 -0
  98. package/one/people/anthony-o-connell.md +440 -0
  99. package/one/people/people.md +567 -0
  100. package/one/repomix-output.md +92634 -0
  101. package/one/things/agentkit.md +349 -0
  102. package/one/things/agents/agent-backend.md +1401 -0
  103. package/one/things/agents/agent-builder.md +955 -0
  104. package/one/things/agents/agent-clean.md +709 -0
  105. package/one/things/agents/agent-clone.md +1341 -0
  106. package/one/things/agents/agent-designer.md +2177 -0
  107. package/one/things/agents/agent-director.md +1508 -0
  108. package/one/things/agents/agent-documenter.md +1049 -0
  109. package/one/things/agents/agent-frontend.md +1119 -0
  110. package/one/things/agents/agent-integrator.md +1192 -0
  111. package/one/things/agents/agent-problem-solver.md +1379 -0
  112. package/one/things/agents/agent-quality.md +1353 -0
  113. package/one/things/agents/agent-sales.md +986 -0
  114. package/one/things/cascade/cascade.yaml +464 -0
  115. package/one/things/cascade/docs/examples/1-1-agent-prompts/design.md +470 -0
  116. package/one/things/cascade/docs/examples/1-1-agent-prompts/tests.md +264 -0
  117. package/one/things/cascade/docs/examples/1-1-agent-prompts.md +486 -0
  118. package/one/things/cascade/docs/examples/1-2-yaml-orchestrator/design.md +497 -0
  119. package/one/things/cascade/docs/examples/1-2-yaml-orchestrator/tests.md +227 -0
  120. package/one/things/cascade/docs/examples/1-2-yaml-orchestrator.md +516 -0
  121. package/one/things/cascade/docs/examples/1-3-event-coordination/design.md +544 -0
  122. package/one/things/cascade/docs/examples/1-3-event-coordination/tests.md +223 -0
  123. package/one/things/cascade/docs/examples/1-3-event-coordination.md +508 -0
  124. package/one/things/cascade/docs/examples/1-4-knowledge-management/design.md +609 -0
  125. package/one/things/cascade/docs/examples/1-4-knowledge-management/tests.md +195 -0
  126. package/one/things/cascade/docs/examples/1-4-knowledge-management.md +577 -0
  127. package/one/things/cascade/docs/examples/1-5-quality-loops/design.md +797 -0
  128. package/one/things/cascade/docs/examples/1-5-quality-loops/tests.md +212 -0
  129. package/one/things/cascade/docs/examples/1-5-quality-loops.md +641 -0
  130. package/one/things/cascade/docs/examples/1-6-numbering-structure/design.md +610 -0
  131. package/one/things/cascade/docs/examples/1-6-numbering-structure/tests.md +213 -0
  132. package/one/things/cascade/docs/examples/1-6-numbering-structure.md +575 -0
  133. package/one/things/cascade/docs/examples/readme.md +222 -0
  134. package/one/things/cascade/docs/getting-started.md +515 -0
  135. package/one/things/cascade/docs/workflow.md +1372 -0
  136. package/one/things/cascade/readme.md +336 -0
  137. package/one/things/cascade/templates/feature-template.md +267 -0
  138. package/one/things/claude/agents/advocacy-activation-manager.md +685 -0
  139. package/one/things/claude/agents/advocacy-campaign-designer.md +663 -0
  140. package/one/things/claude/agents/analyst.md +483 -0
  141. package/one/things/claude/agents/architect.md +480 -0
  142. package/one/things/claude/agents/brand-identity-specialist.md +513 -0
  143. package/one/things/claude/agents/bstp-token-strategist.md +667 -0
  144. package/one/things/claude/agents/builder-repo.md +489 -0
  145. package/one/things/claude/agents/bullstamp-community-builder.md +574 -0
  146. package/one/things/claude/agents/bullstamp-marketing-orchestrator.md +506 -0
  147. package/one/things/claude/agents/bulltilt-platform-growth.md +567 -0
  148. package/one/things/claude/agents/company-bullstamp-character.md +587 -0
  149. package/one/things/claude/agents/company-bullstamp-community.md +292 -0
  150. package/one/things/claude/agents/company-bullstamp-marketing.md +292 -0
  151. package/one/things/claude/agents/company-bullstamp-token.md +292 -0
  152. package/one/things/claude/agents/company-bulltilt-growth.md +292 -0
  153. package/one/things/claude/agents/content-bibliography-formatter.md +381 -0
  154. package/one/things/claude/agents/content-calendar-planner.md +448 -0
  155. package/one/things/claude/agents/content-chapter-formatter.md +488 -0
  156. package/one/things/claude/agents/content-formatter.md +546 -0
  157. package/one/things/claude/agents/content-hook-specialist.md +462 -0
  158. package/one/things/claude/agents/content-image-formatter.md +535 -0
  159. package/one/things/claude/agents/content-introduction-formatter.md +485 -0
  160. package/one/things/claude/agents/content-multiplication-engine.md +556 -0
  161. package/one/things/claude/agents/content-playbook-writer.md +448 -0
  162. package/one/things/claude/agents/content-team-manager.md +622 -0
  163. package/one/things/claude/agents/content-toc-formatter.md +522 -0
  164. package/one/things/claude/agents/convex-backend-specialist.md +2561 -0
  165. package/one/things/claude/agents/core-manager.md +582 -0
  166. package/one/things/claude/agents/core-master.md +403 -0
  167. package/one/things/claude/agents/cross-functional-manager.md +471 -0
  168. package/one/things/claude/agents/crypto-airdrop-strategist.md +602 -0
  169. package/one/things/claude/agents/crypto-analytics-educator.md +553 -0
  170. package/one/things/claude/agents/crypto-architecture-specialist.md +466 -0
  171. package/one/things/claude/agents/crypto-community-analyst.md +298 -0
  172. package/one/things/claude/agents/crypto-community-psychologist.md +509 -0
  173. package/one/things/claude/agents/crypto-dex-optimization-expert.md +538 -0
  174. package/one/things/claude/agents/crypto-dex-optimizer.md +292 -0
  175. package/one/things/claude/agents/crypto-diamond-formation-specialist.md +513 -0
  176. package/one/things/claude/agents/crypto-diamond-hands.md +292 -0
  177. package/one/things/claude/agents/crypto-ecosystem-expansion-manager.md +554 -0
  178. package/one/things/claude/agents/crypto-engagement-specialist.md +540 -0
  179. package/one/things/claude/agents/crypto-market-researcher.md +292 -0
  180. package/one/things/claude/agents/crypto-marketing-orchestrator.md +523 -0
  181. package/one/things/claude/agents/crypto-network-effect-amplifier.md +569 -0
  182. package/one/things/claude/agents/crypto-optimization-analyst.md +554 -0
  183. package/one/things/claude/agents/crypto-strategic-synthesizer.md +517 -0
  184. package/one/things/claude/agents/crypto-team-manager.md +387 -0
  185. package/one/things/claude/agents/crypto-token-analyst.md +278 -0
  186. package/one/things/claude/agents/crypto-viral-content-creator.md +546 -0
  187. package/one/things/claude/agents/crypto-wallet-identification-expert.md +517 -0
  188. package/one/things/claude/agents/crypto-wallet-identifier.md +292 -0
  189. package/one/things/claude/agents/customer-journey-designer.md +481 -0
  190. package/one/things/claude/agents/customer-success-manager.md +581 -0
  191. package/one/things/claude/agents/dev.md +413 -0
  192. package/one/things/claude/agents/documenter.md +546 -0
  193. package/one/things/claude/agents/elevate-marketing-orchestrator.md +410 -0
  194. package/one/things/claude/agents/engagement-specialist.md +509 -0
  195. package/one/things/claude/agents/engineering-architect.md +387 -0
  196. package/one/things/claude/agents/engineering-business-analyst.md +537 -0
  197. package/one/things/claude/agents/engineering-developer.md +387 -0
  198. package/one/things/claude/agents/engineering-director.md +282 -0
  199. package/one/things/claude/agents/engineering-ingestor.md +649 -0
  200. package/one/things/claude/agents/engineering-product-manager.md +537 -0
  201. package/one/things/claude/agents/engineering-product-owner.md +537 -0
  202. package/one/things/claude/agents/engineering-project-coordinator.md +537 -0
  203. package/one/things/claude/agents/engineering-quality-assurance.md +393 -0
  204. package/one/things/claude/agents/engineering-team-manager.md +512 -0
  205. package/one/things/claude/agents/engineering-user-experience.md +387 -0
  206. package/one/things/claude/agents/framework-elevate-manager.md +294 -0
  207. package/one/things/claude/agents/improver.md +763 -0
  208. package/one/things/claude/agents/intelligence-team-manager.md +385 -0
  209. package/one/things/claude/agents/lead-capture-expert.md +466 -0
  210. package/one/things/claude/agents/lead-magnet-creator.md +453 -0
  211. package/one/things/claude/agents/market-research-analyst.md +412 -0
  212. package/one/things/claude/agents/marketing-brand-identity.md +314 -0
  213. package/one/things/claude/agents/marketing-content-hooks.md +450 -0
  214. package/one/things/claude/agents/marketing-content-multiplier.md +326 -0
  215. package/one/things/claude/agents/marketing-content-poster.md +361 -0
  216. package/one/things/claude/agents/marketing-customer-journey.md +326 -0
  217. package/one/things/claude/agents/marketing-director.md +397 -0
  218. package/one/things/claude/agents/marketing-engagement.md +326 -0
  219. package/one/things/claude/agents/marketing-lead-capture.md +326 -0
  220. package/one/things/claude/agents/marketing-lead-magnet.md +326 -0
  221. package/one/things/claude/agents/marketing-network-effects.md +326 -0
  222. package/one/things/claude/agents/marketing-nurture-campaigns.md +326 -0
  223. package/one/things/claude/agents/marketing-share-optimizer.md +326 -0
  224. package/one/things/claude/agents/marketing-team-manager.md +446 -0
  225. package/one/things/claude/agents/marketing-viral-growth.md +201 -0
  226. package/one/things/claude/agents/mission-commander.md +373 -0
  227. package/one/things/claude/agents/network-effect-analyst.md +587 -0
  228. package/one/things/claude/agents/nextjs-15-specialist.md +1547 -0
  229. package/one/things/claude/agents/npx.md +890 -0
  230. package/one/things/claude/agents/nurture-campaign-manager.md +531 -0
  231. package/one/things/claude/agents/one-master.md +355 -0
  232. package/one/things/claude/agents/one-orchestrator.md +315 -0
  233. package/one/things/claude/agents/one.md +601 -0
  234. package/one/things/claude/agents/playbook-generator.md +503 -0
  235. package/one/things/claude/agents/pm.md +326 -0
  236. package/one/things/claude/agents/po.md +345 -0
  237. package/one/things/claude/agents/qa.md +336 -0
  238. package/one/things/claude/agents/research-foundation-analyst.md +307 -0
  239. package/one/things/claude/agents/research-intelligence-gatherer.md +408 -0
  240. package/one/things/claude/agents/research-market-analyst.md +307 -0
  241. package/one/things/claude/agents/research-team-manager.md +482 -0
  242. package/one/things/claude/agents/sales-environment-optimizer.md +494 -0
  243. package/one/things/claude/agents/sales-team-manager.md +400 -0
  244. package/one/things/claude/agents/sales-upsell-strategist.md +307 -0
  245. package/one/things/claude/agents/service-advocacy-campaigns.md +307 -0
  246. package/one/things/claude/agents/service-advocacy-manager.md +307 -0
  247. package/one/things/claude/agents/service-success-manager.md +307 -0
  248. package/one/things/claude/agents/service-team-manager.md +400 -0
  249. package/one/things/claude/agents/shadcn-ui-design-system-specialist.md +2302 -0
  250. package/one/things/claude/agents/share-optimization-specialist.md +551 -0
  251. package/one/things/claude/agents/sm.md +327 -0
  252. package/one/things/claude/agents/story-teller.md +473 -0
  253. package/one/things/claude/agents/task-master.md +596 -0
  254. package/one/things/claude/agents/tauri-cross-platform-specialist.md +1827 -0
  255. package/one/things/claude/agents/tester.md +556 -0
  256. package/one/things/claude/agents/the-bull-character-manager.md +580 -0
  257. package/one/things/claude/agents/tools-playbook-generator.md +489 -0
  258. package/one/things/claude/agents/turbo-repo-builder.md +316 -0
  259. package/one/things/claude/agents/upsell-strategist.md +480 -0
  260. package/one/things/claude/agents/ux-expert.md +335 -0
  261. package/one/things/claude/agents/viral-growth-orchestrator.md +497 -0
  262. package/one/things/claude/claude-code-hooks-development.json +21 -0
  263. package/one/things/claude/claude-code-hooks-production.json +21 -0
  264. package/one/things/claude/claude-code-hooks.json +25 -0
  265. package/one/things/claude/commands/agent.md +104 -0
  266. package/one/things/claude/commands/cascade-status.md +128 -0
  267. package/one/things/claude/commands/ingest.md +290 -0
  268. package/one/things/claude/commands/ingestor.md +136 -0
  269. package/one/things/claude/commands/mission.md +83 -0
  270. package/one/things/claude/commands/npx.md +133 -0
  271. package/one/things/claude/commands/one.md +440 -0
  272. package/one/things/claude/commands/quality-check.md +204 -0
  273. package/one/things/claude/commands/smart-route.md +220 -0
  274. package/one/things/claude/commands/start.md +121 -0
  275. package/one/things/claude/commands/story.md +83 -0
  276. package/one/things/claude/commands/task.md +173 -0
  277. package/one/things/claude/hook-bypass.json +32 -0
  278. package/one/things/claude/hooks/agent-hook-config.json +427 -0
  279. package/one/things/claude/hooks/agent-hook-manager.js +525 -0
  280. package/one/things/claude/hooks/agent-load-balancer.js +271 -0
  281. package/one/things/claude/hooks/agent-request-interceptor.js +70 -0
  282. package/one/things/claude/hooks/build-hook.sh +156 -0
  283. package/one/things/claude/hooks/cascade-feedback.js +297 -0
  284. package/one/things/claude/hooks/cascade-integration-hooks.js +648 -0
  285. package/one/things/claude/hooks/cleanup-hook.sh +201 -0
  286. package/one/things/claude/hooks/continuous-improvement-monitor.js +510 -0
  287. package/one/things/claude/hooks/file-organization-engine.js +427 -0
  288. package/one/things/claude/hooks/file-organization-hook.sh +80 -0
  289. package/one/things/claude/hooks/file-organization-monitor.js +269 -0
  290. package/one/things/claude/hooks/format-hook.sh +43 -0
  291. package/one/things/claude/hooks/hook-bypass.sh +293 -0
  292. package/one/things/claude/hooks/hook-config-manager.js +202 -0
  293. package/one/things/claude/hooks/hook-debouncer.sh +62 -0
  294. package/one/things/claude/hooks/hook-logger.sh +89 -0
  295. package/one/things/claude/hooks/hook-orchestrator.js +662 -0
  296. package/one/things/claude/hooks/hook-performance-report.js +120 -0
  297. package/one/things/claude/hooks/lint-hook.sh +140 -0
  298. package/one/things/claude/hooks/mcp-cascade-integration.js +816 -0
  299. package/one/things/claude/hooks/memory-optimizer.js +510 -0
  300. package/one/things/claude/hooks/notification-hook.sh +204 -0
  301. package/one/things/claude/hooks/ontology-compliance.js +394 -0
  302. package/one/things/claude/hooks/ontology-hook-manager.js +316 -0
  303. package/one/things/claude/hooks/ontology-validation-engine.js +317 -0
  304. package/one/things/claude/hooks/ontology-validation-hook.sh +86 -0
  305. package/one/things/claude/hooks/performance-metrics.json +25 -0
  306. package/one/things/claude/hooks/performance-monitoring-hook.js +422 -0
  307. package/one/things/claude/hooks/quality-scoring-engine.js +834 -0
  308. package/one/things/claude/hooks/security-hook.sh +256 -0
  309. package/one/things/claude/hooks/simple-load-balancer.js +238 -0
  310. package/one/things/claude/hooks/startup-optimizer.js +625 -0
  311. package/one/things/claude/hooks/story-scoring-system.js +445 -0
  312. package/one/things/claude/hooks/story-validation-engine.js +473 -0
  313. package/one/things/claude/hooks/story-validation-hook-enhanced.sh +210 -0
  314. package/one/things/claude/hooks/story-validation-hook.sh +145 -0
  315. package/one/things/claude/hooks/structure-synchronizer.js +194 -0
  316. package/one/things/claude/hooks/sub-agent-output-validator.js +647 -0
  317. package/one/things/claude/hooks/sub-agent-validation-hook.js +343 -0
  318. package/one/things/claude/hooks/test-hook.sh +145 -0
  319. package/one/things/claude/hooks/test-story-validation.sh +170 -0
  320. package/one/things/claude/hooks/trinity-validation-system.js +392 -0
  321. package/one/things/claude/settings-local.json +86 -0
  322. package/one/things/cli-code.md +652 -0
  323. package/one/things/cli-compiler-code.md +652 -0
  324. package/one/things/cli.md +1045 -0
  325. package/one/things/components/card-shadcn.md +929 -0
  326. package/one/things/components/card.md +1050 -0
  327. package/one/things/components.md +1669 -0
  328. package/one/things/componets.md +4 -0
  329. package/one/things/copilotkit.md +1559 -0
  330. package/one/things/creator-diagram.md +166 -0
  331. package/one/things/examples/children/lemonade-stand.md +366 -0
  332. package/one/things/examples/enterprise/crm-saas.md +1429 -0
  333. package/one/things/features/1-1-agent-prompts/design.md +470 -0
  334. package/one/things/features/1-1-agent-prompts/tests.md +264 -0
  335. package/one/things/features/1-1-agent-prompts.md +486 -0
  336. package/one/things/features/1-2-yaml-orchestrator/design.md +497 -0
  337. package/one/things/features/1-2-yaml-orchestrator/tests.md +227 -0
  338. package/one/things/features/1-2-yaml-orchestrator.md +516 -0
  339. package/one/things/features/1-3-event-coordination/design.md +544 -0
  340. package/one/things/features/1-3-event-coordination/tests.md +223 -0
  341. package/one/things/features/1-3-event-coordination.md +508 -0
  342. package/one/things/features/1-4-knowledge-management/design.md +609 -0
  343. package/one/things/features/1-4-knowledge-management/tests.md +195 -0
  344. package/one/things/features/1-4-knowledge-management.md +577 -0
  345. package/one/things/features/1-5-quality-loops/design.md +797 -0
  346. package/one/things/features/1-5-quality-loops/tests.md +212 -0
  347. package/one/things/features/1-5-quality-loops.md +641 -0
  348. package/one/things/features/1-6-numbering-structure/design.md +610 -0
  349. package/one/things/features/1-6-numbering-structure/tests.md +213 -0
  350. package/one/things/features/1-6-numbering-structure.md +575 -0
  351. package/one/things/features/2-cli.md +1235 -0
  352. package/one/things/features/use-one-backend.md +1180 -0
  353. package/one/things/ideas/1-create-workflow.md +189 -0
  354. package/one/things/plans/1-create-workflow-status.md +555 -0
  355. package/one/things/plans/1-create-workflow.md +713 -0
  356. package/one/things/plans/app.md +761 -0
  357. package/one/things/plans/better-auth-any-backend-revised.md +1065 -0
  358. package/one/things/plans/better-auth-any-backend.md +1852 -0
  359. package/one/things/plans/better-auth-available-features.md +235 -0
  360. package/one/things/plans/big-plan.md +38 -0
  361. package/one/things/plans/convex-better-auth.md +1109 -0
  362. package/one/things/plans/convex-on-off.md +389 -0
  363. package/one/things/plans/desktop.md +1121 -0
  364. package/one/things/plans/effect-components.md +1669 -0
  365. package/one/things/plans/effect.md +973 -0
  366. package/one/things/plans/email.md +953 -0
  367. package/one/things/plans/enhance-auth.md +1669 -0
  368. package/one/things/plans/install-components.md +198 -0
  369. package/one/things/plans/landing.md +728 -0
  370. package/one/things/plans/layout.md +205 -0
  371. package/one/things/plans/mail-backend.md +1308 -0
  372. package/one/things/plans/mail.md +2624 -0
  373. package/one/things/plans/next-features.md +83 -0
  374. package/one/things/plans/one.md +658 -0
  375. package/one/things/plans/ontology-6-dimensions.md +2216 -0
  376. package/one/things/plans/ontology-driven-strategy.md +866 -0
  377. package/one/things/plans/ontology-ui-approach.md +357 -0
  378. package/one/things/plans/open-agent.md +785 -0
  379. package/one/things/plans/performace.md +90 -0
  380. package/one/things/plans/releases.md +809 -0
  381. package/one/things/plans/repos.md +76 -0
  382. package/one/things/plans/separate-copy-2.md +1293 -0
  383. package/one/things/plans/separate-copy-3.md +2458 -0
  384. package/one/things/plans/separate-copy.md +1293 -0
  385. package/one/things/plans/separate.md +1983 -0
  386. package/one/things/plans/shadcn-integration-summary.md +450 -0
  387. package/one/things/plans/sidebar.md +172 -0
  388. package/one/things/plans/small-fixes.md +5 -0
  389. package/one/things/plans/test-backend-connection.md +476 -0
  390. package/one/things/plans/workflow-files.md +1196 -0
  391. package/one/things/plans/workflow.md +1372 -0
  392. package/one/things/products/cascade-landing-page.md +737 -0
  393. package/one/things/products/cascade.md +1518 -0
  394. package/one/things/products/context-engineering.md +1427 -0
  395. package/one/things/products/onthology.md +0 -0
  396. package/one/things/products/ontology-ui-shadcn.md +1280 -0
  397. package/one/things/products/ontology-ui.md +1387 -0
  398. package/one/things/products/ontology.md +717 -0
  399. package/one/things/products/sdk.md +557 -0
  400. package/one/things/promptkit.md +903 -0
  401. package/one/things/service-providers-new.md +982 -0
  402. package/one/things/service-providers.md +1092 -0
  403. package/one/things/things.md +349 -0
  404. package/one/things/todo.md +1248 -0
  405. package/package.json +5 -2
@@ -0,0 +1,2427 @@
1
+ # Frontend Development Ontology
2
+
3
+ **Version:** 4.0.0
4
+ **Type System:** Formal ontology for backend-agnostic Astro website development
5
+ **Paradigm:** Pure declarative type theory + Provider pattern + Context engineering
6
+
7
+ ---
8
+
9
+ ## Table of Contents
10
+
11
+ 1. [Core Axioms](#core-axioms)
12
+ 2. [Provider Pattern & Context Engineering](#provider-pattern--context-engineering)
13
+ 3. [Type Hierarchy](#type-hierarchy)
14
+ 4. [Critical Distinctions](#critical-distinctions)
15
+ 5. [State Management Hierarchy](#state-management-hierarchy)
16
+ 6. [DataProvider Interface](#dataprovider-interface-universal-api)
17
+ 7. [Entity Definitions](#entity-definitions)
18
+ 8. [Multi-Tenant Architecture](#multi-tenant-architecture)
19
+ 9. [Caching Ontology](#caching-ontology)
20
+ 10. [Error Propagation Ontology](#error-propagation-ontology)
21
+ 11. [Testing Ontology](#testing-ontology)
22
+ 12. [Pattern Language](#pattern-language)
23
+ 13. [Type Sync Automation](#type-sync-automation)
24
+ 14. [Observability Layer](#observability-layer)
25
+ 15. [Agent Task Mapping](#agent-task-mapping)
26
+ 16. [Common Mistakes](#common-mistakes)
27
+ 17. [Summary](#summary)
28
+
29
+ ---
30
+
31
+ ## Core Axioms
32
+
33
+ ### Axiom 1: Everything is a Thing
34
+ ```
35
+ ∀x ∈ Frontend → x : Thing
36
+ Thing ::= Page | Component | Content | Service | Provider | Configuration
37
+ ```
38
+
39
+ ### Axiom 2: All Things Have Type
40
+ ```
41
+ type : Thing → TypeID
42
+ TypeID ::= String ∈ ontology.things.types
43
+ ```
44
+
45
+ ### Axiom 3: Things Connect
46
+ ```
47
+ connect : Thing × Thing → Connection
48
+ Connection ::= { from: Thing, to: Thing, type: RelationType, metadata: Object }
49
+ ```
50
+
51
+ ### Axiom 4: Actions Emit Events
52
+ ```
53
+ action : Thing → Event
54
+ Event ::= { type: EventType, actor: Thing, target: Thing, timestamp: Time, metadata: Object }
55
+ ```
56
+
57
+ ### Axiom 5: Patterns Compose
58
+ ```
59
+ compose : Pattern × Pattern → Pattern
60
+ Pattern ::= { type: PatternType, inputs: [Thing], outputs: [Thing], transform: Function }
61
+ ```
62
+
63
+ ### Axiom 6: Backend Agnosticism
64
+ ```
65
+ ∀Provider. Provider implements DataProviderInterface → Frontend works with Provider
66
+ DataProviderInterface ::= { organizations, people, things, connections, events, knowledge }
67
+ ```
68
+
69
+ ### Axiom 7: Context Minimalism
70
+ ```
71
+ ∀Operation. Load only required types, not implementations
72
+ ContextUsed << ContextAvailable
73
+ target_reduction: 98%+
74
+ ```
75
+
76
+ **Key Principle:** Frontend knows 6-dimension ontology, not backend implementation.
77
+
78
+ ---
79
+
80
+ ## Provider Pattern & Context Engineering
81
+
82
+ ### The Core Insight: Providers ARE Context Loaders
83
+
84
+ ```typescript
85
+ {
86
+ insight: "Provider pattern = 99.9% context reduction"
87
+
88
+ // ❌ Traditional: Load entire backend
89
+ traditionalApproach: {
90
+ load: "Full Convex schema + all implementations + all docs",
91
+ tokens: 280_000,
92
+ problem: "Frontend context explodes with backend knowledge"
93
+ }
94
+
95
+ // ✅ Provider pattern: Load only interface
96
+ providerApproach: {
97
+ load: "DataProviderInterface only (contract)",
98
+ tokens: 300,
99
+ benefit: "Frontend never loads backend implementation"
100
+ }
101
+
102
+ // Backend translation happens at runtime (0 frontend tokens)
103
+ execution: {
104
+ frontend: "provider.things.get(id)", // Uses interface
105
+ provider: "convexClient.query(...)", // Translates to backend
106
+ backend: "Database query", // Executes
107
+ result: "Frontend context = 300 tokens (not 280k)"
108
+ }
109
+
110
+ result: {
111
+ context_reduction: "99.9%",
112
+ backend_flexibility: "infinite (swap with config)",
113
+ type_safety: "Effect.ts typed errors",
114
+ testability: "Mock provider for tests"
115
+ }
116
+ }
117
+ ```
118
+
119
+ ### Provider as Just-In-Time Loader
120
+
121
+ ```typescript
122
+ // Traditional AI code generation
123
+ ❌ function generateCourseComponent_Traditional() {
124
+ context = {
125
+ convexSchema: loadConvexSchema(), // 15,000 tokens
126
+ convexMutations: loadMutations(), // 20,000 tokens
127
+ convexQueries: loadQueries(), // 18,000 tokens
128
+ implementations: loadImplementations() // 50,000 tokens
129
+ } // Total: 103,000 tokens
130
+
131
+ return ai.generate(task, context)
132
+ }
133
+
134
+ // ✅ Provider pattern
135
+ ✅ function generateCourseComponent_Provider() {
136
+ context = {
137
+ interface: "DataProviderInterface", // 300 tokens
138
+ operations: ["things.get", "things.list"] // Which operations needed
139
+ } // Total: 300 tokens
140
+
141
+ // AI generates code using interface
142
+ code = ai.generate(task, context)
143
+ // Result: provider.things.get(id) - works with ANY backend
144
+
145
+ return code
146
+ }
147
+
148
+ // Savings: 103,000 → 300 tokens = 99.7% reduction
149
+ ```
150
+
151
+ ### Context Engineering Formula
152
+
153
+ ```typescript
154
+ {
155
+ traditional: {
156
+ formula: "ContextSize = Σ(all_files + all_docs + all_examples)",
157
+ typical: "50k-300k tokens per request",
158
+ problem: "Hits context limits, slow, expensive"
159
+ },
160
+
161
+ provider: {
162
+ formula: "ContextSize = interface_definition + operation_signatures",
163
+ typical: "300-500 tokens per request",
164
+ benefit: "Never hits limits, fast, cheap, infinite backends"
165
+ },
166
+
167
+ improvement: {
168
+ context_reduction: "99%+",
169
+ cost_reduction: "100x cheaper",
170
+ speed_improvement: "10x faster",
171
+ backend_flexibility: "∞ backends supported"
172
+ }
173
+ }
174
+ ```
175
+
176
+ ---
177
+
178
+ ## Type Hierarchy
179
+
180
+ ### Base Types
181
+ ```
182
+ Thing
183
+ ├── Artifact // Code artifacts (what agents create)
184
+ │ ├── Page
185
+ │ │ ├── LandingPage
186
+ │ │ ├── BlogIndex
187
+ │ │ ├── BlogPost
188
+ │ │ ├── AppPage
189
+ │ │ ├── AccountPage
190
+ │ │ └── APIRoute
191
+ │ ├── Component
192
+ │ │ ├── UIComponent
193
+ │ │ ├── FeatureComponent
194
+ │ │ ├── Layout
195
+ │ │ └── Island
196
+ │ ├── Content
197
+ │ │ ├── Collection
198
+ │ │ ├── Entry
199
+ │ │ └── Schema
200
+ │ ├── Service // Effect.ts services (type-safe data operations)
201
+ │ │ ├── GenericService // Handles all 66 types (ThingService, ConnectionService)
202
+ │ │ └── SpecializedService // Optional convenience (CourseService)
203
+ │ ├── Provider // Backend implementations (swap backends)
204
+ │ │ ├── ConvexProvider // Convex backend
205
+ │ │ ├── WordPressProvider // WordPress REST API
206
+ │ │ ├── NotionProvider // Notion databases
207
+ │ │ ├── SupabaseProvider // Supabase PostgreSQL
208
+ │ │ └── CustomProvider // Any backend
209
+ │ └── Configuration // Display & provider config (NOT business logic)
210
+ │ ├── DisplayConfig // UI labels, icons, colors
211
+ │ └── ProviderConfig // Backend URL, API keys
212
+ ├── Pattern // Reusable templates
213
+ │ ├── PagePattern
214
+ │ ├── ComponentPattern
215
+ │ ├── DataPattern
216
+ │ ├── ServicePattern
217
+ │ └── StylePattern
218
+ ├── Interface // Abstract contracts
219
+ │ ├── DataProviderInterface // Universal 6-dimension API
220
+ │ └── SubscriptionInterface // Real-time updates (optional)
221
+ ├── Capability // Agent capabilities
222
+ │ ├── Create
223
+ │ ├── Read
224
+ │ ├── Update
225
+ │ └── Delete
226
+ └── Context // Execution context
227
+ ├── TypeContext
228
+ ├── PatternContext
229
+ └── ExampleContext
230
+ ```
231
+
232
+ ---
233
+
234
+ ## Critical Distinctions
235
+
236
+ ### What Frontend IS
237
+ ```typescript
238
+ type FrontendResponsibility =
239
+ | { type: "render"; data: any } // Display UI from data
240
+ | { type: "call_provider"; operation: DataOperation } // Call DataProvider (not direct backend)
241
+ | { type: "manage_ui_state"; state: UIState } // Form inputs, modals, loading (component-local)
242
+ | { type: "route"; path: Path } // Client-side navigation
243
+ | { type: "cache_display"; data: CachedData } // Cache UI data (not business data)
244
+ ```
245
+
246
+ ### What Frontend IS NOT
247
+ ```typescript
248
+ type FrontendProhibition =
249
+ | { type: "database_access"; reason: "Backend-only (provider abstracts)" }
250
+ | { type: "business_logic"; reason: "Backend validates (frontend calls provider)" }
251
+ | { type: "event_logging"; reason: "Backend logs (frontend just triggers)" }
252
+ | { type: "authorization"; reason: "Backend authorizes (frontend just checks state)" }
253
+ | { type: "data_validation"; reason: "Backend validates (frontend UX hints only)" }
254
+ | { type: "org_filtering"; reason: "Provider handles (frontend never filters by org)" }
255
+ | { type: "backend_specific_code"; reason: "Provider abstracts (frontend uses interface)" }
256
+ ```
257
+
258
+ ---
259
+
260
+ ## State Management Hierarchy
261
+
262
+ ### Four-Layer State Architecture
263
+
264
+ ```typescript
265
+ {
266
+ // Level 1: Server State (Provider owns - SOURCE OF TRUTH)
267
+ ServerState: {
268
+ owner: "Provider (backed by database)",
269
+ source: "Backend database",
270
+ access: "Query/Mutation via provider.interface only",
271
+ examples: [
272
+ "course list",
273
+ "user profile",
274
+ "enrollment count",
275
+ "lesson progress"
276
+ ],
277
+ caching: "Provider-level (Cloudflare KV, Edge cache)",
278
+ lifetime: "Persistent (until backend changes)",
279
+ rule: "NEVER duplicate in frontend state. Query when needed."
280
+ },
281
+
282
+ // Level 2: SSR State (Astro owns - REQUEST SCOPED)
283
+ SSRState: {
284
+ owner: "Astro page (.astro files)",
285
+ source: "Server-side provider fetch",
286
+ access: "Props passed to components",
287
+ examples: [
288
+ "Initial page data (course details)",
289
+ "SEO metadata (title, description)",
290
+ "Organization context (from subdomain)"
291
+ ],
292
+ lifetime: "One HTTP request (not persisted)",
293
+ pattern: `
294
+ ---
295
+ const course = await provider.things.get(id)
296
+ ---
297
+ <Layout title={course.name}>
298
+ <CourseDetail course={course} />
299
+ </Layout>
300
+ `,
301
+ rule: "Use for SEO, initial render, server-only data"
302
+ },
303
+
304
+ // Level 3: Island State (React owns - COMPONENT SCOPED)
305
+ IslandState: {
306
+ owner: "React component (useState/useReducer)",
307
+ source: "Component-local logic",
308
+ access: "Component-private (not shared)",
309
+ examples: [
310
+ "Form input values",
311
+ "Modal open/closed",
312
+ "Dropdown expanded",
313
+ "Loading spinner visible"
314
+ ],
315
+ lifetime: "Component mounted (unmount = state destroyed)",
316
+ pattern: `
317
+ export function CourseForm() {
318
+ const [title, setTitle] = useState('')
319
+ const [loading, setLoading] = useState(false)
320
+ // State dies when component unmounts
321
+ }
322
+ `,
323
+ rule: "UI-only state. Never duplicate server state."
324
+ },
325
+
326
+ // Level 4: Shared Client State (Nanostores owns - SESSION SCOPED)
327
+ SharedState: {
328
+ owner: "Nanostores (global atoms)",
329
+ source: "Cross-component coordination",
330
+ access: "Multiple components subscribe",
331
+ examples: [
332
+ "Sidebar expanded/collapsed",
333
+ "Dark/light theme preference",
334
+ "User locale (en/es/fr)",
335
+ "Toast notifications"
336
+ ],
337
+ lifetime: "Browser session + localStorage",
338
+ pattern: `
339
+ // stores/layout.ts
340
+ export const sidebarExpanded = atom(true)
341
+
342
+ // Component A
343
+ const expanded = useStore(sidebarExpanded)
344
+
345
+ // Component B (synced with A)
346
+ const expanded = useStore(sidebarExpanded)
347
+ `,
348
+ rule: "UI preferences only. NOT server data."
349
+ },
350
+
351
+ // Anti-Pattern: Duplicating Server State
352
+ antiPattern: {
353
+ problem: "Storing server data in frontend state",
354
+ example: `
355
+ ❌ const [courses, setCourses] = useState([])
356
+ ❌ useEffect(() => {
357
+ provider.things.list('course').then(setCourses)
358
+ }, [])
359
+ // Problem: Server state duplicated in frontend
360
+ // Problem: Stale data, manual sync, cache invalidation
361
+ `,
362
+ solution: `
363
+ ✅ const courses = useQuery(api.courses.list)
364
+ // Provider handles caching, revalidation, subscriptions
365
+ // Frontend just renders. No state duplication.
366
+ `
367
+ },
368
+
369
+ // Golden Rule
370
+ rule: "State lives at HIGHEST appropriate level. Don't lift unnecessarily."
371
+
372
+ // Decision Tree
373
+ decisionTree: {
374
+ question: "Does this state persist after page reload?",
375
+ yes: {
376
+ question: "Is this data from backend?",
377
+ yes: "ServerState (provider query)",
378
+ no: "SharedState (nanostores + localStorage)"
379
+ },
380
+ no: {
381
+ question: "Do multiple components need this state?",
382
+ yes: "SharedState (nanostores, session-only)",
383
+ no: {
384
+ question: "Is this SSR data?",
385
+ yes: "SSRState (Astro props)",
386
+ no: "IslandState (useState)"
387
+ }
388
+ }
389
+ }
390
+ }
391
+ ```
392
+
393
+ ---
394
+
395
+ ## DataProvider Interface (Universal API)
396
+
397
+ ### Core Contract
398
+ ```typescript
399
+ // ALL backends must implement this interface
400
+ interface DataProviderInterface {
401
+ // Dimension 1: Organizations
402
+ organizations: {
403
+ get: (id: string) → Effect<Organization, OrganizationNotFoundError>
404
+ list: (params: ListParams) → Effect<Organization[], Error>
405
+ update: (id: string, updates: Partial<Organization>) → Effect<void, Error>
406
+ }
407
+
408
+ // Dimension 2: People
409
+ people: {
410
+ get: (id: string) → Effect<Person, PersonNotFoundError | UnauthorizedError>
411
+ list: (params: ListParams) → Effect<Person[], Error>
412
+ create: (input: CreatePersonInput) → Effect<string, PersonCreateError>
413
+ update: (id: string, updates: Partial<Person>) → Effect<void, Error>
414
+ delete: (id: string) → Effect<void, Error>
415
+ }
416
+
417
+ // Dimension 3: Things
418
+ things: {
419
+ get: (id: string) → Effect<Thing, ThingNotFoundError | UnauthorizedError>
420
+ list: (params: { type: ThingType; organizationId?: string; filters?: any }) → Effect<Thing[], Error>
421
+ create: (input: CreateThingInput) → Effect<string, ThingCreateError>
422
+ update: (id: string, updates: Partial<Thing>) → Effect<void, Error>
423
+ delete: (id: string) → Effect<void, Error>
424
+ }
425
+
426
+ // Dimension 4: Connections
427
+ connections: {
428
+ create: (input: CreateConnectionInput) → Effect<string, ConnectionCreateError>
429
+ getRelated: (params: { thingId: string; relationshipType: ConnectionType; direction: Direction }) → Effect<Thing[], Error>
430
+ getCount: (thingId: string, relationshipType: ConnectionType) → Effect<number, Error>
431
+ delete: (id: string) → Effect<void, Error>
432
+ }
433
+
434
+ // Dimension 5: Events
435
+ events: {
436
+ log: (event: LogEventInput) → Effect<void, Error>
437
+ query: (params: EventQueryParams) → Effect<Event[], Error>
438
+ }
439
+
440
+ // Dimension 6: Knowledge
441
+ knowledge: {
442
+ embed: (params: EmbedParams) → Effect<string, Error>
443
+ search: (params: SearchParams) → Effect<KnowledgeMatch[], Error>
444
+ }
445
+
446
+ // Optional: Real-time subscriptions (not all backends support)
447
+ subscriptions?: {
448
+ watchThing: (id: string) → Effect<Observable<Thing>, Error>
449
+ watchList: (type: ThingType, organizationId?: string) → Effect<Observable<Thing[]>, Error>
450
+ }
451
+ }
452
+ ```
453
+
454
+ ### Provider Algebra
455
+ ```typescript
456
+ // Provider composition
457
+ implement : Backend × DataProviderInterface → Provider
458
+
459
+ // Examples:
460
+ ConvexProvider = implement(ConvexBackend, DataProviderInterface)
461
+ WordPressProvider = implement(WordPressBackend, DataProviderInterface)
462
+ NotionProvider = implement(NotionBackend, DataProviderInterface)
463
+
464
+ // Swapping backends (change ONE line in config)
465
+ config.provider = ConvexProvider({ url: "..." })
466
+ // OR
467
+ config.provider = WordPressProvider({ url: "...", apiKey: "..." })
468
+ // OR
469
+ config.provider = NotionProvider({ apiKey: "...", databaseId: "..." })
470
+
471
+ // Result: Frontend components don't change
472
+ ```
473
+
474
+ ---
475
+
476
+ ## Entity Definitions
477
+
478
+ ### Services (Effect.ts Layer)
479
+
480
+ ```typescript
481
+ // Generic Service (handles ALL 66 thing types)
482
+ type GenericService = Service & {
483
+ subtype: "generic"
484
+ coverage: ThingType[] // All 66 types
485
+ operations: CRUD
486
+
487
+ invariant: {
488
+ backend_agnostic: true // Works with ANY provider
489
+ type_safe: true // Effect.ts typed errors
490
+ composable: true // Combines into workflows
491
+ }
492
+ }
493
+
494
+ // Example: ThingService handles courses, lessons, products, EVERYTHING
495
+ type ThingService = GenericService & {
496
+ name: "ThingService"
497
+ operations: {
498
+ get: (id: string) → Effect<Thing, ThingNotFoundError>
499
+ list: (type: ThingType, orgId?: string) → Effect<Thing[], Error>
500
+ create: (input: CreateThingInput) → Effect<string, ThingCreateError>
501
+ update: (id: string, updates: any) → Effect<void, Error>
502
+ delete: (id: string) → Effect<void, Error>
503
+ }
504
+
505
+ // Delegates to configured provider
506
+ implementation: (provider: DataProvider) => ({
507
+ get: (id) => provider.things.get(id),
508
+ list: (type, orgId) => provider.things.list({ type, organizationId: orgId }),
509
+ // ...
510
+ })
511
+ }
512
+
513
+ // Example: ConnectionService handles ALL relationship types
514
+ type ConnectionService = GenericService & {
515
+ name: "ConnectionService"
516
+ operations: {
517
+ create: (input: CreateConnectionInput) → Effect<string, ConnectionCreateError>
518
+ getRelated: (thingId, type, direction) → Effect<Thing[], Error>
519
+ getCount: (thingId, type) → Effect<number, Error>
520
+ delete: (id) → Effect<void, Error>
521
+ }
522
+
523
+ implementation: (provider: DataProvider) => ({
524
+ create: (input) => provider.connections.create(input),
525
+ getRelated: (thingId, type, dir) => provider.connections.getRelated({ thingId, relationshipType: type, direction: dir }),
526
+ // ...
527
+ })
528
+ }
529
+
530
+ // Specialized Service (OPTIONAL - only add when patterns repeat 3+ times)
531
+ type SpecializedService = Service & {
532
+ subtype: "specialized"
533
+ coverage: ThingType[] // Specific types only
534
+ operations: DomainOperations
535
+ dependencies: GenericService[] // Composes generic services
536
+
537
+ invariant: {
538
+ adds_convenience: true // Clearer domain vocabulary
539
+ reduces_repetition: true // Encapsulates multi-step operations
540
+ optional: true // NOT required (can use generic services directly)
541
+ }
542
+ }
543
+
544
+ // Example: CourseService (OPTIONAL - only if you repeat these patterns)
545
+ type CourseService = SpecializedService & {
546
+ name: "CourseService"
547
+ coverage: ["course"]
548
+ dependencies: [ThingService, ConnectionService]
549
+
550
+ operations: {
551
+ // Convenience: Get course with lessons (vs 2 separate calls)
552
+ getCourseWithLessons: (courseId) → Effect<{ course: Thing; lessons: Thing[] }, Error>
553
+
554
+ // Convenience: Domain vocabulary (vs generic connection.create)
555
+ enrollUser: (userId, courseId) → Effect<string, Error>
556
+
557
+ // Convenience: Specific query (vs generic connection.getCount)
558
+ getEnrollmentCount: (courseId) → Effect<number, Error>
559
+ }
560
+
561
+ implementation: (thingService, connectionService) => ({
562
+ getCourseWithLessons: (id) => Effect.all([
563
+ thingService.get(id),
564
+ connectionService.getRelated(id, 'part_of', 'to')
565
+ ]),
566
+ enrollUser: (userId, courseId) => connectionService.create({
567
+ fromThingId: userId,
568
+ toThingId: courseId,
569
+ relationshipType: 'enrolled_in'
570
+ }),
571
+ getEnrollmentCount: (courseId) => connectionService.getCount(courseId, 'enrolled_in')
572
+ })
573
+ }
574
+ ```
575
+
576
+ ### Providers (Backend Implementations)
577
+
578
+ ```typescript
579
+ type Provider = {
580
+ type: "provider"
581
+ backend: Backend // Convex, WordPress, Notion, etc
582
+ implements: DataProviderInterface
583
+
584
+ // Map ontology operations → backend-specific API calls
585
+ translation: {
586
+ things: {
587
+ get: (id) → BackendSpecificCall
588
+ list: (params) → BackendSpecificCall
589
+ create: (input) → BackendSpecificCall
590
+ // ...
591
+ }
592
+ connections: {
593
+ // ...
594
+ }
595
+ // ... all 6 dimensions
596
+ }
597
+
598
+ invariant: {
599
+ implements_interface: true // Must implement DataProviderInterface
600
+ handles_6_dimensions: true // Organizations, People, Things, Connections, Events, Knowledge
601
+ }
602
+ }
603
+
604
+ // Convex Provider
605
+ type ConvexProvider = Provider & {
606
+ backend: "convex"
607
+
608
+ translation: {
609
+ things: {
610
+ get: (id) => convexClient.query(api.queries.things.get, { id }),
611
+ list: (params) => convexClient.query(api.queries.things.list, params),
612
+ create: (input) => convexClient.mutation(api.mutations.things.create, input),
613
+ // ...
614
+ }
615
+ // ... map all operations to Convex API
616
+ }
617
+ }
618
+
619
+ // WordPress Provider
620
+ type WordPressProvider = Provider & {
621
+ backend: "wordpress"
622
+
623
+ translation: {
624
+ things: {
625
+ get: (id) => fetch(`${url}/wp-json/wp/v2/posts/${id}`)
626
+ .then(transformWordPressPost → OneThing),
627
+ list: (params) => fetch(`${url}/wp-json/wp/v2/posts?per_page=${params.limit}`)
628
+ .then(transformWordPressPosts → OneThings),
629
+ create: (input) => fetch(`${url}/wp-json/wp/v2/posts`, {
630
+ method: 'POST',
631
+ body: transformOneThing → WordPressPost
632
+ }),
633
+ // ...
634
+ }
635
+ // ... map all operations to WordPress REST API
636
+ }
637
+ }
638
+
639
+ // Notion Provider
640
+ type NotionProvider = Provider & {
641
+ backend: "notion"
642
+
643
+ translation: {
644
+ things: {
645
+ get: (id) => notionClient.pages.retrieve({ page_id: id })
646
+ .then(transformNotionPage → OneThing),
647
+ list: (params) => notionClient.databases.query({ database_id, page_size: params.limit })
648
+ .then(transformNotionPages → OneThings),
649
+ create: (input) => notionClient.pages.create({
650
+ parent: { database_id },
651
+ properties: transformOneThing → NotionProperties
652
+ }),
653
+ // ...
654
+ }
655
+ // ... map all operations to Notion API
656
+ }
657
+ }
658
+ ```
659
+
660
+ ### Configuration
661
+
662
+ ```typescript
663
+ // Display Configuration (UI only, NOT business logic)
664
+ type DisplayConfig = Configuration & {
665
+ purpose: "ui_presentation"
666
+ scope: ThingType[]
667
+
668
+ properties: {
669
+ displayName: string // "Course" (singular)
670
+ displayNamePlural: string // "Courses" (plural)
671
+ icon: LucideIconName // "BookOpen"
672
+ color: TailwindColor // "green"
673
+ primaryField: string // Which property to show as title
674
+ secondaryField: string // Which property to show as subtitle
675
+ imageField: string // Which property is the image
676
+ fields: FieldConfig[] // Form fields for UI
677
+ }
678
+
679
+ invariant: {
680
+ ui_only: true // NO business logic
681
+ backend_agnostic: true // Works with any provider
682
+ display_hints: true // Labels, placeholders, icons
683
+ }
684
+ }
685
+
686
+ // Provider Configuration (backend connection)
687
+ type ProviderConfig = Configuration & {
688
+ purpose: "backend_connection"
689
+
690
+ properties: {
691
+ provider: ProviderType // "convex" | "wordpress" | "notion" | etc
692
+ url: string // Backend URL
693
+ apiKey?: string // API key (if needed)
694
+ databaseId?: string // Database ID (for Notion)
695
+ // ... other backend-specific config
696
+ }
697
+
698
+ invariant: {
699
+ one_line_swap: true // Change provider in ONE line
700
+ environment_vars: true // Use .env for secrets
701
+ }
702
+ }
703
+ ```
704
+
705
+ ---
706
+
707
+ ## Multi-Tenant Architecture
708
+
709
+ ### Subdomain-Based Organization Isolation
710
+
711
+ ```typescript
712
+ {
713
+ pattern: "subdomain_org_isolation",
714
+ problem: "How does provider handle fitnesspro.one.ie vs techcorp.one.ie?",
715
+
716
+ solution: {
717
+ // Middleware extracts orgId from subdomain
718
+ middleware: `
719
+ // src/middleware.ts
720
+ export function onRequest(context, next) {
721
+ const subdomain = context.url.hostname.split('.')[0]
722
+ const org = await provider.organizations.get({ slug: subdomain })
723
+
724
+ context.locals.organizationId = org._id
725
+ context.locals.organization = org
726
+
727
+ return next()
728
+ }
729
+ `,
730
+
731
+ // Provider auto-injects orgId in ALL queries
732
+ provider: `
733
+ // Provider automatically scopes ALL queries
734
+ class ConvexProvider implements DataProviderInterface {
735
+ constructor(private ctx: Context) {}
736
+
737
+ things = {
738
+ list: (params) => {
739
+ // Provider ALWAYS adds org filter (frontend never needs to)
740
+ return this.client.query(api.things.list, {
741
+ ...params,
742
+ organizationId: this.ctx.locals.organizationId // Auto-injected
743
+ })
744
+ },
745
+
746
+ create: (input) => {
747
+ // Provider ALWAYS stamps org on creation
748
+ return this.client.mutation(api.things.create, {
749
+ ...input,
750
+ properties: {
751
+ ...input.properties,
752
+ organizationId: this.ctx.locals.organizationId // Auto-injected
753
+ }
754
+ })
755
+ }
756
+ }
757
+ }
758
+ `,
759
+
760
+ // Frontend NEVER manually filters by org
761
+ frontend: `
762
+ // ✅ Frontend code (same for all orgs)
763
+ const courses = await provider.things.list({ type: 'course' })
764
+ // Provider adds organizationId automatically
765
+
766
+ // ❌ NEVER do this
767
+ const courses = await provider.things.list({
768
+ type: 'course',
769
+ organizationId: ctx.locals.organizationId // Provider handles this
770
+ })
771
+ `,
772
+
773
+ invariants: [
774
+ "Provider enforces isolation (not frontend)",
775
+ "Frontend never knows about multi-tenancy",
776
+ "One frontend codebase for all orgs",
777
+ "Data isolation enforced at provider level"
778
+ ]
779
+ },
780
+
781
+ benefits: [
782
+ "Frontend code 100% org-agnostic",
783
+ "Security enforced by provider (not UI)",
784
+ "No org-specific frontend builds",
785
+ "Impossible to leak org data (provider enforces)"
786
+ ]
787
+ }
788
+ ```
789
+
790
+ ---
791
+
792
+ ## Caching Ontology
793
+
794
+ ### Four-Tier Caching Architecture
795
+
796
+ ```typescript
797
+ {
798
+ // Tier 1: Type Definition Cache (STATIC - INFINITE TTL)
799
+ L1_TypeDefinitions: {
800
+ what: "Ontology type structures",
801
+ ttl: "∞ (types never change at runtime)",
802
+ storage: "Memory (startup load)",
803
+ size: "200 tokens × 66 types = 13,200 tokens",
804
+ hitRate: "99.9%+ (loaded once)",
805
+
806
+ implementation: `
807
+ class TypeDefinitionCache {
808
+ private cache = new Map<ThingType, TypeDefinition>()
809
+
810
+ async load() {
811
+ // Load all 66 types at startup (one time)
812
+ const types = await import('./ontology/types')
813
+ types.forEach(type => this.cache.set(type.name, type))
814
+ }
815
+
816
+ get(type: ThingType): TypeDefinition {
817
+ return this.cache.get(type) // Always hits (loaded at startup)
818
+ }
819
+ }
820
+
821
+ // Usage: ~13k tokens loaded ONCE, reused for ALL requests
822
+ const typeDef = typeCache.get('course') // 200 tokens, instant
823
+ `,
824
+
825
+ benefit: "AI loads 200 tokens (not 15k implementation tokens)"
826
+ },
827
+
828
+ // Tier 2: Provider Interface Cache (STATIC - INFINITE TTL)
829
+ L2_ProviderInterface: {
830
+ what: "DataProvider method signatures",
831
+ ttl: "∞ (interface never changes)",
832
+ storage: "Memory (startup load)",
833
+ size: "300 tokens (entire interface)",
834
+ hitRate: "100% (never changes)",
835
+
836
+ implementation: `
837
+ // Loaded once at startup
838
+ const providerInterface = {
839
+ things: {
840
+ get: "(id: string) → Effect<Thing, Error>",
841
+ list: "(params) → Effect<Thing[], Error>",
842
+ // ...
843
+ }
844
+ // ... all 6 dimensions
845
+ } // 300 tokens total
846
+
847
+ // Usage: AI references interface (not backend implementation)
848
+ context = { interface: providerInterface } // 300 tokens
849
+ `,
850
+
851
+ benefit: "AI never loads backend implementation (0 tokens)"
852
+ },
853
+
854
+ // Tier 3: SSR Data Cache (DYNAMIC - TTL: 1-60s)
855
+ L3_SSRData: {
856
+ what: "Server-rendered page data",
857
+ ttl: "1-60s (configurable per route)",
858
+ storage: "Cloudflare KV / Edge cache",
859
+ size: "Variable (full pages or data)",
860
+ strategy: "Stale-while-revalidate",
861
+
862
+ implementation: `
863
+ // Astro page with edge caching
864
+ export const prerender = false
865
+
866
+ export async function GET(context) {
867
+ const cacheKey = \`course:\${context.params.id}\`
868
+
869
+ // Check cache
870
+ const cached = await context.locals.cache.get(cacheKey)
871
+ if (cached && !isStale(cached, 60)) {
872
+ return cached
873
+ }
874
+
875
+ // Fetch fresh
876
+ const course = await provider.things.get(context.params.id)
877
+
878
+ // Cache for 60s
879
+ await context.locals.cache.set(cacheKey, course, { ttl: 60 })
880
+
881
+ return course
882
+ }
883
+ `,
884
+
885
+ patterns: {
886
+ high_traffic_pages: "60s TTL (homepage, popular courses)",
887
+ dynamic_pages: "10s TTL (user dashboards)",
888
+ real_time_pages: "0s TTL (admin, analytics)"
889
+ },
890
+
891
+ benefit: "Reduces provider calls by 80-95%"
892
+ },
893
+
894
+ // Tier 4: Client Subscriptions (REALTIME - TTL: 0)
895
+ L4_RealtimeSubscriptions: {
896
+ what: "WebSocket live updates",
897
+ ttl: "0 (always fresh)",
898
+ storage: "Client memory (ephemeral)",
899
+ strategy: "Provider pushes updates",
900
+
901
+ implementation: `
902
+ // React component with real-time subscription
903
+ export function EnrollmentCount({ courseId }) {
904
+ // Convex subscription (or any provider with subscription support)
905
+ const count = useQuery(api.connections.getCount, {
906
+ thingId: courseId,
907
+ relationshipType: 'enrolled_in'
908
+ })
909
+
910
+ // Updates automatically when backend changes
911
+ return <span>{count}</span>
912
+ }
913
+ `,
914
+
915
+ when_to_use: [
916
+ "Real-time dashboards",
917
+ "Live enrollment counts",
918
+ "Collaborative editing",
919
+ "Chat/notifications"
920
+ ],
921
+
922
+ fallback: "If provider doesn't support subscriptions, poll with L3 cache"
923
+ },
924
+
925
+ // Cache Hierarchy Decision Tree
926
+ decisionTree: {
927
+ question: "Is this ontology type data?",
928
+ yes: "L1 (Type Definition Cache) - infinite TTL",
929
+ no: {
930
+ question: "Is this provider interface?",
931
+ yes: "L2 (Provider Interface Cache) - infinite TTL",
932
+ no: {
933
+ question: "Does data change in real-time?",
934
+ yes: "L4 (Real-time Subscriptions) - 0 TTL",
935
+ no: {
936
+ question: "Is data page-level?",
937
+ yes: "L3 (SSR Data Cache) - 1-60s TTL",
938
+ no: "No cache (fetch on demand)"
939
+ }
940
+ }
941
+ }
942
+ },
943
+
944
+ // Golden Rule
945
+ rule: "Cache closer to definition = less context loaded. Types/interface = cached forever."
946
+ }
947
+ ```
948
+
949
+ ### Cache Invalidation Strategies
950
+
951
+ ```typescript
952
+ {
953
+ strategies: {
954
+ // L1 & L2: Never invalidate (static types/interface)
955
+ static: {
956
+ invalidation: "None (only invalidate on deployment)",
957
+ reason: "Types and interface don't change at runtime"
958
+ },
959
+
960
+ // L3: Time-based + event-based
961
+ ssr: {
962
+ time_based: "TTL expires → fetch fresh",
963
+ event_based: "Backend mutation → invalidate affected pages",
964
+
965
+ example: `
966
+ // When course updated, invalidate course page cache
967
+ await provider.things.update(courseId, updates)
968
+ await cache.delete(\`course:\${courseId}\`)
969
+ `
970
+ },
971
+
972
+ // L4: Automatic (subscription handles)
973
+ realtime: {
974
+ invalidation: "Provider pushes updates automatically",
975
+ reason: "WebSocket connection = always fresh"
976
+ }
977
+ }
978
+ }
979
+ ```
980
+
981
+ ---
982
+
983
+ ## Error Propagation Ontology
984
+
985
+ ### Full Error Flow: Provider → Service → Component → UI
986
+
987
+ ```typescript
988
+ {
989
+ errorFlow: "Provider → Service → Component → UI",
990
+
991
+ // Level 1: Provider Errors (Effect.ts tagged errors)
992
+ providerErrors: {
993
+ ThingNotFoundError: {
994
+ _tag: "ThingNotFoundError",
995
+ fields: { thingId: string; type: ThingType },
996
+ recovery: "Show 404 page or 'Not Found' component",
997
+ httpStatus: 404
998
+ },
999
+
1000
+ UnauthorizedError: {
1001
+ _tag: "UnauthorizedError",
1002
+ fields: { userId?: string; requiredPermission: string },
1003
+ recovery: "Redirect to /login with returnUrl",
1004
+ httpStatus: 401
1005
+ },
1006
+
1007
+ NetworkError: {
1008
+ _tag: "NetworkError",
1009
+ fields: { message: string; retryable: boolean },
1010
+ recovery: "Retry with exponential backoff (if retryable)",
1011
+ httpStatus: 503
1012
+ },
1013
+
1014
+ RateLimitError: {
1015
+ _tag: "RateLimitError",
1016
+ fields: { retryAfter: number },
1017
+ recovery: "Show 'Try again in X seconds' message",
1018
+ httpStatus: 429
1019
+ }
1020
+ },
1021
+
1022
+ // Level 2: Service Errors (Domain-specific, compose provider errors)
1023
+ serviceErrors: {
1024
+ pattern: "Transform provider error → domain error",
1025
+
1026
+ example: `
1027
+ // CourseService.ts
1028
+ getCourseWithLessons(id: string) {
1029
+ return Effect.gen(function* () {
1030
+ const course = yield* thingService.get(id)
1031
+ const lessons = yield* connectionService.getRelated(id, 'part_of', 'to')
1032
+
1033
+ return { course, lessons }
1034
+ }).pipe(
1035
+ // Transform provider error → domain error
1036
+ Effect.catchTag('ThingNotFoundError', (e) =>
1037
+ Effect.fail(new CourseNotFoundError({
1038
+ courseId: e.thingId,
1039
+ message: \`Course \${e.thingId} not found\`
1040
+ }))
1041
+ )
1042
+ )
1043
+ }
1044
+ `,
1045
+
1046
+ benefits: [
1047
+ "Domain-specific error vocabulary",
1048
+ "Hides provider implementation details",
1049
+ "Easier for frontend to handle"
1050
+ ]
1051
+ },
1052
+
1053
+ // Level 3: Component Errors (Catch and render)
1054
+ componentErrors: {
1055
+ pattern: "Match error._tag → Render UI component",
1056
+
1057
+ example: `
1058
+ // CourseDetail.tsx
1059
+ export function CourseDetail({ courseId }: Props) {
1060
+ const [course, setCourse] = useState<Thing | null>(null)
1061
+ const [error, setError] = useState<Error | null>(null)
1062
+
1063
+ useEffect(() => {
1064
+ Effect.runPromise(
1065
+ courseService.getCourseWithLessons(courseId)
1066
+ )
1067
+ .then(result => setCourse(result.course))
1068
+ .catch(e => setError(e))
1069
+ }, [courseId])
1070
+
1071
+ // Render based on error type
1072
+ if (error) {
1073
+ switch (error._tag) {
1074
+ case 'CourseNotFoundError':
1075
+ return <Alert variant="warning">Course not found</Alert>
1076
+
1077
+ case 'UnauthorizedError':
1078
+ return <Alert variant="error">Please log in to view</Alert>
1079
+
1080
+ case 'NetworkError':
1081
+ return <Alert variant="error">Network error. Retrying...</Alert>
1082
+
1083
+ default:
1084
+ return <Alert variant="error">Something went wrong</Alert>
1085
+ }
1086
+ }
1087
+
1088
+ return <div>{/* Render course */}</div>
1089
+ }
1090
+ `
1091
+ },
1092
+
1093
+ // Level 4: UI Errors (User-facing messages)
1094
+ uiErrors: {
1095
+ pattern: "Error → User-friendly message + Action",
1096
+
1097
+ mapping: {
1098
+ ThingNotFoundError: {
1099
+ message: "This {type} doesn't exist",
1100
+ action: "Go back or search for another",
1101
+ component: "<Alert404 />"
1102
+ },
1103
+
1104
+ UnauthorizedError: {
1105
+ message: "You need to log in to see this",
1106
+ action: "Log in or Sign up",
1107
+ component: "<LoginPrompt returnUrl={currentPath} />"
1108
+ },
1109
+
1110
+ NetworkError: {
1111
+ message: "Connection issue",
1112
+ action: "Retrying automatically...",
1113
+ component: "<RetryAlert retrying={true} />"
1114
+ },
1115
+
1116
+ RateLimitError: {
1117
+ message: "Too many requests",
1118
+ action: "Try again in {retryAfter} seconds",
1119
+ component: "<RateLimitAlert retryAfter={error.retryAfter} />"
1120
+ }
1121
+ }
1122
+ },
1123
+
1124
+ // Error Boundary Pattern
1125
+ errorBoundary: `
1126
+ // ErrorBoundary.tsx
1127
+ export class ErrorBoundary extends React.Component {
1128
+ state = { error: null }
1129
+
1130
+ static getDerivedStateFromError(error) {
1131
+ return { error }
1132
+ }
1133
+
1134
+ render() {
1135
+ if (this.state.error) {
1136
+ return <ErrorFallback error={this.state.error} />
1137
+ }
1138
+
1139
+ return this.props.children
1140
+ }
1141
+ }
1142
+
1143
+ // Usage: Wrap islands in error boundaries
1144
+ <ErrorBoundary>
1145
+ <CourseDetail client:load courseId={id} />
1146
+ </ErrorBoundary>
1147
+ `,
1148
+
1149
+ // Golden Rule
1150
+ invariant: "Every error path has explicit UI recovery. No silent failures."
1151
+ }
1152
+ ```
1153
+
1154
+ ---
1155
+
1156
+ ## Testing Ontology
1157
+
1158
+ ### Three-Layer Testing Strategy
1159
+
1160
+ ```typescript
1161
+ {
1162
+ // Layer 1: Unit Tests (Service logic with mock provider)
1163
+ unitTests: {
1164
+ what: "Test service logic in isolation",
1165
+ mock: "MockProvider (no real backend)",
1166
+ fast: "Milliseconds per test",
1167
+
1168
+ example: `
1169
+ // tests/unit/services/course.test.ts
1170
+ import { describe, it, expect } from 'vitest'
1171
+ import { Effect, Layer } from 'effect'
1172
+ import { CourseService } from '@/services/CourseService'
1173
+ import { DataProvider } from '@/providers/DataProvider'
1174
+
1175
+ describe('CourseService.getCourseWithLessons', () => {
1176
+ it('should return course with lessons', async () => {
1177
+ // Mock provider
1178
+ const MockProvider = Layer.succeed(DataProvider, {
1179
+ things: {
1180
+ get: (id) => Effect.succeed({
1181
+ _id: id,
1182
+ type: 'course',
1183
+ name: 'Test Course'
1184
+ })
1185
+ },
1186
+ connections: {
1187
+ getRelated: (thingId, type, direction) => Effect.succeed([
1188
+ { _id: 'lesson1', type: 'lesson', name: 'Lesson 1' },
1189
+ { _id: 'lesson2', type: 'lesson', name: 'Lesson 2' }
1190
+ ])
1191
+ }
1192
+ })
1193
+
1194
+ // Test service
1195
+ const result = await Effect.runPromise(
1196
+ Effect.gen(function* () {
1197
+ const service = yield* CourseService
1198
+ return yield* service.getCourseWithLessons('course123')
1199
+ }).pipe(Effect.provide(MockProvider))
1200
+ )
1201
+
1202
+ expect(result.course.name).toBe('Test Course')
1203
+ expect(result.lessons).toHaveLength(2)
1204
+ })
1205
+
1206
+ it('should fail with CourseNotFoundError', async () => {
1207
+ const MockProvider = Layer.succeed(DataProvider, {
1208
+ things: {
1209
+ get: (id) => Effect.fail(new ThingNotFoundError({ thingId: id }))
1210
+ }
1211
+ })
1212
+
1213
+ const result = await Effect.runPromiseExit(
1214
+ Effect.gen(function* () {
1215
+ const service = yield* CourseService
1216
+ return yield* service.getCourseWithLessons('invalid')
1217
+ }).pipe(Effect.provide(MockProvider))
1218
+ )
1219
+
1220
+ expect(result._tag).toBe('Failure')
1221
+ expect(result.cause.error._tag).toBe('CourseNotFoundError')
1222
+ })
1223
+ })
1224
+ `,
1225
+
1226
+ coverage: [
1227
+ "Service logic (business rules)",
1228
+ "Error transformations",
1229
+ "Effect composition",
1230
+ "Edge cases"
1231
+ ]
1232
+ },
1233
+
1234
+ // Layer 2: Integration Tests (Service + Real Provider + Test Backend)
1235
+ integrationTests: {
1236
+ what: "Test service + provider + real backend",
1237
+ backend: "Test Convex deployment (isolated database)",
1238
+ slow: "Seconds per test (real network calls)",
1239
+
1240
+ example: `
1241
+ // tests/integration/course-creation.test.ts
1242
+ import { describe, it, expect, beforeEach, afterEach } from 'vitest'
1243
+ import { convexProvider } from '@/providers/convex'
1244
+ import { CourseService } from '@/services/CourseService'
1245
+
1246
+ describe('Course Creation Flow', () => {
1247
+ let testProvider
1248
+ let testOrgId
1249
+
1250
+ beforeEach(async () => {
1251
+ // Use test Convex deployment
1252
+ testProvider = convexProvider({
1253
+ url: process.env.TEST_CONVEX_URL
1254
+ })
1255
+
1256
+ // Create test org
1257
+ testOrgId = await testProvider.organizations.create({
1258
+ name: 'Test Org',
1259
+ slug: 'test-org'
1260
+ })
1261
+ })
1262
+
1263
+ afterEach(async () => {
1264
+ // Cleanup test data
1265
+ await testProvider.organizations.delete(testOrgId)
1266
+ })
1267
+
1268
+ it('should create course with lessons', async () => {
1269
+ // Create course (real mutation)
1270
+ const courseId = await testProvider.things.create({
1271
+ type: 'course',
1272
+ name: 'Integration Test Course',
1273
+ properties: { organizationId: testOrgId }
1274
+ })
1275
+
1276
+ // Create lessons (real mutations)
1277
+ const lesson1Id = await testProvider.things.create({
1278
+ type: 'lesson',
1279
+ name: 'Lesson 1',
1280
+ properties: { organizationId: testOrgId }
1281
+ })
1282
+
1283
+ await testProvider.connections.create({
1284
+ fromThingId: lesson1Id,
1285
+ toThingId: courseId,
1286
+ relationshipType: 'part_of'
1287
+ })
1288
+
1289
+ // Verify (real query)
1290
+ const result = await CourseService.getCourseWithLessons(courseId)
1291
+
1292
+ expect(result.course.name).toBe('Integration Test Course')
1293
+ expect(result.lessons).toHaveLength(1)
1294
+ expect(result.lessons[0].name).toBe('Lesson 1')
1295
+ })
1296
+ })
1297
+ `,
1298
+
1299
+ coverage: [
1300
+ "Full data flow (service → provider → backend → database)",
1301
+ "Real mutations and queries",
1302
+ "Data consistency",
1303
+ "Backend constraints"
1304
+ ]
1305
+ },
1306
+
1307
+ // Layer 3: E2E Tests (Full UI flow in browser)
1308
+ e2eTests: {
1309
+ what: "Test complete user flows in browser",
1310
+ tool: "Playwright (headless Chrome)",
1311
+ slow: "10-30s per test (full page loads)",
1312
+
1313
+ example: `
1314
+ // tests/e2e/course-enrollment.spec.ts
1315
+ import { test, expect } from '@playwright/test'
1316
+
1317
+ test.describe('Course Enrollment Flow', () => {
1318
+ test('user can enroll in course', async ({ page }) => {
1319
+ // Navigate to course page
1320
+ await page.goto('/courses/course123')
1321
+
1322
+ // Verify course details rendered
1323
+ await expect(page.locator('h1')).toContainText('Test Course')
1324
+
1325
+ // Click enroll button
1326
+ await page.click('button:has-text("Enroll")')
1327
+
1328
+ // Wait for enrollment confirmation
1329
+ await expect(page.locator('.toast')).toContainText('Enrolled successfully')
1330
+
1331
+ // Verify button changed to "Go to Course"
1332
+ await expect(page.locator('button')).toContainText('Go to Course')
1333
+
1334
+ // Navigate to user dashboard
1335
+ await page.goto('/account')
1336
+
1337
+ // Verify course appears in "My Courses"
1338
+ await expect(page.locator('.my-courses')).toContainText('Test Course')
1339
+ })
1340
+
1341
+ test('unauthorized user prompted to login', async ({ page }) => {
1342
+ // Navigate as guest
1343
+ await page.goto('/courses/course123')
1344
+
1345
+ // Click enroll
1346
+ await page.click('button:has-text("Enroll")')
1347
+
1348
+ // Should redirect to login
1349
+ await expect(page).toHaveURL(/\/login/)
1350
+
1351
+ // Login form should have returnUrl
1352
+ await expect(page.locator('form')).toHaveAttribute(
1353
+ 'data-return-url',
1354
+ '/courses/course123'
1355
+ )
1356
+ })
1357
+ })
1358
+ `,
1359
+
1360
+ coverage: [
1361
+ "User flows (click, type, navigate)",
1362
+ "Visual rendering",
1363
+ "Loading states",
1364
+ "Error states",
1365
+ "Authentication flows"
1366
+ ]
1367
+ },
1368
+
1369
+ // Test Pyramid
1370
+ pyramid: {
1371
+ unit: "70% (fast, many tests, mock provider)",
1372
+ integration: "20% (medium, key flows, test backend)",
1373
+ e2e: "10% (slow, critical paths, real UI)"
1374
+ },
1375
+
1376
+ // CI/CD Strategy
1377
+ cicd: {
1378
+ on_pr: "Run unit + integration tests",
1379
+ on_merge: "Run all tests (including E2E)",
1380
+ on_deploy: "Run smoke tests (E2E critical paths)"
1381
+ },
1382
+
1383
+ // Golden Rule
1384
+ invariant: "Mock providers for unit tests. Real providers for integration. Real UI for E2E."
1385
+ }
1386
+ ```
1387
+
1388
+ ---
1389
+
1390
+ ## Pattern Language
1391
+
1392
+ ### Pattern: Backend-Agnostic Data Access
1393
+
1394
+ ```typescript
1395
+ {
1396
+ id: "backend_agnostic_data_access",
1397
+ type: DATA_PATTERN,
1398
+ applicability: (thing) => thing.type === "service" || thing.type === "component",
1399
+
1400
+ inputs: [DataProviderInterface],
1401
+ outputs: [Data],
1402
+
1403
+ transform: (operation) => ({
1404
+ code: `
1405
+ // Works with ANY backend (Convex, WordPress, Notion, etc.)
1406
+ const provider = yield* DataProvider
1407
+
1408
+ // Call ontology operation (backend translates)
1409
+ const data = yield* provider.things.get(id)
1410
+
1411
+ return data
1412
+ `
1413
+ }),
1414
+
1415
+ constraints: [
1416
+ "no_backend_specific_code",
1417
+ "uses_provider_interface",
1418
+ "effect_ts_typed"
1419
+ ],
1420
+
1421
+ benefits: [
1422
+ "swap_backends_one_line",
1423
+ "type_safe_errors",
1424
+ "testable_via_mock_provider"
1425
+ ]
1426
+ }
1427
+ ```
1428
+
1429
+ ### Pattern: Generic vs Specialized Services
1430
+
1431
+ ```typescript
1432
+ {
1433
+ id: "generic_vs_specialized_service_decision",
1434
+ type: SERVICE_PATTERN,
1435
+
1436
+ decision_tree: {
1437
+ // Start with generic
1438
+ question: "Do you need to operate on things?",
1439
+ yes: {
1440
+ default: "Use ThingService (handles all 66 types)",
1441
+ code: `
1442
+ const thingService = yield* ThingService
1443
+ const course = yield* thingService.get(courseId)
1444
+ const lesson = yield* thingService.get(lessonId)
1445
+ `
1446
+ },
1447
+
1448
+ // Add specialized only if needed
1449
+ question: "Do you repeat the same 2-3 operation sequence 3+ times?",
1450
+ yes: {
1451
+ action: "Create SpecializedService",
1452
+ code: `
1453
+ // CourseService.ts (OPTIONAL)
1454
+ export class CourseService {
1455
+ getCourseWithLessons: (id) => Effect.all([
1456
+ thingService.get(id),
1457
+ connectionService.getRelated(id, 'part_of', 'to')
1458
+ ])
1459
+ }
1460
+ `
1461
+ },
1462
+ no: {
1463
+ action: "Keep using generic services",
1464
+ reason: "Don't create specialized services prematurely"
1465
+ }
1466
+ },
1467
+
1468
+ constraints: [
1469
+ "always_have_generic_services",
1470
+ "specialized_services_optional",
1471
+ "add_specialized_when_patterns_emerge"
1472
+ ]
1473
+ }
1474
+ ```
1475
+
1476
+ ### Pattern: Provider Swapping
1477
+
1478
+ ```typescript
1479
+ {
1480
+ id: "provider_swapping",
1481
+ type: CONFIGURATION_PATTERN,
1482
+ applicability: (thing) => thing.type === "configuration",
1483
+
1484
+ inputs: [ProviderConfig],
1485
+ outputs: [ConfiguredProvider],
1486
+
1487
+ transform: (config) => ({
1488
+ // astro.config.ts
1489
+ code: `
1490
+ import { convexProvider } from './providers/convex'
1491
+ // import { wordpressProvider } from './providers/wordpress'
1492
+ // import { notionProvider } from './providers/notion'
1493
+
1494
+ export default defineConfig({
1495
+ integrations: [
1496
+ one({
1497
+ // ✅ Change this ONE line to swap backends
1498
+ provider: convexProvider({
1499
+ url: import.meta.env.PUBLIC_CONVEX_URL
1500
+ })
1501
+
1502
+ // OR use WordPress:
1503
+ // provider: wordpressProvider({
1504
+ // url: 'https://yoursite.com',
1505
+ // apiKey: import.meta.env.WORDPRESS_API_KEY
1506
+ // })
1507
+ })
1508
+ ]
1509
+ })
1510
+ `
1511
+ }),
1512
+
1513
+ constraints: [
1514
+ "one_line_change",
1515
+ "no_code_changes",
1516
+ "components_unchanged"
1517
+ ]
1518
+ }
1519
+ ```
1520
+
1521
+ ### Pattern: Progressive Enhancement
1522
+
1523
+ ```typescript
1524
+ {
1525
+ id: "progressive_enhancement",
1526
+ type: UI_PATTERN,
1527
+ strategy: "Start SSR, enhance with islands, add real-time last",
1528
+
1529
+ // Level 1: Base (works without JS)
1530
+ base: {
1531
+ layer: "Astro SSR",
1532
+ code: `
1533
+ <form action="/api/courses/enroll" method="post">
1534
+ <input type="hidden" name="courseId" value={courseId} />
1535
+ <button type="submit">Enroll</button>
1536
+ </form>
1537
+ `,
1538
+ works_without_js: true,
1539
+ accessibility: "Full keyboard navigation",
1540
+ seo: "Search engines can see content"
1541
+ },
1542
+
1543
+ // Level 2: Enhanced (adds interactivity with JS)
1544
+ enhanced: {
1545
+ layer: "React island",
1546
+ code: `
1547
+ <EnrollButton
1548
+ client:load
1549
+ courseId={courseId}
1550
+ initialEnrolled={enrolled}
1551
+ />
1552
+ `,
1553
+ requires_js: true,
1554
+ benefit: "Optimistic UI, instant feedback, loading states",
1555
+ fallback: "Form still works via SSR if JS fails"
1556
+ },
1557
+
1558
+ // Level 3: Real-time (live updates)
1559
+ realtime: {
1560
+ layer: "WebSocket subscription",
1561
+ code: `
1562
+ export function EnrollmentCount({ courseId }: Props) {
1563
+ const count = useQuery(api.connections.getCount, {
1564
+ thingId: courseId,
1565
+ relationshipType: 'enrolled_in'
1566
+ })
1567
+ return <span>{count} enrolled</span>
1568
+ }
1569
+ `,
1570
+ requires_js: true,
1571
+ requires_subscription: true,
1572
+ benefit: "Live count updates as users enroll",
1573
+ fallback: "SSR shows stale count (still functional)"
1574
+ },
1575
+
1576
+ strategy: {
1577
+ 1: "Start with SSR (universal baseline)",
1578
+ 2: "Add islands for interactivity (progressive)",
1579
+ 3: "Add real-time only where needed (rare)",
1580
+ rule: "Each layer enhances, never replaces previous layer"
1581
+ }
1582
+ }
1583
+ ```
1584
+
1585
+ ---
1586
+
1587
+ ## Type Sync Automation
1588
+
1589
+ ### Automatic Frontend/Backend Type Synchronization
1590
+
1591
+ ```typescript
1592
+ {
1593
+ principle: "Backend schema = single source of truth. Frontend derives types.",
1594
+
1595
+ pipeline: {
1596
+ step1: {
1597
+ where: "Backend",
1598
+ what: "Define schema (convex/schema.ts)",
1599
+ code: `
1600
+ // convex/schema.ts
1601
+ import { defineSchema, defineTable } from 'convex/server'
1602
+ import { v } from 'convex/values'
1603
+
1604
+ export default defineSchema({
1605
+ things: defineTable({
1606
+ type: v.string(),
1607
+ name: v.string(),
1608
+ properties: v.any(),
1609
+ status: v.union(
1610
+ v.literal('draft'),
1611
+ v.literal('published'),
1612
+ v.literal('archived')
1613
+ ),
1614
+ createdAt: v.number(),
1615
+ updatedAt: v.number()
1616
+ })
1617
+ })
1618
+ `
1619
+ },
1620
+
1621
+ step2: {
1622
+ where: "Backend deployment",
1623
+ what: "Deploy → Auto-generate types",
1624
+ command: "npx convex deploy",
1625
+ generates: "convex/_generated/dataModel.d.ts",
1626
+ code: `
1627
+ // Auto-generated by Convex
1628
+ export type Thing = {
1629
+ _id: Id<'things'>
1630
+ _creationTime: number
1631
+ type: string
1632
+ name: string
1633
+ properties: any
1634
+ status: 'draft' | 'published' | 'archived'
1635
+ createdAt: number
1636
+ updatedAt: number
1637
+ }
1638
+ `
1639
+ },
1640
+
1641
+ step3: {
1642
+ where: "Frontend",
1643
+ what: "Import generated types",
1644
+ code: `
1645
+ // src/services/ThingService.ts
1646
+ import type { Id } from '@/convex/_generated/dataModel'
1647
+ import type { Thing } from '@/convex/_generated/dataModel'
1648
+
1649
+ export class ThingService {
1650
+ get(id: Id<'things'>): Effect<Thing, Error> {
1651
+ // TypeScript knows exact shape of Thing
1652
+ }
1653
+ }
1654
+ `
1655
+ },
1656
+
1657
+ step4: {
1658
+ where: "Development",
1659
+ what: "Hot reload triggers type regeneration",
1660
+ trigger: "Save convex/schema.ts",
1661
+ action: "Convex dev server regenerates types",
1662
+ result: "TypeScript immediately shows errors in frontend"
1663
+ }
1664
+ },
1665
+
1666
+ validation: {
1667
+ ci: {
1668
+ check: "TypeScript compilation",
1669
+ command: "npx astro check",
1670
+ fails_if: "Frontend imports types that don't match backend schema",
1671
+ result: "Can't merge PR if types mismatch"
1672
+ },
1673
+
1674
+ dev: {
1675
+ watch: "Convex dev server watches schema changes",
1676
+ regenerates: "Types on every schema save",
1677
+ editor: "VS Code shows TypeScript errors instantly"
1678
+ },
1679
+
1680
+ deploy: {
1681
+ blocks: "Can't deploy frontend if types don't match backend",
1682
+ ensures: "Frontend and backend always in sync"
1683
+ }
1684
+ },
1685
+
1686
+ benefits: [
1687
+ "Single source of truth (backend schema)",
1688
+ "Zero manual type definition duplication",
1689
+ "Immediate feedback on type mismatches",
1690
+ "Impossible to deploy mismatched types",
1691
+ "Refactoring is type-safe (rename propagates)"
1692
+ ],
1693
+
1694
+ example_refactor: `
1695
+ // Backend: Rename field
1696
+ // convex/schema.ts
1697
+ things: defineTable({
1698
+ // name: v.string(), // OLD
1699
+ title: v.string(), // NEW
1700
+ })
1701
+
1702
+ // Deploy: Convex regenerates types
1703
+ // convex/_generated/dataModel.d.ts
1704
+ export type Thing = {
1705
+ title: string // Updated
1706
+ }
1707
+
1708
+ // Frontend: TypeScript shows errors immediately
1709
+ // src/components/CourseCard.tsx
1710
+ <h1>{course.name}</h1> // ❌ Error: Property 'name' doesn't exist
1711
+ <h1>{course.title}</h1> // ✅ Fixed
1712
+
1713
+ // Result: Refactor is type-safe, can't forget any references
1714
+ `,
1715
+
1716
+ invariant: "Backend schema → Generated types → Frontend imports. Never manual sync."
1717
+ }
1718
+ ```
1719
+
1720
+ ---
1721
+
1722
+ ## Observability Layer
1723
+
1724
+ ### Four-Pillar Observability Strategy
1725
+
1726
+ ```typescript
1727
+ {
1728
+ // Pillar 1: Provider Call Observability
1729
+ provider_calls: {
1730
+ what: "Track every provider operation",
1731
+ metrics: [
1732
+ "Duration (p50, p95, p99)",
1733
+ "Success rate (%)",
1734
+ "Error types (grouped by _tag)",
1735
+ "Throughput (ops/sec)"
1736
+ ],
1737
+
1738
+ implementation: `
1739
+ // Wrap provider with observability layer
1740
+ class ObservableProvider implements DataProviderInterface {
1741
+ constructor(
1742
+ private provider: DataProviderInterface,
1743
+ private logger: Logger
1744
+ ) {}
1745
+
1746
+ things = {
1747
+ get: (id) => {
1748
+ const start = Date.now()
1749
+
1750
+ return this.provider.things.get(id).pipe(
1751
+ Effect.tap(() => {
1752
+ const duration = Date.now() - start
1753
+ this.logger.info('provider.things.get', {
1754
+ thingId: id,
1755
+ duration,
1756
+ success: true
1757
+ })
1758
+ }),
1759
+ Effect.tapError((error) => {
1760
+ const duration = Date.now() - start
1761
+ this.logger.error('provider.things.get', {
1762
+ thingId: id,
1763
+ duration,
1764
+ error: error._tag,
1765
+ success: false
1766
+ })
1767
+ })
1768
+ )
1769
+ }
1770
+ }
1771
+ }
1772
+ `,
1773
+
1774
+ alerts: [
1775
+ "Slow queries (>2s p95)",
1776
+ "High error rate (>5% over 5min)",
1777
+ "Specific error spikes (e.g., UnauthorizedError >10/min)"
1778
+ ]
1779
+ },
1780
+
1781
+ // Pillar 2: Context Usage Observability
1782
+ context_usage: {
1783
+ what: "Track AI context loading per request",
1784
+ metrics: [
1785
+ "Tokens loaded (by category: types, patterns, examples)",
1786
+ "Total context size",
1787
+ "Context budget utilization (%)",
1788
+ "Cache hit rate (%)"
1789
+ ],
1790
+
1791
+ implementation: `
1792
+ class ContextManager {
1793
+ private usage = {
1794
+ types: 0,
1795
+ patterns: 0,
1796
+ examples: 0,
1797
+ total: 0
1798
+ }
1799
+
1800
+ addContext(category, content) {
1801
+ const tokens = estimateTokens(content)
1802
+ this.usage[category] += tokens
1803
+ this.usage.total += tokens
1804
+
1805
+ // Log to observability
1806
+ logger.info('context.added', {
1807
+ category,
1808
+ tokens,
1809
+ total: this.usage.total,
1810
+ utilization: this.usage.total / BUDGET.total
1811
+ })
1812
+ }
1813
+
1814
+ getReport() {
1815
+ return {
1816
+ ...this.usage,
1817
+ budget: BUDGET.total,
1818
+ utilization: (this.usage.total / BUDGET.total) * 100,
1819
+ remaining: BUDGET.total - this.usage.total
1820
+ }
1821
+ }
1822
+ }
1823
+ `,
1824
+
1825
+ alerts: [
1826
+ "Context budget exceeded (>5k tokens)",
1827
+ "Utilization >80% (approaching limit)",
1828
+ "Cache miss rate >20% (inefficient loading)"
1829
+ ]
1830
+ },
1831
+
1832
+ // Pillar 3: Cache Efficiency Observability
1833
+ cache_efficiency: {
1834
+ what: "Track cache performance",
1835
+ metrics: [
1836
+ "Hit rate (%) by cache tier (L1, L2, L3, L4)",
1837
+ "Miss count (absolute)",
1838
+ "Eviction rate (items evicted/sec)",
1839
+ "Cache size (MB)"
1840
+ ],
1841
+
1842
+ implementation: `
1843
+ class ObservableCache<K, V> {
1844
+ private hits = 0
1845
+ private misses = 0
1846
+ private cache = new Map<K, V>()
1847
+
1848
+ get(key: K): V | undefined {
1849
+ if (this.cache.has(key)) {
1850
+ this.hits++
1851
+ logger.info('cache.hit', {
1852
+ key,
1853
+ hitRate: this.hitRate()
1854
+ })
1855
+ return this.cache.get(key)
1856
+ } else {
1857
+ this.misses++
1858
+ logger.info('cache.miss', {
1859
+ key,
1860
+ hitRate: this.hitRate()
1861
+ })
1862
+ return undefined
1863
+ }
1864
+ }
1865
+
1866
+ hitRate() {
1867
+ return this.hits / (this.hits + this.misses)
1868
+ }
1869
+
1870
+ getStats() {
1871
+ return {
1872
+ hits: this.hits,
1873
+ misses: this.misses,
1874
+ hitRate: this.hitRate(),
1875
+ size: this.cache.size
1876
+ }
1877
+ }
1878
+ }
1879
+ `,
1880
+
1881
+ alerts: [
1882
+ "L1 hit rate <95% (type cache should be near 100%)",
1883
+ "L3 hit rate <60% (SSR cache not effective)",
1884
+ "Cache size >100MB (memory pressure)"
1885
+ ]
1886
+ },
1887
+
1888
+ // Pillar 4: Page Performance Observability
1889
+ page_performance: {
1890
+ what: "Track Core Web Vitals + custom metrics",
1891
+ metrics: [
1892
+ "TTFB (Time To First Byte)",
1893
+ "FCP (First Contentful Paint)",
1894
+ "LCP (Largest Contentful Paint)",
1895
+ "CLS (Cumulative Layout Shift)",
1896
+ "FID (First Input Delay)",
1897
+ "Provider call duration (frontend metric)"
1898
+ ],
1899
+
1900
+ implementation: `
1901
+ // Client-side performance tracking
1902
+ // src/lib/observability.ts
1903
+ export function trackPagePerformance() {
1904
+ // Core Web Vitals
1905
+ if ('web-vital' in window) {
1906
+ getCLS(sendToAnalytics)
1907
+ getFID(sendToAnalytics)
1908
+ getLCP(sendToAnalytics)
1909
+ }
1910
+
1911
+ // Custom: Provider call timing
1912
+ performance.measure('provider-call', {
1913
+ start: 'provider-start',
1914
+ end: 'provider-end'
1915
+ })
1916
+
1917
+ const measure = performance.getEntriesByName('provider-call')[0]
1918
+ sendToAnalytics({
1919
+ metric: 'provider_call_duration',
1920
+ value: measure.duration
1921
+ })
1922
+ }
1923
+
1924
+ function sendToAnalytics(metric) {
1925
+ fetch('/api/analytics', {
1926
+ method: 'POST',
1927
+ body: JSON.stringify(metric)
1928
+ })
1929
+ }
1930
+ `,
1931
+
1932
+ cloudflare_analytics: {
1933
+ what: "Built-in Cloudflare Pages Analytics",
1934
+ tracks: ["TTFB", "FCP", "LCP", "requests/sec", "bandwidth"],
1935
+ dashboard: "Cloudflare Pages dashboard → Analytics tab"
1936
+ },
1937
+
1938
+ alerts: [
1939
+ "LCP >2.5s (bad user experience)",
1940
+ "CLS >0.1 (layout shift)",
1941
+ "TTFB >800ms (slow backend)"
1942
+ ]
1943
+ },
1944
+
1945
+ // Event Emission Pattern
1946
+ eventEmission: {
1947
+ pattern: "Every significant operation emits event to backend",
1948
+
1949
+ example: `
1950
+ // Frontend calls provider
1951
+ const course = await provider.things.get(courseId)
1952
+
1953
+ // Provider logs event (backend receives)
1954
+ await provider.events.log({
1955
+ type: 'provider_query',
1956
+ actorId: userId,
1957
+ targetId: courseId,
1958
+ timestamp: Date.now(),
1959
+ metadata: {
1960
+ operation: 'things.get',
1961
+ duration: 123,
1962
+ success: true,
1963
+ provider: 'convex'
1964
+ }
1965
+ })
1966
+
1967
+ // Backend stores in events table
1968
+ // Dashboard can query: "Show all provider queries today"
1969
+ `,
1970
+
1971
+ benefits: [
1972
+ "Full audit trail of all operations",
1973
+ "Query events to debug issues",
1974
+ "Aggregate metrics from events",
1975
+ "Events table = observability database"
1976
+ ]
1977
+ },
1978
+
1979
+ // Dashboards
1980
+ dashboards: {
1981
+ realtime: {
1982
+ tool: "Convex Dashboard or custom React dashboard",
1983
+ queries: [
1984
+ "Provider call rate (last 1 hour)",
1985
+ "Error rate by type (last 1 hour)",
1986
+ "Cache hit rate (last 1 hour)",
1987
+ "Top slow queries (p95 >2s)"
1988
+ ]
1989
+ },
1990
+
1991
+ historical: {
1992
+ tool: "Cloudflare Analytics + custom aggregations",
1993
+ queries: [
1994
+ "Page performance trends (last 30 days)",
1995
+ "Provider call trends (last 30 days)",
1996
+ "Error trends by type (last 30 days)",
1997
+ "Cache efficiency trends (last 30 days)"
1998
+ ]
1999
+ }
2000
+ },
2001
+
2002
+ // Golden Rule
2003
+ invariant: "Observe everything. Log to events. Query events for debugging. Alert on anomalies."
2004
+ }
2005
+ ```
2006
+
2007
+ ---
2008
+
2009
+ ## Agent Task Mapping
2010
+
2011
+ ### Frontend-Specific Agent Responsibilities
2012
+
2013
+ ```typescript
2014
+ {
2015
+ agents: {
2016
+ "frontend-service-agent": {
2017
+ creates: ["Effect.ts services"],
2018
+ outputs: [
2019
+ "src/services/ThingService.ts",
2020
+ "src/services/ConnectionService.ts",
2021
+ "src/services/[Domain]Service.ts (optional)"
2022
+ ],
2023
+ coordination: "Autonomous (parallel with provider-agent)"
2024
+ },
2025
+
2026
+ "frontend-provider-agent": {
2027
+ creates: ["DataProvider implementations"],
2028
+ outputs: [
2029
+ "src/providers/convex/ConvexProvider.ts",
2030
+ "src/providers/wordpress/WordPressProvider.ts",
2031
+ "src/providers/[backend]/Provider.ts"
2032
+ ],
2033
+ coordination: "Autonomous (parallel with service-agent)"
2034
+ },
2035
+
2036
+ "frontend-page-agent": {
2037
+ creates: ["Astro SSR pages"],
2038
+ outputs: [
2039
+ "src/pages/[thing]/index.astro",
2040
+ "src/pages/[thing]/[id].astro"
2041
+ ],
2042
+ coordination: "Waits for service-agent (reads task_completed events)"
2043
+ },
2044
+
2045
+ "frontend-component-agent": {
2046
+ creates: ["React islands (interactive components)"],
2047
+ outputs: [
2048
+ "src/components/features/[thing]/[Component].tsx"
2049
+ ],
2050
+ coordination: "Parallel with page-agent (both wait for service-agent)"
2051
+ },
2052
+
2053
+ "frontend-test-agent": {
2054
+ creates: ["Unit, integration, and E2E tests"],
2055
+ outputs: [
2056
+ "tests/unit/services/[name].test.ts",
2057
+ "tests/integration/[flow].test.ts",
2058
+ "tests/e2e/[flow].spec.ts"
2059
+ ],
2060
+ coordination: "Waits for ALL agents (service, provider, page, component)"
2061
+ }
2062
+ },
2063
+
2064
+ // Event-driven coordination (from workflow.md)
2065
+ coordination_mechanism: {
2066
+ type: "Events table (ontology IS the message bus)",
2067
+
2068
+ pattern: `
2069
+ // Agent completes → Emits event
2070
+ await logEvent({
2071
+ type: 'task_completed',
2072
+ actorId: 'frontend-service-agent',
2073
+ targetId: 'task_id',
2074
+ metadata: { files: [...] }
2075
+ })
2076
+
2077
+ // Dependent agent → Queries events
2078
+ const completed = await queryEvents({
2079
+ type: 'task_completed',
2080
+ actorId: 'frontend-service-agent'
2081
+ })
2082
+
2083
+ if (completed) {
2084
+ // Proceed with task
2085
+ }
2086
+ `
2087
+ },
2088
+
2089
+ // Parallel execution (from workflow.md)
2090
+ execution_model: {
2091
+ services_layer: {
2092
+ agents: ["frontend-service-agent", "frontend-provider-agent"],
2093
+ parallelism: "Both start simultaneously",
2094
+ coordination: "Autonomous (no dependencies)"
2095
+ },
2096
+
2097
+ ui_layer: {
2098
+ agents: ["frontend-page-agent", "frontend-component-agent"],
2099
+ parallelism: "Both start after services complete",
2100
+ coordination: "Both wait for service-agent events"
2101
+ },
2102
+
2103
+ testing_layer: {
2104
+ agents: ["frontend-test-agent"],
2105
+ parallelism: "Starts after all implementation complete",
2106
+ coordination: "Waits for all agents"
2107
+ }
2108
+ }
2109
+ }
2110
+ ```
2111
+
2112
+ ---
2113
+
2114
+ ## Common Mistakes
2115
+
2116
+ ### Top 10 Anti-Patterns to Avoid
2117
+
2118
+ ```typescript
2119
+ {
2120
+ // Mistake 1: Coupling to specific provider
2121
+ mistake1: {
2122
+ problem: "Importing Convex directly in frontend code",
2123
+ bad: `
2124
+ // ❌ BAD
2125
+ import { ConvexClient } from 'convex/browser'
2126
+ const client = new ConvexClient(url)
2127
+ const course = await client.query(api.courses.get, { id })
2128
+ `,
2129
+ good: `
2130
+ // ✅ GOOD
2131
+ const provider = yield* DataProvider
2132
+ const course = yield* provider.things.get(id)
2133
+ `,
2134
+ why: "Bad code breaks when you swap backends. Good code works with ANY backend."
2135
+ },
2136
+
2137
+ // Mistake 2: Creating specialized services prematurely
2138
+ mistake2: {
2139
+ problem: "Creating CourseService before patterns emerge",
2140
+ bad: `
2141
+ // ❌ BAD (created after 1 use)
2142
+ class CourseService {
2143
+ getCourseWithLessons(id) {
2144
+ // Used once, doesn't justify specialized service
2145
+ }
2146
+ }
2147
+ `,
2148
+ good: `
2149
+ // ✅ GOOD (use generic services until pattern repeats 3+ times)
2150
+ const course = yield* thingService.get(id)
2151
+ const lessons = yield* connectionService.getRelated(id, 'part_of', 'to')
2152
+
2153
+ // Only create CourseService after repeating this 3+ times
2154
+ `,
2155
+ why: "Premature abstraction creates unnecessary complexity. Wait for patterns."
2156
+ },
2157
+
2158
+ // Mistake 3: Loading too much context
2159
+ mistake3: {
2160
+ problem: "Loading entire codebase for AI generation",
2161
+ bad: `
2162
+ // ❌ BAD
2163
+ const context = {
2164
+ allFiles: loadFiles('**/*.ts'), // 200k tokens
2165
+ allDocs: loadDocs(), // 50k tokens
2166
+ allExamples: loadExamples() // 30k tokens
2167
+ } // 280k tokens
2168
+ `,
2169
+ good: `
2170
+ // ✅ GOOD
2171
+ const context = {
2172
+ interface: DataProviderInterface, // 300 tokens
2173
+ pattern: servicePattern // 400 tokens
2174
+ } // 700 tokens (99.7% reduction)
2175
+ `,
2176
+ why: "Context explosion wastes time and money. Load only what's needed."
2177
+ },
2178
+
2179
+ // Mistake 4: Duplicating server state in frontend
2180
+ mistake4: {
2181
+ problem: "Storing backend data in useState",
2182
+ bad: `
2183
+ // ❌ BAD
2184
+ const [courses, setCourses] = useState([])
2185
+ useEffect(() => {
2186
+ provider.things.list({ type: 'course' })
2187
+ .then(setCourses)
2188
+ }, [])
2189
+ `,
2190
+ good: `
2191
+ // ✅ GOOD
2192
+ const courses = useQuery(api.courses.list)
2193
+ // Provider handles caching, no state duplication
2194
+ `,
2195
+ why: "Duplicating state creates sync issues. Let provider handle caching."
2196
+ },
2197
+
2198
+ // Mistake 5: Not handling error states
2199
+ mistake5: {
2200
+ problem: "No UI for errors",
2201
+ bad: `
2202
+ // ❌ BAD
2203
+ const course = await provider.things.get(id)
2204
+ return <div>{course.name}</div>
2205
+ // What if course is undefined? No error handling!
2206
+ `,
2207
+ good: `
2208
+ // ✅ GOOD
2209
+ try {
2210
+ const course = await provider.things.get(id)
2211
+ return <div>{course.name}</div>
2212
+ } catch (error) {
2213
+ if (error._tag === 'ThingNotFoundError') {
2214
+ return <Alert>Course not found</Alert>
2215
+ }
2216
+ return <Alert>Error loading course</Alert>
2217
+ }
2218
+ `,
2219
+ why: "Errors WILL happen. Always have UI for error states."
2220
+ },
2221
+
2222
+ // Mistake 6: Manual org filtering
2223
+ mistake6: {
2224
+ problem: "Manually filtering by organizationId",
2225
+ bad: `
2226
+ // ❌ BAD
2227
+ const courses = await provider.things.list({
2228
+ type: 'course',
2229
+ organizationId: ctx.locals.organizationId // Manual filtering
2230
+ })
2231
+ `,
2232
+ good: `
2233
+ // ✅ GOOD
2234
+ const courses = await provider.things.list({ type: 'course' })
2235
+ // Provider auto-injects organizationId
2236
+ `,
2237
+ why: "Provider enforces multi-tenancy. Frontend shouldn't know about orgs."
2238
+ },
2239
+
2240
+ // Mistake 7: Not caching type definitions
2241
+ mistake7: {
2242
+ problem: "Loading type definitions on every request",
2243
+ bad: `
2244
+ // ❌ BAD
2245
+ async function generateCode(type) {
2246
+ const typeDef = await loadTypeFromFile(type) // Loads from disk every time
2247
+ return ai.generate(task, { type: typeDef })
2248
+ }
2249
+ `,
2250
+ good: `
2251
+ // ✅ GOOD
2252
+ const typeCache = new Map()
2253
+
2254
+ async function generateCode(type) {
2255
+ if (!typeCache.has(type)) {
2256
+ typeCache.set(type, await loadTypeFromFile(type)) // Load once
2257
+ }
2258
+ return ai.generate(task, { type: typeCache.get(type) })
2259
+ }
2260
+ `,
2261
+ why: "Type definitions never change at runtime. Cache forever."
2262
+ },
2263
+
2264
+ // Mistake 8: Skipping progressive enhancement
2265
+ mistake8: {
2266
+ problem: "JavaScript-only forms (don't work without JS)",
2267
+ bad: `
2268
+ // ❌ BAD
2269
+ <button onClick={() => enroll()}>Enroll</button>
2270
+ // Doesn't work if JS fails to load
2271
+ `,
2272
+ good: `
2273
+ // ✅ GOOD
2274
+ <form action="/api/enroll" method="post">
2275
+ <button type="submit">Enroll</button>
2276
+ </form>
2277
+ // Works with or without JS
2278
+
2279
+ // Then enhance with JS:
2280
+ <EnrollButton client:load /> // Adds optimistic UI
2281
+ `,
2282
+ why: "Always start with working HTML. JavaScript should enhance, not enable."
2283
+ },
2284
+
2285
+ // Mistake 9: Not testing with mock providers
2286
+ mistake9: {
2287
+ problem: "Testing with real backend (slow, flaky)",
2288
+ bad: `
2289
+ // ❌ BAD
2290
+ test('gets course', async () => {
2291
+ const course = await service.get('real_id_from_db')
2292
+ // Depends on real database state
2293
+ })
2294
+ `,
2295
+ good: `
2296
+ // ✅ GOOD
2297
+ test('gets course', async () => {
2298
+ const MockProvider = Layer.succeed(DataProvider, {
2299
+ things: { get: (id) => Effect.succeed(mockCourse) }
2300
+ })
2301
+
2302
+ const course = await service.get('any_id')
2303
+ .pipe(Effect.provide(MockProvider))
2304
+ // Fast, deterministic, no database
2305
+ })
2306
+ `,
2307
+ why: "Unit tests should be fast and deterministic. Use mocks."
2308
+ },
2309
+
2310
+ // Mistake 10: Ignoring type sync
2311
+ mistake10: {
2312
+ problem: "Manually duplicating backend types in frontend",
2313
+ bad: `
2314
+ // ❌ BAD
2315
+ // frontend/types.ts
2316
+ type Course = {
2317
+ id: string
2318
+ title: string
2319
+ // Manually copied from backend
2320
+ }
2321
+ `,
2322
+ good: `
2323
+ // ✅ GOOD
2324
+ import type { Thing } from '@/convex/_generated/dataModel'
2325
+ // Auto-synced from backend schema
2326
+ `,
2327
+ why: "Manual type sync breaks. Use generated types from backend."
2328
+ }
2329
+ }
2330
+ ```
2331
+
2332
+ ---
2333
+
2334
+ ## Summary
2335
+
2336
+ ### Ontology Evolution
2337
+
2338
+ **Version 4.0.0 Additions:**
2339
+ - **Provider as Context Loader** - 99.9% context reduction via interface abstraction
2340
+ - **Multi-Tenant Architecture** - Subdomain-based org isolation enforced by provider
2341
+ - **4-Tier Caching** - Type definitions, interface, SSR data, real-time subscriptions
2342
+ - **State Management Hierarchy** - Server, SSR, Island, Shared (4 layers)
2343
+ - **Error Propagation** - Provider → Service → Component → UI (typed errors)
2344
+ - **Testing Ontology** - Unit (mock), Integration (real backend), E2E (browser)
2345
+ - **Progressive Enhancement** - SSR → Islands → Real-time (3 layers)
2346
+ - **Type Sync Automation** - Backend schema → Generated types → Frontend imports
2347
+ - **Observability Layer** - Provider calls, context usage, cache efficiency, page performance
2348
+ - **Agent Task Mapping** - Event-driven parallel execution with simplified coordination
2349
+
2350
+ ### Key Metrics
2351
+
2352
+ | Metric | v3.0.0 | v4.0.0 | Improvement |
2353
+ |--------|--------|--------|-------------|
2354
+ | **Context per request** | 50k-300k tokens | 300-5k tokens | **99%+ reduction** |
2355
+ | **Backend coupling** | High (Convex-specific) | Zero (provider abstraction) | **Infinite backends** |
2356
+ | **Caching strategy** | Undefined | 4-tier (L1-L4) | **80-95% fewer calls** |
2357
+ | **Error handling** | Basic | Full propagation | **100% coverage** |
2358
+ | **Testing strategy** | Ad-hoc | 3-layer (unit/int/e2e) | **Systematic** |
2359
+ | **State management** | Unclear | 4-layer hierarchy | **No duplication** |
2360
+ | **Observability** | None | 4-pillar (calls, context, cache, perf) | **Full visibility** |
2361
+ | **Agent coordination** | Sequential | Parallel (event-driven) | **5x faster** |
2362
+
2363
+ ### Derivation Power
2364
+
2365
+ ```
2366
+ From minimal axioms:
2367
+ 7 axioms (v4.0.0)
2368
+ + DataProviderInterface
2369
+ + 4-tier caching
2370
+ + 4-layer state management
2371
+ + Error propagation ontology
2372
+ + Testing ontology
2373
+ + Observability layer
2374
+ →
2375
+ ∞ implementations × ∞ backends × ∞ caching strategies
2376
+ ```
2377
+
2378
+ ### Context Engineering Results
2379
+
2380
+ **Traditional approach:**
2381
+ - Load: 50k-300k tokens per request
2382
+ - Cost: $0.50-$3.00 per request
2383
+ - Speed: 30-60 seconds
2384
+ - Backends: 1 (tightly coupled)
2385
+
2386
+ **Ontology-driven approach (v4.0.0):**
2387
+ - Load: 300-5k tokens per request (98-99% reduction)
2388
+ - Cost: $0.003-$0.05 per request (100x cheaper)
2389
+ - Speed: 2-5 seconds (10x faster)
2390
+ - Backends: ∞ (swap with 1 line)
2391
+
2392
+ ### Properties
2393
+
2394
+ - ✅ **Minimal**: Smallest set of axioms for complete expressiveness
2395
+ - ✅ **Complete**: Derives all implementations for all backends
2396
+ - ✅ **Consistent**: No contradictions
2397
+ - ✅ **Composable**: Clear composition algebra
2398
+ - ✅ **Formal**: Mathematically rigorous
2399
+ - ✅ **Practical**: AI-executable
2400
+ - ✅ **Flexible**: Works with ANY backend
2401
+ - ✅ **Observable**: Full instrumentation
2402
+ - ✅ **Testable**: 3-layer testing strategy
2403
+ - ✅ **Performant**: 4-tier caching, 98%+ context reduction
2404
+
2405
+ ### Usage Flow (v4.0.0)
2406
+
2407
+ ```
2408
+ Agent receives task:
2409
+ 1. Load type definition [L1 cache: instant]
2410
+ 2. Load DataProviderInterface [L2 cache: instant]
2411
+ 3. Load pattern [context-engineering: just-in-time]
2412
+ 4. Generate backend-agnostic code
2413
+ 5. Validate: No backend-specific imports
2414
+ 6. Write tests (mock provider for unit tests)
2415
+ 7. Emit events (coordination via ontology)
2416
+ 8. Observe metrics (provider calls, context usage, cache hits)
2417
+
2418
+ Total context: Minimal (vs 280k traditional)
2419
+ Result: Code works with Convex, WordPress, Notion, Supabase, etc.
2420
+ Performance: 98%+ context reduction, 10x faster, 100x cheaper
2421
+ ```
2422
+
2423
+ ---
2424
+
2425
+ **The ontology is executable. Types are the program. Backends are interchangeable. Context is minimal. Everything is observable.**
2426
+
2427
+ **v4.0.0: Complete backend agnosticism + context engineering + observability + event-driven coordination = The future of frontend development.**