reflex-search 2.3.0

A local-first, structure-aware code search engine for AI agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
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
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
//! Trigram-based inverted index for fast full-text code search
//!
//! This module implements the core trigram indexing algorithm used by Reflex.
//! A trigram is a sequence of 3 consecutive bytes. By building an inverted index
//! mapping trigrams to file locations, we can quickly narrow down search candidates
//! and achieve sub-100ms query times even on large codebases.
//!
//! # Algorithm
//!
//! 1. **Indexing**: Extract all trigrams from each file, store locations
//! 2. **Querying**: Extract trigrams from query, intersect posting lists
//! 3. **Verification**: Check actual matches at candidate locations
//!
//! See `.context/TRIGRAM_RESEARCH.md` for detailed algorithm documentation.

use anyhow::{Context, Result};
use std::collections::HashMap;
use std::fs::{File, OpenOptions};
use std::io::Write;
use std::path::{Path, PathBuf};

/// A trigram is 3 consecutive bytes, packed into a u32 for efficient hashing
pub type Trigram = u32;

// Binary format constants for trigrams.bin
pub(crate) const MAGIC: &[u8; 4] = b"RFTG"; // ReFlex TriGrams
/// V4: per-line postings grouped into per-file blocks, no byte offsets,
/// `paths_offset` in the header so `load` never walks the directory.
pub(crate) const VERSION: u32 = 4;
/// Header: magic(4) + version(4) + num_trigrams(8) + num_files(8) + paths_offset(8) = 32 bytes
pub(crate) const HEADER_SIZE: usize = 32;
/// Directory entry: trigram(4) + data_offset(8) + compressed_size(4)
pub(crate) const DIR_ENTRY_SIZE: usize = 16;
/// Header field offsets (bytes 8..16 are also read by `cli/misc.rs`; keep them stable)
const NUM_TRIGRAMS_OFFSET: usize = 8;
const NUM_FILES_OFFSET: usize = 16;
pub(crate) const PATHS_OFFSET_OFFSET: usize = 24;

/// Write a u32 as a varint (variable-length integer)
/// Uses 1-5 bytes depending on magnitude (smaller numbers = fewer bytes)
pub(crate) fn write_varint(writer: &mut impl Write, mut value: u32) -> std::io::Result<()> {
    loop {
        let mut byte = (value & 0x7F) as u8;
        value >>= 7;
        if value != 0 {
            byte |= 0x80; // Set continuation bit
        }
        writer.write_all(&[byte])?;
        if value == 0 {
            break;
        }
    }
    Ok(())
}

/// Read a varint from a byte slice, returns (value, bytes_consumed)
fn read_varint(data: &[u8]) -> Result<(u32, usize)> {
    let mut value: u32 = 0;
    let mut shift = 0;
    let mut pos = 0;

    loop {
        if pos >= data.len() {
            anyhow::bail!("Truncated varint");
        }
        let byte = data[pos];
        pos += 1;

        value |= ((byte & 0x7F) as u32) << shift;
        if byte & 0x80 == 0 {
            break;
        }
        shift += 7;
        if shift >= 32 {
            anyhow::bail!("Varint too large");
        }
    }

    Ok((value, pos))
}

/// Skip one varint without decoding it, returning the bytes consumed
#[inline]
pub(crate) fn skip_varint(data: &[u8]) -> Result<usize> {
    let mut pos = 0;
    loop {
        if pos >= data.len() {
            anyhow::bail!("Truncated varint");
        }
        let byte = data[pos];
        pos += 1;
        if byte & 0x80 == 0 {
            return Ok(pos);
        }
        if pos >= 5 {
            anyhow::bail!("Varint too large");
        }
    }
}

/// Read a little-endian u64 at `off` (caller guarantees bounds)
#[inline]
fn read_u64(data: &[u8], off: usize) -> u64 {
    u64::from_le_bytes(data[off..off + 8].try_into().expect("8 bytes"))
}

/// Read a little-endian u32 at `off` (caller guarantees bounds)
#[inline]
fn read_u32(data: &[u8], off: usize) -> u32 {
    u32::from_le_bytes(data[off..off + 4].try_into().expect("4 bytes"))
}

/// Encode a sorted, key-unique posting list into V4 file blocks.
///
/// Layout, per distinct `file_id` in `locations`:
///
/// ```text
/// varint(file_id - prev_file_id)   // first block: delta from 0
/// varint(n_lines << 1 | enc)       // enc bit reserved; always 0 here
/// n_lines × varint(line - prev_line)   // prev_line restarts at 0 per block
/// ```
///
/// Line deltas never cross a file boundary, so every block starts with two
/// small varints instead of the ~5-byte wrapped deltas V3 paid per file.
pub(crate) fn encode_posting_list(locations: &[FileLocation], out: &mut Vec<u8>) -> Result<()> {
    let mut prev_file_id = 0u32;
    let mut i = 0;
    while i < locations.len() {
        let file_id = locations[i].file_id;
        let mut j = i + 1;
        while j < locations.len() && locations[j].file_id == file_id {
            j += 1;
        }
        let block = &locations[i..j];

        write_varint(out, file_id.wrapping_sub(prev_file_id))?;
        write_varint(out, (block.len() as u32) << 1)?; // enc = 0

        let mut prev_line = 0u32;
        for loc in block {
            write_varint(out, loc.line_no.wrapping_sub(prev_line))?;
            prev_line = loc.line_no;
        }

        prev_file_id = file_id;
        i = j;
    }
    Ok(())
}

/// Decode a complete V4 posting list held in `bytes`.
pub(crate) fn decode_posting_list(bytes: &[u8]) -> Result<Vec<FileLocation>> {
    decompress_posting_list(bytes, 0, bytes.len() as u32)
}

/// Decompress a posting list from memory-mapped data
///
/// Reads a compressed posting list (V4 file blocks) from the given offset
/// and decompresses it into a Vec<FileLocation>.
///
/// # Arguments
/// * `mmap` - Memory-mapped file data
/// * `offset` - Absolute byte offset where compressed data starts
/// * `size` - Number of bytes to read
fn decompress_posting_list(mmap: &[u8], offset: u64, size: u32) -> Result<Vec<FileLocation>> {
    let start = offset as usize;
    let end = start + size as usize;

    if end > mmap.len() {
        anyhow::bail!(
            "Posting list out of bounds: offset={}, size={}, mmap_len={}",
            offset,
            size,
            mmap.len()
        );
    }

    let compressed_data = &mmap[start..end];

    // Rough capacity guess: a typical line entry is one 1-byte varint plus
    // amortised block headers.
    let mut locations = Vec::with_capacity(compressed_data.len());
    let mut cursor = PostingCursor::new(compressed_data)?;
    while let Some(loc) = cursor.current() {
        locations.push(loc);
        cursor.advance()?;
    }

    Ok(locations)
}

/// Streaming decoder over a V4 posting list (see [`encode_posting_list`]).
///
/// Decodes one `FileLocation` per line at a time so a large posting list can
/// be intersected against a small candidate set without materialising it.
/// Block headers are consumed transparently by [`advance`](Self::advance);
/// [`seek`](Self::seek) skips the remainder of a block without decoding line
/// values when the target lies in a later file.
pub(crate) struct PostingCursor<'a> {
    /// Compressed posting list bytes
    data: &'a [u8],
    /// Read position in `data`
    pos: usize,
    /// File id of the block being decoded
    file_id: u32,
    /// Lines left to decode in the current block
    remaining: u32,
    /// Last decoded line in the current block (delta base)
    prev_line: u32,
    /// Current location, `None` once exhausted
    cur: Option<FileLocation>,
}

impl<'a> PostingCursor<'a> {
    /// Create a cursor and decode the first entry (if any)
    pub(crate) fn new(data: &'a [u8]) -> Result<Self> {
        let mut cursor = Self {
            data,
            pos: 0,
            file_id: 0,
            remaining: 0,
            prev_line: 0,
            cur: None,
        };
        cursor.advance()?;
        Ok(cursor)
    }

    /// The entry the cursor is positioned on, or `None` if exhausted
    #[inline]
    pub(crate) fn current(&self) -> Option<FileLocation> {
        self.cur
    }

    /// Consume a block header: `varint(file delta) varint(n_lines << 1 | enc)`
    fn read_block_header(&mut self) -> Result<()> {
        let (file_delta, consumed) = read_varint(&self.data[self.pos..])?;
        self.pos += consumed;
        let (header, consumed) = read_varint(&self.data[self.pos..])?;
        self.pos += consumed;

        if header & 1 != 0 {
            anyhow::bail!("unsupported block encoding (enc=1) in posting list");
        }

        self.file_id = self.file_id.wrapping_add(file_delta);
        self.remaining = header >> 1;
        self.prev_line = 0;
        Ok(())
    }

    /// Decode the next entry, returning it (or `None` at end of list)
    pub(crate) fn advance(&mut self) -> Result<Option<FileLocation>> {
        // A block with n_lines == 0 is never written, but tolerate it
        while self.remaining == 0 {
            if self.pos >= self.data.len() {
                self.cur = None;
                return Ok(None);
            }
            self.read_block_header()?;
        }

        let (line_delta, consumed) = read_varint(&self.data[self.pos..])?;
        self.pos += consumed;
        self.remaining -= 1;

        let line_no = self.prev_line.wrapping_add(line_delta);
        self.prev_line = line_no;
        let loc = FileLocation::new(self.file_id, line_no);
        self.cur = Some(loc);
        Ok(self.cur)
    }

    /// Advance until the current key is `>= target` (or the list is exhausted)
    ///
    /// When the target file id is beyond the current block, the rest of the
    /// block is skipped by scanning varint continuation bits only.
    pub(crate) fn seek(&mut self, target: (u32, u32)) -> Result<Option<FileLocation>> {
        while let Some(loc) = self.cur {
            if key(&loc) >= target {
                break;
            }
            if loc.file_id < target.0 {
                for _ in 0..self.remaining {
                    self.pos += skip_varint(&self.data[self.pos..])?;
                }
                self.remaining = 0;
            }
            self.advance()?;
        }
        Ok(self.cur)
    }
}

/// Intersect a sorted, key-deduplicated candidate set with a streamed posting list.
///
/// For each candidate, seeks the cursor to its key and keeps the candidate when
/// the keys match. Runs in O(|cands| + |list|) without materialising the list.
fn intersect_with_cursor(
    cands: &[FileLocation],
    cur: &mut PostingCursor,
) -> Result<Vec<FileLocation>> {
    let mut out = Vec::new();
    for cand in cands {
        let k = key(cand);
        match cur.seek(k)? {
            Some(loc) if key(&loc) == k => out.push(*cand),
            Some(_) => {}
            None => break,
        }
    }
    Ok(out)
}

/// Mark every candidate present in a streamed posting list.
///
/// Same walk as [`intersect_with_cursor`], but sets `keep[i]` for each hit
/// instead of building a new vector, so several lists (the case variants of
/// one trigram) can be OR-ed into one mask over the same candidate slice.
fn mark_with_cursor(
    cands: &[FileLocation],
    cur: &mut PostingCursor,
    keep: &mut [bool],
) -> Result<()> {
    for (i, cand) in cands.iter().enumerate() {
        if keep[i] {
            continue;
        }
        let k = key(cand);
        match cur.seek(k)? {
            Some(loc) if key(&loc) == k => keep[i] = true,
            Some(_) => {}
            None => break,
        }
    }
    Ok(())
}

/// Location of a trigram occurrence in the codebase: one entry per
/// (file, line) a trigram appears on. Derived `Ord` is the intersection key.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct FileLocation {
    /// File ID (index into file list)
    pub file_id: u32,
    /// Line number (1-indexed)
    pub line_no: u32,
}

impl FileLocation {
    pub fn new(file_id: u32, line_no: u32) -> Self {
        Self { file_id, line_no }
    }
}

/// Directory entry for lazy-loaded trigram index
///
/// Maps each trigram to its compressed posting list location in the data section.
/// Total size: 16 bytes per entry (4 + 8 + 4)
/// Compressed posting bytes worth decoding per surviving candidate line.
///
/// Measured on the synthetic 30 MB corpus (16 cores): streaming a V4 list costs
/// ~7 ns per byte on one thread; verifying one extra candidate line costs
/// ~0.14 µs of CPU spread over the query pool, i.e. ~10–15 ns of wall time.
/// Past this ratio the next list is not worth reading — `ident_7` spent 21 ms
/// streaming four ~750 KB lists that removed no candidate.
const SKIP_BYTES_PER_CANDIDATE: usize = 2;

/// Length in bytes of `v` as a varint.
#[inline]
pub(crate) fn varint_len(v: u32) -> u32 {
    match v {
        0..=0x7F => 1,
        0x80..=0x3FFF => 2,
        0x4000..=0x1F_FFFF => 3,
        0x20_0000..=0xFFF_FFFF => 4,
        _ => 5,
    }
}

/// Planning size of one file's block: `1 + len(varint(n_lines << 1))` plus the
/// line-delta varints. That is the block's V4 encoding with the file-id delta
/// counted as one byte, whatever its real length.
pub(crate) fn block_plan_size(lines: impl IntoIterator<Item = u32>) -> u32 {
    let mut n = 0u32;
    let mut size = 0u32;
    let mut prev = 0u32;
    for line in lines {
        size += varint_len(line.wrapping_sub(prev));
        prev = line;
        n += 1;
    }
    1 + varint_len(n << 1) + size
}

/// Planning size of a sorted posting list: the sum of its blocks' planning sizes.
///
/// The early-stop planner orders and stops by this, not by on-disk bytes. On-disk
/// bytes include each block's file-id delta, which depends on file ids; this
/// does not, and it adds up per file. So an index made of a base, a delta and
/// tombstones plans exactly like a full build of the same tree. It equals the
/// on-disk size whenever every file-id delta is below 128.
pub(crate) fn plan_size(locations: &[FileLocation]) -> u32 {
    let mut total = 0u32;
    let mut i = 0;
    while i < locations.len() {
        let file_id = locations[i].file_id;
        let mut j = i + 1;
        while j < locations.len() && locations[j].file_id == file_id {
            j += 1;
        }
        total += block_plan_size(locations[i..j].iter().map(|l| l.line_no));
        i = j;
    }
    total
}

const PLAN_MAGIC: &[u8; 4] = b"RFPL";
const PLAN_VERSION: u32 = 1;
const PLAN_HEADER: usize = 16;

/// `trigrams.<g>.plan`: the planning size of each directory entry, in directory
/// order. Header: magic `RFPL`, version u32, entry count u64; then one u32 each.
pub(crate) struct PlanSizes {
    mmap: memmap2::Mmap,
    count: usize,
}

impl PlanSizes {
    fn load(path: &Path) -> Result<Self> {
        let file =
            File::open(path).with_context(|| format!("Failed to open {}", path.display()))?;
        let mmap = unsafe {
            memmap2::Mmap::map(&file)
                .with_context(|| format!("Failed to mmap {}", path.display()))?
        };
        if mmap.len() < PLAN_HEADER || &mmap[0..4] != PLAN_MAGIC {
            anyhow::bail!("{} is not a planning-size file", path.display());
        }
        if read_u32(&mmap, 4) != PLAN_VERSION {
            anyhow::bail!("{} has an unsupported version", path.display());
        }
        let count = read_u64(&mmap, 8) as usize;
        if mmap.len() != PLAN_HEADER + count * 4 {
            anyhow::bail!("{} is truncated", path.display());
        }
        Ok(Self { mmap, count })
    }

    fn len(&self) -> usize {
        self.count
    }

    #[inline]
    fn get(&self, index: usize) -> u32 {
        read_u32(&self.mmap, PLAN_HEADER + index * 4)
    }
}

/// Write a planning-size file (tmp + fsync + rename).
pub(crate) fn write_plan_file(path: &Path, sizes: &[u32]) -> Result<()> {
    let tmp = crate::atomic_write::tmp_path_for(path);
    {
        let mut w = std::io::BufWriter::new(
            File::create(&tmp).with_context(|| format!("Failed to create {}", tmp.display()))?,
        );
        w.write_all(PLAN_MAGIC)?;
        w.write_all(&PLAN_VERSION.to_le_bytes())?;
        w.write_all(&(sizes.len() as u64).to_le_bytes())?;
        for size in sizes {
            w.write_all(&size.to_le_bytes())?;
        }
        w.flush()?;
        w.get_ref().sync_all()?;
    }
    crate::atomic_write::atomic_replace(&tmp, path)
        .with_context(|| format!("Failed to move {} into place", path.display()))
}

/// Dead file ids (one bit per id) of one segment.
pub(crate) type DeadIds = [u64];

#[inline]
fn is_dead(dead: Option<&DeadIds>, id: u32) -> bool {
    dead.is_some_and(|bits| {
        bits.get((id / 64) as usize)
            .is_some_and(|w| w & (1u64 << (id % 64)) != 0)
    })
}

/// One segment's part of a trigram's posting list.
#[derive(Clone, Copy)]
pub(crate) struct ListPart<'a> {
    /// The V4-encoded list.
    pub data: &'a [u8],
    /// Added to every decoded file id (the segment's first global id).
    pub id_offset: u32,
    /// Global ids to leave out (superseded or deleted files of this segment).
    pub dead: Option<&'a DeadIds>,
}

/// A trigram's posting list over the segments of an index, as the planner sees it.
pub(crate) struct TrigramList<'a> {
    pub trigram: Trigram,
    /// Planning size of the live postings; 0 means no live posting.
    pub plan: u64,
    /// Parts in ascending id order (each part's ids lie above the previous part's).
    pub parts: Vec<ListPart<'a>>,
}

/// Every live posting of `list`, ascending.
fn decode_list(list: &TrigramList) -> Result<Vec<FileLocation>> {
    let mut out = Vec::new();
    for part in &list.parts {
        let mut cursor = PostingCursor::new(part.data)?;
        while let Some(loc) = cursor.current() {
            let id = loc.file_id + part.id_offset;
            if !is_dead(part.dead, id) {
                out.push(FileLocation::new(id, loc.line_no));
            }
            cursor.advance()?;
        }
    }
    Ok(out)
}

/// The slice of `cands` whose ids fall in `parts[k]`'s range.
fn part_range(cands: &[FileLocation], parts: &[ListPart], k: usize) -> std::ops::Range<usize> {
    let lo = cands.partition_point(|c| c.file_id < parts[k].id_offset);
    let hi = match parts.get(k + 1) {
        Some(next) => cands.partition_point(|c| c.file_id < next.id_offset),
        None => cands.len(),
    };
    lo..hi
}

/// Candidates shifted into a part's own id space.
fn to_local(cands: &[FileLocation], offset: u32) -> Vec<FileLocation> {
    cands
        .iter()
        .map(|c| FileLocation::new(c.file_id - offset, c.line_no))
        .collect()
}

/// The candidates (sorted, key-unique, never dead) present in `list`.
fn intersect_list(cands: &[FileLocation], list: &TrigramList) -> Result<Vec<FileLocation>> {
    if let [part] = list.parts.as_slice()
        && part.id_offset == 0
    {
        let mut cursor = PostingCursor::new(part.data)?;
        return intersect_with_cursor(cands, &mut cursor);
    }
    let mut out = Vec::new();
    for (k, part) in list.parts.iter().enumerate() {
        let range = part_range(cands, &list.parts, k);
        let local = to_local(&cands[range], part.id_offset);
        let mut cursor = PostingCursor::new(part.data)?;
        for hit in intersect_with_cursor(&local, &mut cursor)? {
            out.push(FileLocation::new(hit.file_id + part.id_offset, hit.line_no));
        }
    }
    Ok(out)
}

/// Set `keep[i]` for every candidate present in `list`.
fn mark_list(cands: &[FileLocation], list: &TrigramList, keep: &mut [bool]) -> Result<()> {
    for (k, part) in list.parts.iter().enumerate() {
        let range = part_range(cands, &list.parts, k);
        let mut cursor = PostingCursor::new(part.data)?;
        if part.id_offset == 0 {
            mark_with_cursor(&cands[range.clone()], &mut cursor, &mut keep[range])?;
        } else {
            let local = to_local(&cands[range.clone()], part.id_offset);
            mark_with_cursor(&local, &mut cursor, &mut keep[range])?;
        }
    }
    Ok(())
}

/// Candidate lines for a pattern's trigrams (sorted, deduplicated), each given as
/// its list or `None` when absent. Smallest planning size first; with
/// `allow_skip`, stop once the next list is much larger than the candidates left.
pub(crate) fn plan_intersection(
    lists: Vec<Option<TrigramList>>,
    allow_skip: bool,
) -> Vec<FileLocation> {
    // Any missing (or fully dead) list means the pattern cannot match.
    let mut lists: Vec<TrigramList> = match lists.into_iter().collect::<Option<Vec<_>>>() {
        Some(l) => l,
        None => return vec![],
    };
    if lists.is_empty() || lists.iter().any(|l| l.plan == 0) {
        return vec![];
    }

    // Smallest list first: it is the only one fully decoded.
    lists.sort_by_key(|l| l.plan);

    let mut cands = match decode_list(&lists[0]) {
        Ok(locations) => locations,
        Err(e) => {
            log::warn!(
                "Failed to decompress posting list for trigram {}: {}",
                lists[0].trigram,
                e
            );
            return vec![];
        }
    };
    cands.dedup_by_key(|l| key(l));

    // Stream the remaining lists against the shrinking candidate set.
    for list in &lists[1..] {
        if cands.is_empty() {
            break;
        }
        // Lists are ascending, so once one is too big to be worth decoding, all
        // the remaining ones are too.
        if allow_skip && list.plan as usize > cands.len().saturating_mul(SKIP_BYTES_PER_CANDIDATE) {
            log::debug!(
                "Intersection stopped early: {} candidates, next list {} bytes",
                cands.len(),
                list.plan
            );
            break;
        }
        match intersect_list(&cands, list) {
            Ok(next) => cands = next,
            Err(e) => {
                log::warn!(
                    "Failed to decompress posting list for trigram {}: {}",
                    list.trigram,
                    e
                );
                return vec![];
            }
        }
    }
    cands
}

/// Case-insensitive candidate lines: `windows[w]` holds the lists of window `w`'s
/// case variants that are present. See [`TrigramIndex::search_candidates_fold`].
pub(crate) fn plan_fold_intersection(windows: Vec<Vec<TrigramList>>) -> Vec<FileLocation> {
    // A window with no live variant cannot match in any casing.
    let mut ws: Vec<(u64, Vec<TrigramList>)> = Vec::with_capacity(windows.len());
    for variants in windows {
        let live: Vec<TrigramList> = variants.into_iter().filter(|l| l.plan > 0).collect();
        if live.is_empty() {
            return vec![];
        }
        let weight = live.iter().map(|l| l.plan).sum();
        ws.push((weight, live));
    }
    if ws.is_empty() {
        return vec![];
    }
    ws.sort_by_key(|w| w.0);
    let t_lookup = std::time::Instant::now();

    // Cheapest window: decode every variant and merge.
    let mut cands: Vec<FileLocation> = Vec::new();
    for list in &ws[0].1 {
        match decode_list(list) {
            Ok(l) => cands.extend(l),
            Err(e) => {
                log::warn!(
                    "Failed to decompress posting list for trigram {}: {}",
                    list.trigram,
                    e
                );
                return vec![];
            }
        }
    }
    let t_decode = t_lookup.elapsed();
    let raw = cands.len();
    cands.sort_unstable();
    cands.dedup_by_key(|l| key(l));
    log::debug!(
        "Fold first window: {} variants, {} bytes, {} raw postings -> {} keys; decode {:?}, sort+dedup {:?}",
        ws[0].1.len(),
        ws[0].0,
        raw,
        cands.len(),
        t_decode,
        t_lookup.elapsed() - t_decode
    );

    for (weight, lists) in &ws[1..] {
        if cands.is_empty() {
            break;
        }
        // Each variant walks the whole candidate set once (one seek per
        // candidate, about the cost of decoding one byte), on top of decoding its
        // list. Kubernetes, `(?i)kubernetes`: the second window cost 20 ms to drop
        // 20k of 134k candidates, which the verifier would have handled in 0.3 ms.
        let cost = (*weight as usize).saturating_add(lists.len().saturating_mul(cands.len()));
        if cost > cands.len().saturating_mul(SKIP_BYTES_PER_CANDIDATE) {
            log::debug!(
                "Fold intersection stopped early: {} candidates, next window {} bytes x {} variants",
                cands.len(),
                weight,
                lists.len()
            );
            break;
        }
        let mut keep = vec![false; cands.len()];
        let mut window_ok = true;
        for list in lists {
            if let Err(e) = mark_list(&cands, list, &mut keep) {
                // Skipping a window keeps the result a superset.
                log::warn!(
                    "Failed to read posting list for trigram {}: {}; window skipped",
                    list.trigram,
                    e
                );
                window_ok = false;
                break;
            }
        }
        if !window_ok {
            continue;
        }
        cands = cands
            .iter()
            .zip(&keep)
            .filter(|(_, k)| **k)
            .map(|(c, _)| *c)
            .collect();
    }
    cands
}

/// A list held by one segment.
pub(crate) fn single_list(trigram: Trigram, part: ListPart<'_>, plan: u64) -> TrigramList<'_> {
    TrigramList {
        trigram,
        plan,
        parts: vec![part],
    }
}

/// A pattern's distinct trigrams, sorted; empty when it is too short (the caller
/// then scans).
pub(crate) fn pattern_trigrams(pattern: &str) -> Vec<Trigram> {
    if pattern.len() < 3 {
        // Pattern too short for trigrams - caller must fall back to full scan
        return vec![];
    }
    let mut trigrams = extract_trigrams(pattern);
    // A repeated trigram (e.g. "aaaa") would otherwise be intersected with itself
    trigrams.sort_unstable();
    trigrams.dedup();
    trigrams
}

/// The case variants of each 3-byte window of an ASCII literal (identical windows
/// once, sorted); `None` when the literal is too short or not ASCII.
pub(crate) fn fold_windows(literal: &[u8]) -> Option<Vec<Vec<Trigram>>> {
    if literal.len() < 3 || !literal.is_ascii() {
        return None;
    }
    // Variant set per window; identical windows are intersected once.
    let mut windows: Vec<Vec<Trigram>> = literal.windows(3).map(case_variants).collect();
    windows.sort_unstable();
    windows.dedup();
    Some(windows)
}

/// The trigrams whose lines hold a Kelvin sign (`E2 84 AA`) or a long s
/// (`C5 BF`), for [`TrigramIndex::exotic_fold_lines`]: every `C5 BF ?` trigram
/// (one range), and the Kelvin sign and every `? C5 BF` trigram (singles).
pub(crate) const EXOTIC_LONG_S_RANGE: (Trigram, Trigram) = (0xC5_BF_00, 0xC5_BF_FF);
pub(crate) fn exotic_singles() -> impl Iterator<Item = Trigram> {
    const KELVIN: Trigram = 0xE2_84_AA;
    std::iter::once(KELVIN).chain((0u32..=0xFF).map(|first| first << 16 | 0xC5_BF))
}

/// Every live posting of `lists`, merged, sorted and deduplicated.
pub(crate) fn union_lists(lists: &[TrigramList]) -> Vec<FileLocation> {
    let mut out = Vec::new();
    for list in lists {
        match decode_list(list) {
            Ok(l) => out.extend(l),
            Err(e) => log::warn!(
                "Failed to decompress posting list for trigram {}: {}",
                list.trigram,
                e
            ),
        }
    }
    out.sort_unstable();
    out.dedup_by_key(|l| key(l));
    out
}

#[derive(Debug, Clone)]
struct DirectoryEntry {
    /// Position in the directory (the planning-size file is indexed the same way)
    index: usize,
    /// The trigram value (for binary search)
    trigram: Trigram,
    /// Absolute byte offset in the file where compressed data starts
    data_offset: u64,
    /// Size of compressed posting list in bytes
    compressed_size: u32,
}

/// Trigram-based inverted index
///
/// Maps each trigram to a sorted list of locations where it appears.
/// Posting lists are kept sorted by (file_id, line_no) for efficient intersection.
/// The index itself is kept sorted by trigram for O(log n) binary search.
///
/// Supports three modes:
/// 1. **In-memory mode** (during indexing): All posting lists in RAM
/// 2. **Batch-flush mode** (large codebases): Periodically flushes partial indices to disk to limit RAM
/// 3. **Lazy-loaded mode** (after loading): Compressed posting lists in mmap, decompressed on-demand
pub struct TrigramIndex {
    /// Inverted index: sorted Vec of (trigram, locations) for binary search
    /// Used in in-memory mode (during indexing)
    index: Vec<(Trigram, Vec<FileLocation>)>,
    /// File ID to file path mapping (in-memory mode). Empty in lazy mode: the
    /// paths section stays in the mmap undecoded and `num_files` carries the
    /// count, because content.bin already answers `file_id → path` in O(1).
    files: Vec<PathBuf>,
    /// File count in lazy mode.
    num_files: usize,
    /// Start of the paths section in the mmap (lazy mode).
    paths_offset: usize,
    /// Paths decoded from the mmap on first request (lazy mode).
    lazy_paths: std::sync::OnceLock<Vec<PathBuf>>,
    /// Temporary HashMap used during batch indexing (None when finalized)
    temp_index: Option<HashMap<Trigram, Vec<FileLocation>>>,
    /// Memory-mapped index file (for lazy loading)
    mmap: Option<memmap2::Mmap>,
    /// Number of directory entries in the mmap (lazy mode). The directory is
    /// binary-searched in place; it is never decoded into a Vec.
    num_trigrams: usize,
    /// Cap on posting list size; 0 = unlimited. Enforced at finalize time.
    /// Bounds query latency for high-frequency trigrams (trigram-density lens).
    max_posting_list_entries: usize,
    /// Planning size of every directory entry (lazy mode), when the index was
    /// written with one; see [`plan_size`].
    plan: Option<PlanSizes>,
}

impl TrigramIndex {
    /// Create a new empty trigram index
    pub fn new() -> Self {
        Self {
            index: Vec::new(),
            files: Vec::new(),
            num_files: 0,
            paths_offset: 0,
            lazy_paths: std::sync::OnceLock::new(),
            temp_index: Some(HashMap::new()),
            mmap: None,
            num_trigrams: 0,
            max_posting_list_entries: 0,
            plan: None,
        }
    }

    /// Set maximum posting list entries per trigram (0 = unlimited).
    pub fn set_max_posting_list_entries(&mut self, cap: usize) {
        self.max_posting_list_entries = cap;
    }

    /// Add a file to the index and return its file_id
    pub fn add_file(&mut self, path: PathBuf) -> u32 {
        let file_id = self.files.len() as u32;
        self.files.push(path);
        file_id
    }

    /// Get file path for a file_id
    pub fn get_file(&self, file_id: u32) -> Option<&PathBuf> {
        match &self.mmap {
            None => self.files.get(file_id as usize),
            Some(mmap) => self
                .lazy_paths
                .get_or_init(|| {
                    let mut out = Vec::with_capacity(self.num_files);
                    let mut pos = self.paths_offset;
                    for _ in 0..self.num_files {
                        let Ok((len, consumed)) = read_varint(&mmap[pos..]) else {
                            break;
                        };
                        pos += consumed;
                        let end = pos + len as usize;
                        let Some(bytes) = mmap.get(pos..end) else {
                            break;
                        };
                        out.push(PathBuf::from(String::from_utf8_lossy(bytes).into_owned()));
                        pos = end;
                    }
                    out
                })
                .get(file_id as usize),
        }
    }

    /// Get total number of files
    pub fn file_count(&self) -> usize {
        if self.mmap.is_some() {
            self.num_files
        } else {
            self.files.len()
        }
    }

    /// Get total number of unique trigrams
    pub fn trigram_count(&self) -> usize {
        if self.mmap.is_some() {
            // Lazy-loaded mode
            self.num_trigrams
        } else {
            // In-memory mode
            self.index.len()
        }
    }

    /// Binary-search the mmapped directory for `trigram` (lazy mode only).
    ///
    /// Reads only the 4-byte trigram at each probe; the full 16-byte entry is
    /// decoded once, on a hit. `load` has already checked that the whole
    /// directory lies inside the mmap.
    fn find_entry(&self, trigram: Trigram) -> Option<DirectoryEntry> {
        let mmap = self.mmap.as_ref()?;
        let (mut lo, mut hi) = (0usize, self.num_trigrams);
        while lo < hi {
            let mid = lo + (hi - lo) / 2;
            let off = HEADER_SIZE + mid * DIR_ENTRY_SIZE;
            match read_u32(mmap, off).cmp(&trigram) {
                std::cmp::Ordering::Less => lo = mid + 1,
                std::cmp::Ordering::Greater => hi = mid,
                std::cmp::Ordering::Equal => {
                    return Some(DirectoryEntry {
                        index: mid,
                        trigram,
                        data_offset: read_u64(mmap, off + 4),
                        compressed_size: read_u32(mmap, off + 12),
                    });
                }
            }
        }
        None
    }

    /// Index a file's content
    ///
    /// Extracts all trigrams from the content and adds them to the inverted index.
    /// Must call finalize() after indexing all files to prepare for searching.
    pub fn index_file(&mut self, file_id: u32, content: &str) {
        let trigrams = extract_trigrams_with_locations(content, file_id);

        // Use the persistent HashMap for O(1) updates during batch processing
        if let Some(ref mut temp_map) = self.temp_index {
            for (trigram, location) in trigrams {
                temp_map
                    .entry(trigram)
                    .or_insert_with(Vec::new)
                    .push(location);
            }
        } else {
            panic!("Cannot call index_file() after finalize(). Index is read-only.");
        }
    }

    /// Build index from a collection of pre-extracted trigrams (bulk operation)
    ///
    /// This is much more efficient than calling index_file() multiple times,
    /// as it builds the HashMap once instead of rebuilding it for each file.
    pub fn build_from_trigrams(&mut self, trigrams: Vec<(Trigram, FileLocation)>) {
        let mut temp_map: HashMap<Trigram, Vec<FileLocation>> = HashMap::new();

        // Group trigrams into posting lists
        for (trigram, location) in trigrams {
            temp_map.entry(trigram).or_default().push(location);
        }

        // Convert to sorted Vec for binary search
        self.index = temp_map.into_iter().collect();

        // Clear temp_index since we're using the Vec directly
        self.temp_index = None;

        // Finalize immediately (sort and deduplicate)
        self.finalize();
    }

    /// Finalize the index by sorting all posting lists and the index itself
    ///
    /// Must be called after all files are indexed, before querying.
    /// Converts the HashMap to a sorted Vec for fast binary search.
    ///
    /// If batch flushing was enabled, finalization will be deferred until write()
    /// is called, which will perform streaming merge directly to disk.
    pub fn finalize(&mut self) {
        // Standard finalization (no batch flushing)
        // Convert HashMap to Vec if we have a temp index
        if let Some(temp_map) = self.temp_index.take() {
            self.index = temp_map.into_iter().collect();
        }

        // Sort, deduplicate, and cap posting lists
        let cap = self.max_posting_list_entries;
        for (trigram, list) in self.index.iter_mut() {
            list.sort_unstable();
            list.dedup(); // Remove duplicates (same trigram appearing multiple times on same line)
            if cap > 0 && list.len() > cap {
                log::warn!(
                    "Trigram 0x{:06X} posting list has {} entries (cap {}); truncating.",
                    trigram,
                    list.len(),
                    cap
                );
                list.truncate(cap);
            }
        }

        // Sort the index by trigram for binary search
        self.index.sort_unstable_by_key(|(trigram, _)| *trigram);
    }

    /// Search for a plain text pattern
    ///
    /// Returns candidate file locations that could contain the pattern.
    /// Caller must verify actual matches.
    ///
    /// In lazy-loaded mode: Decompresses posting lists on-demand from mmap.
    /// In in-memory mode: Uses pre-loaded posting lists.
    pub fn search(&self, pattern: &str) -> Vec<FileLocation> {
        self.search_impl(pattern, false)
    }

    /// Candidate lines for `pattern`, allowing the intersection to stop early.
    ///
    /// Every posting list of a common trigram (`ide`, `ent`, `nt_` …) is streamed
    /// in full on every query, and on a pattern like `ident_7` the four largest
    /// lists cost ~45 ms without removing a single candidate that the smallest
    /// list (`t_7`) had not already narrowed to. The caller verifies every
    /// candidate line anyway — exactly, and on a thread pool — so once the next
    /// list is much larger than the surviving candidate set, decoding it costs
    /// more than verifying the extra candidates would. This method stops there;
    /// the result is a superset of [`Self::search`] and never misses a match.
    pub fn search_candidates(&self, pattern: &str) -> Vec<FileLocation> {
        self.search_impl(pattern, true)
    }

    fn search_impl(&self, pattern: &str, allow_skip: bool) -> Vec<FileLocation> {
        let trigrams = pattern_trigrams(pattern);
        if trigrams.is_empty() {
            return vec![];
        }

        // Check if we're in lazy-loaded mode or in-memory mode
        if self.mmap.is_some() {
            // Lazy-loaded mode: look up every directory entry first; any miss
            // means the pattern cannot match.
            let lists = trigrams
                .iter()
                .map(|&t| {
                    self.list_part(t).map(|(part, plan)| TrigramList {
                        trigram: t,
                        plan,
                        parts: vec![part],
                    })
                })
                .collect();
            plan_intersection(lists, allow_skip)
        } else {
            // In-memory mode: use pre-loaded index
            let mut posting_lists: Vec<&[FileLocation]> = Vec::with_capacity(trigrams.len());
            for trigram in &trigrams {
                match self.index.binary_search_by_key(trigram, |(t, _)| *t) {
                    Ok(idx) => posting_lists.push(&self.index[idx].1),
                    // Trigram missing - pattern cannot match
                    Err(_) => return vec![],
                }
            }

            // Sort by list size (smallest first for efficient intersection)
            posting_lists.sort_by_key(|list| list.len());

            if !allow_skip {
                return intersect_sorted(&posting_lists);
            }
            let mut cands: Vec<FileLocation> = posting_lists[0].to_vec();
            cands.dedup_by_key(|l| key(l));
            for list in &posting_lists[1..] {
                if cands.is_empty() {
                    break;
                }
                // ~1.3 bytes per posting on disk; same rule as the lazy path.
                if list.len().saturating_mul(13) / 10
                    > cands.len().saturating_mul(SKIP_BYTES_PER_CANDIDATE)
                {
                    break;
                }
                cands = intersect_two(&cands, list);
            }
            cands
        }
    }

    /// Case-insensitive candidate lines for an ASCII literal.
    ///
    /// Every 3-byte window of `literal` is looked up under all of its ASCII
    /// case variants (≤ 8 trigrams: each letter byte has two forms) and the
    /// variants' posting lists are OR-ed; windows are then AND-ed, cheapest
    /// first, with the same early stop as [`search_candidates`](Self::search_candidates).
    /// The result is a superset of every line that contains the literal in any
    /// ASCII casing; callers verify with a `(?i)` regex.
    ///
    /// Only ASCII case is folded here. Unicode simple case folding also maps
    /// `k` to U+212A KELVIN SIGN and `s` to U+017F LATIN SMALL LETTER LONG S;
    /// a caller whose literal contains `k` or `s` must union
    /// [`exotic_fold_lines`](Self::exotic_fold_lines) into the result to keep
    /// parity with the regex engine. A non-ASCII literal is not supported:
    /// the caller must fall back to a scan.
    pub fn search_candidates_fold(&self, literal: &[u8]) -> Vec<FileLocation> {
        let Some(windows) = fold_windows(literal) else {
            return vec![];
        };

        if self.mmap.is_some() {
            // The present variants of each window; a window with no present
            // variant cannot match in any casing.
            let lists = windows
                .iter()
                .map(|variants| {
                    variants
                        .iter()
                        .filter_map(|&t| {
                            self.list_part(t).map(|(part, plan)| TrigramList {
                                trigram: t,
                                plan,
                                parts: vec![part],
                            })
                        })
                        .collect()
                })
                .collect();
            plan_fold_intersection(lists)
        } else {
            let mut ws: Vec<(usize, Vec<&[FileLocation]>)> = Vec::with_capacity(windows.len());
            for variants in &windows {
                let lists: Vec<&[FileLocation]> = variants
                    .iter()
                    .filter_map(|t| {
                        self.index
                            .binary_search_by_key(t, |(x, _)| *x)
                            .ok()
                            .map(|i| self.index[i].1.as_slice())
                    })
                    .collect();
                if lists.is_empty() {
                    return vec![];
                }
                // ~1.3 bytes per posting on disk; same rule as the lazy path.
                let weight = lists.iter().map(|l| l.len()).sum::<usize>() * 13 / 10;
                ws.push((weight, lists));
            }
            ws.sort_by_key(|w| w.0);

            let mut cands: Vec<FileLocation> =
                ws[0].1.iter().flat_map(|l| l.iter().copied()).collect();
            cands.sort_unstable();
            cands.dedup_by_key(|l| key(l));

            for (weight, lists) in &ws[1..] {
                if cands.is_empty() {
                    break;
                }
                let cost = weight.saturating_add(lists.len().saturating_mul(cands.len()));
                if cost > cands.len().saturating_mul(SKIP_BYTES_PER_CANDIDATE) {
                    break;
                }
                let mut next: Vec<FileLocation> = lists
                    .iter()
                    .flat_map(|l| intersect_two(&cands, l))
                    .collect();
                next.sort_unstable();
                next.dedup_by_key(|l| key(l));
                cands = next;
            }
            cands
        }
    }

    /// Every line that contains U+212A KELVIN SIGN or U+017F LONG S.
    ///
    /// Under Unicode simple case folding a `(?i)` regex lets `k` match the
    /// Kelvin sign and `s` match the long s. Their UTF-8 forms (`E2 84 AA` and
    /// `C5 BF`) never align with the ASCII windows of
    /// [`search_candidates_fold`](Self::search_candidates_fold), so a line whose
    /// only match uses one of them would be missed. The Kelvin sign is its own
    /// trigram; the long s appears in a `C5 BF ?` or `? C5 BF` trigram of any
    /// line long enough to hold a ≥3-byte literal. On code corpora every lookup
    /// misses, so this costs a few hundred directory probes and returns nothing.
    pub fn exotic_fold_lines(&self) -> Vec<FileLocation> {
        let (long_s_lo, long_s_hi) = EXOTIC_LONG_S_RANGE;

        let mut out: Vec<FileLocation> = Vec::new();
        if self.mmap.is_some() {
            let mut lists: Vec<TrigramList> = Vec::new();
            lists.extend(
                self.list_parts_in(long_s_lo, long_s_hi)
                    .into_iter()
                    .map(|(t, part, plan)| single_list(t, part, plan)),
            );
            for t in exotic_singles() {
                lists.extend(self.list_part(t).map(|(p, plan)| single_list(t, p, plan)));
            }
            out = union_lists(&lists);
        } else {
            let lo = self.index.partition_point(|(t, _)| *t < long_s_lo);
            let hi = self.index.partition_point(|(t, _)| *t <= long_s_hi);
            for (_, list) in &self.index[lo..hi] {
                out.extend(list.iter().copied());
            }
            for t in exotic_singles() {
                if let Ok(i) = self.index.binary_search_by_key(&t, |(x, _)| *x) {
                    out.extend(self.index[i].1.iter().copied());
                }
            }
        }
        out.sort_unstable();
        out.dedup_by_key(|l| key(l));
        out
    }

    /// Directory entries with `lo <= trigram <= hi` (lazy mode only).
    fn dir_range(&self, lo: Trigram, hi: Trigram) -> Vec<DirectoryEntry> {
        let Some(mmap) = self.mmap.as_ref() else {
            return vec![];
        };
        let at = |i: usize| read_u32(mmap, HEADER_SIZE + i * DIR_ENTRY_SIZE);
        let (mut l, mut h) = (0usize, self.num_trigrams);
        while l < h {
            let mid = l + (h - l) / 2;
            if at(mid) < lo {
                l = mid + 1;
            } else {
                h = mid;
            }
        }
        let mut out = Vec::new();
        let mut i = l;
        while i < self.num_trigrams {
            let off = HEADER_SIZE + i * DIR_ENTRY_SIZE;
            let trigram = read_u32(mmap, off);
            if trigram > hi {
                break;
            }
            out.push(DirectoryEntry {
                index: i,
                trigram,
                data_offset: read_u64(mmap, off + 4),
                compressed_size: read_u32(mmap, off + 12),
            });
            i += 1;
        }
        out
    }

    /// Search for a plain text pattern and return the distinct candidate file IDs
    ///
    /// Output is sorted ascending. Same caveats as [`search`](Self::search):
    /// callers must verify actual matches, and short patterns yield nothing.
    pub fn search_files(&self, pattern: &str) -> Vec<u32> {
        let mut files: Vec<u32> = self
            .search(pattern)
            .into_iter()
            .map(|l| l.file_id)
            .collect();
        // `search` output is sorted by (file_id, line_no), so duplicates are adjacent
        files.dedup();
        files
    }

    /// Get posting list for a specific trigram (for debugging)
    pub fn get_posting_list(&self, trigram: Trigram) -> Option<&Vec<FileLocation>> {
        self.index
            .binary_search_by_key(&trigram, |(t, _)| *t)
            .ok()
            .map(|idx| &self.index[idx].1)
    }

    /// Write the trigram index to disk
    ///
    /// Binary format V4 (lazy-loadable with directory + data separation):
    /// - Header (32 bytes): magic, version, num_trigrams, num_files, paths_offset
    /// - Directory Section (16 bytes per trigram, sorted by trigram):
    ///   - trigram: u32 (4 bytes)
    ///   - data_offset: u64 (8 bytes) - absolute offset in file
    ///   - compressed_size: u32 (4 bytes) - size of compressed posting list
    /// - Data Section (variable size):
    ///   - Posting lists as per-file blocks (see [`encode_posting_list`])
    /// - File Paths Section at `paths_offset` (variable size):
    ///   - path_len: varint
    ///   - path_bytes: [u8; path_len]
    pub fn write(&mut self, path: impl AsRef<Path>) -> Result<()> {
        let path = path.as_ref();

        // Standard write path (no batch flushing).
        // Crash-safe: stream into `<path>.tmp`, sync, then rename over `path`.
        // A crash mid-write leaves the previous trigrams.bin intact (or no file
        // at all), never a short file with valid magic bytes.
        let tmp_path = crate::atomic_write::tmp_path_for(path);
        let file = OpenOptions::new()
            .create(true)
            .write(true)
            .truncate(true)
            .open(&tmp_path)
            .with_context(|| format!("Failed to create {}", tmp_path.display()))?;

        // Use a large buffer (16MB) for streaming writes
        let mut writer = std::io::BufWriter::with_capacity(16 * 1024 * 1024, file);

        // Step 1: Compress all posting lists and build the directory. Data
        // offsets are known up front because the directory has a fixed size.
        let data_start = (HEADER_SIZE + self.index.len() * DIR_ENTRY_SIZE) as u64;
        let mut current_offset = data_start;
        let mut directory: Vec<DirectoryEntry> = Vec::with_capacity(self.index.len());
        let mut compressed_lists: Vec<Vec<u8>> = Vec::with_capacity(self.index.len());

        for (trigram, locations) in &self.index {
            let mut compressed = Vec::with_capacity(locations.len() + 16);
            encode_posting_list(locations, &mut compressed)?;

            directory.push(DirectoryEntry {
                index: directory.len(),
                trigram: *trigram,
                data_offset: current_offset,
                compressed_size: compressed.len() as u32,
            });
            current_offset += compressed.len() as u64;
            compressed_lists.push(compressed);
        }
        let paths_offset = current_offset;

        // Step 2: Write header
        writer.write_all(MAGIC)?;
        writer.write_all(&VERSION.to_le_bytes())?;
        writer.write_all(&(self.index.len() as u64).to_le_bytes())?; // num_trigrams
        writer.write_all(&(self.files.len() as u64).to_le_bytes())?; // num_files
        writer.write_all(&paths_offset.to_le_bytes())?; // paths_offset

        // Step 3: Write directory
        for entry in &directory {
            writer.write_all(&entry.trigram.to_le_bytes())?;
            writer.write_all(&entry.data_offset.to_le_bytes())?;
            writer.write_all(&entry.compressed_size.to_le_bytes())?;
        }

        // Step 4: Write data section (compressed posting lists)
        for compressed in &compressed_lists {
            writer.write_all(compressed)?;
        }

        // Step 5: Write file paths
        for file_path in &self.files {
            let path_str = file_path.to_string_lossy();
            let path_bytes = path_str.as_bytes();
            write_varint(&mut writer, path_bytes.len() as u32)?;
            writer.write_all(path_bytes)?;
        }

        // Flush and sync, then publish atomically
        writer.flush()?;
        writer.get_ref().sync_all()?;
        drop(writer);
        crate::atomic_write::atomic_replace(&tmp_path, path)
            .with_context(|| format!("Failed to move {} into place", path.display()))?;

        log::info!(
            "Wrote lazy-loadable trigram index: {} trigrams, {} files to {:?}",
            self.index.len(),
            self.files.len(),
            path
        );

        Ok(())
    }

    /// Load trigram index from disk using memory-mapped I/O with lazy loading
    ///
    /// Binary format V4: validates the header, bounds-checks the directory
    /// against `paths_offset`, and decodes only the file paths. The directory
    /// stays in the mmap and is binary-searched in place; posting lists are
    /// decompressed on demand during search. Cost is O(files), not O(trigrams).
    pub fn load(path: impl AsRef<Path>) -> Result<Self> {
        let path = path.as_ref();

        let file =
            File::open(path).with_context(|| format!("Failed to open {}", path.display()))?;

        // Memory-map the file (keep it alive for lazy access)
        let mmap = unsafe {
            memmap2::Mmap::map(&file)
                .with_context(|| format!("Failed to mmap {}", path.display()))?
        };

        // Validate magic + version before the size check so an older (shorter
        // header) format still reports the version mismatch callers key on.
        if mmap.len() < 8 {
            anyhow::bail!(
                "trigrams.bin too small (expected at least {} bytes)",
                HEADER_SIZE
            );
        }

        if &mmap[0..4] != MAGIC {
            anyhow::bail!("Invalid trigrams.bin (wrong magic bytes)");
        }

        let version = read_u32(&mmap, 4);
        if version != VERSION {
            anyhow::bail!(
                "Unsupported trigrams.bin version: {} (expected {}). Please re-index with 'reflex index'.",
                version,
                VERSION
            );
        }

        if mmap.len() < HEADER_SIZE {
            anyhow::bail!(
                "trigrams.bin too small (expected at least {} bytes)",
                HEADER_SIZE
            );
        }

        let num_trigrams = read_u64(&mmap, NUM_TRIGRAMS_OFFSET) as usize;
        let num_files = read_u64(&mmap, NUM_FILES_OFFSET) as usize;
        let paths_offset = read_u64(&mmap, PATHS_OFFSET_OFFSET);

        log::debug!(
            "Loading lazy trigram index: {} trigrams, {} files",
            num_trigrams,
            num_files
        );

        // Layout check: header + directory must end at or before the paths
        // section, which must lie inside the file. This is the only guard the
        // in-place directory search relies on.
        let directory_end = num_trigrams
            .checked_mul(DIR_ENTRY_SIZE)
            .and_then(|d| d.checked_add(HEADER_SIZE))
            .ok_or_else(|| anyhow::anyhow!("trigrams.bin directory size overflows"))?
            as u64;
        if directory_end > paths_offset || paths_offset > mmap.len() as u64 {
            anyhow::bail!(
                "trigrams.bin layout out of bounds: directory_end={}, paths_offset={}, len={}",
                directory_end,
                paths_offset,
                mmap.len()
            );
        }

        // The paths section is validated (bounds only, no allocation) and left in
        // the mmap. Decoding 24k paths into a Vec<PathBuf> was part of every CLI
        // open; the query side reads paths from content.bin, O(1) per id since
        // its V2, and `get_file` decodes this section on first request.
        let mut pos = paths_offset as usize;
        for _ in 0..num_files {
            let (path_len, consumed) = read_varint(&mmap[pos..])?;
            pos += consumed + path_len as usize;
            if pos > mmap.len() {
                anyhow::bail!("Truncated file path at pos={}", pos);
            }
        }
        let files = Vec::new();

        log::info!(
            "Loaded lazy trigram index: {} trigrams, {} files (directory: {} KB, in mmap)",
            num_trigrams,
            num_files,
            num_trigrams * DIR_ENTRY_SIZE / 1024
        );

        Ok(Self {
            index: Vec::new(), // Empty in lazy mode
            files,
            num_files,
            paths_offset: paths_offset as usize,
            lazy_paths: std::sync::OnceLock::new(),
            temp_index: None,
            mmap: Some(mmap), // Keep mmap alive for lazy decompression!
            num_trigrams,
            max_posting_list_entries: 0,
            plan: None,
        })
    }

    /// Attach the planning sizes written next to this index (`trigrams.<g>.plan`).
    /// The early-stop planner then orders and stops by planning size instead of
    /// on-disk bytes (see [`plan_size`]).
    pub fn attach_plan(&mut self, path: impl AsRef<Path>) -> Result<()> {
        let plan = PlanSizes::load(path.as_ref())?;
        if plan.len() != self.num_trigrams {
            anyhow::bail!(
                "{} lists {} trigrams, the index {}",
                path.as_ref().display(),
                plan.len(),
                self.num_trigrams
            );
        }
        self.plan = Some(plan);
        Ok(())
    }

    /// Whether planning sizes are attached.
    pub fn has_plan(&self) -> bool {
        self.plan.is_some()
    }

    /// Every trigram of the directory, ascending (lazy mode).
    pub(crate) fn trigrams(&self) -> impl Iterator<Item = Trigram> + '_ {
        let mmap = self.mmap.as_ref();
        (0..if mmap.is_some() { self.num_trigrams } else { 0 })
            .map(move |i| read_u32(mmap.expect("lazy"), HEADER_SIZE + i * DIR_ENTRY_SIZE))
    }

    /// One trigram's list as the planner sees it (lazy mode): its bytes and its
    /// planning size (on-disk bytes when no planning sizes are attached).
    pub(crate) fn list_part(&self, trigram: Trigram) -> Option<(ListPart<'_>, u64)> {
        let entry = self.find_entry(trigram)?;
        self.part_of(&entry)
    }

    /// Every list with `lo <= trigram <= hi` (lazy mode).
    pub(crate) fn list_parts_in(
        &self,
        lo: Trigram,
        hi: Trigram,
    ) -> Vec<(Trigram, ListPart<'_>, u64)> {
        self.dir_range(lo, hi)
            .into_iter()
            .filter_map(|e| self.part_of(&e).map(|(part, plan)| (e.trigram, part, plan)))
            .collect()
    }

    fn part_of(&self, entry: &DirectoryEntry) -> Option<(ListPart<'_>, u64)> {
        let mmap = self.mmap.as_ref()?;
        let start = entry.data_offset as usize;
        let end = start + entry.compressed_size as usize;
        if end > mmap.len() {
            log::warn!(
                "Posting list out of bounds for trigram {}: offset={}, size={}, mmap_len={}",
                entry.trigram,
                entry.data_offset,
                entry.compressed_size,
                mmap.len()
            );
            return None;
        }
        let plan = match &self.plan {
            Some(p) => p.get(entry.index) as u64,
            None => entry.compressed_size as u64,
        };
        Some((
            ListPart {
                data: &mmap[start..end],
                id_offset: 0,
                dead: None,
            },
            plan,
        ))
    }
}

impl Default for TrigramIndex {
    fn default() -> Self {
        Self::new()
    }
}

/// Extract all trigrams from text
///
/// Returns a vector of trigrams (without location info).
pub fn extract_trigrams(text: &str) -> Vec<Trigram> {
    let bytes = text.as_bytes();
    let mut trigrams = Vec::new();

    for i in 0..bytes.len().saturating_sub(2) {
        let trigram = bytes_to_trigram(&bytes[i..i + 3]);
        trigrams.push(trigram);
    }

    trigrams
}

/// Extract trigrams with file location information
///
/// Returns one `(trigram, location)` pair per **distinct trigram per line**,
/// for building the inverted index. Emitting every byte position (as V3 did)
/// only produced duplicate `(file, line)` keys that the intersection threw
/// away; deduplicating here is what makes `finalize`'s `dedup()` a no-op.
///
/// A trigram that spans a newline is attributed to the line of its first
/// byte, except that a trigram *starting* on `\n` belongs to the next line
/// (unchanged from V3, so `"lo\n"`-style queries keep matching).
pub fn extract_trigrams_with_locations(text: &str, file_id: u32) -> Vec<(Trigram, FileLocation)> {
    let mut result = Vec::with_capacity(text.len().saturating_sub(2));
    scan_line_trigrams(text, |line_no, trigrams| {
        let location = FileLocation::new(file_id, line_no);
        result.extend(trigrams.iter().map(|&t| (t, location)));
    });
    result
}

/// Walk `text` line by line and hand each line's distinct trigrams, sorted, to `f`.
///
/// This is the one place the newline rule lives: a trigram that spans a newline
/// belongs to the line of its first byte, except that a trigram *starting* on
/// `\n` belongs to the next line. Both the extractor above and the indexer's
/// parallel builder (`trigram_build`) are built on it, so the two can never
/// disagree about which line a trigram is on.
pub(crate) fn scan_line_trigrams(text: &str, mut f: impl FnMut(u32, &[Trigram])) {
    let bytes = text.as_bytes();
    // Trigrams of the line being scanned; sorted + deduplicated on flush
    let mut line_trigrams: Vec<Trigram> = Vec::with_capacity(128);
    let mut line_no: u32 = 1;

    for (i, &byte) in bytes.iter().enumerate() {
        // Track newlines
        if byte == b'\n' {
            line_trigrams.sort_unstable();
            line_trigrams.dedup();
            f(line_no, &line_trigrams);
            line_trigrams.clear();
            line_no += 1;
        }

        // Extract trigram
        if i + 2 < bytes.len() {
            line_trigrams.push(bytes_to_trigram(&bytes[i..i + 3]));
        }
    }
    line_trigrams.sort_unstable();
    line_trigrams.dedup();
    f(line_no, &line_trigrams);
}

/// Convert 3 bytes to a trigram (packed u32)
#[inline]
fn bytes_to_trigram(bytes: &[u8]) -> Trigram {
    debug_assert_eq!(bytes.len(), 3);
    (bytes[0] as u32) << 16 | (bytes[1] as u32) << 8 | (bytes[2] as u32)
}

/// All ASCII case variants of a 3-byte window, sorted and deduplicated.
///
/// Each ASCII letter byte contributes two forms, every other byte one, so the
/// result has 1, 2, 4 or 8 trigrams.
fn case_variants(window: &[u8]) -> Vec<Trigram> {
    debug_assert_eq!(window.len(), 3);
    let forms = |b: u8| -> Vec<u8> {
        if b.is_ascii_alphabetic() {
            vec![b.to_ascii_lowercase(), b.to_ascii_uppercase()]
        } else {
            vec![b]
        }
    };
    let mut out = Vec::with_capacity(8);
    for a in forms(window[0]) {
        for b in forms(window[1]) {
            for c in forms(window[2]) {
                out.push(bytes_to_trigram(&[a, b, c]));
            }
        }
    }
    out.sort_unstable();
    out.dedup();
    out
}

/// Convert trigram back to bytes (for debugging)
#[allow(dead_code)]
fn trigram_to_bytes(trigram: Trigram) -> [u8; 3] {
    [
        ((trigram >> 16) & 0xFF) as u8,
        ((trigram >> 8) & 0xFF) as u8,
        (trigram & 0xFF) as u8,
    ]
}

/// Intersection key: posting lists are matched on (file_id, line_no)
#[inline]
fn key(l: &FileLocation) -> (u32, u32) {
    (l.file_id, l.line_no)
}

/// Sorted two-pointer intersection of `a` and `b` on `key`.
///
/// `a` is the running candidate set (sorted, deduplicated by key). `b` is a sorted
/// posting list; should it hold several entries per key, all of them are
/// consumed on a match. When `b` is much larger
/// than `a`, the scan of `b` gallops via `partition_point`. Output keeps the
/// `FileLocation` from `a`, so it stays sorted and key-unique.
fn intersect_two(a: &[FileLocation], b: &[FileLocation]) -> Vec<FileLocation> {
    let mut out = Vec::with_capacity(a.len().min(b.len()));
    let gallop = b.len() > 8 * a.len();
    let (mut i, mut j) = (0, 0);

    while i < a.len() && j < b.len() {
        let ka = key(&a[i]);
        match key(&b[j]).cmp(&ka) {
            std::cmp::Ordering::Less => {
                if gallop {
                    j += b[j..].partition_point(|x| key(x) < ka);
                } else {
                    j += 1;
                }
            }
            std::cmp::Ordering::Greater => i += 1,
            std::cmp::Ordering::Equal => {
                out.push(a[i]);
                i += 1;
                // Consume every entry in `b` with this key
                j += 1;
                while j < b.len() && key(&b[j]) == ka {
                    j += 1;
                }
            }
        }
    }

    out
}

/// Intersect sorted posting lists by (file_id, line_no).
///
/// Returns locations where ALL trigrams appear on the SAME line (not just in the
/// same file), keeping the `FileLocation` from the first list. Callers should
/// pass lists smallest-first: the first list is copied and deduplicated by key,
/// then folded against the rest in linear time.
pub(crate) fn intersect_sorted(lists: &[&[FileLocation]]) -> Vec<FileLocation> {
    let Some((first, rest)) = lists.split_first() else {
        return vec![];
    };

    let mut cands = first.to_vec();
    cands.dedup_by_key(|l| key(l));

    for list in rest {
        if cands.is_empty() {
            break;
        }
        cands = intersect_two(&cands, list);
    }

    cands
}

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

    /// `search_candidates` may stop intersecting once the next list is much larger
    /// than the candidate set; it must then return a superset of the exact
    /// intersection, never a subset, in both lazy and in-memory modes.
    #[test]
    fn search_candidates_is_a_superset_of_search() {
        let mut index = TrigramIndex::new();
        // Many lines share the common trigrams of "ident_"; only a few carry "t_7".
        for f in 0..20u32 {
            let id = index.add_file(PathBuf::from(format!("f{f}.rs")));
            let mut text = String::new();
            for i in 0..200 {
                text.push_str(&format!("let ident_{} = ident_{}; // filler\n", i, i + 1));
            }
            text.push_str("let ident_7 = 1;\n");
            index.index_file(id, &text);
        }
        index.finalize();

        let exact = index.search("ident_7");
        let cands = index.search_candidates("ident_7");
        assert!(!exact.is_empty());
        let exact_keys: std::collections::HashSet<_> = exact.iter().map(key).collect();
        let cand_keys: std::collections::HashSet<_> = cands.iter().map(key).collect();
        assert!(
            exact_keys.is_subset(&cand_keys),
            "candidates must cover every match"
        );

        // Same contract through the on-disk (lazy) path.
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("trigrams.bin");
        index.write(&path).unwrap();
        let lazy = TrigramIndex::load(&path).unwrap();
        let lazy_exact: std::collections::HashSet<_> =
            lazy.search("ident_7").iter().map(key).collect();
        let lazy_cands: std::collections::HashSet<_> =
            lazy.search_candidates("ident_7").iter().map(key).collect();
        assert_eq!(lazy_exact, exact_keys);
        assert!(lazy_exact.is_subset(&lazy_cands));
    }
    /// `search_candidates_fold` plus `exotic_fold_lines` must cover every line a
    /// `(?i)` regex matches, in both modes, including the Kelvin-sign and long-s
    /// folds the regex crate applies to `k` and `s`.
    #[test]
    fn search_candidates_fold_covers_case_insensitive_matches() {
        let mut index = TrigramIndex::new();
        let mut texts: Vec<String> = Vec::new();
        for f in 0..10u32 {
            let id = index.add_file(PathBuf::from(format!("f{f}.rs")));
            let mut text = String::new();
            for i in 0..100 {
                text.push_str(&format!("let ident_{} = other_{}; // filler\n", i, i + 1));
            }
            text.push_str("let RealmId = 1;\n");
            text.push_str("let realmId = 2;\n");
            text.push_str("let REALMID = 3;\n");
            text.push_str("let realm_id = 4;\n");
            text.push_str("let kelvin = 5;\n");
            text.push_str("let \u{212A}elvin = 6;\n");
            text.push_str("let \u{017F}tatus = 7;\n");
            text.push_str("let STATUS = 8;\n");
            index.index_file(id, &text);
            texts.push(text);
        }
        index.finalize();

        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("trigrams.bin");
        index.write(&path).unwrap();
        let lazy = TrigramIndex::load(&path).unwrap();

        for literal in ["realmid", "kelvin", "status", "REALM_ID"] {
            let re = regex::Regex::new(&format!("(?i){}", literal)).unwrap();
            let mut expected = std::collections::HashSet::new();
            for (f, text) in texts.iter().enumerate() {
                for (i, line) in text.lines().enumerate() {
                    if re.is_match(line) {
                        expected.insert((f as u32, i as u32 + 1));
                    }
                }
            }
            assert!(!expected.is_empty(), "{literal}");
            let has_ks = literal
                .bytes()
                .any(|b| matches!(b.to_ascii_lowercase(), b'k' | b's'));

            for (name, idx) in [("memory", &index), ("lazy", &lazy)] {
                let mut cands: std::collections::HashSet<_> = idx
                    .search_candidates_fold(literal.as_bytes())
                    .iter()
                    .map(key)
                    .collect();
                if has_ks {
                    cands.extend(idx.exotic_fold_lines().iter().map(key));
                }
                assert!(
                    expected.is_subset(&cands),
                    "{name}: fold candidates for {literal:?} miss {:?}",
                    expected.difference(&cands).collect::<Vec<_>>()
                );
            }
        }

        // The regex crate really does fold these (Unicode simple case folding),
        // and the ASCII windows alone do not reach them.
        assert!(
            regex::Regex::new("(?i)kelvin")
                .unwrap()
                .is_match("\u{212A}elvin")
        );
        assert!(
            regex::Regex::new("(?i)status")
                .unwrap()
                .is_match("\u{017F}tatus")
        );
        let ascii_only: std::collections::HashSet<_> = lazy
            .search_candidates_fold(b"kelvin")
            .iter()
            .map(key)
            .collect();
        assert!(
            !ascii_only.contains(&(0, 106)),
            "line 106 is the Kelvin-sign line"
        );

        // Exotic lines are exactly the two lines per file that carry the folds.
        assert_eq!(lazy.exotic_fold_lines().len(), 20);
        assert_eq!(index.exotic_fold_lines(), lazy.exotic_fold_lines());

        // A window absent in every casing is a definite miss.
        assert!(lazy.search_candidates_fold(b"zzqx_absent").is_empty());
        // Non-ASCII is not folded here.
        assert!(lazy.search_candidates_fold("straße".as_bytes()).is_empty());
    }

    use tempfile::TempDir;

    #[test]
    fn test_extract_trigrams() {
        let text = "hello";
        let trigrams = extract_trigrams(text);

        // "hello" → "hel", "ell", "llo"
        assert_eq!(trigrams.len(), 3);

        // Verify trigrams are unique
        let expected = vec![
            bytes_to_trigram(b"hel"),
            bytes_to_trigram(b"ell"),
            bytes_to_trigram(b"llo"),
        ];
        assert_eq!(trigrams, expected);
    }

    #[test]
    fn test_extract_trigrams_short() {
        assert_eq!(extract_trigrams("ab").len(), 0);
        assert_eq!(extract_trigrams("abc").len(), 1);
    }

    #[test]
    fn test_bytes_to_trigram() {
        let trigram1 = bytes_to_trigram(b"abc");
        let trigram2 = bytes_to_trigram(b"abc");
        let trigram3 = bytes_to_trigram(b"xyz");

        assert_eq!(trigram1, trigram2);
        assert_ne!(trigram1, trigram3);
    }

    #[test]
    fn test_trigram_roundtrip() {
        let original = b"foo";
        let trigram = bytes_to_trigram(original);
        let recovered = trigram_to_bytes(trigram);
        assert_eq!(original, &recovered);
    }

    #[test]
    fn test_extract_with_locations() {
        let text = "hello\nworld";
        let locs = extract_trigrams_with_locations(text, 0);

        // "hello\nworld" has 9 distinct trigrams:
        // line 1: "hel", "ell", "llo", "lo\n", "o\nw"
        // line 2: "\nwo", "wor", "orl", "rld"   (a trigram starting on '\n' is line 2)
        assert_eq!(locs.len(), 9);
        assert_eq!(locs.iter().filter(|(_, l)| l.line_no == 1).count(), 5);
        assert_eq!(locs.iter().filter(|(_, l)| l.line_no == 2).count(), 4);
        assert!(locs.iter().all(|(_, l)| l.file_id == 0));

        let line_of = |t: &[u8; 3]| {
            locs.iter()
                .find(|(tri, _)| *tri == bytes_to_trigram(t))
                .map(|(_, l)| l.line_no)
        };
        assert_eq!(line_of(b"hel"), Some(1));
        assert_eq!(line_of(b"o\nw"), Some(1));
        assert_eq!(line_of(b"\nwo"), Some(2));
        assert_eq!(line_of(b"wor"), Some(2));
    }

    #[test]
    fn test_extract_emits_one_posting_per_distinct_trigram_per_line() {
        // "aaaa" alone yields "aaa" twice at byte level; per line it must be once.
        let locs = extract_trigrams_with_locations("aaaa\naaaa", 3);
        // line 1: "aaa", "aa\n", "a\na"   line 2: "\naa", "aaa"
        assert_eq!(locs.len(), 5);
        let aaa = bytes_to_trigram(b"aaa");
        let aaa_lines: Vec<u32> = locs
            .iter()
            .filter(|(t, _)| *t == aaa)
            .map(|(_, l)| l.line_no)
            .collect();
        assert_eq!(aaa_lines, vec![1, 2]);

        // Every (trigram, file, line) key is unique and each line's run is sorted
        let mut keys: Vec<(Trigram, u32, u32)> = locs
            .iter()
            .map(|(t, l)| (*t, l.file_id, l.line_no))
            .collect();
        let n = keys.len();
        keys.sort_unstable();
        keys.dedup();
        assert_eq!(keys.len(), n, "duplicate (trigram, line) postings emitted");
        assert!(locs.iter().all(|(_, l)| l.file_id == 3));

        // Heavy indentation: 16 spaces → "   " appears 14 times per line, emitted once
        let indented = "                x\n                y\n";
        let sp = bytes_to_trigram(b"   ");
        let spaces = extract_trigrams_with_locations(indented, 0);
        assert_eq!(spaces.iter().filter(|(t, _)| *t == sp).count(), 2);
    }

    #[test]
    fn test_trigram_index_basic() {
        let mut index = TrigramIndex::new();

        let file_id = index.add_file(PathBuf::from("test.txt"));
        index.index_file(file_id, "hello world");
        index.finalize();

        // Search for "hello"
        let results = index.search("hello");
        assert!(!results.is_empty());

        // Search for "world"
        let results = index.search("world");
        assert!(!results.is_empty());

        // Search for "goodbye" (not in text)
        let results = index.search("goodbye");
        assert!(results.is_empty());
    }

    #[test]
    fn test_search_multifile() {
        let mut index = TrigramIndex::new();

        let file1 = index.add_file(PathBuf::from("file1.txt"));
        let file2 = index.add_file(PathBuf::from("file2.txt"));

        index.index_file(file1, "extract_symbols is here");
        index.index_file(file2, "extract_symbols is also here");
        index.finalize();

        let results = index.search("extract_symbols");
        assert_eq!(results.len(), 2); // One result per file

        // Verify we got both files
        let file_ids: Vec<u32> = results.iter().map(|loc| loc.file_id).collect();
        assert!(file_ids.contains(&file1));
        assert!(file_ids.contains(&file2));
    }

    #[test]
    fn test_persistence_write_header() {
        let temp = TempDir::new().unwrap();
        let trigrams_path = temp.path().join("trigrams.bin");

        // Build and write index
        let mut index = TrigramIndex::new();
        let file1 = index.add_file(PathBuf::from("src/main.rs"));
        let file2 = index.add_file(PathBuf::from("src/lib.rs"));

        index.index_file(file1, "fn main() { println!(\"hello\"); }");
        index.index_file(
            file2,
            "pub fn hello() -> String { String::from(\"hello\") }",
        );
        index.finalize();
        let num_trigrams = index.trigram_count() as u64;

        index.write(&trigrams_path).unwrap();

        let bytes = std::fs::read(&trigrams_path).unwrap();
        assert!(bytes.len() > HEADER_SIZE);
        assert_eq!(&bytes[0..4], MAGIC);
        assert_eq!(read_u32(&bytes, 4), VERSION);
        assert_eq!(read_u64(&bytes, NUM_TRIGRAMS_OFFSET), num_trigrams);
        assert_eq!(read_u64(&bytes, NUM_FILES_OFFSET), 2);

        // paths_offset points just past header + directory + data, and the
        // paths section decodes to the files we added.
        let paths_offset = read_u64(&bytes, PATHS_OFFSET_OFFSET) as usize;
        assert!(paths_offset >= HEADER_SIZE + num_trigrams as usize * DIR_ENTRY_SIZE);
        assert!(paths_offset < bytes.len());
        let (len, consumed) = read_varint(&bytes[paths_offset..]).unwrap();
        let first = &bytes[paths_offset + consumed..paths_offset + consumed + len as usize];
        assert_eq!(first, b"src/main.rs");
    }

    fn loc(file_id: u32, line_no: u32) -> FileLocation {
        FileLocation::new(file_id, line_no)
    }

    /// `unwrap_err` without requiring `Debug` on the success type
    fn load_err(path: &Path) -> String {
        match TrigramIndex::load(path) {
            Ok(_) => panic!("load unexpectedly succeeded"),
            Err(e) => e.to_string(),
        }
    }

    #[test]
    fn test_intersect_two_empty() {
        let a = [loc(0, 1), loc(1, 2)];
        assert!(intersect_two(&a, &[]).is_empty());
        assert!(intersect_two(&[], &a).is_empty());
        assert!(intersect_two(&[], &[]).is_empty());
    }

    #[test]
    fn test_intersect_two_disjoint() {
        let a = [loc(0, 1), loc(0, 3), loc(2, 1)];
        let b = [loc(0, 2), loc(1, 1), loc(2, 2)];
        assert!(intersect_two(&a, &b).is_empty());
        assert!(intersect_two(&b, &a).is_empty());
    }

    #[test]
    fn test_intersect_two_duplicate_keys_in_b() {
        // Repeated keys in `b` are all consumed; result keeps `a`'s entry once
        let a = [loc(0, 1), loc(0, 2), loc(1, 1)];
        let b = [
            loc(0, 1),
            loc(0, 1),
            loc(0, 1),
            loc(1, 1),
            loc(1, 1),
            loc(1, 2),
        ];
        assert_eq!(intersect_two(&a, &b), vec![loc(0, 1), loc(1, 1)]);
    }

    #[test]
    fn test_intersect_two_gallop_path() {
        // 1 vs 200 entries forces the gallop branch (b.len() > 8 * a.len())
        let b: Vec<FileLocation> = (0u32..200).map(|i| loc(i / 10, i % 10 + 1)).collect();
        assert_eq!(intersect_two(&[loc(7, 4)], &b), vec![loc(7, 4)]);
        assert!(intersect_two(&[loc(7, 11)], &b).is_empty());
        assert!(intersect_two(&[loc(20, 1)], &b).is_empty());

        // A few shared keys spread through a large `b`
        let a = [loc(0, 1), loc(5, 5), loc(12, 3), loc(19, 10), loc(25, 1)];
        assert_eq!(
            intersect_two(&a, &b),
            vec![loc(0, 1), loc(5, 5), loc(12, 3), loc(19, 10)]
        );
    }

    #[test]
    fn test_intersect_two_all_equal() {
        let a: Vec<FileLocation> = (0u32..50).map(|i| loc(i, 1)).collect();
        let b: Vec<FileLocation> = (0u32..50).map(|i| loc(i, 1)).collect();
        assert_eq!(intersect_two(&a, &b), a);
    }

    /// Minimal LCG so the property test is deterministic without extra crates
    struct Lcg(u64);

    impl Lcg {
        fn next(&mut self) -> u32 {
            self.0 = self
                .0
                .wrapping_mul(6364136223846793005)
                .wrapping_add(1442695040888963407);
            (self.0 >> 33) as u32
        }
    }

    fn random_sorted_list(rng: &mut Lcg, n: usize) -> Vec<FileLocation> {
        // Keys from a small range (40 files x 60 lines) to force heavy overlap
        let mut list: Vec<FileLocation> = (0..n)
            .map(|_| loc(rng.next() % 40, rng.next() % 60 + 1))
            .collect();
        list.sort_unstable();
        list.dedup();
        list
    }

    fn reference_intersection(lists: &[&[FileLocation]]) -> Vec<FileLocation> {
        use std::collections::HashSet;
        let mut keys: HashSet<(u32, u32)> = lists[0].iter().map(key).collect();
        for list in &lists[1..] {
            let set: HashSet<(u32, u32)> = list.iter().map(key).collect();
            keys.retain(|k| set.contains(k));
        }
        let mut out: Vec<FileLocation> = keys
            .iter()
            .map(|k| *lists[0].iter().find(|l| key(l) == *k).unwrap())
            .collect();
        out.sort_unstable();
        out
    }

    #[test]
    fn test_intersect_sorted_matches_reference() {
        let mut rng = Lcg(0x5eed);
        for _ in 0..5 {
            let lists: Vec<Vec<FileLocation>> = (0..3)
                .map(|_| random_sorted_list(&mut rng, 2_000))
                .collect();
            let mut refs: Vec<&[FileLocation]> = lists.iter().map(|l| l.as_slice()).collect();
            refs.sort_by_key(|l| l.len());

            let expected = reference_intersection(&refs);
            assert!(!expected.is_empty(), "test data should overlap");
            assert_eq!(intersect_sorted(&refs), expected);
        }
    }

    /// Build a 40-file index whose posting lists differ widely in size
    fn random_word_index(seed: u64) -> TrigramIndex {
        let mut rng = Lcg(seed);
        let mut index = TrigramIndex::new();
        for i in 0..40 {
            index.add_file(PathBuf::from(format!("f{i}.txt")));
        }
        let words = ["realm", "real", "alma", "lmn", "rea", "xyz", "ealm"];
        for file_id in 0..40u32 {
            let mut content = String::new();
            for _ in 0..60 {
                for _ in 0..4 {
                    content.push_str(words[(rng.next() % words.len() as u32) as usize]);
                    content.push(' ');
                }
                content.push('\n');
            }
            index.index_file(file_id, &content);
        }
        index.finalize();
        index
    }

    #[test]
    fn test_lazy_search_matches_in_memory() {
        let mut index = random_word_index(0xbeef);

        let temp = TempDir::new().unwrap();
        let path = temp.path().join("trigrams.bin");
        index.write(&path).unwrap();
        let lazy = TrigramIndex::load(&path).unwrap();

        assert_eq!(lazy.trigram_count(), index.trigram_count());
        assert_eq!(lazy.file_count(), 40);
        assert_eq!(lazy.get_file(39), Some(&PathBuf::from("f39.txt")));
        assert_eq!(lazy.get_file(40), None);

        for pattern in ["realm", "alma", "xyz", "lmn r", "ealm x", "nothing", "ab"] {
            assert_eq!(
                lazy.search(pattern),
                index.search(pattern),
                "pattern {pattern:?}"
            );
            assert_eq!(lazy.search_files(pattern), index.search_files(pattern));
        }

        let files = lazy.search_files("realm");
        assert!(!files.is_empty());
        assert!(files.windows(2).all(|w| w[0] < w[1]), "sorted, distinct");
    }

    #[test]
    fn test_find_entry_zero_copy_directory() {
        let mut index = random_word_index(0xf00d);
        let temp = TempDir::new().unwrap();
        let path = temp.path().join("trigrams.bin");
        index.write(&path).unwrap();
        let lazy = TrigramIndex::load(&path).unwrap();

        // In-memory index has no directory to search
        assert!(index.find_entry(bytes_to_trigram(b"rea")).is_none());

        let rea = bytes_to_trigram(b"rea");
        let entry = lazy.find_entry(rea).expect("rea is indexed");
        assert_eq!(entry.trigram, rea);
        let expected_len = index.get_posting_list(rea).unwrap().len();
        let decoded = decompress_posting_list(
            lazy.mmap.as_ref().unwrap(),
            entry.data_offset,
            entry.compressed_size,
        )
        .unwrap();
        assert_eq!(decoded.len(), expected_len);
        assert_eq!(&decoded, index.get_posting_list(rea).unwrap());

        assert!(lazy.find_entry(bytes_to_trigram(b"zzz")).is_none());
        assert!(lazy.find_entry(0).is_none());
        assert!(lazy.find_entry(u32::MAX).is_none());
    }

    #[test]
    fn test_search_repeated_trigram_returns_line_once() {
        let mut index = TrigramIndex::new();
        let file_id = index.add_file(PathBuf::from("a.txt"));
        index.index_file(file_id, "x\naaaa\ny");
        index.finalize();

        let results = index.search("aaaa");
        assert_eq!(results, vec![loc(file_id, 2)]);

        let temp = TempDir::new().unwrap();
        let path = temp.path().join("trigrams.bin");
        index.write(&path).unwrap();
        let lazy = TrigramIndex::load(&path).unwrap();
        assert_eq!(lazy.search("aaaa"), results);
    }

    #[test]
    fn test_posting_list_block_encoding_roundtrip() {
        // Three file blocks; the middle one has a single line, the last is far away
        let locations = vec![
            loc(0, 1),
            loc(0, 7),
            loc(0, 300),
            loc(3, 2),
            loc(70_000, 1),
            loc(70_000, 2),
        ];
        let mut data = Vec::new();
        encode_posting_list(&locations, &mut data).unwrap();

        // Expected bytes: block(0): fd=0, n=3<<1, lines 1,6,293(2 B)
        //                 block(3): fd=3, n=1<<1, line 2
        //                 block(70000): fd=69997 (3 B), n=2<<1, lines 1,1
        assert_eq!(
            data,
            vec![0, 6, 1, 6, 0xA5, 0x02, 3, 2, 2, 0xED, 0xA2, 0x04, 4, 1, 1]
        );

        assert_eq!(
            decompress_posting_list(&data, 0, data.len() as u32).unwrap(),
            locations
        );

        let mut cursor = PostingCursor::new(&data).unwrap();
        assert_eq!(cursor.current(), Some(loc(0, 1)));
        assert_eq!(cursor.seek((0, 7)).unwrap(), Some(loc(0, 7)));
        // Target in a later file: skips the rest of block 0 and block 3
        assert_eq!(cursor.seek((4, 1)).unwrap(), Some(loc(70_000, 1)));
        assert_eq!(cursor.advance().unwrap(), Some(loc(70_000, 2)));
        assert_eq!(cursor.seek((70_000, 2)).unwrap(), Some(loc(70_000, 2)));
        assert_eq!(cursor.seek((70_001, 0)).unwrap(), None);
        assert_eq!(cursor.current(), None);

        // Seeking within the first block by line only
        let mut cursor = PostingCursor::new(&data).unwrap();
        assert_eq!(cursor.seek((0, 8)).unwrap(), Some(loc(0, 300)));
        assert_eq!(cursor.seek((3, 1)).unwrap(), Some(loc(3, 2)));
    }

    #[test]
    fn test_posting_list_empty_and_malformed() {
        let mut data = Vec::new();
        encode_posting_list(&[], &mut data).unwrap();
        assert!(data.is_empty());
        assert!(decompress_posting_list(&data, 0, 0).unwrap().is_empty());

        let empty = PostingCursor::new(&[]).unwrap();
        assert_eq!(empty.current(), None);

        // Truncated varint surfaces as an error rather than a panic
        assert!(PostingCursor::new(&[0x80]).is_err());
        // Block header present, line varint missing
        assert!(PostingCursor::new(&[0, 2]).is_err());
        // Out-of-bounds slice request
        assert!(decompress_posting_list(&[0, 2, 1], 0, 4).is_err());

        // Reserved enc=1 blocks are rejected, not misread
        let enc1 = [0u8, (1 << 1) | 1, 1];
        let err = match PostingCursor::new(&enc1) {
            Ok(_) => panic!("enc=1 block was accepted"),
            Err(e) => e.to_string(),
        };
        assert!(err.contains("unsupported block encoding"), "{err}");
        assert!(decompress_posting_list(&enc1, 0, 3).is_err());

        // A zero-length block is tolerated and skipped
        let with_empty_block = [0u8, 0, 2, 1 << 1, 5];
        assert_eq!(
            decompress_posting_list(&with_empty_block, 0, 5).unwrap(),
            vec![loc(2, 5)]
        );
    }

    #[test]
    fn test_v4_roundtrip_file_block_boundaries() {
        // "needle" sits on several lines of files 0, 2 and 4, on none of 1 and 3,
        // and file 5 has it only on its last line. Every block boundary shape:
        // consecutive files, gaps, single-line block.
        let mut index = TrigramIndex::new();
        for i in 0..6 {
            index.add_file(PathBuf::from(format!("dir/file{i}.rs")));
        }
        let with = "needle here\nnothing\nneedle again\n\nneedle\n";
        let without = "haystack\nonly\n";
        index.index_file(0, with);
        index.index_file(1, without);
        index.index_file(2, with);
        index.index_file(3, without);
        index.index_file(4, with);
        index.index_file(5, "haystack\nneedle");
        index.finalize();

        let expected = vec![
            loc(0, 1),
            loc(0, 3),
            loc(0, 5),
            loc(2, 1),
            loc(2, 3),
            loc(2, 5),
            loc(4, 1),
            loc(4, 3),
            loc(4, 5),
            loc(5, 2),
        ];
        assert_eq!(index.search("needle"), expected);

        let temp = TempDir::new().unwrap();
        let path = temp.path().join("trigrams.bin");
        index.write(&path).unwrap();
        let lazy = TrigramIndex::load(&path).unwrap();

        assert_eq!(lazy.search("needle"), expected);
        assert_eq!(lazy.search_files("needle"), vec![0, 2, 4, 5]);
        assert_eq!(
            lazy.search("haystack"),
            vec![loc(1, 1), loc(3, 1), loc(5, 1)]
        );
        assert_eq!(
            lazy.search("needle again"),
            vec![loc(0, 3), loc(2, 3), loc(4, 3)]
        );
        assert!(lazy.search("needle haystack").is_empty());
        assert_eq!(lazy.file_count(), 6);
        assert_eq!(lazy.get_file(5), Some(&PathBuf::from("dir/file5.rs")));
    }

    #[test]
    fn test_v4_roundtrip_empty_index() {
        let temp = TempDir::new().unwrap();
        let path = temp.path().join("trigrams.bin");

        let mut index = TrigramIndex::new();
        index.finalize();
        index.write(&path).unwrap();

        let lazy = TrigramIndex::load(&path).unwrap();
        assert_eq!(lazy.trigram_count(), 0);
        assert_eq!(lazy.file_count(), 0);
        assert!(lazy.search("anything").is_empty());

        // Files but no indexable content (every file shorter than a trigram)
        let mut index = TrigramIndex::new();
        let f = index.add_file(PathBuf::from("tiny.txt"));
        index.index_file(f, "ab");
        index.finalize();
        index.write(&path).unwrap();
        let lazy = TrigramIndex::load(&path).unwrap();
        assert_eq!(lazy.trigram_count(), 0);
        assert_eq!(lazy.file_count(), 1);
        assert!(lazy.search("abc").is_empty());
    }

    #[test]
    fn test_load_rejects_v3_version() {
        let temp = TempDir::new().unwrap();
        let path = temp.path().join("trigrams.bin");

        // A V3 header: magic, version 3, num_trigrams, num_files (24 bytes)
        let mut bytes = Vec::new();
        bytes.extend_from_slice(MAGIC);
        bytes.extend_from_slice(&3u32.to_le_bytes());
        bytes.extend_from_slice(&0u64.to_le_bytes());
        bytes.extend_from_slice(&0u64.to_le_bytes());
        std::fs::write(&path, &bytes).unwrap();

        let err = load_err(&path);
        assert!(
            err.contains("Unsupported trigrams.bin version: 3 (expected 4)"),
            "{err}"
        );
        assert!(err.contains("re-index"), "{err}");

        // Wrong magic is a different error
        std::fs::write(&path, b"NOPE\x04\x00\x00\x00").unwrap();
        let err = load_err(&path);
        assert!(err.contains("wrong magic"), "{err}");
    }

    #[test]
    fn test_load_rejects_truncated_or_inconsistent_file() {
        let mut index = random_word_index(0xd00d);
        let temp = TempDir::new().unwrap();
        let path = temp.path().join("trigrams.bin");
        index.write(&path).unwrap();
        let full = std::fs::read(&path).unwrap();
        assert!(TrigramIndex::load(&path).is_ok());

        // Cut in the middle of the data section: paths_offset now lies past EOF
        std::fs::write(&path, &full[..full.len() / 2]).unwrap();
        let err = load_err(&path);
        assert!(err.contains("out of bounds"), "{err}");

        // Cut inside the header
        std::fs::write(&path, &full[..10]).unwrap();
        let err = load_err(&path);
        assert!(err.contains("too small"), "{err}");

        // Cut inside the paths section
        std::fs::write(&path, &full[..full.len() - 3]).unwrap();
        let err = load_err(&path);
        assert!(err.contains("Truncated"), "{err}");

        // Directory claims more entries than fit before paths_offset
        let mut bad = full.clone();
        bad[NUM_TRIGRAMS_OFFSET..NUM_TRIGRAMS_OFFSET + 8]
            .copy_from_slice(&(u64::MAX / 32).to_le_bytes());
        std::fs::write(&path, &bad).unwrap();
        let err = load_err(&path);
        assert!(err.contains("out of bounds"), "{err}");
    }

    #[test]
    fn test_posting_list_cap_enforced() {
        let cap: usize = 10;
        let content = "aaa \n".repeat(200);
        let mut index = TrigramIndex::new();
        index.set_max_posting_list_entries(cap);
        let file_id = index.add_file(PathBuf::from("dense.txt"));
        index.index_file(file_id, &content);
        index.finalize();
        let aaa = bytes_to_trigram(b"aaa");
        let list = index
            .get_posting_list(aaa)
            .expect("aaa trigram should exist");
        assert!(list.len() <= cap, "cap exceeded: {} > {}", list.len(), cap);
    }

    #[test]
    fn test_posting_list_cap_zero_means_unlimited() {
        let repetitions = 50;
        // One line per repetition: postings are per line, not per byte
        let content = "aaa \n".repeat(repetitions);
        let mut index = TrigramIndex::new();
        index.set_max_posting_list_entries(0);
        let file_id = index.add_file(PathBuf::from("dense.txt"));
        index.index_file(file_id, &content);
        index.finalize();
        let aaa = bytes_to_trigram(b"aaa");
        let list = index
            .get_posting_list(aaa)
            .expect("aaa trigram should exist");
        assert!(
            list.len() >= repetitions,
            "expected >= {} entries, got {}",
            repetitions,
            list.len()
        );
    }
}