Skip to main content

talos_memory/
store.rs

1use crate::entities::extract_entities;
2use crate::{
3    AssociationResult, EntityKind, EvidenceLink, GraphEdge, GraphNode, MemoryItem, MemoryKind,
4    MemoryStatus, MemoryStoreError, RetentionCandidate, RetentionPolicy, RetrievalResult,
5};
6use chrono::{DateTime, Utc};
7use rusqlite::{Connection, OptionalExtension, params};
8use sha2::{Digest, Sha256};
9use std::collections::HashSet;
10use std::path::Path;
11
12/// SQLite-backed store for semantic and procedural memory.
13///
14/// Provides ADD-only writes, FTS5-based retrieval with multi-signal scoring,
15/// and evidence provenance tracking.
16pub struct MemoryStore {
17    pub(crate) conn: Connection,
18}
19
20impl MemoryStore {
21    /// Open or create a memory store at the given file path.
22    ///
23    /// Creates parent directories if they do not exist. Runs schema migration
24    /// automatically.
25    pub fn open(path: impl AsRef<Path>) -> Result<Self, MemoryStoreError> {
26        if let Some(parent) = path.as_ref().parent() {
27            std::fs::create_dir_all(parent)?;
28        }
29        let conn = Connection::open(path)?;
30        configure_connection(&conn)?;
31        let store = Self { conn };
32        store.migrate()?;
33        Ok(store)
34    }
35
36    /// Open an in-memory store for testing.
37    pub fn open_memory() -> Result<Self, MemoryStoreError> {
38        let conn = Connection::open_in_memory()?;
39        configure_connection(&conn)?;
40        let store = Self { conn };
41        store.migrate()?;
42        Ok(store)
43    }
44
45    /// Create the database schema if it does not exist.
46    fn migrate(&self) -> Result<(), MemoryStoreError> {
47        self.conn.execute_batch(
48            r#"
49            CREATE TABLE IF NOT EXISTS schema_version (version INTEGER PRIMARY KEY);
50
51            CREATE TABLE IF NOT EXISTS memory_items (
52                id TEXT PRIMARY KEY,
53                kind TEXT NOT NULL,
54                key TEXT NOT NULL,
55                content TEXT NOT NULL,
56                content_hash TEXT NOT NULL,
57                confidence REAL NOT NULL,
58                created_at TEXT NOT NULL,
59                last_reinforced TEXT NOT NULL,
60                last_accessed TEXT,
61                contradiction_ref TEXT
62            );
63
64            CREATE UNIQUE INDEX IF NOT EXISTS idx_memory_items_content_hash
65                ON memory_items(content_hash);
66
67            CREATE TABLE IF NOT EXISTS evidence_links (
68                id TEXT PRIMARY KEY,
69                memory_id TEXT NOT NULL,
70                source_type TEXT NOT NULL,
71                source_ref TEXT NOT NULL,
72                created_at TEXT NOT NULL,
73                FOREIGN KEY (memory_id) REFERENCES memory_items(id)
74            );
75
76            CREATE VIRTUAL TABLE IF NOT EXISTS memory_fts USING fts5(
77                memory_id UNINDEXED, content, tokenize='unicode61'
78            );
79
80            CREATE TABLE IF NOT EXISTS entities (
81                id TEXT PRIMARY KEY,
82                name TEXT NOT NULL,
83                kind TEXT NOT NULL,
84                created_at TEXT NOT NULL
85            );
86
87            CREATE TABLE IF NOT EXISTS memory_entities (
88                memory_id TEXT NOT NULL,
89                entity_id TEXT NOT NULL,
90                PRIMARY KEY (memory_id, entity_id),
91                FOREIGN KEY (memory_id) REFERENCES memory_items(id),
92                FOREIGN KEY (entity_id) REFERENCES entities(id)
93            );
94            "#,
95        )?;
96
97        crate::graph::migrate_graph(&self.conn)?;
98
99        // Initialize schema_version if empty (new database).
100        let version_count: i64 =
101            self.conn
102                .query_row("SELECT COUNT(*) FROM schema_version", [], |row| row.get(0))?;
103        if version_count == 0 {
104            let _ = self
105                .conn
106                .execute("INSERT INTO schema_version (version) VALUES (3)", []);
107        } else {
108            let current_version: i64 =
109                self.conn
110                    .query_row("SELECT version FROM schema_version", [], |row| row.get(0))?;
111            if current_version < 3 {
112                let _ = self
113                    .conn
114                    .execute("UPDATE schema_version SET version = 3", []);
115            }
116        }
117
118        Ok(())
119    }
120
121    /// Insert a memory item.
122    ///
123    /// ADD-only: exact duplicates (same `key` + `content` hash) are silently ignored.
124    /// Conflicting entries with the same `key` but different content are preserved
125    /// as separate rows (ADD-only semantics per ADR-016).
126    ///
127    /// Returns `true` if the item was inserted, `false` if it was an exact duplicate.
128    pub fn insert(&mut self, item: MemoryItem) -> Result<bool, MemoryStoreError> {
129        let content_hash = compute_content_hash(&item.key, &item.content);
130        let kind_str = match item.kind {
131            MemoryKind::Semantic => "semantic",
132            MemoryKind::Procedural => "procedural",
133        };
134
135        let tx = self.conn.transaction()?;
136
137        let changes = tx.execute(
138            "INSERT OR IGNORE INTO memory_items \
139             (id, kind, key, content, content_hash, confidence, created_at, last_reinforced, last_accessed, contradiction_ref) \
140             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
141            params![
142                item.id,
143                kind_str,
144                item.key,
145                item.content,
146                content_hash,
147                item.confidence,
148                item.created_at.to_rfc3339(),
149                item.last_reinforced.to_rfc3339(),
150                item.last_accessed.as_ref().map(|dt| dt.to_rfc3339()),
151                item.contradiction_ref,
152            ],
153        )?;
154
155        if changes > 0 {
156            tx.execute(
157                "INSERT INTO memory_fts (memory_id, content) VALUES (?1, ?2)",
158                params![item.id, item.content],
159            )?;
160
161            let entities = extract_entities(&item.content);
162            for (name, kind) in entities {
163                let kind_str = match kind {
164                    EntityKind::File => "file",
165                    EntityKind::Url => "url",
166                    EntityKind::Code => "code",
167                    EntityKind::Concept => "concept",
168                };
169                let entity_id = format!("{kind_str}:{name}");
170                let _ = tx.execute(
171                    "INSERT OR IGNORE INTO entities (id, name, kind, created_at) VALUES (?1, ?2, ?3, ?4)",
172                    params![entity_id, name, kind_str, Utc::now().to_rfc3339()],
173                );
174                let _ = tx.execute(
175                    "INSERT OR IGNORE INTO memory_entities (memory_id, entity_id) VALUES (?1, ?2)",
176                    params![item.id, entity_id],
177                );
178            }
179        }
180
181        tx.commit()?;
182
183        Ok(changes > 0)
184    }
185
186    /// Insert an evidence link for a memory item.
187    pub fn insert_evidence(&self, link: EvidenceLink) -> Result<(), MemoryStoreError> {
188        self.conn.execute(
189            "INSERT INTO evidence_links (id, memory_id, source_type, source_ref, created_at) \
190             VALUES (?1, ?2, ?3, ?4, ?5)",
191            params![
192                link.id,
193                link.memory_id,
194                link.source_type,
195                link.source_ref,
196                link.created_at.to_rfc3339(),
197            ],
198        )?;
199        Ok(())
200    }
201
202    /// Retrieve memory items matching the query, scored by FTS5 relevance, recency, and evidence.
203    ///
204    /// # Scoring Formula
205    ///
206    /// - `fts_score = |bm25| / (1 + |bm25|)` — normalized FTS5 relevance (higher = more relevant)
207    /// - `recency = exp(-days_since_last_reinforced / 30.0)` — exponential decay over 30 days
208    /// - `evidence_score = confidence × ln(1 + evidence_count)` — logarithmic evidence strength
209    /// - `final_score = fts_score × 1.0 + recency × 0.3 + evidence_score × 0.5`
210    ///
211    /// Results are sorted by `final_score` descending and truncated to `limit`.
212    pub fn retrieve(
213        &self,
214        query: &str,
215        limit: usize,
216    ) -> Result<Vec<RetrievalResult>, MemoryStoreError> {
217        if query.trim().is_empty() || limit == 0 {
218            return Ok(Vec::new());
219        }
220
221        // Fetch more candidates from FTS5 to allow scoring to reorder.
222        let candidate_limit = (limit.max(5) * 3) as i64;
223
224        let fts_query = escape_fts_query(query);
225
226        let mut stmt = self.conn.prepare(
227            "SELECT memory_id, rank FROM memory_fts \
228             WHERE memory_fts MATCH ?1 \
229             ORDER BY rank ASC \
230             LIMIT ?2",
231        )?;
232
233        let candidates = stmt
234            .query_map(params![fts_query, candidate_limit], |row| {
235                let memory_id: String = row.get(0)?;
236                let rank: f64 = row.get(1)?;
237                Ok((memory_id, rank))
238            })?
239            .collect::<rusqlite::Result<Vec<_>>>()?;
240
241        let query_entities: HashSet<String> = extract_entities(query)
242            .into_iter()
243            .map(|(name, kind)| {
244                let kind_str = match kind {
245                    EntityKind::File => "file",
246                    EntityKind::Url => "url",
247                    EntityKind::Code => "code",
248                    EntityKind::Concept => "concept",
249                };
250                format!("{kind_str}:{name}")
251            })
252            .collect();
253
254        let mut results = Vec::new();
255        let now = Utc::now();
256
257        for (memory_id, bm25_rank) in candidates {
258            let item = match self.get(&memory_id)? {
259                Some(item) => item,
260                None => continue,
261            };
262
263            // FTS5 bm25: more negative = more relevant. Normalize to [0, 1).
264            let fts_score = bm25_rank.abs() / (1.0 + bm25_rank.abs());
265
266            let seconds_since_reinforced = (now - item.last_reinforced).num_seconds().max(0) as f64;
267            let days_since_reinforced = seconds_since_reinforced / 86400.0;
268            let recency = (-days_since_reinforced / 30.0).exp();
269
270            let evidence_count: i64 = self.conn.query_row(
271                "SELECT COUNT(*) FROM evidence_links WHERE memory_id = ?1",
272                params![memory_id],
273                |row| row.get(0),
274            )?;
275            let evidence_score = item.confidence * (1.0 + evidence_count as f64).ln();
276
277            let memory_entity_ids: HashSet<String> = self
278                .conn
279                .prepare("SELECT entity_id FROM memory_entities WHERE memory_id = ?1")
280                .ok()
281                .and_then(|mut stmt| {
282                    stmt.query_map(params![memory_id], |row| row.get::<_, String>(0))
283                        .ok()
284                        .map(|rows| rows.filter_map(|r| r.ok()).collect::<HashSet<String>>())
285                })
286                .unwrap_or_default();
287
288            let overlap = query_entities.intersection(&memory_entity_ids).count();
289            let entity_score = overlap as f64 * 0.5;
290
291            let final_score = fts_score * 1.0 + recency * 0.3 + evidence_score * 0.5 + entity_score;
292
293            let evidence = self.load_evidence(&memory_id)?;
294
295            // Best-effort update of last_accessed (ignore errors — ranking signal only).
296            let _ = self.conn.execute(
297                "UPDATE memory_items SET last_accessed = ?1 WHERE id = ?2",
298                params![now.to_rfc3339(), memory_id],
299            );
300
301            let score_breakdown = format!(
302                "fts={:.3}, recency={:.3}, evidence={:.3}, entity={:.3}",
303                fts_score, recency, evidence_score, entity_score
304            );
305
306            results.push(RetrievalResult {
307                item,
308                evidence,
309                score: final_score,
310                score_breakdown,
311            });
312        }
313
314        // Sort by final_score descending.
315        results.sort_by(|a, b| {
316            b.score
317                .partial_cmp(&a.score)
318                .unwrap_or(std::cmp::Ordering::Equal)
319        });
320
321        results.truncate(limit);
322
323        Ok(results)
324    }
325
326    /// Get a memory item by ID.
327    pub fn get(&self, id: &str) -> Result<Option<MemoryItem>, MemoryStoreError> {
328        let mut stmt = self.conn.prepare(
329            "SELECT id, kind, key, content, confidence, created_at, last_reinforced, \
330             last_accessed, contradiction_ref \
331             FROM memory_items WHERE id = ?1",
332        )?;
333
334        let row_data = stmt
335            .query_row(params![id], |row| {
336                Ok((
337                    row.get::<_, String>(0)?,
338                    row.get::<_, String>(1)?,
339                    row.get::<_, String>(2)?,
340                    row.get::<_, String>(3)?,
341                    row.get::<_, f64>(4)?,
342                    row.get::<_, String>(5)?,
343                    row.get::<_, String>(6)?,
344                    row.get::<_, Option<String>>(7)?,
345                    row.get::<_, Option<String>>(8)?,
346                ))
347            })
348            .optional()?;
349
350        match row_data {
351            Some((
352                id,
353                kind_str,
354                key,
355                content,
356                confidence,
357                created_at_str,
358                last_reinforced_str,
359                last_accessed_str,
360                contradiction_ref,
361            )) => {
362                let kind = match kind_str.as_str() {
363                    "procedural" => MemoryKind::Procedural,
364                    _ => MemoryKind::Semantic,
365                };
366                Ok(Some(MemoryItem {
367                    id,
368                    kind,
369                    key,
370                    content,
371                    confidence,
372                    created_at: parse_datetime(&created_at_str)?,
373                    last_reinforced: parse_datetime(&last_reinforced_str)?,
374                    last_accessed: last_accessed_str
375                        .as_deref()
376                        .map(parse_datetime)
377                        .transpose()?,
378                    contradiction_ref,
379                }))
380            }
381            None => Ok(None),
382        }
383    }
384
385    /// Count total memory items.
386    pub fn count(&self) -> Result<usize, MemoryStoreError> {
387        let count: i64 = self
388            .conn
389            .query_row("SELECT COUNT(*) FROM memory_items", [], |row| row.get(0))?;
390        Ok(count as usize)
391    }
392
393    /// Checkpoint the SQLite write-ahead log, truncating it when possible.
394    ///
395    /// This is an explicit maintenance operation for storage lifecycle workflows;
396    /// normal memory reads and writes do not invoke it.
397    pub fn checkpoint_truncate(&self) -> Result<(), MemoryStoreError> {
398        self.conn
399            .execute_batch("PRAGMA wal_checkpoint(TRUNCATE);")
400            .map_err(|e| MemoryStoreError::Maintenance(e.to_string()))
401    }
402
403    /// Rebuild the SQLite database file to reclaim free pages.
404    ///
405    /// This should only be called by explicit maintenance commands, never inside
406    /// the agent turn loop.
407    pub fn vacuum(&self) -> Result<(), MemoryStoreError> {
408        self.conn
409            .execute_batch("VACUUM;")
410            .map_err(|e| MemoryStoreError::Maintenance(e.to_string()))
411    }
412
413    /// Report memory store status without exposing any content.
414    pub fn memory_status(&self) -> Result<MemoryStatus, MemoryStoreError> {
415        let total_items: i64 =
416            self.conn
417                .query_row("SELECT COUNT(*) FROM memory_items", [], |row| row.get(0))?;
418
419        let semantic_count: i64 = self.conn.query_row(
420            "SELECT COUNT(*) FROM memory_items WHERE kind = 'semantic'",
421            [],
422            |row| row.get(0),
423        )?;
424
425        let procedural_count: i64 = self.conn.query_row(
426            "SELECT COUNT(*) FROM memory_items WHERE kind = 'procedural'",
427            [],
428            |row| row.get(0),
429        )?;
430
431        let evidence_count: i64 =
432            self.conn
433                .query_row("SELECT COUNT(*) FROM evidence_links", [], |row| row.get(0))?;
434
435        let entity_count: i64 =
436            self.conn
437                .query_row("SELECT COUNT(*) FROM entities", [], |row| row.get(0))?;
438
439        let (db_path, db_size_bytes) = self.db_file_info()?;
440
441        Ok(MemoryStatus {
442            total_items: total_items as usize,
443            semantic_count: semantic_count as usize,
444            procedural_count: procedural_count as usize,
445            evidence_count: evidence_count as usize,
446            entity_count: entity_count as usize,
447            db_path,
448            db_size_bytes,
449        })
450    }
451
452    /// Report memory items that match retention criteria.
453    /// This is DRY-RUN ONLY — no items are deleted. ADD-only semantics are preserved.
454    pub fn retention_candidates(
455        &self,
456        policy: &RetentionPolicy,
457    ) -> Result<Vec<RetentionCandidate>, MemoryStoreError> {
458        let mut query = String::from(
459            "SELECT id, kind, key, confidence, last_reinforced \
460             FROM memory_items WHERE 1=1",
461        );
462        let mut params_vec: Vec<rusqlite::types::Value> = Vec::new();
463
464        if let Some(min_conf) = policy.min_confidence {
465            query.push_str(" AND confidence < ?");
466            params_vec.push(rusqlite::types::Value::Real(min_conf));
467        }
468
469        if let Some(max_age_days) = policy.max_age_days {
470            query.push_str(" AND last_reinforced < datetime('now', ?)");
471            params_vec.push(rusqlite::types::Value::Text(format!(
472                "-{} days",
473                max_age_days
474            )));
475        }
476
477        if policy.unreinforced_only {
478            query.push_str(" AND id NOT IN (SELECT DISTINCT memory_id FROM evidence_links)");
479        }
480
481        let mut stmt = self.conn.prepare(&query)?;
482
483        let param_refs: Vec<&dyn rusqlite::types::ToSql> =
484            params_vec.iter().map(|v| v as _).collect();
485
486        let rows = stmt.query_map(rusqlite::params_from_iter(param_refs.iter()), |row| {
487            Ok((
488                row.get::<_, String>(0)?,
489                row.get::<_, String>(1)?,
490                row.get::<_, String>(2)?,
491                row.get::<_, f64>(3)?,
492                row.get::<_, String>(4)?,
493            ))
494        })?;
495
496        let now = Utc::now();
497        let mut candidates = Vec::new();
498
499        for row in rows {
500            let (id, kind, key, confidence, last_reinforced_str) = row?;
501            let last_reinforced = parse_datetime(&last_reinforced_str)?;
502
503            let evidence_count: i64 = self.conn.query_row(
504                "SELECT COUNT(*) FROM evidence_links WHERE memory_id = ?1",
505                params![&id],
506                |row| row.get(0),
507            )?;
508
509            let key_preview = if key.len() > 30 {
510                format!("{}...", &key[..27])
511            } else {
512                key.clone()
513            };
514
515            let mut reasons = Vec::new();
516            if policy.min_confidence.is_some_and(|m| confidence < m) {
517                reasons.push(format!("confidence {:.2} below threshold", confidence));
518            }
519            if policy.max_age_days.is_some() {
520                let age_days = (now - last_reinforced).num_days();
521                reasons.push(format!("age {} days", age_days));
522            }
523            if policy.unreinforced_only && evidence_count == 0 {
524                reasons.push("no evidence links".to_string());
525            }
526
527            let age_days = (now - last_reinforced).num_days();
528
529            candidates.push(RetentionCandidate {
530                id,
531                kind,
532                key_preview,
533                confidence,
534                last_reinforced,
535                age_days,
536                evidence_count: evidence_count as usize,
537                reason: reasons.join("; "),
538            });
539        }
540
541        Ok(candidates)
542    }
543
544    fn db_file_info(&self) -> Result<(Option<String>, u64), MemoryStoreError> {
545        let mut stmt = self.conn.prepare("PRAGMA database_list")?;
546        let rows = stmt.query_map([], |row| {
547            Ok((
548                row.get::<_, i64>(0)?,
549                row.get::<_, String>(1)?,
550                row.get::<_, String>(2)?,
551            ))
552        })?;
553
554        for row in rows {
555            let (_seq, _name, path) = row?;
556            if path.is_empty() || path == ":memory:" {
557                continue;
558            }
559            if let Ok(meta) = std::fs::metadata(&path) {
560                return Ok((Some(path), meta.len()));
561            }
562        }
563
564        Ok((None, 0))
565    }
566
567    /// Load evidence links for a memory item.
568    fn load_evidence(&self, memory_id: &str) -> Result<Vec<EvidenceLink>, MemoryStoreError> {
569        let mut stmt = self.conn.prepare(
570            "SELECT id, memory_id, source_type, source_ref, created_at \
571             FROM evidence_links WHERE memory_id = ?1 ORDER BY created_at DESC",
572        )?;
573
574        let raw_links = stmt
575            .query_map(params![memory_id], |row| {
576                Ok((
577                    row.get::<_, String>(0)?,
578                    row.get::<_, String>(1)?,
579                    row.get::<_, String>(2)?,
580                    row.get::<_, String>(3)?,
581                    row.get::<_, String>(4)?,
582                ))
583            })?
584            .collect::<rusqlite::Result<Vec<_>>>()?;
585
586        raw_links
587            .into_iter()
588            .map(|(id, memory_id, source_type, source_ref, created_at_str)| {
589                Ok(EvidenceLink {
590                    id,
591                    memory_id,
592                    source_type,
593                    source_ref,
594                    created_at: parse_datetime(&created_at_str)?,
595                })
596            })
597            .collect()
598    }
599
600    pub fn graph_upsert_node(&self, node: &GraphNode) -> Result<(), MemoryStoreError> {
601        crate::graph::upsert_node(&self.conn, node)
602    }
603
604    pub fn graph_upsert_edge(&self, edge: &GraphEdge) -> Result<(), MemoryStoreError> {
605        crate::graph::upsert_edge(&self.conn, edge)
606    }
607
608    pub fn graph_get_node(&self, id: &str) -> Result<Option<GraphNode>, MemoryStoreError> {
609        crate::graph::get_node(&self.conn, id)
610    }
611
612    pub fn graph_recall(
613        &self,
614        seed_ids: &[&str],
615        max_hops: usize,
616        min_edge_weight: f64,
617        fanout: usize,
618    ) -> Result<Vec<AssociationResult>, MemoryStoreError> {
619        crate::graph::recall_associative(
620            &self.conn,
621            seed_ids,
622            max_hops,
623            min_edge_weight,
624            fanout,
625            Utc::now(),
626        )
627    }
628}
629
630fn configure_connection(conn: &Connection) -> Result<(), MemoryStoreError> {
631    conn.execute_batch(
632        "PRAGMA foreign_keys=ON; PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL;",
633    )?;
634    Ok(())
635}
636
637/// Compute SHA-256 hash of `key|content` for exact-duplicate detection.
638fn compute_content_hash(key: &str, content: &str) -> String {
639    let mut hasher = Sha256::new();
640    hasher.update(key.as_bytes());
641    hasher.update(b"|");
642    hasher.update(content.as_bytes());
643    hex::encode(hasher.finalize())
644}
645
646/// Parse an RFC 3339 datetime string into `DateTime<Utc>`.
647fn parse_datetime(s: &str) -> Result<DateTime<Utc>, MemoryStoreError> {
648    DateTime::parse_from_rfc3339(s)
649        .map(|dt| dt.with_timezone(&Utc))
650        .map_err(|e| MemoryStoreError::InvalidTimestamp(e.to_string()))
651}
652
653/// Escape a user query for safe use in FTS5 MATCH.
654///
655/// Replaces FTS5-special characters with spaces so tokenization works
656/// without syntax errors. Entity extraction still runs on the original query.
657fn escape_fts_query(query: &str) -> String {
658    query.replace(['/', '.', '"', '-'], " ")
659}