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