mnemo-engine 0.17.0

Encrypted, single-file, portable agent memory engine with multi-signal recall, sessions, snapshots, and an IVF+PQ index
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
//! Phase 12.7b: essence items (add, append, update, resolve, remove) and the essence render.

use super::*;

/// Split `s` into chunks, each with `<= max_bytes` of UTF-8 content,
/// landing on `char` boundaries. Preserves original ordering; a trailing
/// chunk may be shorter than `max_bytes`.
/// Phase 12.7b helper: pull the `_mnemo.status` string from an
/// essence record. Returns `None` for timeline entries (they have no
/// status) and for malformed records.
pub(super) fn status_of(m: &Memory) -> Option<&str> {
    m.metadata.get(MNEMO_META_STATUS).and_then(|v| v.as_str())
}

/// Phase 12.7b helper: render one essence item as a markdown bullet.
/// Timeline entries get a date tag; section items get `[open]` /
/// `[resolved]` so the reader can scan active work quickly.
fn render_essence_item(section: EssenceSection, m: &Memory, now: i64) -> String {
    if section == EssenceSection::Timeline {
        let date = format_unix_date(m.created_at);
        format!("- [{date}] {}\n", m.content)
    } else {
        let status = status_of(m).unwrap_or(essence_status::OPEN);
        // 13a (13.6): an item past its review date, or its section's age.
        let stale = crate::memory::stale_since(m, now)
            .map(|t| format!(" [stale since {}]", format_unix_date(t)))
            .unwrap_or_default();
        format!("- [{status}] {}{stale}\n", m.content)
    }
}

/// Minimal unix-seconds → `YYYY-MM-DD` formatter (no chrono/time
/// dependency; mirrors the ISO 8601 parser in `transcript.rs`).
pub(crate) fn format_unix_date(secs: i64) -> String {
    let days_total = secs.div_euclid(86_400);
    let (y, m, d) = civil_from_days(days_total);
    format!("{y:04}-{m:02}-{d:02}")
}

/// Howard Hinnant's `civil_from_days` — inverse of `days_from_civil`,
/// adequate for Gregorian dates since 1970. Pure arithmetic, no
/// dependencies.
fn civil_from_days(z: i64) -> (i64, u32, u32) {
    let z = z + 719_468;
    let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
    let doe = (z - era * 146_097) as u64;
    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
    let y = yoe as i64 + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
    let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
    let y = if m <= 2 { y + 1 } else { y };
    (y, m, d)
}

impl Mnemo {
    /// 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.
    pub fn essence_add(
        &mut self,
        scope: EssenceScope,
        section: EssenceSection,
        text: &str,
        refs: Option<Vec<String>>,
    ) -> Result<Ulid> {
        if self.read_only {
            return Err(MnemoError::ReadOnly);
        }
        Self::check_essence_add(section, text)?;
        self.essence_add_with(scope, section, text, refs, None)
    }

    /// [`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.
    pub fn essence_add_with_vector(
        &mut self,
        scope: EssenceScope,
        section: EssenceSection,
        text: &str,
        refs: Option<Vec<String>>,
        vector: Vec<f32>,
    ) -> Result<Ulid> {
        if self.read_only {
            return Err(MnemoError::ReadOnly);
        }
        Self::check_essence_add(section, text)?;
        self.essence_add_with(scope, section, text, refs, Some(vector))
    }

    /// Validation shared by [`Mnemo::essence_add`] and `commit_deltas`.
    pub(super) fn check_essence_add(section: EssenceSection, text: &str) -> Result<()> {
        if section == EssenceSection::Timeline {
            return Err(MnemoError::Invalid(
                "essence_add: use essence_append_timeline for the timeline section".into(),
            ));
        }
        if text.is_empty() {
            return Err(MnemoError::Invalid(
                "essence_add: text must not be empty".into(),
            ));
        }
        if text.len() > section.item_max_bytes() {
            return Err(MnemoError::Invalid(format!(
                "essence_add: '{}' items must be <= {} bytes; got {}",
                section.as_str(),
                section.item_max_bytes(),
                text.len()
            )));
        }
        Ok(())
    }

    /// Write half of `essence_add`, with an optional precomputed vector.
    pub(super) fn essence_add_with(
        &mut self,
        scope: EssenceScope,
        section: EssenceSection,
        text: &str,
        refs: Option<Vec<String>>,
        vector: Option<Vec<f32>>,
    ) -> Result<Ulid> {
        let now = memory::now_secs();
        let mem = self.build_essence_record(scope, section, text, refs, Some(now), vector)?;
        self.put(mem)
    }

    /// 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).
    pub fn essence_append_timeline(
        &mut self,
        scope: EssenceScope,
        text: &str,
        refs: Option<Vec<String>>,
    ) -> Result<Ulid> {
        if self.read_only {
            return Err(MnemoError::ReadOnly);
        }
        Self::check_essence_append(text)?;
        self.essence_append_with(scope, text, refs, None)
    }

    /// [`Mnemo::essence_append_timeline`] with a caller-supplied vector
    /// (see [`Mnemo::essence_add_with_vector`]).
    pub fn essence_append_timeline_with_vector(
        &mut self,
        scope: EssenceScope,
        text: &str,
        refs: Option<Vec<String>>,
        vector: Vec<f32>,
    ) -> Result<Ulid> {
        if self.read_only {
            return Err(MnemoError::ReadOnly);
        }
        Self::check_essence_append(text)?;
        self.essence_append_with(scope, text, refs, Some(vector))
    }

    /// Validation shared by [`Mnemo::essence_append_timeline`] and
    /// `commit_deltas`.
    pub(super) fn check_essence_append(text: &str) -> Result<()> {
        if text.is_empty() {
            return Err(MnemoError::Invalid(
                "essence_append_timeline: text must not be empty".into(),
            ));
        }
        if text.len() > EssenceSection::Timeline.item_max_bytes() {
            return Err(MnemoError::Invalid(format!(
                "essence_append_timeline: entries must be <= {} bytes; got {}",
                EssenceSection::Timeline.item_max_bytes(),
                text.len()
            )));
        }
        Ok(())
    }

    /// Write half of `essence_append_timeline`, with an optional
    /// precomputed vector.
    pub(super) fn essence_append_with(
        &mut self,
        scope: EssenceScope,
        text: &str,
        refs: Option<Vec<String>>,
        vector: Option<Vec<f32>>,
    ) -> Result<Ulid> {
        let mem =
            self.build_essence_record(scope, EssenceSection::Timeline, text, refs, None, vector)?;
        self.put(mem)
    }

    /// 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.
    pub fn essence_update(
        &mut self,
        id: &Ulid,
        text: &str,
        refs: Option<Vec<String>>,
    ) -> Result<WriteOutcome> {
        if self.read_only {
            return Err(MnemoError::ReadOnly);
        }
        let existing = self.load_essence_record(id)?;
        let section = self.section_of(&existing)?;
        if section == EssenceSection::Timeline {
            return Err(MnemoError::Invalid(
                "essence_update: timeline entries are append-only; append a new one instead".into(),
            ));
        }
        if text.is_empty() {
            return Err(MnemoError::Invalid(
                "essence_update: text must not be empty".into(),
            ));
        }
        if text.len() > section.item_max_bytes() {
            return Err(MnemoError::Invalid(format!(
                "essence_update: '{}' items must be <= {} bytes; got {}",
                section.as_str(),
                section.item_max_bytes(),
                text.len()
            )));
        }
        let mut patch = MemoryPatch {
            content: Some(text.to_string()),
            ..Default::default()
        };
        // We don't have a usable embedder-free path for an in-place
        // content update, so provide the same vector as the existing
        // record (the text-vector drift guard in `update` will accept
        // this).
        patch.vector = Some(existing.vector.clone());
        if let Some(r) = refs {
            let mut meta = Map::new();
            // Preserve the user-visible metadata (none for essence —
            // everything lives under `_mnemo.*`) and let `update`'s
            // metadata-replacement path keep the reserved keys.
            meta.insert(
                MNEMO_META_REFS.into(),
                Value::Array(r.into_iter().map(Value::String).collect()),
            );
            patch.metadata = Some(meta);
        }
        self.update_unchecked(id, patch)
    }

    /// 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.
    pub fn essence_resolve(&mut self, id: &Ulid) -> Result<WriteOutcome> {
        self.essence_transition_status(id, essence_status::RESOLVED)
    }

    /// Phase 12.7b: soft-delete a section item. Same semantics as
    /// [`Mnemo::delete`] on any record — space reclaimed by a later
    /// compact.
    pub fn essence_remove(&mut self, id: &Ulid) -> Result<()> {
        if self.read_only {
            return Err(MnemoError::ReadOnly);
        }
        self.delete(id)
    }

    /// 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 …`).
    pub fn essence(&mut self, scope: EssenceScope, max_bytes: usize) -> Result<String> {
        let max_bytes = if max_bytes == 0 {
            ESSENCE_DEFAULT_RENDER_BYTES
        } else {
            max_bytes
        };
        // Collect every live essence record for this scope.
        // R-004.2: only the essence items, from the handle caches.
        let entries = self.essence_entries()?;
        let now = memory::now_secs();
        let mut by_section: std::collections::BTreeMap<&'static str, Vec<Memory>> =
            std::collections::BTreeMap::new();
        for section in EssenceSection::render_order() {
            by_section.insert(section.as_str(), Vec::new());
        }
        for e in &entries {
            let m = self.read_memory(e)?;
            if m.metadata.get(MNEMO_META_KIND).and_then(|v| v.as_str())
                != Some(MNEMO_META_KIND_ESSENCE)
            {
                continue;
            }
            // Scope filter. Project-scope records are shown in every
            // thread's render (and in the project render); thread-scope
            // records only match when scope == same thread.
            let rec_thread = m.metadata.get(MNEMO_META_THREAD).and_then(|v| v.as_str());
            let matches_scope = match (&scope, rec_thread) {
                (EssenceScope::Project, None) => true,
                (EssenceScope::Thread(_), None) => true, // project-scope always shows
                (EssenceScope::Thread(t), Some(rt)) => rt == t,
                (EssenceScope::Project, Some(_)) => false,
            };
            if !matches_scope {
                continue;
            }
            // 13a (13.5): the render shows public and team items.
            if !crate::memory::VisibilitySet::DEFAULT.shows(&m) {
                continue;
            }
            let section_str = m
                .metadata
                .get(MNEMO_META_SECTION)
                .and_then(|v| v.as_str())
                .unwrap_or("timeline");
            by_section
                .entry(
                    EssenceSection::parse(section_str)
                        .map(|s| s.as_str())
                        .unwrap_or("timeline"),
                )
                .or_default()
                .push(m);
        }

        // Sort each section's records:
        // - Decisions + Timeline: newest-first (by created_at desc).
        // - Everything else: sort open items before resolved, then
        //   newest-first. Cheap, deterministic.
        for (name, items) in by_section.iter_mut() {
            let newest_first = matches!(*name, "decisions" | "timeline");
            items.sort_by(|a, b| {
                let a_resolved = status_of(a) == Some(essence_status::RESOLVED);
                let b_resolved = status_of(b) == Some(essence_status::RESOLVED);
                match (a_resolved, b_resolved) {
                    (false, true) => std::cmp::Ordering::Less,
                    (true, false) => std::cmp::Ordering::Greater,
                    _ => {
                        if newest_first {
                            b.created_at.cmp(&a.created_at)
                        } else {
                            a.created_at.cmp(&b.created_at)
                        }
                    }
                }
            });
        }

        // Per-section budget: give intent / conventions / decisions a
        // larger share (they frame the thread), timeline a smaller
        // share (it can fold). This is deterministic because it
        // depends only on `max_bytes`.
        let header_reserve = 256usize; // header + archive pointer
        let body_budget = max_bytes.saturating_sub(header_reserve);
        let per_section_budget = |section: EssenceSection| -> usize {
            match section {
                EssenceSection::Intent => body_budget / 8,
                EssenceSection::Conventions => body_budget / 6,
                EssenceSection::Decisions => body_budget / 4,
                EssenceSection::State => body_budget / 8,
                EssenceSection::Open => body_budget / 8,
                EssenceSection::Next => body_budget / 12,
                EssenceSection::Lessons => body_budget / 12,
                EssenceSection::Timeline => body_budget / 4,
            }
        };

        let mut out = String::with_capacity(max_bytes);
        let scope_label = match &scope {
            EssenceScope::Thread(t) => format!("thread `{t}`"),
            EssenceScope::Project => "project".to_string(),
        };
        out.push_str(&format!("# essence — {scope_label}\n\n"));

        // Phase 12.7c: continuation. If this is a thread render AND
        // the thread has a `_mnemo.continues` link, pull the prior
        // thread's open section items, its `next`, and its last-N
        // timeline entries in ahead of the new thread's own essence.
        if let EssenceScope::Thread(new_id) = &scope {
            if let Some(prev_id) = self.predecessor_thread(new_id)? {
                let continuation = self
                    .render_continuation_prelude(&prev_id, max_bytes.saturating_sub(out.len()))?;
                if !continuation.is_empty() && out.len() + continuation.len() <= max_bytes {
                    out.push_str(&continuation);
                }
            }
        }

        for section in EssenceSection::render_order() {
            let items = match by_section.get(section.as_str()) {
                Some(v) if !v.is_empty() => v,
                _ => continue,
            };
            let budget = per_section_budget(*section);
            let section_header = format!("## {}\n", section.as_str());
            if out.len() + section_header.len() > max_bytes {
                break;
            }
            out.push_str(&section_header);
            let mut used = 0usize;
            let mut rendered = 0usize;
            for item in items {
                let line = render_essence_item(*section, item, now);
                if used + line.len() > budget {
                    break;
                }
                if out.len() + line.len() > max_bytes {
                    break;
                }
                out.push_str(&line);
                used += line.len();
                rendered += 1;
            }
            // Fold the remainder for timeline.
            if *section == EssenceSection::Timeline && rendered < items.len() {
                let fold = format!("- +{} earlier milestones\n", items.len() - rendered);
                if out.len() + fold.len() <= max_bytes {
                    out.push_str(&fold);
                }
            }
            if out.len() < max_bytes {
                out.push('\n');
            }
        }

        // Archive pointer.
        let pointer = match &scope {
            EssenceScope::Thread(t) => format!(
                "> full history: `mnemo thread export <file> --thread {t}` or `recall --thread {t}`\n"
            ),
            EssenceScope::Project => String::from(
                "> full history: `mnemo thread export <file> --thread <id>` or `recall --thread <id>`\n",
            ),
        };
        if out.len() + pointer.len() <= max_bytes {
            out.push_str(&pointer);
        }
        Ok(out)
    }

    // --- essence internal helpers ----------------------------------

    /// Build an essence record. `vector` is a precomputed embedding (the
    /// 12.7d `commit_deltas` batch path); `None` embeds `text` with the
    /// registered embedder, or falls back to an axis-neutral unit vector
    /// when there is none. Essence records are read by `_mnemo.kind` and
    /// scope, not by similarity, so the fallback costs no retrieval
    /// quality; it only has to pass `put`'s non-zero guard.
    pub(super) fn build_essence_record(
        &self,
        scope: EssenceScope,
        section: EssenceSection,
        text: &str,
        refs: Option<Vec<String>>,
        status_at: Option<i64>,
        vector: Option<Vec<f32>>,
    ) -> Result<Memory> {
        let v = match (vector, self.embedder.as_ref()) {
            (Some(v), _) => v,
            (None, Some(e)) => e.embed(&[text])?.pop().ok_or_else(|| {
                MnemoError::Invalid("essence: embedder returned no vector".into())
            })?,
            (None, None) => self.sentinel_vector(),
        };
        let mut m = Memory::new(text.to_string(), MemoryType::Semantic, v).with_importance(0.5);
        m.metadata.insert(
            MNEMO_META_KIND.into(),
            Value::String(MNEMO_META_KIND_ESSENCE.into()),
        );
        m.metadata.insert(
            MNEMO_META_SECTION.into(),
            Value::String(section.as_str().into()),
        );
        if let EssenceScope::Thread(t) = &scope {
            m.metadata
                .insert(MNEMO_META_THREAD.into(), Value::String(t.clone()));
        }
        if let Some(r) = refs {
            m.metadata.insert(
                MNEMO_META_REFS.into(),
                Value::Array(r.into_iter().map(Value::String).collect()),
            );
        }
        if let Some(at) = status_at {
            m.metadata.insert(
                MNEMO_META_STATUS.into(),
                Value::String(essence_status::OPEN.into()),
            );
            m.metadata.insert(
                MNEMO_META_STATUS_HISTORY.into(),
                Value::Array(vec![serde_json::json!({
                    "status": essence_status::OPEN,
                    "at": at,
                })]),
            );
        }
        Ok(m)
    }

    /// Axis-neutral unit vector (every component `1/sqrt(dims)`), used by
    /// essence records without an embedder and by thread-link markers.
    pub(super) fn sentinel_vector(&self) -> Vec<f32> {
        let dims = self.dimensions.max(1);
        vec![1.0 / (dims as f32).sqrt(); dims]
    }

    pub(super) fn load_essence_record(&mut self, id: &Ulid) -> Result<Memory> {
        let m = self.get(id)?;
        if m.metadata.get(MNEMO_META_KIND).and_then(|v| v.as_str()) != Some(MNEMO_META_KIND_ESSENCE)
        {
            return Err(MnemoError::Invalid(format!(
                "essence: record {id} is not an essence record (missing `_mnemo.kind = essence`)"
            )));
        }
        Ok(m)
    }

    pub(super) fn section_of(&self, m: &Memory) -> Result<EssenceSection> {
        let s = m
            .metadata
            .get(MNEMO_META_SECTION)
            .and_then(|v| v.as_str())
            .ok_or_else(|| {
                MnemoError::Invalid("essence: record missing `_mnemo.section`".into())
            })?;
        EssenceSection::parse(s)
            .ok_or_else(|| MnemoError::Invalid(format!("essence: unknown section '{s}' on record")))
    }

    pub(super) fn essence_transition_status(
        &mut self,
        id: &Ulid,
        to: &str,
    ) -> Result<WriteOutcome> {
        if self.read_only {
            return Err(MnemoError::ReadOnly);
        }
        let existing = self.load_essence_record(id)?;
        let section = self.section_of(&existing)?;
        if !section.has_status_lifecycle() {
            return Err(MnemoError::Invalid(format!(
                "essence_transition: '{}' section has no status lifecycle",
                section.as_str()
            )));
        }
        let from = existing
            .metadata
            .get(MNEMO_META_STATUS)
            .and_then(|v| v.as_str())
            .unwrap_or(essence_status::OPEN);
        if from == to {
            return Ok(WriteOutcome::Unchanged);
        }
        let allowed = ESSENCE_TRANSITIONS
            .iter()
            .any(|(f, t)| *f == from && *t == to);
        if !allowed {
            return Err(MnemoError::Invalid(format!(
                "essence_transition: '{from}' → '{to}' is not a valid transition for essence"
            )));
        }
        // Mutate metadata in place and `put` back under the same id
        // so `_mnemo.updated_at` gets stamped and access stats are
        // preserved.
        let mut new = existing.clone();
        new.metadata
            .insert(MNEMO_META_STATUS.into(), Value::String(to.to_string()));
        let now = memory::now_secs();
        let history_entry = serde_json::json!({ "status": to, "at": now });
        let history = new
            .metadata
            .entry(MNEMO_META_STATUS_HISTORY.to_string())
            .or_insert_with(|| Value::Array(Vec::new()));
        if let Value::Array(arr) = history {
            arr.push(history_entry);
        }
        new.metadata
            .insert(MNEMO_META_UPDATED_AT.into(), Value::Number(now.into()));
        new.id = existing.id;
        new.created_at = existing.created_at;
        self.put(new)?;
        Ok(WriteOutcome::Updated)
    }

    // --- Phase 12.7c: continuation + commit_deltas ------------------
}