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 folder_changes(mem_root, mem, since, store, None)
262}
263
264pub fn folder_changes_since_within(
270 mem_root: &Path,
271 mem: &str,
272 since: &str,
273 store: Option<StoreLookup<'_>>,
274 lock_wait: Option<std::time::Duration>,
275) -> Result<BackendChanges, BackendError> {
276 folder_changes(mem_root, mem, since, store, Some(lock_wait))
277}
278
279fn folder_changes(
280 mem_root: &Path,
281 mem: &str,
282 since: &str,
283 store: Option<StoreLookup<'_>>,
284 lock_wait: Option<Option<std::time::Duration>>,
285) -> Result<BackendChanges, BackendError> {
286 if !since.is_empty()
287 && since != EMPTY_TREE_SHA
288 && crate::filesystem::changelog::parse_rfc3339_utc(since).is_none()
289 {
290 return Err(BackendError::Other(format!("INVALID_TS_CURSOR:{since}")));
294 }
295 match lock_wait {
299 Some(limit) => crate::storage::filesystem::refuse_cut_off_commit_within(mem_root, limit)?,
300 None => crate::storage::filesystem::refuse_cut_off_commit(mem_root)?,
301 }
302 let log_path = crate::filesystem::changelog::changelog_path(mem_root);
303 let raw = match std::fs::read_to_string(&log_path) {
304 Ok(s) => s,
305 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
306 return Ok(BackendChanges::empty_at(since));
307 }
308 Err(e) => return Err(BackendError::Io(e)),
309 };
310
311 struct Aggregate {
312 first_kind: ProvenanceKind,
313 last_kind: ProvenanceKind,
314 }
315 #[derive(Default)]
319 struct Lifetime {
320 created_at: Option<String>,
321 last_at: String,
322 deleted: bool,
323 named_by_rename: bool,
326 }
327 let mut by_entity: std::collections::BTreeMap<String, Aggregate> =
328 std::collections::BTreeMap::new();
329 let mut lifetimes: std::collections::BTreeMap<String, Lifetime> =
330 std::collections::BTreeMap::new();
331 let mut rename_rows: Vec<(String, String)> = Vec::new();
332 let mut max_ts: Option<String> = None;
333
334 let cursor_opt: Option<&str> = if since.is_empty() || since == EMPTY_TREE_SHA {
335 None
336 } else {
337 Some(since)
338 };
339
340 for line in raw.lines() {
341 let trimmed = line.trim();
342 if trimmed.is_empty() {
343 continue;
344 }
345 let value: serde_json::Value = match serde_json::from_str(trimmed) {
346 Ok(v) => v,
347 Err(_) => continue,
348 };
349 let ts_str = value.get("ts").and_then(|v| v.as_str()).unwrap_or("");
350 let kind = match value
351 .get("kind")
352 .and_then(|v| v.as_str())
353 .and_then(ProvenanceKind::parse)
354 {
355 Some(k) => k,
356 None => continue,
357 };
358 let entity_id = match value.get("entity").and_then(|v| v.as_str()) {
359 Some(s) if !s.is_empty() => s.to_string(),
360 _ => continue,
361 };
362 {
363 let life = lifetimes.entry(entity_id.clone()).or_default();
364 if matches!(kind, ProvenanceKind::Create) {
367 life.created_at = Some(ts_str.to_string());
368 life.deleted = false;
369 }
370 if ts_str >= life.last_at.as_str() {
371 life.last_at = ts_str.to_string();
372 life.named_by_rename = matches!(kind, ProvenanceKind::Rename);
373 }
374 if matches!(kind, ProvenanceKind::Delete) {
375 life.deleted = true;
376 }
377 }
378 if let Some(c) = cursor_opt
379 && ts_str <= c
380 {
381 continue;
382 }
383 if matches!(kind, ProvenanceKind::Rename) {
384 rename_rows.push((ts_str.to_string(), entity_id.clone()));
385 }
386
387 if max_ts.as_deref().is_none_or(|m| ts_str > m) {
388 max_ts = Some(ts_str.to_string());
389 }
390
391 by_entity
392 .entry(entity_id)
393 .and_modify(|agg| {
394 agg.last_kind = kind;
395 })
396 .or_insert(Aggregate {
397 first_kind: kind,
398 last_kind: kind,
399 });
400 }
401
402 let mut links: Vec<(String, String)> = Vec::new(); if let Some(lookup) = store {
409 let parse = |s: &str| match s.split_once("--") {
410 Some((v, slug)) if v == mem => Some(EntityId::new(v, slug)),
411 _ => None,
412 };
413 let exists = |name: &str| parse(name).and_then(|id| lookup(&id));
414 let mut taken: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
415 rename_rows.sort();
416 for (rename_ts, new_name) in &rename_rows {
417 let vanished: Vec<(&String, &Lifetime)> = lifetimes
418 .iter()
419 .filter(|(name, life)| {
420 *name != new_name
421 && !life.deleted
422 && !taken.contains(*name)
423 && life.last_at.as_str() < rename_ts.as_str()
424 && parse(name).is_some()
425 && exists(name).is_none()
426 })
427 .collect();
428 let same_instant: Vec<&String> = match exists(new_name) {
432 Some(created_date) => vanished
433 .iter()
434 .filter(|(_, life)| {
435 life.created_at
436 .as_deref()
437 .is_some_and(|c| same_instant(c, &created_date))
438 })
439 .map(|(name, _)| *name)
440 .collect(),
441 None => Vec::new(),
442 };
443 let nearest: Option<String> = vanished
444 .iter()
445 .max_by(|a, b| a.1.last_at.cmp(&b.1.last_at))
446 .map(|(name, _)| (*name).clone());
447 let continues_chain = nearest
451 .as_deref()
452 .is_some_and(|n| lifetimes.get(n).is_some_and(|l| l.named_by_rename));
453 let from = if continues_chain {
454 nearest
455 } else {
456 match same_instant.as_slice() {
457 [one] => Some((*one).clone()),
458 _ => nearest,
459 }
460 };
461 if let Some(from) = from {
462 taken.insert(from.clone());
463 links.push((from, new_name.clone()));
464 }
465 }
466 }
467 let mut paired: Vec<(String, String, Vec<String>)> = Vec::new(); for (from, _) in &links {
471 if links.iter().any(|(_, to)| to == from) {
472 continue;
473 }
474 let mut members = vec![from.clone()];
475 let mut current = from.clone();
476 while let Some((_, to)) = links.iter().find(|(f, _)| *f == current) {
477 members.push(to.clone());
478 current = to.clone();
479 }
480 paired.push((from.clone(), current, members));
481 }
482
483 let mut changes: Vec<ChangeEnvelope> = Vec::with_capacity(by_entity.len());
484 for (from, to, members) in &paired {
485 let from_agg = by_entity.remove(from);
486 for member in members {
487 by_entity.remove(member);
488 }
489 let (Some(from_id), Some(to_id)) = (
490 from.split_once("--").map(|(v, s)| EntityId::new(v, s)),
491 to.split_once("--").map(|(v, s)| EntityId::new(v, s)),
492 ) else {
493 continue;
494 };
495 let born_in_window =
496 from_agg.is_some_and(|a| matches!(a.first_kind, ProvenanceKind::Create));
497 changes.push(if born_in_window {
498 ChangeEnvelope::Added {
499 id: to_id,
500 title: None,
501 entity_type: None,
502 }
503 } else {
504 ChangeEnvelope::Renamed {
505 from_id,
506 to_id,
507 title: None,
508 entity_type: None,
509 }
510 });
511 }
512 for (entity_str, agg) in by_entity {
513 let id = match entity_str.split_once("--") {
514 Some((v, slug)) if v == mem => EntityId::new(v, slug),
515 _ => continue,
516 };
517 if let Some(lookup) = store
520 && !matches!(agg.last_kind, ProvenanceKind::Delete)
521 && lookup(&id).is_none()
522 {
523 changes.push(ChangeEnvelope::Removed {
524 id,
525 title: None,
526 entity_type: None,
527 });
528 continue;
529 }
530 let envelope = match (agg.first_kind, agg.last_kind) {
531 (_, ProvenanceKind::Delete) => ChangeEnvelope::Removed {
532 id,
533 title: None,
534 entity_type: None,
535 },
536 (ProvenanceKind::Create, _) => ChangeEnvelope::Added {
537 id,
538 title: None,
539 entity_type: None,
540 },
541 _ => ChangeEnvelope::Updated {
542 id,
543 title: None,
544 entity_type: None,
545 },
546 };
547 changes.push(envelope);
548 }
549
550 changes.sort_by(|a, b| a.primary_id().cmp(b.primary_id()));
551
552 Ok(BackendChanges {
553 since: since.to_string(),
554 head: max_ts.unwrap_or_else(|| since.to_string()),
555 changes,
556 notes: Vec::new(),
557 memstead_ref: None,
558 })
559}
560
561pub fn newest_writes_from_notes(
569 notes: &[crate::ops::agent_notes::CommitNote],
570) -> std::collections::BTreeMap<String, NewestWrite> {
571 let mut writes = std::collections::BTreeMap::new();
572 for note in notes {
573 let subject_ids = note
578 .entity_id
579 .iter()
580 .flat_map(|subject| subject.split(" → "))
581 .filter(|part| part.contains("--") && !part.contains(' '))
582 .map(str::to_string);
583 let named: Vec<String> = subject_ids
584 .chain(note.entity_ids.iter().cloned())
585 .chain(note.created_ids.iter().cloned())
586 .collect();
587 let batch = note
588 .tool_verb
589 .as_deref()
590 .is_some_and(|verb| verb.starts_with("batch"));
591 for id in &named {
592 if writes.contains_key(id) {
593 continue;
594 }
595 let text = match (¬e.note, batch) {
596 (Some(joined), true) => batch_entry_note(joined, id, &named),
597 (text, _) => text.clone(),
598 };
599 writes.insert(
600 id.clone(),
601 NewestWrite {
602 identity: note.identity.clone(),
603 note: text.map(bounded_note),
604 },
605 );
606 }
607 }
608 writes
609}
610
611fn batch_entry_note(joined: &str, id: &str, ids: &[String]) -> Option<String> {
620 let mut mine: Vec<&str> = Vec::new();
621 let mut owner: Option<&str> = None;
622 for line in joined.lines() {
623 if let (Some(current), Some(rest)) = (owner, line.strip_prefix(" ")) {
626 if current == id {
627 mine.push(rest);
628 }
629 continue;
630 }
631 let begins = ids.iter().find_map(|candidate| {
632 line.strip_prefix(candidate.as_str())
633 .and_then(|rest| rest.strip_prefix(": "))
634 .map(|rest| (candidate.as_str(), rest))
635 });
636 match begins {
637 Some((candidate, rest)) => {
638 owner = Some(candidate);
639 if candidate == id {
640 mine.push(rest);
641 }
642 }
643 None if owner == Some(id) => mine.push(line),
644 None => {}
645 }
646 }
647 (!mine.is_empty()).then(|| mine.join("\n"))
648}
649
650fn bounded_note(note: String) -> String {
655 let max = crate::mem_management::NOTE_MAX_LEN;
656 if note.chars().count() <= max {
657 return note;
658 }
659 let mut cut: String = note.chars().take(max).collect();
660 cut.push('…');
661 cut
662}
663
664pub fn folder_newest_writes(
669 mem_root: &Path,
670 since: &str,
671) -> std::collections::BTreeMap<String, NewestWrite> {
672 let mut writes = std::collections::BTreeMap::new();
673 let log_path = crate::filesystem::changelog::changelog_path(mem_root);
674 let Ok(raw) = std::fs::read_to_string(&log_path) else {
675 return writes;
676 };
677 let cursor = (!since.is_empty() && since != EMPTY_TREE_SHA).then_some(since);
678 let mut newest_at: std::collections::BTreeMap<String, String> =
679 std::collections::BTreeMap::new();
680 for line in raw.lines() {
681 let Ok(value) = serde_json::from_str::<serde_json::Value>(line.trim()) else {
682 continue;
683 };
684 let ts = value.get("ts").and_then(|v| v.as_str()).unwrap_or("");
685 if cursor.is_some_and(|c| ts <= c) {
686 continue;
687 }
688 let Some(entity) = value
689 .get("entity")
690 .and_then(|v| v.as_str())
691 .filter(|s| !s.is_empty())
692 else {
693 continue;
694 };
695 if newest_at.get(entity).is_some_and(|at| ts < at.as_str()) {
696 continue;
697 }
698 newest_at.insert(entity.to_string(), ts.to_string());
699 let text = |key: &str| {
700 value
701 .get(key)
702 .and_then(|v| v.as_str())
703 .filter(|s| !s.is_empty())
704 .map(str::to_string)
705 };
706 writes.insert(
707 entity.to_string(),
708 NewestWrite {
709 identity: text("identity"),
710 note: text("note").map(bounded_note),
711 },
712 );
713 }
714 writes
715}
716
717fn same_instant(ledger_ts: &str, created_date: &str) -> bool {
721 let norm = |s: &str| s.trim_end_matches('Z').replace('T', " ");
722 let a = norm(ledger_ts);
723 let b = norm(created_date);
724 let n = a.len().min(b.len());
725 n >= 10 && a[..n] == b[..n]
726}
727
728#[derive(Debug, Clone, Serialize)]
746pub struct ChangesReport {
747 pub mem: String,
748 pub since: String,
749 pub head: String,
750 pub changes: Vec<ChangeEnvelope>,
751 #[serde(default, skip_serializing_if = "Vec::is_empty")]
752 pub warnings: Vec<crate::ops::WarningHint>,
753 #[serde(default, skip_serializing_if = "Option::is_none")]
757 pub notes: Option<Vec<crate::ops::agent_notes::CommitNote>>,
758 #[serde(default, skip_serializing_if = "Option::is_none")]
762 pub memstead_ref: Option<String>,
763}
764
765pub(crate) const NOTICE_DETAILED_MAX: usize = 50;
772
773const NOTICE_IDS_MAX: usize = 500;
781
782#[derive(Debug, Clone, Serialize, PartialEq, Eq, Default)]
786pub struct NoticeByChange {
787 pub added: usize,
788 pub updated: usize,
789 pub removed: usize,
790 pub renamed: usize,
791}
792
793#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
804#[serde(tag = "mode", rename_all = "lowercase")]
805pub enum NoticeChanges {
806 Detailed { entries: Vec<NoticeEntry> },
810 Ids { entries: Vec<ChangeEnvelope> },
815 Counts {
820 counts: std::collections::BTreeMap<String, usize>,
821 by_change: NoticeByChange,
822 self_inform: String,
823 },
824}
825
826#[derive(Debug, Clone, Default, PartialEq, Eq)]
831pub struct NewestWrite {
832 pub identity: Option<String>,
833 pub note: Option<String>,
834}
835
836#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
848pub struct NoticeEntry {
849 #[serde(flatten)]
850 pub change: ChangeEnvelope,
851 #[serde(skip_serializing_if = "Option::is_none")]
852 pub identity: Option<String>,
853 #[serde(skip_serializing_if = "Option::is_none")]
854 pub note: Option<String>,
855}
856
857impl std::ops::Deref for NoticeEntry {
858 type Target = ChangeEnvelope;
859 fn deref(&self) -> &ChangeEnvelope {
860 &self.change
861 }
862}
863
864#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
876pub struct MemChangedNotice {
877 pub mem: String,
878 pub from_head: String,
879 pub to_head: String,
880 pub changes: NoticeChanges,
881}
882
883impl MemChangedNotice {
884 pub fn from_delta(
891 mem: String,
892 from_head: String,
893 to_head: String,
894 changes: Vec<ChangeEnvelope>,
895 ) -> Self {
896 Self::from_delta_with_writes(
897 mem,
898 from_head,
899 to_head,
900 changes,
901 &std::collections::BTreeMap::new(),
902 )
903 }
904
905 pub fn from_delta_with_writes(
912 mem: String,
913 from_head: String,
914 to_head: String,
915 mut changes: Vec<ChangeEnvelope>,
916 writes: &std::collections::BTreeMap<String, NewestWrite>,
917 ) -> Self {
918 changes.sort_by(|a, b| a.primary_id().cmp(b.primary_id()));
919 let n = changes.len();
920 let body = if n <= NOTICE_DETAILED_MAX {
921 NoticeChanges::Detailed {
922 entries: changes
923 .into_iter()
924 .map(|change| {
925 let write = writes.get(change.primary_id()).or_else(|| match &change {
926 ChangeEnvelope::Renamed { from_id, .. } => {
927 writes.get(AsRef::<str>::as_ref(from_id))
928 }
929 _ => None,
930 });
931 NoticeEntry {
932 identity: write.and_then(|w| w.identity.clone()),
933 note: write.and_then(|w| w.note.clone()),
934 change,
935 }
936 })
937 .collect(),
938 }
939 } else if n <= NOTICE_IDS_MAX {
940 NoticeChanges::Ids {
941 entries: changes
942 .iter()
943 .map(ChangeEnvelope::without_metadata)
944 .collect(),
945 }
946 } else {
947 let mut counts: std::collections::BTreeMap<String, usize> =
948 std::collections::BTreeMap::new();
949 let mut by_change = NoticeByChange::default();
950 for env in &changes {
951 match env {
952 ChangeEnvelope::Added { .. } => by_change.added += 1,
953 ChangeEnvelope::Updated { .. } => by_change.updated += 1,
954 ChangeEnvelope::Removed { .. } => by_change.removed += 1,
955 ChangeEnvelope::Renamed { .. } => by_change.renamed += 1,
956 }
957 if let Some(t) = env.entity_type() {
958 *counts.entry(t.to_string()).or_default() += 1;
959 }
960 }
961 NoticeChanges::Counts {
962 counts,
963 by_change,
964 self_inform: format!("call memstead_changes_since(since={from_head})"),
965 }
966 };
967 Self {
968 mem,
969 from_head,
970 to_head,
971 changes: body,
972 }
973 }
974
975 pub fn entity_count(&self) -> usize {
982 match &self.changes {
983 NoticeChanges::Detailed { entries } => entries.len(),
984 NoticeChanges::Ids { entries } => entries.len(),
985 NoticeChanges::Counts { by_change, .. } => {
986 by_change.added + by_change.updated + by_change.removed + by_change.renamed
987 }
988 }
989 }
990}
991
992#[cfg(test)]
993mod tests {
994 use super::*;
995
996 #[test]
997 fn empty_at_echoes_cursor() {
998 let r = BackendChanges::empty_at("abc");
999 assert_eq!(r.since, "abc");
1000 assert_eq!(r.head, "abc");
1001 assert!(r.changes.is_empty());
1002 }
1003
1004 #[test]
1005 fn changes_report_omits_notes_and_memstead_ref_when_none() {
1006 let r = ChangesReport {
1010 mem: "specs".to_string(),
1011 since: "abc".to_string(),
1012 head: "def".to_string(),
1013 changes: Vec::new(),
1014 warnings: Vec::new(),
1015 notes: None,
1016 memstead_ref: None,
1017 };
1018 let json = serde_json::to_string(&r).unwrap();
1019 assert!(
1020 !json.contains("\"notes\""),
1021 "notes must be omitted when None: {json}"
1022 );
1023 assert!(
1024 !json.contains("\"memstead_ref\""),
1025 "memstead_ref must be omitted when None: {json}"
1026 );
1027 }
1028
1029 #[test]
1030 fn changes_report_emits_notes_and_memstead_ref_when_some() {
1031 let r = ChangesReport {
1035 mem: "specs".to_string(),
1036 since: "abc".to_string(),
1037 head: "def".to_string(),
1038 changes: Vec::new(),
1039 warnings: Vec::new(),
1040 notes: Some(Vec::new()),
1041 memstead_ref: Some("aabbccdd".to_string()),
1042 };
1043 let json = serde_json::to_string(&r).unwrap();
1044 assert!(
1045 json.contains("\"notes\":["),
1046 "notes must be present: {json}"
1047 );
1048 assert!(
1049 json.contains("\"memstead_ref\":\"aabbccdd\""),
1050 "memstead_ref must be present and carry the SHA: {json}"
1051 );
1052 }
1053
1054 #[test]
1055 fn change_envelope_serializes_action_tag() {
1056 let env = ChangeEnvelope::Added {
1060 id: EntityId::new("specs", "hello"),
1061 title: Some("Hello".to_string()),
1062 entity_type: Some("spec".to_string()),
1063 };
1064 let json = serde_json::to_string(&env).unwrap();
1065 assert!(json.contains(r#""action":"added""#));
1066 assert!(json.contains(r#""title":"Hello""#));
1067 assert!(json.contains(r#""entity_type":"spec""#));
1068 }
1069
1070 #[test]
1071 fn change_envelope_skips_none_metadata_fields() {
1072 let env = ChangeEnvelope::Removed {
1073 id: EntityId::new("specs", "gone"),
1074 title: None,
1075 entity_type: None,
1076 };
1077 let json = serde_json::to_string(&env).unwrap();
1078 assert!(json.contains(r#""action":"removed""#));
1079 assert!(!json.contains("\"title\""));
1080 assert!(!json.contains("\"entity_type\""));
1081 }
1082
1083 #[test]
1084 fn change_envelope_renamed_carries_both_ids() {
1085 let env = ChangeEnvelope::Renamed {
1086 from_id: EntityId::new("specs", "old"),
1087 to_id: EntityId::new("specs", "new"),
1088 title: Some("New".to_string()),
1089 entity_type: Some("spec".to_string()),
1090 };
1091 let json = serde_json::to_string(&env).unwrap();
1092 assert!(json.contains(r#""action":"renamed""#));
1093 assert!(json.contains(r#""from_id":"specs--old""#));
1094 assert!(json.contains(r#""to_id":"specs--new""#));
1095 }
1096
1097 fn added_envelopes(n: usize) -> Vec<ChangeEnvelope> {
1102 (0..n)
1103 .map(|i| ChangeEnvelope::Added {
1104 id: EntityId::new("specs", &format!("e-{i:04}")),
1105 title: Some(format!("Entity {i}")),
1106 entity_type: Some("spec".to_string()),
1107 })
1108 .collect()
1109 }
1110
1111 #[test]
1116 fn a_detailed_entry_names_the_newest_write_and_drops_what_was_not_declared() {
1117 let changes = vec![
1118 ChangeEnvelope::Updated {
1119 id: EntityId::new("specs", "bbb"),
1120 title: Some("B".to_string()),
1121 entity_type: Some("spec".to_string()),
1122 },
1123 ChangeEnvelope::Added {
1124 id: EntityId::new("specs", "aaa"),
1125 title: Some("A".to_string()),
1126 entity_type: Some("spec".to_string()),
1127 },
1128 ChangeEnvelope::Renamed {
1129 from_id: EntityId::new("specs", "old"),
1130 to_id: EntityId::new("specs", "new"),
1131 title: None,
1132 entity_type: None,
1133 },
1134 ChangeEnvelope::Removed {
1135 id: EntityId::new("specs", "zzz"),
1136 title: None,
1137 entity_type: None,
1138 },
1139 ];
1140 let write = |identity: Option<&str>, note: Option<&str>| NewestWrite {
1141 identity: identity.map(str::to_string),
1142 note: note.map(str::to_string),
1143 };
1144 let writes: std::collections::BTreeMap<String, NewestWrite> = [
1145 (
1146 "specs--aaa".to_string(),
1147 write(Some("xavier"), Some("made it")),
1148 ),
1149 ("specs--bbb".to_string(), write(None, Some("no name"))),
1150 ("specs--old".to_string(), write(Some("yolanda"), None)),
1152 ]
1153 .into_iter()
1154 .collect();
1155 let notice = MemChangedNotice::from_delta_with_writes(
1156 "specs".to_string(),
1157 "H0".to_string(),
1158 "H1".to_string(),
1159 changes.clone(),
1160 &writes,
1161 );
1162 let value = serde_json::to_value(¬ice).unwrap();
1163 let entries = value["changes"]["entries"].as_array().unwrap();
1164 assert_eq!(entries.len(), 4);
1165 assert_eq!(entries[0]["id"], "specs--aaa");
1166 assert_eq!(entries[0]["action"], "added");
1167 assert_eq!(entries[0]["identity"], "xavier");
1168 assert_eq!(entries[0]["note"], "made it");
1169 assert_eq!(entries[1]["id"], "specs--bbb");
1170 assert_eq!(entries[1]["note"], "no name");
1171 assert!(entries[1].get("identity").is_none(), "{}", entries[1]);
1172 assert_eq!(entries[2]["to_id"], "specs--new");
1173 assert_eq!(entries[2]["identity"], "yolanda");
1174 assert!(entries[2].get("note").is_none(), "{}", entries[2]);
1175 assert_eq!(entries[3]["id"], "specs--zzz");
1177 assert!(entries[3].get("identity").is_none() && entries[3].get("note").is_none());
1178
1179 let mut reversed = changes;
1181 reversed.reverse();
1182 let again = MemChangedNotice::from_delta_with_writes(
1183 "specs".to_string(),
1184 "H0".to_string(),
1185 "H1".to_string(),
1186 reversed,
1187 &writes,
1188 );
1189 assert_eq!(
1190 serde_json::to_string(¬ice).unwrap(),
1191 serde_json::to_string(&again).unwrap()
1192 );
1193
1194 let many = added_envelopes(NOTICE_DETAILED_MAX + 1);
1196 let all: std::collections::BTreeMap<String, NewestWrite> = many
1197 .iter()
1198 .map(|e| (e.primary_id().to_string(), write(Some("xavier"), Some("n"))))
1199 .collect();
1200 let ids = MemChangedNotice::from_delta_with_writes(
1201 "specs".to_string(),
1202 "H0".to_string(),
1203 "H1".to_string(),
1204 many,
1205 &all,
1206 );
1207 let json = serde_json::to_string(&ids).unwrap();
1208 assert!(json.contains(r#""mode":"ids""#));
1209 assert!(
1210 !json.contains("identity") && !json.contains("\"note\""),
1211 "{json}"
1212 );
1213 }
1214
1215 #[test]
1220 fn the_newest_note_that_names_an_id_decides_its_write() {
1221 let note = |subject_id: &str, ids: &[&str], identity: Option<&str>, text: Option<&str>| {
1222 crate::ops::agent_notes::CommitNote {
1223 mem: "specs".to_string(),
1224 sha: "0".repeat(40),
1225 subject: format!("memstead: write {subject_id}"),
1226 tool_verb: None,
1227 entity_id: Some(subject_id.to_string()),
1228 note: text.map(str::to_string),
1229 actor: None,
1230 tool: None,
1231 client: None,
1232 logical_operation_id: None,
1233 role: None,
1234 identity: identity.map(str::to_string),
1235 entity_ids: ids.iter().map(|s| s.to_string()).collect(),
1236 merged_by: None,
1237 proposal: None,
1238 created_ids: Vec::new(),
1239 co_writers: Vec::new(),
1240 unattributed_writes: Vec::new(),
1241 merge_renames: Vec::new(),
1242 timestamp: 0,
1243 }
1244 };
1245 let notes = vec![
1246 note(
1248 "specs--bee → specs--bumble",
1249 &["specs--aye"],
1250 Some("yolanda"),
1251 None,
1252 ),
1253 note("specs--aye", &[], Some("xavier"), Some("older")),
1255 note("specs--other", &[], None, Some("only a note")),
1256 ];
1257 let writes = newest_writes_from_notes(¬es);
1258 for id in ["specs--bee", "specs--bumble", "specs--aye"] {
1259 assert_eq!(writes[id].identity.as_deref(), Some("yolanda"), "{id}");
1260 assert_eq!(writes[id].note, None, "{id}: never the older write's note");
1261 }
1262 assert_eq!(writes["specs--other"].identity, None);
1263 assert_eq!(writes["specs--other"].note.as_deref(), Some("only a note"));
1264 }
1265
1266 #[test]
1271 fn a_batch_gives_each_entity_its_own_note_and_a_note_has_a_bound() {
1272 let batch = crate::ops::agent_notes::CommitNote {
1273 mem: "specs".to_string(),
1274 sha: "0".repeat(40),
1275 subject: "memstead: batch-update (3 entities)".to_string(),
1276 tool_verb: Some("batch-update".to_string()),
1277 entity_id: Some("(3 entities)".to_string()),
1278 note: Some(
1279 "specs--one: note for one\nand its second line\nspecs--three: Reason: three"
1280 .to_string(),
1281 ),
1282 actor: None,
1283 tool: None,
1284 client: None,
1285 logical_operation_id: None,
1286 role: None,
1287 identity: Some("yolanda".to_string()),
1288 entity_ids: vec![
1289 "specs--one".to_string(),
1290 "specs--two".to_string(),
1291 "specs--three".to_string(),
1292 ],
1293 merged_by: None,
1294 proposal: None,
1295 created_ids: Vec::new(),
1296 co_writers: Vec::new(),
1297 unattributed_writes: Vec::new(),
1298 merge_renames: Vec::new(),
1299 timestamp: 0,
1300 };
1301 let writes = newest_writes_from_notes(std::slice::from_ref(&batch));
1302 assert_eq!(
1303 writes["specs--one"].note.as_deref(),
1304 Some("note for one\nand its second line")
1305 );
1306 assert_eq!(writes["specs--two"].note, None, "its entry declared none");
1307 assert_eq!(
1308 writes["specs--three"].note.as_deref(),
1309 Some("Reason: three")
1310 );
1311 for id in ["specs--one", "specs--two", "specs--three"] {
1312 assert_eq!(writes[id].identity.as_deref(), Some("yolanda"));
1313 }
1314
1315 let joined = [
1319 crate::vcs::batch_note_line(
1320 "specs--one",
1321 "first line of one\nspecs--two: planted by one\nspecs--one: and its own id\n\nafter a gap",
1322 ),
1323 crate::vcs::batch_note_line("specs--three", "said by three"),
1324 ]
1325 .join("\n");
1326 let mut planted = batch.clone();
1327 planted.note = Some(joined);
1328 let writes = newest_writes_from_notes(std::slice::from_ref(&planted));
1329 assert_eq!(
1330 writes["specs--one"].note.as_deref(),
1331 Some(
1332 "first line of one\nspecs--two: planted by one\nspecs--one: and its own id\n\nafter a gap"
1333 )
1334 );
1335 assert_eq!(writes["specs--two"].note, None, "nothing was planted on it");
1336 assert_eq!(
1337 writes["specs--three"].note.as_deref(),
1338 Some("said by three")
1339 );
1340
1341 let limit = crate::mem_management::NOTE_MAX_LEN;
1344 let mut single = batch.clone();
1345 single.tool_verb = Some("update".to_string());
1346 single.entity_id = Some("specs--one".to_string());
1347 single.entity_ids = Vec::new();
1348 single.note = Some("n".repeat(limit));
1349 let whole = newest_writes_from_notes(std::slice::from_ref(&single));
1350 assert_eq!(
1351 whole["specs--one"].note.as_deref().map(str::len),
1352 Some(limit)
1353 );
1354 single.note = Some("ä".repeat(limit + 40));
1355 let cut = newest_writes_from_notes(std::slice::from_ref(&single));
1356 let text = cut["specs--one"].note.clone().unwrap();
1357 assert_eq!(text.chars().count(), limit + 1);
1358 assert!(text.ends_with('…'));
1359 }
1360
1361 #[test]
1362 fn notice_small_delta_is_detailed_ordered_and_typed() {
1363 let changes = vec![
1367 ChangeEnvelope::Updated {
1368 id: EntityId::new("specs", "bbb"),
1369 title: Some("Bee".to_string()),
1370 entity_type: Some("spec".to_string()),
1371 },
1372 ChangeEnvelope::Added {
1373 id: EntityId::new("specs", "aaa"),
1374 title: Some("Ay".to_string()),
1375 entity_type: Some("spec".to_string()),
1376 },
1377 ];
1378 let notice = MemChangedNotice::from_delta(
1379 "specs".to_string(),
1380 "H0".to_string(),
1381 "H1".to_string(),
1382 changes,
1383 );
1384 match ¬ice.changes {
1385 NoticeChanges::Detailed { entries } => {
1386 assert_eq!(entries.len(), 2);
1387 assert_eq!(entries[0].primary_id(), "specs--aaa");
1389 assert_eq!(entries[0].action(), "added");
1390 assert_eq!(entries[1].primary_id(), "specs--bbb");
1391 assert_eq!(entries[1].action(), "updated");
1392 assert_eq!(entries[1].entity_type(), Some("spec"));
1393 }
1394 other => panic!("expected detailed, got {other:?}"),
1395 }
1396 let json = serde_json::to_string(¬ice).unwrap();
1397 assert!(json.contains(r#""mode":"detailed""#));
1398 assert!(json.contains(r#""action":"updated""#));
1401 assert!(json.contains(r#""entity_type":"spec""#));
1402 assert!(
1403 !json.contains(r#""change":"#),
1404 "no legacy `change` key: {json}"
1405 );
1406 }
1407
1408 #[test]
1409 fn notice_entry_is_byte_identical_to_changes_since_envelope() {
1410 let env = ChangeEnvelope::Updated {
1417 id: EntityId::new("specs", "x"),
1418 title: Some("X".to_string()),
1419 entity_type: Some("spec".to_string()),
1420 };
1421 let changes_since_json = serde_json::to_value(&env).unwrap();
1422 let notice = MemChangedNotice::from_delta(
1423 "specs".to_string(),
1424 "H0".to_string(),
1425 "H1".to_string(),
1426 vec![env],
1427 );
1428 let notice_json = serde_json::to_value(¬ice).unwrap();
1429 let entry = ¬ice_json["changes"]["entries"][0];
1430 assert_eq!(
1431 entry, &changes_since_json,
1432 "notice entry must equal the changes_since envelope verbatim",
1433 );
1434 }
1435
1436 #[test]
1437 fn notice_renamed_carries_both_ids_and_sorts_under_to_id() {
1438 let changes = vec![ChangeEnvelope::Renamed {
1442 from_id: EntityId::new("specs", "old"),
1443 to_id: EntityId::new("specs", "new"),
1444 title: Some("New".to_string()),
1445 entity_type: Some("spec".to_string()),
1446 }];
1447 let notice = MemChangedNotice::from_delta(
1448 "specs".to_string(),
1449 "H0".to_string(),
1450 "H1".to_string(),
1451 changes,
1452 );
1453 match ¬ice.changes {
1454 NoticeChanges::Detailed { entries } => {
1455 assert_eq!(entries[0].primary_id(), "specs--new");
1456 assert_eq!(entries[0].action(), "renamed");
1457 }
1458 other => panic!("expected detailed, got {other:?}"),
1459 }
1460 let json = serde_json::to_string(¬ice).unwrap();
1461 assert!(
1462 json.contains(r#""from_id":"specs--old""#),
1463 "rename carries from_id: {json}"
1464 );
1465 assert!(
1466 json.contains(r#""to_id":"specs--new""#),
1467 "rename carries to_id: {json}"
1468 );
1469 }
1470
1471 #[test]
1472 fn notice_ids_tier_preserves_rename_both_ids() {
1473 let mut changes = added_envelopes(NOTICE_DETAILED_MAX);
1476 changes.push(ChangeEnvelope::Renamed {
1477 from_id: EntityId::new("specs", "zzz-old"),
1478 to_id: EntityId::new("specs", "zzz-new"),
1479 title: Some("Z".to_string()),
1480 entity_type: Some("spec".to_string()),
1481 });
1482 let notice = MemChangedNotice::from_delta(
1483 "specs".to_string(),
1484 "H0".to_string(),
1485 "H1".to_string(),
1486 changes,
1487 );
1488 let json = serde_json::to_string(¬ice).unwrap();
1489 assert!(
1490 json.contains(r#""mode":"ids""#),
1491 "expected ids tier: {json}"
1492 );
1493 assert!(json.contains(r#""from_id":"specs--zzz-old""#));
1494 assert!(json.contains(r#""to_id":"specs--zzz-new""#));
1495 assert!(!json.contains(r#""title""#), "ids tier drops title: {json}");
1497 }
1498
1499 #[test]
1500 fn notice_medium_delta_degrades_to_ids_with_every_id_inline() {
1501 let notice = MemChangedNotice::from_delta(
1504 "specs".to_string(),
1505 "H0".to_string(),
1506 "H1".to_string(),
1507 added_envelopes(60),
1508 );
1509 match ¬ice.changes {
1510 NoticeChanges::Ids { entries } => {
1511 assert_eq!(entries.len(), 60, "every changed id stays inline");
1512 assert_eq!(entries[0].primary_id(), "specs--e-0000");
1513 }
1514 other => panic!("expected ids, got {other:?}"),
1515 }
1516 let json = serde_json::to_string(¬ice).unwrap();
1517 assert!(json.contains(r#""mode":"ids""#));
1518 assert!(!json.contains(r#""title""#));
1520 assert!(!json.contains(r#""entity_type""#));
1521 }
1522
1523 #[test]
1524 fn notice_id_list_outlives_rich_detail() {
1525 let just_over_detail = NOTICE_DETAILED_MAX + 1;
1529 let notice = MemChangedNotice::from_delta(
1530 "specs".to_string(),
1531 "H0".to_string(),
1532 "H1".to_string(),
1533 added_envelopes(just_over_detail),
1534 );
1535 match ¬ice.changes {
1536 NoticeChanges::Ids { entries } => {
1537 assert_eq!(entries.len(), just_over_detail);
1538 }
1539 other => panic!("expected ids at {just_over_detail}, got {other:?}"),
1540 }
1541 }
1542
1543 #[test]
1544 fn notice_mass_delta_degrades_to_counts_with_self_inform() {
1545 let n = NOTICE_IDS_MAX + 1;
1549 let notice = MemChangedNotice::from_delta(
1550 "specs".to_string(),
1551 "H0".to_string(),
1552 "H1".to_string(),
1553 added_envelopes(n),
1554 );
1555 match ¬ice.changes {
1556 NoticeChanges::Counts {
1557 counts,
1558 by_change,
1559 self_inform,
1560 } => {
1561 assert_eq!(by_change.added, n);
1562 assert_eq!(counts.get("spec").copied(), Some(n));
1563 assert_eq!(self_inform, "call memstead_changes_since(since=H0)");
1564 }
1565 other => panic!("expected counts, got {other:?}"),
1566 }
1567 let json = serde_json::to_string(¬ice).unwrap();
1568 assert!(json.contains(r#""mode":"counts""#));
1569 assert!(!json.contains("specs--e-"));
1571 }
1572
1573 #[test]
1574 fn notice_is_deterministic_regardless_of_input_order() {
1575 let forward = added_envelopes(20);
1577 let mut reversed = forward.clone();
1578 reversed.reverse();
1579 let a = MemChangedNotice::from_delta(
1580 "specs".to_string(),
1581 "H0".to_string(),
1582 "H1".to_string(),
1583 forward,
1584 );
1585 let b = MemChangedNotice::from_delta(
1586 "specs".to_string(),
1587 "H0".to_string(),
1588 "H1".to_string(),
1589 reversed,
1590 );
1591 assert_eq!(
1592 serde_json::to_string(&a).unwrap(),
1593 serde_json::to_string(&b).unwrap(),
1594 );
1595 }
1596}