Skip to main content

talos_memory/
consolidation.rs

1//! Episodic-to-semantic memory consolidation pipeline.
2//!
3//! Reads session episodes, extracts semantic memory candidates via a pluggable
4//! [`EpisodeExtractor`], and writes them to [`MemoryStore`] with evidence links.
5//!
6//! The pipeline is bounded, ADD-only, and deterministic when using the default
7//! [`RuleBasedExtractor`]. No LLM or network calls are made.
8
9use chrono::{DateTime, Utc};
10use uuid::Uuid;
11
12use crate::{EvidenceLink, MemoryItem, MemoryKind, MemoryStore, MemoryStoreError};
13
14/// A single episode read from a session, neutral to the session storage format.
15#[derive(Debug, Clone)]
16pub struct SessionEpisode {
17    /// The session this episode belongs to.
18    pub session_id: String,
19    /// Unique identifier for this episode entry.
20    pub entry_id: String,
21    /// Position of this episode in the session sequence.
22    pub turn_index: usize,
23    /// The role that produced this episode: `"user"`, `"assistant"`, `"system"`, `"tool"`.
24    pub role: String,
25    /// The text content of this episode.
26    pub content: String,
27    /// When this episode was created.
28    pub timestamp: DateTime<Utc>,
29}
30
31/// A memory candidate extracted from session episodes.
32#[derive(Debug, Clone)]
33pub struct MemoryCandidate {
34    /// The kind of memory this candidate represents.
35    pub kind: MemoryKind,
36    /// A key identifying the concept or topic.
37    pub key: String,
38    /// The full content of the memory.
39    pub content: String,
40    /// Confidence score (0.0 to 1.0).
41    pub confidence: f64,
42    /// The session this candidate was extracted from.
43    pub source_session_id: String,
44    /// The entry ID within the session.
45    pub source_entry_id: String,
46    /// The turn index within the session.
47    pub source_turn_index: usize,
48}
49
50/// Trait for extracting semantic memory candidates from session episodes.
51///
52/// Implementations must be deterministic: the same input must always produce
53/// the same output.
54pub trait EpisodeExtractor {
55    /// Extract memory candidates from a slice of session episodes.
56    fn extract(&self, episodes: &[SessionEpisode]) -> Vec<MemoryCandidate>;
57}
58
59/// Deterministic rule-based episode extractor (no LLM/provider dependency).
60///
61/// Applies simple heuristics to identify memory-worthy content from session
62/// episodes. Suitable for offline testing and as a baseline extractor.
63pub struct RuleBasedExtractor {
64    /// Maximum number of candidates to return per extraction.
65    max_candidates: usize,
66}
67
68impl RuleBasedExtractor {
69    /// Create a new extractor with the default limit of 20 candidates.
70    pub fn new() -> Self {
71        Self { max_candidates: 20 }
72    }
73
74    /// Create a new extractor with a custom candidate limit.
75    pub fn with_max_candidates(max: usize) -> Self {
76        Self {
77            max_candidates: max,
78        }
79    }
80}
81
82impl Default for RuleBasedExtractor {
83    fn default() -> Self {
84        Self::new()
85    }
86}
87
88impl EpisodeExtractor for RuleBasedExtractor {
89    fn extract(&self, episodes: &[SessionEpisode]) -> Vec<MemoryCandidate> {
90        let mut candidates: Vec<MemoryCandidate> = Vec::new();
91
92        for episode in episodes {
93            // Skip messages shorter than 10 characters (noise).
94            if episode.content.len() < 10 {
95                continue;
96            }
97
98            // Skip system and tool messages (they are events, not original facts).
99            if episode.role == "system" || episode.role == "tool" {
100                continue;
101            }
102
103            // Only process user and assistant messages.
104            if episode.role != "user" && episode.role != "assistant" {
105                continue;
106            }
107
108            // Derive key from first 40 characters, truncated at first newline.
109            let key = derive_key(&episode.content);
110
111            // Compute confidence deterministically.
112            let confidence = compute_confidence(&episode.content, &episode.role);
113
114            candidates.push(MemoryCandidate {
115                kind: MemoryKind::Semantic,
116                key,
117                content: episode.content.clone(),
118                confidence,
119                source_session_id: episode.session_id.clone(),
120                source_entry_id: episode.entry_id.clone(),
121                source_turn_index: episode.turn_index,
122            });
123        }
124
125        // Sort by confidence descending, then by turn_index ascending for ties.
126        candidates.sort_by(|a, b| {
127            b.confidence
128                .partial_cmp(&a.confidence)
129                .unwrap_or(std::cmp::Ordering::Equal)
130                .then_with(|| a.source_turn_index.cmp(&b.source_turn_index))
131        });
132
133        // Limit to max_candidates.
134        candidates.truncate(self.max_candidates);
135
136        candidates
137    }
138}
139
140/// Derive a memory key from content: first 40 chars, truncated at first newline, trimmed.
141fn derive_key(content: &str) -> String {
142    let truncated = content
143        .split_once('\n')
144        .map(|(first, _)| first)
145        .unwrap_or(content);
146    let truncated = truncated.chars().take(40).collect::<String>();
147    truncated.trim().to_string()
148}
149
150/// Compute confidence based on deterministic heuristics.
151fn compute_confidence(content: &str, role: &str) -> f64 {
152    let lower = content.trim_start().to_lowercase();
153
154    // High confidence: explicit memory markers.
155    let markers = ["remember", "note", "important", "always", "never"];
156    if markers.iter().any(|m| lower.starts_with(m)) {
157        return 0.8;
158    }
159
160    // Medium confidence: user message with substantial content.
161    if role == "user" && content.len() > 50 {
162        return 0.6;
163    }
164
165    // Default confidence.
166    0.4
167}
168
169/// Configuration for the consolidation pipeline.
170#[derive(Debug, Clone)]
171pub struct ConsolidationConfig {
172    /// Whether consolidation is enabled. Default: `false` (opt-in for safety).
173    pub enabled: bool,
174    /// Maximum candidates to consider per session.
175    pub max_candidates_per_session: usize,
176}
177
178impl Default for ConsolidationConfig {
179    fn default() -> Self {
180        Self {
181            enabled: false,
182            max_candidates_per_session: 20,
183        }
184    }
185}
186
187/// Report from a consolidation run.
188#[derive(Debug, Clone, Default)]
189pub struct ConsolidationReport {
190    /// Number of candidates extracted by the extractor.
191    pub candidates_extracted: usize,
192    /// Number of candidates successfully inserted into the store.
193    pub inserted: usize,
194    /// Number of candidates skipped as exact duplicates.
195    pub duplicates_skipped: usize,
196    /// Number of evidence links created.
197    pub evidence_links_created: usize,
198    /// Errors encountered during consolidation (non-fatal).
199    pub errors: Vec<String>,
200}
201
202/// Run consolidation: extract candidates from episodes and write to the memory store.
203///
204/// ADD-only: exact content-hash duplicates are skipped. Conflicting same-key
205/// entries with different content are preserved as separate rows per ADR-016.
206///
207/// # Arguments
208///
209/// * `store` — The memory store to write to.
210/// * `episodes` — Session episodes to consolidate.
211/// * `extractor` — The extractor to use for candidate extraction.
212/// * `config` — Pipeline configuration.
213///
214/// # Returns
215///
216/// A [`ConsolidationReport`] summarizing the consolidation run.
217pub fn consolidate_episodes(
218    store: &mut MemoryStore,
219    episodes: &[SessionEpisode],
220    extractor: &dyn EpisodeExtractor,
221    config: &ConsolidationConfig,
222) -> Result<ConsolidationReport, MemoryStoreError> {
223    let mut report = ConsolidationReport::default();
224
225    // If disabled, return immediately without any writes.
226    if !config.enabled {
227        return Ok(report);
228    }
229
230    // Extract candidates.
231    let candidates = extractor.extract(episodes);
232    report.candidates_extracted = candidates.len();
233
234    // Process each candidate.
235    for candidate in &candidates {
236        // Skip malformed candidates (empty content or key).
237        if candidate.content.is_empty() || candidate.key.is_empty() {
238            report.errors.push(format!(
239                "skipped malformed candidate: empty content or key (entry_id={})",
240                candidate.source_entry_id
241            ));
242            continue;
243        }
244
245        let now = Utc::now();
246
247        let memory_id = Uuid::new_v4().to_string();
248        let item = MemoryItem {
249            id: memory_id.clone(),
250            kind: candidate.kind,
251            key: candidate.key.clone(),
252            content: candidate.content.clone(),
253            confidence: candidate.confidence,
254            created_at: now,
255            last_reinforced: now,
256            last_accessed: None,
257            contradiction_ref: None,
258        };
259
260        match store.insert(item) {
261            Ok(inserted) => {
262                if inserted {
263                    report.inserted += 1;
264
265                    let link = EvidenceLink {
266                        id: Uuid::new_v4().to_string(),
267                        memory_id,
268                        source_type: "session".to_string(),
269                        source_ref: format!(
270                            "{}:{}:{}",
271                            candidate.source_session_id,
272                            candidate.source_entry_id,
273                            candidate.source_turn_index
274                        ),
275                        created_at: now,
276                    };
277
278                    if let Err(e) = store.insert_evidence(link) {
279                        report
280                            .errors
281                            .push(format!("failed to insert evidence link: {e}"));
282                    } else {
283                        report.evidence_links_created += 1;
284                    }
285                } else {
286                    report.duplicates_skipped += 1;
287                }
288            }
289            Err(e) => {
290                report
291                    .errors
292                    .push(format!("failed to insert memory item: {e}"));
293            }
294        }
295    }
296
297    Ok(report)
298}
299
300#[cfg(test)]
301mod tests {
302    use super::*;
303
304    fn make_episode(
305        session_id: &str,
306        entry_id: &str,
307        turn_index: usize,
308        role: &str,
309        content: &str,
310    ) -> SessionEpisode {
311        SessionEpisode {
312            session_id: session_id.to_string(),
313            entry_id: entry_id.to_string(),
314            turn_index,
315            role: role.to_string(),
316            content: content.to_string(),
317            timestamp: Utc::now(),
318        }
319    }
320
321    fn make_episodes() -> Vec<SessionEpisode> {
322        vec![
323            make_episode(
324                "sess-1",
325                "entry-1",
326                0,
327                "user",
328                "remember to use Rust edition 2024 for all new projects",
329            ),
330            make_episode(
331                "sess-1",
332                "entry-2",
333                1,
334                "assistant",
335                "I will use Rust edition 2024. It provides improved macro hygiene and async traits.",
336            ),
337            make_episode(
338                "sess-1",
339                "entry-3",
340                2,
341                "system",
342                "Tool call result: success",
343            ),
344            make_episode("sess-1", "entry-4", 3, "user", "short"),
345            make_episode(
346                "sess-1",
347                "entry-5",
348                4,
349                "user",
350                "This is a longer user message that should get medium confidence because it exceeds fifty characters in length",
351            ),
352        ]
353    }
354
355    #[test]
356    fn consolidation_creates_semantic_memory_with_evidence() {
357        let mut store = MemoryStore::open_memory().unwrap();
358        let episodes = make_episodes();
359        let extractor = RuleBasedExtractor::new();
360        let config = ConsolidationConfig {
361            enabled: true,
362            max_candidates_per_session: 20,
363        };
364
365        let report = consolidate_episodes(&mut store, &episodes, &extractor, &config).unwrap();
366
367        assert!(
368            report.inserted > 0,
369            "Should have inserted at least one item"
370        );
371        assert!(
372            report.evidence_links_created > 0,
373            "Should have created evidence links"
374        );
375
376        // Verify retrieval works.
377        let results = store.retrieve("Rust", 10).unwrap();
378        assert!(!results.is_empty(), "Should find Rust-related memory");
379
380        // Verify evidence source_ref contains session_id and entry_id.
381        let has_valid_evidence = results.iter().any(|r| {
382            r.evidence
383                .iter()
384                .any(|e| e.source_ref.contains("sess-1") && e.source_ref.contains("entry-"))
385        });
386        assert!(
387            has_valid_evidence,
388            "Evidence should reference the source session and entry"
389        );
390    }
391
392    #[test]
393    fn exact_duplicate_dedup_by_content_hash() {
394        let mut store = MemoryStore::open_memory().unwrap();
395        let episodes = make_episodes();
396        let extractor = RuleBasedExtractor::new();
397        let config = ConsolidationConfig {
398            enabled: true,
399            max_candidates_per_session: 20,
400        };
401
402        // First run.
403        let report1 = consolidate_episodes(&mut store, &episodes, &extractor, &config).unwrap();
404        let first_inserted = report1.inserted;
405        assert!(first_inserted > 0);
406
407        // Second run on same episodes.
408        let report2 = consolidate_episodes(&mut store, &episodes, &extractor, &config).unwrap();
409
410        assert_eq!(
411            report2.inserted, 0,
412            "Second run should insert nothing (all duplicates)"
413        );
414        assert!(
415            report2.duplicates_skipped > 0,
416            "Second run should skip duplicates"
417        );
418    }
419
420    #[test]
421    fn conflicting_same_key_preserved_not_overwritten() {
422        let mut store = MemoryStore::open_memory().unwrap();
423
424        // Two episodes with same key prefix (first 40 chars match) but different content.
425        let episodes = vec![
426            make_episode(
427                "sess-2",
428                "entry-a",
429                0,
430                "user",
431                "Python is a dynamically typed programming language with great ecosystem",
432            ),
433            make_episode(
434                "sess-2",
435                "entry-b",
436                1,
437                "user",
438                "Python is a statically typed programming language with strict type checking",
439            ),
440        ];
441
442        let extractor = RuleBasedExtractor::new();
443        let config = ConsolidationConfig {
444            enabled: true,
445            max_candidates_per_session: 20,
446        };
447
448        let report = consolidate_episodes(&mut store, &episodes, &extractor, &config).unwrap();
449
450        assert_eq!(
451            report.inserted, 2,
452            "Both conflicting items should be inserted"
453        );
454        assert_eq!(store.count().unwrap(), 2, "Store should contain both items");
455    }
456
457    #[test]
458    fn malformed_and_empty_sessions_degrade_gracefully() {
459        let mut store = MemoryStore::open_memory().unwrap();
460
461        let episodes = vec![
462            // Empty content.
463            make_episode("sess-3", "entry-1", 0, "user", ""),
464            // Very short content (<10 chars).
465            make_episode("sess-3", "entry-2", 1, "user", "hi"),
466            // System role (should be skipped by extractor).
467            make_episode(
468                "sess-3",
469                "entry-3",
470                2,
471                "system",
472                "This is a system message with enough content",
473            ),
474            // Tool role (should be skipped by extractor).
475            make_episode(
476                "sess-3",
477                "entry-4",
478                3,
479                "tool",
480                "Tool output with enough characters to pass length check",
481            ),
482        ];
483
484        let extractor = RuleBasedExtractor::new();
485        let config = ConsolidationConfig {
486            enabled: true,
487            max_candidates_per_session: 20,
488        };
489
490        // Should not panic.
491        let report = consolidate_episodes(&mut store, &episodes, &extractor, &config).unwrap();
492
493        // System and tool are skipped by extractor; empty and short are also skipped.
494        // So candidates_extracted should be 0.
495        assert_eq!(
496            report.candidates_extracted, 0,
497            "No valid candidates from malformed episodes"
498        );
499        assert_eq!(report.inserted, 0);
500        // Errors may or may not be populated depending on where skipping happens.
501        // The key assertion is: no panic occurred.
502    }
503
504    #[test]
505    fn disabled_config_no_writes() {
506        let mut store = MemoryStore::open_memory().unwrap();
507        let episodes = make_episodes();
508        let extractor = RuleBasedExtractor::new();
509        let config = ConsolidationConfig {
510            enabled: false,
511            max_candidates_per_session: 20,
512        };
513
514        let report = consolidate_episodes(&mut store, &episodes, &extractor, &config).unwrap();
515
516        assert_eq!(report.candidates_extracted, 0);
517        assert_eq!(report.inserted, 0);
518        assert_eq!(report.duplicates_skipped, 0);
519        assert_eq!(report.evidence_links_created, 0);
520        assert!(report.errors.is_empty());
521        assert_eq!(store.count().unwrap(), 0, "Store should be empty");
522    }
523
524    #[test]
525    fn rule_based_extractor_is_deterministic() {
526        let episodes = make_episodes();
527        let extractor = RuleBasedExtractor::new();
528
529        let result1 = extractor.extract(&episodes);
530        let result2 = extractor.extract(&episodes);
531
532        assert_eq!(
533            result1.len(),
534            result2.len(),
535            "Both extractions should produce same number of candidates"
536        );
537
538        for (c1, c2) in result1.iter().zip(result2.iter()) {
539            assert_eq!(c1.key, c2.key, "Keys should match");
540            assert_eq!(c1.confidence, c2.confidence, "Confidence should match");
541            assert_eq!(
542                c1.source_turn_index, c2.source_turn_index,
543                "Turn index should match"
544            );
545        }
546    }
547}