croft-software 0.2.32

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
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
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,
}

/// Where in the picked file to land, parsed off the end of the query
/// (#472): `name:236`, `name:236:7` or `name:236-239`. Lines and columns
/// are one-based as typed.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct LineHint {
    pub line: usize,
    pub end: Option<usize>,
    pub col: Option<usize>,
}

#[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
    }

    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;
        }
    }

    /// The line suffix typed after the file part of the query, if any.
    pub fn line_hint(&self) -> Option<LineHint> {
        split_line_hint(&self.query).1
    }

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

    /// The result index at screen row `y`, if `y` lands on a visible row.
    /// The list body starts three rows below `last_rect.y` (top border, the
    /// query prompt, then the separator) and runs `last_inner_height` rows,
    /// so this stays in lock-step with [`render_file_finder`]. Used to map
    /// a mouse click to a result row.
    pub fn row_index_at(&self, y: u16) -> Option<usize> {
        let list_top = self.last_rect.y.saturating_add(3);
        if y < list_top || y - list_top >= self.last_inner_height {
            return None;
        }
        let idx = self.scroll + (y - list_top) as usize;
        (idx < self.results.len()).then_some(idx)
    }

    #[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) {
        // Only the file part takes part in matching: `alpha:236-239` names
        // alpha.rs and a place in it, and a needle carrying the suffix would
        // match nothing at all (#472).
        let (file_part, hint) = split_line_hint(&self.query);
        let mut needle: String = file_part.trim().to_lowercase();
        // A hint with no file (`:236`) names a line in nothing: listing every
        // file and opening the first at that line would be a surprise, so it
        // matches nothing, as it did before hints existed. The cut, not a
        // finished hint, is the test: `:236-` and a bare `:` have no file
        // part either, and listing every file for them would flip the list
        // from empty to everything between two keystrokes. Decided before
        // the exact-name pass below, which these queries can never need.
        let cut = file_part.len() != self.query.trim_end().len();
        if needle.is_empty() && (hint.is_some() || cut) {
            self.results = Vec::new();
            return;
        }
        // A trailing `:` (or a half-typed hint) is also how a real file name
        // can end on Linux. When a file is named exactly what was typed, the
        // query is that name and is matched literally; otherwise the file
        // part goes on matching while the user types the rest of the hint.
        // The exact-name check is a second pass over the corpus, taken only
        // on the keystrokes where the query was cut (`alpha:`, `alpha:23-`);
        // it short-circuits on a hit and costs one traversal on a miss.
        if hint.is_none() {
            let raw = self.query.trim().to_lowercase();
            if raw != needle && entries_have_filename(&self.entries, &raw) {
                needle = raw;
            }
        }
        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);
    }
}

/// Split a trailing line hint off a quick-open query (#472): the file part
/// and, when the query ends in `:line`, `:line:col` or `:line-line`, the
/// parsed hint. The first `:` whose remainder parses as a hint is the cut,
/// so a name that itself contains a colon keeps it. A `:` followed by a hint
/// still being typed (`alpha:`, `alpha:236-`) is cut with no hint, so the
/// file part keeps matching between keystrokes; `refresh_results` restores
/// the literal query when a file is named exactly that. Any other unparsed
/// suffix (`foo:bar`) stays part of the file name.
fn split_line_hint(query: &str) -> (&str, Option<LineHint>) {
    let q = query.trim_end();
    for (i, _) in q.match_indices(':') {
        let rest = &q[i + 1..];
        if let Some(hint) = parse_line_hint(rest) {
            return (&q[..i], Some(hint));
        }
        // A hint still being typed (`alpha:`, `alpha:236-`): keep matching
        // on the file part so the list does not empty between keystrokes,
        // with no hint until it parses.
        if is_partial_line_hint(rest) {
            return (&q[..i], None);
        }
    }
    (q, None)
}

/// Digits, at most one `-` or `:` separator, digits: every prefix of a hint
/// a user types on the way to a complete one, the empty string included.
fn is_partial_line_hint(s: &str) -> bool {
    let mut seen_sep = false;
    for b in s.bytes() {
        match b {
            b'0'..=b'9' => {}
            b'-' | b':' if !seen_sep => seen_sep = true,
            _ => return false,
        }
    }
    true
}

fn parse_line_hint(s: &str) -> Option<LineHint> {
    // One-based as typed; a `0` is not a line anyone can land on.
    // A number too large for usize saturates rather than vanishing: the open
    // path clamps out-of-range lines to the file, and a hint that silently
    // disappeared would open the file at the top with no signal.
    let num = |t: &str| {
        (!t.is_empty() && t.bytes().all(|b| b.is_ascii_digit()))
            .then(|| t.parse::<usize>().unwrap_or(usize::MAX))
            .filter(|n| *n > 0)
    };
    if let Some((a, b)) = s.split_once('-') {
        // `239-236` is the same range as `236-239`; the caller clamps the
        // selection from `line` to `end`, so the pair is ordered here.
        let (a, b) = (num(a)?, num(b)?);
        return Some(LineHint {
            line: a.min(b),
            end: Some(a.max(b)),
            col: None,
        });
    }
    if let Some((a, b)) = s.split_once(':') {
        if b.is_empty() || !b.bytes().all(|c| c.is_ascii_digit()) {
            return None;
        }
        // A zero column is common 0-based tool output: the line is kept and
        // the column dropped, as the terminal's path:line:col parser does,
        // rather than the whole hint vanishing.
        return Some(LineHint {
            line: num(a)?,
            end: None,
            col: num(b),
        });
    }
    Some(LineHint {
        line: num(s)?,
        end: None,
        col: None,
    })
}

/// Whether some entry's file name is exactly `name` (already lower-cased).
fn entries_have_filename(entries: &[FileEntry], name: &str) -> bool {
    entries
        .par_iter()
        .any(|e| &e.rel_lower[e.filename_start_lower..] == name)
}

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);
    }
    // Chars, not bytes: comparing UTF-8 bytes let the pieces of two
    // different characters combine into a match (`é` found inside `ã©`),
    // which translated command titles and non-ASCII names hit. Offsets stay
    // byte offsets, which is what `filename_start` counts.
    let mut needle_chars = needle.chars().peekable();
    let mut score: i32 = 0;
    let mut consecutive: i32 = 0;
    let mut prev_match: Option<usize> = None;
    let mut prev: Option<(usize, char)> = None;
    for (i, c) in hay_lower.char_indices() {
        let Some(&want) = needle_chars.peek() else {
            break;
        };
        if c == want {
            let mut bonus: i32 = 1;
            if i >= filename_start {
                bonus += 4;
            }
            let at_word_boundary = i == 0
                || i == filename_start
                || matches!(prev, Some((_, '/' | '_' | '-' | '.' | ' ')));
            if at_word_boundary {
                bonus += 5;
            }
            if prev_match.is_some() && prev_match == prev.map(|(p, _)| p) {
                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_chars.next();
        }
        prev = Some((i, c));
    }
    if needle_chars.peek().is_none() {
        Some(score - (hay_lower.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",
    // The same class of $HOME toolchain cache for the .NET, Dart and Go
    // ecosystems, plus oh-my-zsh's plugin tree. Measured on a Linux
    // remote opened at /root: .nuget 1127 dirs, .pub-cache 1271,
    // go/pkg/mod 1357 (below, by path) — together the top consumers of a
    // readlink storm that held ~210% CPU for 19 minutes without
    // finishing the walk.
    ".nuget",
    ".pub-cache",
    ".dart-tool",
    ".dotnet",
    ".oh-my-zsh",
];

/// Noise trees whose LEADING component is too generic to blacklist by
/// name: a workspace really can hold a `go/` source directory, so only
/// the module/checksum caches GOPATH parks in `$HOME` are pruned. Matched
/// as a consecutive component run anywhere in the path, so both the cache
/// root and everything under it are covered.
const NOISE_PATH_RUNS: &[&[&str]] = &[&["go", "pkg", "mod"], &["go", "pkg", "sumdb"]];

/// Number of `Normal` components in `path` — its depth, ignoring the root
/// prefix and any `.` / `..` the caller left in.
fn normal_component_count(path: &Path) -> usize {
    path.components()
        .filter(|c| matches!(c, std::path::Component::Normal(_)))
        .count()
}

/// True when `run` appears as consecutive `Normal` components of `path`
/// ENDING deeper than `min_end` components in — that is, the run must reach
/// below the first `min_end` components. `0` matches a run anywhere.
///
/// The depth bound is what lets a run straddle a workspace root: the head of
/// the run may lie in the root's own path as long as its tail does not.
fn has_component_run(path: &Path, run: &[&str], min_end: usize) -> bool {
    let comps: Vec<&std::ffi::OsStr> = path
        .components()
        .filter_map(|c| match c {
            std::path::Component::Normal(s) => Some(s),
            _ => None,
        })
        .collect();
    comps.windows(run.len()).enumerate().any(|(i, w)| {
        i + run.len() > min_end
            && w.iter()
                .zip(run)
                .all(|(a, b)| *a == std::ffi::OsStr::new(b))
    })
}

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` contains one of the [`NOISE_PATH_RUNS`] cache trees,
/// measured RELATIVE TO `root`: the run must REACH BELOW the root.
///
/// The relative part is load-bearing. The workspace root's OWN path is not
/// part of the workspace, so matching the absolute path would prune the
/// entire tree of anyone whose checkout happens to live under a matching
/// ancestor — opening a dependency inside `~/go/pkg/mod/...` to read it
/// would index zero files.
///
/// "Reaches below the root" rather than "lies below it", because a run can
/// STRADDLE the root. A workspace opened at `~/go` — the ordinary GOPATH —
/// keeps its cache at `pkg/mod`, a run whose first component is the root's
/// own last one. Stripping the root off and matching what remained missed
/// exactly that, re-admitting the tree this rule exists to prune.
pub fn has_noise_path_run(path: &Path, root: &Path) -> bool {
    // Components at or above the root cannot make an entry noise on their
    // own; they can only supply the head of a run whose tail is below it. A
    // path outside the root has no root to be measured against, so every
    // component of it counts, as it did before roots entered this rule.
    let depth = if path.starts_with(root) {
        normal_component_count(root)
    } else {
        0
    };
    NOISE_PATH_RUNS
        .iter()
        .any(|r| has_component_run(path, r, depth))
}

/// True when `path` is noise measured RELATIVE TO `root`: it carries a
/// noise-named component, or one of the [`NOISE_PATH_RUNS`] cache trees, at
/// or below the root.
///
/// This is the reading every EVENT path wants. [`is_path_under_noise_dir`]
/// answers the same question about a path in isolation, which is right for
/// the walk (it starts at the root, so everything it reaches is already
/// below it) and wrong for a watcher event, whose path is absolute: a
/// checkout at `~/build/myapp` would have `build` matched among its own
/// ancestors and every file in it classified as noise. The root's ancestors
/// are not part of the workspace, exactly as in [`has_noise_path_run`].
///
/// A `path` that is not under `root` is measured whole. There is no root for
/// its components to be relative to, and a path outside the workspace is not
/// workspace content whichever way it is read.
pub fn is_noise_path_under_root(path: &Path, root: &Path) -> bool {
    let rel = path.strip_prefix(root).unwrap_or(path);
    is_path_under_noise_dir(rel) || has_noise_path_run(path, root)
}

/// 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 filter_root = 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;
            }
            if has_noise_path_run(entry.path(), &filter_root) {
                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,
    theme: crate::theme::Theme,
    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.max(10).min(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(theme.ui(Color::Rgb(0xff, 0xff, 0xff)))
            .add_modifier(Modifier::BOLD),
    );
    let block = Block::default()
        .borders(Borders::ALL)
        .border_style(Style::default().fg(theme.ui(Color::Rgb(0x4e, 0x9a, 0xff))))
        .title(title.clone())
        .style(Style::default().bg(theme.ui(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 theme.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 theme.gradient() {
        let (r, g, b) = crate::gradient::POPUP_SEL_BG;
        Color::Rgb(r, g, b)
    } else {
        theme.ui(Color::Rgb(0x1e, 0x3a, 0x6e))
    };

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

    let query_style = Style::default()
        .fg(theme.ui(Color::Rgb(0xec, 0xef, 0xf4)))
        .add_modifier(Modifier::BOLD);
    let caret_style = Style::default()
        .fg(theme.ui(Color::Rgb(0x16, 0x18, 0x1f)))
        .bg(theme.ui(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(theme.ui(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(theme.ui(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(theme.ui(Color::Rgb(0x7a, 0x82, 0x90))),
            ))
        } else {
            Line::from(Span::styled(
                format!("  No matches for '{}'", finder.query),
                Style::default().fg(theme.ui(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(theme.ui(Color::White))
        } else {
            Style::default().fg(theme.ui(Color::Rgb(0xec, 0xef, 0xf4)))
        };
        let dir_style = if is_selected {
            Style::default()
                .bg(sel_bg)
                .fg(theme.ui(Color::Rgb(0xa0, 0xb4, 0xd8)))
        } else {
            Style::default().fg(theme.ui(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 fuzzy_matching_compares_characters_not_bytes() {
        assert_eq!(fuzzy_score("é", "ã©", 0), None);
        assert!(fuzzy_score("é", "café", 0).is_some());
    }

    /// The click hit-test starts three rows below the popup top (border,
    /// prompt, separator), scrolls with the list, refuses the bottom border
    /// (one past `last_inner_height`), and refuses empty rows past the last
    /// result.
    #[test]
    fn row_index_at_maps_the_quick_pick_list_geometry() {
        let entry = |name: &str| FileEntry {
            path: std::path::PathBuf::from(name),
            rel: name.to_string(),
            rel_lower: name.to_lowercase(),
            filename_start: 0,
            filename_start_lower: 0,
        };
        let mut f = FileFinder::new(Arc::new(vec![entry("a.rs"), entry("b.rs"), entry("c.rs")]));
        f.last_rect = Rect {
            x: 10,
            y: 5,
            width: 60,
            height: 10,
        };
        // inner height 8, minus prompt and separator = 6 list rows;
        // the popup bottom border sits at y = 14.
        f.last_inner_height = 6;
        assert_eq!(f.row_index_at(7), None, "the separator is not a row");
        assert_eq!(
            f.row_index_at(8),
            Some(0),
            "the list starts below the separator"
        );
        assert_eq!(f.row_index_at(10), Some(2));
        assert_eq!(f.row_index_at(11), None, "below the last result is empty");
        assert_eq!(f.row_index_at(14), None, "the bottom border is not a row");
        f.scroll = 2;
        assert_eq!(f.row_index_at(8), Some(2), "scroll offsets the mapping");
    }

    #[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 a_line_suffix_is_split_off_the_query_and_the_file_part_still_matches() {
        // #472: `fileA:236-239` names a file AND where to land in it. The
        // suffix is not part of the file name, so it must not take part in
        // matching, and it has to come back parsed for the open to use.
        let entries = Arc::new(vec![entry("src/alpha.rs"), entry("src/beta.rs")]);
        let mut finder = FileFinder::new(entries);
        for (query, hint) in [
            (
                "alpha:236-239",
                LineHint {
                    line: 236,
                    end: Some(239),
                    col: None,
                },
            ),
            (
                "alpha:236",
                LineHint {
                    line: 236,
                    end: None,
                    col: None,
                },
            ),
            (
                "alpha:236:7",
                LineHint {
                    line: 236,
                    end: None,
                    col: Some(7),
                },
            ),
        ] {
            finder.set_query(query);
            let names: Vec<&str> = finder
                .visible_results()
                .iter()
                .map(|r| r.entry.rel.as_str())
                .collect();
            assert_eq!(
                names,
                vec!["src/alpha.rs"],
                "{query}: the file part alone selects the file; got {names:?}"
            );
            assert_eq!(finder.line_hint(), Some(hint), "{query}");
        }
        // A reversed range is the same range; a zero is no line at all.
        finder.set_query("alpha:239-236");
        assert_eq!(
            finder.line_hint(),
            Some(LineHint {
                line: 236,
                end: Some(239),
                col: None,
            }),
            "a reversed range normalises"
        );
        finder.set_query("alpha:0");
        assert_eq!(finder.line_hint(), None, "line 0 is not a line");
        finder.set_query("alpha");
        assert_eq!(finder.line_hint(), None, "no suffix, no hint");
        // A colon with nothing numeric after it is not a line suffix.
        finder.set_query("alpha:");
        assert_eq!(finder.line_hint(), None, "a bare colon is not a hint");
        // The keystrokes on the way to a complete hint keep the file matched.
        for partial in ["alpha:", "alpha:236-", "alpha:236:"] {
            finder.set_query(partial);
            let names: Vec<&str> = finder
                .visible_results()
                .iter()
                .map(|r| r.entry.rel.as_str())
                .collect();
            assert_eq!(
                names,
                vec!["src/alpha.rs"],
                "{partial}: still matching on the file part"
            );
            assert_eq!(
                finder.line_hint(),
                None,
                "{partial}: no hint until it parses"
            );
        }
        // A hint with no file part names a line in nothing, whether or not
        // it has finished parsing.
        for q in [":236", ":", "::", ":236-", ":0"] {
            finder.set_query(q);
            assert!(
                finder.visible_results().is_empty(),
                "{q:?} alone matches nothing"
            );
        }
        // A zero column keeps the line: the hint is `236`, not nothing.
        finder.set_query("alpha:236:0");
        assert_eq!(
            finder.line_hint().map(|h| (h.line, h.col)),
            Some((236, None)),
            "`:236:0` is line 236 with no column"
        );
        // A number past usize saturates instead of vanishing.
        finder.set_query("alpha:99999999999999999999");
        assert_eq!(finder.line_hint().map(|h| h.line), Some(usize::MAX));
    }

    #[test]
    fn a_filename_that_ends_in_a_colon_still_wins_an_exact_match() {
        // A trailing colon is also how a hint starts, so `alpha:` keeps the
        // list matching on `alpha` while the user types; but on Linux a file
        // can be named `alpha:` and that exact name must still rank first,
        // even beside a file named `alpha`, which the file part alone would
        // rank as the exact match instead.
        let entries = Arc::new(vec![entry("src/alpha"), entry("src/alpha:")]);
        let mut finder = FileFinder::new(entries);
        finder.set_query("alpha:");
        let names: Vec<&str> = finder
            .visible_results()
            .iter()
            .map(|r| r.entry.rel.as_str())
            .collect();
        assert_eq!(
            names.first().copied(),
            Some("src/alpha:"),
            "the file whose name IS the query ranks first; got {names:?}"
        );
        assert_eq!(finder.line_hint(), None);
    }

    #[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}");
        }
    }

    /// The root-relative reading, which is the one every EVENT path wants:
    /// the workspace root's own ancestors are not part of the workspace.
    #[test]
    fn noise_is_measured_from_the_workspace_root_not_the_filesystem_root() {
        let root = Path::new("/home/dev/build/myapp");
        assert!(
            !is_noise_path_under_root(&root.join("src/a.rs"), root),
            "a source file in a workspace under build/ is not noise"
        );
        assert!(
            !is_noise_path_under_root(root, root),
            "nor is the root itself"
        );
        // Noise at or below the root still counts, by name and by run.
        for rel in ["target/debug/x", "node_modules/p/i.js", "go/pkg/mod/x"] {
            assert!(
                is_noise_path_under_root(&root.join(rel), root),
                "{rel} is noise below the root"
            );
        }
        // A path under NEITHER root is measured whole: there is no root for
        // its components to be relative to.
        assert!(is_noise_path_under_root(
            Path::new("/elsewhere/target/x"),
            root
        ));
        // The contrast that was the bug: read absolutely, the workspace's
        // own source file is noise because an ANCESTOR is named `build`.
        assert!(is_path_under_noise_dir(&root.join("src/a.rs")));
    }

    #[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"
        )));
    }

    #[test]
    fn noise_rules_flag_dotnet_dart_and_go_module_caches() {
        // Root-cause guard for the second home-dir readlink storm: these
        // trees were absent from the ignore set, so opening /root walked
        // and watched all of them. Measured there: .nuget 1127 dirs,
        // .pub-cache 1271, go/pkg/mod 1357.
        // Name-matched, from a $HOME workspace root.
        for p in [
            "/root/.nuget/packages/microsoft.codeanalysis.common/5.0.0/lib/x.dll",
            "/root/.pub-cache/hosted/pub.dev/args-2.4.2/lib/args.dart",
            "/root/.dart-tool/pub/bin/x",
            "/root/.dotnet/sdk/8.0.100/x.dll",
            "/root/.oh-my-zsh/plugins/git/git.plugin.zsh",
        ] {
            assert!(is_path_under_noise_dir(Path::new(p)), "{p}");
        }
        // Run-matched, measured relative to the workspace root.
        for p in [
            "/root/go/pkg/mod/golang.org/x/tools@v0.28.0/go/analysis/x.go",
            "/root/go/pkg/sumdb/sum.golang.org/lookup/x",
        ] {
            assert!(has_noise_path_run(Path::new(p), Path::new("/root")), "{p}");
        }
    }

    #[test]
    fn build_file_index_indexes_a_workspace_opened_inside_the_module_cache() {
        // The root's own path is not part of the workspace: opening a
        // checked-out dependency to read it must still index its files.
        // Matching the absolute path pruned every entry at depth >= 1.
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path().join("go/pkg/mod/github.com/x/y@v1.0.0");
        std::fs::create_dir_all(root.join("internal")).unwrap();
        std::fs::write(root.join("main.go"), "x").unwrap();
        std::fs::write(root.join("internal/a.go"), "x").unwrap();
        let idx = build_file_index(&root);
        let mut rels: Vec<&str> = idx.iter().map(|e| e.rel.as_str()).collect();
        rels.sort_unstable();
        assert_eq!(rels, vec!["internal/a.go", "main.go"]);
    }

    #[test]
    fn build_file_index_indexes_a_workspace_under_a_noise_named_ancestor() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path().join("build/myapp");
        std::fs::create_dir_all(root.join("src")).unwrap();
        std::fs::write(root.join("src/main.rs"), "x").unwrap();
        let idx = build_file_index(&root);
        let rels: Vec<&str> = idx.iter().map(|e| e.rel.as_str()).collect();
        assert_eq!(rels, vec!["src/main.rs"]);
    }

    #[test]
    fn noise_rules_keep_a_real_go_source_tree() {
        // `go` alone is a legitimate source directory name, so only the
        // GOPATH cache runs are pruned. A project's own go/ must survive,
        // and so must a go/pkg that is not the module cache.
        let root = Path::new("/Users/v/proj");
        for p in [
            "/Users/v/proj/go/main.go",
            "/Users/v/proj/go/pkg/handler/handler.go",
            "/Users/v/proj/src/mod/thing.rs",
            "/Users/v/proj/pkg/mod/thing.go",
        ] {
            assert!(!has_noise_path_run(Path::new(p), root), "{p}");
            assert!(!is_path_under_noise_dir(Path::new(p)), "{p}");
        }
        // And the root's OWN path never makes its contents noise.
        assert!(!has_noise_path_run(
            Path::new("/home/u/go/pkg/mod/x@v1/main.go"),
            Path::new("/home/u/go/pkg/mod/x@v1")
        ));
    }

    /// A cache run can STRADDLE the root, and both halves of the rule have
    /// to hold at once.
    #[test]
    fn a_gopath_root_still_prunes_the_module_cache_below_it() {
        // A workspace opened at `~/go` - the ordinary GOPATH - keeps its
        // cache at `pkg/mod`, a run whose first component IS the root's own
        // last one. Stripping the root and matching only what was left
        // missed it, re-admitting the tree this rule exists to prune.
        let gopath = Path::new("/home/u/go");
        for p in [
            "/home/u/go/pkg/mod/x@v1/a.go",
            "/home/u/go/pkg/sumdb/lookup/y",
        ] {
            assert!(has_noise_path_run(Path::new(p), gopath), "{p}");
        }
        // The sibling source tree under that same root is not noise.
        assert!(!has_noise_path_run(
            Path::new("/home/u/go/src/app/main.go"),
            gopath
        ));
        // And the other half, unchanged: opening a dependency INSIDE the
        // cache indexes it, because there the whole run is the root's own
        // path rather than anything below it.
        assert!(!has_noise_path_run(
            Path::new("/home/u/go/pkg/mod/x@v1/a.go"),
            Path::new("/home/u/go/pkg/mod/x@v1")
        ));
        // The boundary that decides `>` from `>=`: the run ends exactly at
        // the root's last component, so the cache IS the root and its
        // contents are what the user asked to open.
        assert!(!has_noise_path_run(
            Path::new("/home/u/go/pkg/mod/x/a.go"),
            Path::new("/home/u/go/pkg/mod")
        ));
        // One component shallower, the run's tail lands below the root and
        // the same path is noise again.
        assert!(has_noise_path_run(
            Path::new("/home/u/go/pkg/mod/x/a.go"),
            Path::new("/home/u/go/pkg")
        ));
    }

    #[test]
    fn has_component_run_matches_only_consecutive_whole_components() {
        assert!(has_component_run(
            Path::new("/a/go/pkg/mod/b"),
            &["go", "pkg", "mod"],
            0
        ));
        // Non-consecutive: go/pkg/OTHER/mod must not match.
        assert!(!has_component_run(
            Path::new("/a/go/pkg/other/mod"),
            &["go", "pkg", "mod"],
            0
        ));
        // Substring of a component must not match.
        assert!(!has_component_run(
            Path::new("/a/cargo/pkg/mod"),
            &["go", "pkg", "mod"],
            0
        ));
        // The depth bound: the same run is ignored when it ends at or above
        // `min_end`, which is how a run inside the ROOT'S own path is kept
        // from making the workspace's contents noise.
        assert!(!has_component_run(
            Path::new("/a/go/pkg/mod/b"),
            &["go", "pkg", "mod"],
            4
        ));
        assert!(has_component_run(
            Path::new("/a/go/pkg/mod/b"),
            &["go", "pkg", "mod"],
            3
        ));
    }

    #[test]
    fn build_file_index_skips_the_go_module_cache() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        std::fs::create_dir_all(root.join("go/pkg/mod/golang.org/x")).unwrap();
        std::fs::write(root.join("go/pkg/mod/golang.org/x/cached.go"), "x").unwrap();
        std::fs::create_dir_all(root.join("go/cmd")).unwrap();
        std::fs::write(root.join("go/cmd/main.go"), "x").unwrap();
        let idx = build_file_index(root);
        let rels: Vec<&str> = idx.iter().map(|e| e.rel.as_str()).collect();
        assert!(rels.contains(&"go/cmd/main.go"), "{rels:?}");
        assert!(
            !rels.iter().any(|r| r.contains("pkg/mod")),
            "module cache leaked into the index: {rels:?}"
        );
    }

    /// The degenerate root: the walk STARTS at the GOPATH, so the cache run
    /// straddles the root instead of lying below it.
    ///
    /// `build_file_index_skips_the_go_module_cache` cannot see this: it roots
    /// at `tmp` with the cache at `tmp/go/pkg/mod`, where the whole run is
    /// below the root, so it passed both before and after the straddle fix.
    #[test]
    fn build_file_index_skips_the_module_cache_of_a_gopath_root() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path().join("go");
        std::fs::create_dir_all(root.join("pkg/mod/golang.org/x")).unwrap();
        std::fs::write(root.join("pkg/mod/golang.org/x/cached.go"), "x").unwrap();
        std::fs::create_dir_all(root.join("cmd")).unwrap();
        std::fs::write(root.join("cmd/main.go"), "x").unwrap();
        let idx = build_file_index(&root);
        let rels: Vec<&str> = idx.iter().map(|e| e.rel.as_str()).collect();
        assert!(rels.contains(&"cmd/main.go"), "{rels:?}");
        assert!(
            !rels.iter().any(|r| r.contains("pkg/mod")),
            "a GOPATH root's own module cache leaked into the index: {rels:?}"
        );
    }
}