engram-core 0.19.0

AI Memory Infrastructure - Persistent memory for AI agents with semantic search
Documentation
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
//! Auto-Capture Mode for Proactive Memory (RML-903)
//!
//! Automatically detects and captures valuable information from conversations:
//! - Key decisions and their rationale
//! - Action items and todos
//! - Important facts and context
//! - User preferences and patterns
//! - Technical learnings and insights

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::collections::HashSet;

use crate::types::{Memory, MemoryType};

/// Configuration for auto-capture behavior
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AutoCaptureConfig {
    /// Enable auto-capture mode
    pub enabled: bool,
    /// Minimum confidence threshold for capture (0.0 - 1.0)
    pub min_confidence: f32,
    /// Types of content to capture
    pub capture_types: HashSet<CaptureType>,
    /// Maximum captures per conversation turn
    pub max_per_turn: usize,
    /// Require user confirmation before saving
    pub require_confirmation: bool,
    /// Keywords that trigger capture consideration
    pub trigger_keywords: Vec<String>,
    /// Patterns to ignore (e.g., greetings, small talk)
    pub ignore_patterns: Vec<String>,
}

impl Default for AutoCaptureConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            min_confidence: 0.6,
            capture_types: vec![
                CaptureType::Decision,
                CaptureType::ActionItem,
                CaptureType::KeyFact,
                CaptureType::Preference,
                CaptureType::Learning,
            ]
            .into_iter()
            .collect(),
            max_per_turn: 3,
            require_confirmation: true,
            trigger_keywords: vec![
                "decide".to_string(),
                "decided".to_string(),
                "decision".to_string(),
                "todo".to_string(),
                "remember".to_string(),
                "important".to_string(),
                "always".to_string(),
                "never".to_string(),
                "prefer".to_string(),
                "learned".to_string(),
                "note".to_string(),
                "key".to_string(),
                "critical".to_string(),
                "must".to_string(),
                "should".to_string(),
            ],
            ignore_patterns: vec![
                "hello".to_string(),
                "hi".to_string(),
                "thanks".to_string(),
                "thank you".to_string(),
                "bye".to_string(),
                "goodbye".to_string(),
                "ok".to_string(),
                "okay".to_string(),
                "sure".to_string(),
                "yes".to_string(),
                "no".to_string(),
            ],
        }
    }
}

/// Types of content that can be auto-captured
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum CaptureType {
    /// A decision made during conversation
    Decision,
    /// An action item or task to do
    ActionItem,
    /// An important fact or piece of context
    KeyFact,
    /// A user preference or pattern
    Preference,
    /// A technical learning or insight
    Learning,
    /// A question for follow-up
    Question,
    /// An issue or problem identified
    Issue,
    /// A code snippet or technical artifact
    CodeSnippet,
}

impl CaptureType {
    /// Convert to MemoryType for storage
    pub fn to_memory_type(&self) -> MemoryType {
        match self {
            CaptureType::Decision => MemoryType::Decision,
            CaptureType::ActionItem => MemoryType::Todo,
            CaptureType::KeyFact => MemoryType::Note,
            CaptureType::Preference => MemoryType::Preference,
            CaptureType::Learning => MemoryType::Learning,
            CaptureType::Question => MemoryType::Note,
            CaptureType::Issue => MemoryType::Issue,
            CaptureType::CodeSnippet => MemoryType::Note,
        }
    }

    /// Get detection patterns for this type
    fn patterns(&self) -> Vec<&'static str> {
        match self {
            CaptureType::Decision => vec![
                "decided to",
                "decision is",
                "we'll go with",
                "let's use",
                "the approach is",
                "we chose",
                "going forward",
                "from now on",
            ],
            CaptureType::ActionItem => vec![
                "todo:",
                "action item:",
                "need to",
                "should do",
                "will do",
                "must do",
                "task:",
                "follow up",
                "remember to",
            ],
            CaptureType::KeyFact => vec![
                "important:",
                "note:",
                "key point",
                "the fact is",
                "actually,",
                "turns out",
                "discovered that",
                "found that",
            ],
            CaptureType::Preference => vec![
                "prefer",
                "like to",
                "always use",
                "never use",
                "my style",
                "i want",
                "i don't want",
                "please always",
                "please never",
            ],
            CaptureType::Learning => vec![
                "learned that",
                "til:",
                "today i learned",
                "insight:",
                "realization:",
                "now i understand",
                "turns out that",
            ],
            CaptureType::Question => vec![
                "question:",
                "need to find out",
                "investigate",
                "look into",
                "figure out",
                "unclear about",
            ],
            CaptureType::Issue => vec![
                "bug:",
                "issue:",
                "problem:",
                "error:",
                "broken:",
                "doesn't work",
                "failing",
            ],
            CaptureType::CodeSnippet => vec![
                "```", "code:", "snippet:", "function", "class", "const", "let", "fn ",
            ],
        }
    }
}

/// A candidate for auto-capture
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CaptureCandidate {
    /// The content to potentially capture
    pub content: String,
    /// Detected type
    pub capture_type: CaptureType,
    /// Confidence score (0.0 - 1.0)
    pub confidence: f32,
    /// Source context (where it came from)
    pub source: String,
    /// Suggested tags
    pub suggested_tags: Vec<String>,
    /// Suggested importance (0.0 - 1.0)
    pub suggested_importance: f32,
    /// Detection timestamp
    pub detected_at: DateTime<Utc>,
    /// Reason for capture
    pub reason: String,
}

impl CaptureCandidate {
    /// Convert to a Memory for storage
    pub fn to_memory(&self) -> Memory {
        Memory {
            id: 0, // Will be assigned by storage
            content: self.content.clone(),
            memory_type: self.capture_type.to_memory_type(),
            tags: self.suggested_tags.clone(),
            metadata: std::collections::HashMap::new(),
            importance: self.suggested_importance,
            access_count: 0,
            created_at: chrono::Utc::now(),
            updated_at: chrono::Utc::now(),
            last_accessed_at: None,
            owner_id: None,
            visibility: crate::types::Visibility::Private,
            scope: crate::types::MemoryScope::Global,
            workspace: "default".to_string(),
            tier: crate::types::MemoryTier::Permanent,
            version: 1,
            has_embedding: false,
            expires_at: None,
            content_hash: None, // Will be computed on storage
            event_time: None,
            event_duration_seconds: None,
            trigger_pattern: None,
            procedure_success_count: 0,
            procedure_failure_count: 0,
            summary_of_id: None,
            lifecycle_state: crate::types::LifecycleState::Active,
            media_url: None,
        }
    }
}

/// Auto-capture engine
pub struct AutoCaptureEngine {
    config: AutoCaptureConfig,
}

impl AutoCaptureEngine {
    pub fn new(config: AutoCaptureConfig) -> Self {
        Self { config }
    }

    pub fn with_default_config() -> Self {
        Self::new(AutoCaptureConfig::default())
    }

    /// Analyze text and detect potential captures
    pub fn analyze(&self, text: &str, source: &str) -> Vec<CaptureCandidate> {
        if !self.config.enabled {
            return Vec::new();
        }

        // Skip if matches ignore patterns
        let text_lower = text.to_lowercase();
        if self.should_ignore(&text_lower) {
            return Vec::new();
        }

        let mut candidates = Vec::new();

        // Check each capture type
        for capture_type in &self.config.capture_types {
            if let Some(candidate) = self.detect_type(text, &text_lower, *capture_type, source) {
                if candidate.confidence >= self.config.min_confidence {
                    candidates.push(candidate);
                }
            }
        }

        // Sort by confidence and limit
        candidates.sort_by(|a, b| b.confidence.total_cmp(&a.confidence));
        candidates.truncate(self.config.max_per_turn);

        candidates
    }

    /// Check if text should be ignored
    fn should_ignore(&self, text_lower: &str) -> bool {
        // Too short
        if text_lower.len() < 10 {
            return true;
        }

        // Matches ignore patterns
        for pattern in &self.config.ignore_patterns {
            if text_lower.trim() == pattern.as_str() {
                return true;
            }
        }

        false
    }

    /// Detect a specific capture type
    fn detect_type(
        &self,
        text: &str,
        text_lower: &str,
        capture_type: CaptureType,
        source: &str,
    ) -> Option<CaptureCandidate> {
        let patterns = capture_type.patterns();
        let mut confidence: f32 = 0.0;
        let mut matched_pattern = "";

        // Check patterns
        for pattern in patterns {
            if text_lower.contains(pattern) {
                confidence = 0.7;
                matched_pattern = pattern;
                break;
            }
        }

        // Boost confidence for trigger keywords
        let trigger_count = self
            .config
            .trigger_keywords
            .iter()
            .filter(|kw| text_lower.contains(kw.as_str()))
            .count();
        confidence += (trigger_count as f32 * 0.05).min(0.2);

        // Boost for explicit markers
        if text_lower.contains("remember:") || text_lower.contains("important:") {
            confidence += 0.15;
        }

        // Minimum threshold check
        if confidence < 0.3 {
            return None;
        }

        // Extract the relevant content
        let content = self.extract_content(text, capture_type);
        if content.is_empty() {
            return None;
        }

        // Suggest tags based on content
        let suggested_tags = self.suggest_tags(&content, capture_type);

        // Calculate importance
        let suggested_importance = self.calculate_importance(&content, capture_type, confidence);

        Some(CaptureCandidate {
            content,
            capture_type,
            confidence: confidence.min(1.0),
            source: source.to_string(),
            suggested_tags,
            suggested_importance,
            detected_at: Utc::now(),
            reason: format!("Matched pattern: '{}'", matched_pattern),
        })
    }

    /// Extract the relevant content for capture
    fn extract_content(&self, text: &str, capture_type: CaptureType) -> String {
        let text_lower = text.to_lowercase();

        // Try to extract after common markers
        let markers = match capture_type {
            CaptureType::Decision => vec!["decided to", "decision:", "we'll"],
            CaptureType::ActionItem => vec!["todo:", "action:", "need to"],
            CaptureType::KeyFact => vec!["important:", "note:", "key:"],
            CaptureType::Preference => vec!["prefer", "always", "never"],
            CaptureType::Learning => vec!["learned", "til:", "insight:"],
            CaptureType::Question => vec!["question:", "investigate"],
            CaptureType::Issue => vec!["bug:", "issue:", "problem:"],
            CaptureType::CodeSnippet => vec!["```", "code:"],
        };

        for marker in markers {
            if let Some(pos) = text_lower.find(marker) {
                let start = pos + marker.len();
                let extracted = text[start..].trim();
                // Take until end of sentence or paragraph
                let end = extracted
                    .find(|c: char| c == '\n' || c == '.' && extracted.len() > 10)
                    .unwrap_or(extracted.len().min(500));
                return extracted[..end].trim().to_string();
            }
        }

        // If no marker found, use the whole text (truncated)
        let max_len = 500;
        if text.len() <= max_len {
            text.trim().to_string()
        } else {
            format!("{}...", &text[..max_len].trim())
        }
    }

    /// Suggest tags based on content
    fn suggest_tags(&self, content: &str, capture_type: CaptureType) -> Vec<String> {
        let mut tags = Vec::new();
        let content_lower = content.to_lowercase();

        // Add type-based tag
        tags.push(format!("auto-{:?}", capture_type).to_lowercase());

        // Common technology tags
        let tech_tags = [
            ("rust", "rust"),
            ("python", "python"),
            ("javascript", "javascript"),
            ("typescript", "typescript"),
            ("react", "react"),
            ("sql", "sql"),
            ("api", "api"),
            ("database", "database"),
            ("frontend", "frontend"),
            ("backend", "backend"),
        ];

        for (keyword, tag) in tech_tags {
            if content_lower.contains(keyword) {
                tags.push(tag.to_string());
            }
        }

        // Domain tags
        let domain_tags = [
            ("auth", "authentication"),
            ("login", "authentication"),
            ("security", "security"),
            ("performance", "performance"),
            ("test", "testing"),
            ("deploy", "deployment"),
            ("config", "configuration"),
            ("error", "error-handling"),
        ];

        for (keyword, tag) in domain_tags {
            if content_lower.contains(keyword) {
                tags.push(tag.to_string());
            }
        }

        // Deduplicate
        tags.sort();
        tags.dedup();
        tags.truncate(5);

        tags
    }

    /// Calculate suggested importance
    fn calculate_importance(
        &self,
        content: &str,
        capture_type: CaptureType,
        confidence: f32,
    ) -> f32 {
        let content_lower = content.to_lowercase();
        let mut importance: f32 = 0.5;

        // Base importance by type
        importance += match capture_type {
            CaptureType::Decision => 0.2,
            CaptureType::ActionItem => 0.15,
            CaptureType::Issue => 0.15,
            CaptureType::Preference => 0.1,
            CaptureType::Learning => 0.1,
            CaptureType::KeyFact => 0.1,
            CaptureType::Question => 0.05,
            CaptureType::CodeSnippet => 0.05,
        };

        // Boost for urgency indicators
        let urgency_words = ["critical", "urgent", "asap", "immediately", "blocker"];
        for word in urgency_words {
            if content_lower.contains(word) {
                importance += 0.1;
            }
        }

        // Boost based on confidence
        importance += confidence * 0.1;

        importance.min(1.0)
    }

    /// Update configuration
    pub fn set_config(&mut self, config: AutoCaptureConfig) {
        self.config = config;
    }

    /// Enable/disable auto-capture
    pub fn set_enabled(&mut self, enabled: bool) {
        self.config.enabled = enabled;
    }

    /// Get current config
    pub fn config(&self) -> &AutoCaptureConfig {
        &self.config
    }
}

/// Conversation context for multi-turn capture
#[derive(Debug, Default)]
pub struct ConversationTracker {
    /// Recent messages in the conversation
    messages: Vec<TrackedMessage>,
    /// Candidates detected but not yet confirmed
    pending_captures: Vec<CaptureCandidate>,
    /// Maximum messages to track
    max_messages: usize,
}

#[derive(Debug, Clone)]
struct TrackedMessage {
    content: String,
    role: String,
    #[allow(dead_code)]
    timestamp: DateTime<Utc>,
}

impl ConversationTracker {
    pub fn new(max_messages: usize) -> Self {
        Self {
            messages: Vec::new(),
            pending_captures: Vec::new(),
            max_messages,
        }
    }

    /// Add a message to the tracker
    pub fn add_message(&mut self, content: &str, role: &str) {
        self.messages.push(TrackedMessage {
            content: content.to_string(),
            role: role.to_string(),
            timestamp: Utc::now(),
        });

        // Trim old messages
        if self.messages.len() > self.max_messages {
            self.messages.remove(0);
        }
    }

    /// Get recent context as a string
    pub fn recent_context(&self, num_messages: usize) -> String {
        self.messages
            .iter()
            .rev()
            .take(num_messages)
            .rev()
            .map(|m| format!("[{}]: {}", m.role, m.content))
            .collect::<Vec<_>>()
            .join("\n")
    }

    /// Add pending capture
    pub fn add_pending(&mut self, candidate: CaptureCandidate) {
        self.pending_captures.push(candidate);
    }

    /// Get pending captures
    pub fn pending(&self) -> &[CaptureCandidate] {
        &self.pending_captures
    }

    /// Clear pending captures
    pub fn clear_pending(&mut self) {
        self.pending_captures.clear();
    }

    /// Confirm and remove a pending capture
    pub fn confirm_pending(&mut self, index: usize) -> Option<CaptureCandidate> {
        if index < self.pending_captures.len() {
            Some(self.pending_captures.remove(index))
        } else {
            None
        }
    }

    /// Reject a pending capture
    pub fn reject_pending(&mut self, index: usize) {
        if index < self.pending_captures.len() {
            self.pending_captures.remove(index);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_auto_capture_decision() {
        let engine = AutoCaptureEngine::with_default_config();
        let candidates = engine.analyze(
            "We decided to use Rust for the backend because of performance",
            "conversation",
        );

        assert!(!candidates.is_empty());
        assert_eq!(candidates[0].capture_type, CaptureType::Decision);
        assert!(candidates[0].confidence >= 0.6);
    }

    #[test]
    fn test_auto_capture_action_item() {
        let engine = AutoCaptureEngine::with_default_config();
        let candidates = engine.analyze(
            "TODO: implement the authentication module before Friday",
            "conversation",
        );

        assert!(!candidates.is_empty());
        assert_eq!(candidates[0].capture_type, CaptureType::ActionItem);
    }

    #[test]
    fn test_auto_capture_preference() {
        let engine = AutoCaptureEngine::with_default_config();
        let candidates = engine.analyze(
            "I always prefer using TypeScript over JavaScript for better type safety",
            "conversation",
        );

        assert!(!candidates.is_empty());
        assert_eq!(candidates[0].capture_type, CaptureType::Preference);
    }

    #[test]
    fn test_auto_capture_learning() {
        let engine = AutoCaptureEngine::with_default_config();
        let candidates = engine.analyze(
            "TIL: Rust's ownership system prevents data races at compile time",
            "conversation",
        );

        assert!(!candidates.is_empty());
        assert_eq!(candidates[0].capture_type, CaptureType::Learning);
    }

    #[test]
    fn test_ignore_short_text() {
        let engine = AutoCaptureEngine::with_default_config();
        let candidates = engine.analyze("ok", "conversation");
        assert!(candidates.is_empty());
    }

    #[test]
    fn test_ignore_greetings() {
        let engine = AutoCaptureEngine::with_default_config();
        let candidates = engine.analyze("hello", "conversation");
        assert!(candidates.is_empty());
    }

    #[test]
    fn test_suggest_tags() {
        let engine = AutoCaptureEngine::with_default_config();
        let tags = engine.suggest_tags(
            "implement rust api for authentication",
            CaptureType::ActionItem,
        );

        assert!(tags.contains(&"rust".to_string()));
        assert!(tags.contains(&"api".to_string()));
        assert!(tags.contains(&"authentication".to_string()));
    }

    #[test]
    fn test_conversation_tracker() {
        let mut tracker = ConversationTracker::new(10);

        tracker.add_message("Hello", "user");
        tracker.add_message("Hi there!", "assistant");
        tracker.add_message("I need help with Rust", "user");

        let context = tracker.recent_context(2);
        assert!(context.contains("Hi there!"));
        assert!(context.contains("I need help with Rust"));
    }

    #[test]
    fn test_pending_captures() {
        let mut tracker = ConversationTracker::new(10);

        let candidate = CaptureCandidate {
            content: "Use async/await".to_string(),
            capture_type: CaptureType::Decision,
            confidence: 0.8,
            source: "test".to_string(),
            suggested_tags: vec!["rust".to_string()],
            suggested_importance: 0.7,
            detected_at: Utc::now(),
            reason: "test".to_string(),
        };

        tracker.add_pending(candidate);
        assert_eq!(tracker.pending().len(), 1);

        let confirmed = tracker.confirm_pending(0);
        assert!(confirmed.is_some());
        assert_eq!(tracker.pending().len(), 0);
    }

    #[test]
    fn test_capture_to_memory() {
        let candidate = CaptureCandidate {
            content: "Always use Rust for performance-critical code".to_string(),
            capture_type: CaptureType::Preference,
            confidence: 0.85,
            source: "conversation".to_string(),
            suggested_tags: vec!["rust".to_string(), "performance".to_string()],
            suggested_importance: 0.8,
            detected_at: Utc::now(),
            reason: "Matched pattern".to_string(),
        };

        let memory = candidate.to_memory();
        assert_eq!(memory.content, candidate.content);
        assert_eq!(memory.memory_type, MemoryType::Preference);
        assert_eq!(memory.tags, candidate.suggested_tags);
    }

    #[test]
    fn test_disabled_capture() {
        let config = AutoCaptureConfig {
            enabled: false,
            ..Default::default()
        };

        let engine = AutoCaptureEngine::new(config);
        let candidates = engine.analyze("We decided to use Rust for everything", "conversation");

        assert!(candidates.is_empty());
    }
}