croft-software 0.2.82

VSCode-style TUI written in Rust
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
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};
use std::sync::mpsc::Receiver;
use std::time::{Duration, Instant, SystemTime};

use anyhow::{Context, Result};

use crate::widgets::editor::EditorTabs;
use crate::widgets::file_finder::{has_noise_path_run, is_noise_dir, is_noise_path_under_root};
use crate::widgets::file_tree::{FileTree, affected_dir_for_event};

const FS_POLL_INTERVAL: Duration = Duration::from_millis(50);

const FS_WATCH_PROTECTED_NAMES: &[&str] = &["Library", ".Trash"];

/// Max directories the macOS watch-target walk may visit before it stops and
/// leaves the remainder to the adaptive poll. Bounds the startup/rebind scan on
/// a parent-of-repos root (~/Documents measured at ~140k dirs / 7.6s) to a
/// fraction of a second, while comfortably covering any normal single repo in
/// full. See `collect_macos_watch_targets`.
///
/// macOS-only, like its one use site: on Linux the inotify backend needs no
/// such walk, and an unconditional const is a `dead_code` error there under
/// `-D warnings`.
#[cfg(target_os = "macos")]
const WATCH_WALK_DIR_BUDGET: usize = 8_192;

type FsWatcherInit = (
    notify_debouncer_full::Debouncer<
        notify::RecommendedWatcher,
        notify_debouncer_full::RecommendedCache,
    >,
    Receiver<notify_debouncer_full::DebounceEventResult>,
);

#[derive(Default)]
pub struct FsPoll {
    pub open_file_changed: bool,
    pub dirs_changed: bool,
    pub finder_relevant: bool,
}

#[derive(Default)]
pub struct FsDrain {
    pub got_any: bool,
    pub touched_open_file: bool,
    pub dirs_changed: bool,
    pub finder_relevant: bool,
    /// Workspace FILES whose content an event mutated, for the agent lane
    /// ledger (#345). Directories and pure metadata events are excluded:
    /// the ledger asks "what content changed", and a chmod is not a change
    /// a reviewer needs to see.
    pub changed_files: BTreeSet<PathBuf>,
    /// The `changed_files` that were created, which the language servers
    /// hear about as created rather than changed (#908).
    pub created_files: BTreeSet<PathBuf>,
    /// The `changed_files` a rename put in place (#908): an atomic save
    /// renames a temporary file over the one it replaces, so these are
    /// created or changed by whether the file was there before.
    pub moved_in: BTreeSet<PathBuf>,
    /// Paths a removal or a rename took away (#908). The watcher reports a
    /// directory moved or removed as the directory alone, so the files it
    /// held are found in what the workspace had before.
    pub vanished: BTreeSet<PathBuf>,
    /// The watcher reported a RESCAN: it overflowed its queue and events
    /// were dropped, so `changed_files` is a lower bound rather than the
    /// whole story (#345). A ledger that quietly showed a short list would
    /// be telling the reviewer they had seen everything, which is the one
    /// thing it must never do.
    pub rescan_dropped_events: bool,
}

pub struct FsWatch {
    _watcher: Option<
        notify_debouncer_full::Debouncer<
            notify::RecommendedWatcher,
            notify_debouncer_full::RecommendedCache,
        >,
    >,
    rx: Option<Receiver<notify_debouncer_full::DebounceEventResult>>,
    init_rx: Option<Receiver<FsWatcherInit>>,
    poll_last_check: Instant,
    poll_interval: Duration,
    poll_dir_mtimes: BTreeMap<PathBuf, Option<SystemTime>>,
    /// Per-file stamps for EVERY open tab, not just the focused one. A file
    /// sitting directly in a boundary dir gets no watch at all (that is the
    /// iron law that keeps the FSEvents storm dead) and an in-place write does
    /// not move its parent dir's mtime, so this stat is the only thing that can
    /// see it change. Bounded by the number of open tabs, once per poll tick.
    poll_open_files: BTreeMap<PathBuf, Option<(SystemTime, u64)>>,
    /// The root this instance watches. Multi-root workspaces (#147) run
    /// one `FsWatch` per workspace root, and `drain` must attribute each
    /// event against ITS root — attributing against the shared tree's
    /// primary root silently dropped every event from a secondary root.
    watch_root: PathBuf,
    /// `watch_root` resolved through symlinks, computed once per bind.
    /// `drain_fs_events` compares every event path against the root, and
    /// resolving it inline made `canonicalize` — one `readlink` per path
    /// component, each failing `EINVAL` on a real directory — the largest
    /// single CPU consumer in the process when the root was a home dir.
    canon_watch_root: PathBuf,
}

/// Resolve `root` through symlinks, falling back to the path as given when
/// it cannot be resolved (it may not exist yet). Called once per bind, never
/// per event.
fn canon_of(root: &Path) -> PathBuf {
    root.canonicalize().unwrap_or_else(|_| root.to_path_buf())
}

impl FsWatch {
    pub fn spawn(root: &Path, tree: &FileTree) -> Self {
        Self::spawn_sharing(root, tree, 1)
    }

    /// [`spawn`] with the per-OS watch caps divided by `shares` — the
    /// number of workspace roots (#147). The caps exist to bound kernel
    /// watch descriptors and stream setup per PROCESS, so N concurrent
    /// instances must split one budget rather than multiply it.
    pub fn spawn_sharing(root: &Path, tree: &FileTree, shares: usize) -> Self {
        Self {
            _watcher: None,
            rx: None,
            init_rx: Some(Self::start_watcher_thread(root, shares)),
            poll_last_check: Instant::now(),
            poll_interval: FS_POLL_INTERVAL,
            poll_dir_mtimes: Self::snapshot_expanded_dir_mtimes(tree),
            poll_open_files: BTreeMap::new(),
            watch_root: root.to_path_buf(),
            canon_watch_root: canon_of(root),
        }
    }

    /// A SECONDARY root's watcher (#147): events only. The PRIMARY
    /// instance owns the adaptive poll for the whole tree — its dir-mtime
    /// snapshot walks every root's expanded rows, covering secondary
    /// roots wherever their events fall past the caps — so an extra
    /// instance snapshotting the tree again would only duplicate stat
    /// work if its `poll` were ever called (#148 review).
    pub fn spawn_event_only(root: &Path, shares: usize) -> Self {
        Self {
            _watcher: None,
            rx: None,
            init_rx: Some(Self::start_watcher_thread(root, shares)),
            poll_last_check: Instant::now(),
            poll_interval: FS_POLL_INTERVAL,
            poll_dir_mtimes: BTreeMap::new(),
            poll_open_files: BTreeMap::new(),
            watch_root: root.to_path_buf(),
            canon_watch_root: canon_of(root),
        }
    }

    pub fn rebind(&mut self, root: &Path, tree: &FileTree) {
        self.rebind_sharing(root, tree, 1)
    }

    /// [`rebind`] with the shared-budget divisor, like [`spawn_sharing`].
    pub fn rebind_sharing(&mut self, root: &Path, tree: &FileTree, shares: usize) {
        offload_drop(self._watcher.take());
        self.rx = None;
        self.init_rx = Some(Self::start_watcher_thread(root, shares));
        self.poll_dir_mtimes = Self::snapshot_expanded_dir_mtimes(tree);
        self.watch_root = root.to_path_buf();
        self.canon_watch_root = canon_of(root);
    }

    pub fn disable(&mut self) {
        offload_drop(self._watcher.take());
        self.rx = None;
        self.init_rx = None;
    }

    pub fn try_install_watcher(&mut self) -> bool {
        let Some(rx) = self.init_rx.as_ref() else {
            return false;
        };
        match rx.try_recv() {
            Ok((w, evrx)) => {
                self._watcher = Some(w);
                self.rx = Some(evrx);
                self.init_rx = None;
                true
            }
            Err(std::sync::mpsc::TryRecvError::Disconnected) => {
                self.init_rx = None;
                false
            }
            Err(std::sync::mpsc::TryRecvError::Empty) => false,
        }
    }

    pub fn sync_open_file_mtime(&mut self, open_paths: &[PathBuf]) {
        self.poll_open_files = Self::stamp_all(open_paths);
    }

    fn stamp_all(paths: &[PathBuf]) -> BTreeMap<PathBuf, Option<(SystemTime, u64)>> {
        paths
            .iter()
            .map(|p| (p.clone(), Self::file_stamp(p)))
            .collect()
    }

    /// True when `path` is noise measured against THIS instance's root.
    ///
    /// Event paths are absolute, and the root's own ancestors are not part of
    /// the workspace, so classifying one whole made every event in a
    /// workspace under `~/build/` (or inside `~/go/pkg/mod/`) read as noise:
    /// `changed_files` never filled and `finder_relevant` never went true.
    /// The watch-target walk already measures relative to the root (the
    /// `is_skippable` closure on Linux, `is_skippable_path` on macOS); this
    /// is that same rule applied to the events the walk delivers.
    ///
    /// Both roots are tried because they can disagree: a watcher installed on
    /// a symlinked root reports CANONICAL paths while `watch_root` holds the
    /// path as the user gave it.
    ///
    /// A path under NEITHER falls back to the whole-path reading. Every
    /// EVENT reaching here came from this instance's own watcher, so that
    /// fallback is unreachable for them; the poll, whose dirs can belong to
    /// another root entirely, resolves the owning root first and never asks
    /// this question with the wrong one — see [`Self::is_noise_polled_dir`].
    fn is_noise_event_path(&self, path: &Path) -> bool {
        let root = if path.starts_with(&self.watch_root) {
            &self.watch_root
        } else {
            &self.canon_watch_root
        };
        is_noise_path_under_root(path, root)
    }

    /// True when a POLLED directory is noise, measured against the workspace
    /// root that OWNS it rather than against this instance's.
    ///
    /// The primary instance's poll walks EVERY root's expanded rows (#147),
    /// so a multi-root workspace's secondary folders arrive here. Measuring
    /// one against `watch_root` answers for the wrong workspace, and the
    /// whole-path fallback behind it is worse: a secondary folder at
    /// `~/build/myapp` matched neither root, so its own `build` ancestor made
    /// every change under it read as noise and the finder index stayed stale
    /// for that folder. The owning root is the longest root row that prefixes
    /// the dir, the same resolution `FileTree::owning_root` uses; a dir under
    /// no root at all is left to the event reading.
    fn is_noise_polled_dir(&self, tree: &FileTree, dir: &Path) -> bool {
        match tree
            .root_paths()
            .filter(|r| dir.starts_with(r))
            .max_by_key(|r| r.as_os_str().len())
        {
            Some(root) => is_noise_path_under_root(dir, root),
            None => self.is_noise_event_path(dir),
        }
    }

    pub fn drain(&mut self, tree: &mut FileTree, editor: &EditorTabs) -> FsDrain {
        let mut out = FsDrain::default();
        let Some(rx) = self.rx.as_ref() else {
            return out;
        };
        let mut affected: BTreeSet<PathBuf> = BTreeSet::new();
        let mut new_dirs: Vec<PathBuf> = Vec::new();
        while let Ok(result) = rx.try_recv() {
            let events = match result {
                Ok(evs) => evs,
                Err(_) => {
                    out.got_any = true;
                    continue;
                }
            };
            for ev in events {
                if ev.event.need_rescan() {
                    out.rescan_dropped_events = true;
                }
                // Reading the tree and running git open the root and its
                // files, and inotify reports every open, so acting on one
                // here re-reads the tree and re-runs git forever (#898).
                if is_read_only_access(&ev.event.kind) {
                    continue;
                }
                out.got_any = true;
                let mutates_content = event_mutates_content(&ev.event.kind);
                let arrives = arrives_at_path(&ev.event.kind);
                let created = matches!(ev.event.kind, notify::EventKind::Create(_));
                let leaves = leaves_path(&ev.event.kind);
                for path in &ev.event.paths {
                    if leaves && !self.is_noise_event_path(path) && !path.exists() {
                        out.vanished.insert(path.clone());
                    }
                    if arrives && path.is_dir() && !self.is_noise_event_path(path) {
                        new_dirs.push(path.clone());
                    }
                    if mutates_content && editor.matches_open_path(path) {
                        out.touched_open_file = true;
                    }
                    // The ledger wants files, not the directories whose
                    // mtime moved because a file inside them changed. A
                    // REMOVED directory needs the event kind to tell it
                    // apart: `is_dir()` is already false once it is gone.
                    if mutates_content
                        && !removes_a_directory(&ev.event.kind)
                        && !self.is_noise_event_path(path)
                        && !path.is_dir()
                    {
                        out.changed_files.insert(path.clone());
                        if created {
                            out.created_files.insert(path.clone());
                        } else if arrives {
                            out.moved_in.insert(path.clone());
                        }
                    }
                    if let Some(dir) =
                        affected_dir_for_event(path, &self.watch_root, &self.canon_watch_root)
                    {
                        affected.insert(dir);
                    } else if path == &self.watch_root
                        || path.as_path() == self.canon_watch_root
                        || path.canonicalize().ok().as_deref()
                            == Some(self.canon_watch_root.as_path())
                    {
                        affected.insert(self.watch_root.clone());
                    }
                }
            }
        }
        self.watch_new_dirs(new_dirs, &mut out);
        if !affected.is_empty() {
            for dir in affected.iter().rev() {
                if let Some(idx) = tree.index_of_dir(dir) {
                    tree.refresh_children(idx);
                } else if let Ok(c) = dir.canonicalize()
                    && let Some(idx) = tree.index_of_dir(&c)
                {
                    tree.refresh_children(idx);
                }
            }
            self.poll_dir_mtimes = Self::snapshot_expanded_dir_mtimes(tree);
            out.dirs_changed = true;
            out.finder_relevant = affected.iter().any(|p| !self.is_noise_event_path(p));
        }
        out
    }

    /// Watch directories that appeared after the watcher started (a
    /// `mkdir`, a `git checkout`, `rm -rf build && mkdir build`). Linux
    /// watches one directory at a time, installed once at startup, so
    /// without this nothing inside a new directory was ever reported. Files
    /// already in it may have been written before its watch existed, so
    /// they count as changed.
    fn watch_new_dirs(&mut self, dirs: Vec<PathBuf>, out: &mut FsDrain) {
        if dirs.is_empty() || cfg!(target_os = "macos") {
            // FSEvents streams are recursive: a new directory under one is
            // already covered.
            return;
        }
        let (root, canon) = (self.watch_root.clone(), self.canon_watch_root.clone());
        let noise = |p: &Path| {
            is_noise_path_under_root(p, if p.starts_with(&root) { &root } else { &canon })
        };
        let Some(watcher) = self._watcher.as_mut() else {
            out.rescan_dropped_events = true;
            return;
        };
        // Bounded per drain: a huge tree unpacked at once falls back to the
        // poll and says the ledger may be short.
        let mut budget = 2_000usize;
        let mut stack = dirs;
        while let Some(dir) = stack.pop() {
            if budget == 0 {
                out.rescan_dropped_events = true;
                return;
            }
            budget -= 1;
            let _ = watcher.watch(&dir, notify::RecursiveMode::NonRecursive);
            let Ok(rd) = std::fs::read_dir(&dir) else {
                continue;
            };
            for entry in rd.filter_map(Result::ok) {
                let path = entry.path();
                let Ok(ft) = entry.file_type() else {
                    continue;
                };
                if ft.is_dir() {
                    let name = path.file_name().unwrap_or_default();
                    if !FS_WATCH_PROTECTED_NAMES.iter().any(|n| name == *n) && !noise(&path) {
                        stack.push(path);
                    }
                } else if ft.is_file() && !noise(&path) {
                    out.changed_files.insert(path.clone());
                    out.created_files.insert(path);
                }
            }
        }
    }

    /// Whether the next `poll` would do any work. `drain_fs_events` runs every
    /// frame while the poll fires at most every `FS_POLL_INTERVAL`, so the
    /// caller checks this before collecting the open-tab paths — otherwise the
    /// frame pays a Vec of PathBuf clones just to have `poll` drop it.
    pub fn poll_due(&self) -> bool {
        self.poll_last_check.elapsed() >= self.poll_interval
    }

    pub fn poll(&mut self, tree: &mut FileTree, open_paths: &[PathBuf]) -> FsPoll {
        let mut out = FsPoll::default();
        if !self.poll_due() {
            return out;
        }
        let poll_start = Instant::now();
        self.poll_last_check = poll_start;
        out.open_file_changed = self.poll_open_file_change(open_paths);
        let current = Self::snapshot_expanded_dir_mtimes(tree);
        let changed_dirs: Vec<PathBuf> = current
            .iter()
            .filter_map(|(path, stamp)| {
                if self.poll_dir_mtimes.get(path) == Some(stamp) {
                    None
                } else {
                    Some(path.clone())
                }
            })
            .collect();
        if changed_dirs.is_empty() {
            self.poll_dir_mtimes = current;
            self.poll_interval = Self::back_off(poll_start);
            return out;
        }
        for dir in changed_dirs.iter().rev() {
            if let Some(idx) = tree.index_of_dir(dir) {
                tree.refresh_children(idx);
            }
        }
        self.poll_dir_mtimes = Self::snapshot_expanded_dir_mtimes(tree);
        out.dirs_changed = true;
        out.finder_relevant = changed_dirs
            .iter()
            .any(|p| !self.is_noise_polled_dir(tree, p));
        self.poll_interval = Self::back_off(poll_start);
        out
    }

    /// True when any file backing an open tab has a different stamp than the
    /// last poll saw. A path we have no previous stamp for (a tab just opened)
    /// is only baselined — it is not a change — and a path that has gone away
    /// with its tab simply drops out.
    fn poll_open_file_change(&mut self, open_paths: &[PathBuf]) -> bool {
        let current = Self::stamp_all(open_paths);
        let changed = current.iter().any(
            |(path, stamp)| matches!(self.poll_open_files.get(path), Some(old) if old != stamp),
        );
        self.poll_open_files = current;
        changed
    }

    fn back_off(poll_start: Instant) -> Duration {
        poll_start
            .elapsed()
            .saturating_mul(10)
            .clamp(FS_POLL_INTERVAL, Duration::from_secs(10))
    }

    fn snapshot_expanded_dir_mtimes(tree: &FileTree) -> BTreeMap<PathBuf, Option<SystemTime>> {
        tree.nodes
            .iter()
            .filter(|n| n.is_dir && n.expanded)
            .map(|n| (n.path.clone(), Self::dir_modified(&n.path)))
            .collect()
    }

    fn dir_modified(path: &Path) -> Option<SystemTime> {
        std::fs::metadata(path).and_then(|m| m.modified()).ok()
    }

    fn file_stamp(path: &Path) -> Option<(SystemTime, u64)> {
        let meta = std::fs::metadata(path).ok()?;
        let modified = meta.modified().ok()?;
        Some((modified, meta.len()))
    }

    fn start_watcher_thread(root: &Path, shares: usize) -> Receiver<FsWatcherInit> {
        let (init_tx, init_rx) = std::sync::mpsc::channel();
        let root = root.to_path_buf();
        std::thread::spawn(move || {
            if let Ok(pair) = Self::spawn_watcher_sharing(&root, shares) {
                let _ = init_tx.send(pair);
            }
        });
        init_rx
    }

    #[cfg(test)]
    pub(super) fn spawn_watcher(root: &Path) -> Result<FsWatcherInit> {
        Self::spawn_watcher_sharing(root, 1)
    }

    pub(super) fn spawn_watcher_sharing(root: &Path, shares: usize) -> Result<FsWatcherInit> {
        use notify::RecursiveMode;
        use notify_debouncer_full::new_debouncer;
        let (tx, rx) = std::sync::mpsc::channel();
        let mut debouncer = new_debouncer(Duration::from_millis(100), None, tx)
            .context("creating filesystem watcher")?;
        // The watcher backend is fundamentally different on the two
        // first-class targets, so the install strategy MUST differ too -
        // a single uniform strategy is pathological on one of them:
        //
        //  * macOS / FSEvents is per-TREE. One recursive watch covers an
        //    entire subtree in a single stream with no kernel watch limit,
        //    and every `watch()` call tears down and rebuilds that stream.
        //    Calling `watch()` once per directory therefore fires thousands
        //    of FSEventStreamCreate calls and pins a core at ~100% forever
        //    (confirmed by `sample` 2026-05: the FSEvents thread sits in
        //    FSEventStreamCreate). So on macOS we make as FEW calls as
        //    possible.
        //
        //  * Linux / inotify is per-DIRECTORY. A recursive watch installs
        //    one watch per dir in the subtree, and a real repo's
        //    node_modules/target/.git push past
        //    /proc/sys/fs/inotify/max_user_watches (often 8192 on a VPS),
        //    returning ENOSPC so NO watcher installs and the main loop
        //    falls back to a blocking stat-walk that freezes typing over
        //    SSH. Each inotify_add_watch is cheap and independent (no
        //    stream rebuild), so on Linux we add MANY non-recursive watches.
        //
        // Both branches prune the same protected + noise dirs (target/,
        // node_modules/, .git/, ~/Library Containers) which generate
        // cargo/npm/git write storms the debouncer's FileIdMap memcmp loop
        // can't keep up with, and which on macOS also trip Sonoma's App
        // Management TCC class.
        #[cfg(target_os = "macos")]
        {
            // Depth-aware pruning. We install a recursive watch only at the
            // root of each maximal noise-free subtree, and NEVER root a stream
            // at or above a noise dir (target/, node_modules/, .git/).
            //
            // Why "never above" and not "non-recursive on the boundary": on
            // macOS there is no such thing as a non-recursive FSEvents watch.
            // notify implements RecursiveMode::NonRecursive as a fully
            // recursive FSEventStream rooted at the path, then DISCARDS events
            // whose parent isn't the path — after the kernel has already
            // delivered them and the callback has paid to filter them
            // (notify 8.2.0 src/fsevent.rs: the `recursive_info`
            // `path.starts_with` loop runs for every event in the subtree).
            // So a non-recursive watch on a boundary dir like ~/Documents or
            // a repo root still streams every target/ and node_modules/ write
            // beneath it into the fsevents-loop thread, pinning a core during
            // any cargo/npm build even though zero of those events reach the
            // debouncer. The old code's boundary watches did exactly this; the
            // regression hid because the tests only asserted zero *debouncer*
            // events, never the callback CPU.
            //
            // The boundary dirs' own direct entries (a new top-level file, a
            // Cargo.toml edit) are instead covered by the adaptive-backoff
            // poll, which stats only the expanded/visible dirs — cheap, and
            // already the fallback for everything not under a watch.
            let mut targets: Vec<(PathBuf, RecursiveMode)> = Vec::new();
            // Cap the discovery walk so opening a parent-of-repos root (e.g.
            // ~/Documents, ~140k non-noise dirs → a 7.6s scan) can't turn the
            // watcher thread into a multi-second readdir burst. A typical single
            // repo is far under this, so its behaviour is unchanged; a tree that
            // exceeds it gets watches on the subtrees discovered before the cap
            // and the adaptive poll covers the rest.
            let mut budget = WATCH_WALK_DIR_BUDGET / shares.max(1);
            if collect_macos_watch_targets(root, root, &mut targets, &mut budget) {
                // Whole tree is noise-free (e.g. a small repo with no
                // node_modules): one recursive watch covers it in a single
                // stream, exactly as before.
                targets.push((root.to_path_buf(), RecursiveMode::Recursive));
            }
            // Safety net: if a pathological tree still produces a huge number
            // of streams, keep the shallowest (broadest-coverage) ones and let
            // the adaptive-backoff poll fallback cover the rest, rather than
            // spending forever in FSEventStreamCreate.
            const MAX_WATCHES: usize = 2_000;
            let max_watches = MAX_WATCHES / shares.max(1);
            if targets.len() > max_watches {
                targets.sort_by_key(|(p, _)| p.components().count());
                targets.truncate(max_watches);
            }
            // An empty target list here means `collect` returned `false`: the
            // root is a boundary that contains noise but has no noise-free
            // subtree to anchor a stream on (e.g. a repo that is only .git +
            // node_modules + loose files). The OLD code fell back to a
            // non-recursive watch on the root — which on macOS is a recursive
            // stream over exactly that noise, the storm we're killing. So in
            // that case we install NOTHING and let the adaptive poll cover the
            // root's (few, visible) entries. Watching nothing is correct, not a
            // failure: the poll is the floor for everything outside a watch.
            for (path, mode) in targets {
                let _ = debouncer.watch(&path, mode);
            }
        }
        #[cfg(not(target_os = "macos"))]
        {
            // The run rule is measured relative to `root`: the workspace
            // root's own ancestors are not part of the workspace, so a
            // checkout that happens to live under e.g. `build/` or inside
            // `go/pkg/mod` must not have its whole subtree pruned.
            let is_skippable = |path: &Path| -> bool {
                let name = path.file_name().unwrap_or_default();
                FS_WATCH_PROTECTED_NAMES.iter().any(|n| name == *n)
                    || is_noise_dir(name)
                    || has_noise_path_run(path, root)
            };
            // Hard ceiling so a pathological tree can't spend forever
            // issuing inotify_add_watch syscalls on the init thread;
            // anything beyond is covered by the adaptive-backoff poll
            // fallback. Per-dir failures are tolerated (we keep going), so
            // a tree that still exceeds the limit installs with partial
            // coverage instead of nothing.
            const MAX_WATCHES: usize = 50_000;
            let max_watches = MAX_WATCHES / shares.max(1);
            // A zero share (pathologically many roots) installs NOTHING:
            // the loop below tests the cap only after a watch call, so
            // entering it would grant every instance one descriptor past
            // the shared budget (#148 review). The adaptive poll is the
            // floor, exactly as for a boundary dir.
            if max_watches == 0 {
                return Ok((debouncer, rx));
            }
            let mut stack = vec![root.to_path_buf()];
            let mut watched = 0usize;
            while let Some(dir) = stack.pop() {
                if debouncer.watch(&dir, RecursiveMode::NonRecursive).is_ok() {
                    watched += 1;
                }
                if watched >= max_watches {
                    break;
                }
                let Ok(rd) = std::fs::read_dir(&dir) else {
                    continue;
                };
                for entry in rd.filter_map(Result::ok) {
                    if is_skippable(&entry.path()) {
                        continue;
                    }
                    // `file_type()` does not follow symlinks, so a symlinked
                    // directory reports `is_dir() == false` and we never
                    // descend into it - that also rules out symlink cycles.
                    if entry.file_type().map(|ft| ft.is_dir()).unwrap_or(false) {
                        stack.push(entry.path());
                    }
                }
            }
        }
        Ok((debouncer, rx))
    }

    #[cfg(test)]
    pub fn set_test_events(&mut self, rx: Receiver<notify_debouncer_full::DebounceEventResult>) {
        self._watcher = None;
        self.init_rx = None;
        self.rx = Some(rx);
    }

    #[cfg(test)]
    pub fn force_poll_due(&mut self) {
        self.poll_last_check = Instant::now()
            .checked_sub(self.poll_interval)
            .unwrap_or_else(Instant::now);
    }

    #[cfg(test)]
    pub fn clear_dir_mtimes(&mut self) {
        self.poll_dir_mtimes.clear();
    }
}

/// True for a directory croft must never watch: a protected macOS dir
/// (`Library`/`.Trash`, which trip Sonoma's App Management TCC class), a
/// build/VCS noise dir (`node_modules`/`target`/`.git`/…) whose cargo/npm/git
/// write storms the debouncer's FileIdMap loop cannot keep up with, or one of
/// the `go/pkg/mod` cache runs. The name rules read the entry's own name; the
/// run rule is measured relative to `root`, because the workspace root's own
/// ancestors are not part of the workspace.
#[cfg(target_os = "macos")]
fn is_skippable_path(path: &Path, root: &Path) -> bool {
    let name = path.file_name().unwrap_or_default();
    FS_WATCH_PROTECTED_NAMES.iter().any(|n| name == *n)
        || is_noise_dir(name)
        || has_noise_path_run(path, root)
}

/// Walk `dir` and append the FSEvents watch targets that cover every
/// non-noise file beneath it without ever rooting a stream at or above a noise
/// subtree at any depth (descent stops at noise dirs, so their subtrees are
/// never even read). Returns `true` when `dir`'s entire subtree is noise-free,
/// deferring to the caller to install one recursive watch at the subtree's
/// highest point (a single stream); returns `false` when `dir` is a boundary
/// (it contains noise somewhere beneath it), having pushed a recursive watch
/// on each maximal noise-free child subtree. A boundary dir is deliberately
/// NOT watched itself: on macOS a non-recursive watch is still a recursive
/// FSEventStream (see `spawn_watcher`), so watching a boundary would re-stream
/// the very noise we descended past. Its direct entries fall to the poll.
#[cfg(target_os = "macos")]
pub(super) fn collect_macos_watch_targets(
    dir: &Path,
    root: &Path,
    targets: &mut Vec<(PathBuf, notify::RecursiveMode)>,
    budget: &mut usize,
) -> bool {
    use notify::RecursiveMode;
    // Bound the discovery walk. A parent-of-repos root (e.g. ~/Documents) can
    // hold 100k+ non-noise dirs; walking all of them to confirm they are
    // noise-free costs seconds on the watcher thread. When the budget is spent
    // we report the subtree as NOT clean, so no recursive stream is ever rooted
    // over a tree we didn't finish verifying (the iron law: never watch above
    // unseen noise). The adaptive poll, which already stats every expanded dir
    // each cycle, is the floor for whatever we stop short of watching.
    // ponytail: a flat dir-visit cap; a huge *single* clean repo past the cap
    // falls back to poll-only instead of one recursive watch. Raise the cap if
    // that ever matters; typical single repos are far under it.
    if *budget == 0 {
        return false;
    }
    *budget -= 1;
    let mut has_noise = false;
    let mut subdirs: Vec<PathBuf> = Vec::new();
    if let Ok(rd) = std::fs::read_dir(dir) {
        for entry in rd.filter_map(Result::ok) {
            if is_skippable_path(&entry.path(), root) {
                has_noise = true;
                continue;
            }
            // `file_type()` does not follow symlinks, so a symlinked dir
            // reports `is_dir() == false` and we never descend — that also
            // rules out symlink cycles (e.g. the ~/Library group-container
            // loops that flooded the basedpyright crawl).
            if entry.file_type().map(|ft| ft.is_dir()).unwrap_or(false) {
                subdirs.push(entry.path());
            }
        }
    }
    let child_clean: Vec<(PathBuf, bool)> = subdirs
        .into_iter()
        .map(|sd| {
            let clean = collect_macos_watch_targets(&sd, root, targets, budget);
            (sd, clean)
        })
        .collect();
    if !has_noise && child_clean.iter().all(|(_, clean)| *clean) {
        return true;
    }
    for (sd, clean) in child_clean {
        if clean {
            targets.push((sd, RecursiveMode::Recursive));
        }
    }
    false
}

impl Drop for FsWatch {
    // Dropping the whole watcher (e.g. on app teardown or a workspace swap that
    // replaces the `App`) must offload the notify `Debouncer` exactly like
    // `rebind`/`disable` do; otherwise a `_watcher` still `Some` at drop runs
    // `FsEventWatcher::stop()` inline and can busy-spin the UI thread (see
    // `offload_drop`). `take` leaves `None`, so the field's own drop is a no-op.
    fn drop(&mut self) {
        offload_drop(self._watcher.take());
    }
}

// VA 2026-06-23: Drop `value` on a detached background thread instead of
// inline. Dropping a notify FSEvents watcher runs FsEventWatcher::stop(),
// which busy-spins `while CFRunLoopIsWaiting(runloop) == 0 { thread::yield_now() }`
// (notify 8.2.0, src/fsevent.rs) until the watcher's CFRunLoop thread parks.
// When that thread is mid MustScanSubDirs rescan the spin never ends, so doing
// it on the UI thread (change_workspace_root -> rebind, or disable) freezes the
// whole app and pins a core. Offloading keeps the spin on a throwaway thread the
// UI never joins; `T: Send + 'static` lets the watcher move across the boundary.
pub(super) fn offload_drop<T: Send + 'static>(value: T) {
    std::thread::spawn(move || drop(value));
}

/// A path an event can take away: removed, or renamed from (#908).
fn leaves_path(kind: &notify::EventKind) -> bool {
    use notify::EventKind;
    use notify::event::ModifyKind;
    matches!(
        kind,
        EventKind::Remove(_) | EventKind::Modify(ModifyKind::Name(_))
    )
}

/// The `workspace/didChangeWatchedFiles` events `drain` makes (#908).
/// `known` is the workspace's files as the Quick Open index last saw them,
/// which is before this drain: a file renamed onto one it knew is an atomic
/// save, so changed, where one moved into a new place is created; and a
/// path that vanished takes every file it knew under it, which the watcher
/// reports only as the directory. A path that is gone goes out as deleted
/// whatever it is listed as here (`LspManager::did_change_watched_files`).
pub fn watched_file_changes(
    drain: &FsDrain,
    known: &[crate::widgets::file_finder::FileEntry],
) -> Vec<(PathBuf, lsp_types::FileChangeType)> {
    use lsp_types::FileChangeType;
    let existed = |p: &Path| known.iter().any(|e| e.path == p);
    let mut out = BTreeMap::new();
    for path in &drain.changed_files {
        let created =
            drain.created_files.contains(path) || (drain.moved_in.contains(path) && !existed(path));
        let typ = match created {
            true => FileChangeType::CREATED,
            false => FileChangeType::CHANGED,
        };
        out.insert(path.clone(), typ);
    }
    for gone in &drain.vanished {
        for e in known
            .iter()
            .filter(|e| e.path != *gone && e.path.starts_with(gone))
        {
            out.entry(e.path.clone()).or_insert(FileChangeType::DELETED);
        }
    }
    out.into_iter().collect()
}

/// Whether the event is the removal of a path known to have been a
/// DIRECTORY. Once it is gone `is_dir()` is false, so only the kind can
/// say — and only FSEvents and inotify say it precisely, with
/// `RemoveKind::Folder`; kqueue, the Windows watcher and the poll fallback
/// emit `RemoveKind::Any` for everything they remove.
///
/// `Any` is deliberately NOT excluded. Letting it through costs nothing —
/// a removed directory reaching the ledger resolves to `Baseline::Gone`
/// and `forget_path`, which is a no-op for a path no lane holds — while
/// excluding it would strand a removed FILE in the queue on those three
/// backends, since a deleted file generates no later write to clear it.
/// Both cases end correct this way; excluding `Any` would trade a wrong
/// row for a wrong row.
fn removes_a_directory(kind: &notify::EventKind) -> bool {
    use notify::EventKind;
    use notify::event::RemoveKind;
    matches!(kind, EventKind::Remove(RemoveKind::Folder))
}

/// A path that now exists where it did not: created, or renamed onto.
fn arrives_at_path(kind: &notify::EventKind) -> bool {
    use notify::EventKind;
    use notify::event::{ModifyKind, RenameMode};
    matches!(
        kind,
        EventKind::Create(_)
            | EventKind::Modify(ModifyKind::Name(RenameMode::To | RenameMode::Both))
    )
}

fn event_mutates_content(kind: &notify::EventKind) -> bool {
    use notify::EventKind;
    use notify::event::ModifyKind;
    !matches!(
        kind,
        EventKind::Access(_) | EventKind::Modify(ModifyKind::Metadata(_))
    )
}

/// An open, read or close that wrote nothing. Only a close after writing
/// (`Close(Write)`) says the path may have changed; every other access
/// leaves the tree, git status and every open file exactly as they were.
fn is_read_only_access(kind: &notify::EventKind) -> bool {
    use notify::EventKind;
    use notify::event::{AccessKind, AccessMode};
    matches!(kind, EventKind::Access(access) if *access != AccessKind::Close(AccessMode::Write))
}