Skip to main content

memstead_base/ops/
changes.rs

1//! Backend-neutral entity-level delta surface for `memstead_changes_since`
2//! callers.
3//!
4//! [`ChangeEnvelope`] is the per-entity event shape ("this entity was
5//! added / updated / removed / renamed between cursor X and the
6//! current state"). [`crate::Engine::changes_since`] dispatches per
7//! mount: folder mounts synthesise from `.memstead/changes.jsonl` via
8//! [`folder_changes_since`]; git-branch mounts call the registered
9//! [`crate::GitBranchOps::changes_since`] dispatcher (real tree-diff
10//! with rename detection); archive mounts return an empty report.
11//!
12//! The cursor format is backend-specific and opaque from the caller's
13//! perspective: a commit SHA for git-branch, an RFC-3339 timestamp
14//! for folder, ignored for archive. The empty-tree-SHA sentinel
15//! ([`EMPTY_TREE_SHA`]) is a convention preserved across backends so
16//! "diff against nothing" works without each backend re-inventing
17//! the same first-poll shape.
18//!
19//! `title` and `entity_type` on the envelope variants are populated
20//! by the engine wrapper from the in-memory store (best-effort —
21//! `Removed` envelopes always leave them `None` because the entity
22//! is gone). Backend dispatchers produce id-only envelopes; the
23//! [`crate::Engine::changes_since`] wrapper enriches.
24
25use std::path::Path;
26
27use serde::Serialize;
28
29use crate::backend::BackendError;
30use crate::entity::EntityId;
31use crate::provenance::ProvenanceKind;
32
33/// Canonical git empty-tree hash. Callers without a prior cursor pass
34/// this to get "every entity in the current state as added". Both
35/// the git-branch backend (special-cased to bypass `rev_parse`) and
36/// any future folder-backend implementation honour the same sentinel.
37pub const EMPTY_TREE_SHA: &str = "4b825dc642cb6eb9a060e54bf8d69288fbee4904";
38
39/// Default content-similarity threshold for rename detection (60%).
40/// Callers override per-call via `changes_since`'s `rename_similarity`
41/// parameter; the engine wrapper accepts `[0.1, 1.0]` and emits a
42/// `LIMIT_CLAMPED` warning for out-of-range values. Higher values
43/// miss edited renames; lower values risk false-positive rename
44/// pairing.
45pub const RENAME_SIMILARITY_DEFAULT: f32 = 0.6;
46
47/// Lower bound for `rename_similarity` — anything below 0.1 produces
48/// nearly-random rewrite pairing on a modest diff.
49pub const RENAME_SIMILARITY_MIN: f32 = 0.1;
50
51/// Upper bound for `rename_similarity` — 1.0 means "only paired up
52/// on a byte-identical match"; above that there is no semantic
53/// meaning.
54pub const RENAME_SIMILARITY_MAX: f32 = 1.0;
55
56/// Single delta entry between two snapshots. `Renamed` collapses what
57/// would otherwise appear as a `Removed` + `Added` pair so agents see
58/// one semantic event per filesystem rename.
59///
60/// `title` and `entity_type` are best-effort enrichment from the
61/// engine's in-memory store: present when the backend's diff resolves
62/// to an entity the engine still knows about, `None` otherwise.
63/// `Removed` envelopes always leave both `None` (the entity is gone
64/// by definition); other variants populate when the lookup succeeds.
65#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
66#[serde(tag = "action", rename_all = "lowercase")]
67pub enum ChangeEnvelope {
68    Added {
69        id: EntityId,
70        #[serde(skip_serializing_if = "Option::is_none")]
71        title: Option<String>,
72        #[serde(skip_serializing_if = "Option::is_none")]
73        entity_type: Option<String>,
74    },
75    Updated {
76        id: EntityId,
77        #[serde(skip_serializing_if = "Option::is_none")]
78        title: Option<String>,
79        #[serde(skip_serializing_if = "Option::is_none")]
80        entity_type: Option<String>,
81    },
82    Removed {
83        id: EntityId,
84        #[serde(skip_serializing_if = "Option::is_none")]
85        title: Option<String>,
86        #[serde(skip_serializing_if = "Option::is_none")]
87        entity_type: Option<String>,
88    },
89    Renamed {
90        from_id: EntityId,
91        to_id: EntityId,
92        #[serde(skip_serializing_if = "Option::is_none")]
93        title: Option<String>,
94        #[serde(skip_serializing_if = "Option::is_none")]
95        entity_type: Option<String>,
96    },
97}
98
99impl ChangeEnvelope {
100    /// The id this change sorts and renders under — `to_id` for a
101    /// rename (the surviving entity), the entity id otherwise.
102    pub fn primary_id(&self) -> &str {
103        match self {
104            ChangeEnvelope::Added { id, .. }
105            | ChangeEnvelope::Updated { id, .. }
106            | ChangeEnvelope::Removed { id, .. } => id.as_ref(),
107            ChangeEnvelope::Renamed { to_id, .. } => to_id.as_ref(),
108        }
109    }
110
111    /// The wire `action` verb — the same token the serde tag emits and
112    /// `memstead_changes_since` reports: `added` | `updated` | `removed` |
113    /// `renamed`.
114    pub fn action(&self) -> &'static str {
115        match self {
116            ChangeEnvelope::Added { .. } => "added",
117            ChangeEnvelope::Updated { .. } => "updated",
118            ChangeEnvelope::Removed { .. } => "removed",
119            ChangeEnvelope::Renamed { .. } => "renamed",
120        }
121    }
122
123    /// Best-effort entity type carried on the envelope (`None` on
124    /// `Removed`, or when the store lookup missed).
125    pub fn entity_type(&self) -> Option<&str> {
126        match self {
127            ChangeEnvelope::Added { entity_type, .. }
128            | ChangeEnvelope::Updated { entity_type, .. }
129            | ChangeEnvelope::Removed { entity_type, .. }
130            | ChangeEnvelope::Renamed { entity_type, .. } => entity_type.as_deref(),
131        }
132    }
133
134    /// The same change with `title` / `entity_type` stripped — the
135    /// `ids`-tier projection of a notice entry. The id (and a rename's
136    /// `from_id` / `to_id` pair) is preserved; it is identity, not rich
137    /// detail.
138    fn without_metadata(&self) -> Self {
139        match self {
140            ChangeEnvelope::Added { id, .. } => ChangeEnvelope::Added {
141                id: id.clone(),
142                title: None,
143                entity_type: None,
144            },
145            ChangeEnvelope::Updated { id, .. } => ChangeEnvelope::Updated {
146                id: id.clone(),
147                title: None,
148                entity_type: None,
149            },
150            ChangeEnvelope::Removed { id, .. } => ChangeEnvelope::Removed {
151                id: id.clone(),
152                title: None,
153                entity_type: None,
154            },
155            ChangeEnvelope::Renamed { from_id, to_id, .. } => ChangeEnvelope::Renamed {
156                from_id: from_id.clone(),
157                to_id: to_id.clone(),
158                title: None,
159                entity_type: None,
160            },
161        }
162    }
163}
164
165/// Backend-neutral "what changed" report. The engine wrapper
166/// ([`crate::Engine::changes_since`], landing in a follow-up session)
167/// adds rename-similarity clamping warnings, optional agent-notes
168/// piggyback (git-branch only), and the operator-facing
169/// `mem: String` field on top.
170///
171/// `head` echoes the resolved cursor of the current state — agents
172/// remember it as the next polling cursor so the next call passes it
173/// straight back as `since` without a `memstead_health` round-trip.
174#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
175pub struct BackendChanges {
176    /// The cursor the caller passed in, echoed verbatim.
177    pub since: String,
178    /// The cursor of the current state — opaque to the caller, but
179    /// stable across consecutive polls when nothing has changed.
180    pub head: String,
181    /// Per-entity events. Empty when nothing changed (or when the
182    /// backend has no native diff and inherits the trait's default
183    /// impl — folder + archive today).
184    pub changes: Vec<ChangeEnvelope>,
185    /// Per-commit agent-notes parsed from commit trailers. Empty for
186    /// backends without commit history (folder, archive). Populated
187    /// by the git-branch backend on every `changes_since` call — the
188    /// walk lives inside the backend so the engine has a single source
189    /// of truth for both the rename map (note-driven) and the
190    /// per-commit feed, and the MCP `include_notes` parameter becomes a
191    /// renderer-side filter rather than a separate engine-side trigger.
192    #[serde(default, skip_serializing_if = "Vec::is_empty")]
193    pub notes: Vec<crate::ops::agent_notes::CommitNote>,
194    /// Workspace-level `__MEMSTEAD` ref tip (unified schemas + per-mem
195    /// configs). `None` for backends without commit history; `None`
196    /// also on git-branch backends where the `__MEMSTEAD` ref does not
197    /// (yet) exist — pre-migration workspaces are legitimate.
198    #[serde(default, skip_serializing_if = "Option::is_none")]
199    pub memstead_ref: Option<String>,
200}
201
202impl BackendChanges {
203    /// Empty report at `since` — the default a backend without a
204    /// native diff returns. `head` echoes `since` so the caller's
205    /// cursor stays stable across polls.
206    pub fn empty_at(since: &str) -> Self {
207        Self {
208            since: since.to_string(),
209            head: since.to_string(),
210            changes: Vec::new(),
211            notes: Vec::new(),
212            memstead_ref: None,
213        }
214    }
215}
216
217/// Synthesise per-entity events for a folder-backed mem by reading
218/// `<mem_root>/.memstead/changes.jsonl` and bucketing events by entity.
219///
220/// Net-effect rules per entity:
221/// - Last event = Delete                  → `Removed`
222/// - First event = Create                 → `Added`
223/// - Anything else                        → `Updated`
224///
225/// A `rename` row records only the id the entity now carries (the
226/// ledger's on-disk shape); with `store` present the replay pairs it
227/// with the id that vanished: an id the ledger knows, absent from the
228/// store, never deleted, whose creation instant matches the renamed
229/// entity's `created_date` (a rename keeps it), falling back to the
230/// nearest vanished id before the rename row. A pair inside one window
231/// surfaces as one event: `renamed` with `from_id` and `to_id`, or
232/// `added` under the final id when the entity was also created in the
233/// window. A vanished id that pairs with nothing surfaces as `removed`:
234/// an `added` row for an id no reader can fetch is the one shape the
235/// feed never serves. Without `store` (a bare replay) a rename row
236/// surfaces as `updated` under the new id. `Batch` events have no
237/// entity id and don't contribute envelopes. The cursor is an RFC-3339 timestamp; the
238/// [`EMPTY_TREE_SHA`] sentinel and the empty string mean "from the
239/// beginning". Any other non-parseable cursor **refuses** with the
240/// typed `INVALID_TS_CURSOR:` marker (lifted by the engine to the
241/// `INVALID_CURSOR` code): the folder ledger's timestamps are compared
242/// lexically, and a mutation's `write_id` — fixed-width hex minted
243/// from a nanosecond clock — sorts below every timestamp, so the old
244/// tolerant reading silently replayed the whole history to exactly
245/// the caller who confused the two. `head` echoes the latest
246/// timestamp seen, falling back to `since`.
247///
248/// Envelopes are id-only (`title` / `entity_type` are `None`); the
249/// engine wrapper enriches from its in-memory store.
250/// The store's view the folder replay pairs renames with: for an id
251/// the store serves, its `created_date` as written in the frontmatter;
252/// `None` for an id it does not serve.
253pub type StoreLookup<'a> = &'a dyn Fn(&EntityId) -> Option<String>;
254
255pub fn folder_changes_since(
256    mem_root: &Path,
257    mem: &str,
258    since: &str,
259    store: Option<StoreLookup<'_>>,
260) -> Result<BackendChanges, BackendError> {
261    if !since.is_empty()
262        && since != EMPTY_TREE_SHA
263        && crate::filesystem::changelog::parse_rfc3339_utc(since).is_none()
264    {
265        // Typed marker, same convention as the git backend's
266        // `COMMIT_NOT_FOUND:` — the engine wrapper lifts it to
267        // `EngineError::InvalidTimestampCursor` (code INVALID_CURSOR).
268        return Err(BackendError::Other(format!("INVALID_TS_CURSOR:{since}")));
269    }
270    // The ledger is a file a commit appends to: while a commit of this
271    // mem is cut off, the feed is not read, like every other read that
272    // goes to the mem's files.
273    crate::storage::filesystem::refuse_cut_off_commit(mem_root)?;
274    let log_path = crate::filesystem::changelog::changelog_path(mem_root);
275    let raw = match std::fs::read_to_string(&log_path) {
276        Ok(s) => s,
277        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
278            return Ok(BackendChanges::empty_at(since));
279        }
280        Err(e) => return Err(BackendError::Io(e)),
281    };
282
283    struct Aggregate {
284        first_kind: ProvenanceKind,
285        last_kind: ProvenanceKind,
286    }
287    /// What the whole ledger says about one id, window or not: the
288    /// instant it was created (when the ledger saw it), the instant of
289    /// its last row, and whether a delete row ever closed it.
290    #[derive(Default)]
291    struct Lifetime {
292        created_at: Option<String>,
293        last_at: String,
294        deleted: bool,
295        /// The id's last row is the rename row that named it: it is a
296        /// link in a rename chain, and the next rename continues from it.
297        named_by_rename: bool,
298    }
299    let mut by_entity: std::collections::BTreeMap<String, Aggregate> =
300        std::collections::BTreeMap::new();
301    let mut lifetimes: std::collections::BTreeMap<String, Lifetime> =
302        std::collections::BTreeMap::new();
303    let mut rename_rows: Vec<(String, String)> = Vec::new();
304    let mut max_ts: Option<String> = None;
305
306    let cursor_opt: Option<&str> = if since.is_empty() || since == EMPTY_TREE_SHA {
307        None
308    } else {
309        Some(since)
310    };
311
312    for line in raw.lines() {
313        let trimmed = line.trim();
314        if trimmed.is_empty() {
315            continue;
316        }
317        let value: serde_json::Value = match serde_json::from_str(trimmed) {
318            Ok(v) => v,
319            Err(_) => continue,
320        };
321        let ts_str = value.get("ts").and_then(|v| v.as_str()).unwrap_or("");
322        let kind = match value
323            .get("kind")
324            .and_then(|v| v.as_str())
325            .and_then(ProvenanceKind::parse)
326        {
327            Some(k) => k,
328            None => continue,
329        };
330        let entity_id = match value.get("entity").and_then(|v| v.as_str()) {
331            Some(s) if !s.is_empty() => s.to_string(),
332            _ => continue,
333        };
334        {
335            let life = lifetimes.entry(entity_id.clone()).or_default();
336            // A create revives an id a delete retired: its lifetime is the
337            // newest one, and its creation instant is that create's.
338            if matches!(kind, ProvenanceKind::Create) {
339                life.created_at = Some(ts_str.to_string());
340                life.deleted = false;
341            }
342            if ts_str >= life.last_at.as_str() {
343                life.last_at = ts_str.to_string();
344                life.named_by_rename = matches!(kind, ProvenanceKind::Rename);
345            }
346            if matches!(kind, ProvenanceKind::Delete) {
347                life.deleted = true;
348            }
349        }
350        if let Some(c) = cursor_opt
351            && ts_str <= c
352        {
353            continue;
354        }
355        if matches!(kind, ProvenanceKind::Rename) {
356            rename_rows.push((ts_str.to_string(), entity_id.clone()));
357        }
358
359        if max_ts.as_deref().is_none_or(|m| ts_str > m) {
360            max_ts = Some(ts_str.to_string());
361        }
362
363        by_entity
364            .entry(entity_id)
365            .and_modify(|agg| {
366                agg.last_kind = kind;
367            })
368            .or_insert(Aggregate {
369                first_kind: kind,
370                last_kind: kind,
371            });
372    }
373
374    // Pair every rename row in the window with the id that vanished
375    // for it, when the store can say which ids still exist, then
376    // compose the pairs into chains: a -> b -> c inside one window is
377    // one rename from a to c, and b, a name no reader ever held for
378    // long, surfaces nowhere.
379    let mut links: Vec<(String, String)> = Vec::new(); // (from, to), in row order
380    if let Some(lookup) = store {
381        let parse = |s: &str| match s.split_once("--") {
382            Some((v, slug)) if v == mem => Some(EntityId::new(v, slug)),
383            _ => None,
384        };
385        let exists = |name: &str| parse(name).and_then(|id| lookup(&id));
386        let mut taken: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
387        rename_rows.sort();
388        for (rename_ts, new_name) in &rename_rows {
389            let vanished: Vec<(&String, &Lifetime)> = lifetimes
390                .iter()
391                .filter(|(name, life)| {
392                    *name != new_name
393                        && !life.deleted
394                        && !taken.contains(*name)
395                        && life.last_at.as_str() < rename_ts.as_str()
396                        && parse(name).is_some()
397                        && exists(name).is_none()
398                })
399                .collect();
400            // The renamed entity keeps its creation instant: when the
401            // store serves the new id, the vanished id created at that
402            // instant is the origin, unless the instant is ambiguous.
403            let same_instant: Vec<&String> = match exists(new_name) {
404                Some(created_date) => vanished
405                    .iter()
406                    .filter(|(_, life)| {
407                        life.created_at
408                            .as_deref()
409                            .is_some_and(|c| same_instant(c, &created_date))
410                    })
411                    .map(|(name, _)| *name)
412                    .collect(),
413                None => Vec::new(),
414            };
415            let nearest: Option<String> = vanished
416                .iter()
417                .max_by(|a, b| a.1.last_at.cmp(&b.1.last_at))
418                .map(|(name, _)| (*name).clone());
419            // A vanished id that a rename row named (inside this window
420            // or before it) is a chain link: the row after it continues
421            // the chain, whatever the origin's creation instant says.
422            let continues_chain = nearest
423                .as_deref()
424                .is_some_and(|n| lifetimes.get(n).is_some_and(|l| l.named_by_rename));
425            let from = if continues_chain {
426                nearest
427            } else {
428                match same_instant.as_slice() {
429                    [one] => Some((*one).clone()),
430                    _ => nearest,
431                }
432            };
433            if let Some(from) = from {
434                taken.insert(from.clone());
435                links.push((from, new_name.clone()));
436            }
437        }
438    }
439    // Chains: an origin is a `from` no link renames into; follow it
440    // to the name the entity carries now.
441    let mut paired: Vec<(String, String, Vec<String>)> = Vec::new(); // (origin, final, members)
442    for (from, _) in &links {
443        if links.iter().any(|(_, to)| to == from) {
444            continue;
445        }
446        let mut members = vec![from.clone()];
447        let mut current = from.clone();
448        while let Some((_, to)) = links.iter().find(|(f, _)| *f == current) {
449            members.push(to.clone());
450            current = to.clone();
451        }
452        paired.push((from.clone(), current, members));
453    }
454
455    let mut changes: Vec<ChangeEnvelope> = Vec::with_capacity(by_entity.len());
456    for (from, to, members) in &paired {
457        let from_agg = by_entity.remove(from);
458        for member in members {
459            by_entity.remove(member);
460        }
461        let (Some(from_id), Some(to_id)) = (
462            from.split_once("--").map(|(v, s)| EntityId::new(v, s)),
463            to.split_once("--").map(|(v, s)| EntityId::new(v, s)),
464        ) else {
465            continue;
466        };
467        let born_in_window =
468            from_agg.is_some_and(|a| matches!(a.first_kind, ProvenanceKind::Create));
469        changes.push(if born_in_window {
470            ChangeEnvelope::Added {
471                id: to_id,
472                title: None,
473                entity_type: None,
474            }
475        } else {
476            ChangeEnvelope::Renamed {
477                from_id,
478                to_id,
479                title: None,
480                entity_type: None,
481            }
482        });
483    }
484    for (entity_str, agg) in by_entity {
485        let id = match entity_str.split_once("--") {
486            Some((v, slug)) if v == mem => EntityId::new(v, slug),
487            _ => continue,
488        };
489        // An id the store no longer serves and no delete row closed
490        // vanished without a pair: it is gone for every reader.
491        if let Some(lookup) = store
492            && !matches!(agg.last_kind, ProvenanceKind::Delete)
493            && lookup(&id).is_none()
494        {
495            changes.push(ChangeEnvelope::Removed {
496                id,
497                title: None,
498                entity_type: None,
499            });
500            continue;
501        }
502        let envelope = match (agg.first_kind, agg.last_kind) {
503            (_, ProvenanceKind::Delete) => ChangeEnvelope::Removed {
504                id,
505                title: None,
506                entity_type: None,
507            },
508            (ProvenanceKind::Create, _) => ChangeEnvelope::Added {
509                id,
510                title: None,
511                entity_type: None,
512            },
513            _ => ChangeEnvelope::Updated {
514                id,
515                title: None,
516                entity_type: None,
517            },
518        };
519        changes.push(envelope);
520    }
521
522    changes.sort_by(|a, b| a.primary_id().cmp(b.primary_id()));
523
524    Ok(BackendChanges {
525        since: since.to_string(),
526        head: max_ts.unwrap_or_else(|| since.to_string()),
527        changes,
528        notes: Vec::new(),
529        memstead_ref: None,
530    })
531}
532
533/// The newest write per entity id among `notes`, which run newest
534/// first (the order a git-branch backend's change feed returns them
535/// in): for each id a note names, the identity and note of the first
536/// note that names it. A note names the entity of its subject and
537/// every id its multi-entity trailers list. A batch commit records its
538/// per-entry notes as `<id>: <note>` lines: each entity gets its own
539/// line there and an entity without one gets no note.
540pub fn newest_writes_from_notes(
541    notes: &[crate::ops::agent_notes::CommitNote],
542) -> std::collections::BTreeMap<String, NewestWrite> {
543    let mut writes = std::collections::BTreeMap::new();
544    for note in notes {
545        // The subject of a rename names two ids, `<old> → <new>`: the
546        // write is to the entity under either name.
547        // (A batch's subject names a count, not an id: only what has
548        // the shape of an id is taken.)
549        let subject_ids = note
550            .entity_id
551            .iter()
552            .flat_map(|subject| subject.split(" → "))
553            .filter(|part| part.contains("--") && !part.contains(' '))
554            .map(str::to_string);
555        let named: Vec<String> = subject_ids
556            .chain(note.entity_ids.iter().cloned())
557            .chain(note.created_ids.iter().cloned())
558            .collect();
559        let batch = note
560            .tool_verb
561            .as_deref()
562            .is_some_and(|verb| verb.starts_with("batch"));
563        for id in &named {
564            if writes.contains_key(id) {
565                continue;
566            }
567            let text = match (&note.note, batch) {
568                (Some(joined), true) => batch_entry_note(joined, id, &named),
569                (text, _) => text.clone(),
570            };
571            writes.insert(
572                id.clone(),
573                NewestWrite {
574                    identity: note.identity.clone(),
575                    note: text.map(bounded_note),
576                },
577            );
578        }
579    }
580    writes
581}
582
583/// The note one entity's entry declared in a batch, from the batch
584/// commit's joined note ([`crate::vcs::batch_note_line`]): the text
585/// after `<id>: ` on the line of that id, with the indented lines that
586/// follow it, the indent removed. `None` when the batch has no line for
587/// the id. A record written before the join indented its continuation
588/// lines is read as it was meant where that is unambiguous: an
589/// unindented line that begins no entity's entry continues the entry
590/// above it.
591fn batch_entry_note(joined: &str, id: &str, ids: &[String]) -> Option<String> {
592    let mut mine: Vec<&str> = Vec::new();
593    let mut owner: Option<&str> = None;
594    for line in joined.lines() {
595        // An indented line continues the entry above it, whatever it
596        // says.
597        if let (Some(current), Some(rest)) = (owner, line.strip_prefix("  ")) {
598            if current == id {
599                mine.push(rest);
600            }
601            continue;
602        }
603        let begins = ids.iter().find_map(|candidate| {
604            line.strip_prefix(candidate.as_str())
605                .and_then(|rest| rest.strip_prefix(": "))
606                .map(|rest| (candidate.as_str(), rest))
607        });
608        match begins {
609            Some((candidate, rest)) => {
610                owner = Some(candidate);
611                if candidate == id {
612                    mine.push(rest);
613                }
614            }
615            None if owner == Some(id) => mine.push(line),
616            None => {}
617        }
618    }
619    (!mine.is_empty()).then(|| mine.join("\n"))
620}
621
622/// A note as a notice entry carries it: whole up to the length a write
623/// may declare ([`crate::mem_management::NOTE_MAX_LEN`]), cut there
624/// with an ellipsis when a record holds more, so fifty entries stay a
625/// payload of bounded size.
626fn bounded_note(note: String) -> String {
627    let max = crate::mem_management::NOTE_MAX_LEN;
628    if note.chars().count() <= max {
629        return note;
630    }
631    let mut cut: String = note.chars().take(max).collect();
632    cut.push('…');
633    cut
634}
635
636/// The newest write per entity id in a folder mem's change ledger after
637/// `since` (a ledger timestamp; empty for the whole ledger): the
638/// identity and note of the last row that names the id. A ledger that
639/// cannot be read yields nothing.
640pub fn folder_newest_writes(
641    mem_root: &Path,
642    since: &str,
643) -> std::collections::BTreeMap<String, NewestWrite> {
644    let mut writes = std::collections::BTreeMap::new();
645    let log_path = crate::filesystem::changelog::changelog_path(mem_root);
646    let Ok(raw) = std::fs::read_to_string(&log_path) else {
647        return writes;
648    };
649    let cursor = (!since.is_empty() && since != EMPTY_TREE_SHA).then_some(since);
650    let mut newest_at: std::collections::BTreeMap<String, String> =
651        std::collections::BTreeMap::new();
652    for line in raw.lines() {
653        let Ok(value) = serde_json::from_str::<serde_json::Value>(line.trim()) else {
654            continue;
655        };
656        let ts = value.get("ts").and_then(|v| v.as_str()).unwrap_or("");
657        if cursor.is_some_and(|c| ts <= c) {
658            continue;
659        }
660        let Some(entity) = value
661            .get("entity")
662            .and_then(|v| v.as_str())
663            .filter(|s| !s.is_empty())
664        else {
665            continue;
666        };
667        if newest_at.get(entity).is_some_and(|at| ts < at.as_str()) {
668            continue;
669        }
670        newest_at.insert(entity.to_string(), ts.to_string());
671        let text = |key: &str| {
672            value
673                .get(key)
674                .and_then(|v| v.as_str())
675                .filter(|s| !s.is_empty())
676                .map(str::to_string)
677        };
678        writes.insert(
679            entity.to_string(),
680            NewestWrite {
681                identity: text("identity"),
682                note: text("note").map(bounded_note),
683            },
684        );
685    }
686    writes
687}
688
689/// Whether a ledger timestamp and an entity's `created_date` name the
690/// same instant at the coarser of the two precisions (the ledger
691/// carries milliseconds, a frontmatter date seconds or a bare day).
692fn same_instant(ledger_ts: &str, created_date: &str) -> bool {
693    let norm = |s: &str| s.trim_end_matches('Z').replace('T', " ");
694    let a = norm(ledger_ts);
695    let b = norm(created_date);
696    let n = a.len().min(b.len());
697    n >= 10 && a[..n] == b[..n]
698}
699
700/// Engine-wrapper-level "what changed" shape returned by
701/// [`crate::Engine::changes_since`].
702///
703/// Adds the operator-facing `mem: String` and `warnings:
704/// Vec<WarningHint>` that the engine layer owns (rename-similarity
705/// clamping, etc.) on top of [`BackendChanges`]. Envelope `title` /
706/// `entity_type` fields are enriched from the engine's in-memory
707/// store (best-effort — `Removed` envelopes always leave them
708/// `None`; missing-from-store entities also leave them `None`).
709///
710/// Optional `notes` and `memstead_ref` carry per-commit agent-notes and
711/// the workspace-level `__MEMSTEAD` ref tip when the caller passes
712/// `include_notes: true`. Both fields stay `None` on folder + archive
713/// mounts (no commit history to read). MCP and CLI handlers populate
714/// them for git-branch mounts by pattern-matching on
715/// [`crate::workspace::MountStorage::GitBranch`] and calling
716/// `memstead_git_branch::ops::agent_notes::agent_notes_since` directly.
717#[derive(Debug, Clone, Serialize)]
718pub struct ChangesReport {
719    pub mem: String,
720    pub since: String,
721    pub head: String,
722    pub changes: Vec<ChangeEnvelope>,
723    #[serde(default, skip_serializing_if = "Vec::is_empty")]
724    pub warnings: Vec<crate::ops::WarningHint>,
725    /// Per-commit agent-notes parsed from commit trailers (git-branch
726    /// backend only). `None` when `include_notes` is false or the
727    /// backend has no commit history.
728    #[serde(default, skip_serializing_if = "Option::is_none")]
729    pub notes: Option<Vec<crate::ops::agent_notes::CommitNote>>,
730    /// Workspace-level `__MEMSTEAD` ref tip (unified schemas + per-mem
731    /// configs). `None` when `include_notes` is false or the
732    /// workspace has not been migrated to the unified layout yet.
733    #[serde(default, skip_serializing_if = "Option::is_none")]
734    pub memstead_ref: Option<String>,
735}
736
737// ---- mem_changed notice (reload-before-op awareness contract) ----
738
739/// Max changed-entity count rendered with full per-entity detail
740/// (id + change-kind + title + type) before the notice degrades to
741/// id+kind only. Rich detail is the expensive part of the payload; an
742/// id is cheap. Below this threshold the notice is `mode: "detailed"`.
743pub(crate) const NOTICE_DETAILED_MAX: usize = 50;
744
745/// Max changed-entity count that still lists every changed id inline
746/// (id + change-kind, `mode: "ids"`). The inline id list is exactly
747/// what lets the agent run its own relevance check as a local
748/// set-intersection against its context in zero round-trips, so it
749/// survives well past the rich-detail threshold. Above this, the
750/// notice collapses to `mode: "counts"` and points the agent at
751/// `memstead_changes_since` for the full delta.
752const NOTICE_IDS_MAX: usize = 500;
753
754/// Per-change-kind counts in `mode: "counts"`. Field names track the
755/// `memstead_changes_since` action vocabulary (`updated`, not `modified`)
756/// so the notice and the recovery surface speak one language.
757#[derive(Debug, Clone, Serialize, PartialEq, Eq, Default)]
758pub struct NoticeByChange {
759    pub added: usize,
760    pub updated: usize,
761    pub removed: usize,
762    pub renamed: usize,
763}
764
765/// The size-graceful body of a [`MemChangedNotice`]. Internally
766/// tagged on `mode` so a caller decodes one stable shape and branches
767/// on the discriminator — no request-shape-dependent polymorphism.
768///
769/// The `detailed` and `ids` tiers carry [`ChangeEnvelope`]s — the exact
770/// per-entity shape `memstead_changes_since` emits (same `action`
771/// vocabulary, `from_id` / `to_id` on renames). Sharing the type is the
772/// point: an agent that follows the notice's `self_inform` to
773/// `memstead_changes_since` decodes one shape on both surfaces, and the two
774/// delta representations cannot drift apart in vocabulary or richness.
775#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
776#[serde(tag = "mode", rename_all = "lowercase")]
777pub enum NoticeChanges {
778    /// Small delta — full per-entity [`ChangeEnvelope`]s with `title` /
779    /// `entity_type` enrichment, each with who wrote the entity last
780    /// inside the notice's range and why ([`NoticeEntry`]).
781    Detailed { entries: Vec<NoticeEntry> },
782    /// Medium delta — every changed entity inline as a [`ChangeEnvelope`]
783    /// with `title` / `entity_type` stripped. The id list (and a
784    /// rename's `from_id` / `to_id`) stays complete; only rich detail is
785    /// dropped once the delta exceeds [`NOTICE_DETAILED_MAX`].
786    Ids { entries: Vec<ChangeEnvelope> },
787    /// Mass change — counts by type and by change-kind, plus the
788    /// `memstead_changes_since(since=<from_head>)` instruction for the
789    /// full delta. `counts` keys are entity types (omitted for
790    /// envelopes whose type the store couldn't resolve, e.g. removed).
791    Counts {
792        counts: std::collections::BTreeMap<String, usize>,
793        by_change: NoticeByChange,
794        self_inform: String,
795    },
796}
797
798/// Who wrote an entity last inside a range, and why: the declared
799/// identity and the note of the newest write that names the entity.
800/// Either is `None` when that write declared none; a value never comes
801/// from an older write.
802#[derive(Debug, Clone, Default, PartialEq, Eq)]
803pub struct NewestWrite {
804    pub identity: Option<String>,
805    pub note: Option<String>,
806}
807
808/// One entry of a notice's `detailed` tier: the change as
809/// `memstead_changes_since` reports it, plus the writer and the note of
810/// the newest write to that entity inside the notice's range, so a
811/// reader that is told a mem moved need not make a second call to learn
812/// by whom and why. Either key is absent from the wire when that write
813/// declared none. The other tiers, and the entries
814/// `memstead_changes_since` returns, carry neither: the walk over the
815/// range's writes is the cost the tiers exist to avoid.
816///
817/// Derefs to its [`ChangeEnvelope`], so a reader of the change itself
818/// reads an entry as it reads an envelope.
819#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
820pub struct NoticeEntry {
821    #[serde(flatten)]
822    pub change: ChangeEnvelope,
823    #[serde(skip_serializing_if = "Option::is_none")]
824    pub identity: Option<String>,
825    #[serde(skip_serializing_if = "Option::is_none")]
826    pub note: Option<String>,
827}
828
829impl std::ops::Deref for NoticeEntry {
830    type Target = ChangeEnvelope;
831    fn deref(&self) -> &ChangeEnvelope {
832        &self.change
833    }
834}
835
836/// Non-blocking "the mem moved under you" notice, attached to a
837/// response only when a reload happened during the operation. The
838/// operation's own result/error rides alongside — this is purely the
839/// objective "what else changed" delta, scaled by size, for the agent
840/// to judge relevance against (the engine does not filter to a
841/// per-agent interest model).
842///
843/// Built by [`MemChangedNotice::from_delta`] from the
844/// `from_head → to_head` [`ChangeEnvelope`] list a reload produced.
845/// Entries are ordered lexically by id so two notices over the same
846/// delta are byte-identical.
847#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
848pub struct MemChangedNotice {
849    pub mem: String,
850    pub from_head: String,
851    pub to_head: String,
852    pub changes: NoticeChanges,
853}
854
855impl MemChangedNotice {
856    /// Build a notice from the per-entity delta between `from_head`
857    /// and `to_head`, degrading by size:
858    /// `detailed` (≤ [`NOTICE_DETAILED_MAX`]) → `ids`
859    /// (≤ [`NOTICE_IDS_MAX`]) → `counts`. Entries are sorted lexically
860    /// by primary id (the `to_id` for a rename) so the output is
861    /// deterministic regardless of input order.
862    pub fn from_delta(
863        mem: String,
864        from_head: String,
865        to_head: String,
866        changes: Vec<ChangeEnvelope>,
867    ) -> Self {
868        Self::from_delta_with_writes(
869            mem,
870            from_head,
871            to_head,
872            changes,
873            &std::collections::BTreeMap::new(),
874        )
875    }
876
877    /// [`Self::from_delta`] with the newest write per entity id
878    /// ([`NewestWrite`]), which the `detailed` tier carries on each
879    /// entry. An id without an entry in `writes`, and every entry of
880    /// the other tiers, carries neither key. For a rename the write is
881    /// looked up under the id the entity has now, then under the one it
882    /// had.
883    pub fn from_delta_with_writes(
884        mem: String,
885        from_head: String,
886        to_head: String,
887        mut changes: Vec<ChangeEnvelope>,
888        writes: &std::collections::BTreeMap<String, NewestWrite>,
889    ) -> Self {
890        changes.sort_by(|a, b| a.primary_id().cmp(b.primary_id()));
891        let n = changes.len();
892        let body = if n <= NOTICE_DETAILED_MAX {
893            NoticeChanges::Detailed {
894                entries: changes
895                    .into_iter()
896                    .map(|change| {
897                        let write = writes.get(change.primary_id()).or_else(|| match &change {
898                            ChangeEnvelope::Renamed { from_id, .. } => {
899                                writes.get(AsRef::<str>::as_ref(from_id))
900                            }
901                            _ => None,
902                        });
903                        NoticeEntry {
904                            identity: write.and_then(|w| w.identity.clone()),
905                            note: write.and_then(|w| w.note.clone()),
906                            change,
907                        }
908                    })
909                    .collect(),
910            }
911        } else if n <= NOTICE_IDS_MAX {
912            NoticeChanges::Ids {
913                entries: changes
914                    .iter()
915                    .map(ChangeEnvelope::without_metadata)
916                    .collect(),
917            }
918        } else {
919            let mut counts: std::collections::BTreeMap<String, usize> =
920                std::collections::BTreeMap::new();
921            let mut by_change = NoticeByChange::default();
922            for env in &changes {
923                match env {
924                    ChangeEnvelope::Added { .. } => by_change.added += 1,
925                    ChangeEnvelope::Updated { .. } => by_change.updated += 1,
926                    ChangeEnvelope::Removed { .. } => by_change.removed += 1,
927                    ChangeEnvelope::Renamed { .. } => by_change.renamed += 1,
928                }
929                if let Some(t) = env.entity_type() {
930                    *counts.entry(t.to_string()).or_default() += 1;
931                }
932            }
933            NoticeChanges::Counts {
934                counts,
935                by_change,
936                self_inform: format!("call memstead_changes_since(since={from_head})"),
937            }
938        };
939        Self {
940            mem,
941            from_head,
942            to_head,
943            changes: body,
944        }
945    }
946
947    /// Total changed-entity count this notice describes, across every
948    /// degradation tier. The MCP layer uses it to populate the
949    /// `entities_loaded` field of a `MemReloaded` warning synthesised
950    /// for an error response — a mutation reloads *inside* the engine
951    /// and surfaces only the stashed notice, not a `WarningHint`, so the
952    /// error-text warning line is reconstructed from the notice itself.
953    pub fn entity_count(&self) -> usize {
954        match &self.changes {
955            NoticeChanges::Detailed { entries } => entries.len(),
956            NoticeChanges::Ids { entries } => entries.len(),
957            NoticeChanges::Counts { by_change, .. } => {
958                by_change.added + by_change.updated + by_change.removed + by_change.renamed
959            }
960        }
961    }
962}
963
964#[cfg(test)]
965mod tests {
966    use super::*;
967
968    #[test]
969    fn empty_at_echoes_cursor() {
970        let r = BackendChanges::empty_at("abc");
971        assert_eq!(r.since, "abc");
972        assert_eq!(r.head, "abc");
973        assert!(r.changes.is_empty());
974    }
975
976    #[test]
977    fn changes_report_omits_notes_and_memstead_ref_when_none() {
978        // Default-shaped report (no include_notes) — both Optional
979        // fields skip-serialize-when-none. Consumers that don't
980        // request notes see no notes/memstead_ref keys on the wire.
981        let r = ChangesReport {
982            mem: "specs".to_string(),
983            since: "abc".to_string(),
984            head: "def".to_string(),
985            changes: Vec::new(),
986            warnings: Vec::new(),
987            notes: None,
988            memstead_ref: None,
989        };
990        let json = serde_json::to_string(&r).unwrap();
991        assert!(
992            !json.contains("\"notes\""),
993            "notes must be omitted when None: {json}"
994        );
995        assert!(
996            !json.contains("\"memstead_ref\""),
997            "memstead_ref must be omitted when None: {json}"
998        );
999    }
1000
1001    #[test]
1002    fn changes_report_emits_notes_and_memstead_ref_when_some() {
1003        // When include_notes populates the fields, wire shape carries
1004        // both keys nested at the report root. `memstead_ref` is the SHA
1005        // of `refs/heads/__MEMSTEAD` (unified schemas + per-mem configs).
1006        let r = ChangesReport {
1007            mem: "specs".to_string(),
1008            since: "abc".to_string(),
1009            head: "def".to_string(),
1010            changes: Vec::new(),
1011            warnings: Vec::new(),
1012            notes: Some(Vec::new()),
1013            memstead_ref: Some("aabbccdd".to_string()),
1014        };
1015        let json = serde_json::to_string(&r).unwrap();
1016        assert!(
1017            json.contains("\"notes\":["),
1018            "notes must be present: {json}"
1019        );
1020        assert!(
1021            json.contains("\"memstead_ref\":\"aabbccdd\""),
1022            "memstead_ref must be present and carry the SHA: {json}"
1023        );
1024    }
1025
1026    #[test]
1027    fn change_envelope_serializes_action_tag() {
1028        // Confirms the `action: "added" | "updated" | "removed" |
1029        // "renamed"` discriminator is emitted as the wire shape MCP
1030        // callers expect — same as full's existing ChangeEnvelope.
1031        let env = ChangeEnvelope::Added {
1032            id: EntityId::new("specs", "hello"),
1033            title: Some("Hello".to_string()),
1034            entity_type: Some("spec".to_string()),
1035        };
1036        let json = serde_json::to_string(&env).unwrap();
1037        assert!(json.contains(r#""action":"added""#));
1038        assert!(json.contains(r#""title":"Hello""#));
1039        assert!(json.contains(r#""entity_type":"spec""#));
1040    }
1041
1042    #[test]
1043    fn change_envelope_skips_none_metadata_fields() {
1044        let env = ChangeEnvelope::Removed {
1045            id: EntityId::new("specs", "gone"),
1046            title: None,
1047            entity_type: None,
1048        };
1049        let json = serde_json::to_string(&env).unwrap();
1050        assert!(json.contains(r#""action":"removed""#));
1051        assert!(!json.contains("\"title\""));
1052        assert!(!json.contains("\"entity_type\""));
1053    }
1054
1055    #[test]
1056    fn change_envelope_renamed_carries_both_ids() {
1057        let env = ChangeEnvelope::Renamed {
1058            from_id: EntityId::new("specs", "old"),
1059            to_id: EntityId::new("specs", "new"),
1060            title: Some("New".to_string()),
1061            entity_type: Some("spec".to_string()),
1062        };
1063        let json = serde_json::to_string(&env).unwrap();
1064        assert!(json.contains(r#""action":"renamed""#));
1065        assert!(json.contains(r#""from_id":"specs--old""#));
1066        assert!(json.contains(r#""to_id":"specs--new""#));
1067    }
1068
1069    // ---- MemChangedNotice degradation + determinism --------------
1070
1071    /// `n` added envelopes with predictable ids (`e-0000` …) so tests
1072    /// can assert ordering and inline-id presence.
1073    fn added_envelopes(n: usize) -> Vec<ChangeEnvelope> {
1074        (0..n)
1075            .map(|i| ChangeEnvelope::Added {
1076                id: EntityId::new("specs", &format!("e-{i:04}")),
1077                title: Some(format!("Entity {i}")),
1078                entity_type: Some("spec".to_string()),
1079            })
1080            .collect()
1081    }
1082
1083    /// The detailed tier carries, per entry, the newest write to its
1084    /// entity: the identity and note that write declared, each key
1085    /// absent when it declared none. Two notices over the same delta
1086    /// are byte-identical, and the larger tiers carry neither key.
1087    #[test]
1088    fn a_detailed_entry_names_the_newest_write_and_drops_what_was_not_declared() {
1089        let changes = vec![
1090            ChangeEnvelope::Updated {
1091                id: EntityId::new("specs", "bbb"),
1092                title: Some("B".to_string()),
1093                entity_type: Some("spec".to_string()),
1094            },
1095            ChangeEnvelope::Added {
1096                id: EntityId::new("specs", "aaa"),
1097                title: Some("A".to_string()),
1098                entity_type: Some("spec".to_string()),
1099            },
1100            ChangeEnvelope::Renamed {
1101                from_id: EntityId::new("specs", "old"),
1102                to_id: EntityId::new("specs", "new"),
1103                title: None,
1104                entity_type: None,
1105            },
1106            ChangeEnvelope::Removed {
1107                id: EntityId::new("specs", "zzz"),
1108                title: None,
1109                entity_type: None,
1110            },
1111        ];
1112        let write = |identity: Option<&str>, note: Option<&str>| NewestWrite {
1113            identity: identity.map(str::to_string),
1114            note: note.map(str::to_string),
1115        };
1116        let writes: std::collections::BTreeMap<String, NewestWrite> = [
1117            (
1118                "specs--aaa".to_string(),
1119                write(Some("xavier"), Some("made it")),
1120            ),
1121            ("specs--bbb".to_string(), write(None, Some("no name"))),
1122            // A rename's write is found under the id the entity had.
1123            ("specs--old".to_string(), write(Some("yolanda"), None)),
1124        ]
1125        .into_iter()
1126        .collect();
1127        let notice = MemChangedNotice::from_delta_with_writes(
1128            "specs".to_string(),
1129            "H0".to_string(),
1130            "H1".to_string(),
1131            changes.clone(),
1132            &writes,
1133        );
1134        let value = serde_json::to_value(&notice).unwrap();
1135        let entries = value["changes"]["entries"].as_array().unwrap();
1136        assert_eq!(entries.len(), 4);
1137        assert_eq!(entries[0]["id"], "specs--aaa");
1138        assert_eq!(entries[0]["action"], "added");
1139        assert_eq!(entries[0]["identity"], "xavier");
1140        assert_eq!(entries[0]["note"], "made it");
1141        assert_eq!(entries[1]["id"], "specs--bbb");
1142        assert_eq!(entries[1]["note"], "no name");
1143        assert!(entries[1].get("identity").is_none(), "{}", entries[1]);
1144        assert_eq!(entries[2]["to_id"], "specs--new");
1145        assert_eq!(entries[2]["identity"], "yolanda");
1146        assert!(entries[2].get("note").is_none(), "{}", entries[2]);
1147        // No write known for the id: neither key, not an empty string.
1148        assert_eq!(entries[3]["id"], "specs--zzz");
1149        assert!(entries[3].get("identity").is_none() && entries[3].get("note").is_none());
1150
1151        // The same delta in another order: the same bytes.
1152        let mut reversed = changes;
1153        reversed.reverse();
1154        let again = MemChangedNotice::from_delta_with_writes(
1155            "specs".to_string(),
1156            "H0".to_string(),
1157            "H1".to_string(),
1158            reversed,
1159            &writes,
1160        );
1161        assert_eq!(
1162            serde_json::to_string(&notice).unwrap(),
1163            serde_json::to_string(&again).unwrap()
1164        );
1165
1166        // Past the detailed tier the writes are not carried.
1167        let many = added_envelopes(NOTICE_DETAILED_MAX + 1);
1168        let all: std::collections::BTreeMap<String, NewestWrite> = many
1169            .iter()
1170            .map(|e| (e.primary_id().to_string(), write(Some("xavier"), Some("n"))))
1171            .collect();
1172        let ids = MemChangedNotice::from_delta_with_writes(
1173            "specs".to_string(),
1174            "H0".to_string(),
1175            "H1".to_string(),
1176            many,
1177            &all,
1178        );
1179        let json = serde_json::to_string(&ids).unwrap();
1180        assert!(json.contains(r#""mode":"ids""#));
1181        assert!(
1182            !json.contains("identity") && !json.contains("\"note\""),
1183            "{json}"
1184        );
1185    }
1186
1187    /// The newest write per id among commit notes that run newest
1188    /// first: the first note that names an id decides, a rename's
1189    /// subject names both ids, and a multi-entity commit names every
1190    /// id its trailer lists.
1191    #[test]
1192    fn the_newest_note_that_names_an_id_decides_its_write() {
1193        let note = |subject_id: &str, ids: &[&str], identity: Option<&str>, text: Option<&str>| {
1194            crate::ops::agent_notes::CommitNote {
1195                mem: "specs".to_string(),
1196                sha: "0".repeat(40),
1197                subject: format!("memstead: write {subject_id}"),
1198                tool_verb: None,
1199                entity_id: Some(subject_id.to_string()),
1200                note: text.map(str::to_string),
1201                actor: None,
1202                tool: None,
1203                client: None,
1204                logical_operation_id: None,
1205                role: None,
1206                identity: identity.map(str::to_string),
1207                entity_ids: ids.iter().map(|s| s.to_string()).collect(),
1208                merged_by: None,
1209                proposal: None,
1210                created_ids: Vec::new(),
1211                co_writers: Vec::new(),
1212                unattributed_writes: Vec::new(),
1213                merge_renames: Vec::new(),
1214                timestamp: 0,
1215            }
1216        };
1217        let notes = vec![
1218            // Newest: a rename that also rewrote a referrer, no note.
1219            note(
1220                "specs--bee → specs--bumble",
1221                &["specs--aye"],
1222                Some("yolanda"),
1223                None,
1224            ),
1225            // Older: an update of the referrer.
1226            note("specs--aye", &[], Some("xavier"), Some("older")),
1227            note("specs--other", &[], None, Some("only a note")),
1228        ];
1229        let writes = newest_writes_from_notes(&notes);
1230        for id in ["specs--bee", "specs--bumble", "specs--aye"] {
1231            assert_eq!(writes[id].identity.as_deref(), Some("yolanda"), "{id}");
1232            assert_eq!(writes[id].note, None, "{id}: never the older write's note");
1233        }
1234        assert_eq!(writes["specs--other"].identity, None);
1235        assert_eq!(writes["specs--other"].note.as_deref(), Some("only a note"));
1236    }
1237
1238    /// A batch commit joins its per-entry notes as `<id>: <note>` lines.
1239    /// Each entity's entry names its own note, an entity whose batch
1240    /// entry declared none gets none, and no entry carries the joined
1241    /// text. A note longer than a write may declare is cut.
1242    #[test]
1243    fn a_batch_gives_each_entity_its_own_note_and_a_note_has_a_bound() {
1244        let batch = crate::ops::agent_notes::CommitNote {
1245            mem: "specs".to_string(),
1246            sha: "0".repeat(40),
1247            subject: "memstead: batch-update (3 entities)".to_string(),
1248            tool_verb: Some("batch-update".to_string()),
1249            entity_id: Some("(3 entities)".to_string()),
1250            note: Some(
1251                "specs--one: note for one\nand its second line\nspecs--three: Reason: three"
1252                    .to_string(),
1253            ),
1254            actor: None,
1255            tool: None,
1256            client: None,
1257            logical_operation_id: None,
1258            role: None,
1259            identity: Some("yolanda".to_string()),
1260            entity_ids: vec![
1261                "specs--one".to_string(),
1262                "specs--two".to_string(),
1263                "specs--three".to_string(),
1264            ],
1265            merged_by: None,
1266            proposal: None,
1267            created_ids: Vec::new(),
1268            co_writers: Vec::new(),
1269            unattributed_writes: Vec::new(),
1270            merge_renames: Vec::new(),
1271            timestamp: 0,
1272        };
1273        let writes = newest_writes_from_notes(std::slice::from_ref(&batch));
1274        assert_eq!(
1275            writes["specs--one"].note.as_deref(),
1276            Some("note for one\nand its second line")
1277        );
1278        assert_eq!(writes["specs--two"].note, None, "its entry declared none");
1279        assert_eq!(
1280            writes["specs--three"].note.as_deref(),
1281            Some("Reason: three")
1282        );
1283        for id in ["specs--one", "specs--two", "specs--three"] {
1284            assert_eq!(writes[id].identity.as_deref(), Some("yolanda"));
1285        }
1286
1287        // The writer's join and this reader agree, whatever a note's
1288        // lines say: a line of one entry's note that begins with another
1289        // entry's id, or with its own, stays where it was written.
1290        let joined = [
1291            crate::vcs::batch_note_line(
1292                "specs--one",
1293                "first line of one\nspecs--two: planted by one\nspecs--one: and its own id\n\nafter a gap",
1294            ),
1295            crate::vcs::batch_note_line("specs--three", "said by three"),
1296        ]
1297        .join("\n");
1298        let mut planted = batch.clone();
1299        planted.note = Some(joined);
1300        let writes = newest_writes_from_notes(std::slice::from_ref(&planted));
1301        assert_eq!(
1302            writes["specs--one"].note.as_deref(),
1303            Some(
1304                "first line of one\nspecs--two: planted by one\nspecs--one: and its own id\n\nafter a gap"
1305            )
1306        );
1307        assert_eq!(writes["specs--two"].note, None, "nothing was planted on it");
1308        assert_eq!(
1309            writes["specs--three"].note.as_deref(),
1310            Some("said by three")
1311        );
1312
1313        // A single write's note is carried whole up to the declared
1314        // limit and cut beyond it.
1315        let limit = crate::mem_management::NOTE_MAX_LEN;
1316        let mut single = batch.clone();
1317        single.tool_verb = Some("update".to_string());
1318        single.entity_id = Some("specs--one".to_string());
1319        single.entity_ids = Vec::new();
1320        single.note = Some("n".repeat(limit));
1321        let whole = newest_writes_from_notes(std::slice::from_ref(&single));
1322        assert_eq!(
1323            whole["specs--one"].note.as_deref().map(str::len),
1324            Some(limit)
1325        );
1326        single.note = Some("ä".repeat(limit + 40));
1327        let cut = newest_writes_from_notes(std::slice::from_ref(&single));
1328        let text = cut["specs--one"].note.clone().unwrap();
1329        assert_eq!(text.chars().count(), limit + 1);
1330        assert!(text.ends_with('…'));
1331    }
1332
1333    #[test]
1334    fn notice_small_delta_is_detailed_ordered_and_typed() {
1335        // Out-of-order input; the notice sorts by id and carries full
1336        // detail as `ChangeEnvelope`s — same `action` vocabulary as
1337        // `memstead_changes_since` (`updated`, not `modified`).
1338        let changes = vec![
1339            ChangeEnvelope::Updated {
1340                id: EntityId::new("specs", "bbb"),
1341                title: Some("Bee".to_string()),
1342                entity_type: Some("spec".to_string()),
1343            },
1344            ChangeEnvelope::Added {
1345                id: EntityId::new("specs", "aaa"),
1346                title: Some("Ay".to_string()),
1347                entity_type: Some("spec".to_string()),
1348            },
1349        ];
1350        let notice = MemChangedNotice::from_delta(
1351            "specs".to_string(),
1352            "H0".to_string(),
1353            "H1".to_string(),
1354            changes,
1355        );
1356        match &notice.changes {
1357            NoticeChanges::Detailed { entries } => {
1358                assert_eq!(entries.len(), 2);
1359                // Lexical by id: aaa before bbb.
1360                assert_eq!(entries[0].primary_id(), "specs--aaa");
1361                assert_eq!(entries[0].action(), "added");
1362                assert_eq!(entries[1].primary_id(), "specs--bbb");
1363                assert_eq!(entries[1].action(), "updated");
1364                assert_eq!(entries[1].entity_type(), Some("spec"));
1365            }
1366            other => panic!("expected detailed, got {other:?}"),
1367        }
1368        let json = serde_json::to_string(&notice).unwrap();
1369        assert!(json.contains(r#""mode":"detailed""#));
1370        // Notice and changes_since speak one language: `action`/`updated`,
1371        // and `entity_type` (not the old `change`/`modified`/`type`).
1372        assert!(json.contains(r#""action":"updated""#));
1373        assert!(json.contains(r#""entity_type":"spec""#));
1374        assert!(
1375            !json.contains(r#""change":"#),
1376            "no legacy `change` key: {json}"
1377        );
1378    }
1379
1380    #[test]
1381    fn notice_entry_is_byte_identical_to_changes_since_envelope() {
1382        // Parity: the notice's detailed-tier entry and the
1383        // `memstead_changes_since` event are the *same* serialized shape, so
1384        // an agent decodes one and decodes the other — no translation
1385        // between `change`/`action` or `modified`/`updated` or
1386        // `type`/`entity_type`. Verified by reusing one `ChangeEnvelope`
1387        // on both surfaces and comparing the JSON.
1388        let env = ChangeEnvelope::Updated {
1389            id: EntityId::new("specs", "x"),
1390            title: Some("X".to_string()),
1391            entity_type: Some("spec".to_string()),
1392        };
1393        let changes_since_json = serde_json::to_value(&env).unwrap();
1394        let notice = MemChangedNotice::from_delta(
1395            "specs".to_string(),
1396            "H0".to_string(),
1397            "H1".to_string(),
1398            vec![env],
1399        );
1400        let notice_json = serde_json::to_value(&notice).unwrap();
1401        let entry = &notice_json["changes"]["entries"][0];
1402        assert_eq!(
1403            entry, &changes_since_json,
1404            "notice entry must equal the changes_since envelope verbatim",
1405        );
1406    }
1407
1408    #[test]
1409    fn notice_renamed_carries_both_ids_and_sorts_under_to_id() {
1410        // A rename in the notice carries both prior and new id —
1411        // an agent holding the old id can follow it. Parity with
1412        // `memstead_changes_since` (from_id + to_id, not remove+add).
1413        let changes = vec![ChangeEnvelope::Renamed {
1414            from_id: EntityId::new("specs", "old"),
1415            to_id: EntityId::new("specs", "new"),
1416            title: Some("New".to_string()),
1417            entity_type: Some("spec".to_string()),
1418        }];
1419        let notice = MemChangedNotice::from_delta(
1420            "specs".to_string(),
1421            "H0".to_string(),
1422            "H1".to_string(),
1423            changes,
1424        );
1425        match &notice.changes {
1426            NoticeChanges::Detailed { entries } => {
1427                assert_eq!(entries[0].primary_id(), "specs--new");
1428                assert_eq!(entries[0].action(), "renamed");
1429            }
1430            other => panic!("expected detailed, got {other:?}"),
1431        }
1432        let json = serde_json::to_string(&notice).unwrap();
1433        assert!(
1434            json.contains(r#""from_id":"specs--old""#),
1435            "rename carries from_id: {json}"
1436        );
1437        assert!(
1438            json.contains(r#""to_id":"specs--new""#),
1439            "rename carries to_id: {json}"
1440        );
1441    }
1442
1443    #[test]
1444    fn notice_ids_tier_preserves_rename_both_ids() {
1445        // The rename rule holds in the `ids` tier too: rich detail is dropped but a
1446        // rename still carries both ids (identity, not detail).
1447        let mut changes = added_envelopes(NOTICE_DETAILED_MAX);
1448        changes.push(ChangeEnvelope::Renamed {
1449            from_id: EntityId::new("specs", "zzz-old"),
1450            to_id: EntityId::new("specs", "zzz-new"),
1451            title: Some("Z".to_string()),
1452            entity_type: Some("spec".to_string()),
1453        });
1454        let notice = MemChangedNotice::from_delta(
1455            "specs".to_string(),
1456            "H0".to_string(),
1457            "H1".to_string(),
1458            changes,
1459        );
1460        let json = serde_json::to_string(&notice).unwrap();
1461        assert!(
1462            json.contains(r#""mode":"ids""#),
1463            "expected ids tier: {json}"
1464        );
1465        assert!(json.contains(r#""from_id":"specs--zzz-old""#));
1466        assert!(json.contains(r#""to_id":"specs--zzz-new""#));
1467        // Rich detail still dropped in the ids tier.
1468        assert!(!json.contains(r#""title""#), "ids tier drops title: {json}");
1469    }
1470
1471    #[test]
1472    fn notice_medium_delta_degrades_to_ids_with_every_id_inline() {
1473        // 60 > NOTICE_DETAILED_MAX (50) but ≤ NOTICE_IDS_MAX (500):
1474        // mode drops to "ids" yet every changed id is still listed.
1475        let notice = MemChangedNotice::from_delta(
1476            "specs".to_string(),
1477            "H0".to_string(),
1478            "H1".to_string(),
1479            added_envelopes(60),
1480        );
1481        match &notice.changes {
1482            NoticeChanges::Ids { entries } => {
1483                assert_eq!(entries.len(), 60, "every changed id stays inline");
1484                assert_eq!(entries[0].primary_id(), "specs--e-0000");
1485            }
1486            other => panic!("expected ids, got {other:?}"),
1487        }
1488        let json = serde_json::to_string(&notice).unwrap();
1489        assert!(json.contains(r#""mode":"ids""#));
1490        // Rich detail dropped — no title/entity_type keys in ids mode.
1491        assert!(!json.contains(r#""title""#));
1492        assert!(!json.contains(r#""entity_type""#));
1493    }
1494
1495    #[test]
1496    fn notice_id_list_outlives_rich_detail() {
1497        // Complement AC: there is a delta size that drops title/type
1498        // (mode "ids") while still listing every id — i.e. the id list
1499        // is budgeted on a distinctly higher threshold than the detail.
1500        let just_over_detail = NOTICE_DETAILED_MAX + 1;
1501        let notice = MemChangedNotice::from_delta(
1502            "specs".to_string(),
1503            "H0".to_string(),
1504            "H1".to_string(),
1505            added_envelopes(just_over_detail),
1506        );
1507        match &notice.changes {
1508            NoticeChanges::Ids { entries } => {
1509                assert_eq!(entries.len(), just_over_detail);
1510            }
1511            other => panic!("expected ids at {just_over_detail}, got {other:?}"),
1512        }
1513    }
1514
1515    #[test]
1516    fn notice_mass_delta_degrades_to_counts_with_self_inform() {
1517        // > NOTICE_IDS_MAX (500): collapse to counts. by_change sums
1518        // every event; counts buckets by type; self_inform names
1519        // changes_since with the from_head cursor; no ids inline.
1520        let n = NOTICE_IDS_MAX + 1;
1521        let notice = MemChangedNotice::from_delta(
1522            "specs".to_string(),
1523            "H0".to_string(),
1524            "H1".to_string(),
1525            added_envelopes(n),
1526        );
1527        match &notice.changes {
1528            NoticeChanges::Counts {
1529                counts,
1530                by_change,
1531                self_inform,
1532            } => {
1533                assert_eq!(by_change.added, n);
1534                assert_eq!(counts.get("spec").copied(), Some(n));
1535                assert_eq!(self_inform, "call memstead_changes_since(since=H0)");
1536            }
1537            other => panic!("expected counts, got {other:?}"),
1538        }
1539        let json = serde_json::to_string(&notice).unwrap();
1540        assert!(json.contains(r#""mode":"counts""#));
1541        // No per-entity id list at counts scale.
1542        assert!(!json.contains("specs--e-"));
1543    }
1544
1545    #[test]
1546    fn notice_is_deterministic_regardless_of_input_order() {
1547        // Same delta, reversed input → byte-identical JSON.
1548        let forward = added_envelopes(20);
1549        let mut reversed = forward.clone();
1550        reversed.reverse();
1551        let a = MemChangedNotice::from_delta(
1552            "specs".to_string(),
1553            "H0".to_string(),
1554            "H1".to_string(),
1555            forward,
1556        );
1557        let b = MemChangedNotice::from_delta(
1558            "specs".to_string(),
1559            "H0".to_string(),
1560            "H1".to_string(),
1561            reversed,
1562        );
1563        assert_eq!(
1564            serde_json::to_string(&a).unwrap(),
1565            serde_json::to_string(&b).unwrap(),
1566        );
1567    }
1568}