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    let log_path = crate::filesystem::changelog::changelog_path(mem_root);
271    let raw = match std::fs::read_to_string(&log_path) {
272        Ok(s) => s,
273        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
274            return Ok(BackendChanges::empty_at(since));
275        }
276        Err(e) => return Err(BackendError::Io(e)),
277    };
278
279    struct Aggregate {
280        first_kind: ProvenanceKind,
281        last_kind: ProvenanceKind,
282    }
283    /// What the whole ledger says about one id, window or not: the
284    /// instant it was created (when the ledger saw it), the instant of
285    /// its last row, and whether a delete row ever closed it.
286    #[derive(Default)]
287    struct Lifetime {
288        created_at: Option<String>,
289        last_at: String,
290        deleted: bool,
291        /// The id's last row is the rename row that named it: it is a
292        /// link in a rename chain, and the next rename continues from it.
293        named_by_rename: bool,
294    }
295    let mut by_entity: std::collections::BTreeMap<String, Aggregate> =
296        std::collections::BTreeMap::new();
297    let mut lifetimes: std::collections::BTreeMap<String, Lifetime> =
298        std::collections::BTreeMap::new();
299    let mut rename_rows: Vec<(String, String)> = Vec::new();
300    let mut max_ts: Option<String> = None;
301
302    let cursor_opt: Option<&str> = if since.is_empty() || since == EMPTY_TREE_SHA {
303        None
304    } else {
305        Some(since)
306    };
307
308    for line in raw.lines() {
309        let trimmed = line.trim();
310        if trimmed.is_empty() {
311            continue;
312        }
313        let value: serde_json::Value = match serde_json::from_str(trimmed) {
314            Ok(v) => v,
315            Err(_) => continue,
316        };
317        let ts_str = value.get("ts").and_then(|v| v.as_str()).unwrap_or("");
318        let kind = match value
319            .get("kind")
320            .and_then(|v| v.as_str())
321            .and_then(ProvenanceKind::parse)
322        {
323            Some(k) => k,
324            None => continue,
325        };
326        let entity_id = match value.get("entity").and_then(|v| v.as_str()) {
327            Some(s) if !s.is_empty() => s.to_string(),
328            _ => continue,
329        };
330        {
331            let life = lifetimes.entry(entity_id.clone()).or_default();
332            if matches!(kind, ProvenanceKind::Create) && life.created_at.is_none() {
333                life.created_at = Some(ts_str.to_string());
334            }
335            if ts_str >= life.last_at.as_str() {
336                life.last_at = ts_str.to_string();
337                life.named_by_rename = matches!(kind, ProvenanceKind::Rename);
338            }
339            if matches!(kind, ProvenanceKind::Delete) {
340                life.deleted = true;
341            }
342        }
343        if let Some(c) = cursor_opt
344            && ts_str <= c
345        {
346            continue;
347        }
348        if matches!(kind, ProvenanceKind::Rename) {
349            rename_rows.push((ts_str.to_string(), entity_id.clone()));
350        }
351
352        if max_ts.as_deref().is_none_or(|m| ts_str > m) {
353            max_ts = Some(ts_str.to_string());
354        }
355
356        by_entity
357            .entry(entity_id)
358            .and_modify(|agg| {
359                agg.last_kind = kind;
360            })
361            .or_insert(Aggregate {
362                first_kind: kind,
363                last_kind: kind,
364            });
365    }
366
367    // Pair every rename row in the window with the id that vanished
368    // for it, when the store can say which ids still exist, then
369    // compose the pairs into chains: a -> b -> c inside one window is
370    // one rename from a to c, and b, a name no reader ever held for
371    // long, surfaces nowhere.
372    let mut links: Vec<(String, String)> = Vec::new(); // (from, to), in row order
373    if let Some(lookup) = store {
374        let parse = |s: &str| match s.split_once("--") {
375            Some((v, slug)) if v == mem => Some(EntityId::new(v, slug)),
376            _ => None,
377        };
378        let exists = |name: &str| parse(name).and_then(|id| lookup(&id));
379        let mut taken: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
380        rename_rows.sort();
381        for (rename_ts, new_name) in &rename_rows {
382            let vanished: Vec<(&String, &Lifetime)> = lifetimes
383                .iter()
384                .filter(|(name, life)| {
385                    *name != new_name
386                        && !life.deleted
387                        && !taken.contains(*name)
388                        && life.last_at.as_str() < rename_ts.as_str()
389                        && parse(name).is_some()
390                        && exists(name).is_none()
391                })
392                .collect();
393            // The renamed entity keeps its creation instant: when the
394            // store serves the new id, the vanished id created at that
395            // instant is the origin, unless the instant is ambiguous.
396            let same_instant: Vec<&String> = match exists(new_name) {
397                Some(created_date) => vanished
398                    .iter()
399                    .filter(|(_, life)| {
400                        life.created_at
401                            .as_deref()
402                            .is_some_and(|c| same_instant(c, &created_date))
403                    })
404                    .map(|(name, _)| *name)
405                    .collect(),
406                None => Vec::new(),
407            };
408            let nearest: Option<String> = vanished
409                .iter()
410                .max_by(|a, b| a.1.last_at.cmp(&b.1.last_at))
411                .map(|(name, _)| (*name).clone());
412            // A vanished id that a rename row named (inside this window
413            // or before it) is a chain link: the row after it continues
414            // the chain, whatever the origin's creation instant says.
415            let continues_chain = nearest
416                .as_deref()
417                .is_some_and(|n| lifetimes.get(n).is_some_and(|l| l.named_by_rename));
418            let from = if continues_chain {
419                nearest
420            } else {
421                match same_instant.as_slice() {
422                    [one] => Some((*one).clone()),
423                    _ => nearest,
424                }
425            };
426            if let Some(from) = from {
427                taken.insert(from.clone());
428                links.push((from, new_name.clone()));
429            }
430        }
431    }
432    // Chains: an origin is a `from` no link renames into; follow it
433    // to the name the entity carries now.
434    let mut paired: Vec<(String, String, Vec<String>)> = Vec::new(); // (origin, final, members)
435    for (from, _) in &links {
436        if links.iter().any(|(_, to)| to == from) {
437            continue;
438        }
439        let mut members = vec![from.clone()];
440        let mut current = from.clone();
441        while let Some((_, to)) = links.iter().find(|(f, _)| *f == current) {
442            members.push(to.clone());
443            current = to.clone();
444        }
445        paired.push((from.clone(), current, members));
446    }
447
448    let mut changes: Vec<ChangeEnvelope> = Vec::with_capacity(by_entity.len());
449    for (from, to, members) in &paired {
450        let from_agg = by_entity.remove(from);
451        for member in members {
452            by_entity.remove(member);
453        }
454        let (Some(from_id), Some(to_id)) = (
455            from.split_once("--").map(|(v, s)| EntityId::new(v, s)),
456            to.split_once("--").map(|(v, s)| EntityId::new(v, s)),
457        ) else {
458            continue;
459        };
460        let born_in_window =
461            from_agg.is_some_and(|a| matches!(a.first_kind, ProvenanceKind::Create));
462        changes.push(if born_in_window {
463            ChangeEnvelope::Added {
464                id: to_id,
465                title: None,
466                entity_type: None,
467            }
468        } else {
469            ChangeEnvelope::Renamed {
470                from_id,
471                to_id,
472                title: None,
473                entity_type: None,
474            }
475        });
476    }
477    for (entity_str, agg) in by_entity {
478        let id = match entity_str.split_once("--") {
479            Some((v, slug)) if v == mem => EntityId::new(v, slug),
480            _ => continue,
481        };
482        // An id the store no longer serves and no delete row closed
483        // vanished without a pair: it is gone for every reader.
484        if let Some(lookup) = store
485            && !matches!(agg.last_kind, ProvenanceKind::Delete)
486            && lookup(&id).is_none()
487        {
488            changes.push(ChangeEnvelope::Removed {
489                id,
490                title: None,
491                entity_type: None,
492            });
493            continue;
494        }
495        let envelope = match (agg.first_kind, agg.last_kind) {
496            (_, ProvenanceKind::Delete) => ChangeEnvelope::Removed {
497                id,
498                title: None,
499                entity_type: None,
500            },
501            (ProvenanceKind::Create, _) => ChangeEnvelope::Added {
502                id,
503                title: None,
504                entity_type: None,
505            },
506            _ => ChangeEnvelope::Updated {
507                id,
508                title: None,
509                entity_type: None,
510            },
511        };
512        changes.push(envelope);
513    }
514
515    changes.sort_by(|a, b| a.primary_id().cmp(b.primary_id()));
516
517    Ok(BackendChanges {
518        since: since.to_string(),
519        head: max_ts.unwrap_or_else(|| since.to_string()),
520        changes,
521        notes: Vec::new(),
522        memstead_ref: None,
523    })
524}
525
526/// Whether a ledger timestamp and an entity's `created_date` name the
527/// same instant at the coarser of the two precisions (the ledger
528/// carries milliseconds, a frontmatter date seconds or a bare day).
529fn same_instant(ledger_ts: &str, created_date: &str) -> bool {
530    let norm = |s: &str| s.trim_end_matches('Z').replace('T', " ");
531    let a = norm(ledger_ts);
532    let b = norm(created_date);
533    let n = a.len().min(b.len());
534    n >= 10 && a[..n] == b[..n]
535}
536
537/// Engine-wrapper-level "what changed" shape returned by
538/// [`crate::Engine::changes_since`].
539///
540/// Adds the operator-facing `mem: String` and `warnings:
541/// Vec<WarningHint>` that the engine layer owns (rename-similarity
542/// clamping, etc.) on top of [`BackendChanges`]. Envelope `title` /
543/// `entity_type` fields are enriched from the engine's in-memory
544/// store (best-effort — `Removed` envelopes always leave them
545/// `None`; missing-from-store entities also leave them `None`).
546///
547/// Optional `notes` and `memstead_ref` carry per-commit agent-notes and
548/// the workspace-level `__MEMSTEAD` ref tip when the caller passes
549/// `include_notes: true`. Both fields stay `None` on folder + archive
550/// mounts (no commit history to read). MCP and CLI handlers populate
551/// them for git-branch mounts by pattern-matching on
552/// [`crate::workspace::MountStorage::GitBranch`] and calling
553/// `memstead_git_branch::ops::agent_notes::agent_notes_since` directly.
554#[derive(Debug, Clone, Serialize)]
555pub struct ChangesReport {
556    pub mem: String,
557    pub since: String,
558    pub head: String,
559    pub changes: Vec<ChangeEnvelope>,
560    #[serde(default, skip_serializing_if = "Vec::is_empty")]
561    pub warnings: Vec<crate::ops::WarningHint>,
562    /// Per-commit agent-notes parsed from commit trailers (git-branch
563    /// backend only). `None` when `include_notes` is false or the
564    /// backend has no commit history.
565    #[serde(default, skip_serializing_if = "Option::is_none")]
566    pub notes: Option<Vec<crate::ops::agent_notes::CommitNote>>,
567    /// Workspace-level `__MEMSTEAD` ref tip (unified schemas + per-mem
568    /// configs). `None` when `include_notes` is false or the
569    /// workspace has not been migrated to the unified layout yet.
570    #[serde(default, skip_serializing_if = "Option::is_none")]
571    pub memstead_ref: Option<String>,
572}
573
574// ---- mem_changed notice (reload-before-op awareness contract) ----
575
576/// Max changed-entity count rendered with full per-entity detail
577/// (id + change-kind + title + type) before the notice degrades to
578/// id+kind only. Rich detail is the expensive part of the payload; an
579/// id is cheap. Below this threshold the notice is `mode: "detailed"`.
580const NOTICE_DETAILED_MAX: usize = 50;
581
582/// Max changed-entity count that still lists every changed id inline
583/// (id + change-kind, `mode: "ids"`). The inline id list is exactly
584/// what lets the agent run its own relevance check as a local
585/// set-intersection against its context in zero round-trips, so it
586/// survives well past the rich-detail threshold. Above this, the
587/// notice collapses to `mode: "counts"` and points the agent at
588/// `memstead_changes_since` for the full delta.
589const NOTICE_IDS_MAX: usize = 500;
590
591/// Per-change-kind counts in `mode: "counts"`. Field names track the
592/// `memstead_changes_since` action vocabulary (`updated`, not `modified`)
593/// so the notice and the recovery surface speak one language.
594#[derive(Debug, Clone, Serialize, PartialEq, Eq, Default)]
595pub struct NoticeByChange {
596    pub added: usize,
597    pub updated: usize,
598    pub removed: usize,
599    pub renamed: usize,
600}
601
602/// The size-graceful body of a [`MemChangedNotice`]. Internally
603/// tagged on `mode` so a caller decodes one stable shape and branches
604/// on the discriminator — no request-shape-dependent polymorphism.
605///
606/// The `detailed` and `ids` tiers carry [`ChangeEnvelope`]s — the exact
607/// per-entity shape `memstead_changes_since` emits (same `action`
608/// vocabulary, `from_id` / `to_id` on renames). Sharing the type is the
609/// point: an agent that follows the notice's `self_inform` to
610/// `memstead_changes_since` decodes one shape on both surfaces, and the two
611/// delta representations cannot drift apart in vocabulary or richness.
612#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
613#[serde(tag = "mode", rename_all = "lowercase")]
614pub enum NoticeChanges {
615    /// Small delta — full per-entity [`ChangeEnvelope`]s with `title` /
616    /// `entity_type` enrichment.
617    Detailed { entries: Vec<ChangeEnvelope> },
618    /// Medium delta — every changed entity inline as a [`ChangeEnvelope`]
619    /// with `title` / `entity_type` stripped. The id list (and a
620    /// rename's `from_id` / `to_id`) stays complete; only rich detail is
621    /// dropped once the delta exceeds [`NOTICE_DETAILED_MAX`].
622    Ids { entries: Vec<ChangeEnvelope> },
623    /// Mass change — counts by type and by change-kind, plus the
624    /// `memstead_changes_since(since=<from_head>)` instruction for the
625    /// full delta. `counts` keys are entity types (omitted for
626    /// envelopes whose type the store couldn't resolve, e.g. removed).
627    Counts {
628        counts: std::collections::BTreeMap<String, usize>,
629        by_change: NoticeByChange,
630        self_inform: String,
631    },
632}
633
634/// Non-blocking "the mem moved under you" notice, attached to a
635/// response only when a reload happened during the operation. The
636/// operation's own result/error rides alongside — this is purely the
637/// objective "what else changed" delta, scaled by size, for the agent
638/// to judge relevance against (the engine does not filter to a
639/// per-agent interest model).
640///
641/// Built by [`MemChangedNotice::from_delta`] from the
642/// `from_head → to_head` [`ChangeEnvelope`] list a reload produced.
643/// Entries are ordered lexically by id so two notices over the same
644/// delta are byte-identical.
645#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
646pub struct MemChangedNotice {
647    pub mem: String,
648    pub from_head: String,
649    pub to_head: String,
650    pub changes: NoticeChanges,
651}
652
653impl MemChangedNotice {
654    /// Build a notice from the per-entity delta between `from_head`
655    /// and `to_head`, degrading by size:
656    /// `detailed` (≤ [`NOTICE_DETAILED_MAX`]) → `ids`
657    /// (≤ [`NOTICE_IDS_MAX`]) → `counts`. Entries are sorted lexically
658    /// by primary id (the `to_id` for a rename) so the output is
659    /// deterministic regardless of input order.
660    pub fn from_delta(
661        mem: String,
662        from_head: String,
663        to_head: String,
664        mut changes: Vec<ChangeEnvelope>,
665    ) -> Self {
666        changes.sort_by(|a, b| a.primary_id().cmp(b.primary_id()));
667        let n = changes.len();
668        let body = if n <= NOTICE_DETAILED_MAX {
669            NoticeChanges::Detailed { entries: changes }
670        } else if n <= NOTICE_IDS_MAX {
671            NoticeChanges::Ids {
672                entries: changes
673                    .iter()
674                    .map(ChangeEnvelope::without_metadata)
675                    .collect(),
676            }
677        } else {
678            let mut counts: std::collections::BTreeMap<String, usize> =
679                std::collections::BTreeMap::new();
680            let mut by_change = NoticeByChange::default();
681            for env in &changes {
682                match env {
683                    ChangeEnvelope::Added { .. } => by_change.added += 1,
684                    ChangeEnvelope::Updated { .. } => by_change.updated += 1,
685                    ChangeEnvelope::Removed { .. } => by_change.removed += 1,
686                    ChangeEnvelope::Renamed { .. } => by_change.renamed += 1,
687                }
688                if let Some(t) = env.entity_type() {
689                    *counts.entry(t.to_string()).or_default() += 1;
690                }
691            }
692            NoticeChanges::Counts {
693                counts,
694                by_change,
695                self_inform: format!("call memstead_changes_since(since={from_head})"),
696            }
697        };
698        Self {
699            mem,
700            from_head,
701            to_head,
702            changes: body,
703        }
704    }
705
706    /// Total changed-entity count this notice describes, across every
707    /// degradation tier. The MCP layer uses it to populate the
708    /// `entities_loaded` field of a `MemReloaded` warning synthesised
709    /// for an error response — a mutation reloads *inside* the engine
710    /// and surfaces only the stashed notice, not a `WarningHint`, so the
711    /// error-text warning line is reconstructed from the notice itself.
712    pub fn entity_count(&self) -> usize {
713        match &self.changes {
714            NoticeChanges::Detailed { entries } | NoticeChanges::Ids { entries } => entries.len(),
715            NoticeChanges::Counts { by_change, .. } => {
716                by_change.added + by_change.updated + by_change.removed + by_change.renamed
717            }
718        }
719    }
720}
721
722#[cfg(test)]
723mod tests {
724    use super::*;
725
726    #[test]
727    fn empty_at_echoes_cursor() {
728        let r = BackendChanges::empty_at("abc");
729        assert_eq!(r.since, "abc");
730        assert_eq!(r.head, "abc");
731        assert!(r.changes.is_empty());
732    }
733
734    #[test]
735    fn changes_report_omits_notes_and_memstead_ref_when_none() {
736        // Default-shaped report (no include_notes) — both Optional
737        // fields skip-serialize-when-none. Consumers that don't
738        // request notes see no notes/memstead_ref keys on the wire.
739        let r = ChangesReport {
740            mem: "specs".to_string(),
741            since: "abc".to_string(),
742            head: "def".to_string(),
743            changes: Vec::new(),
744            warnings: Vec::new(),
745            notes: None,
746            memstead_ref: None,
747        };
748        let json = serde_json::to_string(&r).unwrap();
749        assert!(
750            !json.contains("\"notes\""),
751            "notes must be omitted when None: {json}"
752        );
753        assert!(
754            !json.contains("\"memstead_ref\""),
755            "memstead_ref must be omitted when None: {json}"
756        );
757    }
758
759    #[test]
760    fn changes_report_emits_notes_and_memstead_ref_when_some() {
761        // When include_notes populates the fields, wire shape carries
762        // both keys nested at the report root. `memstead_ref` is the SHA
763        // of `refs/heads/__MEMSTEAD` (unified schemas + per-mem configs).
764        let r = ChangesReport {
765            mem: "specs".to_string(),
766            since: "abc".to_string(),
767            head: "def".to_string(),
768            changes: Vec::new(),
769            warnings: Vec::new(),
770            notes: Some(Vec::new()),
771            memstead_ref: Some("aabbccdd".to_string()),
772        };
773        let json = serde_json::to_string(&r).unwrap();
774        assert!(
775            json.contains("\"notes\":["),
776            "notes must be present: {json}"
777        );
778        assert!(
779            json.contains("\"memstead_ref\":\"aabbccdd\""),
780            "memstead_ref must be present and carry the SHA: {json}"
781        );
782    }
783
784    #[test]
785    fn change_envelope_serializes_action_tag() {
786        // Confirms the `action: "added" | "updated" | "removed" |
787        // "renamed"` discriminator is emitted as the wire shape MCP
788        // callers expect — same as full's existing ChangeEnvelope.
789        let env = ChangeEnvelope::Added {
790            id: EntityId::new("specs", "hello"),
791            title: Some("Hello".to_string()),
792            entity_type: Some("spec".to_string()),
793        };
794        let json = serde_json::to_string(&env).unwrap();
795        assert!(json.contains(r#""action":"added""#));
796        assert!(json.contains(r#""title":"Hello""#));
797        assert!(json.contains(r#""entity_type":"spec""#));
798    }
799
800    #[test]
801    fn change_envelope_skips_none_metadata_fields() {
802        let env = ChangeEnvelope::Removed {
803            id: EntityId::new("specs", "gone"),
804            title: None,
805            entity_type: None,
806        };
807        let json = serde_json::to_string(&env).unwrap();
808        assert!(json.contains(r#""action":"removed""#));
809        assert!(!json.contains("\"title\""));
810        assert!(!json.contains("\"entity_type\""));
811    }
812
813    #[test]
814    fn change_envelope_renamed_carries_both_ids() {
815        let env = ChangeEnvelope::Renamed {
816            from_id: EntityId::new("specs", "old"),
817            to_id: EntityId::new("specs", "new"),
818            title: Some("New".to_string()),
819            entity_type: Some("spec".to_string()),
820        };
821        let json = serde_json::to_string(&env).unwrap();
822        assert!(json.contains(r#""action":"renamed""#));
823        assert!(json.contains(r#""from_id":"specs--old""#));
824        assert!(json.contains(r#""to_id":"specs--new""#));
825    }
826
827    // ---- MemChangedNotice degradation + determinism --------------
828
829    /// `n` added envelopes with predictable ids (`e-0000` …) so tests
830    /// can assert ordering and inline-id presence.
831    fn added_envelopes(n: usize) -> Vec<ChangeEnvelope> {
832        (0..n)
833            .map(|i| ChangeEnvelope::Added {
834                id: EntityId::new("specs", &format!("e-{i:04}")),
835                title: Some(format!("Entity {i}")),
836                entity_type: Some("spec".to_string()),
837            })
838            .collect()
839    }
840
841    #[test]
842    fn notice_small_delta_is_detailed_ordered_and_typed() {
843        // Out-of-order input; the notice sorts by id and carries full
844        // detail as `ChangeEnvelope`s — same `action` vocabulary as
845        // `memstead_changes_since` (`updated`, not `modified`).
846        let changes = vec![
847            ChangeEnvelope::Updated {
848                id: EntityId::new("specs", "bbb"),
849                title: Some("Bee".to_string()),
850                entity_type: Some("spec".to_string()),
851            },
852            ChangeEnvelope::Added {
853                id: EntityId::new("specs", "aaa"),
854                title: Some("Ay".to_string()),
855                entity_type: Some("spec".to_string()),
856            },
857        ];
858        let notice = MemChangedNotice::from_delta(
859            "specs".to_string(),
860            "H0".to_string(),
861            "H1".to_string(),
862            changes,
863        );
864        match &notice.changes {
865            NoticeChanges::Detailed { entries } => {
866                assert_eq!(entries.len(), 2);
867                // Lexical by id: aaa before bbb.
868                assert_eq!(entries[0].primary_id(), "specs--aaa");
869                assert_eq!(entries[0].action(), "added");
870                assert_eq!(entries[1].primary_id(), "specs--bbb");
871                assert_eq!(entries[1].action(), "updated");
872                assert_eq!(entries[1].entity_type(), Some("spec"));
873            }
874            other => panic!("expected detailed, got {other:?}"),
875        }
876        let json = serde_json::to_string(&notice).unwrap();
877        assert!(json.contains(r#""mode":"detailed""#));
878        // Notice and changes_since speak one language: `action`/`updated`,
879        // and `entity_type` (not the old `change`/`modified`/`type`).
880        assert!(json.contains(r#""action":"updated""#));
881        assert!(json.contains(r#""entity_type":"spec""#));
882        assert!(
883            !json.contains(r#""change":"#),
884            "no legacy `change` key: {json}"
885        );
886    }
887
888    #[test]
889    fn notice_entry_is_byte_identical_to_changes_since_envelope() {
890        // F3 parity: the notice's detailed-tier entry and the
891        // `memstead_changes_since` event are the *same* serialized shape, so
892        // an agent decodes one and decodes the other — no translation
893        // between `change`/`action` or `modified`/`updated` or
894        // `type`/`entity_type`. Verified by reusing one `ChangeEnvelope`
895        // on both surfaces and comparing the JSON.
896        let env = ChangeEnvelope::Updated {
897            id: EntityId::new("specs", "x"),
898            title: Some("X".to_string()),
899            entity_type: Some("spec".to_string()),
900        };
901        let changes_since_json = serde_json::to_value(&env).unwrap();
902        let notice = MemChangedNotice::from_delta(
903            "specs".to_string(),
904            "H0".to_string(),
905            "H1".to_string(),
906            vec![env],
907        );
908        let notice_json = serde_json::to_value(&notice).unwrap();
909        let entry = &notice_json["changes"]["entries"][0];
910        assert_eq!(
911            entry, &changes_since_json,
912            "notice entry must equal the changes_since envelope verbatim",
913        );
914    }
915
916    #[test]
917    fn notice_renamed_carries_both_ids_and_sorts_under_to_id() {
918        // F2: a rename in the notice carries both prior and new id —
919        // an agent holding the old id can follow it. Parity with
920        // `memstead_changes_since` (from_id + to_id, not remove+add).
921        let changes = vec![ChangeEnvelope::Renamed {
922            from_id: EntityId::new("specs", "old"),
923            to_id: EntityId::new("specs", "new"),
924            title: Some("New".to_string()),
925            entity_type: Some("spec".to_string()),
926        }];
927        let notice = MemChangedNotice::from_delta(
928            "specs".to_string(),
929            "H0".to_string(),
930            "H1".to_string(),
931            changes,
932        );
933        match &notice.changes {
934            NoticeChanges::Detailed { entries } => {
935                assert_eq!(entries[0].primary_id(), "specs--new");
936                assert_eq!(entries[0].action(), "renamed");
937            }
938            other => panic!("expected detailed, got {other:?}"),
939        }
940        let json = serde_json::to_string(&notice).unwrap();
941        assert!(
942            json.contains(r#""from_id":"specs--old""#),
943            "rename carries from_id: {json}"
944        );
945        assert!(
946            json.contains(r#""to_id":"specs--new""#),
947            "rename carries to_id: {json}"
948        );
949    }
950
951    #[test]
952    fn notice_ids_tier_preserves_rename_both_ids() {
953        // F2 holds in the `ids` tier too: rich detail is dropped but a
954        // rename still carries both ids (identity, not detail).
955        let mut changes = added_envelopes(NOTICE_DETAILED_MAX);
956        changes.push(ChangeEnvelope::Renamed {
957            from_id: EntityId::new("specs", "zzz-old"),
958            to_id: EntityId::new("specs", "zzz-new"),
959            title: Some("Z".to_string()),
960            entity_type: Some("spec".to_string()),
961        });
962        let notice = MemChangedNotice::from_delta(
963            "specs".to_string(),
964            "H0".to_string(),
965            "H1".to_string(),
966            changes,
967        );
968        let json = serde_json::to_string(&notice).unwrap();
969        assert!(
970            json.contains(r#""mode":"ids""#),
971            "expected ids tier: {json}"
972        );
973        assert!(json.contains(r#""from_id":"specs--zzz-old""#));
974        assert!(json.contains(r#""to_id":"specs--zzz-new""#));
975        // Rich detail still dropped in the ids tier.
976        assert!(!json.contains(r#""title""#), "ids tier drops title: {json}");
977    }
978
979    #[test]
980    fn notice_medium_delta_degrades_to_ids_with_every_id_inline() {
981        // 60 > NOTICE_DETAILED_MAX (50) but ≤ NOTICE_IDS_MAX (500):
982        // mode drops to "ids" yet every changed id is still listed.
983        let notice = MemChangedNotice::from_delta(
984            "specs".to_string(),
985            "H0".to_string(),
986            "H1".to_string(),
987            added_envelopes(60),
988        );
989        match &notice.changes {
990            NoticeChanges::Ids { entries } => {
991                assert_eq!(entries.len(), 60, "every changed id stays inline");
992                assert_eq!(entries[0].primary_id(), "specs--e-0000");
993            }
994            other => panic!("expected ids, got {other:?}"),
995        }
996        let json = serde_json::to_string(&notice).unwrap();
997        assert!(json.contains(r#""mode":"ids""#));
998        // Rich detail dropped — no title/entity_type keys in ids mode.
999        assert!(!json.contains(r#""title""#));
1000        assert!(!json.contains(r#""entity_type""#));
1001    }
1002
1003    #[test]
1004    fn notice_id_list_outlives_rich_detail() {
1005        // Complement AC: there is a delta size that drops title/type
1006        // (mode "ids") while still listing every id — i.e. the id list
1007        // is budgeted on a distinctly higher threshold than the detail.
1008        let just_over_detail = NOTICE_DETAILED_MAX + 1;
1009        let notice = MemChangedNotice::from_delta(
1010            "specs".to_string(),
1011            "H0".to_string(),
1012            "H1".to_string(),
1013            added_envelopes(just_over_detail),
1014        );
1015        match &notice.changes {
1016            NoticeChanges::Ids { entries } => {
1017                assert_eq!(entries.len(), just_over_detail);
1018            }
1019            other => panic!("expected ids at {just_over_detail}, got {other:?}"),
1020        }
1021    }
1022
1023    #[test]
1024    fn notice_mass_delta_degrades_to_counts_with_self_inform() {
1025        // > NOTICE_IDS_MAX (500): collapse to counts. by_change sums
1026        // every event; counts buckets by type; self_inform names
1027        // changes_since with the from_head cursor; no ids inline.
1028        let n = NOTICE_IDS_MAX + 1;
1029        let notice = MemChangedNotice::from_delta(
1030            "specs".to_string(),
1031            "H0".to_string(),
1032            "H1".to_string(),
1033            added_envelopes(n),
1034        );
1035        match &notice.changes {
1036            NoticeChanges::Counts {
1037                counts,
1038                by_change,
1039                self_inform,
1040            } => {
1041                assert_eq!(by_change.added, n);
1042                assert_eq!(counts.get("spec").copied(), Some(n));
1043                assert_eq!(self_inform, "call memstead_changes_since(since=H0)");
1044            }
1045            other => panic!("expected counts, got {other:?}"),
1046        }
1047        let json = serde_json::to_string(&notice).unwrap();
1048        assert!(json.contains(r#""mode":"counts""#));
1049        // No per-entity id list at counts scale.
1050        assert!(!json.contains("specs--e-"));
1051    }
1052
1053    #[test]
1054    fn notice_is_deterministic_regardless_of_input_order() {
1055        // Same delta, reversed input → byte-identical JSON.
1056        let forward = added_envelopes(20);
1057        let mut reversed = forward.clone();
1058        reversed.reverse();
1059        let a = MemChangedNotice::from_delta(
1060            "specs".to_string(),
1061            "H0".to_string(),
1062            "H1".to_string(),
1063            forward,
1064        );
1065        let b = MemChangedNotice::from_delta(
1066            "specs".to_string(),
1067            "H0".to_string(),
1068            "H1".to_string(),
1069            reversed,
1070        );
1071        assert_eq!(
1072            serde_json::to_string(&a).unwrap(),
1073            serde_json::to_string(&b).unwrap(),
1074        );
1075    }
1076}