Skip to main content

memstead_base/engine/
history.rs

1//! Per-entity history — the narrative query behind an inspector's
2//! "how did this entity get this way".
3//!
4//! The engine already records everything a story needs (commit
5//! subjects, provenance trailers, agent notes, batch entity lists,
6//! rename chains) but exposed it only as branch-wide feeds; every
7//! consumer filtered client-side. This module owns the per-entity
8//! filter, rename-chain attribution, and pagination — one semantic for
9//! every surface.
10//!
11//! Data sources per backend, all pre-existing:
12//! - git-branch: the commit-note walk that already rides
13//!   `changes_since` (`BackendChanges::notes`, newest-first) — full
14//!   fidelity: sha, subject, trailers, batch `Entities:` lists,
15//!   authoritative rename pairs in the subject.
16//! - folder / in-memory: `MemBackend::read_provenance` (the
17//!   `.memstead/changes.jsonl` line scan / its in-memory analogue,
18//!   oldest-first) — same story, coarser: no batch entity lists, and
19//!   rename records carry only the post-rename id, so chains are not
20//!   stitchable. Both gaps surface as stated `limitations`, never as
21//!   silently absent entries.
22//! - archive: the seam records no history — typed refusal, never a
23//!   fabricated empty story.
24//!
25//! This query is read-only and mutates nothing; it deliberately stays
26//! narrative-only (content-level diffs per touch are the pairwise
27//! `diff` op's job, git-branch consumers only).
28
29use serde::Serialize;
30
31use super::{Engine, EngineError};
32use crate::workspace::MountStorage;
33
34/// Default page size when the caller passes `None`.
35pub const HISTORY_PAGE_DEFAULT: usize = 50;
36/// Hard page-size cap; larger requests clamp here.
37pub const HISTORY_PAGE_MAX: usize = 200;
38
39/// One recorded touch of an entity, newest-first in the report.
40#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
41pub struct EntityTouch {
42    /// Backend-native reference for this touch: the commit SHA on
43    /// git-branch mems, the changelog RFC-3339 timestamp on folder /
44    /// in-memory mems. Also the basis of the page cursor.
45    pub reference: String,
46    /// Touch time, seconds since unix epoch.
47    pub timestamp: i64,
48    /// The entity's id when this touch happened — pre-rename touches
49    /// carry their then-current id (criterion: the story starts at the
50    /// first appearance under any prior id).
51    pub id_at_touch: String,
52    /// Mutation verb (`create` / `update` / `delete` / `relate` /
53    /// `rename` / `batch_update`…). `None` when the record predates
54    /// the subject convention or the commit is external.
55    #[serde(skip_serializing_if = "Option::is_none")]
56    pub verb: Option<String>,
57    /// Commit subject line (git-branch only).
58    #[serde(skip_serializing_if = "Option::is_none")]
59    pub subject: Option<String>,
60    /// The agent's stated intent, where one was written.
61    #[serde(skip_serializing_if = "Option::is_none")]
62    pub note: Option<String>,
63    #[serde(skip_serializing_if = "Option::is_none")]
64    pub actor: Option<String>,
65    #[serde(skip_serializing_if = "Option::is_none")]
66    pub client: Option<String>,
67    /// `Tool:` trailer (git-branch only).
68    #[serde(skip_serializing_if = "Option::is_none")]
69    pub tool: Option<String>,
70    /// On a rename touch: the id before the rename. `None` on
71    /// non-rename touches — and on folder-backend rename records,
72    /// which don't carry the pre-rename id (a stated limitation).
73    #[serde(skip_serializing_if = "Option::is_none")]
74    pub renamed_from: Option<String>,
75    /// On a rename touch: the id after the rename.
76    #[serde(skip_serializing_if = "Option::is_none")]
77    pub renamed_to: Option<String>,
78    /// Every id a multi-entity commit touched (batch context — names
79    /// the commit's scope without those entities' own stories
80    /// appearing here). Empty for single-entity touches.
81    #[serde(skip_serializing_if = "Vec::is_empty", default)]
82    pub batch_entity_ids: Vec<String>,
83    /// Correlation id linking commits of one logical operation.
84    #[serde(skip_serializing_if = "Option::is_none")]
85    pub logical_op: Option<String>,
86    /// Caller-declared role this touch was performed in. Absent = unspecified — recorded as absence, never
87    /// defaulted to a real role.
88    #[serde(skip_serializing_if = "Option::is_none")]
89    pub role: Option<String>,
90    /// Caller-declared identity this touch was performed under
91    ///. Absent = undeclared — recorded as
92    /// absence, never inferred from actor or client.
93    #[serde(skip_serializing_if = "Option::is_none")]
94    pub identity: Option<String>,
95}
96
97/// Where the returned story starts — the visible-truncation contract:
98/// whatever the record cannot reach is stated, never silent.
99#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
100#[serde(tag = "kind", rename_all = "lowercase")]
101pub enum StoryStart {
102    /// The oldest recorded touch is the entity's creation — the full
103    /// recorded story is reachable through the pages.
104    Recorded,
105    /// The story stops before the entity's first appearance, and here
106    /// is why (unstitchable rename, records predating the changelog,
107    /// an adopted mem with no history…).
108    Truncated { reason: String },
109}
110
111/// Result of [`Engine::entity_history`] — one page of the newest-first
112/// touch feed plus the explicit bounds of what it omits.
113#[derive(Debug, Clone, Serialize)]
114pub struct EntityHistoryReport {
115    pub mem: String,
116    /// The entity's current id (the query key).
117    pub entity_id: String,
118    /// This page's touches, newest first.
119    pub touches: Vec<EntityTouch>,
120    /// Total recorded touches across all pages — with `next_cursor`,
121    /// this states exactly what a page omits.
122    pub total_recorded: usize,
123    /// Opaque continuation: pass back as `cursor` for the next page.
124    /// `None` = this page ends the recorded story.
125    #[serde(skip_serializing_if = "Option::is_none")]
126    pub next_cursor: Option<String>,
127    /// Where the recorded story starts (visible-truncation contract).
128    pub story_start: StoryStart,
129    /// Stated per-backend gaps (folder rename stitching, batch
130    /// attribution). Empty on full-fidelity backends.
131    #[serde(skip_serializing_if = "Vec::is_empty", default)]
132    pub limitations: Vec<String>,
133}
134
135/// Split a rename record's `entity_id` field (`"old → new"`) into the
136/// pair. Cross-mem peer rewrites (parenthetical qualifier) and
137/// malformed values return `None` — they modify wiki-link bodies in a
138/// peer mem, never the entity itself.
139fn parse_rename_pair(field: &str) -> Option<(String, String)> {
140    if field.contains("(cross-mem rewrite") {
141        return None;
142    }
143    let mut parts = field.splitn(2, " → ");
144    let old = parts.next()?.trim();
145    let new = parts.next()?.trim();
146    if old.is_empty() || new.is_empty() {
147        return None;
148    }
149    Some((old.to_string(), new.to_string()))
150}
151
152/// One derived provenance record — who performed a boundary touch of
153/// an entity's story, in what declared role, when. Served by the entity read's opt-in provenance block.
154#[derive(Debug, Clone, serde::Serialize)]
155pub struct ProvenanceRecord {
156    /// Actor category (`agent` / `cli` / `app` / `external` /
157    /// `unknown`), from the recorded trailer.
158    #[serde(skip_serializing_if = "Option::is_none")]
159    pub actor: Option<String>,
160    /// Client identity (`name@version`) when recorded.
161    #[serde(skip_serializing_if = "Option::is_none")]
162    pub client: Option<String>,
163    /// The caller-declared role, or `"unspecified"` — absence is
164    /// served as the explicit cannot-confirm value, never as any
165    /// real role.
166    pub role: String,
167    /// The caller-declared identity, when one was recorded — the
168    /// independence gate's only comparator.
169    /// Absence downgrades comparisons to `unconfirmable`.
170    #[serde(skip_serializing_if = "Option::is_none")]
171    pub identity: Option<String>,
172    /// Touch time, seconds since unix epoch.
173    pub timestamp: i64,
174    /// Backend-native reference (commit sha / ledger timestamp).
175    pub reference: String,
176    /// The mutation verb of the touch (`create` / `update` / `rename` /
177    /// `retype` / `relate` / …), when the record carries one — so a
178    /// reader can tell a type change from an edit without opening the
179    /// commit.
180    #[serde(skip_serializing_if = "Option::is_none")]
181    pub verb: Option<String>,
182}
183
184/// The entity read's derived provenance block: created-by and
185/// last-modified-by, derived from the append-only history record —
186/// never from anything an agent can edit after the fact.
187#[derive(Debug, Clone, serde::Serialize)]
188pub struct EntityProvenance {
189    /// The creation record. `None` when the recorded story does not
190    /// start at the entity's creation (adopted/migrated mems) — the
191    /// honesty pattern: absence stated, never fabricated.
192    #[serde(skip_serializing_if = "Option::is_none")]
193    pub created_by: Option<ProvenanceRecord>,
194    /// The newest recorded touch.
195    #[serde(skip_serializing_if = "Option::is_none")]
196    pub last_modified_by: Option<ProvenanceRecord>,
197    /// True when the recorded story is truncated (its oldest touch is
198    /// not the creation) — `created_by` is then absent.
199    #[serde(skip_serializing_if = "std::ops::Not::not")]
200    pub story_truncated: bool,
201    /// Derived `verification` check state:
202    /// `never_checked` | `checked_ok` | `check_failed` | `check_stale`
203    /// — computed by comparing the newest verification record's
204    /// entity-hash against the current one, never stamped. Kind-scoped:
205    /// a conformance record never supersedes it.
206    pub check_state: String,
207    /// The newest `verification` record, when one exists.
208    #[serde(skip_serializing_if = "Option::is_none")]
209    pub last_check: Option<crate::check::CheckRecord>,
210    /// Derived `conformance` state — the same four values, computed
211    /// against the newest conformance record with pin-awareness (a
212    /// schema re-pin stales it). `never_checked` when no conformance
213    /// record exists, which is every pre-kind workspace.
214    pub conformance_state: String,
215    /// The newest `conformance` record, when one exists.
216    #[serde(skip_serializing_if = "Option::is_none")]
217    pub last_conformance_check: Option<crate::check::CheckRecord>,
218    /// On an archive mount: the authoring rationale the archive seals
219    /// for this entity (`.memstead/provenance.json`), in place of the
220    /// recorded touches an archive does not carry. Absent on source
221    /// mems.
222    #[serde(skip_serializing_if = "Option::is_none")]
223    pub sealed: Option<SealedProvenance>,
224}
225
226/// The per-entity authoring rationale an installed archive carries,
227/// read from the payload `export` seals; the reader never modifies the
228/// archive. `carried: false` says so explicitly when the archive ships
229/// no payload, or a payload with no entry for this entity: absence is
230/// stated, never substituted.
231#[derive(Debug, Clone, serde::Serialize)]
232pub struct SealedProvenance {
233    /// Whether the archive carries a rationale for this entity.
234    pub carried: bool,
235    /// The payload's history disposition (`summarised`) when a payload
236    /// exists at all.
237    #[serde(skip_serializing_if = "Option::is_none")]
238    pub history: Option<String>,
239    /// The entity's authoring rationale (the most recent mutation note
240    /// sealed for it).
241    #[serde(skip_serializing_if = "Option::is_none")]
242    pub rationale: Option<String>,
243    /// The mutation kind that note rode on (`create` / `update` / ...).
244    #[serde(skip_serializing_if = "Option::is_none")]
245    pub kind: Option<String>,
246    /// When it was recorded, RFC 3339 as sealed.
247    #[serde(skip_serializing_if = "Option::is_none")]
248    pub timestamp: Option<String>,
249    /// The actor category recorded with it.
250    #[serde(skip_serializing_if = "Option::is_none")]
251    pub actor: Option<String>,
252}
253
254fn touch_to_record(t: &EntityTouch) -> ProvenanceRecord {
255    ProvenanceRecord {
256        actor: t.actor.clone(),
257        client: t.client.clone(),
258        role: t.role.clone().unwrap_or_else(|| "unspecified".to_string()),
259        identity: t.identity.clone(),
260        timestamp: t.timestamp,
261        reference: t.reference.clone(),
262        verb: t.verb.clone(),
263    }
264}
265
266impl Engine {
267    /// Derive an entity's provenance block:
268    /// created-by (the oldest recorded touch, only when it IS the
269    /// creation) and last-modified-by (the newest touch), each with
270    /// actor identity, client, declared role, and timestamp — read
271    /// from the same append-only record `entity_history` serves, so
272    /// no verb can alter it after the fact. Pages through the full
273    /// story to reach the creation record when histories exceed one
274    /// page.
275    pub fn entity_provenance(
276        &self,
277        mem: &str,
278        entity_id: &str,
279    ) -> Result<EntityProvenance, EngineError> {
280        // An archive records no touches at the engine seam, but it
281        // carries the rationale `export` sealed per entity: that is the
282        // provenance an installed mem can answer with.
283        if matches!(
284            self.find_mount(mem)?.mount.storage,
285            MountStorage::Archive { .. }
286        ) {
287            return self.sealed_provenance(mem, entity_id);
288        }
289        let mut report = self.entity_history(mem, entity_id, Some(HISTORY_PAGE_MAX), None)?;
290        let newest = report.touches.first().cloned();
291        // Walk to the last page for the oldest touch.
292        while let Some(cursor) = report.next_cursor.clone() {
293            report = self.entity_history(mem, entity_id, Some(HISTORY_PAGE_MAX), Some(&cursor))?;
294        }
295        let oldest = report.touches.last().or(newest.as_ref()).cloned();
296        let truncated = !matches!(report.story_start, StoryStart::Recorded);
297        let (check_state, last_check) = self.entity_check_state(mem, entity_id)?;
298        let (conformance_state, last_conformance_check) =
299            self.entity_conformance_state(mem, entity_id)?;
300        Ok(EntityProvenance {
301            created_by: match (&oldest, truncated) {
302                (Some(t), false) => Some(touch_to_record(t)),
303                _ => None,
304            },
305            last_modified_by: newest.as_ref().map(touch_to_record),
306            story_truncated: truncated,
307            check_state: check_state.as_str().to_string(),
308            last_check,
309            conformance_state: conformance_state.as_str().to_string(),
310            last_conformance_check,
311            sealed: None,
312        })
313    }
314
315    /// The provenance block of an entity on an archive mount: the sealed
316    /// rationale where the payload carries one, `carried: false` where
317    /// it does not, and the check states the workspace ledger holds for
318    /// the id either way. Refuses `ENTITY_NOT_FOUND` for an id the mount
319    /// does not serve, as the history read does.
320    fn sealed_provenance(
321        &self,
322        mem: &str,
323        entity_id: &str,
324    ) -> Result<EntityProvenance, EngineError> {
325        let known = self
326            .store
327            .all_entities()
328            .any(|e| e.mem == mem && e.id.0 == entity_id);
329        if !known {
330            return Err(EngineError::NotFound {
331                id: entity_id.to_string(),
332            });
333        }
334        let id = crate::EntityId(entity_id.to_string());
335        let sealed = match self.archive_provenance_for(mem) {
336            Some(payload) => {
337                let history = Some(
338                    serde_json::to_value(payload.history)
339                        .ok()
340                        .and_then(|v| v.as_str().map(str::to_string))
341                        .unwrap_or_else(|| "unknown".to_string()),
342                );
343                match payload.entity(id.path()) {
344                    Some(rec) => SealedProvenance {
345                        carried: rec.rationale.is_some(),
346                        history,
347                        rationale: rec.rationale.clone(),
348                        kind: rec.kind.clone(),
349                        timestamp: rec.timestamp.clone(),
350                        actor: rec.actor.clone(),
351                    },
352                    None => SealedProvenance {
353                        carried: false,
354                        history,
355                        rationale: None,
356                        kind: None,
357                        timestamp: None,
358                        actor: None,
359                    },
360                }
361            }
362            None => SealedProvenance {
363                carried: false,
364                history: None,
365                rationale: None,
366                kind: None,
367                timestamp: None,
368                actor: None,
369            },
370        };
371        let (check_state, last_check) = self.entity_check_state(mem, entity_id)?;
372        let (conformance_state, last_conformance_check) =
373            self.entity_conformance_state(mem, entity_id)?;
374        Ok(EntityProvenance {
375            created_by: None,
376            last_modified_by: None,
377            story_truncated: false,
378            check_state: check_state.as_str().to_string(),
379            last_check,
380            conformance_state: conformance_state.as_str().to_string(),
381            last_conformance_check,
382            sealed: Some(sealed),
383        })
384    }
385
386    /// An entity's recorded history: every touch, newest-first, with
387    /// rename chains followed so the story starts at the entity's
388    /// first appearance under any prior id. Bounded and pageable —
389    /// `page_size` clamps to [`HISTORY_PAGE_MAX`], `cursor` continues
390    /// a prior page (`INVALID_CURSOR` when it matches no touch).
391    ///
392    /// Refusals: `UNKNOWN_MEM`, `ENTITY_NOT_FOUND` (an unknown id
393    /// never yields an empty story), `INVALID_INPUT` on archive
394    /// mounts (their seam records no history — refusing beats
395    /// fabricating emptiness).
396    pub fn entity_history(
397        &self,
398        mem: &str,
399        entity_id: &str,
400        page_size: Option<usize>,
401        cursor: Option<&str>,
402    ) -> Result<EntityHistoryReport, EngineError> {
403        let m = self.find_mount(mem)?;
404
405        // An unknown entity refuses — marklessness-style honesty: the
406        // caller learns "no such entity", never an empty history that
407        // reads as "exists, untouched".
408        let known = self
409            .store
410            .all_entities()
411            .any(|e| e.mem == mem && e.id.0 == entity_id);
412        if !known {
413            return Err(EngineError::NotFound {
414                id: entity_id.to_string(),
415            });
416        }
417
418        let mut limitations: Vec<String> = Vec::new();
419
420        // ---- Collect the raw record, newest-first, per backend ----
421        let touches: Vec<EntityTouch> = match &m.mount.storage {
422            MountStorage::GitBranch { gitdir, branch } => match self.git_branch_ops.as_ref() {
423                Some(hook) => {
424                    let backend_changes = (hook.changes_since)(
425                        gitdir,
426                        branch,
427                        mem,
428                        crate::ops::EMPTY_TREE_SHA,
429                        crate::ops::RENAME_SIMILARITY_DEFAULT,
430                    )
431                    .map_err(EngineError::Backend)?;
432                    filter_notes_for_entity(entity_id, &backend_changes.notes)
433                }
434                None => {
435                    limitations.push(
436                        "this build carries no git-branch history walk — the recorded story \
437                         is not reachable"
438                            .to_string(),
439                    );
440                    Vec::new()
441                }
442            },
443            MountStorage::Folder { .. } | MountStorage::InMemory => {
444                limitations.push(
445                    "changelog-backed history: rename records carry only the post-rename id \
446                     (prior-id chains are not stitchable) and batch mutations record no \
447                     per-entity attribution on this backend"
448                        .to_string(),
449                );
450                let records = m
451                    .backend
452                    .read_provenance(None)
453                    .map_err(EngineError::Backend)?;
454                filter_provenance_for_entity(entity_id, &records)
455            }
456            MountStorage::Archive { .. } => {
457                return Err(EngineError::InvalidInput(format!(
458                    "mem '{mem}' is an archive mount — archives record no history at the \
459                     engine seam; open the source mem for the entity's story"
460                )));
461            }
462        };
463
464        // ---- Visible-truncation verdict ----
465        // The recorded story is complete exactly when its oldest touch
466        // is the entity's creation. Anything else — empty record,
467        // oldest touch mid-stream — states where and why it stops.
468        let story_start = match touches.last() {
469            // `batch-create` IS this entity's creation when it is the
470            // oldest touch — a batch-authored entity carries the same
471            // append-only provenance (role, identity trailers) as a
472            // single create, and treating it as truncation erased
473            // `created_by` for every batch-authored entity, which
474            // silently degraded the checks independence gate to
475            // `unconfirmable` (found 2026-08-28, graph-plans pilot).
476            Some(oldest)
477                if matches!(
478                    oldest.verb.as_deref(),
479                    Some("create") | Some("batch-create")
480                ) =>
481            {
482                StoryStart::Recorded
483            }
484            Some(oldest) => StoryStart::Truncated {
485                reason: format!(
486                    "oldest recorded touch is a {} of `{}`, not the entity's creation — \
487                     earlier history (an unrecorded prior id, or records predating the \
488                     provenance log) is not reachable",
489                    oldest.verb.as_deref().unwrap_or("touch"),
490                    oldest.id_at_touch
491                ),
492            },
493            None => StoryStart::Truncated {
494                reason: "no touches recorded — the entity predates this mem's provenance \
495                         record (an adopted or migrated mem)"
496                    .to_string(),
497            },
498        };
499
500        // ---- Page ----
501        let size = page_size
502            .unwrap_or(HISTORY_PAGE_DEFAULT)
503            .clamp(1, HISTORY_PAGE_MAX);
504        let start_idx = match cursor {
505            None => 0,
506            Some(c) => {
507                let pos = parse_cursor(c).and_then(|(reference, k)| {
508                    touches
509                        .iter()
510                        .enumerate()
511                        .filter(|(_, t)| t.reference == reference)
512                        .nth(k)
513                        .map(|(i, _)| i + 1)
514                });
515                pos.ok_or_else(|| EngineError::InvalidChangesCursor {
516                    mem: mem.to_string(),
517                    since: c.to_string(),
518                })?
519            }
520        };
521        let total_recorded = touches.len();
522        let page: Vec<EntityTouch> = touches[start_idx.min(total_recorded)..]
523            .iter()
524            .take(size)
525            .cloned()
526            .collect();
527        let next_cursor = if start_idx + page.len() < total_recorded {
528            page.last().map(|last| {
529                let k = touches[..start_idx + page.len()]
530                    .iter()
531                    .filter(|t| t.reference == last.reference)
532                    .count()
533                    - 1;
534                format!("{}@{k}", last.reference)
535            })
536        } else {
537            None
538        };
539
540        Ok(EntityHistoryReport {
541            mem: mem.to_string(),
542            entity_id: entity_id.to_string(),
543            touches: page,
544            total_recorded,
545            next_cursor,
546            story_start,
547            limitations,
548        })
549    }
550}
551
552/// Cursor wire form: `<reference>@<occurrence>` where `occurrence`
553/// disambiguates touches sharing a reference (same-millisecond folder
554/// changelog lines; impossible for commit SHAs but the format stays
555/// uniform). Opaque to callers.
556fn parse_cursor(c: &str) -> Option<(String, usize)> {
557    let (reference, k) = c.rsplit_once('@')?;
558    if reference.is_empty() {
559        return None;
560    }
561    Some((reference.to_string(), k.parse().ok()?))
562}
563
564/// Newest→oldest single pass over the commit-note walk, tracking the
565/// entity's id backwards through authoritative rename records:
566/// `current` starts at the queried id; a rename whose *new* id equals
567/// `current` is that entity's rename touch and flips `current` to the
568/// old id, so every older touch is matched under its then-current id.
569/// A rename whose *old* id equals `current` is a different entity's
570/// departure from an id later reused — deliberately not a touch.
571///
572/// The walk STOPS at the entity's creation: a `create` of the tracked
573/// id is the story's birth, and anything older under the same id
574/// belonged to a previous holder of a reused slug (renamed away or
575/// deleted before this entity existed) — absorbing it would attribute
576/// a stranger's touches to this entity and present the polluted story
577/// as `Recorded` (found by plan 03/02's grading gate).
578fn filter_notes_for_entity(
579    entity_id: &str,
580    notes: &[crate::ops::agent_notes::CommitNote],
581) -> Vec<EntityTouch> {
582    let mut current = entity_id.to_string();
583    let mut out: Vec<EntityTouch> = Vec::new();
584    for n in notes {
585        let base = |id_at: &str| EntityTouch {
586            reference: n.sha.clone(),
587            timestamp: n.timestamp,
588            id_at_touch: id_at.to_string(),
589            verb: n.tool_verb.clone(),
590            subject: Some(n.subject.clone()),
591            note: n.note.clone(),
592            actor: n.actor.clone(),
593            client: n.client.clone(),
594            tool: n.tool.clone(),
595            renamed_from: None,
596            renamed_to: None,
597            batch_entity_ids: Vec::new(),
598            logical_op: n.logical_operation_id.clone(),
599            role: n.role.clone(),
600            identity: n.identity.clone(),
601        };
602        if n.tool_verb.as_deref() == Some("rename") {
603            if let Some((old, new)) = n.entity_id.as_deref().and_then(parse_rename_pair)
604                && new == current
605            {
606                let mut touch = base(&new);
607                touch.renamed_from = Some(old.clone());
608                touch.renamed_to = Some(new);
609                out.push(touch);
610                current = old;
611            }
612            continue;
613        }
614        if n.entity_id.as_deref() == Some(current.as_str()) {
615            let is_create = n.tool_verb.as_deref() == Some("create");
616            out.push(base(&current));
617            if is_create {
618                break;
619            }
620        } else if n.entity_ids.iter().any(|id| id == &current) {
621            let mut touch = base(&current);
622            touch.batch_entity_ids = n.entity_ids.clone();
623            out.push(touch);
624            // A batch-create that lists this entity is its creation —
625            // nothing older can touch it, same stop as single create.
626            if n.tool_verb.as_deref() == Some("batch-create") {
627                break;
628            }
629        }
630    }
631    out
632}
633
634/// Changelog-backed record (folder / in-memory): filter the
635/// oldest-first provenance feed to the entity's id and reverse to
636/// newest-first. Rename records match only when they carry this
637/// entity's (post-rename) id — the pre-rename chain is not recorded
638/// on this backend (stated limitation upstream).
639///
640/// Reused-id guard, symmetric with the git-branch walk: the story
641/// starts at the id's NEWEST `create` record — older records under the
642/// same id belonged to a previous holder of the slug, never to this
643/// entity.
644fn filter_provenance_for_entity(
645    entity_id: &str,
646    records: &[crate::provenance::Provenance],
647) -> Vec<EntityTouch> {
648    let matching: Vec<&crate::provenance::Provenance> = records
649        .iter()
650        .filter(|p| p.entity.as_deref() == Some(entity_id))
651        .collect();
652    let birth = matching
653        .iter()
654        .rposition(|p| matches!(p.kind, crate::provenance::ProvenanceKind::Create))
655        .unwrap_or(0);
656    let mut out: Vec<EntityTouch> = matching[birth..]
657        .iter()
658        .map(|p| {
659            let is_rename = matches!(p.kind, crate::provenance::ProvenanceKind::Rename);
660            EntityTouch {
661                reference: crate::filesystem::changelog::format_rfc3339_utc(p.timestamp),
662                timestamp: p
663                    .timestamp
664                    .duration_since(std::time::UNIX_EPOCH)
665                    .map(|d| d.as_secs() as i64)
666                    .unwrap_or(0),
667                id_at_touch: entity_id.to_string(),
668                verb: Some(p.kind.as_str().to_string()),
669                subject: None,
670                note: p.note.clone(),
671                actor: Some(p.actor.as_trailer().to_string()),
672                client: p
673                    .client
674                    .as_ref()
675                    .map(|c| format!("{}@{}", c.name, c.version)),
676                tool: None,
677                renamed_from: None,
678                renamed_to: is_rename.then(|| entity_id.to_string()),
679                batch_entity_ids: Vec::new(),
680                logical_op: p.logical_operation_id.clone(),
681                role: p.role.as_trailer().map(str::to_string),
682                identity: p.identity.clone(),
683            }
684        })
685        .collect();
686    out.reverse();
687    out
688}
689
690#[cfg(test)]
691mod tests {
692    use crate::storage::MemWriter;
693
694    /// A `batch-create` commit that lists the entity IS its creation:
695    /// the filter stops walking older history there (regression: an
696    /// older unrelated note must not attach), and the touch keeps the
697    /// `batch-create` verb the story-start check accepts — before the
698    /// 2026-08-28 fix every batch-authored entity read as truncated,
699    /// which erased `created_by` and degraded the checks independence
700    /// gate to `unconfirmable`.
701    #[test]
702    fn batch_create_note_is_the_entitys_creation() {
703        use crate::ops::agent_notes::CommitNote;
704        let note = |sha: &str, verb: &str, entity_id: Option<&str>, ids: Vec<&str>| CommitNote {
705            mem: "m".into(),
706            sha: sha.into(),
707            subject: format!("memstead: {verb}"),
708            tool_verb: Some(verb.into()),
709            entity_id: entity_id.map(str::to_string),
710            note: None,
711            actor: Some("cli".into()),
712            tool: None,
713            client: None,
714            logical_operation_id: None,
715            role: Some("author".into()),
716            identity: Some("author-x".into()),
717            entity_ids: ids.into_iter().map(str::to_string).collect(),
718            timestamp: 1,
719        };
720        // Newest-first: an update, then the batch create, then an
721        // unrelated older note that must never be reached.
722        let notes = vec![
723            note("c3", "update", Some("m--thing"), vec![]),
724            note("c2", "batch-create", None, vec!["m--other", "m--thing"]),
725            note("c1", "update", Some("m--thing"), vec![]),
726        ];
727        let touches = super::filter_notes_for_entity("m--thing", &notes);
728        assert_eq!(
729            touches.len(),
730            2,
731            "the walk stops at the batch create: {touches:?}"
732        );
733        let oldest = touches.last().unwrap();
734        assert_eq!(oldest.verb.as_deref(), Some("batch-create"));
735        assert_eq!(oldest.identity.as_deref(), Some("author-x"));
736        assert!(
737            matches!(
738                oldest.verb.as_deref(),
739                Some("create") | Some("batch-create")
740            ),
741            "the story-start acceptance covers the batch verb"
742        );
743    }
744
745    const SEED: &str = "---\ntype: spec\ncreated_date: 2026-01-01\nlast_modified: 2026-01-01\nlevel: M0\n---\n# Seed\n\n## Identity\n\nSeed.\n";
746
747    /// Folder-backed engine with one pre-existing entity written
748    /// outside the engine (no changelog record) — mirrors the review
749    /// module's fixture.
750    fn folder_engine(tmp: &tempfile::TempDir) -> crate::Engine {
751        let dir = tmp.path().join("specs");
752        if !dir.exists() {
753            std::fs::create_dir_all(&dir).unwrap();
754            let writer = crate::storage::FilesystemMemWriter::new(dir.clone());
755            MemWriter::write_entity(&writer, std::path::Path::new("seed.md"), SEED.as_bytes())
756                .unwrap();
757            MemWriter::commit(&writer, "seed", &crate::vcs::CommitContext::internal()).unwrap();
758        }
759        let mount = crate::Mount {
760            mem: "specs".to_string(),
761            schema: Some(memstead_schema::SchemaRef::new(
762                "default",
763                semver::Version::new(1, 0, 0),
764            )),
765            storage: crate::MountStorage::Folder { path: dir.clone() },
766            capability: crate::MountCapability::Write,
767            lifecycle: crate::MountLifecycle::Eager,
768            cross_linkable: false,
769            migration_target: None,
770        };
771        let backend =
772            Box::new(crate::storage::FilesystemMemWriter::new(dir)) as Box<dyn crate::MemBackend>;
773        crate::Engine::from_mounts(vec![(mount, backend)]).unwrap()
774    }
775
776    fn create(engine: &mut crate::Engine, title: &str, note: &str) -> String {
777        let outcome = engine
778            .create_entity(
779                crate::CreateEntityArgs {
780                    mem: "specs".to_string(),
781                    title: title.to_string(),
782                    entity_type: "spec".to_string(),
783                    sections: [
784                        ("identity".to_string(), "x".to_string()),
785                        ("purpose".to_string(), "y".to_string()),
786                    ]
787                    .into_iter()
788                    .collect(),
789                    metadata: Default::default(),
790                    relations: Vec::new(),
791                    anchors: Vec::new(),
792                    dry_run: false,
793                },
794                crate::vcs::Actor::Cli,
795                None,
796                Some(note),
797            )
798            .unwrap();
799        outcome.id.0
800    }
801
802    fn update(engine: &mut crate::Engine, id: &str, note: &str) {
803        engine
804            .update_entity(
805                crate::UpdateEntityArgs {
806                    id: crate::EntityId(id.to_string()),
807                    expected_hash: None,
808                    sections: [("identity".to_string(), format!("touched: {note}"))]
809                        .into_iter()
810                        .collect(),
811                    append_sections: Default::default(),
812                    patch_sections: Default::default(),
813                    sections_unset: Vec::new(),
814                    metadata: Default::default(),
815                    metadata_unset: Vec::new(),
816                    dry_run: false,
817                    declare_relations: Vec::new(),
818                    anchors: Vec::new(),
819                    relations_unset: Vec::new(),
820                    anchors_unset: Vec::new(),
821                },
822                crate::vcs::Actor::App,
823                None,
824                Some(note),
825            )
826            .unwrap();
827    }
828
829    #[test]
830    fn folder_history_serves_touches_with_stated_limitations() {
831        let tmp = tempfile::TempDir::new().unwrap();
832        let mut engine = folder_engine(&tmp);
833        let id = create(&mut engine, "Story", "born");
834        update(&mut engine, &id, "grew");
835
836        let report = engine.entity_history("specs", &id, None, None).unwrap();
837        assert_eq!(report.total_recorded, 2);
838        assert_eq!(report.touches.len(), 2);
839        // Newest first: the update, then the create.
840        assert_eq!(report.touches[0].verb.as_deref(), Some("update"));
841        assert_eq!(report.touches[0].note.as_deref(), Some("grew"));
842        assert_eq!(report.touches[0].actor.as_deref(), Some("app"));
843        assert_eq!(report.touches[1].verb.as_deref(), Some("create"));
844        assert_eq!(report.touches[1].actor.as_deref(), Some("cli"));
845        assert_eq!(report.story_start, super::StoryStart::Recorded);
846        assert!(
847            report
848                .limitations
849                .iter()
850                .any(|l| l.contains("rename records carry only the post-rename id")),
851            "folder limitations must be stated: {:?}",
852            report.limitations
853        );
854        // Touches of the *other* entity (the seed) never appear.
855        assert!(report.touches.iter().all(|t| t.id_at_touch == id));
856    }
857
858    #[test]
859    fn folder_rename_truncates_visibly_not_silently() {
860        let tmp = tempfile::TempDir::new().unwrap();
861        let mut engine = folder_engine(&tmp);
862        let id = create(&mut engine, "Before Rename", "born");
863        let outcome = engine
864            .rename_entity(
865                crate::RenameEntityArgs {
866                    id: crate::EntityId(id.clone()),
867                    expected_hash: None,
868                    new_title: "After Rename".to_string(),
869                },
870                crate::vcs::Actor::Cli,
871                None,
872                Some("renamed"),
873            )
874            .unwrap();
875        let new_id = outcome.new_id.0;
876
877        // The folder changelog records renames under the post-rename
878        // id only — the story under the new id starts at the rename
879        // and SAYS so (never an unexplained short history).
880        let report = engine.entity_history("specs", &new_id, None, None).unwrap();
881        assert_eq!(report.touches[0].verb.as_deref(), Some("rename"));
882        assert!(report.touches[0].renamed_from.is_none());
883        match &report.story_start {
884            super::StoryStart::Truncated { reason } => {
885                assert!(
886                    reason.contains("not the entity's creation"),
887                    "reason must explain the truncation: {reason}"
888                );
889            }
890            other => panic!("expected visible truncation, got {other:?}"),
891        }
892    }
893
894    #[test]
895    fn reused_id_never_absorbs_the_previous_holders_story() {
896        // Rename an entity away, then create a NEW entity under the
897        // freed slug: the newcomer's story must start at ITS create —
898        // pre-fix it absorbed the previous holder's touches and
899        // presented the polluted story as `Recorded` (grading-gate
900        // finding, plan 03/02).
901        let tmp = tempfile::TempDir::new().unwrap();
902        let mut engine = folder_engine(&tmp);
903        let id = create(&mut engine, "Slot", "first holder");
904        update(&mut engine, &id, "first holder grew");
905        engine
906            .rename_entity(
907                crate::RenameEntityArgs {
908                    id: crate::EntityId(id.clone()),
909                    expected_hash: None,
910                    new_title: "Slot Moved".to_string(),
911                },
912                crate::vcs::Actor::Cli,
913                None,
914                Some("moved away"),
915            )
916            .unwrap();
917        let reused = create(&mut engine, "Slot", "second holder");
918        assert_eq!(reused, id, "the slug is reused");
919
920        let report = engine.entity_history("specs", &reused, None, None).unwrap();
921        assert_eq!(report.total_recorded, 1, "only its own birth: {report:#?}");
922        assert_eq!(report.touches[0].verb.as_deref(), Some("create"));
923        assert_eq!(report.touches[0].note.as_deref(), Some("second holder"));
924        assert!(matches!(report.story_start, super::StoryStart::Recorded));
925    }
926
927    #[test]
928    fn refusals_are_typed_never_empty_stories() {
929        let tmp = tempfile::TempDir::new().unwrap();
930        let mut engine = folder_engine(&tmp);
931        let id = create(&mut engine, "Real", "born");
932
933        // Unknown mem.
934        let err = engine.entity_history("ghost", &id, None, None).unwrap_err();
935        assert_eq!(err.code(), "UNKNOWN_MEM");
936        // Unknown entity — never an empty history.
937        let err = engine
938            .entity_history("specs", "specs--nope", None, None)
939            .unwrap_err();
940        assert_eq!(err.code(), "ENTITY_NOT_FOUND");
941        // Garbage cursor.
942        let err = engine
943            .entity_history("specs", &id, None, Some("zzz@0"))
944            .unwrap_err();
945        assert_eq!(err.code(), "INVALID_CURSOR");
946        let err = engine
947            .entity_history("specs", &id, None, Some("no-separator"))
948            .unwrap_err();
949        assert_eq!(err.code(), "INVALID_CURSOR");
950    }
951
952    #[test]
953    fn pre_changelog_entity_states_the_empty_record() {
954        // The seed entity was written outside the engine — no
955        // changelog line exists for it. Its story is empty AND says
956        // why, distinguishable from "exists, untouched" by the stated
957        // truncation.
958        let tmp = tempfile::TempDir::new().unwrap();
959        let engine = folder_engine(&tmp);
960        let report = engine
961            .entity_history("specs", "specs--seed", None, None)
962            .unwrap();
963        assert!(report.touches.is_empty());
964        assert!(matches!(
965            report.story_start,
966            super::StoryStart::Truncated { .. }
967        ));
968    }
969
970    /// An archive mount answers the provenance read with the rationale
971    /// it seals per entity; where the payload carries no entry, or the
972    /// archive ships no payload, the block says so instead of refusing.
973    /// The history read keeps refusing: an archive records no touches.
974    #[test]
975    fn archive_mounts_serve_the_sealed_rationale_as_provenance() {
976        struct SealedBackend {
977            inner: crate::storage::InMemoryBackend,
978            payload: Option<Vec<u8>>,
979        }
980        impl crate::backend::MemBackend for SealedBackend {
981            fn list_entities(
982                &self,
983            ) -> Result<Vec<std::path::PathBuf>, crate::backend::BackendError> {
984                self.inner.list_entities()
985            }
986            fn read_entity(
987                &self,
988                rel: &std::path::Path,
989            ) -> Result<Option<Vec<u8>>, crate::backend::BackendError> {
990                self.inner.read_entity(rel)
991            }
992            fn write_entity(
993                &self,
994                p: &std::path::Path,
995                b: &[u8],
996            ) -> Result<(), crate::backend::BackendError> {
997                self.inner.write_entity(p, b)
998            }
999            fn delete_entity(
1000                &self,
1001                p: &std::path::Path,
1002            ) -> Result<(), crate::backend::BackendError> {
1003                self.inner.delete_entity(p)
1004            }
1005            fn move_entity(
1006                &self,
1007                f: &std::path::Path,
1008                t: &std::path::Path,
1009            ) -> Result<(), crate::backend::BackendError> {
1010                self.inner.move_entity(f, t)
1011            }
1012            fn commit(
1013                &self,
1014                m: &str,
1015                c: &crate::vcs::CommitContext<'_>,
1016            ) -> Result<crate::storage::CommitId, crate::backend::BackendError> {
1017                self.inner.commit(m, c)
1018            }
1019            fn append_provenance(
1020                &self,
1021                r: &crate::provenance::Provenance,
1022            ) -> Result<(), crate::backend::BackendError> {
1023                self.inner.append_provenance(r)
1024            }
1025            fn read_provenance(
1026                &self,
1027                c: Option<&str>,
1028            ) -> Result<Vec<crate::provenance::Provenance>, crate::backend::BackendError>
1029            {
1030                self.inner.read_provenance(c)
1031            }
1032            fn read_archive_provenance(
1033                &self,
1034            ) -> Result<Option<Vec<u8>>, crate::backend::BackendError> {
1035                Ok(self.payload.clone())
1036            }
1037        }
1038        fn engine_with(payload: Option<Vec<u8>>) -> crate::Engine {
1039            let dir = tempfile::TempDir::new().unwrap();
1040            let inner = crate::storage::InMemoryBackend::new();
1041            crate::backend::MemBackend::write_entity(
1042                &inner,
1043                std::path::Path::new("seed.md"),
1044                SEED.as_bytes(),
1045            )
1046            .unwrap();
1047            crate::backend::MemBackend::write_entity(
1048                &inner,
1049                std::path::Path::new("bare.md"),
1050                SEED.replace("# Seed", "# Bare").as_bytes(),
1051            )
1052            .unwrap();
1053            crate::backend::MemBackend::commit(
1054                &inner,
1055                "seed",
1056                &crate::vcs::CommitContext::internal(),
1057            )
1058            .unwrap();
1059            let mount = crate::Mount {
1060                mem: "specs".to_string(),
1061                schema: Some(memstead_schema::SchemaRef::new(
1062                    "default",
1063                    semver::Version::new(1, 0, 0),
1064                )),
1065                storage: crate::MountStorage::Archive {
1066                    path: dir.path().join("sealed.mem"),
1067                },
1068                capability: crate::MountCapability::Write,
1069                lifecycle: crate::MountLifecycle::Eager,
1070                cross_linkable: false,
1071                migration_target: None,
1072            };
1073            crate::Engine::from_mounts(vec![(
1074                mount,
1075                Box::new(SealedBackend { inner, payload }) as Box<dyn crate::MemBackend>,
1076            )])
1077            .unwrap()
1078        }
1079        let payload = serde_json::json!({
1080            "format": 1,
1081            "history": "summarised",
1082            "entities": {
1083                "seed": {
1084                    "rationale": "seeded so the graph starts non-empty",
1085                    "kind": "create",
1086                    "timestamp": "2026-06-24T11:32:02Z",
1087                    "actor": "agent"
1088                }
1089            }
1090        });
1091        let engine = engine_with(Some(serde_json::to_vec(&payload).unwrap()));
1092        let prov = engine.entity_provenance("specs", "specs--seed").unwrap();
1093        let sealed = prov.sealed.expect("archive mount serves the sealed block");
1094        assert!(sealed.carried);
1095        assert_eq!(
1096            sealed.rationale.as_deref(),
1097            Some("seeded so the graph starts non-empty")
1098        );
1099        assert_eq!(sealed.kind.as_deref(), Some("create"));
1100        assert_eq!(sealed.actor.as_deref(), Some("agent"));
1101        assert_eq!(sealed.history.as_deref(), Some("summarised"));
1102        assert!(prov.created_by.is_none() && prov.last_modified_by.is_none());
1103        // An entity the payload does not name: stated as not carried.
1104        let bare = engine.entity_provenance("specs", "specs--bare").unwrap();
1105        let sealed = bare.sealed.unwrap();
1106        assert!(!sealed.carried && sealed.rationale.is_none());
1107        assert_eq!(sealed.history.as_deref(), Some("summarised"));
1108        // An unknown id still refuses, as the history read does.
1109        assert_eq!(
1110            engine
1111                .entity_provenance("specs", "specs--ghost")
1112                .unwrap_err()
1113                .code(),
1114            "ENTITY_NOT_FOUND"
1115        );
1116        // An archive with no payload at all: not carried, no history word.
1117        let engine = engine_with(None);
1118        let none = engine.entity_provenance("specs", "specs--seed").unwrap();
1119        let sealed = none.sealed.unwrap();
1120        assert!(!sealed.carried && sealed.history.is_none());
1121        // The history read keeps its refusal.
1122        assert_eq!(
1123            engine
1124                .entity_history("specs", "specs--seed", None, None)
1125                .unwrap_err()
1126                .code(),
1127            "INVALID_INPUT"
1128        );
1129    }
1130
1131    #[test]
1132    fn archive_mounts_refuse_rather_than_fabricate_emptiness() {
1133        // An archive-declared mount whose backend nonetheless serves
1134        // the store: the storage arm must refuse before the seam's
1135        // history-free `read_provenance` can masquerade as an empty
1136        // story.
1137        let dir = tempfile::TempDir::new().unwrap();
1138        let backend = crate::storage::InMemoryBackend::new();
1139        crate::backend::MemBackend::write_entity(
1140            &backend,
1141            std::path::Path::new("seed.md"),
1142            SEED.as_bytes(),
1143        )
1144        .unwrap();
1145        crate::backend::MemBackend::commit(
1146            &backend,
1147            "seed",
1148            &crate::vcs::CommitContext::internal(),
1149        )
1150        .unwrap();
1151        let mount = crate::Mount {
1152            mem: "specs".to_string(),
1153            schema: Some(memstead_schema::SchemaRef::new(
1154                "default",
1155                semver::Version::new(1, 0, 0),
1156            )),
1157            storage: crate::MountStorage::Archive {
1158                path: dir.path().join("sealed.mem"),
1159            },
1160            capability: crate::MountCapability::Write,
1161            lifecycle: crate::MountLifecycle::Eager,
1162            cross_linkable: false,
1163            migration_target: None,
1164        };
1165        let engine = crate::Engine::from_mounts(vec![(
1166            mount,
1167            Box::new(backend) as Box<dyn crate::MemBackend>,
1168        )])
1169        .unwrap();
1170        let err = engine
1171            .entity_history("specs", "specs--seed", None, None)
1172            .unwrap_err();
1173        assert_eq!(err.code(), "INVALID_INPUT");
1174    }
1175
1176    #[test]
1177    fn pages_compose_without_gaps_or_duplicates() {
1178        let tmp = tempfile::TempDir::new().unwrap();
1179        let mut engine = folder_engine(&tmp);
1180        let id = create(&mut engine, "Paged", "born");
1181        for i in 0..5 {
1182            update(&mut engine, &id, &format!("touch {i}"));
1183        }
1184
1185        let full = engine.entity_history("specs", &id, None, None).unwrap();
1186        assert_eq!(full.total_recorded, 6);
1187        assert!(full.next_cursor.is_none());
1188
1189        // Walk in pages of 2 and re-compose.
1190        let mut collected: Vec<super::EntityTouch> = Vec::new();
1191        let mut cursor: Option<String> = None;
1192        loop {
1193            let page = engine
1194                .entity_history("specs", &id, Some(2), cursor.as_deref())
1195                .unwrap();
1196            assert!(page.touches.len() <= 2);
1197            assert_eq!(page.total_recorded, 6, "every page states the whole");
1198            collected.extend(page.touches.clone());
1199            match page.next_cursor {
1200                Some(c) => cursor = Some(c),
1201                None => break,
1202            }
1203        }
1204        assert_eq!(
1205            collected, full.touches,
1206            "paged walk must equal the single-page story exactly"
1207        );
1208    }
1209}