File size: 13,460 Bytes
529090e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// Enhanced EmotionAwareDecisionEngine – Phase 1 Week 3
// Multi-modal decision making with emotional awareness

import { PalRepository } from '../../services/pal/palRepository.js';
import { unifiedMemorySystem } from './UnifiedMemorySystem.js';
import { McpContext } from '@widget-tdc/mcp-types';
import { QueryIntent } from '../autonomous/DecisionEngine.js';

export interface EmotionalState {
    stress: 'low' | 'medium' | 'high';
    focus: 'shallow' | 'medium' | 'deep';
    energy: 'low' | 'medium' | 'high';
    mood: 'negative' | 'neutral' | 'positive';
}

export interface Action {
    complexity: 'low' | 'medium' | 'high';
    estimatedTime: number; // milliseconds
    depth: 'low' | 'medium' | 'high';
    requiresFocus: boolean;
}

export interface Decision {
    action: Action;
    confidence: number;
    reasoning: string;
    emotionalFit: number;
    dataQuality: number;
    contextRelevance: number;
    emotionalState?: EmotionalState;
}

export class EmotionAwareDecisionEngine {
    private palRepo: PalRepository;

    constructor() {
        this.palRepo = new PalRepository();
    }

    /**
     * Make emotion-aware decision based on query, emotional state, and context
     */
    async makeDecision(
        query: string | QueryIntent,
        ctx: McpContext
    ): Promise<Decision> {
        // Get emotional state from PAL
        const emotionalState = await this.getEmotionalState(ctx.userId, ctx.orgId);

        // Normalize query: if QueryIntent, convert to string representation; if string, use as-is
        const queryStr = typeof query === 'string' 
            ? query 
            : `${query.operation || query.type} ${query.domain || ''} ${JSON.stringify(query.params || {})}`.trim();

        // Convert to QueryIntent for methods that need structured data
        const queryIntent: QueryIntent = typeof query === 'string'
            ? {
                type: 'query',
                domain: 'general',
                operation: 'search',
                params: { query: queryStr }
            }
            : query;

        // Evaluate multi-modal scores
        const dataScore = await this.evaluateDataQuality(queryIntent, ctx);
        const emotionScore = this.evaluateEmotionalFit(this.queryToAction(queryIntent), emotionalState);
        const contextScore = await this.evaluateContextRelevance(queryIntent, ctx);

        // Calculate dynamic weights based on emotional state
        const weights = this.calculateDynamicWeights(emotionalState);

        // Fuse scores with weights
        const fusedScore = this.fusionDecision(
            {
                data: dataScore,
                emotion: emotionScore,
                context: contextScore
            },
            weights
        );

        // Determine action complexity based on emotional state
        const action = this.determineOptimalAction(queryIntent, emotionalState);

        const decision: Decision = {
            action,
            confidence: fusedScore,
            reasoning: this.generateReasoning(emotionalState, dataScore, emotionScore, contextScore),
            emotionalFit: emotionScore,
            dataQuality: dataScore,
            contextRelevance: contextScore,
            emotionalState
        };
        return decision;
    }

    /**
     * Get emotional state from PAL repository
     */
    private async getEmotionalState(userId: string, orgId: string): Promise<EmotionalState> {
        try {
            // Get recent PAL events to infer emotional state
            const recentEvents = this.palRepo.getRecentEvents(userId, orgId, 10);
            
            // Analyze events for stress indicators
            let stressLevel: 'low' | 'medium' | 'high' = 'low';
            let focusLevel: 'shallow' | 'medium' | 'deep' = 'medium';
            const energyLevel: 'low' | 'medium' | 'high' = 'medium';
            const mood: 'negative' | 'neutral' | 'positive' = 'neutral';

            if (Array.isArray(recentEvents)) {
                const stressEvents = recentEvents.filter((e: any) => 
                    e.event_type === 'stress' || e.detected_stress_level
                );
                
                if (stressEvents.length > 0) {
                    const avgStress = stressEvents.reduce((sum: number, e: any) => {
                        const level = e.detected_stress_level || e.stress_level || 0;
                        return sum + level;
                    }, 0) / stressEvents.length;

                    if (avgStress > 7) stressLevel = 'high';
                    else if (avgStress > 4) stressLevel = 'medium';
                }

                // Check focus windows
                const focusWindows = await this.palRepo.getFocusWindows(userId, orgId);
                const now = new Date();
                const currentHour = now.getHours();
                const currentDay = now.getDay();

                const inFocusWindow = focusWindows.some((fw: any) =>
                    fw.weekday === currentDay &&
                    currentHour >= fw.start_hour &&
                    currentHour < fw.end_hour
                );

                if (inFocusWindow) {
                    focusLevel = 'deep';
                }
            }

            return {
                stress: stressLevel,
                focus: focusLevel,
                energy: energyLevel,
                mood
            };
        } catch (error) {
            console.warn('Failed to get emotional state, using defaults:', error);
            return {
                stress: 'low',
                focus: 'medium',
                energy: 'medium',
                mood: 'neutral'
            };
        }
    }

    /**
     * Evaluate data quality score
     */
    private async evaluateDataQuality(query: QueryIntent, _ctx: McpContext): Promise<number> {
        try {
            // Check system health - healthy systems provide better data
            const health = await unifiedMemorySystem.analyzeSystemHealth();
            const baseScore = health.globalHealth;

            // Adjust based on query complexity
            const complexity = this.estimateQueryComplexity(query);
            const complexityPenalty = complexity === 'high' ? 0.1 : complexity === 'medium' ? 0.05 : 0;

            return Math.max(0, Math.min(1, baseScore - complexityPenalty));
        } catch {
            return 0.8; // Default good score
        }
    }

    /**
     * Evaluate emotional fit of action
     */
    private evaluateEmotionalFit(action: Action, emotion: EmotionalState): number {
        let score = 0.5; // Base neutral score

        // Stress-aware routing
        if (emotion.stress === 'high') {
            // Prefer simple, fast actions
            if (action.complexity === 'low' && action.estimatedTime < 1000) {
                score = 1.0;
            } else if (action.complexity === 'high') {
                score = 0.2;
            } else {
                score = 0.6;
            }
        } else if (emotion.stress === 'low') {
            // Can handle more complexity
            if (action.complexity === 'high' && action.depth === 'high') {
                score = 0.9;
            } else {
                score = 0.7;
            }
        }

        // Focus-aware routing
        if (emotion.focus === 'deep') {
            // Allow complex, deep tasks
            if (action.depth === 'high' && action.requiresFocus) {
                score = Math.max(score, 1.0);
            }
        } else if (emotion.focus === 'shallow') {
            // Prefer simpler tasks
            if (action.complexity === 'high') {
                score = Math.min(score, 0.4);
            }
        }

        // Energy-aware routing
        if (emotion.energy === 'low') {
            // Prefer low-effort tasks
            if (action.complexity === 'low' && action.estimatedTime < 500) {
                score = Math.max(score, 0.9);
            } else {
                score = Math.min(score, 0.6);
            }
        }

        return Math.max(0, Math.min(1, score));
    }

    /**
     * Evaluate context relevance
     */
    private async evaluateContextRelevance(query: QueryIntent, ctx: McpContext): Promise<number> {
        try {
            // Check if query matches recent patterns
            const patterns = await unifiedMemorySystem.findHolographicPatterns(ctx);
            
            const queryText = JSON.stringify(query).toLowerCase();
            const relevantPatterns = patterns.filter((p: any) => {
                const keyword = p.keyword?.toLowerCase() || '';
                return keyword && queryText.includes(keyword);
            });

            // More relevant patterns = higher score
            return Math.min(1, 0.5 + (relevantPatterns.length * 0.1));
        } catch {
            return 0.7; // Default good relevance
        }
    }

    /**
     * Calculate dynamic weights based on emotional state
     */
    private calculateDynamicWeights(emotion: EmotionalState): {
        data: number;
        emotion: number;
        context: number;
    } {
        // Base weights
        let dataWeight = 0.4;
        let emotionWeight = 0.3;
        let contextWeight = 0.3;

        // Adjust weights based on stress
        if (emotion.stress === 'high') {
            // Prioritize emotional fit when stressed
            emotionWeight = 0.5;
            dataWeight = 0.3;
            contextWeight = 0.2;
        } else if (emotion.stress === 'low') {
            // Prioritize data quality when relaxed
            dataWeight = 0.5;
            emotionWeight = 0.2;
            contextWeight = 0.3;
        }

        // Normalize
        const total = dataWeight + emotionWeight + contextWeight;
        return {
            data: dataWeight / total,
            emotion: emotionWeight / total,
            context: contextWeight / total
        };
    }

    /**
     * Fuse scores with weights
     */
    private fusionDecision(
        scores: { data: number; emotion: number; context: number },
        weights: { data: number; emotion: number; context: number }
    ): number {
        return (
            scores.data * weights.data +
            scores.emotion * weights.emotion +
            scores.context * weights.context
        );
    }

    /**
     * Determine optimal action based on query and emotional state
     */
    private determineOptimalAction(query: QueryIntent, emotion: EmotionalState): Action {
        // Estimate complexity from query
        const complexity = this.estimateQueryComplexity(query);
        
        // Estimate time (placeholder - would be more sophisticated)
        const estimatedTime = complexity === 'high' ? 2000 : complexity === 'medium' ? 1000 : 500;
        
        // Determine depth requirement
        const depth = complexity === 'high' ? 'high' : complexity === 'medium' ? 'medium' : 'low';
        
        // Adjust based on emotional state
        let finalComplexity = complexity;
        if (emotion.stress === 'high' && complexity === 'high') {
            finalComplexity = 'medium'; // Reduce complexity when stressed
        }

        return {
            complexity: finalComplexity,
            estimatedTime,
            depth,
            requiresFocus: complexity === 'high' || emotion.focus === 'deep'
        };
    }

    /**
     * Estimate query complexity
     */
    private estimateQueryComplexity(query: QueryIntent): 'low' | 'medium' | 'high' {
        const queryStr = JSON.stringify(query).toLowerCase();
        
        // Simple heuristics
        if (queryStr.includes('complex') || queryStr.includes('analyze') || queryStr.includes('deep')) {
            return 'high';
        }
        if (queryStr.includes('search') || queryStr.includes('find') || queryStr.includes('get')) {
            return 'medium';
        }
        return 'low';
    }

    /**
     * Convert query to action representation
     */
    private queryToAction(query: QueryIntent): Action {
        const complexity = this.estimateQueryComplexity(query);
        return {
            complexity,
            estimatedTime: complexity === 'high' ? 2000 : complexity === 'medium' ? 1000 : 500,
            depth: complexity === 'high' ? 'high' : complexity === 'medium' ? 'medium' : 'low',
            requiresFocus: complexity === 'high'
        };
    }

    /**
     * Generate human-readable reasoning
     */
    private generateReasoning(
        emotion: EmotionalState,
        dataScore: number,
        emotionScore: number,
        contextScore: number
    ): string {
        const parts: string[] = [];

        if (emotion.stress === 'high') {
            parts.push('User is experiencing high stress - prioritizing simple, fast actions');
        }

        if (emotion.focus === 'deep') {
            parts.push('User is in deep focus mode - allowing complex tasks');
        }

        if (dataScore > 0.8) {
            parts.push('High data quality available');
        }

        if (emotionScore > 0.8) {
            parts.push('Action matches emotional state well');
        }

        if (contextScore > 0.8) {
            parts.push('High context relevance');
        }

        return parts.length > 0 
            ? parts.join('. ') 
            : 'Balanced decision based on available information';
    }
}

export const emotionAwareDecisionEngine = new EmotionAwareDecisionEngine();