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 pub(super) fn is_identical_keyed_write(incoming: &Memory, live: &Memory) -> bool {
14 if incoming.content != live.content {
15 return false;
16 }
17 if incoming.memory_type != live.memory_type {
18 return false;
19 }
20 if (incoming.importance - live.importance).abs() > f32::EPSILON {
21 return false;
22 }
23 if incoming.vector != live.vector {
24 return false;
25 }
26 // Strip `_mnemo.*` from both sides before comparing user metadata.
27 let strip = |m: &Map<String, Value>| -> Map<String, Value> {
28 m.iter()
29 .filter(|(k, _)| !k.starts_with(crate::memory::MNEMO_META_NS))
30 .map(|(k, v)| (k.clone(), v.clone()))
31 .collect()
32 };
33 strip(&incoming.metadata) == strip(&live.metadata)
34 }
35
36 /// Store a memory under a keyed upsert slot. Returns the live record's
37 /// id and a [`WriteOutcome`] saying whether this write created a new
38 /// slot (`Added`), replaced a prior record (`Superseded`), or matched
39 /// the existing live record byte-for-byte (`Unchanged`, no file write).
40 ///
41 /// The slot is identified by `(scope_owner, key)`:
42 /// * `Scope::Private` memories share a slot per `(agent_id, key)`.
43 /// * `Scope::Shared` memories share one slot per `key` across the file.
44 ///
45 /// On supersession the prior record is **not** deleted — it remains
46 /// retrievable through [`Mnemo::history`] — but it is excluded from
47 /// default [`Mnemo::recall`] and [`Mnemo::about`]. A caller that wants
48 /// the full lineage of a key walks `history(key)`.
49 ///
50 /// This is the atomic 12.1 "supersede-or-noop" write path. Plain
51 /// [`Mnemo::remember`] without a key is unchanged.
52 pub fn remember_keyed(
53 &mut self,
54 mut memory: Memory,
55 key: &str,
56 ) -> Result<(Ulid, WriteOutcome)> {
57 if self.read_only {
58 return Err(MnemoError::ReadOnly);
59 }
60 if key.is_empty() {
61 return Err(MnemoError::Invalid(
62 "remember_keyed: 'key' must not be empty".into(),
63 ));
64 }
65 // RB-001.24: a keyed write is always a new record, so no caller
66 // `_mnemo.*` key is accepted (the engine sets `_mnemo.key` below).
67 if let Some(k) = memory
68 .metadata
69 .keys()
70 .find(|k| k.starts_with(crate::memory::MNEMO_META_NS))
71 {
72 return Err(super::crud::reserved_key_error(k));
73 }
74 self.ensure_key_caches()?;
75 let slot = Self::key_slot_for(&memory, key);
76 let existing = self.key_index.as_ref().and_then(|k| k.get(&slot).copied());
77
78 // The canonical `_mnemo.key`, so the record is self-identifying.
79 memory
80 .metadata
81 .insert(MNEMO_META_KEY.into(), Value::String(key.to_string()));
82
83 // NOOP check: if a live record exists for this slot and its
84 // user-visible fields match, return the existing id without a
85 // write.
86 if let Some(prev_id_u) = existing {
87 let prev_idx = self
88 .index
89 .get(prev_id_u, &self.catalog)
90 .ok_or_else(|| MnemoError::Invalid("key_index drift".into()))?;
91 let prev_entry = self.catalog[prev_idx].clone();
92 let prev_mem = self.read_memory(&prev_entry)?;
93 if Self::is_identical_keyed_write(&memory, &prev_mem) {
94 return Ok((Ulid(prev_id_u), WriteOutcome::Unchanged));
95 }
96
97 // SUPERSESSION: insert the new record, then rewrite the old
98 // with `_mnemo.superseded_by` + `_mnemo.invalid_at`.
99 let now = memory::now_secs();
100 memory.id = Ulid::nil(); // force a fresh ULID in `put`
101 memory.metadata.insert(
102 MNEMO_META_SUPERSEDES.into(),
103 Value::String(Ulid(prev_id_u).to_string()),
104 );
105 let new_id = self.put(memory)?;
106 // Mark the prior record.
107 let mut prev_mut = prev_mem;
108 prev_mut.metadata.insert(
109 MNEMO_META_SUPERSEDED_BY.into(),
110 Value::String(new_id.to_string()),
111 );
112 prev_mut
113 .metadata
114 .insert(MNEMO_META_INVALID_AT.into(), Value::Number(now.into()));
115 // keep prev_mut.id so `put` overwrites in place.
116 self.put(prev_mut)?;
117 // Update caches incrementally.
118 if let Some(k) = self.key_index.as_mut() {
119 k.insert(slot, new_id.0);
120 }
121 if let Some(s) = self.superseded.as_mut() {
122 s.insert(prev_id_u);
123 }
124 return Ok((new_id, WriteOutcome::Superseded));
125 }
126
127 // ADDED: no prior record for this slot.
128 memory.id = Ulid::nil();
129 let new_id = self.put(memory)?;
130 if let Some(k) = self.key_index.as_mut() {
131 k.insert(slot, new_id.0);
132 }
133 Ok((new_id, WriteOutcome::Added))
134 }
135
136 /// Text-side keyed write: embed `content` through the registered
137 /// embedder, then [`Mnemo::remember_keyed`]. Same returns.
138 pub fn remember_keyed_text(
139 &mut self,
140 content: &str,
141 memory_type: MemoryType,
142 key: &str,
143 ) -> Result<(Ulid, WriteOutcome)> {
144 if self.read_only {
145 return Err(MnemoError::ReadOnly);
146 }
147 let embedder = self.embedder.as_ref().ok_or_else(|| {
148 MnemoError::Invalid(
149 "no embedder registered on this handle; call set_embedder first".into(),
150 )
151 })?;
152 let mut vectors = embedder.embed(&[content])?;
153 let vector = vectors.pop().ok_or_else(|| {
154 MnemoError::Invalid("embedder returned no vector for the input text".into())
155 })?;
156 if vector.len() != self.dimensions {
157 return Err(MnemoError::DimensionMismatch {
158 expected: self.dimensions,
159 got: vector.len(),
160 });
161 }
162 let memory = Memory::new(content.to_string(), memory_type, vector);
163 self.remember_keyed(memory, key)
164 }
165
166 /// Update an existing memory in place, preserving its ULID,
167 /// `created_at` and access stats. Returns [`WriteOutcome::Updated`]
168 /// on a real change, [`WriteOutcome::Unchanged`] when every field in
169 /// the patch already matches the live record.
170 ///
171 /// Reserved `_mnemo.*` metadata keys on the existing record are
172 /// preserved across a `metadata` replacement; a `metadata` of
173 /// `Some(map)` replaces every **user-visible** key with `map`'s
174 /// entries. A `content` change requires a matching `vector`
175 /// (use [`Mnemo::update_text`] to re-embed) — a bare `content` patch
176 /// is rejected to stop text and embedding drifting apart silently.
177 ///
178 /// A `metadata` map with a key starting with `_mnemo.` is refused with
179 /// [`MnemoError::Invalid`]: those keys are the engine's, and the
180 /// record's own are kept as described above.
181 pub fn update(&mut self, id: &Ulid, patch: MemoryPatch) -> Result<WriteOutcome> {
182 if let Some(k) = patch.metadata.as_ref().and_then(|m| {
183 m.keys()
184 .find(|k| k.starts_with(crate::memory::MNEMO_META_NS))
185 }) {
186 return Err(super::crud::reserved_key_error(k));
187 }
188 self.update_unchecked(id, patch)
189 }
190
191 /// [`Mnemo::update`] without the reserved-key check, for the engine's own
192 /// updates (essence items carry `_mnemo.refs`).
193 pub(super) fn update_unchecked(
194 &mut self,
195 id: &Ulid,
196 patch: MemoryPatch,
197 ) -> Result<WriteOutcome> {
198 if self.read_only {
199 return Err(MnemoError::ReadOnly);
200 }
201 if patch.content.is_some() && patch.vector.is_none() {
202 return Err(MnemoError::Invalid(
203 "update: a content change needs a matching vector (or call update_text \
204 to re-embed through the registered embedder)"
205 .into(),
206 ));
207 }
208 let idx = self
209 .index
210 .get(id.0, &self.catalog)
211 .ok_or_else(|| MnemoError::NotFound(id.to_string()))?;
212 if self.catalog[idx].deleted {
213 return Err(MnemoError::NotFound(id.to_string()));
214 }
215 let entry = self.catalog[idx].clone();
216 let existing = self.read_memory(&entry)?;
217
218 // Apply patch into a candidate, detect no-op after the fact.
219 let mut cand = existing.clone();
220 if let Some(c) = &patch.content {
221 cand.content = c.clone();
222 }
223 if let Some(v) = &patch.vector {
224 if v.len() != self.dimensions {
225 return Err(MnemoError::DimensionMismatch {
226 expected: self.dimensions,
227 got: v.len(),
228 });
229 }
230 cand.vector = v.clone();
231 }
232 if let Some(i) = patch.importance {
233 cand.importance = i.clamp(0.0, 1.0);
234 }
235 if let Some(mt) = patch.memory_type {
236 cand.memory_type = mt;
237 }
238 if let Some(new_meta) = patch.metadata {
239 // Keep reserved `_mnemo.*` keys from the existing record.
240 let reserved: Vec<(String, Value)> = existing
241 .metadata
242 .iter()
243 .filter(|(k, _)| k.starts_with(crate::memory::MNEMO_META_NS))
244 .map(|(k, v)| (k.clone(), v.clone()))
245 .collect();
246 cand.metadata = new_meta;
247 for (k, v) in reserved {
248 cand.metadata.insert(k, v);
249 }
250 }
251 if let Some(ttl) = patch.ttl_secs {
252 cand.ttl_secs = ttl;
253 }
254
255 // No-op detection: compare all user-visible fields.
256 if cand.content == existing.content
257 && cand.vector == existing.vector
258 && (cand.importance - existing.importance).abs() <= f32::EPSILON
259 && cand.memory_type == existing.memory_type
260 && cand.metadata == existing.metadata
261 && cand.ttl_secs == existing.ttl_secs
262 {
263 return Ok(WriteOutcome::Unchanged);
264 }
265
266 // Stamp `_mnemo.updated_at` and preserve id + created_at.
267 let now = memory::now_secs();
268 cand.metadata
269 .insert(MNEMO_META_UPDATED_AT.into(), Value::Number(now.into()));
270 cand.id = existing.id;
271 cand.created_at = existing.created_at;
272 // put() preserves accessed_at/access_count via the index lookup.
273 self.put(cand)?;
274 // `put` kept the key slot and the other handle caches current.
275 Ok(WriteOutcome::Updated)
276 }
277
278 /// In-place update that re-embeds `new_text` through the registered
279 /// embedder. Shorthand for `update(id, patch.with_content_and_vector)`.
280 pub fn update_text(
281 &mut self,
282 id: &Ulid,
283 new_text: &str,
284 mut patch: MemoryPatch,
285 ) -> Result<WriteOutcome> {
286 if self.read_only {
287 return Err(MnemoError::ReadOnly);
288 }
289 let embedder = self.embedder.as_ref().ok_or_else(|| {
290 MnemoError::Invalid(
291 "no embedder registered on this handle; call set_embedder first".into(),
292 )
293 })?;
294 let mut vectors = embedder.embed(&[new_text])?;
295 let vector = vectors.pop().ok_or_else(|| {
296 MnemoError::Invalid("embedder returned no vector for the input text".into())
297 })?;
298 if vector.len() != self.dimensions {
299 return Err(MnemoError::DimensionMismatch {
300 expected: self.dimensions,
301 got: vector.len(),
302 });
303 }
304 patch.content = Some(new_text.to_string());
305 patch.vector = Some(vector);
306 self.update(id, patch)
307 }
308
309 /// Walk the full chain for a keyed slot: every record this key has
310 /// ever held, newest first. Entry 0 is the **live** record (unless
311 /// the slot is empty, in which case the vector is empty); subsequent
312 /// entries are the superseded history in reverse-supersession order.
313 ///
314 /// **Slot resolution (v0.8.1 bugfix, lane A).** The lookup slot
315 /// matches a keyed `remember` with the same arguments, so the
316 /// obvious `history(key, None)` walks the private slot of the
317 /// default agent — the same slot
318 /// `remember_keyed(Memory::new(...), key)` writes to when the
319 /// caller omits an explicit `agent_id` / `scope`. Pre-v0.8.1
320 /// `agent_id = None` incorrectly looked up the shared slot and
321 /// returned an empty chain for the common case; the old behavior
322 /// is still reachable via `history_in(key, KeyScope::Shared)`.
323 ///
324 /// * `agent_id = Some(a)` → private slot for that agent.
325 /// * `agent_id = None` → private slot for the default agent (same
326 /// as [`KeyScope::private_default`]).
327 ///
328 /// Use [`Mnemo::history_in`] with [`KeyScope::Shared`] for the
329 /// shared slot.
330 pub fn history(&mut self, key: &str, agent_id: Option<&str>) -> Result<Vec<Memory>> {
331 let scope = match agent_id {
332 Some(a) => KeyScope::Private(a.to_string()),
333 None => KeyScope::private_default(),
334 };
335 self.history_in(key, scope)
336 }
337
338 /// Walk the full chain for a keyed slot identified by an explicit
339 /// [`KeyScope`]. Returns the same shape as [`Mnemo::history`] —
340 /// live record first, then the superseded chain newest-first.
341 ///
342 /// Use this when you need the **shared** slot (`KeyScope::Shared`),
343 /// which `history(key, None)` no longer reaches as of v0.8.1.
344 pub fn history_in(&mut self, key: &str, scope: KeyScope) -> Result<Vec<Memory>> {
345 self.ensure_key_caches()?;
346 let slot = crate::store::KeySlot {
347 scope_owner: match scope {
348 KeyScope::Private(a) => Some(a),
349 KeyScope::Shared => None,
350 },
351 key: key.to_string(),
352 };
353 let live_id = self.key_index.as_ref().and_then(|k| k.get(&slot).copied());
354 let mut out = Vec::new();
355 let mut cursor = live_id;
356 while let Some(id_u) = cursor {
357 let idx = self.index.get(id_u, &self.catalog).ok_or_else(|| {
358 MnemoError::Invalid("history: superseded chain references missing id".into())
359 })?;
360 let entry = self.catalog[idx].clone();
361 if entry.deleted {
362 break;
363 }
364 let m = self.read_memory(&entry)?;
365 let next = m
366 .metadata
367 .get(MNEMO_META_SUPERSEDES)
368 .and_then(|v| v.as_str())
369 .and_then(|s| Ulid::from_string(s).ok())
370 .map(|u| u.0);
371 out.push(m);
372 cursor = next;
373 }
374 Ok(out)
375 }
376
377 // --- Phase 12.7a: thread archive --------------------------------
378}