use std::path::Path;
use serde::Serialize;
use crate::backend::BackendError;
use crate::entity::EntityId;
use crate::provenance::ProvenanceKind;
pub const EMPTY_TREE_SHA: &str = "4b825dc642cb6eb9a060e54bf8d69288fbee4904";
pub const RENAME_SIMILARITY_DEFAULT: f32 = 0.6;
pub const RENAME_SIMILARITY_MIN: f32 = 0.1;
pub const RENAME_SIMILARITY_MAX: f32 = 1.0;
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
#[serde(tag = "action", rename_all = "lowercase")]
pub enum ChangeEnvelope {
Added {
id: EntityId,
#[serde(skip_serializing_if = "Option::is_none")]
title: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
entity_type: Option<String>,
},
Updated {
id: EntityId,
#[serde(skip_serializing_if = "Option::is_none")]
title: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
entity_type: Option<String>,
},
Removed {
id: EntityId,
#[serde(skip_serializing_if = "Option::is_none")]
title: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
entity_type: Option<String>,
},
Renamed {
from_id: EntityId,
to_id: EntityId,
#[serde(skip_serializing_if = "Option::is_none")]
title: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
entity_type: Option<String>,
},
}
impl ChangeEnvelope {
pub fn primary_id(&self) -> &str {
match self {
ChangeEnvelope::Added { id, .. }
| ChangeEnvelope::Updated { id, .. }
| ChangeEnvelope::Removed { id, .. } => id.as_ref(),
ChangeEnvelope::Renamed { to_id, .. } => to_id.as_ref(),
}
}
pub fn action(&self) -> &'static str {
match self {
ChangeEnvelope::Added { .. } => "added",
ChangeEnvelope::Updated { .. } => "updated",
ChangeEnvelope::Removed { .. } => "removed",
ChangeEnvelope::Renamed { .. } => "renamed",
}
}
pub fn entity_type(&self) -> Option<&str> {
match self {
ChangeEnvelope::Added { entity_type, .. }
| ChangeEnvelope::Updated { entity_type, .. }
| ChangeEnvelope::Removed { entity_type, .. }
| ChangeEnvelope::Renamed { entity_type, .. } => entity_type.as_deref(),
}
}
fn without_metadata(&self) -> Self {
match self {
ChangeEnvelope::Added { id, .. } => ChangeEnvelope::Added {
id: id.clone(),
title: None,
entity_type: None,
},
ChangeEnvelope::Updated { id, .. } => ChangeEnvelope::Updated {
id: id.clone(),
title: None,
entity_type: None,
},
ChangeEnvelope::Removed { id, .. } => ChangeEnvelope::Removed {
id: id.clone(),
title: None,
entity_type: None,
},
ChangeEnvelope::Renamed { from_id, to_id, .. } => ChangeEnvelope::Renamed {
from_id: from_id.clone(),
to_id: to_id.clone(),
title: None,
entity_type: None,
},
}
}
}
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
pub struct BackendChanges {
pub since: String,
pub head: String,
pub changes: Vec<ChangeEnvelope>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub notes: Vec<crate::ops::agent_notes::CommitNote>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub memstead_ref: Option<String>,
}
impl BackendChanges {
pub fn empty_at(since: &str) -> Self {
Self {
since: since.to_string(),
head: since.to_string(),
changes: Vec::new(),
notes: Vec::new(),
memstead_ref: None,
}
}
}
pub type StoreLookup<'a> = &'a dyn Fn(&EntityId) -> Option<String>;
pub fn folder_changes_since(
mem_root: &Path,
mem: &str,
since: &str,
store: Option<StoreLookup<'_>>,
) -> Result<BackendChanges, BackendError> {
folder_changes(mem_root, mem, since, store, None)
}
pub fn folder_changes_since_within(
mem_root: &Path,
mem: &str,
since: &str,
store: Option<StoreLookup<'_>>,
lock_wait: Option<std::time::Duration>,
) -> Result<BackendChanges, BackendError> {
folder_changes(mem_root, mem, since, store, Some(lock_wait))
}
fn folder_changes(
mem_root: &Path,
mem: &str,
since: &str,
store: Option<StoreLookup<'_>>,
lock_wait: Option<Option<std::time::Duration>>,
) -> Result<BackendChanges, BackendError> {
if !since.is_empty()
&& since != EMPTY_TREE_SHA
&& crate::filesystem::changelog::parse_rfc3339_utc(since).is_none()
{
return Err(BackendError::Other(format!("INVALID_TS_CURSOR:{since}")));
}
match lock_wait {
Some(limit) => crate::storage::filesystem::refuse_cut_off_commit_within(mem_root, limit)?,
None => crate::storage::filesystem::refuse_cut_off_commit(mem_root)?,
}
let log_path = crate::filesystem::changelog::changelog_path(mem_root);
let raw = match std::fs::read_to_string(&log_path) {
Ok(s) => s,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
return Ok(BackendChanges::empty_at(since));
}
Err(e) => return Err(BackendError::Io(e)),
};
struct Aggregate {
first_kind: ProvenanceKind,
last_kind: ProvenanceKind,
}
#[derive(Default)]
struct Lifetime {
created_at: Option<String>,
last_at: String,
deleted: bool,
named_by_rename: bool,
}
let mut by_entity: std::collections::BTreeMap<String, Aggregate> =
std::collections::BTreeMap::new();
let mut lifetimes: std::collections::BTreeMap<String, Lifetime> =
std::collections::BTreeMap::new();
let mut rename_rows: Vec<(String, String)> = Vec::new();
let mut max_ts: Option<String> = None;
let cursor_opt: Option<&str> = if since.is_empty() || since == EMPTY_TREE_SHA {
None
} else {
Some(since)
};
for line in raw.lines() {
let trimmed = line.trim();
if trimmed.is_empty() {
continue;
}
let value: serde_json::Value = match serde_json::from_str(trimmed) {
Ok(v) => v,
Err(_) => continue,
};
let ts_str = value.get("ts").and_then(|v| v.as_str()).unwrap_or("");
let kind = match value
.get("kind")
.and_then(|v| v.as_str())
.and_then(ProvenanceKind::parse)
{
Some(k) => k,
None => continue,
};
let entity_id = match value.get("entity").and_then(|v| v.as_str()) {
Some(s) if !s.is_empty() => s.to_string(),
_ => continue,
};
{
let life = lifetimes.entry(entity_id.clone()).or_default();
if matches!(kind, ProvenanceKind::Create) {
life.created_at = Some(ts_str.to_string());
life.deleted = false;
}
if ts_str >= life.last_at.as_str() {
life.last_at = ts_str.to_string();
life.named_by_rename = matches!(kind, ProvenanceKind::Rename);
}
if matches!(kind, ProvenanceKind::Delete) {
life.deleted = true;
}
}
if let Some(c) = cursor_opt
&& ts_str <= c
{
continue;
}
if matches!(kind, ProvenanceKind::Rename) {
rename_rows.push((ts_str.to_string(), entity_id.clone()));
}
if max_ts.as_deref().is_none_or(|m| ts_str > m) {
max_ts = Some(ts_str.to_string());
}
by_entity
.entry(entity_id)
.and_modify(|agg| {
agg.last_kind = kind;
})
.or_insert(Aggregate {
first_kind: kind,
last_kind: kind,
});
}
let mut links: Vec<(String, String)> = Vec::new(); if let Some(lookup) = store {
let parse = |s: &str| match s.split_once("--") {
Some((v, slug)) if v == mem => Some(EntityId::new(v, slug)),
_ => None,
};
let exists = |name: &str| parse(name).and_then(|id| lookup(&id));
let mut taken: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
rename_rows.sort();
for (rename_ts, new_name) in &rename_rows {
let vanished: Vec<(&String, &Lifetime)> = lifetimes
.iter()
.filter(|(name, life)| {
*name != new_name
&& !life.deleted
&& !taken.contains(*name)
&& life.last_at.as_str() < rename_ts.as_str()
&& parse(name).is_some()
&& exists(name).is_none()
})
.collect();
let same_instant: Vec<&String> = match exists(new_name) {
Some(created_date) => vanished
.iter()
.filter(|(_, life)| {
life.created_at
.as_deref()
.is_some_and(|c| same_instant(c, &created_date))
})
.map(|(name, _)| *name)
.collect(),
None => Vec::new(),
};
let nearest: Option<String> = vanished
.iter()
.max_by(|a, b| a.1.last_at.cmp(&b.1.last_at))
.map(|(name, _)| (*name).clone());
let continues_chain = nearest
.as_deref()
.is_some_and(|n| lifetimes.get(n).is_some_and(|l| l.named_by_rename));
let from = if continues_chain {
nearest
} else {
match same_instant.as_slice() {
[one] => Some((*one).clone()),
_ => nearest,
}
};
if let Some(from) = from {
taken.insert(from.clone());
links.push((from, new_name.clone()));
}
}
}
let mut paired: Vec<(String, String, Vec<String>)> = Vec::new(); for (from, _) in &links {
if links.iter().any(|(_, to)| to == from) {
continue;
}
let mut members = vec![from.clone()];
let mut current = from.clone();
while let Some((_, to)) = links.iter().find(|(f, _)| *f == current) {
members.push(to.clone());
current = to.clone();
}
paired.push((from.clone(), current, members));
}
let mut changes: Vec<ChangeEnvelope> = Vec::with_capacity(by_entity.len());
for (from, to, members) in &paired {
let from_agg = by_entity.remove(from);
for member in members {
by_entity.remove(member);
}
let (Some(from_id), Some(to_id)) = (
from.split_once("--").map(|(v, s)| EntityId::new(v, s)),
to.split_once("--").map(|(v, s)| EntityId::new(v, s)),
) else {
continue;
};
let born_in_window =
from_agg.is_some_and(|a| matches!(a.first_kind, ProvenanceKind::Create));
changes.push(if born_in_window {
ChangeEnvelope::Added {
id: to_id,
title: None,
entity_type: None,
}
} else {
ChangeEnvelope::Renamed {
from_id,
to_id,
title: None,
entity_type: None,
}
});
}
for (entity_str, agg) in by_entity {
let id = match entity_str.split_once("--") {
Some((v, slug)) if v == mem => EntityId::new(v, slug),
_ => continue,
};
if let Some(lookup) = store
&& !matches!(agg.last_kind, ProvenanceKind::Delete)
&& lookup(&id).is_none()
{
changes.push(ChangeEnvelope::Removed {
id,
title: None,
entity_type: None,
});
continue;
}
let envelope = match (agg.first_kind, agg.last_kind) {
(_, ProvenanceKind::Delete) => ChangeEnvelope::Removed {
id,
title: None,
entity_type: None,
},
(ProvenanceKind::Create, _) => ChangeEnvelope::Added {
id,
title: None,
entity_type: None,
},
_ => ChangeEnvelope::Updated {
id,
title: None,
entity_type: None,
},
};
changes.push(envelope);
}
changes.sort_by(|a, b| a.primary_id().cmp(b.primary_id()));
Ok(BackendChanges {
since: since.to_string(),
head: max_ts.unwrap_or_else(|| since.to_string()),
changes,
notes: Vec::new(),
memstead_ref: None,
})
}
pub fn newest_writes_from_notes(
notes: &[crate::ops::agent_notes::CommitNote],
) -> std::collections::BTreeMap<String, NewestWrite> {
let mut writes = std::collections::BTreeMap::new();
for note in notes {
let subject_ids = note
.entity_id
.iter()
.flat_map(|subject| subject.split(" → "))
.filter(|part| part.contains("--") && !part.contains(' '))
.map(str::to_string);
let named: Vec<String> = subject_ids
.chain(note.entity_ids.iter().cloned())
.chain(note.created_ids.iter().cloned())
.collect();
let batch = note
.tool_verb
.as_deref()
.is_some_and(|verb| verb.starts_with("batch"));
for id in &named {
if writes.contains_key(id) {
continue;
}
let text = match (¬e.note, batch) {
(Some(joined), true) => batch_entry_note(joined, id, &named),
(text, _) => text.clone(),
};
writes.insert(
id.clone(),
NewestWrite {
identity: note.identity.clone(),
note: text.map(bounded_note),
},
);
}
}
writes
}
fn batch_entry_note(joined: &str, id: &str, ids: &[String]) -> Option<String> {
let mut mine: Vec<&str> = Vec::new();
let mut owner: Option<&str> = None;
for line in joined.lines() {
if let (Some(current), Some(rest)) = (owner, line.strip_prefix(" ")) {
if current == id {
mine.push(rest);
}
continue;
}
let begins = ids.iter().find_map(|candidate| {
line.strip_prefix(candidate.as_str())
.and_then(|rest| rest.strip_prefix(": "))
.map(|rest| (candidate.as_str(), rest))
});
match begins {
Some((candidate, rest)) => {
owner = Some(candidate);
if candidate == id {
mine.push(rest);
}
}
None if owner == Some(id) => mine.push(line),
None => {}
}
}
(!mine.is_empty()).then(|| mine.join("\n"))
}
fn bounded_note(note: String) -> String {
let max = crate::mem_management::NOTE_MAX_LEN;
if note.chars().count() <= max {
return note;
}
let mut cut: String = note.chars().take(max).collect();
cut.push('…');
cut
}
pub fn folder_newest_writes(
mem_root: &Path,
since: &str,
) -> std::collections::BTreeMap<String, NewestWrite> {
let mut writes = std::collections::BTreeMap::new();
let log_path = crate::filesystem::changelog::changelog_path(mem_root);
let Ok(raw) = std::fs::read_to_string(&log_path) else {
return writes;
};
let cursor = (!since.is_empty() && since != EMPTY_TREE_SHA).then_some(since);
let mut newest_at: std::collections::BTreeMap<String, String> =
std::collections::BTreeMap::new();
for line in raw.lines() {
let Ok(value) = serde_json::from_str::<serde_json::Value>(line.trim()) else {
continue;
};
let ts = value.get("ts").and_then(|v| v.as_str()).unwrap_or("");
if cursor.is_some_and(|c| ts <= c) {
continue;
}
let Some(entity) = value
.get("entity")
.and_then(|v| v.as_str())
.filter(|s| !s.is_empty())
else {
continue;
};
if newest_at.get(entity).is_some_and(|at| ts < at.as_str()) {
continue;
}
newest_at.insert(entity.to_string(), ts.to_string());
let text = |key: &str| {
value
.get(key)
.and_then(|v| v.as_str())
.filter(|s| !s.is_empty())
.map(str::to_string)
};
writes.insert(
entity.to_string(),
NewestWrite {
identity: text("identity"),
note: text("note").map(bounded_note),
},
);
}
writes
}
fn same_instant(ledger_ts: &str, created_date: &str) -> bool {
let norm = |s: &str| s.trim_end_matches('Z').replace('T', " ");
let a = norm(ledger_ts);
let b = norm(created_date);
let n = a.len().min(b.len());
n >= 10 && a[..n] == b[..n]
}
#[derive(Debug, Clone, Serialize)]
pub struct ChangesReport {
pub mem: String,
pub since: String,
pub head: String,
pub changes: Vec<ChangeEnvelope>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub warnings: Vec<crate::ops::WarningHint>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub notes: Option<Vec<crate::ops::agent_notes::CommitNote>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub memstead_ref: Option<String>,
}
pub(crate) const NOTICE_DETAILED_MAX: usize = 50;
const NOTICE_IDS_MAX: usize = 500;
#[derive(Debug, Clone, Serialize, PartialEq, Eq, Default)]
pub struct NoticeByChange {
pub added: usize,
pub updated: usize,
pub removed: usize,
pub renamed: usize,
}
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
#[serde(tag = "mode", rename_all = "lowercase")]
pub enum NoticeChanges {
Detailed { entries: Vec<NoticeEntry> },
Ids { entries: Vec<ChangeEnvelope> },
Counts {
counts: std::collections::BTreeMap<String, usize>,
by_change: NoticeByChange,
self_inform: String,
},
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct NewestWrite {
pub identity: Option<String>,
pub note: Option<String>,
}
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
pub struct NoticeEntry {
#[serde(flatten)]
pub change: ChangeEnvelope,
#[serde(skip_serializing_if = "Option::is_none")]
pub identity: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub note: Option<String>,
}
impl std::ops::Deref for NoticeEntry {
type Target = ChangeEnvelope;
fn deref(&self) -> &ChangeEnvelope {
&self.change
}
}
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
pub struct MemChangedNotice {
pub mem: String,
pub from_head: String,
pub to_head: String,
pub changes: NoticeChanges,
}
impl MemChangedNotice {
pub fn from_delta(
mem: String,
from_head: String,
to_head: String,
changes: Vec<ChangeEnvelope>,
) -> Self {
Self::from_delta_with_writes(
mem,
from_head,
to_head,
changes,
&std::collections::BTreeMap::new(),
)
}
pub fn from_delta_with_writes(
mem: String,
from_head: String,
to_head: String,
mut changes: Vec<ChangeEnvelope>,
writes: &std::collections::BTreeMap<String, NewestWrite>,
) -> Self {
changes.sort_by(|a, b| a.primary_id().cmp(b.primary_id()));
let n = changes.len();
let body = if n <= NOTICE_DETAILED_MAX {
NoticeChanges::Detailed {
entries: changes
.into_iter()
.map(|change| {
let write = writes.get(change.primary_id()).or_else(|| match &change {
ChangeEnvelope::Renamed { from_id, .. } => {
writes.get(AsRef::<str>::as_ref(from_id))
}
_ => None,
});
NoticeEntry {
identity: write.and_then(|w| w.identity.clone()),
note: write.and_then(|w| w.note.clone()),
change,
}
})
.collect(),
}
} else if n <= NOTICE_IDS_MAX {
NoticeChanges::Ids {
entries: changes
.iter()
.map(ChangeEnvelope::without_metadata)
.collect(),
}
} else {
let mut counts: std::collections::BTreeMap<String, usize> =
std::collections::BTreeMap::new();
let mut by_change = NoticeByChange::default();
for env in &changes {
match env {
ChangeEnvelope::Added { .. } => by_change.added += 1,
ChangeEnvelope::Updated { .. } => by_change.updated += 1,
ChangeEnvelope::Removed { .. } => by_change.removed += 1,
ChangeEnvelope::Renamed { .. } => by_change.renamed += 1,
}
if let Some(t) = env.entity_type() {
*counts.entry(t.to_string()).or_default() += 1;
}
}
NoticeChanges::Counts {
counts,
by_change,
self_inform: format!("call memstead_changes_since(since={from_head})"),
}
};
Self {
mem,
from_head,
to_head,
changes: body,
}
}
pub fn entity_count(&self) -> usize {
match &self.changes {
NoticeChanges::Detailed { entries } => entries.len(),
NoticeChanges::Ids { entries } => entries.len(),
NoticeChanges::Counts { by_change, .. } => {
by_change.added + by_change.updated + by_change.removed + by_change.renamed
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn empty_at_echoes_cursor() {
let r = BackendChanges::empty_at("abc");
assert_eq!(r.since, "abc");
assert_eq!(r.head, "abc");
assert!(r.changes.is_empty());
}
#[test]
fn changes_report_omits_notes_and_memstead_ref_when_none() {
let r = ChangesReport {
mem: "specs".to_string(),
since: "abc".to_string(),
head: "def".to_string(),
changes: Vec::new(),
warnings: Vec::new(),
notes: None,
memstead_ref: None,
};
let json = serde_json::to_string(&r).unwrap();
assert!(
!json.contains("\"notes\""),
"notes must be omitted when None: {json}"
);
assert!(
!json.contains("\"memstead_ref\""),
"memstead_ref must be omitted when None: {json}"
);
}
#[test]
fn changes_report_emits_notes_and_memstead_ref_when_some() {
let r = ChangesReport {
mem: "specs".to_string(),
since: "abc".to_string(),
head: "def".to_string(),
changes: Vec::new(),
warnings: Vec::new(),
notes: Some(Vec::new()),
memstead_ref: Some("aabbccdd".to_string()),
};
let json = serde_json::to_string(&r).unwrap();
assert!(
json.contains("\"notes\":["),
"notes must be present: {json}"
);
assert!(
json.contains("\"memstead_ref\":\"aabbccdd\""),
"memstead_ref must be present and carry the SHA: {json}"
);
}
#[test]
fn change_envelope_serializes_action_tag() {
let env = ChangeEnvelope::Added {
id: EntityId::new("specs", "hello"),
title: Some("Hello".to_string()),
entity_type: Some("spec".to_string()),
};
let json = serde_json::to_string(&env).unwrap();
assert!(json.contains(r#""action":"added""#));
assert!(json.contains(r#""title":"Hello""#));
assert!(json.contains(r#""entity_type":"spec""#));
}
#[test]
fn change_envelope_skips_none_metadata_fields() {
let env = ChangeEnvelope::Removed {
id: EntityId::new("specs", "gone"),
title: None,
entity_type: None,
};
let json = serde_json::to_string(&env).unwrap();
assert!(json.contains(r#""action":"removed""#));
assert!(!json.contains("\"title\""));
assert!(!json.contains("\"entity_type\""));
}
#[test]
fn change_envelope_renamed_carries_both_ids() {
let env = ChangeEnvelope::Renamed {
from_id: EntityId::new("specs", "old"),
to_id: EntityId::new("specs", "new"),
title: Some("New".to_string()),
entity_type: Some("spec".to_string()),
};
let json = serde_json::to_string(&env).unwrap();
assert!(json.contains(r#""action":"renamed""#));
assert!(json.contains(r#""from_id":"specs--old""#));
assert!(json.contains(r#""to_id":"specs--new""#));
}
fn added_envelopes(n: usize) -> Vec<ChangeEnvelope> {
(0..n)
.map(|i| ChangeEnvelope::Added {
id: EntityId::new("specs", &format!("e-{i:04}")),
title: Some(format!("Entity {i}")),
entity_type: Some("spec".to_string()),
})
.collect()
}
#[test]
fn a_detailed_entry_names_the_newest_write_and_drops_what_was_not_declared() {
let changes = vec![
ChangeEnvelope::Updated {
id: EntityId::new("specs", "bbb"),
title: Some("B".to_string()),
entity_type: Some("spec".to_string()),
},
ChangeEnvelope::Added {
id: EntityId::new("specs", "aaa"),
title: Some("A".to_string()),
entity_type: Some("spec".to_string()),
},
ChangeEnvelope::Renamed {
from_id: EntityId::new("specs", "old"),
to_id: EntityId::new("specs", "new"),
title: None,
entity_type: None,
},
ChangeEnvelope::Removed {
id: EntityId::new("specs", "zzz"),
title: None,
entity_type: None,
},
];
let write = |identity: Option<&str>, note: Option<&str>| NewestWrite {
identity: identity.map(str::to_string),
note: note.map(str::to_string),
};
let writes: std::collections::BTreeMap<String, NewestWrite> = [
(
"specs--aaa".to_string(),
write(Some("xavier"), Some("made it")),
),
("specs--bbb".to_string(), write(None, Some("no name"))),
("specs--old".to_string(), write(Some("yolanda"), None)),
]
.into_iter()
.collect();
let notice = MemChangedNotice::from_delta_with_writes(
"specs".to_string(),
"H0".to_string(),
"H1".to_string(),
changes.clone(),
&writes,
);
let value = serde_json::to_value(¬ice).unwrap();
let entries = value["changes"]["entries"].as_array().unwrap();
assert_eq!(entries.len(), 4);
assert_eq!(entries[0]["id"], "specs--aaa");
assert_eq!(entries[0]["action"], "added");
assert_eq!(entries[0]["identity"], "xavier");
assert_eq!(entries[0]["note"], "made it");
assert_eq!(entries[1]["id"], "specs--bbb");
assert_eq!(entries[1]["note"], "no name");
assert!(entries[1].get("identity").is_none(), "{}", entries[1]);
assert_eq!(entries[2]["to_id"], "specs--new");
assert_eq!(entries[2]["identity"], "yolanda");
assert!(entries[2].get("note").is_none(), "{}", entries[2]);
assert_eq!(entries[3]["id"], "specs--zzz");
assert!(entries[3].get("identity").is_none() && entries[3].get("note").is_none());
let mut reversed = changes;
reversed.reverse();
let again = MemChangedNotice::from_delta_with_writes(
"specs".to_string(),
"H0".to_string(),
"H1".to_string(),
reversed,
&writes,
);
assert_eq!(
serde_json::to_string(¬ice).unwrap(),
serde_json::to_string(&again).unwrap()
);
let many = added_envelopes(NOTICE_DETAILED_MAX + 1);
let all: std::collections::BTreeMap<String, NewestWrite> = many
.iter()
.map(|e| (e.primary_id().to_string(), write(Some("xavier"), Some("n"))))
.collect();
let ids = MemChangedNotice::from_delta_with_writes(
"specs".to_string(),
"H0".to_string(),
"H1".to_string(),
many,
&all,
);
let json = serde_json::to_string(&ids).unwrap();
assert!(json.contains(r#""mode":"ids""#));
assert!(
!json.contains("identity") && !json.contains("\"note\""),
"{json}"
);
}
#[test]
fn the_newest_note_that_names_an_id_decides_its_write() {
let note = |subject_id: &str, ids: &[&str], identity: Option<&str>, text: Option<&str>| {
crate::ops::agent_notes::CommitNote {
mem: "specs".to_string(),
sha: "0".repeat(40),
subject: format!("memstead: write {subject_id}"),
tool_verb: None,
entity_id: Some(subject_id.to_string()),
note: text.map(str::to_string),
actor: None,
tool: None,
client: None,
logical_operation_id: None,
role: None,
identity: identity.map(str::to_string),
entity_ids: ids.iter().map(|s| s.to_string()).collect(),
merged_by: None,
proposal: None,
created_ids: Vec::new(),
co_writers: Vec::new(),
unattributed_writes: Vec::new(),
merge_renames: Vec::new(),
timestamp: 0,
}
};
let notes = vec![
note(
"specs--bee → specs--bumble",
&["specs--aye"],
Some("yolanda"),
None,
),
note("specs--aye", &[], Some("xavier"), Some("older")),
note("specs--other", &[], None, Some("only a note")),
];
let writes = newest_writes_from_notes(¬es);
for id in ["specs--bee", "specs--bumble", "specs--aye"] {
assert_eq!(writes[id].identity.as_deref(), Some("yolanda"), "{id}");
assert_eq!(writes[id].note, None, "{id}: never the older write's note");
}
assert_eq!(writes["specs--other"].identity, None);
assert_eq!(writes["specs--other"].note.as_deref(), Some("only a note"));
}
#[test]
fn a_batch_gives_each_entity_its_own_note_and_a_note_has_a_bound() {
let batch = crate::ops::agent_notes::CommitNote {
mem: "specs".to_string(),
sha: "0".repeat(40),
subject: "memstead: batch-update (3 entities)".to_string(),
tool_verb: Some("batch-update".to_string()),
entity_id: Some("(3 entities)".to_string()),
note: Some(
"specs--one: note for one\nand its second line\nspecs--three: Reason: three"
.to_string(),
),
actor: None,
tool: None,
client: None,
logical_operation_id: None,
role: None,
identity: Some("yolanda".to_string()),
entity_ids: vec![
"specs--one".to_string(),
"specs--two".to_string(),
"specs--three".to_string(),
],
merged_by: None,
proposal: None,
created_ids: Vec::new(),
co_writers: Vec::new(),
unattributed_writes: Vec::new(),
merge_renames: Vec::new(),
timestamp: 0,
};
let writes = newest_writes_from_notes(std::slice::from_ref(&batch));
assert_eq!(
writes["specs--one"].note.as_deref(),
Some("note for one\nand its second line")
);
assert_eq!(writes["specs--two"].note, None, "its entry declared none");
assert_eq!(
writes["specs--three"].note.as_deref(),
Some("Reason: three")
);
for id in ["specs--one", "specs--two", "specs--three"] {
assert_eq!(writes[id].identity.as_deref(), Some("yolanda"));
}
let joined = [
crate::vcs::batch_note_line(
"specs--one",
"first line of one\nspecs--two: planted by one\nspecs--one: and its own id\n\nafter a gap",
),
crate::vcs::batch_note_line("specs--three", "said by three"),
]
.join("\n");
let mut planted = batch.clone();
planted.note = Some(joined);
let writes = newest_writes_from_notes(std::slice::from_ref(&planted));
assert_eq!(
writes["specs--one"].note.as_deref(),
Some(
"first line of one\nspecs--two: planted by one\nspecs--one: and its own id\n\nafter a gap"
)
);
assert_eq!(writes["specs--two"].note, None, "nothing was planted on it");
assert_eq!(
writes["specs--three"].note.as_deref(),
Some("said by three")
);
let limit = crate::mem_management::NOTE_MAX_LEN;
let mut single = batch.clone();
single.tool_verb = Some("update".to_string());
single.entity_id = Some("specs--one".to_string());
single.entity_ids = Vec::new();
single.note = Some("n".repeat(limit));
let whole = newest_writes_from_notes(std::slice::from_ref(&single));
assert_eq!(
whole["specs--one"].note.as_deref().map(str::len),
Some(limit)
);
single.note = Some("ä".repeat(limit + 40));
let cut = newest_writes_from_notes(std::slice::from_ref(&single));
let text = cut["specs--one"].note.clone().unwrap();
assert_eq!(text.chars().count(), limit + 1);
assert!(text.ends_with('…'));
}
#[test]
fn notice_small_delta_is_detailed_ordered_and_typed() {
let changes = vec![
ChangeEnvelope::Updated {
id: EntityId::new("specs", "bbb"),
title: Some("Bee".to_string()),
entity_type: Some("spec".to_string()),
},
ChangeEnvelope::Added {
id: EntityId::new("specs", "aaa"),
title: Some("Ay".to_string()),
entity_type: Some("spec".to_string()),
},
];
let notice = MemChangedNotice::from_delta(
"specs".to_string(),
"H0".to_string(),
"H1".to_string(),
changes,
);
match ¬ice.changes {
NoticeChanges::Detailed { entries } => {
assert_eq!(entries.len(), 2);
assert_eq!(entries[0].primary_id(), "specs--aaa");
assert_eq!(entries[0].action(), "added");
assert_eq!(entries[1].primary_id(), "specs--bbb");
assert_eq!(entries[1].action(), "updated");
assert_eq!(entries[1].entity_type(), Some("spec"));
}
other => panic!("expected detailed, got {other:?}"),
}
let json = serde_json::to_string(¬ice).unwrap();
assert!(json.contains(r#""mode":"detailed""#));
assert!(json.contains(r#""action":"updated""#));
assert!(json.contains(r#""entity_type":"spec""#));
assert!(
!json.contains(r#""change":"#),
"no legacy `change` key: {json}"
);
}
#[test]
fn notice_entry_is_byte_identical_to_changes_since_envelope() {
let env = ChangeEnvelope::Updated {
id: EntityId::new("specs", "x"),
title: Some("X".to_string()),
entity_type: Some("spec".to_string()),
};
let changes_since_json = serde_json::to_value(&env).unwrap();
let notice = MemChangedNotice::from_delta(
"specs".to_string(),
"H0".to_string(),
"H1".to_string(),
vec![env],
);
let notice_json = serde_json::to_value(¬ice).unwrap();
let entry = ¬ice_json["changes"]["entries"][0];
assert_eq!(
entry, &changes_since_json,
"notice entry must equal the changes_since envelope verbatim",
);
}
#[test]
fn notice_renamed_carries_both_ids_and_sorts_under_to_id() {
let changes = vec![ChangeEnvelope::Renamed {
from_id: EntityId::new("specs", "old"),
to_id: EntityId::new("specs", "new"),
title: Some("New".to_string()),
entity_type: Some("spec".to_string()),
}];
let notice = MemChangedNotice::from_delta(
"specs".to_string(),
"H0".to_string(),
"H1".to_string(),
changes,
);
match ¬ice.changes {
NoticeChanges::Detailed { entries } => {
assert_eq!(entries[0].primary_id(), "specs--new");
assert_eq!(entries[0].action(), "renamed");
}
other => panic!("expected detailed, got {other:?}"),
}
let json = serde_json::to_string(¬ice).unwrap();
assert!(
json.contains(r#""from_id":"specs--old""#),
"rename carries from_id: {json}"
);
assert!(
json.contains(r#""to_id":"specs--new""#),
"rename carries to_id: {json}"
);
}
#[test]
fn notice_ids_tier_preserves_rename_both_ids() {
let mut changes = added_envelopes(NOTICE_DETAILED_MAX);
changes.push(ChangeEnvelope::Renamed {
from_id: EntityId::new("specs", "zzz-old"),
to_id: EntityId::new("specs", "zzz-new"),
title: Some("Z".to_string()),
entity_type: Some("spec".to_string()),
});
let notice = MemChangedNotice::from_delta(
"specs".to_string(),
"H0".to_string(),
"H1".to_string(),
changes,
);
let json = serde_json::to_string(¬ice).unwrap();
assert!(
json.contains(r#""mode":"ids""#),
"expected ids tier: {json}"
);
assert!(json.contains(r#""from_id":"specs--zzz-old""#));
assert!(json.contains(r#""to_id":"specs--zzz-new""#));
assert!(!json.contains(r#""title""#), "ids tier drops title: {json}");
}
#[test]
fn notice_medium_delta_degrades_to_ids_with_every_id_inline() {
let notice = MemChangedNotice::from_delta(
"specs".to_string(),
"H0".to_string(),
"H1".to_string(),
added_envelopes(60),
);
match ¬ice.changes {
NoticeChanges::Ids { entries } => {
assert_eq!(entries.len(), 60, "every changed id stays inline");
assert_eq!(entries[0].primary_id(), "specs--e-0000");
}
other => panic!("expected ids, got {other:?}"),
}
let json = serde_json::to_string(¬ice).unwrap();
assert!(json.contains(r#""mode":"ids""#));
assert!(!json.contains(r#""title""#));
assert!(!json.contains(r#""entity_type""#));
}
#[test]
fn notice_id_list_outlives_rich_detail() {
let just_over_detail = NOTICE_DETAILED_MAX + 1;
let notice = MemChangedNotice::from_delta(
"specs".to_string(),
"H0".to_string(),
"H1".to_string(),
added_envelopes(just_over_detail),
);
match ¬ice.changes {
NoticeChanges::Ids { entries } => {
assert_eq!(entries.len(), just_over_detail);
}
other => panic!("expected ids at {just_over_detail}, got {other:?}"),
}
}
#[test]
fn notice_mass_delta_degrades_to_counts_with_self_inform() {
let n = NOTICE_IDS_MAX + 1;
let notice = MemChangedNotice::from_delta(
"specs".to_string(),
"H0".to_string(),
"H1".to_string(),
added_envelopes(n),
);
match ¬ice.changes {
NoticeChanges::Counts {
counts,
by_change,
self_inform,
} => {
assert_eq!(by_change.added, n);
assert_eq!(counts.get("spec").copied(), Some(n));
assert_eq!(self_inform, "call memstead_changes_since(since=H0)");
}
other => panic!("expected counts, got {other:?}"),
}
let json = serde_json::to_string(¬ice).unwrap();
assert!(json.contains(r#""mode":"counts""#));
assert!(!json.contains("specs--e-"));
}
#[test]
fn notice_is_deterministic_regardless_of_input_order() {
let forward = added_envelopes(20);
let mut reversed = forward.clone();
reversed.reverse();
let a = MemChangedNotice::from_delta(
"specs".to_string(),
"H0".to_string(),
"H1".to_string(),
forward,
);
let b = MemChangedNotice::from_delta(
"specs".to_string(),
"H0".to_string(),
"H1".to_string(),
reversed,
);
assert_eq!(
serde_json::to_string(&a).unwrap(),
serde_json::to_string(&b).unwrap(),
);
}
}