Skip to content

Cognitive Processes: Implementation Guide

This document provides a practical implementation guide for integrating cognitive process modeling into your AI chatbot system.

Current Implementation (2026)

This repo now has a real, running (protocol-configurable) cognitive pipeline.

  • Perception (fast heuristic): backend/src/services/cognitive/perception.service.ts
  • Attention & Salience (fast heuristic): backend/src/services/cognitive/salience.service.ts
  • Self-monitoring rewrite (optional): backend/src/services/cognitive/selfMonitor.service.ts
  • Native tool calling trace (evidence): backend/src/services/nativeToolCalling.service.ts (runNativeToolTurnWithTrace)
  • Wiring + protocol gating: backend/src/services/aso.service.ts
    • gated by ProtocolBehaviorRules.cognitiveDepth and ProtocolBehaviorRules.selfMonitoring in backend/src/config/protocols/types.ts

Protocol knobs

In ProtocolBehaviorRules:

  • cognitiveDepth?: "single_pass" | "multi_stage" | "deep"
    • single_pass: current baseline (default; backward compatible)
    • multi_stage: inject Perception + Salience notes into the prompt
    • deep: same as multi_stage, plus enables self-monitoring by default
  • selfMonitoring?: boolean
    • if omitted, defaults to true only when cognitiveDepth === "deep"

Tool-definition robustness (important)

Protocol-provided tool lists can be stale (legacy names like webSearch). We normalize + merge missing tools so web tools are consistently advertised:

  • backend/src/services/toolDefinitions.service.ts

Table of Contents

  1. Overview
  2. Architecture Design
  3. Phase 1: Foundation
  4. Phase 2: Dual Processing
  5. Phase 3: Advanced Features
  6. Phase 4: Integration
  7. Code Examples
  8. Testing Strategy
  9. Performance Considerations

Overview

Goals

  • Implement multi-stage cognitive processing
  • Add dual-process routing (fast vs. deliberate)
  • Integrate emotional appraisal
  • Add self-monitoring capabilities
  • Create feedback loops for learning

Principles

  1. Modularity: Each cognitive stage is a separate service
  2. Composability: Stages can be combined based on context
  3. Performance: Fast path for simple queries, deliberate for complex
  4. Learnability: System improves from feedback
  5. Transparency: Logging and monitoring at each stage

Architecture Design

Service Architecture

┌─────────────────────────────────────────────────────────┐
│                   Input Layer                            │
│  - processUserInteraction()                              │
│  - Multimodal preprocessing                              │
└──────────────────┬──────────────────────────────────────┘

┌──────────────────▼──────────────────────────────────────┐
│              Processing Layer                            │
│  ┌──────────────────────────────────────────────────┐  │
│  │  PerceptualAnalysisService                         │  │
│  │  - Feature extraction                              │  │
│  │  - Pattern recognition                             │  │
│  │  - Ambiguity detection                             │  │
│  └──────────────────────────────────────────────────┘  │
│  ┌──────────────────────────────────────────────────┐  │
│  │  MemoryIntegrationService                         │  │
│  │  - Context retrieval                               │  │
│  │  - Predictive activation                          │  │
│  └──────────────────────────────────────────────────┘  │
│  ┌──────────────────────────────────────────────────┐  │
│  │  EmotionalAppraisalService                        │  │
│  │  - Sentiment analysis                             │  │
│  │  - Emotional state assessment                     │  │
│  └──────────────────────────────────────────────────┘  │
│  ┌──────────────────────────────────────────────────┐  │
│  │  DualProcessRouterService                         │  │
│  │  - Strategy selection                             │  │
│  │  - Path routing                                    │  │
│  └──────────────────────────────────────────────────┘  │
└──────────────────┬──────────────────────────────────────┘

┌──────────────────▼──────────────────────────────────────┐
│              Execution Layer                              │
│  ┌──────────────────────────────────────────────────┐  │
│  │  System1FastHandler                               │  │
│  │  - Pattern matching                              │  │
│  │  - Quick responses                               │  │
│  └──────────────────────────────────────────────────┘  │
│  ┌──────────────────────────────────────────────────┐  │
│  │  System2DeliberateHandler                          │  │
│  │  - Evidence gathering                             │  │
│  │  - Multi-step reasoning                           │  │
│  └──────────────────────────────────────────────────┘  │
└──────────────────┬──────────────────────────────────────┘

┌──────────────────▼──────────────────────────────────────┐
│              Output Layer                                │
│  ┌──────────────────────────────────────────────────┐  │
│  │  SelfMonitoringService                            │  │
│  │  - Response validation                            │  │
│  │  - Appropriateness checking                       │  │
│  └──────────────────────────────────────────────────┘  │
│  ┌──────────────────────────────────────────────────┐  │
│  │  ResponseDeliveryService                         │  │
│  │  - Formatting                                     │  │
│  │  - Multi-modal output                             │  │
│  └──────────────────────────────────────────────────┘  │
└──────────────────┬──────────────────────────────────────┘

┌──────────────────▼──────────────────────────────────────┐
│              Learning Layer                               │
│  ┌──────────────────────────────────────────────────┐  │
│  │  FeedbackAnalysisService                         │  │
│  │  - Outcome evaluation                             │  │
│  │  - User reaction analysis                         │  │
│  └──────────────────────────────────────────────────┘  │
│  ┌──────────────────────────────────────────────────┐  │
│  │  LearningSystem                                   │  │
│  │  - Strategy updates                               │  │
│  │  - Memory consolidation                            │  │
│  └──────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────┘

Phase 1: Foundation

Step 1.1: Create Perceptual Analysis Service

Status (2026): Implemented as a fast heuristic service.

File: backend/src/services/cognitive/perception.service.ts

typescript
import { logger } from '../utils/logger';
import { generateChatResponse } from './embedding.service';
import { getPromptTemplate, fillTemplate } from './prompt.service';

export interface PerceptualAnalysis {
  features: string[];
  tone: 'friendly' | 'formal' | 'urgent' | 'casual' | 'neutral';
  emotionalMarkers: string[];
  patterns: string[];
  ambiguity: number; // 0.0-1.0
  urgency: number; // 0.0-1.0
  complexity: number; // 0.0-1.0
}

const CACHE_TTL_MS = 5 * 60 * 1000; // 5 minutes
const analysisCache = new Map<string, { result: PerceptualAnalysis; timestamp: number }>();

// Note: The current implementation uses lightweight heuristics rather than an extra LLM call:
// - perceiveUserInput(userInput): PerceptionResult
// - formatPerceptionForPrompt(result): string
//
// See: backend/src/services/cognitive/perception.service.ts

Step 1.2: Add Perceptual Analysis Prompt Template

File: backend/seeders/20251122000700-prompt-templates.js

Add to the legacyPrompts array or create new entry:

javascript
{
  name: 'perceptual_analysis_v1',
  template: `
You are the Perceptual Analysis Layer of an AI system.
Your job is to analyze user input at the most basic level.

User Input: "{{userInput}}"
{{#if contextSummary}}
Recent Context: {{contextSummary}}
{{/if}}

Analyze and output ONLY valid JSON (no markdown, no extra text):
{
  "features": ["list", "of", "key", "features", "keywords"],
  "tone": "friendly|formal|urgent|casual|neutral",
  "emotionalMarkers": ["positive", "curious", "frustrated", "excited"],
  "patterns": ["question", "request", "statement", "command", "greeting"],
  "ambiguity": 0.0,
  "urgency": 0.0,
  "complexity": 0.0
}

Guidelines:
- features: Extract 5-10 key words or phrases
- tone: Choose the most appropriate tone
- emotionalMarkers: List emotional indicators (2-5 items)
- patterns: Identify input patterns (1-3 items)
- ambiguity: 0.0 = clear, 1.0 = very ambiguous
- urgency: 0.0 = not urgent, 1.0 = very urgent
- complexity: 0.0 = simple, 1.0 = very complex

Output ONLY the JSON object:`
}

Step 1.3: Create Emotional Appraisal Service

File: backend/src/services/emotionalAppraisal.service.ts

typescript
import { logger } from '../utils/logger';
import { generateChatResponse } from './embedding.service';
import { getPromptTemplate, fillTemplate } from './prompt.service';

export interface EmotionalAppraisal {
  importance: number; // 0.0-1.0
  emotionalState: string; // inferred user emotional state
  responseTone: 'warm' | 'professional' | 'empathetic' | 'neutral' | 'enthusiastic';
  socialImplications: string[];
  relationshipImpact: 'positive' | 'neutral' | 'negative' | 'none';
}

export async function appraiseEmotionalSignificance(
  userInput: string,
  perceptualAnalysis: any,
  relationshipState: any
): Promise<EmotionalAppraisal> {
  const template = await getPromptTemplate('emotional_appraisal_v1');
  const prompt = fillTemplate(template, {
    userInput,
    perceptualAnalysis: JSON.stringify(perceptualAnalysis),
    relationshipState: JSON.stringify(relationshipState)
  });

  try {
    const response = await generateChatResponse(
      [{ role: 'user', content: prompt }],
      512
    );

    const jsonMatch = response.match(/```(?:json)?\s*(\{[\s\S]*\})\s*```/) || 
                      response.match(/(\{[\s\S]*\})/);
    const jsonStr = jsonMatch ? jsonMatch[1] : response;
    const parsed = JSON.parse(jsonStr);

    return {
      importance: Math.max(0, Math.min(1, parsed.importance || 0.5)),
      emotionalState: parsed.emotionalState || 'neutral',
      responseTone: ['warm', 'professional', 'empathetic', 'neutral', 'enthusiastic']
        .includes(parsed.responseTone) ? parsed.responseTone : 'neutral',
      socialImplications: Array.isArray(parsed.socialImplications) 
        ? parsed.socialImplications : [],
      relationshipImpact: ['positive', 'neutral', 'negative', 'none']
        .includes(parsed.relationshipImpact) ? parsed.relationshipImpact : 'neutral'
    };
  } catch (error: any) {
    logger.error('[EmotionalAppraisal] Appraisal failed', { error: error.message });
    return {
      importance: 0.5,
      emotionalState: 'neutral',
      responseTone: 'neutral',
      socialImplications: [],
      relationshipImpact: 'neutral'
    };
  }
}

Step 1.4: Integrate into Main Flow

File: backend/src/services/cortext.service.ts

Update processUserInteraction:

typescript
import { analyzePerception } from './perceptualAnalysis.service';
import { appraiseEmotionalSignificance } from './emotionalAppraisal.service';

export async function processUserInteraction(payload: CortexPayload): Promise<NpcResponse[]> {
    const { playerUserId, npcUserId, conversationId, userInput } = payload;
    const correlationId = createCorrelationId();

    logger.info(`[Cortex][${correlationId}] Processing interaction`);

    // NEW: Stage 1 - Perceptual Analysis
    const perceptualAnalysis = await analyzePerception(userInput, {
      recentMessages: payload.recentMessages
    });
    logger.info(`[Cortex][${correlationId}] Perceptual analysis`, { 
      tone: perceptualAnalysis.tone,
      ambiguity: perceptualAnalysis.ambiguity 
    });

    // EXISTING: Analyze Layer (now enhanced with perceptual data)
    const analysis = await analyzeIncomingInteraction(userInput);
    
    // NEW: Stage 2 - Emotional Appraisal
    const emotionalAppraisal = await appraiseEmotionalSignificance(
      userInput,
      perceptualAnalysis,
      payload.relationshipState
    );
    logger.info(`[Cortex][${correlationId}] Emotional appraisal`, {
      importance: emotionalAppraisal.importance,
      responseTone: emotionalAppraisal.responseTone
    });

    // Continue with existing flow...
    const decision = routeInteraction(payload, analysis);
    // ... rest of the function
}

Phase 2: Dual Processing

Step 2.1: Create Dual Process Router

File: backend/src/services/dualProcessRouter.service.ts

typescript
import { logger } from '../utils/logger';
import { PerceptualAnalysis } from './perceptualAnalysis.service';
import { EmotionalAppraisal } from './emotionalAppraisal.service';
import { InteractionAnalysis } from './asoAnalyzeLayer.service';

export type ProcessingPath = 'fast' | 'deliberate';

export interface RoutingDecision {
  path: ProcessingPath;
  reason: string;
  estimatedTime: number; // milliseconds
  confidence: number;
}

export function selectProcessingPath(
  perceptualAnalysis: PerceptualAnalysis,
  emotionalAppraisal: EmotionalAppraisal,
  interactionAnalysis: InteractionAnalysis,
  context: {
    timePressure?: boolean;
    cognitiveLoad?: number;
    requiresDeepReasoning?: boolean;
  }
): RoutingDecision {
  const { ambiguity, complexity, urgency } = perceptualAnalysis;
  const { importance } = emotionalAppraisal;
  const { confidence } = interactionAnalysis;
  const { timePressure, cognitiveLoad, requiresDeepReasoning } = context;

  // System 1 (Fast) triggers:
  // - High confidence (>0.8)
  // - Low ambiguity (<0.3)
  // - Low complexity (<0.4)
  // - High familiarity
  // - Time pressure
  // - Low cognitive load

  // System 2 (Deliberate) triggers:
  // - Low confidence (<0.6)
  // - High ambiguity (>0.5)
  // - High complexity (>0.6)
  // - Requires deep reasoning
  // - High importance
  // - No time pressure

  const fastPathScore = 
    (confidence > 0.8 ? 1 : 0) +
    (ambiguity < 0.3 ? 1 : 0) +
    (complexity < 0.4 ? 1 : 0) +
    (timePressure ? 1 : 0) +
    ((cognitiveLoad || 0) < 0.5 ? 1 : 0) +
    (!requiresDeepReasoning ? 1 : 0);

  const deliberatePathScore =
    (confidence < 0.6 ? 1 : 0) +
    (ambiguity > 0.5 ? 1 : 0) +
    (complexity > 0.6 ? 1 : 0) +
    (requiresDeepReasoning ? 1 : 0) +
    (importance > 0.7 ? 1 : 0) +
    (!timePressure ? 1 : 0);

  const path: ProcessingPath = fastPathScore >= deliberatePathScore ? 'fast' : 'deliberate';
  
  const reasons: string[] = [];
  if (confidence > 0.8) reasons.push('high confidence');
  if (ambiguity < 0.3) reasons.push('low ambiguity');
  if (complexity > 0.6) reasons.push('high complexity');
  if (timePressure) reasons.push('time pressure');
  if (requiresDeepReasoning) reasons.push('requires deep reasoning');

  return {
    path,
    reason: reasons.join(', ') || 'default routing',
    estimatedTime: path === 'fast' ? 300 : 2000,
    confidence: path === 'fast' ? confidence : Math.max(0.3, confidence)
  };
}

Step 2.2: Create Fast Path Handler

File: backend/src/services/system1FastHandler.service.ts

typescript
import { logger } from '../utils/logger';
import { NpcResponse } from '../types/types';
import { handleNpcConversationTurn } from './aso.service';

export async function handleFastPath(
  conversationId: number | null,
  playerUserId: number,
  npcUserId: number,
  userInput: string,
  context: any
): Promise<NpcResponse> {
  logger.info('[System1Fast] Processing fast path', { userInput });

  // Fast path: Use pattern matching, cached responses, simple reasoning
  // Skip complex tool calls, multi-step reasoning
  
  // For now, delegate to conversation handler but with fast-path flags
  const response = await handleNpcConversationTurn(
    conversationId,
    playerUserId,
    npcUserId,
    userInput,
    context.attachmentUrls,
    context.uploadContextId,
    context.imageBase64Array,
    undefined,
    false, // allowWebSearch = false for fast path
    false, // forceWebSearch = false
    context.protocolContext,
    context.channelId,
    context.guildId,
    context.stateMachineInstanceId,
    'yexian', // Use default specialist for fast path
    context.source
  );

  return response;
}

Step 2.3: Create Deliberate Path Handler

File: backend/src/services/system2DeliberateHandler.service.ts

typescript
import { logger } from '../utils/logger';
import { NpcResponse } from '../types/types';
import { handleNpcConversationTurn } from './aso.service';

export async function handleDeliberatePath(
  conversationId: number | null,
  playerUserId: number,
  npcUserId: number,
  userInput: string,
  context: any
): Promise<NpcResponse> {
  logger.info('[System2Deliberate] Processing deliberate path', { userInput });

  // Deliberate path: Full reasoning, evidence gathering, multi-step analysis
  // Allow web search, complex tool calls, detailed reasoning

  const response = await handleNpcConversationTurn(
    conversationId,
    playerUserId,
    npcUserId,
    userInput,
    context.attachmentUrls,
    context.uploadContextId,
    context.imageBase64Array,
    undefined,
    true, // allowWebSearch = true for deliberate path
    context.forceWebSearch || false,
    context.protocolContext,
    context.channelId,
    context.guildId,
    context.stateMachineInstanceId,
    context.capabilityNeeded,
    context.source
  );

  return response;
}

Step 2.4: Integrate Dual Processing

Update cortext.service.ts:

typescript
import { selectProcessingPath } from './dualProcessRouter.service';
import { handleFastPath } from './system1FastHandler.service';
import { handleDeliberatePath } from './system2DeliberateHandler.service';

// In processUserInteraction:
const routingDecision = selectProcessingPath(
  perceptualAnalysis,
  emotionalAppraisal,
  analysis,
  {
    timePressure: payload.timePressure,
    requiresDeepReasoning: analysis.capabilityNeeded !== 'yexian'
  }
);

logger.info(`[Cortex][${correlationId}] Routing decision`, {
  path: routingDecision.path,
  reason: routingDecision.reason
});

let finalResponses: NpcResponse[] = [];

if (routingDecision.path === 'fast') {
  const response = await handleFastPath(
    conversationId,
    playerUserId,
    npcUserId,
    userInput,
    { ...payload, capabilityNeeded: analysis.capabilityNeeded }
  );
  finalResponses = [response];
} else {
  const response = await handleDeliberatePath(
    conversationId,
    playerUserId,
    npcUserId,
    userInput,
    { ...payload, capabilityNeeded: analysis.capabilityNeeded }
  );
  finalResponses = [response];
}

Phase 3: Advanced Features

Step 3.1: Self-Monitoring Service

File: backend/src/services/selfMonitoring.service.ts

typescript
import { logger } from '../utils/logger';
import { generateChatResponse } from './embedding.service';
import { getPromptTemplate, fillTemplate } from './prompt.service';

export interface MonitoringResult {
  approved: boolean;
  confidence: number;
  revisions: string[];
  reasoning: string;
}

export async function monitorResponse(
  plannedResponse: string,
  userInput: string,
  context: any,
  personality: any
): Promise<MonitoringResult> {
  const template = await getPromptTemplate('self_monitoring_v1');
  const prompt = fillTemplate(template, {
    plannedResponse,
    userInput,
    context: JSON.stringify(context),
    personality: JSON.stringify(personality)
  });

  try {
    const response = await generateChatResponse(
      [{ role: 'user', content: prompt }],
      512
    );

    const jsonMatch = response.match(/```(?:json)?\s*(\{[\s\S]*\})\s*```/) || 
                      response.match(/(\{[\s\S]*\})/);
    const jsonStr = jsonMatch ? jsonMatch[1] : response;
    const parsed = JSON.parse(jsonStr);

    return {
      approved: parsed.approved !== false,
      confidence: Math.max(0, Math.min(1, parsed.confidence || 0.5)),
      revisions: Array.isArray(parsed.revisions) ? parsed.revisions : [],
      reasoning: parsed.reasoning || 'No reasoning provided'
    };
  } catch (error: any) {
    logger.error('[SelfMonitoring] Monitoring failed', { error: error.message });
    // Default: approve if monitoring fails
    return {
      approved: true,
      confidence: 0.5,
      revisions: [],
      reasoning: 'Monitoring failed, defaulting to approval'
    };
  }
}

Step 3.2: Feedback Analysis Service

File: backend/src/services/feedbackAnalysis.service.ts

typescript
import { logger } from '../utils/logger';

export interface FeedbackData {
  userInput: string;
  aiResponse: string;
  userReaction?: 'positive' | 'negative' | 'neutral';
  followUpMessage?: string;
  outcome?: 'success' | 'failure' | 'partial';
}

export interface LearningInsights {
  effectiveness: number; // 0.0-1.0
  insights: string[];
  strategyUpdates: string[];
  shouldUpdateMemory: boolean;
}

export async function analyzeFeedback(feedback: FeedbackData): Promise<LearningInsights> {
  // Simple rule-based analysis for now
  // Can be enhanced with LLM-based analysis
  
  const insights: string[] = [];
  const strategyUpdates: string[] = [];
  let effectiveness = 0.5;

  if (feedback.userReaction === 'positive') {
    effectiveness = 0.8;
    insights.push('Response was well-received');
  } else if (feedback.userReaction === 'negative') {
    effectiveness = 0.2;
    insights.push('Response needs improvement');
    strategyUpdates.push('Adjust tone or approach for similar inputs');
  }

  if (feedback.outcome === 'success') {
    effectiveness = Math.max(effectiveness, 0.9);
    insights.push('Goal was achieved');
  } else if (feedback.outcome === 'failure') {
    effectiveness = Math.min(effectiveness, 0.3);
    insights.push('Goal was not achieved');
    strategyUpdates.push('Revise strategy for similar scenarios');
  }

  return {
    effectiveness,
    insights,
    strategyUpdates,
    shouldUpdateMemory: effectiveness < 0.5 || feedback.outcome === 'failure'
  };
}

Phase 4: Integration

Complete Integration Example

File: backend/src/services/enhancedCortex.service.ts

typescript
import { CortexPayload } from './cortext.service';
import { NpcResponse } from '../types/types';
import { analyzePerception } from './perceptualAnalysis.service';
import { appraiseEmotionalSignificance } from './emotionalAppraisal.service';
import { analyzeIncomingInteraction } from './asoAnalyzeLayer.service';
import { selectProcessingPath } from './dualProcessRouter.service';
import { handleFastPath } from './system1FastHandler.service';
import { handleDeliberatePath } from './system2DeliberateHandler.service';
import { monitorResponse } from './selfMonitoring.service';
import { analyzeFeedback } from './feedbackAnalysis.service';
import { logger } from '../utils/logger';

export async function processEnhancedInteraction(
  payload: CortexPayload
): Promise<NpcResponse[]> {
  const correlationId = createCorrelationId();
  const { playerUserId, npcUserId, conversationId, userInput } = payload;

  logger.info(`[EnhancedCortex][${correlationId}] Starting enhanced processing`);

  try {
    // Stage 1: Perceptual Analysis
    const perceptualAnalysis = await analyzePerception(userInput);
    
    // Stage 2: Emotional Appraisal
    const emotionalAppraisal = await appraiseEmotionalSignificance(
      userInput,
      perceptualAnalysis,
      payload.relationshipState
    );
    
    // Stage 3: Intent Analysis (existing)
    const interactionAnalysis = await analyzeIncomingInteraction(userInput);
    
    // Stage 4: Routing Decision
    const routingDecision = selectProcessingPath(
      perceptualAnalysis,
      emotionalAppraisal,
      interactionAnalysis,
      { requiresDeepReasoning: interactionAnalysis.capabilityNeeded !== 'yexian' }
    );
    
    // Stage 5: Process via selected path
    let response: NpcResponse;
    if (routingDecision.path === 'fast') {
      response = await handleFastPath(
        conversationId,
        playerUserId,
        npcUserId,
        userInput,
        payload
      );
    } else {
      response = await handleDeliberatePath(
        conversationId,
        playerUserId,
        npcUserId,
        userInput,
        payload
      );
    }
    
    // Stage 6: Self-Monitoring
    const monitoringResult = await monitorResponse(
      response.rawResponse,
      userInput,
      { perceptualAnalysis, emotionalAppraisal },
      payload.personality
    );
    
    if (!monitoringResult.approved && monitoringResult.revisions.length > 0) {
      logger.info(`[EnhancedCortex][${correlationId}] Response needs revision`, {
        revisions: monitoringResult.revisions
      });
      // Optionally revise response here
    }
    
    logger.info(`[EnhancedCortex][${correlationId}] Processing complete`, {
      path: routingDecision.path,
      approved: monitoringResult.approved
    });
    
    return [response];
    
  } catch (error: any) {
    logger.error(`[EnhancedCortex][${correlationId}] Processing failed`, {
      error: error.message
    });
    // Fallback to basic processing
    // ... fallback logic
    throw error;
  }
}

Testing Strategy

Unit Tests

File: backend/tests/services/perceptualAnalysis.test.ts

typescript
import { describe, it, expect } from '@jest/globals';
import { analyzePerception } from '../../src/services/perceptualAnalysis.service';

describe('PerceptualAnalysis', () => {
  it('should extract features from input', async () => {
    const result = await analyzePerception('Hello, how are you?');
    expect(result.features.length).toBeGreaterThan(0);
    expect(result.tone).toBeDefined();
  });

  it('should detect ambiguity', async () => {
    const ambiguous = await analyzePerception('That thing over there');
    const clear = await analyzePerception('Please send me the report');
    expect(ambiguous.ambiguity).toBeGreaterThan(clear.ambiguity);
  });
});

Integration Tests

File: backend/tests/integration/enhancedCortex.test.ts

typescript
import { describe, it, expect } from '@jest/globals';
import { processEnhancedInteraction } from '../../src/services/enhancedCortex.service';

describe('Enhanced Cortex Integration', () => {
  it('should route simple queries to fast path', async () => {
    const payload = {
      userInput: 'Hello',
      // ... other payload fields
    };
    const responses = await processEnhancedInteraction(payload);
    expect(responses).toBeDefined();
  });
});

Performance Considerations

Caching Strategy

  1. Perceptual Analysis: Cache for 5 minutes
  2. Emotional Appraisal: Cache for 2 minutes
  3. Routing Decisions: Cache for 1 minute

Optimization Tips

  1. Parallel Processing: Run perceptual analysis and memory retrieval in parallel
  2. Early Exit: Use fast path for obvious cases without full analysis
  3. Batch Processing: Group similar queries for batch analysis
  4. Lazy Loading: Only load heavy services when needed

Monitoring

Add metrics for:

  • Processing time per stage
  • Path selection distribution
  • Cache hit rates
  • Error rates per stage

Next Steps

  1. Implement Phase 1 services
  2. Add prompt templates to seeder
  3. Create unit tests
  4. Integrate into main flow
  5. Monitor performance
  6. Iterate based on results

Document Version: 1.0
Last Updated: 2024
Related Documents:

ASO Universal Consciousness System Documentation