Skip to main content

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 freelist;
59mod index;
60mod keyslot;
61pub mod mcp;
62mod memory;
63mod pager;
64mod result_cache;
65mod session;
66mod shared;
67mod store;
68mod text;
69mod transcript;
70mod veccol;
71mod wal;
72
73pub use crypto::KdfParams;
74pub use embed::{Embedder, EmbedderIdentity};
75pub use embed_cmd::{EmbedCmd, DEFAULT_EMBED_TIMEOUT};
76pub use error::{MnemoError, Result};
77pub use index::{IndexConfig, IndexInfo};
78pub use memory::{
79    status as essence_status, CommitBatch, CommitReport, EssenceOp, EssenceOpKind, EssenceScope,
80    EssenceSection, ExportedTurn, Filter, FilterTerm, IngestReport, KeyScope, KeyedMemory, Memory,
81    MemoryPatch, MemoryType, Metric, Scope, ScoreWeights, ThreadTurn, TurnPolicy, WriteOutcome,
82    CONTINUATION_TIMELINE_ENTRIES, ESSENCE_DEFAULT_RENDER_BYTES, ESSENCE_SECTION_MAX_BYTES,
83    ESSENCE_TIMELINE_MAX_BYTES, ESSENCE_TRANSITIONS, FINDING_TRANSITIONS, MNEMO_META_CONTINUES,
84    MNEMO_META_INVALID_AT, MNEMO_META_KEY, MNEMO_META_KIND, MNEMO_META_KIND_ESSENCE,
85    MNEMO_META_KIND_THREAD_LINK, MNEMO_META_KIND_TURN, MNEMO_META_LENGTH, MNEMO_META_NS,
86    MNEMO_META_PART, MNEMO_META_REFS, MNEMO_META_ROLE, MNEMO_META_SECTION, MNEMO_META_SEQ,
87    MNEMO_META_SHA256, MNEMO_META_STATUS, MNEMO_META_STATUS_HISTORY, MNEMO_META_SUPERSEDED_BY,
88    MNEMO_META_SUPERSEDES, MNEMO_META_THREAD, MNEMO_META_TURN_ID, MNEMO_META_UPDATED_AT,
89    TASK_TRANSITIONS, THREAD_TOOL_RESULT_TRUNCATE_BYTES, THREAD_TURN_CHUNK_BYTES,
90};
91pub use result_cache::{
92    CacheBudget, CacheFlushPolicy, CachePutOpts, CacheStats, CachedValue, SemanticCachePutOpts,
93    DEFAULT_BATCH_MAX_AGE, DEFAULT_BATCH_MAX_DIRTY, DEFAULT_MAX_BYTES, DEFAULT_MAX_ENTRIES,
94    DEFAULT_SEMANTIC_THRESHOLD,
95};
96pub use session::{Role, Session, Turn};
97pub use shared::{CancelToken, SharedOptions};
98#[doc(hidden)]
99#[cfg(feature = "dev-hooks")]
100pub use store::BudgetReport;
101pub use store::{
102    CloseError, CompactReport, Mnemo, MnemoConfig, RecallMode, RecallRequest, RecallResponse,
103    RecallResult, SharedMnemo, SnapshotInfo, Stats, StatsSummary, VerifyReport,
104    DEFAULT_KEYWORD_WEIGHT, DEFAULT_TURN_COMPRESS_AFTER_SECS, DEFAULT_VECTOR_CACHE_BUDGET,
105    INDEX_PERSIST_EVERY_CHANGES, INDEX_PERSIST_EVERY_COMMITS, V9_ANN_MIN_FACTS, V9_RERANK_PER_HIT,
106};
107pub use text::KeywordIndex;
108pub use transcript::{read_transcript, TranscriptFormat};
109
110/// Re-export of [`ulid::Ulid`], the identifier type used for memories.
111pub use ulid::Ulid;
112
113// --- Fsync counter -----------------------------------------------------
114//
115// Instrumentation plumbing for the Phase 6 top-3 cost #2 fix: the
116// planner wants to know how many `sync_all` calls each `flush()` issues
117// before deciding whether to batch any of them. Every fsync call site
118// bumps a thread-local counter; `Mnemo::flush` snapshots it before and
119// after, exposing the delta on `Stats::fsyncs_last_flush`. Thread-local
120// so handles on separate threads don't poison each other's counts; the
121// engine's one-writer-at-a-time locking means a single handle sees a
122// coherent stream.
123
124mod fsync_counter {
125    use std::cell::Cell;
126
127    thread_local! {
128        static COUNT: Cell<u64> = const { Cell::new(0) };
129    }
130
131    /// Call once per `sync_all`.
132    pub(crate) fn bump() {
133        COUNT.with(|c| c.set(c.get().wrapping_add(1)));
134    }
135
136    /// Monotonic counter snapshot for this thread.
137    pub(crate) fn count() -> u64 {
138        COUNT.with(|c| c.get())
139    }
140}
141
142pub(crate) use fsync_counter::{bump as bump_fsync, count as fsync_count};
143
144/// Build-time cryptographic backend information.
145///
146/// Populated at compile time from the active `cfg` flags. On ARMv8
147/// builds compiled with `--cfg aes_armv8 --cfg polyval_armv8` (set by
148/// the repo's `.cargo/config.toml` and both CI workflows) the `aes`
149/// and `polyval` crates emit hardware AES + PMULL instructions; without
150/// those flags they fall back to a constant-time software path that
151/// runs at roughly 5× the cost per page.
152///
153/// Published through [`build_info`], exposed by `mnemo info` on the
154/// CLI and `mnemo.build_info()` from the Python binding. The point is
155/// verification — nobody should have to profile a release build to find
156/// out whether it's running software AES.
157#[derive(Debug, Clone, Copy, PartialEq, Eq)]
158pub struct BuildInfo {
159    /// Package version (`CARGO_PKG_VERSION`), e.g. `"0.5.1"`.
160    pub version: &'static str,
161    /// Target triple this binary was built for, e.g.
162    /// `"aarch64-apple-darwin"`.
163    pub target: &'static str,
164    /// Human-readable AES backend. One of:
165    /// - `"armv8 hardware"` — ARM with `cfg(aes_armv8)`
166    /// - `"armv8 software"` — ARM without the cfg; constant-time fallback
167    /// - `"x86_64 AES-NI (runtime detect)"` — x86_64 with runtime
168    ///   AES-NI detection in the `aes` crate
169    /// - `"portable software"` — any other target
170    pub aes_backend: &'static str,
171    /// Human-readable PMULL/CLMUL backend used by GHASH (part of AES-GCM).
172    /// Same shape as `aes_backend` but for `polyval`.
173    pub polyval_backend: &'static str,
174}
175
176/// Report this build's cryptographic backend configuration.
177///
178/// Cheap — all fields are `&'static str` populated at compile time.
179/// Safe to call from a hot path if, for some reason, that's useful.
180pub fn build_info() -> BuildInfo {
181    BuildInfo {
182        version: env!("CARGO_PKG_VERSION"),
183        target: TARGET_TRIPLE,
184        aes_backend: aes_backend_name(),
185        polyval_backend: polyval_backend_name(),
186    }
187}
188
189/// Target triple baked in via the `TARGET` env var that `cargo` sets
190/// for the host compile. Falls back to `"unknown"` if the var isn't
191/// set at build time (shouldn't happen under cargo, but a build.rs-free
192/// implementation keeps this crate build-script-free, so we use a
193/// cfg-based dispatch as the second-best).
194const TARGET_TRIPLE: &str = {
195    // `env!("TARGET")` isn't set by cargo for crates; it's set by rustc
196    // only for `std` builds. We approximate from `target_arch` /
197    // `target_os` cfgs so this stays build-script-free. Good enough
198    // for an info line; precise triples are a `cargo` or build.rs job.
199    if cfg!(all(target_arch = "aarch64", target_os = "macos")) {
200        "aarch64-apple-darwin"
201    } else if cfg!(all(target_arch = "aarch64", target_os = "linux")) {
202        "aarch64-unknown-linux-gnu"
203    } else if cfg!(all(target_arch = "x86_64", target_os = "macos")) {
204        "x86_64-apple-darwin"
205    } else if cfg!(all(target_arch = "x86_64", target_os = "linux")) {
206        "x86_64-unknown-linux-gnu"
207    } else if cfg!(all(target_arch = "x86_64", target_os = "windows")) {
208        "x86_64-pc-windows-msvc"
209    } else {
210        "unknown"
211    }
212};
213
214const fn aes_backend_name() -> &'static str {
215    if cfg!(aes_armv8) {
216        "armv8 hardware"
217    } else if cfg!(target_arch = "aarch64") {
218        // Software fallback is the dangerous case this whole mechanism
219        // exists to surface — flag it clearly so `mnemo info` makes it
220        // easy to notice a build picked up the slow path by mistake.
221        "armv8 software (constant-time fallback)"
222    } else if cfg!(target_arch = "x86_64") {
223        // `aes` 0.8.4 on x86_64 picks AES-NI vs the software path at
224        // runtime via the `cpufeatures` crate, so we can't tell from
225        // cfg alone which path a given invocation takes. In practice
226        // every x86_64 CPU shipped since ~2010 has AES-NI.
227        "x86_64 AES-NI (runtime detect)"
228    } else {
229        "portable software"
230    }
231}
232
233const fn polyval_backend_name() -> &'static str {
234    if cfg!(polyval_armv8) {
235        "armv8 PMULL hardware"
236    } else if cfg!(target_arch = "aarch64") {
237        "armv8 software (constant-time fallback)"
238    } else if cfg!(target_arch = "x86_64") {
239        "x86_64 CLMUL (runtime detect)"
240    } else {
241        "portable software"
242    }
243}
244
245/// **Not a stable API** (`dev-hooks` builds only): how many `sync_all`
246/// calls this thread has made, for step 5's bench to count a write's
247/// fsyncs.
248#[cfg(feature = "dev-hooks")]
249#[doc(hidden)]
250pub fn __fsync_count() -> u64 {
251    fsync_count()
252}
253
254/// Test-only crash-injection surface used by the Phase 1.3 proptest
255/// (`mnemo/tests/proptest_store.rs`). Compiled in under `cfg(test)`
256/// and the `failpoints` feature only; absent from release builds.
257///
258/// **Not part of the stable public API.** The double-underscore
259/// convention makes the "internal" contract obvious at the call site.
260#[cfg(any(test, feature = "failpoints"))]
261#[doc(hidden)]
262pub mod __failpoints {
263    /// Arm the pager and WAL commit path to fail on the Nth
264    /// subsequent write. `n = 0` fails the very next write; `n = -1`
265    /// (or any negative) disables. One-shot — disarms on trigger.
266    ///
267    /// Every write is checked before the byte hits the file, so a
268    /// triggered failure is guaranteed torn-BEFORE, never
269    /// torn-AFTER — critical for the "either pre-flush or post-flush"
270    /// invariant the property test asserts.
271    pub fn set_writes_until_fail(n: i64) {
272        crate::pager::failpoints::set_writes_until_fail(n)
273    }
274
275    /// Like [`set_writes_until_fail`], but `count` writes in a row fail.
276    pub fn set_writes_until_fail_n(n: i64, count: u32) {
277        crate::pager::failpoints::set_writes_until_fail_n(n, count)
278    }
279
280    /// Fail exactly the writes numbered in `ns` (from 0, counting from this
281    /// call), consecutive or not; an empty set disarms it.
282    pub fn set_writes_failing(ns: &[u64]) {
283        crate::pager::failpoints::set_writes_failing(ns)
284    }
285
286    /// How many writes this thread has made since the last
287    /// [`set_writes_failing`].
288    pub fn writes_seen() -> u64 {
289        crate::pager::failpoints::writes_seen()
290    }
291
292    thread_local! {
293        static AFTER_SHARED_COMMIT: std::cell::RefCell<Option<Box<dyn FnOnce()>>> =
294            const { std::cell::RefCell::new(None) };
295        static BEFORE_SHARED_COMMIT: std::cell::RefCell<Option<Box<dyn FnOnce()>>> =
296            const { std::cell::RefCell::new(None) };
297    }
298
299    /// Run `f` once, inside this thread's next shared-mode write, after the
300    /// window's closure and before the window's commit (so after the
301    /// window's identity check, 12.4 protocol step 4). Lets a test rename a
302    /// file over the path the way an older build's compaction can.
303    pub fn before_next_shared_commit(f: impl FnOnce() + 'static) {
304        BEFORE_SHARED_COMMIT.with(|c| *c.borrow_mut() = Some(Box::new(f)));
305    }
306
307    pub(crate) fn run_before_shared_commit() {
308        if let Some(f) = BEFORE_SHARED_COMMIT.with(|c| c.borrow_mut().take()) {
309            f();
310        }
311    }
312
313    /// Run `f` once, inside this thread's next shared-mode write, after its
314    /// commit and before the identity check that follows (12.4 protocol
315    /// step 8). Lets a test rename a file over the path at that moment.
316    pub fn after_next_shared_commit(f: impl FnOnce() + 'static) {
317        AFTER_SHARED_COMMIT.with(|c| *c.borrow_mut() = Some(Box::new(f)));
318    }
319
320    pub(crate) fn run_after_shared_commit() {
321        if let Some(f) = AFTER_SHARED_COMMIT.with(|c| c.borrow_mut().take()) {
322            f();
323        }
324    }
325
326    thread_local! {
327        static NEXT_TEMP_NAME: std::cell::RefCell<Option<std::path::PathBuf>> =
328            const { std::cell::RefCell::new(None) };
329    }
330
331    /// Make the next temp file name this thread asks for (compaction,
332    /// `export_encrypted`, `export_rekeyed`) be `path`, once; the attempts
333    /// after it are generated as usual. Lets a test plant a file or a
334    /// symlink at the exact name the engine is about to use.
335    pub fn set_next_temp_name(path: impl Into<std::path::PathBuf>) {
336        NEXT_TEMP_NAME.with(|n| *n.borrow_mut() = Some(path.into()));
337    }
338
339    pub(crate) fn take_next_temp_name() -> Option<std::path::PathBuf> {
340        NEXT_TEMP_NAME.with(|n| n.borrow_mut().take())
341    }
342
343    thread_local! {
344        static SHARED_MAIN_TRIES: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
345        static SHARED_REPLACED: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
346    }
347
348    /// How many times this thread's shared-mode calls have tried the main
349    /// lock (each open, lock and identity check counts once).
350    pub fn shared_main_tries() -> u64 {
351        SHARED_MAIN_TRIES.with(|c| c.get())
352    }
353
354    pub(crate) fn count_shared_main_try() {
355        SHARED_MAIN_TRIES.with(|c| c.set(c.get() + 1));
356    }
357
358    /// Make this thread's next `n` shared-mode tries at the main lock find
359    /// the file replaced (as if a compaction renamed a new file over the
360    /// path between the open and the lock each time). `0` disarms.
361    pub fn set_shared_replaced(n: u64) {
362        SHARED_REPLACED.with(|c| c.set(n));
363    }
364
365    thread_local! {
366        static EUID_OVERRIDE: std::cell::Cell<Option<u32>> = const { std::cell::Cell::new(None) };
367    }
368
369    /// Make this thread's file-owner checks (the dead compaction temp
370    /// files' cleanup) compare against `uid` instead of the effective uid,
371    /// so a test can see a file as another user's without root. `None`
372    /// restores the real check.
373    pub fn set_euid_override(uid: Option<u32>) {
374        EUID_OVERRIDE.with(|c| c.set(uid));
375    }
376
377    // Read by the Unix owner check only.
378    #[cfg(unix)]
379    pub(crate) fn euid_override() -> Option<u32> {
380        EUID_OVERRIDE.with(|c| c.get())
381    }
382
383    thread_local! {
384        static PATH_CHECK_FAILURES: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
385    }
386
387    /// Make this thread's next `n` checks that a handle's path still names
388    /// its open file fail with a permission error (RB-008.2), as when the
389    /// process has lost access to the path. `0` disarms.
390    pub fn set_path_check_failures(n: u64) {
391        PATH_CHECK_FAILURES.with(|c| c.set(n));
392    }
393
394    /// How many armed path-check failures this thread has left.
395    pub fn path_check_failures_left() -> u64 {
396        PATH_CHECK_FAILURES.with(|c| c.get())
397    }
398
399    pub(crate) fn take_path_check_failure() -> bool {
400        PATH_CHECK_FAILURES.with(|c| {
401            let n = c.get();
402            if n > 0 {
403                c.set(n - 1);
404            }
405            n > 0
406        })
407    }
408
409    pub(crate) fn take_shared_replaced() -> bool {
410        SHARED_REPLACED.with(|c| {
411            let n = c.get();
412            if n > 0 {
413                c.set(n - 1);
414            }
415            n > 0
416        })
417    }
418}
419
420/// 12.4 step 2a: the shared lock layer, reached directly by its tests
421/// (`tests/shared_lock.rs`) until `Mnemo::open_shared` (step 2b) wraps it.
422/// Compiled in under `cfg(test)` and the `failpoints` feature only.
423///
424/// **Not part of the stable public API.**
425#[cfg(any(test, feature = "failpoints"))]
426#[doc(hidden)]
427pub mod __shared {
428    use std::path::{Path, PathBuf};
429
430    use crate::shared::{BrainLocks, Call, Held, LockKind};
431    use crate::{Result, SharedOptions};
432
433    /// The sidecar directory's suffix and its two file names.
434    pub const SUFFIX: &str = crate::shared::testing::SUFFIX;
435    pub const INTENT: &str = crate::shared::testing::INTENT;
436    pub const LOCK_INFO: &str = crate::shared::testing::LOCK_INFO;
437
438    /// Whether this build refuses shared mode (Windows, Rust before 1.85).
439    pub const WINDOWS_OLD_RENAME: bool = crate::shared::WINDOWS_OLD_RENAME;
440
441    /// `<brain>.mnemo-shared` for a resolved brain path.
442    pub fn sidecar_path(brain: &Path) -> PathBuf {
443        crate::shared::testing::sidecar_path(brain)
444    }
445
446    /// The macOS synced-folder rule, as a pure function.
447    pub fn classify_synced(path: &Path, home: &Path) -> Option<String> {
448        crate::shared::testing::classify_synced(path, home)
449    }
450
451    /// Whether a Linux `statfs` magic number is allowed.
452    pub fn linux_fs_allowed(magic: u32) -> bool {
453        crate::shared::testing::linux_fs_allowed(magic)
454    }
455
456    /// The lock layer for one brain.
457    #[derive(Debug)]
458    pub struct Locks(BrainLocks);
459
460    impl Locks {
461        pub fn new(path: &Path, opts: &SharedOptions) -> Result<Self> {
462            BrainLocks::new(path, opts).map(Locks)
463        }
464        pub fn shared(&mut self, opts: &SharedOptions) -> Result<Lock> {
465            let mut call = Call::new(opts.deadline, opts.cancel.as_ref());
466            self.0.acquire(LockKind::Shared, &mut call).map(Lock)
467        }
468        pub fn exclusive(&mut self, opts: &SharedOptions) -> Result<Lock> {
469            let mut call = Call::new(opts.deadline, opts.cancel.as_ref());
470            self.0.acquire(LockKind::Exclusive, &mut call).map(Lock)
471        }
472        pub fn has_sidecar(&self) -> bool {
473            self.0.has_sidecar()
474        }
475        pub fn sidecar_path(&self) -> Option<PathBuf> {
476            self.0.sidecar_path().map(Path::to_path_buf)
477        }
478        pub fn notices(&self) -> Vec<String> {
479            self.0.notices().to_vec()
480        }
481    }
482
483    /// One call's main lock; dropping it unlocks.
484    pub struct Lock(Held);
485
486    impl Lock {
487        pub fn announce(&mut self, op: &str) {
488            self.0.announce(op)
489        }
490        pub fn file(&self) -> &std::fs::File {
491            self.0.file()
492        }
493    }
494}
495
496/// WAL entry points for the PERF-1 allocation test
497/// (`tests/wal_recover_alloc.rs`), which needs its own global allocator and
498/// so can't live in this `forbid(unsafe_code)` crate. Not a stable API.
499#[doc(hidden)]
500pub mod __wal {
501    /// Page size of the WAL region.
502    pub const PAGE_SIZE: usize = crate::format::PAGE_SIZE;
503
504    /// One WAL frame: a home page number and its page image.
505    pub type Frame = (u64, Vec<u8>);
506
507    /// Bytes a transaction of `n` page frames occupies.
508    pub fn txn_byte_len(n: usize) -> u64 {
509        crate::wal::txn_byte_len(n, PAGE_SIZE)
510    }
511
512    /// Commit `frames` as transaction `txn_id` at the start of a region.
513    pub fn commit(
514        file: &mut std::fs::File,
515        wal_pages: u64,
516        txn_id: u64,
517        frames: &[Frame],
518    ) -> crate::Result<()> {
519        crate::wal::commit(file, 0, wal_pages, txn_id, frames)
520    }
521
522    /// Run open-time recovery over a region starting at page 0; returns the
523    /// frames to replay, if any.
524    pub fn recover(
525        file: &mut std::fs::File,
526        wal_pages: u64,
527        wal_seq: u64,
528    ) -> crate::Result<Option<Vec<Frame>>> {
529        crate::wal::recover(file, 0, wal_pages, wal_seq)
530    }
531}
532
533/// Internal parse surfaces exposed for cargo-fuzz targets (Phase 1.2).
534///
535/// **Not part of the stable public API.** Each function feeds an
536/// arbitrary byte slice into a parse/decode path that a hostile
537/// `.mnemo` file (or a hostile MCP client) can send us, and returns
538/// `Result<()>` so a fuzz target only asserts "no panic." Marked
539/// `#[doc(hidden)]` so `cargo doc` doesn't advertise it; do not import
540/// from application code.
541#[doc(hidden)]
542pub mod __fuzz {
543    /// Parse a `.mnemo` header page (page 0, plaintext) from arbitrary
544    /// bytes. This is the pre-passphrase attack surface — a hostile
545    /// file hits it before any DEK exists.
546    pub fn parse_header(bytes: &[u8]) -> crate::Result<()> {
547        crate::format::Header::from_page(bytes).map(|_| ())
548    }
549
550    /// Replay the WAL scan over an arbitrary byte region. Delegates
551    /// to [`crate::wal::recover_bytes`]; a corrupt / truncated /
552    /// adversarial region must return `Err` or `Ok(None/Some(_))`,
553    /// never panic.
554    pub fn wal_recover_bytes(region: &[u8], wal_seq: u64) -> crate::Result<()> {
555        crate::wal::recover_bytes(region, wal_seq).map(|_| ())
556    }
557
558    /// Decode a `Memory` record body from arbitrary bytes.
559    pub fn decode_memory(bytes: &[u8]) -> crate::Result<()> {
560        rmp_serde::from_slice::<crate::Memory>(bytes)
561            .map(|_| ())
562            .map_err(|e| crate::MnemoError::Serialize(e.to_string()))
563    }
564
565    /// FMT-9e: decode a v9 `Memory` record body from arbitrary bytes: a
566    /// zstd frame (a compressed thread turn) is decompressed first, under
567    /// the same content-size bound the store applies.
568    pub fn decode_v9_memory(bytes: &[u8]) -> crate::Result<()> {
569        let plain = crate::store::plain_record(bytes)?;
570        rmp_serde::from_slice::<crate::Memory>(&plain)
571            .map(|_| ())
572            .map_err(|e| crate::MnemoError::Serialize(e.to_string()))
573    }
574
575    /// Decode a `CacheEntry` record body from arbitrary bytes. Type is
576    /// `pub(crate)`, so this wrapper hides it behind a unit return.
577    pub fn decode_cache_entry(bytes: &[u8]) -> crate::Result<()> {
578        rmp_serde::from_slice::<crate::result_cache::CacheEntry>(bytes)
579            .map(|_| ())
580            .map_err(|e| crate::MnemoError::Serialize(e.to_string()))
581    }
582
583    /// Decode a cache-directory page-run body (a `Vec<CacheDirectoryEntry>`)
584    /// from arbitrary bytes.
585    pub fn decode_cache_directory(bytes: &[u8]) -> crate::Result<()> {
586        rmp_serde::from_slice::<Vec<crate::result_cache::CacheDirectoryEntry>>(bytes)
587            .map(|_| ())
588            .map_err(|e| crate::MnemoError::Serialize(e.to_string()))
589    }
590
591    /// Parse a single MCP stdio JSON-RPC request line. Malformed
592    /// input returns `Err(String)`; the fuzz target only asserts
593    /// no panic and that the server would not die on this line.
594    pub fn parse_mcp_request_line(line: &str) -> Result<(), String> {
595        crate::mcp::__fuzz_parse_request_line(line)
596    }
597}