pub struct Mnemo { /* private fields */ }Expand description
An encrypted, single-file agent memory database.
Implementations§
Source§impl Mnemo
impl Mnemo
Sourcepub fn build_index(&mut self) -> Result<IndexInfo>
pub fn build_index(&mut self) -> Result<IndexInfo>
Build an IVF+PQ approximate-nearest-neighbour index over every live
memory, using default tuning. After this, Mnemo::recall runs the
tiered pipeline instead of an exact scan. Persisted on the next
flush. Returns a snapshot of the index shape.
Sourcepub fn build_index_with(&mut self, cfg: IndexConfig) -> Result<IndexInfo>
pub fn build_index_with(&mut self, cfg: IndexConfig) -> Result<IndexInfo>
Build the ANN index with explicit tuning.
Sourcepub fn rebuild_index(&mut self) -> Result<IndexInfo>
pub fn rebuild_index(&mut self) -> Result<IndexInfo>
Rebuild the ANN index from scratch — re-clusters centroids and retrains the PQ codebook, undoing the cluster drift that accumulates as memories are inserted against fixed centroids.
Sourcepub fn drop_index(&mut self)
pub fn drop_index(&mut self)
Drop the ANN index; recall reverts to exact scans. Persisted on flush.
No-op on a read-only handle (signature is infallible — callers of
build_index / flush on a read-only handle already get a typed
ReadOnly error, which is the enforceable boundary).
Source§impl Mnemo
impl Mnemo
Sourcepub fn cache_put(
&mut self,
namespace: &str,
key: &str,
value: &[u8],
opts: CachePutOpts,
) -> Result<()>
pub fn cache_put( &mut self, namespace: &str, key: &str, value: &[u8], opts: CachePutOpts, ) -> Result<()>
Insert or overwrite a cache entry at (namespace, key).
The engine SHA-256-hashes key — callers pass the raw input
string. Persists to disk on the next flush() under the current
flush policy (see Mnemo::set_cache_flush_policy); in
CacheFlushPolicy::Batched the engine may call flush()
internally when a threshold trips.
On overflow of the namespace’s CacheBudget (default 10,000
entries / 64 MiB) the LRU entry is tombstoned before the new
insert. Tombstones are reclaimed by
Mnemo::compact_file, not the runtime flush.
Returns MnemoError::ReadOnly on a read-only handle.
Sourcepub fn cache_get(
&mut self,
namespace: &str,
key: &str,
) -> Result<Option<CachedValue>>
pub fn cache_get( &mut self, namespace: &str, key: &str, ) -> Result<Option<CachedValue>>
Look up (namespace, key). Returns None on miss (either the
key was never inserted or the entry is TTL-expired). On hit
updates catalog-side access stats (mirrors the recall v5-trick);
on a read-only handle the stats update is silently skipped.
A miss is recorded as a miss in this handle’s counters even if the key was TTL-expired — from the caller’s perspective the two are indistinguishable.
Sourcepub fn cache_delete(&mut self, namespace: &str, key: &str) -> Result<()>
pub fn cache_delete(&mut self, namespace: &str, key: &str) -> Result<()>
Tombstone the entry at (namespace, key). Silently succeeds if
no such entry exists. Space is reclaimed by compact_file.
Sourcepub fn cache_purge(
&mut self,
namespace: Option<&str>,
expired_only: bool,
) -> Result<usize>
pub fn cache_purge( &mut self, namespace: Option<&str>, expired_only: bool, ) -> Result<usize>
Purge cache entries. If namespace is Some, restrict to that
namespace; otherwise purge across the whole cache. If
expired_only is true, only TTL-expired entries are removed;
otherwise every live entry in the target scope is tombstoned.
Returns the number of entries newly tombstoned.
Sourcepub fn cache_stats(&self, namespace: Option<&str>) -> CacheStats
pub fn cache_stats(&self, namespace: Option<&str>) -> CacheStats
Statistics for namespace (or the whole cache if None).
hits/misses/evictions are per-handle in-memory counters
that reset on reopen; entries/bytes reflect the durable
on-disk state (live entries only, tombstones excluded).
Sourcepub fn set_cache_budget(&mut self, namespace: &str, budget: CacheBudget)
pub fn set_cache_budget(&mut self, namespace: &str, budget: CacheBudget)
Set (or update) the eviction budget for namespace. Applies to
subsequent cache_put calls; does not retroactively evict
entries that already sit under a looser cap.
Sourcepub fn set_cache_flush_policy(&mut self, policy: CacheFlushPolicy)
pub fn set_cache_flush_policy(&mut self, policy: CacheFlushPolicy)
Set the per-handle cache flush policy. Defaults to
CacheFlushPolicy::Strict. Memory writes are never batched;
this affects only cache mutations.
Sourcepub fn cache_put_semantic(
&mut self,
namespace: &str,
key: &str,
vector: Vec<f32>,
value: &[u8],
opts: SemanticCachePutOpts,
) -> Result<()>
pub fn cache_put_semantic( &mut self, namespace: &str, key: &str, vector: Vec<f32>, value: &[u8], opts: SemanticCachePutOpts, ) -> Result<()>
Insert or overwrite a semantic cache entry — same as
Mnemo::cache_put but with a required embedding vector and
model identifier. The vector is stored on the directory entry
so Mnemo::cache_get_semantic can score without decrypting
record bodies.
Vector dimensionality is validated against the database’s
configured dimensions — a mismatch returns
MnemoError::DimensionMismatch, the same signal remember
gives for the memory catalog.
The model string is matched exactly on lookup — a
different model’s cache is invisible to a given query. Pick
canonical identifiers ("text-embedding-3-small",
"bge-large-en-v1.5", …) and stick to them.
Sourcepub fn cache_get_semantic(
&mut self,
namespace: &str,
query_vector: &[f32],
threshold: f32,
model: &str,
) -> Result<Option<(CachedValue, f32)>>
pub fn cache_get_semantic( &mut self, namespace: &str, query_vector: &[f32], threshold: f32, model: &str, ) -> Result<Option<(CachedValue, f32)>>
Semantic recall over the cache: score every live entry in
namespace whose model matches against query_vector using
cosine similarity; return the top-1 hit and its similarity iff
sim >= threshold. None otherwise.
Uses crate::result_cache::DEFAULT_SEMANTIC_THRESHOLD if you
want a sensible default — pass it explicitly (0.97 today).
Exact-key entries (those without a vector) are transparently skipped, as are entries whose model doesn’t match — a different-model hit would be a semantic bug, not a win. TTL-expired entries are also skipped.
Access-stat updates on hit follow the same policy as
Mnemo::cache_get: bumped on read-write handles, silently
skipped on read-only. Hits and misses are recorded in the
per-handle counters just like exact-key lookups.
Source§impl Mnemo
impl Mnemo
Sourcepub fn thread_start(
&mut self,
new_thread_id: &str,
from_thread_id: &str,
) -> Result<Ulid>
pub fn thread_start( &mut self, new_thread_id: &str, from_thread_id: &str, ) -> Result<Ulid>
Start a new thread that continues from a previous one
(Phase 12.7c). Writes a thread-link marker record with
_mnemo.kind = "thread_link" + _mnemo.thread = <new_id> +
_mnemo.continues = <from_id>. The marker holds no user
content; its purpose is to let essence(Thread(new_id))
discover the continuation chain.
The render for the new thread pulls the previous thread’s
open section items, its next, and its last
CONTINUATION_TIMELINE_ENTRIES timeline entries ahead of
the new thread’s own essence — the “new thread, same
experience” path.
Sourcepub fn commit_deltas(&mut self, batch: CommitBatch) -> Result<CommitReport>
pub fn commit_deltas(&mut self, batch: CommitBatch) -> Result<CommitReport>
Atomic batch write combining 12.1 facts, 12.7b essence ops, and 12.7a archive turns in one flush (Phase 12.7c; batch embedding added in 12.7d).
The batch runs in four steps:
- Structural checks on every item: required fields, size
caps, empty keys,
thread_idfor turns, and that everyUpdate/Resolve/Removetargets a live essence record the op can apply to. - One
Embedder::embedcall for every text that needs a vector: facts whosevectoris empty, essenceAdd/AppendTimelinetexts (when an embedder is registered; without one, essence keeps its sentinel vector), and the archive turns’ chunks. - Vector checks (width, non-zero, finite) on supplied and embedded vectors alike.
- Writes: facts, then essence ops, then turns per
turn_policy, then exactly oneflush().
A failure in steps 1–3 returns an error with nothing staged. A
text-only fact, or any turn to archive, with no embedder
registered is a step-1 error. put has no rollback, so an I/O
error during step 4 can leave the batch’s earlier writes staged
on the handle; steps 1–3 exist so nothing else can fail that
late.
Source§impl Mnemo
impl Mnemo
Sourcepub fn set_embedder<E: Embedder + 'static>(&mut self, embedder: E) -> Result<()>
pub fn set_embedder<E: Embedder + 'static>(&mut self, embedder: E) -> Result<()>
Register a text embedder for this handle. Enables
Mnemo::remember_text and the text-side RecallRequest
convenience path. Does two checks before storing the embedder:
- Dimension check. The embedder’s
identity().dimensionsmust equalMnemo::dimensions(the width this database was created with). Mismatch returnsMnemoError::DimensionMismatch. - Identity check (EMBED-ID-1). Every file records the
identity (name, dimensions, normalize) of the first embedder
attached to it, in a reserved, encrypted record that isn’t a
memory:
len,count,stats, recall,aboutandgetnever see it, and compaction, the rekeyed exports and the passphrase import carry it. After that, any other identity, even at the same width (another model, or another revision of the same one), returnsMnemoError::EmbedderMismatch: a store is bound to the model that first wrote to it, so a new model needs a new store.
Files with a manifest (mnemo init, seed.json) also carry
the identity on the manifest at metadata.embedder = { name, dimensions, normalize } (the legacy flat embedder_name /
embedder_dimensions / embedder_normalize keys are read as an
alias). The first registration upserts it there too, as before.
If the manifest and the record disagree, this returns
MnemoError::Invalid naming both.
Files from before EMBED-ID-1 have no record: the first embedder attached after the upgrade is recorded. The check protects from then on; it can’t tell which model made the older vectors.
Read-only handles. set_embedder on an open_read_only
handle performs both checks and adopts the embedder in memory;
it never writes. Readers (CLI --text, agent-side recall_text)
can therefore use the text path next to a writer that holds
the exclusive lock.
On every failure path the handle’s embedder slot is left
unchanged. On success the embedder is wrapped in an Arc<dyn Embedder> and consulted by every text-side call made through
this handle. The slot is per-handle and not persisted — a
fresh open must re-register (same identity, so the check
round-trips cleanly).
Sourcepub fn embedder_identity(&mut self) -> Result<Option<EmbedderIdentity>>
pub fn embedder_identity(&mut self) -> Result<Option<EmbedderIdentity>>
The embedder identity this file records (EMBED-ID-1), or None
before the first set_embedder on a read-write handle. Reads the
reserved record without touching any counter.
Sourcepub fn embedder(&self) -> Option<&dyn Embedder>
pub fn embedder(&self) -> Option<&dyn Embedder>
Borrow the currently-registered embedder, if any. Returns
None when no embedder has been set via
Mnemo::set_embedder. Bindings use this to drive their own
text-side convenience methods without duplicating the identity
check.
Sourcepub fn embedder_arc(&self) -> Option<Arc<dyn Embedder>>
pub fn embedder_arc(&self) -> Option<Arc<dyn Embedder>>
Shared handle to the registered embedder, cloned so the caller
can drop the borrow on this Mnemo before invoking embed().
FIX-1 / PY-1 (R-001.11): the Python binding needs this so an
embedder callback that re-enters Mnemo (e.g. a Python
embedder that calls db.dimensions() or db.cache_get(...))
doesn’t hit PyO3’s “Already borrowed” — we clone the Arc under
a short &self borrow, release that borrow, then invoke
embed() with no &mut Mnemo held.
Sourcepub fn remember_text(
&mut self,
content: &str,
memory_type: MemoryType,
) -> Result<Ulid>
pub fn remember_text( &mut self, content: &str, memory_type: MemoryType, ) -> Result<Ulid>
Embed content with the registered embedder and remember the
result. Returns the new memory’s ULID. Convenience path for
callers who have a string, want it stored, and don’t need any
of the per-memory options Memory exposes (agent, importance,
metadata, ttl, scope) — build a Memory by hand and call
Mnemo::remember for those.
Fails with MnemoError::Invalid if no embedder has been
registered on this handle (call Mnemo::set_embedder first);
with MnemoError::DimensionMismatch if the embedder returned
the wrong width for this database.
Sourcepub fn remember(&mut self, memory: Memory) -> Result<Ulid>
pub fn remember(&mut self, memory: Memory) -> Result<Ulid>
Store a memory. Returns its ULID. If the memory’s ID is nil a fresh one is assigned; an existing ID overwrites in place.
Metadata keys starting with _mnemo. are the engine’s (supersession,
keys, threads, kinds): a new memory carrying one is refused with
MnemoError::Invalid. An in-place overwrite may carry the stored
record’s own _mnemo.* keys through unchanged (the usual get,
change a field, remember), but can’t add, change or drop one.
Source§impl Mnemo
impl Mnemo
Sourcepub fn essence_add(
&mut self,
scope: EssenceScope,
section: EssenceSection,
text: &str,
refs: Option<Vec<String>>,
) -> Result<Ulid>
pub fn essence_add( &mut self, scope: EssenceScope, section: EssenceSection, text: &str, refs: Option<Vec<String>>, ) -> Result<Ulid>
Phase 12.7b: add a new essence item to a section (any section
except EssenceSection::Timeline). Content ≤
memory::ESSENCE_SECTION_MAX_BYTES (280 bytes); items over
that are rejected. Starting status is "open".
Use Mnemo::essence_append_timeline for timeline entries —
they have a different cap (600 bytes), are append-only, and
carry no status lifecycle.
Sourcepub fn essence_add_with_vector(
&mut self,
scope: EssenceScope,
section: EssenceSection,
text: &str,
refs: Option<Vec<String>>,
vector: Vec<f32>,
) -> Result<Ulid>
pub fn essence_add_with_vector( &mut self, scope: EssenceScope, section: EssenceSection, text: &str, refs: Option<Vec<String>>, vector: Vec<f32>, ) -> Result<Ulid>
Mnemo::essence_add with the item’s vector supplied by the
caller instead of the registered embedder, so a caller can embed
text without holding the handle (the UniFFI binding does, as with
Mnemo::ingest_thread_with_vectors). Same validation, same record.
Sourcepub fn essence_append_timeline(
&mut self,
scope: EssenceScope,
text: &str,
refs: Option<Vec<String>>,
) -> Result<Ulid>
pub fn essence_append_timeline( &mut self, scope: EssenceScope, text: &str, refs: Option<Vec<String>>, ) -> Result<Ulid>
Phase 12.7b: append a new timeline entry (append-only
milestone). Content ≤ memory::ESSENCE_TIMELINE_MAX_BYTES
(600 bytes); entries over that are rejected (not truncated —
truncating a milestone silently loses the narrative).
Sourcepub fn essence_append_timeline_with_vector(
&mut self,
scope: EssenceScope,
text: &str,
refs: Option<Vec<String>>,
vector: Vec<f32>,
) -> Result<Ulid>
pub fn essence_append_timeline_with_vector( &mut self, scope: EssenceScope, text: &str, refs: Option<Vec<String>>, vector: Vec<f32>, ) -> Result<Ulid>
Mnemo::essence_append_timeline with a caller-supplied vector
(see Mnemo::essence_add_with_vector).
Sourcepub fn essence_update(
&mut self,
id: &Ulid,
text: &str,
refs: Option<Vec<String>>,
) -> Result<WriteOutcome>
pub fn essence_update( &mut self, id: &Ulid, text: &str, refs: Option<Vec<String>>, ) -> Result<WriteOutcome>
Phase 12.7b: update an existing essence section item in place.
Returns WriteOutcome::Updated / WriteOutcome::Unchanged.
Timeline entries are append-only — calling this on a timeline
record is an error.
Sourcepub fn essence_resolve(&mut self, id: &Ulid) -> Result<WriteOutcome>
pub fn essence_resolve(&mut self, id: &Ulid) -> Result<WriteOutcome>
Phase 12.7b: mark a section item as resolved (open → resolved
transition). A new history entry lands on
_mnemo.status_history. Idempotent — resolving a record that
is already resolved is a no-op.
Sourcepub fn essence_remove(&mut self, id: &Ulid) -> Result<()>
pub fn essence_remove(&mut self, id: &Ulid) -> Result<()>
Phase 12.7b: soft-delete a section item. Same semantics as
Mnemo::delete on any record — space reclaimed by a later
compact.
Sourcepub fn essence(
&mut self,
scope: EssenceScope,
max_bytes: usize,
) -> Result<String>
pub fn essence( &mut self, scope: EssenceScope, max_bytes: usize, ) -> Result<String>
Phase 12.7b: deterministic, budgeted markdown render of the
essence layer for a thread (or the project layer when
scope = EssenceScope::Project). max_bytes caps the output;
sections are emitted in the fixed EssenceSection::render_order,
and each section’s own budget is proportional to its position
in the order. Oldest timeline entries fold into a
+N earlier milestones tail when the budget runs out.
The render always ends with an archive pointer so the reader
knows how to drill in deeper (mnemo thread export … or
recall --thread …).
Source§impl Mnemo
impl Mnemo
Sourcepub fn mistagged_coordination(&mut self) -> Result<usize>
pub fn mistagged_coordination(&mut self) -> Result<usize>
RB-013.1: how many coordination records are tagged as facts in their
rows (an older mnemo rewrote this brain); mnemo compact re-tags
them. They’re found and used all the same.
Sourcepub fn post(
&mut self,
to: &str,
subject: &str,
body: &str,
refs: &[String],
conversation: Option<&str>,
from: Option<&str>,
from_role: Option<&str>,
) -> Result<Message>
pub fn post( &mut self, to: &str, subject: &str, body: &str, refs: &[String], conversation: Option<&str>, from: Option<&str>, from_role: Option<&str>, ) -> Result<Message>
13a (13.1): post a message to to (an agent id, role:<role>, or
all) with a one-line subject and an optional body (at most
crate::memory::MESSAGE_BODY_MAX bytes), from from (else the
handle’s author, else anonymous), in from_role when given.
A reply names its conversation, and its hop count is one more than
the conversation’s highest. A new message between the same two
parties within crate::memory::MESSAGE_PAIR_CARRY_SECS starts one
above the highest count between them in that time, so agents trading
fresh messages still reach the hop cap. Its delivery is sent and its status unread.
Sourcepub fn inbox(
&mut self,
agent: Option<&str>,
role: Option<&str>,
unread_only: bool,
) -> Result<Vec<Message>>
pub fn inbox( &mut self, agent: Option<&str>, role: Option<&str>, unread_only: bool, ) -> Result<Vec<Message>>
13a (13.1): the messages for agent (by id), its role, or
everyone, oldest first, leaving out its own. With unread_only,
only those not yet acked. Reads only; Mnemo::mark_seen records
that they were shown.
Sourcepub fn inbox_in(
&mut self,
agent: Option<&str>,
role: Option<&str>,
unread_only: bool,
visibility: VisibilitySet,
) -> Result<Vec<Message>>
pub fn inbox_in( &mut self, agent: Option<&str>, role: Option<&str>, unread_only: bool, visibility: VisibilitySet, ) -> Result<Vec<Message>>
13a (13.5): Mnemo::inbox with the visibility levels it shows
(inbox itself shows public and team).
Sourcepub fn mark_seen(&mut self, ids: &[Ulid]) -> Result<usize>
pub fn mark_seen(&mut self, ids: &[Ulid]) -> Result<usize>
13a (13.1b): mark these messages seen (from sent or delivered),
in place. Returns how many changed.
Sourcepub fn ack(
&mut self,
id: &Ulid,
note: Option<&str>,
by: Option<&str>,
) -> Result<WriteOutcome>
pub fn ack( &mut self, id: &Ulid, note: Option<&str>, by: Option<&str>, ) -> Result<WriteOutcome>
13a (13.1): ack a message, in place: unread → acked, its delivery
done, and a status_history entry with by (else the handle’s
author) and the optional note. Unchanged when it’s already
acked; an id that isn’t a message is refused.
Sourcepub fn prune_messages(&mut self, older_than_secs: i64) -> Result<usize>
pub fn prune_messages(&mut self, older_than_secs: i64) -> Result<usize>
13a (R-010.8): delete messages acked more than older_than_secs ago
(crate::memory::MESSAGE_ACKED_KEEP_SECS by default in the CLI).
Returns how many went. compact drops the same ones.
Source§impl Mnemo
impl Mnemo
Sourcepub fn coordination_now(&self) -> i64
pub fn coordination_now(&self) -> i64
13a: the clock claims, leases and presence run on, in unix seconds: the wall clock (dev-hooks builds let tests shift it).
Sourcepub fn claim(&mut self, topic: &str, ttl: Option<i64>) -> Result<ClaimOutcome>
pub fn claim(&mut self, topic: &str, ttl: Option<i64>) -> Result<ClaimOutcome>
13a (13.3): claim topic for this handle’s author for ttl seconds
(crate::memory::CLAIM_TTL_DEFAULT, 15 minutes, by default; 30 s
to 24 h).
A claim is a record, not a lock, and it’s advisory: nothing refuses
a write because of one. In a shared handle’s write window it’s a
compare-and-set: two processes can’t both win. The topic is free
when nobody holds it, its claim lapsed at expires_at, or its
holder registered a presence lock when it claimed and has been seen
not alive twice, crate::memory::CLAIM_LAPSE_GRACE_SECS apart
(each look is recorded on the claim). A topic this agent already
holds is ClaimOutcome::HeldBy too: a token can’t be recovered.
One record per topic, changed in place: a new holder gets a new
token.
Sourcepub fn renew(
&mut self,
topic: &str,
token: &str,
ttl: Option<i64>,
) -> Result<ClaimStatus>
pub fn renew( &mut self, topic: &str, token: &str, ttl: Option<i64>, ) -> Result<ClaimStatus>
13a (13.3): renew a claim for ttl seconds from now (its lease by
default). ClaimStatus::Lost when it lapsed or isn’t the token’s.
Sourcepub fn release(&mut self, topic: &str, token: &str) -> Result<ClaimStatus>
pub fn release(&mut self, topic: &str, token: &str) -> Result<ClaimStatus>
13a (13.3): release a claim. ClaimStatus::Lost when it already
lapsed or isn’t the token’s (then nothing changes).
Sourcepub fn check_claim(&mut self, topic: &str, token: &str) -> Result<ClaimStatus>
pub fn check_claim(&mut self, topic: &str, token: &str) -> Result<ClaimStatus>
13a (13.3): whether token still holds topic. Call it before an
irreversible step. Reads only.
Sourcepub fn claims(&mut self) -> Result<Vec<Claim>>
pub fn claims(&mut self) -> Result<Vec<Claim>>
13a (13.3): the live claims, by topic. Reads only.
Sourcepub fn touch_presence(
&mut self,
role: Option<&str>,
tool: Option<&str>,
) -> Result<bool>
pub fn touch_presence( &mut self, role: Option<&str>, tool: Option<&str>, ) -> Result<bool>
13a (13.3): record that this handle’s author is active, with its
role and tool: its presence record’s last_active, changed in
place, at most once a minute (sooner when the role, the tool or the
presence lock changed). Call it before a write the agent makes
anyway, so it rides that commit. false when nothing was written
(too soon, or no author).
Sourcepub fn who(&mut self) -> Result<Vec<Presence>>
pub fn who(&mut self) -> Result<Vec<Presence>>
13a (13.3): every agent with a presence record, most recently active
first: its role, tool, last_active, whether its process is alive
(by its presence lock; Alive::Unknown for an agent with no
long-lived process), and the topics it holds. Reads only.
Source§impl Mnemo
impl Mnemo
Sourcepub fn task(&mut self, slug: &str) -> Result<Option<Task>>
pub fn task(&mut self, slug: &str) -> Result<Option<Task>>
13a (13.1): one task by slug. Reads only.
Sourcepub fn tasks(
&mut self,
status: Option<&str>,
role: Option<&str>,
) -> Result<Vec<Task>>
pub fn tasks( &mut self, status: Option<&str>, role: Option<&str>, ) -> Result<Vec<Task>>
13a (13.1): the tasks, oldest first, with status and for role
when given (a task with no role matches any). Reads only.
Sourcepub fn ready_tasks(&mut self, role: Option<&str>) -> Result<Vec<Task>>
pub fn ready_tasks(&mut self, role: Option<&str>) -> Result<Vec<Task>>
13a (13.1): the queued tasks an agent of role may take now (all
their after tasks done), oldest first. Reads only.
Sourcepub fn task_add(&mut self, spec: &TaskSpec) -> Result<(Task, WriteOutcome)>
pub fn task_add(&mut self, spec: &TaskSpec) -> Result<(Task, WriteOutcome)>
13a (13.1): add a task, queued, created by this handle’s author.
A slug that already names a task updates its title, body, role,
after and pre_approved in place (its status, owner and history
stay); Unchanged when nothing differs. after must name existing
tasks, never itself.
Sourcepub fn task_next(&mut self, role: Option<&str>) -> Result<Option<TaskTaken>>
pub fn task_next(&mut self, role: Option<&str>) -> Result<Option<TaskTaken>>
13a (13.1): take the next task for role, for this handle’s author,
all in one exclusive window in a shared handle: the oldest queued
task for the role whose after tasks are all done; failing that
(R-010.7), an active one whose task:<slug> claim has lapsed,
taken back from its owner with a status_history entry naming it.
It claims task:<slug> for crate::memory::TASK_CLAIM_TTL and
sets active and the owner. None when there’s nothing to take.
Sourcepub fn task_update(
&mut self,
slug: &str,
status: Option<&str>,
note: Option<&str>,
token: Option<&str>,
) -> Result<TaskOutcome>
pub fn task_update( &mut self, slug: &str, status: Option<&str>, note: Option<&str>, token: Option<&str>, ) -> Result<TaskOutcome>
13a (13.1): change a task’s status (along TASK_TRANSITIONS), or
add a note with none, as this handle’s author.
- Its owner moves it from
activetoready,blockedorqueued(handing it back) and fromblockedtoactive, and may add notes; each renews itstask:<slug>claim. With atoken, the claim must be that token’s. An owner whose task was taken back (or whose token isn’t the claim’s) getsTaskOutcome::Lost. ready → doneis its creator’s, or its owner’s whenpre_approved.active → queuedis anyone’s once the owner’s claim has lapsed (an abandoned task).queued → activehappens only throughMnemo::task_next.
ready, done and queued release the claim.
Source§impl Mnemo
impl Mnemo
Sourcepub fn new_work(
&mut self,
agent: Option<&str>,
role: Option<&str>,
) -> Result<NewWork>
pub fn new_work( &mut self, agent: Option<&str>, role: Option<&str>, ) -> Result<NewWork>
13a (13.1b): what’s new for agent (and role) since it was last
shown. Reads only; Mnemo::mark_shown records that it was.
Sourcepub fn mark_shown(&mut self, work: &NewWork) -> Result<()>
pub fn mark_shown(&mut self, work: &NewWork) -> Result<()>
13a (13.1b): record that work was shown: its messages and tasks
seen, its lapsing claims warned about at their expiry. In place.
Sourcepub fn wake_paused(&mut self) -> Result<Option<(String, i64)>>
pub fn wake_paused(&mut self) -> Result<Option<(String, i64)>>
13a (13.1b): whether wake-ups are paused (the kill switch): who paused them and when.
Sourcepub fn set_wake_paused(&mut self, paused: bool) -> Result<WriteOutcome>
pub fn set_wake_paused(&mut self, paused: bool) -> Result<WriteOutcome>
13a (13.1b): pause (true) or resume wake-ups for every session
of this brain, on the manifest. Paused, nothing wakes anyone: items
stay sent, and the per-turn hook and the brief still show them.
Sourcepub fn wake(&mut self, agent: &str, role: Option<&str>) -> Result<Wake>
pub fn wake(&mut self, agent: &str, role: Option<&str>) -> Result<Wake>
13a (13.1b): the wake-up guardrails, in the one place that marks an
item delivered. For agent (and role), the items that may wake
it: pre-approved tasks ready for its role, and messages addressed to
it by id (never to its role or all), still sent. Then:
- paused (the kill switch):
Wake::Held; - an explicit reply past the hop cap (
crate::memory::HOP_CAP) or a pair in a burst (crate::memory::PAIR_BURSTmessages either way incrate::memory::PAIR_BURST_SECS) wakes nobody; - the recipient’s rate (
crate::memory::WAKE_PER_HOUR) and cooldown (crate::memory::WAKE_COOLDOWN_SECS), from its presence record’s_mnemo.wakes.
On Wake::Now the items are marked delivered and the wake-up is
recorded on the recipient’s presence record, in place.
Source§impl Mnemo
impl Mnemo
Sourcepub fn stale(&mut self) -> Result<Vec<Stale>>
pub fn stale(&mut self) -> Result<Vec<Stale>>
13a (13.6): every record that’s stale now
(crate::memory::stale_since), oldest first: past its review_by,
or older than its kind’s default (essence state and next 14
days, open 30, an active task with no update 3, a blocked one
7, an unread message 3). Reads only the rows that can be (essence,
coordination, and those with a review_by).
Source§impl Mnemo
impl Mnemo
Sourcepub fn kind_counts(&self) -> KindCounts
pub fn kind_counts(&self) -> KindCounts
13a (ABOUT-COUNT): how many live records of each kind, from the
catalog’s rows (a v8 file’s records have none and count as facts).
Superseded versions count too, as in Mnemo::len.
Source§impl Mnemo
impl Mnemo
Sourcepub fn flush(&mut self) -> Result<()>
pub fn flush(&mut self) -> Result<()>
Persist all pending changes as one write-ahead-logged transaction.
Sequence:
- Prepare. Serialize the control plane (catalog, ANN index),
grow the WAL if needed, and lease counter and page slots —
bump
header.write_counterandheader.next_pageby upper bounds on this transaction’s consumption and persist that leased header to disk before any encrypted page is written. - Data pages. [
Pager::flush] writes dirty record pages copy-on-write under fresh nonces and fsyncs them. The orphan-page nonce-reuse window (see [Phase 1.1 of the improvement plan]) is closed because the leased header on disk already records awrite_counterpast anything this step can produce. - Control plane. Seal the new catalog / ANN index / snapshot manifest into fresh home page runs.
- Commit. Log all of step 3’s frames plus the final header frame into the WAL and fsync — the durability point.
- Checkpoint. Fold the WAL into the home pages.
A crash before step 4 leaves the previous state intact. A crash
after step 4 is repaired by Mnemo::open replaying the WAL.
Safe to call repeatedly.
Sourcepub fn close(self) -> Result<()>
pub fn close(self) -> Result<()>
Flush and close: consumes the handle and releases the file and its OS advisory lock before returning, so the same file can be reopened right away (by this process or another). On a read-write handle it flushes first, persisting a dirty ANN index too; on a read-only handle there’s nothing to persist.
Using the handle after close is a compile error. If the flush
fails, the error is returned and the handle is dropped all the same:
changes since the last successful Mnemo::flush are lost, as
they would be on a plain drop (which never flushes).
A struct that owns a handle and closes it from &mut self keeps it
in an Option and take()s it:
use mnemo_engine::{Mnemo, Result};
struct App {
db: Option<Mnemo>,
}
impl App {
fn shutdown(&mut self) -> Result<()> {
match self.db.take() {
Some(db) => db.close(),
None => Ok(()), // already closed
}
}
}Changed in v0.12.0: close took &mut self and left the file and
lock held until the handle was dropped.
If the final flush fails, the handle is dropped with it, and the
writes that weren’t flushed are lost (a full disk on a phone, say).
Mnemo::try_close gives the handle back on that path, so the caller
can free space and retry.
Sourcepub fn try_close(self) -> Result<(), CloseError>
pub fn try_close(self) -> Result<(), CloseError>
Mnemo::close that keeps the data when the final flush fails: the
error carries the handle back, with every unflushed write still in
it, as std::io::BufWriter::into_inner does. Retry with
Mnemo::flush or another try_close once the cause is fixed.
A read-only handle never flushes, so it always closes. Added in
v0.12.2 (RB-001.22).
match db.try_close() {
Ok(()) => {}
Err(e) => {
eprintln!("close failed: {}", e.error());
let mut db = e.into_inner(); // still open, still holding the writes
db.flush()?; // e.g. after freeing space
db.close()?;
}
}Sourcepub fn flush_index(&mut self) -> Result<()>
pub fn flush_index(&mut self) -> Result<()>
PERF-1: flush, persisting the ANN index even if the
INDEX_PERSIST_EVERY_COMMITS / INDEX_PERSIST_EVERY_CHANGES
policy wouldn’t yet. Plain Mnemo::flush writes only the catalog
between persists; the index is derived, so a crash costs nothing but
re-assigning the newer records on the next load.
Sourcepub fn set_cache_capacity(&mut self, pages: usize)
pub fn set_cache_capacity(&mut self, pages: usize)
Bound the in-memory page cache to pages decrypted pages.
The cache holds decrypted page payloads to speed repeated reads. By
default it is capped at 1024 pages (~8 MiB; 8192 before v0.10.0).
Lower the cap to trade hit rate for a smaller footprint, or raise
it for a hotter cache. The
cap governs clean pages — pages with un-flushed writes are always
retained until Mnemo::flush, regardless of the cap.
Sourcepub fn set_vector_cache_budget(&mut self, bytes: usize)
pub fn set_vector_cache_budget(&mut self, bytes: usize)
FMT-9b (v9 files): keep the fp16 vector column in memory while it
takes at most bytes (default DEFAULT_VECTOR_CACHE_BUDGET,
96 MiB, about 125K vectors at 384 dims). Above it, recall reads
vector entries through the page cache instead: less memory, slower
recall. Lowering it below the resident size drops the resident copy.
Sourcepub fn page_cache_stats(&self) -> (usize, usize)
pub fn page_cache_stats(&self) -> (usize, usize)
Page-cache occupancy: (pages_cached, capacity). Renamed from
cache_stats in v0.4.0: the result-cache API (Phase 10.1) took
that name for its per-namespace CacheStats summary, and the
page-cache pair is the older/less-user-facing of the two, so it
gets the more-specific name.
Source§impl Mnemo
impl Mnemo
Sourcepub fn default_agent(&mut self) -> Result<Option<String>>
pub fn default_agent(&mut self) -> Result<Option<String>>
13a (AGENT-DEFAULT): the agent the manifest names for a write that
names none (_mnemo.default_agent), if it names one. The CLI and the
MCP server use it in place of default; the engine’s own default is
unchanged.
Sourcepub fn set_default_agent(&mut self, agent: Option<&str>) -> Result<WriteOutcome>
pub fn set_default_agent(&mut self, agent: Option<&str>) -> Result<WriteOutcome>
13a (AGENT-DEFAULT): set (or with None, clear) the manifest’s
_mnemo.default_agent, in place: the manifest keeps its id, content
and vector. agent must be 1 to 64 of [A-Za-z0-9._-]. Returns
Unchanged when it already says so. A brain with no manifest is
refused.
Sourcepub fn remember_keyed(
&mut self,
memory: Memory,
key: &str,
) -> Result<(Ulid, WriteOutcome)>
pub fn remember_keyed( &mut self, memory: Memory, key: &str, ) -> Result<(Ulid, WriteOutcome)>
Store a memory under a keyed upsert slot. Returns the live record’s
id and a WriteOutcome saying whether this write created a new
slot (Added), replaced a prior record (Superseded), or matched
the existing live record byte-for-byte (Unchanged, no file write).
The slot is identified by (scope_owner, key):
Scope::Privatememories share a slot per(agent_id, key).Scope::Sharedmemories share one slot perkeyacross the file.
On supersession the prior record is not deleted — it remains
retrievable through Mnemo::history — but it is excluded from
default Mnemo::recall and Mnemo::about. A caller that wants
the full lineage of a key walks history(key).
This is the atomic 12.1 “supersede-or-noop” write path. Plain
Mnemo::remember without a key is unchanged.
Sourcepub fn remember_keyed_superseding(
&mut self,
memory: Memory,
key: &str,
supersedes: &Ulid,
) -> Result<(Ulid, WriteOutcome)>
pub fn remember_keyed_superseding( &mut self, memory: Memory, key: &str, supersedes: &Ulid, ) -> Result<(Ulid, WriteOutcome)>
12.3 step 5b (v0.15): a keyed write that adopts a named, unkeyed memory as the key’s first version, then supersedes it. Use it to put a fact that was written without a key under one, so the old version stops showing in recall without being deleted.
The old record (supersedes) takes the key (_mnemo.key) and is
marked _mnemo.superseded_by and _mnemo.invalid_at; the new record
gets _mnemo.supersedes = <old id>. Mnemo::history then lists the
old record as the oldest version, and recall and about leave it out,
as for any superseded record. No format change: these are the keyed
path’s own _mnemo.* keys, which older builds carry through.
When the new content matches the old record’s user-visible fields
(the identical-write rule of Mnemo::remember_keyed), no new record
is written: the old one takes the key and becomes the slot’s live
record, and the outcome is WriteOutcome::Updated with its id.
Refused with MnemoError::Invalid when the old id doesn’t exist or
is deleted; is already superseded; already has a key (use the plain
keyed write); is an engine record (any _mnemo.kind, or the
manifest); isn’t in the key’s slot scope (the same agent’s Private
memory for a Private write, a Shared one for a Shared write); or when
the slot already has a live record. MnemoError::ReadOnly on a
read-only handle.
Sourcepub fn remember_keyed_text_superseding(
&mut self,
content: &str,
memory_type: MemoryType,
key: &str,
supersedes: &Ulid,
) -> Result<(Ulid, WriteOutcome)>
pub fn remember_keyed_text_superseding( &mut self, content: &str, memory_type: MemoryType, key: &str, supersedes: &Ulid, ) -> Result<(Ulid, WriteOutcome)>
Mnemo::remember_keyed_superseding with content embedded by the
registered embedder (the document side).
Sourcepub fn remember_keyed_text(
&mut self,
content: &str,
memory_type: MemoryType,
key: &str,
) -> Result<(Ulid, WriteOutcome)>
pub fn remember_keyed_text( &mut self, content: &str, memory_type: MemoryType, key: &str, ) -> Result<(Ulid, WriteOutcome)>
Text-side keyed write: embed content through the registered
embedder, then Mnemo::remember_keyed. Same returns.
Sourcepub fn update(&mut self, id: &Ulid, patch: MemoryPatch) -> Result<WriteOutcome>
pub fn update(&mut self, id: &Ulid, patch: MemoryPatch) -> Result<WriteOutcome>
Update an existing memory in place, preserving its ULID,
created_at and access stats. Returns WriteOutcome::Updated
on a real change, WriteOutcome::Unchanged when every field in
the patch already matches the live record.
Reserved _mnemo.* metadata keys on the existing record are
preserved across a metadata replacement; a metadata of
Some(map) replaces every user-visible key with map’s
entries. A content change requires a matching vector
(use Mnemo::update_text to re-embed) — a bare content patch
is rejected to stop text and embedding drifting apart silently.
A metadata map with a key starting with _mnemo. is refused with
MnemoError::Invalid: those keys are the engine’s, and the
record’s own are kept as described above.
Sourcepub fn update_text(
&mut self,
id: &Ulid,
new_text: &str,
patch: MemoryPatch,
) -> Result<WriteOutcome>
pub fn update_text( &mut self, id: &Ulid, new_text: &str, patch: MemoryPatch, ) -> Result<WriteOutcome>
In-place update that re-embeds new_text through the registered
embedder. Shorthand for update(id, patch.with_content_and_vector).
Sourcepub fn history(
&mut self,
key: &str,
agent_id: Option<&str>,
) -> Result<Vec<Memory>>
pub fn history( &mut self, key: &str, agent_id: Option<&str>, ) -> Result<Vec<Memory>>
Walk the full chain for a keyed slot: every record this key has ever held, newest first. Entry 0 is the live record (unless the slot is empty, in which case the vector is empty); subsequent entries are the superseded history in reverse-supersession order.
Slot resolution (v0.8.1 bugfix, lane A). The lookup slot
matches a keyed remember with the same arguments, so the
obvious history(key, None) walks the private slot of the
default agent — the same slot
remember_keyed(Memory::new(...), key) writes to when the
caller omits an explicit agent_id / scope. Pre-v0.8.1
agent_id = None incorrectly looked up the shared slot and
returned an empty chain for the common case; the old behavior
is still reachable via history_in(key, KeyScope::Shared).
agent_id = Some(a)→ private slot for that agent.agent_id = None→ private slot for the default agent (same asKeyScope::private_default).
Use Mnemo::history_in with KeyScope::Shared for the
shared slot.
Sourcepub fn history_in(&mut self, key: &str, scope: KeyScope) -> Result<Vec<Memory>>
pub fn history_in(&mut self, key: &str, scope: KeyScope) -> Result<Vec<Memory>>
Walk the full chain for a keyed slot identified by an explicit
KeyScope. Returns the same shape as Mnemo::history —
live record first, then the superseded chain newest-first.
Use this when you need the shared slot (KeyScope::Shared),
which history(key, None) no longer reaches as of v0.8.1.
Source§impl Mnemo
impl Mnemo
Sourcepub fn kdf_params(&self) -> KdfParams
pub fn kdf_params(&self) -> KdfParams
Return the KDF (Argon2id) parameters this file currently uses to
wrap its DEK. Needed by callers that want to [rekey] while
keeping the file’s original protection level (e.g. the Python
binding’s rekey(fast=False), whose docstring promises exactly
that). FIX-1 R-001.5.
Sourcepub fn export_encrypted(&mut self, dest: impl AsRef<Path>) -> Result<()>
pub fn export_encrypted(&mut self, dest: impl AsRef<Path>) -> Result<()>
Flush any pending writes, then stream the (encrypted) file to
dest atomically: writes to a sibling temp file in dest’s
parent directory, sync_alls it, renames onto dest, and
fsyncs the parent directory on Unix so a crash never leaves a
partial export.
Refuses when dest resolves to the file this handle has open
— that case would otherwise File::create-truncate the live
database to 0 bytes (fs::copy on Unix reads after the
O_TRUNC, so a naive export-to-self destroys the source).
Unix: compares (dev, ino) of both paths via MetadataExt,
catching symlinks and hard links. Windows: compares
canonicalized paths. (The rename is no second line of defense:
renaming over a file another handle holds open and locked
succeeds on Windows too, as a 2026-11-13 CI probe showed.)
Reads the bytes from the already-open file handle, not by
fs::copy. On Windows that matters: LockFileEx locks are
mandatory, so a second handle opened by fs::copy would fail
while this writer still holds the lock.
FIX-1 R-001.5 + R-002.2 part 3.
Sourcepub fn rekey(&mut self, new_passphrase: &str, kdf: KdfParams) -> Result<()>
pub fn rekey(&mut self, new_passphrase: &str, kdf: KdfParams) -> Result<()>
Change the passphrase. Cheap: re-derives the KEK and re-wraps the DEK; the encrypted pages are never rewritten.
This changes the secret that opens this file from now on; anyone who
had the file and the old secret can still read it and later writes.
The data key stays the same, so an earlier copy of the file (or of
just its header) and the old passphrase still unlock it. The old wrap
is scrubbed from this file (the previous WAL region is zeroed, and any
stale copy of the old header’s key wrap is overwritten); that’s
hygiene, not revocation. To revoke, rotate: rekey, then
Mnemo::compact_file (mnemo rekey --rotate), which rewrites the
file under a fresh data key. Rotation can’t erase old ciphertext the storage hardware still holds: flash keeps rewritten blocks until it reuses them, and that’s out of the engine’s hands.
An error means the old secret is still in force, for this handle and for the file, including after later writes and a close (REKEY-1). The one exception is when the new header’s write fails and putting the old one back fails too: the error then says so, and the file may open with either secret.
Ok means the new secret is in force. Scrubbing the old wrap
afterwards is hygiene; if part of it fails, the rekey still succeeds
and Mnemo::rekey_cleanup_error says what was left.
Sourcepub fn rekey_with_key(&mut self, new_key: &[u8; 32]) -> Result<()>
pub fn rekey_with_key(&mut self, new_key: &[u8; 32]) -> Result<()>
PERF-1 step 7: switch to (or rotate) a raw 256-bit key, recording
KdfParams::raw_key in the header. Like Mnemo::rekey, only the
wrapped DEK changes; pages aren’t rewritten, and it doesn’t revoke
the old key (see Mnemo::rekey).
Errors and the cleanup report work as in Mnemo::rekey.
Sourcepub fn rekey_cleanup_error(&self) -> Option<&str>
pub fn rekey_cleanup_error(&self) -> Option<&str>
REKEY-1 (RB-004.2): after a successful Mnemo::rekey or
Mnemo::rekey_with_key, what couldn’t be scrubbed of the old key
wrap, or None if it all was. The rekey took effect either way; what
is left is plaintext key-wrap bytes the old secret could still use, so
to be sure, rotate (compact_file) as Mnemo::rekey describes.
Each rekey resets it.
Sourcepub fn export_rekeyed(
&mut self,
dest: impl AsRef<Path>,
passphrase: &str,
kdf: KdfParams,
) -> Result<CompactReport>
pub fn export_rekeyed( &mut self, dest: impl AsRef<Path>, passphrase: &str, kdf: KdfParams, ) -> Result<CompactReport>
SEC-2 (RB-001.30): write a copy of this database at dest under a
fresh data key, protected by passphrase through kdf. It goes
through the compaction path (live memories, the result cache and
the index, no history), so the copy shares no key material with
this file: neither this file’s passphrase nor its data key opens
it, and its passphrase opens nothing here. This file is flushed
first (unless read-only) and is otherwise unchanged; dest must not
exist. The copy is v9.
Sourcepub fn export_rekeyed_with_key(
&mut self,
dest: impl AsRef<Path>,
key: &[u8; 32],
) -> Result<CompactReport>
pub fn export_rekeyed_with_key( &mut self, dest: impl AsRef<Path>, key: &[u8; 32], ) -> Result<CompactReport>
Mnemo::export_rekeyed protected by a raw 256-bit key (no KDF).
Sourcepub fn verify(&mut self) -> Result<usize>
pub fn verify(&mut self) -> Result<usize>
Decrypt and validate every live record. Returns the count verified
across memories and cache entries (FIX-1 R-001.1: now that the
cache survives compaction, verify() has to walk it too — the
pre-FIX-1 implementation only checked self.catalog, so a
corrupted cache record went unnoticed).
Sourcepub fn verify_report(&mut self) -> Result<VerifyReport>
pub fn verify_report(&mut self) -> Result<VerifyReport>
Mnemo::verify, also counting the memories whose vector is all
zeros. A file written before the zero-vector rule (Phase 3 PR 10a)
can hold them; they decode fine but score 0.0 on every vector query.
mnemo verify warns about them, and compaction carries them
(giving a legacy manifest the sentinel vector).
Sourcepub fn stats_summary(&self) -> StatsSummary
pub fn stats_summary(&self) -> StatsSummary
The statistics that need no record decrypts and no index load
(v0.12.2, RB-002.3): counts, sizes, the format, whether an index
exists, the recall mode and the bytes the vector column needs. The
first Mnemo::stats on a handle decrypts every record (for its
agent list) and loads a persisted index; this is what a phone app
polling the recall mode should call.
Sourcepub fn stats(&mut self) -> Result<Stats>
pub fn stats(&mut self) -> Result<Stats>
Summary statistics for the open database. The first call on a
handle decrypts every record (to list the agents) and loads a
persisted index; Mnemo::stats_summary does neither.
Sourcepub fn compact_file(path: &str, passphrase: &str) -> Result<CompactReport>
pub fn compact_file(path: &str, passphrase: &str) -> Result<CompactReport>
Rewrite the file, dropping tombstoned and expired memories and reclaiming stale pages left by updates. Done out-of-place via a temp file and an atomic rename.
FIX-1 R-001.1 + R-002.2 part 2: the result cache now survives
compaction. Every live, non-expired directory entry is copied
into the new file verbatim — created_at, ttl_secs,
cost_hint_ms, key_preview, size_bytes, content_type,
vector and model come from the record body; accessed_at
and access_count come from the directory (the record body
only holds the insert-time snapshot — the directory is the
source of truth for the live counts, as of v5’s recall trick).
Tombstoned and TTL-expired entries are dropped. Pre-FIX-1
compaction kept only the memory catalog and silently emptied
the cache; the Planner’s interim README caveat (c417d2e) called
that out — this PR removes the surprise.
The output is always v9, so this is also how a v4–v8 file is converted: the only read-write open that accepts one (the v8 sunset, v0.13). It keeps every live memory.
Sourcepub fn compact_file_with_key(
path: &str,
key: &[u8; 32],
) -> Result<CompactReport>
pub fn compact_file_with_key( path: &str, key: &[u8; 32], ) -> Result<CompactReport>
PERF-1 step 7: Mnemo::compact_file for a raw-key database.
Sourcepub fn compact_file_waiting(
path: &str,
passphrase: &str,
opts: SharedOptions,
) -> Result<CompactReport>
pub fn compact_file_waiting( path: &str, passphrase: &str, opts: SharedOptions, ) -> Result<CompactReport>
Mnemo::compact_file with the lock layer’s options: how long to
wait for the file’s lock (opts.deadline; compact_file waits 10 s),
a cancel, and allow_network_fs. mnemo compact --wait uses it.
Sourcepub fn compact_file_waiting_with_key(
path: &str,
key: &[u8; 32],
opts: SharedOptions,
) -> Result<CompactReport>
pub fn compact_file_waiting_with_key( path: &str, key: &[u8; 32], opts: SharedOptions, ) -> Result<CompactReport>
Mnemo::compact_file_waiting for a raw-key database.
Sourcepub fn reembed_file(
path: &str,
passphrase: &str,
embedder: &dyn Embedder,
) -> Result<ReembedReport>
pub fn reembed_file( path: &str, passphrase: &str, embedder: &dyn Embedder, ) -> Result<ReembedReport>
12.3 step 4 (v0.15): embed every live memory again with
embedder and record its identity, so a file moves to a new model
(or a new query convention, or a new width) in one step.
It’s a compaction with new vectors: it runs under the file’s
exclusive lock (waiting 10 s for it, like Mnemo::compact_file),
writes a temp file beside the brain with the same salt and KDF
parameters, and renames it over the brain while the lock is held. An
interrupted run leaves the old file whole (and a temp file the next
compaction or reembed removes), so the file never opens with two
identities or mixed vectors.
- Every live memory is embedded with
Embedder::embed(the document side), in batches of 64: facts, superseded versions (so history reads stay consistent), essence items and thread turns. A manifest and a thread link (_mnemo.kind = "thread_link") keep their sentinel vector, at the new width, and aren’t embedded. - The new identity is recorded in the
_mnemo.embedderentry and in the manifest’smetadata.embedder. - The result cache is copied as compaction copies it; a semantic entry whose vector has the old width is dropped.
- The ANN index is rebuilt if there was one, and the keyword index with the current tokenizer (TOK-1). Snapshot history is dropped, as by compaction.
Sourcepub fn reembed_file_with_key(
path: &str,
key: &[u8; 32],
embedder: &dyn Embedder,
) -> Result<ReembedReport>
pub fn reembed_file_with_key( path: &str, key: &[u8; 32], embedder: &dyn Embedder, ) -> Result<ReembedReport>
Mnemo::reembed_file for a raw-key database.
Sourcepub fn reembed_file_waiting(
path: &str,
passphrase: &str,
embedder: &dyn Embedder,
opts: SharedOptions,
) -> Result<ReembedReport>
pub fn reembed_file_waiting( path: &str, passphrase: &str, embedder: &dyn Embedder, opts: SharedOptions, ) -> Result<ReembedReport>
Mnemo::reembed_file with the lock layer’s options (how long to
wait for the lock, a cancel), as Mnemo::compact_file_waiting.
Sourcepub fn reembed_file_waiting_with_key(
path: &str,
key: &[u8; 32],
embedder: &dyn Embedder,
opts: SharedOptions,
) -> Result<ReembedReport>
pub fn reembed_file_waiting_with_key( path: &str, key: &[u8; 32], embedder: &dyn Embedder, opts: SharedOptions, ) -> Result<ReembedReport>
Mnemo::reembed_file_waiting for a raw-key database.
Source§impl Mnemo
impl Mnemo
Sourcepub fn create(
path: impl Into<PathBuf>,
passphrase: &str,
config: MnemoConfig,
) -> Result<Mnemo>
pub fn create( path: impl Into<PathBuf>, passphrase: &str, config: MnemoConfig, ) -> Result<Mnemo>
Create a brand-new encrypted database at path.
Sourcepub fn create_with_key(
path: impl Into<PathBuf>,
key: &[u8; 32],
config: MnemoConfig,
) -> Result<Mnemo>
pub fn create_with_key( path: impl Into<PathBuf>, key: &[u8; 32], config: MnemoConfig, ) -> Result<Mnemo>
PERF-1 step 7 (R-004.5): create a database unlocked by a raw
256-bit key instead of a passphrase, for keys held by an OS
keychain or keystore. The key must be uniformly random (see
Mnemo::generate_key); it gets no stretching. The header records
minimal Argon2id parameters (KdfParams::raw_key), so opening
costs microseconds instead of tens of milliseconds. config.kdf is
ignored. No format change: the key goes through the same KEK
derivation a passphrase does.
Sourcepub fn generate_key() -> [u8; 32]
pub fn generate_key() -> [u8; 32]
A fresh random 256-bit key for Mnemo::create_with_key, from the
thread-local CSPRNG (seeded from the OS). Store it in a keychain;
it can’t be recovered from the file.
Sourcepub fn open(path: impl Into<PathBuf>, passphrase: &str) -> Result<Mnemo>
pub fn open(path: impl Into<PathBuf>, passphrase: &str) -> Result<Mnemo>
Open an existing database. A wrong passphrase fails cleanly with
MnemoError::WrongPassphrase. Takes an OS exclusive lock for
the lifetime of the returned handle; a second concurrent open
(from any process) returns MnemoError::Locked.
For a caller that only needs to read (and can tolerate the
pending-recovery / pending-migration cases documented on
Mnemo::open_read_only), prefer that entry point — it takes a
shared lock and coexists with other readers.
Sourcepub fn open_with_key(path: impl Into<PathBuf>, key: &[u8; 32]) -> Result<Mnemo>
pub fn open_with_key(path: impl Into<PathBuf>, key: &[u8; 32]) -> Result<Mnemo>
PERF-1 step 7: open a database created by Mnemo::create_with_key
(or rekeyed with Mnemo::rekey_with_key) with its raw key.
Sourcepub fn open_exclusive(
path: impl AsRef<Path>,
passphrase: &str,
op: &str,
opts: SharedOptions,
) -> Result<Mnemo>
pub fn open_exclusive( path: impl AsRef<Path>, passphrase: &str, op: &str, opts: SharedOptions, ) -> Result<Mnemo>
Open read-write through 12.4’s lock layer, for a long operation that
must not run alongside shared handles’ calls: an import, a rekey, a
compaction (Mnemo::compact_file does this itself).
Unlike Mnemo::open, which tries the lock once and fails with
MnemoError::Locked, this waits up to opts.deadline with writer
preference (the intent lock), so busy shared readers can’t keep it
out. Once it holds the lock it writes a lock-info note naming op,
so a shared caller that times out learns what holds the file. The
handle keeps the exclusive lock until it’s dropped or closed, like
any read-write handle.
Where shared mode isn’t available (a network or synced filesystem
without opts.allow_network_fs, or a Windows build made with Rust
before 1.85) it opens as Mnemo::open does: one try, no note.
Sourcepub fn open_exclusive_with_key(
path: impl AsRef<Path>,
key: &[u8; 32],
op: &str,
opts: SharedOptions,
) -> Result<Mnemo>
pub fn open_exclusive_with_key( path: impl AsRef<Path>, key: &[u8; 32], op: &str, opts: SharedOptions, ) -> Result<Mnemo>
Mnemo::open_exclusive for a raw-key file.
Sourcepub fn open_read_only(
path: impl Into<PathBuf>,
passphrase: &str,
) -> Result<Mnemo>
pub fn open_read_only( path: impl Into<PathBuf>, passphrase: &str, ) -> Result<Mnemo>
Open an existing database in read-only mode. Takes an OS shared
lock; multiple read-only handles can coexist, but any attempt to
open the same file read-write elsewhere returns
MnemoError::Locked. All mutating methods on the returned handle
return MnemoError::ReadOnly, including recall with
track_access(true).
Two conditions block a read-only open and return
MnemoError::NeedsWriteOpen:
- The file has a committed-but-uncheckpointed WAL transaction that would ordinarily be replayed on open. A read-only handle cannot write the recovered pages back.
- The on-disk format version is older than the current
format::VERSION, requiring an on-disk migration.
In either case, open the file read-write once (which recovers / migrates in place), close the handle cleanly, and reopen read-only. This is documented in the README’s Durability section.
Sourcepub fn open_read_only_with_key(
path: impl Into<PathBuf>,
key: &[u8; 32],
) -> Result<Mnemo>
pub fn open_read_only_with_key( path: impl Into<PathBuf>, key: &[u8; 32], ) -> Result<Mnemo>
PERF-1 step 7: Mnemo::open_read_only for a raw-key database.
Sourcepub fn peek_dimensions(path: impl AsRef<Path>) -> Result<usize>
pub fn peek_dimensions(path: impl AsRef<Path>) -> Result<usize>
The embedding width the file at path records, read from its header
(page 0 is sealed, not encrypted): no key, no lock, no KDF. A caller
that embeds before it takes the lock uses it to build its embedder’s
identity (12.4: slow work first, unlocked). A torn header is an
error here (a read-write open heals it).
Sourcepub fn key_opens(path: impl AsRef<Path>, key: &[u8; 32]) -> Result<bool>
pub fn key_opens(path: impl AsRef<Path>, key: &[u8; 32]) -> Result<bool>
Whether key opens the raw-key file at path, decided from its
header alone: no catalog load, no lock, microseconds. Ok(false) is
“not this key”. Unlike a read-only open, it answers for a file that
has a WAL transaction to recover (the state a kill between a commit
and its checkpoint leaves), so a caller trying each of its keys in
turn isn’t stopped by MnemoError::NeedsWriteOpen. A torn header is
judged from the WAL frame that would heal it. Other failures (not a
.mnemo file, a tampered header, an I/O error) are errors. Added in
v0.12.2 (RB-001.23).
Sourcepub fn open_read_only_waiting(
path: impl AsRef<Path>,
passphrase: &str,
opts: SharedOptions,
) -> Result<Mnemo>
pub fn open_read_only_waiting( path: impl AsRef<Path>, passphrase: &str, opts: SharedOptions, ) -> Result<Mnemo>
Mnemo::open_read_only through 12.4’s lock layer: it waits up to
opts.deadline for a writer (a plain handle, a shared write, a
compaction) instead of failing at once with Locked, and runs
alongside other readers. The handle then holds the shared lock for
its life, as any read-only handle does; close it promptly. A Locked
after the wait names what holds the file when it left a note.
Like open_read_only, it never recovers anything: a pending WAL or
a torn header gives MnemoError::NeedsWriteOpen. Where shared
mode isn’t available it tries once, as open_read_only does.
Sourcepub fn open_read_only_waiting_with_key(
path: impl AsRef<Path>,
key: &[u8; 32],
opts: SharedOptions,
) -> Result<Mnemo>
pub fn open_read_only_waiting_with_key( path: impl AsRef<Path>, key: &[u8; 32], opts: SharedOptions, ) -> Result<Mnemo>
Mnemo::open_read_only_waiting for a raw-key file.
13a: stamp _mnemo.author = author on each new record this handle
writes (a fact, a turn, an essence item; an edit in place keeps the
record’s own). The CLI, the MCP server and the hooks set it from
MNEMO_AGENT. Unproven until 13.4 signs it. Per handle, not
persisted.
13a: the author this handle stamps on new records, if any.
Sourcepub fn set_turn_compress_after(&mut self, secs: u64)
pub fn set_turn_compress_after(&mut self, secs: u64)
FMT-9e: compress v9 thread-turn records once they’re older than
secs (by their created_at). The default,
DEFAULT_TURN_COMPRESS_AFTER_SECS, is 7 days: recent turns stay
plain, so a live session reads them at full speed, and each commit
compresses up to 256 turns that have aged past the cutoff. 0
compresses every turn as it’s written. Compaction always compresses
every turn, and so does a vacuum that moves one. Applies to this
handle only (not persisted); a no-op on v8 files, which never
compress. Reading never depends on it.
Sourcepub fn set_max_snapshots(&mut self, max: usize)
pub fn set_max_snapshots(&mut self, max: usize)
Override the manifest snapshot cap on this open handle. 0 disables
the cap; any positive value keeps the most-recent max snapshots and
drops the rest on the next flush. See MnemoConfig::max_snapshots.
Sourcepub fn notices(&self) -> &[String]
pub fn notices(&self) -> &[String]
12.3: what this handle has to tell its owner, once each: today, that a passphrase opened a file whose KDF parameters are the raw-key kind (the keys note, section 1, rule 7), with the fix. Empty otherwise.
Sourcepub fn dimensions(&self) -> usize
pub fn dimensions(&self) -> usize
Embedding dimensionality this database expects.
Source§impl Mnemo
impl Mnemo
Sourcepub fn memories(&mut self) -> Result<Vec<Memory>>
pub fn memories(&mut self) -> Result<Vec<Memory>>
Return every live memory (used by tooling and compaction).
Sourcepub fn recent(&mut self, n: usize) -> Result<Vec<Memory>>
pub fn recent(&mut self, n: usize) -> Result<Vec<Memory>>
12.2 (mnemo://recent): the n most recently written live memories,
newest first. Only facts: no thread turns, essence items, thread
links or onboarding records, and nothing superseded or expired. A
keyed replacement is a new record, so it counts from when it was
written; an in-place Mnemo::update keeps its created_at. Reads
the catalog’s rows and decrypts only the records it returns (on v9),
and doesn’t count as an access.
Sourcepub fn recent_in(
&mut self,
n: usize,
visibility: VisibilitySet,
) -> Result<Vec<Memory>>
pub fn recent_in( &mut self, n: usize, visibility: VisibilitySet, ) -> Result<Vec<Memory>>
13a (13.5): Mnemo::recent with the visibility levels it shows
(recent itself shows public and team).
Sourcepub fn about(&mut self) -> Result<Vec<Memory>>
pub fn about(&mut self) -> Result<Vec<Memory>>
Return the database’s self-describing onboarding memories — the
ones tagged metadata.area = "onboarding". This is the engine-level
surface for the single-file philosophy: an agent who receives a
.mnemo file (and its passphrase) can call this to learn what the
file is, which embedder it expects, the recommended agent id, and any
other conventions the file’s author chose to record — all without
needing any external documentation.
Ordering: the canonical manifest (tag metadata.topic = "manifest")
always comes first; everything else follows in importance descending,
then created_at ascending for deterministic results.
Sourcepub fn about_in(&mut self, visibility: VisibilitySet) -> Result<Vec<Memory>>
pub fn about_in(&mut self, visibility: VisibilitySet) -> Result<Vec<Memory>>
13a (13.5): Mnemo::about with the visibility levels it shows
(about itself shows public and team).
Sourcepub fn about_essence(&mut self) -> Result<Option<String>>
pub fn about_essence(&mut self) -> Result<Option<String>>
The project essence for the about briefing (Phase 12.7d): the
EssenceScope::Project render at the default budget
(ESSENCE_DEFAULT_RENDER_BYTES), or None when the file has no
open project-scope item or timeline entry. The CLI and MCP about
append it after the manifest and onboarding memories; Mnemo::about
itself keeps returning records.
Sourcepub fn search(
&mut self,
query: &[f32],
top_k: usize,
metric: Metric,
) -> Result<Vec<(Memory, f32)>>
pub fn search( &mut self, query: &[f32], top_k: usize, metric: Metric, ) -> Result<Vec<(Memory, f32)>>
Phase-1 brute-force search: rank live memories by raw similarity only. Read-only — does not update access statistics.
Sourcepub fn search_in(
&mut self,
query: &[f32],
top_k: usize,
metric: Metric,
visibility: VisibilitySet,
) -> Result<Vec<(Memory, f32)>>
pub fn search_in( &mut self, query: &[f32], top_k: usize, metric: Metric, visibility: VisibilitySet, ) -> Result<Vec<(Memory, f32)>>
13a (RB-013.2): Mnemo::search with the visibility levels it shows
(search itself shows public and team). Coordination records
(messages, tasks, claims, presence) are never results.
Sourcepub fn recall(&mut self, req: &RecallRequest) -> Result<Vec<RecallResult>>
pub fn recall(&mut self, req: &RecallRequest) -> Result<Vec<RecallResult>>
Phase-5 multi-signal recall under the v0.7.0 scoring-v2 formula
(see crate::ScoreWeights). Thin wrapper over
Mnemo::recall_budgeted that drops the truncated flag;
use the budgeted form if you need to know whether
RecallRequest::max_bytes cut anything.
Sourcepub fn recall_budgeted(&mut self, req: &RecallRequest) -> Result<RecallResponse>
pub fn recall_budgeted(&mut self, req: &RecallRequest) -> Result<RecallResponse>
Phase 12.8 budgeted recall: scoring v2 (see crate::ScoreWeights)
with an optional UTF-8-content byte cap. Ranks by
sim + max(sim, 0) · (β·recency + γ·(importance − 0.5) + δ·tanh(uses/5)),
with type / agent / supersession / TTL filters and the 12.6
Filter applied before the scorer. Updates accessed_at /
access_count on the returned memories (persisted on the next
flush).
When an ANN index has been built (Mnemo::build_index),
recall runs the tiered IVF→PQ→rerank pipeline. If the filters
(type / agent / supersession / TTL / 12.6) reduce the ANN
shortlist below top_k, Phase 12.1’s short-results-on-indexed-
path fix kicks in: the query is retried with n_probe and
n_rerank doubled, and if that would already touch half or
more of the live non-superseded records, the ANN pass is
skipped for an exact scan. Without an index, recall scores
every live non-superseded memory.
Phase 12.8: after top_k is applied, if
RecallRequest::max_bytes is set, hits are dropped in rank
order once the running sum of content UTF-8 bytes would
exceed the budget. The top-1 hit is always kept even if it
alone exceeds the budget. RecallResponse::truncated is
true iff at least one hit was dropped by the budget.
Source§impl Mnemo
impl Mnemo
Open the brain at path in shared mode (12.4): several
processes, sessions and tools can use one file at once. The handle
takes the file’s lock for each call and holds nothing between calls.
The file must exist and be v9; shared mode never creates one. It’s
refused on a network or synced filesystem unless
SharedOptions::allow_network_fs, and on Windows builds made with
Rust before 1.85 (MnemoError::Unsupported).
The handle keeps its secret for its whole life, because every
compaction gives the file a new data key: without the secret, a
handle couldn’t follow a mnemo compact. The passphrase is zeroized
when the handle drops.
Use SharedMnemo::read and SharedMnemo::write to call the
handle’s methods. Rust API only for now; the Python, CLI and MCP
surfaces come later.
Mnemo::open_shared for a raw-key file.
Source§impl Mnemo
impl Mnemo
Sourcepub fn file_stamp(path: &Path) -> Option<String>
pub fn file_stamp(path: &Path) -> Option<String>
13a (R-010.6): a stamp of the file’s committed state, read without
the key and without a lock: page 0’s seal, with the file’s identity,
length and modification time (so a write the seal doesn’t cover yet,
like a WAL a crash left, changes it too). Two equal stamps mean
nothing was committed between them. None when it can’t be read (a
page 0 torn by a write in progress, say): then read the file.
Source§impl Mnemo
impl Mnemo
Sourcepub fn session(&mut self, agent_id: impl Into<String>) -> Session<'_>
pub fn session(&mut self, agent_id: impl Into<String>) -> Session<'_>
Begin a conversation Session for agent_id.
The session borrows the database for its lifetime, records turns as working memory, and consolidates them into episodic memory when closed.
Sourcepub fn snapshots(&self) -> Vec<SnapshotInfo>
pub fn snapshots(&self) -> Vec<SnapshotInfo>
Every committed transaction, oldest first — the restore points
available to Mnemo::restore_to and Mnemo::restore_to_time.
Each flush appends one snapshot. Because the storage engine is
append-only, the pages a past flush wrote are still on disk, so any
listed snapshot can be reinstated exactly. The history reaches back to
the last Mnemo::compact_file, which reclaims space by collapsing
it.
Sourcepub fn restore_to(&mut self, txn_id: u64) -> Result<SnapshotInfo>
pub fn restore_to(&mut self, txn_id: u64) -> Result<SnapshotInfo>
Restore the database to the snapshot produced by transaction txn_id.
The restore is itself a new committed transaction (and a new snapshot), so it is crash-safe and reversible — restoring forward to a later snapshot afterwards works just as well.
Sourcepub fn restore_to_time(&mut self, unix_secs: i64) -> Result<SnapshotInfo>
pub fn restore_to_time(&mut self, unix_secs: i64) -> Result<SnapshotInfo>
Restore the database to the latest snapshot committed at or before
unix_secs. Returns MnemoError::NotFound if no snapshot is that
old. Like Mnemo::restore_to, the restore is a new transaction.
Source§impl Mnemo
impl Mnemo
Sourcepub fn ingest_thread(
&mut self,
thread_id: &str,
turns: &[ThreadTurn],
) -> Result<IngestReport>
pub fn ingest_thread( &mut self, thread_id: &str, turns: &[ThreadTurn], ) -> Result<IngestReport>
Ingest a batch of turns into the archive layer of thread_id.
Each ThreadTurn becomes one or more Episodic records
tagged with the usual thread-archive reserved-metadata set
(_mnemo.kind = "turn", _mnemo.thread, _mnemo.turn_id,
_mnemo.seq, _mnemo.role). The ingest path is
idempotent per turn_id: a turn whose turn_id already
appears on a record in this thread is skipped, so re-running
ingest_thread with an extended transcript appends only
what’s new.
Chunking. A non-tool turn whose UTF-8 content exceeds
THREAD_TURN_CHUNK_BYTES (8 KB) is split into chunks at
char boundaries, each stored as its own record with
_mnemo.part = 0, 1, … under the same turn_id.
Truncation. A role = "tool" turn whose content exceeds
THREAD_TOOL_RESULT_TRUNCATE_BYTES (16 KB) is stored
truncated — the first 16 KB of UTF-8 goes into the record,
and _mnemo.sha256 + _mnemo.length capture the original
hash and byte length so the full content can be recovered
(or verified) out-of-band.
Embedding. An embedder must be registered
(Mnemo::set_embedder); the content strings (one per
resulting chunk / truncated record) are batched into a single
embed() call. A turn of nothing but transcript markers
(MNEMO_META_MARKERS_ONLY, v0.16.1) isn’t embedded: it’s kept
with the sentinel vector, and recall never returns it.
Call self.flush() after a successful ingest to persist.
Sourcepub fn ingest_thread_new_turns(
&mut self,
thread_id: &str,
turns: &[ThreadTurn],
) -> Result<usize>
pub fn ingest_thread_new_turns( &mut self, thread_id: &str, turns: &[ThreadTurn], ) -> Result<usize>
v0.16.1: how many of turns aren’t in thread_id yet, and would be
written by an ingest. Unlike Mnemo::ingest_thread_texts, it
counts a marker-only turn, which has no text to embed. Writes
nothing.
Sourcepub fn ingest_thread_texts(
&mut self,
thread_id: &str,
turns: &[ThreadTurn],
) -> Result<Vec<String>>
pub fn ingest_thread_texts( &mut self, thread_id: &str, turns: &[ThreadTurn], ) -> Result<Vec<String>>
MOBILE-1a: the texts Mnemo::ingest_thread would embed for
turns, in order (one per new chunk or truncated record; turns
already in the thread are skipped). With
Mnemo::ingest_thread_with_vectors it splits an ingest in two, so
a caller can run its embedder between the calls without holding
anything the handle needs, as the UniFFI binding does. Empty when
nothing is new. Writes nothing.
Sourcepub fn ingest_thread_with_vectors(
&mut self,
thread_id: &str,
turns: &[ThreadTurn],
vectors: &[Vec<f32>],
) -> Result<IngestReport>
pub fn ingest_thread_with_vectors( &mut self, thread_id: &str, turns: &[ThreadTurn], vectors: &[Vec<f32>], ) -> Result<IngestReport>
MOBILE-1a: Mnemo::ingest_thread with caller-supplied vectors,
one per text Mnemo::ingest_thread_texts returned for the same
thread_id and turns, in the same order. No embedder is needed.
The ingest is planned again here; if the thread changed in between
(so the count no longer matches) it returns
MnemoError::Invalid and writes nothing, and the caller can ask
for the texts again.
Sourcepub fn thread_export(&mut self, thread_id: &str) -> Result<Vec<Memory>>
pub fn thread_export(&mut self, thread_id: &str) -> Result<Vec<Memory>>
Export the archive layer for thread_id in _mnemo.seq
order. Each entry is the Memory as stored; chunks of a
multi-part turn come out in _mnemo.part order within their
_mnemo.seq. The record .content is the text that was
stored (post-chunking / post-truncation); callers that need
the pre-truncation original should round-trip via
_mnemo.sha256 + _mnemo.length.
Sourcepub fn thread_export_turns(
&mut self,
thread_id: &str,
) -> Result<Vec<ExportedTurn>>
pub fn thread_export_turns( &mut self, thread_id: &str, ) -> Result<Vec<ExportedTurn>>
Export a thread’s archive in the ingest shape (Phase 12.7d):
one ExportedTurn per source turn, in _mnemo.seq order, with
a chunked turn’s parts joined back into one content. Passing
the result back to Mnemo::ingest_thread for the same thread
skips every turn; for a new thread it re-creates the same records.
This is what Python db.thread_export, MCP thread_export and
mnemo thread export return; Mnemo::thread_export still
returns the raw records.
Sourcepub fn thread_forget(&mut self, thread_id: &str) -> Result<usize>
pub fn thread_forget(&mut self, thread_id: &str) -> Result<usize>
Soft-delete every record in the archive layer of thread_id.
Returns the number of records marked deleted. Permanent
removal still requires a subsequent compact_file, same as
any Mnemo::delete.
Does not touch _mnemo.kind = "essence" records or other
non-turn metadata the thread may carry — only _mnemo.kind = "turn" records matching the thread id.