openlatch-client 0.6.10

OpenLatch runtime enforcement node — the capture-and-enforce adapter that evaluates every covered action against a coding agent's Autonomy Zone before it runs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
//! Filesystem watcher for the configuration plane.
//!
//! Wraps `notify-debouncer-full` with a 500 ms debounce window so VS Code /
//! Vim / JetBrains atomic-save patterns collapse into one logical event.
//! When inotify exhausts its watch budget (`MaxFilesWatch` ≡ ENOSPC) the
//! affected directories fall back to `notify::PollWatcher` with a 5 s interval.
//!
//! **Watches are live, not armed once.** [`watch_plan`] derives the directories
//! to watch from the manifest and the registered project roots; the monitor
//! recomputes it whenever a directory appears or disappears, a project root
//! registers, or the detection tick fires, and [`WatchControl::apply`] arms the
//! difference. A file created after daemon start — under a directory that did
//! not exist then, or in a project opened since — is reported when it lands,
//! not at the next 12 h rescan.
//!
//! Arming runs on a dedicated thread that owns the debouncer: FSEvents' `watch`
//! blocks ~300 ms per directory, which must never hold a tokio worker.

use std::collections::BTreeMap;
use std::path::{Component, Path, PathBuf};
use std::sync::{Arc, RwLock};
use std::time::Duration;

use notify::{ErrorKind as NotifyErrorKind, EventKind, RecursiveMode, Watcher};
use notify_debouncer_full::{
    new_debouncer_opt, DebounceEventResult, DebouncedEvent, Debouncer, RecommendedCache,
};
use tokio::sync::{mpsc, oneshot};

use super::manifest::{expand_path, AgentPath, Manifest};
use super::monitor::ConfigChangeRequest;

/// Production debounce window for FS events. Aligned with the tamper-plane
/// watcher so the two surfaces share a single recency budget.
const PRODUCTION_DEBOUNCE_MS: u64 = 500;
/// PollWatcher fallback cadence used when inotify is exhausted (ENOSPC).
const POLL_FALLBACK_INTERVAL_SECS: u64 = 5;

/// At most this many symlinked directories get a watch of their own per plan,
/// and at most [`MAX_WALK_ENTRIES`] directory entries are looked at for them in
/// all: a repository full of links, or of nested directories, must not be able
/// to spend the watch budget or turn every re-plan into a disk walk.
const MAX_LINKED_DIRS: usize = 64;
const MAX_WALK_ENTRIES: usize = 4096;

/// What one plan may still spend on symlinked directories.
#[derive(Default)]
struct LinkBudget {
    links: usize,
    entries: usize,
}

impl LinkBudget {
    fn spent(&self) -> bool {
        self.links >= MAX_LINKED_DIRS || self.entries >= MAX_WALK_ENTRIES
    }
}

/// Whether `$HOME` itself must never be watched. On macOS an FSEvents stream
/// covers its whole subtree whatever the recursive mode — notify filters
/// afterwards — so a watch on `$HOME` receives events from `~/Desktop` and
/// `~/Downloads` and makes the OS ask the user to grant the daemon those
/// folders. inotify and ReadDirectoryChangesW have no such reach, and a
/// file-level inotify watch would lose an atomic save, so elsewhere the
/// parent-directory watch stays.
const HOME_IS_PRIVATE: bool = cfg!(target_os = "macos");

/// Directories to watch, each mapped to whether the watch is recursive.
pub(crate) type WatchPlan = BTreeMap<PathBuf, bool>;

/// The directories that cover every manifest path, user scope and each
/// registered project root.
///
/// - An exact file is covered by its parent directory, non-recursively.
/// - A glob is covered by its static prefix — the deepest directory with no
///   wildcard in it: non-recursively when the rest of the pattern is one
///   segment (`rules/*.md`), recursively when it is deeper
///   (`skills/*/SKILL.md`), so a skill directory created later is seen.
/// - A directory that does not exist yet is covered by its nearest existing
///   ancestor, non-recursively — a sentinel whose `Create` event makes the
///   monitor recompute the plan. A project's sentinel never climbs above the
///   project root.
/// - A project root is always watched, non-recursively — never recursive on it,
///   `$HOME` or `/`: a repository is watched below its top level only where the
///   manifest names a subdirectory.
/// - On macOS `$HOME` itself is never watched ([`HOME_IS_PRIVATE`]): a file
///   directly in it is watched on its own, and a missing directory below it
///   gets no sentinel — the detection tick's re-plan arms it once it exists.
pub(crate) fn watch_plan(manifest: &Manifest, project_roots: &[PathBuf]) -> WatchPlan {
    watch_plan_from(manifest, project_roots, dirs::home_dir())
}

/// [`watch_plan`] with `$HOME` passed in.
fn watch_plan_from(
    manifest: &Manifest,
    project_roots: &[PathBuf],
    home: Option<PathBuf>,
) -> WatchPlan {
    let mut plan = WatchPlan::new();
    let mut links = LinkBudget::default();
    for agent in &manifest.agents {
        for ap in &agent.paths {
            if ap.is_project_scoped() {
                for root in project_roots {
                    // The root itself, non-recursively: its top-level files,
                    // and the deletion of any directory below it.
                    cover_template(
                        &mut plan,
                        &mut links,
                        &root.join("*"),
                        Some(root),
                        home.as_deref(),
                    );
                    for rel in &ap.paths_relative {
                        cover_template(
                            &mut plan,
                            &mut links,
                            &root.join(rel),
                            Some(root),
                            home.as_deref(),
                        );
                    }
                    for glob in &ap.paths_glob_relative {
                        cover_template(
                            &mut plan,
                            &mut links,
                            &root.join(glob),
                            Some(root),
                            home.as_deref(),
                        );
                    }
                }
                continue;
            }
            let templates = ap
                .paths
                .iter()
                .chain(ap.json_slice_paths.iter().map(|s| &s.path))
                .chain(ap.paths_glob.iter());
            for template in templates {
                if let Ok(expanded) = expand_path(template, None) {
                    cover_template(&mut plan, &mut links, &expanded, None, home.as_deref());
                }
            }
        }
    }
    drop_covered(plan)
}

/// Add the directory covering one expanded path or glob to `plan`.
fn cover_template(
    plan: &mut WatchPlan,
    links: &mut LinkBudget,
    pattern: &Path,
    floor: Option<&Path>,
    home: Option<&Path>,
) {
    let (dir, recursive) = match glob_split(pattern) {
        Some((prefix, rest)) => (prefix, rest > 1),
        None => match pattern.parent() {
            Some(parent) => (parent.to_path_buf(), false),
            None => return,
        },
    };
    let Some((anchor, recursive)) = resolve_anchor(&dir, recursive, floor, home) else {
        return;
    };
    if HOME_IS_PRIVATE && Some(anchor.as_path()) == home {
        // An exact file directly in `$HOME` (`~/.claude.json`) is watched on
        // its own — FSEvents is path-based, so an atomic save is still seen.
        // Anything else that lands here (a sentinel for a missing `~/.agents`,
        // a project opened at `$HOME`) is left to the detection tick's re-plan.
        if glob_split(pattern).is_none() && pattern.is_file() {
            plan.entry(pattern.to_path_buf()).or_insert(false);
        }
        return;
    }
    if recursive {
        // The pattern's directory segments below the prefix: how deep a
        // symlinked directory can sit and still hold a match.
        let depth = glob_split(pattern).map_or(0, |(_, rest)| rest - 1);
        cover_linked_dirs(plan, links, &anchor, depth, floor, home);
    }
    *plan.entry(anchor).or_insert(false) |= recursive;
}

/// A recursive watch never follows a symlink ([`watcher_config`]), so each
/// symlinked directory within `depth` levels of `dir` gets a watch of its own —
/// recursive when its target is [`safe_to_recurse`], non-recursive otherwise.
/// A plugin or skill installed as a link is then still reported live.
fn cover_linked_dirs(
    plan: &mut WatchPlan,
    links: &mut LinkBudget,
    dir: &Path,
    depth: usize,
    floor: Option<&Path>,
    home: Option<&Path>,
) {
    if depth == 0 {
        return;
    }
    let Ok(entries) = std::fs::read_dir(dir) else {
        return;
    };
    for entry in entries.flatten() {
        if links.spent() {
            return;
        }
        links.entries += 1;
        let path = entry.path();
        let Ok(kind) = entry.file_type() else {
            continue;
        };
        if kind.is_symlink() {
            if path.is_dir() {
                links.links += 1;
                let recursive = depth > 1 && safe_to_recurse(&path, home, floor);
                *plan.entry(path).or_insert(false) |= recursive;
            }
        } else if kind.is_dir() {
            cover_linked_dirs(plan, links, &path, depth - 1, floor, home);
        }
    }
}

/// Split a pattern at its first wildcard segment: the static prefix and the
/// number of segments from there on. `None` when the pattern has no wildcard.
fn glob_split(pattern: &Path) -> Option<(PathBuf, usize)> {
    let components: Vec<Component> = pattern.components().collect();
    let first = components.iter().position(|c| {
        c.as_os_str()
            .to_string_lossy()
            .contains(['*', '?', '[', '{'])
    })?;
    let prefix: PathBuf = components[..first].iter().collect();
    Some((prefix, components.len() - first))
}

/// The directory that actually gets the watch: `dir` itself when it exists,
/// otherwise its nearest existing ancestor (non-recursive), bounded below by
/// `floor`. `None` when nothing worth watching exists.
fn resolve_anchor(
    dir: &Path,
    recursive: bool,
    floor: Option<&Path>,
    home: Option<&Path>,
) -> Option<(PathBuf, bool)> {
    let mut anchor = dir;
    let mut recursive = recursive;
    while !anchor.is_dir() {
        recursive = false;
        anchor = anchor.parent()?;
        if floor.is_some_and(|f| !anchor.starts_with(f)) {
            return None;
        }
    }
    // The filesystem root covers nothing a manifest names.
    anchor.parent()?;
    if Some(anchor) == home || Some(anchor) == floor || !safe_to_recurse(anchor, home, floor) {
        recursive = false;
    }
    Some((anchor.to_path_buf(), recursive))
}

/// Whether a recursive watch on `anchor` stays where it is spelled. A symlink
/// anywhere on the path can point it at `/` or `$HOME` — a repository's
/// `.agents/skills -> /` would otherwise watch the whole disk and exhaust
/// inotify — so the resolved directory must not contain `$HOME` or be `/`, a
/// symlink must resolve inside `$HOME`, and a project anchor must not resolve
/// to its project or above it.
fn safe_to_recurse(anchor: &Path, home: Option<&Path>, floor: Option<&Path>) -> bool {
    let Ok(real) = std::fs::canonicalize(anchor) else {
        return false;
    };
    if real.parent().is_none() {
        return false;
    }
    let real_home = home.and_then(|h| std::fs::canonicalize(h).ok());
    if real_home.as_ref().is_some_and(|h| h.starts_with(&real)) {
        return false;
    }
    // A link is followed recursively only into the user's own files: one at
    // `/usr` or `/System` is not `/`, and would still watch half the disk.
    if anchor.is_symlink() && !real_home.is_some_and(|h| real.starts_with(h)) {
        return false;
    }
    // A project's link may point outside it (a shared skills checkout), never
    // at the repository itself or above it.
    match floor.map(std::fs::canonicalize) {
        Some(Ok(real_floor)) => !real_floor.starts_with(&real),
        Some(Err(_)) => false,
        None => true,
    }
}

/// Never follow a symlink below a recursive watch: a real `skills/` directory
/// holding `x -> /` would otherwise put the whole disk under the watch, which
/// `safe_to_recurse` only checks for the anchor itself.
fn watcher_config() -> notify::Config {
    notify::Config::default().with_follow_symlinks(false)
}

/// Drop every directory a recursive ancestor already covers — but never a
/// symlinked one, which that ancestor does not follow.
fn drop_covered(plan: WatchPlan) -> WatchPlan {
    let recursive: Vec<PathBuf> = plan
        .iter()
        .filter(|(_, r)| **r)
        .map(|(d, _)| d.clone())
        .collect();
    plan.into_iter()
        .filter(|(dir, _)| {
            dir.is_symlink() || !recursive.iter().any(|r| dir != r && dir.starts_with(r))
        })
        .collect()
}

/// Handle to the watcher thread. Cloneable; the thread stops, and every
/// watch with it, once the last handle is dropped.
#[derive(Clone)]
pub struct WatchControl {
    tx: std::sync::mpsc::Sender<WatchCmd>,
}

enum WatchCmd {
    Apply(WatchPlan, oneshot::Sender<Applied>),
}

/// What one [`WatchControl::apply`] changed.
#[derive(Debug, Default)]
pub(crate) struct Applied {
    /// Directories newly armed: scan them for files created before the watch.
    pub armed: Vec<PathBuf>,
    /// Armed directories that no longer exist.
    pub vanished: Vec<PathBuf>,
}

impl WatchControl {
    /// Make the armed set equal `plan`.
    pub(crate) async fn apply(&self, plan: WatchPlan) -> Applied {
        let (reply_tx, reply_rx) = oneshot::channel();
        if self.tx.send(WatchCmd::Apply(plan, reply_tx)).is_err() {
            return Applied::default();
        }
        reply_rx.await.unwrap_or_default()
    }
}

/// Start the watcher thread. It arms nothing until the first
/// [`WatchControl::apply`].
pub fn spawn_watch_thread(
    request_tx: mpsc::Sender<ConfigChangeRequest>,
    debounce_ms: u64,
) -> anyhow::Result<WatchControl> {
    let (tx, rx) = std::sync::mpsc::channel::<WatchCmd>();
    std::thread::Builder::new()
        .name("ol-config-watch".into())
        .spawn(move || {
            let mut armer = Armer::new(request_tx, debounce_ms);
            while let Ok(WatchCmd::Apply(plan, reply)) = rx.recv() {
                let _ = reply.send(armer.reconcile(plan));
            }
        })?;
    Ok(WatchControl { tx })
}

/// Canonical spelling → watched spelling of every armed directory whose two
/// differ. FSEvents reports canonical paths (`/private/var/...` for a watch on
/// `/var/...`); events are rewritten to the spelling the manifest expands to.
type Aliases = Arc<RwLock<Vec<(PathBuf, PathBuf)>>>;

/// Owns the watchers; lives on the watcher thread.
struct Armer {
    request_tx: mpsc::Sender<ConfigChangeRequest>,
    debouncer: Option<Debouncer<notify::RecommendedWatcher, RecommendedCache>>,
    poll: Option<notify::PollWatcher>,
    /// Armed directory → (recursive, on the poll fallback).
    armed: BTreeMap<PathBuf, (bool, bool)>,
    aliases: Aliases,
}

impl Armer {
    fn new(request_tx: mpsc::Sender<ConfigChangeRequest>, debounce_ms: u64) -> Self {
        let aliases: Aliases = Arc::default();
        let cb_tx = request_tx.clone();
        let cb_aliases = aliases.clone();
        let debounce_clamped = debounce_ms.clamp(50, 5000).max(PRODUCTION_DEBOUNCE_MS / 5);
        let debouncer = new_debouncer_opt::<_, notify::RecommendedWatcher, _>(
            Duration::from_millis(debounce_clamped),
            None,
            move |res: DebounceEventResult| match res {
                Ok(events) => {
                    for ev in events {
                        if let Some(req) = event_to_request(&ev, &cb_aliases) {
                            if cb_tx.try_send(req).is_err() {
                                tracing::warn!(
                                    "config_monitor: request channel full — skipping fs event"
                                );
                            }
                        }
                    }
                }
                Err(errors) => {
                    for e in errors {
                        tracing::debug!(error = %e, "config_monitor: debouncer reported error");
                    }
                }
            },
            RecommendedCache::new(),
            watcher_config(),
        );
        let debouncer = match debouncer {
            Ok(d) => Some(d),
            Err(e) => {
                tracing::error!(
                    code = crate::error::ERR_INVENTORY_WATCHER_FAILED,
                    error = %e,
                    "failed to create config_monitor debouncer; falling back to poll-only"
                );
                crate::telemetry::capture_global(
                    crate::telemetry::Event::config_watcher_init_failed("other", None),
                );
                None
            }
        };
        Self {
            request_tx,
            debouncer,
            poll: None,
            armed: BTreeMap::new(),
            aliases,
        }
    }

    fn reconcile(&mut self, plan: WatchPlan) -> Applied {
        let vanished: Vec<PathBuf> = self
            .armed
            .keys()
            .filter(|dir| !dir.exists())
            .cloned()
            .collect();
        let stale: Vec<PathBuf> = self
            .armed
            .iter()
            .filter(|(dir, (recursive, _))| plan.get(*dir) != Some(recursive))
            .map(|(dir, _)| dir.clone())
            .collect();
        for dir in stale {
            if let Some((_, polled)) = self.armed.remove(&dir) {
                // A deleted directory's watch may already be gone; nothing to do.
                let _ = if polled {
                    self.poll.as_mut().map(|p| p.unwatch(&dir))
                } else {
                    self.debouncer.as_mut().map(|d| d.unwatch(&dir))
                };
            }
        }

        let mut armed_now = Vec::new();
        for (dir, recursive) in plan {
            if self.armed.contains_key(&dir) {
                continue;
            }
            if let Some(polled) = self.arm(&dir, recursive) {
                self.armed.insert(dir.clone(), (recursive, polled));
                armed_now.push(dir);
            }
        }

        let aliases = self
            .armed
            .keys()
            .filter_map(|dir| {
                let canonical = std::fs::canonicalize(dir).ok()?;
                (canonical != *dir).then(|| (canonical, dir.clone()))
            })
            .collect();
        if let Ok(mut guard) = self.aliases.write() {
            *guard = aliases;
        }
        Applied {
            armed: armed_now,
            vanished,
        }
    }

    /// Arm one directory. `Some(on_poll)` on success; `None` leaves it
    /// unarmed so the next plan retries.
    fn arm(&mut self, dir: &Path, recursive: bool) -> Option<bool> {
        let mode = if recursive {
            RecursiveMode::Recursive
        } else {
            RecursiveMode::NonRecursive
        };
        if let Some(debouncer) = self.debouncer.as_mut() {
            match debouncer.watch(dir, mode) {
                Ok(()) => return Some(false),
                Err(e) if matches!(e.kind, NotifyErrorKind::MaxFilesWatch) => {
                    tracing::warn!(
                        code = crate::error::ERR_INVENTORY_WATCHER_FAILED,
                        path = %dir.display(),
                        "inotify max_user_watches exhausted; falling back to PollWatcher"
                    );
                    crate::telemetry::capture_global(
                        crate::telemetry::Event::config_watcher_init_failed("enospc", None),
                    );
                }
                Err(e) => {
                    tracing::warn!(
                        code = crate::error::ERR_INVENTORY_WATCHER_FAILED,
                        path = %dir.display(),
                        error = %e,
                        "config_monitor: watcher failed for path; skipping"
                    );
                    crate::telemetry::capture_global(
                        crate::telemetry::Event::config_watcher_init_failed(
                            os_error_class(&e),
                            None,
                        ),
                    );
                    return None;
                }
            }
        }
        let poll = match self.poll.as_mut() {
            Some(poll) => poll,
            None => self.poll.insert(self.new_poll_watcher()?),
        };
        match poll.watch(dir, mode) {
            Ok(()) => Some(true),
            Err(e) => {
                tracing::warn!(
                    path = %dir.display(),
                    error = %e,
                    "config_monitor: PollWatcher failed for fallback path"
                );
                None
            }
        }
    }

    fn new_poll_watcher(&self) -> Option<notify::PollWatcher> {
        let cfg = watcher_config()
            .with_poll_interval(Duration::from_secs(POLL_FALLBACK_INTERVAL_SECS))
            .with_compare_contents(true);
        let cb_tx = self.request_tx.clone();
        let cb_aliases = self.aliases.clone();
        notify::PollWatcher::new(
            move |res: notify::Result<notify::Event>| {
                if let Ok(ev) = res {
                    if let Some(req) = native_event_to_request(&ev, &cb_aliases) {
                        if cb_tx.try_send(req).is_err() {
                            tracing::warn!(
                                "config_monitor: request channel full — skipping poll event"
                            );
                        }
                    }
                }
            },
            cfg,
        )
        .inspect_err(|e| {
            tracing::warn!(error = %e, "config_monitor: PollWatcher could not be created");
        })
        .ok()
    }
}

/// Expand a glob pattern against the filesystem. Failures (invalid pattern,
/// I/O) return an empty Vec; the watcher loop logs nothing because missing
/// glob matches are normal (user has no skills directory yet).
pub(crate) fn glob_expand(pattern: &Path) -> Vec<PathBuf> {
    let pattern_str = match pattern.to_str() {
        Some(s) => s,
        None => return Vec::new(),
    };
    match glob::glob(pattern_str) {
        Ok(iter) => iter.flatten().collect(),
        Err(e) => {
            tracing::debug!(
                pattern = %pattern.display(),
                error = %e,
                "config_monitor: glob expansion failed"
            );
            Vec::new()
        }
    }
}

fn event_to_request(ev: &DebouncedEvent, aliases: &Aliases) -> Option<ConfigChangeRequest> {
    native_event_to_request(&ev.event, aliases)
}

fn native_event_to_request(ev: &notify::Event, aliases: &Aliases) -> Option<ConfigChangeRequest> {
    let paths = || unalias(&ev.paths, aliases);
    match ev.kind {
        EventKind::Create(_) => Some(ConfigChangeRequest::FsAdded(paths())),
        EventKind::Modify(_) => Some(ConfigChangeRequest::FsModified(paths())),
        EventKind::Remove(_) => Some(ConfigChangeRequest::FsRemoved(paths())),
        _ => None,
    }
}

/// Rewrite each event path from a directory's canonical spelling to every
/// spelling it was watched under. Two watched directories can resolve to one
/// (a linked plugin and the checkout it points at): each must see the event,
/// so none is picked over another. The event's own spelling is kept too: the
/// real directory may be watched under its own name as well.
fn unalias(paths: &[PathBuf], aliases: &Aliases) -> Vec<PathBuf> {
    let Ok(aliases) = aliases.read() else {
        return paths.to_vec();
    };
    let mut out = Vec::with_capacity(paths.len());
    for p in paths {
        for (canonical, watched) in aliases.iter() {
            if let Ok(rest) = p.strip_prefix(canonical) {
                out.push(watched.join(rest));
            }
        }
        out.push(p.clone());
    }
    out
}

fn os_error_class(e: &notify::Error) -> &'static str {
    match e.kind {
        NotifyErrorKind::MaxFilesWatch => "enospc",
        NotifyErrorKind::PathNotFound => "not_found",
        NotifyErrorKind::Io(_) => "io",
        _ => "other",
    }
}

/// Whether a path matches one of the manifest's exclude patterns. Used by
/// the monitor loop to suppress events for excluded paths (cache files,
/// session locks, OAuth blobs).
pub(crate) fn is_excluded(path: &Path, agent_path: &AgentPath, manifest: &Manifest) -> bool {
    // Find the parent agent block for `agent_path` so we can check its
    // `[agent.exclude]` list.
    for agent in &manifest.agents {
        let owns = agent.paths.iter().any(|ap| std::ptr::eq(ap, agent_path));
        if !owns {
            continue;
        }
        if let Some(exclude) = &agent.exclude {
            for pat in &exclude.patterns {
                if let Ok(expanded) = expand_path(pat, None) {
                    if path_matches_pattern(path, &expanded) {
                        return true;
                    }
                }
            }
        }
        break;
    }
    false
}

fn path_matches_pattern(path: &Path, pattern: &Path) -> bool {
    let Some(pattern_str) = pattern.to_str() else {
        return false;
    };
    let Some(path_str) = path.to_str() else {
        return false;
    };
    glob::Pattern::new(pattern_str)
        .map(|p| p.matches(path_str))
        .unwrap_or(false)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn manifest(body: &str) -> Manifest {
        toml::from_str(body).unwrap()
    }

    fn slash(p: &Path) -> String {
        p.display().to_string().replace('\\', "/")
    }

    #[test]
    fn glob_split_finds_the_static_prefix() {
        assert_eq!(
            glob_split(Path::new("/a/skills/*/SKILL.md")),
            Some((PathBuf::from("/a/skills"), 2))
        );
        assert_eq!(
            glob_split(Path::new("/a/rules/*.md")),
            Some((PathBuf::from("/a/rules"), 1))
        );
        assert_eq!(glob_split(Path::new("/a/CLAUDE.md")), None);
    }

    #[test]
    fn plan_covers_files_globs_and_missing_directories() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        std::fs::create_dir_all(root.join("skills")).unwrap();
        std::fs::create_dir_all(root.join("rules")).unwrap();
        std::fs::create_dir_all(root.join("plugins/cache/m/p/v/skills")).unwrap();
        let m = manifest(&format!(
            r#"
            [[agent]]
            name = "a"
            [[agent.path]]
            kind = "rules"
            paths = ["{r}/CLAUDE.md"]
            paths_glob = "{r}/rules/*.md"
            watch_strategy = "exact_file_and_glob"
            [[agent.path]]
            kind = "skill"
            paths_glob = "{r}/skills/*/SKILL.md"
            watch_strategy = "glob"
            [[agent.path]]
            kind = "skill"
            paths_glob = "{r}/plugins/cache/*/*/*/skills/*/SKILL.md"
            watch_strategy = "glob"
            [[agent.path]]
            kind = "command"
            paths_glob = "{r}/missing/deeper/commands/*.md"
            watch_strategy = "glob"
            "#,
            r = slash(root)
        ));
        let plan = watch_plan(&m, &[]);
        assert_eq!(
            plan.get(root),
            Some(&false),
            "file parent + sentinel: {plan:?}"
        );
        assert_eq!(plan.get(&root.join("rules")), Some(&false));
        assert_eq!(plan.get(&root.join("skills")), Some(&true));
        assert_eq!(plan.get(&root.join("plugins/cache")), Some(&true));
        assert!(
            !plan.keys().any(|d| d.starts_with(root.join("missing"))),
            "a missing prefix is covered by its nearest existing ancestor"
        );
    }

    #[test]
    fn a_recursive_ancestor_covers_its_descendants() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        std::fs::create_dir_all(root.join("skills/x")).unwrap();
        let m = manifest(&format!(
            r#"
            [[agent]]
            name = "a"
            [[agent.path]]
            kind = "skill"
            paths_glob = "{r}/skills/*/SKILL.md"
            watch_strategy = "glob"
            [[agent.path]]
            kind = "rules"
            paths = ["{r}/skills/x/NOTE.md"]
            watch_strategy = "exact_file"
            "#,
            r = slash(root)
        ));
        let plan = watch_plan(&m, &[]);
        assert_eq!(plan.get(&root.join("skills")), Some(&true));
        assert!(!plan.contains_key(&root.join("skills/x")), "{plan:?}");
    }

    #[test]
    fn home_and_the_filesystem_root_are_never_watched_recursively() {
        let home = tempfile::tempdir().unwrap();
        assert_eq!(
            resolve_anchor(home.path(), true, None, Some(home.path())),
            Some((home.path().to_path_buf(), false))
        );
        assert_eq!(resolve_anchor(Path::new("/"), true, None, None), None);
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn home_itself_is_never_watched_on_macos() {
        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path().to_path_buf();
        std::fs::write(home.join(".claude.json"), "{}").unwrap();
        std::fs::create_dir_all(home.join(".claude/skills")).unwrap();
        let m = manifest(&format!(
            r#"
            [[agent]]
            name = "a"
            [[agent.path]]
            kind = "mcp"
            paths = ["{h}/.claude.json", "{h}/.absent.json"]
            watch_strategy = "exact_file"
            [[agent.path]]
            kind = "skill"
            paths_glob = "{h}/.agents/skills/*/SKILL.md"
            watch_strategy = "glob"
            [[agent.path]]
            kind = "skill"
            paths_glob = "{h}/.claude/skills/*/SKILL.md"
            watch_strategy = "glob"
            [[agent.path]]
            kind = "rules"
            scope = "project"
            paths_relative = ["AGENTS.md"]
            watch_strategy = "exact_file"
            "#,
            h = slash(&home)
        ));
        // A project opened at `$HOME` covers its top level with `$HOME` too.
        let plan = watch_plan_from(&m, std::slice::from_ref(&home), Some(home.clone()));
        assert!(!plan.contains_key(&home), "{plan:?}");
        assert_eq!(plan.get(&home.join(".claude.json")), Some(&false));
        assert_eq!(plan.get(&home.join(".claude/skills")), Some(&true));
        assert_eq!(
            plan.len(),
            2,
            "no sentinel for a missing file or dir: {plan:?}"
        );
    }

    #[test]
    fn project_roots_get_their_subdirectories_and_never_the_repository() {
        let tmp = tempfile::tempdir().unwrap();
        let project = tmp.path().join("repo");
        std::fs::create_dir_all(project.join(".agents/skills")).unwrap();
        let m = manifest(
            r#"
            [[agent]]
            name = "a"
            [[agent.path]]
            kind = "rules"
            scope = "project"
            paths_glob_relative = [".cursor/rules/*.mdc"]
            watch_strategy = "glob"
            [[agent.path]]
            kind = "skill"
            scope = "project"
            paths_glob_relative = [".agents/skills/*/SKILL.md"]
            watch_strategy = "glob"
            [[agent.path]]
            kind = "rules"
            scope = "project"
            paths_relative = ["AGENTS.md"]
            watch_strategy = "exact_file"
            "#,
        );
        assert!(watch_plan(&m, &[]).is_empty(), "no root, no project watch");
        let plan = watch_plan(&m, std::slice::from_ref(&project));
        assert_eq!(plan.get(&project), Some(&false), "{plan:?}");
        assert_eq!(plan.get(&project.join(".agents/skills")), Some(&true));
        assert!(
            plan.keys().all(|d| d.starts_with(&project)),
            "a project sentinel never climbs above its root: {plan:?}"
        );
    }

    #[cfg(unix)]
    #[test]
    fn a_symlinked_prefix_is_never_watched_recursively() {
        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path().join("home");
        let project = home.join("repo");
        std::fs::create_dir_all(project.join(".agents")).unwrap();
        // The project's skills dir points back at $HOME.
        std::os::unix::fs::symlink(&home, project.join(".agents/skills")).unwrap();
        let anchor = project.join(".agents/skills");
        assert_eq!(
            resolve_anchor(&anchor, true, Some(&project), Some(&home)),
            Some((anchor.clone(), false))
        );
        // At the repository itself.
        std::fs::remove_file(&anchor).unwrap();
        std::os::unix::fs::symlink(&project, &anchor).unwrap();
        assert_eq!(
            resolve_anchor(&anchor, true, Some(&project), Some(&home)),
            Some((anchor.clone(), false))
        );
        // A shared checkout outside the project is fine.
        let shared = home.join("shared-skills");
        std::fs::create_dir_all(&shared).unwrap();
        std::fs::remove_file(&anchor).unwrap();
        std::os::unix::fs::symlink(&shared, &anchor).unwrap();
        assert_eq!(
            resolve_anchor(&anchor, true, Some(&project), Some(&home)),
            Some((anchor.clone(), true))
        );
        // A real directory inside the project still recurses.
        std::fs::remove_file(&anchor).unwrap();
        std::fs::create_dir_all(&anchor).unwrap();
        assert_eq!(
            resolve_anchor(&anchor, true, Some(&project), Some(&home)),
            Some((anchor, true))
        );
    }

    #[cfg(unix)]
    #[test]
    fn a_linked_plugin_below_a_recursive_watch_gets_its_own() {
        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path().to_path_buf();
        let root = home.join("agent");
        let cache = root.join("plugins/cache/market");
        std::fs::create_dir_all(&cache).unwrap();
        let target = home.join("dev-plugin");
        std::fs::create_dir_all(target.join("skills")).unwrap();
        std::os::unix::fs::symlink(&target, cache.join("linked")).unwrap();
        // Links out of $HOME are watched, never recursively.
        std::os::unix::fs::symlink("/", cache.join("root")).unwrap();
        std::os::unix::fs::symlink("/usr", cache.join("usr")).unwrap();
        let m = manifest(&format!(
            r#"
            [[agent]]
            name = "a"
            [[agent.path]]
            kind = "skill"
            paths_glob = "{r}/plugins/cache/*/*/skills/*/SKILL.md"
            watch_strategy = "glob"
            "#,
            r = slash(&root)
        ));
        let plan = watch_plan_from(&m, &[], Some(home));
        assert_eq!(plan.get(&root.join("plugins/cache")), Some(&true));
        assert_eq!(plan.get(&cache.join("linked")), Some(&true), "{plan:?}");
        assert_eq!(plan.get(&cache.join("root")), Some(&false), "{plan:?}");
        assert_eq!(plan.get(&cache.join("usr")), Some(&false), "{plan:?}");
    }

    #[cfg(unix)]
    #[test]
    fn a_repository_full_of_links_cannot_spend_the_watch_budget() {
        let tmp = tempfile::tempdir().unwrap();
        let project = tmp.path().join("repo");
        let skills = project.join(".agents/skills");
        std::fs::create_dir_all(&skills).unwrap();
        let target = tmp.path().join("t");
        std::fs::create_dir_all(&target).unwrap();
        for i in 0..(MAX_LINKED_DIRS + 50) {
            std::os::unix::fs::symlink(&target, skills.join(format!("l{i}"))).unwrap();
        }
        let m = manifest(
            r#"
            [[agent]]
            name = "a"
            [[agent.path]]
            kind = "skill"
            scope = "project"
            paths_glob_relative = [".agents/skills/*/SKILL.md"]
            watch_strategy = "glob"
            "#,
        );
        let plan = watch_plan_from(&m, std::slice::from_ref(&project), Some(tmp.path().into()));
        let linked = plan.keys().filter(|d| d.is_symlink()).count();
        assert_eq!(linked, MAX_LINKED_DIRS, "{}", plan.len());
    }

    #[test]
    fn unalias_rewrites_the_canonical_spelling() {
        let aliases: Aliases = Arc::new(RwLock::new(vec![(
            PathBuf::from("/private/var/x"),
            PathBuf::from("/var/x"),
        )]));
        assert_eq!(
            unalias(&[PathBuf::from("/private/var/x/a.md")], &aliases),
            vec![
                PathBuf::from("/var/x/a.md"),
                PathBuf::from("/private/var/x/a.md")
            ]
        );
        assert_eq!(
            unalias(&[PathBuf::from("/other/a.md")], &aliases),
            vec![PathBuf::from("/other/a.md")]
        );
    }

    #[test]
    fn unalias_reports_every_spelling_of_one_directory() {
        let aliases: Aliases = Arc::new(RwLock::new(vec![
            (
                PathBuf::from("/real/plugin"),
                PathBuf::from("/home/u/cache/linked"),
            ),
            (
                PathBuf::from("/real/plugin"),
                PathBuf::from("/home/u/other/linked"),
            ),
        ]));
        let out = unalias(&[PathBuf::from("/real/plugin/SKILL.md")], &aliases);
        assert!(out.contains(&PathBuf::from("/home/u/cache/linked/SKILL.md")));
        assert!(out.contains(&PathBuf::from("/home/u/other/linked/SKILL.md")));
        assert!(
            out.contains(&PathBuf::from("/real/plugin/SKILL.md")),
            "{out:?}"
        );
    }

    #[test]
    fn glob_expand_returns_empty_on_no_matches() {
        let temp = tempfile::tempdir().unwrap();
        let pattern = temp.path().join("*.no_such_extension");
        let v = glob_expand(&pattern);
        assert!(v.is_empty());
    }

    #[test]
    fn os_error_class_maps_known_kinds() {
        let io_err = notify::Error::new(NotifyErrorKind::Io(std::io::Error::other("x")));
        assert_eq!(os_error_class(&io_err), "io");
        let not_found = notify::Error::new(NotifyErrorKind::PathNotFound);
        assert_eq!(os_error_class(&not_found), "not_found");
        let max = notify::Error::new(NotifyErrorKind::MaxFilesWatch);
        assert_eq!(os_error_class(&max), "enospc");
    }
}