mentedb-cognitive 0.6.2

Cognitive memory features for MenteDB
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
use std::collections::HashSet;

use ahash::AHashSet;
use mentedb_core::types::{MemoryId, Timestamp};
use serde::{Deserialize, Serialize};
use uuid::Uuid;

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub enum PhantomPriority {
    Low,
    Medium,
    High,
    Critical,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PhantomMemory {
    pub id: MemoryId,
    pub gap_description: String,
    pub source_reference: String,
    pub source_turn: u64,
    pub priority: PhantomPriority,
    pub created_at: Timestamp,
    pub resolved: bool,
}

/// Explicit registry of known entities. The AI client registers entities it
/// cares about so that gap detection can be precise rather than heuristic.
pub struct EntityRegistry {
    known_entities: AHashSet<String>,
}

impl EntityRegistry {
    pub fn new() -> Self {
        Self {
            known_entities: AHashSet::new(),
        }
    }

    pub fn register(&mut self, entity: &str) {
        self.known_entities.insert(entity.to_string());
    }

    pub fn register_batch(&mut self, entities: &[&str]) {
        for entity in entities {
            self.known_entities.insert((*entity).to_string());
        }
    }

    pub fn unregister(&mut self, entity: &str) {
        self.known_entities.remove(entity);
    }

    pub fn is_known(&self, entity: &str) -> bool {
        self.known_entities.contains(entity)
    }

    pub fn list(&self) -> Vec<&str> {
        self.known_entities.iter().map(|s| s.as_str()).collect()
    }

    pub fn len(&self) -> usize {
        self.known_entities.len()
    }

    pub fn is_empty(&self) -> bool {
        self.known_entities.is_empty()
    }
}

impl Default for EntityRegistry {
    fn default() -> Self {
        Self::new()
    }
}

/// Configuration for phantom memory detection.
#[derive(Debug, Clone)]
pub struct PhantomConfig {
    /// Words to skip when detecting capitalized entity references.
    pub stop_words: HashSet<String>,
    /// Maximum number of warnings to include in formatted output.
    pub max_warnings: usize,
    /// Minimum word length for technical term detection.
    pub min_word_length: usize,
    /// Whether to use heuristic (capitalized word) detection as a fallback.
    /// Default `true` for backward compatibility; set to `false` to rely
    /// solely on the explicit entity registry.
    pub use_heuristic_detection: bool,
}

impl Default for PhantomConfig {
    fn default() -> Self {
        let stop_words: HashSet<String> = [
            "the", "a", "an", "is", "are", "was", "were", "it", "this", "that", "we", "you",
            "they", "he", "she", "i", "my", "our", "but", "and", "or", "if", "then", "when", "how",
            "what", "where", "who", "do", "does", "did", "have", "has", "had", "be", "been",
            "being", "so", "also", "just", "very", "too", "not", "no", "yes", "can", "will",
            "should", "would", "could", "may", "might", "must", "shall", "note", "see", "use",
            "make", "let", "new", "set", "get",
        ]
        .iter()
        .map(|s| s.to_string())
        .collect();
        Self {
            stop_words,
            max_warnings: 5,
            min_word_length: 3,
            use_heuristic_detection: true,
        }
    }
}

pub struct PhantomTracker {
    phantoms: Vec<PhantomMemory>,
    config: PhantomConfig,
    entity_registry: EntityRegistry,
}

impl PhantomTracker {
    pub fn new(config: PhantomConfig) -> Self {
        Self {
            phantoms: Vec::new(),
            config,
            entity_registry: EntityRegistry::new(),
        }
    }

    /// Convenience: register an entity in the embedded registry.
    pub fn register_entity(&mut self, entity: &str) {
        self.entity_registry.register(entity);
    }

    /// Convenience: register multiple entities at once.
    pub fn register_entities(&mut self, entities: &[&str]) {
        self.entity_registry.register_batch(entities);
    }

    /// Return a reference to the entity registry.
    pub fn entity_registry(&self) -> &EntityRegistry {
        &self.entity_registry
    }

    /// Return a mutable reference to the entity registry.
    pub fn entity_registry_mut(&mut self) -> &mut EntityRegistry {
        &mut self.entity_registry
    }

    /// Scan content for entity references not in `known_entities`.
    ///
    /// Two detection strategies are combined:
    /// 1. **Registry-based** (primary): any registered entity found in
    ///    `content` that is NOT in `known_entities` is flagged at
    ///    `Medium`/`High` priority.
    /// 2. **Heuristic** (fallback): capitalized words, quoted terms, and
    ///    technical terms are flagged at `Low` priority. Disabled when
    ///    `PhantomConfig::use_heuristic_detection` is `false`.
    pub fn detect_gaps(
        &mut self,
        content: &str,
        known_entities: &[String],
        turn_id: u64,
    ) -> Vec<PhantomMemory> {
        let known_lower: Vec<String> = known_entities.iter().map(|e| e.to_lowercase()).collect();
        let mut detected: Vec<(String, PhantomPriority)> = Vec::new();
        let mut seen = AHashSet::new();

        // --- Primary: registry-based detection ---
        let content_lower = content.to_lowercase();
        for entity in self.entity_registry.list() {
            let entity_lower = entity.to_lowercase();
            if content_lower.contains(&entity_lower)
                && !known_lower.contains(&entity_lower)
                && seen.insert(entity_lower)
            {
                let priority = if entity.split_whitespace().count() > 1 {
                    PhantomPriority::High
                } else {
                    PhantomPriority::Medium
                };
                detected.push((entity.to_string(), priority));
            }
        }

        // --- Fallback: heuristic detection (only when enabled) ---
        if self.config.use_heuristic_detection {
            let heuristic = self.heuristic_detect(content, &known_lower, &mut seen);
            for entity in heuristic {
                detected.push((entity, PhantomPriority::Low));
            }
        }

        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_micros() as u64;

        let new_phantoms: Vec<PhantomMemory> = detected
            .into_iter()
            .map(|(entity, priority)| PhantomMemory {
                id: MemoryId::new(),
                gap_description: format!("No stored knowledge about '{}'", entity),
                source_reference: entity,
                source_turn: turn_id,
                priority,
                created_at: now,
                resolved: false,
            })
            .collect();

        self.phantoms.extend(new_phantoms.clone());
        new_phantoms
    }

    /// Preferred explicit API: the caller provides exactly which entities
    /// were mentioned. Entities not in the registry are flagged as gaps.
    pub fn detect_gaps_explicit(
        &mut self,
        content: &str,
        mentioned_entities: &[&str],
        turn_id: u64,
    ) -> Vec<PhantomMemory> {
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_micros() as u64;

        let _ = content; // available for future use; presence keeps API uniform

        let new_phantoms: Vec<PhantomMemory> = mentioned_entities
            .iter()
            .filter(|e| !self.entity_registry.is_known(e))
            .map(|entity| PhantomMemory {
                id: MemoryId::new(),
                gap_description: format!("No stored knowledge about '{}'", entity),
                source_reference: (*entity).to_string(),
                source_turn: turn_id,
                priority: PhantomPriority::Medium,
                created_at: now,
                resolved: false,
            })
            .collect();

        self.phantoms.extend(new_phantoms.clone());
        new_phantoms
    }

    /// Heuristic entity detection (capitalized words, quotes, technical terms).
    fn heuristic_detect(
        &self,
        content: &str,
        known_lower: &[String],
        seen: &mut AHashSet<String>,
    ) -> Vec<String> {
        let mut detected = Vec::new();

        // Detect quoted terms
        let mut in_quote = false;
        let mut quote_start = 0;
        for (i, ch) in content.char_indices() {
            if ch == '\'' || ch == '"' || ch == '\u{2018}' || ch == '\u{2019}' {
                if in_quote {
                    let term = &content[quote_start..i];
                    let trimmed = term.trim();
                    if !trimmed.is_empty()
                        && trimmed.len() >= 2
                        && !known_lower.contains(&trimmed.to_lowercase())
                        && seen.insert(trimmed.to_lowercase())
                    {
                        detected.push(trimmed.to_string());
                    }
                    in_quote = false;
                } else {
                    in_quote = true;
                    quote_start = i + ch.len_utf8();
                }
            }
        }

        // Detect capitalized sequences (e.g., "Kubernetes Cluster", "JWT Token")
        let words: Vec<&str> = content.split_whitespace().collect();
        let mut i = 0;
        while i < words.len() {
            let w = words[i]
                .trim_matches(|c: char| !c.is_alphanumeric() && c != '-' && c != '_' && c != '.');
            if !w.is_empty() && w.chars().next().is_some_and(|c| c.is_uppercase()) && w.len() >= 2 {
                let mut entity_parts = vec![w.to_string()];
                let mut j = i + 1;
                while j < words.len() {
                    let next = words[j].trim_matches(|c: char| {
                        !c.is_alphanumeric() && c != '-' && c != '_' && c != '.'
                    });
                    if !next.is_empty() && next.chars().next().is_some_and(|c| c.is_uppercase()) {
                        entity_parts.push(next.to_string());
                        j += 1;
                    } else {
                        break;
                    }
                }

                let entity = entity_parts.join(" ");
                if entity.split_whitespace().count() == 1
                    && self.config.stop_words.contains(&entity.to_lowercase())
                {
                    i = j;
                    continue;
                }

                if !known_lower.contains(&entity.to_lowercase())
                    && seen.insert(entity.to_lowercase())
                {
                    detected.push(entity);
                }
                i = j;
            } else {
                if !w.is_empty() && w.len() >= self.config.min_word_length {
                    let is_technical = w.contains('-')
                        || w.contains('.')
                        || w.contains('_')
                        || (w.len() >= self.config.min_word_length
                            && w.chars()
                                .all(|c| c.is_uppercase() || c.is_ascii_digit() || c == '_'));

                    if is_technical
                        && !known_lower.contains(&w.to_lowercase())
                        && seen.insert(w.to_lowercase())
                    {
                        detected.push(w.to_string());
                    }
                }
                i += 1;
            }
        }

        detected
    }

    pub fn resolve(&mut self, phantom_id: Uuid) {
        if let Some(p) = self
            .phantoms
            .iter_mut()
            .find(|p| p.id == MemoryId::from(phantom_id))
        {
            p.resolved = true;
        }
    }

    pub fn get_active_phantoms(&self) -> Vec<&PhantomMemory> {
        let mut active: Vec<&PhantomMemory> =
            self.phantoms.iter().filter(|p| !p.resolved).collect();
        active.sort_by_key(|x| std::cmp::Reverse(x.priority));
        active
    }

    pub fn format_phantom_warnings(&self) -> String {
        let active = self.get_active_phantoms();
        if active.is_empty() {
            return String::new();
        }

        active
            .iter()
            .take(self.config.max_warnings)
            .map(|p| {
                format!(
                    "WARNING: User referenced '{}' but no details stored. Consider asking.",
                    p.source_reference
                )
            })
            .collect::<Vec<_>>()
            .join("\n")
    }
}

impl Default for PhantomTracker {
    fn default() -> Self {
        Self::new(PhantomConfig::default())
    }
}

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

    #[test]
    fn test_detect_unknown_entities() {
        let mut tracker = PhantomTracker::default();
        let known = vec!["React".to_string(), "TypeScript".to_string()];
        let phantoms = tracker.detect_gaps(
            "We need to deploy to the Kubernetes cluster using Terraform",
            &known,
            1,
        );
        let refs: Vec<&str> = phantoms
            .iter()
            .map(|p| p.source_reference.as_str())
            .collect();
        assert!(
            refs.iter().any(|r| r.contains("Kubernetes")),
            "Expected Kubernetes, got: {:?}",
            refs
        );
        assert!(
            refs.iter().any(|r| r.contains("Terraform")),
            "Expected Terraform, got: {:?}",
            refs
        );
    }

    #[test]
    fn test_resolve_phantom() {
        let mut tracker = PhantomTracker::default();
        let phantoms = tracker.detect_gaps("Check the Redis cache", &[], 1);
        assert!(!phantoms.is_empty());
        let pid = phantoms[0].id;
        tracker.resolve(pid.into());
        assert!(tracker.get_active_phantoms().iter().all(|p| p.id != pid));
    }

    #[test]
    fn test_format_warnings() {
        let mut tracker = PhantomTracker::default();
        tracker.detect_gaps("Deploy to Kubernetes using Helm", &[], 1);
        let warnings = tracker.format_phantom_warnings();
        assert!(warnings.contains("WARNING"));
    }

    // --- EntityRegistry CRUD ---

    #[test]
    fn test_entity_registry_crud() {
        let mut reg = EntityRegistry::new();
        assert!(reg.is_empty());

        reg.register("Kubernetes");
        reg.register("Terraform");
        assert_eq!(reg.len(), 2);
        assert!(reg.is_known("Kubernetes"));
        assert!(!reg.is_known("Docker"));

        reg.unregister("Kubernetes");
        assert!(!reg.is_known("Kubernetes"));
        assert_eq!(reg.len(), 1);
    }

    #[test]
    fn test_entity_registry_batch() {
        let mut reg = EntityRegistry::new();
        reg.register_batch(&["Redis", "Postgres", "Kafka"]);
        assert_eq!(reg.len(), 3);
        assert!(reg.is_known("Redis"));
        assert!(reg.is_known("Kafka"));
    }

    #[test]
    fn test_entity_registry_list() {
        let mut reg = EntityRegistry::new();
        reg.register_batch(&["B", "A", "C"]);
        let mut items = reg.list();
        items.sort();
        assert_eq!(items, vec!["A", "B", "C"]);
    }

    // --- detect_gaps_explicit ---

    #[test]
    fn test_detect_gaps_explicit_finds_unknown() {
        let mut tracker = PhantomTracker::default();
        tracker.register_entities(&["Kubernetes", "Terraform"]);

        let gaps = tracker.detect_gaps_explicit(
            "Deploy with Kubernetes and Docker",
            &["Kubernetes", "Docker"],
            1,
        );

        // Docker is not registered, so it should be flagged.
        assert_eq!(gaps.len(), 1);
        assert_eq!(gaps[0].source_reference, "Docker");
    }

    #[test]
    fn test_detect_gaps_explicit_no_false_positives() {
        let mut tracker = PhantomTracker::default();
        tracker.register_entities(&["Kubernetes", "Terraform", "Helm"]);

        let gaps =
            tracker.detect_gaps_explicit("Using Kubernetes and Helm", &["Kubernetes", "Helm"], 1);

        // Both are registered — no gaps.
        assert!(gaps.is_empty());
    }

    // --- Heuristic disabled via config ---

    #[test]
    fn test_heuristic_disabled() {
        let mut config = PhantomConfig::default();
        config.use_heuristic_detection = false;
        let mut tracker = PhantomTracker::new(config);

        // No entities registered and heuristic off — should find nothing.
        let gaps = tracker.detect_gaps("Deploy to Kubernetes using Terraform", &[], 1);
        assert!(
            gaps.is_empty(),
            "Expected no gaps with heuristic disabled and empty registry, got: {:?}",
            gaps.iter().map(|g| &g.source_reference).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_heuristic_disabled_with_registry() {
        let mut config = PhantomConfig::default();
        config.use_heuristic_detection = false;
        let mut tracker = PhantomTracker::new(config);
        tracker.register_entity("Kubernetes");

        // Registry-based detection should still work even with heuristic off.
        let gaps = tracker.detect_gaps("Deploy to Kubernetes using Terraform", &[], 1);
        // Kubernetes is registered and referenced but not in known_entities → flagged.
        // Terraform is NOT registered and heuristic is off → not flagged.
        assert_eq!(gaps.len(), 1);
        assert_eq!(gaps[0].source_reference, "Kubernetes");
    }

    // --- Integration: register, detect, resolve ---

    #[test]
    fn test_integration_register_detect_resolve() {
        let mut tracker = PhantomTracker::default();
        tracker.register_entities(&["Redis", "Postgres"]);

        // Caller mentions Redis, Kafka, Postgres — Kafka is unknown.
        let gaps = tracker.detect_gaps_explicit(
            "Need Redis and Kafka and Postgres",
            &["Redis", "Kafka", "Postgres"],
            1,
        );
        assert_eq!(gaps.len(), 1);
        assert_eq!(gaps[0].source_reference, "Kafka");
        assert!(!gaps[0].resolved);

        // Resolve the gap.
        tracker.resolve(gaps[0].id.into());
        assert!(tracker.get_active_phantoms().is_empty());
    }

    // --- Heuristic fallback produces Low priority ---

    #[test]
    fn test_heuristic_fallback_low_priority() {
        let mut tracker = PhantomTracker::default();
        // No entities registered — heuristic only.
        // Use lowercase prefix so "Redis" is detected as a standalone capitalized word.
        let gaps = tracker.detect_gaps("we use Redis for caching", &[], 1);
        let redis_gaps: Vec<_> = gaps
            .iter()
            .filter(|g| g.source_reference == "Redis")
            .collect();
        assert_eq!(redis_gaps.len(), 1);
        assert_eq!(redis_gaps[0].priority, PhantomPriority::Low);
    }

    #[test]
    fn test_registry_detection_higher_priority() {
        let mut tracker = PhantomTracker::default();
        tracker.register_entity("Redis");

        let gaps = tracker.detect_gaps("we use Redis for caching", &[], 1);
        let redis_gaps: Vec<_> = gaps
            .iter()
            .filter(|g| g.source_reference == "Redis")
            .collect();
        assert_eq!(redis_gaps.len(), 1);
        // Registry-based single-word entity → Medium priority.
        assert_eq!(redis_gaps[0].priority, PhantomPriority::Medium);
    }
}