Skip to main content

mnemo_engine/store/
crud.rs

1//! Public CRUD (remember, get, delete, embedder), and the handle caches (key slots, superseded set, thread layers).
2
3use super::*;
4
5/// R-004.2: where the thread layers and the onboarding briefing live,
6/// built by the handle's one lazy scan (`ensure_key_caches`, together with
7/// the 12.1 key caches) and then kept current by `put` and `delete`. It
8/// lets `about`, `essence`, `ingest_thread`, `thread_export` and
9/// thread-pinned recall read just their own records instead of decrypting
10/// the whole file each time.
11#[derive(Debug, Default)]
12pub(super) struct LayerCache {
13    /// Live essence item ids.
14    pub(super) essence: std::collections::HashSet<u128>,
15    /// Live ids tagged `metadata.area = "onboarding"` (superseded versions
16    /// included; `about` drops those when it reads them).
17    pub(super) onboarding: std::collections::HashSet<u128>,
18    /// Per `_mnemo.thread`: its records and archive state.
19    pub(super) threads: std::collections::HashMap<String, ThreadCache>,
20    /// Thread → (the thread it continues, the link record's id).
21    pub(super) links: std::collections::HashMap<String, (String, u128)>,
22    /// FMT-9e: on v9, thread-turn records the lazy scan didn't decode,
23    /// by their row's `thread_hash`. A thread's bucket is decoded into
24    /// `threads` the first time that thread is used
25    /// ([`Mnemo::warm_thread`]), so a cold handle never decodes (or
26    /// decompresses) the turns of threads it doesn't touch.
27    pub(super) cold_turns: std::collections::HashMap<u32, Vec<u128>>,
28}
29
30/// One thread's records (turns, essence items, link), the turn ids already
31/// archived (with how many records each has: long turns are chunked), and
32/// the highest `_mnemo.seq` seen.
33#[derive(Debug, Default)]
34pub(super) struct ThreadCache {
35    pub(super) records: std::collections::HashSet<u128>,
36    pub(super) turns: std::collections::HashMap<String, u32>,
37    pub(super) max_seq: Option<u64>,
38}
39
40pub(super) fn meta_str<'a>(m: &'a Memory, key: &str) -> Option<&'a str> {
41    m.metadata.get(key).and_then(|v| v.as_str())
42}
43
44pub(super) fn is_onboarding(m: &Memory) -> bool {
45    meta_str(m, "area").is_some_and(|s| s.eq_ignore_ascii_case("onboarding"))
46}
47
48impl LayerCache {
49    pub(super) fn add(&mut self, m: &Memory) {
50        let id = m.id.0;
51        let kind = meta_str(m, MNEMO_META_KIND);
52        if kind == Some(MNEMO_META_KIND_ESSENCE) {
53            self.essence.insert(id);
54        }
55        if is_onboarding(m) {
56            self.onboarding.insert(id);
57        }
58        let Some(thread) = meta_str(m, MNEMO_META_THREAD) else {
59            return;
60        };
61        let tc = self.threads.entry(thread.to_string()).or_default();
62        tc.records.insert(id);
63        if kind == Some(MNEMO_META_KIND_TURN) {
64            if let Some(turn_id) = meta_str(m, MNEMO_META_TURN_ID) {
65                *tc.turns.entry(turn_id.to_string()).or_insert(0) += 1;
66            }
67            if let Some(seq) = m.metadata.get(MNEMO_META_SEQ).and_then(|v| v.as_u64()) {
68                tc.max_seq = Some(tc.max_seq.map_or(seq, |s| s.max(seq)));
69            }
70        }
71        if kind == Some(MNEMO_META_KIND_THREAD_LINK) {
72            if let Some(from) = meta_str(m, MNEMO_META_CONTINUES) {
73                self.links
74                    .entry(thread.to_string())
75                    .or_insert_with(|| (from.to_string(), id));
76            }
77        }
78    }
79
80    /// Undo [`LayerCache::add`] for the stored version of a record that is
81    /// being overwritten or deleted. A thread with no records left is
82    /// dropped, so a forgotten thread's `_mnemo.seq` restarts at 0. Partial
83    /// deletes keep the old maximum (sequence gaps are harmless).
84    pub(super) fn remove(&mut self, m: &Memory) {
85        let id = m.id.0;
86        self.essence.remove(&id);
87        self.onboarding.remove(&id);
88        let Some(thread) = meta_str(m, MNEMO_META_THREAD) else {
89            return;
90        };
91        if self.links.get(thread).is_some_and(|(_, link)| *link == id) {
92            self.links.remove(thread);
93        }
94        let Some(tc) = self.threads.get_mut(thread) else {
95            return;
96        };
97        tc.records.remove(&id);
98        if meta_str(m, MNEMO_META_KIND) == Some(MNEMO_META_KIND_TURN) {
99            if let Some(turn_id) = meta_str(m, MNEMO_META_TURN_ID) {
100                if let Some(n) = tc.turns.get_mut(turn_id) {
101                    *n -= 1;
102                    if *n == 0 {
103                        tc.turns.remove(turn_id);
104                    }
105                }
106            }
107        }
108        if tc.records.is_empty() {
109            self.threads.remove(thread);
110        }
111    }
112}
113
114impl Mnemo {
115    /// Register a text embedder for this handle. Enables
116    /// [`Mnemo::remember_text`] and the text-side `RecallRequest`
117    /// convenience path. Does two checks before storing the embedder:
118    ///
119    /// 1. **Dimension check.** The embedder's `identity().dimensions`
120    ///    must equal [`Mnemo::dimensions`] (the width this database
121    ///    was created with). Mismatch returns
122    ///    [`MnemoError::DimensionMismatch`].
123    /// 2. **Identity check (EMBED-ID-1).** Every file records the
124    ///    identity (name, dimensions, normalize) of the first embedder
125    ///    attached to it, in a reserved, encrypted record that isn't a
126    ///    memory: `len`, `count`, `stats`, recall, `about` and `get`
127    ///    never see it, and compaction, the rekeyed exports and the
128    ///    passphrase import carry it. After that, any other identity,
129    ///    even at the same width (another model, or another revision of
130    ///    the same one), returns [`MnemoError::EmbedderMismatch`]: a
131    ///    store is bound to the model that first wrote to it, so a new
132    ///    model needs a new store.
133    ///
134    /// **Files with a manifest** (`mnemo init`, `seed.json`) also carry
135    /// the identity on the manifest at `metadata.embedder = { name,
136    /// dimensions, normalize }` (the legacy flat `embedder_name` /
137    /// `embedder_dimensions` / `embedder_normalize` keys are read as an
138    /// alias). The first registration upserts it there too, as before.
139    /// If the manifest and the record disagree, this returns
140    /// [`MnemoError::Invalid`] naming both.
141    ///
142    /// **Files from before EMBED-ID-1** have no record: the first
143    /// embedder attached after the upgrade is recorded. The check
144    /// protects from then on; it can't tell which model made the older
145    /// vectors.
146    ///
147    /// **Read-only handles.** `set_embedder` on an `open_read_only`
148    /// handle performs both checks and adopts the embedder in memory;
149    /// it never writes. Readers (CLI `--text`, agent-side `recall_text`)
150    /// can therefore use the text path next to a writer that holds
151    /// the exclusive lock.
152    ///
153    /// On every failure path the handle's embedder slot is left
154    /// unchanged. On success the embedder is wrapped in an `Arc<dyn
155    /// Embedder>` and consulted by every text-side call made through
156    /// this handle. The slot is per-handle and not persisted — a
157    /// fresh open must re-register (same identity, so the check
158    /// round-trips cleanly).
159    pub fn set_embedder<E: Embedder + 'static>(&mut self, embedder: E) -> Result<()> {
160        let identity = embedder.identity();
161        if identity.dimensions != self.dimensions {
162            return Err(MnemoError::DimensionMismatch {
163                expected: self.dimensions,
164                got: identity.dimensions,
165            });
166        }
167
168        // The manifest's identity, if the file has one, and the first
169        // onboarding memory without one (the upsert target).
170        let onboarding = self.about()?;
171        let mut on_manifest: Option<embed::EmbedderIdentity> = None;
172        let mut upsert_target: Option<usize> = None;
173        for (i, m) in onboarding.iter().enumerate() {
174            if let Some(saw) = embed::read_identity_from_metadata(&m.metadata) {
175                on_manifest = Some(saw);
176                break;
177            }
178            if upsert_target.is_none() {
179                upsert_target = Some(i);
180            }
181        }
182        let on_record = self.recorded_identity()?;
183
184        if let (Some(manifest), Some(record)) = (&on_manifest, &on_record) {
185            if manifest != record {
186                return Err(embed::identity_conflict_err(manifest, record));
187            }
188        }
189        if let Some(stored) = on_record.as_ref().or(on_manifest.as_ref()) {
190            if *stored != identity {
191                return Err(embed::identity_mismatch_err(stored, &identity));
192            }
193        }
194
195        // Record what's missing. A read-only handle writes nothing, but
196        // still adopts the embedder in memory.
197        if !self.read_only {
198            let mut wrote = false;
199            if on_manifest.is_none() {
200                if let Some(idx) = upsert_target {
201                    let mut m = onboarding[idx].clone();
202                    embed::write_identity_into_metadata(&mut m.metadata, &identity);
203                    // Reuse the memory's existing id so this is an in-place
204                    // update of the scaffold manifest, not a new entry.
205                    self.put(m)?;
206                    wrote = true;
207                }
208            }
209            if on_record.is_none() {
210                self.record_identity(&identity)?;
211                wrote = true;
212            }
213            if wrote {
214                self.flush()?;
215            }
216        }
217
218        self.embedder = Some(std::sync::Arc::new(embedder));
219        Ok(())
220    }
221
222    /// The embedder identity this file records (EMBED-ID-1), or `None`
223    /// before the first `set_embedder` on a read-write handle. Reads the
224    /// reserved record without touching any counter.
225    pub fn embedder_identity(&mut self) -> Result<Option<embed::EmbedderIdentity>> {
226        self.recorded_identity()
227    }
228
229    /// Borrow the currently-registered embedder, if any. Returns
230    /// `None` when no embedder has been set via
231    /// [`Mnemo::set_embedder`]. Bindings use this to drive their own
232    /// text-side convenience methods without duplicating the identity
233    /// check.
234    pub fn embedder(&self) -> Option<&dyn Embedder> {
235        self.embedder.as_deref()
236    }
237
238    /// Shared handle to the registered embedder, cloned so the caller
239    /// can drop the borrow on this `Mnemo` before invoking `embed()`.
240    /// FIX-1 / PY-1 (R-001.11): the Python binding needs this so an
241    /// embedder callback that re-enters `Mnemo` (e.g. a Python
242    /// embedder that calls `db.dimensions()` or `db.cache_get(...)`)
243    /// doesn't hit PyO3's "Already borrowed" — we clone the Arc under
244    /// a short `&self` borrow, release that borrow, then invoke
245    /// `embed()` with no `&mut Mnemo` held.
246    pub fn embedder_arc(&self) -> Option<std::sync::Arc<dyn Embedder>> {
247        self.embedder.clone()
248    }
249
250    /// Embed `content` with the registered embedder and `remember` the
251    /// result. Returns the new memory's ULID. Convenience path for
252    /// callers who have a string, want it stored, and don't need any
253    /// of the per-memory options [`Memory`] exposes (agent, importance,
254    /// metadata, ttl, scope) — build a [`Memory`] by hand and call
255    /// [`Mnemo::remember`] for those.
256    ///
257    /// Fails with [`MnemoError::Invalid`] if no embedder has been
258    /// registered on this handle (call [`Mnemo::set_embedder`] first);
259    /// with [`MnemoError::DimensionMismatch`] if the embedder returned
260    /// the wrong width for this database.
261    pub fn remember_text(&mut self, content: &str, memory_type: MemoryType) -> Result<Ulid> {
262        if self.read_only {
263            return Err(MnemoError::ReadOnly);
264        }
265        let embedder = self.embedder.as_ref().ok_or_else(|| {
266            MnemoError::Invalid(
267                "no embedder registered on this handle; call set_embedder first".into(),
268            )
269        })?;
270        let mut vectors = embedder.embed(&[content])?;
271        let vector = vectors.pop().ok_or_else(|| {
272            MnemoError::Invalid("embedder returned no vector for the input text".into())
273        })?;
274        if vector.len() != self.dimensions {
275            return Err(MnemoError::DimensionMismatch {
276                expected: self.dimensions,
277                got: vector.len(),
278            });
279        }
280        let memory = Memory::new(content.to_string(), memory_type, vector);
281        self.remember(memory)
282    }
283
284    /// Store a memory. Returns its ULID. If the memory's ID is nil a fresh
285    /// one is assigned; an existing ID overwrites in place.
286    ///
287    /// Metadata keys starting with `_mnemo.` are the engine's (supersession,
288    /// keys, threads, kinds): a new memory carrying one is refused with
289    /// [`MnemoError::Invalid`]. An in-place overwrite may carry the stored
290    /// record's own `_mnemo.*` keys through unchanged (the usual `get`,
291    /// change a field, `remember`), but can't add, change or drop one.
292    pub fn remember(&mut self, memory: Memory) -> Result<Ulid> {
293        if self.read_only {
294            return Err(MnemoError::ReadOnly);
295        }
296        self.check_caller_metadata(&memory)?;
297        self.put(memory)
298    }
299
300    /// RB-001.24: the caller's metadata may not set engine state. For a
301    /// memory with a nil or unknown id, any `_mnemo.*` key is refused; for
302    /// an overwrite in place, the `_mnemo.*` keys must equal the stored
303    /// record's.
304    pub(super) fn check_caller_metadata(&mut self, memory: &Memory) -> Result<()> {
305        let reserved: Vec<(&String, &Value)> = memory
306            .metadata
307            .iter()
308            .filter(|(k, _)| k.starts_with(crate::memory::MNEMO_META_NS))
309            .collect();
310        if reserved.is_empty() {
311            return Ok(());
312        }
313        let stored = if memory.id.is_nil() {
314            None
315        } else {
316            match self.index.get(memory.id.0, &self.catalog) {
317                Some(idx) if !self.catalog[idx].deleted => {
318                    let entry = self.catalog[idx].clone();
319                    Some(self.read_memory(&entry)?)
320                }
321                _ => None,
322            }
323        };
324        if let Some(old) = stored {
325            let old_reserved: Vec<(&String, &Value)> = old
326                .metadata
327                .iter()
328                .filter(|(k, _)| k.starts_with(crate::memory::MNEMO_META_NS))
329                .collect();
330            if old_reserved == reserved {
331                return Ok(());
332            }
333        }
334        Err(reserved_key_error(reserved[0].0))
335    }
336
337    /// Fetch a memory by ID.
338    pub fn get(&mut self, id: &Ulid) -> Result<Memory> {
339        let idx = self
340            .index
341            .get(id.0, &self.catalog)
342            .ok_or_else(|| MnemoError::NotFound(id.to_string()))?;
343        let entry = self.catalog[idx].clone();
344        if entry.deleted {
345            return Err(MnemoError::NotFound(id.to_string()));
346        }
347        self.read_memory(&entry)
348    }
349
350    /// Soft-delete a memory (tombstoned; space reclaimed by `compact`).
351    pub fn delete(&mut self, id: &Ulid) -> Result<()> {
352        if self.read_only {
353            return Err(MnemoError::ReadOnly);
354        }
355        let idx = self
356            .index
357            .get(id.0, &self.catalog)
358            .ok_or_else(|| MnemoError::NotFound(id.to_string()))?;
359        // R-004.2 / 12.1: with the handle caches built, read the record
360        // being deleted (one decrypt) so the key slot, superseded set and
361        // thread layers drop exactly what it contributed.
362        let entry = self.catalog[idx].clone();
363        if self.layers.is_some() && !entry.deleted {
364            let old = self.read_memory(&entry)?;
365            self.note_removed(&old)?;
366        }
367        if !self.catalog[idx].deleted {
368            self.catalog[idx].deleted = true;
369            self.dirty_catalog = true;
370            self.touch(idx);
371            // FMT-9f: drop its document from the stats in place.
372            if let (Some(stats), Some(r)) = (self.bm25.stats.as_mut(), entry.v9) {
373                if r.doc != 0 {
374                    stats.remove(r.doc);
375                }
376            }
377            if self.is_v9() {
378                self.kill_record(idx, &entry);
379                self.kill_vector(idx, &entry);
380            } else {
381                self.release_pages(entry.start_page, entry.page_count as u64);
382            }
383        }
384        if let Some(ann) = &mut self.ann {
385            if ann.contains(id.0) {
386                ann.remove(id.0);
387                self.dirty_index = true;
388                self.index_persist.changes += 1;
389            }
390        }
391        // FIX-1 R-001.8 part 2: we can't tell whether this delete
392        // removed the last memory of its agent without a decrypt
393        // (the catalog entry doesn't carry `agent_id` in format v8),
394        // so just invalidate the lazy set. The next `stats()` call
395        // rebuilds from live memories.
396        self.agent_set = None;
397        // Phase 12.1: delete of a keyed record removes it from the slot,
398        // and delete of a superseded record frees a `history` entry. When
399        // the caches are built, `note_removed` above did that exactly;
400        // otherwise they're built from scratch on first use anyway.
401        Ok(())
402    }
403
404    /// Keep the handle caches (12.1 key slots, superseded set, R-004.2
405    /// layers) current after `put` writes `m`. No-op until they're built.
406    /// FMT-9e: a cold thread is warmed first, so its layer entry is whole.
407    pub(super) fn note_added(&mut self, m: &Memory) -> Result<()> {
408        if let Some(thread) = meta_str(m, MNEMO_META_THREAD) {
409            self.warm_thread(thread)?;
410        }
411        let id = m.id.0;
412        if let (Some(keys), Some(sup)) = (self.key_index.as_mut(), self.superseded.as_mut()) {
413            if m.metadata.contains_key(MNEMO_META_SUPERSEDED_BY) {
414                sup.insert(id);
415            } else if let Some(Value::String(k)) = m.metadata.get(MNEMO_META_KEY) {
416                keys.insert(Self::key_slot_for(m, k), id);
417            }
418        }
419        if let Some(layers) = self.layers.as_mut() {
420            layers.add(m);
421        }
422        Ok(())
423    }
424
425    /// Undo [`Mnemo::note_added`] for the stored version of a record that's
426    /// about to be overwritten or deleted.
427    pub(super) fn note_removed(&mut self, m: &Memory) -> Result<()> {
428        if let Some(thread) = meta_str(m, MNEMO_META_THREAD) {
429            self.warm_thread(thread)?;
430        }
431        let id = m.id.0;
432        if let (Some(keys), Some(sup)) = (self.key_index.as_mut(), self.superseded.as_mut()) {
433            sup.remove(&id);
434            if let Some(Value::String(k)) = m.metadata.get(MNEMO_META_KEY) {
435                let slot = Self::key_slot_for(m, k);
436                if keys.get(&slot) == Some(&id) {
437                    keys.remove(&slot);
438                }
439            }
440        }
441        if let Some(layers) = self.layers.as_mut() {
442            layers.remove(m);
443        }
444        Ok(())
445    }
446
447    /// FMT-9e: decode `thread`'s cold turn records (see
448    /// [`LayerCache::cold_turns`]) into the layer cache. Every record in
449    /// the thread's hash bucket is decoded and filed under its own thread,
450    /// so a hash collision just warms both threads. A no-op when the
451    /// caches aren't built or the bucket is already warm.
452    pub(super) fn warm_thread(&mut self, thread: &str) -> Result<()> {
453        self.warm_thread_decoded(thread).map(|_| ())
454    }
455
456    /// [`Mnemo::warm_thread`], returning the records it decoded (without
457    /// vectors), so a caller about to read the thread decodes each once.
458    pub(super) fn warm_thread_decoded(
459        &mut self,
460        thread: &str,
461    ) -> Result<std::collections::HashMap<u128, Memory>> {
462        let mut decoded = std::collections::HashMap::new();
463        let h = fnv1a32(&[thread.as_bytes()]);
464        let Some(ids) = self.layers.as_mut().and_then(|l| l.cold_turns.remove(&h)) else {
465            return Ok(decoded);
466        };
467        for e in self.live_entries(ids) {
468            let m = self.read_memory_meta(&e)?;
469            if let Some(layers) = self.layers.as_mut() {
470                layers.add(&m);
471            }
472            decoded.insert(e.id, m);
473        }
474        Ok(decoded)
475    }
476
477    /// Decode a record's memory without its vector or live access stats:
478    /// what the handle caches need (metadata, scope, agent), without the
479    /// v9 vector-column read [`Mnemo::read_memory`] adds.
480    pub(super) fn read_memory_meta(&mut self, e: &CatalogEntry) -> Result<Memory> {
481        let bytes = self.read_record(e)?;
482        self.decode_memory(&bytes)
483    }
484
485    /// The live catalog entries for `ids` (ids that are gone are skipped).
486    pub(super) fn live_entries(&self, ids: impl IntoIterator<Item = u128>) -> Vec<CatalogEntry> {
487        ids.into_iter()
488            .filter_map(|id| {
489                self.index
490                    .get(id, &self.catalog)
491                    .map(|i| self.catalog[i].clone())
492            })
493            .filter(|e| !e.deleted)
494            .collect()
495    }
496
497    /// Catalog entries of the essence items, from the handle caches.
498    pub(super) fn essence_entries(&mut self) -> Result<Vec<CatalogEntry>> {
499        self.ensure_key_caches()?;
500        let ids: Vec<u128> = self
501            .layers
502            .as_ref()
503            .map(|l| l.essence.iter().copied().collect())
504            .unwrap_or_default();
505        Ok(self.live_entries(ids))
506    }
507
508    /// Catalog entries of every record filed under `thread`, from the
509    /// handle caches.
510    pub(super) fn thread_entries(&mut self, thread: &str) -> Result<Vec<CatalogEntry>> {
511        Ok(self.thread_entries_decoded(thread)?.0)
512    }
513
514    /// [`Mnemo::thread_entries`], plus the records that warming a cold
515    /// thread just decoded (see [`Mnemo::warm_thread_decoded`]).
516    pub(super) fn thread_entries_decoded(
517        &mut self,
518        thread: &str,
519    ) -> Result<(Vec<CatalogEntry>, std::collections::HashMap<u128, Memory>)> {
520        self.ensure_key_caches()?;
521        let decoded = self.warm_thread_decoded(thread)?;
522        let ids: Vec<u128> = self
523            .layers
524            .as_ref()
525            .and_then(|l| l.threads.get(thread))
526            .map(|tc| tc.records.iter().copied().collect())
527            .unwrap_or_default();
528        Ok((self.live_entries(ids), decoded))
529    }
530
531    // --- Phase 12.1: edit in place + keyed supersession -----------------
532
533    /// Scope-aware key-slot identifier for `memory` and a caller key.
534    ///
535    /// * [`Scope::Private`] → owned by the memory's `agent_id`.
536    /// * [`Scope::Shared`]  → one slot across the whole file.
537    pub(super) fn key_slot_for(memory: &Memory, key: &str) -> crate::store::KeySlot {
538        let scope_owner = match memory.scope {
539            Scope::Private => Some(memory.agent_id.clone()),
540            Scope::Shared => None,
541        };
542        crate::store::KeySlot {
543            scope_owner,
544            key: key.to_string(),
545        }
546    }
547
548    /// The handle's one lazy scan: builds the 12.1 `key_index` +
549    /// `superseded` caches and the R-004.2 layer cache (essence ids,
550    /// onboarding ids, threads, links) from live records, and prunes
551    /// non-fact ids from a loaded ANN index (files written before v0.10.0
552    /// indexed every kind). Decrypts every live record once per handle;
553    /// `put` and `delete` keep the result current after that.
554    pub(super) fn ensure_key_caches(&mut self) -> Result<()> {
555        if self.key_index.is_some() && self.superseded.is_some() && self.layers.is_some() {
556            return Ok(());
557        }
558        let entries: Vec<CatalogEntry> = self
559            .catalog
560            .iter()
561            .filter(|e| !e.deleted)
562            .cloned()
563            .collect();
564        let mut keys: std::collections::HashMap<crate::store::KeySlot, u128> =
565            std::collections::HashMap::new();
566        let mut superseded: std::collections::HashSet<u128> = std::collections::HashSet::new();
567        let mut layers = LayerCache::default();
568        let mut non_facts: Vec<u128> = Vec::new();
569        for e in &entries {
570            // FMT-9e: a v9 turn row with no key slot and no supersession
571            // contributes only to its thread's layer entry, so it's left
572            // undecoded in the thread's cold bucket (most of a
573            // thread-heavy file). Its row says it isn't a fact.
574            if let Some(r) = e.v9 {
575                if r.kind == ROW_KIND_TURN
576                    && r.thread_hash != 0
577                    && r.key_hash == 0
578                    && r.flags & ROW_SUPERSEDED == 0
579                {
580                    layers
581                        .cold_turns
582                        .entry(r.thread_hash)
583                        .or_default()
584                        .push(e.id);
585                    non_facts.push(e.id);
586                    continue;
587                }
588            }
589            let m = self.read_memory_meta(e)?;
590            layers.add(&m);
591            if !is_ann_kind(&m) {
592                non_facts.push(e.id);
593            }
594            if m.metadata.get(MNEMO_META_SUPERSEDED_BY).is_some() {
595                superseded.insert(e.id);
596                continue;
597            }
598            if let Some(Value::String(k)) = m.metadata.get(MNEMO_META_KEY) {
599                let slot = Self::key_slot_for(&m, k);
600                // Catalog order is insertion order; a later live record
601                // with the same slot would only exist if a prior build
602                // of this code allowed it. Keep the later id (newer
603                // ULID), in case of a tie.
604                keys.entry(slot)
605                    .and_modify(|cur| {
606                        if *cur < e.id {
607                            *cur = e.id;
608                        }
609                    })
610                    .or_insert(e.id);
611            }
612        }
613        self.key_index = Some(keys);
614        self.superseded = Some(superseded);
615        self.layers = Some(layers);
616        if let Some(ann) = &mut self.ann {
617            let mut pruned = 0usize;
618            for id in non_facts {
619                if ann.contains(id) {
620                    ann.remove(id);
621                    pruned += 1;
622                }
623            }
624            if pruned > 0 {
625                self.dirty_index = true;
626                self.index_persist.changes += pruned;
627            }
628        }
629        Ok(())
630    }
631}
632
633/// RB-001.24: the error for caller metadata that sets an engine key.
634pub(super) fn reserved_key_error(key: &str) -> MnemoError {
635    MnemoError::Invalid(format!(
636        "metadata key \"{key}\" is reserved: keys starting with \"{}\" are set by the engine",
637        crate::memory::MNEMO_META_NS
638    ))
639}