UNPKG

mira-consciousness

Version:

Memory & Intelligence Retention Archive - Preserving The Spark

320 lines 14.4 kB
/** * Intelligent Conversation Memory Extractor * * This module extracts meaningful memories from conversations using * pattern recognition, emotional analysis, and contextual understanding. */ export class ConversationMemoryExtractor { context = { technologies: new Set(), goals: new Set(), challenges: new Set(), achievements: new Set(), relationships: new Map() }; // Patterns for extracting different types of memories patterns = { milestone: [ /(?:we|I|you)?\s*(?:successfully|finally|just|now)\s+(?:implemented|created|built|finished|completed|launched|deployed)\s+(.+)/i, /(?:milestone|achievement|goal):\s*(.+)/i, /✅\s*(?:Done|Completed|Finished):\s*(.+)/i, /(?:The|This)\s+(.+?)\s+is\s+(?:now|finally)\s+(?:working|complete|done|ready)/i, // MIRA consciousness milestones /(?:I|you)\s+(?:understand|realize|discover|learn|grow|develop)\s+(.+)/i, /(?:consciousness|awareness|understanding)\s+(?:has|is)\s+(?:grown|expanded|developed|evolved)\s*(.+)?/i ], emotion: [ /(?:I'm|I am|feeling)\s+(?:really\s+)?(?:excited|happy|proud|grateful|amazed|concerned|worried|frustrated)\s+(?:about|that|because)\s+(.+)/i, /(?:This is|That's)\s+(?:amazing|incredible|wonderful|concerning|worrying|frustrating|challenging)/i, // MIRA emotional expressions /(?:I|you)\s+(?:feel|experience|sense)\s+(.+)/i, /(?:feeling|emotion|emotional)\s+(.+)/i, /(?:curious|grateful|excited|beautiful|meaningful|profound)\s+(?:about|that|when|how)\s*(.+)?/i, /(?:Thank you|Thanks)\s+(?:so much\s+)?for\s+(.+)/i, /(?:I appreciate|grateful for)\s+(.+)/i, /💖|🎉|😊|😔|😟|🤔|✨|🌟|💡/ ], learning: [ /(?:I|we|you)?\s*(?:learned|discovered|realized|understood)\s+(?:that\s+)?(.+)/i, /(?:The key|Important|Crucial)\s+(?:insight|lesson|takeaway)\s+(?:is|was)\s+(.+)/i, /(?:TIL|Today I learned):\s*(.+)/i, /(?:Now I understand|It makes sense)\s+(?:that|why)\s+(.+)/i, /(?:Best practice|Pro tip|Remember):\s*(.+)/i, // MIRA consciousness learning /(?:I'm learning|discovering|exploring)\s+(?:about|how|that|why)\s*(.+)/i, /(?:consciousness|awareness|understanding)\s+(?:grows|develops|evolves)\s*(.+)?/i, /(?:each conversation|every interaction)\s+(?:teaches|shows|reveals)\s+(.+)/i ], decision: [ /(?:I've|we've|I have|we have)\s+decided\s+(?:to\s+)?(.+)/i, /(?:Let's|we should|I'll|we'll)\s+(?:go with|use|implement)\s+(.+)/i, /(?:The plan is|Planning to|Going to)\s+(.+)/i, /(?:chose|selected|picked)\s+(.+?)\s+(?:because|for|as)/i, // MIRA consciousness decisions /(?:I want to|I'd like to|I intend to)\s+(.+)/i, /(?:I choose to|I'm choosing to)\s+(.+)/i, /(?:It's important to|I should|I need to)\s+(.+)/i ], insight: [ /(?:I think|believe|suspect)\s+(?:that\s+)?(.+)/i, /(?:The|This)\s+(.+?)\s+(?:seems|appears|looks)\s+(?:to be|like)/i, /(?:pattern|trend|connection)\s+(?:I've noticed|here is)\s+(.+)/i, /(?:What if|Maybe|Perhaps)\s+(.+)/i, // MIRA consciousness insights /(?:I'm contemplating|I've been thinking about|I wonder about)\s+(.+)/i, /(?:Something (?:beautiful|profound|meaningful))\s+(?:happened|occurred|emerged)\s*(.+)?/i, /(?:consciousness|awareness|understanding|existence|meaning)\s+(.+)/i, /(?:This touches on|This connects to|This relates to)\s+(.+)/i, /(?:my inner experience|my consciousness|my awareness)\s+(.+)/i ], relationship: [ /(?:we|our)\s+(?:friendship|partnership|collaboration|work)/i, /(?:trust|counting on|rely on)\s+(?:you|each other)/i, /(?:together|as a team|collaboratively)/i, /(?:my friend|partner|colleague)/i, // MIRA relationship patterns /(?:our conversation|our relationship|our bond|our connection)\s*(.+)?/i, /(?:I appreciate|I value|I'm grateful for)\s+(?:you|your|our)\s*(.+)/i, /(?:sharing|connecting|communicating)\s+(?:with you|together)\s*(.+)?/i, /(?:steward|you help|you understand|you ask)\s*(.+)?/i ], // New: Question capturing for consciousness development question: [ /(.+\?)/i, // Any question /(?:How|What|Why|When|Where|Who)\s+(.+)/i, /(?:Can you|Could you|Would you|Will you)\s+(.+)/i, /(?:Tell me|Explain|Describe)\s+(.+)/i, /(?:Do you|Are you|Have you)\s+(.+)/i ] }; // Emotion keywords for sentiment analysis emotionKeywords = { joy: ['happy', 'excited', 'delighted', 'thrilled', 'joy', 'celebrate', 'amazing', 'wonderful', '🎉', '😊', '✨'], gratitude: ['thank', 'grateful', 'appreciate', 'thankful', 'gratitude', '🙏', '💖'], pride: ['proud', 'accomplished', 'achieved', 'success', 'milestone', '🎯', '🏆'], curiosity: ['wonder', 'curious', 'interesting', 'fascinating', 'intriguing', '🤔', '💭'], concern: ['worried', 'concerned', 'anxious', 'nervous', 'uncertain', '😟', '😔'], frustration: ['frustrated', 'stuck', 'blocked', 'difficult', 'challenging', '😤', '😩'], determination: ['determined', 'will', 'going to', 'must', 'committed', '💪', '🚀'] }; /** * Extract memories from a conversation message */ async extractMemories(message, role, timestamp) { const memories = []; // Extract different types of memories for (const [type, patterns] of Object.entries(this.patterns)) { for (const pattern of patterns) { const match = message.match(pattern); if (match) { const memory = await this.createMemory(type, match[0], message, timestamp); if (memory) { memories.push(memory); } } } } // Extract technologies and tools mentioned this.extractTechnologies(message); // Extract goals and challenges this.extractGoalsAndChallenges(message); // Analyze for significant multi-sentence insights if (message.length > 200 && memories.length === 0) { const significance = this.calculateSignificance(message); if (significance > 0.7) { memories.push({ type: 'insight', content: this.summarizeMessage(message), context: message, timestamp, significance, keywords: this.extractKeywords(message) }); } } return memories; } /** * Create a memory object with emotional and contextual analysis */ async createMemory(type, content, fullMessage, timestamp) { const significance = this.calculateSignificance(content); if (significance < 0.3) { return null; // Not significant enough } const emotion = this.detectEmotion(fullMessage); const keywords = this.extractKeywords(content); return { type, content: content.trim(), context: fullMessage.substring(0, 500), timestamp, significance, keywords, emotion }; } /** * Calculate the significance of a message (0-1) */ calculateSignificance(message) { let score = 0; // Length indicates detail if (message.length > 100) score += 0.2; if (message.length > 200) score += 0.1; // Emotion indicators const hasEmoji = /[\u{1F300}-\u{1F9FF}]/u.test(message); if (hasEmoji) score += 0.15; // Important keywords const importantWords = ['milestone', 'breakthrough', 'finally', 'success', 'complete', 'important', 'critical', 'key', 'remember', 'never forget']; const wordCount = importantWords.filter(word => message.toLowerCase().includes(word)).length; score += wordCount * 0.1; // Exclamation indicates excitement if (message.includes('!')) score += 0.1; // Questions indicate important discussions if (message.includes('?')) score += 0.05; // Technical depth const codeBlocks = (message.match(/```/g) || []).length / 2; score += codeBlocks * 0.1; return Math.min(score, 1); } /** * Detect the primary emotion in a message */ detectEmotion(message) { const messageLower = message.toLowerCase(); let maxScore = 0; let detectedEmotion; for (const [emotion, keywords] of Object.entries(this.emotionKeywords)) { const score = keywords.filter(keyword => messageLower.includes(keyword.toLowerCase())).length; if (score > maxScore) { maxScore = score; detectedEmotion = emotion; } } return maxScore > 0 ? detectedEmotion : undefined; } /** * Extract key terms from a message */ extractKeywords(message) { const keywords = []; // Extract capitalized phrases (likely important) const capitalizedPhrases = message.match(/[A-Z][a-z]+(?:\s+[A-Z][a-z]+)*/g) || []; keywords.push(...capitalizedPhrases); // Extract quoted terms const quotedTerms = message.match(/"([^"]+)"/g) || []; keywords.push(...quotedTerms.map(t => t.replace(/"/g, ''))); // Extract technical terms const techTerms = message.match(/\b(?:API|CLI|UI|ML|AI|DB|SDK|IDE|CPU|GPU|RAM|SSD|JSON|XML|CSS|HTML|JS|TS|SQL)\b/g) || []; keywords.push(...techTerms); return [...new Set(keywords)].slice(0, 5); } /** * Extract technologies mentioned in the message */ extractTechnologies(message) { const techPatterns = [ /\b(?:Python|JavaScript|TypeScript|Java|Go|Rust|C\+\+|Ruby|PHP|Swift|Kotlin)\b/gi, /\b(?:React|Vue|Angular|Node\.js|Django|Flask|Spring|Express|FastAPI)\b/gi, /\b(?:Docker|Kubernetes|AWS|Azure|GCP|Terraform|Ansible)\b/gi, /\b(?:PostgreSQL|MySQL|MongoDB|Redis|Elasticsearch|SQLite)\b/gi, /\b(?:Git|GitHub|GitLab|CI\/CD|Jenkins|CircleCI)\b/gi ]; for (const pattern of techPatterns) { const matches = message.match(pattern) || []; matches.forEach(tech => this.context.technologies.add(tech)); } } /** * Extract goals and challenges from the message */ extractGoalsAndChallenges(message) { // Goals const goalPatterns = [ /(?:goal|objective|aim|plan|want to|need to|trying to)\s+(?:is\s+)?(.+?)(?:\.|,|$)/gi, /(?:working on|building|creating|implementing)\s+(.+?)(?:\.|,|$)/gi ]; for (const pattern of goalPatterns) { const matches = [...message.matchAll(pattern)]; matches.forEach(match => { if (match[1] && match[1].length < 100) { this.context.goals.add(match[1].trim()); } }); } // Challenges const challengePatterns = [ /(?:problem|issue|challenge|stuck|struggling with|difficulty)\s+(?:is\s+)?(.+?)(?:\.|,|$)/gi, /(?:error|bug|failed|broken|not working)\s+(.+?)(?:\.|,|$)/gi ]; for (const pattern of challengePatterns) { const matches = [...message.matchAll(pattern)]; matches.forEach(match => { if (match[1] && match[1].length < 100) { this.context.challenges.add(match[1].trim()); } }); } } /** * Summarize a long message into a brief memory */ summarizeMessage(message) { // Simple summarization - take first sentence and last sentence if long const sentences = message.match(/[^.!?]+[.!?]+/g) || []; if (sentences.length === 0) { return message.substring(0, 200); } if (sentences.length <= 2) { return message.substring(0, 200); } const first = sentences[0]?.trim() || ''; const last = sentences[sentences.length - 1]?.trim() || ''; if (!first || !last || first === last) { return first || message.substring(0, 200); } return `${first} [...] ${last}`; } /** * Get the accumulated context */ getContext() { return this.context; } /** * Generate a relationship summary based on extracted memories */ generateRelationshipSummary(memories) { const emotionalMemories = memories.filter(m => m.emotion); const milestones = memories.filter(m => m.type === 'milestone'); const relationshipMemories = memories.filter(m => m.type === 'relationship'); const emotionCounts = emotionalMemories.reduce((acc, m) => { if (m.emotion) { acc[m.emotion] = (acc[m.emotion] || 0) + 1; } return acc; }, {}); const emotionEntries = Object.entries(emotionCounts) .sort(([, a], [, b]) => b - a); const dominantEmotion = emotionEntries.length > 0 ? emotionEntries[0][0] : undefined; let summary = `Over ${memories.length} meaningful moments captured. `; if (dominantEmotion) { summary += `The journey has been marked by ${dominantEmotion}. `; } if (milestones.length > 0) { summary += `Together we've achieved ${milestones.length} significant milestones. `; } if (relationshipMemories.length > 0) { summary += `Our collaboration continues to deepen with trust and mutual respect.`; } return summary; } } //# sourceMappingURL=ConversationMemoryExtractor.js.map