oneie 3.3.6 → 3.4.1

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.
@@ -0,0 +1,1734 @@
1
+ # Codebase Improvement Plan: Full Integration & Accuracy
2
+
3
+ **Status:** Draft
4
+ **Version:** 1.0.0
5
+ **Date:** 2025-10-18
6
+ **Goal:** Achieve complete ontology integration, eliminate gaps, and ensure production-ready accuracy across all 6 dimensions
7
+
8
+ ---
9
+
10
+ ## Executive Summary
11
+
12
+ The ONE platform has a **world-class ontology** (6 dimensions, 66 thing types, 25 connections, 67 events) but **incomplete implementation**. This plan identifies 47 specific improvements across backend, frontend, integration, and operations to achieve 100% ontology coverage and production readiness.
13
+
14
+ **Current State:**
15
+ - ✅ Excellent: Ontology design, schema definition, documentation
16
+ - ⚠️ Partial: Backend mutations/queries, frontend integration, auth linkage
17
+ - ❌ Missing: Effect.ts glue layer, protocol integration, RAG implementation, multi-tenant UI
18
+
19
+ **Target State:**
20
+ - 100% ontology coverage in backend (all 66 thing types, 25 connections, 67 events)
21
+ - Complete Effect.ts glue layer with typed errors and service composition
22
+ - Full multi-tenant frontend with group hierarchy navigation
23
+ - Protocol integration (A2A, ACP, AP2, X402, AG-UI) via metadata
24
+ - Production-grade RAG with knowledge chunking and vector search
25
+ - Automated testing across all dimensions
26
+
27
+ ---
28
+
29
+ ## Part 1: Backend Integration (Convex + Effect.ts)
30
+
31
+ ### 1.1 Missing Backend Mutations/Queries
32
+
33
+ **Problem:** Only `groups` and `connections` have implementations. Missing 64 other thing types.
34
+
35
+ **Impact:** Cannot create/update/delete most entities (courses, tokens, agents, content, etc.)
36
+
37
+ **Solution:** Generate complete CRUD operations for all thing types
38
+
39
+ <details>
40
+ <summary>📋 Click to expand: Missing Backend Operations</summary>
41
+
42
+ **Priority 1 (Core Entities):**
43
+ ```typescript
44
+ // backend/convex/mutations/entities.ts
45
+ export const createCreator = mutation({ ... })
46
+ export const createAiClone = mutation({ ... })
47
+ export const createOrganization = mutation({ ... })
48
+ export const updateCreator = mutation({ ... })
49
+ ```
50
+
51
+ **Priority 2 (Content & Products):**
52
+ ```typescript
53
+ // backend/convex/mutations/content.ts
54
+ export const createBlogPost = mutation({ ... })
55
+ export const createCourse = mutation({ ... })
56
+ export const createLesson = mutation({ ... })
57
+ export const publishContent = mutation({ ... })
58
+ ```
59
+
60
+ **Priority 3 (Tokens & Commerce):**
61
+ ```typescript
62
+ // backend/convex/mutations/tokens.ts
63
+ export const createToken = mutation({ ... })
64
+ export const mintTokens = mutation({ ... })
65
+ export const transferTokens = mutation({ ... })
66
+ ```
67
+
68
+ **Priority 4 (Agents & AI):**
69
+ ```typescript
70
+ // backend/convex/mutations/agents.ts
71
+ export const createStrategyAgent = mutation({ ... })
72
+ export const createMarketingAgent = mutation({ ... })
73
+ export const executeAgent = mutation({ ... })
74
+ ```
75
+
76
+ **Priority 5 (Auth & Session):**
77
+ ```typescript
78
+ // backend/convex/mutations/auth.ts
79
+ export const createSession = mutation({ ... })
80
+ export const createOAuthAccount = mutation({ ... })
81
+ export const create2FA = mutation({ ... })
82
+ ```
83
+
84
+ </details>
85
+
86
+ **Acceptance Criteria:**
87
+ - [ ] All 66 thing types have create/update/archive mutations
88
+ - [ ] All 25 connection types have create/update/delete mutations
89
+ - [ ] All mutations log appropriate events
90
+ - [ ] All mutations enforce groupId scoping
91
+ - [ ] TypeScript strict mode passes with no errors
92
+
93
+ **Effort:** 40 hours (5 days)
94
+
95
+ ---
96
+
97
+ ### 1.2 Effect.ts Glue Layer (100% Coverage Goal)
98
+
99
+ **Problem:** No Effect.ts layer exists. Business logic mixed with Convex mutations.
100
+
101
+ **Impact:** No composability, no typed errors, difficult testing, high coupling
102
+
103
+ **Solution:** Implement complete Effect.ts service layer as documented
104
+
105
+ <details>
106
+ <summary>📋 Click to expand: Effect.ts Architecture</summary>
107
+
108
+ **Service Structure:**
109
+ ```typescript
110
+ // backend/convex/services/entities/creator.service.ts
111
+ import { Effect, Layer } from "effect"
112
+
113
+ export class CreatorService extends Effect.Service<CreatorService>()("CreatorService", {
114
+ effect: Effect.gen(function* () {
115
+ const db = yield* DatabaseService
116
+ const events = yield* EventLogService
117
+
118
+ const create = (input: CreateCreatorInput) =>
119
+ Effect.gen(function* () {
120
+ // 1. Validate input
121
+ yield* validateCreatorInput(input)
122
+
123
+ // 2. Check permissions
124
+ yield* checkGroupOwnership(input.groupId)
125
+
126
+ // 3. Create entity
127
+ const creatorId = yield* db.insert("entities", {
128
+ groupId: input.groupId,
129
+ type: "creator",
130
+ name: input.name,
131
+ properties: input.properties,
132
+ status: "active",
133
+ createdAt: Date.now(),
134
+ updatedAt: Date.now()
135
+ })
136
+
137
+ // 4. Log event
138
+ yield* events.log({
139
+ groupId: input.groupId,
140
+ type: "entity_created",
141
+ actorId: input.actorId,
142
+ targetId: creatorId,
143
+ timestamp: Date.now(),
144
+ metadata: { entityType: "creator" }
145
+ })
146
+
147
+ return creatorId
148
+ }).pipe(
149
+ Effect.mapError(e => new CreatorCreationError(e))
150
+ )
151
+
152
+ return { create, update, archive, get, list } as const
153
+ })
154
+ }) {}
155
+ ```
156
+
157
+ **Error Hierarchy:**
158
+ ```typescript
159
+ // backend/convex/services/errors.ts
160
+ export class EntityError extends Data.TaggedClass("EntityError")<{
161
+ message: string
162
+ entityType: string
163
+ }> {}
164
+
165
+ export class CreatorCreationError extends EntityError {
166
+ readonly _tag = "CreatorCreationError"
167
+ }
168
+
169
+ export class ValidationError extends Data.TaggedClass("ValidationError")<{
170
+ field: string
171
+ reason: string
172
+ }> {}
173
+
174
+ export class PermissionError extends Data.TaggedClass("PermissionError")<{
175
+ userId: string
176
+ groupId: string
177
+ action: string
178
+ }> {}
179
+ ```
180
+
181
+ **Service Composition:**
182
+ ```typescript
183
+ // backend/convex/services/layers.ts
184
+ export const ServicesLayer = Layer.mergeAll(
185
+ DatabaseServiceLive,
186
+ EventLogServiceLive,
187
+ CreatorServiceLive,
188
+ GroupServiceLive,
189
+ ConnectionServiceLive,
190
+ AuthServiceLive
191
+ )
192
+
193
+ // Usage in Convex mutation:
194
+ export const createCreator = mutation({
195
+ args: { ... },
196
+ handler: async (ctx, args) => {
197
+ const program = Effect.gen(function* () {
198
+ const creatorService = yield* CreatorService
199
+ return yield* creatorService.create(args)
200
+ })
201
+
202
+ return await Effect.runPromise(
203
+ program.pipe(Effect.provide(ServicesLayer))
204
+ )
205
+ }
206
+ })
207
+ ```
208
+
209
+ </details>
210
+
211
+ **Acceptance Criteria:**
212
+ - [ ] All 66 thing types have Effect.ts services
213
+ - [ ] All services use tagged errors (no try/catch)
214
+ - [ ] All services compose via Layer.mergeAll
215
+ - [ ] Services have 90%+ test coverage
216
+ - [ ] Mutations are thin wrappers (< 10 lines each)
217
+
218
+ **Effort:** 80 hours (10 days)
219
+
220
+ ---
221
+
222
+ ### 1.3 Event Logging Completeness
223
+
224
+ **Problem:** Events are only logged in `groups.ts`. Missing from all other operations.
225
+
226
+ **Impact:** No audit trail, no analytics, no real-time updates
227
+
228
+ **Solution:** Implement comprehensive event logging service
229
+
230
+ <details>
231
+ <summary>📋 Click to expand: Event Logging Strategy</summary>
232
+
233
+ **EventLogService:**
234
+ ```typescript
235
+ // backend/convex/services/events/event-log.service.ts
236
+ export class EventLogService extends Effect.Service<EventLogService>()("EventLogService", {
237
+ effect: Effect.gen(function* () {
238
+ const db = yield* DatabaseService
239
+
240
+ const log = (event: EventInput) =>
241
+ Effect.gen(function* () {
242
+ // Validate event structure
243
+ yield* validateEvent(event)
244
+
245
+ // Insert event
246
+ const eventId = yield* db.insert("events", {
247
+ groupId: event.groupId,
248
+ type: event.type,
249
+ actorId: event.actorId,
250
+ targetId: event.targetId,
251
+ timestamp: event.timestamp,
252
+ metadata: event.metadata
253
+ })
254
+
255
+ // Trigger real-time subscriptions (Convex handles this)
256
+ return eventId
257
+ })
258
+
259
+ const query = (filters: EventFilters) =>
260
+ Effect.gen(function* () {
261
+ const events = yield* db.query("events")
262
+ .withIndex("group_type", q =>
263
+ q.eq("groupId", filters.groupId)
264
+ .eq("type", filters.type)
265
+ )
266
+ .collect()
267
+
268
+ return events
269
+ })
270
+
271
+ return { log, query, getByActor, getByTarget } as const
272
+ })
273
+ }) {}
274
+ ```
275
+
276
+ **Automatic Event Logging:**
277
+ ```typescript
278
+ // Wrap every mutation with event logging
279
+ const withEventLogging = <T>(
280
+ operation: Effect.Effect<T, any, any>,
281
+ eventType: EventType,
282
+ metadata?: Record<string, any>
283
+ ) =>
284
+ Effect.gen(function* () {
285
+ const result = yield* operation
286
+ const events = yield* EventLogService
287
+
288
+ yield* events.log({
289
+ type: eventType,
290
+ actorId: metadata.actorId,
291
+ targetId: result,
292
+ timestamp: Date.now(),
293
+ metadata
294
+ })
295
+
296
+ return result
297
+ })
298
+ ```
299
+
300
+ **Coverage Matrix:**
301
+ ```typescript
302
+ // Ensure every mutation logs the right event
303
+ const EVENT_COVERAGE = {
304
+ // Entity lifecycle
305
+ "entities.create": "entity_created",
306
+ "entities.update": "entity_updated",
307
+ "entities.archive": "entity_archived",
308
+
309
+ // User events
310
+ "auth.register": "user_registered",
311
+ "auth.login": "user_login",
312
+ "auth.verify": "email_verified",
313
+
314
+ // Group events
315
+ "groups.create": "group_created",
316
+ "groups.invite": "user_invited_to_group",
317
+
318
+ // Token events
319
+ "tokens.mint": "token_minted",
320
+ "tokens.transfer": "tokens_transferred",
321
+
322
+ // ... (67 total event types)
323
+ }
324
+ ```
325
+
326
+ </details>
327
+
328
+ **Acceptance Criteria:**
329
+ - [ ] All 67 event types are logged automatically
330
+ - [ ] EventLogService uses Effect.ts with typed errors
331
+ - [ ] Events include proper groupId scoping
332
+ - [ ] Event metadata follows ontology spec
333
+ - [ ] Real-time event streaming works in frontend
334
+
335
+ **Effort:** 24 hours (3 days)
336
+
337
+ ---
338
+
339
+ ### 1.4 Connection Management
340
+
341
+ **Problem:** Basic connection CRUD exists but lacks relationship-specific logic
342
+
343
+ **Impact:** Cannot enforce connection rules (e.g., revenue splits, token balances)
344
+
345
+ **Solution:** Implement connection services with business rules
346
+
347
+ <details>
348
+ <summary>📋 Click to expand: Connection Services</summary>
349
+
350
+ **Ownership Connections:**
351
+ ```typescript
352
+ // backend/convex/services/connections/ownership.service.ts
353
+ export const createOwnership = (input: OwnershipInput) =>
354
+ Effect.gen(function* () {
355
+ const connections = yield* ConnectionService
356
+
357
+ // Validate ownership rules
358
+ if (input.metadata?.revenueShare) {
359
+ yield* validateRevenueShare(input.metadata.revenueShare)
360
+ }
361
+
362
+ // Create connection
363
+ return yield* connections.create({
364
+ fromEntityId: input.ownerId,
365
+ toEntityId: input.ownedEntityId,
366
+ relationshipType: "owns",
367
+ metadata: input.metadata
368
+ })
369
+ })
370
+ ```
371
+
372
+ **Token Holdings:**
373
+ ```typescript
374
+ // backend/convex/services/connections/token-holdings.service.ts
375
+ export const updateTokenBalance = (input: TokenBalanceInput) =>
376
+ Effect.gen(function* () {
377
+ const connections = yield* ConnectionService
378
+
379
+ // Get existing holding connection
380
+ const existing = yield* connections.getByType({
381
+ fromEntityId: input.userId,
382
+ toEntityId: input.tokenId,
383
+ relationshipType: "holds_tokens"
384
+ })
385
+
386
+ if (existing) {
387
+ // Update balance
388
+ yield* connections.update({
389
+ connectionId: existing._id,
390
+ metadata: {
391
+ ...existing.metadata,
392
+ balance: input.newBalance
393
+ }
394
+ })
395
+ } else {
396
+ // Create new holding
397
+ yield* connections.create({
398
+ fromEntityId: input.userId,
399
+ toEntityId: input.tokenId,
400
+ relationshipType: "holds_tokens",
401
+ metadata: { balance: input.newBalance }
402
+ })
403
+ }
404
+ })
405
+ ```
406
+
407
+ **Group Membership with Roles:**
408
+ ```typescript
409
+ // backend/convex/services/connections/membership.service.ts
410
+ export const addGroupMember = (input: MembershipInput) =>
411
+ Effect.gen(function* () {
412
+ const connections = yield* ConnectionService
413
+ const events = yield* EventLogService
414
+
415
+ // Validate role
416
+ yield* validateGroupRole(input.role)
417
+
418
+ // Check if already member
419
+ const existing = yield* connections.getByType({
420
+ fromEntityId: input.userId,
421
+ toEntityId: input.groupId,
422
+ relationshipType: "member_of"
423
+ })
424
+
425
+ if (existing) {
426
+ return yield* new MembershipError({ message: "Already a member" })
427
+ }
428
+
429
+ // Create membership connection
430
+ const connectionId = yield* connections.create({
431
+ fromEntityId: input.userId,
432
+ toEntityId: input.groupId,
433
+ relationshipType: "member_of",
434
+ metadata: {
435
+ role: input.role,
436
+ invitedBy: input.inviterId,
437
+ joinedAt: Date.now()
438
+ }
439
+ })
440
+
441
+ // Log event
442
+ yield* events.log({
443
+ groupId: input.groupId,
444
+ type: "user_joined_group",
445
+ actorId: input.userId,
446
+ targetId: input.groupId,
447
+ timestamp: Date.now(),
448
+ metadata: { role: input.role }
449
+ })
450
+
451
+ return connectionId
452
+ })
453
+ ```
454
+
455
+ </details>
456
+
457
+ **Acceptance Criteria:**
458
+ - [ ] All 25 connection types have specialized services
459
+ - [ ] Connection rules are enforced (revenue shares, balances, etc.)
460
+ - [ ] Bidirectional queries work (fromEntity and toEntity)
461
+ - [ ] Connection metadata follows ontology spec
462
+ - [ ] All connection operations log events
463
+
464
+ **Effort:** 32 hours (4 days)
465
+
466
+ ---
467
+
468
+ ### 1.5 Knowledge & RAG Implementation
469
+
470
+ **Problem:** Knowledge table exists but RAG ingestion pipeline is missing
471
+
472
+ **Impact:** Cannot use vector search, no AI-powered features
473
+
474
+ **Solution:** Implement complete RAG pipeline as documented in ontology
475
+
476
+ <details>
477
+ <summary>📋 Click to expand: RAG Implementation</summary>
478
+
479
+ **Chunking Service:**
480
+ ```typescript
481
+ // backend/convex/services/knowledge/chunking.service.ts
482
+ export class ChunkingService extends Effect.Service<ChunkingService>()("ChunkingService", {
483
+ effect: Effect.gen(function* () {
484
+ const chunk = (text: string, options: ChunkOptions) =>
485
+ Effect.gen(function* () {
486
+ const windowSize = options.windowSize || 800
487
+ const overlap = options.overlap || 200
488
+
489
+ // Smart sentence-aware chunking
490
+ const sentences = text.split(/[.!?]+/)
491
+ const chunks: Chunk[] = []
492
+ let currentChunk = ""
493
+ let tokenCount = 0
494
+
495
+ for (const sentence of sentences) {
496
+ const sentenceTokens = estimateTokens(sentence)
497
+
498
+ if (tokenCount + sentenceTokens > windowSize && currentChunk.length > 0) {
499
+ chunks.push({
500
+ text: currentChunk.trim(),
501
+ tokenCount,
502
+ index: chunks.length
503
+ })
504
+
505
+ // Keep overlap for context
506
+ const overlapText = currentChunk.slice(-overlap)
507
+ currentChunk = overlapText + sentence
508
+ tokenCount = estimateTokens(currentChunk)
509
+ } else {
510
+ currentChunk += sentence
511
+ tokenCount += sentenceTokens
512
+ }
513
+ }
514
+
515
+ // Add final chunk
516
+ if (currentChunk.length > 0) {
517
+ chunks.push({
518
+ text: currentChunk.trim(),
519
+ tokenCount,
520
+ index: chunks.length
521
+ })
522
+ }
523
+
524
+ return chunks
525
+ })
526
+
527
+ return { chunk } as const
528
+ })
529
+ }) {}
530
+ ```
531
+
532
+ **Embedding Service:**
533
+ ```typescript
534
+ // backend/convex/services/knowledge/embedding.service.ts
535
+ export class EmbeddingService extends Effect.Service<EmbeddingService>()("EmbeddingService", {
536
+ effect: Effect.gen(function* () {
537
+ const config = yield* ConfigService
538
+
539
+ const embed = (text: string) =>
540
+ Effect.gen(function* () {
541
+ const model = config.embeddingModel || "text-embedding-3-large"
542
+
543
+ // Call OpenAI API
544
+ const response = yield* Effect.tryPromise({
545
+ try: () => fetch("https://api.openai.com/v1/embeddings", {
546
+ method: "POST",
547
+ headers: {
548
+ "Authorization": `Bearer ${config.openaiApiKey}`,
549
+ "Content-Type": "application/json"
550
+ },
551
+ body: JSON.stringify({ model, input: text })
552
+ }),
553
+ catch: (e) => new EmbeddingError({ message: String(e) })
554
+ })
555
+
556
+ const data = yield* Effect.tryPromise({
557
+ try: () => response.json(),
558
+ catch: (e) => new EmbeddingError({ message: String(e) })
559
+ })
560
+
561
+ return {
562
+ embedding: data.data[0].embedding,
563
+ model,
564
+ dim: data.data[0].embedding.length
565
+ }
566
+ })
567
+
568
+ return { embed, embedBatch } as const
569
+ })
570
+ }) {}
571
+ ```
572
+
573
+ **RAG Ingestion Pipeline:**
574
+ ```typescript
575
+ // backend/convex/services/knowledge/rag-ingestion.service.ts
576
+ export const ingestThing = (thingId: string, fields?: string[]) =>
577
+ Effect.gen(function* () {
578
+ const entities = yield* EntityService
579
+ const chunking = yield* ChunkingService
580
+ const embedding = yield* EmbeddingService
581
+ const knowledge = yield* KnowledgeService
582
+
583
+ // 1. Get thing
584
+ const thing = yield* entities.get(thingId)
585
+
586
+ // 2. Extract text from specified fields
587
+ const texts = yield* extractTexts(thing, fields)
588
+
589
+ // 3. Chunk each text
590
+ const allChunks = []
591
+ for (const { field, text, labels } of texts) {
592
+ const chunks = yield* chunking.chunk(text, {
593
+ windowSize: 800,
594
+ overlap: 200
595
+ })
596
+
597
+ allChunks.push(...chunks.map(c => ({ ...c, field, labels })))
598
+ }
599
+
600
+ // 4. Embed chunks (batch for efficiency)
601
+ const embeddings = yield* embedding.embedBatch(
602
+ allChunks.map(c => c.text)
603
+ )
604
+
605
+ // 5. Store knowledge items
606
+ for (let i = 0; i < allChunks.length; i++) {
607
+ const chunk = allChunks[i]
608
+ const { embedding: vector, model, dim } = embeddings[i]
609
+
610
+ const knowledgeId = yield* knowledge.create({
611
+ groupId: thing.groupId,
612
+ knowledgeType: "chunk",
613
+ text: chunk.text,
614
+ embedding: vector,
615
+ embeddingModel: model,
616
+ embeddingDim: dim,
617
+ sourceThingId: thingId,
618
+ sourceField: chunk.field,
619
+ chunk: {
620
+ index: chunk.index,
621
+ tokenCount: chunk.tokenCount,
622
+ overlap: 200
623
+ },
624
+ labels: chunk.labels
625
+ })
626
+
627
+ // 6. Link to thing via junction table
628
+ yield* knowledge.linkToThing({
629
+ thingId,
630
+ knowledgeId,
631
+ role: "chunk_of"
632
+ })
633
+ }
634
+
635
+ return allChunks.length
636
+ })
637
+ ```
638
+
639
+ **Vector Search:**
640
+ ```typescript
641
+ // backend/convex/services/knowledge/vector-search.service.ts
642
+ export const search = (query: string, options: SearchOptions) =>
643
+ Effect.gen(function* () {
644
+ const embedding = yield* EmbeddingService
645
+ const knowledge = yield* KnowledgeService
646
+
647
+ // 1. Embed query
648
+ const { embedding: queryVector } = yield* embedding.embed(query)
649
+
650
+ // 2. Vector search (use Convex vector search when available)
651
+ const results = yield* knowledge.vectorSearch({
652
+ vectorField: "embedding",
653
+ query: queryVector,
654
+ filter: {
655
+ groupId: options.groupId,
656
+ knowledgeType: "chunk"
657
+ },
658
+ k: options.k || 10
659
+ })
660
+
661
+ // 3. Hybrid scoring with lexical signals
662
+ const scored = results.map(r => ({
663
+ ...r,
664
+ hybridScore: r.similarity * 0.7 + lexicalScore(query, r.text) * 0.3
665
+ }))
666
+
667
+ return scored.sort((a, b) => b.hybridScore - a.hybridScore)
668
+ })
669
+ ```
670
+
671
+ </details>
672
+
673
+ **Acceptance Criteria:**
674
+ - [ ] Chunking service handles 800-token windows with 200-token overlap
675
+ - [ ] Embedding service integrates with OpenAI API
676
+ - [ ] RAG ingestion pipeline processes all content types
677
+ - [ ] Vector search returns relevant chunks with hybrid scoring
678
+ - [ ] Knowledge labels work for taxonomy/categorization
679
+ - [ ] Junction table (thingKnowledge) links chunks to entities
680
+
681
+ **Effort:** 60 hours (7.5 days)
682
+
683
+ ---
684
+
685
+ ## Part 2: Frontend Integration (Astro + React)
686
+
687
+ ### 2.1 Multi-Tenant Dashboard
688
+
689
+ **Problem:** No group-scoped UI. No hierarchy navigation.
690
+
691
+ **Impact:** Cannot manage nested groups or visualize ontology
692
+
693
+ **Solution:** Build complete multi-tenant dashboard
694
+
695
+ <details>
696
+ <summary>📋 Click to expand: Dashboard Components</summary>
697
+
698
+ **Group Selector:**
699
+ ```tsx
700
+ // web/src/components/groups/GroupSelector.tsx
701
+ export function GroupSelector() {
702
+ const currentGroup = useQuery(api.queries.groups.getById, {
703
+ groupId: useGroupId()
704
+ })
705
+ const hierarchy = useQuery(api.queries.groups.getHierarchy, {
706
+ rootGroupId: currentGroup?._id
707
+ })
708
+
709
+ return (
710
+ <Select value={currentGroup?._id} onValueChange={switchGroup}>
711
+ <SelectTrigger>
712
+ <SelectValue>
713
+ {currentGroup?.name} ({currentGroup?.type})
714
+ </SelectValue>
715
+ </SelectTrigger>
716
+ <SelectContent>
717
+ {hierarchy?.map(group => (
718
+ <SelectItem key={group._id} value={group._id}>
719
+ {" ".repeat(group.depth)}{group.name}
720
+ </SelectItem>
721
+ ))}
722
+ </SelectContent>
723
+ </Select>
724
+ )
725
+ }
726
+ ```
727
+
728
+ **Ontology Browser:**
729
+ ```tsx
730
+ // web/src/components/ontology/OntologyBrowser.tsx
731
+ export function OntologyBrowser({ groupId }: { groupId: string }) {
732
+ const [dimension, setDimension] = useState<Dimension>("things")
733
+
734
+ return (
735
+ <div className="grid grid-cols-[250px_1fr]">
736
+ {/* Sidebar: 6 Dimensions */}
737
+ <aside>
738
+ <nav>
739
+ <button onClick={() => setDimension("groups")}>
740
+ 1. Groups
741
+ </button>
742
+ <button onClick={() => setDimension("people")}>
743
+ 2. People
744
+ </button>
745
+ <button onClick={() => setDimension("things")}>
746
+ 3. Things
747
+ </button>
748
+ <button onClick={() => setDimension("connections")}>
749
+ 4. Connections
750
+ </button>
751
+ <button onClick={() => setDimension("events")}>
752
+ 5. Events
753
+ </button>
754
+ <button onClick={() => setDimension("knowledge")}>
755
+ 6. Knowledge
756
+ </button>
757
+ </nav>
758
+ </aside>
759
+
760
+ {/* Main: Dimension Content */}
761
+ <main>
762
+ {dimension === "things" && <ThingsView groupId={groupId} />}
763
+ {dimension === "connections" && <ConnectionsView groupId={groupId} />}
764
+ {dimension === "events" && <EventsView groupId={groupId} />}
765
+ {/* ... */}
766
+ </main>
767
+ </div>
768
+ )
769
+ }
770
+ ```
771
+
772
+ **Real-Time Stats:**
773
+ ```tsx
774
+ // web/src/components/dashboard/DashboardStats.tsx
775
+ export function DashboardStats({ groupId }: { groupId: string }) {
776
+ const stats = useQuery(api.queries.groups.getStats, {
777
+ groupId,
778
+ includeSubgroups: true
779
+ })
780
+
781
+ return (
782
+ <div className="grid grid-cols-4 gap-4">
783
+ <StatsCard
784
+ title="Members"
785
+ value={stats?.stats.members}
786
+ icon={Users}
787
+ />
788
+ <StatsCard
789
+ title="Entities"
790
+ value={stats?.stats.entities}
791
+ icon={Box}
792
+ />
793
+ <StatsCard
794
+ title="Connections"
795
+ value={stats?.stats.connections}
796
+ icon={Link}
797
+ />
798
+ <StatsCard
799
+ title="Events"
800
+ value={stats?.stats.events}
801
+ icon={Activity}
802
+ />
803
+ </div>
804
+ )
805
+ }
806
+ ```
807
+
808
+ </details>
809
+
810
+ **Acceptance Criteria:**
811
+ - [ ] Group selector shows full hierarchy with nesting
812
+ - [ ] Dashboard scopes all data to selected group
813
+ - [ ] Real-time stats update via Convex subscriptions
814
+ - [ ] Ontology browser shows all 6 dimensions
815
+ - [ ] Role-based access control works (group_owner vs group_user)
816
+
817
+ **Effort:** 40 hours (5 days)
818
+
819
+ ---
820
+
821
+ ### 2.2 Entity Management UI
822
+
823
+ **Problem:** No UI to create/edit/view entities by type
824
+
825
+ **Impact:** Cannot test ontology, no user-facing features
826
+
827
+ **Solution:** Build type-specific entity forms and views
828
+
829
+ <details>
830
+ <summary>📋 Click to expand: Entity UI Components</summary>
831
+
832
+ **Generic Entity Form:**
833
+ ```tsx
834
+ // web/src/components/entities/EntityForm.tsx
835
+ export function EntityForm({
836
+ type,
837
+ groupId,
838
+ initialData
839
+ }: EntityFormProps) {
840
+ const createEntity = useMutation(api.mutations.entities.create)
841
+ const schema = getSchemaForType(type)
842
+
843
+ return (
844
+ <Form schema={schema} onSubmit={handleSubmit}>
845
+ <FormField name="name" label="Name" />
846
+
847
+ {/* Type-specific fields */}
848
+ {type === "creator" && (
849
+ <>
850
+ <FormField name="email" label="Email" />
851
+ <FormField name="bio" label="Bio" type="textarea" />
852
+ <FormField name="niche" label="Niche" type="tags" />
853
+ </>
854
+ )}
855
+
856
+ {type === "course" && (
857
+ <>
858
+ <FormField name="title" label="Title" />
859
+ <FormField name="price" label="Price" type="number" />
860
+ <FormField name="duration" label="Duration (hrs)" />
861
+ </>
862
+ )}
863
+
864
+ <Button type="submit">Create {type}</Button>
865
+ </Form>
866
+ )
867
+ }
868
+ ```
869
+
870
+ **Entity List View:**
871
+ ```tsx
872
+ // web/src/components/entities/EntityList.tsx
873
+ export function EntityList({
874
+ groupId,
875
+ type
876
+ }: EntityListProps) {
877
+ const entities = useQuery(api.queries.entities.list, {
878
+ groupId,
879
+ type
880
+ })
881
+
882
+ return (
883
+ <Table>
884
+ <TableHeader>
885
+ <TableRow>
886
+ <TableHead>Name</TableHead>
887
+ <TableHead>Type</TableHead>
888
+ <TableHead>Status</TableHead>
889
+ <TableHead>Created</TableHead>
890
+ <TableHead>Actions</TableHead>
891
+ </TableRow>
892
+ </TableHeader>
893
+ <TableBody>
894
+ {entities?.map(entity => (
895
+ <TableRow key={entity._id}>
896
+ <TableCell>{entity.name}</TableCell>
897
+ <TableCell>
898
+ <Badge>{entity.type}</Badge>
899
+ </TableCell>
900
+ <TableCell>
901
+ <StatusBadge status={entity.status} />
902
+ </TableCell>
903
+ <TableCell>
904
+ {formatDate(entity.createdAt)}
905
+ </TableCell>
906
+ <TableCell>
907
+ <EntityActions entity={entity} />
908
+ </TableCell>
909
+ </TableRow>
910
+ ))}
911
+ </TableBody>
912
+ </Table>
913
+ )
914
+ }
915
+ ```
916
+
917
+ </details>
918
+
919
+ **Acceptance Criteria:**
920
+ - [ ] Entity forms for all 66 thing types
921
+ - [ ] Type-specific property editors (JSON + structured)
922
+ - [ ] Entity list views with filtering and sorting
923
+ - [ ] Entity detail pages with connections and events
924
+ - [ ] Real-time updates when entities change
925
+
926
+ **Effort:** 60 hours (7.5 days)
927
+
928
+ ---
929
+
930
+ ### 2.3 Connection Visualization
931
+
932
+ **Problem:** No way to see relationships between entities
933
+
934
+ **Impact:** Cannot understand data structure, no graph views
935
+
936
+ **Solution:** Build connection graph and relationship explorer
937
+
938
+ <details>
939
+ <summary>📋 Click to expand: Connection Visualization</summary>
940
+
941
+ **Graph View:**
942
+ ```tsx
943
+ // web/src/components/connections/ConnectionGraph.tsx
944
+ import ReactFlow from 'reactflow'
945
+
946
+ export function ConnectionGraph({ groupId }: { groupId: string }) {
947
+ const connections = useQuery(api.queries.connections.list, { groupId })
948
+ const entities = useQuery(api.queries.entities.list, { groupId })
949
+
950
+ const nodes = entities?.map(e => ({
951
+ id: e._id,
952
+ type: 'entity',
953
+ data: { label: e.name, type: e.type },
954
+ position: calculatePosition(e) // Use force-directed layout
955
+ }))
956
+
957
+ const edges = connections?.map(c => ({
958
+ id: c._id,
959
+ source: c.fromEntityId,
960
+ target: c.toEntityId,
961
+ label: c.relationshipType,
962
+ type: 'smoothstep'
963
+ }))
964
+
965
+ return (
966
+ <ReactFlow
967
+ nodes={nodes}
968
+ edges={edges}
969
+ fitView
970
+ >
971
+ <Controls />
972
+ <Background />
973
+ </ReactFlow>
974
+ )
975
+ }
976
+ ```
977
+
978
+ **Relationship Explorer:**
979
+ ```tsx
980
+ // web/src/components/connections/RelationshipExplorer.tsx
981
+ export function RelationshipExplorer({ entityId }: { entityId: string }) {
982
+ const entity = useQuery(api.queries.entities.get, { entityId })
983
+ const outgoing = useQuery(api.queries.connections.getOutgoing, { entityId })
984
+ const incoming = useQuery(api.queries.connections.getIncoming, { entityId })
985
+
986
+ return (
987
+ <div>
988
+ <h2>{entity?.name} Relationships</h2>
989
+
990
+ <section>
991
+ <h3>Outgoing ({outgoing?.length})</h3>
992
+ {outgoing?.map(conn => (
993
+ <RelationshipCard
994
+ key={conn._id}
995
+ type={conn.relationshipType}
996
+ target={conn.toEntityId}
997
+ metadata={conn.metadata}
998
+ />
999
+ ))}
1000
+ </section>
1001
+
1002
+ <section>
1003
+ <h3>Incoming ({incoming?.length})</h3>
1004
+ {incoming?.map(conn => (
1005
+ <RelationshipCard
1006
+ key={conn._id}
1007
+ type={conn.relationshipType}
1008
+ source={conn.fromEntityId}
1009
+ metadata={conn.metadata}
1010
+ />
1011
+ ))}
1012
+ </section>
1013
+ </div>
1014
+ )
1015
+ }
1016
+ ```
1017
+
1018
+ </details>
1019
+
1020
+ **Acceptance Criteria:**
1021
+ - [ ] Interactive graph view with zoom/pan
1022
+ - [ ] Filter connections by relationship type
1023
+ - [ ] Click entity to see details
1024
+ - [ ] Show connection metadata on hover
1025
+ - [ ] Export graph as image/JSON
1026
+
1027
+ **Effort:** 32 hours (4 days)
1028
+
1029
+ ---
1030
+
1031
+ ### 2.4 Event Timeline
1032
+
1033
+ **Problem:** No UI to view event history
1034
+
1035
+ **Impact:** Cannot see audit trail or debug issues
1036
+
1037
+ **Solution:** Build real-time event timeline
1038
+
1039
+ <details>
1040
+ <summary>📋 Click to expand: Event Timeline</summary>
1041
+
1042
+ ```tsx
1043
+ // web/src/components/events/EventTimeline.tsx
1044
+ export function EventTimeline({ groupId }: { groupId: string }) {
1045
+ const events = useQuery(api.queries.events.getRecent, {
1046
+ groupId,
1047
+ limit: 100
1048
+ })
1049
+
1050
+ return (
1051
+ <div className="space-y-4">
1052
+ {events?.map(event => (
1053
+ <EventCard
1054
+ key={event._id}
1055
+ type={event.type}
1056
+ actor={event.actorId}
1057
+ target={event.targetId}
1058
+ timestamp={event.timestamp}
1059
+ metadata={event.metadata}
1060
+ />
1061
+ ))}
1062
+ </div>
1063
+ )
1064
+ }
1065
+
1066
+ function EventCard({ type, actor, target, timestamp, metadata }: EventCardProps) {
1067
+ const actorEntity = useQuery(api.queries.entities.get, { entityId: actor })
1068
+ const targetEntity = useQuery(api.queries.entities.get, { entityId: target })
1069
+
1070
+ return (
1071
+ <Card>
1072
+ <CardHeader>
1073
+ <div className="flex items-center gap-2">
1074
+ <EventIcon type={type} />
1075
+ <CardTitle>{formatEventType(type)}</CardTitle>
1076
+ <Badge variant="outline">{formatTimeAgo(timestamp)}</Badge>
1077
+ </div>
1078
+ </CardHeader>
1079
+ <CardContent>
1080
+ <p>
1081
+ <EntityLink entity={actorEntity} /> {getEventVerb(type)} <EntityLink entity={targetEntity} />
1082
+ </p>
1083
+ {metadata && (
1084
+ <pre className="text-xs mt-2">
1085
+ {JSON.stringify(metadata, null, 2)}
1086
+ </pre>
1087
+ )}
1088
+ </CardContent>
1089
+ </Card>
1090
+ )
1091
+ }
1092
+ ```
1093
+
1094
+ </details>
1095
+
1096
+ **Acceptance Criteria:**
1097
+ - [ ] Real-time event stream (Convex subscription)
1098
+ - [ ] Filter by event type, actor, target
1099
+ - [ ] Group events by time period (hour, day, week)
1100
+ - [ ] Click event to see full details
1101
+ - [ ] Export events as CSV/JSON
1102
+
1103
+ **Effort:** 24 hours (3 days)
1104
+
1105
+ ---
1106
+
1107
+ ## Part 3: Protocol Integration
1108
+
1109
+ ### 3.1 Protocol Metadata Standards
1110
+
1111
+ **Problem:** Protocol identity via `metadata.protocol` is documented but not enforced
1112
+
1113
+ **Impact:** Inconsistent metadata structure across protocols
1114
+
1115
+ **Solution:** Define TypeScript schemas for each protocol
1116
+
1117
+ <details>
1118
+ <summary>📋 Click to expand: Protocol Schemas</summary>
1119
+
1120
+ ```typescript
1121
+ // backend/convex/types/protocols.ts
1122
+
1123
+ // Base protocol metadata
1124
+ export interface ProtocolMetadata {
1125
+ protocol: "a2a" | "acp" | "ap2" | "x402" | "ag-ui"
1126
+ }
1127
+
1128
+ // A2A: Agent-to-Agent Communication
1129
+ export interface A2AMetadata extends ProtocolMetadata {
1130
+ protocol: "a2a"
1131
+ messageType: "task_delegation" | "status_update" | "result"
1132
+ agentPlatform: "elizaos" | "autogen" | "crewai" | "custom"
1133
+ taskId?: string
1134
+ conversationId?: string
1135
+ }
1136
+
1137
+ // ACP: Agentic Commerce Protocol
1138
+ export interface ACPMetadata extends ProtocolMetadata {
1139
+ protocol: "acp"
1140
+ eventType: "purchase_initiated" | "merchant_approved" | "transaction_completed"
1141
+ agentPlatform: "chatgpt" | "claude" | "gemini" | "custom"
1142
+ productId: string
1143
+ amount: number
1144
+ currency: string
1145
+ }
1146
+
1147
+ // AP2: Agent Payments Protocol
1148
+ export interface AP2Metadata extends ProtocolMetadata {
1149
+ protocol: "ap2"
1150
+ mandateType: "intent" | "cart"
1151
+ autoExecute: boolean
1152
+ maxBudget?: number
1153
+ criteria?: Record<string, any>
1154
+ }
1155
+
1156
+ // X402: HTTP Micropayments
1157
+ export interface X402Metadata extends ProtocolMetadata {
1158
+ protocol: "x402"
1159
+ scheme: "permit" | "invoice"
1160
+ network: "base" | "ethereum" | "polygon"
1161
+ txHash?: string
1162
+ amount: string
1163
+ resource: string
1164
+ }
1165
+
1166
+ // AG-UI: Generative UI (CopilotKit)
1167
+ export interface AGUIMetadata extends ProtocolMetadata {
1168
+ protocol: "ag-ui"
1169
+ messageType: "text" | "ui" | "action"
1170
+ component?: string
1171
+ props?: Record<string, any>
1172
+ }
1173
+
1174
+ // Union type for all protocols
1175
+ export type AnyProtocolMetadata =
1176
+ | A2AMetadata
1177
+ | ACPMetadata
1178
+ | AP2Metadata
1179
+ | X402Metadata
1180
+ | AGUIMetadata
1181
+
1182
+ // Validation function
1183
+ export const validateProtocolMetadata = (metadata: any): metadata is AnyProtocolMetadata => {
1184
+ if (!metadata.protocol) return false
1185
+
1186
+ switch (metadata.protocol) {
1187
+ case "a2a":
1188
+ return !!metadata.messageType && !!metadata.agentPlatform
1189
+ case "acp":
1190
+ return !!metadata.eventType && !!metadata.productId
1191
+ case "ap2":
1192
+ return !!metadata.mandateType
1193
+ case "x402":
1194
+ return !!metadata.scheme && !!metadata.network
1195
+ case "ag-ui":
1196
+ return !!metadata.messageType
1197
+ default:
1198
+ return false
1199
+ }
1200
+ }
1201
+ ```
1202
+
1203
+ </details>
1204
+
1205
+ **Acceptance Criteria:**
1206
+ - [ ] TypeScript schemas for all 5 protocols
1207
+ - [ ] Validation functions enforce schema compliance
1208
+ - [ ] Backend mutations reject invalid protocol metadata
1209
+ - [ ] Frontend forms guide users to correct structure
1210
+ - [ ] Documentation updated with examples
1211
+
1212
+ **Effort:** 16 hours (2 days)
1213
+
1214
+ ---
1215
+
1216
+ ### 3.2 Cross-Protocol Analytics
1217
+
1218
+ **Problem:** Cannot analyze usage across protocols
1219
+
1220
+ **Impact:** No visibility into protocol adoption or revenue
1221
+
1222
+ **Solution:** Build protocol analytics dashboard
1223
+
1224
+ <details>
1225
+ <summary>📋 Click to expand: Protocol Analytics</summary>
1226
+
1227
+ ```tsx
1228
+ // web/src/components/analytics/ProtocolDashboard.tsx
1229
+ export function ProtocolDashboard({ groupId }: { groupId: string }) {
1230
+ const analytics = useQuery(api.queries.analytics.getProtocolStats, { groupId })
1231
+
1232
+ return (
1233
+ <div className="grid grid-cols-2 gap-6">
1234
+ {/* Revenue by Protocol */}
1235
+ <Card>
1236
+ <CardHeader>
1237
+ <CardTitle>Revenue by Protocol</CardTitle>
1238
+ </CardHeader>
1239
+ <CardContent>
1240
+ <BarChart data={analytics?.revenueByProtocol} />
1241
+ </CardContent>
1242
+ </Card>
1243
+
1244
+ {/* Transaction Volume */}
1245
+ <Card>
1246
+ <CardHeader>
1247
+ <CardTitle>Transaction Volume</CardTitle>
1248
+ </CardHeader>
1249
+ <CardContent>
1250
+ <LineChart data={analytics?.volumeOverTime} />
1251
+ </CardContent>
1252
+ </Card>
1253
+
1254
+ {/* Protocol Breakdown */}
1255
+ <Card>
1256
+ <CardHeader>
1257
+ <CardTitle>Protocol Usage</CardTitle>
1258
+ </CardHeader>
1259
+ <CardContent>
1260
+ <PieChart data={analytics?.usageByProtocol} />
1261
+ </CardContent>
1262
+ </Card>
1263
+
1264
+ {/* Top Performers */}
1265
+ <Card>
1266
+ <CardHeader>
1267
+ <CardTitle>Top Revenue Generators</CardTitle>
1268
+ </CardHeader>
1269
+ <CardContent>
1270
+ <Table>
1271
+ <TableBody>
1272
+ {analytics?.topEntities.map(entity => (
1273
+ <TableRow key={entity._id}>
1274
+ <TableCell>{entity.name}</TableCell>
1275
+ <TableCell>${entity.revenue}</TableCell>
1276
+ </TableRow>
1277
+ ))}
1278
+ </TableBody>
1279
+ </Table>
1280
+ </CardContent>
1281
+ </Card>
1282
+ </div>
1283
+ )
1284
+ }
1285
+ ```
1286
+
1287
+ **Backend Query:**
1288
+ ```typescript
1289
+ // backend/convex/queries/analytics.ts
1290
+ export const getProtocolStats = query({
1291
+ args: { groupId: v.id("groups") },
1292
+ handler: async (ctx, { groupId }) => {
1293
+ // Get all payment events
1294
+ const paymentEvents = await ctx.db
1295
+ .query("events")
1296
+ .withIndex("group_type", q =>
1297
+ q.eq("groupId", groupId).eq("type", "payment_event")
1298
+ )
1299
+ .collect()
1300
+
1301
+ // Aggregate by protocol
1302
+ const revenueByProtocol = paymentEvents.reduce((acc, e) => {
1303
+ const protocol = e.metadata?.protocol || "traditional"
1304
+ acc[protocol] = (acc[protocol] || 0) + (e.metadata?.amount || 0)
1305
+ return acc
1306
+ }, {} as Record<string, number>)
1307
+
1308
+ return {
1309
+ revenueByProtocol,
1310
+ volumeOverTime: groupByTime(paymentEvents),
1311
+ usageByProtocol: countByProtocol(paymentEvents),
1312
+ topEntities: getTopRevenue(paymentEvents)
1313
+ }
1314
+ }
1315
+ })
1316
+ ```
1317
+
1318
+ </details>
1319
+
1320
+ **Acceptance Criteria:**
1321
+ - [ ] Revenue breakdown by protocol (X402, ACP, AP2, traditional)
1322
+ - [ ] Transaction volume over time (daily, weekly, monthly)
1323
+ - [ ] Protocol usage pie chart
1324
+ - [ ] Top revenue-generating entities
1325
+ - [ ] Export data as CSV
1326
+
1327
+ **Effort:** 24 hours (3 days)
1328
+
1329
+ ---
1330
+
1331
+ ## Part 4: Testing & Quality
1332
+
1333
+ ### 4.1 Backend Test Suite
1334
+
1335
+ **Problem:** No automated tests for backend logic
1336
+
1337
+ **Impact:** Regressions, bugs in production, slow development
1338
+
1339
+ **Solution:** Implement comprehensive test suite
1340
+
1341
+ <details>
1342
+ <summary>📋 Click to expand: Test Structure</summary>
1343
+
1344
+ ```typescript
1345
+ // backend/convex/services/__tests__/creator.service.test.ts
1346
+ import { describe, it, expect } from "vitest"
1347
+ import { Effect, Layer } from "effect"
1348
+ import { CreatorService } from "../entities/creator.service"
1349
+ import { TestDatabaseService } from "./mocks/database.service"
1350
+
1351
+ describe("CreatorService", () => {
1352
+ const TestLayer = Layer.mergeAll(
1353
+ TestDatabaseService,
1354
+ EventLogServiceMock,
1355
+ CreatorServiceLive
1356
+ )
1357
+
1358
+ it("should create a creator entity", async () => {
1359
+ const program = Effect.gen(function* () {
1360
+ const service = yield* CreatorService
1361
+
1362
+ const creatorId = yield* service.create({
1363
+ groupId: "test-group-id",
1364
+ name: "John Doe",
1365
+ properties: {
1366
+ email: "john@example.com",
1367
+ bio: "Fitness coach"
1368
+ },
1369
+ actorId: "test-actor-id"
1370
+ })
1371
+
1372
+ expect(creatorId).toBeDefined()
1373
+ })
1374
+
1375
+ await Effect.runPromise(
1376
+ program.pipe(Effect.provide(TestLayer))
1377
+ )
1378
+ })
1379
+
1380
+ it("should reject invalid email", async () => {
1381
+ const program = Effect.gen(function* () {
1382
+ const service = yield* CreatorService
1383
+
1384
+ yield* service.create({
1385
+ groupId: "test-group-id",
1386
+ name: "John Doe",
1387
+ properties: {
1388
+ email: "invalid-email"
1389
+ },
1390
+ actorId: "test-actor-id"
1391
+ })
1392
+ })
1393
+
1394
+ const result = await Effect.runPromiseExit(
1395
+ program.pipe(Effect.provide(TestLayer))
1396
+ )
1397
+
1398
+ expect(Exit.isFailure(result)).toBe(true)
1399
+ })
1400
+
1401
+ it("should log entity_created event", async () => {
1402
+ const eventLog = new EventLogSpy()
1403
+
1404
+ const program = Effect.gen(function* () {
1405
+ const service = yield* CreatorService
1406
+ yield* service.create({ ... })
1407
+ })
1408
+
1409
+ await Effect.runPromise(
1410
+ program.pipe(Effect.provide(TestLayerWithSpy(eventLog)))
1411
+ )
1412
+
1413
+ expect(eventLog.events).toContainEqual({
1414
+ type: "entity_created",
1415
+ metadata: { entityType: "creator" }
1416
+ })
1417
+ })
1418
+ })
1419
+ ```
1420
+
1421
+ **Coverage Goals:**
1422
+ - Unit tests: All Effect.ts services (90%+ coverage)
1423
+ - Integration tests: Mutations + queries (80%+ coverage)
1424
+ - E2E tests: Critical user flows (50%+ coverage)
1425
+
1426
+ </details>
1427
+
1428
+ **Acceptance Criteria:**
1429
+ - [ ] 90%+ test coverage for services
1430
+ - [ ] All 66 thing types have create/update tests
1431
+ - [ ] All 25 connection types have tests
1432
+ - [ ] All 67 event types are logged in tests
1433
+ - [ ] CI/CD runs tests on every commit
1434
+
1435
+ **Effort:** 80 hours (10 days)
1436
+
1437
+ ---
1438
+
1439
+ ### 4.2 Frontend Integration Tests
1440
+
1441
+ **Problem:** No tests for React components or Convex hooks
1442
+
1443
+ **Impact:** UI bugs, broken real-time updates
1444
+
1445
+ **Solution:** Add Vitest + Testing Library tests
1446
+
1447
+ <details>
1448
+ <summary>📋 Click to expand: Frontend Tests</summary>
1449
+
1450
+ ```typescript
1451
+ // web/src/components/__tests__/EntityForm.test.tsx
1452
+ import { render, screen, userEvent } from "@testing-library/react"
1453
+ import { ConvexProviderWithAuth } from "convex/react"
1454
+ import { EntityForm } from "../entities/EntityForm"
1455
+
1456
+ describe("EntityForm", () => {
1457
+ it("should render creator form fields", () => {
1458
+ render(
1459
+ <ConvexProviderWithAuth client={mockConvexClient}>
1460
+ <EntityForm type="creator" groupId="test-group" />
1461
+ </ConvexProviderWithAuth>
1462
+ )
1463
+
1464
+ expect(screen.getByLabelText("Name")).toBeInTheDocument()
1465
+ expect(screen.getByLabelText("Email")).toBeInTheDocument()
1466
+ expect(screen.getByLabelText("Bio")).toBeInTheDocument()
1467
+ })
1468
+
1469
+ it("should call createCreator mutation on submit", async () => {
1470
+ const createMock = vi.fn()
1471
+
1472
+ render(
1473
+ <ConvexProviderWithAuth client={mockConvexClient}>
1474
+ <EntityForm type="creator" groupId="test-group" />
1475
+ </ConvexProviderWithAuth>
1476
+ )
1477
+
1478
+ await userEvent.type(screen.getByLabelText("Name"), "John Doe")
1479
+ await userEvent.type(screen.getByLabelText("Email"), "john@example.com")
1480
+ await userEvent.click(screen.getByText("Create creator"))
1481
+
1482
+ expect(createMock).toHaveBeenCalledWith({
1483
+ groupId: "test-group",
1484
+ type: "creator",
1485
+ name: "John Doe",
1486
+ properties: { email: "john@example.com" }
1487
+ })
1488
+ })
1489
+ })
1490
+ ```
1491
+
1492
+ </details>
1493
+
1494
+ **Acceptance Criteria:**
1495
+ - [ ] 70%+ test coverage for components
1496
+ - [ ] Mock Convex queries/mutations
1497
+ - [ ] Test real-time updates (subscriptions)
1498
+ - [ ] Visual regression tests (Storybook + Chromatic)
1499
+ - [ ] Accessibility tests (axe-core)
1500
+
1501
+ **Effort:** 40 hours (5 days)
1502
+
1503
+ ---
1504
+
1505
+ ## Part 5: Operations & Deployment
1506
+
1507
+ ### 5.1 Monitoring & Observability
1508
+
1509
+ **Problem:** No logging, metrics, or error tracking
1510
+
1511
+ **Impact:** Cannot debug production issues
1512
+
1513
+ **Solution:** Implement comprehensive monitoring
1514
+
1515
+ <details>
1516
+ <summary>📋 Click to expand: Monitoring Setup</summary>
1517
+
1518
+ **Error Tracking (Sentry):**
1519
+ ```typescript
1520
+ // backend/convex/lib/sentry.ts
1521
+ import * as Sentry from "@sentry/node"
1522
+
1523
+ Sentry.init({
1524
+ dsn: process.env.SENTRY_DSN,
1525
+ environment: process.env.CONVEX_DEPLOYMENT,
1526
+ integrations: [new Sentry.Integrations.Http({ tracing: true })]
1527
+ })
1528
+
1529
+ export const withErrorTracking = <T>(
1530
+ operation: Effect.Effect<T, any, any>
1531
+ ) =>
1532
+ operation.pipe(
1533
+ Effect.tapError(error => {
1534
+ Sentry.captureException(error)
1535
+ return Effect.unit
1536
+ })
1537
+ )
1538
+ ```
1539
+
1540
+ **Metrics (Prometheus):**
1541
+ ```typescript
1542
+ // backend/convex/lib/metrics.ts
1543
+ import { Counter, Histogram } from "prom-client"
1544
+
1545
+ export const entityCreationCounter = new Counter({
1546
+ name: "entity_created_total",
1547
+ help: "Total entities created",
1548
+ labelNames: ["type", "groupId"]
1549
+ })
1550
+
1551
+ export const mutationDuration = new Histogram({
1552
+ name: "mutation_duration_seconds",
1553
+ help: "Mutation execution time",
1554
+ labelNames: ["operation"]
1555
+ })
1556
+ ```
1557
+
1558
+ **Logging (Structured):**
1559
+ ```typescript
1560
+ // backend/convex/lib/logger.ts
1561
+ import pino from "pino"
1562
+
1563
+ export const logger = pino({
1564
+ level: process.env.LOG_LEVEL || "info",
1565
+ formatters: {
1566
+ level: (label) => ({ level: label }),
1567
+ bindings: (bindings) => ({ pid: bindings.pid, hostname: bindings.hostname })
1568
+ }
1569
+ })
1570
+
1571
+ export const logEvent = (event: Event) => {
1572
+ logger.info({
1573
+ event: event.type,
1574
+ groupId: event.groupId,
1575
+ actorId: event.actorId,
1576
+ timestamp: event.timestamp
1577
+ }, "Event logged")
1578
+ }
1579
+ ```
1580
+
1581
+ </details>
1582
+
1583
+ **Acceptance Criteria:**
1584
+ - [ ] Sentry error tracking in production
1585
+ - [ ] Prometheus metrics exported
1586
+ - [ ] Structured logging to Cloudflare
1587
+ - [ ] Real-time alerting (PagerDuty)
1588
+ - [ ] Performance monitoring dashboard
1589
+
1590
+ **Effort:** 24 hours (3 days)
1591
+
1592
+ ---
1593
+
1594
+ ### 5.2 Database Migrations
1595
+
1596
+ **Problem:** Schema changes require manual updates
1597
+
1598
+ **Impact:** Risky deployments, data loss potential
1599
+
1600
+ **Solution:** Automated migration system
1601
+
1602
+ <details>
1603
+ <summary>📋 Click to expand: Migration Strategy</summary>
1604
+
1605
+ ```typescript
1606
+ // backend/convex/migrations/001_add_groupId_to_all_tables.ts
1607
+ export const migration001 = {
1608
+ id: "001_add_groupId",
1609
+ up: async (ctx: MigrationContext) => {
1610
+ // Get all entities without groupId
1611
+ const entities = await ctx.db
1612
+ .query("entities")
1613
+ .filter(q => q.eq(q.field("groupId"), undefined))
1614
+ .collect()
1615
+
1616
+ // Assign to default group
1617
+ const defaultGroup = await ctx.db
1618
+ .query("groups")
1619
+ .withIndex("by_slug", q => q.eq("slug", "default"))
1620
+ .first()
1621
+
1622
+ for (const entity of entities) {
1623
+ await ctx.db.patch(entity._id, {
1624
+ groupId: defaultGroup._id
1625
+ })
1626
+ }
1627
+
1628
+ logger.info(`Migrated ${entities.length} entities to default group`)
1629
+ },
1630
+
1631
+ down: async (ctx: MigrationContext) => {
1632
+ // Rollback logic
1633
+ }
1634
+ }
1635
+ ```
1636
+
1637
+ </details>
1638
+
1639
+ **Acceptance Criteria:**
1640
+ - [ ] Versioned migration system
1641
+ - [ ] Automatic backups before migration
1642
+ - [ ] Rollback capability
1643
+ - [ ] Migration status tracking
1644
+ - [ ] Dry-run mode for testing
1645
+
1646
+ **Effort:** 16 hours (2 days)
1647
+
1648
+ ---
1649
+
1650
+ ## Summary & Timeline
1651
+
1652
+ ### Total Effort Estimate
1653
+
1654
+ | Category | Tasks | Effort | Priority |
1655
+ |----------|-------|--------|----------|
1656
+ | Backend Integration | 1.1-1.5 | 236 hours (29.5 days) | P0 |
1657
+ | Frontend Integration | 2.1-2.4 | 156 hours (19.5 days) | P1 |
1658
+ | Protocol Integration | 3.1-3.2 | 40 hours (5 days) | P2 |
1659
+ | Testing & Quality | 4.1-4.2 | 120 hours (15 days) | P0 |
1660
+ | Operations | 5.1-5.2 | 40 hours (5 days) | P2 |
1661
+ | **TOTAL** | **47 tasks** | **592 hours (74 days)** | |
1662
+
1663
+ ### Recommended Phases
1664
+
1665
+ **Phase 1: Core Backend (Weeks 1-4)**
1666
+ - Complete 1.1: Missing backend mutations/queries
1667
+ - Complete 1.2: Effect.ts glue layer
1668
+ - Complete 1.3: Event logging
1669
+ - **Deliverable:** All 66 thing types operational
1670
+
1671
+ **Phase 2: Testing & Quality (Weeks 5-6)**
1672
+ - Complete 4.1: Backend test suite
1673
+ - Complete 4.2: Frontend integration tests
1674
+ - **Deliverable:** 90% test coverage
1675
+
1676
+ **Phase 3: Frontend (Weeks 7-10)**
1677
+ - Complete 2.1: Multi-tenant dashboard
1678
+ - Complete 2.2: Entity management UI
1679
+ - Complete 2.3: Connection visualization
1680
+ - Complete 2.4: Event timeline
1681
+ - **Deliverable:** Production-ready UI
1682
+
1683
+ **Phase 4: Advanced Features (Weeks 11-12)**
1684
+ - Complete 1.4: Connection management
1685
+ - Complete 1.5: RAG implementation
1686
+ - Complete 3.1-3.2: Protocol integration
1687
+ - **Deliverable:** Full protocol support + RAG
1688
+
1689
+ **Phase 5: Production Ready (Weeks 13-14)**
1690
+ - Complete 5.1: Monitoring
1691
+ - Complete 5.2: Migrations
1692
+ - Load testing
1693
+ - Security audit
1694
+ - **Deliverable:** Launch ready
1695
+
1696
+ ---
1697
+
1698
+ ## Key Metrics for Success
1699
+
1700
+ **Backend Completeness:**
1701
+ - ✅ 66/66 thing types have CRUD operations
1702
+ - ✅ 25/25 connection types implemented
1703
+ - ✅ 67/67 event types logged
1704
+ - ✅ 100% Effect.ts coverage
1705
+
1706
+ **Frontend Completeness:**
1707
+ - ✅ Multi-tenant dashboard with hierarchy
1708
+ - ✅ Entity forms for all types
1709
+ - ✅ Real-time subscriptions working
1710
+ - ✅ Graph visualization
1711
+
1712
+ **Quality:**
1713
+ - ✅ 90%+ backend test coverage
1714
+ - ✅ 70%+ frontend test coverage
1715
+ - ✅ Zero TypeScript errors
1716
+ - ✅ Sub-200ms mutation latency
1717
+
1718
+ **Production Readiness:**
1719
+ - ✅ Error tracking live
1720
+ - ✅ Metrics dashboards
1721
+ - ✅ Automated backups
1722
+ - ✅ Migration system
1723
+
1724
+ ---
1725
+
1726
+ ## Next Steps
1727
+
1728
+ 1. **Review this plan** with team/stakeholders
1729
+ 2. **Prioritize tasks** based on business needs
1730
+ 3. **Start Phase 1** immediately (backend integration)
1731
+ 4. **Set up CI/CD** for automated testing
1732
+ 5. **Track progress** weekly against this plan
1733
+
1734
+ **Golden Rule:** The ontology is perfect. Now make the implementation match it.