Skip to main content

agentmux_srv_core/backend/memory/
native_drift.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Out-of-band write detection for native memory files — §4.5 of
5//! docs/specs/SPEC_MEMORY_VERSION_CONTROL_AND_ARMORY_AUDIT_2026_08_19.md.
6//! Claude Code's CLI writes memory `.md` files directly to
7//! `~/.claude/projects/<hash>/memory/*.md`, with no obligation to go
8//! through `agent:memory:write_file`/`memory.write` — an agent's own
9//! general-purpose filesystem tools can (and, per this spec's own
10//! motivating incident, did) write there directly. When that happens, no
11//! RPC fires, so nothing in `native_memory_handlers.rs` or `app_api::mod`
12//! ever sees it.
13//!
14//! Two independent layers close that gap, so failure of one degrades
15//! rather than blinds the whole system:
16//!
17//! 1. **Fast path** ([`spawn_fast_path`]) — subscribe to every known
18//!    agent's memory directory via the shared `FsWatchPool`
19//!    (`backend::fs_watch`), and record a new `external_fs_write` version
20//!    on any change whose hash doesn't match the latest recorded version.
21//! 2. **Slow path** ([`reconciliation_sweep_once`]) — a periodic sweep, run
22//!    on the same cadence class as `FsWatchPool`'s own
23//!    `HEALTH_SWEEP_INTERVAL` (30s), that hashes every known agent's live
24//!    memory files and compares against the latest recorded version — the
25//!    backstop for a missed fs-watch event, a watch still in retry-backoff,
26//!    or srv having been down entirely when the write happened.
27//!
28//! Both layers call the same [`check_and_record_drift`] — the only
29//! difference between them is how they learn a file might have changed.
30//! Neither promises zero data loss (see the spec's §4.5 "precision,
31//! honestly bounded" section): two out-of-band writes to the same file
32//! between one sweep and the next collapse into one detected version, and
33//! `source_detail` never guesses a `session_id` for a drift-detected write.
34
35use 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
44/// Same cadence class as `FsWatchPool::HEALTH_SWEEP_INTERVAL`
45/// (`backend/fs_watch/recovery.rs`) — chosen for the same reason: frequent
46/// enough that an operator reviewing history isn't waiting long for a
47/// drifted write to surface, infrequent enough not to matter for a
48/// background sweep over what's normally a handful of small markdown files
49/// per agent.
50const SWEEP_INTERVAL: Duration = Duration::from_secs(30);
51
52/// Same cap `native_memory_handlers.rs`/`app_api::mod` already use for a
53/// memory file's live content.
54const MAX_MEMORY_FILE_BYTES: u64 = 10 * 1024 * 1024;
55
56/// The ids of the agents running in this process now. The agent roster and the identity folders are
57/// shared by every channel on the host, but a channel looks at an agent's memory folder only while that
58/// agent runs in it: a second channel starting beside a populated one (a headless start next to a
59/// desktop) reads nothing of the others' agents, records nothing about them, and logs nothing about
60/// them. An agent that is not running is brought up to date when it next spawns (the reconcile before
61/// spawn, `reconcile.rs`).
62pub type OwnedAgents = Arc<dyn Fn() -> HashSet<String> + Send + Sync>;
63
64/// The roster's memory directories of the agents running in this process. An agent is matched by the id
65/// the roster and its memory directory are keyed by (`AgentDefinition::id`).
66pub 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/// What the sweep knows across ticks about files that have a recorded history.
77#[derive(Default)]
78pub(crate) struct DeletionWatch {
79    /// Files this process has itself found on disk. Only one of these can be "deleted": a file with
80    /// history that this process never saw is one it cannot find (a directory resolved another way,
81    /// a store another channel filled), not one that was removed.
82    seen: HashSet<(String, String)>,
83    /// Deletions already reported, so a file that stays gone is reported once, not every tick.
84    reported: HashSet<(String, String)>,
85}
86
87/// Compare `live_content` against the latest recorded version of
88/// `(agent_id, filename)`; if different (including "no version recorded
89/// yet"), insert a new version tagged `source: "external_fs_write"` with
90/// `source_detail: {"detected_via": detected_via}`. Returns `Ok(true)` if a
91/// new version was recorded, `Ok(false)` if the content already matched
92/// (no drift to report).
93pub(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    // reagent P2 on PR #2675: the fast path (per fs-watch event) and slow
102    // path (30s sweep) run as concurrent, independent tokio tasks and can
103    // both observe the same file change — a plain "read latest, then
104    // separately insert" here (two Store calls, each independently
105    // locking/unlocking) is not atomic as a compound operation, so both
106    // could read the same stale "latest" and insert duplicate
107    // external_fs_write rows for one actual change.
108    // `agent_native_memory_version_insert_if_changed` does the compare
109    // AND the insert under a single connection-lock acquisition, closing
110    // that race — see its own doc comment for the full rationale.
111    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
117/// Give every verified agent's memory file with no recorded version its
118/// first one, labelled `agent_inferred` ("Agent" in Memory), before the
119/// drift detector starts. Otherwise the detector finds these ordinary files
120/// on its first sweep and records them as `external_fs_write`, "Detected
121/// outside AgentMux", as it did for every file after a new local-build
122/// channel (SPEC_MEMORY_FOLLOWS_THE_AGENT_2026_09_24.md §1.3, phase M1).
123///
124/// Covers only files that **predate tracking**: those already in the
125/// directory at the moment it is first verified — at startup (after the
126/// identity stores are attached, so an agent's account-linked directory
127/// resolves; this used to be migration m0024, which ran before that and fell
128/// back to a registry guess), or later for an agent verified mid-session.
129///
130/// Anything written after that is a change, and drift detection records it
131/// exactly as it records every direct write to the folder today — including
132/// Claude's own auto-memory writes, which never go through AgentMux. So an
133/// agent whose folder doesn't exist yet is still counted as seen: its first
134/// files are written after verification, like every later one. Pre-existing
135/// files raise no fs-watch event, so the fast path can't race this.
136/// Returns the number of versions recorded.
137pub(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
186/// Read one `.md` file's content the same way the rest of the native-memory
187/// code does: lossy UTF-8. Unlike `native_memory_handlers.rs`'s own
188/// mirror-refresh path — which truncates an oversized file and separately
189/// reports the filename so an interactive caller (`bundle.export_for_agent`)
190/// can surface a warning — the drift detector has no interactive caller to
191/// warn. Silently truncating here would instead record the truncated tail
192/// as a new *version*, permanently misrepresenting content the file never
193/// actually contained as if it were authoritative (reagent P2 on PR
194/// #2675). So an oversized file is refused outright (`ErrorKind::
195/// InvalidData`, distinguishable from a transient I/O error) rather than
196/// read partially; callers log and skip it, same treatment as any other
197/// per-file read failure.
198pub(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
213/// One pass over every agent definition with a configured working
214/// directory: hash each live `.md` file in its memory dir and record drift
215/// if found. Returns the number of drifted files recorded (for logging;
216/// tests assert on it directly). Errors from an individual agent/file are
217/// logged and swallowed — one agent's bad state (e.g. a permissions issue)
218/// must not stop the sweep from covering every other agent.
219///
220/// Also detects and publishes OUT-OF-BAND DELETIONS (Codex P2, PR #2932):
221/// content-drift detection alone only ever compares files that still exist
222/// against their last recorded version — a `.md` file removed directly (not
223/// through `agent:memory:write_file`/`revert`, neither of which delete
224/// files) never surfaces there, and the fast fs-watch path deliberately
225/// ignores `FsWatchEventKind::Removed` (it exists to catch content changes,
226/// not track deletions). Without this, the grid count and an open detail
227/// view for the deleted file would stay stale indefinitely — no event ever
228/// arrives to prompt the frontend's own "the selected file is now gone"
229/// handling to fire.
230///
231/// `watch` is this sweep's own persistent, cross-tick state
232/// (threaded in from `spawn_slow_path`'s loop, same pattern the fast path's
233/// `watched_dirs`/`dir_to_agent` already use) — without it, a file that
234/// STAYS deleted would republish an event every single 30s tick forever,
235/// since "missing from disk" is true on every subsequent sweep too, not
236/// just the first one. A filename leaves the reported set again the
237/// moment it reappears on disk (recreated with new content), so a later
238/// re-deletion is detected fresh rather than staying permanently suppressed.
239/// A file is only ever called deleted after this process saw it on disk ([`DeletionWatch`]).
240///
241/// `targets` are the directories this process may look at ([`owned_targets`]); nothing else is read.
242pub(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    // agent_native_memory_version_list_distinct_files() is unscoped (every
254    // agent's every file with recorded history) — the same primitive
255    // memory/native_retention.rs already uses as its own work list, not a
256    // new query pattern introduced here.
257    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            // Not (or no longer) a tracked target this sweep — out of scope
263            // for this pass; list_all_memory_targets is the same
264            // authoritative source the content-drift loop above already
265            // trusts for "which agents/dirs are live right now."
266            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
285/// Also record the provider's writes into the agent's memory record — a
286/// folder its spawn has reconciled, and whose claim it still holds alone
287/// (SPEC_MEMORY_FOLLOWS_THE_AGENT_2026_09_24.md §2.1.3). Capture only;
288/// the folder isn't touched.
289fn capture_into_record(agent_id: &str, memory_dir: &Path) {
290    use crate::backend::transcript::damage;
291    // A memory record found corrupt is not written to again in this process.
292    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                // Reactive Memory updates (SPEC_ARMORY_REACTIVE_UPDATES_2026_09_02.md).
348                // Only on an actual recorded change (Ok(true)) — this branch
349                // runs once per sweep tick per watched agent, and firing on
350                // every no-op tick would mean an event for every agent every
351                // 30s regardless of whether anything happened.
352                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
361/// Start both layers. Call once at server startup with a fully-built
362/// `AppState`'s `fs_watch_pool`/`mstore`/`id_store`, and `owned`: the agents running
363/// in this process, the only ones either layer looks at ([`OwnedAgents`]). Returns immediately —
364/// both loops run as spawned background tasks for the lifetime of the
365/// process (no shutdown handle; srv itself owns the process lifetime).
366pub 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        // Persistent across ticks, same pattern as the fast path's own
381        // watched_dirs/dir_to_agent — see reconciliation_sweep_once's own
382        // doc comment on why this can't just be a fresh HashSet per call.
383        let mut watch = DeletionWatch::default();
384        // Agents whose directory has had its first-sight backfill.
385        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
395/// Maintains a `memory_dir -> agent_id` map, refreshed every
396/// [`SWEEP_INTERVAL`] tick (piggybacking on the same cadence as the slow
397/// path rather than requiring a separate agent-spawn/teardown hook — a
398/// newly-defined agent is picked up within one tick, not instantly, which
399/// is an acceptable, honestly-bounded lag for a fast path whose whole
400/// purpose is narrowing a gap, not eliminating it). `FsWatchPool`
401/// subscriptions have no `Drop`-based teardown (see `pool.rs` — holding or
402/// discarding a `Subscription` value doesn't affect the underlying watch),
403/// so a dir is watched for the life of the process once first seen; we
404/// only need to track which dirs we've already called `subscribe_dir` on
405/// to avoid redundant re-subscription every tick.
406fn 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                            // "a wake signal, not a guaranteed delivery log"
429                            // (FsWatchPool's own doc) — a lagged receiver
430                            // resyncs via the next reconciliation sweep
431                            // rather than trying to catch up here.
432                            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
443/// One fs-watch event on a watched memory folder. A folder stays watched for the life of the process once
444/// first seen, so the agent is asked about again here: a write is looked at only while the agent runs in
445/// this process. One that stopped here and runs in another channel now is that channel's, and a write
446/// of its last moments is recorded by the reconcile before its next spawn.
447fn 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        // TOCTOU-deleted or transient I/O between the event
474        // and this read — non-fatal, the reconciliation
475        // sweep covers it if the write actually stuck.
476        Err(_) => return,
477    };
478    // Restructured from `if let Err(...) {} else {}` to a full
479    // match while adding the publish below: the old `else`
480    // branch fired on Ok(false) too (content already matched,
481    // nothing recorded), logging "recorded an out-of-band
482    // write" for a no-op — a pre-existing log inaccuracy
483    // fixed as a side effect of needing this branch anyway.
484    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            // Reactive Memory updates (SPEC_ARMORY_REACTIVE_UPDATES_2026_09_02.md).
489            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        // subscribe_dir canonicalizes internally; canonicalize here too so
505        // watched_dirs/dir_to_agent key on the same form an incoming
506        // event's path will actually have (events report canonical paths —
507        // see subscribe_dir's own doc comment).
508        let canonical = memory_dir.canonicalize().unwrap_or_else(|_| memory_dir.clone());
509        if watched_dirs.insert(canonical.clone()) {
510            // Record the files already here BEFORE watching, so a write
511            // landing right after the subscription is a change against them
512            // — never the first sighting that skips their own version. The
513            // slow sweep runs the same idempotent backfill.
514            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    /// A pre-existing file gets one `agent_inferred` version at startup, so
531    /// the first sweep sees no drift and never labels it "Detected outside
532    /// AgentMux" (SPEC_MEMORY_FOLLOWS_THE_AGENT_2026_09_24.md §1.3, M1).
533    #[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        // A file that appears later in a known directory is an outside write
544        // for drift detection to record, not another first sighting.
545        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        // An agent verified mid-session gets its own first sighting.
549        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        // A folder that doesn't exist yet has nothing that predates tracking:
555        // the agent is seen, and files written later are changes for drift
556        // detection, like every direct write to the folder.
557        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(&not_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    /// The fast path records a folder's existing files before it starts
574    /// watching, so an edit right after subscribing is a change against
575    /// them, not their first sighting (ReAgent P1 on #3707).
576    #[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    // SPEC_ARMORY_REACTIVE_UPDATES_2026_09_02.md: an out-of-band write
666    // (bypassing both the WS RPC and MuxAPI surfaces entirely) must still
667    // make the Memory → Personal grid reactive — that's this whole module's reason to
668    // exist, so its own publish path needs the same regression guard the
669    // RPC handlers' publish calls get.
670    #[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    // The other half of the same guard: a sweep tick that finds NO drift
685    // (unchanged content) must NOT publish — the reconciliation sweep runs
686    // every 30s for every watched agent regardless of whether anything
687    // changed, so publishing unconditionally would fire an event storm with
688    // no corresponding real change, defeating the point of an event-driven
689    // refresh (see this module's own SPEC section on why insert_if_changed's
690    // no-op case is explicitly excluded).
691    #[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        // First sweep: genuinely new content, records a version (and would
699        // publish — unobserved here since this test is about the SECOND
700        // sweep finding nothing new).
701        sweep_one_agent_dir(&store, "agent-drift-2", tmp.path(), "reconciliation_sweep", &broker);
702        // Second sweep over the same, unchanged file — no drift to record.
703        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    // reagent P2 on PR #2675: read_memory_file_lossy previously truncated
710    // an oversized file and returned the truncated bytes as if they were
711    // the whole file — the sweep would then record that truncated content
712    // as a new, authoritative version. It must instead refuse to read the
713    // file at all, so no version (correct or corrupted) is recorded.
714    #[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        // list_all_memory_targets also consults the global named-agent
781        // registry (added for reagent P1 on PR #2675) — without isolating
782        // AGENTMUX_SHARED_DIR here, this test would sweep whatever real
783        // live agents happen to be registered on the machine running the
784        // suite, not just the two synthetic ones it sets up below.
785        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    // Codex P2, PR #2932: content-drift detection alone never notices a
831    // file that's gone (nothing to compare content against), and the fast
832    // path deliberately ignores FsWatchEventKind::Removed — without this,
833    // an out-of-band deletion of the file open in the Memory → Personal detail view
834    // stayed stale forever, since no event ever arrived to trigger the
835    // frontend's own "the selected file is gone" handling.
836    #[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        // Sweep 1: file present — establishes the recorded version (and
871        // publishes once, from ordinary content-drift, not deletion logic).
872        reconciliation_sweep_once(&list_all_memory_targets(&state.mstore), &id_store, &broker, &mut watch);
873        assert_eq!(client.received_events().len(), 1);
874
875        // Delete the file out of band (not through write_file/revert).
876        std::fs::remove_file(&file_path).unwrap();
877
878        // Sweep 2: first sweep to observe the deletion — must publish.
879        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        // Sweep 3: file still gone — must NOT publish again (suppressed;
883        // otherwise a permanently-deleted file would fire an event every
884        // 30s tick forever).
885        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        // Recreate the file — content-drift detects it as a new version
889        // (publish #3) and clears the deletion-suppression for this file.
890        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        // Delete it again — must be detected as a FRESH deletion (publish
895        // #4), proving the suppression state was actually cleared on
896        // recreation, not permanently stuck once a file is ever deleted once.
897        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/// A channel starting beside a populated one (a headless start next to a desktop) shares the agent roster
909/// and the identity folders with it, and must leave the other channel's agents' memory alone.
910#[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    /// Runs `f` and returns everything it logged, at every level.
935    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    /// One roster agent with a memory file already on disk and in the shared store's history, as the
944    /// channel that runs it left them.
945    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    /// Every file under `dir` with its bytes and modified time.
965    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        // One file changed since the other channel recorded it: a running channel would record that.
1001        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    /// A folder stays watched once subscribed; a write in it counts only while its agent runs here.
1053    #[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        // History for a file that is not in this folder (another channel's, or a folder resolved another way).
1084        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        // A file this process has seen and that is then removed is reported, once.
1097        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        // The next sweep does not go near the store: a healthy one swapped in sees no read from it.
1126        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}