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
12pub struct MemoryStore {
17 pub(crate) conn: Connection,
18}
19
20impl MemoryStore {
21 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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
637fn 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
646fn 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
653fn escape_fts_query(query: &str) -> String {
658 query.replace(['/', '.', '"', '-'], " ")
659}