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