File size: 24,210 Bytes
5a81b95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
# MCP-COGNITIVE SYSTEM INTEGRATION ARCHITECTURE
## Binding the New Intelligence to Existing Platform

**Dato:** 2025-11-24  
**FormΓ₯l:** Konkret mapping mellem Master Plan og eksisterende MCP kerne

---

## πŸ—οΈ EKSISTERENDE MCP ARKITEKTUR

### Current System Components

```
Frontend (Widget Board)
β”œβ”€β”€ widgets/              (36 widgets)
β”‚   └── UnifiedDataService.ts  (existing)
β”‚
Backend (MCP Core)
β”œβ”€β”€ /api/mcp/route       (mcpRouter.ts)
β”œβ”€β”€ /api/mcp/autonomous  (autonomousRouter.ts - HansPedder)
β”œβ”€β”€ toolHandlers.ts      (CMA, SRAG, PAL, Evolution, Notes handlers)
β”œβ”€β”€ SourceRegistry.ts    (DataSource management)
β”œβ”€β”€ EventBus.ts          (System-wide events)
β”‚
Services Layer
β”œβ”€β”€ memory/              (CMA - MemoryRepository)
β”œβ”€β”€ srag/                (SRAGRepository)
β”œβ”€β”€ evolution/           (EvolutionRepository)
β”œβ”€β”€ pal/                 (PALRepository)
β”œβ”€β”€ project/             (ProjectMemory)
β”‚
Intelligence Layer (Current)
β”œβ”€β”€ AutonomousAgent.ts
β”œβ”€β”€ CognitiveMemory.ts
β”œβ”€β”€ PatternMemory.ts
β”œβ”€β”€ FailureMemory.ts
```

### Current Data Flow

```
Widget Request
   ↓
UnifiedDataService (frontend)
   ↓
POST /api/mcp/route
   ↓
mcpRouter.ts β†’ mcpRegistry.route(MCPMessage)
   ↓
toolHandlers[tool](payload, context)
   ↓
Repository (CMA/SRAG/PAL/Evolution)
   ↓
SQLite Database
   ↓
Response β†’ Widget
```

---

## πŸ”— INTEGRATION POINTS: NEW COGNITIVE SYSTEM

### Phase 1 Integration: Foundation Layer

#### 1.1 UnifiedMemorySystem β†’ Existing Repositories

**File:** `apps/backend/src/mcp/cognitive/UnifiedMemorySystem.ts`

```typescript
import { CognitiveMemory } from '../memory/CognitiveMemory.js';
import { MemoryRepository } from '../../services/memory/memoryRepository.js';
import { SragRepository } from '../../services/srag/sragRepository.js';
import { PalRepository } from '../../services/pal/palRepository.js';
import { EvolutionRepository } from '../../services/evolution/evolutionRepository.js';
import { ProjectMemory } from '../../services/project/ProjectMemory.js';

/**
 * INTEGRATION POINT 1: Unified Memory Bridge
 * Connects new 4-memory architecture to existing repositories
 */
export class UnifiedMemorySystem {
  // EXISTING COMPONENTS (reuse)
  private cognitiveMemory: CognitiveMemory;         // Pattern + Failure memory
  private memoryRepo: MemoryRepository;              // CMA (semantic memory)
  private sragRepo: SragRepository;                  // SRAG (document memory)
  private palRepo: PalRepository;                    // PAL (emotional context)
  private evolutionRepo: EvolutionRepository;        // Evolution (learning)
  private projectMemory: ProjectMemory;              // Episodic memory
  
  // NEW COMPONENTS (Phase 1)
  private workingMemory: Map<string, WorkingMemoryState>;  // Current context
  private proceduralMemory: ProductionRuleEngine;           // Pattern β†’ Action rules
  
  constructor() {
    // Connect to existing singletons
    this.cognitiveMemory = getCognitiveMemory();
    this.memoryRepo = new MemoryRepository();
    this.sragRepo = new SragRepository();
    this.palRepo = new PalRepository();
    this.evolutionRepo = new EvolutionRepository();
    this.projectMemory = new ProjectMemory();
    
    // Initialize new components
    this.workingMemory = new Map();
    this.proceduralMemory = new ProductionRuleEngine(this.cognitiveMemory);
  }
  
  /**
   * INTEGRATION: Holographic pattern correlation
   * Uses EXISTING repositories to find cross-system patterns
   */
  async findHolographicPatterns(ctx: McpContext): Promise<CrossSystemPattern[]> {
    // Query ALL existing systems
    const [palState, cmaEntities, sragDocs, evolutionLearning, cognitivePatterns] = 
      await Promise.all([
        this.palRepo.getRecentEvents(ctx.userId, ctx.orgId, 50),
        this.memoryRepo.searchEntities({
          userId: ctx.userId,
          orgId: ctx.orgId,
          keywords: [],
          limit: 50
        }),
        this.sragRepo.searchDocuments(ctx.orgId, ''), // All recent
        this.evolutionRepo.getRecentGenerations(10),
        this.cognitiveMemory.findSimilarQueries('holographic_scan', 10)
      ]);
    
    // Cross-correlate for patterns
    return this.correlateAcrossSystems({
      emotional: this.analyzePALPatterns(palState),
      knowledge: this.analyzeCMAGraph(cmaEntities),
      documents: this.analyzeSRAGContent(sragDocs),
      learning: this.analyzeEvolutionTrends(evolutionLearning),
      meta: cognitivePatterns
    });
  }
  
  /**
   * INTEGRATION: Query routing with memory context
   * Enhances EXISTING mcpRouter with memory-aware decisions
   */
  async enrichMCPRequest(message: MCPMessage, ctx: McpContext): Promise<EnrichedMCPMessage> {
    // 1. Load working memory for this context
    const workingState = this.workingMemory.get(ctx.userId) || 
      await this.initializeWorkingMemory(ctx);
    
    // 2. Get procedural rules (learned patterns β†’ actions)
    const applicableRules = await this.proceduralMemory.findRules({
      tool: message.tool,
      context: workingState
    });
    
    // 3. Get semantic context from CMA
    const semanticContext = await this.memoryRepo.searchEntities({
      userId: ctx.userId,
      orgId: ctx.orgId,
      keywords: this.extractKeywords(message.payload),
      limit: 10
    });
    
    // 4. Get episodic context from ProjectMemory
    const episodicContext = await this.projectMemory.queryHistory({
      limit: 10,
      filterByUser: ctx.userId
    });
    
    // 5. Enrich message
    return {
      ...message,
      enrichedContext: {
        workingMemory: workingState,
        proceduraRules: applicableRules,
        semanticMemory: semanticContext,
        episodicMemory: episodicContext,
        emotionalState: await this.getEmotionalState(ctx)
      }
    };
  }
}
```

**Integration Point:** `mcpRouter.ts` modification

```typescript
// BEFORE (current):
mcpRouter.post('/route', async (req, res) => {
  const message: MCPMessage = req.body;
  const result = await mcpRegistry.route(message);
  res.json({ success: true, result });
});

// AFTER (Phase 1):
import { getUnifiedMemorySystem } from './cognitive/UnifiedMemorySystem.js';

mcpRouter.post('/route', async (req, res) => {
  const message: MCPMessage = req.body;
  const ctx: McpContext = {
    userId: req.user?.id || 'anonymous',
    orgId: req.user?.orgId || 'default',
    timestamp: new Date()
  };
  
  // NEW: Enrich with cognitive context
  const memorySystem = getUnifiedMemorySystem();
  const enrichedMessage = await memorySystem.enrichMCPRequest(message, ctx);
  
  // Route with enriched context
  const result = await mcpRegistry.route(enrichedMessage);
  
  // NEW: Update working memory with result
  await memorySystem.updateWorkingMemory(ctx, result);
  
  res.json({ success: true, result });
});
```

---

#### 1.2 Autonomous Task Engine β†’ AutonomousAgent Integration

**File:** `apps/backend/src/mcp/cognitive/AutonomousTaskEngine.ts`

```typescript
import { AutonomousAgent } from '../autonomous/AutonomousAgent.js';
import { UnifiedMemorySystem } from './UnifiedMemorySystem.js';
import { EventBus } from '../EventBus.js';

/**
 * INTEGRATION POINT 2: Task-Driven Loop
 * Extends EXISTING AutonomousAgent with BabyAGI-style task generation
 */
export class AutonomousTaskEngine {
  private agent: AutonomousAgent;
  private memorySystem: UnifiedMemorySystem;
  private eventBus: typeof EventBus;
  private taskQueue: PriorityQueue<Task>;
  
  constructor(
    agent: AutonomousAgent,
    memorySystem: UnifiedMemorySystem
  ) {
    this.agent = agent;
    this.memorySystem = memorySystem;
    this.eventBus = EventBus;
    this.taskQueue = new PriorityQueue();
    
    // Listen to system events for task generation
    this.setupEventListeners();
  }
  
  private setupEventListeners() {
    // INTEGRATION: React to existing EventBus events
    this.eventBus.on('system:error', (error) => {
      this.taskQueue.enqueue(new DiagnosticTask(error), 100);
    });
    
    this.eventBus.on('widget:error', ({ widgetId, error }) => {
      this.taskQueue.enqueue(new WidgetFixTask(widgetId, error), 90);
    });
    
    this.eventBus.on('mcp:slow_response', ({ tool, latency }) => {
      if (latency > 5000) {
        this.taskQueue.enqueue(new PerformanceOptimizationTask(tool), 70);
      }
    });
  }
  
  /**
   * INTEGRATION: Main autonomous loop
   * Uses EXISTING AutonomousAgent.executeAndLearn but adds task generation
   */
  async autonomousLoop() {
    while (this.isActive) {
      const task = this.taskQueue.dequeue();
      if (!task) {
        await this.sleep(1000);
        continue;
      }
      
      // Execute using EXISTING AutonomousAgent
      const intent = this.taskToQueryIntent(task);
      const result = await this.agent.executeAndLearn(intent);
      
      // Generate new tasks based on result (NEW)
      const newTasks = await this.generateTasksFromResult(task, result);
      this.taskQueue.enqueueAll(newTasks);
      
      // Reprioritize with emotional awareness (NEW)
      await this.emotionAwarePrioritization();
      
      // Log to episodic memory (INTEGRATION)
      await this.memorySystem.logEpisode({
        task,
        result,
        newTasksGenerated: newTasks.length
      });
    }
  }
}
```

**Integration Point:** `hansPedder.ts` modification

```typescript
// apps/backend/src/orchestrator/hansPedder.ts

import { AutonomousTaskEngine } from '../mcp/cognitive/AutonomousTaskEngine.js';
import { getUnifiedMemorySystem } from '../mcp/cognitive/UnifiedMemorySystem.js';

export async function startHansPedder() {
  const cognitive = getCognitiveMemory();
  const sourceReg = getSourceRegistry();
  const memorySystem = getUnifiedMemorySystem();
  
  // EXISTING AutonomousAgent
  hansPedder = new AutonomousAgent(cognitive, sourceReg);
  
  // NEW: Task engine wraps agent
  const taskEngine = new AutonomousTaskEngine(hansPedder, memorySystem);
  
  console.info('πŸš€ Starting HansPedder with Autonomous Task Engine...');
  hansPedderStatus.active = true;
  hansPedderStatus startedAt = new Date();
  
  // Start task-driven loop (NEW) instead of basic learning loop
  await taskEngine.autonomousLoop();
}
```

---

#### 1.3 Emotion-Aware Decisions β†’ PAL Integration

**File:** `apps/backend/src/mcp/cognitive/EmotionAwareDecisionEngine.ts`

```typescript
import { PalRepository } from '../../services/pal/palRepository.js';
import { AutonomousAgent } from '../autonomous/AutonomousAgent.js';

/**
 * INTEGRATION POINT 3: Emotion-Aware Routing
 * Connects PAL emotional state to decision-making
 */
export class EmotionAwareDecisionEngine {
  private palRepo: PalRepository;
  private agent: AutonomousAgent;
  
  constructor(agent: AutonomousAgent) {
    this.agent = agent;
    this.palRepo = new PalRepository();
  }
  
  /**
   * INTEGRATION: Enhance EXISTING AutonomousAgent.selectSource
   * with emotional context
   */
  async makeEmotionAwareDecision(
    intent: QueryIntent,
    ctx: McpContext
  ): Promise<DataSource> {
    // 1. Get EXISTING data-driven score
    const dataScore = await this.agent.scoreSource(intent);
    
    // 2. Get emotional state from EXISTING PAL
    const emotionalState = await this.getEmotionalState(ctx);
    
    // 3. Adjust scores based on emotion (NEW)
    const emotionAdjustedScores = dataScore.map(sourceScore => ({
      ...sourceScore,
      score: this.adjustForEmotion(sourceScore, emotionalState)
    }));
    
    // 4. Select best
    return emotionAdjustedScores.sort((a, b) => b.score - a.score)[0].source;
  }
  
  private async getEmotionalState(ctx: McpContext): Promise<EmotionalState> {
    // INTEGRATION: Use EXISTING PAL repository
    const recentEvents = this.palRepo.getRecentEvents(ctx.userId, ctx.orgId, 10);
    const stressDistribution = this.palRepo.getStressLevelDistribution(
      ctx.userId, 
      ctx.orgId, 
      1 // last hour
    );
    
    // Analyze stress level
    const highStressEvents = stressDistribution.filter(d => d.stress_level === 'high');
    const stressRatio = highStressEvents.length / Math.max(stressDistribution.length, 1);
    
    return {
      stress: stressRatio > 0.5 ? 'high' : stressRatio > 0.2 ? 'medium' : 'low',
      focus: this.determineFocusLevel(recentEvents),
      engagement: this.determineEngagement(recentEvents)
    };
  }
  
  private adjustForEmotion(
    sourceScore: { source: DataSource, score: number },
    emotion: EmotionalState
  ): number {
    let adjusted = sourceScore.score;
    
    // Stress-aware routing (NEW capability)
    if (emotion.stress === 'high') {
      // Prefer fast, simple sources
      if (sourceScore.source.estimatedLatency < 100) {
        adjusted *= 1.5;  // 50% boost for fast sources
      }
      if (sourceScore.source.complexity === 'low') {
        adjusted *= 1.3;  // 30% boost for simple sources
      }
      if (sourceScore.source.estimatedLatency > 1000) {
        adjusted *= 0.5;  // 50% penalty for slow sources
      }
    }
    
    // Focus-aware routing
    if (emotion.focus === 'deep') {
      // Allow complex, thorough sources
      if (sourceScore.source.depth === 'high') {
        adjusted *= 1.4;
      }
    }
    
    return adjusted;
  }
}
```

**Integration Point:** `AutonomousAgent.ts` modification

```typescript
// apps/backend/src/mcp/autonomous/AutonomousAgent.ts

import { EmotionAwareDecisionEngine } from '../cognitive/EmotionAwareDecisionEngine.js';

export class AutonomousAgent {
  private emotionEngine: EmotionAwareDecisionEngine;
  
  constructor(cognitive: CognitiveMemory, registry: SourceRegistryImpl) {
    // ... existing code ...
    
    // NEW: Initialize emotion engine
    this.emotionEngine = new EmotionAwareDecisionEngine(this);
  }
  
  async executeAndLearn(intent: QueryIntent, ctx?: McpContext): Promise<any> {
    // BEFORE: const source = this.selectSource(intent);
    
    // AFTER: Use emotion-aware selection
    const source = ctx 
      ? await this.emotionEngine.makeEmotionAwareDecision(intent, ctx)
      : this.selectSource(intent);  // fallback to existing
    
    // ... rest of existing code ...
  }
}
```

---

### Phase 2 Integration: Intelligence Layer

#### 2.1 GraphRAG β†’ CMA + SRAG Unification

**File:** `apps/backend/src/mcp/cognitive/UnifiedGraphRAG.ts`

```typescript
import { MemoryRepository } from '../../services/memory/memoryRepository.js';
import { SragRepository } from '../../services/srag/sragRepository.js';
import { HybridSearchEngine } from './HybridSearchEngine.js';

/**
 * INTEGRATION POINT 4: GraphRAG
 * Unifies EXISTING CMA (knowledge graph) + SRAG (documents)
 */
export class UnifiedGraphRAG {
  private cmaRepo: MemoryRepository;        // EXISTING semantic graph
  private sragRepo: SragRepository;         // EXISTING documents
  private hybridSearch: HybridSearchEngine; // NEW hybrid search
  
  /**
   * INTEGRATION: Multi-hop reasoning over CMA graph + SRAG docs
   */
  async query(naturalLanguageQuery: string, ctx: McpContext): Promise<GraphRAGResult> {
    // 1. Hybrid search (NEW) over EXISTING data
    const searchResults = await this.hybridSearch.search(naturalLanguageQuery, {
      userId: ctx.userId,
      orgId: ctx.orgId
    });
    
    // 2. Multi-hop graph traversal on CMA entities
    const graphEntities = searchResults.cma || [];
    const expandedGraph = await this.multiHopTraversal(graphEntities);
    
    // 3. Get related SRAG documents
    const relatedDocs = searchResults.srag || [];
    
    // 4. Synthesize unified context
    return {
      graphContext: expandedGraph,
      documentContext: relatedDocs,
      unifiedSummary: await this.synthesize(expandedGraph, relatedDocs)
    };
  }
  
  private async multiHopTraversal(
    startEntities: MemoryEntity[],
    maxHops: number = 3
  ): Promise<KnowledgeSubgraph> {
    // INTEGRATION: Use EXISTING CMA relations
    const subgraph = new KnowledgeSubgraph();
    const visited = new Set<string>();
    
    let frontier = startEntities;
    
    for (let hop = 0; hop < maxHops; hop++) {
      const nextFrontier: MemoryEntity[] = [];
      
      for (const entity of frontier) {
        if (visited.has(entity.id)) continue;
        visited.add(entity.id);
        subgraph.addNode(entity);
        
        // Get related entities via CMA relations (EXISTING)
        const relations = await this.cmaRepo.getEntityRelations(entity.id);
        for (const rel of relations) {
          const relatedEntity = await this.cmaRepo.getEntity(rel.target_entity_id);
          if (relatedEntity) {
            nextFrontier.push(relatedEntity);
            subgraph.addEdge(entity, relatedEntity, rel.relationship_type);
          }
        }
      }
      
      frontier = nextFrontier;
    }
    
    return subgraph;
  }
}
```

**Integration Point:** New MCP tool handler

```typescript
// apps/backend/src/mcp/toolHandlers.ts

import { getUnifiedGraphRAG } from './cognitive/UnifiedGraphRAG.js';

/**
 * NEW TOOL: graph_rag (Phase 2)
 * Intelligent multi-hop reasoning over unified knowledge
 */
export async function graphRAGHandler(
  payload: { query: string },
  ctx: McpContext
): Promise<any> {
  const graphRAG = getUnifiedGraphRAG();
  const result = await graphRAG.query(payload.query, ctx);
  
  return {
    graphNodes: result.graphContext.nodes.length,
    documents: result.documentContext.length,
    summary: result.unifiedSummary,
    fullContext: result
  };
}

// Register in mcpRegistry
mcpRegistry.registerTool('graph_rag', graphRAGHandler);
```

---

#### 2.2 Frontend Integration: UnifiedDataService Enhancement

**File:** `apps/matrix-frontend/src/services/UnifiedDataService.ts` (modify EXISTING)

```typescript
/**
 * INTEGRATION POINT 5: Frontend Access to Cognitive System
 * Enhances EXISTING UnifiedDataService
 */
export class UnifiedDataService {
  // EXISTING methods remain...
  
  /**
   * NEW (Phase 1): Memory-aware query
   */
  async queryWithMemory(request: {
    tool: string;
    payload: any;
    useMemoryContext?: boolean;
  }): Promise<any> {
    const message: MCPMessage = {
      id: uuidv4(),
      tool: request.tool,
      payload: request.payload,
      createdAt: new Date().toISOString(),
      // NEW: Request memory enrichment
      options: {
        enrichWithMemory: request.useMemoryContext ?? true,
        includeEmotionalContext: true
      }
    };
    
    const response = await fetch('/api/mcp/route', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(message)
    });
    
    return response.json();
  }
  
  /**
   * NEW (Phase 2): GraphRAG query
   */
  async queryGraphRAG(naturalLanguageQuery: string): Promise<GraphRAGResult> {
    return this.queryWithMemory({
      tool: 'graph_rag',
      payload: { query: naturalLanguageQuery }
    });
  }
  
  /**
   * NEW (Phase 3): Get autonomous insights
   */
  async getAutonomousInsights(): Promise<SystemInsights> {
    return this.queryWithMemory({
      tool: 'autonomous_insights',
      payload: {}
    });
  }
}
```

---

## πŸ“Š INTEGRATION DEPENDENCY GRAPH

```
Phase 1: Foundation (Week 1-4)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
UnifiedMemorySystem (NEW)
β”œβ”€β–Ί CognitiveMemory (EXISTING)
β”œβ”€β–Ί MemoryRepository/CMA (EXISTING)
β”œβ”€β–Ί SRAGRepository (EXISTING)
β”œβ”€β–Ί PALRepository (EXISTING)
β”œβ”€β–Ί EvolutionRepository (EXISTING)
└─► ProjectMemory (EXISTING)

AutonomousTaskEngine (NEW)
β”œβ”€β–Ί AutonomousAgent (EXISTING)
β”œβ”€β–Ί UnifiedMemorySystem (NEW - Phase 1)
└─► EventBus (EXISTING)

EmotionAwareDecisionEngine (NEW)
β”œβ”€β–Ί PALRepository (EXISTING)
└─► AutonomousAgent (EXISTING)

HybridSearchEngine (NEW)
β”œβ”€β–Ί MemoryRepository (EXISTING)
β”œβ”€β–Ί SRAGRepository (EXISTING)
└─► CognitiveMemory (EXISTING)

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Phase 2: Intelligence (Week 5-9)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
UnifiedGraphRAG (NEW)
β”œβ”€β–Ί MemoryRepository (EXISTING)
β”œβ”€β–Ί SRAGRepository (EXISTING)
└─► HybridSearchEngine (NEW - Phase 1)

AgentTeam (NEW)
β”œβ”€β–Ί AutonomousAgent (EXISTING)
└─► UnifiedMemorySystem (NEW - Phase 1)

StateGraphRouter (NEW)
β”œβ”€β–Ί mcpRouter (EXISTING)
└─► ProjectMemory (EXISTING)

PatternEvolutionEngine (NEW)
β”œβ”€β–Ί AutonomousAgent (EXISTING)
β”œβ”€β–Ί CognitiveMemory (EXISTING)
└─► ProjectMemory (EXISTING)

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Phase 3: Meta-Cognition (Week 10-12)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
SelfReflectionEngine (NEW)
β”œβ”€β–Ί AutonomousAgent (EXISTING)
β”œβ”€β–Ί CognitiveMemory (EXISTING)
└─► ProjectMemory (EXISTING)

MetaLearningEngine (NEW)
└─► UnifiedMemorySystem (NEW - Phase 1)

RLHFAlignmentSystem (NEW)
β”œβ”€β–Ί AutonomousAgent (EXISTING)
└─► ProjectMemory (EXISTING)
```

---

## πŸ”„ DATA FLOW: BEFORE vs AFTER

### BEFORE (Current):

```
Widget β†’ UnifiedDataService β†’ POST /api/mcp/route β†’ mcpRouter
β†’ toolHandler β†’ Repository β†’ Database β†’ Response
```

### AFTER Phase 1:

```
Widget β†’ UnifiedDataService.queryWithMemory()
  ↓
POST /api/mcp/route (enrichment enabled)
  ↓
UnifiedMemorySystem.enrichMCPRequest()
  β”œβ”€β–Ί Working Memory (current context)
  β”œβ”€β–Ί Procedural Memory (learned rules)
  β”œβ”€β–Ί Semantic Memory (CMA)
  β”œβ”€β–Ί Episodic Memory (ProjectMemory)
  └─► Emotional Context (PAL)
  ↓
EmotionAwareDecisionEngine.makeDecision()
  ↓
EnrichedMCPMessage β†’ toolHandler β†’ Repository β†’ Database
  ↓
UnifiedMemorySystem.updateWorkingMemory()
  ↓
Response (with memory context)
```

### AFTER Phase 2:

```
Widget β†’ UnifiedDataService.queryGraphRAG()
  ↓
POST /api/mcp/route (tool: 'graph_rag')
  ↓
UnifiedGraphRAG.query()
  β”œβ”€β–Ί HybridSearchEngine (keyword + semantic + graph)
  β”œβ”€β–Ί Multi-hop traversal (CMA knowledge graph)
  └─► Document retrieval (SRAG)
  ↓
Synthesized context β†’ Response
```

### AFTER Phase 3:

```
Background Loop: AutonomousTaskEngine
  ↓
Generate tasks β†’ Execute via AutonomousAgent
  ↓
SelfReflectionEngine.reflect()
  ↓
MetaLearningEngine.optimizeLearningStrategy()
  ↓
RLHFAlignmentSystem.optimizePolicy()
  ↓
Update all systems β†’ Improved performance
```

---

## βœ… INTEGRATION CHECKLIST

### Phase 1 (Week 1-4)

- [ ] Create `apps/backend/src/mcp/cognitive/` directory
- [ ] Implement `UnifiedMemorySystem.ts`
- [ ] Modify `mcpRouter.ts` to use enrichment
- [ ] Implement `AutonomousTaskEngine.ts`
- [ ] Modify `hansPedder.ts` to use task engine
- [ ] Implement `EmotionAwareDecisionEngine.ts`
- [ ] Modify `AutonomousAgent.ts` for emotion awareness
- [ ] Implement `HybridSearchEngine.ts`
- [ ] Modify frontend `UnifiedDataService.ts`
- [ ] Integration tests for all components
- [ ] Update `MCPMessage` interface to support enrichment

### Phase 2 (Week 5-9)

- [ ] Implement `UnifiedGraphRAG.ts`
- [ ] Add `graph_rag` tool handler
- [ ] Register GraphRAG tool in `mcpRegistry`
- [ ] Implement `AgentTeam.ts`
- [ ] Implement `StateGraphRouter.ts`
- [ ] Implement `PatternEvolutionEngine.ts`
- [ ] Integration tests for Phase 2
- [ ] Frontend GraphRAG integration
- [ ] Performance optimization

### Phase 3 (Week 10-12)

- [ ] Implement `SelfReflectionEngine.ts`
- [ ] Implement `MetaLearningEngine.ts`
- [ ] Implement `RLHFAlignmentSystem.ts`
- [ ] Connect feedback loops
- [ ] Final integration testing
- [ ] Performance tuning
- [ ] Production deployment

---

## 🎯 SUCCESS METRICS PER PHASE

**Phase 1:** Memory enrichment active, emotion-aware routing functional  
**Phase 2:** GraphRAG queries working, multi-hop reasoning operational  
**Phase 3:** Self-improvement autonomy, continuous optimization

---

**Status:** Integration architecture complete and ready for implementation πŸš€