oneie 3.6.7 → 3.6.12

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 (168) hide show
  1. package/.claude/agents/agent-backend.md +83 -0
  2. package/.claude/agents/agent-designer.md +97 -0
  3. package/.claude/agents/agent-director.md +118 -7
  4. package/.claude/agents/agent-documenter.md +93 -0
  5. package/.claude/agents/agent-frontend.md +96 -0
  6. package/.claude/agents/agent-ops.md +264 -32
  7. package/.claude/agents/agent-problem-solver.md +166 -0
  8. package/.claude/agents/agent-quality.md +127 -0
  9. package/.claude/commands/build.md +293 -0
  10. package/.claude/commands/cascade.md +231 -127
  11. package/.claude/commands/deploy.md +56 -17
  12. package/.claude/commands/mcp-toggle.md +93 -0
  13. package/.claude/commands/one.md +78 -127
  14. package/.claude/commands/plan.md +394 -80
  15. package/.claude/commands/push.md +75 -14
  16. package/.claude/commands/release.md +89 -25
  17. package/.claude/commands/server.md +2 -0
  18. package/.claude/hooks/__pycache__/todo.cpython-313.pyc +0 -0
  19. package/.claude/hooks/root-cleanup.py +75 -0
  20. package/.claude/skills/INDEX.md +523 -0
  21. package/.claude/skills/REGISTRY.md +529 -0
  22. package/.claude/skills/agent-backend-create-mutation.md +319 -0
  23. package/.claude/skills/agent-designer-create-wireframe.md +341 -0
  24. package/.claude/skills/agent-frontend-create-page.md +413 -0
  25. package/.claude/skills/agents/README.md +238 -0
  26. package/dist/clone-web.js +1 -1
  27. package/dist/clone-web.js.map +1 -1
  28. package/folders.yaml +1 -1
  29. package/one/.obsidian/workspace.json +38 -38
  30. package/one/connections/api/queries-reference.md +842 -0
  31. package/one/connections/api-reference.md +1011 -0
  32. package/one/connections/integration-examples.md +875 -0
  33. package/one/connections/integration-guide.md +869 -0
  34. package/one/connections/integration-phase2.md +736 -0
  35. package/one/events/API_ROUTES_FIXES_SUMMARY.md +262 -0
  36. package/one/events/ASTRO-INTEGRATION-EXAMPLES.md +636 -0
  37. package/one/events/BEFORE_AFTER_COMPARISON.md +960 -0
  38. package/one/events/CONNECTIONS_DEMO.md +501 -0
  39. package/one/events/DELIVERABLES.md +432 -0
  40. package/one/events/DEMO-GROUPS-PAGE.md +392 -0
  41. package/one/events/DEMO-TESTING-SUMMARY.md +518 -0
  42. package/one/events/DEMO_COMPONENTS.md +487 -0
  43. package/one/events/DEMO_HOOKS_INDEX.md +334 -0
  44. package/one/events/DEMO_INFRASTRUCTURE.md +905 -0
  45. package/one/events/DEMO_INFRASTRUCTURE_SUMMARY.md +570 -0
  46. package/one/events/DEMO_INTEGRATION_CHECKLIST.md +431 -0
  47. package/one/events/DEMO_QUICK_REFERENCE.md +441 -0
  48. package/one/events/DEMO_SETUP.md +476 -0
  49. package/one/events/EFFECT_TS_API_PATTERN.md +478 -0
  50. package/one/events/GROUPS_DEMO_IMPLEMENTATION.md +414 -0
  51. package/one/events/HOOKS-DEMO.md +441 -0
  52. package/one/events/ONTOLOGY-HOOKS-README.md +700 -0
  53. package/one/events/ONTOLOGY-INTEGRATION-MANIFEST.md +365 -0
  54. package/one/events/QA-CHECKLIST.md +674 -0
  55. package/one/events/QUICK-START-ONTOLOGY.md +408 -0
  56. package/one/events/SEARCH_DEMO_CODE_REFERENCE.md +639 -0
  57. package/one/events/SEARCH_DEMO_DELIVERY.md +415 -0
  58. package/one/events/SEARCH_DEMO_SUMMARY.md +303 -0
  59. package/one/events/SEARCH_DEMO_VISUAL_GUIDE.md +381 -0
  60. package/one/events/TEST-PLAN-INDEX.md +346 -0
  61. package/one/events/TEST-PLAN.md +1417 -0
  62. package/one/events/TESTING-DELIVERY.txt +372 -0
  63. package/one/events/TRANSITIONS-QUICK-START.md +141 -0
  64. package/one/events/TYPESCRIPT_FIXES.md +152 -0
  65. package/one/events/TYPESCRIPT_FIXES_COMPLETE.txt +412 -0
  66. package/one/events/TYPESCRIPT_FIXES_INDEX.md +341 -0
  67. package/one/events/VIEW-TRANSITIONS.md +428 -0
  68. package/one/events/backend-integration-tests.md +606 -0
  69. package/one/events/backend-structure-diagram.txt +393 -0
  70. package/one/events/backend-structure-summary.txt +269 -0
  71. package/one/events/cloudflare-pages-infrastructure-setup.md +264 -0
  72. package/one/events/convex-analysis-index.md +304 -0
  73. package/one/events/convex-structure-analysis.md +700 -0
  74. package/one/events/design-spec-complete.md +208 -0
  75. package/one/events/ontology-test-examples.md +562 -0
  76. package/one/events/phase1-backend-implementation-complete.md +518 -0
  77. package/one/events/test-dashboard.md +345 -0
  78. package/one/events/test-index.md +361 -0
  79. package/one/events/test-report-ontology.md +582 -0
  80. package/one/events/testing-summary.md +344 -0
  81. package/one/groups/features.md +2878 -0
  82. package/one/groups/strategy copy.md +869 -0
  83. package/one/knowledge/backend-api-reference.md +710 -0
  84. package/one/knowledge/documentation-summary.md +285 -0
  85. package/one/knowledge/lessons-learned.md +294 -4
  86. package/one/knowledge/ontology-visual-guide.md +360 -0
  87. package/one/knowledge/ontology.md +9 -17
  88. package/one/things/demo-accessibility-animations.md +999 -0
  89. package/one/things/demo-components.md +1304 -0
  90. package/one/things/demo-design-summary.md +629 -0
  91. package/one/things/demo-design-system.md +919 -0
  92. package/one/things/demo-page-layouts.md +989 -0
  93. package/one/things/designs/accessibility-audit.md +790 -0
  94. package/one/things/designs/component-specifications.md +757 -0
  95. package/one/things/designs/design-overview.md +318 -0
  96. package/one/things/designs/design-tokens.md +414 -0
  97. package/one/things/designs/wireframes-dashboard.md +653 -0
  98. package/one/things/docs/api-requests.md +923 -0
  99. package/one/things/features/0 All Features.md +2 -0
  100. package/one/things/implementation/backend-guide.md +412 -0
  101. package/one/things/plans/2-backend-agnostic-frontend.md +11 -8
  102. package/one/things/plans/2-sites.md +895 -0
  103. package/one/things/plans/ai-elements.md +1259 -0
  104. package/one/things/plans/ai-integration.md +947 -0
  105. package/one/things/plans/ai-sdk.md +761 -0
  106. package/one/things/plans/app.md +1 -1
  107. package/one/things/plans/architecture-summary.md +283 -0
  108. package/one/things/plans/async-ai-agents.md +215 -0
  109. package/one/things/plans/backend-agnostic-frontend.md +11 -6
  110. package/one/things/plans/backend-cleanup-quickstart.md +346 -0
  111. package/one/things/plans/backend-ontology-conformance.md +416 -0
  112. package/one/things/plans/backend-status.md +541 -0
  113. package/one/things/plans/backend-structure.md +799 -0
  114. package/one/things/plans/backend-target-structure.md +438 -0
  115. package/one/things/plans/backend.md +1133 -0
  116. package/one/things/plans/better-auth-any-backend.md +11 -11
  117. package/one/things/plans/cli-updates-required.md +280 -0
  118. package/one/things/plans/complete-step-by-step.md +1302 -0
  119. package/one/things/plans/convex-agents.md +1005 -0
  120. package/one/things/plans/deployment-architecture.md +426 -0
  121. package/one/things/plans/development-plan.md +1220 -0
  122. package/one/things/plans/effect.md +808 -48
  123. package/one/things/plans/integrate-frontend-and-backend.md +579 -0
  124. package/one/things/plans/mcp-clear-context-prompt.md +60 -0
  125. package/one/things/plans/mcp-simple.md +228 -0
  126. package/one/things/plans/one.md +8 -7
  127. package/one/things/plans/ontology-6-dimensions.md +20 -14
  128. package/one/things/plans/quick-wins.md +1273 -0
  129. package/one/things/plans/readme-backend-cleanup.md +361 -0
  130. package/one/things/plans/separate-demo.md +830 -0
  131. package/one/things/plans/separate.md +3 -3
  132. package/one/things/plans/sequence.md +1897 -0
  133. package/one/things/plans/sync-checklist.md +321 -0
  134. package/one/things/plans/unified-implementation-plan.md +3 -3
  135. package/one/things/plans/update-demos.md +513 -0
  136. package/package.json +1 -1
  137. package/.claude/agents/backend-specialist.md +0 -169
  138. package/.claude/agents/designer.md +0 -216
  139. package/.claude/agents/frontend-specialist.md +0 -236
  140. package/.claude/commands/done.md +0 -35
  141. package/.claude/commands/infer.md +0 -138
  142. package/.claude/commands/next.md +0 -53
  143. package/.claude/commands/one copy.md +0 -565
  144. package/.claude/commands/one-template.md +0 -106
  145. package/.claude/commands/one-v1.md +0 -609
  146. package/.claude/hooks/__pycache__/knowledge-post.cpython-313.pyc +0 -0
  147. package/.claude/hooks/__pycache__/knowledge-pre.cpython-313.pyc +0 -0
  148. package/one/groups/nine-padel-customers.md +0 -138
  149. package/one/groups/nine-padel-data-structure.md +0 -167
  150. package/one/groups/nine-padel-ontology-specification.md +0 -359
  151. package/one/groups/nine-padel-ontology.md +0 -143
  152. package/one/groups/nine-padel-strategy.md +0 -234
  153. package/one/groups/nine-padel.md +0 -211
  154. package/one/groups/nine-padle-contents.baked.md +0 -1252
  155. package/one/groups/nine-padle-contents.md +0 -6
  156. package/one/things/features/1-1-agent-prompts/design.md +0 -470
  157. package/one/things/features/1-1-agent-prompts/tests.md +0 -264
  158. package/one/things/features/1-2-yaml-orchestrator/design.md +0 -497
  159. package/one/things/features/1-2-yaml-orchestrator/tests.md +0 -227
  160. package/one/things/features/1-3-event-coordination/design.md +0 -544
  161. package/one/things/features/1-3-event-coordination/tests.md +0 -223
  162. package/one/things/features/1-4-knowledge-management/design.md +0 -609
  163. package/one/things/features/1-4-knowledge-management/tests.md +0 -195
  164. package/one/things/features/1-5-quality-loops/design.md +0 -797
  165. package/one/things/features/1-5-quality-loops/tests.md +0 -212
  166. package/one/things/features/1-6-numbering-structure/design.md +0 -610
  167. package/one/things/features/1-6-numbering-structure/tests.md +0 -213
  168. package/one/things/features/dataprovider-interface/1-tests.md +0 -1522
@@ -0,0 +1,1133 @@
1
+ # ONE Backend API: Complete Ontology-Driven Backend
2
+
3
+ **Version:** 1.0.0
4
+ **Status:** Planning → Implementation Ready
5
+ **Created:** 2025-10-24
6
+ **Tech Stack:** Convex + Hono + AI SDK + Better Auth + Effect.ts (optional confect)
7
+
8
+ ---
9
+
10
+ ## Executive Summary
11
+
12
+ Build a complete, production-ready backend API for ONE Platform that:
13
+
14
+ 1. **Implements the full 6-dimension ontology** (Groups, People, Things, Connections, Events, Knowledge)
15
+ 2. **Provides REST/HTTP API via Hono** for external access with API key auth
16
+ 3. **Integrates AI SDK** for intelligent agents and RAG
17
+ 4. **Uses Better Auth** for 6 authentication methods
18
+ 5. **Enables multi-tenancy** via Groups with perfect data isolation
19
+ 6. **Supports any frontend** (web, mobile, desktop, CLI) with universal API
20
+
21
+ **Key Architecture Decision:** Backend is **headless and universal** - ANY client can connect with an API key.
22
+
23
+ ---
24
+
25
+ ## Table of Contents
26
+
27
+ 1. [Architecture Overview](#architecture-overview)
28
+ 2. [Tech Stack Integration](#tech-stack-integration)
29
+ 3. [API Structure](#api-structure)
30
+ 4. [Authentication & Authorization](#authentication--authorization)
31
+ 5. [Multi-Tenancy via Groups](#multi-tenancy-via-groups)
32
+ 6. [AI SDK Integration](#ai-sdk-integration)
33
+ 7. [Implementation Plan](#implementation-plan)
34
+ 8. [API Examples](#api-examples)
35
+
36
+ ---
37
+
38
+ ## Architecture Overview
39
+
40
+ ```
41
+ ┌──────────────────────────────────────────────────────────────┐
42
+ │ EXTERNAL CLIENTS │
43
+ │ Web App | Mobile App | Desktop App | CLI | Third-Party │
44
+ │ (API Key Required) │
45
+ └─────────────────────────┬────────────────────────────────────┘
46
+ │ HTTPS/REST
47
+ ↓
48
+ ┌──────────────────────────────────────────────────────────────┐
49
+ │ HONO HTTP LAYER │
50
+ │ - REST API endpoints │
51
+ │ - API key authentication │
52
+ │ - Rate limiting per group │
53
+ │ - Request/response validation │
54
+ │ - OpenAPI documentation │
55
+ └─────────────────────────┬────────────────────────────────────┘
56
+ │
57
+ ↓
58
+ ┌──────────────────────────────────────────────────────────────┐
59
+ │ BETTER AUTH (6 Methods) │
60
+ │ 1. Email/Password 4. Password Reset │
61
+ │ 2. OAuth (Google+) 5. Email Verification │
62
+ │ 3. Magic Links 6. 2FA │
63
+ └─────────────────────────┬────────────────────────────────────┘
64
+ │
65
+ ↓
66
+ ┌──────────────────────────────────────────────────────────────┐
67
+ │ CONVEX FUNCTIONS (Business Logic) │
68
+ │ Queries │ Mutations │ Actions │
69
+ │ (read) │ (write) │ (external APIs, AI) │
70
+ └─────────────────────────┬────────────────────────────────────┘
71
+ │
72
+ ↓
73
+ ┌──────────────────────────────────────────────────────────────┐
74
+ │ AI SDK INTEGRATION │
75
+ │ - generateText (OpenAI, Anthropic, etc.) │
76
+ │ - generateObject (structured outputs) │
77
+ │ - streamText (real-time responses) │
78
+ │ - embedMany (RAG vectors) │
79
+ └─────────────────────────┬────────────────────────────────────┘
80
+ │
81
+ ↓
82
+ ┌──────────────────────────────────────────────────────────────┐
83
+ │ CONVEX DATABASE (6-Dimension Ontology) │
84
+ │ │
85
+ │ ┌─────────────────────────────────────────────────────────┐│
86
+ │ │ 1. GROUPS Multi-tenant isolation with nesting ││
87
+ │ │ - friend_circle, business, community, dao, gov, org ││
88
+ │ │ - Hierarchical: parent → child → grandchild... ││
89
+ │ │ - Every group = isolated data namespace ││
90
+ │ └─────────────────────────────────────────────────────────┘│
91
+ │ ┌─────────────────────────────────────────────────────────┐│
92
+ │ │ 2. PEOPLE Authorization & governance ││
93
+ │ │ - platform_owner, group_owner, group_user, customer ││
94
+ │ │ - Role-based access control (RBAC) ││
95
+ │ │ - Multi-group membership supported ││
96
+ │ └─────────────────────────────────────────────────────────┘│
97
+ │ ┌─────────────────────────────────────────────────────────┐│
98
+ │ │ 3. THINGS 66+ entity types (dynamic from YAML) ││
99
+ │ │ - Generic type field (auto-generated from ontology) ││
100
+ │ │ - Flexible properties (any JSON) ││
101
+ │ │ - All scoped to groupId ││
102
+ │ └─────────────────────────────────────────────────────────┘│
103
+ │ ┌─────────────────────────────────────────────────────────┐│
104
+ │ │ 4. CONNECTIONS 25+ relationship types ││
105
+ │ │ - Bidirectional with metadata ││
106
+ │ │ - Protocol-agnostic (via metadata) ││
107
+ │ │ - All scoped to groupId ││
108
+ │ └─────────────────────────────────────────────────────────┘│
109
+ │ ┌─────────────────────────────────────────────────────────┐│
110
+ │ │ 5. EVENTS 67+ event types (complete audit trail) ││
111
+ │ │ - Actor (person) + target (thing) + timestamp ││
112
+ │ │ - All actions logged automatically ││
113
+ │ │ - All scoped to groupId ││
114
+ │ └─────────────────────────────────────────────────────────┘│
115
+ │ ┌─────────────────────────────────────────────────────────┐│
116
+ │ │ 6. KNOWLEDGE Labels + chunks + vectors (RAG) ││
117
+ │ │ - Vector embeddings for semantic search ││
118
+ │ │ - Label taxonomy for categorization ││
119
+ │ │ - All scoped to groupId ││
120
+ │ └─────────────────────────────────────────────────────────┘│
121
+ └──────────────────────────────────────────────────────────────┘
122
+ ```
123
+
124
+ **Key Principle:** Everything flows through the 6-dimension ontology. External clients use Hono HTTP API, internal clients can use Convex directly.
125
+
126
+ ---
127
+
128
+ ## Tech Stack Integration
129
+
130
+ ### 1. Convex (Real-time Backend)
131
+
132
+ **What:** Serverless backend with real-time database
133
+ **Why:** Type-safe, reactive queries, automatic scaling, WebSocket subscriptions
134
+ **Where:** `/backend/convex/`
135
+
136
+ **Current Status:**
137
+ - ✅ Schema defined with 6-dimension ontology
138
+ - ✅ Dynamic type generation from YAML ontologies
139
+ - ✅ Groups, entities, connections, events, knowledge tables
140
+ - ⚠️ Partial mutations/queries (needs completion)
141
+
142
+ **Integration:**
143
+ ```typescript
144
+ // backend/convex/schema.ts
145
+ export default defineSchema({
146
+ groups: defineTable({ ... }), // Dimension 1
147
+ entities: defineTable({ ... }), // Dimension 3 (Things)
148
+ connections: defineTable({ ... }), // Dimension 4
149
+ events: defineTable({ ... }), // Dimension 5
150
+ knowledge: defineTable({ ... }), // Dimension 6
151
+ });
152
+ ```
153
+
154
+ ### 2. Hono (HTTP Layer)
155
+
156
+ **What:** Fast, lightweight web framework for Cloudflare Workers/Edge
157
+ **Why:** Perfect for Convex HTTP endpoints, OpenAPI support, middleware-based
158
+ **Where:** `/backend/convex/http.ts`
159
+
160
+ **Reference:** https://stack.convex.dev/hono-with-convex
161
+
162
+ **Integration Pattern:**
163
+ ```typescript
164
+ // backend/convex/http.ts
165
+ import { Hono } from "hono";
166
+ import { cors } from "hono/cors";
167
+ import { HTTPException } from "hono/http-exception";
168
+ import { handle } from "hono/vercel";
169
+ import { httpRouter } from "convex/server";
170
+
171
+ const app = new Hono();
172
+
173
+ // Middleware
174
+ app.use("*", cors());
175
+ app.use("*", async (c, next) => {
176
+ // API key authentication
177
+ const apiKey = c.req.header("X-API-Key");
178
+ if (!apiKey) {
179
+ throw new HTTPException(401, { message: "API key required" });
180
+ }
181
+ // Verify API key and get groupId
182
+ const group = await verifyApiKey(apiKey);
183
+ c.set("groupId", group._id);
184
+ await next();
185
+ });
186
+
187
+ // Routes (see API Structure section)
188
+ app.get("/api/groups", ...)
189
+ app.post("/api/things", ...)
190
+ app.get("/api/connections/:id", ...)
191
+
192
+ // Convex integration
193
+ export default httpRouter({
194
+ "/": handle(app),
195
+ });
196
+ ```
197
+
198
+ ### 3. AI SDK (Vercel AI SDK)
199
+
200
+ **What:** Universal AI toolkit for TypeScript
201
+ **Why:** Provider-agnostic (OpenAI, Anthropic, etc.), streaming, structured outputs
202
+ **Where:** `/backend/convex/actions/ai.ts`
203
+
204
+ **Key Features:**
205
+ - `generateText()` - Generate responses
206
+ - `generateObject()` - Structured JSON outputs
207
+ - `streamText()` - Real-time streaming
208
+ - `embedMany()` - Vector embeddings for RAG
209
+
210
+ **Integration:**
211
+ ```typescript
212
+ // backend/convex/actions/ai.ts
213
+ import { generateText, embedMany } from "ai";
214
+ import { openai } from "@ai-sdk/openai";
215
+ import { action } from "./_generated/server";
216
+ import { v } from "convex/values";
217
+
218
+ export const generateResponse = action({
219
+ args: {
220
+ groupId: v.id("groups"),
221
+ prompt: v.string(),
222
+ context: v.optional(v.array(v.string())),
223
+ },
224
+ handler: async (ctx, args) => {
225
+ // 1. Search knowledge base for context
226
+ const relevantChunks = await ctx.runQuery(
227
+ internal.queries.knowledge.search,
228
+ { groupId: args.groupId, query: args.prompt, limit: 5 }
229
+ );
230
+
231
+ // 2. Generate response with context
232
+ const { text } = await generateText({
233
+ model: openai("gpt-4o"),
234
+ prompt: args.prompt,
235
+ system: `Context: ${relevantChunks.map(c => c.text).join("\n\n")}`,
236
+ });
237
+
238
+ // 3. Log event
239
+ await ctx.runMutation(internal.mutations.events.log, {
240
+ groupId: args.groupId,
241
+ type: "ai_response_generated",
242
+ metadata: { prompt: args.prompt, responseLength: text.length },
243
+ });
244
+
245
+ return { text };
246
+ },
247
+ });
248
+
249
+ export const embedText = action({
250
+ args: {
251
+ groupId: v.id("groups"),
252
+ texts: v.array(v.string()),
253
+ },
254
+ handler: async (ctx, args) => {
255
+ const { embeddings } = await embedMany({
256
+ model: openai.embedding("text-embedding-3-small"),
257
+ values: args.texts,
258
+ });
259
+
260
+ // Store embeddings in knowledge table
261
+ for (let i = 0; i < embeddings.length; i++) {
262
+ await ctx.runMutation(internal.mutations.knowledge.create, {
263
+ groupId: args.groupId,
264
+ type: "chunk",
265
+ text: args.texts[i],
266
+ embedding: embeddings[i],
267
+ });
268
+ }
269
+
270
+ return { count: embeddings.length };
271
+ },
272
+ });
273
+ ```
274
+
275
+ ### 4. Better Auth
276
+
277
+ **What:** Universal authentication for TypeScript
278
+ **Why:** 6 auth methods, backend-agnostic, multi-tenant ready
279
+ **Where:** `/backend/convex/auth.ts`
280
+
281
+ **Current Status:**
282
+ - ✅ Basic email/password auth implemented
283
+ - ⚠️ Needs full 6-method integration
284
+ - ⚠️ Needs group-scoped sessions
285
+
286
+ **Integration:**
287
+ ```typescript
288
+ // backend/convex/auth.ts
289
+ import { betterAuth } from "better-auth";
290
+ import { convexAdapter } from "better-auth/adapters/convex";
291
+
292
+ export const auth = betterAuth({
293
+ database: convexAdapter(ctx.db),
294
+ emailAndPassword: {
295
+ enabled: true,
296
+ },
297
+ socialProviders: {
298
+ google: {
299
+ clientId: process.env.GOOGLE_CLIENT_ID!,
300
+ clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
301
+ },
302
+ },
303
+ session: {
304
+ expiresIn: 60 * 60 * 24 * 7, // 7 days
305
+ updateAge: 60 * 60 * 24, // 1 day
306
+ },
307
+ });
308
+
309
+ // Group-scoped authentication
310
+ export const signUpWithGroup = mutation({
311
+ args: {
312
+ email: v.string(),
313
+ password: v.string(),
314
+ groupId: v.id("groups"),
315
+ },
316
+ handler: async (ctx, args) => {
317
+ // 1. Create user with Better Auth
318
+ const user = await auth.createUser({
319
+ email: args.email,
320
+ password: args.password,
321
+ });
322
+
323
+ // 2. Create person in ontology (Dimension 2)
324
+ const personId = await ctx.db.insert("entities", {
325
+ groupId: args.groupId,
326
+ type: "creator",
327
+ name: args.email,
328
+ properties: {
329
+ email: args.email,
330
+ userId: user.id,
331
+ role: "group_user",
332
+ },
333
+ status: "active",
334
+ createdAt: Date.now(),
335
+ updatedAt: Date.now(),
336
+ });
337
+
338
+ // 3. Create connection (user → group membership)
339
+ await ctx.db.insert("connections", {
340
+ groupId: args.groupId,
341
+ type: "member_of",
342
+ fromId: personId,
343
+ toId: args.groupId,
344
+ metadata: { role: "group_user" },
345
+ createdAt: Date.now(),
346
+ });
347
+
348
+ // 4. Log event
349
+ await ctx.db.insert("events", {
350
+ groupId: args.groupId,
351
+ type: "person_created",
352
+ actorId: personId,
353
+ targetId: personId,
354
+ timestamp: Date.now(),
355
+ metadata: { method: "email_password" },
356
+ });
357
+
358
+ return { userId: user.id, personId };
359
+ },
360
+ });
361
+ ```
362
+
363
+ ### 5. Effect.ts + confect (Optional)
364
+
365
+ **What:** Functional programming library for type-safe error handling
366
+ **Why:** Composable services, typed errors, dependency injection
367
+ **Where:** Optional - can wrap Convex functions
368
+
369
+ **Reference:** https://github.com/rjdellecese/confect
370
+
371
+ **Integration (Optional):**
372
+ ```typescript
373
+ // backend/convex/confect.ts (if using)
374
+ import { makeConfect } from "@rjdellecese/confect";
375
+ import { Effect } from "effect";
376
+
377
+ export const { query, mutation, action } = makeConfect({
378
+ /* confect config */
379
+ });
380
+
381
+ // Usage
382
+ export const getEntity = query({
383
+ args: { id: v.string() },
384
+ returns: Schema.Struct({
385
+ _id: Schema.String,
386
+ type: Schema.String,
387
+ name: Schema.String,
388
+ }),
389
+ handler: (args) =>
390
+ Effect.gen(function* () {
391
+ const { db } = yield* ConfectQueryCtx;
392
+ const entity = yield* db.get(args.id);
393
+ if (!entity) {
394
+ return yield* Effect.fail(new EntityNotFoundError(args.id));
395
+ }
396
+ return entity;
397
+ }),
398
+ });
399
+ ```
400
+
401
+ **Recommendation:** Start WITHOUT confect for simplicity. Add later if needed for advanced error handling.
402
+
403
+ ---
404
+
405
+ ## API Structure
406
+
407
+ ### REST API Endpoints (via Hono)
408
+
409
+ All endpoints require `X-API-Key` header and are scoped to the group associated with that API key.
410
+
411
+ #### Groups (Dimension 1)
412
+
413
+ ```
414
+ GET /api/groups # List all groups (platform owner only)
415
+ GET /api/groups/:id # Get group details
416
+ POST /api/groups # Create new group
417
+ PATCH /api/groups/:id # Update group
418
+ DELETE /api/groups/:id # Archive group
419
+ GET /api/groups/:id/children # List child groups (hierarchical)
420
+ ```
421
+
422
+ #### People (Dimension 2)
423
+
424
+ ```
425
+ GET /api/people # List people in group
426
+ GET /api/people/:id # Get person details
427
+ POST /api/people # Create person (invite user)
428
+ PATCH /api/people/:id # Update person (role, permissions)
429
+ DELETE /api/people/:id # Remove person from group
430
+ GET /api/people/:id/groups # List groups person belongs to
431
+ ```
432
+
433
+ #### Things (Dimension 3)
434
+
435
+ ```
436
+ GET /api/things # List things (filterable by type)
437
+ GET /api/things/:id # Get thing details
438
+ POST /api/things # Create thing
439
+ PATCH /api/things/:id # Update thing
440
+ DELETE /api/things/:id # Archive thing
441
+ GET /api/things/:id/connections # Get related things
442
+ GET /api/things/:id/events # Get thing history
443
+ ```
444
+
445
+ #### Connections (Dimension 4)
446
+
447
+ ```
448
+ GET /api/connections # List connections
449
+ GET /api/connections/:id # Get connection details
450
+ POST /api/connections # Create connection
451
+ DELETE /api/connections/:id # Delete connection
452
+ GET /api/connections/from/:id # Get connections from thing
453
+ GET /api/connections/to/:id # Get connections to thing
454
+ ```
455
+
456
+ #### Events (Dimension 5)
457
+
458
+ ```
459
+ GET /api/events # List events (filterable)
460
+ GET /api/events/:id # Get event details
461
+ POST /api/events # Log custom event
462
+ GET /api/events/actor/:id # Events by actor (person)
463
+ GET /api/events/target/:id # Events by target (thing)
464
+ GET /api/events/timeline # Timeline view (paginated)
465
+ ```
466
+
467
+ #### Knowledge (Dimension 6)
468
+
469
+ ```
470
+ GET /api/knowledge # List knowledge items
471
+ GET /api/knowledge/:id # Get knowledge details
472
+ POST /api/knowledge # Create knowledge
473
+ DELETE /api/knowledge/:id # Delete knowledge
474
+ POST /api/knowledge/embed # Embed text (AI SDK)
475
+ POST /api/knowledge/search # Semantic search
476
+ ```
477
+
478
+ #### AI Endpoints
479
+
480
+ ```
481
+ POST /api/ai/generate # Generate text response
482
+ POST /api/ai/stream # Stream text response
483
+ POST /api/ai/embed # Generate embeddings
484
+ POST /api/ai/chat # Chat conversation
485
+ ```
486
+
487
+ #### Auth Endpoints
488
+
489
+ ```
490
+ POST /api/auth/signup # Sign up (email/password)
491
+ POST /api/auth/signin # Sign in
492
+ POST /api/auth/signout # Sign out
493
+ POST /api/auth/refresh # Refresh token
494
+ GET /api/auth/session # Get current session
495
+ POST /api/auth/magic-link # Send magic link
496
+ POST /api/auth/verify-email # Verify email
497
+ POST /api/auth/reset-password # Reset password
498
+ POST /api/auth/2fa/enable # Enable 2FA
499
+ POST /api/auth/2fa/verify # Verify 2FA
500
+ ```
501
+
502
+ ---
503
+
504
+ ## Authentication & Authorization
505
+
506
+ ### API Key Authentication
507
+
508
+ **Every request requires:**
509
+ ```
510
+ X-API-Key: gsk_abc123...
511
+ ```
512
+
513
+ **API Key Structure:**
514
+ ```typescript
515
+ {
516
+ _id: Id<"apiKeys">,
517
+ key: string, // Hashed
518
+ groupId: Id<"groups">, // Which group this key accesses
519
+ name: string, // Human-readable name
520
+ permissions: string[], // Optional: limit to specific endpoints
521
+ rateLimit: {
522
+ requests: number, // Per minute
523
+ burst: number,
524
+ },
525
+ expiresAt: number,
526
+ createdAt: number,
527
+ lastUsedAt: number,
528
+ status: "active" | "revoked",
529
+ }
530
+ ```
531
+
532
+ **API Key Generation:**
533
+ ```typescript
534
+ // backend/convex/mutations/apiKeys.ts
535
+ export const createApiKey = mutation({
536
+ args: {
537
+ groupId: v.id("groups"),
538
+ name: v.string(),
539
+ permissions: v.optional(v.array(v.string())),
540
+ },
541
+ handler: async (ctx, args) => {
542
+ // 1. Verify caller is group_owner
543
+ const caller = await getAuthenticatedPerson(ctx);
544
+ if (caller.role !== "group_owner") {
545
+ throw new Error("Only group owners can create API keys");
546
+ }
547
+
548
+ // 2. Generate key
549
+ const key = `gsk_${generateSecureToken()}`;
550
+ const hashedKey = await hashApiKey(key);
551
+
552
+ // 3. Store API key
553
+ const apiKeyId = await ctx.db.insert("apiKeys", {
554
+ key: hashedKey,
555
+ groupId: args.groupId,
556
+ name: args.name,
557
+ permissions: args.permissions || [],
558
+ rateLimit: { requests: 1000, burst: 100 },
559
+ expiresAt: Date.now() + 365 * 24 * 60 * 60 * 1000, // 1 year
560
+ createdAt: Date.now(),
561
+ lastUsedAt: 0,
562
+ status: "active",
563
+ });
564
+
565
+ // 4. Log event
566
+ await ctx.db.insert("events", {
567
+ groupId: args.groupId,
568
+ type: "api_key_created",
569
+ actorId: caller._id,
570
+ targetId: apiKeyId,
571
+ timestamp: Date.now(),
572
+ metadata: { name: args.name },
573
+ });
574
+
575
+ // Return unencrypted key ONCE (never shown again)
576
+ return { key, apiKeyId };
577
+ },
578
+ });
579
+ ```
580
+
581
+ ### Role-Based Access Control (RBAC)
582
+
583
+ **Access Matrix:**
584
+
585
+ | Role | Groups | People | Things | Connections | Events | Knowledge | API Keys |
586
+ |------|--------|--------|--------|-------------|--------|-----------|----------|
587
+ | **platform_owner** | All | All | All | All | All | All | All |
588
+ | **group_owner** | Own | Own Group | Own Group | Own Group | Own Group | Own Group | Create |
589
+ | **group_user** | Read | Read | Create/Edit Own | Create | Create | Create | None |
590
+ | **customer** | None | Read Self | Read | Read | None | None | None |
591
+
592
+ **Middleware:**
593
+ ```typescript
594
+ // backend/convex/lib/auth.ts
595
+ export async function requireRole(
596
+ ctx: QueryCtx | MutationCtx,
597
+ requiredRole: PersonRole
598
+ ) {
599
+ const person = await getAuthenticatedPerson(ctx);
600
+ const roleHierarchy = {
601
+ platform_owner: 4,
602
+ group_owner: 3,
603
+ group_user: 2,
604
+ customer: 1,
605
+ };
606
+
607
+ if (roleHierarchy[person.role] < roleHierarchy[requiredRole]) {
608
+ throw new Error(`Requires ${requiredRole} role or higher`);
609
+ }
610
+
611
+ return person;
612
+ }
613
+ ```
614
+
615
+ ---
616
+
617
+ ## Multi-Tenancy via Groups
618
+
619
+ ### Perfect Data Isolation
620
+
621
+ **Every table has `groupId`:**
622
+ ```typescript
623
+ entities: {
624
+ groupId: Id<"groups">, // REQUIRED
625
+ type: string,
626
+ name: string,
627
+ properties: any,
628
+ }
629
+ ```
630
+
631
+ **All queries filtered by groupId:**
632
+ ```typescript
633
+ // backend/convex/queries/entities.ts
634
+ export const list = query({
635
+ args: { type: v.string() },
636
+ handler: async (ctx, args) => {
637
+ // Get groupId from API key (via Hono middleware)
638
+ const groupId = ctx.auth.getUserIdentity()?.groupId;
639
+ if (!groupId) throw new Error("Group ID required");
640
+
641
+ return await ctx.db
642
+ .query("entities")
643
+ .withIndex("by_group_and_type", (q) =>
644
+ q.eq("groupId", groupId).eq("type", args.type)
645
+ )
646
+ .collect();
647
+ },
648
+ });
649
+ ```
650
+
651
+ ### Hierarchical Groups
652
+
653
+ **Parent groups can access child group data (configurable):**
654
+
655
+ ```typescript
656
+ export const listWithChildren = query({
657
+ args: { includeChildren: v.boolean() },
658
+ handler: async (ctx, args) => {
659
+ const groupId = getGroupId(ctx);
660
+
661
+ if (!args.includeChildren) {
662
+ return getEntitiesForGroup(ctx, groupId);
663
+ }
664
+
665
+ // Get all child groups recursively
666
+ const childGroupIds = await getChildGroups(ctx, groupId);
667
+ const allGroupIds = [groupId, ...childGroupIds];
668
+
669
+ // Query across all groups
670
+ const entities = [];
671
+ for (const gid of allGroupIds) {
672
+ const groupEntities = await getEntitiesForGroup(ctx, gid);
673
+ entities.push(...groupEntities);
674
+ }
675
+
676
+ return entities;
677
+ },
678
+ });
679
+ ```
680
+
681
+ ### Resource Quotas
682
+
683
+ **Enforce limits per group:**
684
+ ```typescript
685
+ export const create = mutation({
686
+ args: { type: v.string(), name: v.string(), properties: v.any() },
687
+ handler: async (ctx, args) => {
688
+ const groupId = getGroupId(ctx);
689
+ const group = await ctx.db.get(groupId);
690
+
691
+ // Check quota
692
+ const currentCount = await ctx.db
693
+ .query("entities")
694
+ .withIndex("by_group", (q) => q.eq("groupId", groupId))
695
+ .collect()
696
+ .length;
697
+
698
+ const limit = group.settings.limits?.entities || 1000;
699
+ if (currentCount >= limit) {
700
+ throw new Error(`Entity limit reached (${limit})`);
701
+ }
702
+
703
+ // Create entity
704
+ return await ctx.db.insert("entities", {
705
+ groupId,
706
+ type: args.type,
707
+ name: args.name,
708
+ properties: args.properties,
709
+ status: "active",
710
+ createdAt: Date.now(),
711
+ updatedAt: Date.now(),
712
+ });
713
+ },
714
+ });
715
+ ```
716
+
717
+ ---
718
+
719
+ ## AI SDK Integration
720
+
721
+ ### RAG (Retrieval-Augmented Generation)
722
+
723
+ **Complete RAG Pipeline:**
724
+
725
+ ```typescript
726
+ // backend/convex/actions/rag.ts
727
+ import { generateText, embedMany } from "ai";
728
+ import { openai } from "@ai-sdk/openai";
729
+ import { action } from "./_generated/server";
730
+ import { internal } from "./_generated/api";
731
+ import { v } from "convex/values";
732
+
733
+ export const ingestDocument = action({
734
+ args: {
735
+ groupId: v.id("groups"),
736
+ title: v.string(),
737
+ text: v.string(),
738
+ },
739
+ handler: async (ctx, args) => {
740
+ // 1. Create document wrapper
741
+ const docId = await ctx.runMutation(internal.mutations.knowledge.create, {
742
+ groupId: args.groupId,
743
+ type: "document",
744
+ text: args.title,
745
+ metadata: { title: args.title },
746
+ });
747
+
748
+ // 2. Chunk text (800 tokens, 200 overlap)
749
+ const chunks = chunkText(args.text, 800, 200);
750
+
751
+ // 3. Generate embeddings for all chunks
752
+ const { embeddings } = await embedMany({
753
+ model: openai.embedding("text-embedding-3-small"),
754
+ values: chunks,
755
+ });
756
+
757
+ // 4. Store chunks with embeddings
758
+ for (let i = 0; i < chunks.length; i++) {
759
+ await ctx.runMutation(internal.mutations.knowledge.create, {
760
+ groupId: args.groupId,
761
+ type: "chunk",
762
+ text: chunks[i],
763
+ embedding: embeddings[i],
764
+ metadata: {
765
+ documentId: docId,
766
+ chunkIndex: i,
767
+ },
768
+ });
769
+ }
770
+
771
+ return { documentId: docId, chunks: chunks.length };
772
+ },
773
+ });
774
+
775
+ export const answerQuestion = action({
776
+ args: {
777
+ groupId: v.id("groups"),
778
+ question: v.string(),
779
+ },
780
+ handler: async (ctx, args) => {
781
+ // 1. Embed question
782
+ const { embeddings: [questionEmbedding] } = await embedMany({
783
+ model: openai.embedding("text-embedding-3-small"),
784
+ values: [args.question],
785
+ });
786
+
787
+ // 2. Search for relevant chunks (vector similarity)
788
+ const relevantChunks = await ctx.runQuery(
789
+ internal.queries.knowledge.searchByVector,
790
+ {
791
+ groupId: args.groupId,
792
+ embedding: questionEmbedding,
793
+ limit: 5,
794
+ }
795
+ );
796
+
797
+ // 3. Generate answer with context
798
+ const context = relevantChunks.map((c) => c.text).join("\n\n");
799
+ const { text } = await generateText({
800
+ model: openai("gpt-4o"),
801
+ prompt: args.question,
802
+ system: `Answer based on this context:\n\n${context}`,
803
+ });
804
+
805
+ // 4. Log event
806
+ await ctx.runMutation(internal.mutations.events.log, {
807
+ groupId: args.groupId,
808
+ type: "question_answered",
809
+ metadata: {
810
+ question: args.question,
811
+ chunksUsed: relevantChunks.length,
812
+ },
813
+ });
814
+
815
+ return { answer: text, sources: relevantChunks };
816
+ },
817
+ });
818
+
819
+ // Helper: Chunk text with overlap
820
+ function chunkText(text: string, maxTokens: number, overlap: number): string[] {
821
+ const words = text.split(" ");
822
+ const chunks: string[] = [];
823
+ const wordsPerToken = 0.75; // Approximate
824
+
825
+ const maxWords = Math.floor(maxTokens * wordsPerToken);
826
+ const overlapWords = Math.floor(overlap * wordsPerToken);
827
+
828
+ for (let i = 0; i < words.length; i += maxWords - overlapWords) {
829
+ const chunk = words.slice(i, i + maxWords).join(" ");
830
+ chunks.push(chunk);
831
+ }
832
+
833
+ return chunks;
834
+ }
835
+ ```
836
+
837
+ ### Streaming Responses
838
+
839
+ ```typescript
840
+ // backend/convex/actions/ai.ts
841
+ import { streamText } from "ai";
842
+ import { openai } from "@ai-sdk/openai";
843
+ import { action } from "./_generated/server";
844
+ import { v } from "convex/values";
845
+
846
+ export const streamResponse = action({
847
+ args: {
848
+ groupId: v.id("groups"),
849
+ prompt: v.string(),
850
+ },
851
+ handler: async (ctx, args) => {
852
+ const { textStream } = await streamText({
853
+ model: openai("gpt-4o"),
854
+ prompt: args.prompt,
855
+ });
856
+
857
+ // Return stream (Hono will handle SSE)
858
+ return textStream;
859
+ },
860
+ });
861
+ ```
862
+
863
+ ### Structured Outputs
864
+
865
+ ```typescript
866
+ import { generateObject } from "ai";
867
+ import { z } from "zod";
868
+
869
+ export const extractEntities = action({
870
+ args: {
871
+ groupId: v.id("groups"),
872
+ text: v.string(),
873
+ },
874
+ handler: async (ctx, args) => {
875
+ const { object } = await generateObject({
876
+ model: openai("gpt-4o"),
877
+ schema: z.object({
878
+ entities: z.array(
879
+ z.object({
880
+ name: z.string(),
881
+ type: z.enum(["person", "organization", "location", "event"]),
882
+ description: z.string(),
883
+ })
884
+ ),
885
+ }),
886
+ prompt: `Extract entities from this text: ${args.text}`,
887
+ });
888
+
889
+ // Store entities in ontology
890
+ for (const entity of object.entities) {
891
+ await ctx.runMutation(internal.mutations.entities.create, {
892
+ groupId: args.groupId,
893
+ type: entity.type,
894
+ name: entity.name,
895
+ properties: { description: entity.description },
896
+ });
897
+ }
898
+
899
+ return object.entities;
900
+ },
901
+ });
902
+ ```
903
+
904
+ ---
905
+
906
+ ## Implementation Plan
907
+
908
+ ### Phase 1: Hono HTTP Layer (Week 1)
909
+
910
+ **Goal:** Set up Hono with API key authentication
911
+
912
+ **Tasks:**
913
+ 1. Install Hono: `npm install hono`
914
+ 2. Create `/backend/convex/http.ts` with Hono setup
915
+ 3. Implement API key middleware
916
+ 4. Add rate limiting per group
917
+ 5. Set up CORS and error handling
918
+ 6. Test with curl/Postman
919
+
920
+ **Deliverable:** `/api/health` endpoint returns `{ status: "ok", groupId: "..." }`
921
+
922
+ ### Phase 2: Complete CRUD Operations (Week 2-3)
923
+
924
+ **Goal:** Implement all CRUD endpoints for 6 dimensions
925
+
926
+ **Tasks:**
927
+ 1. Groups endpoints (7 routes)
928
+ 2. People endpoints (6 routes)
929
+ 3. Things endpoints (6 routes)
930
+ 4. Connections endpoints (6 routes)
931
+ 5. Events endpoints (6 routes)
932
+ 6. Knowledge endpoints (6 routes)
933
+
934
+ **Deliverable:** All 37 REST endpoints operational
935
+
936
+ ### Phase 3: AI SDK Integration (Week 4)
937
+
938
+ **Goal:** Integrate AI SDK for RAG and generation
939
+
940
+ **Tasks:**
941
+ 1. Install AI SDK: `npm install ai @ai-sdk/openai`
942
+ 2. Implement RAG pipeline (ingest, chunk, embed, search)
943
+ 3. Add generateText action
944
+ 4. Add streaming support
945
+ 5. Add structured output (extractEntities)
946
+
947
+ **Deliverable:** `/api/ai/generate` and `/api/ai/search` working
948
+
949
+ ### Phase 4: Better Auth Integration (Week 5)
950
+
951
+ **Goal:** Full 6-method authentication
952
+
953
+ **Tasks:**
954
+ 1. Complete email/password auth
955
+ 2. Add OAuth providers (Google, GitHub)
956
+ 3. Add magic links
957
+ 4. Add password reset flow
958
+ 5. Add email verification
959
+ 6. Add 2FA support
960
+ 7. Integrate with ontology (create person entities)
961
+
962
+ **Deliverable:** All 6 auth methods working with group scoping
963
+
964
+ ### Phase 5: Testing & Documentation (Week 6)
965
+
966
+ **Goal:** Production-ready with complete docs
967
+
968
+ **Tasks:**
969
+ 1. Write integration tests (90% coverage)
970
+ 2. Generate OpenAPI spec
971
+ 3. Create API documentation site
972
+ 4. Add example requests/responses
973
+ 5. Performance testing
974
+ 6. Security audit
975
+
976
+ **Deliverable:** Published API docs at `https://api.one.ie/docs`
977
+
978
+ ### Phase 6: Deployment (Week 7)
979
+
980
+ **Goal:** Deploy to production
981
+
982
+ **Tasks:**
983
+ 1. Configure environment variables
984
+ 2. Set up monitoring (Sentry, LogTail)
985
+ 3. Configure rate limits per plan tier
986
+ 4. Deploy to Convex production
987
+ 5. Set up custom domain (`api.one.ie`)
988
+
989
+ **Deliverable:** Production API live at `https://api.one.ie`
990
+
991
+ ---
992
+
993
+ ## API Examples
994
+
995
+ ### Example 1: Create Thing
996
+
997
+ ```bash
998
+ curl -X POST https://api.one.ie/api/things \
999
+ -H "X-API-Key: gsk_abc123..." \
1000
+ -H "Content-Type: application/json" \
1001
+ -d '{
1002
+ "type": "course",
1003
+ "name": "Introduction to AI",
1004
+ "properties": {
1005
+ "description": "Learn AI fundamentals",
1006
+ "duration": "8 weeks",
1007
+ "price": 299
1008
+ }
1009
+ }'
1010
+ ```
1011
+
1012
+ **Response:**
1013
+ ```json
1014
+ {
1015
+ "_id": "jd7x8y9z...",
1016
+ "groupId": "kg1h2i3j...",
1017
+ "type": "course",
1018
+ "name": "Introduction to AI",
1019
+ "properties": {
1020
+ "description": "Learn AI fundamentals",
1021
+ "duration": "8 weeks",
1022
+ "price": 299
1023
+ },
1024
+ "status": "active",
1025
+ "createdAt": 1730000000000,
1026
+ "updatedAt": 1730000000000
1027
+ }
1028
+ ```
1029
+
1030
+ ### Example 2: Search Knowledge (RAG)
1031
+
1032
+ ```bash
1033
+ curl -X POST https://api.one.ie/api/knowledge/search \
1034
+ -H "X-API-Key: gsk_abc123..." \
1035
+ -H "Content-Type: application/json" \
1036
+ -d '{
1037
+ "query": "How do I implement authentication?",
1038
+ "limit": 5
1039
+ }'
1040
+ ```
1041
+
1042
+ **Response:**
1043
+ ```json
1044
+ {
1045
+ "results": [
1046
+ {
1047
+ "_id": "kl4m5n6o...",
1048
+ "text": "Authentication in ONE Platform uses Better Auth...",
1049
+ "score": 0.92,
1050
+ "metadata": {
1051
+ "documentId": "pm7q8r9s...",
1052
+ "chunkIndex": 3
1053
+ }
1054
+ },
1055
+ ...
1056
+ ],
1057
+ "count": 5
1058
+ }
1059
+ ```
1060
+
1061
+ ### Example 3: Generate AI Response
1062
+
1063
+ ```bash
1064
+ curl -X POST https://api.one.ie/api/ai/generate \
1065
+ -H "X-API-Key: gsk_abc123..." \
1066
+ -H "Content-Type: application/json" \
1067
+ -d '{
1068
+ "prompt": "Explain the 6-dimension ontology",
1069
+ "context": true
1070
+ }'
1071
+ ```
1072
+
1073
+ **Response:**
1074
+ ```json
1075
+ {
1076
+ "text": "The 6-dimension ontology consists of Groups, People, Things, Connections, Events, and Knowledge...",
1077
+ "model": "gpt-4o",
1078
+ "tokens": 245,
1079
+ "sources": [
1080
+ { "title": "Ontology Overview", "score": 0.89 }
1081
+ ]
1082
+ }
1083
+ ```
1084
+
1085
+ ### Example 4: List Things with Filters
1086
+
1087
+ ```bash
1088
+ curl "https://api.one.ie/api/things?type=course&status=published&limit=10" \
1089
+ -H "X-API-Key: gsk_abc123..."
1090
+ ```
1091
+
1092
+ **Response:**
1093
+ ```json
1094
+ {
1095
+ "results": [
1096
+ {
1097
+ "_id": "th1i2j3k...",
1098
+ "type": "course",
1099
+ "name": "Advanced TypeScript",
1100
+ "properties": { ... },
1101
+ "status": "published"
1102
+ },
1103
+ ...
1104
+ ],
1105
+ "count": 10,
1106
+ "hasMore": true,
1107
+ "cursor": "ey4Jh5..."
1108
+ }
1109
+ ```
1110
+
1111
+ ---
1112
+
1113
+ ## Related Documentation
1114
+
1115
+ - **`one/knowledge/ontology.md`** - Complete 6-dimension specification
1116
+ - **`one/knowledge/todo.md`** - 100-inference execution template
1117
+ - **`one/things/plans/effect.md`** - Backend-agnostic Effect.ts integration
1118
+ - **`one/things/plans/separate.md`** - Frontend-backend separation
1119
+ - **`CLAUDE.md`** - Development workflow
1120
+
1121
+ ---
1122
+
1123
+ ## External Resources
1124
+
1125
+ - **Hono + Convex:** https://stack.convex.dev/hono-with-convex
1126
+ - **confect (Effect + Convex):** https://github.com/rjdellecese/confect
1127
+ - **AI SDK:** https://sdk.vercel.ai/docs
1128
+ - **Better Auth:** https://better-auth.com/docs
1129
+ - **Convex Docs:** https://docs.convex.dev
1130
+
1131
+ ---
1132
+
1133
+ **Build once. Deploy anywhere. Connect anything. The backend-agnostic 6-dimension ontology powers it all.**