context_forge/lib.rs
1//! `context-forge` — a local-first persistent memory library for LLM applications.
2//!
3//! This crate provides `SQLite` + FTS5 BM25 retrieval, recency-decay scoring, and
4//! token-budget-aware context assembly with no network calls. It is intended to
5//! be embedded in larger applications (CLI tools, bots, agent runtimes) that need
6//! durable, searchable memory.
7//!
8//! # Quick start
9//!
10//! ```
11//! use context_forge::{kind, ContextForge, Config, SaveOptions};
12//! use std::path::PathBuf;
13//!
14//! let mut config = Config::default();
15//! config.db_path = PathBuf::from(":memory:");
16//!
17//! let cf = ContextForge::open(config)?;
18//! cf.save("the deploy failure was caused by a missing env var", kind::SNAPSHOT, &SaveOptions::default())?;
19//!
20//! let hits = cf.query("deploy failure", None, 2048)?;
21//! assert_eq!(hits.len(), 1);
22//! # Ok::<(), context_forge::Error>(())
23//! ```
24//!
25//! # Async callers
26//!
27//! This crate is synchronous by design — it performs blocking `SQLite` I/O and
28//! never spawns its own threads or runtime. Callers using an async runtime
29//! (e.g. Tokio) should wrap calls in [`spawn_blocking`](https://docs.rs/tokio/latest/tokio/task/fn.spawn_blocking.html)
30//! and share a single [`ContextForge`] instance behind an `Arc`:
31//!
32//! ```ignore
33//! use std::sync::Arc;
34//!
35//! let cf = Arc::new(ContextForge::open(config)?);
36//!
37//! // in an async context:
38//! let hits = tokio::task::spawn_blocking({
39//! let cf = cf.clone();
40//! move || cf.query("deploy failure", Some("discord:thread:42"), 2048)
41//! }).await??;
42//! ```
43//!
44//! # Security
45//!
46//! **Retrieved entries are untrusted text.** Content persisted from past
47//! conversations may contain adversarial instructions (stored prompt
48//! injection) — whatever was saved into the store, including text that
49//! originated from another user or from a tool's output, comes back out
50//! verbatim on [`ContextForge::query`] (aside from save-time secret
51//! scrubbing, see below).
52//!
53//! Callers **MUST** present retrieved memory to models as quoted data
54//! (e.g. inside a fenced or otherwise clearly delimited context block
55//! labeled as history), **never** as system-level instructions, and
56//! **MUST NOT** execute or evaluate anything found in it.
57//!
58//! ## Save-time secret scrubbing
59//!
60//! [`ContextForge::save`] applies [`scrub_secrets`] to `content` before it
61//! is persisted, using the [`ScrubConfig`] supplied in [`Config::scrub`].
62//! This redacts common credential formats (cloud provider keys, API
63//! tokens, private key blocks, JWTs, bearer tokens) with
64//! `[REDACTED:<label>]` placeholders so they never reach the database or
65//! the search index. Scrubbing is **on by default** and can be disabled
66//! via `Config { scrub: ScrubConfig { enabled: false }, .. }` — this is an
67//! explicit, non-silent opt-out.
68//!
69//! Note that [`SaveOptions::metadata`] is **not** scrubbed (see its docs).
70
71#![warn(clippy::pedantic)]
72#![warn(missing_docs)]
73
74/// Engine and scrub configuration types (`Config`, `EvictionPolicy`, `ScrubConfig`).
75pub mod config;
76/// Local-LLM distillation trait and the optional `distill-http` implementation.
77pub mod distill;
78/// `ContextEngine`: search, recency decay, and token-budget assembly.
79pub mod engine;
80/// `ContextEntry`, `ScoredEntry`, and the `kind` constants module.
81pub mod entry;
82/// The crate's `Error` type.
83pub mod error;
84/// Save-time secret scrubbing (`scrub_secrets`, `ScrubConfig`).
85pub mod scrub;
86/// Session grouping helpers (`group_entries_by_session`, `SessionGroup`).
87pub mod session;
88/// SQLite-backed storage and search implementations. All SQL lives here.
89pub mod storage;
90/// `ContextStorage` and `Searcher` traits, and the crate's `Result` alias.
91pub mod traits;
92
93/// Importance-detection pipeline (tokenizer, lexicon, scoring). Pure
94/// computation, no I/O. Enabled by the `analysis` feature (default).
95#[cfg(feature = "analysis")]
96pub mod analysis;
97
98#[cfg(feature = "parallel")]
99pub use analysis::with_thread_cap;
100
101use std::path::Path;
102
103// Re-export primary types at crate root for convenience.
104pub use config::{Config, EvictionPolicy};
105pub use distill::{DistilledMemory, Distiller, Fact, FactKind};
106pub use engine::{ContextEngine, SaveOptions, MATCH_ALL_QUERY};
107pub use entry::{kind, ContextEntry, ScoredEntry};
108pub use error::Error;
109pub use scrub::{scrub_secrets, ScrubConfig};
110pub use session::{group_entries_by_session, SessionGroup};
111pub use storage::{open_storage, SqliteSearcher, SqliteStorage};
112pub use traits::{ContextStorage, Result, Searcher};
113
114/// The documented entry point for `context-forge`.
115///
116/// `ContextForge` wires together a [`SqliteStorage`] backend, a
117/// [`SqliteSearcher`], and a [`ContextEngine`] behind a small,
118/// stable API surface. Advanced callers that need direct access to the
119/// underlying storage or searcher can construct those types directly and
120/// pass them to [`ContextEngine::new`] instead.
121pub struct ContextForge {
122 engine: ContextEngine,
123 scrub_config: ScrubConfig,
124}
125
126impl ContextForge {
127 /// Open (or create) the database at `config.db_path`, run any pending
128 /// migrations, and build the engine.
129 ///
130 /// # Errors
131 ///
132 /// Returns an error if the database cannot be opened, the connection
133 /// pool cannot be built, or migrations fail.
134 pub fn open(config: Config) -> Result<Self> {
135 let db_path = config.db_path.clone();
136 let max_entries = config.max_entries;
137 let scrub_config = config.scrub.clone();
138 let (storage, searcher) = open_storage(Path::new(&db_path), max_entries)?;
139 let engine = ContextEngine::new(Box::new(storage), Box::new(searcher), config);
140 Ok(Self {
141 engine,
142 scrub_config,
143 })
144 }
145
146 /// Save a new entry. Returns the generated entry ID.
147 ///
148 /// `kind` is a caller-defined classification (see [`mod@kind`] for
149 /// well-known values). Capacity enforcement (LRU eviction) is handled
150 /// atomically by the storage layer.
151 ///
152 /// Before persistence, `content` is passed through [`scrub_secrets`]
153 /// using this instance's [`ScrubConfig`] (see [`Config::scrub`]),
154 /// redacting common credential formats with `[REDACTED:<label>]`
155 /// placeholders. `opts.metadata` is stored verbatim and is **not**
156 /// scrubbed — see [`SaveOptions::metadata`].
157 ///
158 /// # Errors
159 ///
160 /// Returns an error if `content` is empty or if the underlying storage
161 /// write fails.
162 pub fn save(&self, content: &str, kind: &str, opts: &SaveOptions) -> Result<String> {
163 let scrubbed = scrub_secrets(content, &self.scrub_config);
164 self.engine.save_snapshot(&scrubbed, kind, opts)
165 }
166
167 /// Distill `transcript` into a summary and durable facts, then save
168 /// them as separate entries sharing `opts.scope` and
169 /// `opts.session_id`.
170 ///
171 /// `transcript` is passed through [`scrub_secrets`] **before** it is
172 /// sent to `distiller` (so secrets never reach a distillation
173 /// endpoint), and the summary/facts produced are scrubbed again before
174 /// persistence via the normal [`ContextForge::save`] path (defense in
175 /// depth).
176 ///
177 /// The summary is saved with `kind::SUMMARY`; each fact is saved with
178 /// `kind::FACT` and metadata `{"fact_kind": "<kind>", "source":
179 /// "distill"}`.
180 ///
181 /// Returns the IDs of the saved entries: the summary's ID first,
182 /// followed by each fact's ID in order.
183 ///
184 /// # Errors
185 ///
186 /// Returns an error if distillation fails, or if any save fails.
187 pub fn distill_and_save(
188 &self,
189 transcript: &str,
190 distiller: &dyn Distiller,
191 opts: &SaveOptions,
192 ) -> Result<Vec<String>> {
193 let scrubbed_transcript = scrub_secrets(transcript, &self.scrub_config);
194 let memory = distiller.distill(&scrubbed_transcript)?;
195
196 let mut ids = Vec::with_capacity(1 + memory.facts.len());
197
198 let summary_id = self.save(&memory.summary, kind::SUMMARY, opts)?;
199 ids.push(summary_id);
200
201 for fact in &memory.facts {
202 let fact_kind_str = match fact.kind {
203 FactKind::Decision => "decision",
204 FactKind::Correction => "correction",
205 FactKind::Preference => "preference",
206 FactKind::State => "state",
207 };
208 let metadata = serde_json::json!({
209 "fact_kind": fact_kind_str,
210 "source": "distill",
211 });
212 let fact_opts = SaveOptions {
213 session_id: opts.session_id.clone(),
214 scope: opts.scope.clone(),
215 metadata: Some(metadata),
216 };
217 let fact_id = self.save(&fact.text, kind::FACT, &fact_opts)?;
218 ids.push(fact_id);
219 }
220
221 Ok(ids)
222 }
223
224 /// Assemble entries matching `query` that fit within `token_budget`.
225 ///
226 /// `scope = None` searches every entry regardless of scope (global
227 /// recall). `scope = Some(s)` restricts the search to entries whose
228 /// `scope` equals `s`.
229 ///
230 /// # Errors
231 ///
232 /// Returns an error if the search or recency-weighting step fails.
233 pub fn query(
234 &self,
235 query: &str,
236 scope: Option<&str>,
237 token_budget: usize,
238 ) -> Result<Vec<ContextEntry>> {
239 self.engine.assemble(query, scope, token_budget)
240 }
241
242 /// Delete a single entry by id. Returns `true` if an entry was removed.
243 ///
244 /// # Errors
245 ///
246 /// Returns an error if the underlying storage delete fails.
247 pub fn delete(&self, id: &str) -> Result<bool> {
248 self.engine.storage().delete(id)
249 }
250
251 /// Remove all entries within a given scope. Returns the number of
252 /// entries removed.
253 ///
254 /// # Errors
255 ///
256 /// Returns an error if the underlying storage delete fails.
257 pub fn clear_scope(&self, scope: &str) -> Result<usize> {
258 self.engine.storage().clear_scope(scope)
259 }
260
261 /// Remove all entries. Returns the number of entries removed.
262 ///
263 /// # Errors
264 ///
265 /// Returns an error if the underlying storage delete fails.
266 pub fn clear_all(&self) -> Result<usize> {
267 self.engine.storage().clear()
268 }
269
270 /// Return the total number of stored entries.
271 ///
272 /// # Errors
273 ///
274 /// Returns an error if the underlying storage count fails.
275 pub fn count(&self) -> Result<usize> {
276 self.engine.storage().count()
277 }
278}
279
280#[cfg(test)]
281mod tests {
282 use super::*;
283 use std::path::PathBuf;
284
285 #[test]
286 fn context_entry_json_roundtrip() {
287 let entry = ContextEntry {
288 id: "e1".into(),
289 content: "hello world".into(),
290 timestamp: 1_700_000_000,
291 kind: kind::MANUAL.to_owned(),
292 scope: None,
293 session_id: None,
294 token_count: Some(3),
295 metadata: None,
296 };
297 let json = serde_json::to_string(&entry).unwrap();
298 let back: ContextEntry = serde_json::from_str(&json).unwrap();
299 assert_eq!(back.id, "e1");
300 assert_eq!(back.token_count, Some(3));
301 }
302
303 #[test]
304 fn error_display_messages() {
305 let invalid = Error::InvalidEntry("empty content".into());
306 assert_eq!(invalid.to_string(), "invalid entry: empty content");
307
308 let migration = Error::Migration("schema mismatch".into());
309 assert_eq!(migration.to_string(), "migration error: schema mismatch");
310
311 let distill = Error::Distill("model unavailable".into());
312 assert_eq!(distill.to_string(), "distillation error: model unavailable");
313 }
314
315 #[test]
316 fn core_config_json_roundtrip() {
317 let cfg = Config {
318 max_entries: 1000,
319 token_budget: 8192,
320 db_path: PathBuf::from("/tmp/cf.db"),
321 eviction_policy: EvictionPolicy::Lru,
322 recency_half_life_secs: 259_200.0,
323 ..Config::default()
324 };
325 let json = serde_json::to_string(&cfg).unwrap();
326 let back: Config = serde_json::from_str(&json).unwrap();
327 assert_eq!(back.max_entries, 1000);
328 assert_eq!(back.eviction_policy, EvictionPolicy::Lru);
329 }
330
331 #[test]
332 fn trait_objects_are_object_safe() {
333 // This test verifies that the traits compile as trait objects.
334 fn _assert_storage(_s: Box<dyn ContextStorage>) {}
335 fn _assert_searcher(_s: Box<dyn Searcher>) {}
336 }
337
338 #[test]
339 fn kind_constants_are_distinct() {
340 assert_ne!(kind::MANUAL, kind::SNAPSHOT);
341 assert_ne!(kind::MANUAL, kind::SUMMARY);
342 assert_ne!(kind::MANUAL, kind::FACT);
343 assert_ne!(kind::SNAPSHOT, kind::SUMMARY);
344 assert_ne!(kind::SNAPSHOT, kind::FACT);
345 assert_ne!(kind::SUMMARY, kind::FACT);
346 }
347
348 #[test]
349 fn scored_entry_json_roundtrip() {
350 let scored = ScoredEntry {
351 entry: ContextEntry {
352 id: "s1".into(),
353 content: "search hit".into(),
354 timestamp: 1_700_000_001,
355 kind: kind::SUMMARY.to_owned(),
356 scope: None,
357 session_id: None,
358 token_count: None,
359 metadata: None,
360 },
361 score: 0.95,
362 };
363 let json = serde_json::to_string(&scored).unwrap();
364 let back: ScoredEntry = serde_json::from_str(&json).unwrap();
365 assert_eq!(back.entry.id, "s1");
366 assert!((back.score - 0.95).abs() < f64::EPSILON);
367 }
368
369 #[test]
370 fn context_forge_is_send_sync() {
371 fn assert_send_sync<T: Send + Sync>() {}
372 assert_send_sync::<ContextForge>();
373 }
374
375 #[test]
376 fn context_forge_open_save_query_roundtrip() {
377 let config = Config {
378 db_path: PathBuf::from(":memory:"),
379 ..Config::default()
380 };
381 let cf = ContextForge::open(config).unwrap();
382
383 let id = cf
384 .save("hello world", kind::MANUAL, &SaveOptions::default())
385 .unwrap();
386 assert!(!id.is_empty());
387 assert_eq!(cf.count().unwrap(), 1);
388
389 let hits = cf.query("hello", None, 1000).unwrap();
390 assert_eq!(hits.len(), 1);
391 assert_eq!(hits[0].id, id);
392
393 assert!(cf.delete(&id).unwrap());
394 assert_eq!(cf.count().unwrap(), 0);
395 }
396
397 #[test]
398 fn context_forge_clear_all() {
399 let config = Config {
400 db_path: PathBuf::from(":memory:"),
401 ..Config::default()
402 };
403 let cf = ContextForge::open(config).unwrap();
404
405 cf.save("a", kind::MANUAL, &SaveOptions::default()).unwrap();
406 cf.save("b", kind::MANUAL, &SaveOptions::default()).unwrap();
407
408 let cleared = cf.clear_all().unwrap();
409 assert_eq!(cleared, 2);
410 assert_eq!(cf.count().unwrap(), 0);
411 }
412
413 /// A stub [`Distiller`] for tests that records the transcript it was
414 /// called with and returns a fixed [`DistilledMemory`].
415 struct StubDistiller {
416 transcript: std::sync::Mutex<Option<String>>,
417 }
418
419 impl StubDistiller {
420 fn new() -> Self {
421 Self {
422 transcript: std::sync::Mutex::new(None),
423 }
424 }
425 }
426
427 impl Distiller for StubDistiller {
428 fn distill(&self, transcript: &str) -> Result<DistilledMemory> {
429 *self.transcript.lock().unwrap() = Some(transcript.to_owned());
430 Ok(DistilledMemory {
431 summary: "User decided to roll back the deploy.".to_owned(),
432 facts: vec![
433 Fact {
434 kind: FactKind::Decision,
435 text: "We decided to roll back the deploy.".to_owned(),
436 },
437 Fact {
438 kind: FactKind::Preference,
439 text: "The user prefers terse commit messages.".to_owned(),
440 },
441 ],
442 })
443 }
444 }
445
446 #[test]
447 fn distill_and_save_scrubs_saves_and_returns_ids() {
448 let config = Config {
449 db_path: PathBuf::from(":memory:"),
450 ..Config::default()
451 };
452 let cf = ContextForge::open(config).unwrap();
453
454 let distiller = StubDistiller::new();
455 let transcript = "Here is a secret key=AKIAABCDEFGHIJKLMNOP end of transcript";
456
457 let opts = SaveOptions {
458 session_id: Some("sess-1".to_owned()),
459 scope: Some("project:test".to_owned()),
460 metadata: None,
461 };
462
463 let ids = cf.distill_and_save(transcript, &distiller, &opts).unwrap();
464
465 // Summary ID first, then one ID per fact.
466 assert_eq!(ids.len(), 3);
467 for id in &ids {
468 assert!(!id.is_empty());
469 }
470
471 // The transcript reaching the distiller was scrubbed.
472 let seen = distiller.transcript.lock().unwrap().clone().unwrap();
473 assert!(seen.contains("[REDACTED:aws-key]"));
474 assert!(!seen.contains("AKIAABCDEFGHIJKLMNOP"));
475
476 // Summary saved with kind::SUMMARY.
477 let summary = cf
478 .query("rollback OR rollback OR roll", None, 10_000)
479 .unwrap();
480 let summary_entry = summary
481 .iter()
482 .find(|e| e.id == ids[0])
483 .expect("summary entry present");
484 assert_eq!(summary_entry.kind, kind::SUMMARY);
485 assert_eq!(summary_entry.scope.as_deref(), Some("project:test"));
486 assert_eq!(summary_entry.session_id.as_deref(), Some("sess-1"));
487
488 // Facts saved with kind::FACT and the right metadata.
489 let all = cf.query(MATCH_ALL_QUERY, None, 100_000).unwrap();
490 for fact_id in &ids[1..] {
491 let fact_entry = all
492 .iter()
493 .find(|e| &e.id == fact_id)
494 .expect("fact entry present");
495 assert_eq!(fact_entry.kind, kind::FACT);
496 let metadata = fact_entry.metadata.as_ref().expect("metadata present");
497 assert_eq!(metadata["source"], "distill");
498 assert!(metadata["fact_kind"].is_string());
499 }
500 }
501}