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    /// On a proposal merge (or amend) touch: the merger's identity from
96    /// the `Merged-By:` trailer, beside `identity` (the proposer on the
97    /// merge commit). Never compared by the independence gate.
98    #[serde(skip_serializing_if = "Option::is_none")]
99    pub merged_by: Option<String>,
100    /// On a proposal merge (or amend) touch: the proposal's id from the
101    /// `Proposal:` trailer.
102    #[serde(skip_serializing_if = "Option::is_none")]
103    pub proposal: Option<String>,
104    /// True when this touch is a proposal merge that created the entity
105    /// in the target (the id sits in the commit's `Created:` trailer):
106    /// the story's birth, as a `create` would be.
107    #[serde(skip_serializing_if = "std::ops::Not::not", default)]
108    pub created_by_merge: bool,
109}
110
111/// Where the returned story starts — the visible-truncation contract:
112/// whatever the record cannot reach is stated, never silent.
113#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
114#[serde(tag = "kind", rename_all = "lowercase")]
115pub enum StoryStart {
116    /// The oldest recorded touch is the entity's creation — the full
117    /// recorded story is reachable through the pages.
118    Recorded,
119    /// The story stops before the entity's first appearance, and here
120    /// is why (unstitchable rename, records predating the changelog,
121    /// an adopted mem with no history…).
122    Truncated { reason: String },
123}
124
125/// Result of [`Engine::entity_history`] — one page of the newest-first
126/// touch feed plus the explicit bounds of what it omits.
127#[derive(Debug, Clone, Serialize)]
128pub struct EntityHistoryReport {
129    pub mem: String,
130    /// The entity's current id (the query key).
131    pub entity_id: String,
132    /// This page's touches, newest first.
133    pub touches: Vec<EntityTouch>,
134    /// Total recorded touches across all pages — with `next_cursor`,
135    /// this states exactly what a page omits.
136    pub total_recorded: usize,
137    /// Opaque continuation: pass back as `cursor` for the next page.
138    /// `None` = this page ends the recorded story.
139    #[serde(skip_serializing_if = "Option::is_none")]
140    pub next_cursor: Option<String>,
141    /// Where the recorded story starts (visible-truncation contract).
142    pub story_start: StoryStart,
143    /// Stated per-backend gaps (folder rename stitching, batch
144    /// attribution). Empty on full-fidelity backends.
145    #[serde(skip_serializing_if = "Vec::is_empty", default)]
146    pub limitations: Vec<String>,
147}
148
149/// Split a rename record's `entity_id` field (`"old → new"`) into the
150/// pair. Cross-mem peer rewrites (parenthetical qualifier) and
151/// malformed values return `None` — they modify wiki-link bodies in a
152/// peer mem, never the entity itself.
153pub(crate) fn parse_rename_pair(field: &str) -> Option<(String, String)> {
154    if field.contains("(cross-mem rewrite") {
155        return None;
156    }
157    let mut parts = field.splitn(2, " → ");
158    let old = parts.next()?.trim();
159    let new = parts.next()?.trim();
160    if old.is_empty() || new.is_empty() {
161        return None;
162    }
163    Some((old.to_string(), new.to_string()))
164}
165
166/// One derived provenance record — who performed a boundary touch of
167/// an entity's story, in what declared role, when. Served by the entity read's opt-in provenance block.
168#[derive(Debug, Clone, serde::Serialize)]
169pub struct ProvenanceRecord {
170    /// Actor category (`agent` / `cli` / `app` / `external` /
171    /// `unknown`), from the recorded trailer.
172    #[serde(skip_serializing_if = "Option::is_none")]
173    pub actor: Option<String>,
174    /// Client identity (`name@version`) when recorded.
175    #[serde(skip_serializing_if = "Option::is_none")]
176    pub client: Option<String>,
177    /// The caller-declared role, or `"unspecified"` — absence is
178    /// served as the explicit cannot-confirm value, never as any
179    /// real role.
180    pub role: String,
181    /// The caller-declared identity, when one was recorded — the
182    /// independence gate's only comparator.
183    /// Absence downgrades comparisons to `unconfirmable`.
184    #[serde(skip_serializing_if = "Option::is_none")]
185    pub identity: Option<String>,
186    /// Touch time, seconds since unix epoch.
187    pub timestamp: i64,
188    /// Backend-native reference (commit sha / ledger timestamp).
189    pub reference: String,
190    /// The mutation verb of the touch (`create` / `update` / `rename` /
191    /// `retype` / `relate` / …), when the record carries one — so a
192    /// reader can tell a type change from an edit without opening the
193    /// commit.
194    #[serde(skip_serializing_if = "Option::is_none")]
195    pub verb: Option<String>,
196    /// On a touch a proposal merge made: the merger's identity
197    /// (`Merged-By:`), beside `identity`, which names the proposer on
198    /// the merge commit and the merger on the amend commit.
199    #[serde(skip_serializing_if = "Option::is_none")]
200    pub merged_by: Option<String>,
201    /// On a touch a proposal merge made: the proposal's id.
202    #[serde(skip_serializing_if = "Option::is_none")]
203    pub proposal: Option<String>,
204    /// On a touch a proposal merge made: the disposition the target's
205    /// proposal record holds for this entity under that proposal
206    /// (`adopt` or `adopt_with_changes`), when the record carries it.
207    #[serde(skip_serializing_if = "Option::is_none")]
208    pub disposition: Option<String>,
209    /// On a touch a proposal merge made: the proposal in the owner's
210    /// words, when the target's proposal record carries a description
211    /// for that proposal.
212    #[serde(skip_serializing_if = "Option::is_none")]
213    pub proposal_description: Option<String>,
214}
215
216/// The entity read's derived provenance block: created-by and
217/// last-modified-by, derived from the append-only history record —
218/// never from anything an agent can edit after the fact.
219#[derive(Debug, Clone, serde::Serialize)]
220pub struct EntityProvenance {
221    /// The creation record. `None` when the recorded story does not
222    /// start at the entity's creation (adopted/migrated mems) — the
223    /// honesty pattern: absence stated, never fabricated.
224    #[serde(skip_serializing_if = "Option::is_none")]
225    pub created_by: Option<ProvenanceRecord>,
226    /// The newest recorded touch.
227    #[serde(skip_serializing_if = "Option::is_none")]
228    pub last_modified_by: Option<ProvenanceRecord>,
229    /// True when the recorded story is truncated (its oldest touch is
230    /// not the creation) — `created_by` is then absent.
231    #[serde(skip_serializing_if = "std::ops::Not::not")]
232    pub story_truncated: bool,
233    /// Derived `verification` check state:
234    /// `never_checked` | `checked_ok` | `check_failed` | `check_stale`
235    /// — computed by comparing the newest verification record's
236    /// entity-hash against the current one, never stamped. Kind-scoped:
237    /// a conformance record never supersedes it.
238    pub check_state: String,
239    /// The newest `verification` record, when one exists.
240    #[serde(skip_serializing_if = "Option::is_none")]
241    pub last_check: Option<crate::check::CheckRecord>,
242    /// The trust class of the CHECK PROSE on this entity: the `method`
243    /// notes that every surface renders verbatim, across the verification
244    /// record, the conformance record and each foreign kind.
245    /// `Some("third-party")` when ANY of them was written by a party other
246    /// than this workspace.
247    ///
248    /// The note is written by whatever agent recorded the check, which in a
249    /// workspace that points a foreign model at its ledger, or that
250    /// transcribes an outside finding under the outsider's handle, is not
251    /// the workspace itself. On an archive mount the value is the one the
252    /// exporting workspace SEALED ([`crate::check::SealedCheck::origin`]),
253    /// because only that workspace knew which identities were its own; on
254    /// every other mount it is derived from this deployment's declared
255    /// identities ([`crate::Engine::check_row_origin_class`]).
256    ///
257    /// One field for all of them, and set if any one is foreign, so a
258    /// renderer contains every note it prints rather than guessing per
259    /// line. That over-contains the owner's own note on an entity that also
260    /// carries a stranger's, which is the safe direction: the alternative
261    /// is a stranger's sentence printed as the report's own voice.
262    ///
263    /// Absent when nothing foreign was recorded, so every response that has
264    /// nothing to warn about is byte-unchanged.
265    #[serde(skip_serializing_if = "Option::is_none")]
266    pub check_prose_origin: Option<String>,
267    /// Derived `conformance` state — the same four values, computed
268    /// against the newest conformance record with pin-awareness (a
269    /// schema re-pin stales it). `never_checked` when no conformance
270    /// record exists, which is every pre-kind workspace.
271    pub conformance_state: String,
272    /// The newest `conformance` record, when one exists.
273    #[serde(skip_serializing_if = "Option::is_none")]
274    pub last_conformance_check: Option<crate::check::CheckRecord>,
275    /// The newest record per foreign `x-<name>` kind, in kind order:
276    /// recorded verbatim, listed here, never aggregated into a state.
277    /// Empty (and absent from the JSON) when none was recorded.
278    #[serde(skip_serializing_if = "Vec::is_empty")]
279    pub foreign_checks: Vec<crate::check::CheckRecord>,
280    /// On an archive mount: the authoring rationale the archive seals
281    /// for this entity (`.memstead/provenance.json`), in place of the
282    /// recorded touches an archive does not carry. Absent on source
283    /// mems.
284    #[serde(skip_serializing_if = "Option::is_none")]
285    pub sealed: Option<SealedProvenance>,
286}
287
288/// The per-entity authoring rationale an installed archive carries,
289/// read from the payload `export` seals; the reader never modifies the
290/// archive. `carried: false` says so explicitly when the archive ships
291/// no payload, or a payload with no entry for this entity: absence is
292/// stated, never substituted.
293#[derive(Debug, Clone, serde::Serialize)]
294pub struct SealedProvenance {
295    /// Whether the archive carries a rationale for this entity.
296    pub carried: bool,
297    /// The payload's history disposition (`summarised`) when a payload
298    /// exists at all.
299    #[serde(skip_serializing_if = "Option::is_none")]
300    pub history: Option<String>,
301    /// The entity's authoring rationale (the most recent mutation note
302    /// sealed for it).
303    #[serde(skip_serializing_if = "Option::is_none")]
304    pub rationale: Option<String>,
305    /// The mutation kind that note rode on (`create` / `update` / ...).
306    #[serde(skip_serializing_if = "Option::is_none")]
307    pub kind: Option<String>,
308    /// When it was recorded, RFC 3339 as sealed.
309    #[serde(skip_serializing_if = "Option::is_none")]
310    pub timestamp: Option<String>,
311    /// The actor category recorded with it.
312    #[serde(skip_serializing_if = "Option::is_none")]
313    pub actor: Option<String>,
314    /// Whether the archive seals a check record for this entity
315    /// (`.memstead/checks.json`). The check states above derive from
316    /// those records alone on an archive mount; when `false` every
317    /// state reads `never_checked` and `checks_reason` says why.
318    pub checks_carried: bool,
319    /// Why no sealed check record answers for this entity: the archive
320    /// carries no check records at all, or none for this entity. Absent
321    /// when one is carried.
322    #[serde(skip_serializing_if = "Option::is_none")]
323    pub checks_reason: Option<String>,
324}
325
326fn touch_to_record(t: &EntityTouch) -> ProvenanceRecord {
327    ProvenanceRecord {
328        actor: t.actor.clone(),
329        client: t.client.clone(),
330        role: t.role.clone().unwrap_or_else(|| "unspecified".to_string()),
331        identity: t.identity.clone(),
332        timestamp: t.timestamp,
333        reference: t.reference.clone(),
334        verb: t.verb.clone(),
335        merged_by: t.merged_by.clone(),
336        proposal: t.proposal.clone(),
337        disposition: None,
338        proposal_description: None,
339    }
340}
341
342impl Engine {
343    /// Derive an entity's provenance block:
344    /// created-by (the oldest recorded touch, only when it IS the
345    /// creation) and last-modified-by (the newest touch), each with
346    /// actor identity, client, declared role, and timestamp — read
347    /// from the same append-only record `entity_history` serves, so
348    /// no verb can alter it after the fact. Pages through the full
349    /// story to reach the creation record when histories exceed one
350    /// page.
351    pub fn entity_provenance(
352        &self,
353        mem: &str,
354        entity_id: &str,
355    ) -> Result<EntityProvenance, EngineError> {
356        // An archive records no touches at the engine seam, but it
357        // carries the rationale `export` sealed per entity: that is the
358        // provenance an installed mem can answer with.
359        if matches!(
360            self.find_mount(mem)?.mount.storage,
361            MountStorage::Archive { .. }
362        ) {
363            return self.sealed_provenance(mem, entity_id);
364        }
365        let mut report = self.entity_history(mem, entity_id, Some(HISTORY_PAGE_MAX), None)?;
366        let newest = report.touches.first().cloned();
367        // Walk to the last page for the oldest touch.
368        while let Some(cursor) = report.next_cursor.clone() {
369            report = self.entity_history(mem, entity_id, Some(HISTORY_PAGE_MAX), Some(&cursor))?;
370        }
371        let oldest = report.touches.last().or(newest.as_ref()).cloned();
372        let truncated = !matches!(report.story_start, StoryStart::Recorded);
373        let (check_state, last_check) = self.entity_check_state(mem, entity_id)?;
374        let (conformance_state, last_conformance_check) =
375            self.entity_conformance_state(mem, entity_id)?;
376        // A touch a proposal merge made names its proposal; the
377        // disposition it landed under and the proposal's description
378        // are read from the target's own record, never from the commit
379        // (the record is the merge's second write, in the same commit).
380        let record = if oldest.as_ref().is_some_and(|t| t.proposal.is_some())
381            || newest.as_ref().is_some_and(|t| t.proposal.is_some())
382        {
383            self.read_proposal_record(mem).ok().flatten()
384        } else {
385            None
386        };
387        let slug = crate::EntityId(entity_id.to_string()).path().to_string();
388        let with_disposition = |t: &EntityTouch| -> ProvenanceRecord {
389            let mut rec = touch_to_record(t);
390            if let (Some(pid), Some(record)) = (t.proposal.as_deref(), record.as_ref())
391                && let Some(entry) = record.proposals.iter().find(|p| p.id == pid)
392            {
393                rec.disposition = entry.entities.get(&slug).map(|d| d.disposition.clone());
394                rec.proposal_description = entry.description.clone();
395            }
396            rec
397        };
398        Ok(EntityProvenance {
399            created_by: match (&oldest, truncated) {
400                (Some(t), false) => Some(with_disposition(t)),
401                _ => None,
402            },
403            last_modified_by: newest.as_ref().map(with_disposition),
404            story_truncated: truncated,
405            check_state: check_state.as_str().to_string(),
406            check_prose_origin: self.foreign_check_prose_marker(
407                mem,
408                entity_id,
409                [last_check.as_ref(), last_conformance_check.as_ref()],
410            ),
411            last_check,
412            conformance_state: conformance_state.as_str().to_string(),
413            last_conformance_check,
414            foreign_checks: self.latest_foreign_checks(mem, entity_id),
415            sealed: None,
416        })
417    }
418
419    /// The provenance block of an entity on an archive mount: the sealed
420    /// rationale where the payload carries one, `carried: false` where
421    /// it does not, and the check states derived from the sealed check
422    /// records (`.memstead/checks.json`) the same way a workspace derives
423    /// them from its ledger: the sealed record's hash against the sealed
424    /// entity's content hash, so a record carried across a later edit
425    /// reads stale. An archive without the member, or without a record
426    /// for this entity, reads `never_checked` with the reason stated
427    /// (`checks_carried: false`, `checks_reason`); a workspace ledger
428    /// beside the mount is never consulted. Refuses `ENTITY_NOT_FOUND`
429    /// for an id the mount does not serve, as the history read does.
430    fn sealed_provenance(
431        &self,
432        mem: &str,
433        entity_id: &str,
434    ) -> Result<EntityProvenance, EngineError> {
435        let known = self
436            .store
437            .all_entities()
438            .any(|e| e.mem == mem && e.id.0 == entity_id);
439        if !known {
440            return Err(EngineError::NotFound {
441                id: entity_id.to_string(),
442            });
443        }
444        let id = crate::EntityId(entity_id.to_string());
445        let (checks_carried, checks_reason) = match self.archive_checks_for(mem) {
446            None => (
447                false,
448                Some(
449                    "the archive carries no check records; every state reads never_checked"
450                        .to_string(),
451                ),
452            ),
453            Some(sealed) if sealed.kinds_of(id.path()).next().is_none() => (
454                false,
455                Some("the archive carries no check record for this entity".to_string()),
456            ),
457            Some(_) => (true, None),
458        };
459        let sealed = match self.archive_provenance_for(mem) {
460            Some(payload) => {
461                let history = Some(
462                    serde_json::to_value(payload.history)
463                        .ok()
464                        .and_then(|v| v.as_str().map(str::to_string))
465                        .unwrap_or_else(|| "unknown".to_string()),
466                );
467                match payload.entity(id.path()) {
468                    Some(rec) => SealedProvenance {
469                        carried: rec.rationale.is_some(),
470                        history,
471                        rationale: rec.rationale.clone(),
472                        kind: rec.kind.clone(),
473                        timestamp: rec.timestamp.clone(),
474                        actor: rec.actor.clone(),
475                        checks_carried,
476                        checks_reason: checks_reason.clone(),
477                    },
478                    None => SealedProvenance {
479                        carried: false,
480                        history,
481                        rationale: None,
482                        kind: None,
483                        timestamp: None,
484                        actor: None,
485                        checks_carried,
486                        checks_reason: checks_reason.clone(),
487                    },
488                }
489            }
490            None => SealedProvenance {
491                carried: false,
492                history: None,
493                rationale: None,
494                kind: None,
495                timestamp: None,
496                actor: None,
497                checks_carried,
498                checks_reason: checks_reason.clone(),
499            },
500        };
501        let (check_state, last_check) = self.entity_check_state(mem, entity_id)?;
502        let (conformance_state, last_conformance_check) =
503            self.entity_conformance_state(mem, entity_id)?;
504        Ok(EntityProvenance {
505            created_by: None,
506            last_modified_by: None,
507            story_truncated: false,
508            check_state: check_state.as_str().to_string(),
509            check_prose_origin: self.foreign_check_prose_marker(
510                mem,
511                entity_id,
512                [last_check.as_ref(), last_conformance_check.as_ref()],
513            ),
514            last_check,
515            conformance_state: conformance_state.as_str().to_string(),
516            last_conformance_check,
517            foreign_checks: self.latest_foreign_checks(mem, entity_id),
518            sealed: Some(sealed),
519        })
520    }
521
522    /// The trust class to report for a check record's own prose, and only
523    /// when it is the foreign one: `Some("third-party")` where the note was
524    /// written by a party other than this workspace, `None` otherwise, so
525    /// the field appears exactly where it warns and every other response is
526    /// byte-unchanged.
527    ///
528    /// On an archive mount the answer is the one the exporting workspace
529    /// sealed beside the row, because that workspace is the only party that
530    /// knew which identities were its own; a member sealed without the field
531    /// falls through to this deployment's reading, as it did before the
532    /// field existed. This is the reader that makes
533    /// [`crate::check::SealedCheck::origin`] load-bearing: the sealed
534    /// `method` note is carried into the record every surface renders, so
535    /// without it a publisher's checker prose reaches a reading agent as the
536    /// consumer's own.
537    fn foreign_check_prose_marker(
538        &self,
539        mem: &str,
540        entity_id: &str,
541        records: [Option<&crate::check::CheckRecord>; 2],
542    ) -> Option<String> {
543        // Nothing can be foreign in the default deployment: with no declared
544        // owner identities on a first-party mem every row reads as the
545        // workspace's own, and only an archive mount can carry a sealed class.
546        // Leaving early keeps the marker from re-reading and re-parsing the
547        // whole check ledger once more per provenance read.
548        if !self.declares_owner_identities()
549            && !self.is_archive_mount(mem)
550            && !self.mem_origin_class(mem).is_third_party()
551        {
552            return None;
553        }
554        let foreign = |rec: &crate::check::CheckRecord| {
555            self.check_row_prose_origin(mem, entity_id, rec)
556                .is_third_party()
557        };
558        let any_foreign = records.into_iter().flatten().any(foreign)
559            || self
560                .latest_foreign_checks(mem, entity_id)
561                .iter()
562                .any(foreign);
563        any_foreign.then(|| crate::render::OriginClass::ThirdParty.as_wire().to_string())
564    }
565
566    /// An entity's recorded history: every touch, newest-first, with
567    /// rename chains followed so the story starts at the entity's
568    /// first appearance under any prior id. Bounded and pageable —
569    /// `page_size` clamps to [`HISTORY_PAGE_MAX`], `cursor` continues
570    /// a prior page (`INVALID_CURSOR` when it matches no touch).
571    ///
572    /// Refusals: `UNKNOWN_MEM`, `ENTITY_NOT_FOUND` (an unknown id
573    /// never yields an empty story), `INVALID_INPUT` on archive
574    /// mounts (their seam records no history — refusing beats
575    /// fabricating emptiness).
576    pub fn entity_history(
577        &self,
578        mem: &str,
579        entity_id: &str,
580        page_size: Option<usize>,
581        cursor: Option<&str>,
582    ) -> Result<EntityHistoryReport, EngineError> {
583        let m = self.find_mount(mem)?;
584
585        // An unknown entity refuses — marklessness-style honesty: the
586        // caller learns "no such entity", never an empty history that
587        // reads as "exists, untouched".
588        let known = self
589            .store
590            .all_entities()
591            .any(|e| e.mem == mem && e.id.0 == entity_id);
592        if !known {
593            return Err(EngineError::NotFound {
594                id: entity_id.to_string(),
595            });
596        }
597
598        let mut limitations: Vec<String> = Vec::new();
599
600        // ---- Collect the raw record, newest-first, per backend ----
601        let touches: Vec<EntityTouch> = match &m.mount.storage {
602            MountStorage::GitBranch { gitdir, branch } => match self.git_branch_ops.as_ref() {
603                Some(hook) => {
604                    let backend_changes = (hook.changes_since)(
605                        gitdir,
606                        branch,
607                        mem,
608                        crate::ops::EMPTY_TREE_SHA,
609                        crate::ops::RENAME_SIMILARITY_DEFAULT,
610                    )
611                    .map_err(EngineError::Backend)?;
612                    filter_notes_for_entity(entity_id, &backend_changes.notes)
613                }
614                None => {
615                    limitations.push(
616                        "this build carries no git-branch history walk — the recorded story \
617                         is not reachable"
618                            .to_string(),
619                    );
620                    Vec::new()
621                }
622            },
623            MountStorage::Folder { .. } | MountStorage::InMemory => {
624                limitations.push(
625                    "changelog-backed history: rename records carry only the post-rename id \
626                     (prior-id chains are not stitchable) and batch mutations record no \
627                     per-entity attribution on this backend"
628                        .to_string(),
629                );
630                let records = m
631                    .backend
632                    .read_provenance(None)
633                    .map_err(EngineError::Backend)?;
634                filter_provenance_for_entity(entity_id, &records)
635            }
636            MountStorage::Archive { .. } => {
637                return Err(EngineError::InvalidInput(format!(
638                    "mem '{mem}' is an archive mount — archives record no history at the \
639                     engine seam; open the source mem for the entity's story"
640                )));
641            }
642        };
643
644        // ---- Visible-truncation verdict ----
645        // The recorded story is complete exactly when its oldest touch
646        // is the entity's creation. Anything else — empty record,
647        // oldest touch mid-stream — states where and why it stops.
648        let story_start = match touches.last() {
649            // `batch-create` IS this entity's creation when it is the
650            // oldest touch — a batch-authored entity carries the same
651            // append-only provenance (role, identity trailers) as a
652            // single create, and treating it as truncation erased
653            // `created_by` for every batch-authored entity, which
654            // silently degraded the checks independence gate to
655            // `unconfirmable` (found 2026-08-28, graph-plans pilot).
656            // A proposal merge that lists the id under `Created:` brought
657            // the entity into the target: its creation, under the
658            // proposer's identity (plan-proposal 03).
659            Some(oldest)
660                if matches!(
661                    oldest.verb.as_deref(),
662                    Some("create") | Some("batch-create")
663                ) || oldest.created_by_merge =>
664            {
665                StoryStart::Recorded
666            }
667            Some(oldest) => StoryStart::Truncated {
668                reason: format!(
669                    "oldest recorded touch is a {} of `{}`, not the entity's creation — \
670                     earlier history (an unrecorded prior id, or records predating the \
671                     provenance log) is not reachable",
672                    oldest.verb.as_deref().unwrap_or("touch"),
673                    oldest.id_at_touch
674                ),
675            },
676            None => StoryStart::Truncated {
677                reason: "no touches recorded — the entity predates this mem's provenance \
678                         record (an adopted or migrated mem)"
679                    .to_string(),
680            },
681        };
682
683        // ---- Page ----
684        let size = page_size
685            .unwrap_or(HISTORY_PAGE_DEFAULT)
686            .clamp(1, HISTORY_PAGE_MAX);
687        let start_idx = match cursor {
688            None => 0,
689            Some(c) => {
690                let pos = parse_cursor(c).and_then(|(reference, k)| {
691                    touches
692                        .iter()
693                        .enumerate()
694                        .filter(|(_, t)| t.reference == reference)
695                        .nth(k)
696                        .map(|(i, _)| i + 1)
697                });
698                pos.ok_or_else(|| EngineError::InvalidChangesCursor {
699                    mem: mem.to_string(),
700                    since: c.to_string(),
701                })?
702            }
703        };
704        let total_recorded = touches.len();
705        let page: Vec<EntityTouch> = touches[start_idx.min(total_recorded)..]
706            .iter()
707            .take(size)
708            .cloned()
709            .collect();
710        let next_cursor = if start_idx + page.len() < total_recorded {
711            page.last().map(|last| {
712                let k = touches[..start_idx + page.len()]
713                    .iter()
714                    .filter(|t| t.reference == last.reference)
715                    .count()
716                    - 1;
717                format!("{}@{k}", last.reference)
718            })
719        } else {
720            None
721        };
722
723        Ok(EntityHistoryReport {
724            mem: mem.to_string(),
725            entity_id: entity_id.to_string(),
726            touches: page,
727            total_recorded,
728            next_cursor,
729            story_start,
730            limitations,
731        })
732    }
733}
734
735/// Cursor wire form: `<reference>@<occurrence>` where `occurrence`
736/// disambiguates touches sharing a reference (same-millisecond folder
737/// changelog lines; impossible for commit SHAs but the format stays
738/// uniform). Opaque to callers.
739fn parse_cursor(c: &str) -> Option<(String, usize)> {
740    let (reference, k) = c.rsplit_once('@')?;
741    if reference.is_empty() {
742        return None;
743    }
744    Some((reference.to_string(), k.parse().ok()?))
745}
746
747/// Newest→oldest single pass over the commit-note walk, tracking the
748/// entity's id backwards through authoritative rename records:
749/// `current` starts at the queried id; a rename whose *new* id equals
750/// `current` is that entity's rename touch and flips `current` to the
751/// old id, so every older touch is matched under its then-current id.
752/// A rename whose *old* id equals `current` is a different entity's
753/// departure from an id later reused — deliberately not a touch.
754///
755/// The walk STOPS at the entity's creation: a `create` of the tracked
756/// id is the story's birth, and anything older under the same id
757/// belonged to a previous holder of a reused slug (renamed away or
758/// deleted before this entity existed) — absorbing it would attribute
759/// a stranger's touches to this entity and present the polluted story
760/// as `Recorded` (found by plan 03/02's grading gate).
761pub(crate) fn filter_notes_for_entity(
762    entity_id: &str,
763    notes: &[crate::ops::agent_notes::CommitNote],
764) -> Vec<EntityTouch> {
765    let mut current = entity_id.to_string();
766    let mut out: Vec<EntityTouch> = Vec::new();
767    for n in notes {
768        let base = |id_at: &str| EntityTouch {
769            reference: n.sha.clone(),
770            timestamp: n.timestamp,
771            id_at_touch: id_at.to_string(),
772            verb: n.tool_verb.clone(),
773            subject: Some(n.subject.clone()),
774            note: n.note.clone(),
775            actor: n.actor.clone(),
776            client: n.client.clone(),
777            tool: n.tool.clone(),
778            renamed_from: None,
779            renamed_to: None,
780            batch_entity_ids: Vec::new(),
781            logical_op: n.logical_operation_id.clone(),
782            role: n.role.clone(),
783            identity: n.identity.clone(),
784            merged_by: n.merged_by.clone(),
785            proposal: n.proposal.clone(),
786            created_by_merge: false,
787        };
788        if n.tool_verb.as_deref() == Some("rename") {
789            if let Some((old, new)) = n.entity_id.as_deref().and_then(parse_rename_pair)
790                && new == current
791            {
792                let mut touch = base(&new);
793                touch.renamed_from = Some(old.clone());
794                touch.renamed_to = Some(new);
795                out.push(touch);
796                current = old;
797            }
798            continue;
799        }
800        if n.entity_id.as_deref() == Some(current.as_str()) {
801            let is_create = n.tool_verb.as_deref() == Some("create");
802            out.push(base(&current));
803            if is_create {
804                break;
805            }
806        } else if n.entity_ids.iter().any(|id| id == &current) {
807            let mut touch = base(&current);
808            touch.batch_entity_ids = n.entity_ids.clone();
809            // A proposal merge that lists this id under `Created:`
810            // brought it into the target: its creation, same stop.
811            let created_by_merge = n.created_ids.iter().any(|id| id == &current);
812            touch.created_by_merge = created_by_merge;
813            out.push(touch);
814            // A batch-create that lists this entity is its creation —
815            // nothing older can touch it, same stop as single create.
816            if n.tool_verb.as_deref() == Some("batch-create") || created_by_merge {
817                break;
818            }
819        }
820    }
821    out
822}
823
824/// Changelog-backed record (folder / in-memory): filter the
825/// oldest-first provenance feed to the entity's id and reverse to
826/// newest-first. Rename records match only when they carry this
827/// entity's (post-rename) id — the pre-rename chain is not recorded
828/// on this backend (stated limitation upstream).
829///
830/// Reused-id guard, symmetric with the git-branch walk: the story
831/// starts at the id's NEWEST `create` record — older records under the
832/// same id belonged to a previous holder of the slug, never to this
833/// entity.
834fn filter_provenance_for_entity(
835    entity_id: &str,
836    records: &[crate::provenance::Provenance],
837) -> Vec<EntityTouch> {
838    let matching: Vec<&crate::provenance::Provenance> = records
839        .iter()
840        .filter(|p| p.entity.as_deref() == Some(entity_id))
841        .collect();
842    let birth = matching
843        .iter()
844        .rposition(|p| matches!(p.kind, crate::provenance::ProvenanceKind::Create))
845        .unwrap_or(0);
846    let mut out: Vec<EntityTouch> = matching[birth..]
847        .iter()
848        .map(|p| {
849            let is_rename = matches!(p.kind, crate::provenance::ProvenanceKind::Rename);
850            EntityTouch {
851                reference: crate::filesystem::changelog::format_rfc3339_utc(p.timestamp),
852                timestamp: p
853                    .timestamp
854                    .duration_since(std::time::UNIX_EPOCH)
855                    .map(|d| d.as_secs() as i64)
856                    .unwrap_or(0),
857                id_at_touch: entity_id.to_string(),
858                verb: Some(p.kind.as_str().to_string()),
859                subject: None,
860                note: p.note.clone(),
861                actor: Some(p.actor.as_trailer().to_string()),
862                client: p
863                    .client
864                    .as_ref()
865                    .map(|c| format!("{}@{}", c.name, c.version)),
866                tool: None,
867                renamed_from: None,
868                renamed_to: is_rename.then(|| entity_id.to_string()),
869                batch_entity_ids: Vec::new(),
870                logical_op: p.logical_operation_id.clone(),
871                role: p.role.as_trailer().map(str::to_string),
872                identity: p.identity.clone(),
873                merged_by: None,
874                proposal: None,
875                created_by_merge: false,
876            }
877        })
878        .collect();
879    out.reverse();
880    out
881}
882
883#[cfg(test)]
884mod tests {
885    use crate::backend::MemBackend;
886
887    /// A `batch-create` commit that lists the entity IS its creation:
888    /// the filter stops walking older history there (regression: an
889    /// older unrelated note must not attach), and the touch keeps the
890    /// `batch-create` verb the story-start check accepts — before the
891    /// 2026-08-28 fix every batch-authored entity read as truncated,
892    /// which erased `created_by` and degraded the checks independence
893    /// gate to `unconfirmable`.
894    #[test]
895    fn batch_create_note_is_the_entitys_creation() {
896        use crate::ops::agent_notes::CommitNote;
897        let note = |sha: &str, verb: &str, entity_id: Option<&str>, ids: Vec<&str>| CommitNote {
898            mem: "m".into(),
899            sha: sha.into(),
900            subject: format!("memstead: {verb}"),
901            tool_verb: Some(verb.into()),
902            entity_id: entity_id.map(str::to_string),
903            note: None,
904            actor: Some("cli".into()),
905            tool: None,
906            client: None,
907            logical_operation_id: None,
908            role: Some("author".into()),
909            identity: Some("author-x".into()),
910            entity_ids: ids.into_iter().map(str::to_string).collect(),
911            merged_by: None,
912            proposal: None,
913            created_ids: Vec::new(),
914            timestamp: 1,
915        };
916        // Newest-first: an update, then the batch create, then an
917        // unrelated older note that must never be reached.
918        let notes = vec![
919            note("c3", "update", Some("m--thing"), vec![]),
920            note("c2", "batch-create", None, vec!["m--other", "m--thing"]),
921            note("c1", "update", Some("m--thing"), vec![]),
922        ];
923        let touches = super::filter_notes_for_entity("m--thing", &notes);
924        assert_eq!(
925            touches.len(),
926            2,
927            "the walk stops at the batch create: {touches:?}"
928        );
929        let oldest = touches.last().unwrap();
930        assert_eq!(oldest.verb.as_deref(), Some("batch-create"));
931        assert_eq!(oldest.identity.as_deref(), Some("author-x"));
932        assert!(
933            matches!(
934                oldest.verb.as_deref(),
935                Some("create") | Some("batch-create")
936            ),
937            "the story-start acceptance covers the batch verb"
938        );
939    }
940
941    /// Plan-proposal 03: a `proposal-merge` note that lists the id under
942    /// `Created:` is the entity's creation (the walk stops there and the
943    /// story reads `Recorded`); one that lists it only under `Entities:`
944    /// is an update touch and the walk continues to the older create.
945    #[test]
946    fn proposal_merge_note_creates_or_touches() {
947        use crate::ops::agent_notes::CommitNote;
948        let merge = |sha: &str, ids: Vec<&str>, created: Vec<&str>| CommitNote {
949            mem: "m".into(),
950            sha: sha.into(),
951            subject: "memstead: proposal-merge f@b".into(),
952            tool_verb: Some("proposal-merge".into()),
953            entity_id: Some("f@b".into()),
954            note: None,
955            actor: Some("cli".into()),
956            tool: Some("proposal_merge".into()),
957            client: None,
958            logical_operation_id: None,
959            role: None,
960            identity: Some("proposer-p1".into()),
961            entity_ids: ids.into_iter().map(str::to_string).collect(),
962            merged_by: Some("owner".into()),
963            proposal: Some("f@b".into()),
964            created_ids: created.into_iter().map(str::to_string).collect(),
965            timestamp: 2,
966        };
967        let create = CommitNote {
968            mem: "m".into(),
969            sha: "c1".into(),
970            subject: "memstead: create m--beta".into(),
971            tool_verb: Some("create".into()),
972            entity_id: Some("m--beta".into()),
973            note: None,
974            actor: Some("cli".into()),
975            tool: None,
976            client: None,
977            logical_operation_id: None,
978            role: None,
979            identity: Some("owner".into()),
980            entity_ids: Vec::new(),
981            merged_by: None,
982            proposal: None,
983            created_ids: Vec::new(),
984            timestamp: 1,
985        };
986        let notes = vec![
987            merge("c2", vec!["m--beta", "m--eta"], vec!["m--eta"]),
988            create.clone(),
989        ];
990        // eta: created by the merge; the walk stops at the merge.
991        let eta = super::filter_notes_for_entity("m--eta", &notes);
992        assert_eq!(eta.len(), 1);
993        assert!(eta[0].created_by_merge);
994        assert_eq!(eta[0].identity.as_deref(), Some("proposer-p1"));
995        assert_eq!(eta[0].merged_by.as_deref(), Some("owner"));
996        assert_eq!(eta[0].proposal.as_deref(), Some("f@b"));
997        // beta: touched by the merge, created earlier.
998        let beta = super::filter_notes_for_entity("m--beta", &notes);
999        assert_eq!(beta.len(), 2);
1000        assert!(!beta[0].created_by_merge);
1001        assert_eq!(beta[1].verb.as_deref(), Some("create"));
1002        let _ = create;
1003    }
1004
1005    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";
1006
1007    /// Folder-backed engine with one pre-existing entity written
1008    /// outside the engine (no changelog record) — mirrors the review
1009    /// module's fixture.
1010    fn folder_engine(tmp: &tempfile::TempDir) -> crate::Engine {
1011        let dir = tmp.path().join("specs");
1012        if !dir.exists() {
1013            std::fs::create_dir_all(&dir).unwrap();
1014            let writer = crate::storage::FilesystemBackend::new(dir.clone());
1015            MemBackend::write_entity(&writer, std::path::Path::new("seed.md"), SEED.as_bytes())
1016                .unwrap();
1017            MemBackend::commit(&writer, "seed", &crate::vcs::CommitContext::internal()).unwrap();
1018        }
1019        let mount = crate::Mount {
1020            mem: "specs".to_string(),
1021            schema: Some(memstead_schema::SchemaRef::new(
1022                "default",
1023                semver::Version::new(1, 0, 0),
1024            )),
1025            storage: crate::MountStorage::Folder { path: dir.clone() },
1026            capability: crate::MountCapability::Write,
1027            lifecycle: crate::MountLifecycle::Eager,
1028            cross_linkable: false,
1029            migration_target: None,
1030        };
1031        let backend =
1032            Box::new(crate::storage::FilesystemBackend::new(dir)) as Box<dyn crate::MemBackend>;
1033        crate::Engine::from_mounts(vec![(mount, backend)]).unwrap()
1034    }
1035
1036    fn create(engine: &mut crate::Engine, title: &str, note: &str) -> String {
1037        let outcome = engine
1038            .create_entity(
1039                crate::CreateEntityArgs {
1040                    mem: "specs".to_string(),
1041                    title: title.to_string(),
1042                    entity_type: "spec".to_string(),
1043                    sections: [
1044                        ("identity".to_string(), "x".to_string()),
1045                        ("purpose".to_string(), "y".to_string()),
1046                    ]
1047                    .into_iter()
1048                    .collect(),
1049                    metadata: Default::default(),
1050                    relations: Vec::new(),
1051                    anchors: Vec::new(),
1052                    dry_run: false,
1053                },
1054                crate::vcs::Actor::Cli,
1055                None,
1056                Some(note),
1057            )
1058            .unwrap();
1059        outcome.id.0
1060    }
1061
1062    fn update(engine: &mut crate::Engine, id: &str, note: &str) {
1063        engine
1064            .update_entity(
1065                crate::UpdateEntityArgs {
1066                    id: crate::EntityId(id.to_string()),
1067                    expected_hash: None,
1068                    sections: [("identity".to_string(), format!("touched: {note}"))]
1069                        .into_iter()
1070                        .collect(),
1071                    append_sections: Default::default(),
1072                    patch_sections: Default::default(),
1073                    sections_unset: Vec::new(),
1074                    metadata: Default::default(),
1075                    metadata_unset: Vec::new(),
1076                    dry_run: false,
1077                    declare_relations: Vec::new(),
1078                    anchors: Vec::new(),
1079                    relations_unset: Vec::new(),
1080                    anchors_unset: Vec::new(),
1081                },
1082                crate::vcs::Actor::App,
1083                None,
1084                Some(note),
1085            )
1086            .unwrap();
1087    }
1088
1089    #[test]
1090    fn folder_history_serves_touches_with_stated_limitations() {
1091        let tmp = tempfile::TempDir::new().unwrap();
1092        let mut engine = folder_engine(&tmp);
1093        let id = create(&mut engine, "Story", "born");
1094        update(&mut engine, &id, "grew");
1095
1096        let report = engine.entity_history("specs", &id, None, None).unwrap();
1097        assert_eq!(report.total_recorded, 2);
1098        assert_eq!(report.touches.len(), 2);
1099        // Newest first: the update, then the create.
1100        assert_eq!(report.touches[0].verb.as_deref(), Some("update"));
1101        assert_eq!(report.touches[0].note.as_deref(), Some("grew"));
1102        assert_eq!(report.touches[0].actor.as_deref(), Some("app"));
1103        assert_eq!(report.touches[1].verb.as_deref(), Some("create"));
1104        assert_eq!(report.touches[1].actor.as_deref(), Some("cli"));
1105        assert_eq!(report.story_start, super::StoryStart::Recorded);
1106        assert!(
1107            report
1108                .limitations
1109                .iter()
1110                .any(|l| l.contains("rename records carry only the post-rename id")),
1111            "folder limitations must be stated: {:?}",
1112            report.limitations
1113        );
1114        // Touches of the *other* entity (the seed) never appear.
1115        assert!(report.touches.iter().all(|t| t.id_at_touch == id));
1116    }
1117
1118    #[test]
1119    fn folder_rename_truncates_visibly_not_silently() {
1120        let tmp = tempfile::TempDir::new().unwrap();
1121        let mut engine = folder_engine(&tmp);
1122        let id = create(&mut engine, "Before Rename", "born");
1123        let outcome = engine
1124            .rename_entity(
1125                crate::RenameEntityArgs {
1126                    id: crate::EntityId(id.clone()),
1127                    expected_hash: None,
1128                    new_title: "After Rename".to_string(),
1129                },
1130                crate::vcs::Actor::Cli,
1131                None,
1132                Some("renamed"),
1133            )
1134            .unwrap();
1135        let new_id = outcome.new_id.0;
1136
1137        // The folder changelog records renames under the post-rename
1138        // id only — the story under the new id starts at the rename
1139        // and SAYS so (never an unexplained short history).
1140        let report = engine.entity_history("specs", &new_id, None, None).unwrap();
1141        assert_eq!(report.touches[0].verb.as_deref(), Some("rename"));
1142        assert!(report.touches[0].renamed_from.is_none());
1143        match &report.story_start {
1144            super::StoryStart::Truncated { reason } => {
1145                assert!(
1146                    reason.contains("not the entity's creation"),
1147                    "reason must explain the truncation: {reason}"
1148                );
1149            }
1150            other => panic!("expected visible truncation, got {other:?}"),
1151        }
1152    }
1153
1154    #[test]
1155    fn reused_id_never_absorbs_the_previous_holders_story() {
1156        // Rename an entity away, then create a NEW entity under the
1157        // freed slug: the newcomer's story must start at ITS create —
1158        // pre-fix it absorbed the previous holder's touches and
1159        // presented the polluted story as `Recorded` (grading-gate
1160        // finding, plan 03/02).
1161        let tmp = tempfile::TempDir::new().unwrap();
1162        let mut engine = folder_engine(&tmp);
1163        let id = create(&mut engine, "Slot", "first holder");
1164        update(&mut engine, &id, "first holder grew");
1165        engine
1166            .rename_entity(
1167                crate::RenameEntityArgs {
1168                    id: crate::EntityId(id.clone()),
1169                    expected_hash: None,
1170                    new_title: "Slot Moved".to_string(),
1171                },
1172                crate::vcs::Actor::Cli,
1173                None,
1174                Some("moved away"),
1175            )
1176            .unwrap();
1177        let reused = create(&mut engine, "Slot", "second holder");
1178        assert_eq!(reused, id, "the slug is reused");
1179
1180        let report = engine.entity_history("specs", &reused, None, None).unwrap();
1181        assert_eq!(report.total_recorded, 1, "only its own birth: {report:#?}");
1182        assert_eq!(report.touches[0].verb.as_deref(), Some("create"));
1183        assert_eq!(report.touches[0].note.as_deref(), Some("second holder"));
1184        assert!(matches!(report.story_start, super::StoryStart::Recorded));
1185    }
1186
1187    #[test]
1188    fn refusals_are_typed_never_empty_stories() {
1189        let tmp = tempfile::TempDir::new().unwrap();
1190        let mut engine = folder_engine(&tmp);
1191        let id = create(&mut engine, "Real", "born");
1192
1193        // Unknown mem.
1194        let err = engine.entity_history("ghost", &id, None, None).unwrap_err();
1195        assert_eq!(err.code(), "UNKNOWN_MEM");
1196        // Unknown entity — never an empty history.
1197        let err = engine
1198            .entity_history("specs", "specs--nope", None, None)
1199            .unwrap_err();
1200        assert_eq!(err.code(), "ENTITY_NOT_FOUND");
1201        // Garbage cursor.
1202        let err = engine
1203            .entity_history("specs", &id, None, Some("zzz@0"))
1204            .unwrap_err();
1205        assert_eq!(err.code(), "INVALID_CURSOR");
1206        let err = engine
1207            .entity_history("specs", &id, None, Some("no-separator"))
1208            .unwrap_err();
1209        assert_eq!(err.code(), "INVALID_CURSOR");
1210    }
1211
1212    #[test]
1213    fn pre_changelog_entity_states_the_empty_record() {
1214        // The seed entity was written outside the engine — no
1215        // changelog line exists for it. Its story is empty AND says
1216        // why, distinguishable from "exists, untouched" by the stated
1217        // truncation.
1218        let tmp = tempfile::TempDir::new().unwrap();
1219        let engine = folder_engine(&tmp);
1220        let report = engine
1221            .entity_history("specs", "specs--seed", None, None)
1222            .unwrap();
1223        assert!(report.touches.is_empty());
1224        assert!(matches!(
1225            report.story_start,
1226            super::StoryStart::Truncated { .. }
1227        ));
1228    }
1229
1230    /// An archive mount answers the provenance read with the rationale
1231    /// it seals per entity; where the payload carries no entry, or the
1232    /// archive ships no payload, the block says so instead of refusing.
1233    /// The history read keeps refusing: an archive records no touches.
1234    #[test]
1235    fn archive_mounts_serve_the_sealed_rationale_as_provenance() {
1236        struct SealedBackend {
1237            inner: crate::storage::InMemoryBackend,
1238            payload: Option<Vec<u8>>,
1239        }
1240        impl crate::backend::MemBackend for SealedBackend {
1241            fn list_entities(
1242                &self,
1243            ) -> Result<Vec<std::path::PathBuf>, crate::backend::BackendError> {
1244                self.inner.list_entities()
1245            }
1246            fn read_entity(
1247                &self,
1248                rel: &std::path::Path,
1249            ) -> Result<Option<Vec<u8>>, crate::backend::BackendError> {
1250                self.inner.read_entity(rel)
1251            }
1252            fn write_entity(
1253                &self,
1254                p: &std::path::Path,
1255                b: &[u8],
1256            ) -> Result<(), crate::backend::BackendError> {
1257                self.inner.write_entity(p, b)
1258            }
1259            fn delete_entity(
1260                &self,
1261                p: &std::path::Path,
1262            ) -> Result<(), crate::backend::BackendError> {
1263                self.inner.delete_entity(p)
1264            }
1265            fn move_entity(
1266                &self,
1267                f: &std::path::Path,
1268                t: &std::path::Path,
1269            ) -> Result<(), crate::backend::BackendError> {
1270                self.inner.move_entity(f, t)
1271            }
1272            fn commit(
1273                &self,
1274                m: &str,
1275                c: &crate::vcs::CommitContext<'_>,
1276            ) -> Result<crate::storage::CommitId, crate::backend::BackendError> {
1277                self.inner.commit(m, c)
1278            }
1279            fn append_provenance(
1280                &self,
1281                r: &crate::provenance::Provenance,
1282            ) -> Result<(), crate::backend::BackendError> {
1283                self.inner.append_provenance(r)
1284            }
1285            fn read_provenance(
1286                &self,
1287                c: Option<&str>,
1288            ) -> Result<Vec<crate::provenance::Provenance>, crate::backend::BackendError>
1289            {
1290                self.inner.read_provenance(c)
1291            }
1292            fn read_archive_provenance(
1293                &self,
1294            ) -> Result<Option<Vec<u8>>, crate::backend::BackendError> {
1295                Ok(self.payload.clone())
1296            }
1297        }
1298        fn engine_with(payload: Option<Vec<u8>>) -> crate::Engine {
1299            let dir = tempfile::TempDir::new().unwrap();
1300            let inner = crate::storage::InMemoryBackend::new();
1301            crate::backend::MemBackend::write_entity(
1302                &inner,
1303                std::path::Path::new("seed.md"),
1304                SEED.as_bytes(),
1305            )
1306            .unwrap();
1307            crate::backend::MemBackend::write_entity(
1308                &inner,
1309                std::path::Path::new("bare.md"),
1310                SEED.replace("# Seed", "# Bare").as_bytes(),
1311            )
1312            .unwrap();
1313            crate::backend::MemBackend::commit(
1314                &inner,
1315                "seed",
1316                &crate::vcs::CommitContext::internal(),
1317            )
1318            .unwrap();
1319            let mount = crate::Mount {
1320                mem: "specs".to_string(),
1321                schema: Some(memstead_schema::SchemaRef::new(
1322                    "default",
1323                    semver::Version::new(1, 0, 0),
1324                )),
1325                storage: crate::MountStorage::Archive {
1326                    path: dir.path().join("sealed.mem"),
1327                },
1328                capability: crate::MountCapability::Write,
1329                lifecycle: crate::MountLifecycle::Eager,
1330                cross_linkable: false,
1331                migration_target: None,
1332            };
1333            crate::Engine::from_mounts(vec![(
1334                mount,
1335                Box::new(SealedBackend { inner, payload }) as Box<dyn crate::MemBackend>,
1336            )])
1337            .unwrap()
1338        }
1339        let payload = serde_json::json!({
1340            "format": 1,
1341            "history": "summarised",
1342            "entities": {
1343                "seed": {
1344                    "rationale": "seeded so the graph starts non-empty",
1345                    "kind": "create",
1346                    "timestamp": "2026-06-24T11:32:02Z",
1347                    "actor": "agent"
1348                }
1349            }
1350        });
1351        let engine = engine_with(Some(serde_json::to_vec(&payload).unwrap()));
1352        let prov = engine.entity_provenance("specs", "specs--seed").unwrap();
1353        let sealed = prov.sealed.expect("archive mount serves the sealed block");
1354        assert!(sealed.carried);
1355        assert_eq!(
1356            sealed.rationale.as_deref(),
1357            Some("seeded so the graph starts non-empty")
1358        );
1359        assert_eq!(sealed.kind.as_deref(), Some("create"));
1360        assert_eq!(sealed.actor.as_deref(), Some("agent"));
1361        assert_eq!(sealed.history.as_deref(), Some("summarised"));
1362        assert!(prov.created_by.is_none() && prov.last_modified_by.is_none());
1363        // An entity the payload does not name: stated as not carried.
1364        let bare = engine.entity_provenance("specs", "specs--bare").unwrap();
1365        let sealed = bare.sealed.unwrap();
1366        assert!(!sealed.carried && sealed.rationale.is_none());
1367        assert_eq!(sealed.history.as_deref(), Some("summarised"));
1368        // An unknown id still refuses, as the history read does.
1369        assert_eq!(
1370            engine
1371                .entity_provenance("specs", "specs--ghost")
1372                .unwrap_err()
1373                .code(),
1374            "ENTITY_NOT_FOUND"
1375        );
1376        // An archive with no payload at all: not carried, no history word.
1377        let engine = engine_with(None);
1378        let none = engine.entity_provenance("specs", "specs--seed").unwrap();
1379        let sealed = none.sealed.unwrap();
1380        assert!(!sealed.carried && sealed.history.is_none());
1381        // The history read keeps its refusal.
1382        assert_eq!(
1383            engine
1384                .entity_history("specs", "specs--seed", None, None)
1385                .unwrap_err()
1386                .code(),
1387            "INVALID_INPUT"
1388        );
1389    }
1390
1391    #[test]
1392    fn archive_mounts_refuse_rather_than_fabricate_emptiness() {
1393        // An archive-declared mount whose backend nonetheless serves
1394        // the store: the storage arm must refuse before the seam's
1395        // history-free `read_provenance` can masquerade as an empty
1396        // story.
1397        let dir = tempfile::TempDir::new().unwrap();
1398        let backend = crate::storage::InMemoryBackend::new();
1399        crate::backend::MemBackend::write_entity(
1400            &backend,
1401            std::path::Path::new("seed.md"),
1402            SEED.as_bytes(),
1403        )
1404        .unwrap();
1405        crate::backend::MemBackend::commit(
1406            &backend,
1407            "seed",
1408            &crate::vcs::CommitContext::internal(),
1409        )
1410        .unwrap();
1411        let mount = crate::Mount {
1412            mem: "specs".to_string(),
1413            schema: Some(memstead_schema::SchemaRef::new(
1414                "default",
1415                semver::Version::new(1, 0, 0),
1416            )),
1417            storage: crate::MountStorage::Archive {
1418                path: dir.path().join("sealed.mem"),
1419            },
1420            capability: crate::MountCapability::Write,
1421            lifecycle: crate::MountLifecycle::Eager,
1422            cross_linkable: false,
1423            migration_target: None,
1424        };
1425        let engine = crate::Engine::from_mounts(vec![(
1426            mount,
1427            Box::new(backend) as Box<dyn crate::MemBackend>,
1428        )])
1429        .unwrap();
1430        let err = engine
1431            .entity_history("specs", "specs--seed", None, None)
1432            .unwrap_err();
1433        assert_eq!(err.code(), "INVALID_INPUT");
1434    }
1435
1436    #[test]
1437    fn pages_compose_without_gaps_or_duplicates() {
1438        let tmp = tempfile::TempDir::new().unwrap();
1439        let mut engine = folder_engine(&tmp);
1440        let id = create(&mut engine, "Paged", "born");
1441        for i in 0..5 {
1442            update(&mut engine, &id, &format!("touch {i}"));
1443        }
1444
1445        let full = engine.entity_history("specs", &id, None, None).unwrap();
1446        assert_eq!(full.total_recorded, 6);
1447        assert!(full.next_cursor.is_none());
1448
1449        // Walk in pages of 2 and re-compose.
1450        let mut collected: Vec<super::EntityTouch> = Vec::new();
1451        let mut cursor: Option<String> = None;
1452        loop {
1453            let page = engine
1454                .entity_history("specs", &id, Some(2), cursor.as_deref())
1455                .unwrap();
1456            assert!(page.touches.len() <= 2);
1457            assert_eq!(page.total_recorded, 6, "every page states the whole");
1458            collected.extend(page.touches.clone());
1459            match page.next_cursor {
1460                Some(c) => cursor = Some(c),
1461                None => break,
1462            }
1463        }
1464        assert_eq!(
1465            collected, full.touches,
1466            "paged walk must equal the single-page story exactly"
1467        );
1468    }
1469}