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/// Whether a ledger timestamp and an entity's `created_date` name the
534/// same instant at the coarser of the two precisions (the ledger
535/// carries milliseconds, a frontmatter date seconds or a bare day).
536fn same_instant(ledger_ts: &str, created_date: &str) -> bool {
537    let norm = |s: &str| s.trim_end_matches('Z').replace('T', " ");
538    let a = norm(ledger_ts);
539    let b = norm(created_date);
540    let n = a.len().min(b.len());
541    n >= 10 && a[..n] == b[..n]
542}
543
544/// Engine-wrapper-level "what changed" shape returned by
545/// [`crate::Engine::changes_since`].
546///
547/// Adds the operator-facing `mem: String` and `warnings:
548/// Vec<WarningHint>` that the engine layer owns (rename-similarity
549/// clamping, etc.) on top of [`BackendChanges`]. Envelope `title` /
550/// `entity_type` fields are enriched from the engine's in-memory
551/// store (best-effort — `Removed` envelopes always leave them
552/// `None`; missing-from-store entities also leave them `None`).
553///
554/// Optional `notes` and `memstead_ref` carry per-commit agent-notes and
555/// the workspace-level `__MEMSTEAD` ref tip when the caller passes
556/// `include_notes: true`. Both fields stay `None` on folder + archive
557/// mounts (no commit history to read). MCP and CLI handlers populate
558/// them for git-branch mounts by pattern-matching on
559/// [`crate::workspace::MountStorage::GitBranch`] and calling
560/// `memstead_git_branch::ops::agent_notes::agent_notes_since` directly.
561#[derive(Debug, Clone, Serialize)]
562pub struct ChangesReport {
563    pub mem: String,
564    pub since: String,
565    pub head: String,
566    pub changes: Vec<ChangeEnvelope>,
567    #[serde(default, skip_serializing_if = "Vec::is_empty")]
568    pub warnings: Vec<crate::ops::WarningHint>,
569    /// Per-commit agent-notes parsed from commit trailers (git-branch
570    /// backend only). `None` when `include_notes` is false or the
571    /// backend has no commit history.
572    #[serde(default, skip_serializing_if = "Option::is_none")]
573    pub notes: Option<Vec<crate::ops::agent_notes::CommitNote>>,
574    /// Workspace-level `__MEMSTEAD` ref tip (unified schemas + per-mem
575    /// configs). `None` when `include_notes` is false or the
576    /// workspace has not been migrated to the unified layout yet.
577    #[serde(default, skip_serializing_if = "Option::is_none")]
578    pub memstead_ref: Option<String>,
579}
580
581// ---- mem_changed notice (reload-before-op awareness contract) ----
582
583/// Max changed-entity count rendered with full per-entity detail
584/// (id + change-kind + title + type) before the notice degrades to
585/// id+kind only. Rich detail is the expensive part of the payload; an
586/// id is cheap. Below this threshold the notice is `mode: "detailed"`.
587const NOTICE_DETAILED_MAX: usize = 50;
588
589/// Max changed-entity count that still lists every changed id inline
590/// (id + change-kind, `mode: "ids"`). The inline id list is exactly
591/// what lets the agent run its own relevance check as a local
592/// set-intersection against its context in zero round-trips, so it
593/// survives well past the rich-detail threshold. Above this, the
594/// notice collapses to `mode: "counts"` and points the agent at
595/// `memstead_changes_since` for the full delta.
596const NOTICE_IDS_MAX: usize = 500;
597
598/// Per-change-kind counts in `mode: "counts"`. Field names track the
599/// `memstead_changes_since` action vocabulary (`updated`, not `modified`)
600/// so the notice and the recovery surface speak one language.
601#[derive(Debug, Clone, Serialize, PartialEq, Eq, Default)]
602pub struct NoticeByChange {
603    pub added: usize,
604    pub updated: usize,
605    pub removed: usize,
606    pub renamed: usize,
607}
608
609/// The size-graceful body of a [`MemChangedNotice`]. Internally
610/// tagged on `mode` so a caller decodes one stable shape and branches
611/// on the discriminator — no request-shape-dependent polymorphism.
612///
613/// The `detailed` and `ids` tiers carry [`ChangeEnvelope`]s — the exact
614/// per-entity shape `memstead_changes_since` emits (same `action`
615/// vocabulary, `from_id` / `to_id` on renames). Sharing the type is the
616/// point: an agent that follows the notice's `self_inform` to
617/// `memstead_changes_since` decodes one shape on both surfaces, and the two
618/// delta representations cannot drift apart in vocabulary or richness.
619#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
620#[serde(tag = "mode", rename_all = "lowercase")]
621pub enum NoticeChanges {
622    /// Small delta — full per-entity [`ChangeEnvelope`]s with `title` /
623    /// `entity_type` enrichment.
624    Detailed { entries: Vec<ChangeEnvelope> },
625    /// Medium delta — every changed entity inline as a [`ChangeEnvelope`]
626    /// with `title` / `entity_type` stripped. The id list (and a
627    /// rename's `from_id` / `to_id`) stays complete; only rich detail is
628    /// dropped once the delta exceeds [`NOTICE_DETAILED_MAX`].
629    Ids { entries: Vec<ChangeEnvelope> },
630    /// Mass change — counts by type and by change-kind, plus the
631    /// `memstead_changes_since(since=<from_head>)` instruction for the
632    /// full delta. `counts` keys are entity types (omitted for
633    /// envelopes whose type the store couldn't resolve, e.g. removed).
634    Counts {
635        counts: std::collections::BTreeMap<String, usize>,
636        by_change: NoticeByChange,
637        self_inform: String,
638    },
639}
640
641/// Non-blocking "the mem moved under you" notice, attached to a
642/// response only when a reload happened during the operation. The
643/// operation's own result/error rides alongside — this is purely the
644/// objective "what else changed" delta, scaled by size, for the agent
645/// to judge relevance against (the engine does not filter to a
646/// per-agent interest model).
647///
648/// Built by [`MemChangedNotice::from_delta`] from the
649/// `from_head → to_head` [`ChangeEnvelope`] list a reload produced.
650/// Entries are ordered lexically by id so two notices over the same
651/// delta are byte-identical.
652#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
653pub struct MemChangedNotice {
654    pub mem: String,
655    pub from_head: String,
656    pub to_head: String,
657    pub changes: NoticeChanges,
658}
659
660impl MemChangedNotice {
661    /// Build a notice from the per-entity delta between `from_head`
662    /// and `to_head`, degrading by size:
663    /// `detailed` (≤ [`NOTICE_DETAILED_MAX`]) → `ids`
664    /// (≤ [`NOTICE_IDS_MAX`]) → `counts`. Entries are sorted lexically
665    /// by primary id (the `to_id` for a rename) so the output is
666    /// deterministic regardless of input order.
667    pub fn from_delta(
668        mem: String,
669        from_head: String,
670        to_head: String,
671        mut changes: Vec<ChangeEnvelope>,
672    ) -> Self {
673        changes.sort_by(|a, b| a.primary_id().cmp(b.primary_id()));
674        let n = changes.len();
675        let body = if n <= NOTICE_DETAILED_MAX {
676            NoticeChanges::Detailed { entries: changes }
677        } else if n <= NOTICE_IDS_MAX {
678            NoticeChanges::Ids {
679                entries: changes
680                    .iter()
681                    .map(ChangeEnvelope::without_metadata)
682                    .collect(),
683            }
684        } else {
685            let mut counts: std::collections::BTreeMap<String, usize> =
686                std::collections::BTreeMap::new();
687            let mut by_change = NoticeByChange::default();
688            for env in &changes {
689                match env {
690                    ChangeEnvelope::Added { .. } => by_change.added += 1,
691                    ChangeEnvelope::Updated { .. } => by_change.updated += 1,
692                    ChangeEnvelope::Removed { .. } => by_change.removed += 1,
693                    ChangeEnvelope::Renamed { .. } => by_change.renamed += 1,
694                }
695                if let Some(t) = env.entity_type() {
696                    *counts.entry(t.to_string()).or_default() += 1;
697                }
698            }
699            NoticeChanges::Counts {
700                counts,
701                by_change,
702                self_inform: format!("call memstead_changes_since(since={from_head})"),
703            }
704        };
705        Self {
706            mem,
707            from_head,
708            to_head,
709            changes: body,
710        }
711    }
712
713    /// Total changed-entity count this notice describes, across every
714    /// degradation tier. The MCP layer uses it to populate the
715    /// `entities_loaded` field of a `MemReloaded` warning synthesised
716    /// for an error response — a mutation reloads *inside* the engine
717    /// and surfaces only the stashed notice, not a `WarningHint`, so the
718    /// error-text warning line is reconstructed from the notice itself.
719    pub fn entity_count(&self) -> usize {
720        match &self.changes {
721            NoticeChanges::Detailed { entries } | NoticeChanges::Ids { entries } => entries.len(),
722            NoticeChanges::Counts { by_change, .. } => {
723                by_change.added + by_change.updated + by_change.removed + by_change.renamed
724            }
725        }
726    }
727}
728
729#[cfg(test)]
730mod tests {
731    use super::*;
732
733    #[test]
734    fn empty_at_echoes_cursor() {
735        let r = BackendChanges::empty_at("abc");
736        assert_eq!(r.since, "abc");
737        assert_eq!(r.head, "abc");
738        assert!(r.changes.is_empty());
739    }
740
741    #[test]
742    fn changes_report_omits_notes_and_memstead_ref_when_none() {
743        // Default-shaped report (no include_notes) — both Optional
744        // fields skip-serialize-when-none. Consumers that don't
745        // request notes see no notes/memstead_ref keys on the wire.
746        let r = ChangesReport {
747            mem: "specs".to_string(),
748            since: "abc".to_string(),
749            head: "def".to_string(),
750            changes: Vec::new(),
751            warnings: Vec::new(),
752            notes: None,
753            memstead_ref: None,
754        };
755        let json = serde_json::to_string(&r).unwrap();
756        assert!(
757            !json.contains("\"notes\""),
758            "notes must be omitted when None: {json}"
759        );
760        assert!(
761            !json.contains("\"memstead_ref\""),
762            "memstead_ref must be omitted when None: {json}"
763        );
764    }
765
766    #[test]
767    fn changes_report_emits_notes_and_memstead_ref_when_some() {
768        // When include_notes populates the fields, wire shape carries
769        // both keys nested at the report root. `memstead_ref` is the SHA
770        // of `refs/heads/__MEMSTEAD` (unified schemas + per-mem configs).
771        let r = ChangesReport {
772            mem: "specs".to_string(),
773            since: "abc".to_string(),
774            head: "def".to_string(),
775            changes: Vec::new(),
776            warnings: Vec::new(),
777            notes: Some(Vec::new()),
778            memstead_ref: Some("aabbccdd".to_string()),
779        };
780        let json = serde_json::to_string(&r).unwrap();
781        assert!(
782            json.contains("\"notes\":["),
783            "notes must be present: {json}"
784        );
785        assert!(
786            json.contains("\"memstead_ref\":\"aabbccdd\""),
787            "memstead_ref must be present and carry the SHA: {json}"
788        );
789    }
790
791    #[test]
792    fn change_envelope_serializes_action_tag() {
793        // Confirms the `action: "added" | "updated" | "removed" |
794        // "renamed"` discriminator is emitted as the wire shape MCP
795        // callers expect — same as full's existing ChangeEnvelope.
796        let env = ChangeEnvelope::Added {
797            id: EntityId::new("specs", "hello"),
798            title: Some("Hello".to_string()),
799            entity_type: Some("spec".to_string()),
800        };
801        let json = serde_json::to_string(&env).unwrap();
802        assert!(json.contains(r#""action":"added""#));
803        assert!(json.contains(r#""title":"Hello""#));
804        assert!(json.contains(r#""entity_type":"spec""#));
805    }
806
807    #[test]
808    fn change_envelope_skips_none_metadata_fields() {
809        let env = ChangeEnvelope::Removed {
810            id: EntityId::new("specs", "gone"),
811            title: None,
812            entity_type: None,
813        };
814        let json = serde_json::to_string(&env).unwrap();
815        assert!(json.contains(r#""action":"removed""#));
816        assert!(!json.contains("\"title\""));
817        assert!(!json.contains("\"entity_type\""));
818    }
819
820    #[test]
821    fn change_envelope_renamed_carries_both_ids() {
822        let env = ChangeEnvelope::Renamed {
823            from_id: EntityId::new("specs", "old"),
824            to_id: EntityId::new("specs", "new"),
825            title: Some("New".to_string()),
826            entity_type: Some("spec".to_string()),
827        };
828        let json = serde_json::to_string(&env).unwrap();
829        assert!(json.contains(r#""action":"renamed""#));
830        assert!(json.contains(r#""from_id":"specs--old""#));
831        assert!(json.contains(r#""to_id":"specs--new""#));
832    }
833
834    // ---- MemChangedNotice degradation + determinism --------------
835
836    /// `n` added envelopes with predictable ids (`e-0000` …) so tests
837    /// can assert ordering and inline-id presence.
838    fn added_envelopes(n: usize) -> Vec<ChangeEnvelope> {
839        (0..n)
840            .map(|i| ChangeEnvelope::Added {
841                id: EntityId::new("specs", &format!("e-{i:04}")),
842                title: Some(format!("Entity {i}")),
843                entity_type: Some("spec".to_string()),
844            })
845            .collect()
846    }
847
848    #[test]
849    fn notice_small_delta_is_detailed_ordered_and_typed() {
850        // Out-of-order input; the notice sorts by id and carries full
851        // detail as `ChangeEnvelope`s — same `action` vocabulary as
852        // `memstead_changes_since` (`updated`, not `modified`).
853        let changes = vec![
854            ChangeEnvelope::Updated {
855                id: EntityId::new("specs", "bbb"),
856                title: Some("Bee".to_string()),
857                entity_type: Some("spec".to_string()),
858            },
859            ChangeEnvelope::Added {
860                id: EntityId::new("specs", "aaa"),
861                title: Some("Ay".to_string()),
862                entity_type: Some("spec".to_string()),
863            },
864        ];
865        let notice = MemChangedNotice::from_delta(
866            "specs".to_string(),
867            "H0".to_string(),
868            "H1".to_string(),
869            changes,
870        );
871        match &notice.changes {
872            NoticeChanges::Detailed { entries } => {
873                assert_eq!(entries.len(), 2);
874                // Lexical by id: aaa before bbb.
875                assert_eq!(entries[0].primary_id(), "specs--aaa");
876                assert_eq!(entries[0].action(), "added");
877                assert_eq!(entries[1].primary_id(), "specs--bbb");
878                assert_eq!(entries[1].action(), "updated");
879                assert_eq!(entries[1].entity_type(), Some("spec"));
880            }
881            other => panic!("expected detailed, got {other:?}"),
882        }
883        let json = serde_json::to_string(&notice).unwrap();
884        assert!(json.contains(r#""mode":"detailed""#));
885        // Notice and changes_since speak one language: `action`/`updated`,
886        // and `entity_type` (not the old `change`/`modified`/`type`).
887        assert!(json.contains(r#""action":"updated""#));
888        assert!(json.contains(r#""entity_type":"spec""#));
889        assert!(
890            !json.contains(r#""change":"#),
891            "no legacy `change` key: {json}"
892        );
893    }
894
895    #[test]
896    fn notice_entry_is_byte_identical_to_changes_since_envelope() {
897        // Parity: the notice's detailed-tier entry and the
898        // `memstead_changes_since` event are the *same* serialized shape, so
899        // an agent decodes one and decodes the other — no translation
900        // between `change`/`action` or `modified`/`updated` or
901        // `type`/`entity_type`. Verified by reusing one `ChangeEnvelope`
902        // on both surfaces and comparing the JSON.
903        let env = ChangeEnvelope::Updated {
904            id: EntityId::new("specs", "x"),
905            title: Some("X".to_string()),
906            entity_type: Some("spec".to_string()),
907        };
908        let changes_since_json = serde_json::to_value(&env).unwrap();
909        let notice = MemChangedNotice::from_delta(
910            "specs".to_string(),
911            "H0".to_string(),
912            "H1".to_string(),
913            vec![env],
914        );
915        let notice_json = serde_json::to_value(&notice).unwrap();
916        let entry = &notice_json["changes"]["entries"][0];
917        assert_eq!(
918            entry, &changes_since_json,
919            "notice entry must equal the changes_since envelope verbatim",
920        );
921    }
922
923    #[test]
924    fn notice_renamed_carries_both_ids_and_sorts_under_to_id() {
925        // A rename in the notice carries both prior and new id —
926        // an agent holding the old id can follow it. Parity with
927        // `memstead_changes_since` (from_id + to_id, not remove+add).
928        let changes = vec![ChangeEnvelope::Renamed {
929            from_id: EntityId::new("specs", "old"),
930            to_id: EntityId::new("specs", "new"),
931            title: Some("New".to_string()),
932            entity_type: Some("spec".to_string()),
933        }];
934        let notice = MemChangedNotice::from_delta(
935            "specs".to_string(),
936            "H0".to_string(),
937            "H1".to_string(),
938            changes,
939        );
940        match &notice.changes {
941            NoticeChanges::Detailed { entries } => {
942                assert_eq!(entries[0].primary_id(), "specs--new");
943                assert_eq!(entries[0].action(), "renamed");
944            }
945            other => panic!("expected detailed, got {other:?}"),
946        }
947        let json = serde_json::to_string(&notice).unwrap();
948        assert!(
949            json.contains(r#""from_id":"specs--old""#),
950            "rename carries from_id: {json}"
951        );
952        assert!(
953            json.contains(r#""to_id":"specs--new""#),
954            "rename carries to_id: {json}"
955        );
956    }
957
958    #[test]
959    fn notice_ids_tier_preserves_rename_both_ids() {
960        // The rename rule holds in the `ids` tier too: rich detail is dropped but a
961        // rename still carries both ids (identity, not detail).
962        let mut changes = added_envelopes(NOTICE_DETAILED_MAX);
963        changes.push(ChangeEnvelope::Renamed {
964            from_id: EntityId::new("specs", "zzz-old"),
965            to_id: EntityId::new("specs", "zzz-new"),
966            title: Some("Z".to_string()),
967            entity_type: Some("spec".to_string()),
968        });
969        let notice = MemChangedNotice::from_delta(
970            "specs".to_string(),
971            "H0".to_string(),
972            "H1".to_string(),
973            changes,
974        );
975        let json = serde_json::to_string(&notice).unwrap();
976        assert!(
977            json.contains(r#""mode":"ids""#),
978            "expected ids tier: {json}"
979        );
980        assert!(json.contains(r#""from_id":"specs--zzz-old""#));
981        assert!(json.contains(r#""to_id":"specs--zzz-new""#));
982        // Rich detail still dropped in the ids tier.
983        assert!(!json.contains(r#""title""#), "ids tier drops title: {json}");
984    }
985
986    #[test]
987    fn notice_medium_delta_degrades_to_ids_with_every_id_inline() {
988        // 60 > NOTICE_DETAILED_MAX (50) but ≤ NOTICE_IDS_MAX (500):
989        // mode drops to "ids" yet every changed id is still listed.
990        let notice = MemChangedNotice::from_delta(
991            "specs".to_string(),
992            "H0".to_string(),
993            "H1".to_string(),
994            added_envelopes(60),
995        );
996        match &notice.changes {
997            NoticeChanges::Ids { entries } => {
998                assert_eq!(entries.len(), 60, "every changed id stays inline");
999                assert_eq!(entries[0].primary_id(), "specs--e-0000");
1000            }
1001            other => panic!("expected ids, got {other:?}"),
1002        }
1003        let json = serde_json::to_string(&notice).unwrap();
1004        assert!(json.contains(r#""mode":"ids""#));
1005        // Rich detail dropped — no title/entity_type keys in ids mode.
1006        assert!(!json.contains(r#""title""#));
1007        assert!(!json.contains(r#""entity_type""#));
1008    }
1009
1010    #[test]
1011    fn notice_id_list_outlives_rich_detail() {
1012        // Complement AC: there is a delta size that drops title/type
1013        // (mode "ids") while still listing every id — i.e. the id list
1014        // is budgeted on a distinctly higher threshold than the detail.
1015        let just_over_detail = NOTICE_DETAILED_MAX + 1;
1016        let notice = MemChangedNotice::from_delta(
1017            "specs".to_string(),
1018            "H0".to_string(),
1019            "H1".to_string(),
1020            added_envelopes(just_over_detail),
1021        );
1022        match &notice.changes {
1023            NoticeChanges::Ids { entries } => {
1024                assert_eq!(entries.len(), just_over_detail);
1025            }
1026            other => panic!("expected ids at {just_over_detail}, got {other:?}"),
1027        }
1028    }
1029
1030    #[test]
1031    fn notice_mass_delta_degrades_to_counts_with_self_inform() {
1032        // > NOTICE_IDS_MAX (500): collapse to counts. by_change sums
1033        // every event; counts buckets by type; self_inform names
1034        // changes_since with the from_head cursor; no ids inline.
1035        let n = NOTICE_IDS_MAX + 1;
1036        let notice = MemChangedNotice::from_delta(
1037            "specs".to_string(),
1038            "H0".to_string(),
1039            "H1".to_string(),
1040            added_envelopes(n),
1041        );
1042        match &notice.changes {
1043            NoticeChanges::Counts {
1044                counts,
1045                by_change,
1046                self_inform,
1047            } => {
1048                assert_eq!(by_change.added, n);
1049                assert_eq!(counts.get("spec").copied(), Some(n));
1050                assert_eq!(self_inform, "call memstead_changes_since(since=H0)");
1051            }
1052            other => panic!("expected counts, got {other:?}"),
1053        }
1054        let json = serde_json::to_string(&notice).unwrap();
1055        assert!(json.contains(r#""mode":"counts""#));
1056        // No per-entity id list at counts scale.
1057        assert!(!json.contains("specs--e-"));
1058    }
1059
1060    #[test]
1061    fn notice_is_deterministic_regardless_of_input_order() {
1062        // Same delta, reversed input → byte-identical JSON.
1063        let forward = added_envelopes(20);
1064        let mut reversed = forward.clone();
1065        reversed.reverse();
1066        let a = MemChangedNotice::from_delta(
1067            "specs".to_string(),
1068            "H0".to_string(),
1069            "H1".to_string(),
1070            forward,
1071        );
1072        let b = MemChangedNotice::from_delta(
1073            "specs".to_string(),
1074            "H0".to_string(),
1075            "H1".to_string(),
1076            reversed,
1077        );
1078        assert_eq!(
1079            serde_json::to_string(&a).unwrap(),
1080            serde_json::to_string(&b).unwrap(),
1081        );
1082    }
1083}