Skip to main content

memori_core/
lib.rs

1//! Persistent memory for AI coding agents — SQLite + FTS5 + vector search in a single binary.
2//!
3//! `memori-ai-core` is the Rust engine behind the `py-memori` Python package and the
4//! `memori` CLI. It stores memories (text + 384-dim embeddings + JSON metadata + access
5//! stats) in one SQLite file with WAL journaling, exposes FTS5 full-text search and
6//! brute-force cosine vector search, and fuses them with Reciprocal Rank Fusion (k=60).
7//!
8//! See <https://github.com/archit15singh/memori> for the full design and CLI usage.
9
10pub mod embed;
11pub mod schema;
12pub mod search;
13pub mod storage;
14pub mod types;
15pub mod util;
16
17use std::collections::HashMap;
18
19pub use types::{InsertResult, Memory, MemoriError, Result, SearchQuery, SortField};
20
21pub struct Memori {
22    conn: rusqlite::Connection,
23}
24
25impl Memori {
26    pub fn open(path: &str) -> Result<Self> {
27        let conn = if path == ":memory:" {
28            rusqlite::Connection::open_in_memory()?
29        } else {
30            rusqlite::Connection::open(path)?
31        };
32        schema::init_db(&conn)?;
33        Ok(Self { conn })
34    }
35
36    /// Resolve a short ID prefix to the full UUID.
37    pub fn resolve_id(&self, id: &str) -> Result<String> {
38        storage::resolve_prefix(&self.conn, id)
39    }
40
41    pub fn insert(
42        &self,
43        content: &str,
44        vector: Option<&[f32]>,
45        metadata: Option<serde_json::Value>,
46        dedup_threshold: Option<f32>,
47        no_embed: bool,
48    ) -> Result<InsertResult> {
49        storage::insert(&self.conn, content, vector, metadata, dedup_threshold, no_embed)
50    }
51
52    pub fn insert_with_id(
53        &self,
54        id: &str,
55        content: &str,
56        vector: Option<&[f32]>,
57        metadata: Option<serde_json::Value>,
58        created_at: f64,
59        updated_at: f64,
60    ) -> Result<String> {
61        storage::insert_with_id(&self.conn, id, content, vector, metadata, created_at, updated_at)
62    }
63
64    pub fn get(&self, id: &str) -> Result<Option<Memory>> {
65        // Resolve prefix; if not found, return None (backwards compat)
66        let full_id = match storage::resolve_prefix(&self.conn, id) {
67            Ok(fid) => fid,
68            Err(MemoriError::NotFound(_)) => return Ok(None),
69            Err(e) => return Err(e),
70        };
71        storage::get(&self.conn, &full_id)
72    }
73
74    pub fn update(
75        &self,
76        id: &str,
77        content: Option<&str>,
78        vector: Option<&[f32]>,
79        metadata: Option<serde_json::Value>,
80        merge_metadata: bool,
81    ) -> Result<()> {
82        let full_id = storage::resolve_prefix(&self.conn, id)?;
83        storage::update(&self.conn, &full_id, content, vector, metadata, merge_metadata)
84    }
85
86    pub fn delete(&self, id: &str) -> Result<()> {
87        let full_id = storage::resolve_prefix(&self.conn, id)?;
88        storage::delete(&self.conn, &full_id)
89    }
90
91    pub fn search(&self, query: SearchQuery) -> Result<Vec<Memory>> {
92        search::search(&self.conn, query)
93    }
94
95    pub fn count(&self) -> Result<usize> {
96        storage::count(&self.conn)
97    }
98
99    pub fn type_distribution(&self) -> Result<HashMap<String, usize>> {
100        storage::type_distribution(&self.conn)
101    }
102
103    pub fn delete_before(&self, before_timestamp: f64) -> Result<usize> {
104        storage::delete_before(&self.conn, before_timestamp)
105    }
106
107    pub fn delete_by_type(&self, type_value: &str) -> Result<usize> {
108        storage::delete_by_type(&self.conn, type_value)
109    }
110
111    pub fn touch(&self, id: &str) -> Result<()> {
112        let full_id = storage::resolve_prefix(&self.conn, id)?;
113        storage::touch(&self.conn, &full_id)
114    }
115
116    pub fn vacuum(&self) -> Result<()> {
117        storage::vacuum(&self.conn)
118    }
119
120    pub fn set_access_stats(
121        &self,
122        id: &str,
123        last_accessed: Option<f64>,
124        access_count: i64,
125    ) -> Result<()> {
126        let full_id = storage::resolve_prefix(&self.conn, id)?;
127        storage::set_access_stats(&self.conn, &full_id, last_accessed, access_count)
128    }
129
130    pub fn backfill_embeddings(&self, batch_size: usize) -> Result<usize> {
131        storage::backfill_embeddings(&self.conn, batch_size)
132    }
133
134    pub fn list(
135        &self,
136        type_filter: Option<&str>,
137        sort: &SortField,
138        limit: usize,
139        offset: usize,
140        before: Option<f64>,
141        after: Option<f64>,
142    ) -> Result<Vec<Memory>> {
143        storage::list(&self.conn, type_filter, sort, limit, offset, before, after)
144    }
145
146    pub fn embedding_stats(&self) -> Result<(usize, usize)> {
147        storage::embedding_stats(&self.conn)
148    }
149
150    /// Get a memory by ID or prefix without bumping access_count.
151    pub fn get_readonly(&self, id_or_prefix: &str) -> Result<Option<Memory>> {
152        let full_id = match storage::resolve_prefix(&self.conn, id_or_prefix) {
153            Ok(fid) => fid,
154            Err(MemoriError::NotFound(_)) => return Ok(None),
155            Err(e) => return Err(e),
156        };
157        storage::get_raw(&self.conn, &full_id)
158    }
159
160    pub fn related(&self, id: &str, limit: usize) -> Result<Vec<Memory>> {
161        let full_id = storage::resolve_prefix(&self.conn, id)?;
162        search::related(&self.conn, &full_id, limit)
163    }
164}