Skip to main content

agentmux_srv_core/backend/fs_watch/
pool.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4use std::collections::HashMap;
5use std::path::{Path, PathBuf};
6use std::sync::{Arc, Mutex};
7use std::time::Duration;
8
9use notify::{EventKind, RecursiveMode, Watcher};
10use tokio::sync::{broadcast, mpsc};
11
12use super::recovery::{HealthState, WatchBackend, FsWatchHealth, RETRY_BACKOFF, HEALTH_SWEEP_INTERVAL};
13
14/// Broadcast channel capacity. Generous relative to real fs-event volume
15/// (file-save bursts, not high-frequency streams) — a slow consumer would
16/// need to fall behind by this many raw events before `RecvError::Lagged`,
17/// at which point it should resync from scratch rather than assume it saw
18/// everything (same "wake signal, not a guaranteed delivery log" contract
19/// the existing three watchers already have via their own debounce logic).
20const EVENT_CHANNEL_CAPACITY: usize = 1024;
21
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub enum FsWatchEventKind {
24    Created,
25    Modified,
26    Removed,
27    Other,
28}
29
30impl From<EventKind> for FsWatchEventKind {
31    fn from(kind: EventKind) -> Self {
32        match kind {
33            EventKind::Create(_) => FsWatchEventKind::Created,
34            EventKind::Modify(_) => FsWatchEventKind::Modified,
35            EventKind::Remove(_) => FsWatchEventKind::Removed,
36            _ => FsWatchEventKind::Other,
37        }
38    }
39}
40
41#[derive(Debug, Clone)]
42pub struct FsWatchEvent {
43    pub path: PathBuf,
44    pub kind: FsWatchEventKind,
45}
46
47/// Handle returned by `subscribe_file`/`subscribe_dir`. Holding this alive
48/// is not required (unlike the raw `notify::Watcher`, which must be kept
49/// alive by its owner) — the pool itself owns the underlying watcher.
50/// `unsubscribe` takes this by value so a caller can't accidentally
51/// unsubscribe the same handle twice.
52#[derive(Debug, Clone)]
53pub struct Subscription {
54    /// What's actually registered with the OS watcher — the parent
55    /// directory for a file subscription (see module doc: this is the
56    /// baked-in atomic-rename-safety rule), or the directory itself for a
57    /// directory subscription.
58    watch_target: PathBuf,
59}
60
61struct WatchEntry {
62    refcount: usize,
63    mode: RecursiveMode,
64}
65
66struct Inner {
67    watcher: Option<Box<dyn Watcher + Send>>,
68    targets: HashMap<PathBuf, WatchEntry>,
69    /// Polls WSL share paths (see [`Inner::watcher_for`]); built on first use.
70    share_poller: Option<Box<dyn Watcher + Send>>,
71    /// Where the share poller's events go: the same stream as `watcher`'s.
72    raw_tx: mpsc::UnboundedSender<notify::Result<notify::Event>>,
73}
74
75/// How often a WSL share folder is polled for changes.
76const SHARE_POLL_INTERVAL: Duration = Duration::from_secs(2);
77
78impl Inner {
79    /// The watcher for `target`. A WSL distro's folder through
80    /// `\\wsl.localhost` (`remote::wsl_fs`) gets a polling watcher: Windows
81    /// delivers no change notifications for that share (checked on Windows 11:
82    /// none for a change made in the distro, and none for one made through the
83    /// share), so a native watch there would succeed and stay silent.
84    fn watcher_for(&mut self, target: &Path) -> Option<&mut Box<dyn Watcher + Send>> {
85        if crate::backend::remote::wsl_fs::share_of(target).is_none() {
86            return self.watcher.as_mut();
87        }
88        if self.share_poller.is_none() {
89            let tx = self.raw_tx.clone();
90            let config = notify::Config::default().with_poll_interval(SHARE_POLL_INTERVAL);
91            match notify::PollWatcher::new(move |res: notify::Result<notify::Event>| { let _ = tx.send(res); }, config) {
92                Ok(w) => self.share_poller = Some(Box::new(w)),
93                Err(e) => tracing::warn!(error = %e, "fs_watch: no polling watcher for WSL folders"),
94            }
95        }
96        self.share_poller.as_mut()
97    }
98}
99
100pub struct FsWatchPool {
101    inner: Mutex<Inner>,
102    health: HealthState,
103    backend: WatchBackend,
104    tx: broadcast::Sender<FsWatchEvent>,
105}
106
107impl FsWatchPool {
108    /// Construct the pool and start its background event-bridging and
109    /// health-sweep tasks. Always succeeds — if even the `PollWatcher`
110    /// fallback fails to construct (practically never happens; it's pure
111    /// userspace polling), the pool still comes up with `watcher: None` and
112    /// every subscribe call fails cleanly into `degraded_paths` rather than
113    /// panicking or requiring every caller to handle an `Option<Arc<Self>>`
114    /// at the top level. Live-update is additive everywhere it's used.
115    pub fn new() -> Arc<Self> {
116        let (raw_tx, mut raw_rx) = mpsc::unbounded_channel::<notify::Result<notify::Event>>();
117        let (watcher, backend) = construct_watcher(raw_tx.clone());
118
119        let (broadcast_tx, _) = broadcast::channel(EVENT_CHANNEL_CAPACITY);
120
121        let this = Arc::new(Self {
122            inner: Mutex::new(Inner { watcher, targets: HashMap::new(), share_poller: None, raw_tx }),
123            health: HealthState::default(),
124            backend,
125            tx: broadcast_tx,
126        });
127
128        // Bridge notify's sync callback (already funneled into raw_rx by
129        // construct_watcher's closure) into the broadcast stream. Mirrors
130        // the sync-callback -> mpsc -> async-task shape all three existing
131        // watchers already use, just shared once here instead of three
132        // times.
133        let bridge = this.clone();
134        tokio::spawn(async move {
135            while let Some(res) = raw_rx.recv().await {
136                match res {
137                    Ok(event) => {
138                        let kind = FsWatchEventKind::from(event.kind);
139                        if matches!(kind, FsWatchEventKind::Other) {
140                            continue;
141                        }
142                        for path in event.paths {
143                            let _ = bridge.tx.send(FsWatchEvent { path, kind });
144                        }
145                    }
146                    Err(e) => bridge.handle_backend_error(e),
147                }
148            }
149        });
150
151        // Periodic self-healing sweep, scoped to already-degraded targets —
152        // see `sweep()`'s own doc comment for the full rationale (a
153        // healthy-looking target is deliberately left untouched, to avoid
154        // both a handle leak and a real event-coverage gap notify's Windows
155        // backend would otherwise cost on every tick).
156        let sweeper = this.clone();
157        tokio::spawn(async move {
158            let mut tick = tokio::time::interval(HEALTH_SWEEP_INTERVAL);
159            loop {
160                tick.tick().await;
161                sweeper.sweep();
162            }
163        });
164
165        this
166    }
167
168    /// Watch the file at `path` (specifically: its parent directory,
169    /// non-recursively — see module doc). Returns a fresh `Subscription`
170    /// even when the underlying OS watch is currently failing (tracked in
171    /// `degraded_paths` instead) — a degraded subscription still becomes
172    /// live automatically once retry/sweep succeeds, with no action needed
173    /// from the caller.
174    pub fn subscribe_file(self: &Arc<Self>, path: &Path) -> Subscription {
175        let canonical = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
176        let target = canonical.parent().map(Path::to_path_buf).unwrap_or(canonical.clone());
177        self.subscribe_target(target, RecursiveMode::NonRecursive)
178    }
179
180    /// Watch the directory at `path` directly (non-recursive — matching
181    /// `media_file_watcher.rs`'s existing behavior; extension/content
182    /// filtering is the caller's concern, not the pool's).
183    pub fn subscribe_dir(self: &Arc<Self>, path: &Path) -> Subscription {
184        let canonical = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
185        self.subscribe_target(canonical, RecursiveMode::NonRecursive)
186    }
187
188    /// Watch `path` and everything under it (widget packages: an edit deep in
189    /// a package folder reloads it).
190    pub fn subscribe_dir_recursive(self: &Arc<Self>, path: &Path) -> Subscription {
191        let canonical = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
192        self.subscribe_target(canonical, RecursiveMode::Recursive)
193    }
194
195    fn subscribe_target(self: &Arc<Self>, target: PathBuf, mode: RecursiveMode) -> Subscription {
196        let is_new = {
197            let mut inner = self.inner.lock().unwrap();
198            let entry = inner.targets.entry(target.clone()).or_insert_with(|| WatchEntry { refcount: 0, mode });
199            entry.refcount += 1;
200            entry.refcount == 1
201        };
202
203        if is_new {
204            self.start_watch(target.clone(), mode);
205        }
206
207        Subscription { watch_target: target }
208    }
209
210    /// Stop watching on behalf of `sub`. Idempotent-safe: unsubscribing the
211    /// same handle twice would underflow the refcount, so this takes `self`
212    /// by shared ref but `sub` by value specifically to discourage reuse —
213    /// callers that need multiple independent subscriptions to the same
214    /// path should call `subscribe_file`/`subscribe_dir` once per logical
215    /// subscriber, matching how `editor_file_watcher.rs` already tracks one
216    /// entry per `block_id` today.
217    pub fn unsubscribe(&self, sub: Subscription) {
218        let should_unwatch = {
219            let mut inner = self.inner.lock().unwrap();
220            let Some(entry) = inner.targets.get_mut(&sub.watch_target) else {
221                return;
222            };
223            entry.refcount = entry.refcount.saturating_sub(1);
224            let empty = entry.refcount == 0;
225            if empty {
226                inner.targets.remove(&sub.watch_target);
227            }
228            empty
229        };
230
231        if should_unwatch {
232            let mut inner = self.inner.lock().unwrap();
233            if let Some(w) = inner.watcher_for(&sub.watch_target) {
234                let _ = w.unwatch(&sub.watch_target);
235            }
236            drop(inner);
237            self.health.clear_degraded(&sub.watch_target);
238        }
239    }
240
241    /// Raw change events for every currently-watched target, pool-wide.
242    /// Each call returns an independent receiver — subscribe to this once
243    /// per domain module (not once per file), and filter down to the paths
244    /// that module actually cares about, same as today's per-watcher
245    /// `Inner.watched_paths` filtering.
246    pub fn events(&self) -> broadcast::Receiver<FsWatchEvent> {
247        self.tx.subscribe()
248    }
249
250    #[allow(dead_code)] // Diagnostics surface, SPEC_SHARED_FS_WATCHER_FRAMEWORK_2026_08_07.md §4 point 4.
251    pub fn health(&self) -> FsWatchHealth {
252        let active_watches = self.inner.lock().unwrap().targets.len();
253        FsWatchHealth {
254            backend: self.backend,
255            active_watches,
256            degraded_paths: self.health.snapshot(),
257        }
258    }
259
260    /// First attempt at a new target, plus a bounded retry-with-backoff if
261    /// it fails — see `RETRY_BACKOFF`'s doc comment. Runs the retries on a
262    /// spawned task so `subscribe_file`/`subscribe_dir` never blocks on it.
263    fn start_watch(self: &Arc<Self>, target: PathBuf, mode: RecursiveMode) {
264        let first_attempt = self.try_watch(&target, mode);
265        if first_attempt.is_ok() {
266            return;
267        }
268        let err = first_attempt.unwrap_err();
269        // A folder that does not exist yet (an agent's memory folder before the agent has written
270        // one) is expected, not a fault: no warning and no retry task. It stays degraded, and the
271        // periodic sweep watches it once it appears.
272        if !target.exists() {
273            tracing::debug!(path = %target.display(), "fs_watch: path does not exist yet, the sweep will watch it when it appears");
274            self.health.mark_degraded(target, err);
275            return;
276        }
277        tracing::warn!(path = %target.display(), error = %err, "fs_watch: initial watch failed, retrying with backoff");
278        self.health.mark_degraded(target.clone(), err);
279
280        let this = self.clone();
281        tokio::spawn(async move {
282            for delay in RETRY_BACKOFF {
283                tokio::time::sleep(delay).await;
284                // The subscription may have been torn down (refcount back to
285                // zero) while we were waiting — don't resurrect a watch
286                // nobody wants anymore.
287                if !this.inner.lock().unwrap().targets.contains_key(&target) {
288                    return;
289                }
290                match this.try_watch(&target, mode) {
291                    Ok(()) => {
292                        this.health.clear_degraded(&target);
293                        tracing::info!(path = %target.display(), "fs_watch: watch recovered after retry");
294                        return;
295                    }
296                    Err(e) => {
297                        this.health.mark_degraded(target.clone(), e);
298                    }
299                }
300            }
301            tracing::warn!(
302                path = %target.display(),
303                "fs_watch: still degraded after all retries — will keep retrying via the periodic health sweep"
304            );
305        });
306    }
307
308    fn try_watch(&self, target: &Path, mode: RecursiveMode) -> Result<(), String> {
309        let mut inner = self.inner.lock().unwrap();
310        let Some(watcher) = inner.watcher_for(target) else {
311            return Err("no fs watcher backend available".to_string());
312        };
313        watcher.watch(target, mode).map_err(|e| e.to_string())
314    }
315
316    /// Handle an async error surfaced by the `notify` backend's own callback
317    /// (piped through `raw_rx` in `Self::new`'s bridge task). Extracted out
318    /// of that task so a test can drive a real `notify::Error` through it
319    /// directly (reagent P2 on #2722: the original three sweep regression
320    /// tests all simulated degradation via a direct `health.mark_degraded`
321    /// call, so none of them actually exercised this fn or proved that
322    /// `notify::Error::paths` lines up with the exact `PathBuf` key
323    /// `inner.targets` uses — the assumption `sweep()`'s `is_degraded()`
324    /// filter depends on to ever re-arm a target that failed this way).
325    ///
326    /// `notify::Error` carries the affected path(s) when it can attribute
327    /// one; mark each degraded so the next sweep re-arms it. A path-less
328    /// error (rare — not attributable to any specific target) can only be
329    /// logged.
330    fn handle_backend_error(&self, e: notify::Error) {
331        tracing::warn!(error = %e, paths = ?e.paths, "fs_watch: backend reported an error");
332        for path in &e.paths {
333            self.health.mark_degraded(path.clone(), e.to_string());
334        }
335    }
336
337    /// Re-arm every currently-*degraded* target — the backstop that lets a
338    /// path recover from a failed `watch()` attempt (at `start_watch` time
339    /// or a prior sweep) without a dedicated retry loop running forever.
340    ///
341    /// **Deliberately does NOT touch a target that already looks healthy**
342    /// (codex P2 on #2722, revising this fn's first version): the original
343    /// fix here unconditionally called `unwatch()` then `watch()` on every
344    /// subscribed target every tick, reasoning that this was needed to
345    /// detect a watch that died *silently* (no error ever surfaced). Two
346    /// problems with that, both real:
347    /// 1. **The handle leak this fn exists to fix** — `notify` 7.0.0's
348    ///    Windows backend (`add_watch` in the vendored `windows.rs`) opens a
349    ///    brand-new `CreateFileW` handle + `CreateSemaphoreW` on *every*
350    ///    `watch()` call, unconditionally, and silently drops the previous
351    ///    entry's handles with no cleanup — see
352    ///    `docs/status/STATUS_FS_WATCH_SWEEP_HANDLE_LEAK_2026_08_22.md`.
353    /// 2. **A real coverage gap** — `unwatch()` then `watch()` leaves the
354    ///    target genuinely unwatched for the gap between the two calls.
355    ///    `memory::native_drift`'s slow-path reconciliation sweep backstops a
356    ///    missed event there, but `config_watcher_fs`, `EditorFileWatcher`,
357    ///    and `MediaFileWatcher` all rely solely on the broadcast stream —
358    ///    a create/modify landing in that gap would go unnoticed until some
359    ///    *later*, unrelated change on the same path happened to trigger a
360    ///    refresh.
361    ///
362    /// Skipping healthy targets fixes both: nothing is ever double-watched
363    /// (no leak) and a healthy watch is never touched (no gap). The
364    /// **honestly-bounded trade-off**: a watch that fails *silently* — dies
365    /// without `notify` or the OS ever reporting an error on it — is no
366    /// longer self-healed by this sweep, only a watch that's already known
367    /// degraded (an explicit prior failure). Accepted because a truly
368    /// silent death has no confirmed occurrence in this codebase's history
369    /// (the scenarios `HEALTH_SWEEP_INTERVAL`'s own doc comment lists —
370    /// inotify instance-limit churn, flaky network mounts — are Linux-
371    /// flavored concerns on a Windows-primary codebase), against a
372    /// certain, systematic cost (leak or gap, every target, every tick) for
373    /// every other watch the alternative would have imposed.
374    ///
375    /// **Race with concurrent `unsubscribe()` — closed by re-checking under
376    /// one held lock** (reagent P1, second review round on #2722): the
377    /// degraded-target list above is a snapshot; without re-verification, a
378    /// concurrent `unsubscribe()` dropping the last subscriber for one of
379    /// these targets between the snapshot and this loop's `watch()` call
380    /// would remove it from `targets` and `unwatch()` it, while this sweep's
381    /// in-flight `watch()` call still re-established a native watch for the
382    /// now-untracked path — orphaning exactly the handle pair this fn exists
383    /// to stop leaking, just via a race instead of per-tick re-watching.
384    /// Each target's re-check + `unwatch()` + `watch()` now happens under a
385    /// single `inner` lock acquisition (not `try_watch()`, which takes its
386    /// own lock and would deadlock if called while this one is held) — a
387    /// concurrent `unsubscribe()` either finishes its own removal entirely
388    /// before this runs (this loop then sees the target is gone and skips
389    /// it) or entirely after (its own `unwatch()` then correctly tears down
390    /// the watch this loop just re-armed) — `Mutex` serializes the two, so
391    /// no interleaving in between is possible.
392    fn sweep(&self) {
393        let targets: Vec<PathBuf> = {
394            let inner = self.inner.lock().unwrap();
395            inner
396                .targets
397                .keys()
398                .filter(|p| self.health.is_degraded(p))
399                .cloned()
400                .collect()
401        };
402        for target in targets {
403            self.rearm_if_still_subscribed(target);
404        }
405    }
406
407    /// The per-target half of a sweep: re-verify `target` is still
408    /// subscribed, then `unwatch()` + `watch()` it, all under one held
409    /// `inner` lock (see `sweep()`'s doc comment for why the re-check and
410    /// the single lock both matter). Split out from `sweep()`'s loop body
411    /// so a test can call it directly with a `target` captured *before* a
412    /// real `unsubscribe()` ran — deterministically reproducing "sweep
413    /// already decided to process this target, then it was removed before
414    /// the action ran" without needing to win a real thread-scheduling
415    /// race.
416    fn rearm_if_still_subscribed(&self, target: PathBuf) {
417        let mut inner = self.inner.lock().unwrap();
418        // Re-check: still subscribed? A concurrent unsubscribe() may have
419        // removed it since the caller's snapshot — don't resurrect a watch
420        // nobody wants anymore.
421        let Some(mode) = inner.targets.get(&target).map(|e| e.mode) else {
422            return;
423        };
424        let Some(w) = inner.watcher_for(&target) else {
425            return;
426        };
427        // Best-effort: a never-established watch has nothing to unwatch —
428        // the watch() call below (re)establishes it regardless of whether
429        // this succeeds.
430        let _ = w.unwatch(&target);
431        let result = w.watch(&target, mode).map_err(|e| e.to_string());
432        drop(inner);
433        match result {
434            Ok(()) => self.health.clear_degraded(&target),
435            Err(e) => self.health.mark_degraded(target, e),
436        }
437    }
438}
439
440/// Build the watcher backend: prefer the native OS backend
441/// (inotify/FSEvents/ReadDirectoryChangesW); fall back to `notify`'s
442/// stat-based `PollWatcher` if the native backend can't even construct
443/// (practically never on the platforms AgentMux ships for, but real on some
444/// restricted/containerized environments). Returns `(None, Native)` only if
445/// both fail to construct — recorded as `WatchBackend::Native` since that
446/// was the attempted backend; every `subscribe_*` call will immediately
447/// fail into `degraded_paths` until the process restarts, matching the
448/// existing three watchers' "live-update becomes unavailable, nothing else
449/// breaks" posture, just now with a health signal instead of silence.
450fn construct_watcher(
451    tx: mpsc::UnboundedSender<notify::Result<notify::Event>>,
452) -> (Option<Box<dyn Watcher + Send>>, WatchBackend) {
453    let tx_native = tx.clone();
454    match notify::recommended_watcher(move |res: notify::Result<notify::Event>| {
455        let _ = tx_native.send(res);
456    }) {
457        Ok(w) => return (Some(Box::new(w)), WatchBackend::Native),
458        Err(e) => {
459            tracing::warn!(error = %e, "fs_watch: native backend unavailable, falling back to polling");
460        }
461    }
462
463    let poll_config = notify::Config::default().with_poll_interval(Duration::from_secs(2));
464    match notify::PollWatcher::new(move |res: notify::Result<notify::Event>| { let _ = tx.send(res); }, poll_config) {
465        Ok(w) => (Some(Box::new(w)), WatchBackend::Polling),
466        Err(e) => {
467            tracing::error!(error = %e, "fs_watch: polling fallback also failed to construct — live-update unavailable this session");
468            (None, WatchBackend::Native)
469        }
470    }
471}
472
473#[cfg(test)]
474mod tests {
475    use super::*;
476    use std::time::Duration as StdDuration;
477
478    /// A WSL share folder is polled, whatever the native backend is, and every
479    /// other path keeps the native watcher.
480    #[cfg(windows)]
481    #[test]
482    fn a_wsl_share_folder_gets_the_polling_watcher() {
483        let (raw_tx, _raw_rx) = mpsc::unbounded_channel();
484        let mut inner = Inner { watcher: None, targets: HashMap::new(), share_poller: None, raw_tx };
485        assert!(inner.watcher_for(Path::new(r"C:\Users\me\proj")).is_none(), "no native backend here");
486        assert!(inner.watcher_for(Path::new(r"\\?\UNC\wsl.localhost\Ubuntu\home\u")).is_some());
487        assert!(inner.share_poller.is_some(), "built on first use");
488        assert!(inner.watcher_for(Path::new(r"\\wsl$\Debian\srv")).is_some(), "and shared");
489    }
490
491    /// End to end on a Windows machine with WSL: a file written inside a
492    /// distro shows up as an event for its folder watched through the share.
493    /// Needs a distro, so it is not run on CI. Run manually with the distro to
494    /// use: `WSL_TEST_DISTRO=Ubuntu cargo test -p agentmux-srv-core --lib
495    /// a_change_inside_a_distro_reaches_a_share_watch -- --ignored`
496    #[cfg(windows)]
497    #[tokio::test]
498    #[ignore]
499    async fn a_change_inside_a_distro_reaches_a_share_watch() {
500        let distro = std::env::var("WSL_TEST_DISTRO").unwrap_or_else(|_| "Ubuntu".to_string());
501        let dir = crate::backend::remote::wsl_fs::share_path(&distro, "/tmp");
502        // What `canonicalize` really returns for a share path is still one: the
503        // editor's write rule and the protected folders read that form.
504        let canonical = Path::new(&dir).canonicalize().expect("the share path resolves");
505        assert_eq!(
506            crate::backend::remote::wsl_fs::split_share(&canonical.to_string_lossy()).map(|s| s.linux),
507            Some("/tmp".to_string()),
508            "{}",
509            canonical.display()
510        );
511        let pool = FsWatchPool::new();
512        let mut events = pool.events();
513        let _sub = pool.subscribe_dir(Path::new(&dir));
514        let name = format!("am-share-watch-{}", std::process::id());
515        let status = std::process::Command::new("wsl.exe")
516            .args(["-d", &distro, "--exec", "sh", "-c", &format!("echo x > /tmp/{name}")])
517            .status()
518            .expect("wsl.exe runs");
519        assert!(status.success());
520        let seen = tokio::time::timeout(StdDuration::from_secs(10), async {
521            loop {
522                if let Ok(ev) = events.recv().await {
523                    if ev.path.to_string_lossy().ends_with(&name) {
524                        return ev;
525                    }
526                }
527            }
528        })
529        .await;
530        let _ = std::process::Command::new("wsl.exe")
531            .args(["-d", &distro, "--exec", "rm", "-f", &format!("/tmp/{name}")])
532            .status();
533        assert!(seen.is_ok(), "no event for {name} in {dir} within 10s");
534    }
535
536    /// A folder that is not there yet is degraded without a retry task (no warning either), and the
537    /// sweep watches it once it exists.
538    #[tokio::test]
539    async fn a_missing_folder_is_degraded_quietly_and_watched_once_it_appears() {
540        let pool = FsWatchPool::new();
541        let tmp = std::env::temp_dir().join("agentmux_fs_watch_pool_missing_folder_test");
542        let _ = std::fs::remove_dir_all(&tmp);
543
544        let sub = pool.subscribe_dir(&tmp);
545        assert!(pool.health.is_degraded(&sub.watch_target), "a missing folder cannot be watched yet");
546
547        std::fs::create_dir_all(&tmp).unwrap();
548        pool.sweep();
549        assert!(!pool.health.is_degraded(&sub.watch_target), "the sweep watches the folder once it exists");
550
551        pool.unsubscribe(sub);
552        let _ = std::fs::remove_dir_all(&tmp);
553    }
554
555    #[tokio::test]
556    async fn subscribe_unsubscribe_refcounting_does_not_panic() {
557        let pool = FsWatchPool::new();
558        let tmp = std::env::temp_dir().join("agentmux_fs_watch_pool_test");
559        std::fs::create_dir_all(&tmp).unwrap();
560
561        let sub1 = pool.subscribe_dir(&tmp);
562        let sub2 = pool.subscribe_dir(&tmp);
563        assert_eq!(pool.health().active_watches, 1, "two subscriptions to the same dir share one OS watch");
564
565        pool.unsubscribe(sub1);
566        assert_eq!(pool.health().active_watches, 1, "still watched — sub2 is still active");
567
568        pool.unsubscribe(sub2);
569        assert_eq!(pool.health().active_watches, 0, "last subscriber gone -> watch torn down");
570
571        let _ = std::fs::remove_dir_all(&tmp);
572    }
573
574    /// Regression test for reagent's P2 on #2722: the round-2 fix
575    /// (`handle_backend_error`, née an inline branch in the bridge task)
576    /// only helps `sweep()` re-arm a target if `notify::Error::paths`
577    /// actually lines up with the exact `PathBuf` key `inner.targets` uses
578    /// — otherwise `mark_degraded` records a path `is_degraded()` will
579    /// faithfully report as degraded, but that never matches any key
580    /// `sweep()`'s `targets.keys().filter(is_degraded)` iterates, so the
581    /// re-arm silently never happens for any *real* backend error. Uses a
582    /// real subscription's `watch_target` (produced by the same
583    /// `canonicalize()` path a live `notify` callback's error would need to
584    /// match) rather than a hand-built path, so this actually exercises
585    /// that assumption instead of just asserting `handle_backend_error`
586    /// calls `mark_degraded` (which the original three sweep tests already
587    /// covered indirectly by calling `mark_degraded` directly).
588    #[tokio::test]
589    async fn handle_backend_error_degrades_the_exact_target_key_sweep_looks_up() {
590        let pool = FsWatchPool::new();
591        let dir = std::env::temp_dir().join("agentmux_fs_watch_pool_backend_error_test");
592        let _ = std::fs::remove_dir_all(&dir);
593        std::fs::create_dir_all(&dir).unwrap();
594
595        let sub = pool.subscribe_dir(&dir);
596        let target = sub.watch_target.clone();
597        assert!(!pool.health.is_degraded(&target), "precondition: not degraded yet");
598
599        pool.handle_backend_error(notify::Error::generic("simulated backend error").add_path(target.clone()));
600
601        assert!(
602            pool.health.is_degraded(&target),
603            "handle_backend_error() must mark the exact watch_target key degraded \
604             so sweep()'s is_degraded() filter (which iterates inner.targets' own \
605             keys) actually picks it up — a mismatched path here would silently \
606             defeat the whole reagent-P1 fix for any real notify backend error"
607        );
608
609        pool.unsubscribe(sub);
610        let _ = std::fs::remove_dir_all(&dir);
611    }
612
613    #[tokio::test]
614    async fn subscribe_file_watches_the_parent_directory() {
615        let pool = FsWatchPool::new();
616        let dir = std::env::temp_dir().join("agentmux_fs_watch_pool_file_test");
617        std::fs::create_dir_all(&dir).unwrap();
618        let file = dir.join("thing.md");
619        std::fs::write(&file, "hello").unwrap();
620
621        let sub = pool.subscribe_file(&file);
622        assert_eq!(sub.watch_target, dir.canonicalize().unwrap());
623
624        pool.unsubscribe(sub);
625        let _ = std::fs::remove_dir_all(&dir);
626    }
627
628    #[tokio::test]
629    async fn a_change_event_is_observable_on_the_broadcast_stream() {
630        let pool = FsWatchPool::new();
631        let dir = std::env::temp_dir().join("agentmux_fs_watch_pool_event_test");
632        let _ = std::fs::remove_dir_all(&dir);
633        std::fs::create_dir_all(&dir).unwrap();
634        let file = dir.join("watched.md");
635        std::fs::write(&file, "v1").unwrap();
636
637        let mut events = pool.events();
638        let sub = pool.subscribe_file(&file);
639        // Give the native backend a moment to actually register before we
640        // write — otherwise this is a flaky "wrote before the watch was live"
641        // race, not a real assertion about the pool's behavior.
642        tokio::time::sleep(StdDuration::from_millis(200)).await;
643        std::fs::write(&file, "v2").unwrap();
644
645        let seen = tokio::time::timeout(StdDuration::from_secs(5), async {
646            loop {
647                match events.recv().await {
648                    Ok(ev) if ev.path.file_name() == file.file_name() => return true,
649                    Ok(_) => continue,
650                    Err(_) => return false,
651                }
652            }
653        })
654        .await
655        .unwrap_or(false);
656
657        assert!(seen, "expected to observe a change event for the watched file");
658
659        pool.unsubscribe(sub);
660        let _ = std::fs::remove_dir_all(&dir);
661    }
662
663    #[tokio::test]
664    async fn health_reports_the_constructed_backend() {
665        let pool = FsWatchPool::new();
666        // On every platform this actually runs on in CI, the native backend
667        // constructs successfully — this just pins that expectation rather
668        // than the (currently untestable-without-platform-mocking) fallback
669        // path, which recovery.rs's own unit tests cover at the bookkeeping
670        // level instead.
671        assert_eq!(pool.health().backend, WatchBackend::Native);
672    }
673
674    /// Regression test for
675    /// `docs/status/STATUS_FS_WATCH_SWEEP_HANDLE_LEAK_2026_08_22.md`, healthy
676    /// side: `sweep()` used to call `watch()` unconditionally on every
677    /// subscribed target on every `HEALTH_SWEEP_INTERVAL` tick, leaking a
678    /// File + Semaphore handle pair per call (see companion test below for
679    /// why) — the fix (codex P2 on #2722) is to skip a target entirely once
680    /// it's healthy, not just to `unwatch()` before re-`watch()`-ing it (that
681    /// still leaked nothing, but cost every other watcher a real event-
682    /// coverage gap). Simulates many sweep ticks on a healthy target and
683    /// asserts both that handle count does not grow *and* that a healthy
684    /// watch is never touched at all.
685    #[cfg(target_os = "windows")]
686    #[tokio::test]
687    async fn sweep_leaves_a_healthy_target_untouched() {
688        let pool = FsWatchPool::new();
689        let tmp = std::env::temp_dir().join("agentmux_fs_watch_pool_sweep_healthy_test");
690        let _ = std::fs::remove_dir_all(&tmp);
691        std::fs::create_dir_all(&tmp).unwrap();
692
693        let sub = pool.subscribe_dir(&tmp);
694        // Let the initial watch settle before measuring.
695        tokio::time::sleep(StdDuration::from_millis(100)).await;
696        assert!(!pool.health.is_degraded(&sub.watch_target), "a freshly-established watch must be healthy");
697
698        let pid = std::process::id();
699        let before = crate::backend::sysinfo::process_handle_count(pid)
700            .expect("own handle count must be queryable");
701
702        const SWEEPS: u32 = 200;
703        for _ in 0..SWEEPS {
704            pool.sweep();
705        }
706
707        let after = crate::backend::sysinfo::process_handle_count(pid)
708            .expect("own handle count must be queryable");
709        let grew_by = after.saturating_sub(before);
710
711        pool.unsubscribe(sub);
712        let _ = std::fs::remove_dir_all(&tmp);
713
714        assert!(
715            grew_by < SWEEPS / 2,
716            "handle count grew by {grew_by} over {SWEEPS} sweep() calls on a \
717             healthy target (before={before}, after={after}) — a healthy \
718             target must never be re-watched at all"
719        );
720    }
721
722    /// Companion to the test above: exercises the actual `unwatch()` +
723    /// `watch()` re-arm path that runs for a *degraded* target, proving that
724    /// path itself doesn't leak either (the original bug — `notify` 7.0.0's
725    /// Windows backend opens a new `CreateFileW` + `CreateSemaphoreW` on
726    /// every `watch()` call, unconditionally, and its internal map's
727    /// `insert()` silently drops the previous entry's handles with no
728    /// cleanup). Forces the target into `degraded` state directly before
729    /// every sweep so each call really re-arms it, then asserts handle
730    /// count does not grow linearly with sweep count.
731    #[cfg(target_os = "windows")]
732    #[tokio::test]
733    async fn sweep_does_not_leak_a_handle_pair_per_call_for_a_degraded_target() {
734        let pool = FsWatchPool::new();
735        let tmp = std::env::temp_dir().join("agentmux_fs_watch_pool_sweep_degraded_test");
736        let _ = std::fs::remove_dir_all(&tmp);
737        std::fs::create_dir_all(&tmp).unwrap();
738
739        let sub = pool.subscribe_dir(&tmp);
740        tokio::time::sleep(StdDuration::from_millis(100)).await;
741        let target = sub.watch_target.clone();
742
743        let pid = std::process::id();
744        let before = crate::backend::sysinfo::process_handle_count(pid)
745            .expect("own handle count must be queryable");
746
747        const SWEEPS: u32 = 200;
748        for _ in 0..SWEEPS {
749            // Force degraded so this tick's sweep() actually re-arms the
750            // watch (unwatch() + watch()), same as it would for a real
751            // failure — clear_degraded() on success would otherwise make
752            // only the first sweep do real work.
753            pool.health.mark_degraded(target.clone(), "simulated for test".to_string());
754            pool.sweep();
755        }
756
757        let after = crate::backend::sysinfo::process_handle_count(pid)
758            .expect("own handle count must be queryable");
759        let grew_by = after.saturating_sub(before);
760
761        pool.unsubscribe(sub);
762        let _ = std::fs::remove_dir_all(&tmp);
763
764        assert!(
765            grew_by < SWEEPS / 2,
766            "handle count grew by {grew_by} over {SWEEPS} sweep() calls on a \
767             degraded target (before={before}, after={after}) — the \
768             unwatch()-before-watch() re-arm path must not leak a \
769             File+Semaphore pair per call"
770        );
771    }
772
773    /// Regression test for reagent's second-round P1 on #2722: `sweep()`
774    /// snapshots the degraded-target list, then acts on each one later.
775    /// Without re-verification, a concurrent `unsubscribe()` dropping the
776    /// last subscriber for one of these targets in that window would remove
777    /// it from `targets` (and `unwatch()` it), while this sweep's own
778    /// in-flight `watch()` call still re-established a native watch for the
779    /// now-untracked path — orphaning the handle pair forever, since nothing
780    /// is left to `unwatch()` it again.
781    ///
782    /// **Deterministic, not a timing-based race** (an earlier version of
783    /// this test tried to actually race `sweep()` against `unsubscribe()`
784    /// on separate tasks — unreliable: `unsubscribe()`'s critical section is
785    /// so much shorter than `spawn_blocking`'s own scheduling latency that
786    /// it essentially always completed entirely before or after `sweep()`
787    /// ran, never in the middle, so it couldn't reliably exercise the
788    /// vulnerable window either way). Instead, `sweep()`'s per-target action
789    /// is split into its own method
790    /// ([`rearm_if_still_subscribed`](Self::rearm_if_still_subscribed)) so
791    /// this test can call it directly with a target captured *before* a
792    /// real `unsubscribe()` runs — deterministically reproducing "sweep
793    /// already decided to process this target, then it was removed before
794    /// the action ran" without needing to win any race at all.
795    /// **Asserts the guard directly, not via OS handle counts.** An earlier
796    /// version of this test measured `process_handle_count()` across 200
797    /// rounds and asserted the total grew by less than half that. The
798    /// measurement is process-GLOBAL, so in a full `cargo test` run the
799    /// ~3400 other tests executing in parallel contribute their own file,
800    /// socket and thread churn to the same window — it failed in CI and
801    /// locally at `grew_by=103` against a threshold of 100 while passing in
802    /// isolation, i.e. it was measuring the test suite, not the code under
803    /// test. (It also had to be `#[cfg(target_os = "windows")]`, since
804    /// `process_handle_count` is Windows-only, so two of three platforms
805    /// got no protection at all.)
806    ///
807    /// The guard's observable signature is used instead:
808    /// `rearm_if_still_subscribed()` only ever touches degraded state on a
809    /// path that actually reaches `watch()` — `clear_degraded` on success,
810    /// `mark_degraded` on failure. Returning early, as it must for an
811    /// unsubscribed target, leaves the entry untouched. So the target is
812    /// marked degraded with a sentinel reason *after* the unsubscribe, and
813    /// the assertion is that the reason is still exactly that sentinel:
814    /// deterministic, unaffected by anything else running, and portable.
815    ///
816    /// **The REASON, not just the presence of a degraded entry** (Codex P2
817    /// on #3235, fixed here). Asserting only `is_degraded()` conflated two
818    /// different outcomes, because `mark_degraded` is also what runs when
819    /// `watch()` FAILS — so a bypassed guard whose `watch()` call errored
820    /// (permissions, resource exhaustion, an unavailable backend) left the
821    /// flag set and passed the test, which is precisely the
822    /// passes-under-broken-logic failure mode #3235 set out to remove.
823    /// Comparing the reason separates all three cases: sentinel intact =
824    /// returned early; entry gone = `watch()` succeeded; any other string =
825    /// `watch()` failed. The last two both mean the guard was bypassed.
826    ///
827    /// The `watcher.is_some()` precondition closes the remaining vacuous
828    /// path — a pool whose watcher failed to construct returns early at a
829    /// *different* guard, so the probe would hold for a reason unrelated to
830    /// what this test checks.
831    #[tokio::test]
832    async fn sweep_does_not_resurrect_a_target_unsubscribed_after_being_snapshotted() {
833        let pool = FsWatchPool::new();
834        let dir = std::env::temp_dir().join("agentmux_fs_watch_pool_sweep_race_test");
835        let _ = std::fs::remove_dir_all(&dir);
836        std::fs::create_dir_all(&dir).unwrap();
837
838        // A watcher that failed to construct makes `rearm_if_still_subscribed()`
839        // return early at its `inner.watcher` guard regardless of the
840        // targets re-check this test is about — which would pass the probe
841        // below vacuously. `FsWatchPool::new()` documents `watcher: None` as
842        // reachable, so assert it explicitly rather than silently skipping.
843        assert!(
844            pool.inner.lock().unwrap().watcher.is_some(),
845            "precondition: the pool must have a live watcher, or the stale-rearm \
846             path short-circuits before the re-check this test exercises"
847        );
848
849        let sub = pool.subscribe_dir(&dir);
850        // Captured now, exactly as sweep()'s own snapshot phase would —
851        // before the real unsubscribe() below runs.
852        let target = sub.watch_target.clone();
853
854        // The real teardown — exactly what a concurrent unsubscribe() does,
855        // landing (for this test) strictly *after* the target was
856        // "snapshotted" above but strictly *before* the re-arm action below.
857        pool.unsubscribe(sub);
858
859        // Mark degraded AFTER the unsubscribe, which clears the flag for a
860        // target it drops. This is the probe — see the doc comment: only a
861        // call that reaches `watch()` touches this entry again, and the
862        // REASON distinguishes which way it went.
863        const PROBE_REASON: &str = "probe sentinel — must survive a correctly-guarded stale rearm";
864        pool.health.mark_degraded(target.clone(), PROBE_REASON.to_string());
865
866        // sweep()'s per-target action, called directly with the stale
867        // (now-unsubscribed) target — the exact call sweep()'s loop would
868        // have made had it reached this target after losing the race.
869        pool.rearm_if_still_subscribed(target.clone());
870
871        // The REASON, not merely the presence of a degraded entry — see the
872        // doc comment for why the boolean alone is not a sufficient probe.
873        let reason_after = pool
874            .health
875            .snapshot()
876            .into_iter()
877            .find(|(p, _)| p == &target)
878            .map(|(_, reason)| reason);
879        let still_untracked = !pool.inner.lock().unwrap().targets.contains_key(&target);
880
881        let _ = std::fs::remove_dir_all(&dir);
882
883        assert!(
884            still_untracked,
885            "precondition: the target must still be absent from `targets` after \
886             unsubscribe — otherwise this test isn't exercising the stale-rearm \
887             path at all"
888        );
889        assert_eq!(
890            reason_after.as_deref(),
891            Some(PROBE_REASON),
892            "rearm_if_still_subscribed() reached watch() for a target that was \
893             unsubscribed after being snapshotted. The degraded reason is the probe: \
894             it is still `{PROBE_REASON}` only if the function returned early without \
895             touching health state. `None` means watch() SUCCEEDED (clear_degraded); \
896             any other string means watch() FAILED (mark_degraded overwrote the \
897             reason with the backend error). Either way the guard was bypassed and a \
898             native watch nobody tracks was re-established, orphaning the handle pair \
899             with nothing left to ever unwatch() it"
900        );
901    }
902}