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(self.not_found(entity_id));
441        }
442        let id = crate::EntityId(entity_id.to_string());
443        let (checks_carried, checks_reason) = match self.archive_checks_for(mem) {
444            None => (
445                false,
446                Some(
447                    "the archive carries no check records; every state reads never_checked"
448                        .to_string(),
449                ),
450            ),
451            Some(sealed) if sealed.kinds_of(id.path()).next().is_none() => (
452                false,
453                Some("the archive carries no check record for this entity".to_string()),
454            ),
455            Some(_) => (true, None),
456        };
457        let sealed = match self.archive_provenance_for(mem) {
458            Some(payload) => {
459                let history = Some(
460                    serde_json::to_value(payload.history)
461                        .ok()
462                        .and_then(|v| v.as_str().map(str::to_string))
463                        .unwrap_or_else(|| "unknown".to_string()),
464                );
465                match payload.entity(id.path()) {
466                    Some(rec) => SealedProvenance {
467                        carried: rec.rationale.is_some(),
468                        history,
469                        rationale: rec.rationale.clone(),
470                        kind: rec.kind.clone(),
471                        timestamp: rec.timestamp.clone(),
472                        actor: rec.actor.clone(),
473                        checks_carried,
474                        checks_reason: checks_reason.clone(),
475                    },
476                    None => SealedProvenance {
477                        carried: false,
478                        history,
479                        rationale: None,
480                        kind: None,
481                        timestamp: None,
482                        actor: None,
483                        checks_carried,
484                        checks_reason: checks_reason.clone(),
485                    },
486                }
487            }
488            None => SealedProvenance {
489                carried: false,
490                history: None,
491                rationale: None,
492                kind: None,
493                timestamp: None,
494                actor: None,
495                checks_carried,
496                checks_reason: checks_reason.clone(),
497            },
498        };
499        let (check_state, last_check) = self.entity_check_state(mem, entity_id)?;
500        let (conformance_state, last_conformance_check) =
501            self.entity_conformance_state(mem, entity_id)?;
502        Ok(EntityProvenance {
503            created_by: None,
504            last_modified_by: None,
505            story_truncated: false,
506            check_state: check_state.as_str().to_string(),
507            check_prose_origin: self.foreign_check_prose_marker(
508                mem,
509                entity_id,
510                [last_check.as_ref(), last_conformance_check.as_ref()],
511            ),
512            last_check,
513            conformance_state: conformance_state.as_str().to_string(),
514            last_conformance_check,
515            foreign_checks: self.latest_foreign_checks(mem, entity_id),
516            sealed: Some(sealed),
517        })
518    }
519
520    /// The trust class to report for a check record's own prose, and only
521    /// when it is the foreign one: `Some("third-party")` where the note was
522    /// written by a party other than this workspace, `None` otherwise, so
523    /// the field appears exactly where it warns and every other response is
524    /// byte-unchanged.
525    ///
526    /// On an archive mount the answer is the one the exporting workspace
527    /// sealed beside the row, because that workspace is the only party that
528    /// knew which identities were its own; a member sealed without the field
529    /// falls through to this deployment's reading, as it did before the
530    /// field existed. This is the reader that makes
531    /// [`crate::check::SealedCheck::origin`] load-bearing: the sealed
532    /// `method` note is carried into the record every surface renders, so
533    /// without it a publisher's checker prose reaches a reading agent as the
534    /// consumer's own.
535    fn foreign_check_prose_marker(
536        &self,
537        mem: &str,
538        entity_id: &str,
539        records: [Option<&crate::check::CheckRecord>; 2],
540    ) -> Option<String> {
541        // Nothing can be foreign in the default deployment: with no declared
542        // owner identities on a first-party mem every row reads as the
543        // workspace's own, and only an archive mount can carry a sealed class.
544        // Leaving early keeps the marker from re-reading and re-parsing the
545        // whole check ledger once more per provenance read.
546        if !self.declares_owner_identities()
547            && !self.is_archive_mount(mem)
548            && !self.mem_origin_class(mem).is_third_party()
549        {
550            return None;
551        }
552        let foreign = |rec: &crate::check::CheckRecord| {
553            self.check_row_prose_origin(mem, entity_id, rec)
554                .is_third_party()
555        };
556        let any_foreign = records.into_iter().flatten().any(foreign)
557            || self
558                .latest_foreign_checks(mem, entity_id)
559                .iter()
560                .any(foreign);
561        any_foreign.then(|| crate::render::OriginClass::ThirdParty.as_wire().to_string())
562    }
563
564    /// An entity's recorded history: every touch, newest-first, with
565    /// rename chains followed so the story starts at the entity's
566    /// first appearance under any prior id. Bounded and pageable —
567    /// `page_size` clamps to [`HISTORY_PAGE_MAX`], `cursor` continues
568    /// a prior page (`INVALID_CURSOR` when it matches no touch).
569    ///
570    /// Refusals: `UNKNOWN_MEM`, `ENTITY_NOT_FOUND` (an unknown id
571    /// never yields an empty story), `INVALID_INPUT` on archive
572    /// mounts (their seam records no history — refusing beats
573    /// fabricating emptiness).
574    pub fn entity_history(
575        &self,
576        mem: &str,
577        entity_id: &str,
578        page_size: Option<usize>,
579        cursor: Option<&str>,
580    ) -> Result<EntityHistoryReport, EngineError> {
581        let m = self.find_mount(mem)?;
582
583        // An unknown entity refuses — marklessness-style honesty: the
584        // caller learns "no such entity", never an empty history that
585        // reads as "exists, untouched".
586        let known = self
587            .store
588            .all_entities()
589            .any(|e| e.mem == mem && e.id.0 == entity_id);
590        if !known {
591            return Err(self.not_found(entity_id));
592        }
593
594        let mut limitations: Vec<String> = Vec::new();
595
596        // ---- Collect the raw record, newest-first, per backend ----
597        let touches: Vec<EntityTouch> = match &m.mount.storage {
598            MountStorage::GitBranch { gitdir, branch } => match self.git_branch_ops.as_ref() {
599                Some(hook) => {
600                    let backend_changes = (hook.changes_since)(
601                        gitdir,
602                        branch,
603                        mem,
604                        crate::ops::EMPTY_TREE_SHA,
605                        crate::ops::RENAME_SIMILARITY_DEFAULT,
606                    )
607                    .map_err(EngineError::Backend)?;
608                    filter_notes_for_entity(entity_id, &backend_changes.notes)
609                }
610                None => {
611                    limitations.push(
612                        "this build carries no git-branch history walk — the recorded story \
613                         is not reachable"
614                            .to_string(),
615                    );
616                    Vec::new()
617                }
618            },
619            MountStorage::Folder { .. } | MountStorage::InMemory => {
620                limitations.push(
621                    "changelog-backed history: a rename record written before the engine \
622                     recorded the prior id ends the chain there, and batch mutations record \
623                     no per-entity attribution on this backend"
624                        .to_string(),
625                );
626                let records = m
627                    .backend
628                    .read_provenance(None)
629                    .map_err(EngineError::Backend)?;
630                filter_provenance_for_entity(entity_id, &records)
631            }
632            MountStorage::Archive { .. } => {
633                return Err(EngineError::InvalidInput(format!(
634                    "mem '{mem}' is an archive mount — archives record no history at the \
635                     engine seam; open the source mem for the entity's story"
636                )));
637            }
638        };
639
640        // ---- Visible-truncation verdict ----
641        // The recorded story is complete exactly when its oldest touch
642        // is the entity's creation. Anything else — empty record,
643        // oldest touch mid-stream — states where and why it stops.
644        let story_start = match touches.last() {
645            // `batch-create` IS this entity's creation when it is the
646            // oldest touch — a batch-authored entity carries the same
647            // append-only provenance (role, identity trailers) as a
648            // single create, and treating it as truncation erased
649            // `created_by` for every batch-authored entity, which
650            // silently degraded the checks independence gate to
651            // `unconfirmable`.
652            // A proposal merge that lists the id under `Created:` brought
653            // the entity into the target: its creation, under the
654            // proposer's identity (plan-proposal 03).
655            Some(oldest)
656                if matches!(
657                    oldest.verb.as_deref(),
658                    Some("create") | Some("batch-create")
659                ) || oldest.created_by_merge =>
660            {
661                StoryStart::Recorded
662            }
663            Some(oldest) => StoryStart::Truncated {
664                reason: format!(
665                    "oldest recorded touch is a {} of `{}`, not the entity's creation — \
666                     earlier history (an unrecorded prior id, or records predating the \
667                     provenance log) is not reachable",
668                    oldest.verb.as_deref().unwrap_or("touch"),
669                    oldest.id_at_touch
670                ),
671            },
672            None => StoryStart::Truncated {
673                reason: "no touches recorded — the entity predates this mem's provenance \
674                         record (an adopted or migrated mem)"
675                    .to_string(),
676            },
677        };
678
679        // ---- Page ----
680        let size = page_size
681            .unwrap_or(HISTORY_PAGE_DEFAULT)
682            .clamp(1, HISTORY_PAGE_MAX);
683        let start_idx = match cursor {
684            None => 0,
685            Some(c) => {
686                let pos = parse_cursor(c).and_then(|(reference, k)| {
687                    touches
688                        .iter()
689                        .enumerate()
690                        .filter(|(_, t)| t.reference == reference)
691                        .nth(k)
692                        .map(|(i, _)| i + 1)
693                });
694                pos.ok_or_else(|| EngineError::InvalidChangesCursor {
695                    mem: mem.to_string(),
696                    since: c.to_string(),
697                })?
698            }
699        };
700        let total_recorded = touches.len();
701        let page: Vec<EntityTouch> = touches[start_idx.min(total_recorded)..]
702            .iter()
703            .take(size)
704            .cloned()
705            .collect();
706        let next_cursor = if start_idx + page.len() < total_recorded {
707            page.last().map(|last| {
708                let k = touches[..start_idx + page.len()]
709                    .iter()
710                    .filter(|t| t.reference == last.reference)
711                    .count()
712                    - 1;
713                format!("{}@{k}", last.reference)
714            })
715        } else {
716            None
717        };
718
719        Ok(EntityHistoryReport {
720            mem: mem.to_string(),
721            entity_id: entity_id.to_string(),
722            touches: page,
723            total_recorded,
724            next_cursor,
725            story_start,
726            limitations,
727        })
728    }
729}
730
731/// Cursor wire form: `<reference>@<occurrence>` where `occurrence`
732/// disambiguates touches sharing a reference (same-millisecond folder
733/// changelog lines; impossible for commit SHAs but the format stays
734/// uniform). Opaque to callers.
735fn parse_cursor(c: &str) -> Option<(String, usize)> {
736    let (reference, k) = c.rsplit_once('@')?;
737    if reference.is_empty() {
738        return None;
739    }
740    Some((reference.to_string(), k.parse().ok()?))
741}
742
743/// Newest→oldest single pass over the commit-note walk, tracking the
744/// entity's id backwards through authoritative rename records:
745/// `current` starts at the queried id; a rename whose *new* id equals
746/// `current` is that entity's rename touch and flips `current` to the
747/// old id, so every older touch is matched under its then-current id.
748/// A rename whose *old* id equals `current` is a different entity's
749/// departure from an id later reused — deliberately not a touch.
750///
751/// The walk STOPS at the entity's creation: a `create` of the tracked
752/// id is the story's birth, and anything older under the same id
753/// belonged to a previous holder of a reused slug (renamed away or
754/// deleted before this entity existed) — absorbing it would attribute
755/// a stranger's touches to this entity and present the polluted story
756/// as `Recorded`.
757pub(crate) fn filter_notes_for_entity(
758    entity_id: &str,
759    notes: &[crate::ops::agent_notes::CommitNote],
760) -> Vec<EntityTouch> {
761    let mut current = entity_id.to_string();
762    let mut out: Vec<EntityTouch> = Vec::new();
763    for n in notes {
764        let base = |id_at: &str| EntityTouch {
765            reference: n.sha.clone(),
766            timestamp: n.timestamp,
767            id_at_touch: id_at.to_string(),
768            verb: n.tool_verb.clone(),
769            subject: Some(n.subject.clone()),
770            note: n.note.clone(),
771            actor: n.actor.clone(),
772            client: n.client.clone(),
773            tool: n.tool.clone(),
774            renamed_from: None,
775            renamed_to: None,
776            batch_entity_ids: Vec::new(),
777            logical_op: n.logical_operation_id.clone(),
778            role: n.role.clone(),
779            identity: n.identity.clone(),
780            merged_by: n.merged_by.clone(),
781            proposal: n.proposal.clone(),
782            created_by_merge: false,
783        };
784        if n.tool_verb.as_deref() == Some("rename") {
785            if let Some((old, new)) = n.entity_id.as_deref().and_then(parse_rename_pair)
786                && new == current
787            {
788                let mut touch = base(&new);
789                touch.renamed_from = Some(old.clone());
790                touch.renamed_to = Some(new);
791                out.push(touch);
792                current = old;
793            } else if n.entity_ids.iter().any(|id| id == &current) {
794                // The rename rewrote a link inside this entry: a write
795                // of it, under the renamer's identity.
796                let mut touch = base(&current);
797                touch.batch_entity_ids = n.entity_ids.clone();
798                out.push(touch);
799            }
800            continue;
801        }
802        if n.entity_id.as_deref() == Some(current.as_str()) {
803            let is_create = n.tool_verb.as_deref() == Some("create");
804            out.push(base(&current));
805            if is_create {
806                break;
807            }
808        } else if n.entity_ids.iter().any(|id| id == &current) {
809            let mut touch = base(&current);
810            touch.batch_entity_ids = n.entity_ids.clone();
811            // A proposal merge that lists this id under `Created:`
812            // brought it into the target: its creation, same stop.
813            let created_by_merge = n.created_ids.iter().any(|id| id == &current);
814            // A merge that landed a fork rename creates the new id from
815            // the old one: the story continues under the old id.
816            let renamed_from = n
817                .merge_renames
818                .iter()
819                .filter_map(|pair| parse_rename_pair(pair))
820                .find(|(_, new)| new == &current)
821                .map(|(old, _)| old);
822            touch.created_by_merge = created_by_merge && renamed_from.is_none();
823            if let Some(old) = &renamed_from {
824                touch.renamed_from = Some(old.clone());
825                touch.renamed_to = Some(current.clone());
826            }
827            out.push(touch);
828            if let Some(old) = renamed_from {
829                current = old;
830                continue;
831            }
832            // A batch-create that lists this entity is its creation —
833            // nothing older can touch it, same stop as single create.
834            if n.tool_verb.as_deref() == Some("batch-create") || created_by_merge {
835                break;
836            }
837        }
838    }
839    out
840}
841
842/// Changelog-backed record (folder / in-memory): filter the
843/// oldest-first provenance feed to the entity's id and reverse to
844/// newest-first. Rename records match only when they carry this
845/// entity's (post-rename) id — the pre-rename chain is not recorded
846/// on this backend (stated limitation upstream).
847///
848/// Reused-id guard, symmetric with the git-branch walk: the story
849/// starts at the id's NEWEST `create` record — older records under the
850/// same id belonged to a previous holder of the slug, never to this
851/// entity.
852fn filter_provenance_for_entity(
853    entity_id: &str,
854    records: &[crate::provenance::Provenance],
855) -> Vec<EntityTouch> {
856    // Newest first, following each rename line back to the id it left,
857    // and stopping at the creation of whichever id the walk is on.
858    let mut current = entity_id.to_string();
859    let mut out: Vec<EntityTouch> = Vec::new();
860    for p in records.iter().rev() {
861        if p.entity.as_deref() != Some(current.as_str()) {
862            continue;
863        }
864        let is_rename = matches!(p.kind, crate::provenance::ProvenanceKind::Rename);
865        let is_create = matches!(p.kind, crate::provenance::ProvenanceKind::Create);
866        let renamed_from = if is_rename {
867            p.renamed_from.clone()
868        } else {
869            None
870        };
871        out.push(EntityTouch {
872            reference: crate::filesystem::changelog::format_rfc3339_utc(p.timestamp),
873            timestamp: p
874                .timestamp
875                .duration_since(std::time::UNIX_EPOCH)
876                .map(|d| d.as_secs() as i64)
877                .unwrap_or(0),
878            id_at_touch: current.clone(),
879            verb: Some(p.kind.as_str().to_string()),
880            subject: None,
881            note: p.note.clone(),
882            actor: Some(p.actor.as_trailer().to_string()),
883            client: p
884                .client
885                .as_ref()
886                .map(|c| format!("{}@{}", c.name, c.version)),
887            tool: None,
888            renamed_from: renamed_from.clone(),
889            renamed_to: is_rename.then(|| current.clone()),
890            batch_entity_ids: Vec::new(),
891            logical_op: p.logical_operation_id.clone(),
892            role: p.role.as_trailer().map(str::to_string),
893            identity: p.identity.clone(),
894            merged_by: None,
895            proposal: None,
896            created_by_merge: false,
897        });
898        if let Some(old) = renamed_from {
899            current = old;
900        } else if is_create {
901            break;
902        }
903    }
904    out
905}
906
907#[cfg(test)]
908mod tests {
909    use crate::backend::MemBackend;
910
911    /// A `batch-create` commit that lists the entity IS its creation:
912    /// the filter stops walking older history there (regression: an
913    /// older unrelated note must not attach), and the touch keeps the
914    /// `batch-create` verb the story-start check accepts — before the
915    /// 2026-08-28 fix every batch-authored entity read as truncated,
916    /// which erased `created_by` and degraded the checks independence
917    /// gate to `unconfirmable`.
918    #[test]
919    fn batch_create_note_is_the_entitys_creation() {
920        use crate::ops::agent_notes::CommitNote;
921        let note = |sha: &str, verb: &str, entity_id: Option<&str>, ids: Vec<&str>| CommitNote {
922            mem: "m".into(),
923            sha: sha.into(),
924            subject: format!("memstead: {verb}"),
925            tool_verb: Some(verb.into()),
926            entity_id: entity_id.map(str::to_string),
927            note: None,
928            actor: Some("cli".into()),
929            tool: None,
930            client: None,
931            logical_operation_id: None,
932            role: Some("author".into()),
933            identity: Some("author-x".into()),
934            entity_ids: ids.into_iter().map(str::to_string).collect(),
935            merged_by: None,
936            proposal: None,
937            created_ids: Vec::new(),
938            co_writers: Vec::new(),
939            merge_renames: Vec::new(),
940            unattributed_writes: Vec::new(),
941            timestamp: 1,
942        };
943        // Newest-first: an update, then the batch create, then an
944        // unrelated older note that must never be reached.
945        let notes = vec![
946            note("c3", "update", Some("m--thing"), vec![]),
947            note("c2", "batch-create", None, vec!["m--other", "m--thing"]),
948            note("c1", "update", Some("m--thing"), vec![]),
949        ];
950        let touches = super::filter_notes_for_entity("m--thing", &notes);
951        assert_eq!(
952            touches.len(),
953            2,
954            "the walk stops at the batch create: {touches:?}"
955        );
956        let oldest = touches.last().unwrap();
957        assert_eq!(oldest.verb.as_deref(), Some("batch-create"));
958        assert_eq!(oldest.identity.as_deref(), Some("author-x"));
959        assert!(
960            matches!(
961                oldest.verb.as_deref(),
962                Some("create") | Some("batch-create")
963            ),
964            "the story-start acceptance covers the batch verb"
965        );
966    }
967
968    /// Plan-proposal 03: a `proposal-merge` note that lists the id under
969    /// `Created:` is the entity's creation (the walk stops there and the
970    /// story reads `Recorded`); one that lists it only under `Entities:`
971    /// is an update touch and the walk continues to the older create.
972    #[test]
973    fn proposal_merge_note_creates_or_touches() {
974        use crate::ops::agent_notes::CommitNote;
975        let merge = |sha: &str, ids: Vec<&str>, created: Vec<&str>| CommitNote {
976            mem: "m".into(),
977            sha: sha.into(),
978            subject: "memstead: proposal-merge f@b".into(),
979            tool_verb: Some("proposal-merge".into()),
980            entity_id: Some("f@b".into()),
981            note: None,
982            actor: Some("cli".into()),
983            tool: Some("proposal_merge".into()),
984            client: None,
985            logical_operation_id: None,
986            role: None,
987            identity: Some("proposer-p1".into()),
988            entity_ids: ids.into_iter().map(str::to_string).collect(),
989            merged_by: Some("owner".into()),
990            proposal: Some("f@b".into()),
991            created_ids: created.into_iter().map(str::to_string).collect(),
992            co_writers: Vec::new(),
993            merge_renames: Vec::new(),
994            unattributed_writes: Vec::new(),
995            timestamp: 2,
996        };
997        let create = CommitNote {
998            mem: "m".into(),
999            sha: "c1".into(),
1000            subject: "memstead: create m--beta".into(),
1001            tool_verb: Some("create".into()),
1002            entity_id: Some("m--beta".into()),
1003            note: None,
1004            actor: Some("cli".into()),
1005            tool: None,
1006            client: None,
1007            logical_operation_id: None,
1008            role: None,
1009            identity: Some("owner".into()),
1010            entity_ids: Vec::new(),
1011            merged_by: None,
1012            proposal: None,
1013            created_ids: Vec::new(),
1014            co_writers: Vec::new(),
1015            merge_renames: Vec::new(),
1016            unattributed_writes: Vec::new(),
1017            timestamp: 1,
1018        };
1019        let notes = vec![
1020            merge("c2", vec!["m--beta", "m--eta"], vec!["m--eta"]),
1021            create.clone(),
1022        ];
1023        // eta: created by the merge; the walk stops at the merge.
1024        let eta = super::filter_notes_for_entity("m--eta", &notes);
1025        assert_eq!(eta.len(), 1);
1026        assert!(eta[0].created_by_merge);
1027        assert_eq!(eta[0].identity.as_deref(), Some("proposer-p1"));
1028        assert_eq!(eta[0].merged_by.as_deref(), Some("owner"));
1029        assert_eq!(eta[0].proposal.as_deref(), Some("f@b"));
1030        // beta: touched by the merge, created earlier.
1031        let beta = super::filter_notes_for_entity("m--beta", &notes);
1032        assert_eq!(beta.len(), 2);
1033        assert!(!beta[0].created_by_merge);
1034        assert_eq!(beta[1].verb.as_deref(), Some("create"));
1035        let _ = create;
1036    }
1037
1038    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";
1039
1040    /// Folder-backed engine with one pre-existing entity written
1041    /// outside the engine (no changelog record) — mirrors the review
1042    /// module's fixture.
1043    fn folder_engine(tmp: &tempfile::TempDir) -> crate::Engine {
1044        let dir = tmp.path().join("specs");
1045        if !dir.exists() {
1046            std::fs::create_dir_all(&dir).unwrap();
1047            let writer = crate::storage::FilesystemBackend::new(dir.clone());
1048            MemBackend::write_entity(&writer, std::path::Path::new("seed.md"), SEED.as_bytes())
1049                .unwrap();
1050            MemBackend::commit(&writer, "seed", &crate::vcs::CommitContext::internal()).unwrap();
1051        }
1052        let mount = crate::Mount {
1053            mem: "specs".to_string(),
1054            schema: Some(memstead_schema::SchemaRef::new(
1055                "default",
1056                semver::Version::new(1, 0, 0),
1057            )),
1058            storage: crate::MountStorage::Folder { path: dir.clone() },
1059            capability: crate::MountCapability::Write,
1060            lifecycle: crate::MountLifecycle::Eager,
1061            cross_linkable: false,
1062            migration_target: None,
1063        };
1064        let backend =
1065            Box::new(crate::storage::FilesystemBackend::new(dir)) as Box<dyn crate::MemBackend>;
1066        crate::Engine::from_mounts(vec![(mount, backend)]).unwrap()
1067    }
1068
1069    fn create(engine: &mut crate::Engine, title: &str, note: &str) -> String {
1070        let outcome = engine
1071            .create_entity(
1072                crate::CreateEntityArgs {
1073                    mem: "specs".to_string(),
1074                    title: title.to_string(),
1075                    entity_type: "spec".to_string(),
1076                    sections: [
1077                        ("identity".to_string(), "x".to_string()),
1078                        ("purpose".to_string(), "y".to_string()),
1079                    ]
1080                    .into_iter()
1081                    .collect(),
1082                    metadata: Default::default(),
1083                    relations: Vec::new(),
1084                    anchors: Vec::new(),
1085                    dry_run: false,
1086                },
1087                crate::vcs::Actor::Cli,
1088                None,
1089                Some(note),
1090            )
1091            .unwrap();
1092        outcome.id.0
1093    }
1094
1095    fn update(engine: &mut crate::Engine, id: &str, note: &str) {
1096        engine
1097            .update_entity(
1098                crate::UpdateEntityArgs {
1099                    id: crate::EntityId(id.to_string()),
1100                    expected_hash: crate::ExpectedHash::from_token(
1101                        engine
1102                            .get_entity(&crate::EntityId(id.to_string()))
1103                            .map(|e| e.content_hash.clone()),
1104                    ),
1105                    sections: [("identity".to_string(), format!("touched: {note}"))]
1106                        .into_iter()
1107                        .collect(),
1108                    append_sections: Default::default(),
1109                    patch_sections: Default::default(),
1110                    sections_unset: Vec::new(),
1111                    metadata: Default::default(),
1112                    metadata_unset: Vec::new(),
1113                    dry_run: false,
1114                    declare_relations: Vec::new(),
1115                    anchors: Vec::new(),
1116                    relations_unset: Vec::new(),
1117                    anchors_unset: Vec::new(),
1118                },
1119                crate::vcs::Actor::App,
1120                None,
1121                Some(note),
1122            )
1123            .unwrap();
1124    }
1125
1126    #[test]
1127    fn folder_history_serves_touches_with_stated_limitations() {
1128        let tmp = tempfile::TempDir::new().unwrap();
1129        let mut engine = folder_engine(&tmp);
1130        let id = create(&mut engine, "Story", "born");
1131        update(&mut engine, &id, "grew");
1132
1133        let report = engine.entity_history("specs", &id, None, None).unwrap();
1134        assert_eq!(report.total_recorded, 2);
1135        assert_eq!(report.touches.len(), 2);
1136        // Newest first: the update, then the create.
1137        assert_eq!(report.touches[0].verb.as_deref(), Some("update"));
1138        assert_eq!(report.touches[0].note.as_deref(), Some("grew"));
1139        assert_eq!(report.touches[0].actor.as_deref(), Some("app"));
1140        assert_eq!(report.touches[1].verb.as_deref(), Some("create"));
1141        assert_eq!(report.touches[1].actor.as_deref(), Some("cli"));
1142        assert_eq!(report.story_start, super::StoryStart::Recorded);
1143        assert!(
1144            report
1145                .limitations
1146                .iter()
1147                .any(|l| l.contains("batch mutations record no per-entity attribution")),
1148            "folder limitations must be stated: {:?}",
1149            report.limitations
1150        );
1151        // Touches of the *other* entity (the seed) never appear.
1152        assert!(report.touches.iter().all(|t| t.id_at_touch == id));
1153    }
1154
1155    #[test]
1156    fn folder_rename_follows_the_prior_id_to_the_creation() {
1157        let tmp = tempfile::TempDir::new().unwrap();
1158        let mut engine = folder_engine(&tmp);
1159        let id = create(&mut engine, "Before Rename", "born");
1160        let outcome = engine
1161            .rename_entity(
1162                crate::RenameEntityArgs {
1163                    id: crate::EntityId(id.clone()),
1164                    expected_hash: crate::ExpectedHash::from_token(
1165                        engine
1166                            .get_entity(&crate::EntityId(id.clone()))
1167                            .map(|e| e.content_hash.clone()),
1168                    ),
1169                    new_title: "After Rename".to_string(),
1170                },
1171                crate::vcs::Actor::Cli,
1172                None,
1173                Some("renamed"),
1174            )
1175            .unwrap();
1176        let new_id = outcome.new_id.0;
1177
1178        // The rename line names the id it left: the story under the
1179        // new id runs through the rename back to the creation.
1180        let report = engine.entity_history("specs", &new_id, None, None).unwrap();
1181        assert_eq!(report.touches[0].verb.as_deref(), Some("rename"));
1182        assert_eq!(report.touches[0].renamed_from.as_deref(), Some(id.as_str()));
1183        assert_eq!(report.touches[1].verb.as_deref(), Some("create"));
1184        assert_eq!(report.touches[1].id_at_touch, id);
1185        assert_eq!(report.story_start, super::StoryStart::Recorded);
1186    }
1187
1188    #[test]
1189    fn reused_id_never_absorbs_the_previous_holders_story() {
1190        // Rename an entity away, then create a NEW entity under the
1191        // freed slug: the newcomer's story must start at ITS create —
1192        // pre-fix it absorbed the previous holder's touches and
1193        // presented the polluted story as `Recorded`.
1194        let tmp = tempfile::TempDir::new().unwrap();
1195        let mut engine = folder_engine(&tmp);
1196        let id = create(&mut engine, "Slot", "first holder");
1197        update(&mut engine, &id, "first holder grew");
1198        engine
1199            .rename_entity(
1200                crate::RenameEntityArgs {
1201                    id: crate::EntityId(id.clone()),
1202                    expected_hash: crate::ExpectedHash::from_token(
1203                        engine
1204                            .get_entity(&crate::EntityId(id.clone()))
1205                            .map(|e| e.content_hash.clone()),
1206                    ),
1207                    new_title: "Slot Moved".to_string(),
1208                },
1209                crate::vcs::Actor::Cli,
1210                None,
1211                Some("moved away"),
1212            )
1213            .unwrap();
1214        let reused = create(&mut engine, "Slot", "second holder");
1215        assert_eq!(reused, id, "the slug is reused");
1216
1217        let report = engine.entity_history("specs", &reused, None, None).unwrap();
1218        assert_eq!(report.total_recorded, 1, "only its own birth: {report:#?}");
1219        assert_eq!(report.touches[0].verb.as_deref(), Some("create"));
1220        assert_eq!(report.touches[0].note.as_deref(), Some("second holder"));
1221        assert!(matches!(report.story_start, super::StoryStart::Recorded));
1222    }
1223
1224    #[test]
1225    fn refusals_are_typed_never_empty_stories() {
1226        let tmp = tempfile::TempDir::new().unwrap();
1227        let mut engine = folder_engine(&tmp);
1228        let id = create(&mut engine, "Real", "born");
1229
1230        // Unknown mem.
1231        let err = engine.entity_history("ghost", &id, None, None).unwrap_err();
1232        assert_eq!(err.code(), "UNKNOWN_MEM");
1233        // Unknown entity — never an empty history.
1234        let err = engine
1235            .entity_history("specs", "specs--nope", None, None)
1236            .unwrap_err();
1237        assert_eq!(err.code(), "ENTITY_NOT_FOUND");
1238        // Garbage cursor.
1239        let err = engine
1240            .entity_history("specs", &id, None, Some("zzz@0"))
1241            .unwrap_err();
1242        assert_eq!(err.code(), "INVALID_CURSOR");
1243        let err = engine
1244            .entity_history("specs", &id, None, Some("no-separator"))
1245            .unwrap_err();
1246        assert_eq!(err.code(), "INVALID_CURSOR");
1247    }
1248
1249    #[test]
1250    fn pre_changelog_entity_states_the_empty_record() {
1251        // The seed entity was written outside the engine — no
1252        // changelog line exists for it. Its story is empty AND says
1253        // why, distinguishable from "exists, untouched" by the stated
1254        // truncation.
1255        let tmp = tempfile::TempDir::new().unwrap();
1256        let engine = folder_engine(&tmp);
1257        let report = engine
1258            .entity_history("specs", "specs--seed", None, None)
1259            .unwrap();
1260        assert!(report.touches.is_empty());
1261        assert!(matches!(
1262            report.story_start,
1263            super::StoryStart::Truncated { .. }
1264        ));
1265    }
1266
1267    /// An archive mount answers the provenance read with the rationale
1268    /// it seals per entity; where the payload carries no entry, or the
1269    /// archive ships no payload, the block says so instead of refusing.
1270    /// The history read keeps refusing: an archive records no touches.
1271    #[test]
1272    fn archive_mounts_serve_the_sealed_rationale_as_provenance() {
1273        struct SealedBackend {
1274            inner: crate::storage::InMemoryBackend,
1275            payload: Option<Vec<u8>>,
1276        }
1277        impl crate::backend::MemBackend for SealedBackend {
1278            fn list_entities(
1279                &self,
1280            ) -> Result<Vec<std::path::PathBuf>, crate::backend::BackendError> {
1281                self.inner.list_entities()
1282            }
1283            fn read_entity(
1284                &self,
1285                rel: &std::path::Path,
1286            ) -> Result<Option<Vec<u8>>, crate::backend::BackendError> {
1287                self.inner.read_entity(rel)
1288            }
1289            fn write_entity(
1290                &self,
1291                p: &std::path::Path,
1292                b: &[u8],
1293            ) -> Result<(), crate::backend::BackendError> {
1294                self.inner.write_entity(p, b)
1295            }
1296            fn delete_entity(
1297                &self,
1298                p: &std::path::Path,
1299            ) -> Result<(), crate::backend::BackendError> {
1300                self.inner.delete_entity(p)
1301            }
1302            fn move_entity(
1303                &self,
1304                f: &std::path::Path,
1305                t: &std::path::Path,
1306            ) -> Result<(), crate::backend::BackendError> {
1307                self.inner.move_entity(f, t)
1308            }
1309            fn commit(
1310                &self,
1311                m: &str,
1312                c: &crate::vcs::CommitContext<'_>,
1313            ) -> Result<crate::storage::CommitId, crate::backend::BackendError> {
1314                self.inner.commit(m, c)
1315            }
1316            fn stage_provenance(
1317                &self,
1318                r: &crate::provenance::Provenance,
1319            ) -> Result<(), crate::backend::BackendError> {
1320                self.inner.stage_provenance(r)
1321            }
1322            fn append_provenance(
1323                &self,
1324                r: &crate::provenance::Provenance,
1325            ) -> Result<(), crate::backend::BackendError> {
1326                self.inner.append_provenance(r)
1327            }
1328            fn read_provenance(
1329                &self,
1330                c: Option<&str>,
1331            ) -> Result<Vec<crate::provenance::Provenance>, crate::backend::BackendError>
1332            {
1333                self.inner.read_provenance(c)
1334            }
1335            fn read_archive_provenance(
1336                &self,
1337            ) -> Result<Option<Vec<u8>>, crate::backend::BackendError> {
1338                Ok(self.payload.clone())
1339            }
1340        }
1341        fn engine_with(payload: Option<Vec<u8>>) -> crate::Engine {
1342            let dir = tempfile::TempDir::new().unwrap();
1343            let inner = crate::storage::InMemoryBackend::new();
1344            crate::backend::MemBackend::write_entity(
1345                &inner,
1346                std::path::Path::new("seed.md"),
1347                SEED.as_bytes(),
1348            )
1349            .unwrap();
1350            crate::backend::MemBackend::write_entity(
1351                &inner,
1352                std::path::Path::new("bare.md"),
1353                SEED.replace("# Seed", "# Bare").as_bytes(),
1354            )
1355            .unwrap();
1356            crate::backend::MemBackend::commit(
1357                &inner,
1358                "seed",
1359                &crate::vcs::CommitContext::internal(),
1360            )
1361            .unwrap();
1362            let mount = crate::Mount {
1363                mem: "specs".to_string(),
1364                schema: Some(memstead_schema::SchemaRef::new(
1365                    "default",
1366                    semver::Version::new(1, 0, 0),
1367                )),
1368                storage: crate::MountStorage::Archive {
1369                    path: dir.path().join("sealed.mem"),
1370                },
1371                capability: crate::MountCapability::Write,
1372                lifecycle: crate::MountLifecycle::Eager,
1373                cross_linkable: false,
1374                migration_target: None,
1375            };
1376            crate::Engine::from_mounts(vec![(
1377                mount,
1378                Box::new(SealedBackend { inner, payload }) as Box<dyn crate::MemBackend>,
1379            )])
1380            .unwrap()
1381        }
1382        let payload = serde_json::json!({
1383            "format": 1,
1384            "history": "summarised",
1385            "entities": {
1386                "seed": {
1387                    "rationale": "seeded so the graph starts non-empty",
1388                    "kind": "create",
1389                    "timestamp": "2026-06-24T11:32:02Z",
1390                    "actor": "agent"
1391                }
1392            }
1393        });
1394        let engine = engine_with(Some(serde_json::to_vec(&payload).unwrap()));
1395        let prov = engine.entity_provenance("specs", "specs--seed").unwrap();
1396        let sealed = prov.sealed.expect("archive mount serves the sealed block");
1397        assert!(sealed.carried);
1398        assert_eq!(
1399            sealed.rationale.as_deref(),
1400            Some("seeded so the graph starts non-empty")
1401        );
1402        assert_eq!(sealed.kind.as_deref(), Some("create"));
1403        assert_eq!(sealed.actor.as_deref(), Some("agent"));
1404        assert_eq!(sealed.history.as_deref(), Some("summarised"));
1405        assert!(prov.created_by.is_none() && prov.last_modified_by.is_none());
1406        // An entity the payload does not name: stated as not carried.
1407        let bare = engine.entity_provenance("specs", "specs--bare").unwrap();
1408        let sealed = bare.sealed.unwrap();
1409        assert!(!sealed.carried && sealed.rationale.is_none());
1410        assert_eq!(sealed.history.as_deref(), Some("summarised"));
1411        // An unknown id still refuses, as the history read does.
1412        assert_eq!(
1413            engine
1414                .entity_provenance("specs", "specs--ghost")
1415                .unwrap_err()
1416                .code(),
1417            "ENTITY_NOT_FOUND"
1418        );
1419        // An archive with no payload at all: not carried, no history word.
1420        let engine = engine_with(None);
1421        let none = engine.entity_provenance("specs", "specs--seed").unwrap();
1422        let sealed = none.sealed.unwrap();
1423        assert!(!sealed.carried && sealed.history.is_none());
1424        // The history read keeps its refusal.
1425        assert_eq!(
1426            engine
1427                .entity_history("specs", "specs--seed", None, None)
1428                .unwrap_err()
1429                .code(),
1430            "INVALID_INPUT"
1431        );
1432    }
1433
1434    #[test]
1435    fn archive_mounts_refuse_rather_than_fabricate_emptiness() {
1436        // An archive-declared mount whose backend nonetheless serves
1437        // the store: the storage arm must refuse before the seam's
1438        // history-free `read_provenance` can masquerade as an empty
1439        // story.
1440        let dir = tempfile::TempDir::new().unwrap();
1441        let backend = crate::storage::InMemoryBackend::new();
1442        crate::backend::MemBackend::write_entity(
1443            &backend,
1444            std::path::Path::new("seed.md"),
1445            SEED.as_bytes(),
1446        )
1447        .unwrap();
1448        crate::backend::MemBackend::commit(
1449            &backend,
1450            "seed",
1451            &crate::vcs::CommitContext::internal(),
1452        )
1453        .unwrap();
1454        let mount = crate::Mount {
1455            mem: "specs".to_string(),
1456            schema: Some(memstead_schema::SchemaRef::new(
1457                "default",
1458                semver::Version::new(1, 0, 0),
1459            )),
1460            storage: crate::MountStorage::Archive {
1461                path: dir.path().join("sealed.mem"),
1462            },
1463            capability: crate::MountCapability::Write,
1464            lifecycle: crate::MountLifecycle::Eager,
1465            cross_linkable: false,
1466            migration_target: None,
1467        };
1468        let engine = crate::Engine::from_mounts(vec![(
1469            mount,
1470            Box::new(backend) as Box<dyn crate::MemBackend>,
1471        )])
1472        .unwrap();
1473        let err = engine
1474            .entity_history("specs", "specs--seed", None, None)
1475            .unwrap_err();
1476        assert_eq!(err.code(), "INVALID_INPUT");
1477    }
1478
1479    #[test]
1480    fn pages_compose_without_gaps_or_duplicates() {
1481        let tmp = tempfile::TempDir::new().unwrap();
1482        let mut engine = folder_engine(&tmp);
1483        let id = create(&mut engine, "Paged", "born");
1484        for i in 0..5 {
1485            update(&mut engine, &id, &format!("touch {i}"));
1486        }
1487
1488        let full = engine.entity_history("specs", &id, None, None).unwrap();
1489        assert_eq!(full.total_recorded, 6);
1490        assert!(full.next_cursor.is_none());
1491
1492        // Walk in pages of 2 and re-compose.
1493        let mut collected: Vec<super::EntityTouch> = Vec::new();
1494        let mut cursor: Option<String> = None;
1495        loop {
1496            let page = engine
1497                .entity_history("specs", &id, Some(2), cursor.as_deref())
1498                .unwrap();
1499            assert!(page.touches.len() <= 2);
1500            assert_eq!(page.total_recorded, 6, "every page states the whole");
1501            collected.extend(page.touches.clone());
1502            match page.next_cursor {
1503                Some(c) => cursor = Some(c),
1504                None => break,
1505            }
1506        }
1507        assert_eq!(
1508            collected, full.touches,
1509            "paged walk must equal the single-page story exactly"
1510        );
1511    }
1512}