1use serde::Serialize;
30
31use super::{Engine, EngineError};
32use crate::workspace::MountStorage;
33
34pub const HISTORY_PAGE_DEFAULT: usize = 50;
36pub const HISTORY_PAGE_MAX: usize = 200;
38
39#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
41pub struct EntityTouch {
42 pub reference: String,
46 pub timestamp: i64,
48 pub id_at_touch: String,
52 #[serde(skip_serializing_if = "Option::is_none")]
56 pub verb: Option<String>,
57 #[serde(skip_serializing_if = "Option::is_none")]
59 pub subject: Option<String>,
60 #[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 #[serde(skip_serializing_if = "Option::is_none")]
69 pub tool: Option<String>,
70 #[serde(skip_serializing_if = "Option::is_none")]
74 pub renamed_from: Option<String>,
75 #[serde(skip_serializing_if = "Option::is_none")]
77 pub renamed_to: Option<String>,
78 #[serde(skip_serializing_if = "Vec::is_empty", default)]
82 pub batch_entity_ids: Vec<String>,
83 #[serde(skip_serializing_if = "Option::is_none")]
85 pub logical_op: Option<String>,
86 #[serde(skip_serializing_if = "Option::is_none")]
89 pub role: Option<String>,
90 #[serde(skip_serializing_if = "Option::is_none")]
94 pub identity: Option<String>,
95 #[serde(skip_serializing_if = "Option::is_none")]
99 pub merged_by: Option<String>,
100 #[serde(skip_serializing_if = "Option::is_none")]
103 pub proposal: Option<String>,
104 #[serde(skip_serializing_if = "std::ops::Not::not", default)]
108 pub created_by_merge: bool,
109}
110
111#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
114#[serde(tag = "kind", rename_all = "lowercase")]
115pub enum StoryStart {
116 Recorded,
119 Truncated { reason: String },
123}
124
125#[derive(Debug, Clone, Serialize)]
128pub struct EntityHistoryReport {
129 pub mem: String,
130 pub entity_id: String,
132 pub touches: Vec<EntityTouch>,
134 pub total_recorded: usize,
137 #[serde(skip_serializing_if = "Option::is_none")]
140 pub next_cursor: Option<String>,
141 pub story_start: StoryStart,
143 #[serde(skip_serializing_if = "Vec::is_empty", default)]
146 pub limitations: Vec<String>,
147}
148
149pub(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#[derive(Debug, Clone, serde::Serialize)]
169pub struct ProvenanceRecord {
170 #[serde(skip_serializing_if = "Option::is_none")]
173 pub actor: Option<String>,
174 #[serde(skip_serializing_if = "Option::is_none")]
176 pub client: Option<String>,
177 pub role: String,
181 #[serde(skip_serializing_if = "Option::is_none")]
185 pub identity: Option<String>,
186 pub timestamp: i64,
188 pub reference: String,
190 #[serde(skip_serializing_if = "Option::is_none")]
195 pub verb: Option<String>,
196 #[serde(skip_serializing_if = "Option::is_none")]
200 pub merged_by: Option<String>,
201 #[serde(skip_serializing_if = "Option::is_none")]
203 pub proposal: Option<String>,
204 #[serde(skip_serializing_if = "Option::is_none")]
208 pub disposition: Option<String>,
209 #[serde(skip_serializing_if = "Option::is_none")]
213 pub proposal_description: Option<String>,
214}
215
216#[derive(Debug, Clone, serde::Serialize)]
220pub struct EntityProvenance {
221 #[serde(skip_serializing_if = "Option::is_none")]
225 pub created_by: Option<ProvenanceRecord>,
226 #[serde(skip_serializing_if = "Option::is_none")]
228 pub last_modified_by: Option<ProvenanceRecord>,
229 #[serde(skip_serializing_if = "std::ops::Not::not")]
232 pub story_truncated: bool,
233 pub check_state: String,
239 #[serde(skip_serializing_if = "Option::is_none")]
241 pub last_check: Option<crate::check::CheckRecord>,
242 #[serde(skip_serializing_if = "Option::is_none")]
266 pub check_prose_origin: Option<String>,
267 pub conformance_state: String,
272 #[serde(skip_serializing_if = "Option::is_none")]
274 pub last_conformance_check: Option<crate::check::CheckRecord>,
275 #[serde(skip_serializing_if = "Vec::is_empty")]
279 pub foreign_checks: Vec<crate::check::CheckRecord>,
280 #[serde(skip_serializing_if = "Option::is_none")]
285 pub sealed: Option<SealedProvenance>,
286}
287
288#[derive(Debug, Clone, serde::Serialize)]
294pub struct SealedProvenance {
295 pub carried: bool,
297 #[serde(skip_serializing_if = "Option::is_none")]
300 pub history: Option<String>,
301 #[serde(skip_serializing_if = "Option::is_none")]
304 pub rationale: Option<String>,
305 #[serde(skip_serializing_if = "Option::is_none")]
307 pub kind: Option<String>,
308 #[serde(skip_serializing_if = "Option::is_none")]
310 pub timestamp: Option<String>,
311 #[serde(skip_serializing_if = "Option::is_none")]
313 pub actor: Option<String>,
314 pub checks_carried: bool,
319 #[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 pub fn entity_provenance(
352 &self,
353 mem: &str,
354 entity_id: &str,
355 ) -> Result<EntityProvenance, EngineError> {
356 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 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 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 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 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 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 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 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 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 let story_start = match touches.last() {
649 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 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
735fn 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
747pub(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(¤t));
803 if is_create {
804 break;
805 }
806 } else if n.entity_ids.iter().any(|id| id == ¤t) {
807 let mut touch = base(¤t);
808 touch.batch_entity_ids = n.entity_ids.clone();
809 let created_by_merge = n.created_ids.iter().any(|id| id == ¤t);
812 touch.created_by_merge = created_by_merge;
813 out.push(touch);
814 if n.tool_verb.as_deref() == Some("batch-create") || created_by_merge {
817 break;
818 }
819 }
820 }
821 out
822}
823
824fn 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 #[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 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", ¬es);
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 #[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 let eta = super::filter_notes_for_entity("m--eta", ¬es);
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 let beta = super::filter_notes_for_entity("m--beta", ¬es);
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 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 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 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 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 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 let err = engine.entity_history("ghost", &id, None, None).unwrap_err();
1195 assert_eq!(err.code(), "UNKNOWN_MEM");
1196 let err = engine
1198 .entity_history("specs", "specs--nope", None, None)
1199 .unwrap_err();
1200 assert_eq!(err.code(), "ENTITY_NOT_FOUND");
1201 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 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 #[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 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 assert_eq!(
1370 engine
1371 .entity_provenance("specs", "specs--ghost")
1372 .unwrap_err()
1373 .code(),
1374 "ENTITY_NOT_FOUND"
1375 );
1376 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 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 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 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}