mnemo-engine 0.16.1

Encrypted, single-file, portable agent memory engine with multi-signal recall, sessions, snapshots, and an IVF+PQ index
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
//! # Mnemo
//!
//! Mnemo is an **encrypted, single-file, portable agent-memory engine**.
//!
//! A whole memory store — vectors, content, metadata, and the multi-signal
//! recall machinery an agent needs — lives in one file you can copy, back up,
//! or hand to another process. The file is encrypted at rest with a two-tier
//! key hierarchy: an Argon2id key-encryption key (KEK) derived from a
//! passphrase wraps a random data-encryption key (DEK), and the DEK encrypts
//! every page with AES-256-GCM.
//!
//! ## Quick start
//!
//! ```no_run
//! use mnemo_engine::{Mnemo, MnemoConfig, Memory, MemoryType, RecallRequest};
//!
//! # fn main() -> mnemo_engine::Result<()> {
//! let cfg = MnemoConfig { dimensions: 3, ..Default::default() };
//! let mut db = Mnemo::create("agent.mnemo", "correct horse battery", cfg)?;
//!
//! db.remember(
//!     Memory::new("the user prefers dark mode", MemoryType::Semantic, vec![0.1, 0.2, 0.9])
//!         .with_agent("assistant-1")
//!         .with_importance(0.8),
//! )?;
//! db.flush()?;
//!
//! let hits = db.recall(&RecallRequest::new(vec![0.1, 0.2, 0.9]).top_k(5))?;
//! for h in hits {
//!     println!("{:.3}  {}", h.score, h.memory.content);
//! }
//! # Ok(())
//! # }
//! ```
//!
//! ## What is and is not built
//!
//! This crate implements a real, tested core: the encrypted single-file
//! storage engine, the crypto layer, the agent-memory model, multi-signal
//! recall, an IVF+PQ approximate-nearest-neighbour index, a write-ahead log,
//! snapshot-based point-in-time recovery, a bounded LRU page cache, and the
//! [`Session`] conversation wrapper. Exact brute-force search remains
//! available as the ground-truth baseline; a built index makes
//! [`Mnemo::recall`] sub-linear. Each [`Mnemo::flush`] is one atomic,
//! WAL-committed transaction and a restorable snapshot — [`Mnemo::restore_to`]
//! rewinds the database to any past transaction. Python and TypeScript
//! language bindings are the one documented roadmap item — see the README.

#![forbid(unsafe_code)]
#![warn(missing_docs)]
// Since step 5a (MSRV 1.92, now 1.94): `as_chunks` (stable since 1.88) is within the
// MSRV, so clippy suggests it for every constant-size `chunks_exact`. Those
// are the hot kernels (PQ distance tables, fp16 vectors, the WAL checksum);
// rewriting them waits for a change that measures them with the benches.
// `unknown_lints` first, so a clippy older than the lint (before 1.100)
// doesn't fail on its name.
#![allow(unknown_lints)]
#![allow(clippy::chunks_exact_to_as_chunks)]

/// 12.3 step 5 (v0.15): the built-in embedder (snowflake-arctic-embed-xs on
/// candle), behind the `embed-candle` feature.
#[cfg(feature = "embed-candle")]
pub mod builtin;
mod cache;
mod crypto;
mod embed;
mod embed_cmd;
mod error;
mod format;
mod freelist;
pub mod guide;
mod ident;
mod index;
pub mod keys;
mod keyslot;
pub mod mcp;
mod memory;
mod pager;
pub mod redact;
mod result_cache;
mod session;
mod shared;
mod store;
mod text;
mod transcript;
mod veccol;
mod wal;

#[cfg(feature = "embed-candle")]
pub use builtin::BuiltinEmbedder;
pub use crypto::{KdfParams, SecretKind};
pub use embed::{Embedder, EmbedderIdentity};
pub use embed_cmd::{EmbedCmd, DEFAULT_EMBED_TIMEOUT};
pub use error::{MnemoError, Result};
pub use index::{IndexConfig, IndexInfo};
pub use memory::{
    status as essence_status, CommitBatch, CommitReport, EssenceOp, EssenceOpKind, EssenceScope,
    EssenceSection, ExportedTurn, Filter, FilterTerm, IngestReport, KeyScope, KeyedMemory, Memory,
    MemoryPatch, MemoryType, Metric, Scope, ScoreWeights, ThreadTurn, TurnPolicy, WriteOutcome,
    CONTINUATION_TIMELINE_ENTRIES, ESSENCE_DEFAULT_RENDER_BYTES, ESSENCE_SECTION_MAX_BYTES,
    ESSENCE_TIMELINE_MAX_BYTES, ESSENCE_TRANSITIONS, FINDING_TRANSITIONS, MNEMO_META_CONTINUES,
    MNEMO_META_INVALID_AT, MNEMO_META_KEY, MNEMO_META_KIND, MNEMO_META_KIND_ESSENCE,
    MNEMO_META_KIND_THREAD_LINK, MNEMO_META_KIND_TURN, MNEMO_META_LENGTH, MNEMO_META_MARKERS_ONLY,
    MNEMO_META_NS, MNEMO_META_PART, MNEMO_META_REFS, MNEMO_META_ROLE, MNEMO_META_SECTION,
    MNEMO_META_SEQ, MNEMO_META_SHA256, MNEMO_META_STATUS, MNEMO_META_STATUS_HISTORY,
    MNEMO_META_SUPERSEDED_BY, MNEMO_META_SUPERSEDES, MNEMO_META_THREAD, MNEMO_META_TURN_ID,
    MNEMO_META_UPDATED_AT, TASK_TRANSITIONS, THREAD_TOOL_RESULT_TRUNCATE_BYTES,
    THREAD_TURN_CHUNK_BYTES,
};
pub use result_cache::{
    CacheBudget, CacheFlushPolicy, CachePutOpts, CacheStats, CachedValue, SemanticCachePutOpts,
    DEFAULT_BATCH_MAX_AGE, DEFAULT_BATCH_MAX_DIRTY, DEFAULT_MAX_BYTES, DEFAULT_MAX_ENTRIES,
    DEFAULT_SEMANTIC_THRESHOLD,
};
pub use session::{Role, Session, Turn};
pub use shared::{CancelToken, SharedOptions};
#[doc(hidden)]
#[cfg(feature = "dev-hooks")]
pub use store::BudgetReport;
pub use store::{
    CloseError, CompactReport, Mnemo, MnemoConfig, RecallMode, RecallRequest, RecallResponse,
    RecallResult, ReembedReport, SharedMnemo, SnapshotInfo, Stats, StatsSummary, VerifyReport,
    DEFAULT_KEYWORD_WEIGHT, DEFAULT_TEXT_KEYWORD_WEIGHT, DEFAULT_TURN_COMPRESS_AFTER_SECS,
    DEFAULT_VECTOR_CACHE_BUDGET, INDEX_PERSIST_EVERY_CHANGES, INDEX_PERSIST_EVERY_COMMITS,
    V9_ANN_MIN_FACTS, V9_RERANK_PER_HIT,
};
pub use text::{KeywordIndex, KeywordTokenizer};
pub use transcript::{
    read_transcript, read_transcript_with, ToolResults, TranscriptFormat, TranscriptOptions,
};

/// Re-export of [`ulid::Ulid`], the identifier type used for memories.
pub use ulid::Ulid;

// --- Fsync counter -----------------------------------------------------
//
// Instrumentation plumbing for the Phase 6 top-3 cost #2 fix: the
// planner wants to know how many `sync_all` calls each `flush()` issues
// before deciding whether to batch any of them. Every fsync call site
// bumps a thread-local counter; `Mnemo::flush` snapshots it before and
// after, exposing the delta on `Stats::fsyncs_last_flush`. Thread-local
// so handles on separate threads don't poison each other's counts; the
// engine's one-writer-at-a-time locking means a single handle sees a
// coherent stream.

mod fsync_counter {
    use std::cell::Cell;

    thread_local! {
        static COUNT: Cell<u64> = const { Cell::new(0) };
    }

    /// Call once per `sync_all`.
    pub(crate) fn bump() {
        COUNT.with(|c| c.set(c.get().wrapping_add(1)));
    }

    /// Monotonic counter snapshot for this thread.
    pub(crate) fn count() -> u64 {
        COUNT.with(|c| c.get())
    }
}

pub(crate) use fsync_counter::{bump as bump_fsync, count as fsync_count};

/// Build-time cryptographic backend information.
///
/// Populated at compile time from the active `cfg` flags. On ARMv8
/// builds compiled with `--cfg aes_armv8 --cfg polyval_armv8` (set by
/// the repo's `.cargo/config.toml` and both CI workflows) the `aes`
/// and `polyval` crates emit hardware AES + PMULL instructions; without
/// those flags they fall back to a constant-time software path that
/// runs at roughly 5× the cost per page.
///
/// Published through [`build_info`], exposed by `mnemo info` on the
/// CLI and `mnemo.build_info()` from the Python binding. The point is
/// verification — nobody should have to profile a release build to find
/// out whether it's running software AES.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BuildInfo {
    /// Package version (`CARGO_PKG_VERSION`), e.g. `"0.5.1"`.
    pub version: &'static str,
    /// Target triple this binary was built for, e.g.
    /// `"aarch64-apple-darwin"`.
    pub target: &'static str,
    /// Human-readable AES backend. One of:
    /// - `"armv8 hardware"` — ARM with `cfg(aes_armv8)`
    /// - `"armv8 software"` — ARM without the cfg; constant-time fallback
    /// - `"x86_64 AES-NI (runtime detect)"` — x86_64 with runtime
    ///   AES-NI detection in the `aes` crate
    /// - `"portable software"` — any other target
    pub aes_backend: &'static str,
    /// Human-readable PMULL/CLMUL backend used by GHASH (part of AES-GCM).
    /// Same shape as `aes_backend` but for `polyval`.
    pub polyval_backend: &'static str,
}

/// Report this build's cryptographic backend configuration.
///
/// Cheap — all fields are `&'static str` populated at compile time.
/// Safe to call from a hot path if, for some reason, that's useful.
pub fn build_info() -> BuildInfo {
    BuildInfo {
        version: env!("CARGO_PKG_VERSION"),
        target: TARGET_TRIPLE,
        aes_backend: aes_backend_name(),
        polyval_backend: polyval_backend_name(),
    }
}

/// Target triple baked in via the `TARGET` env var that `cargo` sets
/// for the host compile. Falls back to `"unknown"` if the var isn't
/// set at build time (shouldn't happen under cargo, but a build.rs-free
/// implementation keeps this crate build-script-free, so we use a
/// cfg-based dispatch as the second-best).
const TARGET_TRIPLE: &str = {
    // `env!("TARGET")` isn't set by cargo for crates; it's set by rustc
    // only for `std` builds. We approximate from `target_arch` /
    // `target_os` cfgs so this stays build-script-free. Good enough
    // for an info line; precise triples are a `cargo` or build.rs job.
    if cfg!(all(target_arch = "aarch64", target_os = "macos")) {
        "aarch64-apple-darwin"
    } else if cfg!(all(target_arch = "aarch64", target_os = "linux")) {
        "aarch64-unknown-linux-gnu"
    } else if cfg!(all(target_arch = "x86_64", target_os = "macos")) {
        "x86_64-apple-darwin"
    } else if cfg!(all(target_arch = "x86_64", target_os = "linux")) {
        "x86_64-unknown-linux-gnu"
    } else if cfg!(all(target_arch = "x86_64", target_os = "windows")) {
        "x86_64-pc-windows-msvc"
    } else {
        "unknown"
    }
};

const fn aes_backend_name() -> &'static str {
    if cfg!(aes_armv8) {
        "armv8 hardware"
    } else if cfg!(target_arch = "aarch64") {
        // Software fallback is the dangerous case this whole mechanism
        // exists to surface — flag it clearly so `mnemo info` makes it
        // easy to notice a build picked up the slow path by mistake.
        "armv8 software (constant-time fallback)"
    } else if cfg!(target_arch = "x86_64") {
        // `aes` 0.8.4 on x86_64 picks AES-NI vs the software path at
        // runtime via the `cpufeatures` crate, so we can't tell from
        // cfg alone which path a given invocation takes. In practice
        // every x86_64 CPU shipped since ~2010 has AES-NI.
        "x86_64 AES-NI (runtime detect)"
    } else {
        "portable software"
    }
}

const fn polyval_backend_name() -> &'static str {
    if cfg!(polyval_armv8) {
        "armv8 PMULL hardware"
    } else if cfg!(target_arch = "aarch64") {
        "armv8 software (constant-time fallback)"
    } else if cfg!(target_arch = "x86_64") {
        "x86_64 CLMUL (runtime detect)"
    } else {
        "portable software"
    }
}

/// **Not a stable API** (`dev-hooks` builds only): how many `sync_all`
/// calls this thread has made, for step 5's bench to count a write's
/// fsyncs.
#[cfg(feature = "dev-hooks")]
#[doc(hidden)]
pub fn __fsync_count() -> u64 {
    fsync_count()
}

/// Test-only crash-injection surface used by the Phase 1.3 proptest
/// (`mnemo/tests/proptest_store.rs`). Compiled in under `cfg(test)`
/// and the `failpoints` feature only; absent from release builds.
///
/// **Not part of the stable public API.** The double-underscore
/// convention makes the "internal" contract obvious at the call site.
#[cfg(any(test, feature = "failpoints"))]
#[doc(hidden)]
pub mod __failpoints {
    /// Arm the pager and WAL commit path to fail on the Nth
    /// subsequent write. `n = 0` fails the very next write; `n = -1`
    /// (or any negative) disables. One-shot — disarms on trigger.
    ///
    /// Every write is checked before the byte hits the file, so a
    /// triggered failure is guaranteed torn-BEFORE, never
    /// torn-AFTER — critical for the "either pre-flush or post-flush"
    /// invariant the property test asserts.
    pub fn set_writes_until_fail(n: i64) {
        crate::pager::failpoints::set_writes_until_fail(n)
    }

    /// Like [`set_writes_until_fail`], but `count` writes in a row fail.
    pub fn set_writes_until_fail_n(n: i64, count: u32) {
        crate::pager::failpoints::set_writes_until_fail_n(n, count)
    }

    /// Fail exactly the writes numbered in `ns` (from 0, counting from this
    /// call), consecutive or not; an empty set disarms it.
    pub fn set_writes_failing(ns: &[u64]) {
        crate::pager::failpoints::set_writes_failing(ns)
    }

    /// How many writes this thread has made since the last
    /// [`set_writes_failing`].
    pub fn writes_seen() -> u64 {
        crate::pager::failpoints::writes_seen()
    }

    thread_local! {
        static AFTER_SHARED_COMMIT: std::cell::RefCell<Option<Box<dyn FnOnce()>>> =
            const { std::cell::RefCell::new(None) };
        static BEFORE_SHARED_COMMIT: std::cell::RefCell<Option<Box<dyn FnOnce()>>> =
            const { std::cell::RefCell::new(None) };
    }

    /// Run `f` once, inside this thread's next shared-mode write, after the
    /// window's closure and before the window's commit (so after the
    /// window's identity check, 12.4 protocol step 4). Lets a test rename a
    /// file over the path the way an older build's compaction can.
    pub fn before_next_shared_commit(f: impl FnOnce() + 'static) {
        BEFORE_SHARED_COMMIT.with(|c| *c.borrow_mut() = Some(Box::new(f)));
    }

    pub(crate) fn run_before_shared_commit() {
        if let Some(f) = BEFORE_SHARED_COMMIT.with(|c| c.borrow_mut().take()) {
            f();
        }
    }

    /// Run `f` once, inside this thread's next shared-mode write, after its
    /// commit and before the identity check that follows (12.4 protocol
    /// step 8). Lets a test rename a file over the path at that moment.
    pub fn after_next_shared_commit(f: impl FnOnce() + 'static) {
        AFTER_SHARED_COMMIT.with(|c| *c.borrow_mut() = Some(Box::new(f)));
    }

    pub(crate) fn run_after_shared_commit() {
        if let Some(f) = AFTER_SHARED_COMMIT.with(|c| c.borrow_mut().take()) {
            f();
        }
    }

    thread_local! {
        static NEXT_TEMP_NAME: std::cell::RefCell<Option<std::path::PathBuf>> =
            const { std::cell::RefCell::new(None) };
    }

    /// Make the next temp file name this thread asks for (compaction,
    /// `export_encrypted`, `export_rekeyed`) be `path`, once; the attempts
    /// after it are generated as usual. Lets a test plant a file or a
    /// symlink at the exact name the engine is about to use.
    pub fn set_next_temp_name(path: impl Into<std::path::PathBuf>) {
        NEXT_TEMP_NAME.with(|n| *n.borrow_mut() = Some(path.into()));
    }

    pub(crate) fn take_next_temp_name() -> Option<std::path::PathBuf> {
        NEXT_TEMP_NAME.with(|n| n.borrow_mut().take())
    }

    thread_local! {
        static SHARED_MAIN_TRIES: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
        static SHARED_REPLACED: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
    }

    /// How many times this thread's shared-mode calls have tried the main
    /// lock (each open, lock and identity check counts once).
    pub fn shared_main_tries() -> u64 {
        SHARED_MAIN_TRIES.with(|c| c.get())
    }

    pub(crate) fn count_shared_main_try() {
        SHARED_MAIN_TRIES.with(|c| c.set(c.get() + 1));
    }

    /// Make this thread's next `n` shared-mode tries at the main lock find
    /// the file replaced (as if a compaction renamed a new file over the
    /// path between the open and the lock each time). `0` disarms.
    pub fn set_shared_replaced(n: u64) {
        SHARED_REPLACED.with(|c| c.set(n));
    }

    thread_local! {
        static EUID_OVERRIDE: std::cell::Cell<Option<u32>> = const { std::cell::Cell::new(None) };
    }

    /// Make this thread's file-owner checks (the dead compaction temp
    /// files' cleanup) compare against `uid` instead of the effective uid,
    /// so a test can see a file as another user's without root. `None`
    /// restores the real check.
    pub fn set_euid_override(uid: Option<u32>) {
        EUID_OVERRIDE.with(|c| c.set(uid));
    }

    // Read by the Unix owner check only.
    #[cfg(unix)]
    pub(crate) fn euid_override() -> Option<u32> {
        EUID_OVERRIDE.with(|c| c.get())
    }

    thread_local! {
        static PATH_CHECK_FAILURES: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
    }

    /// Make this thread's next `n` checks that a handle's path still names
    /// its open file fail with a permission error (RB-008.2), as when the
    /// process has lost access to the path. `0` disarms.
    pub fn set_path_check_failures(n: u64) {
        PATH_CHECK_FAILURES.with(|c| c.set(n));
    }

    /// How many armed path-check failures this thread has left.
    pub fn path_check_failures_left() -> u64 {
        PATH_CHECK_FAILURES.with(|c| c.get())
    }

    pub(crate) fn take_path_check_failure() -> bool {
        PATH_CHECK_FAILURES.with(|c| {
            let n = c.get();
            if n > 0 {
                c.set(n - 1);
            }
            n > 0
        })
    }

    pub(crate) fn take_shared_replaced() -> bool {
        SHARED_REPLACED.with(|c| {
            let n = c.get();
            if n > 0 {
                c.set(n - 1);
            }
            n > 0
        })
    }
}

/// 12.4 step 2a: the shared lock layer, reached directly by its tests
/// (`tests/shared_lock.rs`) until `Mnemo::open_shared` (step 2b) wraps it.
/// Compiled in under `cfg(test)` and the `failpoints` feature only.
///
/// **Not part of the stable public API.**
#[cfg(any(test, feature = "failpoints"))]
#[doc(hidden)]
pub mod __shared {
    use std::path::{Path, PathBuf};

    use crate::shared::{BrainLocks, Call, Held, LockKind};
    use crate::{Result, SharedOptions};

    /// The sidecar directory's suffix and its two file names.
    pub const SUFFIX: &str = crate::shared::testing::SUFFIX;
    pub const INTENT: &str = crate::shared::testing::INTENT;
    pub const LOCK_INFO: &str = crate::shared::testing::LOCK_INFO;
    /// LOCK-2's valve file name.
    pub const VALVE: &str = crate::shared::testing::VALVE;

    /// Whether this build refuses shared mode (Windows, Rust before 1.85).
    pub const WINDOWS_OLD_RENAME: bool = crate::shared::WINDOWS_OLD_RENAME;

    /// `<brain>.mnemo-shared` for a resolved brain path.
    pub fn sidecar_path(brain: &Path) -> PathBuf {
        crate::shared::testing::sidecar_path(brain)
    }

    /// The macOS synced-folder rule, as a pure function.
    pub fn classify_synced(path: &Path, home: &Path) -> Option<String> {
        crate::shared::testing::classify_synced(path, home)
    }

    /// Whether a Linux `statfs` magic number is allowed.
    pub fn linux_fs_allowed(magic: u32) -> bool {
        crate::shared::testing::linux_fs_allowed(magic)
    }

    /// The lock layer for one brain.
    #[derive(Debug)]
    pub struct Locks(BrainLocks);

    impl Locks {
        pub fn new(path: &Path, opts: &SharedOptions) -> Result<Self> {
            BrainLocks::new(path, opts).map(Locks)
        }
        /// A plain long operation's layer, which never creates the sidecar.
        pub fn for_plain(path: &Path, opts: &SharedOptions) -> Result<Self> {
            BrainLocks::for_plain(path, opts).map(Locks)
        }
        /// LOCK-2: how many times this layer's writers took the valve.
        pub fn valve_takes(&self) -> u64 {
            self.0.valve_takes()
        }
        pub fn shared(&mut self, opts: &SharedOptions) -> Result<Lock> {
            let mut call = Call::new(opts.deadline, opts.cancel.as_ref());
            self.0.acquire(LockKind::Shared, &mut call).map(Lock)
        }
        pub fn exclusive(&mut self, opts: &SharedOptions) -> Result<Lock> {
            let mut call = Call::new(opts.deadline, opts.cancel.as_ref());
            self.0.acquire(LockKind::Exclusive, &mut call).map(Lock)
        }
        pub fn has_sidecar(&self) -> bool {
            self.0.has_sidecar()
        }
        pub fn sidecar_path(&self) -> Option<PathBuf> {
            self.0.sidecar_path().map(Path::to_path_buf)
        }
        pub fn notices(&self) -> Vec<String> {
            self.0.notices().to_vec()
        }
    }

    /// One call's main lock; dropping it unlocks.
    pub struct Lock(Held);

    impl Lock {
        pub fn announce(&mut self, op: &str) {
            self.0.announce(op)
        }
        pub fn file(&self) -> &std::fs::File {
            self.0.file()
        }
    }
}

/// WAL entry points for the PERF-1 allocation test
/// (`tests/wal_recover_alloc.rs`), which needs its own global allocator and
/// so can't live in this `forbid(unsafe_code)` crate. Not a stable API.
#[doc(hidden)]
pub mod __wal {
    /// Page size of the WAL region.
    pub const PAGE_SIZE: usize = crate::format::PAGE_SIZE;

    /// One WAL frame: a home page number and its page image.
    pub type Frame = (u64, Vec<u8>);

    /// Bytes a transaction of `n` page frames occupies.
    pub fn txn_byte_len(n: usize) -> u64 {
        crate::wal::txn_byte_len(n, PAGE_SIZE)
    }

    /// Commit `frames` as transaction `txn_id` at the start of a region.
    pub fn commit(
        file: &mut std::fs::File,
        wal_pages: u64,
        txn_id: u64,
        frames: &[Frame],
    ) -> crate::Result<()> {
        crate::wal::commit(file, 0, wal_pages, txn_id, frames)
    }

    /// Run open-time recovery over a region starting at page 0; returns the
    /// frames to replay, if any.
    pub fn recover(
        file: &mut std::fs::File,
        wal_pages: u64,
        wal_seq: u64,
    ) -> crate::Result<Option<Vec<Frame>>> {
        crate::wal::recover(file, 0, wal_pages, wal_seq)
    }
}

/// Internal parse surfaces exposed for cargo-fuzz targets (Phase 1.2).
///
/// **Not part of the stable public API.** Each function feeds an
/// arbitrary byte slice into a parse/decode path that a hostile
/// `.mnemo` file (or a hostile MCP client) can send us, and returns
/// `Result<()>` so a fuzz target only asserts "no panic." Marked
/// `#[doc(hidden)]` so `cargo doc` doesn't advertise it; do not import
/// from application code.
#[doc(hidden)]
pub mod __fuzz {
    /// Parse a `.mnemo` header page (page 0, plaintext) from arbitrary
    /// bytes. This is the pre-passphrase attack surface — a hostile
    /// file hits it before any DEK exists.
    pub fn parse_header(bytes: &[u8]) -> crate::Result<()> {
        crate::format::Header::from_page(bytes).map(|_| ())
    }

    /// Replay the WAL scan over an arbitrary byte region. Delegates
    /// to [`crate::wal::recover_bytes`]; a corrupt / truncated /
    /// adversarial region must return `Err` or `Ok(None/Some(_))`,
    /// never panic.
    pub fn wal_recover_bytes(region: &[u8], wal_seq: u64) -> crate::Result<()> {
        crate::wal::recover_bytes(region, wal_seq).map(|_| ())
    }

    /// Decode a `Memory` record body from arbitrary bytes.
    pub fn decode_memory(bytes: &[u8]) -> crate::Result<()> {
        rmp_serde::from_slice::<crate::Memory>(bytes)
            .map(|_| ())
            .map_err(|e| crate::MnemoError::Serialize(e.to_string()))
    }

    /// FMT-9e: decode a v9 `Memory` record body from arbitrary bytes: a
    /// zstd frame (a compressed thread turn) is decompressed first, under
    /// the same content-size bound the store applies.
    pub fn decode_v9_memory(bytes: &[u8]) -> crate::Result<()> {
        let plain = crate::store::plain_record(bytes)?;
        rmp_serde::from_slice::<crate::Memory>(&plain)
            .map(|_| ())
            .map_err(|e| crate::MnemoError::Serialize(e.to_string()))
    }

    /// Decode a `CacheEntry` record body from arbitrary bytes. Type is
    /// `pub(crate)`, so this wrapper hides it behind a unit return.
    pub fn decode_cache_entry(bytes: &[u8]) -> crate::Result<()> {
        rmp_serde::from_slice::<crate::result_cache::CacheEntry>(bytes)
            .map(|_| ())
            .map_err(|e| crate::MnemoError::Serialize(e.to_string()))
    }

    /// Decode a cache-directory page-run body (a `Vec<CacheDirectoryEntry>`)
    /// from arbitrary bytes.
    pub fn decode_cache_directory(bytes: &[u8]) -> crate::Result<()> {
        rmp_serde::from_slice::<Vec<crate::result_cache::CacheDirectoryEntry>>(bytes)
            .map(|_| ())
            .map_err(|e| crate::MnemoError::Serialize(e.to_string()))
    }

    /// Parse a single MCP stdio JSON-RPC request line. Malformed
    /// input returns `Err(String)`; the fuzz target only asserts
    /// no panic and that the server would not die on this line.
    pub fn parse_mcp_request_line(line: &str) -> Result<(), String> {
        crate::mcp::__fuzz_parse_request_line(line)
    }
}