Expand description
§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
use mnemo_engine::{Mnemo, MnemoConfig, Memory, MemoryType, RecallRequest};
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);
}§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.
Modules§
- essence_
status - Status values the essence section supports (Phase 12.7b). More
kinds (tasks:
queued → active → ready → done | blocked; findings:open → accepted | deferred | rejected | needs-user → verified) ship with Phase 13 reusing the same status-record core; the transition tables for those are declared as constants in this crate but currently unused. - mcp
- Hand-rolled Model Context Protocol (MCP) stdio server for MNemo.
Structs§
- Build
Info - Build-time cryptographic backend information.
- Cache
Budget - Per-namespace eviction budget.
cache_putenforces both caps: on insert, the LRU is evicted until both live-entry count and live byte total fit under the caps. - Cache
PutOpts - Options accepted by
Mnemo::cache_put. Defaults describe an untyped, never-expiring, non-cost-hinted entry. - Cache
Stats - Summary statistics for a namespace (or the whole cache).
- Cached
Value - A returned cache hit.
accessed_at/access_countare updated on the directory before this is constructed, so the values here reflect the post-touch state (mirroring the recall-time convention). - Commit
Batch - Atomic write batch for
crate::Mnemo::commit_deltas(Phase 12.7c). The planner’s “one call that composes facts + essence + turns” shape: everything validates up front, then every write runs under a singleflush(). - Commit
Report - Result of
crate::Mnemo::commit_deltas(Phase 12.7c). - Compact
Report - Result of a
Mnemo::compact_filerun. - Embed
Cmd - Persistent-child-process adapter for a user-supplied embedder command. See the module docs for the protocol.
- Embedder
Identity - Describe an embedder’s observable identity. Used both in-memory on
an open [
Mnemo] handle and persisted atmetadata.embedderon the scaffold manifest so that reopening with a different embedder is caught atset_embeddertime instead of silently polluting the index. - Essence
Op - One essence op inside a
CommitBatch(Phase 12.7c). Validation (missing/extra fields per kind) runs up front incrate::Mnemo::commit_deltas— a single bad op aborts the whole batch before any write lands. - Exported
Turn - One turn of a thread’s archive in the ingest shape (Phase 12.7d),
as returned by
crate::Mnemo::thread_export_turnsand by Pythondb.thread_export, MCPthread_exportandmnemo thread export. - Filter
- Pre-scoring filter applied by
crate::Mnemo::recall(Phase 12.6). - Index
Config - Tuning knobs for building and querying an [
IvfPqIndex]. - Index
Info - A read-only snapshot of an index’s shape, surfaced via
Mnemo::stats. - Ingest
Report - Result of one
crate::Mnemo::ingest_threadcall (Phase 12.7a). - KdfParams
- Argon2id cost parameters. Stored (unencrypted) in the file header so the KEK can be re-derived on open.
- Keyed
Memory - One keyed fact inside a
CommitBatch(Phase 12.7c). - Memory
- A single memory entry.
- Memory
Patch - Patch body for
crate::Mnemo::update(Phase 12.1): every field is optional, and only theSome(...)fields overwrite the corresponding field on the target memory. All fields can be set independently. - Mnemo
- An encrypted, single-file agent memory database.
- Mnemo
Config - Configuration for creating a new database.
- Recall
Request - A retrieval request for
Mnemo::recall. - Recall
Response - Phase 12.8 budgeted-recall envelope returned by
Mnemo::recall_budgeted. Wraps theVec<RecallResult>the legacyMnemo::recallreturns so callers can tell whetherRecallRequest::max_bytescut anything. - Recall
Result - One scored result from
Mnemo::recall. - Score
Weights - Weights for the multi-signal recall score (scoring v2, shipped in v0.7.0).
- Semantic
Cache PutOpts - Options for
crate::Mnemo::cache_put_semantic. Same asCachePutOptsplus a requiredmodelstring — a hit from a different embedding model’s cache is a semantics bug, not a win, so the engine forces callers to declare the model and matches it on lookup. - Session
- A scoped conversation session over a
Mnemodatabase. - Snapshot
Info - A restorable point in a database’s history — see
Mnemo::snapshots. - Stats
- Summary statistics for a database.
- Thread
Turn - One turn fed into
crate::Mnemo::ingest_thread(Phase 12.7a). - Turn
- One conversation turn, written to working memory by
Session::add_turn. - Ulid
- Re-export of
ulid::Ulid, the identifier type used for memories. A Ulid is a unique 128-bit lexicographically sortable identifier
Enums§
- Cache
Flush Policy - Per-handle flush policy for cache writes. Memory writes ignore this
and always behave as
Strict. - Essence
OpKind - Which op a
EssenceOpcarries. Mirrors the per-methodMnemo::essence_*surface so one batch can mix section + timeline edits in one call. - Essence
Scope - Scope selector for an essence item (Phase 12.7b). Thread-scoped
items belong to one
_mnemo.thread; project-scoped items are shared across every thread in the file. - Essence
Section - Which essence section an item belongs to.
- Filter
Term - One AND-ed condition applied to a candidate memory’s metadata during
filtered recall (Phase 12.6). Terms are combined conjunctively — a
memory passes the filter only if every term evaluates true against
its
metadatamap. SeeFilterfor the surface API. - KeyScope
- Scope selector for a keyed slot (Phase 12.1.1). A keyed
remember’s slot is always identified by(scope_owner, key):Private(agent_id)slots are per-agent,Sharedslots are per-file.history_in(key, scope)uses the same selector so the lookup matches the write exactly. - Memory
Type - The four kinds of agent memory.
- Metric
- Distance/similarity metric for vector comparison.
- Mnemo
Error - All errors the Mnemo engine can produce.
- Role
- Who produced a conversation turn.
- Scope
- Visibility of a memory across agents sharing one
.mnemofile. - Transcript
Format - The supported transcript shapes for
read_transcript/mnemo thread ingest --format …. - Turn
Policy - What
crate::Mnemo::commit_deltasdoes with theturnscarried in the batch (Phase 12.7c). - Write
Outcome - Outcome of a 12.1 write operation (
rememberwithkey, orupdate).
Constants§
- CONTINUATION_
TIMELINE_ ENTRIES - How many timeline entries from the predecessor thread the continuation render pulls in (Phase 12.7c). Small enough to keep the render under the default 6 KB budget, large enough to carry a handful of milestones.
- DEFAULT_
BATCH_ MAX_ AGE - Default
max_ageforCacheFlushPolicy::Batched. - DEFAULT_
BATCH_ MAX_ DIRTY - Default
max_dirtyforCacheFlushPolicy::Batched. - DEFAULT_
EMBED_ TIMEOUT - Default per-request timeout. Set generously because a cold-start
sentence-transformerscall can genuinely take a few seconds the first time; configurable viaEmbedCmd::with_timeout(Rust API) or the--embed-timeoutCLI flag. - DEFAULT_
MAX_ BYTES - Default per-namespace byte budget (values + directory overhead).
Once exceeded,
cache_putevicts LRU until the total falls back under the cap. - DEFAULT_
MAX_ ENTRIES - Default per-namespace entry-count budget. Once a namespace holds this
many live entries,
cache_putevicts the LRU entry before inserting. - DEFAULT_
SEMANTIC_ THRESHOLD - Default similarity threshold for
crate::Mnemo::cache_get_semantic. Lookups below this are treated as misses. Chosen conservatively to avoid false hits on subtly-different prompts; callers can override per-lookup. Model-dependent — text-embedding-ada-002 and BGE at this threshold rarely surface unrelated content, but if you’re working with a lossier embedder consider raising it. - ESSENCE_
DEFAULT_ RENDER_ BYTES - Default byte budget for
crate::Mnemo::essencerendering (Phase 12.7b). Matches the planner’s “max_bytes = 6144” spec, which sits comfortably below a 4K-token context window. - ESSENCE_
SECTION_ MAX_ BYTES - Maximum content length for a section item (Phase 12.7b). intent / conventions / decisions / state / open / next / lessons all share the same single-line cap. Items over this are rejected.
- ESSENCE_
TIMELINE_ MAX_ BYTES - Maximum content length for a timeline entry (Phase 12.7b). Entries over this are rejected, not truncated — the planner’s spec is explicit about this because truncation would lose the narrative, and splitting across records would lose ordering.
- ESSENCE_
TRANSITIONS - Essence transition table for Phase 12.7b. Only
open → resolvedis allowed. Timeline entries don’t use this (they’re append-only and have no status). - FINDING_
TRANSITIONS - Finding transition table (declared for Phase 13; currently unused
in the engine).
open → {accepted | deferred | rejected | needs-user} → verified. - MNEMO_
META_ CONTINUES - Reserved
_mnemo.continueskey (Phase 12.7c). Set on a thread-start marker record to point at the previous thread whose context the new thread continues from. Value: the prior thread id (string). Rendering a continued thread pulls the prior thread’s open items,nextand last-N timeline entries ahead of the new thread’s own essence. - MNEMO_
META_ INVALID_ AT - Set on the earlier record when superseded. Value: unix seconds (i64).
Not interpreted by the engine’s scorer — purely for audit /
history. - MNEMO_
META_ KEY - Upsert slot name on a
remember(…, key = K)write (12.1). Combined with the memory’sscope(andagent_idforPrivatescope) to identify a single live memory per slot: a newerremember(key=K)supersedes the prior one. - MNEMO_
META_ KIND - Record kind for thread-archive turns (Phase 12.7a). Value:
"turn". - MNEMO_
META_ KIND_ ESSENCE - Marker value for
_mnemo.kindon essence records (Phase 12.7b). - MNEMO_
META_ KIND_ THREAD_ LINK - Marker value for
_mnemo.kindon a thread-start record (one perthread_start(new, --from old)call, carrying the link in_mnemo.continues). - MNEMO_
META_ KIND_ TURN - Marker value for
_mnemo.kindon thread-turn records. - MNEMO_
META_ LENGTH - Byte length of the original tool-result content (Phase 12.7a). Set
alongside
_mnemo.sha256when truncation happened; absent otherwise. - MNEMO_
META_ NS - Namespace prefix used for every v0.8.0+ reserved metadata key (R-001.10). Keys outside this namespace are untouched user metadata.
- MNEMO_
META_ PART - Zero-based part number for a turn that was chunked at the 8 KB boundary during ingest (Phase 12.7a). Absent → the turn fits in a single record.
- MNEMO_
META_ REFS - Reserved
_mnemo.refskey — optional array of free-form reference strings (turn ids, memory ids, commits, paths) attached to an essence record (Phase 12.7b). - MNEMO_
META_ ROLE - Role of the turn’s author (Phase 12.7a). Value:
"user","assistant","system","tool", or any other string the source transcript used. - MNEMO_
META_ SECTION - Reserved
_mnemo.sectionkey — which essence section an item belongs to (Phase 12.7b). Values:"timeline","intent","conventions","decisions","state","open","next","lessons". Timeline entries are append-only. - MNEMO_
META_ SEQ - Monotonically increasing sequence number within the thread
(Phase 12.7a). Value: unsigned integer, 0-based. Lets
thread exportreconstruct the transcript in order. - MNEMO_
META_ SHA256 - Hex-encoded SHA-256 of the original tool-result content (Phase 12.7a). Set when the content exceeded the 16 KB truncation cap during ingest; absent otherwise.
- MNEMO_
META_ STATUS - Reserved
_mnemo.statuskey — current status of a status-record. Values are per-kind (Phase 12.7b: essence uses"open"and"resolved"). Timeline entries never carry this. - MNEMO_
META_ STATUS_ HISTORY - Reserved
_mnemo.status_historykey — array of status transitions, each{"status": <str>, "at": <unix_secs>}. Append-only — the first entry records creation, each later entry records a transition. - MNEMO_
META_ SUPERSEDED_ BY - Set on the earlier record when a newer
remember(key=K)has replaced it. Value: the new record’s ULID string. Together with_mnemo.invalid_atthis marks the record as “superseded, not current” — defaultrecall,aboutand the key index skip it;history(key)walks the chain. - MNEMO_
META_ SUPERSEDES - Set on the newly-inserted record when a
remember(key=K)supersedes an earlier record. Value: the superseded record’s ULID string. - MNEMO_
META_ THREAD - Thread identifier the record belongs to (Phase 12.7a). Value: a caller-supplied string, typically the Claude Code session uuid or the planner-chosen thread slug.
- MNEMO_
META_ TURN_ ID - Opaque per-turn identifier from the source transcript
(Phase 12.7a). Value: typically a uuid4. Used for idempotence —
ingest_threadskips any turn whoseturn_idalready exists on a record in the target thread. - MNEMO_
META_ UPDATED_ AT - Set on a record each time
Mnemo::updatesucceeds. Value: unix seconds. Lets callers distinguish an unchanged-since-creation record from one that has been edited in place. Not interpreted by the scorer. - TASK_
TRANSITIONS - Task transition table (declared for Phase 13; currently unused
in the engine).
queued → active → ready → done | blocked, withblocked → activeas the only back-edge. - THREAD_
TOOL_ RESULT_ TRUNCATE_ BYTES - Maximum content size for a tool-result turn before truncation
(Phase 12.7a). Tool results frequently run tens of kilobytes;
stored truncated with
_mnemo.sha256+_mnemo.lengthso the original can be recovered (or verified) out-of-band. - THREAD_
TURN_ CHUNK_ BYTES - Maximum content size for a single turn record before chunking kicks in (Phase 12.7a). 8 KB per chunk keeps each record small enough that the per-record page cost dominates — and so that a thread of mostly short messages ingests as one record each.
Traits§
- Embedder
- Minimal trait any embedder implementation must satisfy. Returns
vectors in the same order as the input
texts.
Functions§
- build_
info - Report this build’s cryptographic backend configuration.
- read_
transcript - Read a transcript from any
Readin the given format and return the turns in file order. Non-matching / unrecognized line types are skipped silently (Claude Code adds newtypevalues over time).
Type Aliases§
- Result
- Convenience result alias used throughout the crate.