File size: 13,653 Bytes
34367da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// UnifiedMemorySystem – Phase 1 foundation
// Provides Working, Procedural, Semantic, and Episodic memory layers
// Integrates existing repositories (CMA, SRAG, PAL, Evolution, ProjectMemory)

import { getCognitiveMemory, initCognitiveMemory, CognitiveMemory } from '../memory/CognitiveMemory.js';
import { getDatabase, getSqlJsDatabase } from '../../database/index.js';
import { getDatabaseAdapter } from '../../platform/db/PrismaDatabaseAdapter.js';
import { PostgresStorageAdapter } from '../memory/StorageAdapter.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';
import { McpContext } from '@widget-tdc/mcp-types';
import { QueryIntent } from '../autonomous/DecisionEngine.js';
import { hybridSearchEngine } from './HybridSearchEngine.js';
import { emotionAwareDecisionEngine } from './EmotionAwareDecisionEngine.js';

/** WorkingMemoryState – transient context for the current request */
export interface WorkingMemoryState {
    recentEvents: any[];
    recentFeatures: any[];
    recentPatterns?: any[];
    widgetStates: Record<string, any>; // Live data fra widgets
    userMood: {
        sentiment: 'positive' | 'neutral' | 'negative' | 'stressed';
        arousal: number; // 0-1 (Hvor aktiv er brugeren?)
        lastUpdated: number;
    };
    suggestedLayout?: {
        mode: 'focus' | 'discovery' | 'alert';
        activeWidgets: string[]; // ID på widgets der bør være fremme
        theme?: string;
    };
}

/** ProductionRuleEngine – simple procedural memory placeholder */
class ProductionRuleEngine {
    constructor(private cognitive: CognitiveMemory) { }
    // TODO: implement rule extraction from cognitive patterns
    async findRules(_opts: any): Promise<any[]> { return []; }
}

export class UnifiedMemorySystem {
    // Existing repositories
    private cognitive: CognitiveMemory;
    private memoryRepo: MemoryRepository;
    private sragRepo: SragRepository;
    private palRepo: PalRepository;
    private evolutionRepo: EvolutionRepository;

    // New memory layers
    private workingMemory: Map<string, WorkingMemoryState> = new Map();
    private proceduralMemory: ProductionRuleEngine;

    constructor() {
        // Initialize repositories
        this.memoryRepo = new MemoryRepository();
        this.sragRepo = new SragRepository();
        this.palRepo = new PalRepository();
        this.evolutionRepo = new EvolutionRepository();

        // Initialize cognitive memory lazily or assume initialized
        // We cannot call getDatabase() here because it might not be ready
        // The cognitive memory should be passed in or retrieved lazily
        this.cognitive = {} as any; // Placeholder, will be set in init() or getter
        this.proceduralMemory = new ProductionRuleEngine(this.cognitive);
    }

    // New init method to be called after DB is ready
    public init() {
        const dbAdapter = getDatabaseAdapter();
        if (dbAdapter.isAvailable()) {
            initCognitiveMemory(new PostgresStorageAdapter(dbAdapter));
        } else {
            const db = getSqlJsDatabase();
            // Note: getSqlJsDatabase returns the raw sql.js instance needed for .exec()
            // If it returns null, CognitiveMemory handles it (memory-only mode)
            initCognitiveMemory(db);
        }
        this.cognitive = getCognitiveMemory();
        this.proceduralMemory = new ProductionRuleEngine(this.cognitive);
    }

    /** Retrieve or create working memory for a user/org context */
    async getWorkingMemory(ctx: McpContext): Promise<WorkingMemoryState> {
        const key = `${ctx.orgId}:${ctx.userId}`;
        if (!this.workingMemory.has(key)) {
            const events = projectMemory.getLifecycleEvents(20);
            const features = projectMemory.getFeatures();
            this.workingMemory.set(key, {
                recentEvents: events,
                recentFeatures: features,
                widgetStates: {},
                userMood: { sentiment: 'neutral', arousal: 0.5, lastUpdated: Date.now() }
            });
        }
        return this.workingMemory.get(key)!;
    }

    /** Opdater widget state og kør adaptiv analyse */
    async updateWidgetState(ctx: McpContext, widgetId: string, state: any): Promise<void> {
        const wm = await this.getWorkingMemory(ctx);
        wm.widgetStates[widgetId] = { ...state, lastUpdated: Date.now() };

        // Trigger holographic analysis when state changes
        const patterns = await this.findHolographicPatterns(ctx);

        // Opdater adaptivt layout baseret på mønstre
        this.updateAdaptiveLayout(wm, patterns);
    }

    /** Persist result (e.g., tool output) into working memory for future context */
    async updateWorkingMemory(ctx: McpContext, result: any): Promise<void> {
        const key = `${ctx.orgId}:${ctx.userId}`;
        const state = this.workingMemory.get(key);
        if (state) {
            state.recentEvents = [...(state.recentEvents || []), result];

            // Simuleret humør-analyse baseret på interaktion
            // Hvis resultatet er en fejl -> stress op
            if (result?.error) {
                state.userMood.sentiment = 'stressed';
                state.userMood.arousal = Math.min(1, state.userMood.arousal + 0.2);
            } else {
                // Reset langsomt mod neutral
                state.userMood.arousal = Math.max(0.2, state.userMood.arousal - 0.05);
            }

            this.workingMemory.set(key, state);
        }
    }

    /** Enrich an incoming MCPMessage with memory context */
    async enrichMCPRequest(message: any, ctx: McpContext): Promise<any> {
        const wm = await this.getWorkingMemory(ctx);
        return {
            ...message,
            memoryContext: {
                recentEvents: wm.recentEvents,
                recentFeatures: wm.recentFeatures,
                activeWidgets: wm.widgetStates,
                systemSuggestion: wm.suggestedLayout
            }
        };
    }

    /** Example holographic pattern correlation across subsystems */
    async findHolographicPatterns(ctx: McpContext): Promise<any[]> {
        const wm = await this.getWorkingMemory(ctx);
        const widgetData = Object.values(wm.widgetStates);

        const [pal, cma, srag] = await Promise.all([
            Promise.resolve(this.palRepo.getRecentEvents(ctx.userId, ctx.orgId, 50)).catch(() => []),
            Promise.resolve(this.memoryRepo.searchEntities({ orgId: ctx.orgId, userId: ctx.userId, keywords: [], limit: 50 })).catch(() => []),
            Promise.resolve(this.sragRepo.searchDocuments(ctx.orgId, '')).catch(() => []),
        ]);

        // Inkluder widget data i korrelationen
        return this.correlateAcrossSystems([pal, cma, srag, widgetData]);
    }

    /** Opdater layout forslag baseret på mønstre og humør */
    private updateAdaptiveLayout(wm: WorkingMemoryState, patterns: any[]) {
        // 1. Tjek for kritiske mønstre (Sikkerhed)
        const securityPattern = patterns.find(p =>
            ['threat', 'attack', 'breach', 'password', 'alert'].includes(p.keyword) && p.frequency > 2
        );

        if (securityPattern) {
            wm.suggestedLayout = {
                mode: 'alert',
                activeWidgets: ['DarkWebMonitorWidget', 'NetworkSpyWidget', 'CybersecurityOverwatchWidget'],
                theme: 'red-alert'
            };
            return;
        }

        // 2. Tjek brugerens humør (Emotion Aware)
        if (wm.userMood.sentiment === 'stressed' || wm.userMood.arousal > 0.8) {
            wm.suggestedLayout = {
                mode: 'focus',
                activeWidgets: ['StatusWidget', 'IntelligentNotesWidget'], // Kun det mest nødvendige
                theme: 'calm-blue'
            };
            return;
        }

        // 3. Default: Discovery mode hvis mange data-kilder er aktive
        if (patterns.length > 5) {
            wm.suggestedLayout = {
                mode: 'discovery',
                activeWidgets: ['VisualizerWidget', 'SearchInterfaceWidget', 'KnowledgeGraphWidget'],
                theme: 'default'
            };
        }
    }

    /** Cross-correlate patterns across subsystems */
    private correlateAcrossSystems(systems: any[]): any[] {
        const patterns: any[] = [];

        // Simple correlation: find common keywords/topics across systems
        const allKeywords = new Map<string, number>();

        if (!Array.isArray(systems)) return [];

        systems.forEach((system, idx) => {
            if (Array.isArray(system)) {
                system.forEach((item: any) => {
                    if (!item) return;
                    const text = JSON.stringify(item).toLowerCase();
                    const words = text.match(/\b\w{4,}\b/g) || [];
                    words.forEach(word => {
                        allKeywords.set(word, (allKeywords.get(word) || 0) + 1);
                    });
                });
            }
        });

        // Find keywords that appear in multiple systems (holographic pattern)
        Array.from(allKeywords.entries())
            .filter(([_, count]) => count >= 2)
            .forEach(([keyword, count]) => {
                patterns.push({
                    keyword,
                    frequency: count,
                    systems: systems.length,
                    type: 'holographic_pattern'
                });
            });

        return patterns;
    }

    /** Whole-part system health analysis */
    async analyzeSystemHealth(): Promise<SystemHealthReport> {
        const wholeSystem = {
            globalHealth: await this.calculateGlobalHealth(),
            emergentPatterns: await this.detectEmergentBehaviors(),
            systemRhythms: await this.detectTemporalCycles()
        };

        const parts = await Promise.all([
            this.componentHealth('pal'),
            this.componentHealth('cma'),
            this.componentHealth('srag'),
            this.componentHealth('evolution'),
            this.componentHealth('autonomous-agent')
        ]);

        return this.modelWholePartRelationships(wholeSystem, parts);
    }

    private async calculateGlobalHealth(): Promise<number> {
        try {
            const health = await this.cognitive.getSourceHealth('system');
            return health?.healthScore || 0.8; // Default to 80% if no data
        } catch {
            return 0.8;
        }
    }

    private async detectEmergentBehaviors(): Promise<any[]> {
        // Placeholder: detect patterns that emerge from system interactions
        return [];
    }

    private async detectTemporalCycles(): Promise<any[]> {
        // Placeholder: detect recurring patterns over time
        return [];
    }

    private async componentHealth(component: string): Promise<ComponentHealth> {
        try {
            if (!this.cognitive || !this.cognitive.getSourceHealth) {
                return {
                    name: component,
                    healthScore: 0.8, // Default optimistic
                    latency: 0,
                    successRate: 0.9
                };
            }
            const health = await this.cognitive.getSourceHealth(component);
            return {
                name: component,
                healthScore: health?.healthScore || 0.8,
                latency: health?.latency?.p50 || 0,
                successRate: health?.successRate || 0.9
            };
        } catch {
            return {
                name: component,
                healthScore: 0.8,
                latency: 0,
                successRate: 0.9
            };
        }
    }

    private modelWholePartRelationships(whole: any, parts: ComponentHealth[]): SystemHealthReport {
        const avgPartHealth = parts.reduce((sum, p) => sum + p.healthScore, 0) / parts.length;
        const wholeHealth = whole.globalHealth;

        return {
            globalHealth: wholeHealth,
            componentHealth: parts,
            emergentPatterns: whole.emergentPatterns,
            systemRhythms: whole.systemRhythms,
            wholePartRatio: wholeHealth / Math.max(avgPartHealth, 0.1), // How whole relates to parts
            healthVariance: this.calculateVariance(parts.map(p => p.healthScore))
        };
    }

    private calculateVariance(values: number[]): number {
        if (values.length === 0) return 0;
        const mean = values.reduce((a, b) => a + b, 0) / values.length;
        const variance = values.reduce((sum, val) => sum + Math.pow(val - mean, 2), 0) / values.length;
        return variance;
    }
}

interface ComponentHealth {
    name: string;
    healthScore: number;
    latency: number;
    successRate: number;
}

interface SystemHealthReport {
    globalHealth: number;
    componentHealth: ComponentHealth[];
    emergentPatterns: any[];
    systemRhythms: any[];
    wholePartRatio: number;
    healthVariance: number;
}

export const unifiedMemorySystem = new UnifiedMemorySystem();