whycodes-index 0.6.31

Fast, gitignore-aware workspace file index for WhyCodes
Documentation
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
//! whycodes-index — fast, gitignore-aware workspace file index.
//!
//! One background scan of the project roots feeds every consumer:
//!
//! * **TUI file picker** — fuzzy path queries (`@file`, Ctrl+Space) served by
//!   a resident [`nucleo`] engine; keystroke queries never touch the disk.
//! * **File tools** — `glob` / `list` / `grep` enumerate the in-memory store
//!   instead of re-walking the tree on every tool call. Grep also consults
//!   a resident content-trigram overlay so regex confirm only opens files
//!   that could contain a required literal.
//!
//! The walk honours `.gitignore` / `.ignore` (via the [`ignore`] crate, the
//! same engine ripgrep uses) plus the shared pruning [`policy`]. After the
//! initial scan a `notify` watcher streams debounced deltas so the index
//! stays warm as files are created, edited and deleted during a session.
//!
//! ```no_run
//! let index = whycodes_index::WorkspaceIndex::start(vec![".".into()]);
//! let hits = index.query("main.rs", 20);
//! ```

mod content;
mod fuzzy;
pub mod policy;
mod store;
pub mod walk;
mod watch;

use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicU8, AtomicUsize, Ordering};
use std::sync::mpsc::{self, Receiver, Sender};
use std::sync::{Arc, Mutex, MutexGuard, RwLock, RwLockReadGuard, RwLockWriteGuard};
use std::thread::JoinHandle;
use std::time::{Duration, Instant};

pub use content::{
    ContentIndex, MAX_INDEX_BYTES, TRIGRAM_LEN, extract_trigrams, pack_trigram, required_trigrams,
};
pub use fuzzy::FileMatch;
use fuzzy::FuzzyEngine;
pub use store::{Entry, IndexStore};
pub use walk::{WalkEntry, WalkStats, walk_root, walk_root_limited};
use watch::{Change, ChangeKind, Command};

/// Project-local WhyCodes dir: `.whycodes`.
/// Duplicated from `whycodes-core::paths` because `index` is a leaf crate
/// and must not depend on `core`.
fn project_meta_dir(working_dir: &Path) -> PathBuf {
    working_dir.join(".whycodes")
}

/// Default cap on indexed entries per root.
pub const DEFAULT_MAX_ENTRIES: usize = 200_000;

/// Debounce window for watcher events (save storms, builds, checkouts).
const WATCH_DEBOUNCE: Duration = Duration::from_millis(250);

const STATE_SCANNING: u8 = 0;
const STATE_READY: u8 = 1;

/// Scan progress reported by [`WorkspaceIndex::status`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScanStatus {
    /// Initial walk still running; fuzzy queries already return partial hits.
    Scanning {
        /// Entries discovered so far (all roots).
        scanned: usize,
    },
    /// Index warm; tools may skip their own walks.
    Ready {
        /// Total indexed entries.
        total: usize,
        /// True when the entry cap stopped the scan early.
        truncated: bool,
    },
}

/// Options for [`WorkspaceIndex::start_with`].
#[derive(Debug, Clone)]
pub struct IndexOptions {
    /// Keep the index fresh with a filesystem watcher (default true).
    pub watch: bool,
    /// Hard cap on indexed entries per root (default 200k).
    pub max_entries: usize,
    /// Walk threads per root; 0 = auto (min(8, cores)), 1 = serial.
    pub threads: usize,
}

impl Default for IndexOptions {
    fn default() -> Self {
        Self {
            watch: true,
            max_entries: DEFAULT_MAX_ENTRIES,
            threads: 0,
        }
    }
}

/// Per-root state: the store (tools/browse) and the fuzzy engine (picker).
struct RootState {
    store: RwLock<IndexStore>,
    fuzzy: Mutex<FuzzyEngine>,
    content: RwLock<ContentIndex>,
}

/// State shared between the public handle and the scanner thread.
struct Shared {
    roots: Vec<PathBuf>,
    states: Vec<RootState>,
    scanned: AtomicUsize,
    state: AtomicU8,
    truncated: AtomicBool,
    cancel: AtomicBool,
    cmd_tx: Sender<Command>,
    /// Flipped by nucleo worker threads (via the notify callback) whenever
    /// fresh fuzzy results are ready; the UI polls with [`take_results_dirty`].
    results_dirty: Arc<AtomicBool>,
    threads: usize,
    max_entries: usize,
    watch: bool,
}

fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
    m.lock().unwrap_or_else(|e| e.into_inner())
}
fn read<T>(l: &RwLock<T>) -> RwLockReadGuard<'_, T> {
    l.read().unwrap_or_else(|e| e.into_inner())
}
fn write<T>(l: &RwLock<T>) -> RwLockWriteGuard<'_, T> {
    l.write().unwrap_or_else(|e| e.into_inner())
}

/// Resident workspace file index. Clone-handle via `Arc`.
///
/// The background scanner thread is owned by this handle: dropping the last
/// handle cancels the walk and joins the thread (bounded — the walk checks
/// the cancel flag per entry and the command loop wakes every 250 ms).
pub struct WorkspaceIndex {
    shared: Arc<Shared>,
    scanner: Option<JoinHandle<()>>,
}

impl WorkspaceIndex {
    /// Start scanning `roots` in the background with default options.
    pub fn start(roots: Vec<PathBuf>) -> Arc<Self> {
        Self::start_with(roots, IndexOptions::default())
    }

    /// Like [`start`](Self::start) with explicit options.
    ///
    /// Roots are canonicalized; missing/non-dir roots and roots nested inside
    /// an earlier root are dropped (they would duplicate entries).
    pub fn start_with(roots: Vec<PathBuf>, opts: IndexOptions) -> Arc<Self> {
        let roots = sanitize_roots(roots);
        let results_dirty = Arc::new(AtomicBool::new(false));
        let states = (0..roots.len())
            .map(|_| RootState {
                store: RwLock::new(IndexStore::new()),
                fuzzy: Mutex::new(FuzzyEngine::new(results_dirty.clone())),
                content: RwLock::new(ContentIndex::new()),
            })
            .collect();
        let (cmd_tx, cmd_rx) = mpsc::channel();
        let threads = if opts.threads == 0 {
            std::thread::available_parallelism()
                .map(|n| n.get().min(8))
                .unwrap_or(1)
        } else {
            opts.threads
        };
        let shared = Arc::new(Shared {
            roots,
            states,
            scanned: AtomicUsize::new(0),
            state: AtomicU8::new(STATE_SCANNING),
            truncated: AtomicBool::new(false),
            cancel: AtomicBool::new(false),
            cmd_tx,
            results_dirty,
            threads,
            max_entries: opts.max_entries,
            watch: opts.watch,
        });
        let thread_shared = shared.clone();
        let scanner = std::thread::Builder::new()
            .name("whycodes-index".into())
            .spawn(move || scanner_main(thread_shared, cmd_rx))
            .ok();
        Arc::new(Self { shared, scanner })
    }

    /// Roots of the index: `[working_dir]` plus every directory listed in
    /// `.whycodes/external_dirs_allowed`.
    pub fn project_roots(working_dir: &Path) -> Vec<PathBuf> {
        let mut roots = vec![working_dir.to_path_buf()];
        let allow = project_meta_dir(working_dir).join("external_dirs_allowed");
        if let Ok(content) = std::fs::read_to_string(&allow) {
            for line in content.lines() {
                let line = line.trim();
                if line.is_empty() || line.starts_with('#') {
                    continue;
                }
                roots.push(PathBuf::from(line));
            }
        }
        roots
    }

    /// The canonicalized roots being indexed.
    pub fn roots(&self) -> &[PathBuf] {
        &self.shared.roots
    }

    /// The primary root (working directory). `None` if no roots were indexed.
    pub fn primary_root(&self) -> Option<&Path> {
        self.shared.roots.first().map(PathBuf::as_path)
    }

    /// Current scan progress.
    pub fn status(&self) -> ScanStatus {
        if self.shared.state.load(Ordering::Acquire) == STATE_READY {
            ScanStatus::Ready {
                total: self.len(),
                truncated: self.shared.truncated.load(Ordering::Relaxed),
            }
        } else {
            ScanStatus::Scanning {
                scanned: self.shared.scanned.load(Ordering::Relaxed),
            }
        }
    }

    /// True once the initial walk has finished.
    pub fn is_ready(&self) -> bool {
        self.shared.state.load(Ordering::Acquire) == STATE_READY
    }

    /// Total indexed entries across roots.
    pub fn len(&self) -> usize {
        self.shared
            .states
            .iter()
            .map(|s| read(&s.store).len())
            .sum()
    }

    /// True when no entries are indexed (yet).
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Block until the index is ready or `timeout` elapses. For tests and
    /// one-shot CLI paths; the TUI should poll [`status`](Self::status).
    pub fn wait_ready(&self, timeout: Duration) -> bool {
        let deadline = Instant::now() + timeout;
        while !self.is_ready() && Instant::now() < deadline {
            std::thread::sleep(Duration::from_millis(2));
        }
        self.is_ready()
    }

    /// Non-blocking picker query: point every engine at `pattern` and read
    /// the matches currently available. Never waits on a rematch — fresh
    /// results are announced via [`take_results_dirty`] and picked up with
    /// [`read_matches`](Self::read_matches).
    ///
    /// Special forms: an empty pattern browses the top level of the primary
    /// root; a pattern ending in `/` browses that directory (store-backed,
    /// always synchronous).
    pub fn query_now(&self, pattern: &str, limit: usize) -> Vec<FileMatch> {
        let pattern = pattern.trim();
        if pattern.is_empty() {
            return self.browse(0, "");
        }
        if let Some(dir) = pattern.strip_suffix('/') {
            return self.browse(0, dir);
        }
        for state in &self.shared.states {
            lock(&state.fuzzy).set_query(pattern);
        }
        self.read_fuzzy(limit).0
    }

    /// Non-blocking re-read of current matches (call when
    /// [`take_results_dirty`](Self::take_results_dirty) returns true).
    pub fn read_matches(&self, limit: usize) -> Vec<FileMatch> {
        self.read_fuzzy(limit).0
    }

    /// One-shot check for freshly published matcher results.
    pub fn take_results_dirty(&self) -> bool {
        self.shared.results_dirty.swap(false, Ordering::Acquire)
    }

    /// Re-issue the last fuzzy query so workers publish a snapshot.
    ///
    /// Needed when a `tick(0)` missed notify and the picker is idle on an
    /// empty list. See `FuzzyEngine::rearm`.
    pub fn rearm_fuzzy(&self) {
        for state in &self.shared.states {
            lock(&state.fuzzy).rearm();
        }
    }

    /// True while any engine is still matching or ingesting (walk running).
    /// UIs should keep polling on a short cadence while this holds.
    pub fn matching(&self) -> bool {
        self.shared.states.iter().any(|s| lock(&s.fuzzy).nudge())
    }

    /// Merge current fuzzy results across roots, best-first, capped.
    fn read_fuzzy(&self, limit: usize) -> (Vec<FileMatch>, bool) {
        let mut all = Vec::new();
        let mut running = false;
        for (i, state) in self.shared.states.iter().enumerate() {
            let (mut hits, r) = lock(&state.fuzzy).read(limit);
            running |= r;
            for h in &mut hits {
                h.root = i as u16;
            }
            all.extend(hits);
        }
        all.sort_by(|a, b| {
            b.score
                .cmp(&a.score)
                .then_with(|| a.rel.len().cmp(&b.rel.len()))
        });
        all.truncate(limit);
        (all, running)
    }

    /// Blocking fuzzy query (tests / one-shot callers). UIs should use
    /// [`query_now`](Self::query_now) + the dirty flag instead.
    pub fn query(&self, pattern: &str, limit: usize) -> Vec<FileMatch> {
        let pattern = pattern.trim();
        if pattern.is_empty() {
            return self.browse(0, "");
        }
        if let Some(dir) = pattern.strip_suffix('/') {
            return self.browse(0, dir);
        }
        let mut all = Vec::new();
        for (i, state) in self.shared.states.iter().enumerate() {
            let mut hits = lock(&state.fuzzy).query_blocking(pattern, limit);
            for h in &mut hits {
                h.root = i as u16;
            }
            all.extend(hits);
        }
        all.sort_by(|a, b| {
            b.score
                .cmp(&a.score)
                .then_with(|| a.rel.len().cmp(&b.rel.len()))
        });
        all.truncate(limit);
        all
    }

    /// Depth-1 listing of `rel_dir` inside `root` (dirs first, alpha).
    /// `""` lists the top level. Filesystem-free — reads the store.
    pub fn browse(&self, root: u16, rel_dir: &str) -> Vec<FileMatch> {
        let Some(state) = self.shared.states.get(root as usize) else {
            return Vec::new();
        };
        read(&state.store)
            .browse(root, rel_dir)
            .into_iter()
            .map(|e| FileMatch {
                rel: e.rel.to_string(),
                is_dir: e.is_dir,
                score: 0,
                indices: Vec::new(),
                root,
            })
            .collect()
    }

    /// Visit every primary-root entry without cloning (tools hot path).
    /// Return `false` from `f` to stop early.
    pub fn visit(&self, f: &mut dyn FnMut(&Entry) -> bool) {
        if let Some(state) = self.shared.states.first() {
            for e in read(&state.store).entries() {
                if !f(e) {
                    return;
                }
            }
        }
    }

    /// Visit primary-root files under `search_root` that the content overlay
    /// cannot rule out for `pattern`. `None` means "do not prune" (regex /
    /// too short / Unicode case-fold / overlay not complete / path outside
    /// the primary root) — the caller should fall back to [`visit`].
    ///
    /// `f` receives `(abs, rel, size)` with `rel` scoped to `search_root`,
    /// matching [`visit`] + tools `visit_index`. Return `false` to stop.
    pub fn visit_content_candidates(
        &self,
        search_root: &Path,
        pattern: &str,
        case_insensitive: bool,
        f: &mut dyn FnMut(&Path, &str, u64) -> bool,
    ) -> Option<()> {
        let required = required_trigrams(pattern, case_insensitive)?;
        let state = self.shared.states.first()?;
        // Lock order: store → content (never reversed; see apply_changes).
        let store = read(&state.store);
        let content = read(&state.content);
        if !content.is_complete() {
            return None;
        }
        let root = self.shared.roots.first()?;
        let prefix = content_search_prefix(root, search_root)?;
        for e in store.entries() {
            if e.is_dir || !content_entry_in_scope(&prefix, &e.rel) {
                continue;
            }
            if !content.may_match(&e.rel, &required) {
                continue;
            }
            let rel = content_scoped_rel(&prefix, &e.rel);
            if !f(&root.join(&*e.rel), &rel, e.size) {
                break;
            }
        }
        Some(())
    }

    /// Clone of all primary-root entries (tools that need owned data).
    pub fn entries(&self) -> Vec<Entry> {
        self.shared
            .states
            .first()
            .map(|s| read(&s.store).entries().to_vec())
            .unwrap_or_default()
    }

    /// Absolute path for a match.
    pub fn resolve(&self, m: &FileMatch) -> PathBuf {
        self.shared.roots[m.root as usize].join(&m.rel)
    }

    /// Trigger a full background rescan (e.g. after branch switches).
    pub fn rescan(&self) {
        let _ = self.shared.cmd_tx.send(Command::Rescan);
    }
}

impl Drop for WorkspaceIndex {
    fn drop(&mut self) {
        self.shared.cancel.store(true, Ordering::Relaxed);
        let _ = self.shared.cmd_tx.send(Command::Shutdown);
        if let Some(h) = self.scanner.take() {
            // Windows ReadDirectoryChangesW watcher Drop can block; never
            // stall process exit on the scanner thread.
            let _ = h.join();
        }
    }
}

impl std::fmt::Debug for WorkspaceIndex {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("WorkspaceIndex")
            .field("roots", &self.shared.roots)
            .field("status", &self.status())
            .finish()
    }
}

fn content_search_prefix(primary: &Path, search_root: &Path) -> Option<String> {
    let search = std::fs::canonicalize(search_root).unwrap_or_else(|_| search_root.to_path_buf());
    let rel = search.strip_prefix(primary).ok()?;
    let prefix = rel.to_string_lossy().replace('\\', "/");
    Some(prefix.trim_matches('/').to_string())
}

fn content_entry_in_scope(prefix: &str, rel: &str) -> bool {
    prefix.is_empty()
        || (rel.len() > prefix.len()
            && rel.starts_with(prefix)
            && rel.as_bytes().get(prefix.len()) == Some(&b'/'))
}

fn content_scoped_rel(prefix: &str, rel: &str) -> String {
    if prefix.is_empty() {
        rel.to_string()
    } else {
        rel[prefix.len() + 1..].to_string()
    }
}

/// Canonicalize roots, drop missing/non-dirs, dedup exact and nested roots.
fn sanitize_roots(roots: Vec<PathBuf>) -> Vec<PathBuf> {
    let mut out: Vec<PathBuf> = Vec::new();
    for root in roots {
        let Ok(canon) = std::fs::canonicalize(&root) else {
            continue;
        };
        if !canon.is_dir() {
            continue;
        }
        // A root equal to or nested inside an earlier one duplicates entries.
        if out.iter().any(|r| canon.starts_with(r)) {
            continue;
        }
        out.push(canon);
    }
    out
}

#[cfg(test)]
pub(crate) fn recv_should_stop(e: mpsc::RecvTimeoutError) -> bool {
    matches!(e, mpsc::RecvTimeoutError::Disconnected)
}

#[derive(Debug)]
pub(crate) enum RecvAct {
    Stop,
    Idle,
    Rescan,
    Batch(Vec<Change>),
}

pub(crate) fn classify_recv(r: Result<Command, mpsc::RecvTimeoutError>) -> RecvAct {
    match r {
        Ok(Command::Shutdown) => RecvAct::Stop,
        Ok(Command::Rescan) => RecvAct::Rescan,
        Ok(Command::Batch(cs)) => RecvAct::Batch(cs),
        Err(mpsc::RecvTimeoutError::Disconnected) => RecvAct::Stop,
        Err(mpsc::RecvTimeoutError::Timeout) => RecvAct::Idle,
    }
}

/// Scanner thread body: initial scan, then watcher-fed delta loop.
fn scanner_main(shared: Arc<Shared>, cmd_rx: Receiver<Command>) {
    full_scan(&shared);
    if shared.cancel.load(Ordering::Relaxed) {
        return;
    }

    // Arm notify *before* flipping Ready. `wait_ready` is the test/TUI
    // signal that creates will be seen — if Ready precedes `watch()`, a
    // write in that window is lost (CI: `watcher_picks_up_changes`).
    let watcher = if shared.watch {
        watch::spawn(&shared.roots, shared.cmd_tx.clone())
    } else {
        None
    };
    shared.state.store(STATE_READY, Ordering::Release);

    let mut pending: Vec<Change> = Vec::new();
    loop {
        if shared.cancel.load(Ordering::Relaxed) {
            break;
        }
        match classify_recv(cmd_rx.recv_timeout(WATCH_DEBOUNCE)) {
            RecvAct::Stop => break,
            RecvAct::Idle => {}
            RecvAct::Rescan => {
                pending.clear();
                full_scan(&shared);
                if !shared.cancel.load(Ordering::Relaxed) {
                    shared.state.store(STATE_READY, Ordering::Release);
                }
            }
            RecvAct::Batch(cs) => pending.extend(cs),
        }
        if !pending.is_empty() {
            apply_changes(&shared, std::mem::take(&mut pending));
        }
    }
    // Drop the watcher off this thread: Windows ReadDirectoryChangesW
    // teardown can block, and Drop of WorkspaceIndex joins us.
    if let Some(watcher) = watcher {
        detach_watcher(watcher);
    }
}

/// Spawn a thread whose only job is `drop(watcher)`. Failure to spawn is
/// logged; the watcher then drops on this thread (join may stall on Windows).
fn detach_watcher(watcher: notify::RecommendedWatcher) {
    log_unwatch_spawn(
        std::thread::Builder::new()
            .name("whycodes-index-unwatch".into())
            .spawn(move || drop(watcher)),
    );
}

pub(crate) fn log_unwatch_spawn(result: std::io::Result<std::thread::JoinHandle<()>>) {
    if let Err(e) = result {
        tracing::debug!(error = %e, "index unwatch thread spawn failed");
    }
}

/// Full (re)scan of every root: streams entries into the fuzzy engines
/// (queries stay live during the scan) and fills the stores.
fn full_scan(shared: &Arc<Shared>) {
    shared.scanned.store(0, Ordering::Relaxed);
    shared.truncated.store(false, Ordering::Relaxed);
    shared.state.store(STATE_SCANNING, Ordering::Release);

    for (i, state) in shared.states.iter().enumerate() {
        if shared.cancel.load(Ordering::Relaxed) {
            return;
        }
        write(&state.store).clear();
        write(&state.content).clear();
        let injector = {
            let mut fz = lock(&state.fuzzy);
            fz.restart();
            fz.injector()
        };
        let remaining = shared
            .max_entries
            .saturating_sub(shared.scanned.load(Ordering::Relaxed));
        if remaining == 0 {
            shared.truncated.store(true, Ordering::Relaxed);
            break;
        }
        // Walk threads push straight into nucleo (streaming matches) and
        // queue entries for a bulk store insert afterwards.
        let queue = Mutex::new(Vec::new());
        let stats = walk::walk_root(
            &shared.roots[i],
            shared.threads,
            remaining,
            &shared.scanned,
            &shared.cancel,
            &|e: WalkEntry| {
                FuzzyEngine::push(&injector, &e.rel, e.is_dir);
                lock(&queue).push(e);
            },
        );
        // A cancel inside stops the fill; the next root's check returns.
        fill_root(shared, i, std::mem::take(&mut *lock(&queue)));
        if stats.truncated {
            shared.truncated.store(true, Ordering::Relaxed);
            break;
        }
    }
}

/// Bulk-insert one root's walked entries into its stores. Reading every
/// file for the content index is the slow part: on a huge tree (a home
/// directory hits `max_entries`) it ran for minutes, and the drop at exit
/// joined it, so the process never quit. On a network mount (a WSL share)
/// each read costs milliseconds, so files are read with no lock held:
/// holding the store lock across them froze every `entries()` caller,
/// including the TUI's first frame.
fn fill_root(shared: &Shared, i: usize, entries: Vec<WalkEntry>) {
    let state = &shared.states[i];
    let mut files = Vec::new();
    {
        let mut store = write(&state.store);
        for e in entries {
            if !e.is_dir {
                files.push((e.rel.clone(), e.size));
            }
            store.insert(i as u16, e.rel, e.is_dir, e.size);
        }
    }
    for (rel, size) in files {
        if shared.cancel.load(Ordering::Relaxed) {
            return;
        }
        let posting = ContentIndex::load(&shared.roots[i], &rel, size);
        write(&state.content).insert(&rel, posting);
    }
    write(&state.content).mark_complete();
}

/// Apply one debounced watcher batch: upserts push into nucleo; removals
/// rebuild that root's engine from the store (nucleo has no item removal).
pub(crate) fn apply_changes(shared: &Arc<Shared>, changes: Vec<Change>) {
    // Group by root so each engine is touched at most once per batch.
    let mut by_root: rustc_hash::FxHashMap<u16, Vec<Change>> = Default::default();
    for c in changes {
        by_root.entry(c.root).or_default().push(c);
    }
    for (root_idx, cs) in by_root {
        let Some(state) = shared.states.get(root_idx as usize) else {
            continue;
        };
        let root = &shared.roots[root_idx as usize];
        let mut saw_removal = false;
        let mut upserts: Vec<(Box<str>, bool)> = Vec::new();
        {
            let mut store = write(&state.store);
            let mut content = write(&state.content);
            for c in cs {
                match c.kind {
                    ChangeKind::Remove => {
                        store.remove_tree(root_idx, &c.rel);
                        content.remove_tree(&c.rel);
                        saw_removal = true;
                    }
                    ChangeKind::Upsert => {
                        // Re-stat; a create+delete inside one debounce window
                        // collapses to a remove.
                        match std::fs::symlink_metadata(root.join(&c.rel)) {
                            Ok(md) => {
                                let is_dir = md.is_dir();
                                let size = if is_dir { 0 } else { md.len() };
                                upserts.push((c.rel.clone().into_boxed_str(), is_dir));
                                if is_dir {
                                    content.remove(&c.rel);
                                } else {
                                    content.upsert(root, &c.rel, size);
                                }
                                store.insert(root_idx, c.rel.into_boxed_str(), is_dir, size);
                            }
                            Err(_) => {
                                store.remove_tree(root_idx, &c.rel);
                                content.remove_tree(&c.rel);
                                saw_removal = true;
                            }
                        }
                    }
                }
            }
        }
        // Lock order is store → content, then (after drop) fuzzy → store.
        // Never reverse either pair.
        let mut fz = lock(&state.fuzzy);
        if saw_removal {
            fz.restart();
            let inj = fz.injector();
            for e in read(&state.store).iter_root(root_idx) {
                FuzzyEngine::push(&inj, &e.rel, e.is_dir);
            }
        } else {
            let inj = fz.injector();
            for (rel, is_dir) in upserts {
                FuzzyEngine::push(&inj, &rel, is_dir);
            }
        }
    }
}

#[cfg(test)]
#[path = "lib_tests.rs"]
mod tests;