mnemo/lib.rs
1//! # Mnemo
2//!
3//! Mnemo is an **encrypted, single-file, portable agent-memory engine**.
4//!
5//! A whole memory store — vectors, content, metadata, and the multi-signal
6//! recall machinery an agent needs — lives in one file you can copy, back up,
7//! or hand to another process. The file is encrypted at rest with a two-tier
8//! key hierarchy: an Argon2id key-encryption key (KEK) derived from a
9//! passphrase wraps a random data-encryption key (DEK), and the DEK encrypts
10//! every page with AES-256-GCM.
11//!
12//! ## Quick start
13//!
14//! ```no_run
15//! use mnemo::{Mnemo, MnemoConfig, Memory, MemoryType, RecallRequest};
16//!
17//! # fn main() -> mnemo::Result<()> {
18//! let cfg = MnemoConfig { dimensions: 3, ..Default::default() };
19//! let mut db = Mnemo::create("agent.mnemo", "correct horse battery", cfg)?;
20//!
21//! db.remember(
22//! Memory::new("the user prefers dark mode", MemoryType::Semantic, vec![0.1, 0.2, 0.9])
23//! .with_agent("assistant-1")
24//! .with_importance(0.8),
25//! )?;
26//! db.flush()?;
27//!
28//! let hits = db.recall(&RecallRequest::new(vec![0.1, 0.2, 0.9]).top_k(5))?;
29//! for h in hits {
30//! println!("{:.3} {}", h.score, h.memory.content);
31//! }
32//! # Ok(())
33//! # }
34//! ```
35//!
36//! ## What is and is not built
37//!
38//! This crate implements a real, tested core: the encrypted single-file
39//! storage engine, the crypto layer, the agent-memory model, multi-signal
40//! recall, an IVF+PQ approximate-nearest-neighbour index, a write-ahead log,
41//! snapshot-based point-in-time recovery, a bounded LRU page cache, and the
42//! [`Session`] conversation wrapper. Exact brute-force search remains
43//! available as the ground-truth baseline; a built index makes
44//! [`Mnemo::recall`] sub-linear. Each [`Mnemo::flush`] is one atomic,
45//! WAL-committed transaction and a restorable snapshot — [`Mnemo::restore_to`]
46//! rewinds the database to any past transaction. Python and TypeScript
47//! language bindings are the one documented roadmap item — see the README.
48
49#![forbid(unsafe_code)]
50#![warn(missing_docs)]
51
52mod cache;
53mod crypto;
54mod error;
55mod format;
56mod index;
57pub mod mcp;
58mod memory;
59mod pager;
60mod result_cache;
61mod session;
62mod store;
63mod wal;
64
65pub use crypto::KdfParams;
66pub use error::{MnemoError, Result};
67pub use index::{IndexConfig, IndexInfo};
68pub use memory::{Memory, MemoryType, Metric, Scope, ScoreWeights};
69pub use result_cache::{
70 CacheBudget, CacheFlushPolicy, CachePutOpts, CacheStats, CachedValue, SemanticCachePutOpts,
71 DEFAULT_BATCH_MAX_AGE, DEFAULT_BATCH_MAX_DIRTY, DEFAULT_MAX_BYTES, DEFAULT_MAX_ENTRIES,
72 DEFAULT_SEMANTIC_THRESHOLD,
73};
74pub use session::{Role, Session, Turn};
75pub use store::{
76 CompactReport, Mnemo, MnemoConfig, RecallRequest, RecallResult, SnapshotInfo, Stats,
77};
78
79/// Re-export of [`ulid::Ulid`], the identifier type used for memories.
80pub use ulid::Ulid;
81
82/// Test-only crash-injection surface used by the Phase 1.3 proptest
83/// (`mnemo/tests/proptest_store.rs`). Compiled in under `cfg(test)`
84/// and the `failpoints` feature only; absent from release builds.
85///
86/// **Not part of the stable public API.** The double-underscore
87/// convention makes the "internal" contract obvious at the call site.
88#[cfg(any(test, feature = "failpoints"))]
89#[doc(hidden)]
90pub mod __failpoints {
91 /// Arm the pager and WAL commit path to fail on the Nth
92 /// subsequent write. `n = 0` fails the very next write; `n = -1`
93 /// (or any negative) disables. One-shot — disarms on trigger.
94 ///
95 /// Every write is checked before the byte hits the file, so a
96 /// triggered failure is guaranteed torn-BEFORE, never
97 /// torn-AFTER — critical for the "either pre-flush or post-flush"
98 /// invariant the property test asserts.
99 pub fn set_writes_until_fail(n: i64) {
100 crate::pager::failpoints::set_writes_until_fail(n)
101 }
102}
103
104/// Internal parse surfaces exposed for cargo-fuzz targets (Phase 1.2).
105///
106/// **Not part of the stable public API.** Each function feeds an
107/// arbitrary byte slice into a parse/decode path that a hostile
108/// `.mnemo` file (or a hostile MCP client) can send us, and returns
109/// `Result<()>` so a fuzz target only asserts "no panic." Marked
110/// `#[doc(hidden)]` so `cargo doc` doesn't advertise it; do not import
111/// from application code.
112#[doc(hidden)]
113pub mod __fuzz {
114 /// Parse a `.mnemo` header page (page 0, plaintext) from arbitrary
115 /// bytes. This is the pre-passphrase attack surface — a hostile
116 /// file hits it before any DEK exists.
117 pub fn parse_header(bytes: &[u8]) -> crate::Result<()> {
118 crate::format::Header::from_page(bytes).map(|_| ())
119 }
120
121 /// Replay the WAL scan over an arbitrary byte region. Delegates
122 /// to [`crate::wal::recover_bytes`]; a corrupt / truncated /
123 /// adversarial region must return `Err` or `Ok(None/Some(_))`,
124 /// never panic.
125 pub fn wal_recover_bytes(region: &[u8], wal_seq: u64) -> crate::Result<()> {
126 crate::wal::recover_bytes(region, wal_seq).map(|_| ())
127 }
128
129 /// Decode a `Memory` record body from arbitrary bytes.
130 pub fn decode_memory(bytes: &[u8]) -> crate::Result<()> {
131 rmp_serde::from_slice::<crate::Memory>(bytes)
132 .map(|_| ())
133 .map_err(|e| crate::MnemoError::Serialize(e.to_string()))
134 }
135
136 /// Decode a `CacheEntry` record body from arbitrary bytes. Type is
137 /// `pub(crate)`, so this wrapper hides it behind a unit return.
138 pub fn decode_cache_entry(bytes: &[u8]) -> crate::Result<()> {
139 rmp_serde::from_slice::<crate::result_cache::CacheEntry>(bytes)
140 .map(|_| ())
141 .map_err(|e| crate::MnemoError::Serialize(e.to_string()))
142 }
143
144 /// Decode a cache-directory page-run body (a `Vec<CacheDirectoryEntry>`)
145 /// from arbitrary bytes.
146 pub fn decode_cache_directory(bytes: &[u8]) -> crate::Result<()> {
147 rmp_serde::from_slice::<Vec<crate::result_cache::CacheDirectoryEntry>>(bytes)
148 .map(|_| ())
149 .map_err(|e| crate::MnemoError::Serialize(e.to_string()))
150 }
151
152 /// Parse a single MCP stdio JSON-RPC request line. Malformed
153 /// input returns `Err(String)`; the fuzz target only asserts
154 /// no panic and that the server would not die on this line.
155 pub fn parse_mcp_request_line(line: &str) -> Result<(), String> {
156 crate::mcp::__fuzz_parse_request_line(line)
157 }
158}