1use std::path::Path;
26
27use serde::Serialize;
28
29use crate::backend::BackendError;
30use crate::entity::EntityId;
31use crate::provenance::ProvenanceKind;
32
33pub const EMPTY_TREE_SHA: &str = "4b825dc642cb6eb9a060e54bf8d69288fbee4904";
38
39pub const RENAME_SIMILARITY_DEFAULT: f32 = 0.6;
46
47pub const RENAME_SIMILARITY_MIN: f32 = 0.1;
50
51pub const RENAME_SIMILARITY_MAX: f32 = 1.0;
55
56#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
66#[serde(tag = "action", rename_all = "lowercase")]
67pub enum ChangeEnvelope {
68 Added {
69 id: EntityId,
70 #[serde(skip_serializing_if = "Option::is_none")]
71 title: Option<String>,
72 #[serde(skip_serializing_if = "Option::is_none")]
73 entity_type: Option<String>,
74 },
75 Updated {
76 id: EntityId,
77 #[serde(skip_serializing_if = "Option::is_none")]
78 title: Option<String>,
79 #[serde(skip_serializing_if = "Option::is_none")]
80 entity_type: Option<String>,
81 },
82 Removed {
83 id: EntityId,
84 #[serde(skip_serializing_if = "Option::is_none")]
85 title: Option<String>,
86 #[serde(skip_serializing_if = "Option::is_none")]
87 entity_type: Option<String>,
88 },
89 Renamed {
90 from_id: EntityId,
91 to_id: EntityId,
92 #[serde(skip_serializing_if = "Option::is_none")]
93 title: Option<String>,
94 #[serde(skip_serializing_if = "Option::is_none")]
95 entity_type: Option<String>,
96 },
97}
98
99impl ChangeEnvelope {
100 pub fn primary_id(&self) -> &str {
103 match self {
104 ChangeEnvelope::Added { id, .. }
105 | ChangeEnvelope::Updated { id, .. }
106 | ChangeEnvelope::Removed { id, .. } => id.as_ref(),
107 ChangeEnvelope::Renamed { to_id, .. } => to_id.as_ref(),
108 }
109 }
110
111 pub fn action(&self) -> &'static str {
115 match self {
116 ChangeEnvelope::Added { .. } => "added",
117 ChangeEnvelope::Updated { .. } => "updated",
118 ChangeEnvelope::Removed { .. } => "removed",
119 ChangeEnvelope::Renamed { .. } => "renamed",
120 }
121 }
122
123 pub fn entity_type(&self) -> Option<&str> {
126 match self {
127 ChangeEnvelope::Added { entity_type, .. }
128 | ChangeEnvelope::Updated { entity_type, .. }
129 | ChangeEnvelope::Removed { entity_type, .. }
130 | ChangeEnvelope::Renamed { entity_type, .. } => entity_type.as_deref(),
131 }
132 }
133
134 fn without_metadata(&self) -> Self {
139 match self {
140 ChangeEnvelope::Added { id, .. } => ChangeEnvelope::Added {
141 id: id.clone(),
142 title: None,
143 entity_type: None,
144 },
145 ChangeEnvelope::Updated { id, .. } => ChangeEnvelope::Updated {
146 id: id.clone(),
147 title: None,
148 entity_type: None,
149 },
150 ChangeEnvelope::Removed { id, .. } => ChangeEnvelope::Removed {
151 id: id.clone(),
152 title: None,
153 entity_type: None,
154 },
155 ChangeEnvelope::Renamed { from_id, to_id, .. } => ChangeEnvelope::Renamed {
156 from_id: from_id.clone(),
157 to_id: to_id.clone(),
158 title: None,
159 entity_type: None,
160 },
161 }
162 }
163}
164
165#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
175pub struct BackendChanges {
176 pub since: String,
178 pub head: String,
181 pub changes: Vec<ChangeEnvelope>,
185 #[serde(default, skip_serializing_if = "Vec::is_empty")]
193 pub notes: Vec<crate::ops::agent_notes::CommitNote>,
194 #[serde(default, skip_serializing_if = "Option::is_none")]
199 pub memstead_ref: Option<String>,
200}
201
202impl BackendChanges {
203 pub fn empty_at(since: &str) -> Self {
207 Self {
208 since: since.to_string(),
209 head: since.to_string(),
210 changes: Vec::new(),
211 notes: Vec::new(),
212 memstead_ref: None,
213 }
214 }
215}
216
217pub type StoreLookup<'a> = &'a dyn Fn(&EntityId) -> Option<String>;
254
255pub fn folder_changes_since(
256 mem_root: &Path,
257 mem: &str,
258 since: &str,
259 store: Option<StoreLookup<'_>>,
260) -> Result<BackendChanges, BackendError> {
261 if !since.is_empty()
262 && since != EMPTY_TREE_SHA
263 && crate::filesystem::changelog::parse_rfc3339_utc(since).is_none()
264 {
265 return Err(BackendError::Other(format!("INVALID_TS_CURSOR:{since}")));
269 }
270 crate::storage::filesystem::refuse_cut_off_commit(mem_root)?;
274 let log_path = crate::filesystem::changelog::changelog_path(mem_root);
275 let raw = match std::fs::read_to_string(&log_path) {
276 Ok(s) => s,
277 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
278 return Ok(BackendChanges::empty_at(since));
279 }
280 Err(e) => return Err(BackendError::Io(e)),
281 };
282
283 struct Aggregate {
284 first_kind: ProvenanceKind,
285 last_kind: ProvenanceKind,
286 }
287 #[derive(Default)]
291 struct Lifetime {
292 created_at: Option<String>,
293 last_at: String,
294 deleted: bool,
295 named_by_rename: bool,
298 }
299 let mut by_entity: std::collections::BTreeMap<String, Aggregate> =
300 std::collections::BTreeMap::new();
301 let mut lifetimes: std::collections::BTreeMap<String, Lifetime> =
302 std::collections::BTreeMap::new();
303 let mut rename_rows: Vec<(String, String)> = Vec::new();
304 let mut max_ts: Option<String> = None;
305
306 let cursor_opt: Option<&str> = if since.is_empty() || since == EMPTY_TREE_SHA {
307 None
308 } else {
309 Some(since)
310 };
311
312 for line in raw.lines() {
313 let trimmed = line.trim();
314 if trimmed.is_empty() {
315 continue;
316 }
317 let value: serde_json::Value = match serde_json::from_str(trimmed) {
318 Ok(v) => v,
319 Err(_) => continue,
320 };
321 let ts_str = value.get("ts").and_then(|v| v.as_str()).unwrap_or("");
322 let kind = match value
323 .get("kind")
324 .and_then(|v| v.as_str())
325 .and_then(ProvenanceKind::parse)
326 {
327 Some(k) => k,
328 None => continue,
329 };
330 let entity_id = match value.get("entity").and_then(|v| v.as_str()) {
331 Some(s) if !s.is_empty() => s.to_string(),
332 _ => continue,
333 };
334 {
335 let life = lifetimes.entry(entity_id.clone()).or_default();
336 if matches!(kind, ProvenanceKind::Create) {
339 life.created_at = Some(ts_str.to_string());
340 life.deleted = false;
341 }
342 if ts_str >= life.last_at.as_str() {
343 life.last_at = ts_str.to_string();
344 life.named_by_rename = matches!(kind, ProvenanceKind::Rename);
345 }
346 if matches!(kind, ProvenanceKind::Delete) {
347 life.deleted = true;
348 }
349 }
350 if let Some(c) = cursor_opt
351 && ts_str <= c
352 {
353 continue;
354 }
355 if matches!(kind, ProvenanceKind::Rename) {
356 rename_rows.push((ts_str.to_string(), entity_id.clone()));
357 }
358
359 if max_ts.as_deref().is_none_or(|m| ts_str > m) {
360 max_ts = Some(ts_str.to_string());
361 }
362
363 by_entity
364 .entry(entity_id)
365 .and_modify(|agg| {
366 agg.last_kind = kind;
367 })
368 .or_insert(Aggregate {
369 first_kind: kind,
370 last_kind: kind,
371 });
372 }
373
374 let mut links: Vec<(String, String)> = Vec::new(); if let Some(lookup) = store {
381 let parse = |s: &str| match s.split_once("--") {
382 Some((v, slug)) if v == mem => Some(EntityId::new(v, slug)),
383 _ => None,
384 };
385 let exists = |name: &str| parse(name).and_then(|id| lookup(&id));
386 let mut taken: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
387 rename_rows.sort();
388 for (rename_ts, new_name) in &rename_rows {
389 let vanished: Vec<(&String, &Lifetime)> = lifetimes
390 .iter()
391 .filter(|(name, life)| {
392 *name != new_name
393 && !life.deleted
394 && !taken.contains(*name)
395 && life.last_at.as_str() < rename_ts.as_str()
396 && parse(name).is_some()
397 && exists(name).is_none()
398 })
399 .collect();
400 let same_instant: Vec<&String> = match exists(new_name) {
404 Some(created_date) => vanished
405 .iter()
406 .filter(|(_, life)| {
407 life.created_at
408 .as_deref()
409 .is_some_and(|c| same_instant(c, &created_date))
410 })
411 .map(|(name, _)| *name)
412 .collect(),
413 None => Vec::new(),
414 };
415 let nearest: Option<String> = vanished
416 .iter()
417 .max_by(|a, b| a.1.last_at.cmp(&b.1.last_at))
418 .map(|(name, _)| (*name).clone());
419 let continues_chain = nearest
423 .as_deref()
424 .is_some_and(|n| lifetimes.get(n).is_some_and(|l| l.named_by_rename));
425 let from = if continues_chain {
426 nearest
427 } else {
428 match same_instant.as_slice() {
429 [one] => Some((*one).clone()),
430 _ => nearest,
431 }
432 };
433 if let Some(from) = from {
434 taken.insert(from.clone());
435 links.push((from, new_name.clone()));
436 }
437 }
438 }
439 let mut paired: Vec<(String, String, Vec<String>)> = Vec::new(); for (from, _) in &links {
443 if links.iter().any(|(_, to)| to == from) {
444 continue;
445 }
446 let mut members = vec![from.clone()];
447 let mut current = from.clone();
448 while let Some((_, to)) = links.iter().find(|(f, _)| *f == current) {
449 members.push(to.clone());
450 current = to.clone();
451 }
452 paired.push((from.clone(), current, members));
453 }
454
455 let mut changes: Vec<ChangeEnvelope> = Vec::with_capacity(by_entity.len());
456 for (from, to, members) in &paired {
457 let from_agg = by_entity.remove(from);
458 for member in members {
459 by_entity.remove(member);
460 }
461 let (Some(from_id), Some(to_id)) = (
462 from.split_once("--").map(|(v, s)| EntityId::new(v, s)),
463 to.split_once("--").map(|(v, s)| EntityId::new(v, s)),
464 ) else {
465 continue;
466 };
467 let born_in_window =
468 from_agg.is_some_and(|a| matches!(a.first_kind, ProvenanceKind::Create));
469 changes.push(if born_in_window {
470 ChangeEnvelope::Added {
471 id: to_id,
472 title: None,
473 entity_type: None,
474 }
475 } else {
476 ChangeEnvelope::Renamed {
477 from_id,
478 to_id,
479 title: None,
480 entity_type: None,
481 }
482 });
483 }
484 for (entity_str, agg) in by_entity {
485 let id = match entity_str.split_once("--") {
486 Some((v, slug)) if v == mem => EntityId::new(v, slug),
487 _ => continue,
488 };
489 if let Some(lookup) = store
492 && !matches!(agg.last_kind, ProvenanceKind::Delete)
493 && lookup(&id).is_none()
494 {
495 changes.push(ChangeEnvelope::Removed {
496 id,
497 title: None,
498 entity_type: None,
499 });
500 continue;
501 }
502 let envelope = match (agg.first_kind, agg.last_kind) {
503 (_, ProvenanceKind::Delete) => ChangeEnvelope::Removed {
504 id,
505 title: None,
506 entity_type: None,
507 },
508 (ProvenanceKind::Create, _) => ChangeEnvelope::Added {
509 id,
510 title: None,
511 entity_type: None,
512 },
513 _ => ChangeEnvelope::Updated {
514 id,
515 title: None,
516 entity_type: None,
517 },
518 };
519 changes.push(envelope);
520 }
521
522 changes.sort_by(|a, b| a.primary_id().cmp(b.primary_id()));
523
524 Ok(BackendChanges {
525 since: since.to_string(),
526 head: max_ts.unwrap_or_else(|| since.to_string()),
527 changes,
528 notes: Vec::new(),
529 memstead_ref: None,
530 })
531}
532
533pub fn newest_writes_from_notes(
541 notes: &[crate::ops::agent_notes::CommitNote],
542) -> std::collections::BTreeMap<String, NewestWrite> {
543 let mut writes = std::collections::BTreeMap::new();
544 for note in notes {
545 let subject_ids = note
550 .entity_id
551 .iter()
552 .flat_map(|subject| subject.split(" → "))
553 .filter(|part| part.contains("--") && !part.contains(' '))
554 .map(str::to_string);
555 let named: Vec<String> = subject_ids
556 .chain(note.entity_ids.iter().cloned())
557 .chain(note.created_ids.iter().cloned())
558 .collect();
559 let batch = note
560 .tool_verb
561 .as_deref()
562 .is_some_and(|verb| verb.starts_with("batch"));
563 for id in &named {
564 if writes.contains_key(id) {
565 continue;
566 }
567 let text = match (¬e.note, batch) {
568 (Some(joined), true) => batch_entry_note(joined, id, &named),
569 (text, _) => text.clone(),
570 };
571 writes.insert(
572 id.clone(),
573 NewestWrite {
574 identity: note.identity.clone(),
575 note: text.map(bounded_note),
576 },
577 );
578 }
579 }
580 writes
581}
582
583fn batch_entry_note(joined: &str, id: &str, ids: &[String]) -> Option<String> {
592 let mut mine: Vec<&str> = Vec::new();
593 let mut owner: Option<&str> = None;
594 for line in joined.lines() {
595 if let (Some(current), Some(rest)) = (owner, line.strip_prefix(" ")) {
598 if current == id {
599 mine.push(rest);
600 }
601 continue;
602 }
603 let begins = ids.iter().find_map(|candidate| {
604 line.strip_prefix(candidate.as_str())
605 .and_then(|rest| rest.strip_prefix(": "))
606 .map(|rest| (candidate.as_str(), rest))
607 });
608 match begins {
609 Some((candidate, rest)) => {
610 owner = Some(candidate);
611 if candidate == id {
612 mine.push(rest);
613 }
614 }
615 None if owner == Some(id) => mine.push(line),
616 None => {}
617 }
618 }
619 (!mine.is_empty()).then(|| mine.join("\n"))
620}
621
622fn bounded_note(note: String) -> String {
627 let max = crate::mem_management::NOTE_MAX_LEN;
628 if note.chars().count() <= max {
629 return note;
630 }
631 let mut cut: String = note.chars().take(max).collect();
632 cut.push('…');
633 cut
634}
635
636pub fn folder_newest_writes(
641 mem_root: &Path,
642 since: &str,
643) -> std::collections::BTreeMap<String, NewestWrite> {
644 let mut writes = std::collections::BTreeMap::new();
645 let log_path = crate::filesystem::changelog::changelog_path(mem_root);
646 let Ok(raw) = std::fs::read_to_string(&log_path) else {
647 return writes;
648 };
649 let cursor = (!since.is_empty() && since != EMPTY_TREE_SHA).then_some(since);
650 let mut newest_at: std::collections::BTreeMap<String, String> =
651 std::collections::BTreeMap::new();
652 for line in raw.lines() {
653 let Ok(value) = serde_json::from_str::<serde_json::Value>(line.trim()) else {
654 continue;
655 };
656 let ts = value.get("ts").and_then(|v| v.as_str()).unwrap_or("");
657 if cursor.is_some_and(|c| ts <= c) {
658 continue;
659 }
660 let Some(entity) = value
661 .get("entity")
662 .and_then(|v| v.as_str())
663 .filter(|s| !s.is_empty())
664 else {
665 continue;
666 };
667 if newest_at.get(entity).is_some_and(|at| ts < at.as_str()) {
668 continue;
669 }
670 newest_at.insert(entity.to_string(), ts.to_string());
671 let text = |key: &str| {
672 value
673 .get(key)
674 .and_then(|v| v.as_str())
675 .filter(|s| !s.is_empty())
676 .map(str::to_string)
677 };
678 writes.insert(
679 entity.to_string(),
680 NewestWrite {
681 identity: text("identity"),
682 note: text("note").map(bounded_note),
683 },
684 );
685 }
686 writes
687}
688
689fn same_instant(ledger_ts: &str, created_date: &str) -> bool {
693 let norm = |s: &str| s.trim_end_matches('Z').replace('T', " ");
694 let a = norm(ledger_ts);
695 let b = norm(created_date);
696 let n = a.len().min(b.len());
697 n >= 10 && a[..n] == b[..n]
698}
699
700#[derive(Debug, Clone, Serialize)]
718pub struct ChangesReport {
719 pub mem: String,
720 pub since: String,
721 pub head: String,
722 pub changes: Vec<ChangeEnvelope>,
723 #[serde(default, skip_serializing_if = "Vec::is_empty")]
724 pub warnings: Vec<crate::ops::WarningHint>,
725 #[serde(default, skip_serializing_if = "Option::is_none")]
729 pub notes: Option<Vec<crate::ops::agent_notes::CommitNote>>,
730 #[serde(default, skip_serializing_if = "Option::is_none")]
734 pub memstead_ref: Option<String>,
735}
736
737pub(crate) const NOTICE_DETAILED_MAX: usize = 50;
744
745const NOTICE_IDS_MAX: usize = 500;
753
754#[derive(Debug, Clone, Serialize, PartialEq, Eq, Default)]
758pub struct NoticeByChange {
759 pub added: usize,
760 pub updated: usize,
761 pub removed: usize,
762 pub renamed: usize,
763}
764
765#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
776#[serde(tag = "mode", rename_all = "lowercase")]
777pub enum NoticeChanges {
778 Detailed { entries: Vec<NoticeEntry> },
782 Ids { entries: Vec<ChangeEnvelope> },
787 Counts {
792 counts: std::collections::BTreeMap<String, usize>,
793 by_change: NoticeByChange,
794 self_inform: String,
795 },
796}
797
798#[derive(Debug, Clone, Default, PartialEq, Eq)]
803pub struct NewestWrite {
804 pub identity: Option<String>,
805 pub note: Option<String>,
806}
807
808#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
820pub struct NoticeEntry {
821 #[serde(flatten)]
822 pub change: ChangeEnvelope,
823 #[serde(skip_serializing_if = "Option::is_none")]
824 pub identity: Option<String>,
825 #[serde(skip_serializing_if = "Option::is_none")]
826 pub note: Option<String>,
827}
828
829impl std::ops::Deref for NoticeEntry {
830 type Target = ChangeEnvelope;
831 fn deref(&self) -> &ChangeEnvelope {
832 &self.change
833 }
834}
835
836#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
848pub struct MemChangedNotice {
849 pub mem: String,
850 pub from_head: String,
851 pub to_head: String,
852 pub changes: NoticeChanges,
853}
854
855impl MemChangedNotice {
856 pub fn from_delta(
863 mem: String,
864 from_head: String,
865 to_head: String,
866 changes: Vec<ChangeEnvelope>,
867 ) -> Self {
868 Self::from_delta_with_writes(
869 mem,
870 from_head,
871 to_head,
872 changes,
873 &std::collections::BTreeMap::new(),
874 )
875 }
876
877 pub fn from_delta_with_writes(
884 mem: String,
885 from_head: String,
886 to_head: String,
887 mut changes: Vec<ChangeEnvelope>,
888 writes: &std::collections::BTreeMap<String, NewestWrite>,
889 ) -> Self {
890 changes.sort_by(|a, b| a.primary_id().cmp(b.primary_id()));
891 let n = changes.len();
892 let body = if n <= NOTICE_DETAILED_MAX {
893 NoticeChanges::Detailed {
894 entries: changes
895 .into_iter()
896 .map(|change| {
897 let write = writes.get(change.primary_id()).or_else(|| match &change {
898 ChangeEnvelope::Renamed { from_id, .. } => {
899 writes.get(AsRef::<str>::as_ref(from_id))
900 }
901 _ => None,
902 });
903 NoticeEntry {
904 identity: write.and_then(|w| w.identity.clone()),
905 note: write.and_then(|w| w.note.clone()),
906 change,
907 }
908 })
909 .collect(),
910 }
911 } else if n <= NOTICE_IDS_MAX {
912 NoticeChanges::Ids {
913 entries: changes
914 .iter()
915 .map(ChangeEnvelope::without_metadata)
916 .collect(),
917 }
918 } else {
919 let mut counts: std::collections::BTreeMap<String, usize> =
920 std::collections::BTreeMap::new();
921 let mut by_change = NoticeByChange::default();
922 for env in &changes {
923 match env {
924 ChangeEnvelope::Added { .. } => by_change.added += 1,
925 ChangeEnvelope::Updated { .. } => by_change.updated += 1,
926 ChangeEnvelope::Removed { .. } => by_change.removed += 1,
927 ChangeEnvelope::Renamed { .. } => by_change.renamed += 1,
928 }
929 if let Some(t) = env.entity_type() {
930 *counts.entry(t.to_string()).or_default() += 1;
931 }
932 }
933 NoticeChanges::Counts {
934 counts,
935 by_change,
936 self_inform: format!("call memstead_changes_since(since={from_head})"),
937 }
938 };
939 Self {
940 mem,
941 from_head,
942 to_head,
943 changes: body,
944 }
945 }
946
947 pub fn entity_count(&self) -> usize {
954 match &self.changes {
955 NoticeChanges::Detailed { entries } => entries.len(),
956 NoticeChanges::Ids { entries } => entries.len(),
957 NoticeChanges::Counts { by_change, .. } => {
958 by_change.added + by_change.updated + by_change.removed + by_change.renamed
959 }
960 }
961 }
962}
963
964#[cfg(test)]
965mod tests {
966 use super::*;
967
968 #[test]
969 fn empty_at_echoes_cursor() {
970 let r = BackendChanges::empty_at("abc");
971 assert_eq!(r.since, "abc");
972 assert_eq!(r.head, "abc");
973 assert!(r.changes.is_empty());
974 }
975
976 #[test]
977 fn changes_report_omits_notes_and_memstead_ref_when_none() {
978 let r = ChangesReport {
982 mem: "specs".to_string(),
983 since: "abc".to_string(),
984 head: "def".to_string(),
985 changes: Vec::new(),
986 warnings: Vec::new(),
987 notes: None,
988 memstead_ref: None,
989 };
990 let json = serde_json::to_string(&r).unwrap();
991 assert!(
992 !json.contains("\"notes\""),
993 "notes must be omitted when None: {json}"
994 );
995 assert!(
996 !json.contains("\"memstead_ref\""),
997 "memstead_ref must be omitted when None: {json}"
998 );
999 }
1000
1001 #[test]
1002 fn changes_report_emits_notes_and_memstead_ref_when_some() {
1003 let r = ChangesReport {
1007 mem: "specs".to_string(),
1008 since: "abc".to_string(),
1009 head: "def".to_string(),
1010 changes: Vec::new(),
1011 warnings: Vec::new(),
1012 notes: Some(Vec::new()),
1013 memstead_ref: Some("aabbccdd".to_string()),
1014 };
1015 let json = serde_json::to_string(&r).unwrap();
1016 assert!(
1017 json.contains("\"notes\":["),
1018 "notes must be present: {json}"
1019 );
1020 assert!(
1021 json.contains("\"memstead_ref\":\"aabbccdd\""),
1022 "memstead_ref must be present and carry the SHA: {json}"
1023 );
1024 }
1025
1026 #[test]
1027 fn change_envelope_serializes_action_tag() {
1028 let env = ChangeEnvelope::Added {
1032 id: EntityId::new("specs", "hello"),
1033 title: Some("Hello".to_string()),
1034 entity_type: Some("spec".to_string()),
1035 };
1036 let json = serde_json::to_string(&env).unwrap();
1037 assert!(json.contains(r#""action":"added""#));
1038 assert!(json.contains(r#""title":"Hello""#));
1039 assert!(json.contains(r#""entity_type":"spec""#));
1040 }
1041
1042 #[test]
1043 fn change_envelope_skips_none_metadata_fields() {
1044 let env = ChangeEnvelope::Removed {
1045 id: EntityId::new("specs", "gone"),
1046 title: None,
1047 entity_type: None,
1048 };
1049 let json = serde_json::to_string(&env).unwrap();
1050 assert!(json.contains(r#""action":"removed""#));
1051 assert!(!json.contains("\"title\""));
1052 assert!(!json.contains("\"entity_type\""));
1053 }
1054
1055 #[test]
1056 fn change_envelope_renamed_carries_both_ids() {
1057 let env = ChangeEnvelope::Renamed {
1058 from_id: EntityId::new("specs", "old"),
1059 to_id: EntityId::new("specs", "new"),
1060 title: Some("New".to_string()),
1061 entity_type: Some("spec".to_string()),
1062 };
1063 let json = serde_json::to_string(&env).unwrap();
1064 assert!(json.contains(r#""action":"renamed""#));
1065 assert!(json.contains(r#""from_id":"specs--old""#));
1066 assert!(json.contains(r#""to_id":"specs--new""#));
1067 }
1068
1069 fn added_envelopes(n: usize) -> Vec<ChangeEnvelope> {
1074 (0..n)
1075 .map(|i| ChangeEnvelope::Added {
1076 id: EntityId::new("specs", &format!("e-{i:04}")),
1077 title: Some(format!("Entity {i}")),
1078 entity_type: Some("spec".to_string()),
1079 })
1080 .collect()
1081 }
1082
1083 #[test]
1088 fn a_detailed_entry_names_the_newest_write_and_drops_what_was_not_declared() {
1089 let changes = vec![
1090 ChangeEnvelope::Updated {
1091 id: EntityId::new("specs", "bbb"),
1092 title: Some("B".to_string()),
1093 entity_type: Some("spec".to_string()),
1094 },
1095 ChangeEnvelope::Added {
1096 id: EntityId::new("specs", "aaa"),
1097 title: Some("A".to_string()),
1098 entity_type: Some("spec".to_string()),
1099 },
1100 ChangeEnvelope::Renamed {
1101 from_id: EntityId::new("specs", "old"),
1102 to_id: EntityId::new("specs", "new"),
1103 title: None,
1104 entity_type: None,
1105 },
1106 ChangeEnvelope::Removed {
1107 id: EntityId::new("specs", "zzz"),
1108 title: None,
1109 entity_type: None,
1110 },
1111 ];
1112 let write = |identity: Option<&str>, note: Option<&str>| NewestWrite {
1113 identity: identity.map(str::to_string),
1114 note: note.map(str::to_string),
1115 };
1116 let writes: std::collections::BTreeMap<String, NewestWrite> = [
1117 (
1118 "specs--aaa".to_string(),
1119 write(Some("xavier"), Some("made it")),
1120 ),
1121 ("specs--bbb".to_string(), write(None, Some("no name"))),
1122 ("specs--old".to_string(), write(Some("yolanda"), None)),
1124 ]
1125 .into_iter()
1126 .collect();
1127 let notice = MemChangedNotice::from_delta_with_writes(
1128 "specs".to_string(),
1129 "H0".to_string(),
1130 "H1".to_string(),
1131 changes.clone(),
1132 &writes,
1133 );
1134 let value = serde_json::to_value(¬ice).unwrap();
1135 let entries = value["changes"]["entries"].as_array().unwrap();
1136 assert_eq!(entries.len(), 4);
1137 assert_eq!(entries[0]["id"], "specs--aaa");
1138 assert_eq!(entries[0]["action"], "added");
1139 assert_eq!(entries[0]["identity"], "xavier");
1140 assert_eq!(entries[0]["note"], "made it");
1141 assert_eq!(entries[1]["id"], "specs--bbb");
1142 assert_eq!(entries[1]["note"], "no name");
1143 assert!(entries[1].get("identity").is_none(), "{}", entries[1]);
1144 assert_eq!(entries[2]["to_id"], "specs--new");
1145 assert_eq!(entries[2]["identity"], "yolanda");
1146 assert!(entries[2].get("note").is_none(), "{}", entries[2]);
1147 assert_eq!(entries[3]["id"], "specs--zzz");
1149 assert!(entries[3].get("identity").is_none() && entries[3].get("note").is_none());
1150
1151 let mut reversed = changes;
1153 reversed.reverse();
1154 let again = MemChangedNotice::from_delta_with_writes(
1155 "specs".to_string(),
1156 "H0".to_string(),
1157 "H1".to_string(),
1158 reversed,
1159 &writes,
1160 );
1161 assert_eq!(
1162 serde_json::to_string(¬ice).unwrap(),
1163 serde_json::to_string(&again).unwrap()
1164 );
1165
1166 let many = added_envelopes(NOTICE_DETAILED_MAX + 1);
1168 let all: std::collections::BTreeMap<String, NewestWrite> = many
1169 .iter()
1170 .map(|e| (e.primary_id().to_string(), write(Some("xavier"), Some("n"))))
1171 .collect();
1172 let ids = MemChangedNotice::from_delta_with_writes(
1173 "specs".to_string(),
1174 "H0".to_string(),
1175 "H1".to_string(),
1176 many,
1177 &all,
1178 );
1179 let json = serde_json::to_string(&ids).unwrap();
1180 assert!(json.contains(r#""mode":"ids""#));
1181 assert!(
1182 !json.contains("identity") && !json.contains("\"note\""),
1183 "{json}"
1184 );
1185 }
1186
1187 #[test]
1192 fn the_newest_note_that_names_an_id_decides_its_write() {
1193 let note = |subject_id: &str, ids: &[&str], identity: Option<&str>, text: Option<&str>| {
1194 crate::ops::agent_notes::CommitNote {
1195 mem: "specs".to_string(),
1196 sha: "0".repeat(40),
1197 subject: format!("memstead: write {subject_id}"),
1198 tool_verb: None,
1199 entity_id: Some(subject_id.to_string()),
1200 note: text.map(str::to_string),
1201 actor: None,
1202 tool: None,
1203 client: None,
1204 logical_operation_id: None,
1205 role: None,
1206 identity: identity.map(str::to_string),
1207 entity_ids: ids.iter().map(|s| s.to_string()).collect(),
1208 merged_by: None,
1209 proposal: None,
1210 created_ids: Vec::new(),
1211 co_writers: Vec::new(),
1212 unattributed_writes: Vec::new(),
1213 merge_renames: Vec::new(),
1214 timestamp: 0,
1215 }
1216 };
1217 let notes = vec![
1218 note(
1220 "specs--bee → specs--bumble",
1221 &["specs--aye"],
1222 Some("yolanda"),
1223 None,
1224 ),
1225 note("specs--aye", &[], Some("xavier"), Some("older")),
1227 note("specs--other", &[], None, Some("only a note")),
1228 ];
1229 let writes = newest_writes_from_notes(¬es);
1230 for id in ["specs--bee", "specs--bumble", "specs--aye"] {
1231 assert_eq!(writes[id].identity.as_deref(), Some("yolanda"), "{id}");
1232 assert_eq!(writes[id].note, None, "{id}: never the older write's note");
1233 }
1234 assert_eq!(writes["specs--other"].identity, None);
1235 assert_eq!(writes["specs--other"].note.as_deref(), Some("only a note"));
1236 }
1237
1238 #[test]
1243 fn a_batch_gives_each_entity_its_own_note_and_a_note_has_a_bound() {
1244 let batch = crate::ops::agent_notes::CommitNote {
1245 mem: "specs".to_string(),
1246 sha: "0".repeat(40),
1247 subject: "memstead: batch-update (3 entities)".to_string(),
1248 tool_verb: Some("batch-update".to_string()),
1249 entity_id: Some("(3 entities)".to_string()),
1250 note: Some(
1251 "specs--one: note for one\nand its second line\nspecs--three: Reason: three"
1252 .to_string(),
1253 ),
1254 actor: None,
1255 tool: None,
1256 client: None,
1257 logical_operation_id: None,
1258 role: None,
1259 identity: Some("yolanda".to_string()),
1260 entity_ids: vec![
1261 "specs--one".to_string(),
1262 "specs--two".to_string(),
1263 "specs--three".to_string(),
1264 ],
1265 merged_by: None,
1266 proposal: None,
1267 created_ids: Vec::new(),
1268 co_writers: Vec::new(),
1269 unattributed_writes: Vec::new(),
1270 merge_renames: Vec::new(),
1271 timestamp: 0,
1272 };
1273 let writes = newest_writes_from_notes(std::slice::from_ref(&batch));
1274 assert_eq!(
1275 writes["specs--one"].note.as_deref(),
1276 Some("note for one\nand its second line")
1277 );
1278 assert_eq!(writes["specs--two"].note, None, "its entry declared none");
1279 assert_eq!(
1280 writes["specs--three"].note.as_deref(),
1281 Some("Reason: three")
1282 );
1283 for id in ["specs--one", "specs--two", "specs--three"] {
1284 assert_eq!(writes[id].identity.as_deref(), Some("yolanda"));
1285 }
1286
1287 let joined = [
1291 crate::vcs::batch_note_line(
1292 "specs--one",
1293 "first line of one\nspecs--two: planted by one\nspecs--one: and its own id\n\nafter a gap",
1294 ),
1295 crate::vcs::batch_note_line("specs--three", "said by three"),
1296 ]
1297 .join("\n");
1298 let mut planted = batch.clone();
1299 planted.note = Some(joined);
1300 let writes = newest_writes_from_notes(std::slice::from_ref(&planted));
1301 assert_eq!(
1302 writes["specs--one"].note.as_deref(),
1303 Some(
1304 "first line of one\nspecs--two: planted by one\nspecs--one: and its own id\n\nafter a gap"
1305 )
1306 );
1307 assert_eq!(writes["specs--two"].note, None, "nothing was planted on it");
1308 assert_eq!(
1309 writes["specs--three"].note.as_deref(),
1310 Some("said by three")
1311 );
1312
1313 let limit = crate::mem_management::NOTE_MAX_LEN;
1316 let mut single = batch.clone();
1317 single.tool_verb = Some("update".to_string());
1318 single.entity_id = Some("specs--one".to_string());
1319 single.entity_ids = Vec::new();
1320 single.note = Some("n".repeat(limit));
1321 let whole = newest_writes_from_notes(std::slice::from_ref(&single));
1322 assert_eq!(
1323 whole["specs--one"].note.as_deref().map(str::len),
1324 Some(limit)
1325 );
1326 single.note = Some("ä".repeat(limit + 40));
1327 let cut = newest_writes_from_notes(std::slice::from_ref(&single));
1328 let text = cut["specs--one"].note.clone().unwrap();
1329 assert_eq!(text.chars().count(), limit + 1);
1330 assert!(text.ends_with('…'));
1331 }
1332
1333 #[test]
1334 fn notice_small_delta_is_detailed_ordered_and_typed() {
1335 let changes = vec![
1339 ChangeEnvelope::Updated {
1340 id: EntityId::new("specs", "bbb"),
1341 title: Some("Bee".to_string()),
1342 entity_type: Some("spec".to_string()),
1343 },
1344 ChangeEnvelope::Added {
1345 id: EntityId::new("specs", "aaa"),
1346 title: Some("Ay".to_string()),
1347 entity_type: Some("spec".to_string()),
1348 },
1349 ];
1350 let notice = MemChangedNotice::from_delta(
1351 "specs".to_string(),
1352 "H0".to_string(),
1353 "H1".to_string(),
1354 changes,
1355 );
1356 match ¬ice.changes {
1357 NoticeChanges::Detailed { entries } => {
1358 assert_eq!(entries.len(), 2);
1359 assert_eq!(entries[0].primary_id(), "specs--aaa");
1361 assert_eq!(entries[0].action(), "added");
1362 assert_eq!(entries[1].primary_id(), "specs--bbb");
1363 assert_eq!(entries[1].action(), "updated");
1364 assert_eq!(entries[1].entity_type(), Some("spec"));
1365 }
1366 other => panic!("expected detailed, got {other:?}"),
1367 }
1368 let json = serde_json::to_string(¬ice).unwrap();
1369 assert!(json.contains(r#""mode":"detailed""#));
1370 assert!(json.contains(r#""action":"updated""#));
1373 assert!(json.contains(r#""entity_type":"spec""#));
1374 assert!(
1375 !json.contains(r#""change":"#),
1376 "no legacy `change` key: {json}"
1377 );
1378 }
1379
1380 #[test]
1381 fn notice_entry_is_byte_identical_to_changes_since_envelope() {
1382 let env = ChangeEnvelope::Updated {
1389 id: EntityId::new("specs", "x"),
1390 title: Some("X".to_string()),
1391 entity_type: Some("spec".to_string()),
1392 };
1393 let changes_since_json = serde_json::to_value(&env).unwrap();
1394 let notice = MemChangedNotice::from_delta(
1395 "specs".to_string(),
1396 "H0".to_string(),
1397 "H1".to_string(),
1398 vec![env],
1399 );
1400 let notice_json = serde_json::to_value(¬ice).unwrap();
1401 let entry = ¬ice_json["changes"]["entries"][0];
1402 assert_eq!(
1403 entry, &changes_since_json,
1404 "notice entry must equal the changes_since envelope verbatim",
1405 );
1406 }
1407
1408 #[test]
1409 fn notice_renamed_carries_both_ids_and_sorts_under_to_id() {
1410 let changes = vec![ChangeEnvelope::Renamed {
1414 from_id: EntityId::new("specs", "old"),
1415 to_id: EntityId::new("specs", "new"),
1416 title: Some("New".to_string()),
1417 entity_type: Some("spec".to_string()),
1418 }];
1419 let notice = MemChangedNotice::from_delta(
1420 "specs".to_string(),
1421 "H0".to_string(),
1422 "H1".to_string(),
1423 changes,
1424 );
1425 match ¬ice.changes {
1426 NoticeChanges::Detailed { entries } => {
1427 assert_eq!(entries[0].primary_id(), "specs--new");
1428 assert_eq!(entries[0].action(), "renamed");
1429 }
1430 other => panic!("expected detailed, got {other:?}"),
1431 }
1432 let json = serde_json::to_string(¬ice).unwrap();
1433 assert!(
1434 json.contains(r#""from_id":"specs--old""#),
1435 "rename carries from_id: {json}"
1436 );
1437 assert!(
1438 json.contains(r#""to_id":"specs--new""#),
1439 "rename carries to_id: {json}"
1440 );
1441 }
1442
1443 #[test]
1444 fn notice_ids_tier_preserves_rename_both_ids() {
1445 let mut changes = added_envelopes(NOTICE_DETAILED_MAX);
1448 changes.push(ChangeEnvelope::Renamed {
1449 from_id: EntityId::new("specs", "zzz-old"),
1450 to_id: EntityId::new("specs", "zzz-new"),
1451 title: Some("Z".to_string()),
1452 entity_type: Some("spec".to_string()),
1453 });
1454 let notice = MemChangedNotice::from_delta(
1455 "specs".to_string(),
1456 "H0".to_string(),
1457 "H1".to_string(),
1458 changes,
1459 );
1460 let json = serde_json::to_string(¬ice).unwrap();
1461 assert!(
1462 json.contains(r#""mode":"ids""#),
1463 "expected ids tier: {json}"
1464 );
1465 assert!(json.contains(r#""from_id":"specs--zzz-old""#));
1466 assert!(json.contains(r#""to_id":"specs--zzz-new""#));
1467 assert!(!json.contains(r#""title""#), "ids tier drops title: {json}");
1469 }
1470
1471 #[test]
1472 fn notice_medium_delta_degrades_to_ids_with_every_id_inline() {
1473 let notice = MemChangedNotice::from_delta(
1476 "specs".to_string(),
1477 "H0".to_string(),
1478 "H1".to_string(),
1479 added_envelopes(60),
1480 );
1481 match ¬ice.changes {
1482 NoticeChanges::Ids { entries } => {
1483 assert_eq!(entries.len(), 60, "every changed id stays inline");
1484 assert_eq!(entries[0].primary_id(), "specs--e-0000");
1485 }
1486 other => panic!("expected ids, got {other:?}"),
1487 }
1488 let json = serde_json::to_string(¬ice).unwrap();
1489 assert!(json.contains(r#""mode":"ids""#));
1490 assert!(!json.contains(r#""title""#));
1492 assert!(!json.contains(r#""entity_type""#));
1493 }
1494
1495 #[test]
1496 fn notice_id_list_outlives_rich_detail() {
1497 let just_over_detail = NOTICE_DETAILED_MAX + 1;
1501 let notice = MemChangedNotice::from_delta(
1502 "specs".to_string(),
1503 "H0".to_string(),
1504 "H1".to_string(),
1505 added_envelopes(just_over_detail),
1506 );
1507 match ¬ice.changes {
1508 NoticeChanges::Ids { entries } => {
1509 assert_eq!(entries.len(), just_over_detail);
1510 }
1511 other => panic!("expected ids at {just_over_detail}, got {other:?}"),
1512 }
1513 }
1514
1515 #[test]
1516 fn notice_mass_delta_degrades_to_counts_with_self_inform() {
1517 let n = NOTICE_IDS_MAX + 1;
1521 let notice = MemChangedNotice::from_delta(
1522 "specs".to_string(),
1523 "H0".to_string(),
1524 "H1".to_string(),
1525 added_envelopes(n),
1526 );
1527 match ¬ice.changes {
1528 NoticeChanges::Counts {
1529 counts,
1530 by_change,
1531 self_inform,
1532 } => {
1533 assert_eq!(by_change.added, n);
1534 assert_eq!(counts.get("spec").copied(), Some(n));
1535 assert_eq!(self_inform, "call memstead_changes_since(since=H0)");
1536 }
1537 other => panic!("expected counts, got {other:?}"),
1538 }
1539 let json = serde_json::to_string(¬ice).unwrap();
1540 assert!(json.contains(r#""mode":"counts""#));
1541 assert!(!json.contains("specs--e-"));
1543 }
1544
1545 #[test]
1546 fn notice_is_deterministic_regardless_of_input_order() {
1547 let forward = added_envelopes(20);
1549 let mut reversed = forward.clone();
1550 reversed.reverse();
1551 let a = MemChangedNotice::from_delta(
1552 "specs".to_string(),
1553 "H0".to_string(),
1554 "H1".to_string(),
1555 forward,
1556 );
1557 let b = MemChangedNotice::from_delta(
1558 "specs".to_string(),
1559 "H0".to_string(),
1560 "H1".to_string(),
1561 reversed,
1562 );
1563 assert_eq!(
1564 serde_json::to_string(&a).unwrap(),
1565 serde_json::to_string(&b).unwrap(),
1566 );
1567 }
1568}