mnemo_engine/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_engine::{Mnemo, MnemoConfig, Memory, MemoryType, RecallRequest};
16//!
17//! # fn main() -> mnemo_engine::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 embed;
55mod embed_cmd;
56mod error;
57mod format;
58mod index;
59pub mod mcp;
60mod memory;
61mod pager;
62mod result_cache;
63mod session;
64mod store;
65mod wal;
66
67pub use crypto::KdfParams;
68pub use embed::{Embedder, EmbedderIdentity};
69pub use embed_cmd::{EmbedCmd, DEFAULT_EMBED_TIMEOUT};
70pub use error::{MnemoError, Result};
71pub use index::{IndexConfig, IndexInfo};
72pub use memory::{
73 Filter, FilterTerm, KeyScope, Memory, MemoryPatch, MemoryType, Metric, Scope, ScoreWeights,
74 WriteOutcome, MNEMO_META_INVALID_AT, MNEMO_META_KEY, MNEMO_META_NS, MNEMO_META_SUPERSEDED_BY,
75 MNEMO_META_SUPERSEDES, MNEMO_META_UPDATED_AT,
76};
77pub use result_cache::{
78 CacheBudget, CacheFlushPolicy, CachePutOpts, CacheStats, CachedValue, SemanticCachePutOpts,
79 DEFAULT_BATCH_MAX_AGE, DEFAULT_BATCH_MAX_DIRTY, DEFAULT_MAX_BYTES, DEFAULT_MAX_ENTRIES,
80 DEFAULT_SEMANTIC_THRESHOLD,
81};
82pub use session::{Role, Session, Turn};
83pub use store::{
84 CompactReport, Mnemo, MnemoConfig, RecallRequest, RecallResponse, RecallResult, SnapshotInfo,
85 Stats,
86};
87
88/// Re-export of [`ulid::Ulid`], the identifier type used for memories.
89pub use ulid::Ulid;
90
91// --- Fsync counter -----------------------------------------------------
92//
93// Instrumentation plumbing for the Phase 6 top-3 cost #2 fix: the
94// planner wants to know how many `sync_all` calls each `flush()` issues
95// before deciding whether to batch any of them. Every fsync call site
96// bumps a thread-local counter; `Mnemo::flush` snapshots it before and
97// after, exposing the delta on `Stats::fsyncs_last_flush`. Thread-local
98// so handles on separate threads don't poison each other's counts; the
99// engine's one-writer-at-a-time locking means a single handle sees a
100// coherent stream.
101
102mod fsync_counter {
103 use std::cell::Cell;
104
105 thread_local! {
106 static COUNT: Cell<u64> = const { Cell::new(0) };
107 }
108
109 /// Call once per `sync_all`.
110 pub(crate) fn bump() {
111 COUNT.with(|c| c.set(c.get().wrapping_add(1)));
112 }
113
114 /// Monotonic counter snapshot for this thread.
115 pub(crate) fn count() -> u64 {
116 COUNT.with(|c| c.get())
117 }
118}
119
120pub(crate) use fsync_counter::{bump as bump_fsync, count as fsync_count};
121
122/// Build-time cryptographic backend information.
123///
124/// Populated at compile time from the active `cfg` flags. On ARMv8
125/// builds compiled with `--cfg aes_armv8 --cfg polyval_armv8` (set by
126/// the repo's `.cargo/config.toml` and both CI workflows) the `aes`
127/// and `polyval` crates emit hardware AES + PMULL instructions; without
128/// those flags they fall back to a constant-time software path that
129/// runs at roughly 5× the cost per page.
130///
131/// Published through [`build_info`], exposed by `mnemo info` on the
132/// CLI and `mnemo.build_info()` from the Python binding. The point is
133/// verification — nobody should have to profile a release build to find
134/// out whether it's running software AES.
135#[derive(Debug, Clone, Copy, PartialEq, Eq)]
136pub struct BuildInfo {
137 /// Package version (`CARGO_PKG_VERSION`), e.g. `"0.5.1"`.
138 pub version: &'static str,
139 /// Target triple this binary was built for, e.g.
140 /// `"aarch64-apple-darwin"`.
141 pub target: &'static str,
142 /// Human-readable AES backend. One of:
143 /// - `"armv8 hardware"` — ARM with `cfg(aes_armv8)`
144 /// - `"armv8 software"` — ARM without the cfg; constant-time fallback
145 /// - `"x86_64 AES-NI (runtime detect)"` — x86_64 with runtime
146 /// AES-NI detection in the `aes` crate
147 /// - `"portable software"` — any other target
148 pub aes_backend: &'static str,
149 /// Human-readable PMULL/CLMUL backend used by GHASH (part of AES-GCM).
150 /// Same shape as `aes_backend` but for `polyval`.
151 pub polyval_backend: &'static str,
152}
153
154/// Report this build's cryptographic backend configuration.
155///
156/// Cheap — all fields are `&'static str` populated at compile time.
157/// Safe to call from a hot path if, for some reason, that's useful.
158pub fn build_info() -> BuildInfo {
159 BuildInfo {
160 version: env!("CARGO_PKG_VERSION"),
161 target: TARGET_TRIPLE,
162 aes_backend: aes_backend_name(),
163 polyval_backend: polyval_backend_name(),
164 }
165}
166
167/// Target triple baked in via the `TARGET` env var that `cargo` sets
168/// for the host compile. Falls back to `"unknown"` if the var isn't
169/// set at build time (shouldn't happen under cargo, but a build.rs-free
170/// implementation keeps this crate build-script-free, so we use a
171/// cfg-based dispatch as the second-best).
172const TARGET_TRIPLE: &str = {
173 // `env!("TARGET")` isn't set by cargo for crates; it's set by rustc
174 // only for `std` builds. We approximate from `target_arch` /
175 // `target_os` cfgs so this stays build-script-free. Good enough
176 // for an info line; precise triples are a `cargo` or build.rs job.
177 if cfg!(all(target_arch = "aarch64", target_os = "macos")) {
178 "aarch64-apple-darwin"
179 } else if cfg!(all(target_arch = "aarch64", target_os = "linux")) {
180 "aarch64-unknown-linux-gnu"
181 } else if cfg!(all(target_arch = "x86_64", target_os = "macos")) {
182 "x86_64-apple-darwin"
183 } else if cfg!(all(target_arch = "x86_64", target_os = "linux")) {
184 "x86_64-unknown-linux-gnu"
185 } else if cfg!(all(target_arch = "x86_64", target_os = "windows")) {
186 "x86_64-pc-windows-msvc"
187 } else {
188 "unknown"
189 }
190};
191
192const fn aes_backend_name() -> &'static str {
193 if cfg!(aes_armv8) {
194 "armv8 hardware"
195 } else if cfg!(target_arch = "aarch64") {
196 // Software fallback is the dangerous case this whole mechanism
197 // exists to surface — flag it clearly so `mnemo info` makes it
198 // easy to notice a build picked up the slow path by mistake.
199 "armv8 software (constant-time fallback)"
200 } else if cfg!(target_arch = "x86_64") {
201 // `aes` 0.8.4 on x86_64 picks AES-NI vs the software path at
202 // runtime via the `cpufeatures` crate, so we can't tell from
203 // cfg alone which path a given invocation takes. In practice
204 // every x86_64 CPU shipped since ~2010 has AES-NI.
205 "x86_64 AES-NI (runtime detect)"
206 } else {
207 "portable software"
208 }
209}
210
211const fn polyval_backend_name() -> &'static str {
212 if cfg!(polyval_armv8) {
213 "armv8 PMULL hardware"
214 } else if cfg!(target_arch = "aarch64") {
215 "armv8 software (constant-time fallback)"
216 } else if cfg!(target_arch = "x86_64") {
217 "x86_64 CLMUL (runtime detect)"
218 } else {
219 "portable software"
220 }
221}
222
223/// Test-only crash-injection surface used by the Phase 1.3 proptest
224/// (`mnemo/tests/proptest_store.rs`). Compiled in under `cfg(test)`
225/// and the `failpoints` feature only; absent from release builds.
226///
227/// **Not part of the stable public API.** The double-underscore
228/// convention makes the "internal" contract obvious at the call site.
229#[cfg(any(test, feature = "failpoints"))]
230#[doc(hidden)]
231pub mod __failpoints {
232 /// Arm the pager and WAL commit path to fail on the Nth
233 /// subsequent write. `n = 0` fails the very next write; `n = -1`
234 /// (or any negative) disables. One-shot — disarms on trigger.
235 ///
236 /// Every write is checked before the byte hits the file, so a
237 /// triggered failure is guaranteed torn-BEFORE, never
238 /// torn-AFTER — critical for the "either pre-flush or post-flush"
239 /// invariant the property test asserts.
240 pub fn set_writes_until_fail(n: i64) {
241 crate::pager::failpoints::set_writes_until_fail(n)
242 }
243}
244
245/// Internal parse surfaces exposed for cargo-fuzz targets (Phase 1.2).
246///
247/// **Not part of the stable public API.** Each function feeds an
248/// arbitrary byte slice into a parse/decode path that a hostile
249/// `.mnemo` file (or a hostile MCP client) can send us, and returns
250/// `Result<()>` so a fuzz target only asserts "no panic." Marked
251/// `#[doc(hidden)]` so `cargo doc` doesn't advertise it; do not import
252/// from application code.
253#[doc(hidden)]
254pub mod __fuzz {
255 /// Parse a `.mnemo` header page (page 0, plaintext) from arbitrary
256 /// bytes. This is the pre-passphrase attack surface — a hostile
257 /// file hits it before any DEK exists.
258 pub fn parse_header(bytes: &[u8]) -> crate::Result<()> {
259 crate::format::Header::from_page(bytes).map(|_| ())
260 }
261
262 /// Replay the WAL scan over an arbitrary byte region. Delegates
263 /// to [`crate::wal::recover_bytes`]; a corrupt / truncated /
264 /// adversarial region must return `Err` or `Ok(None/Some(_))`,
265 /// never panic.
266 pub fn wal_recover_bytes(region: &[u8], wal_seq: u64) -> crate::Result<()> {
267 crate::wal::recover_bytes(region, wal_seq).map(|_| ())
268 }
269
270 /// Decode a `Memory` record body from arbitrary bytes.
271 pub fn decode_memory(bytes: &[u8]) -> crate::Result<()> {
272 rmp_serde::from_slice::<crate::Memory>(bytes)
273 .map(|_| ())
274 .map_err(|e| crate::MnemoError::Serialize(e.to_string()))
275 }
276
277 /// Decode a `CacheEntry` record body from arbitrary bytes. Type is
278 /// `pub(crate)`, so this wrapper hides it behind a unit return.
279 pub fn decode_cache_entry(bytes: &[u8]) -> crate::Result<()> {
280 rmp_serde::from_slice::<crate::result_cache::CacheEntry>(bytes)
281 .map(|_| ())
282 .map_err(|e| crate::MnemoError::Serialize(e.to_string()))
283 }
284
285 /// Decode a cache-directory page-run body (a `Vec<CacheDirectoryEntry>`)
286 /// from arbitrary bytes.
287 pub fn decode_cache_directory(bytes: &[u8]) -> crate::Result<()> {
288 rmp_serde::from_slice::<Vec<crate::result_cache::CacheDirectoryEntry>>(bytes)
289 .map(|_| ())
290 .map_err(|e| crate::MnemoError::Serialize(e.to_string()))
291 }
292
293 /// Parse a single MCP stdio JSON-RPC request line. Malformed
294 /// input returns `Err(String)`; the fuzz target only asserts
295 /// no panic and that the server would not die on this line.
296 pub fn parse_mcp_request_line(line: &str) -> Result<(), String> {
297 crate::mcp::__fuzz_parse_request_line(line)
298 }
299}