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(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 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 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 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 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 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 let story_start = match touches.last() {
645 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 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
731fn 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
743pub(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 == ¤t) {
794 let mut touch = base(¤t);
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(¤t));
805 if is_create {
806 break;
807 }
808 } else if n.entity_ids.iter().any(|id| id == ¤t) {
809 let mut touch = base(¤t);
810 touch.batch_entity_ids = n.entity_ids.clone();
811 let created_by_merge = n.created_ids.iter().any(|id| id == ¤t);
814 let renamed_from = n
817 .merge_renames
818 .iter()
819 .filter_map(|pair| parse_rename_pair(pair))
820 .find(|(_, new)| new == ¤t)
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 if n.tool_verb.as_deref() == Some("batch-create") || created_by_merge {
835 break;
836 }
837 }
838 }
839 out
840}
841
842fn filter_provenance_for_entity(
853 entity_id: &str,
854 records: &[crate::provenance::Provenance],
855) -> Vec<EntityTouch> {
856 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 #[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 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", ¬es);
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 #[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 let eta = super::filter_notes_for_entity("m--eta", ¬es);
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 let beta = super::filter_notes_for_entity("m--beta", ¬es);
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 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 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 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 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 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 let err = engine.entity_history("ghost", &id, None, None).unwrap_err();
1232 assert_eq!(err.code(), "UNKNOWN_MEM");
1233 let err = engine
1235 .entity_history("specs", "specs--nope", None, None)
1236 .unwrap_err();
1237 assert_eq!(err.code(), "ENTITY_NOT_FOUND");
1238 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 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 #[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 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 assert_eq!(
1413 engine
1414 .entity_provenance("specs", "specs--ghost")
1415 .unwrap_err()
1416 .code(),
1417 "ENTITY_NOT_FOUND"
1418 );
1419 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 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 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 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}