Skip to main content

mnemo_engine/store/
keyed.rs

1//! Phase 12.1: keyed upserts, edit in place (update), and supersession history.
2
3use super::*;
4
5impl Mnemo {
6    /// Stage-identical check for a 12.1 keyed no-op. The incoming write
7    /// is byte-equal to the live record iff every user-visible field
8    /// (content, type, importance, vector, user metadata) matches. The
9    /// `_mnemo.*` reserved keys on the live record are **ignored** for
10    /// this comparison — a repeat of an identical write re-issued by an
11    /// extractor must be a NOOP even if the live record already carries
12    /// supersession bookkeeping from a prior op.
13    ///
14    /// `rounded` says the live vector was read from a v9 file's fp16 column
15    /// (FMT-9b), so it's compared with the incoming vector after the same
16    /// rounding: a real embedder's value never survives it exactly, and
17    /// before v0.16 every such re-write added a version.
18    pub(super) fn is_identical_keyed_write(
19        incoming: &Memory,
20        live: &Memory,
21        rounded: bool,
22    ) -> bool {
23        if incoming.content != live.content {
24            return false;
25        }
26        if incoming.memory_type != live.memory_type {
27            return false;
28        }
29        if (incoming.importance - live.importance).abs() > f32::EPSILON {
30            return false;
31        }
32        let same_vector = if rounded {
33            crate::veccol::dequantize(&crate::veccol::quantize(&incoming.vector).0) == live.vector
34        } else {
35            incoming.vector == live.vector
36        };
37        if !same_vector {
38            return false;
39        }
40        // Strip `_mnemo.*` from both sides before comparing user metadata,
41        // all but the caller's own (13a: visibility and freshness count).
42        let strip = |m: &Map<String, Value>| -> Map<String, Value> {
43            m.iter()
44                .filter(|(k, _)| !k.starts_with(crate::memory::MNEMO_META_NS) || is_caller_key(k))
45                .map(|(k, v)| (k.clone(), v.clone()))
46                .collect()
47        };
48        strip(&incoming.metadata) == strip(&live.metadata)
49    }
50
51    /// 13a (AGENT-DEFAULT): the agent the manifest names for a write that
52    /// names none (`_mnemo.default_agent`), if it names one. The CLI and the
53    /// MCP server use it in place of `default`; the engine's own default is
54    /// unchanged.
55    pub fn default_agent(&mut self) -> Result<Option<String>> {
56        Ok(self
57            .about_in(crate::memory::VisibilitySet::ALL)?
58            .into_iter()
59            .find(is_manifest)
60            .and_then(|m| {
61                m.metadata
62                    .get(MNEMO_META_DEFAULT_AGENT)
63                    .and_then(Value::as_str)
64                    .map(str::to_string)
65            }))
66    }
67
68    /// 13a (AGENT-DEFAULT): set (or with `None`, clear) the manifest's
69    /// `_mnemo.default_agent`, in place: the manifest keeps its id, content
70    /// and vector. `agent` must be 1 to 64 of `[A-Za-z0-9._-]`. Returns
71    /// `Unchanged` when it already says so. A brain with no manifest is
72    /// refused.
73    pub fn set_default_agent(&mut self, agent: Option<&str>) -> Result<WriteOutcome> {
74        if self.read_only {
75            return Err(MnemoError::ReadOnly);
76        }
77        if let Some(a) = agent {
78            if !crate::memory::valid_agent_id(a) {
79                return Err(MnemoError::Invalid(format!(
80                    "{a:?} isn't an agent id: 1 to 64 of letters, digits, '.', '_' and '-'"
81                )));
82            }
83        }
84        let Some(mut m) = self
85            .about_in(crate::memory::VisibilitySet::ALL)?
86            .into_iter()
87            .find(is_manifest)
88        else {
89            return Err(MnemoError::Invalid(
90                "this brain has no manifest to record a default agent on".into(),
91            ));
92        };
93        let want = agent.map(|a| Value::String(a.to_string()));
94        if m.metadata.get(MNEMO_META_DEFAULT_AGENT) == want.as_ref() {
95            return Ok(WriteOutcome::Unchanged);
96        }
97        match want {
98            Some(v) => m.metadata.insert(MNEMO_META_DEFAULT_AGENT.into(), v),
99            None => m.metadata.remove(MNEMO_META_DEFAULT_AGENT),
100        };
101        m.metadata.insert(
102            crate::memory::MNEMO_META_UPDATED_AT.into(),
103            Value::Number(memory::now_secs().into()),
104        );
105        self.put(m)?;
106        Ok(WriteOutcome::Updated)
107    }
108
109    /// Store a memory under a keyed upsert slot. Returns the live record's
110    /// id and a [`WriteOutcome`] saying whether this write created a new
111    /// slot (`Added`), replaced a prior record (`Superseded`), or matched
112    /// the existing live record byte-for-byte (`Unchanged`, no file write).
113    ///
114    /// The slot is identified by `(scope_owner, key)`:
115    /// * `Scope::Private` memories share a slot per `(agent_id, key)`.
116    /// * `Scope::Shared` memories share one slot per `key` across the file.
117    ///
118    /// On supersession the prior record is **not** deleted — it remains
119    /// retrievable through [`Mnemo::history`] — but it is excluded from
120    /// default [`Mnemo::recall`] and [`Mnemo::about`]. A caller that wants
121    /// the full lineage of a key walks `history(key)`.
122    ///
123    /// This is the atomic 12.1 "supersede-or-noop" write path. Plain
124    /// [`Mnemo::remember`] without a key is unchanged.
125    pub fn remember_keyed(
126        &mut self,
127        mut memory: Memory,
128        key: &str,
129    ) -> Result<(Ulid, WriteOutcome)> {
130        if self.read_only {
131            return Err(MnemoError::ReadOnly);
132        }
133        if key.is_empty() {
134            return Err(MnemoError::Invalid(
135                "remember_keyed: 'key' must not be empty".into(),
136            ));
137        }
138        // RB-001.24: a keyed write is always a new record, so no caller
139        // `_mnemo.*` key is accepted (the engine sets `_mnemo.key` below).
140        // 13a: visibility and freshness are the caller's (checked); no other
141        // `_mnemo.*` key is.
142        check_caller_reserved(&memory.metadata)?;
143        self.ensure_key_caches()?;
144        let slot = Self::key_slot_for(&memory, key);
145        let existing = self.key_index.as_ref().and_then(|k| k.get(&slot).copied());
146
147        // The canonical `_mnemo.key`, so the record is self-identifying.
148        memory
149            .metadata
150            .insert(MNEMO_META_KEY.into(), Value::String(key.to_string()));
151
152        // NOOP check: if a live record exists for this slot and its
153        // user-visible fields match, return the existing id without a
154        // write.
155        if let Some(prev_id_u) = existing {
156            let prev_idx = self
157                .index
158                .get(prev_id_u, &self.catalog)
159                .ok_or_else(|| MnemoError::Invalid("key_index drift".into()))?;
160            let prev_entry = self.catalog[prev_idx].clone();
161            let prev_mem = self.read_memory(&prev_entry)?;
162            inherit_levels(&mut memory, &prev_mem);
163            let rounded = prev_entry.v9.is_some() && !self.float_vectors();
164            if Self::is_identical_keyed_write(&memory, &prev_mem, rounded) {
165                return Ok((Ulid(prev_id_u), WriteOutcome::Unchanged));
166            }
167
168            // SUPERSESSION: insert the new record, then rewrite the old
169            // with `_mnemo.superseded_by` + `_mnemo.invalid_at`.
170            let now = memory::now_secs();
171            memory.id = Ulid::nil(); // force a fresh ULID in `put`
172            memory.metadata.insert(
173                MNEMO_META_SUPERSEDES.into(),
174                Value::String(Ulid(prev_id_u).to_string()),
175            );
176            let new_id = self.put(memory)?;
177            // Mark the prior record.
178            let mut prev_mut = prev_mem;
179            prev_mut.metadata.insert(
180                MNEMO_META_SUPERSEDED_BY.into(),
181                Value::String(new_id.to_string()),
182            );
183            prev_mut
184                .metadata
185                .insert(MNEMO_META_INVALID_AT.into(), Value::Number(now.into()));
186            // keep prev_mut.id so `put` overwrites in place.
187            self.put(prev_mut)?;
188            // Update caches incrementally.
189            if let Some(k) = self.key_index.as_mut() {
190                k.insert(slot, new_id.0);
191            }
192            if let Some(s) = self.superseded.as_mut() {
193                s.insert(prev_id_u);
194            }
195            return Ok((new_id, WriteOutcome::Superseded));
196        }
197
198        // ADDED: no prior record for this slot.
199        memory.id = Ulid::nil();
200        let new_id = self.put(memory)?;
201        if let Some(k) = self.key_index.as_mut() {
202            k.insert(slot, new_id.0);
203        }
204        Ok((new_id, WriteOutcome::Added))
205    }
206
207    /// 12.3 step 5b (v0.15): a keyed write that **adopts a named, unkeyed
208    /// memory as the key's first version, then supersedes it**. Use it to
209    /// put a fact that was written without a key under one, so the old
210    /// version stops showing in recall without being deleted.
211    ///
212    /// The old record (`supersedes`) takes the key (`_mnemo.key`) and is
213    /// marked `_mnemo.superseded_by` and `_mnemo.invalid_at`; the new record
214    /// gets `_mnemo.supersedes = <old id>`. [`Mnemo::history`] then lists the
215    /// old record as the oldest version, and recall and `about` leave it out,
216    /// as for any superseded record. No format change: these are the keyed
217    /// path's own `_mnemo.*` keys, which older builds carry through.
218    ///
219    /// **When the new content matches the old record's** user-visible fields
220    /// (the identical-write rule of [`Mnemo::remember_keyed`]), no new record
221    /// is written: the old one takes the key and becomes the slot's live
222    /// record, and the outcome is [`WriteOutcome::Updated`] with its id.
223    ///
224    /// Refused with [`MnemoError::Invalid`] when the old id doesn't exist or
225    /// is deleted; is already superseded; already has a key (use the plain
226    /// keyed write); is an engine record (any `_mnemo.kind`, or the
227    /// manifest); isn't in the key's slot scope (the same agent's Private
228    /// memory for a Private write, a Shared one for a Shared write); or when
229    /// the slot already has a live record. [`MnemoError::ReadOnly`] on a
230    /// read-only handle.
231    pub fn remember_keyed_superseding(
232        &mut self,
233        mut memory: Memory,
234        key: &str,
235        supersedes: &Ulid,
236    ) -> Result<(Ulid, WriteOutcome)> {
237        if self.read_only {
238            return Err(MnemoError::ReadOnly);
239        }
240        if key.is_empty() {
241            return Err(MnemoError::Invalid(
242                "remember_keyed_superseding: 'key' must not be empty".into(),
243            ));
244        }
245        // 13a: visibility and freshness are the caller's (checked); no other
246        // `_mnemo.*` key is.
247        check_caller_reserved(&memory.metadata)?;
248        self.ensure_key_caches()?;
249        let slot = Self::key_slot_for(&memory, key);
250        if self
251            .key_index
252            .as_ref()
253            .is_some_and(|k| k.contains_key(&slot))
254        {
255            return Err(MnemoError::Invalid(format!(
256                "supersedes: key {key:?} already has a live record; a named memory can only \
257                 become a key's first version (use the plain keyed write)"
258            )));
259        }
260        let bad = |why: &str| MnemoError::Invalid(format!("supersedes {supersedes}: {why}"));
261        let old_idx = self
262            .index
263            .get(supersedes.0, &self.catalog)
264            .ok_or_else(|| bad("no such memory"))?;
265        let old_entry = self.catalog[old_idx].clone();
266        if old_entry.deleted {
267            return Err(bad("the memory is deleted"));
268        }
269        let mut old = self.read_memory(&old_entry)?;
270        if old.metadata.contains_key(MNEMO_META_SUPERSEDED_BY)
271            || self
272                .superseded
273                .as_ref()
274                .is_some_and(|s| s.contains(&supersedes.0))
275        {
276            return Err(bad("it is already superseded"));
277        }
278        if old.metadata.contains_key(MNEMO_META_KEY) {
279            return Err(bad(
280                "it already has a key; use the plain keyed write with that key",
281            ));
282        }
283        if old.metadata.contains_key(MNEMO_META_KIND) || is_manifest(&old) {
284            return Err(bad(
285                "it is an engine record (a thread, essence or the manifest)",
286            ));
287        }
288        if Self::key_slot_for(&old, key) != slot {
289            return Err(bad(
290                "it isn't in this key's scope (a Private write takes this agent's Private \
291                 memory, a Shared write a Shared one)",
292            ));
293        }
294        memory
295            .metadata
296            .insert(MNEMO_META_KEY.into(), Value::String(key.to_string()));
297        old.metadata
298            .insert(MNEMO_META_KEY.into(), Value::String(key.to_string()));
299        inherit_levels(&mut memory, &old);
300        let rounded = old_entry.v9.is_some() && !self.float_vectors();
301        if Self::is_identical_keyed_write(&memory, &old, rounded) {
302            // Adopt the old record as the slot's live record.
303            self.put(old)?;
304            if let Some(k) = self.key_index.as_mut() {
305                k.insert(slot, supersedes.0);
306            }
307            return Ok((*supersedes, WriteOutcome::Updated));
308        }
309        let now = memory::now_secs();
310        memory.id = Ulid::nil();
311        memory.metadata.insert(
312            MNEMO_META_SUPERSEDES.into(),
313            Value::String(supersedes.to_string()),
314        );
315        let new_id = self.put(memory)?;
316        old.metadata.insert(
317            MNEMO_META_SUPERSEDED_BY.into(),
318            Value::String(new_id.to_string()),
319        );
320        old.metadata
321            .insert(MNEMO_META_INVALID_AT.into(), Value::Number(now.into()));
322        self.put(old)?;
323        if let Some(k) = self.key_index.as_mut() {
324            k.insert(slot, new_id.0);
325        }
326        if let Some(s) = self.superseded.as_mut() {
327            s.insert(supersedes.0);
328        }
329        Ok((new_id, WriteOutcome::Superseded))
330    }
331
332    /// [`Mnemo::remember_keyed_superseding`] with `content` embedded by the
333    /// registered embedder (the document side).
334    pub fn remember_keyed_text_superseding(
335        &mut self,
336        content: &str,
337        memory_type: MemoryType,
338        key: &str,
339        supersedes: &Ulid,
340    ) -> Result<(Ulid, WriteOutcome)> {
341        if self.read_only {
342            return Err(MnemoError::ReadOnly);
343        }
344        let embedder = self.embedder.as_ref().ok_or_else(|| {
345            MnemoError::Invalid(
346                "no embedder registered on this handle; call set_embedder first".into(),
347            )
348        })?;
349        let mut vectors = embedder.embed(&[content])?;
350        let vector = vectors.pop().ok_or_else(|| {
351            MnemoError::Invalid("embedder returned no vector for the input text".into())
352        })?;
353        if vector.len() != self.dimensions {
354            return Err(MnemoError::DimensionMismatch {
355                expected: self.dimensions,
356                got: vector.len(),
357            });
358        }
359        let memory = Memory::new(content.to_string(), memory_type, vector);
360        self.remember_keyed_superseding(memory, key, supersedes)
361    }
362
363    /// Text-side keyed write: embed `content` through the registered
364    /// embedder, then [`Mnemo::remember_keyed`]. Same returns.
365    pub fn remember_keyed_text(
366        &mut self,
367        content: &str,
368        memory_type: MemoryType,
369        key: &str,
370    ) -> Result<(Ulid, WriteOutcome)> {
371        if self.read_only {
372            return Err(MnemoError::ReadOnly);
373        }
374        let embedder = self.embedder.as_ref().ok_or_else(|| {
375            MnemoError::Invalid(
376                "no embedder registered on this handle; call set_embedder first".into(),
377            )
378        })?;
379        let mut vectors = embedder.embed(&[content])?;
380        let vector = vectors.pop().ok_or_else(|| {
381            MnemoError::Invalid("embedder returned no vector for the input text".into())
382        })?;
383        if vector.len() != self.dimensions {
384            return Err(MnemoError::DimensionMismatch {
385                expected: self.dimensions,
386                got: vector.len(),
387            });
388        }
389        let memory = Memory::new(content.to_string(), memory_type, vector);
390        self.remember_keyed(memory, key)
391    }
392
393    /// Update an existing memory in place, preserving its ULID,
394    /// `created_at` and access stats. Returns [`WriteOutcome::Updated`]
395    /// on a real change, [`WriteOutcome::Unchanged`] when every field in
396    /// the patch already matches the live record.
397    ///
398    /// Reserved `_mnemo.*` metadata keys on the existing record are
399    /// preserved across a `metadata` replacement; a `metadata` of
400    /// `Some(map)` replaces every **user-visible** key with `map`'s
401    /// entries. A `content` change requires a matching `vector`
402    /// (use [`Mnemo::update_text`] to re-embed) — a bare `content` patch
403    /// is rejected to stop text and embedding drifting apart silently.
404    ///
405    /// A `metadata` map with a key starting with `_mnemo.` is refused with
406    /// [`MnemoError::Invalid`]: those keys are the engine's, and the
407    /// record's own are kept as described above.
408    pub fn update(&mut self, id: &Ulid, patch: MemoryPatch) -> Result<WriteOutcome> {
409        if let Some(m) = patch.metadata.as_ref() {
410            check_caller_reserved(m)?;
411        }
412        if let Some(m) = patch.caller_keys.as_ref() {
413            for (k, v) in m {
414                if !is_caller_key(k) {
415                    return Err(super::crud::reserved_key_error(k));
416                }
417                if !v.is_null() {
418                    crate::memory::check_caller_key(k, v).map_err(MnemoError::Invalid)?;
419                }
420            }
421        }
422        self.update_unchecked(id, patch)
423    }
424
425    /// [`Mnemo::update`] without the reserved-key check, for the engine's own
426    /// updates (essence items carry `_mnemo.refs`).
427    pub(super) fn update_unchecked(
428        &mut self,
429        id: &Ulid,
430        patch: MemoryPatch,
431    ) -> Result<WriteOutcome> {
432        if self.read_only {
433            return Err(MnemoError::ReadOnly);
434        }
435        if patch.content.is_some() && patch.vector.is_none() {
436            return Err(MnemoError::Invalid(
437                "update: a content change needs a matching vector (or call update_text \
438                 to re-embed through the registered embedder)"
439                    .into(),
440            ));
441        }
442        let idx = self
443            .index
444            .get(id.0, &self.catalog)
445            .ok_or_else(|| MnemoError::NotFound(id.to_string()))?;
446        if self.catalog[idx].deleted {
447            return Err(MnemoError::NotFound(id.to_string()));
448        }
449        let entry = self.catalog[idx].clone();
450        let existing = self.read_memory(&entry)?;
451        // RB-014: a finding changes only by triage and verification.
452        if super::findings::is_finding(&existing) {
453            return Err(super::findings::finding_write_refused("updated"));
454        }
455
456        // Apply patch into a candidate, detect no-op after the fact.
457        let mut cand = existing.clone();
458        if let Some(c) = &patch.content {
459            cand.content = c.clone();
460        }
461        if let Some(v) = &patch.vector {
462            if v.len() != self.dimensions {
463                return Err(MnemoError::DimensionMismatch {
464                    expected: self.dimensions,
465                    got: v.len(),
466                });
467            }
468            cand.vector = v.clone();
469        }
470        if let Some(i) = patch.importance {
471            cand.importance = i.clamp(0.0, 1.0);
472        }
473        if let Some(mt) = patch.memory_type {
474            cand.memory_type = mt;
475        }
476        if let Some(new_meta) = patch.metadata {
477            // Keep reserved `_mnemo.*` keys from the existing record.
478            // 13a: but a caller key the patch sets (visibility, freshness)
479            // is the patch's.
480            let reserved: Vec<(String, Value)> = existing
481                .metadata
482                .iter()
483                .filter(|(k, _)| k.starts_with(crate::memory::MNEMO_META_NS))
484                .filter(|(k, _)| !(is_caller_key(k) && new_meta.contains_key(k.as_str())))
485                .map(|(k, v)| (k.clone(), v.clone()))
486                .collect();
487            cand.metadata = new_meta;
488            for (k, v) in reserved {
489                cand.metadata.insert(k, v);
490            }
491        }
492        if let Some(keys) = patch.caller_keys {
493            for (k, v) in keys {
494                if v.is_null() {
495                    cand.metadata.remove(&k);
496                } else {
497                    cand.metadata.insert(k, v);
498                }
499            }
500        }
501        if let Some(ttl) = patch.ttl_secs {
502            cand.ttl_secs = ttl;
503        }
504
505        // No-op detection: compare all user-visible fields.
506        if cand.content == existing.content
507            && cand.vector == existing.vector
508            && (cand.importance - existing.importance).abs() <= f32::EPSILON
509            && cand.memory_type == existing.memory_type
510            && cand.metadata == existing.metadata
511            && cand.ttl_secs == existing.ttl_secs
512        {
513            return Ok(WriteOutcome::Unchanged);
514        }
515
516        // Stamp `_mnemo.updated_at` and preserve id + created_at.
517        let now = memory::now_secs();
518        cand.metadata
519            .insert(MNEMO_META_UPDATED_AT.into(), Value::Number(now.into()));
520        cand.id = existing.id;
521        cand.created_at = existing.created_at;
522        // put() preserves accessed_at/access_count via the index lookup.
523        self.put(cand)?;
524        // `put` kept the key slot and the other handle caches current.
525        Ok(WriteOutcome::Updated)
526    }
527
528    /// In-place update that re-embeds `new_text` through the registered
529    /// embedder. Shorthand for `update(id, patch.with_content_and_vector)`.
530    pub fn update_text(
531        &mut self,
532        id: &Ulid,
533        new_text: &str,
534        mut patch: MemoryPatch,
535    ) -> Result<WriteOutcome> {
536        if self.read_only {
537            return Err(MnemoError::ReadOnly);
538        }
539        let embedder = self.embedder.as_ref().ok_or_else(|| {
540            MnemoError::Invalid(
541                "no embedder registered on this handle; call set_embedder first".into(),
542            )
543        })?;
544        let mut vectors = embedder.embed(&[new_text])?;
545        let vector = vectors.pop().ok_or_else(|| {
546            MnemoError::Invalid("embedder returned no vector for the input text".into())
547        })?;
548        if vector.len() != self.dimensions {
549            return Err(MnemoError::DimensionMismatch {
550                expected: self.dimensions,
551                got: vector.len(),
552            });
553        }
554        patch.content = Some(new_text.to_string());
555        patch.vector = Some(vector);
556        self.update(id, patch)
557    }
558
559    /// Walk the full chain for a keyed slot: every record this key has
560    /// ever held, newest first. Entry 0 is the **live** record (unless
561    /// the slot is empty, in which case the vector is empty); subsequent
562    /// entries are the superseded history in reverse-supersession order.
563    ///
564    /// **Slot resolution (v0.8.1 bugfix, lane A).** The lookup slot
565    /// matches a keyed `remember` with the same arguments, so the
566    /// obvious `history(key, None)` walks the private slot of the
567    /// default agent — the same slot
568    /// `remember_keyed(Memory::new(...), key)` writes to when the
569    /// caller omits an explicit `agent_id` / `scope`. Pre-v0.8.1
570    /// `agent_id = None` incorrectly looked up the shared slot and
571    /// returned an empty chain for the common case; the old behavior
572    /// is still reachable via `history_in(key, KeyScope::Shared)`.
573    ///
574    /// * `agent_id = Some(a)` → private slot for that agent.
575    /// * `agent_id = None` → private slot for the default agent (same
576    ///   as [`KeyScope::private_default`]).
577    ///
578    /// Use [`Mnemo::history_in`] with [`KeyScope::Shared`] for the
579    /// shared slot.
580    pub fn history(&mut self, key: &str, agent_id: Option<&str>) -> Result<Vec<Memory>> {
581        let scope = match agent_id {
582            Some(a) => KeyScope::Private(a.to_string()),
583            None => KeyScope::private_default(),
584        };
585        self.history_in(key, scope)
586    }
587
588    /// Walk the full chain for a keyed slot identified by an explicit
589    /// [`KeyScope`]. Returns the same shape as [`Mnemo::history`] —
590    /// live record first, then the superseded chain newest-first.
591    ///
592    /// Use this when you need the **shared** slot (`KeyScope::Shared`),
593    /// which `history(key, None)` no longer reaches as of v0.8.1.
594    pub fn history_in(&mut self, key: &str, scope: KeyScope) -> Result<Vec<Memory>> {
595        self.ensure_key_caches()?;
596        let slot = crate::store::KeySlot {
597            scope_owner: match scope {
598                KeyScope::Private(a) => Some(a),
599                KeyScope::Shared => None,
600            },
601            key: key.to_string(),
602        };
603        let live_id = self.key_index.as_ref().and_then(|k| k.get(&slot).copied());
604        let mut out = Vec::new();
605        let mut cursor = live_id;
606        while let Some(id_u) = cursor {
607            let idx = self.index.get(id_u, &self.catalog).ok_or_else(|| {
608                MnemoError::Invalid("history: superseded chain references missing id".into())
609            })?;
610            let entry = self.catalog[idx].clone();
611            if entry.deleted {
612                break;
613            }
614            let m = self.read_memory(&entry)?;
615            let next = m
616                .metadata
617                .get(MNEMO_META_SUPERSEDES)
618                .and_then(|v| v.as_str())
619                .and_then(|s| Ulid::from_string(s).ok())
620                .map(|u| u.0);
621            out.push(m);
622            cursor = next;
623        }
624        Ok(out)
625    }
626
627    // --- Phase 12.7a: thread archive --------------------------------
628}
629
630/// RB-013.2: a keyed write that gives no visibility (or no review date)
631/// takes the live version's, so revising a private fact by its key keeps it
632/// private. A caller who wants another level says so.
633fn inherit_levels(new: &mut Memory, prev: &Memory) {
634    for k in [
635        crate::memory::MNEMO_META_VISIBILITY,
636        crate::memory::MNEMO_META_REVIEW_BY,
637    ] {
638        if !new.metadata.contains_key(k) {
639            if let Some(v) = prev.metadata.get(k) {
640                new.metadata.insert(k.into(), v.clone());
641            }
642        }
643    }
644}
645
646impl Mnemo {
647    /// RB-013.2: when the keyed version `id` changed the level of the
648    /// version it superseded, the two levels (`(old, new)`), so a caller can
649    /// say so (`superseded (private → team)`).
650    pub fn superseded_level_change(&mut self, id: &Ulid) -> Result<Option<(String, String)>> {
651        let new = self.get(id)?;
652        let Some(old) = new
653            .metadata
654            .get(MNEMO_META_SUPERSEDES)
655            .and_then(Value::as_str)
656            .and_then(|s| Ulid::from_string(s).ok())
657        else {
658            return Ok(None);
659        };
660        let old = self.get(&old)?;
661        let (a, b) = (
662            crate::memory::visibility_of(&old).to_string(),
663            crate::memory::visibility_of(&new).to_string(),
664        );
665        Ok((a != b).then_some((a, b)))
666    }
667}