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
//! # aimem-core
//!
//! **Give your AI a memory — reusable core library.**
//!
//! `aimem-core` is a pure-Rust library that stores, retrieves, and searches
//! text memories using [Turso](https://github.com/tursodatabase/turso) (an in-process
//! SQLite engine with native vector support) as the sole storage backend.
//! No external vector database, no cloud service, no API key.
//!
//! ## Feature overview
//!
//! | Feature | Implementation |
//! |---------|---------------|
//! | Vector storage | Turso `vector32()` BLOB column |
//! | Semantic search | `vector_distance_cos()` — SimSIMD-accelerated cosine |
//! | Full-text search | SQL `LIKE` scan (Turso FTS index optional) |
//! | Embedding generation | [`fastembed`](https://crates.io/crates/fastembed) — `all-MiniLM-L6-v2` locally |
//! | Knowledge graph | Temporal entity-relationship triples in SQLite |
//! | Graph traversal | BFS over wing/room adjacency — no graph DB needed |
//! | MCP protocol | Implemented in `aimem-mcp` (separate crate) |
//!
//! ## Architecture: 4-Layer Memory Stack
//!
//! ```text
//! ┌─────────────────────────────────────────────────────────┐
//! │ L0 Identity text ~100 tokens always loaded │
//! │ L1 Essential story ~500-800 tok always loaded │
//! │ L2 On-demand recall ~200-500 tok loaded on ask │
//! │ L3 Deep semantic search unlimited full memory │
//! └─────────────────────────────────────────────────────────┘
//! ```
//!
//! ## Storage model
//!
//! Everything lives in a **single Turso DB file** (default: `~/.aimem/aimem.db`):
//!
//! ```text
//! aimem.db
//! ├── drawers — verbatim text chunks + vector32 embeddings
//! ├── entities — knowledge graph nodes
//! └── triples — temporal (subject → predicate → object) edges
//! ```
//!
//! ## Concepts
//!
//! | Term | Meaning |
//! |------|---------|
//! | **Store** | The entire AiMem memory store (one DB file) |
//! | **Wing** | A named project or domain (e.g. `"my_app"`, `"journal"`) |
//! | **Room** | A topic within a wing (e.g. `"backend"`, `"decisions"`) |
//! | **Drawer** | One verbatim text chunk (800 chars) with its embedding |
//! | **Tunnel** | A room that spans multiple wings — a conceptual bridge |
//!
//! ## Quick start
//!
//! ```toml
//! # Cargo.toml
//! [dependencies]
//! tokio = { version = "1", features = ["full"] }
//! ```
//!
//! ```bash
//! cargo add aimem-core
//! ```
//!
//! ```rust,no_run
//! use aimem_core::prelude::*;
//!
//! #[tokio::main]
//! async fn main() -> anyhow::Result<()> {
//! // 1. Load config (env > ~/.aimem/config.json > defaults)
//! let cfg = Config::load()?;
//!
//! // 2. Open the AiMem DB (creates DB + schema on first run)
//! let db = AimemDb::open(&cfg.db_path).await?;
//!
//! // 3. Load local embedding model (downloads ~23 MB on first use)
//! let embedder = Embedder::new()?;
//!
//! // 4. Build the memory stack
//! let stack = MemoryStack::new(db, embedder, &cfg);
//!
//! // 5. Wake-up prompt: L0 (identity) + L1 (top memories) — inject into LLM context
//! println!("{}", stack.wake_up(None).await?);
//!
//! // 6. Semantic search — uses Turso vector_distance_cos() natively
//! println!("{}", stack.search("why did we choose Rust?", None, None).await?);
//!
//! Ok(())
//! }
//! ```
//!
//! ## Mining a project
//!
//! ```rust,no_run
//! use aimem_core::prelude::*;
//!
//! #[tokio::main]
//! async fn main() -> anyhow::Result<()> {
//! let cfg = Config::load()?;
//! let db = AimemDb::open(&cfg.db_path).await?;
//! let embedder = Embedder::new()?;
//!
//! let miner = Miner::new(db, Some(embedder));
//!
//! // Reads aimem.yaml in the project directory for wing/room config
//! let stats = miner.mine("~/projects/my_app", None, "claude", 0, false).await?;
//!
//! println!(
//! "Mined {} drawers from {} files",
//! stats.drawers_added,
//! stats.files_scanned - stats.files_skipped,
//! );
//! Ok(())
//! }
//! ```
//!
//! ## Keyword-only search without embeddings
//!
//! If you mine with `Miner::new(db, None)` or `ConvoMiner::new(db, None)`,
//! drawers still participate in SQL keyword search even though they have no embeddings.
//!
//! ```rust,no_run
//! use aimem_core::prelude::*;
//!
//! #[tokio::main]
//! async fn main() -> anyhow::Result<()> {
//! let db = AimemDb::memory().await?;
//! let drawer = Drawer {
//! id: "drawer_kw_001".into(),
//! wing: "demo".into(),
//! room: "backend".into(),
//! content: "Turso keeps the backend local and simple.".into(),
//! source_file: None,
//! chunk_index: 0,
//! added_by: "example".into(),
//! filed_at: chrono::Utc::now().to_rfc3339(),
//! };
//! db.insert_drawer(&drawer, None).await?;
//!
//! let searcher = Searcher::keyword_only(db);
//! let hits = searcher.keyword_search("Turso", Some("demo"), None, 5).await?;
//! assert_eq!(hits.len(), 1);
//! Ok(())
//! }
//! ```
//!
//! ## Knowledge graph
//!
//! ```rust,no_run
//! use aimem_core::prelude::*;
//!
//! #[tokio::main]
//! async fn main() -> anyhow::Result<()> {
//! let db = AimemDb::memory().await?; // in-memory for demo
//! let kg = KnowledgeGraph::new(db);
//!
//! // Store a temporal fact
//! kg.add_triple("Max", "does", "swimming", Some("2025-01-01"), None).await?;
//! kg.add_triple("Max", "loves", "chess", Some("2025-10-01"), None).await?;
//!
//! // Query all outgoing facts for "Max"
//! let facts = kg.query_entity("Max", None, "outgoing").await?;
//! for f in &facts {
//! println!("{} → {} → {}", f.subject, f.predicate, f.object);
//! }
//!
//! // Invalidate a fact (set valid_to = today)
//! kg.invalidate("Max", "does", "swimming", None).await?;
//!
//! Ok(())
//! }
//! ```
//!
//! ## Low-level storage operations
//!
//! ```rust,no_run
//! use aimem_core::prelude::*;
//!
//! #[tokio::main]
//! async fn main() -> anyhow::Result<()> {
//! let db = AimemDb::memory().await?;
//! let embedder = Embedder::new()?;
//!
//! let content = "We decided to use Rust for performance and memory safety.";
//! let embedding = embedder.embed_one(content)?;
//!
//! let drawer = Drawer {
//! id: "drawer_test_decision_001".to_string(),
//! wing: "my_project".to_string(),
//! room: "decisions".to_string(),
//! content: content.to_string(),
//! source_file: Some("DECISIONS.md".to_string()),
//! chunk_index: 0,
//! added_by: "claude".to_string(),
//! filed_at: chrono::Utc::now().to_rfc3339(),
//! };
//!
//! let inserted = db.insert_drawer(&drawer, Some(&embedding)).await?;
//! println!("Inserted: {inserted}");
//! println!("Total drawers: {}", db.drawer_count().await?);
//!
//! Ok(())
//! }
//! ```
//!
//! ## Crate feature flags
//!
//! `aimem-core` has no optional features itself — the embedding model
//! is always available. The `hf-hub` feature of `fastembed` controls whether
//! `Embedder::new()` can download models automatically.
//!
//! ## Reusing in other projects
//!
//! Because this is a library crate with no binary, any project can depend on it:
//!
//! ```toml
//! [dependencies]
//! aimem-core = { git = "https://github.com/v1cc0/aimem" }
//! # or local path:
//! aimem-core = { path = "/path/to/aimem/crates/aimem-core" }
//! ```
//!
//! The public re-exports in this file form the stable API surface.
//! Consumers should prefer `aimem_core::{...}` root imports over deep module
//! paths. The root re-exports are the intended stable integration surface.
pub use Config;
pub use ;
pub use AimemDb;
pub use Embedder;
pub use ;
pub use KnowledgeGraph;
pub use MemoryStack;
pub use Miner;
pub use Searcher;
pub use ;
/// Curated high-level imports for typical AiMem integrations.
///
/// This is the easiest way to get the common building blocks without pulling
/// in deeper module paths.
///
/// ```rust
/// use aimem_core::prelude::*;
///
/// fn _accepts_common_types(
/// _cfg: Config,
/// _db: AimemDb,
/// _drawer: Drawer,
/// _searcher: Searcher,
/// _miner: Miner,
/// _convo: ConvoMiner,
/// _graph: AimemGraph,
/// _kg: KnowledgeGraph,
/// _stack: MemoryStack,
/// _result: SearchResult,
/// _triple: Triple,
/// ) {
/// }
/// ```