1use std::collections::HashSet;
36use std::path::{Path, PathBuf};
37use std::sync::Arc;
38use std::time::Duration;
39
40use crate::backend::fs_watch::{FsWatchEventKind, FsWatchPool};
41use crate::backend::storage::store::Store;
42use crate::backend::memory::native_files::list_all_memory_targets;
43
44const SWEEP_INTERVAL: Duration = Duration::from_secs(30);
51
52const MAX_MEMORY_FILE_BYTES: u64 = 10 * 1024 * 1024;
55
56pub type OwnedAgents = Arc<dyn Fn() -> HashSet<String> + Send + Sync>;
63
64pub fn owned_targets(mstore: &Store, owned: &OwnedAgents) -> Vec<(String, PathBuf)> {
67 let own = owned();
68 if own.is_empty() {
69 return Vec::new();
70 }
71 let mut targets = list_all_memory_targets(mstore);
72 targets.retain(|(agent_id, _)| own.contains(agent_id));
73 targets
74}
75
76#[derive(Default)]
78pub(crate) struct DeletionWatch {
79 seen: HashSet<(String, String)>,
83 reported: HashSet<(String, String)>,
85}
86
87pub(crate) fn check_and_record_drift(
94 id_store: &Store,
95 agent_id: &str,
96 filename: &str,
97 live_content: &str,
98 detected_via: &str,
99) -> Result<bool, String> {
100 let detail = serde_json::json!({ "detected_via": detected_via }).to_string();
101 id_store
112 .agent_native_memory_version_insert_if_changed(agent_id, filename, live_content, "external_fs_write", &detail, "")
113 .map_err(|e| e.to_string())
114 .map(|v| v.is_some())
115}
116
117pub(crate) fn backfill_newly_verified(
138 id_store: &Store,
139 targets: &[(String, PathBuf)],
140 known: &mut HashSet<String>,
141) -> usize {
142 let new: Vec<(String, PathBuf)> = targets.iter().filter(|(id, _)| !known.contains(id)).cloned().collect();
143 for (id, _) in &new {
144 known.insert(id.clone());
145 }
146 backfill_first_sight_versions_for(id_store, &new)
147}
148
149fn backfill_first_sight_versions_for(id_store: &Store, targets: &[(String, PathBuf)]) -> usize {
150 let mut recorded = 0;
151 for (agent_id, dir) in targets {
152 let Ok(entries) = std::fs::read_dir(dir) else { continue };
153 for entry in entries.flatten() {
154 let filename = entry.file_name().to_string_lossy().into_owned();
155 if !filename.ends_with(".md") || !entry.path().is_file() {
156 continue;
157 }
158 match id_store.agent_native_memory_version_latest(agent_id, &filename) {
159 Ok(None) => {}
160 Ok(Some(_)) => continue,
161 Err(e) => {
162 tracing::warn!(agent_id, filename, error = %e, "native_memory: first-sight backfill: lookup failed");
163 continue;
164 }
165 }
166 let content = match read_memory_file_lossy(&entry.path()) {
167 Ok(c) => c,
168 Err(e) => {
169 tracing::warn!(agent_id, filename, error = %e, "native_memory: first-sight backfill: skipping unreadable file");
170 continue;
171 }
172 };
173 match id_store.agent_native_memory_version_insert_if_changed(agent_id, &filename, &content, "agent_inferred", "{}", "") {
174 Ok(Some(_)) => recorded += 1,
175 Ok(None) => {}
176 Err(e) => tracing::warn!(agent_id, filename, error = %e, "native_memory: first-sight backfill: insert failed"),
177 }
178 }
179 }
180 if recorded > 0 {
181 tracing::info!(recorded, "native_memory: first-sight backfill recorded versions");
182 }
183 recorded
184}
185
186pub(crate) fn read_memory_file_lossy(path: &Path) -> std::io::Result<String> {
199 use std::io::Read;
200 let mut buf = Vec::new();
201 let read = std::fs::File::open(path)?
202 .take(MAX_MEMORY_FILE_BYTES + 1)
203 .read_to_end(&mut buf)?;
204 if read as u64 > MAX_MEMORY_FILE_BYTES {
205 return Err(std::io::Error::new(
206 std::io::ErrorKind::InvalidData,
207 format!("file exceeds the {MAX_MEMORY_FILE_BYTES}-byte cap — refusing to record truncated content as authoritative"),
208 ));
209 }
210 Ok(String::from_utf8_lossy(&buf).into_owned())
211}
212
213pub(crate) fn reconciliation_sweep_once(
243 targets: &[(String, PathBuf)],
244 id_store: &Store,
245 broker: &crate::backend::mps::Broker,
246 watch: &mut DeletionWatch,
247) -> usize {
248 let mut drifted = 0;
249 for (agent_id, memory_dir) in targets {
250 drifted += sweep_one_agent_dir(id_store, agent_id, memory_dir, "reconciliation_sweep", broker);
251 }
252
253 let Ok(distinct) = id_store.agent_native_memory_version_list_distinct_files() else {
258 return drifted;
259 };
260 for (agent_id, filename) in distinct {
261 let Some((_, memory_dir)) = targets.iter().find(|(id, _)| *id == agent_id) else {
262 continue;
267 };
268 let key = (agent_id.clone(), filename.clone());
269 if memory_dir.join(&filename).is_file() {
270 watch.reported.remove(&key);
271 watch.seen.insert(key);
272 continue;
273 }
274 if !watch.seen.contains(&key) {
275 continue;
276 }
277 if watch.reported.insert(key) {
278 tracing::info!(agent_id = %agent_id, filename = %filename, "native_memory_drift: detected an out-of-band deletion");
279 broker.publish_event_for::<crate::backend::mps_events::AgentMemoryChanged>(&agent_id, &(), vec![], 0);
280 }
281 }
282 drifted
283}
284
285fn capture_into_record(agent_id: &str, memory_dir: &Path) {
290 use crate::backend::transcript::damage;
291 let zone = damage::memory_zone(agent_id);
293 let Some(fs) = damage::global_for(&zone) else { return };
294 match crate::backend::memory::reconcile::capture_while_running(&fs, agent_id, memory_dir, crate::backend::memory::reconcile::CAPTURE_SETTLE) {
295 Ok(0) => {}
296 Ok(n) => tracing::info!(agent_id, recorded = n, "native_memory_drift: recorded provider writes into the memory record"),
297 Err(e) => {
298 if !damage::note_corrupt(&zone, "memory capture", &e) {
299 tracing::warn!(agent_id, error = %e, "native_memory_drift: memory record capture failed; retried next sweep");
300 }
301 }
302 }
303}
304
305fn sweep_one_agent_dir(
306 id_store: &Store,
307 agent_id: &str,
308 memory_dir: &Path,
309 detected_via: &str,
310 broker: &crate::backend::mps::Broker,
311) -> usize {
312 capture_into_record(agent_id, memory_dir);
313 let entries = match std::fs::read_dir(memory_dir) {
314 Ok(e) => e,
315 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return 0,
316 Err(e) => {
317 tracing::warn!(agent_id, dir = %memory_dir.display(), error = %e, "native_memory_drift: sweep: read_dir failed");
318 return 0;
319 }
320 };
321
322 let mut drifted = 0;
323 for entry in entries.flatten() {
324 let name = entry.file_name().to_string_lossy().into_owned();
325 if !name.ends_with(".md") {
326 continue;
327 }
328 let Ok(file_type) = entry.file_type() else { continue };
329 if !file_type.is_file() {
330 continue;
331 }
332 let content = match read_memory_file_lossy(&entry.path()) {
333 Ok(c) => c,
334 Err(e) if e.kind() == std::io::ErrorKind::InvalidData => {
335 tracing::warn!(agent_id, filename = %name, error = %e, "native_memory_drift: sweep: file exceeds size cap, skipping (not recording truncated content)");
336 continue;
337 }
338 Err(e) => {
339 tracing::warn!(agent_id, filename = %name, error = %e, "native_memory_drift: sweep: read failed, retrying next sweep");
340 continue;
341 }
342 };
343 match check_and_record_drift(id_store, agent_id, &name, &content, detected_via) {
344 Ok(true) => {
345 drifted += 1;
346 tracing::info!(agent_id, filename = %name, detected_via, "native_memory_drift: recorded an out-of-band write");
347 broker.publish_event_for::<crate::backend::mps_events::AgentMemoryChanged>(&agent_id, &(), vec![], 0);
353 }
354 Ok(false) => {}
355 Err(e) => tracing::warn!(agent_id, filename = %name, error = %e, "native_memory_drift: check_and_record_drift failed"),
356 }
357 }
358 drifted
359}
360
361pub fn spawn(
367 fs_watch_pool: Arc<FsWatchPool>,
368 mstore: Arc<Store>,
369 id_store: Arc<Store>,
370 broker: Arc<crate::backend::mps::Broker>,
371 owned: OwnedAgents,
372) {
373 spawn_fast_path(fs_watch_pool, mstore.clone(), id_store.clone(), broker.clone(), owned.clone());
374 spawn_slow_path(mstore, id_store, broker, owned);
375}
376
377fn spawn_slow_path(mstore: Arc<Store>, id_store: Arc<Store>, broker: Arc<crate::backend::mps::Broker>, owned: OwnedAgents) {
378 tokio::spawn(async move {
379 let mut tick = tokio::time::interval(SWEEP_INTERVAL);
380 let mut watch = DeletionWatch::default();
384 let mut backfilled: HashSet<String> = HashSet::new();
386 loop {
387 tick.tick().await;
388 let targets = owned_targets(&mstore, &owned);
389 backfill_newly_verified(&id_store, &targets, &mut backfilled);
390 reconciliation_sweep_once(&targets, &id_store, &broker, &mut watch);
391 }
392 });
393}
394
395fn spawn_fast_path(
407 fs_watch_pool: Arc<FsWatchPool>,
408 mstore: Arc<Store>,
409 id_store: Arc<Store>,
410 broker: Arc<crate::backend::mps::Broker>,
411 owned: OwnedAgents,
412) {
413 tokio::spawn(async move {
414 let mut events = fs_watch_pool.events();
415 let mut watched_dirs: HashSet<PathBuf> = HashSet::new();
416 let mut dir_to_agent: std::collections::HashMap<PathBuf, String> = std::collections::HashMap::new();
417 let mut tick = tokio::time::interval(SWEEP_INTERVAL);
418
419 loop {
420 tokio::select! {
421 _ = tick.tick() => {
422 refresh_subscriptions(&fs_watch_pool, &owned_targets(&mstore, &owned), &id_store, &mut watched_dirs, &mut dir_to_agent);
423 }
424 event = events.recv() => {
425 let event = match event {
426 Ok(e) => e,
427 Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {
428 continue;
433 }
434 Err(tokio::sync::broadcast::error::RecvError::Closed) => break,
435 };
436 handle_fs_event(&event, &dir_to_agent, &owned, &id_store, &broker);
437 }
438 }
439 }
440 });
441}
442
443fn handle_fs_event(
448 event: &crate::backend::fs_watch::FsWatchEvent,
449 dir_to_agent: &std::collections::HashMap<PathBuf, String>,
450 owned: &OwnedAgents,
451 id_store: &Store,
452 broker: &crate::backend::mps::Broker,
453) {
454 if !matches!(event.kind, FsWatchEventKind::Created | FsWatchEventKind::Modified) {
455 return;
456 }
457 let Some(filename) = event.path.file_name().and_then(|n| n.to_str()) else { return };
458 if !filename.ends_with(".md") {
459 return;
460 }
461 let Some(parent) = event.path.parent() else { return };
462 let Some(agent_id) = dir_to_agent.get(parent).cloned() else { return };
463 if !owned().contains(&agent_id) {
464 return;
465 }
466
467 let content = match read_memory_file_lossy(&event.path) {
468 Ok(c) => c,
469 Err(e) if e.kind() == std::io::ErrorKind::InvalidData => {
470 tracing::warn!(agent_id, filename, error = %e, "native_memory_drift: fast path: file exceeds size cap, skipping (not recording truncated content)");
471 return;
472 }
473 Err(_) => return,
477 };
478 capture_into_record(&agent_id, parent);
485 match check_and_record_drift(id_store, &agent_id, filename, &content, "fs_watch") {
486 Ok(true) => {
487 tracing::info!(agent_id, filename, "native_memory_drift: fast path recorded an out-of-band write");
488 broker.publish_event_for::<crate::backend::mps_events::AgentMemoryChanged>(&agent_id, &(), vec![], 0);
490 }
491 Ok(false) => {}
492 Err(e) => tracing::warn!(agent_id, filename, error = %e, "native_memory_drift: fast path: check_and_record_drift failed"),
493 }
494}
495
496fn refresh_subscriptions(
497 fs_watch_pool: &Arc<FsWatchPool>,
498 targets: &[(String, PathBuf)],
499 id_store: &Store,
500 watched_dirs: &mut HashSet<PathBuf>,
501 dir_to_agent: &mut std::collections::HashMap<PathBuf, String>,
502) {
503 for (agent_id, memory_dir) in targets.iter().cloned() {
504 let canonical = memory_dir.canonicalize().unwrap_or_else(|_| memory_dir.clone());
509 if watched_dirs.insert(canonical.clone()) {
510 backfill_first_sight_versions_for(id_store, &[(agent_id.clone(), memory_dir.clone())]);
515 fs_watch_pool.subscribe_dir(&memory_dir);
516 dir_to_agent.insert(canonical, agent_id);
517 }
518 }
519}
520
521#[cfg(test)]
522mod tests {
523 use super::*;
524 use crate::backend::memory::native_files::memory_dir_for_agent_by_id;
525
526 fn shared_store() -> Store {
527 Store::open_shared(std::path::Path::new(":memory:")).unwrap()
528 }
529
530 #[test]
534 fn first_sight_backfill_records_once_and_the_sweep_then_sees_no_drift() {
535 let store = shared_store();
536 let dir = tempfile::tempdir().unwrap();
537 std::fs::write(dir.path().join("MEMORY.md"), "pre-existing").unwrap();
538 std::fs::write(dir.path().join("notes.txt"), "not memory").unwrap();
539 let targets = vec![("agent-1".to_string(), dir.path().to_path_buf())];
540 let mut known = HashSet::new();
541
542 assert_eq!(backfill_newly_verified(&store, &targets, &mut known), 1);
543 std::fs::write(dir.path().join("later.md"), "appeared later").unwrap();
546 assert_eq!(backfill_newly_verified(&store, &targets, &mut known), 0);
547 assert!(store.agent_native_memory_version_latest("agent-1", "later.md").unwrap().is_none());
548 let dir2 = tempfile::tempdir().unwrap();
550 std::fs::write(dir2.path().join("MEMORY.md"), "second agent").unwrap();
551 let more = vec![targets[0].clone(), ("agent-2".to_string(), dir2.path().to_path_buf())];
552 assert_eq!(backfill_newly_verified(&store, &more, &mut known), 1);
553
554 let root = tempfile::tempdir().unwrap();
558 let not_yet = root.path().join("memory");
559 let pending = vec![("agent-3".to_string(), not_yet.clone())];
560 assert_eq!(backfill_newly_verified(&store, &pending, &mut known), 0);
561 assert!(known.contains("agent-3"));
562 std::fs::create_dir_all(¬_yet).unwrap();
563 std::fs::write(not_yet.join("MEMORY.md"), "first write").unwrap();
564 assert_eq!(backfill_newly_verified(&store, &pending, &mut known), 0);
565 let history = store.agent_native_memory_version_list("agent-1", "MEMORY.md").unwrap();
566 assert_eq!(history.len(), 1);
567 assert_eq!(history[0].source, "agent_inferred");
568
569 let drifted = check_and_record_drift(&store, "agent-1", "MEMORY.md", "pre-existing", "reconciliation_sweep").unwrap();
570 assert!(!drifted, "unchanged content is not an outside write");
571 }
572
573 #[tokio::test]
577 async fn the_fast_path_backfills_a_folder_before_watching_it() {
578 let _guard = crate::test_support::ISOLATED_AUTH_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
579 let id_store = shared_store();
580 let mstore = Store::open_in_memory().unwrap();
581 let config = tempfile::tempdir().unwrap();
582 let mut def = crate::backend::storage::agents::test_agent_def("agent-fp", "Agent FP", "claude", "agent", 1, "");
583 def.working_directory = "/work/fp".to_string();
584 mstore.agent_def_insert(&mut def).unwrap();
585 mstore
586 .agent_content_set(&crate::backend::storage::AgentContent {
587 agent_id: def.id.clone(),
588 content_type: "env".to_string(),
589 content: format!("CLAUDE_CONFIG_DIR={}\n", config.path().display()),
590 updated_at: 0,
591 })
592 .unwrap();
593 let dir = memory_dir_for_agent_by_id(&mstore, &def).unwrap();
594 std::fs::create_dir_all(&dir).unwrap();
595 std::fs::write(dir.join("MEMORY.md"), "before watching").unwrap();
596
597 let pool = FsWatchPool::new();
598 let mut watched = HashSet::new();
599 let mut dir_to_agent = std::collections::HashMap::new();
600 refresh_subscriptions(&pool, &list_all_memory_targets(&mstore), &id_store, &mut watched, &mut dir_to_agent);
601
602 let v = id_store.agent_native_memory_version_latest(&def.id, "MEMORY.md").unwrap().unwrap();
603 assert_eq!(v.source, "agent_inferred");
604 assert_eq!(v.content, "before watching");
605 }
606
607 #[test]
608 fn first_observation_of_a_file_is_drift() {
609 let store = shared_store();
610 let drifted = check_and_record_drift(&store, "agent-1", "MEMORY.md", "content", "fs_watch").unwrap();
611 assert!(drifted, "a file with no prior version must count as drift");
612
613 let history = store.agent_native_memory_version_list("agent-1", "MEMORY.md").unwrap();
614 assert_eq!(history.len(), 1);
615 assert_eq!(history[0].source, "external_fs_write");
616 assert!(history[0].source_detail.contains("fs_watch"));
617 }
618
619 #[test]
620 fn unchanged_content_is_not_drift() {
621 let store = shared_store();
622 store
623 .agent_native_memory_version_insert("agent-1", "MEMORY.md", "same", "human", "{}", "")
624 .unwrap();
625
626 let drifted = check_and_record_drift(&store, "agent-1", "MEMORY.md", "same", "fs_watch").unwrap();
627 assert!(!drifted, "identical content must not record a new version");
628
629 let history = store.agent_native_memory_version_list("agent-1", "MEMORY.md").unwrap();
630 assert_eq!(history.len(), 1, "no new version should have been inserted");
631 }
632
633 #[test]
634 fn changed_content_is_drift_and_chains_onto_the_prior_version() {
635 let store = shared_store();
636 let v1 = store
637 .agent_native_memory_version_insert("agent-1", "MEMORY.md", "v1", "human", "{}", "")
638 .unwrap();
639
640 let drifted = check_and_record_drift(&store, "agent-1", "MEMORY.md", "v2 — written outside AgentMux", "reconciliation_sweep").unwrap();
641 assert!(drifted);
642
643 let history = store.agent_native_memory_version_list("agent-1", "MEMORY.md").unwrap();
644 assert_eq!(history.len(), 2);
645 assert_eq!(history[0].parent_version_id, Some(v1.id));
646 assert_eq!(history[0].source, "external_fs_write");
647 assert!(history[0].source_detail.contains("reconciliation_sweep"));
648 }
649
650 #[test]
651 fn sweep_finds_a_file_written_directly_to_disk() {
652 let store = shared_store();
653 let tmp = tempfile::tempdir().unwrap();
654 std::fs::write(tmp.path().join("MEMORY.md"), "written outside any RPC").unwrap();
655
656 let broker = crate::backend::mps::Broker::new();
657 let drifted = sweep_one_agent_dir(&store, "agent-1", tmp.path(), "reconciliation_sweep", &broker);
658 assert_eq!(drifted, 1);
659
660 let history = store.agent_native_memory_version_list("agent-1", "MEMORY.md").unwrap();
661 assert_eq!(history.len(), 1);
662 assert_eq!(history[0].source, "external_fs_write");
663 }
664
665 #[test]
671 fn sweep_publishes_agent_memory_changed_when_drift_is_recorded() {
672 let store = shared_store();
673 let tmp = tempfile::tempdir().unwrap();
674 std::fs::write(tmp.path().join("MEMORY.md"), "written outside any RPC").unwrap();
675
676 let (broker, client) = crate::test_support::broker_recording("agent:memory:changed:agent-drift-1");
677 sweep_one_agent_dir(&store, "agent-drift-1", tmp.path(), "reconciliation_sweep", &broker);
678
679 let events = client.received_events();
680 assert_eq!(events.len(), 1, "a real drift must publish exactly one event");
681 assert_eq!(events[0].1.event, "agent:memory:changed:agent-drift-1");
682 }
683
684 #[test]
692 fn sweep_does_not_publish_when_content_is_unchanged() {
693 let store = shared_store();
694 let tmp = tempfile::tempdir().unwrap();
695 std::fs::write(tmp.path().join("MEMORY.md"), "same content").unwrap();
696
697 let (broker, client) = crate::test_support::broker_recording("agent:memory:changed:agent-drift-2");
698 sweep_one_agent_dir(&store, "agent-drift-2", tmp.path(), "reconciliation_sweep", &broker);
702 sweep_one_agent_dir(&store, "agent-drift-2", tmp.path(), "reconciliation_sweep", &broker);
704
705 let events = client.received_events();
706 assert_eq!(events.len(), 1, "only the first sweep's real drift may publish; the second (no-op) must not");
707 }
708
709 #[test]
715 fn sweep_refuses_to_record_an_oversized_file_as_authoritative() {
716 let store = shared_store();
717 let tmp = tempfile::tempdir().unwrap();
718 let oversized = "x".repeat((MAX_MEMORY_FILE_BYTES + 1) as usize);
719 std::fs::write(tmp.path().join("MEMORY.md"), &oversized).unwrap();
720
721 let broker = crate::backend::mps::Broker::new();
722 let drifted = sweep_one_agent_dir(&store, "agent-1", tmp.path(), "reconciliation_sweep", &broker);
723 assert_eq!(drifted, 0, "an oversized file must not be recorded as drift");
724
725 let history = store.agent_native_memory_version_list("agent-1", "MEMORY.md").unwrap();
726 assert!(history.is_empty(), "no truncated content may be recorded as a version");
727 }
728
729 #[test]
730 fn read_memory_file_lossy_reads_a_file_at_exactly_the_cap() {
731 let tmp = tempfile::tempdir().unwrap();
732 let path = tmp.path().join("MEMORY.md");
733 let at_cap = "x".repeat(MAX_MEMORY_FILE_BYTES as usize);
734 std::fs::write(&path, &at_cap).unwrap();
735
736 let content = read_memory_file_lossy(&path).unwrap();
737 assert_eq!(content.len(), MAX_MEMORY_FILE_BYTES as usize);
738 }
739
740 #[test]
741 fn read_memory_file_lossy_rejects_a_file_one_byte_over_the_cap() {
742 let tmp = tempfile::tempdir().unwrap();
743 let path = tmp.path().join("MEMORY.md");
744 let over_cap = "x".repeat((MAX_MEMORY_FILE_BYTES + 1) as usize);
745 std::fs::write(&path, &over_cap).unwrap();
746
747 let err = read_memory_file_lossy(&path).unwrap_err();
748 assert_eq!(err.kind(), std::io::ErrorKind::InvalidData);
749 }
750
751 #[test]
752 fn sweep_ignores_non_md_files_and_missing_directories() {
753 let store = shared_store();
754 let tmp = tempfile::tempdir().unwrap();
755 std::fs::write(tmp.path().join("notes.txt"), "not a memory file").unwrap();
756
757 let broker = crate::backend::mps::Broker::new();
758 assert_eq!(sweep_one_agent_dir(&store, "agent-1", tmp.path(), "reconciliation_sweep", &broker), 0);
759 assert_eq!(
760 sweep_one_agent_dir(&store, "agent-1", &tmp.path().join("does-not-exist"), "reconciliation_sweep", &broker),
761 0
762 );
763 }
764
765 #[test]
766 fn sweep_scopes_versions_to_the_given_agent_id() {
767 let store = shared_store();
768 let tmp = tempfile::tempdir().unwrap();
769 std::fs::write(tmp.path().join("MEMORY.md"), "content").unwrap();
770
771 let broker = crate::backend::mps::Broker::new();
772 sweep_one_agent_dir(&store, "agent-specific", tmp.path(), "reconciliation_sweep", &broker);
773
774 assert_eq!(store.agent_native_memory_version_list("agent-specific", "MEMORY.md").unwrap().len(), 1);
775 assert_eq!(store.agent_native_memory_version_list("agent-other", "MEMORY.md").unwrap().len(), 0);
776 }
777
778 #[tokio::test]
779 async fn reconciliation_sweep_once_covers_every_agent_with_a_working_directory() {
780 let _guard = crate::test_support::ISOLATED_AUTH_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
786 let prev_shared_dir = std::env::var_os("AGENTMUX_SHARED_DIR");
787 let shared = tempfile::tempdir().unwrap();
788 std::env::set_var("AGENTMUX_SHARED_DIR", shared.path());
789
790 let tmp = tempfile::NamedTempFile::new().unwrap();
791 let id_store = Store::open_shared(tmp.path()).unwrap();
792 let state = crate::test_support::core_parts();
793
794 let config_a = tempfile::tempdir().unwrap();
795 let config_b = tempfile::tempdir().unwrap();
796 for (id, dir) in [("sweep-agent-a", config_a.path()), ("sweep-agent-b", config_b.path())] {
797 let mut def = crate::backend::storage::AgentDefinition {
798 working_directory: format!("/work/{id}"),
799 ..crate::backend::storage::agents::test_agent_def(id, "Test", "claude", "host", 0, "")
800 };
801 state.mstore.agent_def_insert(&mut def).unwrap();
802 state
803 .mstore
804 .agent_content_set(&crate::backend::storage::AgentContent {
805 agent_id: id.to_string(),
806 content_type: "env".to_string(),
807 content: format!("CLAUDE_CONFIG_DIR={}\n", dir.display()),
808 updated_at: 0,
809 })
810 .unwrap();
811
812 let memory_dir = memory_dir_for_agent_by_id(&state.mstore, &def).unwrap();
813 std::fs::create_dir_all(&memory_dir).unwrap();
814 std::fs::write(memory_dir.join("MEMORY.md"), format!("content for {id}")).unwrap();
815 }
816
817 let broker = crate::backend::mps::Broker::new();
818 let mut watch = DeletionWatch::default();
819 let drifted = reconciliation_sweep_once(&list_all_memory_targets(&state.mstore), &id_store, &broker, &mut watch);
820 assert_eq!(drifted, 2, "sweep must cover every agent with a working directory");
821 assert_eq!(id_store.agent_native_memory_version_list("sweep-agent-a", "MEMORY.md").unwrap().len(), 1);
822 assert_eq!(id_store.agent_native_memory_version_list("sweep-agent-b", "MEMORY.md").unwrap().len(), 1);
823
824 match prev_shared_dir {
825 Some(v) => std::env::set_var("AGENTMUX_SHARED_DIR", v),
826 None => std::env::remove_var("AGENTMUX_SHARED_DIR"),
827 }
828 }
829
830 #[tokio::test]
837 async fn reconciliation_sweep_detects_an_out_of_band_deletion_once_then_suppresses_repeats_until_recreated() {
838 let _guard = crate::test_support::ISOLATED_AUTH_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
839 let prev_shared_dir = std::env::var_os("AGENTMUX_SHARED_DIR");
840 let shared = tempfile::tempdir().unwrap();
841 std::env::set_var("AGENTMUX_SHARED_DIR", shared.path());
842
843 let tmp = tempfile::NamedTempFile::new().unwrap();
844 let id_store = Store::open_shared(tmp.path()).unwrap();
845 let state = crate::test_support::core_parts();
846 let config = tempfile::tempdir().unwrap();
847
848 let mut def = crate::backend::storage::AgentDefinition {
849 working_directory: "/work/sweep-delete-agent".to_string(),
850 ..crate::backend::storage::agents::test_agent_def("sweep-delete-agent", "Test", "claude", "host", 0, "")
851 };
852 state.mstore.agent_def_insert(&mut def).unwrap();
853 state
854 .mstore
855 .agent_content_set(&crate::backend::storage::AgentContent {
856 agent_id: def.id.clone(),
857 content_type: "env".to_string(),
858 content: format!("CLAUDE_CONFIG_DIR={}\n", config.path().display()),
859 updated_at: 0,
860 })
861 .unwrap();
862 let memory_dir = memory_dir_for_agent_by_id(&state.mstore, &def).unwrap();
863 std::fs::create_dir_all(&memory_dir).unwrap();
864 let file_path = memory_dir.join("MEMORY.md");
865 std::fs::write(&file_path, "content").unwrap();
866
867 let (broker, client) = crate::test_support::broker_recording("agent:memory:changed:sweep-delete-agent");
868 let mut watch = DeletionWatch::default();
869
870 reconciliation_sweep_once(&list_all_memory_targets(&state.mstore), &id_store, &broker, &mut watch);
873 assert_eq!(client.received_events().len(), 1);
874
875 std::fs::remove_file(&file_path).unwrap();
877
878 reconciliation_sweep_once(&list_all_memory_targets(&state.mstore), &id_store, &broker, &mut watch);
880 assert_eq!(client.received_events().len(), 2, "the sweep that first observes a deletion must publish");
881
882 reconciliation_sweep_once(&list_all_memory_targets(&state.mstore), &id_store, &broker, &mut watch);
886 assert_eq!(client.received_events().len(), 2, "a repeat sweep over an already-reported deletion must not re-publish");
887
888 std::fs::write(&file_path, "recreated content").unwrap();
891 reconciliation_sweep_once(&list_all_memory_targets(&state.mstore), &id_store, &broker, &mut watch);
892 assert_eq!(client.received_events().len(), 3);
893
894 std::fs::remove_file(&file_path).unwrap();
898 reconciliation_sweep_once(&list_all_memory_targets(&state.mstore), &id_store, &broker, &mut watch);
899 assert_eq!(client.received_events().len(), 4, "a re-deletion after recreation must be detected as a fresh event");
900
901 match prev_shared_dir {
902 Some(v) => std::env::set_var("AGENTMUX_SHARED_DIR", v),
903 None => std::env::remove_var("AGENTMUX_SHARED_DIR"),
904 }
905 }
906}
907
908#[cfg(test)]
911mod ownership_tests {
912 use super::*;
913 use crate::backend::memory::native_files::memory_dir_for_agent_by_id;
914 use std::sync::Mutex;
915
916 #[derive(Clone, Default)]
917 struct Capture(Arc<Mutex<Vec<u8>>>);
918 impl std::io::Write for Capture {
919 fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
920 self.0.lock().unwrap().extend_from_slice(buf);
921 Ok(buf.len())
922 }
923 fn flush(&mut self) -> std::io::Result<()> {
924 Ok(())
925 }
926 }
927 impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for Capture {
928 type Writer = Capture;
929 fn make_writer(&'a self) -> Capture {
930 self.clone()
931 }
932 }
933
934 fn logged(f: impl FnOnce()) -> String {
936 let out = Capture::default();
937 let subscriber = tracing_subscriber::fmt().with_writer(out.clone()).with_max_level(tracing::Level::TRACE).finish();
938 tracing::subscriber::with_default(subscriber, f);
939 let text = String::from_utf8(out.0.lock().unwrap().clone()).unwrap();
940 text
941 }
942
943 fn populated(mstore: &Store, id_store: &Store, id: &str, file: &str, body: &str, config: &Path) -> PathBuf {
946 let mut def = crate::backend::storage::agents::test_agent_def(id, id, "claude", "agent", 1, "");
947 def.working_directory = format!("/work/{id}");
948 mstore.agent_def_insert(&mut def).unwrap();
949 mstore
950 .agent_content_set(&crate::backend::storage::AgentContent {
951 agent_id: def.id.clone(),
952 content_type: "env".to_string(),
953 content: format!("CLAUDE_CONFIG_DIR={}\n", config.display()),
954 updated_at: 0,
955 })
956 .unwrap();
957 let dir = memory_dir_for_agent_by_id(mstore, &def).unwrap();
958 std::fs::create_dir_all(&dir).unwrap();
959 std::fs::write(dir.join(file), body).unwrap();
960 id_store.agent_native_memory_version_insert(id, file, body, "agent_inferred", "{}", "").unwrap();
961 dir
962 }
963
964 fn snapshot(dir: &Path) -> Vec<(String, Vec<u8>, std::time::SystemTime)> {
966 let mut out: Vec<_> = std::fs::read_dir(dir)
967 .unwrap()
968 .flatten()
969 .map(|e| (e.file_name().to_string_lossy().into_owned(), std::fs::read(e.path()).unwrap(), e.metadata().unwrap().modified().unwrap()))
970 .collect();
971 out.sort_by(|a, b| a.0.cmp(&b.0));
972 out
973 }
974
975 fn isolated() -> (std::sync::MutexGuard<'static, ()>, Option<std::ffi::OsString>, tempfile::TempDir) {
976 let guard = crate::test_support::ISOLATED_AUTH_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
977 let prev = std::env::var_os("AGENTMUX_SHARED_DIR");
978 let shared = tempfile::tempdir().unwrap();
979 std::env::set_var("AGENTMUX_SHARED_DIR", shared.path());
980 (guard, prev, shared)
981 }
982
983 fn restore(prev: Option<std::ffi::OsString>) {
984 match prev {
985 Some(v) => std::env::set_var("AGENTMUX_SHARED_DIR", v),
986 None => std::env::remove_var("AGENTMUX_SHARED_DIR"),
987 }
988 }
989
990 #[tokio::test]
991 async fn a_channel_running_none_of_the_agents_touches_none_of_their_memory_and_logs_nothing() {
992 let (_guard, prev, _shared) = isolated();
993 let mstore = Store::open_in_memory().unwrap();
994 let id_store = Store::open_shared(Path::new(":memory:")).unwrap();
995 let config = tempfile::tempdir().unwrap();
996 let dirs: Vec<PathBuf> = ["roster-a", "roster-b", "roster-c"]
997 .iter()
998 .map(|id| populated(&mstore, &id_store, id, "secret-topic-notes.md", "what the agent knows", config.path()))
999 .collect();
1000 std::fs::write(dirs[1].join("secret-topic-notes.md"), "changed since").unwrap();
1002 let before: Vec<_> = dirs.iter().map(|d| snapshot(d)).collect();
1003 let versions_before = id_store.agent_native_memory_version_list("roster-b", "secret-topic-notes.md").unwrap().len();
1004
1005 let (broker, client) = crate::test_support::broker_recording("agent:memory:changed:roster-b");
1006 let owned: OwnedAgents = Arc::new(HashSet::new);
1007 let pool = FsWatchPool::new();
1008 let text = logged(|| {
1009 let targets = owned_targets(&mstore, &owned);
1010 assert!(targets.is_empty(), "no agent runs here, so no folder is looked at");
1011 let mut watch = DeletionWatch::default();
1012 let mut backfilled = HashSet::new();
1013 for _ in 0..3 {
1014 backfill_newly_verified(&id_store, &targets, &mut backfilled);
1015 assert_eq!(reconciliation_sweep_once(&targets, &id_store, &broker, &mut watch), 0);
1016 refresh_subscriptions(&pool, &targets, &id_store, &mut HashSet::new(), &mut std::collections::HashMap::new());
1017 }
1018 });
1019
1020 let after: Vec<_> = dirs.iter().map(|d| snapshot(d)).collect();
1021 assert_eq!(before, after, "every file is byte-identical, with the same modified time");
1022 let versions_after = id_store.agent_native_memory_version_list("roster-b", "secret-topic-notes.md").unwrap().len();
1023 assert_eq!(versions_before, versions_after, "nothing is recorded in the shared store for them");
1024 assert!(client.received_events().is_empty(), "no change is announced for them");
1025 for word in ["roster-a", "roster-b", "roster-c", "secret-topic-notes", "native_memory_drift"] {
1026 assert!(!text.contains(word), "the log names {word}: {text}");
1027 }
1028 restore(prev);
1029 }
1030
1031 #[tokio::test]
1032 async fn a_channel_looks_only_at_the_agents_running_in_it() {
1033 let (_guard, prev, _shared) = isolated();
1034 let mstore = Store::open_in_memory().unwrap();
1035 let id_store = Store::open_shared(Path::new(":memory:")).unwrap();
1036 let config = tempfile::tempdir().unwrap();
1037 let mine = populated(&mstore, &id_store, "mine", "notes.md", "one", config.path());
1038 let theirs = populated(&mstore, &id_store, "theirs", "notes.md", "one", config.path());
1039 std::fs::write(mine.join("notes.md"), "mine changed").unwrap();
1040 std::fs::write(theirs.join("notes.md"), "theirs changed").unwrap();
1041
1042 let owned: OwnedAgents = Arc::new(|| HashSet::from(["mine".to_string()]));
1043 let targets = owned_targets(&mstore, &owned);
1044 assert_eq!(targets.iter().map(|(id, _)| id.as_str()).collect::<Vec<_>>(), vec!["mine"]);
1045 let broker = crate::backend::mps::Broker::new();
1046 assert_eq!(reconciliation_sweep_once(&targets, &id_store, &broker, &mut DeletionWatch::default()), 1);
1047 assert_eq!(id_store.agent_native_memory_version_list("mine", "notes.md").unwrap().len(), 2);
1048 assert_eq!(id_store.agent_native_memory_version_list("theirs", "notes.md").unwrap().len(), 1);
1049 restore(prev);
1050 }
1051
1052 #[test]
1054 fn the_fast_path_ignores_a_write_in_the_folder_of_an_agent_that_no_longer_runs_here() {
1055 let id_store = Store::open_shared(Path::new(":memory:")).unwrap();
1056 let dir = tempfile::tempdir().unwrap();
1057 id_store.agent_native_memory_version_insert("was-mine", "notes.md", "one", "agent_inferred", "{}", "").unwrap();
1058 std::fs::write(dir.path().join("notes.md"), "two, written by another channel's run of it").unwrap();
1059 let mut dir_to_agent = std::collections::HashMap::new();
1060 dir_to_agent.insert(dir.path().to_path_buf(), "was-mine".to_string());
1061 let event = crate::backend::fs_watch::FsWatchEvent { path: dir.path().join("notes.md"), kind: FsWatchEventKind::Modified };
1062 let (broker, client) = crate::test_support::broker_recording("agent:memory:changed:was-mine");
1063 let history = || id_store.agent_native_memory_version_list("was-mine", "notes.md").unwrap().len();
1064
1065 let stopped: OwnedAgents = Arc::new(HashSet::new);
1066 let text = logged(|| handle_fs_event(&event, &dir_to_agent, &stopped, &id_store, &broker));
1067 assert_eq!(history(), 1, "nothing is recorded for it");
1068 assert!(client.received_events().is_empty() && text.is_empty(), "nothing is announced or logged: {text}");
1069
1070 let running: OwnedAgents = Arc::new(|| HashSet::from(["was-mine".to_string()]));
1071 handle_fs_event(&event, &dir_to_agent, &running, &id_store, &broker);
1072 assert_eq!(history(), 2, "while it runs here, the write is recorded");
1073 assert_eq!(client.received_events().len(), 1);
1074 }
1075
1076 #[tokio::test]
1077 async fn a_file_this_process_never_saw_is_not_reported_deleted_but_one_it_saw_is() {
1078 let (_guard, prev, _shared) = isolated();
1079 let mstore = Store::open_in_memory().unwrap();
1080 let id_store = Store::open_shared(Path::new(":memory:")).unwrap();
1081 let config = tempfile::tempdir().unwrap();
1082 let dir = populated(&mstore, &id_store, "mine", "kept.md", "kept", config.path());
1083 id_store.agent_native_memory_version_insert("mine", "elsewhere.md", "not here", "agent_inferred", "{}", "").unwrap();
1085
1086 let owned: OwnedAgents = Arc::new(|| HashSet::from(["mine".to_string()]));
1087 let (broker, client) = crate::test_support::broker_recording("agent:memory:changed:mine");
1088 let mut watch = DeletionWatch::default();
1089 let text = logged(|| {
1090 reconciliation_sweep_once(&owned_targets(&mstore, &owned), &id_store, &broker, &mut watch);
1091 reconciliation_sweep_once(&owned_targets(&mstore, &owned), &id_store, &broker, &mut watch);
1092 });
1093 assert!(!text.contains("deletion") && !text.contains("elsewhere"), "{text}");
1094 assert!(client.received_events().is_empty());
1095
1096 std::fs::remove_file(dir.join("kept.md")).unwrap();
1098 let text = logged(|| {
1099 for _ in 0..3 {
1100 reconciliation_sweep_once(&owned_targets(&mstore, &owned), &id_store, &broker, &mut watch);
1101 }
1102 });
1103 assert_eq!(text.matches("out-of-band deletion").count(), 1, "{text}");
1104 assert_eq!(client.received_events().len(), 1);
1105 restore(prev);
1106 }
1107}
1108
1109#[cfg(test)]
1110mod damage_tests {
1111 use super::*;
1112 use crate::backend::storage::filestore::FileStore;
1113 use crate::backend::transcript::damage::{self, test_support};
1114 use std::sync::Arc;
1115
1116 #[test]
1117 fn a_capture_that_finds_the_shared_store_corrupt_marks_the_memory_record_and_stops() {
1118 let agent = "uid-drift-damage-1";
1119 let dir = tempfile::tempdir().unwrap();
1120 let fs = Arc::new(FileStore::open_in_memory().unwrap());
1121 let _g = test_support::use_global(&fs);
1122 test_support::corrupt(&fs);
1123 capture_into_record(agent, dir.path());
1124 assert!(damage::is_damaged(&damage::memory_zone(agent)));
1125 let fixed = Arc::new(FileStore::open_in_memory().unwrap());
1127 let _g2 = test_support::use_global(&fixed);
1128 capture_into_record(agent, dir.path());
1129 assert!(fixed.conn().lock().unwrap().query_row("SELECT count(*) FROM db_wave_file", [], |r| r.get::<_, i64>(0)).unwrap() == 0);
1130 }
1131}