croft-software 0.1.736

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
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
use ignore::{WalkBuilder, WalkState};
use ratatui::{
    buffer::Buffer,
    layout::Rect,
    style::{Color, Modifier, Style},
    text::{Line, Span},
    widgets::{Block, Borders, Clear, Paragraph, Widget},
};
use rayon::prelude::*;
use std::cmp::Ordering;
use std::collections::BinaryHeap;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};

const MAX_RESULTS: usize = 40;

#[derive(Clone, Debug)]
pub struct FileEntry {
    pub path: PathBuf,
    pub rel: String,
    pub rel_lower: String,
    /// Byte offset of the filename within `rel` (rendering's dir/file
    /// split). `rel_lower` gets its own offset below: lowercasing can
    /// change a component's byte length (e.g. `İ` → `i̇`), so one offset
    /// cannot index both strings.
    pub filename_start: usize,
    /// Byte offset of the filename within `rel_lower` — the scoring
    /// string. Slicing `rel_lower` with the `rel` offset panicked on a
    /// non-boundary whenever an earlier component's lowercase changed
    /// byte length (#148 review).
    pub filename_start_lower: usize,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum MatchTier {
    Subsequence = 1,
    PathSubstring = 2,
    FilenameSubstring = 3,
    FilenamePrefix = 4,
    ExactFilename = 5,
}

#[derive(Clone, Debug)]
pub struct ScoredResult {
    pub entry: FileEntry,
}

#[derive(Default)]
pub struct FileFinder {
    pub query: String,
    pub cursor: usize,
    pub entries: Arc<Vec<FileEntry>>,
    pub results: Vec<ScoredResult>,
    pub selected: usize,
    pub scroll: usize,
    pub last_rect: Rect,
    pub last_inner_height: u16,
}

impl FileFinder {
    pub fn new(entries: Arc<Vec<FileEntry>>) -> Self {
        let mut me = Self {
            query: String::new(),
            cursor: 0,
            entries,
            results: Vec::new(),
            selected: 0,
            scroll: 0,
            last_rect: Rect::default(),
            last_inner_height: 0,
        };
        me.refresh_results();
        me
    }

    #[cfg(test)]
    pub fn set_query(&mut self, q: &str) {
        if q == self.query {
            return;
        }
        self.query = q.to_string();
        self.cursor = self.query.chars().count();
        self.refresh_results();
        self.selected = 0;
        self.scroll = 0;
    }

    fn char_count(&self) -> usize {
        self.query.chars().count()
    }

    fn byte_offset(&self, char_idx: usize) -> usize {
        self.query
            .char_indices()
            .nth(char_idx)
            .map(|(b, _)| b)
            .unwrap_or(self.query.len())
    }

    pub fn replace_entries(&mut self, entries: Arc<Vec<FileEntry>>) {
        if Arc::ptr_eq(&self.entries, &entries) {
            return;
        }
        self.entries = entries;
        self.refresh_results();
        if self.results.is_empty() {
            self.selected = 0;
        } else if self.selected >= self.results.len() {
            self.selected = self.results.len() - 1;
        }
        if self.scroll > self.selected {
            self.scroll = self.selected;
        }
    }

    pub fn push_char(&mut self, c: char) {
        let at = self.byte_offset(self.cursor);
        self.query.insert(at, c);
        self.cursor += 1;
        self.refresh_results();
        self.selected = 0;
        self.scroll = 0;
    }

    pub fn pop_char(&mut self) {
        if self.cursor == 0 {
            return;
        }
        let at = self.byte_offset(self.cursor - 1);
        self.query.remove(at);
        self.cursor -= 1;
        self.refresh_results();
        self.selected = 0;
        self.scroll = 0;
    }

    pub fn delete_char(&mut self) {
        if self.cursor >= self.char_count() {
            return;
        }
        let at = self.byte_offset(self.cursor);
        self.query.remove(at);
        self.refresh_results();
        self.selected = 0;
        self.scroll = 0;
    }

    pub fn move_cursor_left(&mut self) {
        self.cursor = self.cursor.saturating_sub(1);
    }

    pub fn move_cursor_right(&mut self) {
        self.cursor = (self.cursor + 1).min(self.char_count());
    }

    pub fn move_cursor_home(&mut self) {
        self.cursor = 0;
    }

    pub fn move_cursor_end(&mut self) {
        self.cursor = self.char_count();
    }

    pub fn select_next(&mut self) {
        if self.results.is_empty() {
            return;
        }
        if self.selected + 1 < self.results.len() {
            self.selected += 1;
        }
    }

    pub fn select_prev(&mut self) {
        if self.selected > 0 {
            self.selected -= 1;
        }
    }

    pub fn selected_entry(&self) -> Option<&FileEntry> {
        self.results.get(self.selected).map(|r| &r.entry)
    }

    #[cfg(test)]
    pub fn selected_index(&self) -> usize {
        self.selected
    }

    #[cfg(test)]
    pub fn visible_results(&self) -> &[ScoredResult] {
        &self.results
    }

    fn refresh_results(&mut self) {
        let needle: String = self.query.trim().to_lowercase();
        if needle.is_empty() {
            let mut scored: Vec<ScoredResult> = Vec::with_capacity(MAX_RESULTS);
            for entry in self.entries.iter().take(MAX_RESULTS) {
                scored.push(ScoredResult {
                    entry: entry.clone(),
                });
            }
            scored.sort_by(|a, b| a.entry.rel.cmp(&b.entry.rel));
            self.results = scored;
            return;
        }
        let entries: &[FileEntry] = &self.entries;
        // Score in parallel with rayon and accumulate per-thread top-K
        // bounded heaps, then merge. With N=1.5M entries on a typical
        // home dir, this drops keystroke latency from ~300 ms (serial,
        // full sort) to single-digit ms (multi-core, heap of K=40).
        let merged: BinaryHeap<RankedSlot> = entries
            .par_iter()
            .enumerate()
            .fold(
                || BinaryHeap::<RankedSlot>::with_capacity(MAX_RESULTS + 1),
                |mut heap, (idx, entry)| {
                    if let Some((tier, score)) =
                        score_entry(&needle, &entry.rel_lower, entry.filename_start_lower)
                    {
                        push_topk(
                            &mut heap,
                            RankedSlot {
                                tier,
                                rel_len: entry.rel.len() as u32,
                                score,
                                idx,
                            },
                            MAX_RESULTS,
                        );
                    }
                    heap
                },
            )
            .reduce(
                || BinaryHeap::<RankedSlot>::with_capacity(MAX_RESULTS + 1),
                |mut a, b| {
                    for slot in b {
                        push_topk(&mut a, slot, MAX_RESULTS);
                    }
                    a
                },
            );
        // Our Ord orders BEST as LEAST (so the max-heap root is the
        // worst-of-top-K, evictable in O(log K)). into_sorted_vec
        // therefore returns ascending = best-first already.
        let top: Vec<RankedSlot> = merged.into_sorted_vec();
        self.results = top
            .into_iter()
            .map(|slot| ScoredResult {
                entry: entries[slot.idx].clone(),
            })
            .collect();
    }
}

/// One ranked match candidate. Ordering is "worse comes first" so a
/// `BinaryHeap` (max-heap) keeps the WORST of the top-K at the root,
/// letting us evict it in O(log K) when a better candidate arrives.
#[derive(Clone, Copy, Debug)]
struct RankedSlot {
    tier: MatchTier,
    rel_len: u32,
    score: i32,
    idx: usize,
}

impl PartialEq for RankedSlot {
    fn eq(&self, other: &Self) -> bool {
        self.cmp(other) == Ordering::Equal
    }
}

impl Eq for RankedSlot {}

impl PartialOrd for RankedSlot {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for RankedSlot {
    /// Mirrors the old sort_by in refresh_results, but inverted so
    /// the BinaryHeap (max-heap) root is the WORST candidate in the
    /// current top-K. Tie-break order, BEST -> WORST:
    ///   1. Higher MatchTier (ExactFilename > Subsequence)
    ///   2. Shorter rel.len (workspace-root storage.py beats deep)
    ///   3. Higher fuzzy score
    ///   4. Lexicographic rel ascending (handled at idx tiebreak)
    fn cmp(&self, other: &Self) -> Ordering {
        // Worse-first: invert each comparison vs "best".
        other
            .tier
            .cmp(&self.tier)
            .then_with(|| self.rel_len.cmp(&other.rel_len))
            .then_with(|| other.score.cmp(&self.score))
            .then_with(|| self.idx.cmp(&other.idx))
    }
}

fn push_topk(heap: &mut BinaryHeap<RankedSlot>, slot: RankedSlot, k: usize) {
    if heap.len() < k {
        heap.push(slot);
        return;
    }
    // heap.peek() is the worst-of-top-K under our Ord. If incoming is
    // strictly better (= less under cmp), evict + insert.
    if let Some(worst) = heap.peek()
        && slot.cmp(worst) == Ordering::Less
    {
        heap.pop();
        heap.push(slot);
    }
}

pub fn score_entry(
    needle: &str,
    hay_lower: &str,
    filename_start: usize,
) -> Option<(MatchTier, i32)> {
    if needle.is_empty() {
        return Some((MatchTier::Subsequence, 0));
    }
    let filename = &hay_lower[filename_start..];
    if filename == needle {
        return Some((MatchTier::ExactFilename, 10_000));
    }
    if filename.starts_with(needle) {
        return Some((MatchTier::FilenamePrefix, 5_000));
    }
    if filename.contains(needle) {
        return Some((MatchTier::FilenameSubstring, 2_500));
    }
    if hay_lower.contains(needle) {
        return Some((MatchTier::PathSubstring, 1_000));
    }
    fuzzy_score(needle, hay_lower, filename_start).map(|s| (MatchTier::Subsequence, s))
}

pub fn fuzzy_score(needle: &str, hay_lower: &str, filename_start: usize) -> Option<i32> {
    if needle.is_empty() {
        return Some(0);
    }
    let needle_bytes = needle.as_bytes();
    let hay_bytes = hay_lower.as_bytes();
    let mut score: i32 = 0;
    let mut consecutive: i32 = 0;
    let mut needle_idx = 0usize;
    let mut prev_match: Option<usize> = None;
    for (i, &b) in hay_bytes.iter().enumerate() {
        if needle_idx >= needle_bytes.len() {
            break;
        }
        if b == needle_bytes[needle_idx] {
            let mut bonus: i32 = 1;
            if i >= filename_start {
                bonus += 4;
            }
            let prev_byte = if i == 0 { None } else { Some(hay_bytes[i - 1]) };
            let at_word_boundary = i == 0
                || i == filename_start
                || matches!(
                    prev_byte,
                    Some(b'/') | Some(b'_') | Some(b'-') | Some(b'.') | Some(b' ')
                );
            if at_word_boundary {
                bonus += 5;
            }
            if prev_match == Some(i.saturating_sub(1)) && i > 0 {
                consecutive += 1;
                bonus += consecutive * 5;
            } else {
                if let Some(p) = prev_match {
                    let gap = i.saturating_sub(p + 1) as i32;
                    bonus -= gap.min(20);
                }
                consecutive = 0;
            }
            score += bonus;
            prev_match = Some(i);
            needle_idx += 1;
        }
    }
    if needle_idx == needle_bytes.len() {
        Some(score - (hay_bytes.len() as i32 / 4))
    } else {
        None
    }
}

/// Directory names that are vendored / generated / VCS-internal and
/// will never be a useful Cmd+P target. Including these in the index
/// would drown signal in noise (every `.git/objects/*` blob,
/// `node_modules/**`, `target/debug/incremental/*`, etc.) and balloon
/// the walk by orders of magnitude. The match is exact on the path
/// component name - a real workspace file literally named `target.md`
/// is still indexed.
const NOISE_DIR_NAMES: &[&str] = &[
    ".git",
    ".hg",
    ".svn",
    ".bzr",
    "node_modules",
    "target",
    "__pycache__",
    ".venv",
    "venv",
    ".tox",
    ".mypy_cache",
    ".pytest_cache",
    ".ruff_cache",
    ".next",
    ".nuxt",
    ".cache",
    "dist",
    "build",
    ".gradle",
    ".idea",
    ".vscode-test",
    ".DS_Store",
    // Package-manager, language-toolchain, and agent caches that live in
    // $HOME. Never edit targets, and several (.cargo, .claude, .npm) are
    // written to continuously, so watching them turns a home-dir workspace
    // into a perpetual FS-event storm. Measured on a Linux remote opened at
    // /root: ~7000 inotify watches and 39% of CPU stuck in readlink
    // path-walks re-scanning these trees (~200% CPU total). They dominate
    // both the watch count and the churn, so excluding them is the fix.
    ".cargo",
    ".rustup",
    ".npm",
    ".nvm",
    ".bun",
    ".pnpm-store",
    ".deno",
    ".gem",
    ".pyenv",
    ".rbenv",
    ".m2",
    ".local",
    ".docker",
    ".claude",
    ".codex",
];

pub fn is_noise_dir(name: &std::ffi::OsStr) -> bool {
    name.to_str().is_some_and(|n| NOISE_DIR_NAMES.contains(&n))
}

/// True when `path` sits inside (or names) one of the noise dirs the
/// finder index already excludes from its walk. Callers use this to
/// avoid kicking a full index rebuild for FS events the finder would
/// have ignored anyway — e.g. cargo writing into `target/`, npm into
/// `node_modules/`, git into `.git/`. Without this gate, a sustained
/// cargo build produces a continuous index-rebuild storm that pegs
/// every core via the parallel walker.
pub fn is_path_under_noise_dir(path: &Path) -> bool {
    path.components()
        .filter_map(|c| match c {
            std::path::Component::Normal(s) => Some(s),
            _ => None,
        })
        .any(is_noise_dir)
}

/// Absolute paths to prune from the walk for two reasons:
///   1. `Library/Containers` and `Library/Group Containers` trigger a
///      macOS TCC consent prompt ("App would like to access data from
///      other apps") because they live behind
///      kTCCServiceSystemPolicyAppData.
///   2. The Library/Caches, Library/Application Support, Library/Mobile
///      Documents, Library/Developer, Library/CoreSimulator,
///      Library/Mail, Library/Messages, Library/CloudStorage,
///      Library/Safari, Library/Cookies trees collectively account
///      for ~1.4M of the ~1.5M files found by a `~`-rooted walk on a
///      typical developer Mac. None of those are useful Cmd+P
///      targets, and including them blows per-keystroke match
///      latency from ~5ms to ~300ms. Library/Logs is kept in because
///      log files DO get opened (the user's lsp.log lives at
///      `~/.croft/lsp.log` but `~/Library/Logs/*` is a reasonable
///      Cmd+P target too).
fn macos_blocked_paths() -> Vec<PathBuf> {
    match std::env::var_os("HOME") {
        Some(home) => macos_blocked_paths_for(&PathBuf::from(home)),
        None => Vec::new(),
    }
}

/// The pure half of [`macos_blocked_paths`], taking the home directory as
/// an argument so tests never repoint the process-global `$HOME` (#37):
/// the env var is resolved at call time by every concurrent reader (the
/// PDF rasteriser's cache dir, the session paths), and a substituted value
/// leaking across test threads made unrelated tests fail on paths inside
/// the fake home.
fn macos_blocked_paths_for(home: &Path) -> Vec<PathBuf> {
    let lib = home.join("Library");
    [
        "Containers",
        "Group Containers",
        "Caches",
        "Application Support",
        "Mobile Documents",
        "CloudStorage",
        "Developer",
        "CoreSimulator",
        "Mail",
        "Messages",
        "Safari",
        "Cookies",
        "Metadata",
        "Suggestions",
        "Biome",
        "Calendars",
        "Reminders",
        "PersonalizationPortrait",
        "HomeKit",
        "Photos",
        "Daemon Containers",
        "WebKit",
    ]
    .iter()
    .map(|leaf| lib.join(leaf))
    .collect()
}

pub fn build_file_index(root: &Path) -> Vec<FileEntry> {
    build_file_index_with_blocked(root, macos_blocked_paths())
}

/// The Quick Open index over EVERY workspace root (#147). One root is the
/// plain per-root index; with more, each root's entries carry a
/// `<root-name>/` prefix on `rel` — the VS Code multi-root label rule — so
/// same-named files in different roots stay distinguishable and ranking
/// never mixes two projects' bare paths. `filename_start` shifts with the
/// prefix, keeping the filename-tier scoring anchored on the filename.
pub fn build_multi_file_index(roots: &[PathBuf]) -> Vec<FileEntry> {
    if roots.len() == 1 {
        return build_file_index(&roots[0]);
    }
    let labels = crate::workspace::root_display_labels(roots);
    let mut out = Vec::new();
    for (root, label) in roots.iter().zip(&labels) {
        let prefix = format!("{label}/");
        for mut e in build_file_index(root) {
            e.rel = format!("{prefix}{}", e.rel);
            // Recompute BOTH offsets from the final strings: hand-shifting
            // by prefix.len() poisoned rel_lower's offset whenever the
            // label's lowercase changed byte length (#148 review).
            e.rel_lower = e.rel.to_lowercase();
            e.filename_start = e.rel.rfind('/').map(|i| i + 1).unwrap_or(0);
            e.filename_start_lower = e.rel_lower.rfind('/').map(|i| i + 1).unwrap_or(0);
            out.push(e);
        }
    }
    out
}

/// [`build_file_index`] with the blocked-path set injected, so tests drive
/// the macOS exclusion rules against a fake home without mutating `$HOME`.
fn build_file_index_with_blocked(root: &Path, blocked: Vec<PathBuf>) -> Vec<FileEntry> {
    let collected: Arc<Mutex<Vec<FileEntry>>> = Arc::new(Mutex::new(Vec::new()));
    let root_buf = root.to_path_buf();
    let walker = WalkBuilder::new(root)
        .git_ignore(true)
        .require_git(false)
        // .hidden(false) so user dot-dirs (.croft, .cursor, .config,
        // .continue, .databridge) ARE walked - the user explicitly
        // wants to Cmd+P into them. NOISE_DIR_NAMES below prunes the
        // vendored / generated dot-dirs (.git, .venv, .mypy_cache,
        // .next, .cache, ...) that would otherwise drown the index.
        .hidden(false)
        .filter_entry(move |entry| {
            let depth = entry.depth();
            if depth == 0 {
                return true;
            }
            if is_noise_dir(entry.file_name()) {
                return false;
            }
            // Hard-skip macOS app-data containers so readdir does not
            // trip a TCC consent prompt on every launch. starts_with
            // matches both the container root and any descendant.
            for b in &blocked {
                if entry.path().starts_with(b) {
                    return false;
                }
            }
            true
        })
        .build_parallel();
    walker.run(|| {
        let collected = collected.clone();
        let root_buf = root_buf.clone();
        Box::new(move |entry| {
            let entry = match entry {
                Ok(e) => e,
                Err(_) => return WalkState::Continue,
            };
            if !entry.file_type().is_some_and(|t| t.is_file()) {
                return WalkState::Continue;
            }
            let path = entry.path().to_path_buf();
            let rel_path = path.strip_prefix(&root_buf).unwrap_or(&path);
            let rel = rel_path.to_string_lossy().replace('\\', "/");
            if rel.is_empty() {
                return WalkState::Continue;
            }
            let rel_lower = rel.to_lowercase();
            let filename_start = rel.rfind('/').map(|i| i + 1).unwrap_or(0);
            let filename_start_lower = rel_lower.rfind('/').map(|i| i + 1).unwrap_or(0);
            if let Ok(mut g) = collected.lock() {
                g.push(FileEntry {
                    path,
                    rel,
                    rel_lower,
                    filename_start,
                    filename_start_lower,
                });
            }
            WalkState::Continue
        })
    });
    let mut out = Arc::try_unwrap(collected)
        .map(|m| m.into_inner().unwrap_or_default())
        .unwrap_or_default();
    out.sort_by(|a, b| a.rel.cmp(&b.rel));
    out
}

pub fn render_file_finder(
    finder: &mut FileFinder,
    area: Rect,
    buf: &mut Buffer,
    gradient: bool,
    center: bool,
) {
    let width = area.width.saturating_mul(7) / 10;
    let width = width.clamp(40, 100.min(area.width));
    let height = area.height.saturating_mul(6) / 10;
    let height = height.clamp(10, area.height);
    let x = area.x + (area.width.saturating_sub(width)) / 2;
    // Quick Input Position: Top anchors in the upper third (VS Code's
    // default); Center pins it to the vertical middle.
    let y = if center {
        area.y + (area.height.saturating_sub(height)) / 2
    } else {
        area.y + (area.height.saturating_sub(height)) / 4
    };
    let rect = Rect {
        x,
        y,
        width,
        height,
    };
    finder.last_rect = rect;

    Widget::render(Clear, rect, buf);
    let title = Span::styled(
        " Go to File — Esc to close, ↑/↓ to navigate, Enter to open ",
        Style::default()
            .fg(Color::Rgb(0xff, 0xff, 0xff))
            .add_modifier(Modifier::BOLD),
    );
    let block = Block::default()
        .borders(Borders::ALL)
        .border_style(Style::default().fg(Color::Rgb(0x4e, 0x9a, 0xff)))
        .title(title.clone())
        .style(Style::default().bg(Color::Rgb(0x16, 0x18, 0x1f)));
    let inner = Rect {
        x: rect.x + 1,
        y: rect.y + 1,
        width: rect.width.saturating_sub(2),
        height: rect.height.saturating_sub(2),
    };
    Widget::render(block, rect, buf);
    // Black theme: gradient border over the solid one, then re-stamp the title.
    if gradient {
        crate::gradient::paint_gradient_box(buf, rect);
        buf.set_span(rect.x + 1, rect.y, &title, title.width() as u16);
    }
    let sel_bg = if gradient {
        let (r, g, b) = crate::gradient::POPUP_SEL_BG;
        Color::Rgb(r, g, b)
    } else {
        Color::Rgb(0x1e, 0x3a, 0x6e)
    };

    if inner.height == 0 || inner.width == 0 {
        return;
    }

    let query_style = Style::default()
        .fg(Color::Rgb(0xec, 0xef, 0xf4))
        .add_modifier(Modifier::BOLD);
    let caret_style = Style::default()
        .fg(Color::Rgb(0x16, 0x18, 0x1f))
        .bg(Color::Rgb(0xec, 0xef, 0xf4))
        .add_modifier(Modifier::SLOW_BLINK);
    let cursor = finder.cursor.min(finder.query.chars().count());
    let before: String = finder.query.chars().take(cursor).collect();
    let at: String = finder.query.chars().skip(cursor).take(1).collect();
    let after: String = finder.query.chars().skip(cursor + 1).collect();
    let caret_glyph = if at.is_empty() { String::from(" ") } else { at };
    let prompt_line = Line::from(vec![
        Span::styled("> ", Style::default().fg(Color::Rgb(0x88, 0xc0, 0xd0))),
        Span::styled(before, query_style),
        Span::styled(caret_glyph, caret_style),
        Span::styled(after, query_style),
    ]);
    let prompt_rect = Rect {
        x: inner.x,
        y: inner.y,
        width: inner.width,
        height: 1,
    };
    Widget::render(Paragraph::new(prompt_line), prompt_rect, buf);

    let separator_rect = Rect {
        x: inner.x,
        y: inner.y + 1,
        width: inner.width,
        height: 1,
    };
    let sep_line = Line::from(Span::styled(
        "─".repeat(separator_rect.width as usize),
        Style::default().fg(Color::Rgb(0x3b, 0x42, 0x52)),
    ));
    Widget::render(Paragraph::new(sep_line), separator_rect, buf);

    let list_rect = Rect {
        x: inner.x,
        y: inner.y + 2,
        width: inner.width,
        height: inner.height.saturating_sub(2),
    };
    finder.last_inner_height = list_rect.height;
    if list_rect.height == 0 {
        return;
    }

    let visible = list_rect.height as usize;
    let total = finder.results.len();
    if finder.selected >= finder.scroll + visible {
        finder.scroll = finder.selected + 1 - visible;
    }
    if finder.selected < finder.scroll {
        finder.scroll = finder.selected;
    }
    let end = (finder.scroll + visible).min(total);

    if total == 0 {
        let empty = if finder.query.trim().is_empty() {
            Line::from(Span::styled(
                "  (no files indexed)",
                Style::default().fg(Color::Rgb(0x7a, 0x82, 0x90)),
            ))
        } else {
            Line::from(Span::styled(
                format!("  No matches for '{}'", finder.query),
                Style::default().fg(Color::Rgb(0x7a, 0x82, 0x90)),
            ))
        };
        Widget::render(Paragraph::new(empty), list_rect, buf);
        return;
    }

    let mut lines: Vec<Line<'static>> = Vec::with_capacity(end - finder.scroll);
    for (offset, result) in finder.results[finder.scroll..end].iter().enumerate() {
        let row_idx = finder.scroll + offset;
        let is_selected = row_idx == finder.selected;
        let row_style = if is_selected {
            Style::default().bg(sel_bg).fg(Color::White)
        } else {
            Style::default().fg(Color::Rgb(0xec, 0xef, 0xf4))
        };
        let dir_style = if is_selected {
            Style::default().bg(sel_bg).fg(Color::Rgb(0xa0, 0xb4, 0xd8))
        } else {
            Style::default().fg(Color::Rgb(0x8e, 0x95, 0xa4))
        };
        let (dir_part, file_part) = split_dir_file(&result.entry.rel, result.entry.filename_start);
        let prefix = if is_selected { "> " } else { "  " };
        let spans: Vec<Span<'static>> = vec![
            Span::styled(prefix.to_string(), row_style),
            Span::styled(
                file_part.to_string(),
                row_style.add_modifier(Modifier::BOLD),
            ),
            Span::styled(
                if dir_part.is_empty() {
                    String::new()
                } else {
                    format!("  {dir_part}")
                },
                dir_style,
            ),
        ];
        lines.push(Line::from(spans));
    }
    Widget::render(Paragraph::new(lines), list_rect, buf);
}

fn split_dir_file(rel: &str, filename_start: usize) -> (&str, &str) {
    if filename_start == 0 {
        ("", rel)
    } else {
        let dir = &rel[..filename_start.saturating_sub(1)];
        let file = &rel[filename_start..];
        (dir, file)
    }
}

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

    #[test]
    fn multi_root_index_survives_root_names_whose_lowercase_changes_byte_length() {
        // `İ` (U+0130) lowercases to `i` + U+0307 — one byte LONGER — so a
        // hand-shifted shared offset lands mid-char in rel_lower and
        // scoring panics on the slice (#148 review). Both offsets are now
        // computed per string.
        let a = tempfile::tempdir().unwrap();
        let root_i = a.path().join("İİ");
        let root_b = a.path().join("beta");
        std::fs::create_dir(&root_i).unwrap();
        std::fs::create_dir(&root_b).unwrap();
        std::fs::write(
            root_i.join("main.rs"),
            "x
",
        )
        .unwrap();
        std::fs::write(
            root_b.join("main.rs"),
            "y
",
        )
        .unwrap();
        let idx = build_multi_file_index(&[root_i, root_b]);
        let turkish = idx
            .iter()
            .find(|e| e.rel.starts_with("İİ/"))
            .expect("the entry keeps its root label");
        assert_eq!(&turkish.rel[turkish.filename_start..], "main.rs");
        assert_eq!(
            &turkish.rel_lower[turkish.filename_start_lower..],
            "main.rs",
            "the scoring string slices at ITS own offset"
        );
        assert_eq!(
            score_entry("main.rs", &turkish.rel_lower, turkish.filename_start_lower)
                .map(|(t, _)| t),
            Some(MatchTier::ExactFilename),
            "filename-tier scoring works through the unicode root label"
        );
    }

    #[test]
    fn multi_root_index_disambiguates_same_named_roots() {
        let outer = tempfile::tempdir().unwrap();
        let work = outer.path().join("work").join("api");
        let archive = outer.path().join("archive").join("api");
        std::fs::create_dir_all(&work).unwrap();
        std::fs::create_dir_all(&archive).unwrap();
        std::fs::write(
            work.join("main.rs"),
            "a
",
        )
        .unwrap();
        std::fs::write(
            archive.join("main.rs"),
            "b
",
        )
        .unwrap();
        let idx = build_multi_file_index(&[work, archive]);
        let rels: Vec<&str> = idx.iter().map(|e| e.rel.as_str()).collect();
        assert!(
            rels.contains(&"api (work)/main.rs") && rels.contains(&"api (archive)/main.rs"),
            "same-named roots label with their parents: {rels:?}"
        );
    }

    #[test]
    fn multi_root_index_prefixes_rels_with_the_root_name_and_keeps_filename_scoring() {
        let a = tempfile::tempdir().unwrap();
        let b = tempfile::tempdir().unwrap();
        let a_root = a.path().join("alpha");
        let b_root = b.path().join("beta");
        std::fs::create_dir(&a_root).unwrap();
        std::fs::create_dir(&b_root).unwrap();
        // The SAME relative path in both roots: the multi-root prefix is
        // the only thing keeping the two rows distinguishable.
        std::fs::write(a_root.join("main.rs"), "a\n").unwrap();
        std::fs::write(b_root.join("main.rs"), "b\n").unwrap();

        let idx = build_multi_file_index(&[a_root.clone(), b_root.clone()]);
        let rels: Vec<&str> = idx.iter().map(|e| e.rel.as_str()).collect();
        assert!(rels.contains(&"alpha/main.rs"), "rels: {rels:?}");
        assert!(rels.contains(&"beta/main.rs"), "rels: {rels:?}");
        for e in &idx {
            assert_eq!(
                &e.rel[e.filename_start..],
                "main.rs",
                "filename_start must shift with the prefix so filename-tier scoring holds"
            );
            assert!(e.path.is_absolute() && e.path.ends_with("main.rs"));
        }

        // One root: the plain index, no prefixes.
        let single = build_multi_file_index(&[a_root]);
        assert_eq!(single.len(), 1);
        assert_eq!(single[0].rel, "main.rs");
    }

    fn entry(rel: &str) -> FileEntry {
        let rel_lower = rel.to_lowercase();
        let filename_start = rel.rfind('/').map(|i| i + 1).unwrap_or(0);
        let filename_start_lower = rel_lower.rfind('/').map(|i| i + 1).unwrap_or(0);
        FileEntry {
            path: PathBuf::from(rel),
            rel: rel.to_string(),
            rel_lower,
            filename_start,
            filename_start_lower,
        }
    }

    #[test]
    fn fuzzy_score_returns_some_for_subsequence_match() {
        let score = fuzzy_score(
            "ab",
            "alpha/beta.rs",
            "alpha/beta.rs".rfind('/').unwrap() + 1,
        );
        assert!(
            score.is_some(),
            "'ab' must subsequence-match 'alpha/beta.rs'"
        );
    }

    #[test]
    fn fuzzy_score_returns_none_when_chars_are_out_of_order() {
        let score = fuzzy_score("zx", "abc/def.rs", 4);
        assert!(score.is_none());
    }

    #[test]
    fn filename_matches_rank_above_directory_matches() {
        let dir_match = fuzzy_score(
            "be",
            "beta_dir/zoom.rs",
            "beta_dir/zoom.rs".rfind('/').unwrap() + 1,
        );
        let file_match = fuzzy_score("be", "zoom/beta.rs", "zoom/beta.rs".rfind('/').unwrap() + 1);
        assert!(
            file_match > dir_match,
            "matches inside the filename must score higher than matches in directory segments (file={file_match:?}, dir={dir_match:?})"
        );
    }

    #[test]
    fn consecutive_chars_score_higher_than_split_chars() {
        let consec = fuzzy_score("alp", "alpha.rs", 0).unwrap();
        let split = fuzzy_score("alp", "a_l_p_xx.rs", 0).unwrap();
        assert!(
            consec > split,
            "'alp' against 'alpha.rs' must score higher than against 'a_l_p_xx.rs'"
        );
    }

    #[test]
    fn file_finder_with_empty_query_lists_files_alphabetically() {
        let entries = Arc::new(vec![
            entry("zeta.rs"),
            entry("alpha.rs"),
            entry("mid/beta.rs"),
        ]);
        let finder = FileFinder::new(entries);
        let names: Vec<&str> = finder
            .visible_results()
            .iter()
            .map(|r| r.entry.rel.as_str())
            .collect();
        assert_eq!(names, vec!["alpha.rs", "mid/beta.rs", "zeta.rs"]);
    }

    #[test]
    fn cursor_supports_mid_string_insert_and_delete() {
        let finder_entries = Arc::new(vec![entry("a.rs")]);
        let mut f = FileFinder::new(finder_entries);
        for c in "abc".chars() {
            f.push_char(c);
        }
        assert_eq!((f.query.as_str(), f.cursor), ("abc", 3));
        f.move_cursor_left();
        f.move_cursor_left();
        assert_eq!(f.cursor, 1);
        f.push_char('X');
        assert_eq!((f.query.as_str(), f.cursor), ("aXbc", 2));
        f.pop_char();
        assert_eq!((f.query.as_str(), f.cursor), ("abc", 1));
        f.delete_char();
        assert_eq!((f.query.as_str(), f.cursor), ("ac", 1));
        f.move_cursor_home();
        assert_eq!(f.cursor, 0);
        f.move_cursor_end();
        assert_eq!(f.cursor, 2);
        f.move_cursor_right();
        assert_eq!(
            f.cursor, 2,
            "cursor must not move past the end of the query"
        );
    }

    #[test]
    fn query_with_path_separator_matches_the_relative_path() {
        let entries = Arc::new(vec![
            entry("md2pdf/core.py"),
            entry("other/core.py"),
            entry("core.py"),
        ]);
        let mut finder = FileFinder::new(entries);
        finder.set_query("md2pdf/core.py");
        let names: Vec<&str> = finder
            .visible_results()
            .iter()
            .map(|r| r.entry.rel.as_str())
            .collect();
        assert_eq!(
            names.first().copied(),
            Some("md2pdf/core.py"),
            "a query containing '/' must match against the relative path; got {names:?}"
        );
    }

    #[test]
    fn typing_filters_to_subsequence_matches_only() {
        let entries = Arc::new(vec![
            entry("alpha.rs"),
            entry("sub/beta.rs"),
            entry("gamma.rs"),
        ]);
        let mut finder = FileFinder::new(entries);
        finder.set_query("be");
        let names: Vec<&str> = finder
            .visible_results()
            .iter()
            .map(|r| r.entry.rel.as_str())
            .collect();
        assert_eq!(
            names,
            vec!["sub/beta.rs"],
            "filter 'be' must keep only beta.rs"
        );
    }

    #[test]
    fn selection_clamps_when_results_shrink_under_typing() {
        let entries = Arc::new(vec![entry("alpha.rs"), entry("beta.rs")]);
        let mut finder = FileFinder::new(entries);
        finder.select_next();
        assert_eq!(finder.selected_index(), 1);
        finder.set_query("alp");
        assert_eq!(
            finder.selected_index(),
            0,
            "selection must reset to 0 when the result list changes shape"
        );
    }

    #[test]
    fn select_next_caps_at_last_result() {
        let entries = Arc::new(vec![entry("a.rs"), entry("b.rs")]);
        let mut finder = FileFinder::new(entries);
        finder.select_next();
        finder.select_next();
        finder.select_next();
        assert_eq!(
            finder.selected_index(),
            1,
            "select_next must not overshoot the last index"
        );
    }

    #[test]
    fn select_prev_caps_at_zero() {
        let entries = Arc::new(vec![entry("a.rs"), entry("b.rs")]);
        let mut finder = FileFinder::new(entries);
        finder.select_prev();
        finder.select_prev();
        assert_eq!(finder.selected_index(), 0);
    }

    #[test]
    fn build_file_index_walks_workspace_and_honours_gitignore() {
        let tmp = tempfile::tempdir().unwrap();
        std::fs::write(tmp.path().join("alpha.rs"), "").unwrap();
        std::fs::create_dir(tmp.path().join("sub")).unwrap();
        std::fs::write(tmp.path().join("sub").join("beta.rs"), "").unwrap();
        std::fs::write(tmp.path().join(".gitignore"), "ignored.txt\n").unwrap();
        std::fs::write(tmp.path().join("ignored.txt"), "").unwrap();
        let entries = build_file_index(tmp.path());
        let names: Vec<&str> = entries.iter().map(|e| e.rel.as_str()).collect();
        assert!(names.contains(&"alpha.rs"));
        assert!(names.contains(&"sub/beta.rs"));
        assert!(
            !names.contains(&"ignored.txt"),
            "gitignored files must be excluded from the Cmd+P index"
        );
    }

    #[test]
    fn build_file_index_includes_user_owned_dot_directories() {
        // Regression for the user's "Cmd+P does not find ~/.croft/lsp.log
        // even when I type lsp.log" report. The old build_file_index
        // called .hidden(true) which silently excluded every dot-dir,
        // including the user's own ~/.croft, ~/.cursor, ~/.continue,
        // ~/.config, etc. - exactly the directories whose contents the
        // Cmd+P finder is supposed to help locate.
        let tmp = tempfile::tempdir().unwrap();
        std::fs::create_dir(tmp.path().join(".croft")).unwrap();
        std::fs::write(tmp.path().join(".croft").join("lsp.log"), b"").unwrap();
        std::fs::create_dir(tmp.path().join(".config")).unwrap();
        std::fs::write(tmp.path().join(".config").join("init.toml"), b"").unwrap();
        let entries = build_file_index(tmp.path());
        let names: Vec<&str> = entries.iter().map(|e| e.rel.as_str()).collect();
        assert!(
            names.contains(&".croft/lsp.log"),
            "Cmd+P index must include files under user dot-dirs like .croft/; got {names:?}"
        );
        assert!(
            names.contains(&".config/init.toml"),
            "Cmd+P index must include files under .config/ and similar user dot-dirs; got {names:?}"
        );
    }

    #[test]
    fn build_file_index_skips_macos_app_data_containers() {
        // Regression for the user's "iTerm.app would like to access
        // data from other apps" TCC prompt that fired repeatedly
        // after the 0.1.148 background-index landed. macOS gates
        // ~/Library/Containers/<bundle-id> and ~/Library/Group
        // Containers/<group-id> behind kTCCServiceSystemPolicyAppData;
        // any process that readdir's into those paths trips a
        // consent prompt on the parent terminal app. None of those
        // files are useful Cmd+P targets, so prune the two directory
        // trees outright. Test simulates a workspace rooted at a fake
        // $HOME so the path-shape match fires deterministically.
        let tmp = tempfile::tempdir().unwrap();
        let fake_home = tmp.path();
        let containers = fake_home
            .join("Library")
            .join("Containers")
            .join("com.example.app")
            .join("Data");
        std::fs::create_dir_all(&containers).unwrap();
        std::fs::write(containers.join("private.sqlite"), b"").unwrap();
        let group = fake_home
            .join("Library")
            .join("Group Containers")
            .join("group.example")
            .join("shared");
        std::fs::create_dir_all(&group).unwrap();
        std::fs::write(group.join("shared.db"), b"").unwrap();
        // A normal Library subdir the user DOES want indexed - Logs
        // is the canonical lsp.log location regression target.
        let logs = fake_home.join("Library").join("Logs");
        std::fs::create_dir_all(&logs).unwrap();
        std::fs::write(logs.join("app.log"), b"").unwrap();
        // The blocked set is injected instead of repointing `$HOME` (#37):
        // concurrent tests resolve the env var at call time, and a
        // substituted value made unrelated readers (the PDF rasteriser's
        // cache dir) fail on paths inside the fake home.
        let entries = build_file_index_with_blocked(fake_home, macos_blocked_paths_for(fake_home));
        let names: Vec<&str> = entries.iter().map(|e| e.rel.as_str()).collect();
        assert!(
            names.contains(&"Library/Logs/app.log"),
            "Library/Logs/app.log must still be indexed; got {names:?}"
        );
        assert!(
            !names.iter().any(|n| n.starts_with("Library/Containers/")),
            "Library/Containers/** must be excluded to avoid macOS AppData TCC prompts; got {names:?}"
        );
        assert!(
            !names
                .iter()
                .any(|n| n.starts_with("Library/Group Containers/")),
            "Library/Group Containers/** must be excluded for the same TCC reason; got {names:?}"
        );
    }

    #[test]
    fn build_file_index_skips_vendored_noise_directories() {
        // Including hidden dirs would otherwise drown the index in
        // .git/objects/* and node_modules/* — paths the user never
        // wants to open via Cmd+P. Make sure the noise-dir filter
        // keeps those out even though .hidden(false) is now in
        // effect.
        let tmp = tempfile::tempdir().unwrap();
        for noise in [
            ".git",
            "node_modules",
            "target",
            "__pycache__",
            ".venv",
            ".tox",
            ".mypy_cache",
        ] {
            let dir = tmp.path().join(noise);
            std::fs::create_dir(&dir).unwrap();
            std::fs::write(dir.join("blob"), b"").unwrap();
        }
        std::fs::write(tmp.path().join("real.txt"), b"").unwrap();
        let entries = build_file_index(tmp.path());
        let names: Vec<&str> = entries.iter().map(|e| e.rel.as_str()).collect();
        assert!(
            names.contains(&"real.txt"),
            "the regular workspace file must still be indexed; got {names:?}"
        );
        for noise in [
            ".git/blob",
            "node_modules/blob",
            "target/blob",
            "__pycache__/blob",
            ".venv/blob",
            ".tox/blob",
            ".mypy_cache/blob",
        ] {
            assert!(
                !names.contains(&noise),
                "{noise} must be filtered out so vendored / generated dirs do not drown the Cmd+P index; got {names:?}"
            );
        }
    }

    #[test]
    fn exact_filename_match_beats_every_substring_or_subsequence_match() {
        let entries = Arc::new(vec![
            entry("packages/anterior-dev-py/tests/test_citations_storage.py"),
            entry("app/oncohealth/tasks/main/tests/test_configure_agent_v1.py"),
            entry("packages/anterior-dev-py/src/anterior/dev/citations/storage.py"),
        ]);
        let mut finder = FileFinder::new(entries);
        finder.set_query("storage.py");
        let rels: Vec<&str> = finder
            .visible_results()
            .iter()
            .map(|r| r.entry.rel.as_str())
            .collect();
        assert_eq!(
            rels.first().copied(),
            Some("packages/anterior-dev-py/src/anterior/dev/citations/storage.py"),
            "exact filename match 'storage.py' MUST come before test_citations_storage.py (filename-substring) and test_configure_agent_v1.py (only a scattered subsequence) — got {rels:?}. Subsequence tier swamping exact match is the bug the user yelled about at 10:54 on 2026-05-13."
        );
    }

    #[test]
    fn filename_prefix_beats_filename_substring_which_beats_path_substring_which_beats_subsequence()
    {
        let entries = Arc::new(vec![
            entry("zzz_other/random_storage_thing.py"),
            entry("dir_with_storage_in_name/other.py"),
            entry("a/test_storage.py"),
            entry("b/storage_helper.py"),
        ]);
        let mut finder = FileFinder::new(entries);
        finder.set_query("storage");
        let rels: Vec<&str> = finder
            .visible_results()
            .iter()
            .map(|r| r.entry.rel.as_str())
            .collect();
        assert_eq!(
            rels,
            vec![
                "b/storage_helper.py",
                "a/test_storage.py",
                "zzz_other/random_storage_thing.py",
                "dir_with_storage_in_name/other.py",
            ],
            "tier order must be: filename starts-with > filename contains > path contains > scattered subsequence — got {rels:?}"
        );
    }

    #[test]
    fn within_the_same_tier_the_shorter_relative_path_wins() {
        let entries = Arc::new(vec![
            entry("a/very/deeply/nested/dir/structure/storage.py"),
            entry("storage.py"),
            entry("b/c/storage.py"),
        ]);
        let mut finder = FileFinder::new(entries);
        finder.set_query("storage.py");
        let rels: Vec<&str> = finder
            .visible_results()
            .iter()
            .map(|r| r.entry.rel.as_str())
            .collect();
        assert_eq!(
            rels,
            vec![
                "storage.py",
                "b/c/storage.py",
                "a/very/deeply/nested/dir/structure/storage.py",
            ],
            "all three are exact-filename matches; tie-break must be ascending rel.len() so the workspace-root storage.py wins — got {rels:?}"
        );
    }

    /// Manual diagnostic: walks the real `$HOME`, then types
    /// "lsp.log" one char at a time, printing per-keystroke latency.
    /// Marked #[ignore] so it never runs in CI/regular `cargo test`.
    /// Invoke as:
    ///   cargo test --release --bin croft -- --ignored --nocapture bench_cmd_p_real_home
    #[test]
    #[ignore]
    fn bench_cmd_p_real_home() {
        let home = std::env::var("HOME").expect("$HOME");
        let root = std::path::PathBuf::from(home);
        let t0 = std::time::Instant::now();
        let entries = build_file_index(&root);
        let walk_ms = t0.elapsed().as_secs_f64() * 1000.0;
        eprintln!("walk: indexed {} files in {:.0} ms", entries.len(), walk_ms);
        let arc = std::sync::Arc::new(entries);
        let mut finder = FileFinder::new(arc.clone());
        for c in "lsp.log".chars() {
            let t = std::time::Instant::now();
            finder.push_char(c);
            let ms = t.elapsed().as_secs_f64() * 1000.0;
            eprintln!(
                "type '{}' -> query={:?} results={} latency={:.2} ms",
                c,
                finder.query,
                finder.visible_results().len(),
                ms
            );
        }
    }

    #[test]
    fn replace_entries_re_ranks_results_against_the_new_index() {
        let entries = Arc::new(vec![entry("alpha.rs"), entry("beta.rs")]);
        let mut finder = FileFinder::new(entries);
        finder.set_query("resolver.ts");
        assert!(
            finder.visible_results().is_empty(),
            "no resolver.ts in initial index"
        );
        let new_entries = Arc::new(vec![
            entry("alpha.rs"),
            entry("beta.rs"),
            entry("packages/ant-ts-lib-noggin/src/entities/files/resolver.ts"),
        ]);
        finder.replace_entries(new_entries);
        let rels: Vec<&str> = finder
            .visible_results()
            .iter()
            .map(|r| r.entry.rel.as_str())
            .collect();
        assert_eq!(
            rels.first().copied(),
            Some("packages/ant-ts-lib-noggin/src/entities/files/resolver.ts"),
            "after replace_entries the new index must drive the result list; got {rels:?}"
        );
    }

    #[test]
    fn replace_entries_clamps_selection_when_results_shrink() {
        let entries = Arc::new(vec![entry("alpha.rs"), entry("beta.rs"), entry("gamma.rs")]);
        let mut finder = FileFinder::new(entries);
        finder.select_next();
        finder.select_next();
        assert_eq!(finder.selected_index(), 2);
        finder.replace_entries(Arc::new(vec![entry("alpha.rs")]));
        assert_eq!(
            finder.selected_index(),
            0,
            "selection must clamp to last visible row when the index shrinks"
        );
    }

    #[test]
    fn fuzzy_score_handles_mixed_case_via_lowercased_haystack() {
        let rel = "Sub/BetaFile.rs";
        let rel_lower = rel.to_lowercase();
        let filename_start = rel.rfind('/').map(|i| i + 1).unwrap_or(0);
        let score = fuzzy_score("beta", &rel_lower, filename_start);
        assert!(score.is_some());
    }

    #[test]
    fn is_path_under_noise_dir_flags_cargo_and_npm_output_paths() {
        // Root-cause guard: a sample run on a live croft pegged ~150%
        // CPU showed 50+ workers in `ignore::WalkBuilder::build_parallel`
        // because every cargo write into `target/` triggered a Cmd+P
        // index rebuild — even though the rebuild itself skips target/.
        // The gate lives in this helper; if it ever stops recognising
        // cargo/npm/git output paths, the storm comes back.
        assert!(is_path_under_noise_dir(Path::new(
            "/Users/v/proj/target/debug/build/croft-abcd"
        )));
        assert!(is_path_under_noise_dir(Path::new(
            "/Users/v/proj/node_modules/foo/bar.js"
        )));
        assert!(is_path_under_noise_dir(Path::new(
            "/Users/v/proj/.git/objects/ff/abcd"
        )));
    }

    #[test]
    fn is_path_under_noise_dir_flags_home_tool_caches() {
        // Root-cause guard: a Linux remote opened at /root pegged ~200% CPU
        // because .cargo/.npm/.nvm/.bun/.claude under $HOME were watched and
        // re-walked on every cache write. If these stop being recognised,
        // the home-dir FS-event storm comes back.
        for p in [
            "/root/.cargo/registry/src/index/foo-1.0/src/lib.rs",
            "/root/.claude/projects/x/session.jsonl",
            "/root/.npm/_cacache/index-v5/aa/bb",
            "/root/.nvm/versions/node/v20/lib/x.js",
            "/root/.bun/install/cache/pkg/index.js",
            "/root/.local/share/pipx/venvs/tool/bin/x",
        ] {
            assert!(is_path_under_noise_dir(Path::new(p)), "{p}");
        }
    }

    #[test]
    fn is_path_under_noise_dir_does_not_flag_workspace_source_paths() {
        assert!(!is_path_under_noise_dir(Path::new(
            "/Users/v/proj/src/app.rs"
        )));
        assert!(!is_path_under_noise_dir(Path::new(
            "/Users/v/proj/README.md"
        )));
        // A file literally named "target.md" must NOT be classified as
        // noise — the gate matches whole path components, not substrings.
        assert!(!is_path_under_noise_dir(Path::new(
            "/Users/v/proj/docs/target.md"
        )));
    }
}