whycodes-index 0.6.30

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
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
use super::*;
use std::fs;

impl WorkspaceIndex {
    fn apply_test_changes(&self, changes: Vec<Change>) {
        apply_changes(&self.shared, changes);
    }

    fn cancel_only(&self) {
        self.shared.cancel.store(true, Ordering::Relaxed);
    }

    fn send_batch(&self, changes: Vec<Change>) {
        let _ = self.shared.cmd_tx.send(Command::Batch(changes));
    }
}

fn fixture() -> tempfile::TempDir {
    let dir = tempfile::TempDir::new().unwrap();
    let root = dir.path();
    fs::create_dir_all(root.join("src/nested")).unwrap();
    fs::write(root.join("src/main.rs"), "fn main() {}").unwrap();
    fs::write(root.join("src/nested/deep.rs"), "// deep").unwrap();
    fs::write(root.join("Cargo.toml"), "[package]").unwrap();
    fs::create_dir_all(root.join("target/debug")).unwrap();
    fs::write(root.join("target/debug/x.o"), "bin").unwrap();
    fs::write(root.join(".env"), "SECRET=1").unwrap();
    dir
}

#[test]
fn end_to_end_scan_query_browse() {
    let dir = fixture();
    let idx = WorkspaceIndex::start_with(
        vec![dir.path().to_path_buf()],
        IndexOptions {
            watch: false,
            ..Default::default()
        },
    );
    assert!(idx.wait_ready(Duration::from_secs(10)));
    match idx.status() {
        ScanStatus::Ready { total, truncated } => {
            assert!(total >= 5, "total={total}");
            assert!(!truncated);
        }
        other => panic!("expected Ready, got {other:?}"),
    }

    // Fuzzy.
    let hits = idx.query("main.rs", 10);
    assert!(!hits.is_empty());
    assert_eq!(hits[0].rel, "src/main.rs");
    assert_eq!(hits[0].root, 0);

    // Pruned entries never made it in.
    assert!(idx.query("x.o", 10).is_empty());
    assert!(idx.query(".env", 10).is_empty());

    // Browse: empty query → top level, dirs first.
    let top = idx.query("", 20);
    assert!(top.iter().any(|m| m.rel == "src" && m.is_dir));
    assert!(top.iter().any(|m| m.rel == "Cargo.toml" && !m.is_dir));
    assert!(top[0].is_dir, "dirs first: {top:?}");

    // Browse subdir via trailing slash.
    let src = idx.query("src/", 20);
    assert!(src.iter().any(|m| m.rel == "src/main.rs"));
    assert!(src.iter().all(|m| m.rel.starts_with("src/")));

    // Tools view.
    assert!(idx.entries().iter().any(|e| &*e.rel == "src/main.rs"));
    let mut seen = 0;
    idx.visit(&mut |_| {
        seen += 1;
        true
    });
    assert!(seen >= 5);
    let mut stopped = 0;
    idx.visit(&mut |_| {
        stopped += 1;
        false
    });
    assert_eq!(stopped, 1);

    // Resolve.
    let m = &hits[0];
    assert!(idx.resolve(m).ends_with("src/main.rs"));
}

// Skipped by `scripts/coverage.sh` (notify-timing flake under llvm-cov).
#[test]
fn watcher_picks_up_changes() {
    let dir = fixture();
    let idx = WorkspaceIndex::start(vec![dir.path().to_path_buf()]);
    assert!(idx.wait_ready(Duration::from_secs(10)));
    let before = idx.len();

    // Create → appears. `wait_ready` now means the watcher is armed, so
    // this write cannot race the first `watch()`. Still poll: debounce
    // is 250 ms and CI can starve the apply thread.
    fs::write(dir.path().join("src/new_file.rs"), "// new").unwrap();
    let deadline = Instant::now() + Duration::from_secs(15);
    let appeared = loop {
        let hit = idx
            .query("new_file", 10)
            .iter()
            .any(|m| m.rel == "src/new_file.rs");
        if hit || Instant::now() >= deadline {
            break hit;
        }
        std::thread::sleep(Duration::from_millis(50));
    };
    assert!(appeared, "create must be indexed");
    assert_eq!(idx.len(), before + 1, "create adds one store entry");

    // Delete → disappears from the store (fuzzy engine rebuilds).
    fs::remove_file(dir.path().join("src/new_file.rs")).unwrap();
    let deadline = Instant::now() + Duration::from_secs(15);
    loop {
        let gone = {
            let mut found = false;
            idx.visit(&mut |e| {
                found |= &*e.rel == "src/new_file.rs";
                true
            });
            !found
        };
        if gone || Instant::now() >= deadline {
            break;
        }
        std::thread::sleep(Duration::from_millis(50));
    }
    let mut found = false;
    idx.visit(&mut |e| {
        found |= &*e.rel == "src/new_file.rs";
        true
    });
    assert!(!found, "delete must be removed from store");
}

#[test]
fn sanitize_roots_dedups_nested() {
    let dir = fixture();
    let root = dir.path().canonicalize().unwrap();
    let roots = sanitize_roots(vec![
        root.clone(),
        root.join("src"),     // nested → dropped
        root.join("missing"), // nonexistent → dropped
        root.clone(),         // dup → dropped
    ]);
    assert_eq!(roots, vec![root]);
}

#[test]
fn project_roots_without_allowlist() {
    let dir = fixture();
    let roots = WorkspaceIndex::project_roots(dir.path());
    assert_eq!(roots, vec![dir.path().to_path_buf()]);
}

#[test]
fn project_roots_reads_allowlist() {
    let dir = fixture();
    let ext = tempfile::TempDir::new().unwrap();
    fs::create_dir_all(dir.path().join(".whycodes")).unwrap();
    fs::write(
        dir.path().join(".whycodes/external_dirs_allowed"),
        format!("# comment\n{}\n\n", ext.path().display()),
    )
    .unwrap();
    let roots = WorkspaceIndex::project_roots(dir.path());
    assert_eq!(roots.len(), 2);
    assert_eq!(roots[0], dir.path());
    assert_eq!(roots[1], ext.path());
}

#[test]
fn empty_roots_is_safe() {
    let idx = WorkspaceIndex::start_with(vec![], IndexOptions::default());
    assert!(idx.roots().is_empty());
    assert!(idx.primary_root().is_none());
    assert!(idx.query("x", 5).is_empty());
}

/// The UI contract: query_now never blocks on a rematch, fresh results
/// arrive via the dirty flag, and matching eventually settles.
#[test]
fn async_query_eventually_consistent() {
    // 5k files — big enough that a full rematch is measurable.
    let dir = tempfile::TempDir::new().unwrap();
    for d in 0..50 {
        let p = dir.path().join(format!("pkg{d}/src"));
        fs::create_dir_all(&p).unwrap();
        for f in 0..100 {
            fs::write(p.join(format!("file{f}.rs")), "x").unwrap();
        }
    }
    fs::write(dir.path().join("pkg7/src/needle.rs"), "x").unwrap();
    let idx = WorkspaceIndex::start_with(
        vec![dir.path().to_path_buf()],
        IndexOptions {
            watch: false,
            ..Default::default()
        },
    );
    assert!(idx.wait_ready(Duration::from_secs(30)));

    // set path returns fast even with a full rematch queued.
    let t = Instant::now();
    let _ = idx.query_now("needle.rs", 10);
    let first_ms = t.elapsed().as_secs_f64() * 1000.0;
    assert!(first_ms < 50.0, "query_now blocked {first_ms:.1}ms");

    // Dirty flag flips and results converge without another keystroke.
    // Always nudge (`matching`) so a missed nucleo notify cannot stall
    // the snapshot — same contract the TUI picker now uses.
    let deadline = Instant::now() + Duration::from_secs(5);
    let mut found = false;
    while Instant::now() < deadline {
        let dirty = idx.take_results_dirty();
        let running = idx.matching();
        if dirty || !running {
            let hits = idx.read_matches(10);
            if hits.iter().any(|m| m.rel.ends_with("needle.rs")) {
                found = true;
                break;
            }
        }
        std::thread::sleep(Duration::from_millis(2));
    }
    assert!(found, "needle.rs never appeared via dirty-flag polling");
    // …and matching reports quiescence once converged.
    let deadline = Instant::now() + Duration::from_secs(5);
    while idx.matching() && Instant::now() < deadline {
        std::thread::sleep(Duration::from_millis(2));
    }
    assert!(!idx.matching());
}

#[test]
fn cancel_aborts_scan_and_loop() {
    let dir = fixture();
    let idx = WorkspaceIndex::start_with(
        vec![dir.path().to_path_buf()],
        IndexOptions {
            watch: true,
            threads: 1,
            ..Default::default()
        },
    );
    assert!(idx.wait_ready(Duration::from_secs(10)));
    std::thread::sleep(Duration::from_millis(300));
    idx.cancel_only();
    std::thread::sleep(Duration::from_millis(300));
    let _ = idx.query_now("rs", 20);
    let _ = idx.matching();
    let hits = idx.read_matches(20);
    let _ = hits.len();

    let dir = fixture();
    let idx = WorkspaceIndex::start_with(
        vec![dir.path().to_path_buf()],
        IndexOptions {
            watch: false,
            threads: 1,
            ..Default::default()
        },
    );
    idx.cancel_only();
    let _ = idx.wait_ready(Duration::from_millis(200));
}

#[test]
fn fill_root_stops_reading_files_once_cancelled() {
    let dir = fixture();
    let idx = WorkspaceIndex::start_with(
        vec![dir.path().to_path_buf()],
        IndexOptions {
            watch: false,
            threads: 1,
            ..Default::default()
        },
    );
    assert!(idx.wait_ready(Duration::from_secs(10)));
    let entry = |rel: &str| WalkEntry {
        rel: rel.into(),
        is_dir: false,
        size: 0,
    };
    let content = || read(&idx.shared.states[0].content);
    write(&idx.shared.states[0].content).clear();
    fill_root(&idx.shared, 0, vec![entry("src/main.rs")]);
    assert_eq!(content().indexed_len(), 1);
    assert!(content().is_complete());
    write(&idx.shared.states[0].content).clear();
    idx.cancel_only();
    fill_root(&idx.shared, 0, vec![entry("src/main.rs")]);
    assert_eq!(content().indexed_len(), 0);
    assert!(!content().is_complete());
}

#[test]
fn fill_root_reads_files_without_holding_the_store_lock() {
    // A network mount (WSL share) makes each read slow; `entries()` callers,
    // the TUI's first frame among them, must not wait on those reads.
    let dir = fixture();
    let idx = WorkspaceIndex::start_with(
        vec![dir.path().to_path_buf()],
        IndexOptions {
            watch: false,
            threads: 1,
            ..Default::default()
        },
    );
    assert!(idx.wait_ready(Duration::from_secs(10)));
    let entry = WalkEntry {
        rel: "src/main.rs".into(),
        is_dir: false,
        size: 0,
    };
    // Hold the content lock: the store fill must still finish, and the store
    // must stay readable while the read loop waits on content.
    let content = write(&idx.shared.states[0].content);
    let filled = std::thread::scope(|s| {
        let filler = s.spawn(|| fill_root(&idx.shared, 0, vec![entry]));
        let deadline = Instant::now() + Duration::from_secs(5);
        let mut filled = false;
        while !filled && Instant::now() < deadline {
            std::thread::sleep(Duration::from_millis(2));
            // `try_read`: a store held across the reads must fail the test,
            // not hang it.
            filled = idx.shared.states[0].store.try_read().is_ok_and(|store| {
                store
                    .entries()
                    .iter()
                    .any(|e| &*e.rel == "src/main.rs" && e.size == 0)
            });
        }
        drop(content);
        filler.join().unwrap();
        filled
    });
    assert!(filled, "store fill waited on the content lock");
}

#[test]
fn log_unwatch_spawn_ok_and_err() {
    log_unwatch_spawn(std::thread::Builder::new().spawn(|| {}));
    log_unwatch_spawn(Err(std::io::Error::other("no thread")));
}

#[test]
fn query_now_same_pattern_after_blocking_still_hits() {
    let dir = fixture();
    let idx = WorkspaceIndex::start_with(
        vec![dir.path().to_path_buf()],
        IndexOptions {
            watch: false,
            threads: 1,
            ..Default::default()
        },
    );
    assert!(idx.wait_ready(Duration::from_secs(10)));
    assert!(
        idx.query("main", 10).iter().any(|m| m.rel == "src/main.rs"),
        "blocking fuzzy missed src/main.rs"
    );
    // `set_query` used to return immediately on the same pattern; a missed
    // notify then left `query_now` on an empty snapshot (CI picker flake).
    assert!(
        idx.query_now("main", 10)
            .iter()
            .any(|m| m.rel == "src/main.rs"),
        "same-pattern query_now missed src/main.rs"
    );
    assert!(idx.query_now("zzzznotapath", 10).is_empty());
}

#[test]
fn query_now_sorts_multiple_hits() {
    let dir = fixture();
    let idx = WorkspaceIndex::start_with(
        vec![dir.path().to_path_buf()],
        IndexOptions {
            watch: false,
            threads: 1,
            ..Default::default()
        },
    );
    assert!(idx.wait_ready(Duration::from_secs(10)));
    let _ = idx.query_now("rs", 20);
    idx.rearm_fuzzy();
    let deadline = Instant::now() + Duration::from_secs(5);
    let mut hits = Vec::new();
    while Instant::now() < deadline {
        let _ = idx.matching();
        hits = idx.read_matches(20);
        if hits.len() >= 2 {
            break;
        }
        std::thread::sleep(Duration::from_millis(10));
    }
    assert!(hits.len() >= 2, "{hits:?}");
}

#[test]
fn blocking_query_merges_and_sorts_across_roots() {
    let a = fixture();
    let b = fixture();
    let idx = WorkspaceIndex::start_with(
        vec![a.path().to_path_buf(), b.path().to_path_buf()],
        IndexOptions {
            watch: false,
            threads: 1,
            ..Default::default()
        },
    );
    assert!(idx.wait_ready(Duration::from_secs(10)));

    // Distinct scores: the comparator's score branch runs on >=2 hits.
    let hits = idx.query("rs", 20);
    assert!(hits.len() >= 4, "{hits:?}");
    for w in hits.windows(2) {
        assert!(
            w[0].score > w[1].score
                || (w[0].score == w[1].score && w[0].rel.len() <= w[1].rel.len()),
            "unsorted: {w:?}"
        );
    }

    // Same file in both roots -> equal scores, exercising the rel-length
    // tie-break in the sort comparator.
    let tied = idx.query("main.rs", 10);
    assert_eq!(tied.len(), 2, "{tied:?}");
    assert_eq!(tied[0].score, tied[1].score);
    assert!(tied.iter().any(|m| m.root == 0));
    assert!(tied.iter().any(|m| m.root == 1));
}

#[test]
fn recv_should_stop_only_on_disconnect() {
    assert!(!recv_should_stop(
        std::sync::mpsc::RecvTimeoutError::Timeout
    ));
    assert!(recv_should_stop(
        std::sync::mpsc::RecvTimeoutError::Disconnected
    ));
    assert!(matches!(
        classify_recv(Err(std::sync::mpsc::RecvTimeoutError::Timeout)),
        RecvAct::Idle
    ));
    assert!(matches!(
        classify_recv(Err(std::sync::mpsc::RecvTimeoutError::Disconnected)),
        RecvAct::Stop
    ));
    assert!(matches!(
        classify_recv(Ok(Command::Shutdown)),
        RecvAct::Stop
    ));
    assert!(matches!(
        classify_recv(Ok(Command::Rescan)),
        RecvAct::Rescan
    ));
    assert!(matches!(
        classify_recv(Ok(Command::Batch(vec![]))),
        RecvAct::Batch(_)
    ));
}

#[test]
fn start_helpers_status_browse_and_rescan() {
    let dir = fixture();
    let file = dir.path().join("not-a-dir.txt");
    fs::write(&file, "x").unwrap();
    let idx = WorkspaceIndex::start(vec![
        dir.path().to_path_buf(),
        file,
        PathBuf::from("/no/such/index/root"),
    ]);
    assert!(idx.wait_ready(Duration::from_secs(10)));
    assert_eq!(
        idx.primary_root(),
        Some(dir.path().canonicalize().unwrap().as_path())
    );
    assert!(!idx.is_empty());
    let _ = format!("{:?}", idx);
    match idx.status() {
        ScanStatus::Ready { .. } => {}
        other => panic!("{other:?}"),
    }
    assert!(idx.browse(99, "").is_empty());
    let now = idx.query_now("", 10);
    assert!(now.iter().any(|m| m.rel == "src" && m.is_dir));
    let src = idx.query_now("src/", 10);
    assert!(src.iter().any(|m| m.rel.starts_with("src/")));
    idx.rescan();
    let deadline = Instant::now() + Duration::from_secs(10);
    while idx.is_ready() && Instant::now() < deadline {
        std::thread::sleep(Duration::from_millis(2));
    }
    assert!(idx.wait_ready(Duration::from_secs(10)));
    assert!(idx.entries().iter().any(|e| &*e.rel == "src/main.rs"));
    let _ = idx.query_now("rs", 20);
    let _ = idx.read_matches(20);
}

#[test]
fn scanning_status_before_ready_and_empty_visit() {
    let dir = fixture();
    let idx = WorkspaceIndex::start_with(
        vec![dir.path().to_path_buf()],
        IndexOptions {
            watch: false,
            threads: 1,
            max_entries: DEFAULT_MAX_ENTRIES,
        },
    );
    let _ = idx.status();
    let _ = idx.is_empty();
    assert!(idx.wait_ready(Duration::from_secs(10)));

    let empty = WorkspaceIndex::start_with(vec![], IndexOptions::default());
    assert!(empty.is_empty());
    empty.visit(&mut |_| panic!("no entries"));
    assert!(empty.entries().is_empty());
    assert!(empty.query_now("x", 5).is_empty());
    assert!(empty.query("x", 5).is_empty());
}

#[test]
fn max_entries_one_truncates_walk() {
    let dir = fixture();
    let idx = WorkspaceIndex::start_with(
        vec![dir.path().to_path_buf()],
        IndexOptions {
            watch: false,
            max_entries: 1,
            threads: 1,
        },
    );
    assert!(idx.wait_ready(Duration::from_secs(10)));
    match idx.status() {
        ScanStatus::Ready { truncated, .. } => assert!(truncated),
        other => panic!("{other:?}"),
    }
}

#[test]
fn max_entries_zero_truncates() {
    let dir = fixture();
    let idx = WorkspaceIndex::start_with(
        vec![dir.path().to_path_buf()],
        IndexOptions {
            watch: false,
            max_entries: 0,
            threads: 1,
        },
    );
    assert!(idx.wait_ready(Duration::from_secs(10)));
    match idx.status() {
        ScanStatus::Ready { truncated, .. } => assert!(truncated),
        other => panic!("{other:?}"),
    }
}

#[test]
fn apply_changes_upsert_and_remove() {
    let dir = fixture();
    let idx = WorkspaceIndex::start_with(
        vec![dir.path().to_path_buf()],
        IndexOptions {
            watch: false,
            threads: 1,
            ..Default::default()
        },
    );
    assert!(idx.wait_ready(Duration::from_secs(10)));
    let new = dir.path().join("src/extra.rs");
    fs::write(&new, "fn extra() {}").unwrap();
    idx.apply_test_changes(vec![Change {
        root: 0,
        rel: "src/extra.rs".into(),
        kind: ChangeKind::Upsert,
    }]);
    let mut found = false;
    idx.visit(&mut |e| {
        found |= &*e.rel == "src/extra.rs";
        true
    });
    assert!(found, "upsert must land in the store");

    fs::remove_file(&new).unwrap();
    idx.apply_test_changes(vec![Change {
        root: 0,
        rel: "src/extra.rs".into(),
        kind: ChangeKind::Upsert,
    }]);
    found = false;
    idx.visit(&mut |e| {
        found |= &*e.rel == "src/extra.rs";
        true
    });
    assert!(!found, "gone file collapses to remove");

    idx.apply_test_changes(vec![Change {
        root: 0,
        rel: "src/main.rs".into(),
        kind: ChangeKind::Remove,
    }]);
    found = false;
    idx.visit(&mut |e| {
        found |= &*e.rel == "src/main.rs";
        true
    });
    assert!(!found);

    idx.apply_test_changes(vec![Change {
        root: 9,
        rel: "nope.rs".into(),
        kind: ChangeKind::Remove,
    }]);
}

/// Drive `scanner_main`'s `RecvAct::Batch` arm through the command channel.
/// Coverage skips `watcher_picks_up_changes` (notify flake under llvm-cov),
/// so this is the deterministic path that keeps those two `lib.rs` lines
/// at the 100% floor.
#[test]
fn scanner_applies_batched_command() {
    let dir = fixture();
    let idx = WorkspaceIndex::start_with(
        vec![dir.path().to_path_buf()],
        IndexOptions {
            watch: false,
            threads: 1,
            ..Default::default()
        },
    );
    assert!(idx.wait_ready(Duration::from_secs(10)));
    fs::write(dir.path().join("src/batch.rs"), "// batch").unwrap();
    idx.send_batch(vec![Change {
        root: 0,
        rel: "src/batch.rs".into(),
        kind: ChangeKind::Upsert,
    }]);
    let deadline = Instant::now() + Duration::from_secs(5);
    let appeared = loop {
        let mut found = false;
        idx.visit(&mut |e| {
            found |= &*e.rel == "src/batch.rs";
            true
        });
        if found || Instant::now() >= deadline {
            break found;
        }
        std::thread::sleep(Duration::from_millis(20));
    };
    assert!(appeared, "scanner_main must apply Command::Batch");
}

#[test]
fn lock_helpers_survive_poison() {
    fn poison<T: Send + 'static>(make: fn() -> T) {
        let m = std::sync::Arc::new(std::sync::Mutex::new(make()));
        let m2 = std::sync::Arc::clone(&m);
        let _ = std::thread::spawn(move || {
            let _g = m2.lock().unwrap();
            panic!("poison");
        })
        .join();
        let _g = lock(&m);
    }
    poison(|| 1u8);
    let r = std::sync::Arc::new(std::sync::RwLock::new(0u8));
    let r2 = std::sync::Arc::clone(&r);
    let _ = std::thread::spawn(move || {
        let _g = r2.write().unwrap();
        panic!("poison");
    })
    .join();
    drop(read(&r));
    let w = std::sync::Arc::new(std::sync::RwLock::new(0u8));
    let w2 = std::sync::Arc::clone(&w);
    let _ = std::thread::spawn(move || {
        let _g = w2.write().unwrap();
        panic!("poison");
    })
    .join();
    drop(write(&w));
    poison(FuzzyEngine::default);
    poison(Vec::<WalkEntry>::new);
    let store = std::sync::Arc::new(std::sync::RwLock::new(IndexStore::new()));
    let store2 = std::sync::Arc::clone(&store);
    let _ = std::thread::spawn(move || {
        let _g = store2.write().unwrap();
        panic!("poison");
    })
    .join();
    drop(read(&store));
    let store = std::sync::Arc::new(std::sync::RwLock::new(IndexStore::new()));
    let store2 = std::sync::Arc::clone(&store);
    let _ = std::thread::spawn(move || {
        let _g = store2.write().unwrap();
        panic!("poison");
    })
    .join();
    drop(write(&store));
}

#[test]
fn visit_content_candidates_prunes_and_scopes() {
    let dir = fixture();
    fs::write(dir.path().join("src/main.rs"), "fn unique_needle() {}\n").unwrap();
    fs::write(dir.path().join("src/nested/deep.rs"), "// other\n").unwrap();
    fs::write(dir.path().join("srcx.rs"), "fn unique_needle() {}\n").unwrap();
    let idx = WorkspaceIndex::start_with(
        vec![dir.path().to_path_buf()],
        IndexOptions {
            watch: false,
            threads: 1,
            ..Default::default()
        },
    );
    assert!(idx.wait_ready(Duration::from_secs(10)));

    let mut hits = Vec::new();
    assert!(
        idx.visit_content_candidates(dir.path(), "unique_needle", false, &mut |_, rel, _| {
            hits.push(rel.to_string());
            true
        })
        .is_some()
    );
    assert!(hits.contains(&"src/main.rs".to_string()), "{hits:?}");
    assert!(hits.contains(&"srcx.rs".to_string()), "{hits:?}");
    assert_eq!(hits.len(), 2, "{hits:?}");

    let mut scoped = Vec::new();
    assert!(
        idx.visit_content_candidates(
            &dir.path().join("src"),
            "unique_needle",
            false,
            &mut |_, rel, _| {
                scoped.push(rel.to_string());
                true
            }
        )
        .is_some()
    );
    assert_eq!(scoped, vec!["main.rs".to_string()]);
    assert!(!scoped.iter().any(|r| r.contains("srcx")), "{scoped:?}");

    let mut stopped = 0;
    idx.visit_content_candidates(dir.path(), "unique_needle", false, &mut |_, _, _| {
        stopped += 1;
        false
    });
    assert_eq!(stopped, 1);

    assert!(
        idx.visit_content_candidates(dir.path(), "unique.needle", false, &mut |_, _, _| true)
            .is_none(),
        "regex must not prune"
    );
    assert!(
        idx.visit_content_candidates(dir.path(), "ab", false, &mut |_, _, _| true)
            .is_none()
    );
    assert!(
        idx.visit_content_candidates(
            Path::new("/no/such/grep/root"),
            "unique_needle",
            false,
            &mut |_, _, _| true
        )
        .is_none()
    );

    let empty = WorkspaceIndex::start_with(vec![], IndexOptions::default());
    assert!(
        empty
            .visit_content_candidates(Path::new("."), "unique_needle", false, &mut |_, _, _| true)
            .is_none()
    );
}

#[test]
fn visit_content_candidates_incomplete_when_truncated_empty() {
    let dir = fixture();
    let idx = WorkspaceIndex::start_with(
        vec![dir.path().to_path_buf()],
        IndexOptions {
            watch: false,
            max_entries: 0,
            threads: 1,
        },
    );
    assert!(idx.wait_ready(Duration::from_secs(10)));
    assert!(
        idx.visit_content_candidates(dir.path(), "unique_needle", false, &mut |_, _, _| true)
            .is_none()
    );
}

#[test]
fn apply_changes_updates_content_overlay() {
    let dir = fixture();
    let idx = WorkspaceIndex::start_with(
        vec![dir.path().to_path_buf()],
        IndexOptions {
            watch: false,
            threads: 1,
            ..Default::default()
        },
    );
    assert!(idx.wait_ready(Duration::from_secs(10)));
    fs::write(dir.path().join("src/extra.rs"), "fn extra_unique() {}\n").unwrap();
    idx.apply_test_changes(vec![Change {
        root: 0,
        rel: "src/extra.rs".into(),
        kind: ChangeKind::Upsert,
    }]);
    let mut hits = Vec::new();
    idx.visit_content_candidates(dir.path(), "extra_unique", false, &mut |_, rel, _| {
        hits.push(rel.to_string());
        true
    });
    assert_eq!(hits, vec!["src/extra.rs".to_string()]);

    fs::remove_file(dir.path().join("src/extra.rs")).unwrap();
    idx.apply_test_changes(vec![Change {
        root: 0,
        rel: "src/extra.rs".into(),
        kind: ChangeKind::Remove,
    }]);
    hits.clear();
    idx.visit_content_candidates(dir.path(), "extra_unique", false, &mut |_, rel, _| {
        hits.push(rel.to_string());
        true
    });
    assert!(hits.is_empty(), "{hits:?}");

    idx.apply_test_changes(vec![Change {
        root: 0,
        rel: "src".into(),
        kind: ChangeKind::Upsert,
    }]);
    hits.clear();
    idx.visit_content_candidates(dir.path(), "fn main", false, &mut |_, rel, _| {
        hits.push(rel.to_string());
        true
    });
    assert!(hits.iter().any(|r| r == "src/main.rs"), "{hits:?}");
}